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; /// /// 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 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. /// public class ManagementAuditDurabilityTests : TestKit, IDisposable { private readonly RealAuditDatabase _db = new(); private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction(); /// Registers the real audit service. public ManagementAuditDurabilityTests() { _services.AddScoped(_ => _db.AuditService); } /// 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.Instance))); actor.Tell(new ManagementEnvelope( new AuthenticatedUser("auditor", "Auditor", roles, Array.Empty()), command, Guid.NewGuid().ToString("N"))); ExpectMsg(TimeSpan.FromSeconds(5)); } /// API-key family: security api-key delete leaves a persisted row. /// A task that represents the asynchronous operation. [Fact] public async Task DeleteApiKey_AuditRowIsPersisted() { var admin = Substitute.For(); admin.DeleteAsync("k1", Arg.Any()).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)); } /// Shared-schema family: delete leaves a persisted row. /// A task that represents the asynchronous operation. [Fact] public async Task DeleteSharedSchema_AuditRowIsPersisted() { var repo = Substitute.For(); repo.GetByIdAsync(5, Arg.Any()).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)); } /// External-system-method family: delete leaves a persisted row. /// A task that represents the asynchronous operation. [Fact] public async Task DeleteExternalSystemMethod_AuditRowIsPersisted() { var repo = Substitute.For(); repo.SaveChangesAsync(Arg.Any()).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)); } /// /// data-connection move leaves a persisted row whose after-state is the SCRUBBED /// public shape (MGT-4): the raw entity carried the protocol configuration's credentials. /// /// A task that represents the asynchronous operation. [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(); siteRepo.GetDataConnectionByIdAsync(5, Arg.Any()).Returns(conn); siteRepo.GetSiteByIdAsync(2, Arg.Any()).Returns(new Site("Target", "SITE-B") { Id = 2 }); siteRepo.GetDataConnectionsBySiteIdAsync(2, Arg.Any()).Returns(new List()); siteRepo.GetInstancesReferencingDataConnectionAsync(5, Arg.Any()).Returns(new List()); siteRepo.GetInstancesWithNativeAlarmOverridesBySiteIdAsync(1, Arg.Any()).Returns(new List()); siteRepo.SaveChangesAsync(Arg.Any()).Returns(1); _services.AddScoped(_ => siteRepo); _services.AddScoped(_ => Substitute.For()); 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); } }