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.
302 lines
14 KiB
C#
302 lines
14 KiB
C#
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
|
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;
|
|
|
|
public class AuditServiceTests : IDisposable
|
|
{
|
|
private readonly ScadaBridgeDbContext _context;
|
|
private readonly AuditCorrelationContext _correlationContext;
|
|
private readonly AuditService _auditService;
|
|
|
|
/// <summary>Initializes the test class with an in-memory SQLite database and an audit service.</summary>
|
|
public AuditServiceTests()
|
|
{
|
|
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
|
.UseSqlite("DataSource=:memory:")
|
|
.Options;
|
|
|
|
_context = new ScadaBridgeDbContext(options);
|
|
_context.Database.OpenConnection();
|
|
_context.Database.EnsureCreated();
|
|
_correlationContext = new AuditCorrelationContext();
|
|
_auditService = new AuditService(_context, _correlationContext);
|
|
}
|
|
|
|
/// <summary>Releases the resources held by the test fixture.</summary>
|
|
public void Dispose()
|
|
{
|
|
_context.Database.CloseConnection();
|
|
_context.Dispose();
|
|
}
|
|
|
|
/// <summary>Verifies that logging creates an audit entry committed together with the entity change.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_CreatesAuditEntry_CommittedWithEntityChange()
|
|
{
|
|
// Simulate entity change + audit in same transaction
|
|
var template = new Template("TestTemplate");
|
|
_context.Templates.Add(template);
|
|
|
|
await _auditService.LogAsync("admin", "Create", "Template", "1", "TestTemplate",
|
|
new { Name = "TestTemplate" });
|
|
|
|
// Single SaveChangesAsync commits both
|
|
await _context.SaveChangesAsync();
|
|
|
|
var audit = await _context.AuditLogEntries.SingleAsync();
|
|
Assert.Equal("admin", audit.User);
|
|
Assert.Equal("Create", audit.Action);
|
|
Assert.Equal("Template", audit.EntityType);
|
|
Assert.NotNull(audit.AfterStateJson);
|
|
|
|
// Template also committed
|
|
Assert.Single(await _context.Templates.ToListAsync());
|
|
}
|
|
|
|
/// <summary>Verifies that a rollback undoes both the entity change and its audit entry.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_Rollback_BothChangeAndAuditRolledBack()
|
|
{
|
|
// Use a separate context to simulate rollback via not calling SaveChanges
|
|
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
|
.UseSqlite(_context.Database.GetDbConnection())
|
|
.Options;
|
|
|
|
using var context2 = new ScadaBridgeDbContext(options);
|
|
var auditService2 = new AuditService(context2, new AuditCorrelationContext());
|
|
|
|
var template = new Template("RollbackTemplate");
|
|
context2.Templates.Add(template);
|
|
await auditService2.LogAsync("admin", "Create", "Template", "99", "RollbackTemplate",
|
|
new { Name = "RollbackTemplate" });
|
|
|
|
// Intentionally do NOT call SaveChangesAsync — simulates rollback
|
|
// Verify nothing persisted
|
|
Assert.Empty(await _context.AuditLogEntries.Where(a => a.EntityName == "RollbackTemplate").ToListAsync());
|
|
Assert.Empty(await _context.Templates.Where(t => t.Name == "RollbackTemplate").ToListAsync());
|
|
}
|
|
|
|
/// <summary>Verifies that the after-state is serialized as JSON.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_SerializesAfterStateAsJson()
|
|
{
|
|
var state = new { Name = "Test", Value = 42, Nested = new { Prop = "inner" } };
|
|
await _auditService.LogAsync("admin", "Create", "Entity", "1", "Test", state);
|
|
await _context.SaveChangesAsync();
|
|
|
|
var audit = await _context.AuditLogEntries.SingleAsync();
|
|
Assert.NotNull(audit.AfterStateJson);
|
|
|
|
var deserialized = JsonSerializer.Deserialize<JsonElement>(audit.AfterStateJson!);
|
|
Assert.Equal("Test", deserialized.GetProperty("Name").GetString());
|
|
Assert.Equal(42, deserialized.GetProperty("Value").GetInt32());
|
|
}
|
|
|
|
/// <summary>Verifies that a null after-state is stored for deletes.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_NullAfterState_ForDeletes()
|
|
{
|
|
await _auditService.LogAsync("admin", "Delete", "Template", "1", "DeletedTemplate", null);
|
|
await _context.SaveChangesAsync();
|
|
|
|
var audit = await _context.AuditLogEntries.SingleAsync();
|
|
Assert.Null(audit.AfterStateJson);
|
|
Assert.Equal("Delete", audit.Action);
|
|
}
|
|
|
|
/// <summary>Verifies that the audit timestamp is set to the current UTC time.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_SetsTimestampToUtcNow()
|
|
{
|
|
var before = DateTimeOffset.UtcNow;
|
|
await _auditService.LogAsync("admin", "Create", "Template", "1", "T1", new { });
|
|
await _context.SaveChangesAsync();
|
|
var after = DateTimeOffset.UtcNow;
|
|
|
|
var audit = await _context.AuditLogEntries.SingleAsync();
|
|
// Allow 2 second tolerance for SQLite precision
|
|
Assert.True(audit.Timestamp >= before.AddSeconds(-2));
|
|
Assert.True(audit.Timestamp <= after.AddSeconds(2));
|
|
}
|
|
|
|
/// <summary>Verifies that the audit service is append-only and exposes no update or delete methods.</summary>
|
|
[Fact]
|
|
public void AuditService_IsAppendOnly_NoUpdateOrDeleteMethods()
|
|
{
|
|
// Verify IAuditService only exposes LogAsync — no update/delete
|
|
var methods = typeof(IAuditService).GetMethods();
|
|
Assert.Single(methods, m => m.Name == "LogAsync");
|
|
Assert.DoesNotContain(methods, m => m.Name.Contains("Update", StringComparison.OrdinalIgnoreCase));
|
|
Assert.DoesNotContain(methods, m => m.Name.Contains("Delete", StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
/// <summary>Verifies that the bundle import id is stamped from the correlation context.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_StampsBundleImportId_FromCorrelationContext()
|
|
{
|
|
// Bundle importer sets the correlation context for the duration of ApplyAsync;
|
|
// every AuditLogEntry written under that scope must carry the BundleImportId so
|
|
// the imported configuration is attributable to the import session.
|
|
var bundleId = Guid.NewGuid();
|
|
_correlationContext.BundleImportId = bundleId;
|
|
|
|
await _auditService.LogAsync("admin", "Create", "Template", "1", "BundleImportedTemplate",
|
|
new { Name = "BundleImportedTemplate" });
|
|
await _context.SaveChangesAsync();
|
|
|
|
var audit = await _context.AuditLogEntries.SingleAsync();
|
|
Assert.Equal(bundleId, audit.BundleImportId);
|
|
}
|
|
|
|
/// <summary>Verifies that the bundle import id stays null when the correlation context has no value.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_LeavesBundleImportIdNull_WhenCorrelationContextHasNoValue()
|
|
{
|
|
// Default code path (interactive user edit, not a bundle import) must leave
|
|
// the column NULL so normal audit rows are distinguishable from bundle-import
|
|
// rows in queries and reports.
|
|
Assert.Null(_correlationContext.BundleImportId);
|
|
|
|
await _auditService.LogAsync("admin", "Create", "Template", "1", "InteractiveTemplate",
|
|
new { Name = "InteractiveTemplate" });
|
|
await _context.SaveChangesAsync();
|
|
|
|
var audit = await _context.AuditLogEntries.SingleAsync();
|
|
Assert.Null(audit.BundleImportId);
|
|
}
|
|
|
|
// Self-referential POCO used to reproduce a reference cycle in afterState.
|
|
private sealed class CyclicNode
|
|
{
|
|
/// <summary>Gets or sets the node name.</summary>
|
|
public string Name { get; set; } = "node";
|
|
/// <summary>Gets or sets the self-referencing node that forms the cycle.</summary>
|
|
public CyclicNode? Self { get; set; }
|
|
}
|
|
|
|
/// <summary>Verifies that an after-state containing a reference cycle neither throws nor rolls back the audited operation.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_AfterStateWithReferenceCycle_DoesNotThrow_AndDoesNotRollBackOperation()
|
|
{
|
|
// Regression guard for serializing an afterState
|
|
// object that contains a reference cycle must not throw a JsonException —
|
|
// that would roll back the entire business operation it is auditing.
|
|
var node = new CyclicNode();
|
|
node.Self = node; // reference cycle
|
|
|
|
var template = new Template("CyclicAuditTemplate");
|
|
_context.Templates.Add(template);
|
|
|
|
// Must not throw.
|
|
await _auditService.LogAsync("admin", "Create", "Template", "1", "CyclicAuditTemplate", node);
|
|
|
|
// The audited business operation must still commit successfully.
|
|
await _context.SaveChangesAsync();
|
|
|
|
var audit = await _context.AuditLogEntries.SingleAsync();
|
|
Assert.NotNull(audit.AfterStateJson);
|
|
Assert.Contains("node", audit.AfterStateJson);
|
|
Assert.Single(await _context.Templates.Where(t => t.Name == "CyclicAuditTemplate").ToListAsync());
|
|
}
|
|
|
|
/// <summary>An oversized after-state is replaced by a small valid-JSON truncation marker (review 08/G1).</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogAsync_OversizedAfterState_IsTruncatedToMarker()
|
|
{
|
|
await _auditService.LogAsync("admin", "Update", "Template", "1", "Big",
|
|
new { Code = new string('x', AuditService.MaxAfterStateChars + 10) });
|
|
await _context.SaveChangesAsync();
|
|
|
|
var json = _context.AuditLogEntries.Single().AfterStateJson!;
|
|
Assert.True(json.Length < 16 * 1024);
|
|
using var doc = JsonDocument.Parse(json);
|
|
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);
|
|
}
|
|
}
|