diff --git a/docs/requirements/Component-Commons.md b/docs/requirements/Component-Commons.md index c3a57589..7a86d89d 100644 --- a/docs/requirements/Component-Commons.md +++ b/docs/requirements/Component-Commons.md @@ -116,7 +116,7 @@ Implementations of these interfaces are owned by the Configuration Database comp Commons must define service interfaces for cross-cutting concerns that multiple components consume: -- **`IAuditService`**: Provides a single method for components to log audit entries: `LogAsync(user, action, entityType, entityId, entityName, afterState)`. The implementation (owned by the Configuration Database component) serializes the state as JSON and adds the audit entry to the current unit-of-work transaction. Defined in Commons so any central component can call it without depending on the Configuration Database component directly. +- **`IAuditService`**: Lets components log audit entries: `LogAsync(user, action, entityType, entityId, entityName, afterState)` stages the entry in the current unit-of-work transaction (the caller's save commits it); `LogAndSaveAsync(...)` (same arguments) also saves it immediately, best-effort and never throwing, for callers that audit after their final save (code review 2026-12-02 DEP-1). The implementation (owned by the Configuration Database component) serializes the state as JSON. Defined in Commons so any central component can call it without depending on the Configuration Database component directly. - **`IDatabaseGateway`**: Provides script-facing ADO.NET database access via named database connections. Implemented by the External System Gateway, consumed by the Site Runtime's script runtime context. - **`IExternalSystemClient`**: Provides script-facing invocation of external system HTTP APIs (synchronous `Call` and store-and-forward `CachedCall`). Implemented by the External System Gateway, consumed by the script runtime context. - **`IInstanceLocator`**: Resolves an instance unique name to its site identifier. Used by the Inbound API's `Route.To()` to determine the destination site. diff --git a/docs/requirements/Component-ConfigurationDatabase.md b/docs/requirements/Component-ConfigurationDatabase.md index 1e713e5b..007beb67 100644 --- a/docs/requirements/Component-ConfigurationDatabase.md +++ b/docs/requirements/Component-ConfigurationDatabase.md @@ -256,6 +256,12 @@ Audit entries are written **synchronously** within the same database transaction - If the change fails and rolls back, the audit entry is also rolled back. - No audit entries are lost due to process crashes between the change and the audit write. +#### `LogAndSaveAsync` — when the audit call comes after the last save + +`LogAsync` only **stages** the row; the guarantee above holds only if something saves afterwards. A caller that audits AFTER its final `SaveChangesAsync` — and is not running inside the `ConfigurationCommandTransaction`, whose trailing save flushes staged rows — must call `IAuditService.LogAndSaveAsync(...)` instead (code review 2026-12-02 DEP-1 / MGT-1 / TPL-3). It adds the row and saves it immediately, **best-effort**: any failure (including cancellation) is logged at Warning and swallowed, never thrown, and the unsaved row is detached so it cannot fail or be silently written by a later save. Because the save flushes the whole unit of work, call it only once the operation's own changes are saved; inside an ambient transaction the row commits or rolls back with that transaction. + +Before this, every post-save `LogAsync` with no later save was silently discarded with the DI scope: the rig showed zero `Disable`/`Enable`/`Delete`/`DeployArtifacts` rows, 16 `Deploy` rows for 62 deployments, and one `Create`/`Instance` row for instance ids up to 3876. Post-save callers now on `LogAndSaveAsync`: `DeploymentService` (deploy, deploy-failed, reconciled, disable/enable/delete and their timeouts), `ArtifactDeploymentService` (`DeployArtifacts` — now written before the best-effort revision stamp — `RetryArtifactDeployment`, `DeploySiteSecrets`), `InstanceService`, `AreaService`, `SiteService`, and the `ManagementActor` handlers outside the configuration-command list (API keys, shared schemas, external-system methods, data-connection move). Services that already save after `LogAsync` (`TemplateService`, `SharedScriptService`, `TemplateFolderService`, the Transport importer/exporter) are unchanged. + ### Integration Example ```mermaid diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IAuditService.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IAuditService.cs index f76b56ad..87af99c1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IAuditService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IAuditService.cs @@ -14,4 +14,27 @@ public interface IAuditService /// Cancellation token for the log write. /// A task that represents the asynchronous operation. Task LogAsync(string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default); + + /// + /// Appends an audit log entry AND persists it immediately, best-effort: any failure + /// (including the save) is logged and swallowed, and the unsaved entry is detached so it + /// cannot poison a later save. Never throws (code review 2026-12-02 DEP-1/MGT-1/TPL-3). + /// + /// + /// Use this — not — wherever the audit call comes AFTER the + /// operation's final SaveChangesAsync: only stages the + /// row on the change tracker, so a staged row with no later save is silently discarded + /// when the DI scope is disposed. The save flushes the whole unit of work, so call this + /// only once the operation's own changes are saved; inside an ambient transaction the + /// row commits (or rolls back) with that transaction. + /// + /// The authenticated username performing the action. + /// The action performed (e.g., "Create", "Update", "Delete"). + /// The type name of the affected entity. + /// The string representation of the entity's primary key. + /// The display name of the affected entity. + /// The entity state after the action; may be null for deletes. + /// Cancellation token for the log write. + /// A task that represents the asynchronous operation; it never faults. + Task LogAndSaveAsync(string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default); } diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Services/AuditService.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Services/AuditService.cs index 45451306..9be5475b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Services/AuditService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Services/AuditService.cs @@ -1,4 +1,7 @@ using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport; @@ -9,6 +12,7 @@ public class AuditService : IAuditService { private readonly ScadaBridgeDbContext _context; private readonly IAuditCorrelationContext _correlationContext; + private readonly ILogger _logger; /// /// Serializer options for audit afterState payloads. Audit writes commit in the @@ -37,10 +41,15 @@ public class AuditService : IAuditService /// /// The EF Core database context used to stage audit entries. /// Provides the active bundle import id for audit row stamping. - public AuditService(ScadaBridgeDbContext context, IAuditCorrelationContext correlationContext) + /// Logs a failed best-effort ; optional. + public AuditService( + ScadaBridgeDbContext context, + IAuditCorrelationContext correlationContext, + ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _correlationContext = correlationContext ?? throw new ArgumentNullException(nameof(correlationContext)); + _logger = logger ?? NullLogger.Instance; } /// @@ -53,7 +62,51 @@ public class AuditService : IAuditService object? afterState, CancellationToken cancellationToken = default) { - var entry = new AuditLogEntry(user, action, entityType, entityId, entityName) + // Add to change tracker only — caller is responsible for calling SaveChangesAsync + // to ensure atomicity with the entity change. + await _context.AuditLogEntries.AddAsync( + BuildEntry(user, action, entityType, entityId, entityName, afterState), cancellationToken); + } + + /// + public async Task LogAndSaveAsync( + string user, + string action, + string entityType, + string entityId, + string entityName, + object? afterState, + CancellationToken cancellationToken = default) + { + AuditLogEntry? entry = null; + try + { + entry = BuildEntry(user, action, entityType, entityId, entityName, afterState); + await _context.AuditLogEntries.AddAsync(entry, cancellationToken); + await _context.SaveChangesAsync(cancellationToken); + } + catch (Exception ex) + { + // Best-effort: the action this row records has already committed, so an audit + // failure must never surface to the caller. Detach the unsaved row so it cannot + // fail (or be silently written by) a later save on this unit of work. + if (entry is not null) + { + try { _context.Entry(entry).State = EntityState.Detached; } + catch { /* the row was never tracked */ } + } + + _logger.LogWarning(ex, + "Failed to persist {Action} audit entry for {EntityType} {EntityName} ({EntityId}) by {User}; " + + "the action itself succeeded and audit is best-effort", + action, entityType, entityName, entityId, user); + } + } + + private AuditLogEntry BuildEntry( + string user, string action, string entityType, string entityId, string entityName, object? afterState) + { + return new AuditLogEntry(user, action, entityType, entityId, entityName) { Timestamp = DateTimeOffset.UtcNow, AfterStateJson = afterState != null @@ -64,10 +117,6 @@ public class AuditService : IAuditService // interactive code path. BundleImportId = _correlationContext.BundleImportId }; - - // Add to change tracker only — caller is responsible for calling SaveChangesAsync - // to ensure atomicity with the entity change. - await _context.AuditLogEntries.AddAsync(entry, cancellationToken); } /// diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/ArtifactDeploymentService.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/ArtifactDeploymentService.cs index 60ee69f0..c7415f5a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/ArtifactDeploymentService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/ArtifactDeploymentService.cs @@ -245,6 +245,11 @@ public class ArtifactDeploymentService /// error — never , Nonce, Tag, /// WrappedDek, or any other material (global constraint: never plaintext or material /// in logs or audit rows). + /// + /// The row is saved here (, which never throws): + /// on the retry path nothing saves after it, so a staged-only row was discarded with the + /// DI scope — a refused retry (missing secret) wrote no row at all (code review + /// 2026-12-02 DEP-1). /// private Task LogSecretsAuditAsync( string user, @@ -269,7 +274,7 @@ public class ArtifactDeploymentService if (!hasSecretRefs) return Task.CompletedTask; - return _auditService.LogAsync( + return _auditService.LogAndSaveAsync( user, "DeploySiteSecrets", "SiteSecrets", siteIdentifier, siteName, new { @@ -596,6 +601,22 @@ public class ArtifactDeploymentService // Only sites whose deploy SUCCEEDED are stamped. A failed site is deliberately // left untouched so it keeps its previous stamp (or none at all) and keeps // reading "out of date" on the Sites page. + var summary = new ArtifactDeploymentSummary( + deploymentId, + results.ToList(), + results.Count(r => r.Success), + results.Count(r => !r.Success)); + + // Code review 2026-12-02 DEP-1: this row used to be staged with LogAsync AFTER the + // stamp's save, so nothing ever wrote it (zero DeployArtifacts rows on the rig). It is + // now saved on its own (LogAndSaveAsync never throws) and — per the ordering rule + // above — BEFORE the best-effort stamp, so a failed stamp that leaves Site entries + // tracked as Modified cannot take the audit row's save down with it. + await _auditService.LogAndSaveAsync(user, "DeployArtifacts", "SystemArtifact", + deploymentId, "Artifacts", + new { summary.SuccessCount, summary.FailureCount }, + cancellationToken); + var successfulSites = sites .Where(site => perSiteResults.TryGetValue(site.SiteIdentifier, out var r) && r.Success) .ToList(); @@ -606,17 +627,6 @@ public class ArtifactDeploymentService cancellationToken); } - var summary = new ArtifactDeploymentSummary( - deploymentId, - results.ToList(), - results.Count(r => r.Success), - results.Count(r => !r.Success)); - - await _auditService.LogAsync(user, "DeployArtifacts", "SystemArtifact", - deploymentId, "Artifacts", - new { summary.SuccessCount, summary.FailureCount }, - cancellationToken); - return Result.Success(summary); } @@ -682,7 +692,9 @@ public class ArtifactDeploymentService // returned Result — an old site's/partial site's reply must not read as success. var result = ReconcileSecretsOutcome(command, response, siteIdentifier, siteIdentifier); - await _auditService.LogAsync(user, "RetryArtifactDeployment", "SystemArtifact", + // Saved here (DEP-1): nothing on the retry path saves after it unless the + // retry succeeds and the stamp runs. + await _auditService.LogAndSaveAsync(user, "RetryArtifactDeployment", "SystemArtifact", command.DeploymentId, siteIdentifier, new { result.Success }, cancellationToken); // Ordering rule: audit before the best-effort stamp. diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs index 968ac9e6..4b1b1474 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs @@ -2328,7 +2328,9 @@ public class DeploymentService // who issued the original timed-out / stuck deployment. The original // deployer is preserved in the detail object so forensics can still // see who launched the run that reconciliation rescued. - await _auditService.LogAsync(currentUser, "DeployReconciled", "Instance", + // LogAndSaveAsync: the row comes after the last save above (code review + // 2026-12-02 DEP-1) — a staged LogAsync row here was never written. + await _auditService.LogAndSaveAsync(currentUser, "DeployReconciled", "Instance", instance.Id.ToString(), instance.UniqueName, new { @@ -2522,6 +2524,11 @@ public class DeploymentService /// must NEVER surface to the caller or flip the committed status — "audit-write /// failure NEVER aborts the user-facing action" (Centralized Audit Log design). /// Any exception is swallowed and logged at Warning. + /// + /// Every caller runs this AFTER its final SaveChangesAsync, so the row must be + /// saved here (): a staged-only + /// LogAsync row was discarded with the DI scope (code review 2026-12-02 DEP-1). + /// /// private async Task TryLogAuditAsync( string user, @@ -2534,7 +2541,7 @@ public class DeploymentService { try { - await _auditService.LogAsync( + await _auditService.LogAndSaveAsync( user, action, entityType, entityId, entityName, afterState, cancellationToken); } catch (Exception auditEx) @@ -2556,7 +2563,8 @@ public class DeploymentService { try { - await _auditService.LogAsync( + // Post-save, like TryLogAuditAsync: persist the row here (DEP-1). + await _auditService.LogAndSaveAsync( user, action, "Instance", diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index 923e6e47..1a396ed8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -737,6 +737,22 @@ public class ManagementActor : ReceiveActor await auditService.LogAsync(user, action, entityType, entityId, entityName, afterState); } + /// + /// Logs AND persists an audit entry, best-effort, for a handler that is NOT a + /// configuration command (code review 2026-12-02 MGT-1). + /// + /// + /// only stages the row; for a command in + /// the ConfigurationCommandTransaction's final + /// save flushes it. A command outside that list runs through plain + /// DispatchCommand with no trailing save, so a staged row there was discarded with + /// the scope (API keys, shared schemas, external-system methods, data-connection move). + /// Such handlers call this AFTER their own save (or after a store call that saves + /// internally); it never throws. + /// + private static Task AuditAndSaveAsync(IServiceProvider sp, string user, string action, string entityType, string entityId, string entityName, object? afterState) => + sp.GetRequiredService().LogAndSaveAsync(user, action, entityType, entityId, entityName, afterState); + // ======================================================================== // Template handlers // ======================================================================== @@ -1027,7 +1043,9 @@ public class ManagementActor : ReceiveActor var svc = sp.GetRequiredService(); var result = await svc.CreateInstanceAsync(cmd.UniqueName, cmd.TemplateId, cmd.SiteId, cmd.AreaId, user.Username); if (!result.IsSuccess) throw new ManagementCommandException(result.Error); - await AuditAsync(sp, user.Username, "Create", "Instance", result.Value.Id.ToString(), result.Value.UniqueName, result.Value); + // No AuditAsync here: InstanceService.CreateInstanceAsync audits the Create itself + // (see the AuditAsync contract). Both rows used to be staged and lost (code review + // 2026-12-02 TPL-3); now that the service saves its row, a second row would double-log. return result.Value; } @@ -2378,7 +2396,10 @@ public class ManagementActor : ReceiveActor conn.SiteId = cmd.TargetSiteId; await repo.UpdateDataConnectionAsync(conn); await repo.SaveChangesAsync(); - await AuditAsync(sp, user, "Move", "DataConnection", conn.Id.ToString(), conn.Name, conn); + // AuditAndSaveAsync (MGT-1): Move is not a configuration command, so a staged row + // was never saved. The after-state is the scrubbed public shape (MGT-4) — the raw + // entity carries the decrypted protocol configuration, credentials included. + await AuditAndSaveAsync(sp, user, "Move", "DataConnection", conn.Id.ToString(), conn.Name, DataConnectionPublicShape(conn)); return conn; } @@ -2520,7 +2541,7 @@ public class ManagementActor : ReceiveActor await repo.AddExternalSystemMethodAsync(method); await repo.SaveChangesAsync(); await InvalidateExternalDefinitionCacheAfterCommit(sp); - await AuditAsync(sp, user, "Create", "ExternalSystemMethod", method.Id.ToString(), method.Name, method); + await AuditAndSaveAsync(sp, user, "Create", "ExternalSystemMethod", method.Id.ToString(), method.Name, method); return method; } @@ -2537,7 +2558,7 @@ public class ManagementActor : ReceiveActor await repo.UpdateExternalSystemMethodAsync(method); await repo.SaveChangesAsync(); await InvalidateExternalDefinitionCacheAfterCommit(sp); - await AuditAsync(sp, user, "Update", "ExternalSystemMethod", method.Id.ToString(), method.Name, method); + await AuditAndSaveAsync(sp, user, "Update", "ExternalSystemMethod", method.Id.ToString(), method.Name, method); return method; } @@ -2547,7 +2568,7 @@ public class ManagementActor : ReceiveActor await repo.DeleteExternalSystemMethodAsync(cmd.MethodId); await repo.SaveChangesAsync(); await InvalidateExternalDefinitionCacheAfterCommit(sp); - await AuditAsync(sp, user, "Delete", "ExternalSystemMethod", cmd.MethodId.ToString(), cmd.MethodId.ToString(), null); + await AuditAndSaveAsync(sp, user, "Delete", "ExternalSystemMethod", cmd.MethodId.ToString(), cmd.MethodId.ToString(), null); return true; } @@ -3031,7 +3052,7 @@ public class ManagementActor : ReceiveActor var admin = sp.GetRequiredService(); var created = await admin.CreateAsync(cmd.Name, cmd.Methods); - await AuditAsync(sp, user, "Create", "ApiKey", created.KeyId, cmd.Name, + await AuditAndSaveAsync(sp, user, "Create", "ApiKey", created.KeyId, cmd.Name, new { created.KeyId, cmd.Name }); return new @@ -3048,7 +3069,7 @@ public class ManagementActor : ReceiveActor var deleted = await admin.DeleteAsync(cmd.KeyId); if (!deleted) throw new ManagementCommandException($"API key '{cmd.KeyId}' not found."); - await AuditAsync(sp, user, "Delete", "ApiKey", cmd.KeyId, cmd.KeyId, null); + await AuditAndSaveAsync(sp, user, "Delete", "ApiKey", cmd.KeyId, cmd.KeyId, null); return deleted; } @@ -3750,7 +3771,7 @@ public class ManagementActor : ReceiveActor var schema = new SharedSchema { Name = name, Scope = cmd.Scope, SchemaJson = cmd.SchemaJson }; await repo.AddAsync(schema); - await AuditAsync(sp, user, "Create", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope }); + await AuditAndSaveAsync(sp, user, "Create", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope }); return schema; } @@ -3775,7 +3796,7 @@ public class ManagementActor : ReceiveActor schema.Scope = cmd.Scope; schema.SchemaJson = cmd.SchemaJson; await repo.UpdateAsync(schema); - await AuditAsync(sp, user, "Update", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope }); + await AuditAndSaveAsync(sp, user, "Update", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope }); return schema; } @@ -3787,7 +3808,7 @@ public class ManagementActor : ReceiveActor // Site delete handler. Falls back to the id when the row is already absent. var schema = await repo.GetByIdAsync(cmd.SharedSchemaId); await repo.DeleteAsync(cmd.SharedSchemaId); - await AuditAsync(sp, user, "Delete", "SharedSchema", cmd.SharedSchemaId.ToString(), + await AuditAndSaveAsync(sp, user, "Delete", "SharedSchema", cmd.SharedSchemaId.ToString(), schema?.Name ?? cmd.SharedSchemaId.ToString(), null); return true; } @@ -4100,7 +4121,7 @@ public class ManagementActor : ReceiveActor var updated = await admin.SetEnabledAsync(cmd.KeyId, cmd.IsEnabled); if (!updated) throw new ManagementCommandException($"API key '{cmd.KeyId}' not found."); - await AuditAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId, + await AuditAndSaveAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId, new { cmd.KeyId, cmd.IsEnabled }); return new { cmd.KeyId, cmd.IsEnabled }; } @@ -4116,7 +4137,7 @@ public class ManagementActor : ReceiveActor var updated = await admin.SetMethodsAsync(cmd.KeyId, cmd.Methods); if (!updated) throw new ManagementCommandException($"API key '{cmd.KeyId}' not found."); - await AuditAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId, + await AuditAndSaveAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId, new { cmd.KeyId, cmd.Methods }); return new { cmd.KeyId, Methods = cmd.Methods }; } diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs index 4e317c95..9dfcee7a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs @@ -70,7 +70,7 @@ public class AreaService await _repository.AddAreaAsync(area, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Create", "Area", area.Id.ToString(), name, area, cancellationToken); + await _auditService.LogAndSaveAsync(user, "Create", "Area", area.Id.ToString(), name, area, cancellationToken); return Result.Success(area); } @@ -107,7 +107,7 @@ public class AreaService await _repository.UpdateAreaAsync(area, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Update", "Area", area.Id.ToString(), name, area, cancellationToken); + await _auditService.LogAndSaveAsync(user, "Update", "Area", area.Id.ToString(), name, area, cancellationToken); return Result.Success(area); } @@ -167,7 +167,7 @@ public class AreaService await _repository.UpdateAreaAsync(area, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Move", "Area", area.Id.ToString(), area.Name, area, cancellationToken); + await _auditService.LogAndSaveAsync(user, "Move", "Area", area.Id.ToString(), area.Name, area, cancellationToken); return Result.Success(area); } @@ -218,7 +218,7 @@ public class AreaService await _repository.DeleteAreaAsync(areaId, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Delete", "Area", areaId.ToString(), area.Name, null, cancellationToken); + await _auditService.LogAndSaveAsync(user, "Delete", "Area", areaId.ToString(), area.Name, null, cancellationToken); return Result.Success(true); } diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs index 39e5be85..76d8ec35 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs @@ -11,6 +11,9 @@ namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Services; /// /// Instance CRUD operations. +/// Every mutation audits with AFTER its own save +/// (code review 2026-12-02 TPL-3): a staged-only LogAsync row was lost whenever the +/// caller — the management/CLI path — did not happen to save again. /// - Create instance from template at site /// - Assign to area /// - Override non-locked attribute values @@ -99,7 +102,7 @@ public class InstanceService try { await _repository.SaveChangesAsync(cancellationToken); } catch (InstanceNameConflictException ex) { return Result.Failure(ex.Message); } - await _auditService.LogAsync(user, "Create", "Instance", instance.Id.ToString(), + await _auditService.LogAndSaveAsync(user, "Create", "Instance", instance.Id.ToString(), uniqueName, instance, cancellationToken); return Result.Success(instance); @@ -136,7 +139,7 @@ public class InstanceService await _repository.UpdateInstanceAsync(instance, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "AssignArea", "Instance", instance.Id.ToString(), + await _auditService.LogAndSaveAsync(user, "AssignArea", "Instance", instance.Id.ToString(), instance.UniqueName, instance, cancellationToken); return Result.Success(instance); @@ -187,7 +190,7 @@ public class InstanceService await _repository.UpdateInstanceAttributeOverrideAsync(existingOverride, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "UpdateOverride", "InstanceAttributeOverride", + await _auditService.LogAndSaveAsync(user, "UpdateOverride", "InstanceAttributeOverride", existingOverride.Id.ToString(), attributeName, existingOverride, cancellationToken); return Result.Success(existingOverride); @@ -204,7 +207,7 @@ public class InstanceService await _repository.AddInstanceAttributeOverrideAsync(newOverride, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "CreateOverride", "InstanceAttributeOverride", + await _auditService.LogAndSaveAsync(user, "CreateOverride", "InstanceAttributeOverride", newOverride.Id.ToString(), attributeName, newOverride, cancellationToken); return Result.Success(newOverride); @@ -272,7 +275,7 @@ public class InstanceService await _repository.UpdateInstanceAlarmOverrideAsync(existingOverride, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "UpdateAlarmOverride", "InstanceAlarmOverride", + await _auditService.LogAndSaveAsync(user, "UpdateAlarmOverride", "InstanceAlarmOverride", existingOverride.Id.ToString(), alarmCanonicalName, existingOverride, cancellationToken); return Result.Success(existingOverride); @@ -290,7 +293,7 @@ public class InstanceService await _repository.AddInstanceAlarmOverrideAsync(newOverride, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "CreateAlarmOverride", "InstanceAlarmOverride", + await _auditService.LogAndSaveAsync(user, "CreateAlarmOverride", "InstanceAlarmOverride", newOverride.Id.ToString(), alarmCanonicalName, newOverride, cancellationToken); return Result.Success(newOverride); @@ -320,7 +323,7 @@ public class InstanceService await _repository.DeleteInstanceAlarmOverrideAsync(existing.Id, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "DeleteAlarmOverride", "InstanceAlarmOverride", + await _auditService.LogAndSaveAsync(user, "DeleteAlarmOverride", "InstanceAlarmOverride", existing.Id.ToString(), alarmCanonicalName, existing, cancellationToken); return Result.Success(true); @@ -373,7 +376,7 @@ public class InstanceService await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "SetConnectionBindings", "Instance", + await _auditService.LogAndSaveAsync(user, "SetConnectionBindings", "Instance", instance.Id.ToString(), instance.UniqueName, bindings, cancellationToken); return Result>.Success(results); @@ -396,7 +399,7 @@ public class InstanceService await _repository.UpdateInstanceAsync(instance, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Enable", "Instance", instance.Id.ToString(), + await _auditService.LogAndSaveAsync(user, "Enable", "Instance", instance.Id.ToString(), instance.UniqueName, instance, cancellationToken); return Result.Success(instance); @@ -419,7 +422,7 @@ public class InstanceService await _repository.UpdateInstanceAsync(instance, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Disable", "Instance", instance.Id.ToString(), + await _auditService.LogAndSaveAsync(user, "Disable", "Instance", instance.Id.ToString(), instance.UniqueName, instance, cancellationToken); return Result.Success(instance); @@ -441,7 +444,7 @@ public class InstanceService await _repository.DeleteInstanceAsync(instanceId, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Delete", "Instance", instanceId.ToString(), + await _auditService.LogAndSaveAsync(user, "Delete", "Instance", instanceId.ToString(), instance.UniqueName, null, cancellationToken); return Result.Success(true); diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/SiteService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/SiteService.cs index 8ed913bf..e8fac2d2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/SiteService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/SiteService.cs @@ -51,7 +51,7 @@ public class SiteService await _repository.AddSiteAsync(site, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Create", "Site", site.Id.ToString(), name, site, cancellationToken); + await _auditService.LogAndSaveAsync(user, "Create", "Site", site.Id.ToString(), name, site, cancellationToken); return Result.Success(site); } @@ -76,7 +76,7 @@ public class SiteService await _repository.UpdateSiteAsync(site, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Update", "Site", site.Id.ToString(), name, site, cancellationToken); + await _auditService.LogAndSaveAsync(user, "Update", "Site", site.Id.ToString(), name, site, cancellationToken); return Result.Success(site); } @@ -104,7 +104,7 @@ public class SiteService await _repository.DeleteSiteAsync(siteId, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Delete", "Site", siteId.ToString(), site.Name, null, cancellationToken); + await _auditService.LogAndSaveAsync(user, "Delete", "Site", siteId.ToString(), site.Name, null, cancellationToken); return Result.Success(true); } @@ -144,7 +144,7 @@ public class SiteService await _repository.DeleteDataConnectionAsync(connectionId, cancellationToken); await _repository.SaveChangesAsync(cancellationToken); - await _auditService.LogAsync(user, "Delete", "DataConnection", + await _auditService.LogAndSaveAsync(user, "Delete", "DataConnection", connectionId.ToString(), connection.Name, null, cancellationToken); return Result.Success(true); diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/AuditServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/AuditServiceTests.cs index 237dd1be..18981f8c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/AuditServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/AuditServiceTests.cs @@ -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) ---- + + /// + /// LogAndSaveAsync 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. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task LogAndSaveAsync_PersistsRow_WithoutACallerSave() + { + await _auditService.LogAndSaveAsync("admin", "Disable", "Instance", "42", "Pump1", new { State = "Disabled" }); + + var options = new DbContextOptionsBuilder() + .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); + } + + /// + /// Contrast pin: LogAsync alone only stages the row; nothing reaches the database + /// until someone saves. This is the hazard LogAndSaveAsync exists for. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task LogAsync_WithoutSave_LeavesNoRow() + { + await _auditService.LogAsync("admin", "Disable", "Instance", "42", "Pump1", null); + + var options = new DbContextOptionsBuilder() + .UseSqlite(_context.Database.GetDbConnection()) + .Options; + await using var reader = new ScadaBridgeDbContext(options); + Assert.Empty(await reader.AuditLogEntries.ToListAsync()); + } + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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); + } + + /// A cancelled token is also swallowed: audit never faults the caller. + /// A task that represents the asynchronous operation. + [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); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/ArtifactDeploymentServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/ArtifactDeploymentServiceTests.cs index 2553a428..20d633a0 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/ArtifactDeploymentServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/ArtifactDeploymentServiceTests.cs @@ -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(), "retry-site", Arg.Any(), Arg.Any()); } @@ -406,6 +406,83 @@ public class ArtifactDeploymentServiceTests : TestKit await _siteRepo.Received(1).SaveChangesAsync(Arg.Any()); } + // ── Real-context audit durability (code review 2026-12-02 DEP-1) ── + + /// + /// Deploy Artifacts leaves a persisted DeployArtifacts 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. + /// + /// Whether the stamp's save throws. + /// A task that represents the asynchronous operation. + [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()).Returns(new List { site }); + if (stampSaveFails) + { + _siteRepo.SaveChangesAsync(Arg.Any()) + .Returns(_ => 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); + } + + /// + /// A retry refused for a missing secret sends nothing and returns failure; nothing saves + /// after the audit call on that path, so the DeploySiteSecrets row used to be lost. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RetryForSiteAsync_MissingSecret_SecretsAuditRowIsPersisted() + { + using var db = new RealAuditDatabase(); + _siteRepo.GetDataConnectionsBySiteIdAsync(7, Arg.Any()) + .Returns(new List + { + 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); + } + + /// A successful retry persists its RetryArtifactDeployment row. + /// A task that represents the asynchronous operation. + [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"); + } + /// Verifies that a failed site keeps its previous artifact stamp. /// A task that represents the asynchronous operation. [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(), "DeploySiteSecrets", Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } @@ -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(), "DeploySiteSecrets", Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())) .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(), "DeploySiteSecrets", Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())) .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(), "DeploySiteSecrets", Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())) .Do(ci => @@ -1206,7 +1283,7 @@ public class ArtifactDeploymentServiceTests : TestKit } private ArtifactDeploymentService CreateServiceWithCommActor( - IActorRef commActor, ILogger? logger = null) + IActorRef commActor, ILogger? 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(), "DeploySiteSecrets", Arg.Any(), "sec-site", Arg.Any(), Arg.Any(), Arg.Any())) .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(), Arg.Any(), Arg.Any()); } @@ -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(), "DeploySiteSecrets", Arg.Any(), "site-1", Arg.Any(), Arg.Any(), Arg.Any())) .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(), "DeploySiteSecrets", Arg.Any(), "site-1", Arg.Any(), Arg.Any(), Arg.Any())) .Do(ci => audited = ci[5]); diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceFailurePathTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceFailurePathTests.cs index bd8f06aa..53016e05 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceFailurePathTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceFailurePathTests.cs @@ -141,9 +141,9 @@ public class DeploymentServiceFailurePathTests : TestKit await _repo.DidNotReceive().AddDeployedSnapshotAsync(Arg.Any(), Arg.Any()); await _repo.DidNotReceive().UpdateDeployedSnapshotAsync(Arg.Any(), Arg.Any()); // 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(), Arg.Any()); - await _audit.DidNotReceive().LogAsync(Arg.Any(), "DeployFailed", Arg.Any(), + await _audit.DidNotReceive().LogAndSaveAsync(Arg.Any(), "DeployFailed", Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } @@ -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(), Arg.Any()); } @@ -285,7 +285,7 @@ public class DeploymentServiceFailurePathTests : TestKit await _repo.DidNotReceive().UpdateInstanceAsync(Arg.Any(), Arg.Any()); await _repo.DidNotReceive().DeleteInstanceAsync(Arg.Any(), Arg.Any()); await _repo.DidNotReceive().SaveChangesAsync(Arg.Any()); - await _audit.Received(1).LogAsync("admin", action.ToString(), "Instance", "20", "LcInst", + await _audit.Received(1).LogAndSaveAsync("admin", action.ToString(), "Instance", "20", "LcInst", Arg.Any(), Arg.Any()); } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceTests.cs index 1bc82507..412156db 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceTests.cs @@ -953,7 +953,7 @@ public class DeploymentServiceTests : TestKit await _service.DeployInstanceAsync(1, "admin"); - await _audit.DidNotReceive().LogAsync( + await _audit.DidNotReceive().LogAndSaveAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } @@ -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(), Arg.Any()); } @@ -999,8 +999,8 @@ public class DeploymentServiceTests : TestKit _repo.GetCurrentDeploymentStatusAsync(52, Arg.Any()) .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(), "Deploy", Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())) .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()); - await _audit.Received().LogAsync( + await _audit.Received().LogAndSaveAsync( "admin", "Disable", "Instance", "51", "DisInst", Arg.Any(), Arg.Any()); } @@ -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()); - await _audit.Received().LogAsync( + await _audit.Received().LogAndSaveAsync( "admin", "Enable", "Instance", "52", "EnInst", Arg.Any(), Arg.Any()); } @@ -1224,11 +1224,78 @@ public class DeploymentServiceTests : TestKit Assert.True(result.IsSuccess); await _repo.Received().DeleteInstanceAsync(53, Arg.Any()); - await _audit.Received().LogAsync( + await _audit.Received().LogAndSaveAsync( "admin", "Delete", "Instance", "53", "DelInst", Arg.Any(), Arg.Any()); } + // ── 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. + + /// Disable, Enable and Delete each leave a persisted audit row. + /// The lifecycle action to run. + /// A task that represents the asynchronous operation. + [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()).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); + } + + /// A single-instance deploy leaves a persisted Deploy audit row. + /// A task that represents the asynchronous operation. + [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()).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); + } + /// Verifies that deploy instance async same instance operation lock serializes concurrent deploys. /// A task that represents the asynchronous operation. [Fact] @@ -1269,7 +1336,7 @@ public class DeploymentServiceTests : TestKit /// the notify-and-fetch fail-fast guard. /// 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(), _pipeline, comms, _lockManager, _audit, + _repo, siteRepo, Substitute.For(), _pipeline, comms, _lockManager, audit ?? _audit, new DiffService(), new RevisionHashService(), new DeploymentStatusNotifier(NullLogger.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(), Arg.Any()); // 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(), Arg.Any()); } @@ -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", diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/RealAuditDatabase.cs b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/RealAuditDatabase.cs new file mode 100644 index 00000000..76d48c3c --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/RealAuditDatabase.cs @@ -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; + +/// +/// A real 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 IAuditService 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. +/// +internal sealed class RealAuditDatabase : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly DbContextOptions _options; + + /// Opens the database and builds the audit service over a fresh context. + public RealAuditDatabase() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + _options = new DbContextOptionsBuilder().UseSqlite(_connection).Options; + Context = new ScadaBridgeDbContext(_options); + Context.Database.EnsureCreated(); + AuditService = new AuditService(Context, new AuditCorrelationContext()); + } + + /// The unit-of-work context the audit service writes through. + public ScadaBridgeDbContext Context { get; } + + /// The real audit service under test. + public AuditService AuditService { get; } + + /// Reads the committed audit rows through an independent context. + /// Every persisted audit row. + public async Task> PersistedRowsAsync() + { + await using var reader = new ScadaBridgeDbContext(_options); + return await reader.AuditLogEntries.AsNoTracking().ToListAsync(); + } + + /// + public void Dispose() + { + Context.Dispose(); + _connection.Dispose(); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests.csproj b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests.csproj index 89006e83..edca32ca 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests.csproj +++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests.csproj @@ -11,6 +11,7 @@ + @@ -24,6 +25,7 @@ + diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ApiKeyCreationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ApiKeyCreationTests.cs index cc6aea59..593ab038 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ApiKeyCreationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ApiKeyCreationTests.cs @@ -80,7 +80,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable actor.Tell(Envelope(new CreateApiKeyCommand("MES-Production", new[] { "MethodA" }), "Administrator")); ExpectMsg(TimeSpan.FromSeconds(5)); - _auditService.Received(1).LogAsync( + _auditService.Received(1).LogAndSaveAsync( "admin", "Create", "ApiKey", Arg.Any(), "MES-Production", Arg.Any()); } @@ -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(), Arg.Any()); } @@ -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(), Arg.Any()); } @@ -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(), "Update", "ApiKey", Arg.Any(), Arg.Any(), Arg.Any()); } @@ -218,7 +218,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable var response = ExpectMsg(TimeSpan.FromSeconds(5)); Assert.Contains("key-unknown", response.Error); - _auditService.DidNotReceive().LogAsync( + _auditService.DidNotReceive().LogAndSaveAsync( Arg.Any(), "Update", "ApiKey", Arg.Any(), Arg.Any(), Arg.Any()); } @@ -232,7 +232,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable var response = ExpectMsg(TimeSpan.FromSeconds(5)); Assert.Contains("key-unknown", response.Error); - _auditService.DidNotReceive().LogAsync( + _auditService.DidNotReceive().LogAndSaveAsync( Arg.Any(), "Delete", "ApiKey", Arg.Any(), Arg.Any(), Arg.Any()); } @@ -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(), "Create", "ApiKey", Arg.Any(), Arg.Any(), Arg.Any()); } @@ -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(), "Update", "ApiKey", Arg.Any(), Arg.Any(), Arg.Any()); } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs index a754a4f9..19cf6adc 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs @@ -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(), "Pump1", + Arg.Any(), Arg.Any()); + _auditService.DidNotReceive().LogAsync( + Arg.Any(), "Create", "Instance", Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any()); } /// Verifies that set native alarm source override, when on locked source, returns management error. @@ -5280,7 +5289,8 @@ public class ManagementActorTests : TestKit, IDisposable siteRepo.Received(1).UpdateDataConnectionAsync( Arg.Is(c => c.Id == 5 && c.SiteId == 2), Arg.Any()); - _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(), Arg.Any()); } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementAuditDurabilityTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementAuditDurabilityTests.cs new file mode 100644 index 00000000..a983915d --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementAuditDurabilityTests.cs @@ -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; + +/// +/// 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); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/RealAuditDatabase.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/RealAuditDatabase.cs new file mode 100644 index 00000000..592b412c --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/RealAuditDatabase.cs @@ -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; + +/// +/// A real 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 IAuditService 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. +/// +internal sealed class RealAuditDatabase : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly DbContextOptions _options; + + /// Opens the database and builds the audit service over a fresh context. + public RealAuditDatabase() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + _options = new DbContextOptionsBuilder().UseSqlite(_connection).Options; + Context = new ScadaBridgeDbContext(_options); + Context.Database.EnsureCreated(); + AuditService = new AuditService(Context, new AuditCorrelationContext()); + } + + /// The unit-of-work context the audit service writes through. + public ScadaBridgeDbContext Context { get; } + + /// The real audit service under test. + public AuditService AuditService { get; } + + /// Reads the committed audit rows through an independent context. + /// Every persisted audit row. + public async Task> PersistedRowsAsync() + { + await using var reader = new ScadaBridgeDbContext(_options); + return await reader.AuditLogEntries.AsNoTracking().ToListAsync(); + } + + /// + public void Dispose() + { + Context.Dispose(); + _connection.Dispose(); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SchemaLibraryHandlerTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SchemaLibraryHandlerTests.cs index ee361f20..8256eb19 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SchemaLibraryHandlerTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SchemaLibraryHandlerTests.cs @@ -334,9 +334,10 @@ public class SchemaLibraryHandlerTests : TestKit, IDisposable actor.Tell(envelope); ExpectMsg(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(), "Delete", "SharedSchema", "5", "Addr", Arg.Any(), Arg.Any()); } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests.csproj b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests.csproj index e0f8673e..51ce73e4 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests.csproj +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests.csproj @@ -13,6 +13,7 @@ + @@ -24,6 +25,7 @@ + diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/RealAuditDatabase.cs b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/RealAuditDatabase.cs new file mode 100644 index 00000000..53578800 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/RealAuditDatabase.cs @@ -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; + +/// +/// A real 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 IAuditService 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. +/// +internal sealed class RealAuditDatabase : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly DbContextOptions _options; + + /// Opens the database and builds the audit service over a fresh context. + public RealAuditDatabase() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + _options = new DbContextOptionsBuilder().UseSqlite(_connection).Options; + Context = new ScadaBridgeDbContext(_options); + Context.Database.EnsureCreated(); + AuditService = new AuditService(Context, new AuditCorrelationContext()); + } + + /// The unit-of-work context the audit service writes through. + public ScadaBridgeDbContext Context { get; } + + /// The real audit service under test. + public AuditService AuditService { get; } + + /// Reads the committed audit rows through an independent context. + /// Every persisted audit row. + public async Task> PersistedRowsAsync() + { + await using var reader = new ScadaBridgeDbContext(_options); + return await reader.AuditLogEntries.AsNoTracking().ToListAsync(); + } + + /// + public void Dispose() + { + Context.Dispose(); + _connection.Dispose(); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/AreaServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/AreaServiceTests.cs index f14d7145..71cadcde 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/AreaServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/AreaServiceTests.cs @@ -153,7 +153,7 @@ public class AreaServiceTests Assert.True(result.IsSuccess); Assert.Equal(2, result.Value.ParentAreaId); _repoMock.Verify(r => r.UpdateAreaAsync(It.Is(a => a.Id == 3 && a.ParentAreaId == 2), It.IsAny()), Times.Once); - _auditMock.Verify(a => a.LogAsync("admin", "Move", "Area", "3", "Leaf", It.IsAny(), It.IsAny()), Times.Once); + _auditMock.Verify(a => a.LogAndSaveAsync("admin", "Move", "Area", "3", "Leaf", It.IsAny(), It.IsAny()), Times.Once); } /// Verifies that moving an area to the site root succeeds. @@ -277,7 +277,7 @@ public class AreaServiceTests Assert.True(result.IsSuccess); _repoMock.Verify(r => r.UpdateAreaAsync(It.IsAny(), It.IsAny()), Times.Never); - _auditMock.Verify(a => a.LogAsync(It.IsAny(), "Move", It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + _auditMock.Verify(a => a.LogAndSaveAsync(It.IsAny(), "Move", It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } /// Verifies that moving an area fails when the target parent does not exist. diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceAuditDurabilityTests.cs b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceAuditDurabilityTests.cs new file mode 100644 index 00000000..74e2f3bb --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceAuditDurabilityTests.cs @@ -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; + +/// +/// Code review 2026-12-02 TPL-3: every mutation saved its change +/// and THEN staged its audit row with LogAsync, 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. +/// +public class InstanceServiceAuditDurabilityTests : IDisposable +{ + private readonly Mock _repoMock = new(); + private readonly RealAuditDatabase _db = new(); + private readonly InstanceService _sut; + + /// Builds the service over a mocked repository and a real audit service. + public InstanceServiceAuditDurabilityTests() + { + _repoMock.Setup(r => r.SaveChangesAsync(It.IsAny())).ReturnsAsync(1); + _sut = new InstanceService(_repoMock.Object, _db.AuditService); + } + + /// + public void Dispose() => _db.Dispose(); + + /// Create persists its audit row (the CLI instance create path). + /// A task that represents the asynchronous operation. + [Fact] + public async Task CreateInstance_AuditRowIsPersisted() + { + _repoMock.Setup(r => r.GetTemplateByIdAsync(1, It.IsAny())) + .ReturnsAsync(new Template("T") { Id = 1 }); + _repoMock.Setup(r => r.GetInstanceByUniqueNameAsync("Inst1", It.IsAny())) + .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)); + } + + /// SetConnectionBindings persists its audit row (the CLI instance set-bindings path). + /// A task that represents the asynchronous operation. + [Fact] + public async Task SetConnectionBindings_AuditRowIsPersisted() + { + _repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny())) + .ReturnsAsync(new Instance("Inst1") { Id = 1 }); + _repoMock.Setup(r => r.GetBindingsByInstanceIdAsync(1, It.IsAny())) + .ReturnsAsync(new List()); + + var result = await _sut.SetConnectionBindingsAsync(1, [new ConnectionBinding("Temp", 100)], "admin"); + + Assert.True(result.IsSuccess); + Assert.Equal("SetConnectionBindings", Assert.Single(await _db.PersistedRowsAsync()).Action); + } + + /// Enable / Disable / Delete each persist their audit row. + /// The audited action. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData("Enable")] + [InlineData("Disable")] + [InlineData("Delete")] + public async Task StateChanges_AuditRowIsPersisted(string action) + { + _repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny())) + .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); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.csproj b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.csproj index 17b38fd2..71fe05df 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.csproj +++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.csproj @@ -10,6 +10,7 @@ + @@ -22,6 +23,7 @@ + \ No newline at end of file