using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Khaemhat.Core.Instance; using Khaemhat.Data; using Khaemhat.Data.Querying; namespace Khaemhat.Application.Audit; /// A security or instance action to record. /// The action code, for example login.succeeded, user.created, license.activated. /// Who acted. /// The company concerned. /// What the action was about. /// Further details, serialized as JSON (never secrets). /// The client address. public sealed record SecurityEvent( string Action, string? UserName, string? CompanyCode = null, string? Target = null, object? Details = null, string? IpAddress = null); /// Writes sys_security_audit. public interface ISecurityAuditLog { /// Records an action. /// The action. /// Cancellation. /// A task. Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default); } /// /// The immutable security audit (SPEC ยง7.3): rows are only inserted, each with the SHA-256 of its content chained to /// the previous row, under an application lock so that two writers never fork the chain. /// finds a changed or removed row. /// /// Opens the system database. /// The clock. public sealed class SecurityAuditLog(IUnitOfWorkFactory factory, TimeProvider clock) : ISecurityAuditLog { private const string LockKey = "security-audit"; /// public async Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(securityEvent); var entry = new SecurityAuditEntry { At = Truncate(clock.GetUtcNow().UtcDateTime), Action = Clip(securityEvent.Action, 100)!, UserName = Clip(securityEvent.UserName, 100), CompanyCode = Clip(securityEvent.CompanyCode, 20), Target = Clip(securityEvent.Target, 200), IpAddress = Clip(securityEvent.IpAddress, 64), Details = securityEvent.Details is null ? null : JsonSerializer.Serialize(securityEvent.Details), }; await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); await unitOfWork.InTransactionAsync( async ct => { await unitOfWork.AcquireLockAsync(LockKey, ct).ConfigureAwait(false); var repository = unitOfWork.Repository(); var last = await repository.FindAsync(Query.For().OrderByDescending(e => e.Id).Take(1), ct).ConfigureAwait(false); entry.PreviousHash = last?.Hash ?? string.Empty; entry.Hash = ComputeHash(entry); await repository.InsertAsync(entry, ct).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); } /// Checks the whole chain. /// Cancellation. /// The identifier of the first row that does not match, or when the chain is intact. public async Task VerifyAsync(CancellationToken cancellationToken = default) { await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); var previous = string.Empty; const int PageSize = 1000; for (var offset = 0; ; offset += PageSize) { var page = await unitOfWork.Repository() .ListAsync(Query.For().OrderBy(e => e.Id).Page(offset, PageSize), cancellationToken).ConfigureAwait(false); foreach (var entry in page.Items) { if (entry.PreviousHash != previous || entry.Hash != ComputeHash(entry)) { return entry.Id; } previous = entry.Hash; } if (page.Items.Count < PageSize) { return null; } } } /// The hash of a row: every field and the previous hash, separated so that fields cannot run into each other. /// The row. /// 64 hexadecimal digits. public static string ComputeHash(SecurityAuditEntry entry) { ArgumentNullException.ThrowIfNull(entry); var content = string.Join( '\u001F', entry.PreviousHash, DateTime.SpecifyKind(entry.At, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ", CultureInfo.InvariantCulture), entry.Action, entry.UserName ?? string.Empty, entry.CompanyCode ?? string.Empty, entry.IpAddress ?? string.Empty, entry.Target ?? string.Empty, entry.Details ?? string.Empty); return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(content))); } private static DateTime Truncate(DateTime value) => DateTime.SpecifyKind(new DateTime(value.Ticks - (value.Ticks % 10)), DateTimeKind.Utc); private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length]; }