5ca998dc56
IAuditService.LogAsync only stages the row; every caller that audited after its last SaveChangesAsync, outside the configuration-command transaction, lost the row with the DI scope (rig: zero Disable/Enable/ Delete/DeployArtifacts rows, 16 Deploy rows for 62 deployments, one Create/Instance row for ids up to 3876). - New IAuditService.LogAndSaveAsync: stage + save, best-effort (logs and swallows any failure incl. cancellation, detaches the unsaved row). - DeploymentService (deploy/failed/reconciled/lifecycle + timeouts), ArtifactDeploymentService (DeployArtifacts now before the best-effort stamp, RetryArtifactDeployment, DeploySiteSecrets), InstanceService, AreaService, SiteService: post-save LogAsync -> LogAndSaveAsync. - ManagementActor: AuditAndSaveAsync for the non-configuration handlers (API keys, shared schemas, ES methods, data-connection move); move now audits the scrubbed public shape (MGT-4) so the fix does not start writing protocol credentials into AuditLogEntries. - HandleCreateInstance no longer stages a second Create row on top of InstanceService's own. Tests: real-context (SQLite) tests per family read the row back through a second context - DeploymentService, ArtifactDeploymentService, InstanceService, ManagementActor; each fails against the old code. Test projects gain a ConfigurationDatabase + EF Sqlite reference.
133 lines
6.2 KiB
C#
133 lines
6.2 KiB
C#
using Akka.Actor;
|
|
using Akka.TestKit.Xunit2;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using NSubstitute;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Schemas;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Security;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
|
using ZB.MOM.WW.ScadaBridge.ManagementService;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
|
|
|
|
/// <summary>
|
|
/// Code review 2026-12-02 MGT-1: the API-key, shared-schema, external-system-method and
|
|
/// data-connection-move commands are not configuration commands, so they run without the
|
|
/// transaction wrapper's trailing save — and each staged its audit row AFTER its own save.
|
|
/// The row was discarded with the scope; the mocked tests only proved the call was made.
|
|
/// These drive the real <see cref="ManagementActor"/> against a REAL audit service over
|
|
/// SQLite (repositories stay mocks and never touch that context) and read the row back
|
|
/// through a second context, one test per family.
|
|
/// </summary>
|
|
public class ManagementAuditDurabilityTests : TestKit, IDisposable
|
|
{
|
|
private readonly RealAuditDatabase _db = new();
|
|
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
|
|
|
|
/// <summary>Registers the real audit service.</summary>
|
|
public ManagementAuditDurabilityTests()
|
|
{
|
|
_services.AddScoped<IAuditService>(_ => _db.AuditService);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
void IDisposable.Dispose()
|
|
{
|
|
Shutdown();
|
|
_db.Dispose();
|
|
}
|
|
|
|
private void Run(object command, params string[] roles)
|
|
{
|
|
var actor = Sys.ActorOf(Props.Create(() => new ManagementActor(
|
|
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
|
|
actor.Tell(new ManagementEnvelope(
|
|
new AuthenticatedUser("auditor", "Auditor", roles, Array.Empty<string>()),
|
|
command, Guid.NewGuid().ToString("N")));
|
|
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
|
}
|
|
|
|
/// <summary>API-key family: <c>security api-key delete</c> leaves a persisted row.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task DeleteApiKey_AuditRowIsPersisted()
|
|
{
|
|
var admin = Substitute.For<IInboundApiKeyAdmin>();
|
|
admin.DeleteAsync("k1", Arg.Any<CancellationToken>()).Returns(true);
|
|
_services.AddScoped(_ => admin);
|
|
|
|
Run(new DeleteApiKeyCommand("k1"), "Administrator");
|
|
|
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
|
Assert.Equal(("Delete", "ApiKey", "k1", "auditor"), (row.Action, row.EntityType, row.EntityId, row.User));
|
|
}
|
|
|
|
/// <summary>Shared-schema family: delete leaves a persisted row.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task DeleteSharedSchema_AuditRowIsPersisted()
|
|
{
|
|
var repo = Substitute.For<ISharedSchemaRepository>();
|
|
repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(new SharedSchema { Id = 5, Name = "Addr", SchemaJson = "{}" });
|
|
_services.AddScoped(_ => repo);
|
|
|
|
Run(new DeleteSharedSchemaCommand(5), "Designer");
|
|
|
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
|
Assert.Equal(("Delete", "SharedSchema", "Addr"), (row.Action, row.EntityType, row.EntityName));
|
|
}
|
|
|
|
/// <summary>External-system-method family: delete leaves a persisted row.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task DeleteExternalSystemMethod_AuditRowIsPersisted()
|
|
{
|
|
var repo = Substitute.For<IExternalSystemRepository>();
|
|
repo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
|
|
_services.AddScoped(_ => repo);
|
|
|
|
Run(new DeleteExternalSystemMethodCommand(9), "Designer");
|
|
|
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
|
Assert.Equal(("Delete", "ExternalSystemMethod", "9"), (row.Action, row.EntityType, row.EntityId));
|
|
}
|
|
|
|
/// <summary>
|
|
/// <c>data-connection move</c> leaves a persisted row whose after-state is the SCRUBBED
|
|
/// public shape (MGT-4): the raw entity carried the protocol configuration's credentials.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task MoveDataConnection_AuditRowIsPersisted_WithoutTheSecret()
|
|
{
|
|
var conn = new DataConnection("Opc1", "OpcUa", 1)
|
|
{
|
|
Id = 5,
|
|
PrimaryConfiguration = """{"endpointUrl":"opc.tcp://plc:4840","password":"hunter2-primary"}""",
|
|
BackupConfiguration = """{"endpointUrl":"opc.tcp://plc2:4840","password":"hunter2-backup"}""",
|
|
};
|
|
var siteRepo = Substitute.For<ISiteRepository>();
|
|
siteRepo.GetDataConnectionByIdAsync(5, Arg.Any<CancellationToken>()).Returns(conn);
|
|
siteRepo.GetSiteByIdAsync(2, Arg.Any<CancellationToken>()).Returns(new Site("Target", "SITE-B") { Id = 2 });
|
|
siteRepo.GetDataConnectionsBySiteIdAsync(2, Arg.Any<CancellationToken>()).Returns(new List<DataConnection>());
|
|
siteRepo.GetInstancesReferencingDataConnectionAsync(5, Arg.Any<CancellationToken>()).Returns(new List<Instance>());
|
|
siteRepo.GetInstancesWithNativeAlarmOverridesBySiteIdAsync(1, Arg.Any<CancellationToken>()).Returns(new List<Instance>());
|
|
siteRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
|
|
_services.AddScoped(_ => siteRepo);
|
|
_services.AddScoped(_ => Substitute.For<ITemplateEngineRepository>());
|
|
|
|
Run(new MoveDataConnectionCommand(5, 2), "Designer");
|
|
|
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
|
Assert.Equal(("Move", "DataConnection", "5"), (row.Action, row.EntityType, row.EntityId));
|
|
Assert.NotNull(row.AfterStateJson);
|
|
Assert.DoesNotContain("hunter2", row.AfterStateJson);
|
|
Assert.Contains(ConfigSecretScrubber.Sentinel, row.AfterStateJson);
|
|
}
|
|
}
|