ed2ed0a367
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
184 lines
8.3 KiB
C#
184 lines
8.3 KiB
C#
using System.Text.Json;
|
|
using Akka.Actor;
|
|
using Akka.TestKit.Xunit2;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using NSubstitute;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
|
|
|
|
/// <summary>
|
|
/// The <c>ListAuditArchives</c> / <c>VerifyAuditArchive</c> management commands
|
|
/// (ScadaBridge#42): role gate, site-scope refusal, an unconfigured archive directory, bad
|
|
/// names, and the results reaching the wire with enums as names.
|
|
/// </summary>
|
|
public class AuditArchiveCommandTests : TestKit
|
|
{
|
|
private const string Name = "auditlog-2025-10-20261109T120000123Z";
|
|
|
|
private readonly IAuditLogArchive _archive = Substitute.For<IAuditLogArchive>();
|
|
|
|
/// <summary>Configures the archive substitute as a configured, enabled archive.</summary>
|
|
public AuditArchiveCommandTests()
|
|
{
|
|
_archive.IsConfigured.Returns(true);
|
|
_archive.IsEnabled.Returns(true);
|
|
}
|
|
|
|
private IActorRef CreateActor(bool registerArchive = true)
|
|
{
|
|
var services = new ServiceCollection().AddTestConfigurationTransaction();
|
|
if (registerArchive)
|
|
{
|
|
services.AddScoped(_ => _archive);
|
|
}
|
|
|
|
return Sys.ActorOf(Props.Create(() => new ManagementActor(
|
|
services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
|
|
}
|
|
|
|
private static ManagementEnvelope Envelope(object command, string[] sites, params string[] roles) =>
|
|
new(new AuthenticatedUser("u", "U", roles, sites), command, Guid.NewGuid().ToString("N"));
|
|
|
|
private static AuditArchiveManifest Manifest() => new(
|
|
2, Name, new DateTime(2025, 10, 1, 0, 0, 0, DateTimeKind.Utc), "2025-10",
|
|
new DateTime(2026, 11, 9, 12, 0, 0, DateTimeKind.Utc), AuditArchiveStatus.Purged,
|
|
new DateTime(2026, 11, 9, 12, 0, 1, DateTimeKind.Utc), 10, null, null,
|
|
Name + ".parquet", "ab", 1234);
|
|
|
|
/// <summary>A Viewer lists the archives; status renders as a name.</summary>
|
|
[Fact]
|
|
public void Viewer_ListsArchives()
|
|
{
|
|
_archive.ListAsync(Arg.Any<CancellationToken>()).Returns([Manifest()]);
|
|
|
|
CreateActor().Tell(Envelope(new ListAuditArchivesCommand(), [], "Viewer"));
|
|
|
|
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
|
using var json = JsonDocument.Parse(response.JsonData);
|
|
Assert.True(json.RootElement.GetProperty("enabled").GetBoolean());
|
|
var archive = json.RootElement.GetProperty("archives")[0];
|
|
Assert.Equal(Name, archive.GetProperty("name").GetString());
|
|
Assert.Equal("Purged", archive.GetProperty("status").GetString());
|
|
}
|
|
|
|
/// <summary>Verification results reach the wire, status as a name.</summary>
|
|
[Fact]
|
|
public void Viewer_GetsVerificationResult()
|
|
{
|
|
_archive.VerifyAsync(Name, Arg.Any<CancellationToken>()).Returns(new AuditArchiveVerificationResult(
|
|
Name, "2025-10", AuditArchiveStatus.Purged, true, true, null, 10));
|
|
|
|
CreateActor().Tell(Envelope(new VerifyAuditArchiveCommand(Name), [], "Viewer"));
|
|
|
|
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
|
using var json = JsonDocument.Parse(response.JsonData);
|
|
Assert.True(json.RootElement.GetProperty("verified").GetBoolean());
|
|
Assert.Equal("Purged", json.RootElement.GetProperty("manifestStatus").GetString());
|
|
Assert.Equal(10, json.RootElement.GetProperty("rowsRead").GetInt64());
|
|
Assert.False(json.RootElement.TryGetProperty("chains", out _));
|
|
}
|
|
|
|
/// <summary>Designer/Deployer without an OperationalAudit role are refused both commands.</summary>
|
|
[Fact]
|
|
public void NonAuditRole_IsUnauthorized()
|
|
{
|
|
var actor = CreateActor();
|
|
actor.Tell(Envelope(new ListAuditArchivesCommand(), [], "Designer", "Deployer"));
|
|
ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
|
|
actor.Tell(Envelope(new VerifyAuditArchiveCommand(Name), [], "Designer", "Deployer"));
|
|
ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
|
|
_archive.DidNotReceiveWithAnyArgs().ListAsync(default);
|
|
_archive.DidNotReceiveWithAnyArgs().VerifyAsync(default!, default);
|
|
}
|
|
|
|
/// <summary>A site-scoped Viewer is refused: an archive holds every site's rows.</summary>
|
|
[Fact]
|
|
public void SiteScopedViewer_IsRefused()
|
|
{
|
|
CreateActor().Tell(Envelope(new VerifyAuditArchiveCommand(Name), ["3"], "Viewer"));
|
|
|
|
var response = ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
|
|
Assert.Contains("every site", response.Message);
|
|
_archive.DidNotReceiveWithAnyArgs().VerifyAsync(default!, default);
|
|
}
|
|
|
|
/// <summary>No archive directory configured is an explicit error code, not an empty list.</summary>
|
|
[Fact]
|
|
public void UnconfiguredArchive_IsArchiveNotConfigured()
|
|
{
|
|
_archive.IsConfigured.Returns(false);
|
|
|
|
CreateActor().Tell(Envelope(new ListAuditArchivesCommand(), [], "Administrator"));
|
|
|
|
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
|
|
Assert.Equal("ARCHIVE_NOT_CONFIGURED", response.ErrorCode);
|
|
}
|
|
|
|
/// <summary>A malformed name is INVALID_ARGUMENT; an unknown one is NOT_FOUND.</summary>
|
|
[Fact]
|
|
public void BadNames_MapToCallerErrors()
|
|
{
|
|
_archive.VerifyAsync("../etc", Arg.Any<CancellationToken>())
|
|
.Returns<Task<AuditArchiveVerificationResult>>(_ => throw new ArgumentException("not an archive name"));
|
|
_archive.VerifyAsync(Name, Arg.Any<CancellationToken>())
|
|
.Returns<Task<AuditArchiveVerificationResult>>(_ => throw new FileNotFoundException("no archive"));
|
|
|
|
var actor = CreateActor();
|
|
actor.Tell(Envelope(new VerifyAuditArchiveCommand("../etc"), [], "Administrator"));
|
|
Assert.Equal("INVALID_ARGUMENT", ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5)).ErrorCode);
|
|
actor.Tell(Envelope(new VerifyAuditArchiveCommand(Name), [], "Administrator"));
|
|
Assert.Equal("NOT_FOUND", ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5)).ErrorCode);
|
|
}
|
|
|
|
/// <summary>Archive verification runs under the long-running Ask timeout.</summary>
|
|
[Fact]
|
|
public void VerifyAuditArchive_UsesLongRunningAskTimeout()
|
|
{
|
|
Assert.Equal(TimeSpan.FromMinutes(5),
|
|
ManagementEndpoints.ResolveAskTimeout(new ManagementServiceOptions(), typeof(VerifyAuditArchiveCommand)));
|
|
}
|
|
|
|
/// <summary>ScadaBridge#109: an Administrator runs the cleanup; the dry-run flag reaches the archive.</summary>
|
|
/// <param name="dryRun">The flag.</param>
|
|
[Theory]
|
|
[InlineData(true)]
|
|
[InlineData(false)]
|
|
public void Administrator_RunsCleanup_WithTheDryRunFlag(bool dryRun)
|
|
{
|
|
_archive.CleanupAsync(dryRun, Arg.Any<CancellationToken>()).Returns(new AuditArchiveCleanupResult(dryRun, 0,
|
|
[new AuditArchiveCleanupItem(Name, "2025-10", AuditArchiveCleanupAction.DeletedSuperseded, "superseded")]));
|
|
|
|
CreateActor().Tell(Envelope(new CleanupAuditArchivesCommand(dryRun), [], "Administrator"));
|
|
|
|
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
|
using var json = JsonDocument.Parse(response.JsonData);
|
|
Assert.Equal(dryRun, json.RootElement.GetProperty("dryRun").GetBoolean());
|
|
Assert.Equal("DeletedSuperseded", json.RootElement.GetProperty("items")[0].GetProperty("action").GetString());
|
|
_archive.Received(1).CleanupAsync(dryRun, Arg.Any<CancellationToken>());
|
|
}
|
|
|
|
/// <summary>Cleanup deletes files: a Viewer (audit reader) is refused.</summary>
|
|
[Fact]
|
|
public void Viewer_CannotRunCleanup()
|
|
{
|
|
CreateActor().Tell(Envelope(new CleanupAuditArchivesCommand(true), [], "Viewer"));
|
|
|
|
ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
|
|
_archive.DidNotReceiveWithAnyArgs().CleanupAsync(default, default);
|
|
}
|
|
|
|
/// <summary>No archive directory configured: ARCHIVE_NOT_CONFIGURED, as for list/verify.</summary>
|
|
[Fact]
|
|
public void Cleanup_WithoutAnArchiveDirectory_IsNotConfigured()
|
|
{
|
|
_archive.IsConfigured.Returns(false);
|
|
CreateActor().Tell(Envelope(new CleanupAuditArchivesCommand(true), [], "Administrator"));
|
|
|
|
Assert.Equal("ARCHIVE_NOT_CONFIGURED", ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5)).ErrorCode);
|
|
}
|
|
}
|