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

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:
Alby96andClaude Opus 5.5 committed 2026-11-11 15:29:24 +01:00
1 parent 4582837b70
commit 032c602b49
107 files changed
+12202 -116

No files matched your search

@@ -0,0 +1,382 @@
using System.Globalization;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text.Json;
using Khaemhat.Core.Caching;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Infrastructure.Caching;
/// <summary>
/// Where Redis is (<c>KHAEMHAT_REDIS</c>, SPEC §6): <c>redis://[[user]:password@]host[:6379][/db]</c>, or
/// <c>rediss://</c> for TLS. The password never appears in <see cref="ToString"/>.
/// </summary>
public sealed class RedisEndpoint
{
private RedisEndpoint(string host, int port, bool tls, string? user, string? password, int database)
{
Host = host;
Port = port;
UseTls = tls;
User = user;
Password = password;
Database = database;
}
/// <summary>The host.</summary>
public string Host { get; }
/// <summary>The port.</summary>
public int Port { get; }
/// <summary>Whether to use TLS.</summary>
public bool UseTls { get; }
/// <summary>The ACL user, if any.</summary>
public string? User { get; }
/// <summary>The password, if any.</summary>
public string? Password { get; }
/// <summary>The database number.</summary>
public int Database { get; }
/// <summary>Parses the URL.</summary>
/// <param name="url">The URL.</param>
/// <returns>The endpoint.</returns>
/// <exception cref="FormatException">The URL is not valid (the message does not repeat it).</exception>
public static RedisEndpoint Parse(string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("redis" or "rediss") || string.IsNullOrEmpty(uri.Host))
{
throw new FormatException("KHAEMHAT_REDIS must be redis://[:password@]host:6379/0 or rediss://.");
}
string? user = null, password = null;
if (uri.UserInfo.Length > 0)
{
var colon = uri.UserInfo.IndexOf(':', StringComparison.Ordinal);
user = colon < 0 ? null : Uri.UnescapeDataString(uri.UserInfo[..colon]);
password = Uri.UnescapeDataString(colon < 0 ? uri.UserInfo : uri.UserInfo[(colon + 1)..]);
user = string.IsNullOrEmpty(user) ? null : user;
}
var path = uri.AbsolutePath.Trim('/');
var database = path.Length == 0 ? 0 : int.TryParse(path, NumberStyles.None, CultureInfo.InvariantCulture, out var db) ? db : throw new FormatException("The Redis database must be a number.");
return new RedisEndpoint(uri.Host, uri.IsDefaultPort ? 6379 : uri.Port, uri.Scheme == "rediss", user, password, database);
}
/// <inheritdoc />
public override string ToString() => (UseTls ? "rediss://" : "redis://") + (Password is null ? string.Empty : "***@") + Host + ":" + Port.ToString(CultureInfo.InvariantCulture) + "/" + Database.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// A minimal Redis client written in house (SPEC §1.2: no external libraries): one connection, one command at a time,
/// reconnecting after an error. Enough for the cache; pipelining and clustering are not needed.
/// </summary>
/// <param name="endpoint">Where Redis is.</param>
public sealed class RedisClient(RedisEndpoint endpoint) : IAsyncDisposable
{
private readonly SemaphoreSlim _gate = new(1, 1);
private TcpClient? _tcp;
private Stream? _stream;
private BufferedReader? _reader;
/// <summary>The endpoint.</summary>
public RedisEndpoint Endpoint { get; } = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
/// <summary>The time allowed to connect and for each command.</summary>
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(2);
/// <summary>Sends a command and reads its reply.</summary>
/// <param name="arguments">The command and its arguments.</param>
/// <returns>The reply.</returns>
/// <exception cref="RedisException">Redis answered with an error.</exception>
/// <exception cref="IOException">The connection failed.</exception>
public Task<RespValue> ExecuteAsync(params IReadOnlyList<object> arguments) => ExecuteAsync(arguments, CancellationToken.None);
/// <summary>Sends a command and reads its reply.</summary>
/// <param name="arguments">The command and its arguments.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reply.</returns>
public async Task<RespValue> ExecuteAsync(IReadOnlyList<object> arguments, CancellationToken cancellationToken)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
await _gate.WaitAsync(timeout.Token).ConfigureAwait(false);
try
{
if (_stream is null)
{
await ConnectAsync(timeout.Token).ConfigureAwait(false);
}
var reply = await SendAsync(arguments, timeout.Token).ConfigureAwait(false);
return reply.Kind == RespKind.Error ? throw new RedisException(reply.Text ?? "Redis error.") : reply;
}
catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException or AuthenticationException)
{
Close();
if (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)
{
throw new IOException("Redis did not answer in time.", ex);
}
throw;
}
finally
{
_gate.Release();
}
}
/// <inheritdoc />
public ValueTask DisposeAsync()
{
Close();
_gate.Dispose();
return ValueTask.CompletedTask;
}
private async Task ConnectAsync(CancellationToken cancellationToken)
{
var tcp = new TcpClient { NoDelay = true };
try
{
await tcp.ConnectAsync(Endpoint.Host, Endpoint.Port, cancellationToken).ConfigureAwait(false);
Stream stream = tcp.GetStream();
if (Endpoint.UseTls)
{
var ssl = new SslStream(stream, leaveInnerStreamOpen: false);
await ssl.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = Endpoint.Host }, cancellationToken).ConfigureAwait(false);
stream = ssl;
}
_tcp = tcp;
_stream = stream;
_reader = new BufferedReader(stream);
}
catch
{
tcp.Dispose();
throw;
}
if (Endpoint.Password is not null)
{
var auth = await SendAsync(Endpoint.User is null ? ["AUTH", Endpoint.Password] : ["AUTH", Endpoint.User, Endpoint.Password], cancellationToken).ConfigureAwait(false);
if (auth.Kind == RespKind.Error)
{
Close();
throw new RedisException("Redis refused the credentials.");
}
}
if (Endpoint.Database != 0)
{
var select = await SendAsync(["SELECT", Endpoint.Database], cancellationToken).ConfigureAwait(false);
if (select.Kind == RespKind.Error)
{
Close();
throw new RedisException(select.Text ?? "SELECT failed.");
}
}
}
private async Task<RespValue> SendAsync(IReadOnlyList<object> arguments, CancellationToken cancellationToken)
{
await _stream!.WriteAsync(Resp.Command(arguments), cancellationToken).ConfigureAwait(false);
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
return await Resp.ReadAsync(_reader!, cancellationToken).ConfigureAwait(false);
}
private void Close()
{
_stream?.Dispose();
_tcp?.Dispose();
_stream = null;
_tcp = null;
_reader = null;
}
}
/// <summary>
/// The shared cache on Redis (SPEC §9.3), for instances that run side by side. Values are JSON with a time to live.
/// When Redis cannot be reached the cache falls back to memory and says so in the log (once a minute): nothing fails
/// because of the cache.
/// </summary>
public sealed partial class RedisCacheProvider : ICacheProvider, IAsyncDisposable
{
private const string InvalidationChannel = "kh:invalidate";
private readonly RedisClient _client;
private readonly MemoryCacheProvider _fallback;
private readonly TimeProvider _clock;
private readonly ILogger<RedisCacheProvider> _logger;
private DateTimeOffset _lastWarning = DateTimeOffset.MinValue;
private volatile bool _healthy = true;
/// <summary>Creates the cache.</summary>
/// <param name="client">The Redis client.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public RedisCacheProvider(RedisClient client, TimeProvider clock, ILogger<RedisCacheProvider> logger)
{
ArgumentNullException.ThrowIfNull(client);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_client = client;
_clock = clock;
_logger = logger;
_fallback = new MemoryCacheProvider(clock);
}
/// <inheritdoc />
public bool IsDistributed => _healthy;
/// <inheritdoc />
public async ValueTask<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(key);
var reply = await TryAsync(["GET", key], cancellationToken).ConfigureAwait(false);
if (reply is null)
{
return await _fallback.GetAsync<T>(key, cancellationToken).ConfigureAwait(false);
}
return reply.Bytes is { } bytes ? JsonSerializer.Deserialize<T>(bytes) : default;
}
/// <inheritdoc />
public async ValueTask SetAsync<T>(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(key);
var json = JsonSerializer.SerializeToUtf8Bytes(value);
var milliseconds = Math.Max(1, (long)timeToLive.TotalMilliseconds);
if (await TryAsync(["SET", key, json, "PX", milliseconds], cancellationToken).ConfigureAwait(false) is null)
{
_fallback.SetRaw(key, json, timeToLive);
}
}
/// <inheritdoc />
public async ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(key);
await _fallback.RemoveAsync(key, cancellationToken).ConfigureAwait(false);
await TryAsync(["DEL", key], cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(prefix);
await _fallback.RemoveByPrefixAsync(prefix, cancellationToken).ConfigureAwait(false);
var cursor = "0";
do
{
var reply = await TryAsync(["SCAN", cursor, "MATCH", EscapePattern(prefix) + "*", "COUNT", 500], cancellationToken).ConfigureAwait(false);
if (reply?.Items is not [var next, { Items: { } keys }])
{
return;
}
cursor = next.Text ?? "0";
if (keys.Count > 0)
{
await TryAsync(["DEL", .. keys.Select(k => (object)k.Bytes!)], cancellationToken).ConfigureAwait(false);
}
}
while (cursor != "0");
}
/// <inheritdoc />
public async ValueTask<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, ValueTask<T>> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(factory);
var reply = await TryAsync(["GET", key], cancellationToken).ConfigureAwait(false);
if (reply is null)
{
return await _fallback.GetOrCreateAsync(key, factory, timeToLive, cancellationToken).ConfigureAwait(false);
}
if (reply.Bytes is { } bytes)
{
return JsonSerializer.Deserialize<T>(bytes)!;
}
var value = await factory(cancellationToken).ConfigureAwait(false);
await SetAsync(key, value, timeToLive, cancellationToken).ConfigureAwait(false);
return value;
}
/// <inheritdoc />
/// <remarks>Keys live only in Redis, so deleting them is enough; the message lets future local copies follow.</remarks>
public async ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default)
{
await RemoveByPrefixAsync(prefix, cancellationToken).ConfigureAwait(false);
await TryAsync(["PUBLISH", InvalidationChannel, prefix], cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks the connection (<c>PING</c>), for the start log and the system page.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when Redis answered.</returns>
public async Task<bool> PingAsync(CancellationToken cancellationToken = default) =>
(await TryAsync(["PING"], cancellationToken).ConfigureAwait(false))?.Text == "PONG";
/// <inheritdoc />
public ValueTask DisposeAsync() => _client.DisposeAsync();
/// <summary>Escapes the glob characters of a key prefix for <c>SCAN MATCH</c>.</summary>
/// <param name="prefix">The prefix.</param>
/// <returns>The escaped prefix.</returns>
public static string EscapePattern(string prefix)
{
ArgumentNullException.ThrowIfNull(prefix);
var builder = new System.Text.StringBuilder(prefix.Length + 8);
foreach (var c in prefix)
{
if (c is '*' or '?' or '[' or ']' or '\\')
{
builder.Append('\\');
}
builder.Append(c);
}
return builder.ToString();
}
private async Task<RespValue?> TryAsync(IReadOnlyList<object> arguments, CancellationToken cancellationToken)
{
try
{
var reply = await _client.ExecuteAsync(arguments, cancellationToken).ConfigureAwait(false);
if (!_healthy)
{
_healthy = true;
LogRecovered(_logger, _client.Endpoint.ToString());
}
return reply;
}
catch (Exception ex) when (ex is IOException or SocketException or RedisException or AuthenticationException)
{
_healthy = false;
var now = _clock.GetUtcNow();
if (now - _lastWarning > TimeSpan.FromMinutes(1))
{
_lastWarning = now;
LogUnavailable(_logger, _client.Endpoint.ToString(), ex.Message);
}
return null;
}
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Redis {Endpoint} is not available, the cache works in memory: {Reason}")]
private static partial void LogUnavailable(ILogger logger, string endpoint, string reason);
[LoggerMessage(Level = LogLevel.Information, Message = "Redis {Endpoint} is available again.")]
private static partial void LogRecovered(ILogger logger, string endpoint);
}