CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s
The instance now starts on its own from KHAEMHAT_* variables: it migrates the system and company databases, creates the super user and the first company, and only then reports ready. Users sign in with password and TOTP through revocable database sessions, and licences decide which modules and how many companies are available. - Configuration: every wrong variable reported at once (exit code 2), _FILE variants - Accounts, password policy and lockout, TOTP with recovery codes, session states with token rotation, security audit with a hash chain - Sign-in pages (mockups 001-003), authorization attributes, security headers and a CSP without inline scripts, login rate limit - Signed licences, activation codes, test mode, licence tool - DataProtection keys in the system database, encrypted with the instance key - Memory or Redis cache (in-house RESP client) that falls back to memory - Database log by section with trace id; cron scheduler with locks and system jobs; record history (audit_log) - Company creation, states, company context and X-Company, 503 in maintenance - In-memory SQLite databases stay alive for the process (tests, demo) - Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
125 lines
5.4 KiB
C#
125 lines
5.4 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.Reflection;
|
|
using System.Text.Json;
|
|
using Khaemhat.Core.Entities;
|
|
using Khaemhat.Core.Instance;
|
|
using Khaemhat.Data;
|
|
using Khaemhat.Data.Querying;
|
|
|
|
namespace Khaemhat.Application.Audit;
|
|
|
|
/// <summary>What happened to a record.</summary>
|
|
public enum AuditAction
|
|
{
|
|
/// <summary>Created.</summary>
|
|
Insert = 0,
|
|
|
|
/// <summary>Changed.</summary>
|
|
Update = 1,
|
|
|
|
/// <summary>Deleted.</summary>
|
|
Delete = 2,
|
|
}
|
|
|
|
/// <summary>
|
|
/// The history of the records of a company (SPEC §7.4): every insert, update and delete of master data, documents,
|
|
/// entries and settings writes a row in the company's <c>audit_log</c>, in the same unit of work as the change, with the
|
|
/// changed fields as JSON <c>{"Field": [old, new]}</c>. Audit columns and secrets are never written.
|
|
/// </summary>
|
|
public sealed class AuditTrail(TimeProvider clock)
|
|
{
|
|
private static readonly HashSet<string> Skipped = new(StringComparer.Ordinal)
|
|
{
|
|
nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion",
|
|
"PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString",
|
|
};
|
|
|
|
/// <summary>Writes the history row of a change, inside the caller's unit of work.</summary>
|
|
/// <typeparam name="T">The entity type.</typeparam>
|
|
/// <param name="unitOfWork">The company unit of work holding the change.</param>
|
|
/// <param name="action">What happened.</param>
|
|
/// <param name="entityId">The record.</param>
|
|
/// <param name="before">The record before (updates and deletes).</param>
|
|
/// <param name="after">The record after (inserts and updates).</param>
|
|
/// <param name="userName">Who did it.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns><see langword="true"/> when a row was written (an update that changes nothing writes none).</returns>
|
|
public async Task<bool> RecordAsync<T>(
|
|
IUnitOfWork unitOfWork, AuditAction action, object entityId, T? before, T? after, string? userName, CancellationToken cancellationToken = default)
|
|
where T : class
|
|
{
|
|
ArgumentNullException.ThrowIfNull(unitOfWork);
|
|
ArgumentNullException.ThrowIfNull(entityId);
|
|
var diff = Diff(before, after);
|
|
if (action == AuditAction.Update && diff.Count == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
await unitOfWork.Repository<AuditEntry, long>().InsertAsync(
|
|
new AuditEntry
|
|
{
|
|
At = clock.GetUtcNow().UtcDateTime,
|
|
Entity = typeof(T).Name,
|
|
EntityId = Convert.ToString(entityId, CultureInfo.InvariantCulture) ?? string.Empty,
|
|
Action = action.ToString(),
|
|
UserName = userName,
|
|
Diff = JsonSerializer.Serialize(diff),
|
|
TraceId = Activity.Current?.TraceId.ToString(),
|
|
},
|
|
cancellationToken).ConfigureAwait(false);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>The history of a record, newest first (the "Storico" panel).</summary>
|
|
/// <param name="unitOfWork">A company unit of work.</param>
|
|
/// <param name="entity">The entity name.</param>
|
|
/// <param name="entityId">The record.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The rows.</returns>
|
|
public static async Task<IReadOnlyList<AuditEntry>> HistoryAsync(IUnitOfWork unitOfWork, string entity, string entityId, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(unitOfWork);
|
|
return (await unitOfWork.Repository<AuditEntry, long>().ListAsync(
|
|
Query.For<AuditEntry>().Where(a => a.Entity == entity && a.EntityId == entityId).OrderByDescending(a => a.Id), cancellationToken).ConfigureAwait(false)).Items;
|
|
}
|
|
|
|
/// <summary>The changed fields between two versions of a record.</summary>
|
|
/// <typeparam name="T">The entity type.</typeparam>
|
|
/// <param name="before">The old version, or <see langword="null"/>.</param>
|
|
/// <param name="after">The new version, or <see langword="null"/>.</param>
|
|
/// <returns>Field name to <c>[old, new]</c>.</returns>
|
|
public static IReadOnlyDictionary<string, object?[]> Diff<T>(T? before, T? after)
|
|
where T : class
|
|
{
|
|
var result = new SortedDictionary<string, object?[]>(StringComparer.Ordinal);
|
|
foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
|
{
|
|
if (!property.CanRead || property.GetIndexParameters().Length > 0 || Skipped.Contains(property.Name))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var old = before is null ? null : Simple(property.GetValue(before));
|
|
var current = after is null ? null : Simple(property.GetValue(after));
|
|
if (!Equals(old, current))
|
|
{
|
|
result[property.Name] = [old, current];
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static object? Simple(object? value) => value switch
|
|
{
|
|
null => null,
|
|
string or bool or int or long or decimal or double => value,
|
|
DateTime date => date.ToString("O", CultureInfo.InvariantCulture),
|
|
Enum e => e.ToString(),
|
|
IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture),
|
|
_ => value.ToString(),
|
|
};
|
|
}
|