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,128 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Core.Caching;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// The in-memory cache of a single instance. Values are kept as JSON, like in Redis, so a cached object is never shared
|
||||
/// by reference between callers. Expired entries are removed when read and by a sweep every few hundred writes.
|
||||
/// </summary>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class MemoryCacheProvider(TimeProvider clock) : ICacheProvider
|
||||
{
|
||||
private const int SweepEvery = 512;
|
||||
private readonly ConcurrentDictionary<string, Entry> _entries = new(StringComparer.Ordinal);
|
||||
private int _writes;
|
||||
|
||||
/// <summary>Creates a cache on the system clock.</summary>
|
||||
public MemoryCacheProvider()
|
||||
: this(TimeProvider.System)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDistributed => false;
|
||||
|
||||
/// <summary>The number of entries, expired ones included until swept.</summary>
|
||||
public int Count => _entries.Count;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
if (_entries.TryGetValue(key, out var entry))
|
||||
{
|
||||
if (entry.ExpiresAt > clock.GetUtcNow())
|
||||
{
|
||||
return ValueTask.FromResult(JsonSerializer.Deserialize<T>(entry.Json));
|
||||
}
|
||||
|
||||
_entries.TryRemove(new KeyValuePair<string, Entry>(key, entry));
|
||||
}
|
||||
|
||||
return ValueTask.FromResult(default(T));
|
||||
}
|
||||
|
||||
/// <summary>Reads the raw JSON of a value (the Redis fallback uses it).</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns>The JSON, or <see langword="null"/>.</returns>
|
||||
public byte[]? GetRaw(string key) =>
|
||||
_entries.TryGetValue(key, out var entry) && entry.ExpiresAt > clock.GetUtcNow() ? entry.Json : null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask SetAsync<T>(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SetRaw(key, JsonSerializer.SerializeToUtf8Bytes(value), timeToLive);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Stores raw JSON.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="json">The JSON.</param>
|
||||
/// <param name="timeToLive">How long it stays.</param>
|
||||
public void SetRaw(string key, byte[] json, TimeSpan timeToLive)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
ArgumentNullException.ThrowIfNull(json);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(timeToLive, TimeSpan.Zero);
|
||||
_entries[key] = new Entry(json, clock.GetUtcNow() + timeToLive);
|
||||
if (Interlocked.Increment(ref _writes) % SweepEvery == 0)
|
||||
{
|
||||
Sweep();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
_entries.TryRemove(key, out _);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(prefix);
|
||||
foreach (var key in _entries.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)))
|
||||
{
|
||||
_entries.TryRemove(key, out _);
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<T> GetOrCreateAsync<T>(
|
||||
string key, Func<CancellationToken, ValueTask<T>> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
if (GetRaw(key) is { } json)
|
||||
{
|
||||
return JsonSerializer.Deserialize<T>(json)!;
|
||||
}
|
||||
|
||||
var value = await factory(cancellationToken).ConfigureAwait(false);
|
||||
await SetAsync(key, value, timeToLive, cancellationToken).ConfigureAwait(false);
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default) =>
|
||||
RemoveByPrefixAsync(prefix, cancellationToken);
|
||||
|
||||
/// <summary>Removes everything (used when Redis comes back, so stale local values are not served).</summary>
|
||||
public void Clear() => _entries.Clear();
|
||||
|
||||
private void Sweep()
|
||||
{
|
||||
var now = clock.GetUtcNow();
|
||||
foreach (var pair in _entries.Where(p => p.Value.ExpiresAt <= now))
|
||||
{
|
||||
_entries.TryRemove(pair);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record Entry(byte[] Json, DateTimeOffset ExpiresAt);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using System.Buffers;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Caching;
|
||||
|
||||
/// <summary>The kinds of RESP2 replies.</summary>
|
||||
public enum RespKind
|
||||
{
|
||||
/// <summary><c>+OK</c>.</summary>
|
||||
SimpleString = 0,
|
||||
|
||||
/// <summary><c>-ERR ...</c>.</summary>
|
||||
Error = 1,
|
||||
|
||||
/// <summary><c>:42</c>.</summary>
|
||||
Number = 2,
|
||||
|
||||
/// <summary><c>$5 hello</c>.</summary>
|
||||
BulkString = 3,
|
||||
|
||||
/// <summary><c>*2 ...</c>.</summary>
|
||||
Array = 4,
|
||||
|
||||
/// <summary><c>$-1</c> or <c>*-1</c>.</summary>
|
||||
Null = 5,
|
||||
}
|
||||
|
||||
/// <summary>A reply of the Redis protocol (RESP2).</summary>
|
||||
/// <param name="Kind">The kind.</param>
|
||||
/// <param name="Bytes">The bytes of a string or error.</param>
|
||||
/// <param name="Number">The value of an integer.</param>
|
||||
/// <param name="Items">The elements of an array.</param>
|
||||
public sealed record RespValue(RespKind Kind, byte[]? Bytes = null, long Number = 0, IReadOnlyList<RespValue>? Items = null)
|
||||
{
|
||||
/// <summary>The null reply.</summary>
|
||||
public static RespValue Null { get; } = new(RespKind.Null);
|
||||
|
||||
/// <summary>The text of a string or error reply.</summary>
|
||||
public string? Text => Bytes is null ? null : Encoding.UTF8.GetString(Bytes);
|
||||
}
|
||||
|
||||
/// <summary>A Redis error reply.</summary>
|
||||
public sealed class RedisException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public RedisException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a message.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
public RedisException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a message and a cause.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public RedisException(string message, Exception innerException) : base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Encodes commands and decodes replies of RESP2 (https://redis.io/docs/reference/protocol-spec/).</summary>
|
||||
public static class Resp
|
||||
{
|
||||
private static readonly byte[] CrLf = "\r\n"u8.ToArray();
|
||||
|
||||
/// <summary>Encodes a command as an array of bulk strings.</summary>
|
||||
/// <param name="arguments">The command and its arguments.</param>
|
||||
/// <returns>The bytes to send.</returns>
|
||||
public static byte[] Command(params IReadOnlyList<object> arguments)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(arguments);
|
||||
var buffer = new ArrayBufferWriter<byte>();
|
||||
Ascii(buffer, "*" + arguments.Count.ToString(CultureInfo.InvariantCulture));
|
||||
foreach (var argument in arguments)
|
||||
{
|
||||
var bytes = argument switch
|
||||
{
|
||||
byte[] raw => raw,
|
||||
string text => Encoding.UTF8.GetBytes(text),
|
||||
IFormattable number => Encoding.UTF8.GetBytes(number.ToString(null, CultureInfo.InvariantCulture)),
|
||||
_ => throw new ArgumentException("Arguments are strings, numbers or byte arrays.", nameof(arguments)),
|
||||
};
|
||||
Ascii(buffer, "$" + bytes.Length.ToString(CultureInfo.InvariantCulture));
|
||||
buffer.Write(bytes);
|
||||
buffer.Write(CrLf);
|
||||
}
|
||||
|
||||
return buffer.WrittenSpan.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Reads one reply.</summary>
|
||||
/// <param name="stream">The connection.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The reply.</returns>
|
||||
/// <exception cref="IOException">The connection closed or sent something that is not RESP.</exception>
|
||||
public static async Task<RespValue> ReadAsync(BufferedReader stream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var line = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (line.Length == 0)
|
||||
{
|
||||
throw new IOException("Empty RESP line.");
|
||||
}
|
||||
|
||||
var rest = line[1..];
|
||||
switch (line[0])
|
||||
{
|
||||
case '+':
|
||||
return new RespValue(RespKind.SimpleString, Encoding.UTF8.GetBytes(rest));
|
||||
case '-':
|
||||
return new RespValue(RespKind.Error, Encoding.UTF8.GetBytes(rest));
|
||||
case ':':
|
||||
return new RespValue(RespKind.Number, Number: Parse(rest));
|
||||
case '$':
|
||||
var length = Parse(rest);
|
||||
if (length < 0)
|
||||
{
|
||||
return RespValue.Null;
|
||||
}
|
||||
|
||||
var bytes = await stream.ReadExactlyAsync((int)length, cancellationToken).ConfigureAwait(false);
|
||||
var end = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false);
|
||||
return end.Length == 0 ? new RespValue(RespKind.BulkString, bytes) : throw new IOException("Bulk string without its line end.");
|
||||
case '*':
|
||||
var count = Parse(rest);
|
||||
if (count < 0)
|
||||
{
|
||||
return RespValue.Null;
|
||||
}
|
||||
|
||||
var items = new RespValue[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
items[i] = await ReadAsync(stream, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new RespValue(RespKind.Array, Items: items);
|
||||
default:
|
||||
throw new IOException("Unexpected RESP reply type.");
|
||||
}
|
||||
}
|
||||
|
||||
private static long Parse(string text) =>
|
||||
long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var value) ? value : throw new IOException("Invalid RESP length.");
|
||||
|
||||
private static void Ascii(ArrayBufferWriter<byte> buffer, string text)
|
||||
{
|
||||
buffer.Write(Encoding.ASCII.GetBytes(text));
|
||||
buffer.Write(CrLf);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads lines and fixed-size blocks from a stream, with its own buffer.</summary>
|
||||
/// <param name="stream">The stream.</param>
|
||||
public sealed class BufferedReader(Stream stream)
|
||||
{
|
||||
private readonly byte[] _buffer = new byte[16 * 1024];
|
||||
private int _start;
|
||||
private int _end;
|
||||
|
||||
/// <summary>Reads up to <c>\r\n</c> (not included), as ASCII.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The line.</returns>
|
||||
public async Task<string> ReadLineAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var line = new List<byte>();
|
||||
while (true)
|
||||
{
|
||||
for (var i = _start; i < _end; i++)
|
||||
{
|
||||
if (_buffer[i] == '\n' && (i > _start ? _buffer[i - 1] == '\r' : line.Count > 0 && line[^1] == '\r'))
|
||||
{
|
||||
line.AddRange(_buffer.AsSpan(_start, i - _start).ToArray());
|
||||
_start = i + 1;
|
||||
line.RemoveAt(line.Count - 1);
|
||||
return Encoding.UTF8.GetString([.. line]);
|
||||
}
|
||||
}
|
||||
|
||||
line.AddRange(_buffer.AsSpan(_start, _end - _start).ToArray());
|
||||
await FillAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads exactly <paramref name="count"/> bytes.</summary>
|
||||
/// <param name="count">How many.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The bytes.</returns>
|
||||
public async Task<byte[]> ReadExactlyAsync(int count, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new byte[count];
|
||||
var copied = 0;
|
||||
while (copied < count)
|
||||
{
|
||||
if (_start == _end)
|
||||
{
|
||||
await FillAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var take = Math.Min(count - copied, _end - _start);
|
||||
_buffer.AsSpan(_start, take).CopyTo(result.AsSpan(copied));
|
||||
_start += take;
|
||||
copied += take;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task FillAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_start = 0;
|
||||
_end = await stream.ReadAsync(_buffer, cancellationToken).ConfigureAwait(false);
|
||||
if (_end == 0)
|
||||
{
|
||||
throw new IOException("The Redis connection was closed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,11 @@
|
||||
<RootNamespace>Khaemhat.Infrastructure</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- The ASP.NET Core shared framework (logging, options, DataProtection, hosting): part of .NET, not a package. -->
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
|
||||
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Khaemhat.Infrastructure.Security;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Licensing;
|
||||
|
||||
/// <summary>
|
||||
/// An instance licence (SPEC §8.2). It travels as a <c>.khl</c> file: a JSON object with the licence and an ECDSA
|
||||
/// P-256 signature over its canonical form (<see cref="CanonicalBytes"/>).
|
||||
/// </summary>
|
||||
public sealed record LicenseDocument
|
||||
{
|
||||
/// <summary>The licence identifier.</summary>
|
||||
public string Id { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>The licence holder.</summary>
|
||||
public string Licensee { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>The instance the licence is bound to; <see langword="null"/> for any instance.</summary>
|
||||
public string? InstanceId { get; init; }
|
||||
|
||||
/// <summary>When it was issued (UTC).</summary>
|
||||
public DateTime IssuedAt { get; init; }
|
||||
|
||||
/// <summary>When it expires (UTC); <see langword="null"/> for no expiry.</summary>
|
||||
public DateTime? ExpiresAt { get; init; }
|
||||
|
||||
/// <summary>Concurrent users across all companies.</summary>
|
||||
public int MaxConcurrentUsers { get; init; }
|
||||
|
||||
/// <summary>Companies on the instance.</summary>
|
||||
public int MaxCompanies { get; init; }
|
||||
|
||||
/// <summary>The module codes.</summary>
|
||||
public IReadOnlyList<string> Modules { get; init; } = [];
|
||||
|
||||
/// <summary>Days of full use after the expiry, before read-only.</summary>
|
||||
public int GracePeriodDays { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The bytes that are signed: compact JSON with the properties in declaration order, modules upper-case and sorted,
|
||||
/// times in ISO 8601 UTC to the second. Two equal licences always give the same bytes.
|
||||
/// </summary>
|
||||
/// <returns>The UTF-8 bytes.</returns>
|
||||
public byte[] CanonicalBytes()
|
||||
{
|
||||
var canonical = new Canonical(
|
||||
Id,
|
||||
Licensee,
|
||||
InstanceId,
|
||||
Format(IssuedAt),
|
||||
ExpiresAt is { } expires ? Format(expires) : null,
|
||||
MaxConcurrentUsers,
|
||||
MaxCompanies,
|
||||
[.. Modules.Select(m => m.Trim().ToUpperInvariant()).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)],
|
||||
GracePeriodDays);
|
||||
return JsonSerializer.SerializeToUtf8Bytes(canonical, LicenseJson.Options);
|
||||
}
|
||||
|
||||
private static string Format(DateTime value) =>
|
||||
DateTime.SpecifyKind(value, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
|
||||
|
||||
private sealed record Canonical(
|
||||
string Id, string Licensee, string? InstanceId, string IssuedAt, string? ExpiresAt,
|
||||
int MaxConcurrentUsers, int MaxCompanies, string[] Modules, int GracePeriodDays);
|
||||
}
|
||||
|
||||
/// <summary>The JSON settings of licence files.</summary>
|
||||
internal static class LicenseJson
|
||||
{
|
||||
public static JsonSerializerOptions Options { get; } = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
||||
WriteIndented = false,
|
||||
};
|
||||
|
||||
public static JsonSerializerOptions Indented { get; } = new(Options) { WriteIndented = true };
|
||||
}
|
||||
|
||||
/// <summary>The outcome of a licence check. <see cref="Error"/> is <c>format_invalid</c> or <c>signature_invalid</c>.</summary>
|
||||
/// <param name="Document">The licence, when valid.</param>
|
||||
/// <param name="Error">The error code otherwise.</param>
|
||||
public sealed record LicenseVerification(LicenseDocument? Document, string? Error)
|
||||
{
|
||||
/// <summary>Whether the licence is authentic.</summary>
|
||||
public bool IsValid => Document is not null;
|
||||
}
|
||||
|
||||
/// <summary>Signs licences and activation codes. Used only by <c>tools/Khaemhat.LicenseTool</c>, with the private key.</summary>
|
||||
public static class LicenseSigner
|
||||
{
|
||||
/// <summary>The format marker of <c>.khl</c> files.</summary>
|
||||
public const string Format = "khl1";
|
||||
|
||||
/// <summary>Creates a key pair.</summary>
|
||||
/// <returns>The private key (PKCS#8 PEM) and the public key (SubjectPublicKeyInfo, base64).</returns>
|
||||
public static (string PrivateKeyPem, string PublicKeyBase64) CreateKeyPair()
|
||||
{
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
return (key.ExportPkcs8PrivateKeyPem(), Convert.ToBase64String(key.ExportSubjectPublicKeyInfo()));
|
||||
}
|
||||
|
||||
/// <summary>Signs a licence.</summary>
|
||||
/// <param name="document">The licence.</param>
|
||||
/// <param name="privateKey">The private key.</param>
|
||||
/// <returns>The <c>.khl</c> text.</returns>
|
||||
public static string Sign(LicenseDocument document, ECDsa privateKey)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(document);
|
||||
ArgumentNullException.ThrowIfNull(privateKey);
|
||||
var signature = privateKey.SignData(document.CanonicalBytes(), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
var file = new LicenseFile(Format, document, Convert.ToBase64String(signature));
|
||||
return JsonSerializer.Serialize(file, LicenseJson.Indented);
|
||||
}
|
||||
|
||||
/// <summary>Creates a signed activation code for one module (see <see cref="ModuleActivationCode"/>).</summary>
|
||||
/// <param name="module">The module code.</param>
|
||||
/// <param name="expiresMonth">The last month of validity.</param>
|
||||
/// <param name="instanceId">The instance it is bound to, or <see langword="null"/> for any instance.</param>
|
||||
/// <param name="privateKey">The private key.</param>
|
||||
/// <returns>The code.</returns>
|
||||
public static string SignActivationCode(string module, DateOnly expiresMonth, string? instanceId, ECDsa privateKey)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(module);
|
||||
ArgumentNullException.ThrowIfNull(privateKey);
|
||||
var payload = new byte[10];
|
||||
RandomNumberGenerator.Fill(payload.AsSpan(0, 5));
|
||||
ModuleActivationCode.InstanceTag(instanceId).CopyTo(payload.AsSpan(5));
|
||||
var body = ModuleActivationCode.Body(module.Trim().ToUpperInvariant(), expiresMonth, Base32.Encode(payload));
|
||||
var signature = privateKey.SignData(Encoding.ASCII.GetBytes(body), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
return body + "-" + Base32.Encode(signature);
|
||||
}
|
||||
|
||||
internal sealed record LicenseFile(string Format, LicenseDocument License, string Signature);
|
||||
}
|
||||
|
||||
/// <summary>Checks licences and activation codes with the public key built into the product (SPEC §8.2).</summary>
|
||||
public sealed class LicenseVerifier
|
||||
{
|
||||
/// <summary>
|
||||
/// The public key of the BalboSoft licences (SubjectPublicKeyInfo, base64). The private key never enters the repository.
|
||||
/// </summary>
|
||||
public const string ProductPublicKey =
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEE4ybLR3rfbtmjS7vRBg8WQOz6qNOPG8itlFy9MufvWrT/qoOfxCLwehR9DnKE77GXvqD2J+ZM0Fs6ccS84YBDw==";
|
||||
|
||||
private readonly byte[] _publicKey;
|
||||
|
||||
/// <summary>Creates a verifier.</summary>
|
||||
/// <param name="publicKeyBase64">The public key (SubjectPublicKeyInfo, base64).</param>
|
||||
public LicenseVerifier(string publicKeyBase64)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(publicKeyBase64);
|
||||
_publicKey = Convert.FromBase64String(publicKeyBase64);
|
||||
}
|
||||
|
||||
/// <summary>A verifier with <see cref="ProductPublicKey"/>.</summary>
|
||||
public static LicenseVerifier Product { get; } = new(ProductPublicKey);
|
||||
|
||||
/// <summary>Checks a <c>.khl</c> file.</summary>
|
||||
/// <param name="text">The file content.</param>
|
||||
/// <returns>The licence when the signature is valid.</returns>
|
||||
public LicenseVerification Verify(string text)
|
||||
{
|
||||
LicenseSigner.LicenseFile? file;
|
||||
try
|
||||
{
|
||||
file = JsonSerializer.Deserialize<LicenseSigner.LicenseFile>(text ?? string.Empty, LicenseJson.Options);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return new LicenseVerification(null, LicenseErrors.FormatInvalid);
|
||||
}
|
||||
|
||||
if (file is not { Format: LicenseSigner.Format, License: not null, Signature: not null })
|
||||
{
|
||||
return new LicenseVerification(null, LicenseErrors.FormatInvalid);
|
||||
}
|
||||
|
||||
byte[] signature;
|
||||
try
|
||||
{
|
||||
signature = Convert.FromBase64String(file.Signature);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return new LicenseVerification(null, LicenseErrors.FormatInvalid);
|
||||
}
|
||||
|
||||
return VerifySignature(file.License.CanonicalBytes(), signature)
|
||||
? new LicenseVerification(file.License, null)
|
||||
: new LicenseVerification(null, LicenseErrors.SignatureInvalid);
|
||||
}
|
||||
|
||||
/// <summary>Checks a module activation code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The parsed code when the signature is valid, or the error code.</returns>
|
||||
public (ModuleActivationCode? Code, string? Error) VerifyActivationCode(string code)
|
||||
{
|
||||
if (!ModuleActivationCode.TryParse(code, out var parsed, out var signature))
|
||||
{
|
||||
return (null, LicenseErrors.FormatInvalid);
|
||||
}
|
||||
|
||||
return VerifySignature(Encoding.ASCII.GetBytes(parsed.SignedBody), signature)
|
||||
? (parsed, null)
|
||||
: (null, LicenseErrors.SignatureInvalid);
|
||||
}
|
||||
|
||||
private bool VerifySignature(byte[] data, byte[] signature)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = ECDsa.Create();
|
||||
key.ImportSubjectPublicKeyInfo(_publicKey, out _);
|
||||
return key.VerifyData(data, signature, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
}
|
||||
catch (CryptographicException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An activation code for one module: <c>KH1-<MODULE>-<YYYYMM>-<payload base32>-<signature base32></c>
|
||||
/// (SPEC §8.2). The payload holds a serial and a tag of the instance (zeros for any instance); the module stays active
|
||||
/// until the end of the month <c>YYYYMM</c>.
|
||||
/// </summary>
|
||||
public sealed record ModuleActivationCode(string Module, DateOnly ExpiresMonth, string Payload)
|
||||
{
|
||||
/// <summary>The format version.</summary>
|
||||
public const string Prefix = "KH1";
|
||||
|
||||
/// <summary>The text that is signed (everything before the signature).</summary>
|
||||
public string SignedBody => Body(Module, ExpiresMonth, Payload);
|
||||
|
||||
/// <summary>The last moment of validity: the end of <see cref="ExpiresMonth"/> (UTC).</summary>
|
||||
public DateTime ExpiresAt => new DateTime(ExpiresMonth.Year, ExpiresMonth.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddTicks(-10);
|
||||
|
||||
/// <summary>Whether the code works on an instance.</summary>
|
||||
/// <param name="instanceId">The instance identifier.</param>
|
||||
/// <returns><see langword="true"/> if the code is for any instance or for this one.</returns>
|
||||
public bool IsFor(string instanceId)
|
||||
{
|
||||
var tag = Base32.Decode(Payload).AsSpan(5);
|
||||
return tag.IndexOfAnyExcept((byte)0) < 0 || tag.SequenceEqual(InstanceTag(instanceId));
|
||||
}
|
||||
|
||||
internal static string Body(string module, DateOnly expiresMonth, string payload) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{Prefix}-{module}-{expiresMonth.Year:D4}{expiresMonth.Month:D2}-{payload}");
|
||||
|
||||
internal static byte[] InstanceTag(string? instanceId) =>
|
||||
instanceId is null ? new byte[5] : SHA256.HashData(Encoding.UTF8.GetBytes(instanceId.Trim().ToUpperInvariant()))[..5];
|
||||
|
||||
internal static bool TryParse(string? text, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out ModuleActivationCode? code, out byte[] signature)
|
||||
{
|
||||
code = null;
|
||||
signature = [];
|
||||
var parts = text?.Trim().ToUpperInvariant().Split('-');
|
||||
if (parts is not { Length: 5 } || parts[0] != Prefix || parts[1].Length is < 2 or > 10 || parts[2].Length != 6
|
||||
|| !int.TryParse(parts[2][..4], NumberStyles.None, CultureInfo.InvariantCulture, out var year)
|
||||
|| !int.TryParse(parts[2][4..], NumberStyles.None, CultureInfo.InvariantCulture, out var month)
|
||||
|| year < 2000 || month is < 1 or > 12)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (Base32.Decode(parts[3]).Length != 10)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
signature = Base32.Decode(parts[4]);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
code = new ModuleActivationCode(parts[1], new DateOnly(year, month, 1), parts[3]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The error codes of licences.</summary>
|
||||
public static class LicenseErrors
|
||||
{
|
||||
/// <summary>The text is not a licence or a code.</summary>
|
||||
public const string FormatInvalid = "format_invalid";
|
||||
|
||||
/// <summary>The signature does not match: changed or not issued by BalboSoft.</summary>
|
||||
public const string SignatureInvalid = "signature_invalid";
|
||||
|
||||
/// <summary>A fictitious code outside test mode (SPEC §8.3).</summary>
|
||||
public const string TestOnly = "license_test_only";
|
||||
|
||||
/// <summary>The licence or code has expired.</summary>
|
||||
public const string Expired = "license_expired";
|
||||
|
||||
/// <summary>The licence or code belongs to another instance.</summary>
|
||||
public const string WrongInstance = "license_wrong_instance";
|
||||
|
||||
/// <summary>The module code is unknown.</summary>
|
||||
public const string UnknownModule = "module_unknown";
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Logging;
|
||||
using Khaemhat.Data;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// The database half of the single log pipeline (SPEC §9.5): every event that passes the filters goes to stdout (JSON
|
||||
/// console) and here to <c>sys_log</c>. Events are queued and written in batches by <see cref="DbLogSink"/>; until the
|
||||
/// system database is ready (<see cref="DbLogSink.Start"/>) they wait in the queue. Section, trace, user, company and
|
||||
/// request come from the logging scopes.
|
||||
/// </summary>
|
||||
[ProviderAlias("Database")]
|
||||
public sealed class DbLoggerProvider : ILoggerProvider, ISupportExternalScope
|
||||
{
|
||||
private readonly DbLogSink _sink;
|
||||
private IExternalScopeProvider _scopes = new LoggerExternalScopeProvider();
|
||||
|
||||
/// <summary>Creates the provider.</summary>
|
||||
/// <param name="sink">The queue that writes the events.</param>
|
||||
public DbLoggerProvider(DbLogSink sink)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sink);
|
||||
_sink = sink;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ILogger CreateLogger(string categoryName) => new DbLogger(categoryName, this);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SetScopeProvider(IExternalScopeProvider scopeProvider) => _scopes = scopeProvider ?? new LoggerExternalScopeProvider();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
private sealed class DbLogger(string category, DbLoggerProvider provider) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state)
|
||||
where TState : notnull => provider._scopes.Push(state);
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None && !DbLogSink.IsWriting;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel) || category.StartsWith(typeof(DbLogSink).Namespace!, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var entry = new LogEntry
|
||||
{
|
||||
At = DateTime.UtcNow,
|
||||
Level = logLevel.ToString(),
|
||||
Section = LogSections.FromCategory(category).ToString(),
|
||||
Source = category.Length > 200 ? category[..200] : category,
|
||||
Message = formatter(state, exception),
|
||||
Exception = exception?.ToString(),
|
||||
};
|
||||
|
||||
var data = new Dictionary<string, object?>(StringComparer.Ordinal);
|
||||
if (state is IEnumerable<KeyValuePair<string, object?>> values)
|
||||
{
|
||||
foreach (var (key, value) in values)
|
||||
{
|
||||
if (key != "{OriginalFormat}")
|
||||
{
|
||||
data[key] = Simple(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider._scopes.ForEachScope(
|
||||
static (scope, target) =>
|
||||
{
|
||||
if (scope is not IEnumerable<KeyValuePair<string, object?>> pairs)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var (key, value) in pairs)
|
||||
{
|
||||
var text = value?.ToString();
|
||||
switch (key)
|
||||
{
|
||||
case LogSections.ScopeKey when text is not null: target.Entry.Section = text; break;
|
||||
case LogSections.TraceIdKey: target.Entry.TraceId = Clip(text, 64); break;
|
||||
case LogSections.UserKey: target.Entry.UserName = Clip(text, 100); break;
|
||||
case LogSections.CompanyKey: target.Entry.CompanyCode = Clip(text, 20); break;
|
||||
case LogSections.RequestKey: target.Entry.Request = Clip(text, 400); break;
|
||||
case LogSections.EntityKey: target.Entry.Entity = Clip(text, 100); break;
|
||||
case LogSections.EntityIdKey: target.Entry.EntityId = Clip(text, 100); break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
},
|
||||
(Entry: entry, Data: data));
|
||||
|
||||
if (data.Count > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
entry.Data = JsonSerializer.Serialize(data);
|
||||
}
|
||||
catch (NotSupportedException)
|
||||
{
|
||||
entry.Data = null;
|
||||
}
|
||||
}
|
||||
|
||||
provider._sink.Enqueue(entry);
|
||||
}
|
||||
|
||||
private static object? Simple(object? value) => value switch
|
||||
{
|
||||
null or string or bool or int or long or double or decimal or float or short or byte => value,
|
||||
DateTime or DateTimeOffset or Guid or TimeSpan or Enum => value.ToString(),
|
||||
_ => value.ToString(),
|
||||
};
|
||||
|
||||
private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes queued log events to <c>sys_log</c> in batches (up to 200 events or every second). The queue is bounded:
|
||||
/// when the database cannot keep up the oldest events are dropped, never the application. Events logged while the
|
||||
/// sink itself writes are ignored, so a database error cannot loop.
|
||||
/// </summary>
|
||||
public sealed class DbLogSink : IAsyncDisposable
|
||||
{
|
||||
private const int BatchSize = 200;
|
||||
private static readonly AsyncLocal<bool> Writing = new();
|
||||
private readonly Channel<LogEntry> _queue = Channel.CreateBounded<LogEntry>(
|
||||
new BoundedChannelOptions(20_000) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
|
||||
|
||||
private IUnitOfWorkFactory? _factory;
|
||||
private Task? _writer;
|
||||
private CancellationTokenSource? _stopping;
|
||||
|
||||
/// <summary>Whether the current flow is the sink writing (its own events are not logged to the database).</summary>
|
||||
public static bool IsWriting => Writing.Value;
|
||||
|
||||
/// <summary>Events written since the start.</summary>
|
||||
public long Written { get; private set; }
|
||||
|
||||
/// <summary>Events lost because the database failed.</summary>
|
||||
public long Failed { get; private set; }
|
||||
|
||||
/// <summary>Queues an event.</summary>
|
||||
/// <param name="entry">The event.</param>
|
||||
public void Enqueue(LogEntry entry) => _queue.Writer.TryWrite(entry);
|
||||
|
||||
/// <summary>Starts writing, once the system database is migrated.</summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
public void Start(IUnitOfWorkFactory factory)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
if (_writer is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_factory = factory;
|
||||
_stopping = new CancellationTokenSource();
|
||||
_writer = Task.Run(() => RunAsync(_stopping.Token));
|
||||
}
|
||||
|
||||
/// <summary>Writes what is queued now (tests, shutdown).</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task FlushAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var batch = new List<LogEntry>();
|
||||
while (_queue.Reader.TryRead(out var entry))
|
||||
{
|
||||
batch.Add(entry);
|
||||
if (batch.Count == BatchSize)
|
||||
{
|
||||
await WriteAsync(batch, cancellationToken).ConfigureAwait(false);
|
||||
batch.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
if (batch.Count > 0)
|
||||
{
|
||||
await WriteAsync(batch, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_stopping is null || _writer is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _stopping.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await _writer.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
|
||||
await FlushAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
_stopping.Dispose();
|
||||
}
|
||||
|
||||
private async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await _queue.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false);
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
|
||||
await FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WriteAsync(List<LogEntry> batch, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_factory is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Writing.Value = true;
|
||||
try
|
||||
{
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var repository = unitOfWork.Repository<LogEntry, long>();
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
foreach (var entry in batch)
|
||||
{
|
||||
await repository.InsertAsync(entry, ct).ConfigureAwait(false);
|
||||
}
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
Written += batch.Count;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
Failed += batch.Count;
|
||||
await Console.Error.WriteLineAsync(new StringBuilder("Khaemhat: log events not written to sys_log: ").Append(ex.GetType().Name).Append(' ').Append(ex.Message), CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Writing.Value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Security;
|
||||
|
||||
/// <summary>Base32 of RFC 4648 (alphabet <c>A-Z2-7</c>), used by TOTP secrets and activation codes. No padding is written.</summary>
|
||||
public static class Base32
|
||||
{
|
||||
private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
|
||||
/// <summary>Encodes bytes.</summary>
|
||||
/// <param name="data">The bytes.</param>
|
||||
/// <returns>The text, without padding.</returns>
|
||||
public static string Encode(ReadOnlySpan<byte> data)
|
||||
{
|
||||
var builder = new StringBuilder((data.Length * 8 + 4) / 5);
|
||||
int buffer = 0, bits = 0;
|
||||
foreach (var b in data)
|
||||
{
|
||||
buffer = (buffer << 8) | b;
|
||||
bits += 8;
|
||||
while (bits >= 5)
|
||||
{
|
||||
builder.Append(Alphabet[(buffer >> (bits - 5)) & 31]);
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
|
||||
if (bits > 0)
|
||||
{
|
||||
builder.Append(Alphabet[(buffer << (5 - bits)) & 31]);
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Decodes text; spaces, dashes and padding are ignored, letters may be lower-case.</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <returns>The bytes.</returns>
|
||||
/// <exception cref="FormatException">A character is not in the alphabet.</exception>
|
||||
public static byte[] Decode(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var output = new List<byte>(text.Length * 5 / 8);
|
||||
int buffer = 0, bits = 0;
|
||||
foreach (var raw in text)
|
||||
{
|
||||
if (raw is ' ' or '-' or '=')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var index = Alphabet.IndexOf(char.ToUpperInvariant(raw), StringComparison.Ordinal);
|
||||
if (index < 0)
|
||||
{
|
||||
throw new FormatException("The text is not valid base32.");
|
||||
}
|
||||
|
||||
buffer = (buffer << 5) | index;
|
||||
bits += 5;
|
||||
if (bits >= 8)
|
||||
{
|
||||
output.Add((byte)((buffer >> (bits - 8)) & 0xFF));
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
|
||||
return [.. output];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using System.Xml.Linq;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Microsoft.AspNetCore.DataProtection.Repositories;
|
||||
using Microsoft.AspNetCore.DataProtection.XmlEncryption;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// The ASP.NET Core DataProtection key ring in <c>sys_data_protection_keys</c> (SPEC §1.5: no key files on disk), so
|
||||
/// that cookies, antiforgery tokens and circuits survive restarts and are shared by instances on the same system
|
||||
/// database. Keys are encrypted with <see cref="SecretKeyXmlEncryptor"/>.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
public sealed class DataProtectionKeyStore(IUnitOfWorkFactory factory) : IXmlRepository
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<XElement> GetAllElements() =>
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System).ConfigureAwait(false);
|
||||
var rows = await unitOfWork.Repository<DataProtectionKey, long>().ListAsync(Query.For<DataProtectionKey>().OrderBy(k => k.Id)).ConfigureAwait(false);
|
||||
return (IReadOnlyCollection<XElement>)[.. rows.Items.Select(k => XElement.Parse(k.Xml))];
|
||||
}).GetAwaiter().GetResult();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void StoreElement(XElement element, string friendlyName)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(element);
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System).ConfigureAwait(false);
|
||||
await unitOfWork.Repository<DataProtectionKey, long>().InsertAsync(new DataProtectionKey
|
||||
{
|
||||
FriendlyName = friendlyName.Length > 200 ? friendlyName[..200] : friendlyName,
|
||||
Xml = element.ToString(SaveOptions.DisableFormatting),
|
||||
}).ConfigureAwait(false);
|
||||
}).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Encrypts DataProtection keys with the instance key (<c>KHAEMHAT_SECRET_KEY</c>).</summary>
|
||||
/// <param name="protector">The instance key.</param>
|
||||
public sealed class SecretKeyXmlEncryptor(ISecretProtector protector) : IXmlEncryptor
|
||||
{
|
||||
/// <summary>The purpose of the encryption.</summary>
|
||||
public const string Purpose = "dataprotection:keys";
|
||||
|
||||
/// <inheritdoc />
|
||||
public EncryptedXmlInfo Encrypt(XElement plaintextElement)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plaintextElement);
|
||||
var value = protector.Protect(plaintextElement.ToString(SaveOptions.DisableFormatting), Purpose);
|
||||
return new EncryptedXmlInfo(new XElement("khaemhatEncryptedKey", new XElement("value", value)), typeof(SecretKeyXmlDecryptor));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Decrypts what <see cref="SecretKeyXmlEncryptor"/> wrote; created by DataProtection with the service provider.</summary>
|
||||
public sealed class SecretKeyXmlDecryptor : IXmlDecryptor
|
||||
{
|
||||
private readonly ISecretProtector _protector;
|
||||
|
||||
/// <summary>Creates the decryptor.</summary>
|
||||
/// <param name="services">The services, holding the instance key.</param>
|
||||
public SecretKeyXmlDecryptor(IServiceProvider services) => _protector = services.GetRequiredService<ISecretProtector>();
|
||||
|
||||
/// <inheritdoc />
|
||||
public XElement Decrypt(XElement encryptedElement)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(encryptedElement);
|
||||
var value = encryptedElement.Element("value")?.Value ?? throw new SecretProtectionException("The DataProtection key has no value.");
|
||||
return XElement.Parse(_protector.Unprotect(value, SecretKeyXmlEncryptor.Purpose));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Security;
|
||||
|
||||
/// <summary>The result of checking a password against a stored hash.</summary>
|
||||
public enum PasswordVerification
|
||||
{
|
||||
/// <summary>The password does not match (or the hash is not readable).</summary>
|
||||
Failed = 0,
|
||||
|
||||
/// <summary>The password matches.</summary>
|
||||
Succeeded = 1,
|
||||
|
||||
/// <summary>The password matches, but the hash uses older parameters: store a new hash.</summary>
|
||||
SucceededRehashNeeded = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Password hashes with PBKDF2-HMAC-SHA256 (SPEC §7.3): 600,000 iterations, a random 16-byte salt and a 32-byte
|
||||
/// result, stored as <c>pbkdf2-sha256$600000$<salt base64>$<hash base64></c>. The comparison runs in
|
||||
/// constant time.
|
||||
/// </summary>
|
||||
public static class PasswordHasher
|
||||
{
|
||||
/// <summary>The algorithm prefix of the stored format.</summary>
|
||||
public const string Algorithm = "pbkdf2-sha256";
|
||||
|
||||
/// <summary>The iterations of new hashes (OWASP 2023 recommendation for PBKDF2-HMAC-SHA256).</summary>
|
||||
public const int Iterations = 600_000;
|
||||
|
||||
private const int SaltLength = 16;
|
||||
private const int HashLength = 32;
|
||||
|
||||
/// <summary>Hashes a password with a new random salt.</summary>
|
||||
/// <param name="password">The password.</param>
|
||||
/// <returns>The stored form.</returns>
|
||||
public static string Hash(string password) => Hash(password, Iterations);
|
||||
|
||||
/// <summary>Hashes a password with the given iterations (tests use fewer to stay fast).</summary>
|
||||
/// <param name="password">The password.</param>
|
||||
/// <param name="iterations">The PBKDF2 iterations.</param>
|
||||
/// <returns>The stored form.</returns>
|
||||
public static string Hash(string password, int iterations)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(password);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(iterations, 1);
|
||||
var salt = RandomNumberGenerator.GetBytes(SaltLength);
|
||||
var hash = Derive(password, salt, iterations);
|
||||
return string.Join('$', Algorithm, iterations.ToString(CultureInfo.InvariantCulture), Convert.ToBase64String(salt), Convert.ToBase64String(hash));
|
||||
}
|
||||
|
||||
/// <summary>Checks a password against a stored hash.</summary>
|
||||
/// <param name="storedHash">The stored form; <see langword="null"/> never matches.</param>
|
||||
/// <param name="password">The password typed.</param>
|
||||
/// <returns>The outcome.</returns>
|
||||
public static PasswordVerification Verify(string? storedHash, string password)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(password);
|
||||
if (!TryParse(storedHash, out var iterations, out var salt, out var expected))
|
||||
{
|
||||
return PasswordVerification.Failed;
|
||||
}
|
||||
|
||||
var actual = Derive(password, salt, iterations, expected.Length);
|
||||
if (!CryptographicOperations.FixedTimeEquals(actual, expected))
|
||||
{
|
||||
return PasswordVerification.Failed;
|
||||
}
|
||||
|
||||
return iterations < Iterations ? PasswordVerification.SucceededRehashNeeded : PasswordVerification.Succeeded;
|
||||
}
|
||||
|
||||
private static byte[] Derive(string password, byte[] salt, int iterations, int length = HashLength)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(password);
|
||||
try
|
||||
{
|
||||
return Rfc2898DeriveBytes.Pbkdf2(bytes, salt, iterations, HashAlgorithmName.SHA256, length);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryParse(string? stored, out int iterations, out byte[] salt, out byte[] hash)
|
||||
{
|
||||
iterations = 0;
|
||||
salt = [];
|
||||
hash = [];
|
||||
var parts = stored?.Split('$');
|
||||
if (parts is not { Length: 4 } || parts[0] != Algorithm
|
||||
|| !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out iterations) || iterations < 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
salt = Convert.FromBase64String(parts[2]);
|
||||
hash = Convert.FromBase64String(parts[3]);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return salt.Length >= 8 && hash.Length >= 16;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Random tokens for sessions, password recovery and recovery codes. Tokens are URL-safe base64 without padding; the
|
||||
/// database stores only <see cref="Hash"/>, so a copy of a table does not reveal a usable token.
|
||||
/// </summary>
|
||||
public static class SecureTokenGenerator
|
||||
{
|
||||
/// <summary>A token of <paramref name="bytes"/> random bytes (32 = 256 bits).</summary>
|
||||
/// <param name="bytes">The entropy in bytes.</param>
|
||||
/// <returns>The token.</returns>
|
||||
public static string Create(int bytes = 32)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(bytes, 16);
|
||||
return Base64Url(RandomNumberGenerator.GetBytes(bytes));
|
||||
}
|
||||
|
||||
/// <summary>A short code for people: groups of letters and digits without look-alikes, for example <c>K7QM-2XRP</c>.</summary>
|
||||
/// <param name="groups">The number of groups of four characters.</param>
|
||||
/// <returns>The code.</returns>
|
||||
public static string CreateReadableCode(int groups = 2)
|
||||
{
|
||||
const string Alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(groups, 1);
|
||||
var builder = new StringBuilder(groups * 5);
|
||||
for (var g = 0; g < groups; g++)
|
||||
{
|
||||
if (g > 0)
|
||||
{
|
||||
builder.Append('-');
|
||||
}
|
||||
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
builder.Append(Alphabet[RandomNumberGenerator.GetInt32(Alphabet.Length)]);
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The SHA-256 hash of a token in lower-case hexadecimal, as stored in the database.</summary>
|
||||
/// <param name="token">The token.</param>
|
||||
/// <returns>64 hexadecimal digits.</returns>
|
||||
public static string Hash(string token)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(token);
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||
}
|
||||
|
||||
/// <summary>Compares two token hashes in constant time.</summary>
|
||||
/// <param name="a">A hash.</param>
|
||||
/// <param name="b">Another hash.</param>
|
||||
/// <returns>Whether they are equal.</returns>
|
||||
public static bool HashesEqual(string? a, string? b) =>
|
||||
a is not null && b is not null
|
||||
&& CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(a), Encoding.ASCII.GetBytes(b));
|
||||
|
||||
private static string Base64Url(byte[] data) =>
|
||||
Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Time-based one-time passwords of RFC 6238 with the parameters every authenticator app supports: HMAC-SHA1,
|
||||
/// 6 digits, 30-second steps. Verification accepts one step before and after the current one (clock drift) and never
|
||||
/// the same step twice.
|
||||
/// </summary>
|
||||
public static class TotpGenerator
|
||||
{
|
||||
/// <summary>The length of a step in seconds.</summary>
|
||||
public const int StepSeconds = 30;
|
||||
|
||||
/// <summary>The number of digits.</summary>
|
||||
public const int Digits = 6;
|
||||
|
||||
/// <summary>The length of new secrets in bytes (160 bits, as RFC 4226 recommends).</summary>
|
||||
public const int SecretLength = 20;
|
||||
|
||||
/// <summary>A new random secret in base32, to show to the user and store encrypted.</summary>
|
||||
/// <returns>The secret.</returns>
|
||||
public static string CreateSecret() => Base32.Encode(RandomNumberGenerator.GetBytes(SecretLength));
|
||||
|
||||
/// <summary>The time step of a moment.</summary>
|
||||
/// <param name="time">The moment.</param>
|
||||
/// <returns>The step number.</returns>
|
||||
public static long StepOf(DateTimeOffset time) => time.ToUnixTimeSeconds() / StepSeconds;
|
||||
|
||||
/// <summary>The code of a step.</summary>
|
||||
/// <param name="secret">The secret bytes.</param>
|
||||
/// <param name="step">The step number.</param>
|
||||
/// <returns>The code, zero-padded to six digits.</returns>
|
||||
public static string Compute(ReadOnlySpan<byte> secret, long step)
|
||||
{
|
||||
Span<byte> counter = stackalloc byte[8];
|
||||
BinaryPrimitives.WriteInt64BigEndian(counter, step);
|
||||
Span<byte> hash = stackalloc byte[20];
|
||||
#pragma warning disable CA5350 // RFC 6238 and the authenticator apps use HMAC-SHA1; it is not used here for collision resistance.
|
||||
HMACSHA1.HashData(secret, counter, hash);
|
||||
#pragma warning restore CA5350
|
||||
var offset = hash[^1] & 0x0F;
|
||||
var binary = ((hash[offset] & 0x7F) << 24) | (hash[offset + 1] << 16) | (hash[offset + 2] << 8) | hash[offset + 3];
|
||||
return (binary % 1_000_000).ToString("D6", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>Checks a code.</summary>
|
||||
/// <param name="secretBase32">The secret in base32.</param>
|
||||
/// <param name="code">The code typed (spaces are ignored).</param>
|
||||
/// <param name="now">The current time.</param>
|
||||
/// <param name="lastUsedStep">The last step accepted for this account, or <see langword="null"/>.</param>
|
||||
/// <returns>The matching step, to store as the last used one; <see langword="null"/> if the code is not valid.</returns>
|
||||
public static long? Verify(string secretBase32, string? code, DateTimeOffset now, long? lastUsedStep)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(secretBase32);
|
||||
var digits = code?.Replace(" ", string.Empty, StringComparison.Ordinal);
|
||||
if (digits is not { Length: Digits } || !digits.All(char.IsAsciiDigit))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var secret = Base32.Decode(secretBase32);
|
||||
try
|
||||
{
|
||||
var current = StepOf(now);
|
||||
for (var step = current - 1; step <= current + 1; step++)
|
||||
{
|
||||
if (lastUsedStep is { } last && step <= last)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var expected = Compute(secret, step);
|
||||
if (CryptographicOperations.FixedTimeEquals(
|
||||
System.Text.Encoding.ASCII.GetBytes(expected), System.Text.Encoding.ASCII.GetBytes(digits)))
|
||||
{
|
||||
return step;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(secret);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <c>otpauth://</c> address that authenticator apps read (key URI format), for the QR code or a link.
|
||||
/// </summary>
|
||||
/// <param name="secretBase32">The secret in base32.</param>
|
||||
/// <param name="account">The account label, for example <c>root@DEMO</c>.</param>
|
||||
/// <param name="issuer">The issuer shown by the app.</param>
|
||||
/// <returns>The address.</returns>
|
||||
public static string ProvisioningUri(string secretBase32, string account, string issuer = "Khaemhat")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(secretBase32);
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(issuer);
|
||||
var label = Uri.EscapeDataString(issuer) + ":" + Uri.EscapeDataString(account);
|
||||
return $"otpauth://totp/{label}?secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm=SHA1&digits={Digits}&period={StepSeconds}";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user