feat(cli): working audit verify-chain via the VerifyAuditChain management command (ScadaBridge#41)
verify-chain was a no-op stub that printed "not enabled" and exited 0 without contacting the server. It now sends VerifyAuditChain(Month) over POST /management and maps the verdict to the exit code: 0 intact or not chained, 3 broken (first break: partition, ChainSeq, EventId, kind), 1 error, 2 unauthorized. Table and JSON renderings. ManagementActor: new HandleVerifyAuditChain arm, gated on the OperationalAudit roles (Administrator, Viewer) and refusing a site-scoped caller because a month's chain spans every site; INVALID_ARGUMENT for a bad month, CHAIN_BUSY when the chain lock is held; long-running Ask timeout. Result enums serialise as names. Parity: RequiredRoleMatrixTests freezes the gate; ManagementSurfaceParityTests now probes `audit verify-chain` (the one audit leaf that is a management contract) instead of skipping the whole audit group. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
@@ -1,29 +1,95 @@
|
||||
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.
|
||||
/// v1 is a no-op stub: a valid <c>--month</c> prints the documented "not enabled"
|
||||
/// message and exits 0; a malformed month or a missing <c>--month</c> exits non-zero.
|
||||
/// 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
|
||||
{
|
||||
/// <summary>Verifies that verifying the chain for a valid month exits with zero and prints the documented message.</summary>
|
||||
[Fact]
|
||||
public void VerifyChain_ValidMonth_ExitsZeroWithDocumentedMessage()
|
||||
{
|
||||
var root = AuditCommandTestHarness.BuildRoot();
|
||||
var (exit, output, _) = AuditCommandTestHarness.Invoke(
|
||||
root, "audit", "verify-chain", "--month", "2026-05");
|
||||
private const string IntactBody =
|
||||
"{\"partition\":\"2026-05\",\"status\":\"Intact\",\"rowsVerified\":42,\"tombstonesApplied\":1,\"headSeq\":43,\"unchainedRows\":0}";
|
||||
|
||||
Assert.Equal(0, exit);
|
||||
Assert.Contains("Hash-chain tamper-evidence is not enabled", output);
|
||||
Assert.Contains("Component-AuditLog.md", output);
|
||||
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 makes the command exit with a non-zero code.</summary>
|
||||
/// <summary>Verifies that a malformed month value exits non-zero without contacting the server.</summary>
|
||||
[Fact]
|
||||
public void VerifyChain_MalformedMonth_ExitsNonZero()
|
||||
{
|
||||
|
||||
@@ -93,7 +93,10 @@ public class ManagementSurfaceParityTests
|
||||
foreach (var (leaf, path) in Leaves(root, []))
|
||||
{
|
||||
// Separate REST and persistent SignalR surfaces, not management contracts.
|
||||
if (path.Length == 0 || path[0] == "audit" || path[0] == omitGroup
|
||||
// `audit verify-chain` is the one audit leaf that IS a management contract
|
||||
// (VerifyAuditChain, ScadaBridge#41), so it stays in the probe.
|
||||
if (path.Length == 0 || (path[0] == "audit" && string.Join(' ', path) != "audit verify-chain")
|
||||
|| path[0] == omitGroup
|
||||
|| string.Join(' ', path) == "debug stream") continue;
|
||||
currentPath = string.Join(' ', path);
|
||||
var args = new List<string>(path);
|
||||
@@ -155,6 +158,7 @@ public class ManagementSurfaceParityTests
|
||||
"--from-address" => "sender@example.test",
|
||||
"--thumbprint" => new string('A', 40),
|
||||
"--role" => "Designer",
|
||||
"--month" => "2026-05",
|
||||
"--code" or "--script" => "return null;",
|
||||
_ => "fixture"
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user