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,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-&lt;MODULE&gt;-&lt;YYYYMM&gt;-&lt;payload base32&gt;-&lt;signature base32&gt;</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";
}