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;
///
/// Tests for scadabridge audit verify-heads (ScadaBridge#107 item 1): reading off-box
/// exported chain heads (file-sink lines and syslog-collector lines), collapsing duplicates,
/// sending VerifyAuditChainHeads, and mapping the verdict to the exit code.
///
[Collection("Console")]
public sealed class AuditVerifyHeadsCommandTests : IDisposable
{
private readonly DirectoryInfo _dir = Directory.CreateTempSubdirectory("verify-heads-");
///
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 + "\"}";
///
/// 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.
///
[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);
}
/// A record missing its hash or sequence is not a record.
/// The line.
[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));
}
///
/// Round trip: the request carries VerifyAuditChainHeads with the distinct records,
/// and the verdict drives the exit code (0 verified, 3 not).
///
/// Whether the fake server reports verified.
/// Output format.
/// Expected exit code.
/// Text the report must contain.
/// A task that represents the asynchronous operation.
[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();
}
}
/// No records found is an input error, and nothing is sent.
[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);
}
}