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
@@ -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);
}
}