feat(audit)!: remove the AuditLog hash chain, head export and two-login maintenance hardening
Owner decision 2026-11-15, at IT security's request, pending a family-wide general solution. Removed: the chaining service, hasher, verifier, chain head/tombstone entities and store, the #139 chain-start cutoff, AuditLog:HashChain (incl. ChainBacklog and HeadExport with its File/Syslog sinks and export service), the audit-chain-head-export health check, the VerifyAuditChain / VerifyAuditChainHeads management commands and the `audit verify-chain` / `audit verify-heads` CLI commands, and the two-login plumbing (AuditLog:MaintenanceConnectionString, AuditMaintenanceContext, the keyed audit-maintenance repository/archive). Purge, archive, retention, partition roll-forward and backfill-source-node all run on the runtime connection again, as before #107. Parquet archive (#42) kept, chain-free: format v2 (ten stored columns, no tombstone file, manifest without chain state), the switch guard is the row count only (51003 gone), verify = data-file size, SHA-256 and row count, and superseded-stale cleanup proves coverage by EventId. Format-v1 archives still list, verify and are cleaned up (their tombstone file too). Migration RemoveAuditLogHashChain drops the chain indexes, the scadabridge_audit_chainer role (members first), both chain tables, ChainSeq/RowHash and the purger's AuditMaintenanceGrants grants; writer/purger roles stay. Down restores them. Every chain-column reference is EXEC-deferred for the idempotent script (#126); FlipAuditLogClusteredKey's two chain index statements get the same deferral, behaviour unchanged, so re-running the idempotent script on a migrated database works. The partition-switch staging table adds the chain columns only when the live table has them, so the new binary purges either schema. Deploy gate: old binaries map the chain columns, so the migration ships with the new binaries, both centrals stopped. A leftover AuditLog:HashChain section or MaintenanceConnectionString (DEV/QA still carry AuditLog__HashChain__Enabled=true) is ignored with one startup warning (RetiredAuditSettingsWarning). Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
This commit is contained in:
@@ -1,155 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -713,9 +713,9 @@ public class AuditLogPurgeActorTests : TestKit, IClassFixture<MsSqlMigrationFixt
|
||||
}
|
||||
|
||||
private static AuditArchiveManifest ManifestFor(DateTime boundary) => new(
|
||||
1, $"auditlog-{boundary:yyyy-MM}-20261109T120000000Z", boundary, boundary.ToString("yyyy-MM"),
|
||||
DateTime.UtcNow, AuditArchiveStatus.Archived, null, 7, 7, 0, null, null,
|
||||
"d.parquet", "00", 99, "t.parquet", "00", 0, []);
|
||||
2, $"auditlog-{boundary:yyyy-MM}-20261109T120000000Z", boundary, boundary.ToString("yyyy-MM"),
|
||||
DateTime.UtcNow, AuditArchiveStatus.Archived, null, 7, null, null,
|
||||
"d.parquet", "00", 99);
|
||||
|
||||
/// <summary>
|
||||
/// With archiving enabled every expired partition is archived and then purged by the
|
||||
@@ -793,36 +793,6 @@ public class AuditLogPurgeActorTests : TestKit, IClassFixture<MsSqlMigrationFixt
|
||||
StopPurgeActor(actor);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ScadaBridge#107 item 3: when the host registered the maintenance-connection repository
|
||||
/// (keyed <c>audit-maintenance</c>), the purge runs on it, never on the runtime one.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Tick_UsesTheMaintenanceConnectionRepository_WhenRegistered()
|
||||
{
|
||||
var runtime = new RecordingRepo { Boundaries = [new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc)] };
|
||||
var maintenance = new RecordingRepo { Boundaries = [new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc)] };
|
||||
var services = new ServiceCollection();
|
||||
services.AddScoped<IAuditLogRepository>(_ => runtime);
|
||||
services.AddKeyedScoped<IAuditLogRepository>(
|
||||
ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance.AuditMaintenanceContext.ServiceKey, (_, _) => maintenance);
|
||||
var sp = services.BuildServiceProvider();
|
||||
var actor = Sys.ActorOf(Props.Create(() => new AuditLogPurgeActor(
|
||||
sp,
|
||||
Options.Create(FastTickOptions()),
|
||||
Options.Create(new AuditLogOptions()),
|
||||
NullLogger<AuditLogPurgeActor>.Instance)));
|
||||
|
||||
AwaitAssert(
|
||||
() => Assert.NotEmpty(maintenance.SwitchedBoundaries),
|
||||
duration: TimeSpan.FromSeconds(3),
|
||||
interval: TimeSpan.FromMilliseconds(50));
|
||||
Assert.Empty(runtime.ThresholdQueries);
|
||||
Assert.Empty(runtime.SwitchedBoundaries);
|
||||
|
||||
StopPurgeActor(actor);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ScadaBridge#109: with archiving enabled every tick ends with the archive cleanup pass —
|
||||
/// also on a tick with no expired partition — and never runs it when archiving is off.
|
||||
|
||||
-207
@@ -1,207 +0,0 @@
|
||||
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.AuditLog.Central.HeadExport;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Central.HeadExport;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="AuditChainHeadExportService"/> (ScadaBridge#107 item 1): first tick exports every
|
||||
/// head, later ticks only the changed ones, a failed write is retried with the same heads, and
|
||||
/// the options validator guards each sink's settings.
|
||||
/// </summary>
|
||||
public sealed class AuditChainHeadExportServiceTests
|
||||
{
|
||||
private sealed class FakeStore : IAuditChainHeadStore
|
||||
{
|
||||
public List<AuditChainHeadSnapshot> Heads { get; } = [];
|
||||
|
||||
public Task<IReadOnlyList<AuditChainHeadSnapshot>> ReadHeadsAsync(CancellationToken ct = default)
|
||||
=> Task.FromResult<IReadOnlyList<AuditChainHeadSnapshot>>(Heads.ToList());
|
||||
|
||||
public Task<AuditChainHeadVerificationResult> VerifyExportedHeadsAsync(
|
||||
IReadOnlyList<AuditChainHeadRecord> records, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
private sealed class RecordingSink : IAuditChainHeadSink
|
||||
{
|
||||
public List<IReadOnlyList<AuditChainHeadRecord>> Writes { get; } = [];
|
||||
|
||||
public bool Fail { get; set; }
|
||||
|
||||
public string Describe => "recording";
|
||||
|
||||
public Task WriteAsync(IReadOnlyList<AuditChainHeadRecord> records, CancellationToken ct)
|
||||
{
|
||||
if (Fail)
|
||||
{
|
||||
throw new IOException("share offline");
|
||||
}
|
||||
|
||||
Writes.Add(records);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private static AuditChainHeadSnapshot Head(int month, long seq, long rows) => new(
|
||||
new DateTime(2026, month, 1, 0, 0, 0, DateTimeKind.Utc), seq, Enumerable.Repeat((byte)seq, 32).ToArray(),
|
||||
null, null, rows, 0, new DateTime(2026, month, 2, 0, 0, 0, DateTimeKind.Utc));
|
||||
|
||||
private static (AuditChainHeadExportService Service, FakeStore Store, RecordingSink Sink) Create(
|
||||
bool exportUnchanged = false, AuditChainHeadExportStatus? status = null, TimeProvider? time = null)
|
||||
{
|
||||
var store = new FakeStore();
|
||||
var sink = new RecordingSink();
|
||||
var services = new ServiceCollection();
|
||||
services.AddScoped<IAuditChainHeadStore>(_ => store);
|
||||
var options = Options.Create(new AuditLogHashChainOptions
|
||||
{
|
||||
HeadExport = new AuditChainHeadExportOptions { Enabled = true, ExportUnchanged = exportUnchanged },
|
||||
});
|
||||
var service = new AuditChainHeadExportService(
|
||||
services.BuildServiceProvider().GetRequiredService<IServiceScopeFactory>(),
|
||||
options, sink, "central-a", NullLogger<AuditChainHeadExportService>.Instance, time, status);
|
||||
return (service, store, sink);
|
||||
}
|
||||
|
||||
/// <summary>First tick: every head; next tick: only the head that moved; unchanged: nothing.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Tick_ExportsAllHeadsFirst_ThenOnlyChangedOnes()
|
||||
{
|
||||
var (service, store, sink) = Create();
|
||||
store.Heads.AddRange([Head(4, 10, 10), Head(5, 20, 20)]);
|
||||
|
||||
Assert.Equal(2, await service.TickAsync(default));
|
||||
Assert.Equal(0, await service.TickAsync(default));
|
||||
|
||||
store.Heads[1] = Head(5, 25, 25);
|
||||
Assert.Equal(1, await service.TickAsync(default));
|
||||
|
||||
// A per-channel purge (row -> tombstone) keeps rows + tombstones, so it is not a change;
|
||||
// a row disappearing without a tombstone is.
|
||||
store.Heads[0] = Head(4, 10, 9);
|
||||
Assert.Equal(1, await service.TickAsync(default));
|
||||
|
||||
Assert.Equal(3, sink.Writes.Count);
|
||||
Assert.Equal(["2026-04", "2026-05"], sink.Writes[0].Select(r => r.Month));
|
||||
var moved = Assert.Single(sink.Writes[1]);
|
||||
Assert.Equal(("2026-05", 25L, string.Concat(Enumerable.Repeat("19", 32))), (moved.Month, moved.LastSeq, moved.LastHash));
|
||||
Assert.Equal("central-a", moved.Node);
|
||||
Assert.Equal(AuditChainHeadRecord.CurrentVersion, moved.V);
|
||||
}
|
||||
|
||||
/// <summary>ExportUnchanged re-exports every head every tick.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Tick_WithExportUnchanged_ExportsEveryHeadEveryTick()
|
||||
{
|
||||
var (service, store, _) = Create(exportUnchanged: true);
|
||||
store.Heads.AddRange([Head(4, 10, 10), Head(5, 20, 20)]);
|
||||
|
||||
Assert.Equal(2, await service.TickAsync(default));
|
||||
Assert.Equal(2, await service.TickAsync(default));
|
||||
}
|
||||
|
||||
/// <summary>A failed write is contained and the same heads go out on the next tick.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Tick_AfterAFailedWrite_RetriesTheSameHeads()
|
||||
{
|
||||
var (service, store, sink) = Create();
|
||||
store.Heads.Add(Head(4, 10, 10));
|
||||
sink.Fail = true;
|
||||
|
||||
Assert.Equal(0, await service.TickAsync(default));
|
||||
sink.Fail = false;
|
||||
Assert.Equal(1, await service.TickAsync(default));
|
||||
Assert.Equal(10, Assert.Single(Assert.Single(sink.Writes)).LastSeq);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ScadaBridge#115: a failed tick bumps the failure counter metric and the status
|
||||
/// (consecutive + total + last error); the next success clears the consecutive count.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task FailedTick_RecordsMetricAndStatus_SuccessResetsConsecutive()
|
||||
{
|
||||
var status = new AuditChainHeadExportStatus();
|
||||
var (service, store, sink) = Create(status: status);
|
||||
store.Heads.Add(Head(4, 10, 10));
|
||||
long measured = 0;
|
||||
using var listener = new System.Diagnostics.Metrics.MeterListener();
|
||||
listener.InstrumentPublished = (i, l) =>
|
||||
{
|
||||
if (i.Name == "scadabridge.audit.chain_head_export.failures")
|
||||
{
|
||||
l.EnableMeasurementEvents(i);
|
||||
}
|
||||
};
|
||||
listener.SetMeasurementEventCallback<long>((_, v, _, _) => Interlocked.Add(ref measured, v));
|
||||
listener.Start();
|
||||
|
||||
sink.Fail = true;
|
||||
await service.TickAsync(default);
|
||||
await service.TickAsync(default);
|
||||
|
||||
Assert.Equal(2, Interlocked.Read(ref measured));
|
||||
Assert.Equal(2, status.ConsecutiveFailures);
|
||||
Assert.Equal(2, status.TotalFailures);
|
||||
Assert.Equal("share offline", status.LastError);
|
||||
Assert.Null(status.LastSuccessUtc);
|
||||
|
||||
sink.Fail = false;
|
||||
await service.TickAsync(default);
|
||||
|
||||
Assert.Equal(0, status.ConsecutiveFailures);
|
||||
Assert.Equal(2, status.TotalFailures);
|
||||
Assert.NotNull(status.LastSuccessUtc);
|
||||
Assert.Equal(2, Interlocked.Read(ref measured));
|
||||
}
|
||||
|
||||
/// <summary>The validator ignores a disabled export and checks each sink's settings when enabled.</summary>
|
||||
/// <param name="configure">Which settings to apply.</param>
|
||||
/// <param name="expectedError">A fragment of the expected failure, or null when valid.</param>
|
||||
[Theory]
|
||||
[InlineData("disabled-bad", null)]
|
||||
[InlineData("file-ok", null)]
|
||||
[InlineData("file-relative", "File:Directory")]
|
||||
[InlineData("file-missing", "File:Directory")]
|
||||
[InlineData("syslog-ok", null)]
|
||||
[InlineData("syslog-no-host", "Syslog:Host")]
|
||||
[InlineData("syslog-bad-port", "Syslog:Port")]
|
||||
[InlineData("syslog-bad-facility", "Syslog:Facility")]
|
||||
[InlineData("interval-zero", "IntervalMinutes")]
|
||||
public void Validator_ChecksTheSelectedSink(string configure, string? expectedError)
|
||||
{
|
||||
var root = OperatingSystem.IsWindows() ? @"C:\heads" : "/var/heads";
|
||||
var export = configure switch
|
||||
{
|
||||
"disabled-bad" => new AuditChainHeadExportOptions { Enabled = false, IntervalMinutes = 0 },
|
||||
"file-ok" => new AuditChainHeadExportOptions { Enabled = true, File = { Directory = root } },
|
||||
"file-relative" => new AuditChainHeadExportOptions { Enabled = true, File = { Directory = "heads" } },
|
||||
"file-missing" => new AuditChainHeadExportOptions { Enabled = true },
|
||||
"syslog-ok" => new AuditChainHeadExportOptions { Enabled = true, Sink = AuditChainHeadSinkKind.Syslog, Syslog = { Host = "collector" } },
|
||||
"syslog-no-host" => new AuditChainHeadExportOptions { Enabled = true, Sink = AuditChainHeadSinkKind.Syslog },
|
||||
"syslog-bad-port" => new AuditChainHeadExportOptions { Enabled = true, Sink = AuditChainHeadSinkKind.Syslog, Syslog = { Host = "c", Port = 0 } },
|
||||
"syslog-bad-facility" => new AuditChainHeadExportOptions { Enabled = true, Sink = AuditChainHeadSinkKind.Syslog, Syslog = { Host = "c", Facility = 24 } },
|
||||
_ => new AuditChainHeadExportOptions { Enabled = true, IntervalMinutes = 0, File = { Directory = root } },
|
||||
};
|
||||
|
||||
var result = new AuditLogHashChainOptionsValidator().Validate(null, new AuditLogHashChainOptions { HeadExport = export });
|
||||
|
||||
if (expectedError is null)
|
||||
{
|
||||
Assert.True(result.Succeeded, result.FailureMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.True(result.Failed);
|
||||
Assert.Contains(expectedError, result.FailureMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
-135
@@ -1,135 +0,0 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Central.HeadExport;
|
||||
|
||||
/// <summary>
|
||||
/// The two off-box chain-head sinks (ScadaBridge#107 item 1): the append-only JSON-lines file
|
||||
/// sink, and RFC 5424 syslog over UDP and TCP (octet-counted framing).
|
||||
/// </summary>
|
||||
public sealed class AuditChainHeadSinkTests : IDisposable
|
||||
{
|
||||
private readonly DirectoryInfo _dir = Directory.CreateTempSubdirectory("head-sink-");
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => _dir.Delete(recursive: true);
|
||||
|
||||
private static AuditChainHeadRecord Record(string month, long seq) => new(
|
||||
1, month, seq, new string('a', 64), null, null, seq, 0,
|
||||
new DateTime(2026, 5, 3, 0, 0, 0, DateTimeKind.Utc), new DateTime(2026, 5, 3, 1, 0, 0, DateTimeKind.Utc), "central-a");
|
||||
|
||||
private sealed class FixedClock(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => now;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes append to the node's file for the day — never truncate it — one JSON record per
|
||||
/// line, and a pre-existing line survives.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task FileSink_AppendsJsonLines_ToThePerNodePerDayFile_WithoutTruncating()
|
||||
{
|
||||
var clock = new FixedClock(new DateTimeOffset(2026, 5, 3, 1, 0, 0, TimeSpan.Zero));
|
||||
var sink = new FileAuditChainHeadSink(_dir.FullName, "central-a", clock);
|
||||
var path = sink.PathFor(clock.GetUtcNow().UtcDateTime);
|
||||
Assert.Equal(Path.Combine(_dir.FullName, "2026", "audit-chain-heads-2026-05-03-central-a.jsonl"), path);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
await File.WriteAllTextAsync(path, "earlier line\n");
|
||||
|
||||
await sink.WriteAsync([Record("2026-04", 3), Record("2026-05", 7)], default);
|
||||
await sink.WriteAsync([Record("2026-05", 9)], default);
|
||||
|
||||
var lines = await File.ReadAllLinesAsync(path);
|
||||
Assert.Equal(4, lines.Length);
|
||||
Assert.Equal("earlier line", lines[0]);
|
||||
var parsed = lines.Skip(1).Select(l => JsonSerializer.Deserialize<AuditChainHeadRecord>(l, new JsonSerializerOptions(JsonSerializerDefaults.Web))!).ToList();
|
||||
Assert.Equal([3L, 7L, 9L], parsed.Select(r => r.LastSeq));
|
||||
Assert.Equal(Record("2026-05", 9), parsed[2]);
|
||||
}
|
||||
|
||||
/// <summary>A relative export directory is refused.</summary>
|
||||
[Fact]
|
||||
public void FileSink_RejectsARelativeDirectory()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new FileAuditChainHeadSink("relative/dir", "central-a"));
|
||||
}
|
||||
|
||||
/// <summary>UDP: one RFC 5424 datagram per record — PRI, version, MSGID, nil SD, JSON body.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SyslogSink_Udp_SendsOneRfc5424DatagramPerRecord()
|
||||
{
|
||||
using var server = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));
|
||||
var port = ((IPEndPoint)server.Client.LocalEndPoint!).Port;
|
||||
var sink = new SyslogAuditChainHeadSink(
|
||||
new AuditChainHeadSyslogSinkOptions { Host = "127.0.0.1", Port = port, Protocol = AuditSyslogProtocol.Udp, Facility = 13 },
|
||||
hostName: "central a", time: new FixedClock(new DateTimeOffset(2026, 5, 3, 1, 2, 3, 456, TimeSpan.Zero)));
|
||||
|
||||
await sink.WriteAsync([Record("2026-04", 3), Record("2026-05", 7)], default);
|
||||
|
||||
var first = Encoding.UTF8.GetString((await server.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5))).Buffer);
|
||||
var second = Encoding.UTF8.GetString((await server.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5))).Buffer);
|
||||
// facility 13 (log audit) * 8 + severity 5 (notice) = 109; the space in the host name is dropped.
|
||||
Assert.StartsWith($"<109>1 2026-05-03T01:02:03.456Z centrala scadabridge {Environment.ProcessId} chainhead - {{", first);
|
||||
AssertRecordBody(first, 3);
|
||||
AssertRecordBody(second, 7);
|
||||
}
|
||||
|
||||
/// <summary>TCP: octet-counted frames (RFC 6587), one per record, on one connection.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SyslogSink_Tcp_SendsOctetCountedFrames()
|
||||
{
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
try
|
||||
{
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
var received = Task.Run(async () =>
|
||||
{
|
||||
using var client = await listener.AcceptTcpClientAsync();
|
||||
using var ms = new MemoryStream();
|
||||
await client.GetStream().CopyToAsync(ms);
|
||||
return ms.ToArray();
|
||||
});
|
||||
var sink = new SyslogAuditChainHeadSink(
|
||||
new AuditChainHeadSyslogSinkOptions { Host = "127.0.0.1", Port = port, Protocol = AuditSyslogProtocol.Tcp });
|
||||
|
||||
await sink.WriteAsync([Record("2026-04", 3), Record("2026-05", 7)], default);
|
||||
|
||||
var bytes = await received.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
var frames = new List<string>();
|
||||
var i = 0;
|
||||
while (i < bytes.Length)
|
||||
{
|
||||
var space = Array.IndexOf(bytes, (byte)' ', i);
|
||||
var length = int.Parse(Encoding.ASCII.GetString(bytes, i, space - i));
|
||||
frames.Add(Encoding.UTF8.GetString(bytes, space + 1, length));
|
||||
i = space + 1 + length;
|
||||
}
|
||||
|
||||
Assert.Equal(2, frames.Count);
|
||||
Assert.All(frames, f => Assert.StartsWith("<109>1 ", f));
|
||||
AssertRecordBody(frames[0], 3);
|
||||
AssertRecordBody(frames[1], 7);
|
||||
}
|
||||
finally
|
||||
{
|
||||
listener.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
private static void AssertRecordBody(string message, long seq)
|
||||
{
|
||||
var json = message[message.IndexOf('{')..];
|
||||
var record = JsonSerializer.Deserialize<AuditChainHeadRecord>(json, new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
|
||||
Assert.Equal(seq, record.LastSeq);
|
||||
Assert.Equal(new string('a', 64), record.LastHash);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using ZB.MOM.WW.ScadaBridge.AuditLog.Central;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Central;
|
||||
|
||||
/// <summary>
|
||||
/// The hash chain and the maintenance login were removed on 2026-11-15; a node still carrying
|
||||
/// their settings (DEV/QA have <c>AuditLog__HashChain__Enabled=true</c> in the Central service
|
||||
/// env) must boot and be told the keys are ignored.
|
||||
/// </summary>
|
||||
public class RetiredAuditSettingsWarningTests
|
||||
{
|
||||
private static IConfiguration Config(params (string Key, string Value)[] values) =>
|
||||
new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(values.Select(v => new KeyValuePair<string, string?>(v.Key, v.Value)))
|
||||
.Build();
|
||||
|
||||
/// <summary>The env var left on DEV/QA (and the maintenance login) are both reported.</summary>
|
||||
[Fact]
|
||||
public void FindRetired_ReportsTheHashChainSection_AndTheMaintenanceConnectionString()
|
||||
{
|
||||
var config = Config(
|
||||
("AuditLog:HashChain:Enabled", "true"),
|
||||
("AuditLog:MaintenanceConnectionString", "Server=x;Database=y"));
|
||||
|
||||
Assert.Equal(
|
||||
[RetiredAuditSettingsWarning.HashChainSection, RetiredAuditSettingsWarning.MaintenanceConnectionStringKey],
|
||||
RetiredAuditSettingsWarning.FindRetired(config));
|
||||
}
|
||||
|
||||
/// <summary>A clean configuration (and the archive settings that remain) reports nothing.</summary>
|
||||
[Fact]
|
||||
public void FindRetired_ReportsNothing_ForCurrentSettings()
|
||||
{
|
||||
var config = Config(
|
||||
("AuditLog:Archive:Enabled", "true"),
|
||||
("AuditLog:RetentionDays", "365"),
|
||||
("AuditLog:MaintenanceConnectionString", " "));
|
||||
|
||||
Assert.Empty(RetiredAuditSettingsWarning.FindRetired(config));
|
||||
}
|
||||
}
|
||||
@@ -69,9 +69,9 @@ public class CommandTreeTests
|
||||
Assert.Contains("bundle", groupNames);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the audit command group exposes the query, export, verify-chain and archive subcommands.</summary>
|
||||
/// <summary>Verifies that the audit command group exposes the query, export and archive subcommands, and no hash-chain verify (removed 2026-11-15).</summary>
|
||||
[Fact]
|
||||
public void AuditCommandGroup_HasQueryExportAndVerifyChain()
|
||||
public void AuditCommandGroup_HasQueryExportAndArchive()
|
||||
{
|
||||
// Pin the audit sub-command surface so a rename / accidental
|
||||
// removal of one of these is caught.
|
||||
@@ -79,8 +79,9 @@ public class CommandTreeTests
|
||||
var subNames = audit.Subcommands.Select(c => c.Name).ToHashSet();
|
||||
Assert.Contains("query", subNames);
|
||||
Assert.Contains("export", subNames);
|
||||
Assert.Contains("verify-chain", subNames);
|
||||
Assert.Contains("archive", subNames);
|
||||
Assert.DoesNotContain("verify-chain", subNames);
|
||||
Assert.DoesNotContain("verify-heads", subNames);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the bundle command group exposes the export, preview and import subcommands.</summary>
|
||||
|
||||
@@ -18,17 +18,15 @@ public class AuditArchiveCommandTests
|
||||
|
||||
private const string ListBody =
|
||||
"{\"enabled\":true,\"archives\":[{\"name\":\"" + Name + "\",\"partition\":\"2025-10\",\"status\":\"Purged\"," +
|
||||
"\"rowCount\":11,\"chainedRowCount\":10,\"dataBytes\":4096}]}";
|
||||
"\"rowCount\":11,\"dataBytes\":4096}]}";
|
||||
|
||||
private const string VerifiedBody =
|
||||
"{\"name\":\"" + Name + "\",\"partition\":\"2025-10\",\"manifestStatus\":\"Purged\",\"verified\":true,\"filesIntact\":true," +
|
||||
"\"rowsRead\":11,\"chains\":[{\"chain\":{\"partition\":\"2025-10\",\"status\":\"Intact\",\"rowsVerified\":10," +
|
||||
"\"tombstonesApplied\":2,\"unchainedRows\":1},\"anchor\":\"Matches\",\"anchorDetail\":\"ends at the anchor\"}]}";
|
||||
"\"rowsRead\":11}";
|
||||
|
||||
private const string MismatchBody =
|
||||
"{\"name\":\"" + Name + "\",\"partition\":\"2025-10\",\"manifestStatus\":\"Purged\",\"verified\":false,\"filesIntact\":true," +
|
||||
"\"rowsRead\":11,\"chains\":[{\"chain\":{\"partition\":\"2025-10\",\"status\":\"Intact\",\"rowsVerified\":10," +
|
||||
"\"tombstonesApplied\":0,\"unchainedRows\":0},\"anchor\":\"Mismatch\",\"anchorDetail\":\"hash differs\"}]}";
|
||||
"{\"name\":\"" + Name + "\",\"partition\":\"2025-10\",\"manifestStatus\":\"Purged\",\"verified\":false,\"filesIntact\":false," +
|
||||
"\"fileProblem\":\"The data file holds 10 rows; the manifest records 11.\",\"rowsRead\":10}";
|
||||
|
||||
/// <summary>The audit group carries the archive group with list + verify + cleanup (ScadaBridge#109).</summary>
|
||||
[Fact]
|
||||
@@ -60,10 +58,10 @@ public class AuditArchiveCommandTests
|
||||
/// <param name="expectedText">Text the report must contain.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(VerifiedBody, "table", 0, "anchor Matches")]
|
||||
[InlineData(VerifiedBody, "table", 0, "Rows read : 11")]
|
||||
[InlineData(VerifiedBody, "json", 0, "\"verified\":true")]
|
||||
[InlineData(MismatchBody, "table", 3, "Verified : NO")]
|
||||
[InlineData(MismatchBody, "json", 3, "\"anchor\":\"Mismatch\"")]
|
||||
[InlineData(MismatchBody, "json", 3, "\"filesIntact\":false")]
|
||||
public async Task Verify_SendsVerifyAuditArchive_AndMapsVerdictToExitCode(
|
||||
string body, string format, int expectedExit, string expectedText)
|
||||
{
|
||||
|
||||
@@ -27,14 +27,14 @@ public class AuditCommandsScaffoldTests
|
||||
Assert.False(string.IsNullOrWhiteSpace(audit.Description));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the audit group exposes the query, export, tree, verify-chain, verify-heads, backfill-source-node and archive subcommands.</summary>
|
||||
/// <summary>Verifies that the audit group exposes the query, export, tree, backfill-source-node and archive subcommands (verify-chain / verify-heads removed with the hash chain, 2026-11-15).</summary>
|
||||
[Fact]
|
||||
public void Audit_HasSevenSubcommands_QueryExportTreeVerifyChainVerifyHeadsBackfillSourceNodeArchive()
|
||||
public void Audit_HasFiveSubcommands_QueryExportTreeBackfillSourceNodeArchive()
|
||||
{
|
||||
var audit = BuildAudit();
|
||||
var names = audit.Subcommands.Select(c => c.Name).OrderBy(n => n).ToArray();
|
||||
Assert.Equal(
|
||||
new[] { "archive", "backfill-source-node", "export", "query", "tree", "verify-chain", "verify-heads" },
|
||||
new[] { "archive", "backfill-source-node", "export", "query", "tree" },
|
||||
names);
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ public class AuditCommandsScaffoldTests
|
||||
Assert.Contains("query", text);
|
||||
Assert.Contains("export", text);
|
||||
Assert.Contains("tree", text);
|
||||
Assert.Contains("verify-chain", text);
|
||||
Assert.DoesNotContain("verify-chain", text);
|
||||
Assert.Contains("backfill-source-node", text);
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ public class AuditCommandsScaffoldTests
|
||||
// `archive` is a group (list / verify, ScadaBridge#42; cleanup, ScadaBridge#109): check its leaves, not it.
|
||||
var audit = BuildAudit();
|
||||
var leaves = audit.Subcommands.SelectMany(c => c.Subcommands.Count == 0 ? [c] : c.Subcommands).ToList();
|
||||
Assert.Equal(9, leaves.Count); // + verify-heads (ScadaBridge#107), archive cleanup (ScadaBridge#109)
|
||||
Assert.Equal(7, leaves.Count); // query, export, tree, backfill-source-node, archive list|verify|cleanup
|
||||
Assert.All(leaves, sub =>
|
||||
Assert.True(sub.Action != null, $"Leaf command '{sub.Name}' has no action."));
|
||||
}
|
||||
|
||||
@@ -91,12 +91,12 @@ public class AuditConfigDeprecationTests
|
||||
}
|
||||
|
||||
// The two groups are distinct objects with distinct subcommand sets:
|
||||
// `audit` has query/export/verify-chain; `audit-config` has only query.
|
||||
// `audit` has query/export/archive; `audit-config` has only query.
|
||||
var audit = root.Subcommands.Single(c => c.Name == "audit");
|
||||
var auditConfig = root.Subcommands.Single(c => c.Name == "audit-config");
|
||||
Assert.NotSame(audit, auditConfig);
|
||||
Assert.Contains(audit.Subcommands, c => c.Name == "verify-chain");
|
||||
Assert.DoesNotContain(auditConfig.Subcommands, c => c.Name == "verify-chain");
|
||||
Assert.Contains(audit.Subcommands, c => c.Name == "archive");
|
||||
Assert.DoesNotContain(auditConfig.Subcommands, c => c.Name == "archive");
|
||||
|
||||
// `audit-config` carries the deprecated `audit-log` alias; `audit` does not.
|
||||
Assert.Contains(AuditLogCommands.DeprecatedAlias, auditConfig.Aliases);
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the <c>scadabridge audit verify-chain</c> subcommand (ScadaBridge#41). The
|
||||
/// command sends the <c>VerifyAuditChain</c> management command for the month and maps
|
||||
/// the verification status onto the exit code: 0 intact / not chained, 3 broken.
|
||||
/// </summary>
|
||||
[Collection("Console")]
|
||||
public class AuditVerifyChainCommandTests
|
||||
{
|
||||
private const string IntactBody =
|
||||
"{\"partition\":\"2026-05\",\"status\":\"Intact\",\"rowsVerified\":42,\"tombstonesApplied\":1,\"headSeq\":43,\"unchainedRows\":0}";
|
||||
|
||||
private const string BrokenBody =
|
||||
"{\"partition\":\"2026-05\",\"status\":\"Broken\",\"rowsVerified\":6,\"tombstonesApplied\":0,\"headSeq\":43,\"unchainedRows\":2," +
|
||||
"\"firstBreak\":{\"partition\":\"2026-05\",\"chainSeq\":7,\"eventId\":\"11111111-2222-3333-4444-555555555555\",\"kind\":\"HashMismatch\",\"detail\":\"edited\"}}";
|
||||
|
||||
/// <summary>
|
||||
/// CLI round trip: the request carries <c>VerifyAuditChain</c> + the month, and the
|
||||
/// server's verdict drives the exit code and the report.
|
||||
/// </summary>
|
||||
/// <param name="body">The verification result the fake management endpoint serves.</param>
|
||||
/// <param name="format">Output format.</param>
|
||||
/// <param name="expectedExit">Expected exit code.</param>
|
||||
/// <param name="expectedText">Text the report must contain.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(IntactBody, "table", 0, "Status : Intact")]
|
||||
[InlineData(IntactBody, "json", 0, "\"status\":\"Intact\"")]
|
||||
[InlineData(BrokenBody, "table", 3, "eventId : 11111111-2222-3333-4444-555555555555")]
|
||||
[InlineData(BrokenBody, "json", 3, "\"chainSeq\":7")]
|
||||
public async Task VerifyChain_SendsVerifyAuditChain_AndMapsVerdictToExitCode(
|
||||
string body, string format, int expectedExit, string expectedText)
|
||||
{
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
try
|
||||
{
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
string? requestBody = null;
|
||||
var server = Task.Run(async () =>
|
||||
{
|
||||
using var client = await listener.AcceptTcpClientAsync();
|
||||
await using var stream = client.GetStream();
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
|
||||
var length = 0;
|
||||
while (await reader.ReadLineAsync() is { Length: > 0 } line)
|
||||
if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase))
|
||||
length = int.Parse(line[15..].Trim());
|
||||
var buffer = new char[length];
|
||||
var read = 0;
|
||||
while (read < length)
|
||||
{
|
||||
var count = await reader.ReadAsync(buffer.AsMemory(read));
|
||||
if (count == 0) throw new EndOfStreamException();
|
||||
read += count;
|
||||
}
|
||||
requestBody = new string(buffer);
|
||||
var bytes = Encoding.UTF8.GetBytes(body);
|
||||
var headers = Encoding.ASCII.GetBytes(
|
||||
$"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {bytes.Length}\r\nConnection: close\r\n\r\n");
|
||||
await stream.WriteAsync(headers);
|
||||
await stream.WriteAsync(bytes);
|
||||
});
|
||||
|
||||
var root = AuditCommandTestHarness.BuildRoot();
|
||||
var (exit, output, _) = AuditCommandTestHarness.Invoke(
|
||||
root, "audit", "verify-chain", "--month", "2026-05",
|
||||
"--url", $"http://127.0.0.1:{port}", "--username", "u", "--password", "p", "--format", format);
|
||||
await server.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.Equal(expectedExit, exit);
|
||||
Assert.Contains(expectedText, output);
|
||||
using var payload = JsonDocument.Parse(requestBody!);
|
||||
Assert.Equal("VerifyAuditChain", payload.RootElement.GetProperty("command").GetString());
|
||||
var month = payload.RootElement.GetProperty("payload").EnumerateObject()
|
||||
.First(p => string.Equals(p.Name, "month", StringComparison.OrdinalIgnoreCase)).Value.GetString();
|
||||
Assert.Equal("2026-05", month);
|
||||
}
|
||||
finally
|
||||
{
|
||||
listener.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a malformed month value exits non-zero without contacting the server.</summary>
|
||||
[Fact]
|
||||
public void VerifyChain_MalformedMonth_ExitsNonZero()
|
||||
{
|
||||
var root = AuditCommandTestHarness.BuildRoot();
|
||||
var (exit, _, _) = AuditCommandTestHarness.Invoke(
|
||||
root, "audit", "verify-chain", "--month", "2026-13");
|
||||
|
||||
Assert.NotEqual(0, exit);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that omitting the month option produces the required-option error.</summary>
|
||||
[Fact]
|
||||
public void VerifyChain_MissingMonth_ProducesRequiredFlagError()
|
||||
{
|
||||
var root = AuditCommandTestHarness.BuildRoot();
|
||||
var (exit, _, err) = AuditCommandTestHarness.Invoke(root, "audit", "verify-chain");
|
||||
|
||||
Assert.NotEqual(0, exit);
|
||||
Assert.Contains("--month", err);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ScadaBridge#139: the table report shows the chain cutoff and the pre-cutoff rows, and a
|
||||
/// month whose backlog is out of scope still exits 0 (pre-cutoff rows are never a break).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Render_Table_ShowsCutoffAndPreCutoffRows()
|
||||
{
|
||||
const string body = "{\"partition\":\"2026-11\",\"status\":\"Intact\",\"rowsVerified\":12,\"tombstonesApplied\":0," +
|
||||
"\"purgedThroughSeq\":null,\"headSeq\":12,\"unchainedRows\":0,\"firstBreak\":null," +
|
||||
"\"preCutoffRows\":3441,\"chainFromUtc\":\"2026-11-13T09:30:00.1234567Z\"}";
|
||||
using var output = new StringWriter();
|
||||
|
||||
var exit = AuditVerifyChainHelpers.Render(body, "table", output);
|
||||
|
||||
Assert.Equal(0, exit);
|
||||
Assert.Contains("Chain from : 2026-11-13T09:30:00.1234567Z", output.ToString());
|
||||
Assert.Contains("Pre-cutoff rows : 3441", output.ToString());
|
||||
}
|
||||
|
||||
/// <summary>A legacy (whole-table) chain renders without a cutoff.</summary>
|
||||
[Fact]
|
||||
public void Render_Table_NoCutoff_SaysWholeTable()
|
||||
{
|
||||
const string body = "{\"partition\":\"2026-05\",\"status\":\"Intact\",\"rowsVerified\":1,\"unchainedRows\":0}";
|
||||
using var output = new StringWriter();
|
||||
|
||||
Assert.Equal(0, AuditVerifyChainHelpers.Render(body, "table", output));
|
||||
Assert.Contains("Chain from : - (whole table in scope)", output.ToString());
|
||||
Assert.Contains("Pre-cutoff rows : 0", output.ToString());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that month validation accepts only values in <c>yyyy-MM</c> format.</summary>
|
||||
/// <param name="month">The month string to validate.</param>
|
||||
/// <param name="expected">Whether the month is expected to be valid.</param>
|
||||
[Theory]
|
||||
[InlineData("2026-05", true)]
|
||||
[InlineData("2026-01", true)]
|
||||
[InlineData("2026-12", true)]
|
||||
[InlineData("2026-13", false)]
|
||||
[InlineData("2026-00", false)]
|
||||
[InlineData("2026-5", false)]
|
||||
[InlineData("not-a-month", false)]
|
||||
[InlineData("", false)]
|
||||
public void IsValidMonth_ValidatesYyyyMm(string month, bool expected)
|
||||
{
|
||||
Assert.Equal(expected, AuditVerifyChainHelpers.IsValidMonth(month));
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for <c>scadabridge audit verify-heads</c> (ScadaBridge#107 item 1): reading off-box
|
||||
/// exported chain heads (file-sink lines and syslog-collector lines), collapsing duplicates,
|
||||
/// sending <c>VerifyAuditChainHeads</c>, and mapping the verdict to the exit code.
|
||||
/// </summary>
|
||||
[Collection("Console")]
|
||||
public sealed class AuditVerifyHeadsCommandTests : IDisposable
|
||||
{
|
||||
private readonly DirectoryInfo _dir = Directory.CreateTempSubdirectory("verify-heads-");
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => _dir.Delete(recursive: true);
|
||||
|
||||
private static string Line(string month, long seq, char hash, string exportedAt = "2026-05-02T00:00:00Z", string node = "central-a") =>
|
||||
"{\"v\":1,\"month\":\"" + month + "\",\"lastSeq\":" + seq + ",\"lastHash\":\"" + new string(hash, 64)
|
||||
+ "\",\"purgedThroughSeq\":null,\"purgedThroughHash\":null,\"chainedRows\":" + seq + ",\"tombstones\":0,"
|
||||
+ "\"headUpdatedAtUtc\":\"2026-05-02T00:00:00Z\",\"exportedAtUtc\":\"" + exportedAt + "\",\"node\":\"" + node + "\"}";
|
||||
|
||||
/// <summary>
|
||||
/// File-sink lines and RFC 5424 syslog lines both parse; junk is skipped; the same head
|
||||
/// exported by both nodes (and re-exported) collapses to one record.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ReadRecords_ParsesFileAndSyslogLines_SkipsJunk_AndCollapsesDuplicates()
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(_dir.FullName, "2026"));
|
||||
File.WriteAllLines(Path.Combine(_dir.FullName, "2026", "audit-chain-heads-2026-05-02-central-a.jsonl"),
|
||||
[
|
||||
Line("2026-05", 10, 'a'),
|
||||
Line("2026-05", 12, 'b'),
|
||||
"not json at all",
|
||||
"",
|
||||
]);
|
||||
File.WriteAllLines(Path.Combine(_dir.FullName, "syslog.log"),
|
||||
[
|
||||
"Nov 10 03:00:00 collector <109>1 2026-05-02T00:00:00.000Z central-b scadabridge 42 chainhead - "
|
||||
+ Line("2026-05", 12, 'b', "2026-05-02T01:00:00Z", "central-b"),
|
||||
"<109>1 2026-05-02T00:00:00.000Z central-b scadabridge 42 chainhead - " + Line("2026-04", 7, 'c'),
|
||||
]);
|
||||
File.WriteAllText(Path.Combine(_dir.FullName, "ignored.csv"), Line("2026-03", 1, 'd'));
|
||||
|
||||
var read = AuditVerifyHeadsHelpers.ReadRecords(_dir.FullName);
|
||||
|
||||
Assert.Equal(2, read.Files);
|
||||
Assert.Equal(4, read.LinesRead);
|
||||
Assert.Equal(1, read.LinesSkipped);
|
||||
Assert.Equal(["2026-04/7", "2026-05/10", "2026-05/12"], read.Records.Select(r => $"{r.Month}/{r.LastSeq}"));
|
||||
// The duplicate kept is the latest export.
|
||||
Assert.Equal("central-b", read.Records.Single(r => r.LastSeq == 12).Node);
|
||||
}
|
||||
|
||||
/// <summary>A record missing its hash or sequence is not a record.</summary>
|
||||
/// <param name="line">The line.</param>
|
||||
[Theory]
|
||||
[InlineData("{\"v\":1,\"month\":\"2026-05\",\"lastSeq\":0,\"lastHash\":\"aa\"}")]
|
||||
[InlineData("{\"v\":1,\"month\":\"2026-05\",\"lastSeq\":3}")]
|
||||
[InlineData("{\"month\":\"2026-05\",\"lastSeq\":3,\"lastHash\":\"aa\"}")]
|
||||
[InlineData("{ broken")]
|
||||
public void TryParseLine_RejectsIncompleteRecords(string line)
|
||||
{
|
||||
Assert.Null(AuditVerifyHeadsHelpers.TryParseLine(line));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Round trip: the request carries <c>VerifyAuditChainHeads</c> with the distinct records,
|
||||
/// and the verdict drives the exit code (0 verified, 3 not).
|
||||
/// </summary>
|
||||
/// <param name="verified">Whether the fake server reports verified.</param>
|
||||
/// <param name="format">Output format.</param>
|
||||
/// <param name="expectedExit">Expected exit code.</param>
|
||||
/// <param name="expectedText">Text the report must contain.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(true, "table", 0, "Verified : yes")]
|
||||
[InlineData(false, "table", 3, "Mismatch")]
|
||||
[InlineData(false, "json", 3, "\"verified\":false")]
|
||||
public async Task VerifyHeads_SendsTheRecords_AndMapsVerdictToExitCode(bool verified, string format, int expectedExit, string expectedText)
|
||||
{
|
||||
var file = Path.Combine(_dir.FullName, "heads.jsonl");
|
||||
File.WriteAllLines(file, [Line("2026-05", 12, 'b'), Line("2026-05", 12, 'b', "2026-05-02T02:00:00Z")]);
|
||||
var body = "{\"verified\":" + (verified ? "true" : "false") + ",\"recordsChecked\":1,\"checks\":[{\"month\":\"2026-05\","
|
||||
+ "\"exportedSeq\":12,\"exportedAtUtc\":\"2026-05-02T02:00:00Z\",\"node\":\"central-a\",\"status\":\""
|
||||
+ (verified ? "Matches" : "Mismatch") + "\",\"databaseSeq\":12,\"detail\":\"d\"}]}";
|
||||
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
try
|
||||
{
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
string? requestBody = null;
|
||||
var server = Task.Run(async () =>
|
||||
{
|
||||
using var client = await listener.AcceptTcpClientAsync();
|
||||
await using var stream = client.GetStream();
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
|
||||
var length = 0;
|
||||
while (await reader.ReadLineAsync() is { Length: > 0 } line)
|
||||
if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase))
|
||||
length = int.Parse(line[15..].Trim());
|
||||
var buffer = new char[length];
|
||||
var read = 0;
|
||||
while (read < length)
|
||||
{
|
||||
var count = await reader.ReadAsync(buffer.AsMemory(read));
|
||||
if (count == 0) throw new EndOfStreamException();
|
||||
read += count;
|
||||
}
|
||||
requestBody = new string(buffer);
|
||||
var bytes = Encoding.UTF8.GetBytes(body);
|
||||
var headers = Encoding.ASCII.GetBytes(
|
||||
$"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {bytes.Length}\r\nConnection: close\r\n\r\n");
|
||||
await stream.WriteAsync(headers);
|
||||
await stream.WriteAsync(bytes);
|
||||
});
|
||||
|
||||
var root = AuditCommandTestHarness.BuildRoot();
|
||||
var (exit, output, _) = AuditCommandTestHarness.Invoke(
|
||||
root, "audit", "verify-heads", "--path", file,
|
||||
"--url", $"http://127.0.0.1:{port}", "--username", "u", "--password", "p", "--format", format);
|
||||
await server.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.Equal(expectedExit, exit);
|
||||
Assert.Contains(expectedText, output);
|
||||
using var payload = JsonDocument.Parse(requestBody!);
|
||||
Assert.Equal("VerifyAuditChainHeads", payload.RootElement.GetProperty("command").GetString());
|
||||
var records = payload.RootElement.GetProperty("payload").EnumerateObject()
|
||||
.First(p => string.Equals(p.Name, "records", StringComparison.OrdinalIgnoreCase)).Value;
|
||||
Assert.Equal(1, records.GetArrayLength());
|
||||
Assert.Equal(new string('b', 64), records[0].EnumerateObject()
|
||||
.First(p => string.Equals(p.Name, "lastHash", StringComparison.OrdinalIgnoreCase)).Value.GetString());
|
||||
}
|
||||
finally
|
||||
{
|
||||
listener.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>No records found is an input error, and nothing is sent.</summary>
|
||||
[Fact]
|
||||
public void VerifyHeads_NoRecords_ExitsOneWithoutContactingTheServer()
|
||||
{
|
||||
var file = Path.Combine(_dir.FullName, "empty.jsonl");
|
||||
File.WriteAllText(file, "nothing here\n");
|
||||
var root = AuditCommandTestHarness.BuildRoot();
|
||||
var (exit, _, _) = AuditCommandTestHarness.Invoke(
|
||||
root, "audit", "verify-heads", "--path", file, "--url", "http://127.0.0.1:1", "--username", "u", "--password", "p");
|
||||
|
||||
Assert.Equal(1, exit);
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ public class ManagementSurfaceParityTests
|
||||
}
|
||||
|
||||
private static readonly HashSet<string> AuditManagementLeaves =
|
||||
["audit verify-chain", "audit verify-heads", "audit archive list", "audit archive verify", "audit archive cleanup"];
|
||||
["audit archive list", "audit archive verify", "audit archive cleanup"];
|
||||
|
||||
private static async Task<ConcurrentDictionary<string, string>> ProbeProductionTree(string? omitGroup = null)
|
||||
{
|
||||
@@ -56,12 +56,6 @@ public class ManagementSurfaceParityTests
|
||||
await File.WriteAllTextAsync(file, "{}");
|
||||
var csv = Path.Combine(directory.FullName, "native.csv");
|
||||
await File.WriteAllTextAsync(csv, "SourceName,Connection,SourceReference,Filter\nSource,Connection,Path,\n");
|
||||
// `audit verify-heads` (ScadaBridge#107) reads exported chain heads before it sends anything.
|
||||
HeadsFile = Path.Combine(directory.FullName, "heads.jsonl");
|
||||
await File.WriteAllTextAsync(HeadsFile,
|
||||
"{\"v\":1,\"month\":\"2026-05\",\"lastSeq\":3,\"lastHash\":\"" + new string('a', 64)
|
||||
+ "\",\"purgedThroughSeq\":null,\"purgedThroughHash\":null,\"chainedRows\":3,\"tombstones\":0,"
|
||||
+ "\"headUpdatedAtUtc\":\"2026-05-02T00:00:00Z\",\"exportedAtUtc\":\"2026-05-02T00:00:00Z\",\"node\":\"central-a\"}\n");
|
||||
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
@@ -102,10 +96,9 @@ public class ManagementSurfaceParityTests
|
||||
foreach (var (leaf, path) in Leaves(root, []))
|
||||
{
|
||||
// Separate REST and persistent SignalR surfaces, not management contracts.
|
||||
// `audit verify-chain` (VerifyAuditChain, ScadaBridge#41), `audit verify-heads`
|
||||
// (VerifyAuditChainHeads, ScadaBridge#107) and `audit archive
|
||||
// list|verify` (ListAuditArchives / VerifyAuditArchive, ScadaBridge#42) are the
|
||||
// audit leaves that ARE management contracts, so they stay in the probe.
|
||||
// `audit archive list|verify|cleanup` (ListAuditArchives / VerifyAuditArchive /
|
||||
// CleanupAuditArchives, ScadaBridge#42/#109) are the audit leaves that ARE
|
||||
// management contracts, so they stay in the probe.
|
||||
if (path.Length == 0 || (path[0] == "audit" && !AuditManagementLeaves.Contains(string.Join(' ', path)))
|
||||
|| path[0] == omitGroup
|
||||
|| string.Join(' ', path) == "debug stream") continue;
|
||||
@@ -142,11 +135,8 @@ public class ManagementSurfaceParityTests
|
||||
foreach (var entry in Leaves(child, [.. path, child.Name])) yield return entry;
|
||||
}
|
||||
|
||||
private static string HeadsFile = "";
|
||||
|
||||
private static string ValueFor(Option option, string path, string file, string csv)
|
||||
{
|
||||
if (path == "audit verify-heads" && option.Name == "--path") return HeadsFile;
|
||||
var type = option.GetType().GetGenericArguments().FirstOrDefault();
|
||||
type = Nullable.GetUnderlyingType(type ?? typeof(string)) ?? type;
|
||||
if (type == typeof(int) || type == typeof(long) || type == typeof(double)) return "1";
|
||||
|
||||
-5
@@ -47,11 +47,6 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;
|
||||
/// one-time ops procedure; the append-only invariant still applies to all
|
||||
/// other columns and all other UPDATE forms.
|
||||
/// </description></item>
|
||||
/// <item><description>
|
||||
/// <c>AuditLogHashChain.WriteLinksAsync</c> (ScadaBridge#41): the chaining job's
|
||||
/// <c>UPDATE dbo.AuditLog SET ChainSeq, RowHash</c>, guarded by
|
||||
/// <c>ChainSeq IS NULL</c> — it only ever fills the two hash-chain link columns once.
|
||||
/// </description></item>
|
||||
/// </list>
|
||||
/// The allow-list is applied in the file-scan test only
|
||||
/// (<see cref="ConfigurationDatabase_ShouldNotContainAuditLogMutations"/>) — the
|
||||
|
||||
+3
-5
@@ -105,9 +105,9 @@ public class AuditLogEntityTypeConfigurationTests : IDisposable
|
||||
// C5: 10 canonical columns (EventId, OccurredAtUtc, Actor, Action, Outcome,
|
||||
// Channel[=Category], Target, SourceNode, CorrelationId, DetailsJson) + 6
|
||||
// persisted computed columns (Kind, Status, SourceSiteId, ExecutionId,
|
||||
// ParentExecutionId, IngestedAtUtc) + 2 hash-chain link columns (ChainSeq,
|
||||
// RowHash — ScadaBridge#41) = 18.
|
||||
Assert.Equal(18, properties.Count);
|
||||
// ParentExecutionId, IngestedAtUtc) = 16. (The two hash-chain link columns were
|
||||
// removed with the hash chain on 2026-11-15.)
|
||||
Assert.Equal(16, properties.Count);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the channel property maps to the canonical category column.</summary>
|
||||
@@ -186,7 +186,6 @@ public class AuditLogEntityTypeConfigurationTests : IDisposable
|
||||
var expected = new[]
|
||||
{
|
||||
"IX_AuditLog_Actor_Occurred",
|
||||
"IX_AuditLog_ChainSeq", // hash chain (ScadaBridge#41)
|
||||
"IX_AuditLog_Channel_Status_Occurred",
|
||||
"IX_AuditLog_CorrelationId",
|
||||
"IX_AuditLog_Execution",
|
||||
@@ -196,7 +195,6 @@ public class AuditLogEntityTypeConfigurationTests : IDisposable
|
||||
"IX_AuditLog_ParentExecution",
|
||||
"IX_AuditLog_Site_Occurred",
|
||||
"IX_AuditLog_Target_Occurred",
|
||||
"IX_AuditLog_Unchained", // hash chain (ScadaBridge#41)
|
||||
"UX_AuditLog_EventId_Occurred", // FlipAuditLogClusteredKey (ScadaBridge#111)
|
||||
// UX_AuditLog_EventId (single-column, non-aligned) is intentionally absent —
|
||||
// dropped by AlignAuditLogEventIdUniqueness.
|
||||
|
||||
+66
-89
@@ -1,14 +1,14 @@
|
||||
using Parquet;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using Parquet.Schema;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// Storage-free tests for the AuditLog archive Parquet layout (ScadaBridge#42): rows and
|
||||
/// tombstones round-trip exactly (tick-precise timestamps, NULL vs empty strings, unicode,
|
||||
/// the chain columns), the archived rows re-verify against the archived chain head, and an
|
||||
/// edit made inside the Parquet file breaks that verification.
|
||||
/// Storage-free tests for the AuditLog archive Parquet layout (ScadaBridge#42): rows round-trip
|
||||
/// exactly (tick-precise timestamps, NULL vs empty strings, unicode), and a format-v1 data file
|
||||
/// — written while the hash chain existed, with its <c>ChainSeq</c>/<c>RowHash</c> columns —
|
||||
/// still reads.
|
||||
/// </summary>
|
||||
public class AuditArchiveParquetTests
|
||||
{
|
||||
@@ -19,8 +19,7 @@ public class AuditArchiveParquetTests
|
||||
[Fact]
|
||||
public async Task Rows_RoundTrip_Exactly_AcrossRowGroups()
|
||||
{
|
||||
var (rows, _) = BuildChain(2_503);
|
||||
rows.Add(Row(9_999) with { ChainSeq = null, RowHash = null }); // an unchained row
|
||||
var rows = Enumerable.Range(1, 2_503).Select(Row).ToList();
|
||||
|
||||
var bytes = await WriteAsync(rows, rowGroupSize: 1_000);
|
||||
var back = await ReadAsync(bytes);
|
||||
@@ -28,100 +27,44 @@ public class AuditArchiveParquetTests
|
||||
Assert.Equal(rows.Select(Key), back.Select(Key));
|
||||
await using var reader = await ParquetReader.CreateAsync(new MemoryStream(bytes));
|
||||
Assert.Equal(3, reader.RowGroupCount);
|
||||
Assert.Equal("1", reader.CustomMetadata[AuditArchiveParquet.FormatVersionKey]);
|
||||
Assert.Equal("2", reader.CustomMetadata[AuditArchiveParquet.FormatVersionKey]);
|
||||
Assert.Equal("2025-10", reader.CustomMetadata[AuditArchiveParquet.PartitionKey]);
|
||||
}
|
||||
|
||||
/// <summary>Tombstones round-trip exactly.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
/// <summary>The v2 data file carries the ten stored columns and nothing from the removed hash chain.</summary>
|
||||
[Fact]
|
||||
public async Task Tombstones_RoundTrip_Exactly()
|
||||
public void DataSchema_HasNoChainColumns()
|
||||
{
|
||||
var tombstones = Enumerable.Range(1, 5).Select(i => new AuditArchiveTombstone(
|
||||
Month, i * 3, Enumerable.Repeat((byte)i, 32).ToArray(), Guid.NewGuid(),
|
||||
new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc).AddMilliseconds(i))).ToList();
|
||||
|
||||
var stream = new MemoryStream();
|
||||
await using (var writer = await AuditArchiveParquet.CreateTombstoneWriterAsync(stream, "2025-10", 2))
|
||||
{
|
||||
foreach (var t in tombstones)
|
||||
{
|
||||
await writer.AddAsync(t);
|
||||
}
|
||||
}
|
||||
|
||||
var back = new List<AuditArchiveTombstone>();
|
||||
await foreach (var t in AuditArchiveParquet.ReadTombstonesAsync(new MemoryStream(stream.ToArray())))
|
||||
{
|
||||
back.Add(t);
|
||||
}
|
||||
|
||||
Assert.Equal(
|
||||
tombstones.Select(t => (t.ChainMonth, t.ChainSeq, Convert.ToHexString(t.RowHash), t.EventId, t.PurgedAtUtc)),
|
||||
back.Select(t => (t.ChainMonth, t.ChainSeq, Convert.ToHexString(t.RowHash), t.EventId, t.PurgedAtUtc)));
|
||||
var names = AuditArchiveParquet.DataSchema.DataFields.Select(f => f.Name).ToList();
|
||||
Assert.DoesNotContain("ChainSeq", names);
|
||||
Assert.DoesNotContain("RowHash", names);
|
||||
Assert.Contains("DetailsJson", names); // positive control: the schema was read
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rows read back from an archive re-verify against the archived head — the same
|
||||
/// check <c>audit archive verify</c> makes long after the database dropped them.
|
||||
/// A format-v1 archive data file (the v2 columns plus <c>ChainSeq</c>/<c>RowHash</c>) reads
|
||||
/// with the v2 reader: the extra columns are ignored and every stored column is intact.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ArchivedRows_ReverifyAgainstTheArchivedHead()
|
||||
public async Task FormatV1DataFile_WithChainColumns_StillReads()
|
||||
{
|
||||
var (rows, head) = BuildChain(50);
|
||||
var verifier = new AuditChainVerifier(Month, head, new Dictionary<long, byte[]>());
|
||||
foreach (var row in await ReadAsync(await WriteAsync(rows, 16)))
|
||||
var rows = Enumerable.Range(1, 40).Select(Row).ToList();
|
||||
var bytes = await WriteV1Async(rows);
|
||||
|
||||
await using (var raw = await ParquetReader.CreateAsync(new MemoryStream(bytes)))
|
||||
{
|
||||
verifier.Accept(row);
|
||||
// Positive control: the file really carries the v1 chain columns.
|
||||
Assert.Contains(raw.Schema.DataFields, f => f.Name == "ChainSeq");
|
||||
}
|
||||
|
||||
var result = verifier.Complete(0);
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(50, result.RowsVerified);
|
||||
var back = await ReadAsync(bytes);
|
||||
Assert.Equal(rows.Select(Key), back.Select(Key));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Positive control for the test above: a row edited inside the archive (re-written
|
||||
/// file, as a forger would) fails re-verification at that row.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RowEditedInsideTheArchive_FailsReverification()
|
||||
{
|
||||
var (rows, head) = BuildChain(50);
|
||||
rows[17] = rows[17] with { DetailsJson = "{\"kind\":\"ApiCall\",\"forged\":true}" };
|
||||
|
||||
var verifier = new AuditChainVerifier(Month, head, new Dictionary<long, byte[]>());
|
||||
foreach (var row in await ReadAsync(await WriteAsync(rows, 16)))
|
||||
{
|
||||
verifier.Accept(row);
|
||||
}
|
||||
|
||||
var result = verifier.Complete(0);
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, result.FirstBreak!.Kind);
|
||||
Assert.Equal(18, result.FirstBreak.ChainSeq);
|
||||
}
|
||||
|
||||
internal static (List<AuditChainRow> Rows, AuditChainHeadState Head) BuildChain(int count)
|
||||
{
|
||||
var rows = new List<AuditChainRow>();
|
||||
var previous = AuditChainHasher.GenesisHash.ToArray();
|
||||
for (var i = 1; i <= count; i++)
|
||||
{
|
||||
var row = Row(i);
|
||||
var hash = AuditChainHasher.ComputeRowHash(previous, Month, i, row);
|
||||
rows.Add(row with { ChainSeq = i, RowHash = hash });
|
||||
previous = hash;
|
||||
}
|
||||
|
||||
return (rows, new AuditChainHeadState(count, previous, null, null));
|
||||
}
|
||||
|
||||
private static AuditChainRow Row(int i) => new(
|
||||
private static AuditArchiveRow Row(int i) => new(
|
||||
Guid.NewGuid(),
|
||||
// Odd ticks on purpose: the archive must keep datetime2(7) precision the hash covers.
|
||||
// Odd ticks on purpose: the archive must keep datetime2(7) precision.
|
||||
Month.AddMinutes(i).AddTicks(1_234_567 + i),
|
||||
i % 5 == 0 ? null : i % 7 == 0 ? string.Empty : "api-key-" + i,
|
||||
"ApiOutbound.ApiCall",
|
||||
@@ -132,12 +75,11 @@ public class AuditArchiveParquetTests
|
||||
i % 2 == 0 ? Guid.NewGuid() : null,
|
||||
i % 8 == 0 ? null : $"{{\"kind\":\"ApiCall\",\"status\":\"Delivered\",\"n\":{i}}}");
|
||||
|
||||
private static string Key(AuditChainRow r) => string.Join('|',
|
||||
private static string Key(AuditArchiveRow r) => string.Join('|',
|
||||
r.EventId, r.OccurredAtUtc.Ticks, r.OccurredAtUtc.Kind, r.Actor ?? "<null>", r.Action, r.Outcome, r.Category,
|
||||
r.Target ?? "<null>", r.SourceNode ?? "<null>", r.CorrelationId?.ToString() ?? "<null>", r.DetailsJson ?? "<null>",
|
||||
r.ChainSeq?.ToString() ?? "<null>", r.RowHash is null ? "<null>" : Convert.ToHexString(r.RowHash));
|
||||
r.Target ?? "<null>", r.SourceNode ?? "<null>", r.CorrelationId?.ToString() ?? "<null>", r.DetailsJson ?? "<null>");
|
||||
|
||||
private static async Task<byte[]> WriteAsync(IEnumerable<AuditChainRow> rows, int rowGroupSize)
|
||||
internal static async Task<byte[]> WriteAsync(IEnumerable<AuditArchiveRow> rows, int rowGroupSize)
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
await using (var writer = await AuditArchiveParquet.CreateDataWriterAsync(stream, "2025-10", rowGroupSize))
|
||||
@@ -151,9 +93,44 @@ public class AuditArchiveParquetTests
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
private static async Task<List<AuditChainRow>> ReadAsync(byte[] bytes)
|
||||
/// <summary>Writes rows in the format-v1 layout: the v2 columns, then the two chain columns.</summary>
|
||||
private static async Task<byte[]> WriteV1Async(IReadOnlyList<AuditArchiveRow> rows)
|
||||
{
|
||||
var rows = new List<AuditChainRow>();
|
||||
var v2 = AuditArchiveParquet.DataSchema.DataFields;
|
||||
var chainSeq = new DataField<long>("ChainSeq", true);
|
||||
var rowHash = new DataField<byte[]>("RowHash", true);
|
||||
var schema = new ParquetSchema(v2.Cast<Field>().Append(chainSeq).Append(rowHash).ToArray());
|
||||
|
||||
var stream = new MemoryStream();
|
||||
await using (var writer = await ParquetWriter.CreateAsync(schema, stream))
|
||||
{
|
||||
writer.CustomMetadata = new Dictionary<string, string>
|
||||
{
|
||||
[AuditArchiveParquet.FormatVersionKey] = "1",
|
||||
[AuditArchiveParquet.PartitionKey] = "2025-10",
|
||||
};
|
||||
using var group = writer.CreateRowGroup();
|
||||
await group.WriteAsync((DataField<string>)v2[0], rows.Select(r => r.EventId.ToString("D")).ToArray());
|
||||
await group.WriteAsync<DateTime>((DateTimeDataField)v2[1], rows.Select(r => r.OccurredAtUtc).ToArray());
|
||||
await group.WriteAsync<long>((DataField<long>)v2[2], rows.Select(r => r.OccurredAtUtc.Ticks).ToArray());
|
||||
await group.WriteAsync((DataField<string>)v2[3], rows.Select(r => r.Actor).ToArray()!);
|
||||
await group.WriteAsync((DataField<string>)v2[4], rows.Select(r => r.Action).ToArray());
|
||||
await group.WriteAsync((DataField<string>)v2[5], rows.Select(r => r.Outcome).ToArray());
|
||||
await group.WriteAsync((DataField<string>)v2[6], rows.Select(r => r.Category).ToArray());
|
||||
await group.WriteAsync((DataField<string>)v2[7], rows.Select(r => r.Target).ToArray()!);
|
||||
await group.WriteAsync((DataField<string>)v2[8], rows.Select(r => r.SourceNode).ToArray()!);
|
||||
await group.WriteAsync((DataField<string>)v2[9], rows.Select(r => r.CorrelationId?.ToString("D")).ToArray()!);
|
||||
await group.WriteAsync((DataField<string>)v2[10], rows.Select(r => r.DetailsJson).ToArray()!);
|
||||
await group.WriteAsync<long>(chainSeq, rows.Select((_, i) => (long?)(i + 1)).ToArray());
|
||||
await group.WriteAsync(rowHash, rows.Select(_ => new byte[32]).ToArray());
|
||||
}
|
||||
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
internal static async Task<List<AuditArchiveRow>> ReadAsync(byte[] bytes)
|
||||
{
|
||||
var rows = new List<AuditArchiveRow>();
|
||||
await foreach (var row in AuditArchiveParquet.ReadRowsAsync(new MemoryStream(bytes)))
|
||||
{
|
||||
rows.Add(row);
|
||||
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// Pure verdict table of <see cref="AuditChainHeadComparer"/> (ScadaBridge#107 item 1) for the
|
||||
/// branches the SQL Server tests do not reach: a link carried by a tombstone, the partition
|
||||
/// anchor itself, and malformed input.
|
||||
/// </summary>
|
||||
public sealed class AuditChainHeadComparerTests
|
||||
{
|
||||
private static readonly byte[] H1 = Enumerable.Repeat((byte)1, 32).ToArray();
|
||||
private static readonly byte[] H2 = Enumerable.Repeat((byte)2, 32).ToArray();
|
||||
|
||||
private static AuditChainHeadRecord Exported(long seq, byte[] hash) => new(
|
||||
1, "2026-05", seq, AuditChainHeadComparer.ToHex(hash), null, null, seq, 0, DateTime.UtcNow, DateTime.UtcNow, "central-a");
|
||||
|
||||
private static AuditChainHeadSnapshot Head(long seq, byte[] hash, long? anchor = null, byte[]? anchorHash = null) =>
|
||||
new(new DateTime(2026, 5, 1, 0, 0, 0, DateTimeKind.Utc), seq, hash, anchor, anchorHash, seq, 0, DateTime.UtcNow);
|
||||
|
||||
private static Func<long, Task<AuditChainHeadComparer.StoredLink>> Link(byte[]? row, byte[]? tombstone)
|
||||
=> _ => Task.FromResult(new AuditChainHeadComparer.StoredLink(row, tombstone));
|
||||
|
||||
private static Func<long, Task<AuditChainHeadComparer.StoredLink>> NoLookup
|
||||
=> _ => throw new InvalidOperationException("no link lookup expected");
|
||||
|
||||
/// <summary>The exported link was later purged per channel: the tombstone carries the hash.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GrownChain_LinkOnATombstone_IsExtended_OrMismatch()
|
||||
{
|
||||
Assert.Equal(AuditChainHeadStatus.Extended,
|
||||
(await AuditChainHeadComparer.CompareAsync(Exported(3, H1), Head(9, H2), Link(null, H1))).Status);
|
||||
Assert.Equal(AuditChainHeadStatus.Mismatch,
|
||||
(await AuditChainHeadComparer.CompareAsync(Exported(3, H1), Head(9, H2), Link(null, H2))).Status);
|
||||
}
|
||||
|
||||
/// <summary>The exported head is the partition-purge anchor: compared with the anchor's hash, no lookup.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GrownChain_ExportedHeadIsTheAnchor_ComparesTheAnchorHash()
|
||||
{
|
||||
Assert.Equal(AuditChainHeadStatus.Extended,
|
||||
(await AuditChainHeadComparer.CompareAsync(Exported(4, H1), Head(9, H2, 4, H1), NoLookup)).Status);
|
||||
Assert.Equal(AuditChainHeadStatus.Mismatch,
|
||||
(await AuditChainHeadComparer.CompareAsync(Exported(4, H1), Head(9, H2, 4, H2), NoLookup)).Status);
|
||||
Assert.Equal(AuditChainHeadStatus.Purged,
|
||||
(await AuditChainHeadComparer.CompareAsync(Exported(2, H1), Head(9, H2, 4, H2), NoLookup)).Status);
|
||||
}
|
||||
|
||||
/// <summary>A record whose hash is not 32 bytes of hex can never match.</summary>
|
||||
/// <param name="hash">The exported hash text.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData("abc")]
|
||||
[InlineData("zz0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")]
|
||||
public async Task MalformedExportedHash_IsMismatch(string hash)
|
||||
{
|
||||
var record = Exported(3, H1) with { LastHash = hash };
|
||||
Assert.Equal(AuditChainHeadStatus.Mismatch,
|
||||
(await AuditChainHeadComparer.CompareAsync(record, Head(3, H1), NoLookup)).Status);
|
||||
}
|
||||
|
||||
/// <summary>Only the tamper verdicts count as failures.</summary>
|
||||
/// <param name="status">The verdict.</param>
|
||||
/// <param name="failure">Whether it is a failure.</param>
|
||||
[Theory]
|
||||
[InlineData(AuditChainHeadStatus.Matches, false)]
|
||||
[InlineData(AuditChainHeadStatus.Extended, false)]
|
||||
[InlineData(AuditChainHeadStatus.Purged, false)]
|
||||
[InlineData(AuditChainHeadStatus.Mismatch, true)]
|
||||
[InlineData(AuditChainHeadStatus.Regressed, true)]
|
||||
[InlineData(AuditChainHeadStatus.MissingHead, true)]
|
||||
[InlineData(AuditChainHeadStatus.MissingLink, true)]
|
||||
[InlineData(AuditChainHeadStatus.CountMismatch, true)]
|
||||
public void IsFailure_IsTrueOnlyForTamperVerdicts(AuditChainHeadStatus status, bool failure)
|
||||
{
|
||||
Assert.Equal(failure, new AuditChainHeadCheck("2026-05", 1, DateTime.UtcNow, null, status, 1, "").IsFailure);
|
||||
}
|
||||
}
|
||||
-312
@@ -1,312 +0,0 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ZB.MOM.WW.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server tests for the chain-head export store (ScadaBridge#107 item 1): heads read with
|
||||
/// their counts, and exported heads checked against the database. The key case is the forgery
|
||||
/// the export exists for: rows rewritten AND every later link and the head recomputed — which
|
||||
/// <c>verify-chain</c> accepts — is caught because the exported hash no longer matches.
|
||||
/// </summary>
|
||||
/// <remarks>Each test owns one month (partition) of the shared fixture database.</remarks>
|
||||
public sealed class AuditChainHeadStoreTests : IClassFixture<MsSqlMigrationFixture>
|
||||
{
|
||||
private readonly MsSqlMigrationFixture _fixture;
|
||||
|
||||
/// <summary>Creates the test class with the shared migrated SQL Server fixture.</summary>
|
||||
/// <param name="fixture">The shared migration fixture.</param>
|
||||
public AuditChainHeadStoreTests(MsSqlMigrationFixture fixture) => _fixture = fixture;
|
||||
|
||||
/// <summary>The head snapshot carries the chain end and the live row + tombstone counts.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ReadHeads_ReportsTheChainEnd_AndRowAndTombstoneCounts()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 3);
|
||||
await InsertAsync(Enumerable.Range(1, 5).Select(i => NewEvent(month.AddDays(i))));
|
||||
await InsertAsync([NewEvent(month.AddHours(1), AuditChannel.DbOutbound)]);
|
||||
await DrainAsync();
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
Assert.Equal(1, await new AuditLogRepository(ctx).PurgeChannelOlderThanAsync("DbOutbound", month.AddDays(1), 100));
|
||||
}
|
||||
|
||||
var head = await HeadAsync(month);
|
||||
|
||||
Assert.Equal(6, head.LastSeq);
|
||||
Assert.Equal(5, head.ChainedRows);
|
||||
Assert.Equal(1, head.Tombstones);
|
||||
Assert.Null(head.PurgedThroughSeq);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unchanged chain: Matches. The chain grew: Extended. Both centrals' duplicate exports
|
||||
/// collapse to one check.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ExportedHeads_MatchTheUnchangedChain_AndAreExtendedByLaterLinks()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 4);
|
||||
await InsertAsync(Enumerable.Range(1, 4).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var exported = Export(await HeadAsync(month));
|
||||
|
||||
var same = await VerifyAsync(exported, exported with { Node = "central-b" });
|
||||
Assert.True(same.Verified);
|
||||
Assert.Equal(AuditChainHeadStatus.Matches, Assert.Single(same.Checks).Status);
|
||||
|
||||
await InsertAsync([NewEvent(month.AddDays(10))]);
|
||||
await DrainAsync();
|
||||
var grown = await VerifyAsync(exported);
|
||||
Assert.True(grown.Verified);
|
||||
var check = Assert.Single(grown.Checks);
|
||||
Assert.Equal(AuditChainHeadStatus.Extended, check.Status);
|
||||
Assert.Equal(5, check.DatabaseSeq);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The forgery: a chained row's content is rewritten and every link from it plus the head
|
||||
/// are recomputed with the real hasher. <c>VerifyMonthAsync</c> reports the forged chain
|
||||
/// Intact (positive control: the in-database chain alone cannot see it); the exported head
|
||||
/// does not match it.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ARewrittenAndRehashedChain_PassesVerifyChain_ButFailsTheExportedHead()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 5);
|
||||
await InsertAsync(Enumerable.Range(1, 6).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var exported = Export(await HeadAsync(month));
|
||||
|
||||
await ForgeChainAsync(month, fromSeq: 3);
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
var chain = await new AuditLogHashChain(ctx).VerifyMonthAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Intact, chain.Status);
|
||||
}
|
||||
|
||||
var result = await VerifyAsync(exported);
|
||||
Assert.False(result.Verified);
|
||||
Assert.Equal(AuditChainHeadStatus.Mismatch, Assert.Single(result.Checks).Status);
|
||||
}
|
||||
|
||||
/// <summary>Each structural tampering maps to its own verdict.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task TamperedHeadsAndRows_AreReported_WithTheirOwnVerdicts()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
|
||||
// Head rolled back below the export (tail deletion + head rewrite).
|
||||
var regressed = Month(2026, 6);
|
||||
await InsertAsync(Enumerable.Range(1, 3).Select(i => NewEvent(regressed.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var regressedExport = Export(await HeadAsync(regressed));
|
||||
await ExecAsync("UPDATE dbo.AuditLogChainHead SET LastSeq = LastSeq - 1 WHERE ChainMonth = @m;", regressed);
|
||||
|
||||
// Head row deleted.
|
||||
var missingHead = Month(2026, 7);
|
||||
await InsertAsync([NewEvent(missingHead.AddDays(1))]);
|
||||
await DrainAsync();
|
||||
var missingHeadExport = Export(await HeadAsync(missingHead));
|
||||
await ExecAsync("DELETE FROM dbo.AuditLogChainHead WHERE ChainMonth = @m;", missingHead);
|
||||
|
||||
// A chained row deleted with no tombstone, head unchanged: counts no longer add up.
|
||||
var counted = Month(2026, 8);
|
||||
await InsertAsync(Enumerable.Range(1, 3).Select(i => NewEvent(counted.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var countedExport = Export(await HeadAsync(counted));
|
||||
await ExecAsync("DELETE FROM dbo.AuditLog WHERE ChainSeq = 2 AND OccurredAtUtc >= @m AND OccurredAtUtc < DATEADD(MONTH, 1, @m);", counted);
|
||||
|
||||
// The exported link itself deleted after the chain grew past it.
|
||||
var missingLink = Month(2026, 9);
|
||||
await InsertAsync(Enumerable.Range(1, 2).Select(i => NewEvent(missingLink.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var missingLinkExport = Export(await HeadAsync(missingLink));
|
||||
await InsertAsync([NewEvent(missingLink.AddDays(5))]);
|
||||
await DrainAsync();
|
||||
await ExecAsync("DELETE FROM dbo.AuditLog WHERE ChainSeq = 2 AND OccurredAtUtc >= @m AND OccurredAtUtc < DATEADD(MONTH, 1, @m);", missingLink);
|
||||
|
||||
var result = await VerifyAsync(regressedExport, missingHeadExport, countedExport, missingLinkExport);
|
||||
|
||||
Assert.False(result.Verified);
|
||||
var byMonth = result.Checks.ToDictionary(c => c.Month, c => c.Status);
|
||||
Assert.Equal(AuditChainHeadStatus.Regressed, byMonth["2026-06"]);
|
||||
Assert.Equal(AuditChainHeadStatus.MissingHead, byMonth["2026-07"]);
|
||||
Assert.Equal(AuditChainHeadStatus.CountMismatch, byMonth["2026-08"]);
|
||||
Assert.Equal(AuditChainHeadStatus.MissingLink, byMonth["2026-09"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sanctioned purges are not tamper evidence: a per-channel purge (row to tombstone) keeps
|
||||
/// Matches; after a partition switch the exported head is the anchor, so the check still
|
||||
/// passes, and an older exported sequence the switch removed is reported Purged.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task SanctionedPurges_AreNotFailures()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 10);
|
||||
await InsertAsync(Enumerable.Range(1, 3).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var early = Export(await HeadAsync(month));
|
||||
await InsertAsync([NewEvent(month.AddDays(5), AuditChannel.Notification)]);
|
||||
await DrainAsync();
|
||||
var late = Export(await HeadAsync(month));
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
Assert.Equal(1, await new AuditLogRepository(ctx).PurgeChannelOlderThanAsync("Notification", month.AddDays(6), 100));
|
||||
}
|
||||
|
||||
Assert.Equal(AuditChainHeadStatus.Matches, Assert.Single((await VerifyAsync(late)).Checks).Status);
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
await new AuditLogRepository(ctx).SwitchOutPartitionAsync(month);
|
||||
}
|
||||
|
||||
var afterSwitch = await VerifyAsync(late, early);
|
||||
Assert.True(afterSwitch.Verified);
|
||||
var statuses = afterSwitch.Checks.ToDictionary(c => c.ExportedSeq, c => c.Status);
|
||||
Assert.Equal(AuditChainHeadStatus.Matches, statuses[4]);
|
||||
Assert.Equal(AuditChainHeadStatus.Purged, statuses[3]);
|
||||
}
|
||||
|
||||
private static AuditChainHeadRecord Export(AuditChainHeadSnapshot head) => new(
|
||||
AuditChainHeadRecord.CurrentVersion,
|
||||
AuditChainHasher.PartitionLabel(head.Month),
|
||||
head.LastSeq,
|
||||
AuditChainHeadComparer.ToHex(head.LastHash),
|
||||
head.PurgedThroughSeq,
|
||||
head.PurgedThroughHash is null ? null : AuditChainHeadComparer.ToHex(head.PurgedThroughHash),
|
||||
head.ChainedRows,
|
||||
head.Tombstones,
|
||||
head.UpdatedAtUtc,
|
||||
DateTime.UtcNow,
|
||||
"central-a");
|
||||
|
||||
private async Task<AuditChainHeadSnapshot> HeadAsync(DateTime month)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var heads = await new AuditLogHashChain(ctx).ReadHeadsAsync();
|
||||
return Assert.Single(heads, h => h.Month == month);
|
||||
}
|
||||
|
||||
private async Task<AuditChainHeadVerificationResult> VerifyAsync(params AuditChainHeadRecord[] records)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
return await new AuditLogHashChain(ctx).VerifyExportedHeadsAsync(records);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites the row at <paramref name="fromSeq"/> and re-links it and every later row plus the
|
||||
/// head with the production hasher — what a principal with full write access could do.
|
||||
/// </summary>
|
||||
private async Task ForgeChainAsync(DateTime month, long fromSeq)
|
||||
{
|
||||
await using var conn = _fixture.OpenConnection();
|
||||
await using (var edit = new SqlCommand(
|
||||
"UPDATE dbo.AuditLog SET Target = N'forged' WHERE ChainSeq = @s AND OccurredAtUtc >= @m AND OccurredAtUtc < DATEADD(MONTH, 1, @m);", conn))
|
||||
{
|
||||
edit.Parameters.AddWithValue("@s", fromSeq);
|
||||
edit.Parameters.Add(new SqlParameter("@m", System.Data.SqlDbType.DateTime2) { Scale = 7, Value = month });
|
||||
Assert.Equal(1, await edit.ExecuteNonQueryAsync());
|
||||
}
|
||||
|
||||
var rows = new List<AuditChainRow>();
|
||||
await using (var read = new SqlCommand(
|
||||
$"SELECT {AuditLogHashChain.RowColumns}, ChainSeq, RowHash FROM dbo.AuditLog " +
|
||||
"WHERE ChainSeq IS NOT NULL AND OccurredAtUtc >= @m AND OccurredAtUtc < DATEADD(MONTH, 1, @m) ORDER BY ChainSeq;", conn))
|
||||
{
|
||||
read.Parameters.Add(new SqlParameter("@m", System.Data.SqlDbType.DateTime2) { Scale = 7, Value = month });
|
||||
await using var reader = await read.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
rows.Add(AuditLogHashChain.ReadRow(reader, withLink: true));
|
||||
}
|
||||
}
|
||||
|
||||
var previous = rows.Single(r => r.ChainSeq == fromSeq - 1).RowHash!;
|
||||
foreach (var row in rows.Where(r => r.ChainSeq >= fromSeq))
|
||||
{
|
||||
var hash = AuditChainHasher.ComputeRowHash(previous, month, row.ChainSeq!.Value, row);
|
||||
await using var update = new SqlCommand("UPDATE dbo.AuditLog SET RowHash = @h WHERE EventId = @e AND OccurredAtUtc = @o;", conn);
|
||||
update.Parameters.AddWithValue("@h", hash);
|
||||
update.Parameters.AddWithValue("@e", row.EventId);
|
||||
update.Parameters.Add(new SqlParameter("@o", System.Data.SqlDbType.DateTime2) { Scale = 7, Value = row.OccurredAtUtc });
|
||||
Assert.Equal(1, await update.ExecuteNonQueryAsync());
|
||||
previous = hash;
|
||||
}
|
||||
|
||||
await using var head = new SqlCommand("UPDATE dbo.AuditLogChainHead SET LastHash = @h WHERE ChainMonth = @m;", conn);
|
||||
head.Parameters.AddWithValue("@h", previous);
|
||||
head.Parameters.Add(new SqlParameter("@m", System.Data.SqlDbType.Date) { Value = month });
|
||||
Assert.Equal(1, await head.ExecuteNonQueryAsync());
|
||||
}
|
||||
|
||||
private async Task ExecAsync(string sql, DateTime month)
|
||||
{
|
||||
await using var conn = _fixture.OpenConnection();
|
||||
await using var cmd = new SqlCommand(sql, conn);
|
||||
cmd.Parameters.Add(new SqlParameter("@m", System.Data.SqlDbType.DateTime2) { Scale = 7, Value = month });
|
||||
Assert.True(await cmd.ExecuteNonQueryAsync() >= 1);
|
||||
}
|
||||
|
||||
private async Task InsertAsync(IEnumerable<AuditEvent> events)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var repo = new AuditLogRepository(ctx);
|
||||
foreach (var e in events)
|
||||
{
|
||||
await repo.InsertIfNotExistsAsync(e);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DrainAsync()
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var chain = new AuditLogHashChain(ctx);
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var r = await chain.ChainPendingAsync(500, chainBacklog: true);
|
||||
if (r.RowsChained == 0 && !r.LockBusy)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Chain did not drain.");
|
||||
}
|
||||
|
||||
private static DateTime Month(int year, int month) => new(year, month, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private ScadaBridgeDbContext CreateContext()
|
||||
=> new(new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlServer(_fixture.ConnectionString).Options);
|
||||
|
||||
private static AuditEvent NewEvent(DateTime occurredAtUtc, AuditChannel channel = AuditChannel.ApiOutbound) =>
|
||||
ScadaBridgeAuditEventFactory.Create(
|
||||
channel: channel,
|
||||
kind: channel == AuditChannel.DbOutbound ? AuditKind.DbWrite : AuditKind.ApiCall,
|
||||
status: AuditStatus.Delivered,
|
||||
occurredAtUtc: occurredAtUtc,
|
||||
actor: "head-test",
|
||||
target: "erp",
|
||||
sourceNode: "central-a",
|
||||
sourceSiteId: "head-test",
|
||||
correlationId: Guid.NewGuid());
|
||||
}
|
||||
-370
@@ -1,370 +0,0 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// Storage-free tests for the AuditLog hash-chain hasher + verifier (ScadaBridge#41):
|
||||
/// tamper detection for an edited, a deleted and a reordered row, tombstone and
|
||||
/// partition-anchor bridging, and a pinned known-answer vector for the v1 canonical form.
|
||||
/// </summary>
|
||||
public class AuditChainVerifierTests
|
||||
{
|
||||
private static readonly DateTime Month = new(2026, 5, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
/// <summary>An untouched chain verifies intact and covers every row.</summary>
|
||||
[Fact]
|
||||
public void IntactChain_Verifies()
|
||||
{
|
||||
var (rows, head) = BuildChain(5);
|
||||
var result = Verify(rows, head);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(5, result.RowsVerified);
|
||||
Assert.Null(result.FirstBreak);
|
||||
}
|
||||
|
||||
/// <summary>Editing any stored column of a chained row is a HashMismatch at that row.</summary>
|
||||
[Fact]
|
||||
public void EditedRow_IsHashMismatch_AtThatRow()
|
||||
{
|
||||
var (rows, head) = BuildChain(5);
|
||||
rows[2] = rows[2] with { Target = "tampered" };
|
||||
|
||||
var result = Verify(rows, head);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, result.FirstBreak!.Kind);
|
||||
Assert.Equal(3, result.FirstBreak.ChainSeq);
|
||||
Assert.Equal(rows[2].EventId, result.FirstBreak.EventId);
|
||||
Assert.Equal("2026-05", result.FirstBreak.Partition);
|
||||
Assert.Equal(2, result.RowsVerified);
|
||||
}
|
||||
|
||||
/// <summary>A row deleted from the middle (no tombstone) is a MissingRow at its sequence number.</summary>
|
||||
[Fact]
|
||||
public void DeletedMiddleRow_IsMissingRow()
|
||||
{
|
||||
var (rows, head) = BuildChain(5);
|
||||
var deleted = rows[1];
|
||||
rows.RemoveAt(1);
|
||||
|
||||
var result = Verify(rows, head);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.MissingRow, result.FirstBreak!.Kind);
|
||||
Assert.Equal(deleted.ChainSeq, result.FirstBreak.ChainSeq);
|
||||
Assert.Equal(rows[1].EventId, result.FirstBreak.EventId); // the next surviving row
|
||||
}
|
||||
|
||||
/// <summary>Deleting the newest rows leaves a self-consistent prefix; the head catches it.</summary>
|
||||
[Fact]
|
||||
public void DeletedTailRows_IsHeadMismatch()
|
||||
{
|
||||
var (rows, head) = BuildChain(5);
|
||||
rows.RemoveRange(3, 2);
|
||||
|
||||
var result = Verify(rows, head);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HeadMismatch, result.FirstBreak!.Kind);
|
||||
Assert.Equal(4, result.FirstBreak.ChainSeq);
|
||||
Assert.Null(result.FirstBreak.EventId);
|
||||
}
|
||||
|
||||
/// <summary>Swapping two rows' sequence numbers is a HashMismatch at the first moved row.</summary>
|
||||
[Fact]
|
||||
public void ReorderedRows_IsHashMismatch()
|
||||
{
|
||||
var (rows, head) = BuildChain(5);
|
||||
var a = rows[1];
|
||||
var b = rows[3];
|
||||
rows[1] = b with { ChainSeq = a.ChainSeq };
|
||||
rows[3] = a with { ChainSeq = b.ChainSeq };
|
||||
|
||||
var result = Verify(rows, head);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, result.FirstBreak!.Kind);
|
||||
Assert.Equal(2, result.FirstBreak.ChainSeq);
|
||||
Assert.Equal(b.EventId, result.FirstBreak.EventId);
|
||||
}
|
||||
|
||||
/// <summary>A duplicated sequence number is reported, not silently skipped.</summary>
|
||||
[Fact]
|
||||
public void DuplicateSequence_IsReported()
|
||||
{
|
||||
var (rows, head) = BuildChain(3);
|
||||
rows.Insert(2, rows[1] with { EventId = Guid.NewGuid() });
|
||||
|
||||
var result = Verify(rows, head);
|
||||
|
||||
Assert.Equal(AuditChainBreakKind.DuplicateSequence, result.FirstBreak!.Kind);
|
||||
}
|
||||
|
||||
/// <summary>A sanctioned per-channel purge leaves a tombstone that bridges the gap.</summary>
|
||||
[Fact]
|
||||
public void TombstonedRow_BridgesTheGap()
|
||||
{
|
||||
var (rows, head) = BuildChain(5);
|
||||
var purged = rows[2];
|
||||
rows.RemoveAt(2);
|
||||
var tombstones = new Dictionary<long, byte[]> { [purged.ChainSeq!.Value] = purged.RowHash! };
|
||||
|
||||
var result = Verify(rows, head, tombstones);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(4, result.RowsVerified);
|
||||
Assert.Equal(1, result.TombstonesApplied);
|
||||
}
|
||||
|
||||
/// <summary>A tombstone with the wrong hash does not hide a deletion.</summary>
|
||||
[Fact]
|
||||
public void ForgedTombstone_IsDetectedAtTheNextRow()
|
||||
{
|
||||
var (rows, head) = BuildChain(5);
|
||||
var purged = rows[2];
|
||||
rows.RemoveAt(2);
|
||||
var tombstones = new Dictionary<long, byte[]> { [purged.ChainSeq!.Value] = new byte[32] };
|
||||
|
||||
var result = Verify(rows, head, tombstones);
|
||||
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, result.FirstBreak!.Kind);
|
||||
Assert.Equal(4, result.FirstBreak.ChainSeq);
|
||||
}
|
||||
|
||||
/// <summary>After a partition purge, verification resumes at the checkpoint anchor.</summary>
|
||||
[Fact]
|
||||
public void PartitionPurgeAnchor_VerifiesTheRest()
|
||||
{
|
||||
var (rows, head) = BuildChain(6);
|
||||
var anchor = rows[3];
|
||||
var survivors = rows.Skip(4).ToList();
|
||||
var anchored = head with { PurgedThroughSeq = anchor.ChainSeq, PurgedThroughHash = anchor.RowHash };
|
||||
|
||||
var result = Verify(survivors, anchored);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(2, result.RowsVerified);
|
||||
Assert.Equal(4, result.PurgedThroughSeq);
|
||||
}
|
||||
|
||||
/// <summary>A month with neither rows nor head reports NotChained.</summary>
|
||||
[Fact]
|
||||
public void EmptyMonth_IsNotChained()
|
||||
{
|
||||
var result = Verify([], null, unchained: 7);
|
||||
|
||||
Assert.Equal(AuditChainStatus.NotChained, result.Status);
|
||||
Assert.Equal(7, result.UnchainedRows);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pins the v1 canonical form: a change to the serialisation silently invalidates every
|
||||
/// chain already in a database, so it must fail a test first. The expected value was
|
||||
/// computed by an independent implementation of the documented v1 encoding (Python
|
||||
/// hashlib/struct), not by this code.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void KnownAnswerVector_V1()
|
||||
{
|
||||
var row = new AuditChainRow(
|
||||
Guid.Parse("0f8fad5b-d9cb-469f-a165-70867728950e"),
|
||||
new DateTime(2026, 5, 20, 10, 30, 0, DateTimeKind.Utc).AddTicks(1234567),
|
||||
"alice", "ApiOutbound.ApiCall", "Success", "ApiOutbound", "Erp", "central-a",
|
||||
Guid.Parse("7c9e6679-7425-40de-944b-e07fc1f90ae7"), "{\"kind\":\"ApiCall\",\"status\":\"Delivered\"}");
|
||||
|
||||
var hash = AuditChainHasher.ComputeRowHash(AuditChainHasher.GenesisHash, Month, 1, row);
|
||||
|
||||
Assert.Equal("a3137c9961f35f931c7d84de6bced66ce1fe8bbb1dc500f9740b97efd9983ad4", Convert.ToHexStringLower(hash));
|
||||
}
|
||||
|
||||
/// <summary>NULL and the empty string hash differently (presence byte), as do adjacent-field shifts.</summary>
|
||||
[Fact]
|
||||
public void Canonical_DistinguishesNullEmptyAndFieldBoundaries()
|
||||
{
|
||||
var baseRow = NewRow(1);
|
||||
var nullTarget = baseRow with { Target = null };
|
||||
var emptyTarget = baseRow with { Target = "" };
|
||||
var shifted = baseRow with { Actor = "ab", Target = "c" };
|
||||
var shifted2 = baseRow with { Actor = "a", Target = "bc" };
|
||||
|
||||
Assert.NotEqual(Hash(nullTarget), Hash(emptyTarget));
|
||||
Assert.NotEqual(Hash(shifted), Hash(shifted2));
|
||||
}
|
||||
|
||||
private static string Hash(AuditChainRow row)
|
||||
=> Convert.ToHexString(AuditChainHasher.ComputeRowHash(AuditChainHasher.GenesisHash, Month, 1, row));
|
||||
|
||||
private static AuditChainVerificationResult Verify(
|
||||
IEnumerable<AuditChainRow> rows,
|
||||
AuditChainHeadState? head,
|
||||
IReadOnlyDictionary<long, byte[]>? tombstones = null,
|
||||
long unchained = 0)
|
||||
{
|
||||
var verifier = new AuditChainVerifier(Month, head, tombstones ?? new Dictionary<long, byte[]>());
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (!verifier.Accept(row))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return verifier.Complete(unchained);
|
||||
}
|
||||
|
||||
// ── chain start / cutoff (ScadaBridge#139) ───────────────────────────────
|
||||
|
||||
private static readonly DateTime CutoffAt = Month.AddHours(12); // rows are dated Month + i days
|
||||
|
||||
/// <summary>A cutoff-started month links its first row to the anchor and verifies intact.</summary>
|
||||
[Fact]
|
||||
public void CutoffStartedChain_Verifies_FromTheAnchor()
|
||||
{
|
||||
var anchor = AuditChainHasher.ComputeCutoffAnchorHash(CutoffAt);
|
||||
var (rows, head) = BuildChain(4, anchor);
|
||||
|
||||
var result = VerifyCutoff(rows, head, anchor);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(4, result.RowsVerified);
|
||||
Assert.Equal(0, result.TombstonesApplied); // the anchor is not a purge tombstone
|
||||
Assert.Equal(CutoffAt, result.ChainFromUtc);
|
||||
Assert.Equal(7, result.PreCutoffRows);
|
||||
}
|
||||
|
||||
/// <summary>Without its anchor, a cutoff-started month fails at its first link.</summary>
|
||||
[Fact]
|
||||
public void CutoffStartedChain_WithoutItsAnchor_FailsAtTheFirstLink()
|
||||
{
|
||||
var anchor = AuditChainHasher.ComputeCutoffAnchorHash(CutoffAt);
|
||||
var (rows, head) = BuildChain(4, anchor);
|
||||
|
||||
var result = Verify(rows, head);
|
||||
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, result.FirstBreak!.Kind);
|
||||
Assert.Equal(1, result.FirstBreak.ChainSeq);
|
||||
}
|
||||
|
||||
/// <summary>A different cutoff is a different anchor: the anchor hash binds the instant.</summary>
|
||||
[Fact]
|
||||
public void CutoffAnchorHash_BindsTheInstant()
|
||||
{
|
||||
Assert.False(AuditChainHasher.ComputeCutoffAnchorHash(CutoffAt).AsSpan()
|
||||
.SequenceEqual(AuditChainHasher.ComputeCutoffAnchorHash(CutoffAt.AddTicks(1))));
|
||||
Assert.Equal(AuditChainHasher.HashLength, AuditChainHasher.ComputeCutoffAnchorHash(CutoffAt).Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The eligibility attack: a chained row re-dated before the cutoff is a
|
||||
/// ChainedBeforeCutoff break even when its hash were recomputed to match.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ChainedRowDatedBeforeTheCutoff_IsChainedBeforeCutoff()
|
||||
{
|
||||
var anchor = AuditChainHasher.ComputeCutoffAnchorHash(CutoffAt);
|
||||
var (rows, _) = BuildChain(4, anchor);
|
||||
|
||||
// Re-date row 3 before the cutoff and re-hash the chain from it (an attacker who
|
||||
// rewrites the links): only the cutoff rule can still see it.
|
||||
rows[2] = rows[2] with { OccurredAtUtc = CutoffAt.AddMinutes(-1) };
|
||||
var previous = rows[1].RowHash!;
|
||||
for (var i = 2; i < rows.Count; i++)
|
||||
{
|
||||
var hash = AuditChainHasher.ComputeRowHash(previous, Month, i + 1, rows[i] with { ChainSeq = null, RowHash = null });
|
||||
rows[i] = rows[i] with { RowHash = hash };
|
||||
previous = hash;
|
||||
}
|
||||
|
||||
var result = VerifyCutoff(rows, new AuditChainHeadState(4, previous, null, null), anchor);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.ChainedBeforeCutoff, result.FirstBreak!.Kind);
|
||||
Assert.Equal(3, result.FirstBreak.ChainSeq);
|
||||
Assert.Equal(rows[2].EventId, result.FirstBreak.EventId);
|
||||
}
|
||||
|
||||
/// <summary>An anchor the caller found invalid fails the month even when every link verifies.</summary>
|
||||
[Fact]
|
||||
public void InvalidAnchor_IsCutoffAnchorInvalid()
|
||||
{
|
||||
var anchor = AuditChainHasher.ComputeCutoffAnchorHash(CutoffAt);
|
||||
var (rows, head) = BuildChain(4, anchor);
|
||||
var tombstones = new Dictionary<long, byte[]> { [AuditChainHasher.CutoffAnchorSeq] = anchor };
|
||||
var verifier = new AuditChainVerifier(Month, head, tombstones, CutoffAt, "anchor altered");
|
||||
foreach (var row in rows)
|
||||
{
|
||||
verifier.Accept(row);
|
||||
}
|
||||
|
||||
var result = verifier.Complete(0);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.CutoffAnchorInvalid, result.FirstBreak!.Kind);
|
||||
Assert.Equal(AuditChainHasher.CutoffAnchorSeq, result.FirstBreak.ChainSeq);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After a partition purge the checkpoint anchor, not the cutoff anchor, is where
|
||||
/// verification resumes; the cutoff anchor in the same tombstone set is ignored.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void PurgeCheckpoint_TakesPrecedenceOverTheCutoffAnchor()
|
||||
{
|
||||
var anchor = AuditChainHasher.ComputeCutoffAnchorHash(CutoffAt);
|
||||
var (rows, _) = BuildChain(5, anchor);
|
||||
var head = new AuditChainHeadState(5, rows[4].RowHash!, 3, rows[2].RowHash!);
|
||||
|
||||
var result = VerifyCutoff(rows.Skip(3), head, anchor);
|
||||
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(2, result.RowsVerified);
|
||||
}
|
||||
|
||||
private static AuditChainVerificationResult VerifyCutoff(IEnumerable<AuditChainRow> rows, AuditChainHeadState head, byte[] anchor)
|
||||
{
|
||||
var tombstones = new Dictionary<long, byte[]> { [AuditChainHasher.CutoffAnchorSeq] = anchor };
|
||||
var verifier = new AuditChainVerifier(Month, head, tombstones, CutoffAt);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (!verifier.Accept(row))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return verifier.Complete(0, preCutoffRows: 7);
|
||||
}
|
||||
|
||||
private static (List<AuditChainRow> Rows, AuditChainHeadState Head) BuildChain(int count)
|
||||
=> BuildChain(count, AuditChainHasher.GenesisHash.ToArray());
|
||||
|
||||
private static (List<AuditChainRow> Rows, AuditChainHeadState Head) BuildChain(int count, byte[] genesis)
|
||||
{
|
||||
var rows = new List<AuditChainRow>();
|
||||
var previous = genesis;
|
||||
for (var seq = 1; seq <= count; seq++)
|
||||
{
|
||||
var row = NewRow(seq);
|
||||
var hash = AuditChainHasher.ComputeRowHash(previous, Month, seq, row);
|
||||
rows.Add(row with { ChainSeq = seq, RowHash = hash });
|
||||
previous = hash;
|
||||
}
|
||||
|
||||
return (rows, new AuditChainHeadState(count, previous, null, null));
|
||||
}
|
||||
|
||||
private static AuditChainRow NewRow(int i)
|
||||
=> new(
|
||||
Guid.NewGuid(),
|
||||
Month.AddDays(i).AddTicks(i),
|
||||
$"actor-{i}",
|
||||
"ApiOutbound.ApiCall",
|
||||
"Success",
|
||||
"ApiOutbound",
|
||||
$"target-{i}",
|
||||
"central-a",
|
||||
null,
|
||||
$"{{\"kind\":\"ApiCall\",\"n\":{i}}}");
|
||||
}
|
||||
+16
-35
@@ -31,9 +31,8 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
public void Dispose() => _root.Delete(recursive: true);
|
||||
|
||||
/// <summary>
|
||||
/// The retried purge: archive A goes stale (a row arrives and the chain advances), B purges.
|
||||
/// Dry run reports A as superseded and deletes nothing; the real pass deletes exactly A's
|
||||
/// three files and B still verifies.
|
||||
/// The retried purge: archive A goes stale (a row arrives), B purges. Dry run reports A as
|
||||
/// superseded and deletes nothing; the real pass deletes exactly A's files and B still verifies.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
@@ -42,14 +41,11 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var dir = Dir("retried");
|
||||
var month = Month(2027, 1);
|
||||
await InsertAsync(Enumerable.Range(1, 5).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
await InsertAsync([NewEvent(month.AddDays(7))]); // unchained in A
|
||||
await InsertAsync(Enumerable.Range(1, 6).Select(i => NewEvent(month.AddDays(i))));
|
||||
var stale = await ArchiveAsync(dir, month);
|
||||
Assert.Equal(1, stale.UnchainedRowCount);
|
||||
Assert.Equal(6, stale.RowCount);
|
||||
|
||||
await InsertAsync([NewEvent(month.AddDays(9))]);
|
||||
await DrainAsync(); // A's unchained row is now chained; the chain moved past A's end
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
await Assert.ThrowsAsync<AuditArchiveStaleException>(() => Archive(ctx, dir).PurgeArchivedPartitionAsync(stale));
|
||||
@@ -83,8 +79,8 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A stale archive holding an unchained row that a per-channel purge removed before the
|
||||
/// later archive (no tombstone for an unchained row) is the only copy of that row: kept.
|
||||
/// A stale archive holding a row that a per-channel purge removed before the later archive
|
||||
/// is the only copy of that row: kept.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
@@ -94,8 +90,7 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
var dir = Dir("kept");
|
||||
var month = Month(2027, 3);
|
||||
await InsertAsync(Enumerable.Range(1, 3).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
await InsertAsync([NewEvent(month.AddHours(1), AuditChannel.DbOutbound)]); // unchained
|
||||
await InsertAsync([NewEvent(month.AddHours(1), AuditChannel.DbOutbound)]);
|
||||
var stale = await ArchiveAsync(dir, month);
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
@@ -114,7 +109,7 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
|
||||
var kept = Assert.Single(result.Items);
|
||||
Assert.Equal((stale.Name, AuditArchiveCleanupAction.KeptStale), (kept.Name, kept.Action));
|
||||
Assert.Contains("unchained row", kept.Detail);
|
||||
Assert.Contains("1 row(s) of this archive are not in", kept.Detail);
|
||||
Assert.True(File.Exists(ManifestPath(dir, stale)));
|
||||
}
|
||||
|
||||
@@ -130,7 +125,6 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
var dir = Dir("sole");
|
||||
var month = Month(2027, 4);
|
||||
await InsertAsync(Enumerable.Range(1, 3).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var manifest = await ArchiveAsync(dir, month);
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
@@ -165,6 +159,10 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
await InsertAsync([NewEvent(liveMonth.AddDays(1))]);
|
||||
var live = await ArchiveAsync(dir, liveMonth); // never purged: rows still in the table
|
||||
|
||||
// As if it were a format-v1 archive (written with the hash chain): it also has a tombstone file.
|
||||
var legacyTombstones = Path.Combine(dir, "2027", purged.Name + AuditArchiveParquet.LegacyTombstoneSuffix);
|
||||
await File.WriteAllTextAsync(legacyTombstones, "v1");
|
||||
|
||||
var monthEnd = purgedMonth.AddMonths(1);
|
||||
var farFuture = liveMonth.AddMonths(1).AddDays(1000);
|
||||
Assert.Empty((await CleanupAsync(dir, dryRun: false, retentionDays: 0, now: farFuture)).Items);
|
||||
@@ -175,10 +173,11 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
var expired = Assert.Single(result.Items);
|
||||
Assert.Equal((purged.Name, AuditArchiveCleanupAction.DeletedExpired), (expired.Name, expired.Action));
|
||||
Assert.False(File.Exists(ManifestPath(dir, purged)));
|
||||
Assert.False(File.Exists(legacyTombstones)); // a format-v1 archive's tombstone file goes with it
|
||||
Assert.True(File.Exists(ManifestPath(dir, live)));
|
||||
}
|
||||
|
||||
/// <summary>Deletion uses the archive name's own three files — never a path from the manifest.</summary>
|
||||
/// <summary>Deletion uses the archive name's own files — never a path from the manifest.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task Deletion_NeverFollowsAManifestPath_OutOfTheArchiveFolder()
|
||||
@@ -199,7 +198,6 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
var tampered = JsonSerializer.Deserialize<AuditArchiveManifest>(await File.ReadAllTextAsync(path), Json)! with
|
||||
{
|
||||
DataFile = "../../outside.parquet",
|
||||
TombstoneFile = "../../outside.parquet",
|
||||
};
|
||||
await File.WriteAllTextAsync(path, JsonSerializer.Serialize(tampered, Json));
|
||||
|
||||
@@ -223,7 +221,6 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
var dir = Dir("orphans");
|
||||
var month = Month(2027, 6);
|
||||
await InsertAsync(Enumerable.Range(1, 3).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var committed = await ArchiveAsync(dir, month);
|
||||
var year = Directory.CreateDirectory(Path.Combine(dir, "2027")).FullName;
|
||||
|
||||
@@ -239,7 +236,7 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
}
|
||||
|
||||
var oldTmpData = Make(orphanA + ".parquet.tmp");
|
||||
var oldTmpTomb = Make(orphanA + ".tombstones.parquet.tmp");
|
||||
var oldTmpTomb = Make(orphanA + ".tombstones.parquet.tmp"); // a format-v1 writer's temp file
|
||||
var oldTmpManifest = Make(orphanA + ".manifest.json.tmp");
|
||||
var oldNoManifestData = Make(orphanA + ".parquet");
|
||||
var oldNoManifestTomb = Make(orphanA + ".tombstones.parquet");
|
||||
@@ -252,7 +249,7 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
var otherDir = Path.Combine(dir, "misc", orphanA + ".parquet.tmp");
|
||||
File.WriteAllText(otherDir, "x");
|
||||
File.SetLastWriteTimeUtc(otherDir, old);
|
||||
var committedFiles = new[] { ManifestPath(dir, committed), Path.Combine(year, committed.Name + ".parquet"), Path.Combine(year, committed.Name + ".tombstones.parquet") };
|
||||
var committedFiles = new[] { ManifestPath(dir, committed), Path.Combine(year, committed.Name + ".parquet") };
|
||||
foreach (var f in committedFiles)
|
||||
{
|
||||
File.SetLastWriteTimeUtc(f, old);
|
||||
@@ -323,22 +320,6 @@ public sealed class AuditLogArchiveCleanupTests : IClassFixture<MsSqlMigrationFi
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DrainAsync()
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var chain = new AuditLogHashChain(ctx);
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var r = await chain.ChainPendingAsync(500, chainBacklog: true);
|
||||
if (r.RowsChained == 0 && !r.LockBusy)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Chain did not drain.");
|
||||
}
|
||||
|
||||
private static DateTime Month(int year, int month) => new(year, month, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private ScadaBridgeDbContext CreateContext()
|
||||
|
||||
-561
@@ -1,561 +0,0 @@
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ZB.MOM.WW.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server integration tests for the hash-chain cutoff (ScadaBridge#139): enabling the
|
||||
/// chain on a database with history chains only rows from the enablement instant on (owner
|
||||
/// decision on #107, 2026-11-13), verification treats the backlog as out of scope, the
|
||||
/// tamper cases are still caught, moving a row (or the cutoff) across the cutoff is caught,
|
||||
/// both purge paths keep the chain verifiable across the cutoff, and both central nodes
|
||||
/// settle on one cutoff.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The cutoff is one row per database, so every test starts from an empty AuditLog and empty
|
||||
/// chain tables (<see cref="ResetAsync"/>). xunit runs a class's tests sequentially.
|
||||
/// </remarks>
|
||||
public sealed class AuditLogHashChainCutoffTests : IClassFixture<MsSqlMigrationFixture>, IDisposable
|
||||
{
|
||||
private static readonly DateTime Backlog = new(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime CutoffMonth = new(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime After = new(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime Cutoff = new(2026, 3, 15, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private readonly MsSqlMigrationFixture _fixture;
|
||||
private readonly DirectoryInfo _archiveRoot = Directory.CreateTempSubdirectory("auditlog-cutoff-archive-");
|
||||
|
||||
/// <summary>Creates the test class with its own migrated SQL Server database.</summary>
|
||||
/// <param name="fixture">The per-class migration fixture.</param>
|
||||
public AuditLogHashChainCutoffTests(MsSqlMigrationFixture fixture) => _fixture = fixture;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => _archiveRoot.Delete(recursive: true);
|
||||
|
||||
/// <summary>
|
||||
/// The owner's decision end to end: a backlog exists, the chain is enabled, only rows dated
|
||||
/// from the cutoff on are chained, the backlog is untouched, and every month verifies —
|
||||
/// the backlog as pre-cutoff rows, never as unchained rows or a break.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task FirstEnablement_ChainsOnlyFromTheCutoff_BacklogUntouched_VerifiesIntact()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
await ResetAsync();
|
||||
var backlog = Rows(Backlog.AddDays(3), 4).Concat(Rows(CutoffMonth.AddDays(2), 3)).ToList();
|
||||
await InsertAsync(backlog);
|
||||
|
||||
await DrainAsync(); // first enablement: records the anchor at Cutoff, chains nothing
|
||||
|
||||
Assert.Equal(Cutoff, await AnchorCutoffAsync());
|
||||
Assert.Equal(0L, await ScalarAsync<long>("SELECT COUNT_BIG(*) FROM dbo.AuditLog WHERE ChainSeq IS NOT NULL;"));
|
||||
Assert.Equal(0L, await ScalarAsync<long>("SELECT COUNT_BIG(*) FROM dbo.AuditLogChainHead;"));
|
||||
|
||||
var post = Rows(Cutoff.AddMinutes(1), 5).Concat(Rows(After.AddDays(1), 2)).ToList();
|
||||
await InsertAsync(post);
|
||||
await DrainAsync();
|
||||
|
||||
// Every backlog row stays exactly as it was: unchained.
|
||||
foreach (var e in backlog)
|
||||
{
|
||||
Assert.Equal(DBNull.Value, await ScalarAsync<object>($"SELECT ChainSeq FROM dbo.AuditLog WHERE EventId = '{e.EventId}';"));
|
||||
}
|
||||
|
||||
var march = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Intact, march.Status);
|
||||
Assert.Equal(5, march.RowsVerified);
|
||||
Assert.Equal(0, march.UnchainedRows);
|
||||
Assert.Equal(3, march.PreCutoffRows);
|
||||
Assert.Equal(Cutoff, march.ChainFromUtc);
|
||||
|
||||
var february = await VerifyAsync(Backlog);
|
||||
Assert.Equal(AuditChainStatus.NotChained, february.Status);
|
||||
Assert.Equal(0, february.UnchainedRows);
|
||||
Assert.Equal(4, february.PreCutoffRows);
|
||||
|
||||
var april = await VerifyAsync(After);
|
||||
Assert.Equal(AuditChainStatus.Intact, april.Status);
|
||||
Assert.Equal(2, april.RowsVerified);
|
||||
Assert.Equal(0, april.PreCutoffRows);
|
||||
|
||||
// A late site row dated before the cutoff that reaches central after enablement is
|
||||
// keyed on OccurredAtUtc: it stays out of scope (documented limit), not pending.
|
||||
await InsertAsync(Rows(Cutoff.AddHours(-2), 1));
|
||||
await DrainAsync();
|
||||
march = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Intact, march.Status);
|
||||
Assert.Equal(4, march.PreCutoffRows);
|
||||
Assert.Equal(0, march.UnchainedRows);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The cutoff month's first row links to the anchor, not to 32 zero bytes, and the
|
||||
/// ordinary tamper cases are still caught after a cutoff start: edit, delete, tail delete.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task TamperCases_AreStillDetected_AfterACutoffStart()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var events = await SeedCutoffChainAsync(postRows: 6);
|
||||
Assert.Equal(AuditChainStatus.Intact, (await VerifyAsync(CutoffMonth)).Status);
|
||||
|
||||
// Edit the FIRST link (the one hashed against the anchor).
|
||||
await ExecAsync($"UPDATE dbo.AuditLog SET Target = N'forged' WHERE EventId = '{events[0]}';");
|
||||
var edited = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, edited.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, edited.FirstBreak!.Kind);
|
||||
Assert.Equal(1, edited.FirstBreak.ChainSeq);
|
||||
Assert.Equal(events[0], edited.FirstBreak.EventId);
|
||||
await ExecAsync($"UPDATE dbo.AuditLog SET Target = N'erp' WHERE EventId = '{events[0]}';");
|
||||
Assert.Equal(AuditChainStatus.Intact, (await VerifyAsync(CutoffMonth)).Status);
|
||||
|
||||
var middleSeq = await SeqOfAsync(events[2]);
|
||||
await ExecAsync($"DELETE FROM dbo.AuditLog WHERE EventId = '{events[2]}';");
|
||||
var deleted = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, deleted.Status);
|
||||
Assert.Equal(AuditChainBreakKind.MissingRow, deleted.FirstBreak!.Kind);
|
||||
Assert.Equal(middleSeq, deleted.FirstBreak.ChainSeq);
|
||||
|
||||
await ResetAsync();
|
||||
events = await SeedCutoffChainAsync(postRows: 4);
|
||||
await ExecAsync($"DELETE FROM dbo.AuditLog WHERE EventId = '{events[^1]}';");
|
||||
var tail = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, tail.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HeadMismatch, tail.FirstBreak!.Kind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The cutoff-eligibility attack: move a chained row's timestamp back before the cutoff to
|
||||
/// hide it among the unprotected backlog rows. Caught with its ChainSeq left in place
|
||||
/// (<see cref="AuditChainBreakKind.ChainedBeforeCutoff"/>), and with its link cleared too
|
||||
/// (its sequence number goes missing). Moving it into an earlier month is caught in both months.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ChainedRowMovedBeforeTheCutoff_IsDetected()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var events = await SeedCutoffChainAsync(postRows: 5);
|
||||
var victim = events[2];
|
||||
var victimSeq = await SeqOfAsync(victim);
|
||||
|
||||
// 1. Timestamp moved back across the cutoff, link left in place.
|
||||
await ExecAsync($"UPDATE dbo.AuditLog SET OccurredAtUtc = '{Cutoff.AddHours(-1):yyyy-MM-dd HH:mm:ss}' WHERE EventId = '{victim}';");
|
||||
var moved = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, moved.Status);
|
||||
Assert.Equal(AuditChainBreakKind.ChainedBeforeCutoff, moved.FirstBreak!.Kind);
|
||||
Assert.Equal(victim, moved.FirstBreak.EventId);
|
||||
Assert.Equal(victimSeq, moved.FirstBreak.ChainSeq);
|
||||
|
||||
// 2. ...and its link cleared, so it looks like any other pre-cutoff row.
|
||||
await ExecAsync($"UPDATE dbo.AuditLog SET ChainSeq = NULL, RowHash = NULL WHERE EventId = '{victim}';");
|
||||
var hidden = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, hidden.Status);
|
||||
Assert.Equal(AuditChainBreakKind.MissingRow, hidden.FirstBreak!.Kind);
|
||||
Assert.Equal(victimSeq, hidden.FirstBreak.ChainSeq);
|
||||
Assert.Equal(4, hidden.PreCutoffRows); // the 3 backlog rows + the hidden one
|
||||
|
||||
// 3. Moved into the previous (backlog) month with its link: caught in both months.
|
||||
await ResetAsync();
|
||||
events = await SeedCutoffChainAsync(postRows: 5);
|
||||
victim = events[1];
|
||||
await ExecAsync($"UPDATE dbo.AuditLog SET OccurredAtUtc = '{Backlog.AddDays(9):yyyy-MM-dd HH:mm:ss}' WHERE EventId = '{victim}';");
|
||||
Assert.Equal(AuditChainBreakKind.MissingRow, (await VerifyAsync(CutoffMonth)).FirstBreak!.Kind);
|
||||
var february = await VerifyAsync(Backlog);
|
||||
Assert.Equal(AuditChainStatus.Broken, february.Status);
|
||||
Assert.Equal(AuditChainBreakKind.ChainedBeforeCutoff, february.FirstBreak!.Kind);
|
||||
Assert.Equal(victim, february.FirstBreak.EventId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The other half of the eligibility attack: moving the cutoff itself. Editing the anchor's
|
||||
/// cutoff, re-hashing the anchor to match, deleting it, or adding a second anchor are each
|
||||
/// reported, so the backlog/scope boundary cannot be shifted silently.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task CutoffAnchorTampering_IsDetected()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
await SeedCutoffChainAsync(postRows: 4);
|
||||
var later = Cutoff.AddDays(5);
|
||||
|
||||
// Cutoff moved forward, anchor hash left alone.
|
||||
await ExecAsync($"UPDATE dbo.AuditLogChainTombstone SET PurgedAtUtc = '{later:yyyy-MM-dd HH:mm:ss}' WHERE ChainSeq = 0;");
|
||||
var moved = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, moved.Status);
|
||||
Assert.Equal(AuditChainBreakKind.CutoffAnchorInvalid, moved.FirstBreak!.Kind);
|
||||
Assert.Equal(AuditChainStatus.Broken, (await VerifyAsync(After)).Status); // every month sees it
|
||||
|
||||
// Cutoff moved forward AND the anchor re-hashed to match: the chained rows now precede it.
|
||||
await SetAnchorAsync(later, AuditChainHasher.ComputeCutoffAnchorHash(later));
|
||||
var rehashed = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, rehashed.Status);
|
||||
Assert.Equal(AuditChainBreakKind.ChainedBeforeCutoff, rehashed.FirstBreak!.Kind);
|
||||
|
||||
// Anchor deleted: the cutoff month's first link no longer starts from it.
|
||||
await ExecAsync("DELETE FROM dbo.AuditLogChainTombstone WHERE ChainSeq = 0;");
|
||||
var deleted = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, deleted.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, deleted.FirstBreak!.Kind);
|
||||
Assert.Equal(1, deleted.FirstBreak.ChainSeq);
|
||||
|
||||
// Restored → intact (positive control); then a second anchor is reported.
|
||||
await SetAnchorAsync(Cutoff, AuditChainHasher.ComputeCutoffAnchorHash(Cutoff));
|
||||
Assert.Equal(AuditChainStatus.Intact, (await VerifyAsync(CutoffMonth)).Status);
|
||||
var earlier = Backlog.AddDays(1);
|
||||
await ExecAsync(
|
||||
"INSERT INTO dbo.AuditLogChainTombstone (ChainMonth, ChainSeq, RowHash, EventId, PurgedAtUtc) " +
|
||||
$"VALUES ('{Backlog:yyyy-MM-dd}', 0, 0x{Convert.ToHexString(AuditChainHasher.ComputeCutoffAnchorHash(earlier))}, NEWID(), '{earlier:yyyy-MM-dd HH:mm:ss}');");
|
||||
var twoAnchors = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Broken, twoAnchors.Status);
|
||||
Assert.Equal(AuditChainBreakKind.CutoffAnchorInvalid, twoAnchors.FirstBreak!.Kind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Both purge paths across the cutoff: a per-channel purge that deletes backlog and chained
|
||||
/// rows alike leaves an intact chain; the head store and an export of it agree (the anchor is
|
||||
/// not counted as a purge tombstone); the partition switch-out of the cutoff month keeps the
|
||||
/// anchor and anchors the month; the archive of that month verifies from its own files; and
|
||||
/// the chainer still honours the cutoff afterwards.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task PurgeAcrossTheCutoff_KeepsEveryChainVerifiable()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
await ResetAsync();
|
||||
var preDb = Rows(CutoffMonth.AddDays(1), 2, AuditChannel.DbOutbound);
|
||||
var preApi = Rows(CutoffMonth.AddDays(2), 2);
|
||||
await InsertAsync(preDb.Concat(preApi));
|
||||
await DrainAsync();
|
||||
var postDb = Rows(Cutoff.AddHours(1), 3, AuditChannel.DbOutbound);
|
||||
var postApi = Rows(Cutoff.AddHours(2), 3);
|
||||
await InsertAsync(postDb.Concat(postApi));
|
||||
await DrainAsync();
|
||||
|
||||
// Per-channel purge with a threshold past the cutoff: 2 backlog + 3 chained DbOutbound rows.
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
var purged = await new AuditLogRepository(ctx).PurgeChannelOlderThanAsync(
|
||||
nameof(AuditChannel.DbOutbound), Cutoff.AddDays(1), batchSize: 2);
|
||||
Assert.Equal(5, purged);
|
||||
}
|
||||
|
||||
var afterChannelPurge = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Intact, afterChannelPurge.Status);
|
||||
Assert.Equal(3, afterChannelPurge.TombstonesApplied);
|
||||
Assert.Equal(3, afterChannelPurge.RowsVerified);
|
||||
Assert.Equal(2, afterChannelPurge.PreCutoffRows);
|
||||
|
||||
// Head store + export: the anchor is not a purge tombstone; an export verifies as Matches.
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
var head = Assert.Single(await new AuditLogHashChain(ctx).ReadHeadsAsync());
|
||||
Assert.Equal(3, head.Tombstones);
|
||||
Assert.Equal(3, head.ChainedRows);
|
||||
var exported = await new AuditLogHashChain(ctx).VerifyExportedHeadsAsync([Export(head)]);
|
||||
Assert.True(exported.Verified);
|
||||
Assert.Equal(AuditChainHeadStatus.Matches, Assert.Single(exported.Checks).Status);
|
||||
}
|
||||
|
||||
// Archive the cutoff month, then switch it out through the archive guard.
|
||||
AuditArchiveManifest manifest;
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
manifest = await Archive(ctx).ArchivePartitionAsync(CutoffMonth);
|
||||
await Archive(ctx).PurgeArchivedPartitionAsync(manifest);
|
||||
}
|
||||
|
||||
Assert.Equal(Cutoff, await AnchorCutoffAsync()); // the anchor survives the switch-out
|
||||
var switched = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Intact, switched.Status);
|
||||
Assert.Equal(6, switched.PurgedThroughSeq);
|
||||
Assert.Equal(0, switched.PreCutoffRows);
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
var archived = await Archive(ctx).VerifyAsync(manifest.Name);
|
||||
Assert.True(archived.Verified, archived.FileProblem);
|
||||
var chain = Assert.Single(archived.Chains).Chain;
|
||||
Assert.Equal(AuditChainStatus.Intact, chain.Status);
|
||||
Assert.Equal(3, chain.RowsVerified);
|
||||
Assert.Equal(3, chain.TombstonesApplied);
|
||||
Assert.Equal(2, chain.PreCutoffRows); // the archive classifies its backlog rows too
|
||||
Assert.Equal(0, chain.UnchainedRows);
|
||||
Assert.Equal(Cutoff, chain.ChainFromUtc);
|
||||
}
|
||||
|
||||
// After the purge the cutoff still holds: a late backlog row stays out, a late post-cutoff row chains on.
|
||||
var lateBacklog = Rows(Backlog.AddDays(4), 1);
|
||||
var latePost = Rows(Cutoff.AddHours(5), 1);
|
||||
await InsertAsync(lateBacklog.Concat(latePost));
|
||||
await DrainAsync();
|
||||
Assert.Equal(DBNull.Value, await ScalarAsync<object>($"SELECT ChainSeq FROM dbo.AuditLog WHERE EventId = '{lateBacklog[0].EventId}';"));
|
||||
var late = await VerifyAsync(CutoffMonth);
|
||||
Assert.Equal(AuditChainStatus.Intact, late.Status);
|
||||
Assert.Equal(7, late.HeadSeq);
|
||||
Assert.Equal(1, (await VerifyAsync(Backlog)).PreCutoffRows);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Both central nodes settle on ONE cutoff: two chainers race the first enablement on a
|
||||
/// pristine database with the real database clock, exactly one anchor is written (inside the
|
||||
/// database clock window of the race), and a node configured to chain the backlog that runs
|
||||
/// after the decision cannot override it.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task BothNodes_AgreeOnOneCutoff()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
await ResetAsync();
|
||||
var backlog = Rows(CutoffMonth.AddDays(1), 5);
|
||||
await InsertAsync(backlog);
|
||||
|
||||
var before = await ScalarAsync<DateTime>("SELECT SYSUTCDATETIME();");
|
||||
var start = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
async Task Node()
|
||||
{
|
||||
await start.Task;
|
||||
for (var i = 0; i < 20; i++)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
await new AuditLogHashChain(ctx).ChainPendingAsync(100); // production clock
|
||||
}
|
||||
}
|
||||
|
||||
var nodes = new[] { Task.Run(Node), Task.Run(Node) };
|
||||
start.SetResult();
|
||||
await Task.WhenAll(nodes);
|
||||
var after = await ScalarAsync<DateTime>("SELECT SYSUTCDATETIME();");
|
||||
|
||||
Assert.Equal(1L, await ScalarAsync<long>("SELECT COUNT_BIG(*) FROM dbo.AuditLogChainTombstone WHERE ChainSeq = 0;"));
|
||||
var cutoff = await AnchorCutoffAsync();
|
||||
Assert.InRange(cutoff, before, after);
|
||||
|
||||
// The peer node configured with ChainBacklog=true runs after the decision: still no backlog chained.
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
Assert.Equal(0, (await new AuditLogHashChain(ctx).ChainPendingAsync(100, chainBacklog: true)).RowsChained);
|
||||
}
|
||||
|
||||
Assert.Equal(0L, await ScalarAsync<long>("SELECT COUNT_BIG(*) FROM dbo.AuditLog WHERE ChainSeq IS NOT NULL;"));
|
||||
Assert.Equal(1L, await ScalarAsync<long>("SELECT COUNT_BIG(*) FROM dbo.AuditLogChainTombstone WHERE ChainSeq = 0;"));
|
||||
var verified = await VerifyAsync(AuditChainHasher.MonthOf(cutoff));
|
||||
Assert.Equal(cutoff, verified.ChainFromUtc);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The old behaviour stays reachable and unchanged: ChainBacklog=true on a pristine database
|
||||
/// writes no anchor and chains everything, and a database that already holds a chain (legacy
|
||||
/// enablement, no anchor) keeps chaining every row even with ChainBacklog=false.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ChainBacklog_AndLegacyChains_KeepChainingEverything()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
await ResetAsync();
|
||||
await InsertAsync(Rows(Backlog.AddDays(1), 3));
|
||||
await DrainAsync(chainBacklog: true);
|
||||
Assert.Equal(0L, await ScalarAsync<long>("SELECT COUNT_BIG(*) FROM dbo.AuditLogChainTombstone WHERE ChainSeq = 0;"));
|
||||
Assert.Equal(3L, await ScalarAsync<long>("SELECT COUNT_BIG(*) FROM dbo.AuditLog WHERE ChainSeq IS NOT NULL;"));
|
||||
|
||||
// Now a node on the default (no backlog) sees an existing chain: no anchor, old rows still chain.
|
||||
await InsertAsync(Rows(Backlog.AddDays(10), 2));
|
||||
await DrainAsync();
|
||||
Assert.Equal(0L, await ScalarAsync<long>("SELECT COUNT_BIG(*) FROM dbo.AuditLogChainTombstone WHERE ChainSeq = 0;"));
|
||||
var february = await VerifyAsync(Backlog);
|
||||
Assert.Equal(AuditChainStatus.Intact, february.Status);
|
||||
Assert.Equal(5, february.RowsVerified);
|
||||
Assert.Null(february.ChainFromUtc);
|
||||
Assert.Equal(0, february.PreCutoffRows);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The hardened maintenance login (<c>scadabridge_audit_chainer</c> + <c>scadabridge_audit_purger</c>,
|
||||
/// ScadaBridge#107 item 3) can write the chain-start anchor: no extra grant, no migration.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task MaintenanceLogin_CanWriteTheAnchor()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
await ResetAsync();
|
||||
var login = "sbc_" + Guid.NewGuid().ToString("N")[..10];
|
||||
const string password = "Sb_W22_cutoff#2026";
|
||||
await ExecAsync($@"
|
||||
CREATE LOGIN [{login}] WITH PASSWORD = N'{password}', CHECK_POLICY = OFF;
|
||||
CREATE USER [{login}] FOR LOGIN [{login}];
|
||||
ALTER ROLE scadabridge_audit_chainer ADD MEMBER [{login}];
|
||||
ALTER ROLE scadabridge_audit_purger ADD MEMBER [{login}];");
|
||||
try
|
||||
{
|
||||
await InsertAsync(Rows(Backlog.AddDays(2), 2));
|
||||
var maintenance = new SqlConnectionStringBuilder(_fixture.ConnectionString)
|
||||
{
|
||||
IntegratedSecurity = false,
|
||||
UserID = login,
|
||||
Password = password,
|
||||
Pooling = false,
|
||||
}.ConnectionString;
|
||||
await using (var ctx = new ScadaBridgeDbContext(
|
||||
new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlServer(maintenance).Options))
|
||||
{
|
||||
var chain = new AuditLogHashChain(ctx) { AnchorClock = () => Cutoff };
|
||||
Assert.Equal(0, (await chain.ChainPendingAsync(100)).RowsChained);
|
||||
}
|
||||
|
||||
Assert.Equal(Cutoff, await AnchorCutoffAsync());
|
||||
}
|
||||
finally
|
||||
{
|
||||
SqlConnection.ClearAllPools();
|
||||
await ExecAsync($@"
|
||||
DECLARE @kill nvarchar(max) = N'';
|
||||
SELECT @kill = @kill + N'KILL ' + CAST(session_id AS nvarchar(10)) + N';' FROM sys.dm_exec_sessions WHERE login_name = N'{login}';
|
||||
EXEC sp_executesql @kill;
|
||||
DROP USER [{login}];
|
||||
DROP LOGIN [{login}];");
|
||||
}
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Backlog in February and early March, first enablement at <see cref="Cutoff"/>, then
|
||||
/// <paramref name="postRows"/> rows after it, all chained. Returns the post-cutoff EventIds in chain order.
|
||||
/// </summary>
|
||||
private async Task<List<Guid>> SeedCutoffChainAsync(int postRows)
|
||||
{
|
||||
await ResetAsync();
|
||||
await InsertAsync(Rows(Backlog.AddDays(3), 2).Concat(Rows(CutoffMonth.AddDays(2), 3)));
|
||||
await DrainAsync();
|
||||
var post = Rows(Cutoff.AddMinutes(1), postRows);
|
||||
await InsertAsync(post);
|
||||
await DrainAsync();
|
||||
return post.Select(e => e.EventId).ToList();
|
||||
}
|
||||
|
||||
private async Task ResetAsync()
|
||||
{
|
||||
if (!_fixture.Available)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await ExecAsync("DELETE FROM dbo.AuditLog; DELETE FROM dbo.AuditLogChainHead; DELETE FROM dbo.AuditLogChainTombstone;");
|
||||
}
|
||||
|
||||
private async Task DrainAsync(bool chainBacklog = false)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var chain = new AuditLogHashChain(ctx) { AnchorClock = () => Cutoff };
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var r = await chain.ChainPendingAsync(500, chainBacklog);
|
||||
if (r.RowsChained == 0 && !r.LockBusy)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Chain did not drain.");
|
||||
}
|
||||
|
||||
private async Task<AuditChainVerificationResult> VerifyAsync(DateTime month)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
return await new AuditLogHashChain(ctx).VerifyMonthAsync(month);
|
||||
}
|
||||
|
||||
private async Task<DateTime> AnchorCutoffAsync()
|
||||
=> DateTime.SpecifyKind(
|
||||
await ScalarAsync<DateTime>("SELECT PurgedAtUtc FROM dbo.AuditLogChainTombstone WHERE ChainSeq = 0;"),
|
||||
DateTimeKind.Utc);
|
||||
|
||||
private async Task SetAnchorAsync(DateTime chainFrom, byte[] hash)
|
||||
{
|
||||
await ExecAsync("DELETE FROM dbo.AuditLogChainTombstone WHERE ChainSeq = 0;");
|
||||
await ExecAsync(
|
||||
"INSERT INTO dbo.AuditLogChainTombstone (ChainMonth, ChainSeq, RowHash, EventId, PurgedAtUtc) " +
|
||||
$"VALUES ('{AuditChainHasher.MonthOf(chainFrom):yyyy-MM-dd}', 0, 0x{Convert.ToHexString(hash)}, '{AuditChainHasher.CutoffAnchorEventId}', '{chainFrom:yyyy-MM-dd HH:mm:ss}');");
|
||||
}
|
||||
|
||||
private async Task<long> SeqOfAsync(Guid eventId)
|
||||
=> await ScalarAsync<long>($"SELECT ChainSeq FROM dbo.AuditLog WHERE EventId = '{eventId}';");
|
||||
|
||||
private async Task InsertAsync(IEnumerable<AuditEvent> events)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var repo = new AuditLogRepository(ctx);
|
||||
foreach (var e in events)
|
||||
{
|
||||
await repo.InsertIfNotExistsAsync(e);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExecAsync(string sql)
|
||||
{
|
||||
await using var conn = new SqlConnection(_fixture.ConnectionString);
|
||||
await conn.OpenAsync();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = sql;
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
private async Task<T> ScalarAsync<T>(string sql)
|
||||
{
|
||||
await using var conn = new SqlConnection(_fixture.ConnectionString);
|
||||
await conn.OpenAsync();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = sql;
|
||||
var value = await cmd.ExecuteScalarAsync();
|
||||
return value is DateTime dt && typeof(T) == typeof(DateTime)
|
||||
? (T)(object)DateTime.SpecifyKind(dt, DateTimeKind.Utc)
|
||||
: (T)value!;
|
||||
}
|
||||
|
||||
private AuditLogPartitionArchive Archive(ScadaBridgeDbContext ctx) => new(ctx, new AuditLogArchiveOptions
|
||||
{
|
||||
Enabled = true,
|
||||
Directory = _archiveRoot.FullName,
|
||||
RowGroupSize = 1_000,
|
||||
});
|
||||
|
||||
private static AuditChainHeadRecord Export(AuditChainHeadSnapshot head) => new(
|
||||
AuditChainHeadRecord.CurrentVersion,
|
||||
AuditChainHasher.PartitionLabel(head.Month),
|
||||
head.LastSeq,
|
||||
AuditChainHeadComparer.ToHex(head.LastHash),
|
||||
head.PurgedThroughSeq,
|
||||
head.PurgedThroughHash is null ? null : AuditChainHeadComparer.ToHex(head.PurgedThroughHash),
|
||||
head.ChainedRows,
|
||||
head.Tombstones,
|
||||
head.UpdatedAtUtc,
|
||||
DateTime.UtcNow,
|
||||
"central-a");
|
||||
|
||||
private ScadaBridgeDbContext CreateContext()
|
||||
=> new(new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlServer(_fixture.ConnectionString).Options);
|
||||
|
||||
private static List<AuditEvent> Rows(DateTime first, int count, AuditChannel channel = AuditChannel.ApiOutbound)
|
||||
=> Enumerable.Range(0, count).Select(i => ScadaBridgeAuditEventFactory.Create(
|
||||
channel: channel,
|
||||
kind: channel == AuditChannel.DbOutbound ? AuditKind.DbWrite : AuditKind.ApiCall,
|
||||
status: AuditStatus.Delivered,
|
||||
occurredAtUtc: first.AddMinutes(i),
|
||||
target: "erp",
|
||||
sourceNode: "central-a",
|
||||
sourceSiteId: "cutoff-test")).ToList();
|
||||
}
|
||||
-346
@@ -1,346 +0,0 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ZB.MOM.WW.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server integration tests for the AuditLog hash chain (ScadaBridge#41) against the
|
||||
/// real migrated, partitioned schema: continuity under concurrent writers and chainers,
|
||||
/// detection of an edited / deleted / reordered row, and survival of both purge paths.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The fixture database is shared by the class and the chain is per month across the whole
|
||||
/// table, so every test owns a distinct month (xunit runs one class's tests sequentially).
|
||||
/// Each test drains the chain before tampering so no other month is left unchained.
|
||||
/// </remarks>
|
||||
public class AuditLogHashChainTests : IClassFixture<MsSqlMigrationFixture>
|
||||
{
|
||||
private readonly MsSqlMigrationFixture _fixture;
|
||||
|
||||
/// <summary>Creates the test class with the shared migrated SQL Server fixture.</summary>
|
||||
/// <param name="fixture">The shared migration fixture.</param>
|
||||
public AuditLogHashChainTests(MsSqlMigrationFixture fixture) => _fixture = fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Many concurrent INSERTs (the two central nodes + site ingest) racing two concurrent
|
||||
/// chainers (a dual-active central pair) still produce one gap-free, intact chain.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ConcurrentWritersAndChainers_ProduceOneIntactGapFreeChain()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 2);
|
||||
const int writers = 8;
|
||||
const int rowsPerWriter = 40;
|
||||
|
||||
using var stop = new CancellationTokenSource();
|
||||
var lockBusySeen = 0;
|
||||
async Task ChainLoop()
|
||||
{
|
||||
while (!stop.IsCancellationRequested)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var r = await new AuditLogHashChain(ctx).ChainPendingAsync(17, chainBacklog: true);
|
||||
if (r.LockBusy) Interlocked.Increment(ref lockBusySeen);
|
||||
if (r.RowsChained == 0) await Task.Delay(5);
|
||||
}
|
||||
}
|
||||
|
||||
var chainers = new[] { Task.Run(ChainLoop), Task.Run(ChainLoop) };
|
||||
var writerTasks = Enumerable.Range(0, writers).Select(w => Task.Run(async () =>
|
||||
{
|
||||
for (var i = 0; i < rowsPerWriter; i++)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
// Out-of-order OccurredAtUtc on purpose: late-arriving site rows.
|
||||
var at = month.AddDays((w * 7 + i * 13) % 27).AddSeconds(i);
|
||||
await new AuditLogRepository(ctx).InsertIfNotExistsAsync(NewEvent(at, sourceNode: $"node-{w}"));
|
||||
}
|
||||
})).ToArray();
|
||||
|
||||
await Task.WhenAll(writerTasks);
|
||||
await Task.Delay(200);
|
||||
await stop.CancelAsync();
|
||||
await Task.WhenAll(chainers);
|
||||
await DrainAsync();
|
||||
|
||||
var result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(writers * rowsPerWriter, result.RowsVerified);
|
||||
Assert.Equal(writers * rowsPerWriter, result.HeadSeq);
|
||||
Assert.Equal(0, result.UnchainedRows);
|
||||
|
||||
var seqs = await ChainSeqsAsync(month);
|
||||
Assert.Equal(Enumerable.Range(1, writers * rowsPerWriter).Select(i => (long)i), seqs);
|
||||
}
|
||||
|
||||
/// <summary>Editing a chained row's content is reported at that row.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task EditedRow_IsDetected_WithRowIdAndPartition()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 3);
|
||||
var events = await SeedAndChainAsync(month, 6);
|
||||
Assert.Equal(AuditChainStatus.Intact, (await VerifyAsync(month)).Status);
|
||||
|
||||
var victim = events[3];
|
||||
await ExecAsync($"UPDATE dbo.AuditLog SET Target = N'forged' WHERE EventId = '{victim}';");
|
||||
|
||||
var result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, result.FirstBreak!.Kind);
|
||||
Assert.Equal("2026-03", result.FirstBreak.Partition);
|
||||
Assert.Equal(victim, result.FirstBreak.EventId);
|
||||
Assert.Equal(await SeqOfAsync(victim), result.FirstBreak.ChainSeq);
|
||||
}
|
||||
|
||||
/// <summary>Deleting a chained row outside the purge path is reported as a missing sequence number.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task DeletedRow_IsDetected()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 4);
|
||||
var events = await SeedAndChainAsync(month, 6);
|
||||
var victim = events[2];
|
||||
var victimSeq = await SeqOfAsync(victim);
|
||||
|
||||
await ExecAsync($"DELETE FROM dbo.AuditLog WHERE EventId = '{victim}';");
|
||||
|
||||
var result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.MissingRow, result.FirstBreak!.Kind);
|
||||
Assert.Equal(victimSeq, result.FirstBreak.ChainSeq);
|
||||
Assert.Equal("2026-04", result.FirstBreak.Partition);
|
||||
}
|
||||
|
||||
/// <summary>Swapping two rows' chain positions is reported.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ReorderedRows_AreDetected()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 5);
|
||||
var events = await SeedAndChainAsync(month, 6);
|
||||
var a = events[1];
|
||||
var b = events[4];
|
||||
var seqA = await SeqOfAsync(a);
|
||||
var seqB = await SeqOfAsync(b);
|
||||
|
||||
await ExecAsync(
|
||||
$"UPDATE dbo.AuditLog SET ChainSeq = CASE WHEN EventId = '{a}' THEN {seqB} ELSE {seqA} END " +
|
||||
$"WHERE EventId IN ('{a}', '{b}');");
|
||||
|
||||
var result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Broken, result.Status);
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, result.FirstBreak!.Kind);
|
||||
Assert.Equal(Math.Min(seqA, seqB), result.FirstBreak.ChainSeq);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The per-channel retention DELETE removes chained rows from the middle of a month and
|
||||
/// the chain still verifies (tombstones); a later chaining pass continues the chain.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task PerChannelPurge_LeavesAVerifiableChain()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 6);
|
||||
var rows = new List<AuditEvent>();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
rows.Add(NewEvent(month.AddDays(i + 1),
|
||||
channel: i % 2 == 0 ? AuditChannel.DbOutbound : AuditChannel.ApiOutbound,
|
||||
kind: i % 2 == 0 ? AuditKind.DbWrite : AuditKind.ApiCall));
|
||||
}
|
||||
|
||||
await InsertAsync(rows);
|
||||
await DrainAsync();
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
var purged = await new AuditLogRepository(ctx).PurgeChannelOlderThanAsync(
|
||||
nameof(AuditChannel.DbOutbound), month.AddDays(8), batchSize: 2);
|
||||
Assert.Equal(4, purged); // days 1,3,5,7
|
||||
}
|
||||
|
||||
var result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(4, result.TombstonesApplied);
|
||||
Assert.Equal(6, result.RowsVerified);
|
||||
|
||||
// A row arriving after the purge chains on from the existing head.
|
||||
await InsertAsync([NewEvent(month.AddDays(20))]);
|
||||
await DrainAsync();
|
||||
result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(11, result.HeadSeq);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The monthly partition-switch purge removes the whole month; the head's checkpoint
|
||||
/// anchor keeps the month verifiable, including for a late row chained afterwards.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task PartitionSwitchPurge_LeavesAnAnchoredVerifiableChain()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 7);
|
||||
await SeedAndChainAsync(month, 5);
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
await new AuditLogRepository(ctx).SwitchOutPartitionAsync(month);
|
||||
}
|
||||
|
||||
var result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(5, result.PurgedThroughSeq);
|
||||
Assert.Equal(0, result.RowsVerified);
|
||||
|
||||
await InsertAsync([NewEvent(month.AddDays(3))]);
|
||||
await DrainAsync();
|
||||
result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(1, result.RowsVerified);
|
||||
Assert.Equal(6, result.HeadSeq);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SourceNode backfill (the other sanctioned AuditLog UPDATE) must not touch a chained
|
||||
/// row — SourceNode is inside its hash.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task SourceNodeBackfill_SkipsChainedRows()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 8);
|
||||
await InsertAsync([NewEvent(month.AddDays(2), sourceNode: null)]);
|
||||
await DrainAsync();
|
||||
var unchained = NewEvent(month.AddDays(3), sourceNode: null);
|
||||
|
||||
// A row written after the drain stays unchained until the next pass.
|
||||
await InsertAsync([unchained]);
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
await new AuditLogRepository(ctx).BackfillSourceNodeAsync("unknown", month.AddMonths(1), batchSize: 10);
|
||||
}
|
||||
|
||||
await DrainAsync();
|
||||
var result = await VerifyAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Intact, result.Status);
|
||||
Assert.Equal(2, result.RowsVerified);
|
||||
Assert.Equal("unknown", await ScalarAsync<string>($"SELECT SourceNode FROM dbo.AuditLog WHERE EventId = '{unchained.EventId}';"));
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static DateTime Month(int year, int month) => new(year, month, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private async Task<List<Guid>> SeedAndChainAsync(DateTime month, int count)
|
||||
{
|
||||
var events = Enumerable.Range(1, count).Select(i => NewEvent(month.AddDays(i).AddMinutes(i))).ToList();
|
||||
await InsertAsync(events);
|
||||
await DrainAsync();
|
||||
return events.Select(e => e.EventId).ToList();
|
||||
}
|
||||
|
||||
private async Task InsertAsync(IEnumerable<AuditEvent> events)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var repo = new AuditLogRepository(ctx);
|
||||
foreach (var e in events)
|
||||
{
|
||||
await repo.InsertIfNotExistsAsync(e);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DrainAsync()
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var chain = new AuditLogHashChain(ctx);
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var r = await chain.ChainPendingAsync(500, chainBacklog: true);
|
||||
if (r.RowsChained == 0 && !r.LockBusy)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Chain did not drain.");
|
||||
}
|
||||
|
||||
private async Task<AuditChainVerificationResult> VerifyAsync(DateTime month)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
return await new AuditLogHashChain(ctx).VerifyMonthAsync(month);
|
||||
}
|
||||
|
||||
private async Task<long> SeqOfAsync(Guid eventId)
|
||||
=> await ScalarAsync<long>($"SELECT ChainSeq FROM dbo.AuditLog WHERE EventId = '{eventId}';");
|
||||
|
||||
private async Task<List<long>> ChainSeqsAsync(DateTime month)
|
||||
{
|
||||
await using var conn = new SqlConnection(_fixture.ConnectionString);
|
||||
await conn.OpenAsync();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT ChainSeq FROM dbo.AuditLog WHERE OccurredAtUtc >= @s AND OccurredAtUtc < @e ORDER BY ChainSeq;";
|
||||
cmd.Parameters.Add(new SqlParameter("@s", System.Data.SqlDbType.DateTime2) { Value = month });
|
||||
cmd.Parameters.Add(new SqlParameter("@e", System.Data.SqlDbType.DateTime2) { Value = month.AddMonths(1) });
|
||||
var list = new List<long>();
|
||||
await using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
list.Add(reader.GetInt64(0));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private async Task ExecAsync(string sql)
|
||||
{
|
||||
await using var conn = new SqlConnection(_fixture.ConnectionString);
|
||||
await conn.OpenAsync();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = sql;
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
private async Task<T> ScalarAsync<T>(string sql)
|
||||
{
|
||||
await using var conn = new SqlConnection(_fixture.ConnectionString);
|
||||
await conn.OpenAsync();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = sql;
|
||||
return (T)(await cmd.ExecuteScalarAsync())!;
|
||||
}
|
||||
|
||||
private ScadaBridgeDbContext CreateContext()
|
||||
=> new(new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlServer(_fixture.ConnectionString).Options);
|
||||
|
||||
private static AuditEvent NewEvent(
|
||||
DateTime occurredAtUtc,
|
||||
AuditChannel channel = AuditChannel.ApiOutbound,
|
||||
AuditKind kind = AuditKind.ApiCall,
|
||||
string? sourceNode = "central-a") =>
|
||||
ScadaBridgeAuditEventFactory.Create(
|
||||
channel: channel,
|
||||
kind: kind,
|
||||
status: AuditStatus.Delivered,
|
||||
occurredAtUtc: occurredAtUtc,
|
||||
target: "erp",
|
||||
sourceNode: sourceNode,
|
||||
sourceSiteId: "hash-chain-test");
|
||||
}
|
||||
+72
-136
@@ -13,13 +13,12 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server integration tests for the AuditLog Parquet archive (ScadaBridge#42) against the
|
||||
/// real migrated, partitioned schema: archive-then-purge leaves the month's hash chain
|
||||
/// verifiable and the archive re-verifiable against the purge anchor; the purge refuses to
|
||||
/// drop a partition that changed after it was archived; tampering with an archive is caught.
|
||||
/// real migrated, partitioned schema: archive-then-purge archives exactly the partition's rows
|
||||
/// and then drops them; the purge refuses to drop a partition that changed after it was
|
||||
/// archived; a damaged archive file is caught by verify.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Every test owns a distinct month (partition) of the shared fixture database; the chain
|
||||
/// and the per-channel purge are table-wide, so each test drains the chain itself.
|
||||
/// Every test owns a distinct month (partition) of the shared fixture database.
|
||||
/// </remarks>
|
||||
public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigrationFixture>, IDisposable
|
||||
{
|
||||
@@ -34,42 +33,37 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
public void Dispose() => _root.Delete(recursive: true);
|
||||
|
||||
/// <summary>
|
||||
/// Archive, then purge: the archive holds exactly the partition's rows (chained,
|
||||
/// unchained, with their chain columns) and its tombstones; after the switch the month's
|
||||
/// chain still verifies from the anchor, and the archive verifies against that anchor.
|
||||
/// Archive, then purge: the archive holds exactly the partition's stored rows; the switch
|
||||
/// drops them, the manifest is marked Purged, and the archive verifies.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ArchiveThenPurge_KeepsTheChainVerifiable_AndTheArchiveMatchesTheAnchor()
|
||||
public async Task ArchiveThenPurge_ArchivesExactlyThePartition_AndVerifies()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 2);
|
||||
await InsertAsync(Enumerable.Range(1, 10).Select(i => NewEvent(month.AddDays(i).AddTicks(i * 7_777))));
|
||||
// Two rows of a short-retention channel, purged per channel mid-chain → tombstones.
|
||||
// Two rows of a short-retention channel, purged per channel before the archive.
|
||||
await InsertAsync([NewEvent(month.AddHours(1), AuditChannel.DbOutbound), NewEvent(month.AddHours(2), AuditChannel.DbOutbound)]);
|
||||
await DrainAsync();
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
Assert.Equal(2, await new AuditLogRepository(ctx).PurgeChannelOlderThanAsync("DbOutbound", month.AddDays(1), 100));
|
||||
}
|
||||
|
||||
await InsertAsync([NewEvent(month.AddDays(20))]); // written after the drain: unchained
|
||||
await InsertAsync([NewEvent(month.AddDays(20))]);
|
||||
var before = await PartitionRowsAsync(month);
|
||||
Assert.Equal(11, before.Count);
|
||||
|
||||
var manifest = await ArchiveAsync(month);
|
||||
Assert.Equal(AuditArchiveStatus.Archived, manifest.Status);
|
||||
Assert.Equal(AuditArchiveParquet.FormatVersion, manifest.FormatVersion);
|
||||
Assert.Equal(11, manifest.RowCount);
|
||||
Assert.Equal(10, manifest.ChainedRowCount);
|
||||
Assert.Equal(1, manifest.UnchainedRowCount);
|
||||
Assert.Equal(2, manifest.TombstoneCount);
|
||||
var chain = Assert.Single(manifest.Chains);
|
||||
Assert.Equal("2026-02", chain.Partition);
|
||||
Assert.Equal(12, chain.LastSeq);
|
||||
Assert.Equal("2026-02", manifest.Partition);
|
||||
|
||||
// Row equality: the archive's data file holds exactly the partition's stored rows.
|
||||
var archived = await ReadArchiveRowsAsync(manifest);
|
||||
Assert.Equal(before.Select(Key).Order(), archived.Select(Key).Order());
|
||||
Assert.False(File.Exists(Path.Combine(_root.FullName, "2026", manifest.Name + AuditArchiveParquet.LegacyTombstoneSuffix)));
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
@@ -77,20 +71,11 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
}
|
||||
|
||||
Assert.Empty(await PartitionRowsAsync(month));
|
||||
var monthChain = await VerifyMonthAsync(month);
|
||||
Assert.Equal(AuditChainStatus.Intact, monthChain.Status);
|
||||
Assert.Equal(12, monthChain.PurgedThroughSeq);
|
||||
|
||||
var verification = await VerifyArchiveAsync(manifest.Name);
|
||||
Assert.True(verification.Verified, verification.FileProblem);
|
||||
Assert.Equal(AuditArchiveStatus.Purged, verification.ManifestStatus);
|
||||
Assert.Equal(11, verification.RowsRead);
|
||||
var v = Assert.Single(verification.Chains);
|
||||
Assert.Equal(AuditChainStatus.Intact, v.Chain.Status);
|
||||
Assert.Equal(10, v.Chain.RowsVerified);
|
||||
Assert.Equal(2, v.Chain.TombstonesApplied);
|
||||
Assert.Equal(1, v.Chain.UnchainedRows);
|
||||
Assert.Equal(AuditArchiveAnchorStatus.Matches, v.Anchor);
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
@@ -112,7 +97,6 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 3);
|
||||
await InsertAsync(Enumerable.Range(1, 5).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var stale = await ArchiveAsync(month);
|
||||
|
||||
await InsertAsync([NewEvent(month.AddDays(9))]);
|
||||
@@ -123,12 +107,10 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
}
|
||||
|
||||
Assert.Equal(6, (await PartitionRowsAsync(month)).Count);
|
||||
Assert.Null((await VerifyMonthAsync(month)).PurgedThroughSeq);
|
||||
|
||||
var staleVerification = await VerifyArchiveAsync(stale.Name);
|
||||
Assert.True(staleVerification.Verified);
|
||||
Assert.Equal(AuditArchiveStatus.Archived, staleVerification.ManifestStatus);
|
||||
Assert.Equal(AuditArchiveAnchorStatus.NotPurged, Assert.Single(staleVerification.Chains).Anchor);
|
||||
|
||||
// Positive control: a fresh archive holds the new row and is allowed to purge.
|
||||
var fresh = await ArchiveAsync(month);
|
||||
@@ -142,45 +124,16 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A chaining pass between the archive and the purge (the row count is unchanged, the
|
||||
/// chain head moved) also stops the purge: otherwise the anchor would cover links the
|
||||
/// archive does not hold.
|
||||
/// A damaged archive fails verification: a flipped byte (file hash), and a re-written file
|
||||
/// with one row dropped and the manifest's hash/size updated (row count).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task ChainAdvancingAfterTheArchive_StopsThePurge()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 4);
|
||||
await InsertAsync(Enumerable.Range(1, 4).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
await InsertAsync([NewEvent(month.AddDays(8))]); // unchained at archive time
|
||||
var manifest = await ArchiveAsync(month);
|
||||
Assert.Equal(1, manifest.UnchainedRowCount);
|
||||
|
||||
await DrainAsync(); // links the row: head 4 → 5, row count unchanged
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
var ex = await Assert.ThrowsAsync<AuditArchiveStaleException>(() => Archive(ctx).PurgeArchivedPartitionAsync(manifest));
|
||||
Assert.Equal(AuditPartitionSwitchGuard.ChainAdvancedError, ((SqlException)ex.InnerException!).Number);
|
||||
}
|
||||
|
||||
Assert.Equal(5, (await PartitionRowsAsync(month)).Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tampering with a purged archive is caught three ways: a flipped byte (file hash), a
|
||||
/// re-written file with an edited row and a re-hashed manifest (chain), and a forger who
|
||||
/// also recomputes the whole chain (the purge anchor in the database no longer matches).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task TamperedArchive_FailsVerification()
|
||||
public async Task DamagedArchive_FailsVerification()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 5);
|
||||
await InsertAsync(Enumerable.Range(1, 8).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var manifest = await ArchiveAndPurgeAsync(month);
|
||||
Assert.True((await VerifyArchiveAsync(manifest.Name)).Verified);
|
||||
|
||||
@@ -198,34 +151,14 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
Assert.False(result.FilesIntact);
|
||||
Assert.Contains("SHA-256", result.FileProblem);
|
||||
|
||||
// 2. An edited row in a re-written file, manifest hash/size updated to match.
|
||||
// 2. A row dropped from a re-written file, manifest hash/size updated to match.
|
||||
var rows = await ReadArchiveRowsAsync(manifest, original);
|
||||
var victim = rows[3];
|
||||
rows[3] = victim with { Target = "forged" };
|
||||
await RewriteAsync(rows, manifest, dataPath, manifestPath, lastHash: null);
|
||||
rows.RemoveAt(3);
|
||||
await RewriteAsync(rows, manifest, dataPath, manifestPath);
|
||||
result = await VerifyArchiveAsync(manifest.Name);
|
||||
Assert.False(result.Verified);
|
||||
Assert.True(result.FilesIntact);
|
||||
var brk = Assert.Single(result.Chains).Chain.FirstBreak!;
|
||||
Assert.Equal(AuditChainBreakKind.HashMismatch, brk.Kind);
|
||||
Assert.Equal(victim.EventId, brk.EventId);
|
||||
|
||||
// 3. The forger recomputes every link and the manifest's chain end: the archive is
|
||||
// self-consistent, but its end no longer matches the anchor the purge left.
|
||||
var previous = AuditChainHasher.GenesisHash.ToArray();
|
||||
for (var i = 0; i < rows.Count; i++)
|
||||
{
|
||||
var hash = AuditChainHasher.ComputeRowHash(previous, month, rows[i].ChainSeq!.Value, rows[i]);
|
||||
rows[i] = rows[i] with { RowHash = hash };
|
||||
previous = hash;
|
||||
}
|
||||
|
||||
await RewriteAsync(rows, manifest, dataPath, manifestPath, lastHash: Convert.ToHexStringLower(previous));
|
||||
result = await VerifyArchiveAsync(manifest.Name);
|
||||
Assert.False(result.Verified);
|
||||
var c = Assert.Single(result.Chains);
|
||||
Assert.Equal(AuditChainStatus.Intact, c.Chain.Status);
|
||||
Assert.Equal(AuditArchiveAnchorStatus.Mismatch, c.Anchor);
|
||||
Assert.False(result.FilesIntact);
|
||||
Assert.Contains("7 rows", result.FileProblem);
|
||||
|
||||
// Positive control: the untouched archive still verifies.
|
||||
await File.WriteAllBytesAsync(dataPath, original);
|
||||
@@ -234,36 +167,63 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rows that arrive for a month after it was purged chain on from the anchor; archiving
|
||||
/// and purging them again produces a second archive that resumes from the first one's end.
|
||||
/// The first archive then reports its anchor as superseded, and both verify.
|
||||
/// Rows that arrive for a month after it was purged are archived and purged again in a
|
||||
/// second archive; both verify.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task LateRows_AreArchivedAgain_FromTheAnchor()
|
||||
public async Task LateRows_AreArchivedAgain()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 6);
|
||||
await InsertAsync(Enumerable.Range(1, 3).Select(i => NewEvent(month.AddDays(i))));
|
||||
await DrainAsync();
|
||||
var first = await ArchiveAndPurgeAsync(month);
|
||||
|
||||
await InsertAsync([NewEvent(month.AddDays(15)), NewEvent(month.AddDays(16))]);
|
||||
await DrainAsync();
|
||||
await Task.Delay(5); // distinct archive name (millisecond stamp)
|
||||
var second = await ArchiveAndPurgeAsync(month);
|
||||
var chain = Assert.Single(second.Chains);
|
||||
Assert.Equal(3, chain.PriorPurgedThroughSeq);
|
||||
Assert.Equal(5, chain.LastSeq);
|
||||
Assert.Equal(2, second.RowCount);
|
||||
Assert.Empty(await PartitionRowsAsync(month));
|
||||
|
||||
var secondResult = await VerifyArchiveAsync(second.Name);
|
||||
Assert.True(secondResult.Verified);
|
||||
Assert.Equal(AuditArchiveAnchorStatus.Matches, Assert.Single(secondResult.Chains).Anchor);
|
||||
Assert.Equal(2, Assert.Single(secondResult.Chains).Chain.RowsVerified);
|
||||
Assert.True((await VerifyArchiveAsync(second.Name)).Verified);
|
||||
Assert.True((await VerifyArchiveAsync(first.Name)).Verified);
|
||||
}
|
||||
|
||||
var firstResult = await VerifyArchiveAsync(first.Name);
|
||||
Assert.True(firstResult.Verified);
|
||||
Assert.Equal(AuditArchiveAnchorStatus.Superseded, Assert.Single(firstResult.Chains).Anchor);
|
||||
/// <summary>
|
||||
/// A format-v1 manifest (written while the hash chain existed, with chain and tombstone
|
||||
/// fields) is still listed and verified.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task FormatV1Manifest_IsListedAndVerified()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var month = Month(2026, 7);
|
||||
await InsertAsync(Enumerable.Range(1, 4).Select(i => NewEvent(month.AddDays(i))));
|
||||
var manifest = await ArchiveAndPurgeAsync(month);
|
||||
|
||||
var manifestPath = Path.Combine(_root.FullName, "2026", manifest.Name + ".manifest.json");
|
||||
var node = System.Text.Json.Nodes.JsonNode.Parse(await File.ReadAllTextAsync(manifestPath))!.AsObject();
|
||||
node["formatVersion"] = 1;
|
||||
node["chainedRowCount"] = 4;
|
||||
node["unchainedRowCount"] = 0;
|
||||
node["tombstoneFile"] = manifest.Name + AuditArchiveParquet.LegacyTombstoneSuffix;
|
||||
node["tombstoneSha256"] = new string('0', 64);
|
||||
node["tombstoneCount"] = 0;
|
||||
node["chains"] = new System.Text.Json.Nodes.JsonArray(new System.Text.Json.Nodes.JsonObject
|
||||
{
|
||||
["partition"] = "2026-07", ["lastSeq"] = 4, ["lastHash"] = new string('a', 64), ["tombstoneCount"] = 0,
|
||||
});
|
||||
await File.WriteAllTextAsync(manifestPath, node.ToJsonString());
|
||||
|
||||
await using (var ctx = CreateContext())
|
||||
{
|
||||
var listed = Assert.Single(await Archive(ctx).ListAsync(), m => m.Partition == "2026-07");
|
||||
Assert.Equal(1, listed.FormatVersion);
|
||||
Assert.Equal(4, listed.RowCount);
|
||||
}
|
||||
|
||||
Assert.True((await VerifyArchiveAsync(manifest.Name)).Verified);
|
||||
}
|
||||
|
||||
/// <summary>A name that is not an archive name (e.g. a path) is rejected before any file access.</summary>
|
||||
@@ -308,16 +268,10 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
return await Archive(ctx).VerifyAsync(name);
|
||||
}
|
||||
|
||||
private async Task<AuditChainVerificationResult> VerifyMonthAsync(DateTime month)
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
return await new AuditLogHashChain(ctx).VerifyMonthAsync(month);
|
||||
}
|
||||
|
||||
private async Task<List<AuditChainRow>> ReadArchiveRowsAsync(AuditArchiveManifest manifest, byte[]? bytes = null)
|
||||
private async Task<List<AuditArchiveRow>> ReadArchiveRowsAsync(AuditArchiveManifest manifest, byte[]? bytes = null)
|
||||
{
|
||||
bytes ??= await File.ReadAllBytesAsync(Path.Combine(_root.FullName, manifest.Partition[..4], manifest.DataFile));
|
||||
var rows = new List<AuditChainRow>();
|
||||
var rows = new List<AuditArchiveRow>();
|
||||
await foreach (var row in AuditArchiveParquet.ReadRowsAsync(new MemoryStream(bytes)))
|
||||
{
|
||||
rows.Add(row);
|
||||
@@ -327,7 +281,7 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
}
|
||||
|
||||
private static async Task RewriteAsync(
|
||||
List<AuditChainRow> rows, AuditArchiveManifest manifest, string dataPath, string manifestPath, string? lastHash)
|
||||
List<AuditArchiveRow> rows, AuditArchiveManifest manifest, string dataPath, string manifestPath)
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
await using (var writer = await AuditArchiveParquet.CreateDataWriterAsync(stream, manifest.Partition, 1_000))
|
||||
@@ -345,7 +299,6 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
Status = AuditArchiveStatus.Purged,
|
||||
DataSha256 = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)),
|
||||
DataBytes = bytes.Length,
|
||||
Chains = lastHash is null ? manifest.Chains : [manifest.Chains[0] with { LastHash = lastHash }],
|
||||
};
|
||||
await File.WriteAllTextAsync(manifestPath, JsonSerializer.Serialize(forged, new JsonSerializerOptions
|
||||
{
|
||||
@@ -353,29 +306,28 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
}));
|
||||
}
|
||||
|
||||
private async Task<List<AuditChainRow>> PartitionRowsAsync(DateTime month)
|
||||
private async Task<List<AuditArchiveRow>> PartitionRowsAsync(DateTime month)
|
||||
{
|
||||
await using var conn = new SqlConnection(_fixture.ConnectionString);
|
||||
await conn.OpenAsync();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = $"SELECT {AuditLogHashChain.RowColumns}, ChainSeq, RowHash FROM dbo.AuditLog "
|
||||
cmd.CommandText = $"SELECT {AuditArchiveParquet.RowColumns} FROM dbo.AuditLog "
|
||||
+ "WHERE OccurredAtUtc >= @s AND OccurredAtUtc < @e;";
|
||||
cmd.Parameters.Add(new SqlParameter("@s", System.Data.SqlDbType.DateTime2) { Value = month });
|
||||
cmd.Parameters.Add(new SqlParameter("@e", System.Data.SqlDbType.DateTime2) { Value = month.AddMonths(1) });
|
||||
var rows = new List<AuditChainRow>();
|
||||
var rows = new List<AuditArchiveRow>();
|
||||
await using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
rows.Add(AuditLogHashChain.ReadRow(reader, withLink: true));
|
||||
rows.Add(AuditArchiveParquet.ReadRow(reader));
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
private static string Key(AuditChainRow r) => string.Join('|',
|
||||
private static string Key(AuditArchiveRow r) => string.Join('|',
|
||||
r.EventId, r.OccurredAtUtc.Ticks, r.Actor ?? "<null>", r.Action, r.Outcome, r.Category, r.Target ?? "<null>",
|
||||
r.SourceNode ?? "<null>", r.CorrelationId?.ToString() ?? "<null>", r.DetailsJson ?? "<null>",
|
||||
r.ChainSeq?.ToString() ?? "<null>", r.RowHash is null ? "<null>" : Convert.ToHexString(r.RowHash));
|
||||
r.SourceNode ?? "<null>", r.CorrelationId?.ToString() ?? "<null>", r.DetailsJson ?? "<null>");
|
||||
|
||||
private async Task InsertAsync(IEnumerable<AuditEvent> events)
|
||||
{
|
||||
@@ -387,22 +339,6 @@ public sealed class AuditLogPartitionArchiveTests : IClassFixture<MsSqlMigration
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DrainAsync()
|
||||
{
|
||||
await using var ctx = CreateContext();
|
||||
var chain = new AuditLogHashChain(ctx);
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var r = await chain.ChainPendingAsync(500, chainBacklog: true);
|
||||
if (r.RowsChained == 0 && !r.LockBusy)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Chain did not drain.");
|
||||
}
|
||||
|
||||
private ScadaBridgeDbContext CreateContext()
|
||||
=> new(new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlServer(_fixture.ConnectionString).Options);
|
||||
|
||||
|
||||
-249
@@ -1,249 +0,0 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// The hardened two-login setup (ScadaBridge#107 item 3), end to end on SQL Server: a writer
|
||||
/// login (<c>db_datareader</c> + <c>db_datawriter</c> + <c>scadabridge_audit_writer</c>) and a
|
||||
/// maintenance login (<c>scadabridge_audit_chainer</c> + <c>scadabridge_audit_purger</c> only),
|
||||
/// wired through <c>AddConfigurationDatabase(writer, maintenance)</c>. The writer ingests but
|
||||
/// cannot chain, update or delete; the maintenance services run on the maintenance login and
|
||||
/// can chain, verify, export heads, per-channel purge, enumerate partitions, archive and switch.
|
||||
/// </summary>
|
||||
public sealed class AuditMaintenanceLoginTests : IClassFixture<MsSqlMigrationFixture>, IAsyncLifetime
|
||||
{
|
||||
private const string Password = "Sb_W22_maint#2026";
|
||||
|
||||
private readonly MsSqlMigrationFixture _fixture;
|
||||
private readonly string _suffix = Guid.NewGuid().ToString("N")[..10];
|
||||
private readonly DirectoryInfo _archiveDir = Directory.CreateTempSubdirectory("maint-login-archive-");
|
||||
|
||||
/// <summary>Creates the test class with its own migrated SQL Server database.</summary>
|
||||
/// <param name="fixture">The per-class migration fixture.</param>
|
||||
public AuditMaintenanceLoginTests(MsSqlMigrationFixture fixture) => _fixture = fixture;
|
||||
|
||||
private string WriterLogin => "sbw_" + _suffix;
|
||||
|
||||
private string MaintenanceLogin => "sbm_" + _suffix;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
if (!_fixture.Available)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var conn = _fixture.OpenConnection();
|
||||
await using var cmd = new SqlCommand($@"
|
||||
CREATE LOGIN [{WriterLogin}] WITH PASSWORD = N'{Password}', CHECK_POLICY = OFF;
|
||||
CREATE LOGIN [{MaintenanceLogin}] WITH PASSWORD = N'{Password}', CHECK_POLICY = OFF;
|
||||
CREATE USER [{WriterLogin}] FOR LOGIN [{WriterLogin}];
|
||||
CREATE USER [{MaintenanceLogin}] FOR LOGIN [{MaintenanceLogin}];
|
||||
ALTER ROLE db_datareader ADD MEMBER [{WriterLogin}];
|
||||
ALTER ROLE db_datawriter ADD MEMBER [{WriterLogin}];
|
||||
ALTER ROLE scadabridge_audit_writer ADD MEMBER [{WriterLogin}];
|
||||
ALTER ROLE scadabridge_audit_chainer ADD MEMBER [{MaintenanceLogin}];
|
||||
ALTER ROLE scadabridge_audit_purger ADD MEMBER [{MaintenanceLogin}];", conn);
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
_archiveDir.Delete(recursive: true);
|
||||
if (!_fixture.Available)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SqlConnection.ClearAllPools();
|
||||
await using var conn = _fixture.OpenConnection();
|
||||
await using var cmd = new SqlCommand($@"
|
||||
DECLARE @kill nvarchar(max) = N'';
|
||||
SELECT @kill = @kill + N'KILL ' + CAST(session_id AS nvarchar(10)) + N';' FROM sys.dm_exec_sessions
|
||||
WHERE login_name IN (N'{WriterLogin}', N'{MaintenanceLogin}');
|
||||
EXEC sp_executesql @kill;
|
||||
IF USER_ID(N'{WriterLogin}') IS NOT NULL DROP USER [{WriterLogin}];
|
||||
IF USER_ID(N'{MaintenanceLogin}') IS NOT NULL DROP USER [{MaintenanceLogin}];
|
||||
IF SUSER_ID(N'{WriterLogin}') IS NOT NULL DROP LOGIN [{WriterLogin}];
|
||||
IF SUSER_ID(N'{MaintenanceLogin}') IS NOT NULL DROP LOGIN [{MaintenanceLogin}];", conn);
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writer ingests and is refused every maintenance write; the maintenance services, resolved
|
||||
/// from DI on the separate login, do the whole chain + purge + archive cycle.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task HardenedTwoLoginSetup_WriterIngestsOnly_MaintenanceLoginRunsChainAndPurges()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var writerCs = As(WriterLogin);
|
||||
var maintenanceCs = As(MaintenanceLogin);
|
||||
var month = new DateTime(2027, 2, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// The writer login ingests.
|
||||
await using (var writerCtx = Context(writerCs))
|
||||
{
|
||||
var repo = new AuditLogRepository(writerCtx);
|
||||
foreach (var i in Enumerable.Range(1, 4))
|
||||
{
|
||||
await repo.InsertIfNotExistsAsync(NewEvent(month.AddDays(i), AuditChannel.ApiOutbound));
|
||||
}
|
||||
|
||||
await repo.InsertIfNotExistsAsync(NewEvent(month.AddHours(2), AuditChannel.DbOutbound));
|
||||
}
|
||||
|
||||
// Negative controls: the writer login can neither chain nor delete.
|
||||
await using (var writerCtx = Context(writerCs))
|
||||
{
|
||||
await Assert.ThrowsAsync<SqlException>(() => new AuditLogHashChain(writerCtx).ChainPendingAsync(100, chainBacklog: true));
|
||||
await Assert.ThrowsAsync<SqlException>(() =>
|
||||
new AuditLogRepository(writerCtx).PurgeChannelOlderThanAsync("DbOutbound", month.AddDays(1), 100));
|
||||
}
|
||||
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddConfigurationDatabase(writerCs, maintenanceCs);
|
||||
services.AddSingleton(Options.Create(new AuditLogArchiveOptions
|
||||
{
|
||||
Enabled = true,
|
||||
Directory = _archiveDir.FullName,
|
||||
RowGroupSize = 1_000,
|
||||
}));
|
||||
await using var provider = services.BuildServiceProvider();
|
||||
|
||||
await using (var scope = provider.CreateAsyncScope())
|
||||
{
|
||||
var maintenance = scope.ServiceProvider.GetRequiredService<AuditMaintenanceContext>();
|
||||
Assert.True(maintenance.UsesSeparateLogin);
|
||||
Assert.Equal(MaintenanceLogin, await LoginNameAsync(maintenance.Context));
|
||||
Assert.Equal(WriterLogin, await LoginNameAsync(scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>()));
|
||||
|
||||
var chain = scope.ServiceProvider.GetRequiredService<IAuditLogHashChain>();
|
||||
Assert.Equal(5, (await chain.ChainPendingAsync(100, chainBacklog: true)).RowsChained);
|
||||
Assert.Equal(AuditChainStatus.Intact, (await chain.VerifyMonthAsync(month)).Status);
|
||||
var head = Assert.Single(await scope.ServiceProvider.GetRequiredService<IAuditChainHeadStore>().ReadHeadsAsync());
|
||||
Assert.Equal(5, head.LastSeq);
|
||||
|
||||
var repo = scope.ServiceProvider.GetRequiredKeyedService<IAuditLogRepository>(AuditMaintenanceContext.ServiceKey);
|
||||
Assert.Equal(1, await repo.PurgeChannelOlderThanAsync("DbOutbound", month.AddDays(1), 100));
|
||||
Assert.Contains(month, await repo.GetPartitionBoundariesOlderThanAsync(month.AddYears(5)));
|
||||
|
||||
var archive = scope.ServiceProvider.GetRequiredKeyedService<IAuditLogArchive>(AuditMaintenanceContext.ServiceKey);
|
||||
var manifest = await archive.ArchivePartitionAsync(month);
|
||||
Assert.Equal(4, manifest.RowCount);
|
||||
Assert.Equal(4, await archive.PurgeArchivedPartitionAsync(manifest));
|
||||
Assert.Equal(AuditChainStatus.Intact, (await chain.VerifyMonthAsync(month)).Status);
|
||||
}
|
||||
|
||||
// Unset maintenance string: the maintenance context is the runtime context, as before.
|
||||
var plain = new ServiceCollection();
|
||||
plain.AddLogging();
|
||||
plain.AddConfigurationDatabase(writerCs);
|
||||
await using var plainProvider = plain.BuildServiceProvider();
|
||||
await using var plainScope = plainProvider.CreateAsyncScope();
|
||||
var shared = plainScope.ServiceProvider.GetRequiredService<AuditMaintenanceContext>();
|
||||
Assert.False(shared.UsesSeparateLogin);
|
||||
Assert.Same(plainScope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>(), shared.Context);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ScadaBridge#113: the monthly roll-forward (<c>ALTER PARTITION FUNCTION … SPLIT RANGE</c>) and
|
||||
/// the <c>SourceNode</c> backfill run on the maintenance login — and are refused to the writer
|
||||
/// login — with only the role grants the <c>AuditMaintenanceGrants</c> migration provisions.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task RollForwardAndSourceNodeBackfill_RunOnTheMaintenanceLogin_NotTheWriter()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
var writerCs = As(WriterLogin);
|
||||
var maintenanceCs = As(MaintenanceLogin);
|
||||
var month = new DateTime(2027, 4, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// A pre-feature row: no SourceNode, not chained.
|
||||
await using (var writerCtx = Context(writerCs))
|
||||
{
|
||||
var legacy = NewEvent(month.AddDays(1), AuditChannel.ApiOutbound) with { SourceNode = null };
|
||||
await new AuditLogRepository(writerCtx).InsertIfNotExistsAsync(legacy);
|
||||
}
|
||||
|
||||
// Negative controls: the writer login can neither split the partition function nor backfill.
|
||||
await using (var writerCtx = Context(writerCs))
|
||||
{
|
||||
await Assert.ThrowsAsync<SqlException>(() => new AuditLogPartitionMaintenance(writerCtx).EnsureLookaheadAsync(60));
|
||||
await Assert.ThrowsAsync<SqlException>(() =>
|
||||
new AuditLogRepository(writerCtx).BackfillSourceNodeAsync("unknown", month.AddYears(1), 100));
|
||||
}
|
||||
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddConfigurationDatabase(writerCs, maintenanceCs);
|
||||
await using var provider = services.BuildServiceProvider();
|
||||
await using (var scope = provider.CreateAsyncScope())
|
||||
{
|
||||
var maintenance = scope.ServiceProvider.GetRequiredService<AuditMaintenanceContext>();
|
||||
var roll = scope.ServiceProvider.GetRequiredService<ZB.MOM.WW.ScadaBridge.Commons.Interfaces.IPartitionMaintenance>();
|
||||
var before = await roll.GetMaxBoundaryAsync();
|
||||
var added = await roll.EnsureLookaheadAsync(60);
|
||||
Assert.NotEmpty(added);
|
||||
Assert.True(await roll.GetMaxBoundaryAsync() > before);
|
||||
|
||||
var repo = scope.ServiceProvider.GetRequiredKeyedService<IAuditLogRepository>(
|
||||
ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories.AuditLogServiceKeys.Maintenance);
|
||||
Assert.Equal(1, await repo.BackfillSourceNodeAsync("unknown", month.AddYears(1), 100));
|
||||
Assert.Equal(MaintenanceLogin, await LoginNameAsync(maintenance.Context));
|
||||
}
|
||||
}
|
||||
|
||||
private string As(string login) => new SqlConnectionStringBuilder(_fixture.ConnectionString)
|
||||
{
|
||||
UserID = login,
|
||||
Password = Password,
|
||||
IntegratedSecurity = false,
|
||||
}.ConnectionString;
|
||||
|
||||
private static ScadaBridgeDbContext Context(string cs)
|
||||
=> new(new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlServer(cs).Options);
|
||||
|
||||
private static async Task<string> LoginNameAsync(ScadaBridgeDbContext ctx)
|
||||
{
|
||||
var conn = ctx.Database.GetDbConnection();
|
||||
await conn.OpenAsync();
|
||||
try
|
||||
{
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT SUSER_SNAME();";
|
||||
return (string)(await cmd.ExecuteScalarAsync())!;
|
||||
}
|
||||
finally
|
||||
{
|
||||
await conn.CloseAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static AuditEvent NewEvent(DateTime occurredAtUtc, AuditChannel channel) =>
|
||||
ScadaBridgeAuditEventFactory.Create(
|
||||
channel: channel,
|
||||
kind: channel == AuditChannel.DbOutbound ? AuditKind.DbWrite : AuditKind.ApiCall,
|
||||
status: AuditStatus.Delivered,
|
||||
occurredAtUtc: occurredAtUtc,
|
||||
actor: "maint-login-test",
|
||||
target: "erp",
|
||||
sourceNode: "central-a",
|
||||
sourceSiteId: "maint-login-test",
|
||||
correlationId: Guid.NewGuid());
|
||||
}
|
||||
+40
-23
@@ -29,14 +29,18 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
|
||||
// The migration immediately before the flip, so "Down" reverts exactly this one.
|
||||
private static readonly string PreviousMigration = MigrationBefore(FlipMigration);
|
||||
|
||||
// The ten non-clustered indexes at head. RemoveAuditLogHashChain (2026-11-15, after the
|
||||
// flip) dropped the two hash-chain indexes; one migration before the flip they still exist.
|
||||
private static readonly string[] NonClusteredIndexes =
|
||||
[
|
||||
"IX_AuditLog_OccurredAtUtc", "IX_AuditLog_Site_Occurred", "IX_AuditLog_CorrelationId",
|
||||
"IX_AuditLog_Channel_Status_Occurred", "IX_AuditLog_Target_Occurred", "IX_AuditLog_Execution",
|
||||
"IX_AuditLog_ParentExecution", "IX_AuditLog_Node_Occurred", "IX_AuditLog_Kind_Occurred",
|
||||
"IX_AuditLog_Actor_Occurred", "IX_AuditLog_Unchained", "IX_AuditLog_ChainSeq",
|
||||
"IX_AuditLog_Actor_Occurred",
|
||||
];
|
||||
|
||||
private static readonly string[] ChainIndexes = ["IX_AuditLog_Unchained", "IX_AuditLog_ChainSeq"];
|
||||
|
||||
private readonly MsSqlMigrationFixture _fixture;
|
||||
private readonly ITestOutputHelper _output;
|
||||
|
||||
@@ -50,9 +54,10 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After the full chain: clustered PK (OccurredAtUtc, EventId), the unique aligned
|
||||
/// (EventId, OccurredAtUtc) index, all twelve non-clustered indexes with unchanged keys and
|
||||
/// filters, everything on ps_AuditLog_Month, and every append-only/chain grant intact.
|
||||
/// After the full migration chain: clustered PK (OccurredAtUtc, EventId), the unique aligned
|
||||
/// (EventId, OccurredAtUtc) index, the ten non-clustered indexes with unchanged keys and
|
||||
/// filters (the two hash-chain indexes gone), everything on ps_AuditLog_Month, and every
|
||||
/// append-only grant intact.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
@@ -67,7 +72,7 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
|
||||
Assert.True(indexes["UX_AuditLog_EventId_Occurred"].Unique);
|
||||
Assert.Equal(NonClusteredIndexes.Length + 2, indexes.Count);
|
||||
Assert.All(indexes.Values, i => Assert.Equal("ps_AuditLog_Month", i.DataSpace));
|
||||
AssertTwelveNonClusteredIndexes(indexes);
|
||||
AssertNonClusteredIndexes(indexes, withChainIndexes: false);
|
||||
Assert.Equal(ExpectedGrants, await ReadGrantsAsync());
|
||||
}
|
||||
|
||||
@@ -86,14 +91,16 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
|
||||
var down = await ReadIndexesAsync();
|
||||
Assert.Equal("EventId, OccurredAtUtc", down["PK_AuditLog"].Keys);
|
||||
Assert.False(down.ContainsKey("UX_AuditLog_EventId_Occurred"));
|
||||
AssertTwelveNonClusteredIndexes(down);
|
||||
Assert.Equal(GrantsBeforeMaintenanceGrants, await ReadGrantsAsync());
|
||||
AssertNonClusteredIndexes(down, withChainIndexes: true);
|
||||
Assert.Equal(GrantsBeforeTheFlip, await ReadGrantsAsync());
|
||||
|
||||
// Old shape: the purge's staging table must take the old key order.
|
||||
// Old shape: the purge's staging table must take the old key order — and, since this is
|
||||
// also before RemoveAuditLogHashChain, carry the two chain columns the live table still has.
|
||||
await AssertSwitchOutPurgesAsync(new DateTime(2027, 3, 1, 0, 0, 0, DateTimeKind.Utc));
|
||||
|
||||
// Back to head (not just to the flip): migrations after it — AuditMaintenanceGrants —
|
||||
// were reverted by the Down too, and the class leaves the database fully migrated.
|
||||
// Back to head (not just to the flip): migrations after it — AuditMaintenanceGrants,
|
||||
// RemoveAuditLogHashChain — were reverted by the Down too, and the class leaves the
|
||||
// database fully migrated.
|
||||
await MigrateToHeadAsync();
|
||||
var up = await ReadIndexesAsync();
|
||||
Assert.Equal("OccurredAtUtc, EventId", up["PK_AuditLog"].Keys);
|
||||
@@ -146,26 +153,29 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
|
||||
}
|
||||
}
|
||||
|
||||
// At head: RemoveAuditLogHashChain dropped the chainer role and revoked the purger's
|
||||
// AuditMaintenanceGrants column grant.
|
||||
private static readonly string[] ExpectedGrants =
|
||||
[
|
||||
"scadabridge_audit_chainer|SELECT|GRANT|",
|
||||
"scadabridge_audit_chainer|UPDATE|GRANT|ChainSeq",
|
||||
"scadabridge_audit_chainer|UPDATE|GRANT|RowHash",
|
||||
"scadabridge_audit_purger|DELETE|GRANT|",
|
||||
"scadabridge_audit_purger|SELECT|GRANT|",
|
||||
// AuditMaintenanceGrants (migration 64, after the flip) — the archive path's column grant.
|
||||
"scadabridge_audit_purger|UPDATE|GRANT|SourceNode",
|
||||
"scadabridge_audit_writer|DELETE|DENY|",
|
||||
"scadabridge_audit_writer|INSERT|GRANT|",
|
||||
"scadabridge_audit_writer|SELECT|GRANT|",
|
||||
"scadabridge_audit_writer|UPDATE|DENY|",
|
||||
];
|
||||
|
||||
// The grants one migration before the flip: AuditMaintenanceGrants is not applied yet.
|
||||
private static readonly string[] GrantsBeforeMaintenanceGrants =
|
||||
ExpectedGrants.Where(g => !g.EndsWith("|SourceNode", StringComparison.Ordinal)).ToArray();
|
||||
// One migration before the flip: the hash chain's chainer grants exist (AddAuditLogHashChain)
|
||||
// and AuditMaintenanceGrants is not applied yet.
|
||||
private static readonly string[] GrantsBeforeTheFlip =
|
||||
ExpectedGrants.Concat(
|
||||
[
|
||||
"scadabridge_audit_chainer|SELECT|GRANT|",
|
||||
"scadabridge_audit_chainer|UPDATE|GRANT|ChainSeq",
|
||||
"scadabridge_audit_chainer|UPDATE|GRANT|RowHash",
|
||||
]).Order(StringComparer.Ordinal).ToArray();
|
||||
|
||||
private static void AssertTwelveNonClusteredIndexes(IReadOnlyDictionary<string, IndexShape> indexes)
|
||||
private static void AssertNonClusteredIndexes(IReadOnlyDictionary<string, IndexShape> indexes, bool withChainIndexes)
|
||||
{
|
||||
Assert.Equal("OccurredAtUtc DESC", indexes["IX_AuditLog_OccurredAtUtc"].Keys);
|
||||
Assert.Equal("Status", indexes["IX_AuditLog_OccurredAtUtc"].Included);
|
||||
@@ -180,11 +190,18 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
|
||||
Assert.Equal("SourceNode, OccurredAtUtc", indexes["IX_AuditLog_Node_Occurred"].Keys);
|
||||
Assert.Equal("Kind, OccurredAtUtc DESC", indexes["IX_AuditLog_Kind_Occurred"].Keys);
|
||||
Assert.Equal("Actor, OccurredAtUtc DESC", indexes["IX_AuditLog_Actor_Occurred"].Keys);
|
||||
Assert.Equal("OccurredAtUtc, EventId", indexes["IX_AuditLog_Unchained"].Keys);
|
||||
Assert.Equal("([ChainSeq] IS NULL)", indexes["IX_AuditLog_Unchained"].Filter);
|
||||
Assert.Equal("ChainSeq", indexes["IX_AuditLog_ChainSeq"].Keys);
|
||||
Assert.Equal("([ChainSeq] IS NOT NULL)", indexes["IX_AuditLog_ChainSeq"].Filter);
|
||||
Assert.All(NonClusteredIndexes, n => Assert.False(indexes[n].Clustered, n));
|
||||
if (withChainIndexes)
|
||||
{
|
||||
Assert.Equal("OccurredAtUtc, EventId", indexes["IX_AuditLog_Unchained"].Keys);
|
||||
Assert.Equal("([ChainSeq] IS NULL)", indexes["IX_AuditLog_Unchained"].Filter);
|
||||
Assert.Equal("ChainSeq", indexes["IX_AuditLog_ChainSeq"].Keys);
|
||||
Assert.Equal("([ChainSeq] IS NOT NULL)", indexes["IX_AuditLog_ChainSeq"].Filter);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.All(ChainIndexes, n => Assert.False(indexes.ContainsKey(n), n));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AssertSwitchOutPurgesAsync(DateTime month)
|
||||
|
||||
+2
-1
@@ -60,7 +60,8 @@ public sealed class IdempotentMigrationScriptTests : IClassFixture<MsSqlMigratio
|
||||
|
||||
await RunScriptAsync(script);
|
||||
Assert.Equal(all, await ReadHistoryAsync());
|
||||
Assert.Equal(2, await CountChainIndexesAsync());
|
||||
// AddAuditLogHashChain created the two chain indexes, RemoveAuditLogHashChain dropped them.
|
||||
Assert.Equal(0, await CountChainIndexesAsync());
|
||||
|
||||
// Second run against the fully-migrated database: every guard is false.
|
||||
await RunScriptAsync(script);
|
||||
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Migrations.Operations;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server tests for the <c>RemoveAuditLogHashChain</c> migration (2026-11-15): at head the
|
||||
/// hash-chain columns, tables, indexes and chainer role are gone and the purger keeps only its
|
||||
/// original grants; Down restores what <c>AddAuditLogHashChain</c> + <c>AuditMaintenanceGrants</c>
|
||||
/// created; and Up is re-runnable and drops a chainer role that still has members.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The tests in this class migrate the fixture database down and back up, so they own their
|
||||
/// fixture (one database per test class) and every test leaves the database fully migrated.
|
||||
/// </remarks>
|
||||
public sealed class RemoveAuditLogHashChainMigrationTests : IClassFixture<MsSqlMigrationFixture>
|
||||
{
|
||||
private const string RemoveMigration = "20261115221558_RemoveAuditLogHashChain";
|
||||
|
||||
private static readonly string PreviousMigration = MigrationBefore(RemoveMigration);
|
||||
|
||||
private readonly MsSqlMigrationFixture _fixture;
|
||||
|
||||
/// <summary>Creates the test class with its own migrated SQL Server database.</summary>
|
||||
/// <param name="fixture">The per-class migration fixture.</param>
|
||||
public RemoveAuditLogHashChainMigrationTests(MsSqlMigrationFixture fixture) => _fixture = fixture;
|
||||
|
||||
/// <summary>At head nothing of the hash chain or the maintenance grants is left.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task AtHead_TheChainSchema_AndTheMaintenanceGrants_AreGone()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
await AssertRemovedAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Down restores the chain schema exactly (columns, tables, indexes, chainer role and grants,
|
||||
/// the purger's maintenance grants); Up then drops it again, also when the chainer role has a
|
||||
/// member; and re-running Up's SQL on the migrated schema changes nothing.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
public async Task DownUp_RoundTrips_DropsAChainerRoleWithMembers_AndIsReRunnable()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
|
||||
await MigrateToAsync(PreviousMigration);
|
||||
try
|
||||
{
|
||||
Assert.True(await ScalarAsync<int>("SELECT CASE WHEN COL_LENGTH('dbo.AuditLog','ChainSeq') IS NULL THEN 0 ELSE 1 END;") == 1);
|
||||
Assert.True(await ScalarAsync<int>("SELECT CASE WHEN COL_LENGTH('dbo.AuditLog','RowHash') IS NULL THEN 0 ELSE 1 END;") == 1);
|
||||
Assert.True(await ScalarAsync<int>("SELECT CASE WHEN OBJECT_ID('dbo.AuditLogChainHead','U') IS NULL THEN 0 ELSE 1 END;") == 1);
|
||||
Assert.True(await ScalarAsync<int>("SELECT CASE WHEN OBJECT_ID('dbo.AuditLogChainTombstone','U') IS NULL THEN 0 ELSE 1 END;") == 1);
|
||||
Assert.Equal(2, await ScalarAsync<int>(
|
||||
"SELECT COUNT(*) FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.AuditLog') AND name IN ('IX_AuditLog_Unchained','IX_AuditLog_ChainSeq');"));
|
||||
Assert.Contains("scadabridge_audit_chainer|UPDATE|GRANT|ChainSeq", await ReadAuditLogGrantsAsync());
|
||||
Assert.Contains("scadabridge_audit_purger|UPDATE|GRANT|SourceNode", await ReadAuditLogGrantsAsync());
|
||||
Assert.Equal(1, await ScalarAsync<int>(
|
||||
"SELECT COUNT(*) FROM sys.database_permissions p JOIN sys.database_principals pr ON pr.principal_id = p.grantee_principal_id "
|
||||
+ "WHERE pr.name = 'scadabridge_audit_purger' AND p.class = 0 AND p.permission_name = 'ALTER ANY DATASPACE' AND p.state_desc = 'GRANT';"));
|
||||
|
||||
// A login was put in the chainer role (the hardened two-login setup): Up must still drop the role.
|
||||
await ExecAsync("IF DATABASE_PRINCIPAL_ID('rm_chain_test_user') IS NULL CREATE USER rm_chain_test_user WITHOUT LOGIN;"
|
||||
+ "ALTER ROLE scadabridge_audit_chainer ADD MEMBER rm_chain_test_user;");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await MigrateToHeadAsync();
|
||||
}
|
||||
|
||||
await AssertRemovedAsync();
|
||||
Assert.Equal(1, await ScalarAsync<int>("SELECT CASE WHEN DATABASE_PRINCIPAL_ID('rm_chain_test_user') IS NULL THEN 0 ELSE 1 END;"));
|
||||
|
||||
// Re-run Up's SQL against the migrated schema: every statement is guarded.
|
||||
foreach (var op in new RemoveAuditLogHashChain().UpOperations.OfType<SqlOperation>())
|
||||
{
|
||||
await ExecAsync(op.Sql);
|
||||
}
|
||||
|
||||
await AssertRemovedAsync();
|
||||
}
|
||||
|
||||
private async Task AssertRemovedAsync()
|
||||
{
|
||||
Assert.Equal(0, await ScalarAsync<int>("SELECT CASE WHEN COL_LENGTH('dbo.AuditLog','ChainSeq') IS NULL THEN 0 ELSE 1 END;"));
|
||||
Assert.Equal(0, await ScalarAsync<int>("SELECT CASE WHEN COL_LENGTH('dbo.AuditLog','RowHash') IS NULL THEN 0 ELSE 1 END;"));
|
||||
Assert.Equal(0, await ScalarAsync<int>("SELECT CASE WHEN OBJECT_ID('dbo.AuditLogChainHead','U') IS NULL THEN 0 ELSE 1 END;"));
|
||||
Assert.Equal(0, await ScalarAsync<int>("SELECT CASE WHEN OBJECT_ID('dbo.AuditLogChainTombstone','U') IS NULL THEN 0 ELSE 1 END;"));
|
||||
Assert.Equal(0, await ScalarAsync<int>(
|
||||
"SELECT COUNT(*) FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.AuditLog') AND name IN ('IX_AuditLog_Unchained','IX_AuditLog_ChainSeq');"));
|
||||
Assert.Equal(0, await ScalarAsync<int>("SELECT CASE WHEN DATABASE_PRINCIPAL_ID('scadabridge_audit_chainer') IS NULL THEN 0 ELSE 1 END;"));
|
||||
Assert.Equal(0, await ScalarAsync<int>(
|
||||
"SELECT COUNT(*) FROM sys.database_permissions p JOIN sys.database_principals pr ON pr.principal_id = p.grantee_principal_id "
|
||||
+ "WHERE pr.name = 'scadabridge_audit_purger' AND p.class = 0 AND p.permission_name = 'ALTER ANY DATASPACE';"));
|
||||
|
||||
// The roles that predate the chain stay, with exactly their original AuditLog grants.
|
||||
Assert.Equal(
|
||||
new[]
|
||||
{
|
||||
"scadabridge_audit_purger|DELETE|GRANT|",
|
||||
"scadabridge_audit_purger|SELECT|GRANT|",
|
||||
"scadabridge_audit_writer|DELETE|DENY|",
|
||||
"scadabridge_audit_writer|INSERT|GRANT|",
|
||||
"scadabridge_audit_writer|SELECT|GRANT|",
|
||||
"scadabridge_audit_writer|UPDATE|DENY|",
|
||||
},
|
||||
await ReadAuditLogGrantsAsync());
|
||||
}
|
||||
|
||||
private async Task<T> ScalarAsync<T>(string sql)
|
||||
{
|
||||
await using var conn = _fixture.OpenConnection();
|
||||
await using var cmd = new SqlCommand(sql, conn);
|
||||
return (T)Convert.ChangeType((await cmd.ExecuteScalarAsync())!, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private async Task ExecAsync(string sql)
|
||||
{
|
||||
await using var conn = _fixture.OpenConnection();
|
||||
await using var cmd = new SqlCommand(sql, conn) { CommandTimeout = 300 };
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
private async Task<string[]> ReadAuditLogGrantsAsync()
|
||||
{
|
||||
await using var conn = _fixture.OpenConnection();
|
||||
await using var cmd = new SqlCommand(@"
|
||||
SELECT pr.name, p.permission_name, p.state_desc, COL_NAME(p.major_id, p.minor_id)
|
||||
FROM sys.database_permissions p JOIN sys.database_principals pr ON pr.principal_id = p.grantee_principal_id
|
||||
WHERE p.major_id = OBJECT_ID('dbo.AuditLog') AND p.class = 1;", conn);
|
||||
var list = new List<string>();
|
||||
await using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
list.Add($"{reader.GetString(0)}|{reader.GetString(1)}|{reader.GetString(2)}|{(reader.IsDBNull(3) ? "" : reader.GetString(3))}");
|
||||
}
|
||||
|
||||
return list.Order(StringComparer.Ordinal).ToArray();
|
||||
}
|
||||
|
||||
private async Task MigrateToAsync(string migration)
|
||||
{
|
||||
await using var ctx = new ScadaBridgeDbContext(new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||
.UseSqlServer(_fixture.ConnectionString, sql => sql.CommandTimeout(600)).Options);
|
||||
await ctx.GetService<IMigrator>().MigrateAsync(migration);
|
||||
}
|
||||
|
||||
private async Task MigrateToHeadAsync()
|
||||
{
|
||||
await using var ctx = new ScadaBridgeDbContext(new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||
.UseSqlServer(_fixture.ConnectionString, sql => sql.CommandTimeout(600)).Options);
|
||||
await ctx.GetService<IMigrator>().MigrateAsync();
|
||||
}
|
||||
|
||||
private static string MigrationBefore(string migration)
|
||||
{
|
||||
using var ctx = new ScadaBridgeDbContext(new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||
.UseSqlServer("Server=unused;Database=unused").Options);
|
||||
var all = ctx.Database.GetMigrations().ToList();
|
||||
return all[all.IndexOf(migration) - 1];
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
|
||||
using ZB.MOM.WW.ScadaBridge.Host.Health;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Host.Tests;
|
||||
|
||||
/// <summary>ScadaBridge#115: the chain-head export readiness entry.</summary>
|
||||
public sealed class AuditChainHeadExportHealthCheckTests
|
||||
{
|
||||
private sealed class Clock(DateTime now) : TimeProvider
|
||||
{
|
||||
public DateTime Now { get; set; } = now;
|
||||
public override DateTimeOffset GetUtcNow() => new(DateTime.SpecifyKind(Now, DateTimeKind.Utc));
|
||||
}
|
||||
|
||||
private static readonly DateTime T0 = new(2026, 11, 10, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static async Task<HealthStatus> Check(AuditChainHeadExportStatus s, Clock c)
|
||||
=> (await new AuditChainHeadExportHealthCheck(s, c).CheckHealthAsync(new HealthCheckContext())).Status;
|
||||
|
||||
/// <summary>Disabled export is healthy; failing or stale export is Degraded; recovery clears it.</summary>
|
||||
[Fact]
|
||||
public async Task Status_follows_export_outcome()
|
||||
{
|
||||
var clock = new Clock(T0);
|
||||
var status = new AuditChainHeadExportStatus();
|
||||
Assert.Equal(HealthStatus.Healthy, await Check(status, clock)); // disabled
|
||||
|
||||
status.MarkStarted(60, T0);
|
||||
Assert.Equal(HealthStatus.Healthy, await Check(status, clock));
|
||||
|
||||
status.RecordFailure(T0, "share offline");
|
||||
var result = await new AuditChainHeadExportHealthCheck(status, clock).CheckHealthAsync(new HealthCheckContext());
|
||||
Assert.Equal(HealthStatus.Degraded, result.Status);
|
||||
Assert.Contains("share offline", result.Description);
|
||||
|
||||
status.RecordSuccess(T0);
|
||||
Assert.Equal(HealthStatus.Healthy, await Check(status, clock));
|
||||
|
||||
clock.Now = T0.AddMinutes(121); // no success for > 2 intervals
|
||||
Assert.Equal(HealthStatus.Degraded, await Check(status, clock));
|
||||
status.RecordSuccess(clock.Now);
|
||||
Assert.Equal(HealthStatus.Healthy, await Check(status, clock));
|
||||
}
|
||||
}
|
||||
@@ -44,11 +44,10 @@ public class AuditArchiveCommandTests : TestKit
|
||||
new(new AuthenticatedUser("u", "U", roles, sites), command, Guid.NewGuid().ToString("N"));
|
||||
|
||||
private static AuditArchiveManifest Manifest() => new(
|
||||
1, Name, new DateTime(2025, 10, 1, 0, 0, 0, DateTimeKind.Utc), "2025-10",
|
||||
2, Name, new DateTime(2025, 10, 1, 0, 0, 0, DateTimeKind.Utc), "2025-10",
|
||||
new DateTime(2026, 11, 9, 12, 0, 0, DateTimeKind.Utc), AuditArchiveStatus.Purged,
|
||||
new DateTime(2026, 11, 9, 12, 0, 1, DateTimeKind.Utc), 10, 9, 1, null, null,
|
||||
Name + ".parquet", "ab", 1234, Name + ".tombstones.parquet", "cd", 0,
|
||||
[new AuditArchiveChainState("2025-10", 9, new string('0', 64), null, null, 0)]);
|
||||
new DateTime(2026, 11, 9, 12, 0, 1, DateTimeKind.Utc), 10, null, null,
|
||||
Name + ".parquet", "ab", 1234);
|
||||
|
||||
/// <summary>A Viewer lists the archives; status renders as a name.</summary>
|
||||
[Fact]
|
||||
@@ -66,23 +65,21 @@ public class AuditArchiveCommandTests : TestKit
|
||||
Assert.Equal("Purged", archive.GetProperty("status").GetString());
|
||||
}
|
||||
|
||||
/// <summary>Verification results reach the wire with the anchor and chain status as names.</summary>
|
||||
/// <summary>Verification results reach the wire, status as a name.</summary>
|
||||
[Fact]
|
||||
public void Viewer_GetsVerificationResult()
|
||||
{
|
||||
var chain = new AuditChainVerificationResult("2025-10", AuditChainStatus.Intact, 9, 0, null, 9, 1, null);
|
||||
_archive.VerifyAsync(Name, Arg.Any<CancellationToken>()).Returns(new AuditArchiveVerificationResult(
|
||||
Name, "2025-10", AuditArchiveStatus.Purged, true, true, null, 10,
|
||||
[new AuditArchiveChainVerification(chain, AuditArchiveAnchorStatus.Matches, "ends at the anchor")]));
|
||||
Name, "2025-10", AuditArchiveStatus.Purged, true, true, null, 10));
|
||||
|
||||
CreateActor().Tell(Envelope(new VerifyAuditArchiveCommand(Name), [], "Viewer"));
|
||||
|
||||
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
using var json = JsonDocument.Parse(response.JsonData);
|
||||
Assert.True(json.RootElement.GetProperty("verified").GetBoolean());
|
||||
var c = json.RootElement.GetProperty("chains")[0];
|
||||
Assert.Equal("Matches", c.GetProperty("anchor").GetString());
|
||||
Assert.Equal("Intact", c.GetProperty("chain").GetProperty("status").GetString());
|
||||
Assert.Equal("Purged", json.RootElement.GetProperty("manifestStatus").GetString());
|
||||
Assert.Equal(10, json.RootElement.GetProperty("rowsRead").GetInt64());
|
||||
Assert.False(json.RootElement.TryGetProperty("chains", out _));
|
||||
}
|
||||
|
||||
/// <summary>Designer/Deployer without an OperationalAudit role are refused both commands.</summary>
|
||||
|
||||
@@ -168,12 +168,8 @@ public class RequiredRoleMatrixTests
|
||||
["FlowDebugReplay"] = FlowDebuggerReplayers,
|
||||
|
||||
// ---- Audit reads (OperationalAudit) -----------------------------------------
|
||||
// AuditLog hash-chain verification (ScadaBridge#41) carries audit query's
|
||||
// OperationalAudit permission (alog.md §15.1); written out by hand to keep the freeze.
|
||||
["VerifyAuditChain"] = [Roles.Administrator, Roles.Viewer],
|
||||
// Off-box exported chain heads (ScadaBridge#107): same audit-read gate.
|
||||
["VerifyAuditChainHeads"] = [Roles.Administrator, Roles.Viewer],
|
||||
// AuditLog Parquet archives (ScadaBridge#42): same audit-read gate as verify-chain.
|
||||
// AuditLog Parquet archives (ScadaBridge#42) carry audit query's OperationalAudit
|
||||
// permission (alog.md §15.1); written out by hand to keep the freeze.
|
||||
["ListAuditArchives"] = [Roles.Administrator, Roles.Viewer],
|
||||
["VerifyAuditArchive"] = [Roles.Administrator, Roles.Viewer],
|
||||
// Archive cleanup deletes files (ScadaBridge#109): Administrator only.
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
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)));
|
||||
}
|
||||
}
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
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>VerifyAuditChainHeads</c> management command (ScadaBridge#107 item 1): role gate,
|
||||
/// site-scope refusal, input bounds, and the verdicts reaching the wire with enums as names.
|
||||
/// </summary>
|
||||
public class VerifyAuditChainHeadsCommandTests : TestKit
|
||||
{
|
||||
private readonly IAuditChainHeadStore _store = Substitute.For<IAuditChainHeadStore>();
|
||||
|
||||
private static readonly AuditChainHeadRecord Record = new(
|
||||
1, "2026-05", 12, new string('a', 64), null, null, 12, 0,
|
||||
new DateTime(2026, 5, 3, 0, 0, 0, DateTimeKind.Utc), new DateTime(2026, 5, 3, 1, 0, 0, DateTimeKind.Utc), "central-a");
|
||||
|
||||
private IActorRef CreateActor()
|
||||
{
|
||||
var services = new ServiceCollection().AddTestConfigurationTransaction();
|
||||
services.AddScoped(_ => _store);
|
||||
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 store's verdicts; the records reach the store unchanged.</summary>
|
||||
[Fact]
|
||||
public void Viewer_GetsTheVerdicts_ForTheSuppliedRecords()
|
||||
{
|
||||
var check = new AuditChainHeadCheck("2026-05", 12, Record.ExportedAtUtc, "central-a",
|
||||
AuditChainHeadStatus.Mismatch, 12, "rewritten");
|
||||
_store.VerifyExportedHeadsAsync(Arg.Any<IReadOnlyList<AuditChainHeadRecord>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new AuditChainHeadVerificationResult(false, 1, [check]));
|
||||
|
||||
CreateActor().Tell(Envelope(new VerifyAuditChainHeadsCommand([Record]), [], "Viewer"));
|
||||
|
||||
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
using var json = JsonDocument.Parse(response.JsonData);
|
||||
Assert.False(json.RootElement.GetProperty("verified").GetBoolean());
|
||||
Assert.Equal("Mismatch", json.RootElement.GetProperty("checks")[0].GetProperty("status").GetString());
|
||||
_store.Received(1).VerifyExportedHeadsAsync(
|
||||
Arg.Is<IReadOnlyList<AuditChainHeadRecord>>(r => r.Count == 1 && r[0] == Record), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>A Designer/Deployer without an OperationalAudit role is refused.</summary>
|
||||
[Fact]
|
||||
public void NonAuditRole_IsUnauthorized()
|
||||
{
|
||||
CreateActor().Tell(Envelope(new VerifyAuditChainHeadsCommand([Record]), [], "Designer", "Deployer"));
|
||||
|
||||
ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
|
||||
_store.DidNotReceiveWithAnyArgs().VerifyExportedHeadsAsync(default!, default);
|
||||
}
|
||||
|
||||
/// <summary>A site-scoped Viewer is refused: the chain spans every site.</summary>
|
||||
[Fact]
|
||||
public void SiteScopedViewer_IsRefused()
|
||||
{
|
||||
CreateActor().Tell(Envelope(new VerifyAuditChainHeadsCommand([Record]), ["3"], "Viewer"));
|
||||
|
||||
var response = ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
|
||||
Assert.Contains("spans every site", response.Message);
|
||||
_store.DidNotReceiveWithAnyArgs().VerifyExportedHeadsAsync(default!, default);
|
||||
}
|
||||
|
||||
/// <summary>No records, or more than the cap, is a caller error.</summary>
|
||||
/// <param name="count">Records supplied.</param>
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(ManagementActor.MaxChainHeadRecords + 1)]
|
||||
public void EmptyOrOversizedInput_IsInvalidArgument(int count)
|
||||
{
|
||||
CreateActor().Tell(Envelope(
|
||||
new VerifyAuditChainHeadsCommand(Enumerable.Repeat(Record, count).ToList()), [], "Administrator"));
|
||||
|
||||
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("INVALID_ARGUMENT", response.ErrorCode);
|
||||
_store.DidNotReceiveWithAnyArgs().VerifyExportedHeadsAsync(default!, default);
|
||||
}
|
||||
|
||||
/// <summary>A chain lock that cannot be had surfaces as CHAIN_BUSY.</summary>
|
||||
[Fact]
|
||||
public void BusyChain_IsChainBusy()
|
||||
{
|
||||
_store.VerifyExportedHeadsAsync(Arg.Any<IReadOnlyList<AuditChainHeadRecord>>(), Arg.Any<CancellationToken>())
|
||||
.Returns<Task<AuditChainHeadVerificationResult>>(_ => throw new TimeoutException("busy"));
|
||||
|
||||
CreateActor().Tell(Envelope(new VerifyAuditChainHeadsCommand([Record]), [], "Administrator"));
|
||||
|
||||
Assert.Equal("CHAIN_BUSY", ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5)).ErrorCode);
|
||||
}
|
||||
|
||||
/// <summary>Runs under the long-running Ask timeout.</summary>
|
||||
[Fact]
|
||||
public void VerifyAuditChainHeads_UsesLongRunningAskTimeout()
|
||||
{
|
||||
Assert.Equal(TimeSpan.FromMinutes(5),
|
||||
ManagementEndpoints.ResolveAskTimeout(new ManagementServiceOptions(), typeof(VerifyAuditChainHeadsCommand)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user