fix(audit): persist config audit rows written after the final save (DEP-1, MGT-1, TPL-3, WP1 task 1.4)
IAuditService.LogAsync only stages the row; every caller that audited after its last SaveChangesAsync, outside the configuration-command transaction, lost the row with the DI scope (rig: zero Disable/Enable/ Delete/DeployArtifacts rows, 16 Deploy rows for 62 deployments, one Create/Instance row for ids up to 3876). - New IAuditService.LogAndSaveAsync: stage + save, best-effort (logs and swallows any failure incl. cancellation, detaches the unsaved row). - DeploymentService (deploy/failed/reconciled/lifecycle + timeouts), ArtifactDeploymentService (DeployArtifacts now before the best-effort stamp, RetryArtifactDeployment, DeploySiteSecrets), InstanceService, AreaService, SiteService: post-save LogAsync -> LogAndSaveAsync. - ManagementActor: AuditAndSaveAsync for the non-configuration handlers (API keys, shared schemas, ES methods, data-connection move); move now audits the scrubbed public shape (MGT-4) so the fix does not start writing protocol credentials into AuditLogEntries. - HandleCreateInstance no longer stages a second Create row on top of InstanceService's own. Tests: real-context (SQLite) tests per family read the row back through a second context - DeploymentService, ArtifactDeploymentService, InstanceService, ManagementActor; each fails against the old code. Test projects gain a ConfigurationDatabase + EF Sqlite reference.
This commit is contained in:
@@ -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:
|
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.
|
- **`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.
|
- **`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.
|
- **`IInstanceLocator`**: Resolves an instance unique name to its site identifier. Used by the Inbound API's `Route.To()` to determine the destination site.
|
||||||
|
|||||||
@@ -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.
|
- 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.
|
- 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
|
### Integration Example
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
|
|||||||
@@ -14,4 +14,27 @@ public interface IAuditService
|
|||||||
/// <param name="cancellationToken">Cancellation token for the log write.</param>
|
/// <param name="cancellationToken">Cancellation token for the log write.</param>
|
||||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
Task LogAsync(string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default);
|
Task LogAsync(string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Use this — not <see cref="LogAsync"/> — wherever the audit call comes AFTER the
|
||||||
|
/// operation's final <c>SaveChangesAsync</c>: <see cref="LogAsync"/> 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.
|
||||||
|
/// </remarks>
|
||||||
|
/// <param name="user">The authenticated username performing the action.</param>
|
||||||
|
/// <param name="action">The action performed (e.g., "Create", "Update", "Delete").</param>
|
||||||
|
/// <param name="entityType">The type name of the affected entity.</param>
|
||||||
|
/// <param name="entityId">The string representation of the entity's primary key.</param>
|
||||||
|
/// <param name="entityName">The display name of the affected entity.</param>
|
||||||
|
/// <param name="afterState">The entity state after the action; may be null for deletes.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the log write.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation; it never faults.</returns>
|
||||||
|
Task LogAndSaveAsync(string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
using System.Text.Json;
|
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.Entities.Audit;
|
||||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
|
||||||
@@ -9,6 +12,7 @@ public class AuditService : IAuditService
|
|||||||
{
|
{
|
||||||
private readonly ScadaBridgeDbContext _context;
|
private readonly ScadaBridgeDbContext _context;
|
||||||
private readonly IAuditCorrelationContext _correlationContext;
|
private readonly IAuditCorrelationContext _correlationContext;
|
||||||
|
private readonly ILogger<AuditService> _logger;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Serializer options for audit <c>afterState</c> payloads. Audit writes commit in the
|
/// Serializer options for audit <c>afterState</c> payloads. Audit writes commit in the
|
||||||
@@ -37,10 +41,15 @@ public class AuditService : IAuditService
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context">The EF Core database context used to stage audit entries.</param>
|
/// <param name="context">The EF Core database context used to stage audit entries.</param>
|
||||||
/// <param name="correlationContext">Provides the active bundle import id for audit row stamping.</param>
|
/// <param name="correlationContext">Provides the active bundle import id for audit row stamping.</param>
|
||||||
public AuditService(ScadaBridgeDbContext context, IAuditCorrelationContext correlationContext)
|
/// <param name="logger">Logs a failed best-effort <see cref="LogAndSaveAsync"/>; optional.</param>
|
||||||
|
public AuditService(
|
||||||
|
ScadaBridgeDbContext context,
|
||||||
|
IAuditCorrelationContext correlationContext,
|
||||||
|
ILogger<AuditService>? logger = null)
|
||||||
{
|
{
|
||||||
_context = context ?? throw new ArgumentNullException(nameof(context));
|
_context = context ?? throw new ArgumentNullException(nameof(context));
|
||||||
_correlationContext = correlationContext ?? throw new ArgumentNullException(nameof(correlationContext));
|
_correlationContext = correlationContext ?? throw new ArgumentNullException(nameof(correlationContext));
|
||||||
|
_logger = logger ?? NullLogger<AuditService>.Instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@@ -53,7 +62,51 @@ public class AuditService : IAuditService
|
|||||||
object? afterState,
|
object? afterState,
|
||||||
CancellationToken cancellationToken = default)
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
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,
|
Timestamp = DateTimeOffset.UtcNow,
|
||||||
AfterStateJson = afterState != null
|
AfterStateJson = afterState != null
|
||||||
@@ -64,10 +117,6 @@ public class AuditService : IAuditService
|
|||||||
// interactive code path.
|
// interactive code path.
|
||||||
BundleImportId = _correlationContext.BundleImportId
|
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -245,6 +245,11 @@ public class ArtifactDeploymentService
|
|||||||
/// error — never <see cref="SecretArtifact.Ciphertext"/>, <c>Nonce</c>, <c>Tag</c>,
|
/// error — never <see cref="SecretArtifact.Ciphertext"/>, <c>Nonce</c>, <c>Tag</c>,
|
||||||
/// <c>WrappedDek</c>, or any other material (global constraint: never plaintext or material
|
/// <c>WrappedDek</c>, or any other material (global constraint: never plaintext or material
|
||||||
/// in logs or audit rows).
|
/// in logs or audit rows).
|
||||||
|
///
|
||||||
|
/// The row is saved here (<see cref="IAuditService.LogAndSaveAsync"/>, 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).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private Task LogSecretsAuditAsync(
|
private Task LogSecretsAuditAsync(
|
||||||
string user,
|
string user,
|
||||||
@@ -269,7 +274,7 @@ public class ArtifactDeploymentService
|
|||||||
if (!hasSecretRefs)
|
if (!hasSecretRefs)
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
|
|
||||||
return _auditService.LogAsync(
|
return _auditService.LogAndSaveAsync(
|
||||||
user, "DeploySiteSecrets", "SiteSecrets", siteIdentifier, siteName,
|
user, "DeploySiteSecrets", "SiteSecrets", siteIdentifier, siteName,
|
||||||
new
|
new
|
||||||
{
|
{
|
||||||
@@ -596,6 +601,22 @@ public class ArtifactDeploymentService
|
|||||||
// Only sites whose deploy SUCCEEDED are stamped. A failed site is deliberately
|
// 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
|
// left untouched so it keeps its previous stamp (or none at all) and keeps
|
||||||
// reading "out of date" on the Sites page.
|
// 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
|
var successfulSites = sites
|
||||||
.Where(site => perSiteResults.TryGetValue(site.SiteIdentifier, out var r) && r.Success)
|
.Where(site => perSiteResults.TryGetValue(site.SiteIdentifier, out var r) && r.Success)
|
||||||
.ToList();
|
.ToList();
|
||||||
@@ -606,17 +627,6 @@ public class ArtifactDeploymentService
|
|||||||
cancellationToken);
|
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<ArtifactDeploymentSummary>.Success(summary);
|
return Result<ArtifactDeploymentSummary>.Success(summary);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -682,7 +692,9 @@ public class ArtifactDeploymentService
|
|||||||
// returned Result — an old site's/partial site's reply must not read as success.
|
// returned Result — an old site's/partial site's reply must not read as success.
|
||||||
var result = ReconcileSecretsOutcome(command, response, siteIdentifier, siteIdentifier);
|
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);
|
command.DeploymentId, siteIdentifier, new { result.Success }, cancellationToken);
|
||||||
|
|
||||||
// Ordering rule: audit before the best-effort stamp.
|
// Ordering rule: audit before the best-effort stamp.
|
||||||
|
|||||||
@@ -2328,7 +2328,9 @@ public class DeploymentService
|
|||||||
// who issued the original timed-out / stuck deployment. The original
|
// who issued the original timed-out / stuck deployment. The original
|
||||||
// deployer is preserved in the detail object so forensics can still
|
// deployer is preserved in the detail object so forensics can still
|
||||||
// see who launched the run that reconciliation rescued.
|
// 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,
|
instance.Id.ToString(), instance.UniqueName,
|
||||||
new
|
new
|
||||||
{
|
{
|
||||||
@@ -2522,6 +2524,11 @@ public class DeploymentService
|
|||||||
/// must NEVER surface to the caller or flip the committed status — "audit-write
|
/// must NEVER surface to the caller or flip the committed status — "audit-write
|
||||||
/// failure NEVER aborts the user-facing action" (Centralized Audit Log design).
|
/// failure NEVER aborts the user-facing action" (Centralized Audit Log design).
|
||||||
/// Any exception is swallowed and logged at Warning.
|
/// Any exception is swallowed and logged at Warning.
|
||||||
|
/// <para>
|
||||||
|
/// Every caller runs this AFTER its final <c>SaveChangesAsync</c>, so the row must be
|
||||||
|
/// saved here (<see cref="IAuditService.LogAndSaveAsync"/>): a staged-only
|
||||||
|
/// <c>LogAsync</c> row was discarded with the DI scope (code review 2026-12-02 DEP-1).
|
||||||
|
/// </para>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task TryLogAuditAsync(
|
private async Task TryLogAuditAsync(
|
||||||
string user,
|
string user,
|
||||||
@@ -2534,7 +2541,7 @@ public class DeploymentService
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await _auditService.LogAsync(
|
await _auditService.LogAndSaveAsync(
|
||||||
user, action, entityType, entityId, entityName, afterState, cancellationToken);
|
user, action, entityType, entityId, entityName, afterState, cancellationToken);
|
||||||
}
|
}
|
||||||
catch (Exception auditEx)
|
catch (Exception auditEx)
|
||||||
@@ -2556,7 +2563,8 @@ public class DeploymentService
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await _auditService.LogAsync(
|
// Post-save, like TryLogAuditAsync: persist the row here (DEP-1).
|
||||||
|
await _auditService.LogAndSaveAsync(
|
||||||
user,
|
user,
|
||||||
action,
|
action,
|
||||||
"Instance",
|
"Instance",
|
||||||
|
|||||||
@@ -737,6 +737,22 @@ public class ManagementActor : ReceiveActor
|
|||||||
await auditService.LogAsync(user, action, entityType, entityId, entityName, afterState);
|
await auditService.LogAsync(user, action, entityType, entityId, entityName, afterState);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Logs AND persists an audit entry, best-effort, for a handler that is NOT a
|
||||||
|
/// configuration command (code review 2026-12-02 MGT-1).
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <see cref="AuditAsync"/> only stages the row; for a command in
|
||||||
|
/// <see cref="IsConfigurationCommand"/> the <c>ConfigurationCommandTransaction</c>'s final
|
||||||
|
/// save flushes it. A command outside that list runs through plain
|
||||||
|
/// <c>DispatchCommand</c> 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.
|
||||||
|
/// </remarks>
|
||||||
|
private static Task AuditAndSaveAsync(IServiceProvider sp, string user, string action, string entityType, string entityId, string entityName, object? afterState) =>
|
||||||
|
sp.GetRequiredService<IAuditService>().LogAndSaveAsync(user, action, entityType, entityId, entityName, afterState);
|
||||||
|
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
// Template handlers
|
// Template handlers
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
@@ -1027,7 +1043,9 @@ public class ManagementActor : ReceiveActor
|
|||||||
var svc = sp.GetRequiredService<InstanceService>();
|
var svc = sp.GetRequiredService<InstanceService>();
|
||||||
var result = await svc.CreateInstanceAsync(cmd.UniqueName, cmd.TemplateId, cmd.SiteId, cmd.AreaId, user.Username);
|
var result = await svc.CreateInstanceAsync(cmd.UniqueName, cmd.TemplateId, cmd.SiteId, cmd.AreaId, user.Username);
|
||||||
if (!result.IsSuccess) throw new ManagementCommandException(result.Error);
|
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;
|
return result.Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2378,7 +2396,10 @@ public class ManagementActor : ReceiveActor
|
|||||||
conn.SiteId = cmd.TargetSiteId;
|
conn.SiteId = cmd.TargetSiteId;
|
||||||
await repo.UpdateDataConnectionAsync(conn);
|
await repo.UpdateDataConnectionAsync(conn);
|
||||||
await repo.SaveChangesAsync();
|
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;
|
return conn;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2520,7 +2541,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
await repo.AddExternalSystemMethodAsync(method);
|
await repo.AddExternalSystemMethodAsync(method);
|
||||||
await repo.SaveChangesAsync();
|
await repo.SaveChangesAsync();
|
||||||
await InvalidateExternalDefinitionCacheAfterCommit(sp);
|
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;
|
return method;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2537,7 +2558,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
await repo.UpdateExternalSystemMethodAsync(method);
|
await repo.UpdateExternalSystemMethodAsync(method);
|
||||||
await repo.SaveChangesAsync();
|
await repo.SaveChangesAsync();
|
||||||
await InvalidateExternalDefinitionCacheAfterCommit(sp);
|
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;
|
return method;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2547,7 +2568,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
await repo.DeleteExternalSystemMethodAsync(cmd.MethodId);
|
await repo.DeleteExternalSystemMethodAsync(cmd.MethodId);
|
||||||
await repo.SaveChangesAsync();
|
await repo.SaveChangesAsync();
|
||||||
await InvalidateExternalDefinitionCacheAfterCommit(sp);
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3031,7 +3052,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
var admin = sp.GetRequiredService<IInboundApiKeyAdmin>();
|
var admin = sp.GetRequiredService<IInboundApiKeyAdmin>();
|
||||||
var created = await admin.CreateAsync(cmd.Name, cmd.Methods);
|
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 });
|
new { created.KeyId, cmd.Name });
|
||||||
|
|
||||||
return new
|
return new
|
||||||
@@ -3048,7 +3069,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
var deleted = await admin.DeleteAsync(cmd.KeyId);
|
var deleted = await admin.DeleteAsync(cmd.KeyId);
|
||||||
if (!deleted)
|
if (!deleted)
|
||||||
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
|
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;
|
return deleted;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3750,7 +3771,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
|
|
||||||
var schema = new SharedSchema { Name = name, Scope = cmd.Scope, SchemaJson = cmd.SchemaJson };
|
var schema = new SharedSchema { Name = name, Scope = cmd.Scope, SchemaJson = cmd.SchemaJson };
|
||||||
await repo.AddAsync(schema);
|
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;
|
return schema;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3775,7 +3796,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
schema.Scope = cmd.Scope;
|
schema.Scope = cmd.Scope;
|
||||||
schema.SchemaJson = cmd.SchemaJson;
|
schema.SchemaJson = cmd.SchemaJson;
|
||||||
await repo.UpdateAsync(schema);
|
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;
|
return schema;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3787,7 +3808,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
// Site delete handler. Falls back to the id when the row is already absent.
|
// Site delete handler. Falls back to the id when the row is already absent.
|
||||||
var schema = await repo.GetByIdAsync(cmd.SharedSchemaId);
|
var schema = await repo.GetByIdAsync(cmd.SharedSchemaId);
|
||||||
await repo.DeleteAsync(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);
|
schema?.Name ?? cmd.SharedSchemaId.ToString(), null);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -4100,7 +4121,7 @@ public class ManagementActor : ReceiveActor
|
|||||||
var updated = await admin.SetEnabledAsync(cmd.KeyId, cmd.IsEnabled);
|
var updated = await admin.SetEnabledAsync(cmd.KeyId, cmd.IsEnabled);
|
||||||
if (!updated)
|
if (!updated)
|
||||||
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
|
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 });
|
new { cmd.KeyId, cmd.IsEnabled });
|
||||||
return 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);
|
var updated = await admin.SetMethodsAsync(cmd.KeyId, cmd.Methods);
|
||||||
if (!updated)
|
if (!updated)
|
||||||
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
|
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 });
|
new { cmd.KeyId, cmd.Methods });
|
||||||
return new { cmd.KeyId, Methods = cmd.Methods };
|
return new { cmd.KeyId, Methods = cmd.Methods };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ public class AreaService
|
|||||||
await _repository.AddAreaAsync(area, cancellationToken);
|
await _repository.AddAreaAsync(area, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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<Area>.Success(area);
|
return Result<Area>.Success(area);
|
||||||
}
|
}
|
||||||
@@ -107,7 +107,7 @@ public class AreaService
|
|||||||
await _repository.UpdateAreaAsync(area, cancellationToken);
|
await _repository.UpdateAreaAsync(area, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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<Area>.Success(area);
|
return Result<Area>.Success(area);
|
||||||
}
|
}
|
||||||
@@ -167,7 +167,7 @@ public class AreaService
|
|||||||
await _repository.UpdateAreaAsync(area, cancellationToken);
|
await _repository.UpdateAreaAsync(area, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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<Area>.Success(area);
|
return Result<Area>.Success(area);
|
||||||
}
|
}
|
||||||
@@ -218,7 +218,7 @@ public class AreaService
|
|||||||
await _repository.DeleteAreaAsync(areaId, cancellationToken);
|
await _repository.DeleteAreaAsync(areaId, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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<bool>.Success(true);
|
return Result<bool>.Success(true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Services;
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Instance CRUD operations.
|
/// Instance CRUD operations.
|
||||||
|
/// Every mutation audits with <see cref="IAuditService.LogAndSaveAsync"/> AFTER its own save
|
||||||
|
/// (code review 2026-12-02 TPL-3): a staged-only <c>LogAsync</c> row was lost whenever the
|
||||||
|
/// caller — the management/CLI path — did not happen to save again.
|
||||||
/// - Create instance from template at site
|
/// - Create instance from template at site
|
||||||
/// - Assign to area
|
/// - Assign to area
|
||||||
/// - Override non-locked attribute values
|
/// - Override non-locked attribute values
|
||||||
@@ -99,7 +102,7 @@ public class InstanceService
|
|||||||
try { await _repository.SaveChangesAsync(cancellationToken); }
|
try { await _repository.SaveChangesAsync(cancellationToken); }
|
||||||
catch (InstanceNameConflictException ex) { return Result<Instance>.Failure(ex.Message); }
|
catch (InstanceNameConflictException ex) { return Result<Instance>.Failure(ex.Message); }
|
||||||
|
|
||||||
await _auditService.LogAsync(user, "Create", "Instance", instance.Id.ToString(),
|
await _auditService.LogAndSaveAsync(user, "Create", "Instance", instance.Id.ToString(),
|
||||||
uniqueName, instance, cancellationToken);
|
uniqueName, instance, cancellationToken);
|
||||||
|
|
||||||
return Result<Instance>.Success(instance);
|
return Result<Instance>.Success(instance);
|
||||||
@@ -136,7 +139,7 @@ public class InstanceService
|
|||||||
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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);
|
instance.UniqueName, instance, cancellationToken);
|
||||||
|
|
||||||
return Result<Instance>.Success(instance);
|
return Result<Instance>.Success(instance);
|
||||||
@@ -187,7 +190,7 @@ public class InstanceService
|
|||||||
await _repository.UpdateInstanceAttributeOverrideAsync(existingOverride, cancellationToken);
|
await _repository.UpdateInstanceAttributeOverrideAsync(existingOverride, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(cancellationToken);
|
await _repository.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await _auditService.LogAsync(user, "UpdateOverride", "InstanceAttributeOverride",
|
await _auditService.LogAndSaveAsync(user, "UpdateOverride", "InstanceAttributeOverride",
|
||||||
existingOverride.Id.ToString(), attributeName, existingOverride, cancellationToken);
|
existingOverride.Id.ToString(), attributeName, existingOverride, cancellationToken);
|
||||||
|
|
||||||
return Result<InstanceAttributeOverride>.Success(existingOverride);
|
return Result<InstanceAttributeOverride>.Success(existingOverride);
|
||||||
@@ -204,7 +207,7 @@ public class InstanceService
|
|||||||
await _repository.AddInstanceAttributeOverrideAsync(newOverride, cancellationToken);
|
await _repository.AddInstanceAttributeOverrideAsync(newOverride, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(cancellationToken);
|
await _repository.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await _auditService.LogAsync(user, "CreateOverride", "InstanceAttributeOverride",
|
await _auditService.LogAndSaveAsync(user, "CreateOverride", "InstanceAttributeOverride",
|
||||||
newOverride.Id.ToString(), attributeName, newOverride, cancellationToken);
|
newOverride.Id.ToString(), attributeName, newOverride, cancellationToken);
|
||||||
|
|
||||||
return Result<InstanceAttributeOverride>.Success(newOverride);
|
return Result<InstanceAttributeOverride>.Success(newOverride);
|
||||||
@@ -272,7 +275,7 @@ public class InstanceService
|
|||||||
await _repository.UpdateInstanceAlarmOverrideAsync(existingOverride, cancellationToken);
|
await _repository.UpdateInstanceAlarmOverrideAsync(existingOverride, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(cancellationToken);
|
await _repository.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await _auditService.LogAsync(user, "UpdateAlarmOverride", "InstanceAlarmOverride",
|
await _auditService.LogAndSaveAsync(user, "UpdateAlarmOverride", "InstanceAlarmOverride",
|
||||||
existingOverride.Id.ToString(), alarmCanonicalName, existingOverride, cancellationToken);
|
existingOverride.Id.ToString(), alarmCanonicalName, existingOverride, cancellationToken);
|
||||||
|
|
||||||
return Result<InstanceAlarmOverride>.Success(existingOverride);
|
return Result<InstanceAlarmOverride>.Success(existingOverride);
|
||||||
@@ -290,7 +293,7 @@ public class InstanceService
|
|||||||
await _repository.AddInstanceAlarmOverrideAsync(newOverride, cancellationToken);
|
await _repository.AddInstanceAlarmOverrideAsync(newOverride, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(cancellationToken);
|
await _repository.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await _auditService.LogAsync(user, "CreateAlarmOverride", "InstanceAlarmOverride",
|
await _auditService.LogAndSaveAsync(user, "CreateAlarmOverride", "InstanceAlarmOverride",
|
||||||
newOverride.Id.ToString(), alarmCanonicalName, newOverride, cancellationToken);
|
newOverride.Id.ToString(), alarmCanonicalName, newOverride, cancellationToken);
|
||||||
|
|
||||||
return Result<InstanceAlarmOverride>.Success(newOverride);
|
return Result<InstanceAlarmOverride>.Success(newOverride);
|
||||||
@@ -320,7 +323,7 @@ public class InstanceService
|
|||||||
await _repository.DeleteInstanceAlarmOverrideAsync(existing.Id, cancellationToken);
|
await _repository.DeleteInstanceAlarmOverrideAsync(existing.Id, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(cancellationToken);
|
await _repository.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await _auditService.LogAsync(user, "DeleteAlarmOverride", "InstanceAlarmOverride",
|
await _auditService.LogAndSaveAsync(user, "DeleteAlarmOverride", "InstanceAlarmOverride",
|
||||||
existing.Id.ToString(), alarmCanonicalName, existing, cancellationToken);
|
existing.Id.ToString(), alarmCanonicalName, existing, cancellationToken);
|
||||||
|
|
||||||
return Result<bool>.Success(true);
|
return Result<bool>.Success(true);
|
||||||
@@ -373,7 +376,7 @@ public class InstanceService
|
|||||||
|
|
||||||
await _repository.SaveChangesAsync(cancellationToken);
|
await _repository.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await _auditService.LogAsync(user, "SetConnectionBindings", "Instance",
|
await _auditService.LogAndSaveAsync(user, "SetConnectionBindings", "Instance",
|
||||||
instance.Id.ToString(), instance.UniqueName, bindings, cancellationToken);
|
instance.Id.ToString(), instance.UniqueName, bindings, cancellationToken);
|
||||||
|
|
||||||
return Result<IReadOnlyList<InstanceConnectionBinding>>.Success(results);
|
return Result<IReadOnlyList<InstanceConnectionBinding>>.Success(results);
|
||||||
@@ -396,7 +399,7 @@ public class InstanceService
|
|||||||
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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);
|
instance.UniqueName, instance, cancellationToken);
|
||||||
|
|
||||||
return Result<Instance>.Success(instance);
|
return Result<Instance>.Success(instance);
|
||||||
@@ -419,7 +422,7 @@ public class InstanceService
|
|||||||
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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);
|
instance.UniqueName, instance, cancellationToken);
|
||||||
|
|
||||||
return Result<Instance>.Success(instance);
|
return Result<Instance>.Success(instance);
|
||||||
@@ -441,7 +444,7 @@ public class InstanceService
|
|||||||
await _repository.DeleteInstanceAsync(instanceId, cancellationToken);
|
await _repository.DeleteInstanceAsync(instanceId, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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);
|
instance.UniqueName, null, cancellationToken);
|
||||||
|
|
||||||
return Result<bool>.Success(true);
|
return Result<bool>.Success(true);
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ public class SiteService
|
|||||||
await _repository.AddSiteAsync(site, cancellationToken);
|
await _repository.AddSiteAsync(site, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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<Site>.Success(site);
|
return Result<Site>.Success(site);
|
||||||
}
|
}
|
||||||
@@ -76,7 +76,7 @@ public class SiteService
|
|||||||
await _repository.UpdateSiteAsync(site, cancellationToken);
|
await _repository.UpdateSiteAsync(site, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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<Site>.Success(site);
|
return Result<Site>.Success(site);
|
||||||
}
|
}
|
||||||
@@ -104,7 +104,7 @@ public class SiteService
|
|||||||
await _repository.DeleteSiteAsync(siteId, cancellationToken);
|
await _repository.DeleteSiteAsync(siteId, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(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<bool>.Success(true);
|
return Result<bool>.Success(true);
|
||||||
}
|
}
|
||||||
@@ -144,7 +144,7 @@ public class SiteService
|
|||||||
await _repository.DeleteDataConnectionAsync(connectionId, cancellationToken);
|
await _repository.DeleteDataConnectionAsync(connectionId, cancellationToken);
|
||||||
await _repository.SaveChangesAsync(cancellationToken);
|
await _repository.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await _auditService.LogAsync(user, "Delete", "DataConnection",
|
await _auditService.LogAndSaveAsync(user, "Delete", "DataConnection",
|
||||||
connectionId.ToString(), connection.Name, null, cancellationToken);
|
connectionId.ToString(), connection.Name, null, cancellationToken);
|
||||||
|
|
||||||
return Result<bool>.Success(true);
|
return Result<bool>.Success(true);
|
||||||
|
|||||||
@@ -228,4 +228,74 @@ public class AuditServiceTests : IDisposable
|
|||||||
Assert.True(doc.RootElement.GetProperty("AuditTruncated").GetBoolean());
|
Assert.True(doc.RootElement.GetProperty("AuditTruncated").GetBoolean());
|
||||||
Assert.True(doc.RootElement.GetProperty("OriginalLength").GetInt32() > AuditService.MaxAfterStateChars);
|
Assert.True(doc.RootElement.GetProperty("OriginalLength").GetInt32() > AuditService.MaxAfterStateChars);
|
||||||
}
|
}
|
||||||
|
// ---- LogAndSaveAsync (code review 2026-12-02 DEP-1 / MGT-1 / TPL-3) ----
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>LogAndSaveAsync</c> persists the row itself: a caller that has already done its
|
||||||
|
/// final save (the DEP-1/MGT-1/TPL-3 shape) no longer loses the staged row when the
|
||||||
|
/// scope is disposed. Read back through a second context on the same connection.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task LogAndSaveAsync_PersistsRow_WithoutACallerSave()
|
||||||
|
{
|
||||||
|
await _auditService.LogAndSaveAsync("admin", "Disable", "Instance", "42", "Pump1", new { State = "Disabled" });
|
||||||
|
|
||||||
|
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||||
|
.UseSqlite(_context.Database.GetDbConnection())
|
||||||
|
.Options;
|
||||||
|
await using var reader = new ScadaBridgeDbContext(options);
|
||||||
|
var row = await reader.AuditLogEntries.SingleAsync();
|
||||||
|
Assert.Equal("Disable", row.Action);
|
||||||
|
Assert.Equal("Pump1", row.EntityName);
|
||||||
|
Assert.DoesNotContain(_context.ChangeTracker.Entries(), e => e.State != EntityState.Unchanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contrast pin: <c>LogAsync</c> alone only stages the row; nothing reaches the database
|
||||||
|
/// until someone saves. This is the hazard <c>LogAndSaveAsync</c> exists for.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task LogAsync_WithoutSave_LeavesNoRow()
|
||||||
|
{
|
||||||
|
await _auditService.LogAsync("admin", "Disable", "Instance", "42", "Pump1", null);
|
||||||
|
|
||||||
|
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||||
|
.UseSqlite(_context.Database.GetDbConnection())
|
||||||
|
.Options;
|
||||||
|
await using var reader = new ScadaBridgeDbContext(options);
|
||||||
|
Assert.Empty(await reader.AuditLogEntries.ToListAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Best-effort: a failing save is swallowed (never thrown to the caller) and the unsaved
|
||||||
|
/// row is detached, so it cannot fail — or be silently written by — a later save.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task LogAndSaveAsync_SaveFails_DoesNotThrow_AndDetachesTheRow()
|
||||||
|
{
|
||||||
|
await _context.Database.ExecuteSqlRawAsync("DROP TABLE AuditLogEntries;");
|
||||||
|
|
||||||
|
var ex = await Record.ExceptionAsync(() =>
|
||||||
|
_auditService.LogAndSaveAsync("admin", "Delete", "Instance", "7", "Gone", null));
|
||||||
|
|
||||||
|
Assert.Null(ex);
|
||||||
|
Assert.DoesNotContain(_context.ChangeTracker.Entries(), e => e.Entity is ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit.AuditLogEntry);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A cancelled token is also swallowed: audit never faults the caller.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task LogAndSaveAsync_Cancelled_DoesNotThrow()
|
||||||
|
{
|
||||||
|
using var cts = new CancellationTokenSource();
|
||||||
|
await cts.CancelAsync();
|
||||||
|
|
||||||
|
var ex = await Record.ExceptionAsync(() =>
|
||||||
|
_auditService.LogAndSaveAsync("admin", "Delete", "Instance", "7", "Gone", null, cts.Token));
|
||||||
|
|
||||||
|
Assert.Null(ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+88
-11
@@ -337,7 +337,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
Assert.Equal("retry-site", result.Value.SiteId);
|
Assert.Equal("retry-site", result.Value.SiteId);
|
||||||
await _audit.Received().LogAsync(
|
await _audit.Received().LogAndSaveAsync(
|
||||||
"admin", "RetryArtifactDeployment", "SystemArtifact",
|
"admin", "RetryArtifactDeployment", "SystemArtifact",
|
||||||
Arg.Any<string>(), "retry-site", Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<string>(), "retry-site", Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
@@ -406,6 +406,83 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
await _siteRepo.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
await _siteRepo.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Real-context audit durability (code review 2026-12-02 DEP-1) ──
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Deploy Artifacts leaves a persisted <c>DeployArtifacts</c> row (the rig had 71 records
|
||||||
|
/// and zero rows: the row was staged after the stamp's save and never written), even when
|
||||||
|
/// the best-effort stamp save then fails.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="stampSaveFails">Whether the stamp's save throws.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Theory]
|
||||||
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public async Task DeployToAllSitesAsync_DeployArtifactsAuditRowIsPersisted(bool stampSaveFails)
|
||||||
|
{
|
||||||
|
using var db = new RealAuditDatabase();
|
||||||
|
var site = new Site("Site One", "site-1") { Id = 1 };
|
||||||
|
_siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site> { site });
|
||||||
|
if (stampSaveFails)
|
||||||
|
{
|
||||||
|
_siteRepo.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||||
|
.Returns<int>(_ => throw new InvalidOperationException("db down"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var recorder = new ArtifactProbeRecorder();
|
||||||
|
var probe = Sys.ActorOf(Props.Create(() => new ArtifactProbeActor(recorder)));
|
||||||
|
var service = CreateServiceWithCommActor(probe, audit: db.AuditService);
|
||||||
|
|
||||||
|
var result = await service.DeployToAllSitesAsync("admin");
|
||||||
|
|
||||||
|
Assert.True(result.IsSuccess);
|
||||||
|
var row = Assert.Single(await db.PersistedRowsAsync(), r => r.Action == "DeployArtifacts");
|
||||||
|
Assert.Equal(result.Value.DeploymentId, row.EntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A retry refused for a missing secret sends nothing and returns failure; nothing saves
|
||||||
|
/// after the audit call on that path, so the <c>DeploySiteSecrets</c> row used to be lost.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task RetryForSiteAsync_MissingSecret_SecretsAuditRowIsPersisted()
|
||||||
|
{
|
||||||
|
using var db = new RealAuditDatabase();
|
||||||
|
_siteRepo.GetDataConnectionsBySiteIdAsync(7, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(new List<DataConnection>
|
||||||
|
{
|
||||||
|
new("GW1", "MxGateway", 7) { PrimaryConfiguration = """{"ApiKey":"secret:missing-key"}""" }
|
||||||
|
});
|
||||||
|
var recorder = new ArtifactProbeRecorder();
|
||||||
|
var probe = Sys.ActorOf(Props.Create(() => new ArtifactProbeActor(recorder)));
|
||||||
|
var service = CreateServiceWithCommActor(probe, audit: db.AuditService);
|
||||||
|
|
||||||
|
var result = await service.RetryForSiteAsync(7, "retry-site", "admin");
|
||||||
|
|
||||||
|
Assert.True(result.IsFailure);
|
||||||
|
var row = Assert.Single(await db.PersistedRowsAsync());
|
||||||
|
Assert.Equal("DeploySiteSecrets", row.Action);
|
||||||
|
Assert.Equal("retry-site", row.EntityId);
|
||||||
|
Assert.Contains("missing-key", row.AfterStateJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A successful retry persists its <c>RetryArtifactDeployment</c> row.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task RetryForSiteAsync_SiteSucceeds_RetryAuditRowIsPersisted()
|
||||||
|
{
|
||||||
|
using var db = new RealAuditDatabase();
|
||||||
|
var recorder = new ArtifactProbeRecorder();
|
||||||
|
var probe = Sys.ActorOf(Props.Create(() => new ArtifactProbeActor(recorder)));
|
||||||
|
var service = CreateServiceWithCommActor(probe, audit: db.AuditService);
|
||||||
|
|
||||||
|
var result = await service.RetryForSiteAsync(7, "retry-site", "admin");
|
||||||
|
|
||||||
|
Assert.True(result.IsSuccess, result.IsFailure ? result.Error : null);
|
||||||
|
Assert.Single(await db.PersistedRowsAsync(), r => r.Action == "RetryArtifactDeployment");
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that a failed site keeps its previous artifact stamp.</summary>
|
/// <summary>Verifies that a failed site keeps its previous artifact stamp.</summary>
|
||||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -921,7 +998,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
// DeploySiteSecrets audit row is written for a deploy that carried no secrets.
|
// DeploySiteSecrets audit row is written for a deploy that carried no secrets.
|
||||||
Assert.Null(siteResult.SecretsDeployed);
|
Assert.Null(siteResult.SecretsDeployed);
|
||||||
Assert.NotNull(site.ArtifactRevisionHash);
|
Assert.NotNull(site.ArtifactRevisionHash);
|
||||||
await _audit.DidNotReceive().LogAsync(
|
await _audit.DidNotReceive().LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(),
|
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(),
|
||||||
Arg.Any<string>(), Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
Arg.Any<string>(), Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
@@ -958,7 +1035,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
object? captured = null;
|
object? captured = null;
|
||||||
var callCount = 0;
|
var callCount = 0;
|
||||||
_audit.When(x => x.LogAsync(
|
_audit.When(x => x.LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||||
.Do(ci =>
|
.Do(ci =>
|
||||||
@@ -1086,7 +1163,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
object? captured = null;
|
object? captured = null;
|
||||||
var callCount = 0;
|
var callCount = 0;
|
||||||
_audit.When(x => x.LogAsync(
|
_audit.When(x => x.LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||||
.Do(ci =>
|
.Do(ci =>
|
||||||
@@ -1144,7 +1221,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
object? captured = null;
|
object? captured = null;
|
||||||
var callCount = 0;
|
var callCount = 0;
|
||||||
_audit.When(x => x.LogAsync(
|
_audit.When(x => x.LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||||
.Do(ci =>
|
.Do(ci =>
|
||||||
@@ -1206,7 +1283,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
}
|
}
|
||||||
|
|
||||||
private ArtifactDeploymentService CreateServiceWithCommActor(
|
private ArtifactDeploymentService CreateServiceWithCommActor(
|
||||||
IActorRef commActor, ILogger<ArtifactDeploymentService>? logger = null)
|
IActorRef commActor, ILogger<ArtifactDeploymentService>? logger = null, IAuditService? audit = null)
|
||||||
{
|
{
|
||||||
var comms = new CommunicationService(
|
var comms = new CommunicationService(
|
||||||
Options.Create(new CommunicationOptions
|
Options.Create(new CommunicationOptions
|
||||||
@@ -1218,7 +1295,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
return new ArtifactDeploymentService(
|
return new ArtifactDeploymentService(
|
||||||
_siteRepo, _deploymentRepo, _templateRepo, _externalSystemRepo,
|
_siteRepo, _deploymentRepo, _templateRepo, _externalSystemRepo,
|
||||||
comms, _audit,
|
comms, audit ?? _audit,
|
||||||
Options.Create(new DeploymentManagerOptions
|
Options.Create(new DeploymentManagerOptions
|
||||||
{
|
{
|
||||||
ArtifactDeploymentTimeoutPerSite = TimeSpan.FromSeconds(5)
|
ArtifactDeploymentTimeoutPerSite = TimeSpan.FromSeconds(5)
|
||||||
@@ -1341,7 +1418,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
var service = CreateServiceWithCommActor(probe);
|
var service = CreateServiceWithCommActor(probe);
|
||||||
|
|
||||||
object? audited = null;
|
object? audited = null;
|
||||||
_audit.When(x => x.LogAsync(
|
_audit.When(x => x.LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "sec-site", Arg.Any<string>(),
|
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "sec-site", Arg.Any<string>(),
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||||
.Do(ci => audited = ci[5]);
|
.Do(ci => audited = ci[5]);
|
||||||
@@ -1418,7 +1495,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Contains("Central secret store could not be read", result.Error);
|
Assert.Contains("Central secret store could not be read", result.Error);
|
||||||
Assert.Empty(recorder.Received);
|
Assert.Empty(recorder.Received);
|
||||||
await _audit.Received(1).LogAsync(
|
await _audit.Received(1).LogAndSaveAsync(
|
||||||
"admin", "DeploySiteSecrets", "SiteSecrets", "sec-site", Arg.Any<string>(),
|
"admin", "DeploySiteSecrets", "SiteSecrets", "sec-site", Arg.Any<string>(),
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
@@ -1441,7 +1518,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
var service = CreateServiceWithCommActor(probe);
|
var service = CreateServiceWithCommActor(probe);
|
||||||
|
|
||||||
object? audited = null;
|
object? audited = null;
|
||||||
_audit.When(x => x.LogAsync(
|
_audit.When(x => x.LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "site-1", Arg.Any<string>(),
|
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "site-1", Arg.Any<string>(),
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||||
.Do(ci => audited = ci[5]);
|
.Do(ci => audited = ci[5]);
|
||||||
@@ -1473,7 +1550,7 @@ public class ArtifactDeploymentServiceTests : TestKit
|
|||||||
var service = CreateServiceWithCommActor(probe);
|
var service = CreateServiceWithCommActor(probe);
|
||||||
|
|
||||||
object? audited = null;
|
object? audited = null;
|
||||||
_audit.When(x => x.LogAsync(
|
_audit.When(x => x.LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "site-1", Arg.Any<string>(),
|
Arg.Any<string>(), "DeploySiteSecrets", Arg.Any<string>(), "site-1", Arg.Any<string>(),
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||||
.Do(ci => audited = ci[5]);
|
.Do(ci => audited = ci[5]);
|
||||||
|
|||||||
+4
-4
@@ -141,9 +141,9 @@ public class DeploymentServiceFailurePathTests : TestKit
|
|||||||
await _repo.DidNotReceive().AddDeployedSnapshotAsync(Arg.Any<DeployedConfigSnapshot>(), Arg.Any<CancellationToken>());
|
await _repo.DidNotReceive().AddDeployedSnapshotAsync(Arg.Any<DeployedConfigSnapshot>(), Arg.Any<CancellationToken>());
|
||||||
await _repo.DidNotReceive().UpdateDeployedSnapshotAsync(Arg.Any<DeployedConfigSnapshot>(), Arg.Any<CancellationToken>());
|
await _repo.DidNotReceive().UpdateDeployedSnapshotAsync(Arg.Any<DeployedConfigSnapshot>(), Arg.Any<CancellationToken>());
|
||||||
// The outcome is audited as a Deploy with Failed status — not as a DeployFailed fault.
|
// The outcome is audited as a Deploy with Failed status — not as a DeployFailed fault.
|
||||||
await _audit.Received(1).LogAsync("admin", "Deploy", "Instance", "10", "Inst10",
|
await _audit.Received(1).LogAndSaveAsync("admin", "Deploy", "Instance", "10", "Inst10",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
await _audit.DidNotReceive().LogAsync(Arg.Any<string>(), "DeployFailed", Arg.Any<string>(),
|
await _audit.DidNotReceive().LogAndSaveAsync(Arg.Any<string>(), "DeployFailed", Arg.Any<string>(),
|
||||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,7 +222,7 @@ public class DeploymentServiceFailurePathTests : TestKit
|
|||||||
Assert.Equal(expectedFailedWrites, failedWrites);
|
Assert.Equal(expectedFailedWrites, failedWrites);
|
||||||
_repo.Received(1).DetachPendingChanges();
|
_repo.Received(1).DetachPendingChanges();
|
||||||
// The failure audit row is written even when the status write could not be.
|
// The failure audit row is written even when the status write could not be.
|
||||||
await _audit.Received(1).LogAsync("admin", "DeployFailed", "Instance", "12", "Inst12",
|
await _audit.Received(1).LogAndSaveAsync("admin", "DeployFailed", "Instance", "12", "Inst12",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -285,7 +285,7 @@ public class DeploymentServiceFailurePathTests : TestKit
|
|||||||
await _repo.DidNotReceive().UpdateInstanceAsync(Arg.Any<Instance>(), Arg.Any<CancellationToken>());
|
await _repo.DidNotReceive().UpdateInstanceAsync(Arg.Any<Instance>(), Arg.Any<CancellationToken>());
|
||||||
await _repo.DidNotReceive().DeleteInstanceAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
|
await _repo.DidNotReceive().DeleteInstanceAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||||
await _repo.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
await _repo.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
await _audit.Received(1).LogAsync("admin", action.ToString(), "Instance", "20", "LcInst",
|
await _audit.Received(1).LogAndSaveAsync("admin", action.ToString(), "Instance", "20", "LcInst",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -953,7 +953,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
await _service.DeployInstanceAsync(1, "admin");
|
await _service.DeployInstanceAsync(1, "admin");
|
||||||
|
|
||||||
await _audit.DidNotReceive().LogAsync(
|
await _audit.DidNotReceive().LogAndSaveAsync(
|
||||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||||
Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
@@ -979,7 +979,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
var result = await service.DeployInstanceAsync(50, "admin");
|
var result = await service.DeployInstanceAsync(50, "admin");
|
||||||
|
|
||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
await _audit.Received().LogAsync(
|
await _audit.Received().LogAndSaveAsync(
|
||||||
"admin", "Deploy", "Instance", "50", "AuditInst",
|
"admin", "Deploy", "Instance", "50", "AuditInst",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
@@ -999,8 +999,8 @@ public class DeploymentServiceTests : TestKit
|
|||||||
_repo.GetCurrentDeploymentStatusAsync(52, Arg.Any<CancellationToken>())
|
_repo.GetCurrentDeploymentStatusAsync(52, Arg.Any<CancellationToken>())
|
||||||
.Returns((DeploymentRecord?)null);
|
.Returns((DeploymentRecord?)null);
|
||||||
|
|
||||||
// The Deploy audit LogAsync faults.
|
// The Deploy audit LogAndSaveAsync faults.
|
||||||
_audit.When(a => a.LogAsync(
|
_audit.When(a => a.LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "Deploy", Arg.Any<string>(), Arg.Any<string>(),
|
Arg.Any<string>(), "Deploy", Arg.Any<string>(), Arg.Any<string>(),
|
||||||
Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>()))
|
||||||
.Do(_ => throw new InvalidOperationException("audit pipeline down"));
|
.Do(_ => throw new InvalidOperationException("audit pipeline down"));
|
||||||
@@ -1179,7 +1179,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
Assert.Equal(InstanceState.Disabled, instance.State);
|
Assert.Equal(InstanceState.Disabled, instance.State);
|
||||||
await _repo.Received().UpdateInstanceAsync(instance, Arg.Any<CancellationToken>());
|
await _repo.Received().UpdateInstanceAsync(instance, Arg.Any<CancellationToken>());
|
||||||
await _audit.Received().LogAsync(
|
await _audit.Received().LogAndSaveAsync(
|
||||||
"admin", "Disable", "Instance", "51", "DisInst",
|
"admin", "Disable", "Instance", "51", "DisInst",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
@@ -1202,7 +1202,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
Assert.Equal(InstanceState.Enabled, instance.State);
|
Assert.Equal(InstanceState.Enabled, instance.State);
|
||||||
await _repo.Received().UpdateInstanceAsync(instance, Arg.Any<CancellationToken>());
|
await _repo.Received().UpdateInstanceAsync(instance, Arg.Any<CancellationToken>());
|
||||||
await _audit.Received().LogAsync(
|
await _audit.Received().LogAndSaveAsync(
|
||||||
"admin", "Enable", "Instance", "52", "EnInst",
|
"admin", "Enable", "Instance", "52", "EnInst",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
@@ -1224,11 +1224,78 @@ public class DeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
await _repo.Received().DeleteInstanceAsync(53, Arg.Any<CancellationToken>());
|
await _repo.Received().DeleteInstanceAsync(53, Arg.Any<CancellationToken>());
|
||||||
await _audit.Received().LogAsync(
|
await _audit.Received().LogAndSaveAsync(
|
||||||
"admin", "Delete", "Instance", "53", "DelInst",
|
"admin", "Delete", "Instance", "53", "DelInst",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Real-context audit durability (code review 2026-12-02 DEP-1) ──
|
||||||
|
//
|
||||||
|
// The audit rows below used to be staged with LogAsync AFTER the method's final save and
|
||||||
|
// nothing saved again, so they were discarded with the DI scope (the rig had zero
|
||||||
|
// Disable/Enable/Delete rows). These run the lifecycle against a REAL AuditService over
|
||||||
|
// SQLite and read the row back through a second context — the mocked tests above only
|
||||||
|
// prove the call was made.
|
||||||
|
|
||||||
|
/// <summary>Disable, Enable and Delete each leave a persisted audit row.</summary>
|
||||||
|
/// <param name="action">The lifecycle action to run.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Disable")]
|
||||||
|
[InlineData("Enable")]
|
||||||
|
[InlineData("Delete")]
|
||||||
|
public async Task Lifecycle_SiteSucceeds_AuditRowIsPersisted(string action)
|
||||||
|
{
|
||||||
|
using var db = new RealAuditDatabase();
|
||||||
|
var instance = new Instance("DurableInst")
|
||||||
|
{
|
||||||
|
Id = 61, SiteId = 1,
|
||||||
|
State = action == "Enable" ? InstanceState.Disabled : InstanceState.Enabled
|
||||||
|
};
|
||||||
|
_repo.GetInstanceByIdAsync(61, Arg.Any<CancellationToken>()).Returns(instance);
|
||||||
|
|
||||||
|
var counters = new ReconcileProbeCounters();
|
||||||
|
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||||
|
new ReconcileProbeActor(counters, siteHash: "x", failQuery: false)));
|
||||||
|
var service = CreateServiceWithCommActor(commActor, audit: db.AuditService);
|
||||||
|
|
||||||
|
var result = action switch
|
||||||
|
{
|
||||||
|
"Disable" => (await service.DisableInstanceAsync(61, "admin")).IsSuccess,
|
||||||
|
"Enable" => (await service.EnableInstanceAsync(61, "admin")).IsSuccess,
|
||||||
|
_ => (await service.DeleteInstanceAsync(61, "admin")).IsSuccess,
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.True(result);
|
||||||
|
var row = Assert.Single(await db.PersistedRowsAsync());
|
||||||
|
Assert.Equal(action, row.Action);
|
||||||
|
Assert.Equal("Instance", row.EntityType);
|
||||||
|
Assert.Equal("61", row.EntityId);
|
||||||
|
Assert.Equal("admin", row.User);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A single-instance deploy leaves a persisted <c>Deploy</c> audit row.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task DeployInstanceAsync_SiteSucceeds_AuditRowIsPersisted()
|
||||||
|
{
|
||||||
|
using var db = new RealAuditDatabase();
|
||||||
|
var instance = new Instance("DurableDeploy") { Id = 62, SiteId = 1, State = InstanceState.NotDeployed };
|
||||||
|
_repo.GetInstanceByIdAsync(62, Arg.Any<CancellationToken>()).Returns(instance);
|
||||||
|
SetupValidPipeline(62, "DurableDeploy", "sha256:durable");
|
||||||
|
|
||||||
|
var counters = new ReconcileProbeCounters();
|
||||||
|
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||||
|
new ReconcileProbeActor(counters, siteHash: "sha256:other", failQuery: false)));
|
||||||
|
var service = CreateServiceWithCommActor(commActor, audit: db.AuditService);
|
||||||
|
|
||||||
|
var result = await service.DeployInstanceAsync(62, "admin");
|
||||||
|
|
||||||
|
Assert.True(result.IsSuccess, result.IsFailure ? result.Error : null);
|
||||||
|
var row = Assert.Single(await db.PersistedRowsAsync(), r => r.Action == "Deploy");
|
||||||
|
Assert.Equal("62", row.EntityId);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that deploy instance async same instance operation lock serializes concurrent deploys.</summary>
|
/// <summary>Verifies that deploy instance async same instance operation lock serializes concurrent deploys.</summary>
|
||||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -1269,7 +1336,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
/// the notify-and-fetch fail-fast guard.
|
/// the notify-and-fetch fail-fast guard.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private DeploymentService CreateServiceWithCommActor(
|
private DeploymentService CreateServiceWithCommActor(
|
||||||
IActorRef commActor, string centralFetchBaseUrl = TestFetchBaseUrl)
|
IActorRef commActor, string centralFetchBaseUrl = TestFetchBaseUrl, IAuditService? audit = null)
|
||||||
{
|
{
|
||||||
var comms = new CommunicationService(
|
var comms = new CommunicationService(
|
||||||
Options.Create(new CommunicationOptions
|
Options.Create(new CommunicationOptions
|
||||||
@@ -1282,7 +1349,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
var siteRepo = CreateSiteRepoStub();
|
var siteRepo = CreateSiteRepoStub();
|
||||||
return new DeploymentService(
|
return new DeploymentService(
|
||||||
_repo, siteRepo, Substitute.For<ITemplateEngineRepository>(), _pipeline, comms, _lockManager, _audit,
|
_repo, siteRepo, Substitute.For<ITemplateEngineRepository>(), _pipeline, comms, _lockManager, audit ?? _audit,
|
||||||
new DiffService(),
|
new DiffService(),
|
||||||
new RevisionHashService(),
|
new RevisionHashService(),
|
||||||
new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance),
|
new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance),
|
||||||
@@ -1863,11 +1930,11 @@ public class DeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
// Audit row's actor is the current user.
|
// Audit row's actor is the current user.
|
||||||
await _audit.Received().LogAsync(
|
await _audit.Received().LogAndSaveAsync(
|
||||||
"currentUser", "DeployReconciled", "Instance", "73", "ReconcileAuditUser",
|
"currentUser", "DeployReconciled", "Instance", "73", "ReconcileAuditUser",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
// And the prior deployer was NOT used as the actor.
|
// And the prior deployer was NOT used as the actor.
|
||||||
await _audit.DidNotReceive().LogAsync(
|
await _audit.DidNotReceive().LogAndSaveAsync(
|
||||||
"originalUser", "DeployReconciled", "Instance", "73", "ReconcileAuditUser",
|
"originalUser", "DeployReconciled", "Instance", "73", "ReconcileAuditUser",
|
||||||
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
@@ -1979,7 +2046,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
|
|
||||||
// The DisableTimedOut audit entry must have been written. Pre-fix the
|
// The DisableTimedOut audit entry must have been written. Pre-fix the
|
||||||
// catch block returned without calling _auditService at all.
|
// catch block returned without calling _auditService at all.
|
||||||
await _audit.Received(1).LogAsync(
|
await _audit.Received(1).LogAndSaveAsync(
|
||||||
"operator-jane",
|
"operator-jane",
|
||||||
"DisableTimedOut",
|
"DisableTimedOut",
|
||||||
"Instance",
|
"Instance",
|
||||||
@@ -2027,7 +2094,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
var result = await service.EnableInstanceAsync(62, "operator-jane");
|
var result = await service.EnableInstanceAsync(62, "operator-jane");
|
||||||
|
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
await _audit.Received(1).LogAsync(
|
await _audit.Received(1).LogAndSaveAsync(
|
||||||
"operator-jane",
|
"operator-jane",
|
||||||
"EnableTimedOut",
|
"EnableTimedOut",
|
||||||
"Instance",
|
"Instance",
|
||||||
@@ -2075,7 +2142,7 @@ public class DeploymentServiceTests : TestKit
|
|||||||
var result = await service.DeleteInstanceAsync(63, "operator-jane");
|
var result = await service.DeleteInstanceAsync(63, "operator-jane");
|
||||||
|
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
await _audit.Received(1).LogAsync(
|
await _audit.Received(1).LogAndSaveAsync(
|
||||||
"operator-jane",
|
"operator-jane",
|
||||||
"DeleteTimedOut",
|
"DeleteTimedOut",
|
||||||
"Instance",
|
"Instance",
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A real <see cref="AuditService"/> over an in-memory SQLite configuration database, for the
|
||||||
|
/// code review 2026-12-02 DEP-1 / MGT-1 / TPL-3 regression tests. The pre-fix unit tests
|
||||||
|
/// mocked <c>IAuditService</c> and only asserted the call, which passed while the staged row
|
||||||
|
/// was never saved; these tests read the row back through a SECOND context on the same
|
||||||
|
/// connection, so only a row that was actually committed counts.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class RealAuditDatabase : IDisposable
|
||||||
|
{
|
||||||
|
private readonly SqliteConnection _connection;
|
||||||
|
private readonly DbContextOptions<ScadaBridgeDbContext> _options;
|
||||||
|
|
||||||
|
/// <summary>Opens the database and builds the audit service over a fresh context.</summary>
|
||||||
|
public RealAuditDatabase()
|
||||||
|
{
|
||||||
|
_connection = new SqliteConnection("DataSource=:memory:");
|
||||||
|
_connection.Open();
|
||||||
|
_options = new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlite(_connection).Options;
|
||||||
|
Context = new ScadaBridgeDbContext(_options);
|
||||||
|
Context.Database.EnsureCreated();
|
||||||
|
AuditService = new AuditService(Context, new AuditCorrelationContext());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The unit-of-work context the audit service writes through.</summary>
|
||||||
|
public ScadaBridgeDbContext Context { get; }
|
||||||
|
|
||||||
|
/// <summary>The real audit service under test.</summary>
|
||||||
|
public AuditService AuditService { get; }
|
||||||
|
|
||||||
|
/// <summary>Reads the committed audit rows through an independent context.</summary>
|
||||||
|
/// <returns>Every persisted audit row.</returns>
|
||||||
|
public async Task<List<AuditLogEntry>> PersistedRowsAsync()
|
||||||
|
{
|
||||||
|
await using var reader = new ScadaBridgeDbContext(_options);
|
||||||
|
return await reader.AuditLogEntries.AsNoTracking().ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Context.Dispose();
|
||||||
|
_connection.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
@@ -11,6 +11,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Akka.TestKit.Xunit2" />
|
<PackageReference Include="Akka.TestKit.Xunit2" />
|
||||||
<PackageReference Include="coverlet.collector" />
|
<PackageReference Include="coverlet.collector" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||||
<PackageReference Include="NSubstitute" />
|
<PackageReference Include="NSubstitute" />
|
||||||
<PackageReference Include="xunit" />
|
<PackageReference Include="xunit" />
|
||||||
@@ -24,6 +25,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.DeploymentManager/ZB.MOM.WW.ScadaBridge.DeploymentManager.csproj" />
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.DeploymentManager/ZB.MOM.WW.ScadaBridge.DeploymentManager.csproj" />
|
||||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
|
||||||
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.csproj" />
|
||||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Communication/ZB.MOM.WW.ScadaBridge.Communication.csproj" />
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Communication/ZB.MOM.WW.ScadaBridge.Communication.csproj" />
|
||||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj" />
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
actor.Tell(Envelope(new CreateApiKeyCommand("MES-Production", new[] { "MethodA" }), "Administrator"));
|
actor.Tell(Envelope(new CreateApiKeyCommand("MES-Production", new[] { "MethodA" }), "Administrator"));
|
||||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
_auditService.Received(1).LogAsync(
|
_auditService.Received(1).LogAndSaveAsync(
|
||||||
"admin", "Create", "ApiKey", Arg.Any<string>(), "MES-Production", Arg.Any<object?>());
|
"admin", "Create", "ApiKey", Arg.Any<string>(), "MES-Production", Arg.Any<object?>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +142,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
Assert.Equal("key-1", doc.RootElement.GetProperty("keyId").GetString());
|
Assert.Equal("key-1", doc.RootElement.GetProperty("keyId").GetString());
|
||||||
Assert.False(doc.RootElement.GetProperty("isEnabled").GetBoolean());
|
Assert.False(doc.RootElement.GetProperty("isEnabled").GetBoolean());
|
||||||
|
|
||||||
_auditService.Received(1).LogAsync(
|
_auditService.Received(1).LogAndSaveAsync(
|
||||||
"admin", "Update", "ApiKey", "key-1", Arg.Any<string>(), Arg.Any<object?>());
|
"admin", "Update", "ApiKey", "key-1", Arg.Any<string>(), Arg.Any<object?>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,7 +160,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
Assert.DoesNotContain("key-1", _admin.Keys.Keys);
|
Assert.DoesNotContain("key-1", _admin.Keys.Keys);
|
||||||
Assert.Equal("true", response.JsonData);
|
Assert.Equal("true", response.JsonData);
|
||||||
|
|
||||||
_auditService.Received(1).LogAsync(
|
_auditService.Received(1).LogAndSaveAsync(
|
||||||
"admin", "Delete", "ApiKey", "key-1", "key-1", null);
|
"admin", "Delete", "ApiKey", "key-1", "key-1", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,7 +184,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
.Select(m => m.GetString()).ToArray();
|
.Select(m => m.GetString()).ToArray();
|
||||||
Assert.Equal(new[] { "New1", "New2", "New3" }, methods);
|
Assert.Equal(new[] { "New1", "New2", "New3" }, methods);
|
||||||
|
|
||||||
_auditService.Received(1).LogAsync(
|
_auditService.Received(1).LogAndSaveAsync(
|
||||||
"admin", "Update", "ApiKey", "key-1", Arg.Any<string>(), Arg.Any<object?>());
|
"admin", "Update", "ApiKey", "key-1", Arg.Any<string>(), Arg.Any<object?>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,7 +204,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
|
|
||||||
Assert.Contains("key-unknown", response.Error);
|
Assert.Contains("key-unknown", response.Error);
|
||||||
// Seam returned false → audit must not have fired.
|
// Seam returned false → audit must not have fired.
|
||||||
_auditService.DidNotReceive().LogAsync(
|
_auditService.DidNotReceive().LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,7 +218,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
|
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
Assert.Contains("key-unknown", response.Error);
|
Assert.Contains("key-unknown", response.Error);
|
||||||
_auditService.DidNotReceive().LogAsync(
|
_auditService.DidNotReceive().LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,7 +232,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
|
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
Assert.Contains("key-unknown", response.Error);
|
Assert.Contains("key-unknown", response.Error);
|
||||||
_auditService.DidNotReceive().LogAsync(
|
_auditService.DidNotReceive().LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "Delete", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
Arg.Any<string>(), "Delete", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,7 +252,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
Assert.Contains("method", response.Error, StringComparison.OrdinalIgnoreCase);
|
Assert.Contains("method", response.Error, StringComparison.OrdinalIgnoreCase);
|
||||||
// No key should have been created.
|
// No key should have been created.
|
||||||
Assert.Empty(_admin.Keys);
|
Assert.Empty(_admin.Keys);
|
||||||
_auditService.DidNotReceive().LogAsync(
|
_auditService.DidNotReceive().LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "Create", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
Arg.Any<string>(), "Create", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,7 +270,7 @@ public class ApiKeyCreationTests : TestKit, IDisposable
|
|||||||
Assert.Contains("method", response.Error, StringComparison.OrdinalIgnoreCase);
|
Assert.Contains("method", response.Error, StringComparison.OrdinalIgnoreCase);
|
||||||
// Existing scope set must be unchanged.
|
// Existing scope set must be unchanged.
|
||||||
Assert.Equal(new[] { "M1" }, _admin.Keys["key-1"].Methods);
|
Assert.Equal(new[] { "M1" }, _admin.Keys["key-1"].Methods);
|
||||||
_auditService.DidNotReceive().LogAsync(
|
_auditService.DidNotReceive().LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -428,6 +428,15 @@ public class ManagementActorTests : TestKit, IDisposable
|
|||||||
Assert.Equal(envelope.CorrelationId, response.CorrelationId);
|
Assert.Equal(envelope.CorrelationId, response.CorrelationId);
|
||||||
Assert.NotNull(response.JsonData);
|
Assert.NotNull(response.JsonData);
|
||||||
Assert.Contains("Pump1", response.JsonData);
|
Assert.Contains("Pump1", response.JsonData);
|
||||||
|
|
||||||
|
// Code review 2026-12-02 TPL-3: InstanceService saves its own Create row; the
|
||||||
|
// handler no longer stages a second one (both used to be staged and lost).
|
||||||
|
_auditService.Received(1).LogAndSaveAsync(
|
||||||
|
"testuser", "Create", "Instance", Arg.Any<string>(), "Pump1",
|
||||||
|
Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
||||||
|
_auditService.DidNotReceive().LogAsync(
|
||||||
|
Arg.Any<string>(), "Create", "Instance", Arg.Any<string>(), Arg.Any<string>(),
|
||||||
|
Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that set native alarm source override, when on locked source, returns management error.</summary>
|
/// <summary>Verifies that set native alarm source override, when on locked source, returns management error.</summary>
|
||||||
@@ -5280,7 +5289,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
|||||||
siteRepo.Received(1).UpdateDataConnectionAsync(
|
siteRepo.Received(1).UpdateDataConnectionAsync(
|
||||||
Arg.Is<Commons.Entities.Sites.DataConnection>(c => c.Id == 5 && c.SiteId == 2),
|
Arg.Is<Commons.Entities.Sites.DataConnection>(c => c.Id == 5 && c.SiteId == 2),
|
||||||
Arg.Any<CancellationToken>());
|
Arg.Any<CancellationToken>());
|
||||||
_auditService.Received(1).LogAsync(
|
// Saved, not just staged: Move is not a configuration command (MGT-1).
|
||||||
|
_auditService.Received(1).LogAndSaveAsync(
|
||||||
"testuser", "Move", "DataConnection", "5", "Opc1",
|
"testuser", "Move", "DataConnection", "5", "Opc1",
|
||||||
Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|||||||
+132
@@ -0,0 +1,132 @@
|
|||||||
|
using Akka.Actor;
|
||||||
|
using Akka.TestKit.Xunit2;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using NSubstitute;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Schemas;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Security;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.ManagementService;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Code review 2026-12-02 MGT-1: the API-key, shared-schema, external-system-method and
|
||||||
|
/// data-connection-move commands are not configuration commands, so they run without the
|
||||||
|
/// transaction wrapper's trailing save — and each staged its audit row AFTER its own save.
|
||||||
|
/// The row was discarded with the scope; the mocked tests only proved the call was made.
|
||||||
|
/// These drive the real <see cref="ManagementActor"/> against a REAL audit service over
|
||||||
|
/// SQLite (repositories stay mocks and never touch that context) and read the row back
|
||||||
|
/// through a second context, one test per family.
|
||||||
|
/// </summary>
|
||||||
|
public class ManagementAuditDurabilityTests : TestKit, IDisposable
|
||||||
|
{
|
||||||
|
private readonly RealAuditDatabase _db = new();
|
||||||
|
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
|
||||||
|
|
||||||
|
/// <summary>Registers the real audit service.</summary>
|
||||||
|
public ManagementAuditDurabilityTests()
|
||||||
|
{
|
||||||
|
_services.AddScoped<IAuditService>(_ => _db.AuditService);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
void IDisposable.Dispose()
|
||||||
|
{
|
||||||
|
Shutdown();
|
||||||
|
_db.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Run(object command, params string[] roles)
|
||||||
|
{
|
||||||
|
var actor = Sys.ActorOf(Props.Create(() => new ManagementActor(
|
||||||
|
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
|
||||||
|
actor.Tell(new ManagementEnvelope(
|
||||||
|
new AuthenticatedUser("auditor", "Auditor", roles, Array.Empty<string>()),
|
||||||
|
command, Guid.NewGuid().ToString("N")));
|
||||||
|
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>API-key family: <c>security api-key delete</c> leaves a persisted row.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task DeleteApiKey_AuditRowIsPersisted()
|
||||||
|
{
|
||||||
|
var admin = Substitute.For<IInboundApiKeyAdmin>();
|
||||||
|
admin.DeleteAsync("k1", Arg.Any<CancellationToken>()).Returns(true);
|
||||||
|
_services.AddScoped(_ => admin);
|
||||||
|
|
||||||
|
Run(new DeleteApiKeyCommand("k1"), "Administrator");
|
||||||
|
|
||||||
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
||||||
|
Assert.Equal(("Delete", "ApiKey", "k1", "auditor"), (row.Action, row.EntityType, row.EntityId, row.User));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shared-schema family: delete leaves a persisted row.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task DeleteSharedSchema_AuditRowIsPersisted()
|
||||||
|
{
|
||||||
|
var repo = Substitute.For<ISharedSchemaRepository>();
|
||||||
|
repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(new SharedSchema { Id = 5, Name = "Addr", SchemaJson = "{}" });
|
||||||
|
_services.AddScoped(_ => repo);
|
||||||
|
|
||||||
|
Run(new DeleteSharedSchemaCommand(5), "Designer");
|
||||||
|
|
||||||
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
||||||
|
Assert.Equal(("Delete", "SharedSchema", "Addr"), (row.Action, row.EntityType, row.EntityName));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>External-system-method family: delete leaves a persisted row.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task DeleteExternalSystemMethod_AuditRowIsPersisted()
|
||||||
|
{
|
||||||
|
var repo = Substitute.For<IExternalSystemRepository>();
|
||||||
|
repo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
|
||||||
|
_services.AddScoped(_ => repo);
|
||||||
|
|
||||||
|
Run(new DeleteExternalSystemMethodCommand(9), "Designer");
|
||||||
|
|
||||||
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
||||||
|
Assert.Equal(("Delete", "ExternalSystemMethod", "9"), (row.Action, row.EntityType, row.EntityId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>data-connection move</c> leaves a persisted row whose after-state is the SCRUBBED
|
||||||
|
/// public shape (MGT-4): the raw entity carried the protocol configuration's credentials.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task MoveDataConnection_AuditRowIsPersisted_WithoutTheSecret()
|
||||||
|
{
|
||||||
|
var conn = new DataConnection("Opc1", "OpcUa", 1)
|
||||||
|
{
|
||||||
|
Id = 5,
|
||||||
|
PrimaryConfiguration = """{"endpointUrl":"opc.tcp://plc:4840","password":"hunter2-primary"}""",
|
||||||
|
BackupConfiguration = """{"endpointUrl":"opc.tcp://plc2:4840","password":"hunter2-backup"}""",
|
||||||
|
};
|
||||||
|
var siteRepo = Substitute.For<ISiteRepository>();
|
||||||
|
siteRepo.GetDataConnectionByIdAsync(5, Arg.Any<CancellationToken>()).Returns(conn);
|
||||||
|
siteRepo.GetSiteByIdAsync(2, Arg.Any<CancellationToken>()).Returns(new Site("Target", "SITE-B") { Id = 2 });
|
||||||
|
siteRepo.GetDataConnectionsBySiteIdAsync(2, Arg.Any<CancellationToken>()).Returns(new List<DataConnection>());
|
||||||
|
siteRepo.GetInstancesReferencingDataConnectionAsync(5, Arg.Any<CancellationToken>()).Returns(new List<Instance>());
|
||||||
|
siteRepo.GetInstancesWithNativeAlarmOverridesBySiteIdAsync(1, Arg.Any<CancellationToken>()).Returns(new List<Instance>());
|
||||||
|
siteRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
|
||||||
|
_services.AddScoped(_ => siteRepo);
|
||||||
|
_services.AddScoped(_ => Substitute.For<ITemplateEngineRepository>());
|
||||||
|
|
||||||
|
Run(new MoveDataConnectionCommand(5, 2), "Designer");
|
||||||
|
|
||||||
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
||||||
|
Assert.Equal(("Move", "DataConnection", "5"), (row.Action, row.EntityType, row.EntityId));
|
||||||
|
Assert.NotNull(row.AfterStateJson);
|
||||||
|
Assert.DoesNotContain("hunter2", row.AfterStateJson);
|
||||||
|
Assert.Contains(ConfigSecretScrubber.Sentinel, row.AfterStateJson);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A real <see cref="AuditService"/> over an in-memory SQLite configuration database, for the
|
||||||
|
/// code review 2026-12-02 DEP-1 / MGT-1 / TPL-3 regression tests. The pre-fix unit tests
|
||||||
|
/// mocked <c>IAuditService</c> and only asserted the call, which passed while the staged row
|
||||||
|
/// was never saved; these tests read the row back through a SECOND context on the same
|
||||||
|
/// connection, so only a row that was actually committed counts.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class RealAuditDatabase : IDisposable
|
||||||
|
{
|
||||||
|
private readonly SqliteConnection _connection;
|
||||||
|
private readonly DbContextOptions<ScadaBridgeDbContext> _options;
|
||||||
|
|
||||||
|
/// <summary>Opens the database and builds the audit service over a fresh context.</summary>
|
||||||
|
public RealAuditDatabase()
|
||||||
|
{
|
||||||
|
_connection = new SqliteConnection("DataSource=:memory:");
|
||||||
|
_connection.Open();
|
||||||
|
_options = new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlite(_connection).Options;
|
||||||
|
Context = new ScadaBridgeDbContext(_options);
|
||||||
|
Context.Database.EnsureCreated();
|
||||||
|
AuditService = new AuditService(Context, new AuditCorrelationContext());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The unit-of-work context the audit service writes through.</summary>
|
||||||
|
public ScadaBridgeDbContext Context { get; }
|
||||||
|
|
||||||
|
/// <summary>The real audit service under test.</summary>
|
||||||
|
public AuditService AuditService { get; }
|
||||||
|
|
||||||
|
/// <summary>Reads the committed audit rows through an independent context.</summary>
|
||||||
|
/// <returns>Every persisted audit row.</returns>
|
||||||
|
public async Task<List<AuditLogEntry>> PersistedRowsAsync()
|
||||||
|
{
|
||||||
|
await using var reader = new ScadaBridgeDbContext(_options);
|
||||||
|
return await reader.AuditLogEntries.AsNoTracking().ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Context.Dispose();
|
||||||
|
_connection.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -334,9 +334,10 @@ public class SchemaLibraryHandlerTests : TestKit, IDisposable
|
|||||||
actor.Tell(envelope);
|
actor.Tell(envelope);
|
||||||
|
|
||||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||||
// LogAsync(user, action, entityType, entityId, entityName, afterState, ct):
|
// LogAndSaveAsync(user, action, entityType, entityId, entityName, afterState, ct):
|
||||||
// entityId is the id ("5"), entityName is the resolved name ("Addr").
|
// entityId is the id ("5"), entityName is the resolved name ("Addr"). Saved, not
|
||||||
_auditService.Received(1).LogAsync(
|
// just staged: DeleteSharedSchema is not a configuration command (MGT-1).
|
||||||
|
_auditService.Received(1).LogAndSaveAsync(
|
||||||
Arg.Any<string>(), "Delete", "SharedSchema", "5", "Addr",
|
Arg.Any<string>(), "Delete", "SharedSchema", "5", "Addr",
|
||||||
Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|||||||
+2
@@ -13,6 +13,7 @@
|
|||||||
<PackageReference Include="Akka.TestKit.Xunit2" />
|
<PackageReference Include="Akka.TestKit.Xunit2" />
|
||||||
<PackageReference Include="coverlet.collector" />
|
<PackageReference Include="coverlet.collector" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.TestHost" />
|
<PackageReference Include="Microsoft.AspNetCore.TestHost" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||||
<PackageReference Include="NSubstitute" />
|
<PackageReference Include="NSubstitute" />
|
||||||
<PackageReference Include="xunit" />
|
<PackageReference Include="xunit" />
|
||||||
@@ -24,6 +25,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ManagementService/ZB.MOM.WW.ScadaBridge.ManagementService.csproj" />
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ManagementService/ZB.MOM.WW.ScadaBridge.ManagementService.csproj" />
|
||||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Commons/ZB.MOM.WW.ScadaBridge.Commons.csproj" />
|
||||||
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.csproj" />
|
||||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Security/ZB.MOM.WW.ScadaBridge.Security.csproj" />
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.Security/ZB.MOM.WW.ScadaBridge.Security.csproj" />
|
||||||
<!-- #206: SecuredWrite audit now routes through the real CentralAuditWriter so the
|
<!-- #206: SecuredWrite audit now routes through the real CentralAuditWriter so the
|
||||||
handler tests verify SourceNode stamping end-to-end (actor → writer → repo). -->
|
handler tests verify SourceNode stamping end-to-end (actor → writer → repo). -->
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A real <see cref="AuditService"/> over an in-memory SQLite configuration database, for the
|
||||||
|
/// code review 2026-12-02 DEP-1 / MGT-1 / TPL-3 regression tests. The pre-fix unit tests
|
||||||
|
/// mocked <c>IAuditService</c> and only asserted the call, which passed while the staged row
|
||||||
|
/// was never saved; these tests read the row back through a SECOND context on the same
|
||||||
|
/// connection, so only a row that was actually committed counts.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class RealAuditDatabase : IDisposable
|
||||||
|
{
|
||||||
|
private readonly SqliteConnection _connection;
|
||||||
|
private readonly DbContextOptions<ScadaBridgeDbContext> _options;
|
||||||
|
|
||||||
|
/// <summary>Opens the database and builds the audit service over a fresh context.</summary>
|
||||||
|
public RealAuditDatabase()
|
||||||
|
{
|
||||||
|
_connection = new SqliteConnection("DataSource=:memory:");
|
||||||
|
_connection.Open();
|
||||||
|
_options = new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlite(_connection).Options;
|
||||||
|
Context = new ScadaBridgeDbContext(_options);
|
||||||
|
Context.Database.EnsureCreated();
|
||||||
|
AuditService = new AuditService(Context, new AuditCorrelationContext());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The unit-of-work context the audit service writes through.</summary>
|
||||||
|
public ScadaBridgeDbContext Context { get; }
|
||||||
|
|
||||||
|
/// <summary>The real audit service under test.</summary>
|
||||||
|
public AuditService AuditService { get; }
|
||||||
|
|
||||||
|
/// <summary>Reads the committed audit rows through an independent context.</summary>
|
||||||
|
/// <returns>Every persisted audit row.</returns>
|
||||||
|
public async Task<List<AuditLogEntry>> PersistedRowsAsync()
|
||||||
|
{
|
||||||
|
await using var reader = new ScadaBridgeDbContext(_options);
|
||||||
|
return await reader.AuditLogEntries.AsNoTracking().ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Context.Dispose();
|
||||||
|
_connection.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -153,7 +153,7 @@ public class AreaServiceTests
|
|||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
Assert.Equal(2, result.Value.ParentAreaId);
|
Assert.Equal(2, result.Value.ParentAreaId);
|
||||||
_repoMock.Verify(r => r.UpdateAreaAsync(It.Is<Area>(a => a.Id == 3 && a.ParentAreaId == 2), It.IsAny<CancellationToken>()), Times.Once);
|
_repoMock.Verify(r => r.UpdateAreaAsync(It.Is<Area>(a => a.Id == 3 && a.ParentAreaId == 2), It.IsAny<CancellationToken>()), Times.Once);
|
||||||
_auditMock.Verify(a => a.LogAsync("admin", "Move", "Area", "3", "Leaf", It.IsAny<object>(), It.IsAny<CancellationToken>()), Times.Once);
|
_auditMock.Verify(a => a.LogAndSaveAsync("admin", "Move", "Area", "3", "Leaf", It.IsAny<object>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that moving an area to the site root succeeds.</summary>
|
/// <summary>Verifies that moving an area to the site root succeeds.</summary>
|
||||||
@@ -277,7 +277,7 @@ public class AreaServiceTests
|
|||||||
|
|
||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
_repoMock.Verify(r => r.UpdateAreaAsync(It.IsAny<Area>(), It.IsAny<CancellationToken>()), Times.Never);
|
_repoMock.Verify(r => r.UpdateAreaAsync(It.IsAny<Area>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||||
_auditMock.Verify(a => a.LogAsync(It.IsAny<string>(), "Move", It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<CancellationToken>()), Times.Never);
|
_auditMock.Verify(a => a.LogAndSaveAsync(It.IsAny<string>(), "Move", It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that moving an area fails when the target parent does not exist.</summary>
|
/// <summary>Verifies that moving an area fails when the target parent does not exist.</summary>
|
||||||
|
|||||||
+90
@@ -0,0 +1,90 @@
|
|||||||
|
using Moq;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Services;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Code review 2026-12-02 TPL-3: every <see cref="InstanceService"/> mutation saved its change
|
||||||
|
/// and THEN staged its audit row with <c>LogAsync</c>, so on the management/CLI path (no later
|
||||||
|
/// save) the row was discarded — the rig had one Create row for instance ids up to 3876. These
|
||||||
|
/// run the service against a REAL audit service over SQLite and read the row back through a
|
||||||
|
/// second context, so only a committed row passes. The repository stays a mock: it never
|
||||||
|
/// touches the audit context, so nothing but the audit service itself can persist the row.
|
||||||
|
/// </summary>
|
||||||
|
public class InstanceServiceAuditDurabilityTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly Mock<ITemplateEngineRepository> _repoMock = new();
|
||||||
|
private readonly RealAuditDatabase _db = new();
|
||||||
|
private readonly InstanceService _sut;
|
||||||
|
|
||||||
|
/// <summary>Builds the service over a mocked repository and a real audit service.</summary>
|
||||||
|
public InstanceServiceAuditDurabilityTests()
|
||||||
|
{
|
||||||
|
_repoMock.Setup(r => r.SaveChangesAsync(It.IsAny<CancellationToken>())).ReturnsAsync(1);
|
||||||
|
_sut = new InstanceService(_repoMock.Object, _db.AuditService);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose() => _db.Dispose();
|
||||||
|
|
||||||
|
/// <summary>Create persists its audit row (the CLI <c>instance create</c> path).</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task CreateInstance_AuditRowIsPersisted()
|
||||||
|
{
|
||||||
|
_repoMock.Setup(r => r.GetTemplateByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
|
.ReturnsAsync(new Template("T") { Id = 1 });
|
||||||
|
_repoMock.Setup(r => r.GetInstanceByUniqueNameAsync("Inst1", It.IsAny<CancellationToken>()))
|
||||||
|
.ReturnsAsync((Instance?)null);
|
||||||
|
|
||||||
|
var result = await _sut.CreateInstanceAsync("Inst1", 1, 1, null, "admin");
|
||||||
|
|
||||||
|
Assert.True(result.IsSuccess);
|
||||||
|
var row = Assert.Single(await _db.PersistedRowsAsync());
|
||||||
|
Assert.Equal(("Create", "Instance", "Inst1", "admin"), (row.Action, row.EntityType, row.EntityName, row.User));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SetConnectionBindings persists its audit row (the CLI <c>instance set-bindings</c> path).</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task SetConnectionBindings_AuditRowIsPersisted()
|
||||||
|
{
|
||||||
|
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
|
.ReturnsAsync(new Instance("Inst1") { Id = 1 });
|
||||||
|
_repoMock.Setup(r => r.GetBindingsByInstanceIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
|
.ReturnsAsync(new List<InstanceConnectionBinding>());
|
||||||
|
|
||||||
|
var result = await _sut.SetConnectionBindingsAsync(1, [new ConnectionBinding("Temp", 100)], "admin");
|
||||||
|
|
||||||
|
Assert.True(result.IsSuccess);
|
||||||
|
Assert.Equal("SetConnectionBindings", Assert.Single(await _db.PersistedRowsAsync()).Action);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Enable / Disable / Delete each persist their audit row.</summary>
|
||||||
|
/// <param name="action">The audited action.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Enable")]
|
||||||
|
[InlineData("Disable")]
|
||||||
|
[InlineData("Delete")]
|
||||||
|
public async Task StateChanges_AuditRowIsPersisted(string action)
|
||||||
|
{
|
||||||
|
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||||
|
.ReturnsAsync(new Instance("Inst1") { Id = 1, State = InstanceState.Disabled });
|
||||||
|
|
||||||
|
var ok = action switch
|
||||||
|
{
|
||||||
|
"Enable" => (await _sut.EnableAsync(1, "admin")).IsSuccess,
|
||||||
|
"Disable" => (await _sut.DisableAsync(1, "admin")).IsSuccess,
|
||||||
|
_ => (await _sut.DeleteAsync(1, "admin")).IsSuccess,
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.True(ok);
|
||||||
|
Assert.Equal(action, Assert.Single(await _db.PersistedRowsAsync()).Action);
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
@@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="coverlet.collector" />
|
<PackageReference Include="coverlet.collector" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||||
<PackageReference Include="Moq" />
|
<PackageReference Include="Moq" />
|
||||||
<PackageReference Include="xunit" />
|
<PackageReference Include="xunit" />
|
||||||
@@ -22,6 +23,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj" />
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj" />
|
||||||
|
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
Reference in New Issue
Block a user