Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditArchiveHelpers.cs
T
Joseph Doherty ed2ed0a367 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
2026-11-15 17:38:22 -05:00

141 lines
6.2 KiB
C#

using System.Globalization;
using System.Text.Json;
namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;
/// <summary>
/// Helpers for the <c>audit archive list</c> / <c>audit archive verify</c> subcommands
/// (AuditLog Parquet cold archive, ScadaBridge#42). Both send a management command
/// (<c>ListAuditArchives</c>, <c>VerifyAuditArchive</c>); the archives live on the central
/// nodes' archive directory, not on the operator's machine.
/// </summary>
/// <remarks>
/// <c>verify</c> exit codes: <c>0</c> verified, <see cref="NotVerifiedExitCode"/> when the
/// data file disagrees with its manifest, <c>1</c> on a request error, <c>2</c> on an
/// authorization failure.
/// </remarks>
public static class AuditArchiveHelpers
{
/// <summary>Process exit code when an archive failed verification.</summary>
public const int NotVerifiedExitCode = 3;
/// <summary>
/// Client deadline for <c>verify</c>: the server hashes and reads a whole month under
/// the long-running management Ask (5 min); the client waits a little longer.
/// </summary>
public static readonly TimeSpan VerifyRequestTimeout = TimeSpan.FromMinutes(6);
/// <summary>Renders a <c>ListAuditArchives</c> result.</summary>
/// <param name="json">The success body (an <c>AuditArchiveListResult</c>, camelCase).</param>
/// <param name="format">Resolved output format.</param>
/// <param name="output">Writer for the report.</param>
/// <returns>Always <c>0</c>.</returns>
public static int RenderList(string json, string format, TextWriter output)
{
if (!string.Equals(format, "table", StringComparison.OrdinalIgnoreCase))
{
output.WriteLine(json);
output.Flush();
return 0;
}
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var enabled = root.TryGetProperty("enabled", out var e) && e.ValueKind == JsonValueKind.True;
output.WriteLine($"Archiving: {(enabled ? "enabled" : "disabled")}");
if (!root.TryGetProperty("archives", out var archives) || archives.GetArrayLength() == 0)
{
output.WriteLine("No archives.");
output.Flush();
return 0;
}
output.WriteLine($"{"NAME",-42} {"PARTITION",-9} {"STATUS",-8} {"ROWS",12} {"BYTES",14}");
foreach (var a in archives.EnumerateArray())
{
output.WriteLine(string.Create(CultureInfo.InvariantCulture,
$"{Str(a, "name"),-42} {Str(a, "partition"),-9} {Str(a, "status"),-8} {Num(a, "rowCount"),12} {Num(a, "dataBytes"),14}"));
}
output.Flush();
return 0;
}
/// <summary>Renders a <c>VerifyAuditArchive</c> result and maps it to the exit code.</summary>
/// <param name="json">The success body (an <c>AuditArchiveVerificationResult</c>, camelCase).</param>
/// <param name="format">Resolved output format.</param>
/// <param name="output">Writer for the report.</param>
/// <returns><c>0</c> when verified, <see cref="NotVerifiedExitCode"/> otherwise.</returns>
public static int RenderVerify(string json, string format, TextWriter output)
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var verified = root.TryGetProperty("verified", out var v) && v.ValueKind == JsonValueKind.True;
if (!string.Equals(format, "table", StringComparison.OrdinalIgnoreCase))
{
output.WriteLine(json);
output.Flush();
return verified ? 0 : NotVerifiedExitCode;
}
output.WriteLine($"Archive : {Str(root, "name")}");
output.WriteLine($"Partition : {Str(root, "partition")}");
output.WriteLine($"Manifest : {Str(root, "manifestStatus")}");
output.WriteLine($"Verified : {(verified ? "yes" : "NO")}");
output.WriteLine($"Files intact: {(root.TryGetProperty("filesIntact", out var f) && f.ValueKind == JsonValueKind.True ? "yes" : "NO")}");
if (Str(root, "fileProblem") is { Length: > 0 } problem)
{
output.WriteLine($" problem : {problem}");
}
output.WriteLine($"Rows read : {Num(root, "rowsRead")}");
output.Flush();
return verified ? 0 : NotVerifiedExitCode;
}
/// <summary>
/// Renders a <c>CleanupAuditArchives</c> result (ScadaBridge#109). Always exit 0 — kept
/// stale archives are reported, not an error.
/// </summary>
/// <param name="json">The success body (an <c>AuditArchiveCleanupResult</c>, camelCase).</param>
/// <param name="format">Resolved output format.</param>
/// <param name="output">Writer for the report.</param>
/// <returns><c>0</c>.</returns>
public static int RenderCleanup(string json, string format, TextWriter output)
{
if (!string.Equals(format, "table", StringComparison.OrdinalIgnoreCase))
{
output.WriteLine(json);
output.Flush();
return 0;
}
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var dryRun = root.TryGetProperty("dryRun", out var d) && d.ValueKind == JsonValueKind.True;
var retention = Num(root, "retentionDays");
output.WriteLine($"{(dryRun ? "Dry run — nothing deleted. " : "")}Archive retention: {(retention == "0" ? "never delete" : retention + " days")}");
var items = root.TryGetProperty("items", out var i) && i.ValueKind == JsonValueKind.Array ? i.EnumerateArray().ToList() : [];
if (items.Count == 0)
{
output.WriteLine("Nothing to clean up.");
}
foreach (var item in items)
{
output.WriteLine($"{Str(item, "action"),-18} {Str(item, "name")} {Str(item, "detail")}");
}
output.Flush();
return 0;
}
private static string Str(JsonElement e, string name, string missing = "")
=> e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? missing : missing;
private static string Num(JsonElement e, string name, string missing = "0")
=> e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number ? v.GetInt64().ToString(CultureInfo.InvariantCulture) : missing;
}