using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
///
/// Writes the record of a deliberate config change (OPEN-64).
///
/// The posture is the one thing to read here. The change has already been
/// applied by the time this runs — enforcement is the product, and a rule that
/// was refused because its audit row would not fit is a rule the operator
/// believes they have and does not. So a failed record never rolls the change
/// back and never fails the request. What it does instead is get counted:
/// changeWriteFailures and changesNotWritten on /admin-api/state,
/// the same shape the other durable pillars have, because "the config changed
/// and the record of it did not land" has to be a sentence the operator can
/// read rather than one that silently never happened.
///
public sealed class ConfigChangeWriter
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly DurabilityHealth _health;
private readonly ILogger _log;
public ConfigChangeWriter(IServiceScopeFactory scopeFactory, DurabilityHealth health,
ILogger log)
{
_scopeFactory = scopeFactory;
_health = health;
_log = log;
}
/// Record one change. Returns whether the row landed — the caller
/// does not act on the answer, and that is deliberate: the only thing a
/// caller could do with a false is undo a change the operator made.
public async Task RecordAsync(
string section, string action, string target, string? detail = null,
string actor = ConfigChangeLog.ActorOperator, CancellationToken ct = default)
{
var row = new ConfigChange
{
At = DateTimeOffset.UtcNow,
Section = section,
Action = action,
// Clipped, never refused: the change happened, and a record that
// drops it because a sentence was long is the worse failure.
Target = ConfigChangeLog.Clip(target, ConfigChangeLog.MaxTargetLength),
Detail = string.IsNullOrWhiteSpace(detail)
? null
: ConfigChangeLog.Clip(detail, ConfigChangeLog.MaxDetailLength),
Actor = actor
};
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
db.ConfigChanges.Add(row);
await db.SaveChangesAsync(ct);
_health.RecordSuccess(DurabilityHealth.Changes, 1);
return true;
}
catch (Exception ex)
{
_health.RecordFailure(DurabilityHealth.Changes, ex, 1);
_log.LogWarning(ex, "ConfigChangeWriter: the record of a {Section} {Action} did not land.",
section, action);
return false;
}
}
}