feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
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
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>
This commit is contained in:
1 parent
4582837b70
commit
032c602b49
107 files changed
+12202
-116
No files matched your search
@@ -0,0 +1,122 @@
|
||||
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;
|
||||
|
||||
/// <summary>A security or instance action to record.</summary>
|
||||
/// <param name="Action">The action code, for example <c>login.succeeded</c>, <c>user.created</c>, <c>license.activated</c>.</param>
|
||||
/// <param name="UserName">Who acted.</param>
|
||||
/// <param name="CompanyCode">The company concerned.</param>
|
||||
/// <param name="Target">What the action was about.</param>
|
||||
/// <param name="Details">Further details, serialized as JSON (never secrets).</param>
|
||||
/// <param name="IpAddress">The client address.</param>
|
||||
public sealed record SecurityEvent(
|
||||
string Action, string? UserName, string? CompanyCode = null, string? Target = null, object? Details = null, string? IpAddress = null);
|
||||
|
||||
/// <summary>Writes <c>sys_security_audit</c>.</summary>
|
||||
public interface ISecurityAuditLog
|
||||
{
|
||||
/// <summary>Records an action.</summary>
|
||||
/// <param name="securityEvent">The action.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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. <see cref="VerifyAsync"/>
|
||||
/// finds a changed or removed row.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class SecurityAuditLog(IUnitOfWorkFactory factory, TimeProvider clock) : ISecurityAuditLog
|
||||
{
|
||||
private const string LockKey = "security-audit";
|
||||
|
||||
/// <inheritdoc />
|
||||
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<SecurityAuditEntry, long>();
|
||||
var last = await repository.FindAsync(Query.For<SecurityAuditEntry>().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);
|
||||
}
|
||||
|
||||
/// <summary>Checks the whole chain.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The identifier of the first row that does not match, or <see langword="null"/> when the chain is intact.</returns>
|
||||
public async Task<long?> 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<SecurityAuditEntry, long>()
|
||||
.ListAsync(Query.For<SecurityAuditEntry>().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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The hash of a row: every field and the previous hash, separated so that fields cannot run into each other.</summary>
|
||||
/// <param name="entry">The row.</param>
|
||||
/// <returns>64 hexadecimal digits.</returns>
|
||||
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];
|
||||
}
|
||||
Reference in new issue
Block a user