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:
Joseph Doherty
2026-11-15 17:37:33 -05:00
parent 125db03232
commit ed2ed0a367
82 changed files with 3203 additions and 7603 deletions
@@ -30,8 +30,6 @@ public sealed class AuditLogArchiveOptionsValidator : OptionsValidatorBase<Audit
$"AuditLog:Archive:{nameof(AuditLogArchiveOptions.RowGroupSize)} ({options.RowGroupSize}) must be between 1000 and 1000000.");
builder.RequireThat(options.ReadCommandTimeoutMinutes > 0,
$"AuditLog:Archive:{nameof(AuditLogArchiveOptions.ReadCommandTimeoutMinutes)} ({options.ReadCommandTimeoutMinutes}) must be > 0.");
builder.RequireThat(options.ChainLockTimeoutSeconds > 0,
$"AuditLog:Archive:{nameof(AuditLogArchiveOptions.ChainLockTimeoutSeconds)} ({options.ChainLockTimeoutSeconds}) must be > 0.");
builder.RequireThat(options.RetentionDays is >= 0 and <= 36_500,
$"AuditLog:Archive:{nameof(AuditLogArchiveOptions.RetentionDays)} ({options.RetentionDays}) must be between 0 (never delete) and 36500.");
}
@@ -1,99 +0,0 @@
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.");
}
}
}
@@ -1,151 +0,0 @@
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();
}
}
@@ -49,9 +49,7 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central;
/// </para>
/// <para>
/// <b>DI scopes.</b> <see cref="IAuditLogRepository"/> is a scoped EF Core
/// service registered by <c>AddConfigurationDatabase</c> — the
/// <see cref="AuditMaintenanceContext.ServiceKey"/>-keyed one, on the AuditLog maintenance
/// connection (ScadaBridge#107 item 3), when registered. The singleton
/// service registered by <c>AddConfigurationDatabase</c>. The singleton
/// opens one DI scope per tick and reuses the same repository across every
/// boundary in that tick — mirrors the
/// <see cref="SiteAuditReconciliationActor"/> pattern.
@@ -152,11 +150,7 @@ public class AuditLogPurgeActor : ReceiveActor
IAuditLogRepository repository;
try
{
// The maintenance-connection repository when the host registered one
// (AddConfigurationDatabase, ScadaBridge#107 item 3 — on the separate maintenance
// login if AuditLog:MaintenanceConnectionString is set), else the plain one.
repository = scope.ServiceProvider.GetKeyedService<IAuditLogRepository>(AuditMaintenanceContext.ServiceKey)
?? scope.ServiceProvider.GetRequiredService<IAuditLogRepository>();
repository = scope.ServiceProvider.GetRequiredService<IAuditLogRepository>();
}
catch (Exception ex)
{
@@ -210,8 +204,7 @@ public class AuditLogPurgeActor : ReceiveActor
{
try
{
archive = scope.ServiceProvider.GetKeyedService<IAuditLogArchive>(AuditMaintenanceContext.ServiceKey)
?? scope.ServiceProvider.GetRequiredService<IAuditLogArchive>();
archive = scope.ServiceProvider.GetRequiredService<IAuditLogArchive>();
}
catch (Exception ex)
{
@@ -305,8 +298,7 @@ public class AuditLogPurgeActor : ReceiveActor
return;
}
archive = services.GetKeyedService<IAuditLogArchive>(AuditMaintenanceContext.ServiceKey)
?? services.GetRequiredService<IAuditLogArchive>();
archive = services.GetRequiredService<IAuditLogArchive>();
}
var result = await archive.CleanupAsync(dryRun: false).ConfigureAwait(false);
@@ -1,87 +0,0 @@
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
/// <summary>Where exported chain heads go.</summary>
public enum AuditChainHeadSinkKind
{
/// <summary>Append-only JSON-lines files in a directory (local or UNC).</summary>
File,
/// <summary>RFC 5424 syslog over UDP or TCP.</summary>
Syslog,
}
/// <summary>Syslog transport.</summary>
public enum AuditSyslogProtocol
{
/// <summary>One datagram per record (RFC 5426).</summary>
Udp,
/// <summary>Octet-counted frames on one TCP connection per export (RFC 6587).</summary>
Tcp,
}
/// <summary>
/// Off-box export of the AuditLog hash-chain heads (section <c>AuditLog:HashChain:HeadExport</c>,
/// ScadaBridge#107 item 1). <b>Default OFF.</b> Every <see cref="IntervalMinutes"/> both central
/// nodes read each month's chain head (month, last sequence + hash, partition-purge anchor,
/// chained-row and tombstone counts) and append the heads that changed since their previous
/// export to a sink the database login cannot write. <c>audit verify-heads</c> later compares
/// those records with the database: a chain someone rewrote and re-hashed inside SQL Server no
/// longer carries the hash that was exported.
/// </summary>
public sealed class AuditChainHeadExportOptions
{
/// <summary>Whether the export runs (default false).</summary>
public bool Enabled { get; set; }
/// <summary>Minutes between exports (default 60).</summary>
public int IntervalMinutes { get; set; } = 60;
/// <summary>
/// Re-export unchanged heads every tick too (default false: only heads whose sequence,
/// anchor or counts moved since this node's previous export, plus every head on the first
/// tick after start).
/// </summary>
public bool ExportUnchanged { get; set; }
/// <summary>Which sink (default <see cref="AuditChainHeadSinkKind.File"/>).</summary>
public AuditChainHeadSinkKind Sink { get; set; } = AuditChainHeadSinkKind.File;
/// <summary>File sink settings.</summary>
public AuditChainHeadFileSinkOptions File { get; set; } = new();
/// <summary>Syslog sink settings.</summary>
public AuditChainHeadSyslogSinkOptions Syslog { get; set; } = new();
}
/// <summary>File sink: <c>{Directory}/{yyyy}/audit-chain-heads-{yyyy-MM-dd}-{node}.jsonl</c>, opened for append only.</summary>
public sealed class AuditChainHeadFileSinkOptions
{
/// <summary>
/// Absolute directory (local path or UNC share). Give the service account create + append
/// rights only; the SQL Server login has no access to it by construction.
/// </summary>
public string? Directory { get; set; }
}
/// <summary>Syslog sink (RFC 5424).</summary>
public sealed class AuditChainHeadSyslogSinkOptions
{
/// <summary>Collector host name or address.</summary>
public string? Host { get; set; }
/// <summary>Collector port (default 514).</summary>
public int Port { get; set; } = 514;
/// <summary>Transport (default UDP).</summary>
public AuditSyslogProtocol Protocol { get; set; } = AuditSyslogProtocol.Udp;
/// <summary>Syslog facility 0–23 (default 13, "log audit").</summary>
public int Facility { get; set; } = 13;
/// <summary>APP-NAME field (default <c>scadabridge</c>).</summary>
public string AppName { get; set; } = "scadabridge";
/// <summary>Send/connect timeout in seconds (default 10).</summary>
public int TimeoutSeconds { get; set; } = 10;
}
@@ -1,205 +0,0 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
/// <summary>
/// Central hosted service that exports the AuditLog hash-chain heads off-box
/// (<c>AuditLog:HashChain:HeadExport</c>, ScadaBridge#107 item 1). Default off.
/// </summary>
/// <remarks>
/// <para>
/// Runs on both central nodes (each record names its node). A tick reads every month's head in
/// one consistent snapshot (<see cref="IAuditChainHeadStore.ReadHeadsAsync"/>, chain lock
/// SHARED) and writes the heads that changed since this node's last successful export — all of
/// them on the first tick after start — to the configured <see cref="IAuditChainHeadSink"/>.
/// A failed write is logged and retried on the next tick with the same heads (the in-memory
/// "last exported" state only advances on success). No signing: the protection is that the
/// sink sits outside the database login's reach.
/// </para>
/// </remarks>
public sealed class AuditChainHeadExportService : IHostedService, IDisposable
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly AuditChainHeadExportOptions _options;
private readonly IAuditChainHeadSink? _sink;
private readonly string? _node;
private readonly TimeProvider _time;
private readonly ILogger<AuditChainHeadExportService> _logger;
private readonly AuditChainHeadExportStatus _status;
private readonly Dictionary<DateTime, (long Seq, long? Purged, long Links)> _lastExported = new();
private CancellationTokenSource? _cts;
private Task? _loop;
/// <summary>Initializes the service.</summary>
/// <param name="scopeFactory">Scope factory for the scoped head store.</param>
/// <param name="options">Hash-chain options (the <c>HeadExport</c> sub-section is used).</param>
/// <param name="sink">The sink (null when the export is disabled).</param>
/// <param name="nodeName">This node's name for the records.</param>
/// <param name="logger">Logger.</param>
/// <param name="time">Clock.</param>
/// <param name="status">Health status the tick outcome is recorded on (ScadaBridge#115).</param>
public AuditChainHeadExportService(
IServiceScopeFactory scopeFactory,
IOptions<AuditLogHashChainOptions> options,
IAuditChainHeadSink? sink,
string? nodeName,
ILogger<AuditChainHeadExportService> logger,
TimeProvider? time = null,
AuditChainHeadExportStatus? status = null)
{
_status = status ?? new AuditChainHeadExportStatus();
_scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
_options = (options ?? throw new ArgumentNullException(nameof(options))).Value.HeadExport;
_sink = sink;
_node = nodeName;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_time = time ?? TimeProvider.System;
}
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
if (!_options.Enabled || _sink is null)
{
_logger.LogInformation("AuditLog chain-head export disabled (AuditLog:HashChain:HeadExport:Enabled=false).");
return Task.CompletedTask;
}
_status.MarkStarted(_options.IntervalMinutes, _time.GetUtcNow().UtcDateTime);
_logger.LogInformation("AuditLog chain-head export every {Minutes} min to {Sink}.", _options.IntervalMinutes, _sink.Describe);
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.FromMinutes(_options.IntervalMinutes), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
}
/// <summary>Runs one export tick.</summary>
/// <param name="ct">Cancellation token.</param>
/// <returns>The number of records written (0 on failure or nothing changed).</returns>
internal async Task<int> TickAsync(CancellationToken ct)
{
if (_sink is null)
{
return 0;
}
try
{
IReadOnlyList<AuditChainHeadSnapshot> heads;
await using (var scope = _scopeFactory.CreateAsyncScope())
{
heads = await scope.ServiceProvider.GetRequiredService<IAuditChainHeadStore>()
.ReadHeadsAsync(ct).ConfigureAwait(false);
}
var now = _time.GetUtcNow().UtcDateTime;
var changed = heads
.Where(h => _options.ExportUnchanged
|| !_lastExported.TryGetValue(h.Month, out var last)
|| last != (h.LastSeq, h.PurgedThroughSeq, h.ChainedRows + h.Tombstones))
.ToList();
if (changed.Count == 0)
{
_status.RecordSuccess(now);
return 0;
}
var records = changed.Select(h => ToRecord(h, now, _node)).ToList();
await _sink.WriteAsync(records, ct).ConfigureAwait(false);
foreach (var h in changed)
{
_lastExported[h.Month] = (h.LastSeq, h.PurgedThroughSeq, h.ChainedRows + h.Tombstones);
}
_status.RecordSuccess(now);
_logger.LogDebug("Exported {Count} AuditLog chain head(s) to {Sink}.", records.Count, _sink.Describe);
return records.Count;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return 0;
}
catch (Exception ex)
{
// Contained: the next tick retries the same heads (nothing was marked exported).
_logger.LogError(ex, "AuditLog chain-head export to {Sink} failed; retrying next tick.", _sink.Describe);
_status.RecordFailure(_time.GetUtcNow().UtcDateTime, ex.Message);
return 0;
}
}
/// <summary>Maps a database head to its exported record.</summary>
/// <param name="head">The head.</param>
/// <param name="exportedAtUtc">Export time.</param>
/// <param name="node">Exporting node.</param>
/// <returns>The record.</returns>
public static AuditChainHeadRecord ToRecord(AuditChainHeadSnapshot head, DateTime exportedAtUtc, string? node)
{
ArgumentNullException.ThrowIfNull(head);
return new AuditChainHeadRecord(
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,
exportedAtUtc,
node);
}
/// <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();
}
}
@@ -1,91 +0,0 @@
using System.Diagnostics.Metrics;
using ZB.MOM.WW.ScadaBridge.Commons.Observability;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
/// <summary>
/// Health signal of the off-box chain-head export (ScadaBridge#115). Updated by
/// <see cref="AuditChainHeadExportService"/> on every tick; read by the Host's
/// <c>audit-chain-head-export</c> /health/ready check. A sink that stays down used to be a
/// log line only, silently stopping the external anchor.
/// </summary>
public sealed class AuditChainHeadExportStatus
{
private static readonly Meter Meter = new(ScadaBridgeTelemetry.MeterName);
private static readonly Counter<long> FailuresCounter =
Meter.CreateCounter<long>("scadabridge.audit.chain_head_export.failures", unit: "1",
description: "AuditLog chain-head export ticks that failed to read or write the heads (sink offline / unreachable); retried next tick.");
private readonly object _gate = new();
private long _totalFailures;
private int _consecutiveFailures;
private DateTime? _lastSuccessUtc;
private DateTime? _lastFailureUtc;
private string? _lastError;
private DateTime? _startedUtc;
/// <summary>Whether the export is running at all (false = disabled, nothing to report).</summary>
public bool Enabled { get; private set; }
/// <summary>Minutes between export ticks (for the staleness test).</summary>
public int IntervalMinutes { get; private set; } = 60;
/// <summary>Total failed ticks since process start.</summary>
public long TotalFailures { get { lock (_gate) { return _totalFailures; } } }
/// <summary>Failed ticks since the last success.</summary>
public int ConsecutiveFailures { get { lock (_gate) { return _consecutiveFailures; } } }
/// <summary>UTC time of the last successful tick, or null.</summary>
public DateTime? LastSuccessUtc { get { lock (_gate) { return _lastSuccessUtc; } } }
/// <summary>UTC time of the last failed tick, or null.</summary>
public DateTime? LastFailureUtc { get { lock (_gate) { return _lastFailureUtc; } } }
/// <summary>Message of the last failure (never a secret: the exception message only), or null.</summary>
public string? LastError { get { lock (_gate) { return _lastError; } } }
/// <summary>UTC time the export loop started, or null.</summary>
public DateTime? StartedUtc { get { lock (_gate) { return _startedUtc; } } }
/// <summary>Marks the export as running.</summary>
/// <param name="intervalMinutes">Tick interval.</param>
/// <param name="nowUtc">Start time.</param>
public void MarkStarted(int intervalMinutes, DateTime nowUtc)
{
lock (_gate)
{
Enabled = true;
IntervalMinutes = intervalMinutes;
_startedUtc = nowUtc;
}
}
/// <summary>Records a successful tick.</summary>
/// <param name="nowUtc">Time of the tick.</param>
public void RecordSuccess(DateTime nowUtc)
{
lock (_gate)
{
_consecutiveFailures = 0;
_lastSuccessUtc = nowUtc;
}
}
/// <summary>Records a failed tick and bumps the failure counter metric.</summary>
/// <param name="nowUtc">Time of the tick.</param>
/// <param name="error">The failure message.</param>
public void RecordFailure(DateTime nowUtc, string error)
{
lock (_gate)
{
_totalFailures++;
_consecutiveFailures++;
_lastFailureUtc = nowUtc;
_lastError = error;
}
FailuresCounter.Add(1);
}
}
@@ -1,21 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
/// <summary>The one JSON shape every sink writes (and <c>audit verify-heads</c> reads).</summary>
public static class AuditChainHeadJson
{
/// <summary>camelCase, compact, nulls kept so every record has every field.</summary>
public static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web)
{
WriteIndented = false,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
};
/// <summary>Serialises one record to a single line.</summary>
/// <param name="record">The record.</param>
/// <returns>Compact JSON.</returns>
public static string Serialize(AuditChainHeadRecord record) => JsonSerializer.Serialize(record, Options);
}
@@ -1,79 +0,0 @@
using System.Text;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
/// <summary>
/// Appends exported heads as JSON lines to <c>{Directory}/{yyyy}/audit-chain-heads-{yyyy-MM-dd}-{node}.jsonl</c>.
/// </summary>
/// <remarks>
/// The file is only ever opened with <see cref="FileMode.Append"/> — never truncated, rewritten
/// or deleted by ScadaBridge — so the share can grant the service account create + append data
/// only. One file per node per UTC day keeps the two central nodes from interleaving writes in
/// one file. Each batch is flushed to disk before the call returns.
/// </remarks>
public sealed class FileAuditChainHeadSink : IAuditChainHeadSink
{
private readonly string _directory;
private readonly string _node;
private readonly TimeProvider _time;
/// <summary>Creates the sink.</summary>
/// <param name="directory">Absolute export directory.</param>
/// <param name="node">This node's name (part of the file name).</param>
/// <param name="time">Clock (file-per-day naming).</param>
public FileAuditChainHeadSink(string directory, string node, TimeProvider? time = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(directory);
if (!Path.IsPathFullyQualified(directory))
{
throw new ArgumentException($"Head-export directory '{directory}' must be absolute.", nameof(directory));
}
_directory = directory;
_node = SafeName(string.IsNullOrWhiteSpace(node) ? "node" : node);
_time = time ?? TimeProvider.System;
}
/// <inheritdoc />
public string Describe => _directory;
/// <summary>The file a write at <paramref name="nowUtc"/> lands in.</summary>
/// <param name="nowUtc">The write time.</param>
/// <returns>The full path.</returns>
public string PathFor(DateTime nowUtc) => Path.Combine(
_directory, nowUtc.ToString("yyyy", System.Globalization.CultureInfo.InvariantCulture),
$"audit-chain-heads-{nowUtc:yyyy-MM-dd}-{_node}.jsonl");
/// <inheritdoc />
public async Task WriteAsync(IReadOnlyList<AuditChainHeadRecord> records, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(records);
if (records.Count == 0)
{
return;
}
var path = PathFor(_time.GetUtcNow().UtcDateTime);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var text = new StringBuilder();
foreach (var record in records)
{
text.Append(AuditChainHeadJson.Serialize(record)).Append('\n');
}
var bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(text.ToString());
await using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, useAsync: true);
await stream.WriteAsync(bytes, ct).ConfigureAwait(false);
await stream.FlushAsync(ct).ConfigureAwait(false);
stream.Flush(flushToDisk: true);
}
private static string SafeName(string value)
{
var invalid = Path.GetInvalidFileNameChars();
var chars = value.Select(c => invalid.Contains(c) || c == ' ' ? '_' : c).ToArray();
return new string(chars);
}
}
@@ -1,16 +0,0 @@
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
/// <summary>An off-box destination for exported chain heads (ScadaBridge#107 item 1).</summary>
public interface IAuditChainHeadSink
{
/// <summary>Short description for logs (e.g. the directory or <c>host:port/udp</c>).</summary>
string Describe { get; }
/// <summary>Writes the records; throws when they could not all be delivered.</summary>
/// <param name="records">The records, oldest month first.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that completes when the records are durably handed off.</returns>
Task WriteAsync(IReadOnlyList<AuditChainHeadRecord> records, CancellationToken ct);
}
@@ -1,108 +0,0 @@
using System.Globalization;
using System.Net.Sockets;
using System.Text;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central.HeadExport;
/// <summary>
/// Sends exported heads as RFC 5424 syslog messages — one message per head, the JSON record as
/// MSG — over UDP (RFC 5426, one datagram each) or TCP (RFC 6587 octet-counting framing, one
/// connection per export).
/// </summary>
/// <remarks>
/// Message: <c>&lt;PRI&gt;1 TIMESTAMP HOSTNAME APP-NAME PROCID chainhead - {json}</c>, severity
/// Notice (5), PRI = facility × 8 + 5. No structured data (a private enterprise number would be
/// needed); the collector keeps the JSON body, which <c>audit verify-heads</c> reads back from
/// any line that contains it. UDP is fire-and-forget — use TCP where a lost datagram matters.
/// </remarks>
public sealed class SyslogAuditChainHeadSink : IAuditChainHeadSink
{
/// <summary>MSGID of every head message.</summary>
public const string MessageId = "chainhead";
private const int SeverityNotice = 5;
private readonly AuditChainHeadSyslogSinkOptions _options;
private readonly string _hostName;
private readonly TimeProvider _time;
/// <summary>Creates the sink.</summary>
/// <param name="options">Syslog settings.</param>
/// <param name="hostName">HOSTNAME field (defaults to the machine name).</param>
/// <param name="time">Clock for TIMESTAMP.</param>
public SyslogAuditChainHeadSink(AuditChainHeadSyslogSinkOptions options, string? hostName = null, TimeProvider? time = null)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
ArgumentException.ThrowIfNullOrWhiteSpace(options.Host);
_hostName = Token(hostName ?? Environment.MachineName, 255);
_time = time ?? TimeProvider.System;
}
/// <inheritdoc />
public string Describe => $"{_options.Host}:{_options.Port}/{_options.Protocol.ToString().ToLowerInvariant()}";
/// <summary>Formats one RFC 5424 message (no framing).</summary>
/// <param name="record">The record.</param>
/// <returns>The message text.</returns>
public string Format(AuditChainHeadRecord record)
{
var pri = (_options.Facility * 8) + SeverityNotice;
var timestamp = _time.GetUtcNow().UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
return string.Create(CultureInfo.InvariantCulture,
$"<{pri}>1 {timestamp} {_hostName} {Token(_options.AppName, 48)} {Environment.ProcessId} {MessageId} - {AuditChainHeadJson.Serialize(record)}");
}
/// <inheritdoc />
public async Task WriteAsync(IReadOnlyList<AuditChainHeadRecord> records, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(records);
if (records.Count == 0)
{
return;
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(Math.Max(1, _options.TimeoutSeconds)));
var token = timeout.Token;
if (_options.Protocol == AuditSyslogProtocol.Udp)
{
using var udp = new UdpClient();
udp.Connect(_options.Host!, _options.Port);
foreach (var record in records)
{
var bytes = Encoding.UTF8.GetBytes(Format(record));
await udp.SendAsync(bytes, token).ConfigureAwait(false);
}
return;
}
using var tcp = new TcpClient();
await tcp.ConnectAsync(_options.Host!, _options.Port, token).ConfigureAwait(false);
var stream = tcp.GetStream();
foreach (var record in records)
{
var message = Encoding.UTF8.GetBytes(Format(record));
var frame = Encoding.ASCII.GetBytes(message.Length.ToString(CultureInfo.InvariantCulture) + " ");
await stream.WriteAsync(frame, token).ConfigureAwait(false);
await stream.WriteAsync(message, token).ConfigureAwait(false);
}
await stream.FlushAsync(token).ConfigureAwait(false);
tcp.Client.Shutdown(SocketShutdown.Send);
}
// RFC 5424 header fields are PRINTUSASCII (33-126), no spaces; "-" when empty.
private static string Token(string? value, int max)
{
if (string.IsNullOrEmpty(value))
{
return "-";
}
var chars = value.Where(c => c is >= '!' and <= '~').Take(max).ToArray();
return chars.Length == 0 ? "-" : new string(chars);
}
}
@@ -0,0 +1,73 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central;
/// <summary>
/// Logs one warning at central startup for each AuditLog setting that no longer does anything.
/// </summary>
/// <remarks>
/// The hash chain (<c>AuditLog:HashChain</c>, including its head export) and the two-login
/// maintenance hardening (<c>AuditLog:MaintenanceConnectionString</c>) were removed on
/// 2026-11-15 at IT security's request. Nothing validates unknown keys, so a node still carrying
/// them (for example <c>AuditLog__HashChain__Enabled=true</c> in its service environment) boots
/// normally; this warning tells the operator the keys can be deleted.
/// </remarks>
public sealed class RetiredAuditSettingsWarning : IHostedService
{
/// <summary>The retired hash-chain section.</summary>
public const string HashChainSection = "AuditLog:HashChain";
/// <summary>The retired maintenance-login connection string.</summary>
public const string MaintenanceConnectionStringKey = "AuditLog:MaintenanceConnectionString";
private readonly IConfiguration _configuration;
private readonly ILogger<RetiredAuditSettingsWarning> _logger;
/// <summary>Initializes a new instance of the <see cref="RetiredAuditSettingsWarning"/> class.</summary>
/// <param name="configuration">Application configuration.</param>
/// <param name="logger">Logger.</param>
public RetiredAuditSettingsWarning(IConfiguration configuration, ILogger<RetiredAuditSettingsWarning> logger)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <summary>The retired keys present in <paramref name="configuration"/>.</summary>
/// <param name="configuration">The configuration to inspect.</param>
/// <returns>Each retired key or section that is set.</returns>
public static IReadOnlyList<string> FindRetired(IConfiguration configuration)
{
ArgumentNullException.ThrowIfNull(configuration);
var found = new List<string>();
if (configuration.GetSection(HashChainSection).Exists())
{
found.Add(HashChainSection);
}
if (!string.IsNullOrWhiteSpace(configuration[MaintenanceConnectionStringKey]))
{
found.Add(MaintenanceConnectionStringKey);
}
return found;
}
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
foreach (var key in FindRetired(_configuration))
{
_logger.LogWarning(
"{Setting} is no longer supported and is ignored: the AuditLog hash chain and the two-login "
+ "maintenance hardening were removed on 2026-11-15. Delete the setting.",
key);
}
return Task.CompletedTask;
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
@@ -52,15 +52,6 @@ public static class ServiceCollectionExtensions
/// <summary>Configuration section bound to <see cref="AuditLogPartitionMaintenanceOptions"/>.</summary>
public const string PartitionMaintenanceSectionName = "AuditLog:PartitionMaintenance";
/// <summary>
/// Optional connection string for the AuditLog maintenance paths — the hash-chain job and both
/// purge paths (ScadaBridge#107 item 3). Unset: they run on <c>ScadaBridge:Database:ConfigurationDb</c>.
/// </summary>
public const string MaintenanceConnectionStringKey = "AuditLog:MaintenanceConnectionString";
/// <summary>Configuration section bound to <see cref="AuditLogHashChainOptions"/> (ScadaBridge#41).</summary>
public const string HashChainSectionName = "AuditLog:HashChain";
/// <summary>
/// Configuration section bound to
/// <see cref="ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance.AuditLogArchiveOptions"/> (ScadaBridge#42).
@@ -410,34 +401,9 @@ public static class ServiceCollectionExtensions
AuditLogPartitionMaintenanceOptionsValidator>(config, PartitionMaintenanceSectionName);
services.AddHostedService<AuditLogPartitionMaintenanceService>();
// Hash-chain tamper evidence (ScadaBridge#41). Default OFF; the hosted service is
// always registered and returns from StartAsync without a loop when disabled.
// IAuditLogHashChain is registered by AddConfigurationDatabase (central only).
services.AddValidatedOptions<AuditLogHashChainOptions, AuditLogHashChainOptionsValidator>(
config, HashChainSectionName);
services.AddHostedService<AuditLogHashChainService>();
// Off-box chain-head export (ScadaBridge#107 item 1, AuditLog:HashChain:HeadExport,
// default off). The sink is built from the bound options; null when disabled.
services.AddSingleton<Central.HeadExport.AuditChainHeadExportStatus>();
services.AddHostedService(sp =>
{
var options = sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<AuditLogHashChainOptions>>();
var node = sp.GetService<INodeIdentityProvider>()?.NodeName;
var export = options.Value.HeadExport;
Central.HeadExport.IAuditChainHeadSink? sink = !export.Enabled ? null : export.Sink switch
{
Central.HeadExport.AuditChainHeadSinkKind.Syslog => new Central.HeadExport.SyslogAuditChainHeadSink(export.Syslog),
_ => new Central.HeadExport.FileAuditChainHeadSink(export.File.Directory!, node ?? Environment.MachineName),
};
return new Central.HeadExport.AuditChainHeadExportService(
sp.GetRequiredService<IServiceScopeFactory>(),
options,
sink,
node,
sp.GetRequiredService<ILogger<Central.HeadExport.AuditChainHeadExportService>>(),
status: sp.GetRequiredService<Central.HeadExport.AuditChainHeadExportStatus>());
});
// The hash chain and the two-login maintenance hardening were removed on 2026-11-15;
// a node still carrying their settings boots normally and is told to delete them.
services.AddHostedService<RetiredAuditSettingsWarning>();
// Parquet cold archive (ScadaBridge#42). Default OFF; when enabled the purge actor
// archives each expired partition before switching it out. IAuditLogArchive is