5ca998dc56
IAuditService.LogAsync only stages the row; every caller that audited after its last SaveChangesAsync, outside the configuration-command transaction, lost the row with the DI scope (rig: zero Disable/Enable/ Delete/DeployArtifacts rows, 16 Deploy rows for 62 deployments, one Create/Instance row for ids up to 3876). - New IAuditService.LogAndSaveAsync: stage + save, best-effort (logs and swallows any failure incl. cancellation, detaches the unsaved row). - DeploymentService (deploy/failed/reconciled/lifecycle + timeouts), ArtifactDeploymentService (DeployArtifacts now before the best-effort stamp, RetryArtifactDeployment, DeploySiteSecrets), InstanceService, AreaService, SiteService: post-save LogAsync -> LogAndSaveAsync. - ManagementActor: AuditAndSaveAsync for the non-configuration handlers (API keys, shared schemas, ES methods, data-connection move); move now audits the scrubbed public shape (MGT-4) so the fix does not start writing protocol credentials into AuditLogEntries. - HandleCreateInstance no longer stages a second Create row on top of InstanceService's own. Tests: real-context (SQLite) tests per family read the row back through a second context - DeploymentService, ArtifactDeploymentService, InstanceService, ManagementActor; each fails against the old code. Test projects gain a ConfigurationDatabase + EF Sqlite reference.
155 lines
6.4 KiB
C#
155 lines
6.4 KiB
C#
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
|
|
|
public class AuditService : IAuditService
|
|
{
|
|
private readonly ScadaBridgeDbContext _context;
|
|
private readonly IAuditCorrelationContext _correlationContext;
|
|
private readonly ILogger<AuditService> _logger;
|
|
|
|
/// <summary>
|
|
/// Serializer options for audit <c>afterState</c> payloads. Audit writes commit in the
|
|
/// same transaction as the change they record, so a serialization exception here would
|
|
/// roll back the entire business operation. Reference cycles (common when an EF entity
|
|
/// with loaded navigations is passed in) are ignored rather than thrown, and depth is
|
|
/// bounded so a pathological graph cannot produce an unbounded payload.
|
|
/// </summary>
|
|
private static readonly JsonSerializerOptions AuditSerializerOptions = new()
|
|
{
|
|
ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
|
|
MaxDepth = 32
|
|
};
|
|
|
|
/// <summary>
|
|
/// Upper bound (characters) on a serialized <c>AfterStateJson</c>. A larger payload (e.g. a
|
|
/// whole template graph with every script body) is replaced by a small truncation marker so
|
|
/// one audit row can never grow without bound. Valid JSON is preserved either way.
|
|
/// </summary>
|
|
public const int MaxAfterStateChars = 256 * 1024;
|
|
|
|
private const int TruncatedPreviewChars = 4 * 1024;
|
|
|
|
/// <summary>
|
|
/// Initializes the audit service with the EF Core context and correlation context.
|
|
/// </summary>
|
|
/// <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="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));
|
|
_correlationContext = correlationContext ?? throw new ArgumentNullException(nameof(correlationContext));
|
|
_logger = logger ?? NullLogger<AuditService>.Instance;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task LogAsync(
|
|
string user,
|
|
string action,
|
|
string entityType,
|
|
string entityId,
|
|
string entityName,
|
|
object? afterState,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
// 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,
|
|
AfterStateJson = afterState != null
|
|
? SerializeAfterState(afterState)
|
|
: null,
|
|
// Stamp the active bundle import id (if any) so audit rows emitted during a
|
|
// bundle import are attributable to that import session. Null in the normal
|
|
// interactive code path.
|
|
BundleImportId = _correlationContext.BundleImportId
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Serializes the caller-supplied after-state, tolerating arbitrary object shapes.
|
|
/// Reference cycles are ignored via <see cref="AuditSerializerOptions"/>. If serialization
|
|
/// still fails (e.g. <c>MaxDepth</c> exceeded), the audit entry is preserved with a
|
|
/// diagnostic placeholder rather than throwing — a serialization failure must never
|
|
/// roll back the business operation the audit entry is recording.
|
|
/// </summary>
|
|
private static string SerializeAfterState(object afterState)
|
|
{
|
|
try
|
|
{
|
|
var json = JsonSerializer.Serialize(afterState, AuditSerializerOptions);
|
|
if (json.Length <= MaxAfterStateChars)
|
|
return json;
|
|
|
|
return JsonSerializer.Serialize(new
|
|
{
|
|
AuditTruncated = true,
|
|
OriginalLength = json.Length,
|
|
StateType = afterState.GetType().FullName,
|
|
Preview = json[..TruncatedPreviewChars]
|
|
});
|
|
}
|
|
catch (Exception ex) when (ex is JsonException or NotSupportedException)
|
|
{
|
|
return JsonSerializer.Serialize(new
|
|
{
|
|
AuditSerializationError = ex.Message,
|
|
StateType = afterState.GetType().FullName
|
|
});
|
|
}
|
|
}
|
|
}
|