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

+176 -5
View File
@@ -1,6 +1,177 @@
// Khaemhat.LicenseTool: key pair, issuing and verification of .khl licences (SPEC §8). The private key never
// enters the repository. Completed in milestone M2; until then it only explains that and exits with an error.
// Khaemhat.LicenseTool: key pair, issuing and verification of .khl licences and module activation codes (SPEC §8.2).
// The private key (.khkey, PKCS#8 PEM) stays outside the repository: .gitignore excludes *.khkey and *.pem.
Console.Error.WriteLine("Khaemhat.LicenseTool: non ancora disponibile, arriva con la milestone M2 (SPEC §8).");
Console.Error.WriteLine("Comandi previsti: keygen, issue, verify.");
return 1;
using System.Globalization;
using System.Security.Cryptography;
using Khaemhat.Infrastructure.Licensing;
const string Usage = """
Khaemhat.LicenseTool
keygen --out <file.khkey>
Creates a key pair: writes the private key and prints the public key to put in LicenseVerifier.ProductPublicKey.
issue --key <file.khkey> --licensee <name> --modules CORE,ACCT,... --users <n> --companies <n>
[--expires yyyy-mm-dd] [--grace <days>] [--instance <id>] [--id <id>] --out <file.khl>
Signs an instance licence.
code --key <file.khkey> --module <CODE> --expires yyyy-mm [--instance <id>]
Signs an activation code for one module.
verify <file.khl | activation code> [--public-key <base64>]
Checks a licence or a code with the product public key (or the one given).
""";
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
{
Console.WriteLine(Usage);
return args.Length == 0 ? 1 : 0;
}
try
{
var options = Options.Parse(args.Skip(1));
return args[0] switch
{
"keygen" => KeyGen(options),
"issue" => Issue(options),
"code" => Code(options),
"verify" => Verify(options),
_ => Fail($"Unknown command '{args[0]}'.\n\n{Usage}"),
};
}
catch (Exception ex) when (ex is ArgumentException or FormatException or IOException or CryptographicException or UnauthorizedAccessException)
{
return Fail(ex.Message);
}
static int KeyGen(Options options)
{
var path = options.Required("out");
if (File.Exists(path))
{
return Fail($"{path} exists: the tool never overwrites a key.");
}
var (privateKey, publicKey) = LicenseSigner.CreateKeyPair();
File.WriteAllText(path, privateKey);
Console.WriteLine($"Private key written to {path}. Keep it outside the repository and back it up.");
Console.WriteLine("Public key (LicenseVerifier.ProductPublicKey):");
Console.WriteLine(publicKey);
return 0;
}
static int Issue(Options options)
{
using var key = LoadKey(options.Required("key"));
var document = new LicenseDocument
{
Id = options.Optional("id") ?? "KHL-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture),
Licensee = options.Required("licensee"),
InstanceId = options.Optional("instance"),
IssuedAt = DateTime.UtcNow,
ExpiresAt = options.Optional("expires") is { } expires
? DateTime.SpecifyKind(DateTime.ParseExact(expires, "yyyy-MM-dd", CultureInfo.InvariantCulture).AddDays(1).AddSeconds(-1), DateTimeKind.Utc)
: null,
MaxConcurrentUsers = int.Parse(options.Required("users"), CultureInfo.InvariantCulture),
MaxCompanies = int.Parse(options.Required("companies"), CultureInfo.InvariantCulture),
Modules = [.. options.Required("modules").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)],
GracePeriodDays = int.Parse(options.Optional("grace") ?? "30", CultureInfo.InvariantCulture),
};
var path = options.Required("out");
File.WriteAllText(path, LicenseSigner.Sign(document, key));
Console.WriteLine($"Licence {document.Id} for {document.Licensee} written to {path}.");
return 0;
}
static int Code(Options options)
{
using var key = LoadKey(options.Required("key"));
var month = DateOnly.ParseExact(options.Required("expires") + "-01", "yyyy-MM-dd", CultureInfo.InvariantCulture);
Console.WriteLine(LicenseSigner.SignActivationCode(options.Required("module"), month, options.Optional("instance"), key));
return 0;
}
static int Verify(Options options)
{
var input = options.Positional ?? throw new ArgumentException("Give a .khl file or an activation code.");
var verifier = options.Optional("public-key") is { } publicKey ? new LicenseVerifier(publicKey) : LicenseVerifier.Product;
if (File.Exists(input))
{
var result = verifier.Verify(File.ReadAllText(input));
if (!result.IsValid)
{
return Fail($"Not valid: {result.Error}.");
}
var d = result.Document!;
Console.WriteLine($"Valid licence {d.Id} for {d.Licensee}: modules {string.Join(',', d.Modules)}, {d.MaxConcurrentUsers} users, "
+ $"{d.MaxCompanies} companies, expires {d.ExpiresAt?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) ?? "never"}, grace {d.GracePeriodDays} days.");
return 0;
}
var (code, error) = verifier.VerifyActivationCode(input);
if (code is null)
{
return Fail($"Not valid: {error}.");
}
Console.WriteLine($"Valid activation code for {code.Module} until {code.ExpiresAt:yyyy-MM-dd}.");
return 0;
}
static ECDsa LoadKey(string path)
{
var key = ECDsa.Create();
key.ImportFromPem(File.ReadAllText(path));
return key;
}
static int Fail(string message)
{
Console.Error.WriteLine(message);
return 1;
}
/// <summary>Command-line options: <c>--name value</c> pairs and one positional argument.</summary>
internal sealed class Options
{
private readonly Dictionary<string, string> _values = new(StringComparer.Ordinal);
/// <summary>The positional argument.</summary>
public string? Positional { get; private set; }
/// <summary>Parses the arguments after the command.</summary>
/// <param name="args">The arguments.</param>
/// <returns>The options.</returns>
public static Options Parse(IEnumerable<string> args)
{
var options = new Options();
using var e = args.GetEnumerator();
while (e.MoveNext())
{
if (e.Current.StartsWith("--", StringComparison.Ordinal))
{
var name = e.Current[2..];
options._values[name] = e.MoveNext() ? e.Current : throw new ArgumentException($"--{name} needs a value.");
}
else
{
options.Positional = e.Current;
}
}
return options;
}
/// <summary>A required option.</summary>
/// <param name="name">The name.</param>
/// <returns>The value.</returns>
public string Required(string name) => _values.TryGetValue(name, out var value) ? value : throw new ArgumentException($"--{name} is required.");
/// <summary>An optional option.</summary>
/// <param name="name">The name.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
public string? Optional(string name) => _values.GetValueOrDefault(name);
}