fix(audit): persist config audit rows written after the final save (DEP-1, MGT-1, TPL-3, WP1 task 1.4)

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.
This commit is contained in:
Joseph Doherty
2026-12-03 09:59:19 -05:00
parent 5469ece012
commit 5ca998dc56
26 changed files with 829 additions and 98 deletions
@@ -80,7 +80,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
actor.Tell(Envelope(new CreateApiKeyCommand("MES-Production", new[] { "MethodA" }), "Administrator"));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
_auditService.Received(1).LogAsync(
_auditService.Received(1).LogAndSaveAsync(
"admin", "Create", "ApiKey", Arg.Any<string>(), "MES-Production", Arg.Any<object?>());
}
@@ -142,7 +142,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
Assert.Equal("key-1", doc.RootElement.GetProperty("keyId").GetString());
Assert.False(doc.RootElement.GetProperty("isEnabled").GetBoolean());
_auditService.Received(1).LogAsync(
_auditService.Received(1).LogAndSaveAsync(
"admin", "Update", "ApiKey", "key-1", Arg.Any<string>(), Arg.Any<object?>());
}
@@ -160,7 +160,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
Assert.DoesNotContain("key-1", _admin.Keys.Keys);
Assert.Equal("true", response.JsonData);
_auditService.Received(1).LogAsync(
_auditService.Received(1).LogAndSaveAsync(
"admin", "Delete", "ApiKey", "key-1", "key-1", null);
}
@@ -184,7 +184,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
.Select(m => m.GetString()).ToArray();
Assert.Equal(new[] { "New1", "New2", "New3" }, methods);
_auditService.Received(1).LogAsync(
_auditService.Received(1).LogAndSaveAsync(
"admin", "Update", "ApiKey", "key-1", Arg.Any<string>(), Arg.Any<object?>());
}
@@ -204,7 +204,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
Assert.Contains("key-unknown", response.Error);
// Seam returned false → audit must not have fired.
_auditService.DidNotReceive().LogAsync(
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
@@ -218,7 +218,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Contains("key-unknown", response.Error);
_auditService.DidNotReceive().LogAsync(
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
@@ -232,7 +232,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Contains("key-unknown", response.Error);
_auditService.DidNotReceive().LogAsync(
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Delete", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
@@ -252,7 +252,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
Assert.Contains("method", response.Error, StringComparison.OrdinalIgnoreCase);
// No key should have been created.
Assert.Empty(_admin.Keys);
_auditService.DidNotReceive().LogAsync(
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Create", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
@@ -270,7 +270,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
Assert.Contains("method", response.Error, StringComparison.OrdinalIgnoreCase);
// Existing scope set must be unchanged.
Assert.Equal(new[] { "M1" }, _admin.Keys["key-1"].Methods);
_auditService.DidNotReceive().LogAsync(
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
@@ -428,6 +428,15 @@ public class ManagementActorTests : TestKit, IDisposable
Assert.Equal(envelope.CorrelationId, response.CorrelationId);
Assert.NotNull(response.JsonData);
Assert.Contains("Pump1", response.JsonData);
// Code review 2026-12-02 TPL-3: InstanceService saves its own Create row; the
// handler no longer stages a second one (both used to be staged and lost).
_auditService.Received(1).LogAndSaveAsync(
"testuser", "Create", "Instance", Arg.Any<string>(), "Pump1",
Arg.Any<object?>(), Arg.Any<CancellationToken>());
_auditService.DidNotReceive().LogAsync(
Arg.Any<string>(), "Create", "Instance", Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<object?>(), Arg.Any<CancellationToken>());
}
/// <summary>Verifies that set native alarm source override, when on locked source, returns management error.</summary>
@@ -5280,7 +5289,8 @@ public class ManagementActorTests : TestKit, IDisposable
siteRepo.Received(1).UpdateDataConnectionAsync(
Arg.Is<Commons.Entities.Sites.DataConnection>(c => c.Id == 5 && c.SiteId == 2),
Arg.Any<CancellationToken>());
_auditService.Received(1).LogAsync(
// Saved, not just staged: Move is not a configuration command (MGT-1).
_auditService.Received(1).LogAndSaveAsync(
"testuser", "Move", "DataConnection", "5", "Opc1",
Arg.Any<object?>(), Arg.Any<CancellationToken>());
}
@@ -0,0 +1,132 @@
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);
}
}
@@ -0,0 +1,52 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
/// <summary>
/// A real <see cref="AuditService"/> over an in-memory SQLite configuration database, for the
/// code review 2026-12-02 DEP-1 / MGT-1 / TPL-3 regression tests. The pre-fix unit tests
/// mocked <c>IAuditService</c> and only asserted the call, which passed while the staged row
/// was never saved; these tests read the row back through a SECOND context on the same
/// connection, so only a row that was actually committed counts.
/// </summary>
internal sealed class RealAuditDatabase : IDisposable
{
private readonly SqliteConnection _connection;
private readonly DbContextOptions<ScadaBridgeDbContext> _options;
/// <summary>Opens the database and builds the audit service over a fresh context.</summary>
public RealAuditDatabase()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
_options = new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlite(_connection).Options;
Context = new ScadaBridgeDbContext(_options);
Context.Database.EnsureCreated();
AuditService = new AuditService(Context, new AuditCorrelationContext());
}
/// <summary>The unit-of-work context the audit service writes through.</summary>
public ScadaBridgeDbContext Context { get; }
/// <summary>The real audit service under test.</summary>
public AuditService AuditService { get; }
/// <summary>Reads the committed audit rows through an independent context.</summary>
/// <returns>Every persisted audit row.</returns>
public async Task<List<AuditLogEntry>> PersistedRowsAsync()
{
await using var reader = new ScadaBridgeDbContext(_options);
return await reader.AuditLogEntries.AsNoTracking().ToListAsync();
}
/// <inheritdoc />
public void Dispose()
{
Context.Dispose();
_connection.Dispose();
}
}
@@ -334,9 +334,10 @@ public class SchemaLibraryHandlerTests : TestKit, IDisposable
actor.Tell(envelope);
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
// LogAsync(user, action, entityType, entityId, entityName, afterState, ct):
// entityId is the id ("5"), entityName is the resolved name ("Addr").
_auditService.Received(1).LogAsync(
// LogAndSaveAsync(user, action, entityType, entityId, entityName, afterState, ct):
// entityId is the id ("5"), entityName is the resolved name ("Addr"). Saved, not
// just staged: DeleteSharedSchema is not a configuration command (MGT-1).
_auditService.Received(1).LogAndSaveAsync(
Arg.Any<string>(), "Delete", "SharedSchema", "5", "Addr",
Arg.Any<object?>(), Arg.Any<CancellationToken>());
}
@@ -13,6 +13,7 @@
<PackageReference Include="Akka.TestKit.Xunit2" />
<PackageReference Include="coverlet.collector" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="xunit" />
@@ -24,6 +25,7 @@
<ItemGroup>
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ManagementService/ZB.MOM.WW.ScadaBridge.ManagementService.csproj" />
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.csproj" />
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Security/ZB.MOM.WW.ScadaBridge.Security.csproj" />
<!-- #206: SecuredWrite audit now routes through the real CentralAuditWriter so the
handler tests verify SourceNode stamping end-to-end (actor → writer → repo). -->