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:
@@ -228,4 +228,74 @@ public class AuditServiceTests : IDisposable
|
||||
Assert.True(doc.RootElement.GetProperty("AuditTruncated").GetBoolean());
|
||||
Assert.True(doc.RootElement.GetProperty("OriginalLength").GetInt32() > AuditService.MaxAfterStateChars);
|
||||
}
|
||||
// ---- LogAndSaveAsync (code review 2026-12-02 DEP-1 / MGT-1 / TPL-3) ----
|
||||
|
||||
/// <summary>
|
||||
/// <c>LogAndSaveAsync</c> persists the row itself: a caller that has already done its
|
||||
/// final save (the DEP-1/MGT-1/TPL-3 shape) no longer loses the staged row when the
|
||||
/// scope is disposed. Read back through a second context on the same connection.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task LogAndSaveAsync_PersistsRow_WithoutACallerSave()
|
||||
{
|
||||
await _auditService.LogAndSaveAsync("admin", "Disable", "Instance", "42", "Pump1", new { State = "Disabled" });
|
||||
|
||||
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||
.UseSqlite(_context.Database.GetDbConnection())
|
||||
.Options;
|
||||
await using var reader = new ScadaBridgeDbContext(options);
|
||||
var row = await reader.AuditLogEntries.SingleAsync();
|
||||
Assert.Equal("Disable", row.Action);
|
||||
Assert.Equal("Pump1", row.EntityName);
|
||||
Assert.DoesNotContain(_context.ChangeTracker.Entries(), e => e.State != EntityState.Unchanged);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contrast pin: <c>LogAsync</c> alone only stages the row; nothing reaches the database
|
||||
/// until someone saves. This is the hazard <c>LogAndSaveAsync</c> exists for.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task LogAsync_WithoutSave_LeavesNoRow()
|
||||
{
|
||||
await _auditService.LogAsync("admin", "Disable", "Instance", "42", "Pump1", null);
|
||||
|
||||
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||
.UseSqlite(_context.Database.GetDbConnection())
|
||||
.Options;
|
||||
await using var reader = new ScadaBridgeDbContext(options);
|
||||
Assert.Empty(await reader.AuditLogEntries.ToListAsync());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Best-effort: a failing save is swallowed (never thrown to the caller) and the unsaved
|
||||
/// row is detached, so it cannot fail — or be silently written by — a later save.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task LogAndSaveAsync_SaveFails_DoesNotThrow_AndDetachesTheRow()
|
||||
{
|
||||
await _context.Database.ExecuteSqlRawAsync("DROP TABLE AuditLogEntries;");
|
||||
|
||||
var ex = await Record.ExceptionAsync(() =>
|
||||
_auditService.LogAndSaveAsync("admin", "Delete", "Instance", "7", "Gone", null));
|
||||
|
||||
Assert.Null(ex);
|
||||
Assert.DoesNotContain(_context.ChangeTracker.Entries(), e => e.Entity is ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit.AuditLogEntry);
|
||||
}
|
||||
|
||||
/// <summary>A cancelled token is also swallowed: audit never faults the caller.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task LogAndSaveAsync_Cancelled_DoesNotThrow()
|
||||
{
|
||||
using var cts = new CancellationTokenSource();
|
||||
await cts.CancelAsync();
|
||||
|
||||
var ex = await Record.ExceptionAsync(() =>
|
||||
_auditService.LogAndSaveAsync("admin", "Delete", "Instance", "7", "Gone", null, cts.Token));
|
||||
|
||||
Assert.Null(ex);
|
||||
}
|
||||
}
|
||||
|
||||
+88
-11
@@ -337,7 +337,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("retry-site", result.Value.SiteId);
|
||||
await _audit.Received().LogAsync(
|
||||
await _audit.Received().LogAndSaveAsync(
|
||||
"admin", "RetryArtifactDeployment", "SystemArtifact",
|
||||
Arg.Any<string>(), "retry-site", Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -406,6 +406,83 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
await _siteRepo.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Real-context audit durability (code review 2026-12-02 DEP-1) ──
|
||||
|
||||
/// <summary>
|
||||
/// Deploy Artifacts leaves a persisted <c>DeployArtifacts</c> row (the rig had 71 records
|
||||
/// and zero rows: the row was staged after the stamp's save and never written), even when
|
||||
/// the best-effort stamp save then fails.
|
||||
/// </summary>
|
||||
/// <param name="stampSaveFails">Whether the stamp's save throws.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task DeployToAllSitesAsync_DeployArtifactsAuditRowIsPersisted(bool stampSaveFails)
|
||||
{
|
||||
using var db = new RealAuditDatabase();
|
||||
var site = new Site("Site One", "site-1") { Id = 1 };
|
||||
_siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site> { site });
|
||||
if (stampSaveFails)
|
||||
{
|
||||
_siteRepo.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns<int>(_ => throw new InvalidOperationException("db down"));
|
||||
}
|
||||
|
||||
var recorder = new ArtifactProbeRecorder();
|
||||
var probe = Sys.ActorOf(Props.Create(() => new ArtifactProbeActor(recorder)));
|
||||
var service = CreateServiceWithCommActor(probe, audit: db.AuditService);
|
||||
|
||||
var result = await service.DeployToAllSitesAsync("admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var row = Assert.Single(await db.PersistedRowsAsync(), r => r.Action == "DeployArtifacts");
|
||||
Assert.Equal(result.Value.DeploymentId, row.EntityId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A retry refused for a missing secret sends nothing and returns failure; nothing saves
|
||||
/// after the audit call on that path, so the <c>DeploySiteSecrets</c> row used to be lost.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RetryForSiteAsync_MissingSecret_SecretsAuditRowIsPersisted()
|
||||
{
|
||||
using var db = new RealAuditDatabase();
|
||||
_siteRepo.GetDataConnectionsBySiteIdAsync(7, Arg.Any<CancellationToken>())
|
||||
.Returns(new List<DataConnection>
|
||||
{
|
||||
new("GW1", "MxGateway", 7) { PrimaryConfiguration = """{"ApiKey":"secret:missing-key"}""" }
|
||||
});
|
||||
var recorder = new ArtifactProbeRecorder();
|
||||
var probe = Sys.ActorOf(Props.Create(() => new ArtifactProbeActor(recorder)));
|
||||
var service = CreateServiceWithCommActor(probe, audit: db.AuditService);
|
||||
|
||||
var result = await service.RetryForSiteAsync(7, "retry-site", "admin");
|
||||
|
||||
Assert.True(result.IsFailure);
|
||||
var row = Assert.Single(await db.PersistedRowsAsync());
|
||||
Assert.Equal("DeploySiteSecrets", row.Action);
|
||||
Assert.Equal("retry-site", row.EntityId);
|
||||
Assert.Contains("missing-key", row.AfterStateJson);
|
||||
}
|
||||
|
||||
/// <summary>A successful retry persists its <c>RetryArtifactDeployment</c> row.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RetryForSiteAsync_SiteSucceeds_RetryAuditRowIsPersisted()
|
||||
{
|
||||
using var db = new RealAuditDatabase();
|
||||
var recorder = new ArtifactProbeRecorder();
|
||||
var probe = Sys.ActorOf(Props.Create(() => new ArtifactProbeActor(recorder)));
|
||||
var service = CreateServiceWithCommActor(probe, audit: db.AuditService);
|
||||
|
||||
var result = await service.RetryForSiteAsync(7, "retry-site", "admin");
|
||||
|
||||
Assert.True(result.IsSuccess, result.IsFailure ? result.Error : null);
|
||||
Assert.Single(await db.PersistedRowsAsync(), r => r.Action == "RetryArtifactDeployment");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a failed site keeps its previous artifact stamp.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
@@ -921,7 +998,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
// DeploySiteSecrets audit row is written for a deploy that carried no secrets.
|
||||
Assert.Null(siteResult.SecretsDeployed);
|
||||
Assert.NotNull(site.ArtifactRevisionHash);
|
||||
await _audit.DidNotReceive().LogAsync(
|
||||
await _audit.DidNotReceive().LogAndSaveAsync(
|
||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(),
|
||||
Arg.Any<string>(), Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -958,7 +1035,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
|
||||
object? captured = null;
|
||||
var callCount = 0;
|
||||
_audit.When(x => x.LogAsync(
|
||||
_audit.When(x => x.LogAndSaveAsync(
|
||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||
.Do(ci =>
|
||||
@@ -1086,7 +1163,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
|
||||
object? captured = null;
|
||||
var callCount = 0;
|
||||
_audit.When(x => x.LogAsync(
|
||||
_audit.When(x => x.LogAndSaveAsync(
|
||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||
.Do(ci =>
|
||||
@@ -1144,7 +1221,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
|
||||
object? captured = null;
|
||||
var callCount = 0;
|
||||
_audit.When(x => x.LogAsync(
|
||||
_audit.When(x => x.LogAndSaveAsync(
|
||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||
.Do(ci =>
|
||||
@@ -1206,7 +1283,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
}
|
||||
|
||||
private ArtifactDeploymentService CreateServiceWithCommActor(
|
||||
IActorRef commActor, ILogger<ArtifactDeploymentService>? logger = null)
|
||||
IActorRef commActor, ILogger<ArtifactDeploymentService>? logger = null, IAuditService? audit = null)
|
||||
{
|
||||
var comms = new CommunicationService(
|
||||
Options.Create(new CommunicationOptions
|
||||
@@ -1218,7 +1295,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
|
||||
return new ArtifactDeploymentService(
|
||||
_siteRepo, _deploymentRepo, _templateRepo, _externalSystemRepo,
|
||||
comms, _audit,
|
||||
comms, audit ?? _audit,
|
||||
Options.Create(new DeploymentManagerOptions
|
||||
{
|
||||
ArtifactDeploymentTimeoutPerSite = TimeSpan.FromSeconds(5)
|
||||
@@ -1341,7 +1418,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
var service = CreateServiceWithCommActor(probe);
|
||||
|
||||
object? audited = null;
|
||||
_audit.When(x => x.LogAsync(
|
||||
_audit.When(x => x.LogAndSaveAsync(
|
||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "sec-site", Arg.Any<string>(),
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||
.Do(ci => audited = ci[5]);
|
||||
@@ -1418,7 +1495,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains("Central secret store could not be read", result.Error);
|
||||
Assert.Empty(recorder.Received);
|
||||
await _audit.Received(1).LogAsync(
|
||||
await _audit.Received(1).LogAndSaveAsync(
|
||||
"admin", "DeploySiteSecrets", "SiteSecrets", "sec-site", Arg.Any<string>(),
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -1441,7 +1518,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
var service = CreateServiceWithCommActor(probe);
|
||||
|
||||
object? audited = null;
|
||||
_audit.When(x => x.LogAsync(
|
||||
_audit.When(x => x.LogAndSaveAsync(
|
||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "site-1", Arg.Any<string>(),
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||
.Do(ci => audited = ci[5]);
|
||||
@@ -1473,7 +1550,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
||||
var service = CreateServiceWithCommActor(probe);
|
||||
|
||||
object? audited = null;
|
||||
_audit.When(x => x.LogAsync(
|
||||
_audit.When(x => x.LogAndSaveAsync(
|
||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "site-1", Arg.Any<string>(),
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||
.Do(ci => audited = ci[5]);
|
||||
|
||||
+4
-4
@@ -141,9 +141,9 @@ public class DeploymentServiceFailurePathTests : TestKit
|
||||
await _repo.DidNotReceive().AddDeployedSnapshotAsync(Arg.Any<DeployedConfigSnapshot>(), Arg.Any<CancellationToken>());
|
||||
await _repo.DidNotReceive().UpdateDeployedSnapshotAsync(Arg.Any<DeployedConfigSnapshot>(), Arg.Any<CancellationToken>());
|
||||
// The outcome is audited as a Deploy with Failed status — not as a DeployFailed fault.
|
||||
await _audit.Received(1).LogAsync("admin", "Deploy", "Instance", "10", "Inst10",
|
||||
await _audit.Received(1).LogAndSaveAsync("admin", "Deploy", "Instance", "10", "Inst10",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
await _audit.DidNotReceive().LogAsync(Arg.Any<string>(), "DeployFailed", Arg.Any<string>(),
|
||||
await _audit.DidNotReceive().LogAndSaveAsync(Arg.Any<string>(), "DeployFailed", Arg.Any<string>(),
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -222,7 +222,7 @@ public class DeploymentServiceFailurePathTests : TestKit
|
||||
Assert.Equal(expectedFailedWrites, failedWrites);
|
||||
_repo.Received(1).DetachPendingChanges();
|
||||
// The failure audit row is written even when the status write could not be.
|
||||
await _audit.Received(1).LogAsync("admin", "DeployFailed", "Instance", "12", "Inst12",
|
||||
await _audit.Received(1).LogAndSaveAsync("admin", "DeployFailed", "Instance", "12", "Inst12",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -285,7 +285,7 @@ public class DeploymentServiceFailurePathTests : TestKit
|
||||
await _repo.DidNotReceive().UpdateInstanceAsync(Arg.Any<Instance>(), Arg.Any<CancellationToken>());
|
||||
await _repo.DidNotReceive().DeleteInstanceAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
await _repo.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _audit.Received(1).LogAsync("admin", action.ToString(), "Instance", "20", "LcInst",
|
||||
await _audit.Received(1).LogAndSaveAsync("admin", action.ToString(), "Instance", "20", "LcInst",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -953,7 +953,7 @@ public class DeploymentServiceTests : TestKit
|
||||
|
||||
await _service.DeployInstanceAsync(1, "admin");
|
||||
|
||||
await _audit.DidNotReceive().LogAsync(
|
||||
await _audit.DidNotReceive().LogAndSaveAsync(
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||
Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -979,7 +979,7 @@ public class DeploymentServiceTests : TestKit
|
||||
var result = await service.DeployInstanceAsync(50, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
await _audit.Received().LogAsync(
|
||||
await _audit.Received().LogAndSaveAsync(
|
||||
"admin", "Deploy", "Instance", "50", "AuditInst",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -999,8 +999,8 @@ public class DeploymentServiceTests : TestKit
|
||||
_repo.GetCurrentDeploymentStatusAsync(52, Arg.Any<CancellationToken>())
|
||||
.Returns((DeploymentRecord?)null);
|
||||
|
||||
// The Deploy audit LogAsync faults.
|
||||
_audit.When(a => a.LogAsync(
|
||||
// The Deploy audit LogAndSaveAsync faults.
|
||||
_audit.When(a => a.LogAndSaveAsync(
|
||||
Arg.Any<string>(), "Deploy", Arg.Any<string>(), Arg.Any<string>(),
|
||||
Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||
.Do(_ => throw new InvalidOperationException("audit pipeline down"));
|
||||
@@ -1179,7 +1179,7 @@ public class DeploymentServiceTests : TestKit
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(InstanceState.Disabled, instance.State);
|
||||
await _repo.Received().UpdateInstanceAsync(instance, Arg.Any<CancellationToken>());
|
||||
await _audit.Received().LogAsync(
|
||||
await _audit.Received().LogAndSaveAsync(
|
||||
"admin", "Disable", "Instance", "51", "DisInst",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -1202,7 +1202,7 @@ public class DeploymentServiceTests : TestKit
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(InstanceState.Enabled, instance.State);
|
||||
await _repo.Received().UpdateInstanceAsync(instance, Arg.Any<CancellationToken>());
|
||||
await _audit.Received().LogAsync(
|
||||
await _audit.Received().LogAndSaveAsync(
|
||||
"admin", "Enable", "Instance", "52", "EnInst",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -1224,11 +1224,78 @@ public class DeploymentServiceTests : TestKit
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
await _repo.Received().DeleteInstanceAsync(53, Arg.Any<CancellationToken>());
|
||||
await _audit.Received().LogAsync(
|
||||
await _audit.Received().LogAndSaveAsync(
|
||||
"admin", "Delete", "Instance", "53", "DelInst",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Real-context audit durability (code review 2026-12-02 DEP-1) ──
|
||||
//
|
||||
// The audit rows below used to be staged with LogAsync AFTER the method's final save and
|
||||
// nothing saved again, so they were discarded with the DI scope (the rig had zero
|
||||
// Disable/Enable/Delete rows). These run the lifecycle against a REAL AuditService over
|
||||
// SQLite and read the row back through a second context — the mocked tests above only
|
||||
// prove the call was made.
|
||||
|
||||
/// <summary>Disable, Enable and Delete each leave a persisted audit row.</summary>
|
||||
/// <param name="action">The lifecycle action to run.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData("Disable")]
|
||||
[InlineData("Enable")]
|
||||
[InlineData("Delete")]
|
||||
public async Task Lifecycle_SiteSucceeds_AuditRowIsPersisted(string action)
|
||||
{
|
||||
using var db = new RealAuditDatabase();
|
||||
var instance = new Instance("DurableInst")
|
||||
{
|
||||
Id = 61, SiteId = 1,
|
||||
State = action == "Enable" ? InstanceState.Disabled : InstanceState.Enabled
|
||||
};
|
||||
_repo.GetInstanceByIdAsync(61, Arg.Any<CancellationToken>()).Returns(instance);
|
||||
|
||||
var counters = new ReconcileProbeCounters();
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ReconcileProbeActor(counters, siteHash: "x", failQuery: false)));
|
||||
var service = CreateServiceWithCommActor(commActor, audit: db.AuditService);
|
||||
|
||||
var result = action switch
|
||||
{
|
||||
"Disable" => (await service.DisableInstanceAsync(61, "admin")).IsSuccess,
|
||||
"Enable" => (await service.EnableInstanceAsync(61, "admin")).IsSuccess,
|
||||
_ => (await service.DeleteInstanceAsync(61, "admin")).IsSuccess,
|
||||
};
|
||||
|
||||
Assert.True(result);
|
||||
var row = Assert.Single(await db.PersistedRowsAsync());
|
||||
Assert.Equal(action, row.Action);
|
||||
Assert.Equal("Instance", row.EntityType);
|
||||
Assert.Equal("61", row.EntityId);
|
||||
Assert.Equal("admin", row.User);
|
||||
}
|
||||
|
||||
/// <summary>A single-instance deploy leaves a persisted <c>Deploy</c> audit row.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DeployInstanceAsync_SiteSucceeds_AuditRowIsPersisted()
|
||||
{
|
||||
using var db = new RealAuditDatabase();
|
||||
var instance = new Instance("DurableDeploy") { Id = 62, SiteId = 1, State = InstanceState.NotDeployed };
|
||||
_repo.GetInstanceByIdAsync(62, Arg.Any<CancellationToken>()).Returns(instance);
|
||||
SetupValidPipeline(62, "DurableDeploy", "sha256:durable");
|
||||
|
||||
var counters = new ReconcileProbeCounters();
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ReconcileProbeActor(counters, siteHash: "sha256:other", failQuery: false)));
|
||||
var service = CreateServiceWithCommActor(commActor, audit: db.AuditService);
|
||||
|
||||
var result = await service.DeployInstanceAsync(62, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess, result.IsFailure ? result.Error : null);
|
||||
var row = Assert.Single(await db.PersistedRowsAsync(), r => r.Action == "Deploy");
|
||||
Assert.Equal("62", row.EntityId);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that deploy instance async same instance operation lock serializes concurrent deploys.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
@@ -1269,7 +1336,7 @@ public class DeploymentServiceTests : TestKit
|
||||
/// the notify-and-fetch fail-fast guard.
|
||||
/// </summary>
|
||||
private DeploymentService CreateServiceWithCommActor(
|
||||
IActorRef commActor, string centralFetchBaseUrl = TestFetchBaseUrl)
|
||||
IActorRef commActor, string centralFetchBaseUrl = TestFetchBaseUrl, IAuditService? audit = null)
|
||||
{
|
||||
var comms = new CommunicationService(
|
||||
Options.Create(new CommunicationOptions
|
||||
@@ -1282,7 +1349,7 @@ public class DeploymentServiceTests : TestKit
|
||||
|
||||
var siteRepo = CreateSiteRepoStub();
|
||||
return new DeploymentService(
|
||||
_repo, siteRepo, Substitute.For<ITemplateEngineRepository>(), _pipeline, comms, _lockManager, _audit,
|
||||
_repo, siteRepo, Substitute.For<ITemplateEngineRepository>(), _pipeline, comms, _lockManager, audit ?? _audit,
|
||||
new DiffService(),
|
||||
new RevisionHashService(),
|
||||
new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance),
|
||||
@@ -1863,11 +1930,11 @@ public class DeploymentServiceTests : TestKit
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
// Audit row's actor is the current user.
|
||||
await _audit.Received().LogAsync(
|
||||
await _audit.Received().LogAndSaveAsync(
|
||||
"currentUser", "DeployReconciled", "Instance", "73", "ReconcileAuditUser",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
// And the prior deployer was NOT used as the actor.
|
||||
await _audit.DidNotReceive().LogAsync(
|
||||
await _audit.DidNotReceive().LogAndSaveAsync(
|
||||
"originalUser", "DeployReconciled", "Instance", "73", "ReconcileAuditUser",
|
||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -1979,7 +2046,7 @@ public class DeploymentServiceTests : TestKit
|
||||
|
||||
// The DisableTimedOut audit entry must have been written. Pre-fix the
|
||||
// catch block returned without calling _auditService at all.
|
||||
await _audit.Received(1).LogAsync(
|
||||
await _audit.Received(1).LogAndSaveAsync(
|
||||
"operator-jane",
|
||||
"DisableTimedOut",
|
||||
"Instance",
|
||||
@@ -2027,7 +2094,7 @@ public class DeploymentServiceTests : TestKit
|
||||
var result = await service.EnableInstanceAsync(62, "operator-jane");
|
||||
|
||||
Assert.True(result.IsFailure);
|
||||
await _audit.Received(1).LogAsync(
|
||||
await _audit.Received(1).LogAndSaveAsync(
|
||||
"operator-jane",
|
||||
"EnableTimedOut",
|
||||
"Instance",
|
||||
@@ -2075,7 +2142,7 @@ public class DeploymentServiceTests : TestKit
|
||||
var result = await service.DeleteInstanceAsync(63, "operator-jane");
|
||||
|
||||
Assert.True(result.IsFailure);
|
||||
await _audit.Received(1).LogAsync(
|
||||
await _audit.Received(1).LogAndSaveAsync(
|
||||
"operator-jane",
|
||||
"DeleteTimedOut",
|
||||
"Instance",
|
||||
|
||||
@@ -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.DeploymentManager.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();
|
||||
}
|
||||
}
|
||||
+2
@@ -11,6 +11,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Akka.TestKit.Xunit2" />
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<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.DeploymentManager/ZB.MOM.WW.ScadaBridge.DeploymentManager.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.Communication/ZB.MOM.WW.ScadaBridge.Communication.csproj" />
|
||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -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>());
|
||||
}
|
||||
|
||||
+132
@@ -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>());
|
||||
}
|
||||
|
||||
+2
@@ -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). -->
|
||||
|
||||
@@ -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.TemplateEngine.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();
|
||||
}
|
||||
}
|
||||
@@ -153,7 +153,7 @@ public class AreaServiceTests
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2, result.Value.ParentAreaId);
|
||||
_repoMock.Verify(r => r.UpdateAreaAsync(It.Is<Area>(a => a.Id == 3 && a.ParentAreaId == 2), It.IsAny<CancellationToken>()), Times.Once);
|
||||
_auditMock.Verify(a => a.LogAsync("admin", "Move", "Area", "3", "Leaf", It.IsAny<object>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
_auditMock.Verify(a => a.LogAndSaveAsync("admin", "Move", "Area", "3", "Leaf", It.IsAny<object>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that moving an area to the site root succeeds.</summary>
|
||||
@@ -277,7 +277,7 @@ public class AreaServiceTests
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
_repoMock.Verify(r => r.UpdateAreaAsync(It.IsAny<Area>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
_auditMock.Verify(a => a.LogAsync(It.IsAny<string>(), "Move", It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
_auditMock.Verify(a => a.LogAndSaveAsync(It.IsAny<string>(), "Move", It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that moving an area fails when the target parent does not exist.</summary>
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
using Moq;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Services;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 TPL-3: every <see cref="InstanceService"/> mutation saved its change
|
||||
/// and THEN staged its audit row with <c>LogAsync</c>, so on the management/CLI path (no later
|
||||
/// save) the row was discarded — the rig had one Create row for instance ids up to 3876. These
|
||||
/// run the service against a REAL audit service over SQLite and read the row back through a
|
||||
/// second context, so only a committed row passes. The repository stays a mock: it never
|
||||
/// touches the audit context, so nothing but the audit service itself can persist the row.
|
||||
/// </summary>
|
||||
public class InstanceServiceAuditDurabilityTests : IDisposable
|
||||
{
|
||||
private readonly Mock<ITemplateEngineRepository> _repoMock = new();
|
||||
private readonly RealAuditDatabase _db = new();
|
||||
private readonly InstanceService _sut;
|
||||
|
||||
/// <summary>Builds the service over a mocked repository and a real audit service.</summary>
|
||||
public InstanceServiceAuditDurabilityTests()
|
||||
{
|
||||
_repoMock.Setup(r => r.SaveChangesAsync(It.IsAny<CancellationToken>())).ReturnsAsync(1);
|
||||
_sut = new InstanceService(_repoMock.Object, _db.AuditService);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => _db.Dispose();
|
||||
|
||||
/// <summary>Create persists its audit row (the CLI <c>instance create</c> path).</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task CreateInstance_AuditRowIsPersisted()
|
||||
{
|
||||
_repoMock.Setup(r => r.GetTemplateByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Template("T") { Id = 1 });
|
||||
_repoMock.Setup(r => r.GetInstanceByUniqueNameAsync("Inst1", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync((Instance?)null);
|
||||
|
||||
var result = await _sut.CreateInstanceAsync("Inst1", 1, 1, null, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var row = Assert.Single(await _db.PersistedRowsAsync());
|
||||
Assert.Equal(("Create", "Instance", "Inst1", "admin"), (row.Action, row.EntityType, row.EntityName, row.User));
|
||||
}
|
||||
|
||||
/// <summary>SetConnectionBindings persists its audit row (the CLI <c>instance set-bindings</c> path).</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SetConnectionBindings_AuditRowIsPersisted()
|
||||
{
|
||||
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Instance("Inst1") { Id = 1 });
|
||||
_repoMock.Setup(r => r.GetBindingsByInstanceIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<InstanceConnectionBinding>());
|
||||
|
||||
var result = await _sut.SetConnectionBindingsAsync(1, [new ConnectionBinding("Temp", 100)], "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("SetConnectionBindings", Assert.Single(await _db.PersistedRowsAsync()).Action);
|
||||
}
|
||||
|
||||
/// <summary>Enable / Disable / Delete each persist their audit row.</summary>
|
||||
/// <param name="action">The audited action.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData("Enable")]
|
||||
[InlineData("Disable")]
|
||||
[InlineData("Delete")]
|
||||
public async Task StateChanges_AuditRowIsPersisted(string action)
|
||||
{
|
||||
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Instance("Inst1") { Id = 1, State = InstanceState.Disabled });
|
||||
|
||||
var ok = action switch
|
||||
{
|
||||
"Enable" => (await _sut.EnableAsync(1, "admin")).IsSuccess,
|
||||
"Disable" => (await _sut.DisableAsync(1, "admin")).IsSuccess,
|
||||
_ => (await _sut.DeleteAsync(1, "admin")).IsSuccess,
|
||||
};
|
||||
|
||||
Assert.True(ok);
|
||||
Assert.Equal(action, Assert.Single(await _db.PersistedRowsAsync()).Action);
|
||||
}
|
||||
}
|
||||
+2
@@ -10,6 +10,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="Moq" />
|
||||
<PackageReference Include="xunit" />
|
||||
@@ -22,6 +23,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj" />
|
||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user