Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/AuditLogHashChainService.cs
T
Joseph Doherty 52da02a76a feat(audit): hash-chain cutoff - chain only rows written from first enablement, no backlog (#139)
Owner decision on #107 (2026-11-13): enabling AuditLog:HashChain must not
chain the historical backlog. main chained every unchained row oldest-first.

- The first chaining pass on a pristine database (no head, no chained row)
  writes a chain-start anchor: AuditLogChainTombstone (cutoff month,
  ChainSeq 0), PurgedAtUtc = DB SYSUTCDATETIME(), RowHash =
  SHA-256("ScadaBridge.AuditLog.ChainCutoff.v1" || YYYY-MM || ticks).
  Written once under the exclusive chain lock, so both centrals agree
  whatever their clocks/config. No migration: existing table + grants.
- Only rows with OccurredAtUtc >= cutoff are chained. The anchor hash is
  the cutoff month's genesis, binding the cutoff into the chain.
- AuditLog:HashChain:ChainBacklog (default false) restores chain-everything,
  read only on the very first enablement. Legacy chains (heads, no anchor)
  keep chaining everything.
- verify-chain splits unchained rows into UnchainedRows vs PreCutoffRows
  (+ ChainFromUtc); new breaks ChainedBeforeCutoff (row re-dated before the
  cutoff, or cutoff moved forward) and CutoffAnchorInvalid (anchor hash /
  month / multiplicity). Archive verify uses the anchor from its own
  tombstone file or the DB.
- Partition switch-out keeps the anchor (deletes ChainSeq > 0 only); the
  head store / export / verify-heads tombstone count excludes it.
- CLI verify-chain table prints Chain from + Pre-cutoff rows.

Tests: AuditLogHashChainCutoffTests (7, MSSQL), 6 verifier unit tests,
service/CLI/management wire tests; 9 mutations all killed.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-13 03:14:14 -05:00

152 lines
5.4 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central;
/// <summary>
/// Central hosted service that links newly written AuditLog rows into their month's
/// SHA-256 hash chain (audit roadmap T1, alog.md §11.4, ScadaBridge#41). The chaining
/// job of alog.md §11.4, run incrementally — every <see cref="AuditLogHashChainOptions.IntervalSeconds"/>
/// rather than only once a month has closed, so a row is tamper-evident within about a
/// minute of reaching central instead of up to a month later.
/// </summary>
/// <remarks>
/// <para>
/// Same shape as <see cref="AuditLogPartitionMaintenanceService"/>: a background loop, a
/// fresh DI scope per tick, every failure logged and contained. Runs on BOTH central nodes;
/// <see cref="IAuditLogHashChain.ChainPendingAsync"/> takes an exclusive SQL application
/// lock with a zero timeout, so the peer's pass skips instead of racing (and correctness
/// does not depend on Akka's view of which node is active).
/// </para>
/// </remarks>
public sealed class AuditLogHashChainService : IHostedService, IDisposable
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly IOptions<AuditLogHashChainOptions> _options;
private readonly ILogger<AuditLogHashChainService> _logger;
private CancellationTokenSource? _cts;
private Task? _loop;
/// <summary>Initializes the service.</summary>
/// <param name="scopeFactory">Scope factory used to resolve the scoped chain implementation per tick.</param>
/// <param name="options">Hash-chain options.</param>
/// <param name="logger">Logger.</param>
public AuditLogHashChainService(
IServiceScopeFactory scopeFactory,
IOptions<AuditLogHashChainOptions> options,
ILogger<AuditLogHashChainService> logger)
{
_scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
if (!_options.Value.Enabled)
{
_logger.LogInformation("AuditLog hash chain disabled (AuditLog:HashChain:Enabled=false); no chaining job started.");
return Task.CompletedTask;
}
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_cts = cts;
var token = cts.Token;
_loop = Task.Run(() => RunLoopAsync(token), CancellationToken.None);
return Task.CompletedTask;
}
private async Task RunLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
await TickAsync(ct).ConfigureAwait(false);
try
{
await Task.Delay(TimeSpan.FromSeconds(_options.Value.IntervalSeconds), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
}
/// <summary>
/// Runs one tick: chains batches until the backlog is empty, the peer holds the lock,
/// or <see cref="AuditLogHashChainOptions.MaxBatchesPerTick"/> is reached.
/// </summary>
/// <param name="ct">Cancellation token.</param>
/// <returns>The number of rows chained in this tick.</returns>
internal async Task<long> TickAsync(CancellationToken ct)
{
long total = 0;
try
{
var options = _options.Value;
await using var scope = _scopeFactory.CreateAsyncScope();
var chain = scope.ServiceProvider.GetRequiredService<IAuditLogHashChain>();
for (var i = 0; i < options.MaxBatchesPerTick && !ct.IsCancellationRequested; i++)
{
var result = await chain.ChainPendingAsync(options.BatchSize, options.ChainBacklog, ct).ConfigureAwait(false);
total += result.RowsChained;
if (result.LockBusy || result.RowsChained == 0)
{
break;
}
}
if (total > 0)
{
_logger.LogDebug("AuditLog hash chain linked {Rows} rows this tick.", total);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Shutdown.
}
catch (Exception ex)
{
// Contained: a transient SQL failure must not end the loop; the next tick
// resumes from wherever the last committed pass left the chain.
_logger.LogError(ex, "AuditLog hash-chain tick failed after linking {Rows} rows.", total);
}
return total;
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
try
{
_cts?.Cancel();
}
catch (ObjectDisposedException)
{
// Dispose already cancelled the loop.
}
return _loop ?? Task.CompletedTask;
}
/// <inheritdoc />
public void Dispose()
{
try
{
_cts?.Cancel();
}
catch (ObjectDisposedException)
{
// Idempotent.
}
_cts?.Dispose();
}
}