52da02a76a
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
162 lines
7.4 KiB
C#
162 lines
7.4 KiB
C#
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));
|
|
}
|
|
}
|