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:
@@ -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";
|
||||
|
||||
Reference in New Issue
Block a user