Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/AuditLogHashChainOptions.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

100 lines
5.0 KiB
C#

using ZB.MOM.WW.Configuration;
using ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central;
/// <summary>
/// Options for the central <see cref="AuditLogHashChainService"/> (section
/// <c>AuditLog:HashChain</c>) — hash-chain tamper evidence for the AuditLog
/// (audit roadmap T1, alog.md §11.4, ScadaBridge#41).
/// </summary>
/// <remarks>
/// <para>
/// <b>Default OFF</b> (alog.md §11.4: "Default off … to avoid operational burden"). When
/// enabled, both central nodes run the job; the SQL application lock means only one of
/// them chains at a time, so a dual-active pair still produces one gap-free chain per month.
/// </para>
/// <para>
/// <b>Chain start (ScadaBridge#139).</b> Enabling it on an existing database does NOT chain the
/// historical backlog: the first chaining pass records a chain-start anchor in the database at
/// the database's current UTC time, and only rows dated from then on are chained. Older rows
/// stay unchained and are reported by <c>audit verify-chain</c> as pre-cutoff rows, never as a
/// break. The anchor is written once and is the same for both central nodes. Set
/// <see cref="ChainBacklog"/> to chain the backlog instead (only effective on the very first
/// enablement). Run <c>audit backfill-source-node</c> BEFORE enabling either way: a chained
/// row's SourceNode is frozen.
/// </para>
/// </remarks>
public sealed class AuditLogHashChainOptions
{
/// <summary>Whether the chaining job runs (default false).</summary>
public bool Enabled { get; set; }
/// <summary>
/// Chain the historical backlog on first enablement instead of starting the chain at the
/// enablement instant (default false — owner decision on ScadaBridge#107, 2026-11-13: no
/// backlog chaining). Only read while nothing has been chained yet: once the database holds
/// a chain-start anchor or any chained row, the decision is fixed and this value is ignored.
/// Set it the same on both central nodes; if they differ, whichever chains first decides.
/// </summary>
public bool ChainBacklog { get; set; }
/// <summary>Seconds between chaining ticks (default 60).</summary>
public int IntervalSeconds { get; set; } = 60;
/// <summary>Rows linked per transaction (default 1000).</summary>
public int BatchSize { get; set; } = 1000;
/// <summary>Upper bound on batches per tick so a backlog yields between ticks (default 100).</summary>
public int MaxBatchesPerTick { get; set; } = 100;
/// <summary>
/// Off-box export of the per-month chain heads (<c>AuditLog:HashChain:HeadExport</c>,
/// ScadaBridge#107 item 1) — the chain's external anchor. Default off.
/// </summary>
public AuditChainHeadExportOptions HeadExport { get; set; } = new();
}
/// <summary>Validates <see cref="AuditLogHashChainOptions"/> at host startup.</summary>
public sealed class AuditLogHashChainOptionsValidator : OptionsValidatorBase<AuditLogHashChainOptions>
{
/// <inheritdoc />
protected override void Validate(ValidationBuilder builder, AuditLogHashChainOptions options)
{
builder.RequireThat(options.IntervalSeconds > 0,
$"AuditLog:HashChain:{nameof(AuditLogHashChainOptions.IntervalSeconds)} ({options.IntervalSeconds}) must be > 0.");
builder.RequireThat(options.BatchSize is > 0 and <= 10_000,
$"AuditLog:HashChain:{nameof(AuditLogHashChainOptions.BatchSize)} ({options.BatchSize}) must be between 1 and 10000.");
builder.RequireThat(options.MaxBatchesPerTick > 0,
$"AuditLog:HashChain:{nameof(AuditLogHashChainOptions.MaxBatchesPerTick)} ({options.MaxBatchesPerTick}) must be > 0.");
var export = options.HeadExport ?? new AuditChainHeadExportOptions();
if (!export.Enabled)
{
return;
}
const string section = "AuditLog:HashChain:HeadExport";
builder.RequireThat(export.IntervalMinutes > 0,
$"{section}:IntervalMinutes ({export.IntervalMinutes}) must be > 0.");
if (export.Sink == AuditChainHeadSinkKind.File)
{
var dir = export.File?.Directory;
builder.RequireThat(!string.IsNullOrWhiteSpace(dir) && Path.IsPathFullyQualified(dir),
$"{section}:File:Directory ('{dir}') must be an absolute path (local or UNC) when Sink=File.");
}
else
{
var syslog = export.Syslog ?? new AuditChainHeadSyslogSinkOptions();
builder.RequireThat(!string.IsNullOrWhiteSpace(syslog.Host),
$"{section}:Syslog:Host is required when Sink=Syslog.");
builder.RequireThat(syslog.Port is > 0 and <= 65535,
$"{section}:Syslog:Port ({syslog.Port}) must be between 1 and 65535.");
builder.RequireThat(syslog.Facility is >= 0 and <= 23,
$"{section}:Syslog:Facility ({syslog.Facility}) must be between 0 and 23.");
builder.RequireThat(syslog.TimeoutSeconds > 0,
$"{section}:Syslog:TimeoutSeconds ({syslog.TimeoutSeconds}) must be > 0.");
}
}
}