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,384 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Configuration;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Infrastructure.Licensing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Licensing;
|
||||
|
||||
/// <summary>The licence in force and the modules it activates.</summary>
|
||||
public interface ILicenseGate
|
||||
{
|
||||
/// <summary>The licence computed at the last refresh.</summary>
|
||||
LicenseState Current { get; }
|
||||
|
||||
/// <summary>Whether a module is licensed.</summary>
|
||||
/// <param name="moduleCode">The module code.</param>
|
||||
/// <returns><see langword="true"/> if active.</returns>
|
||||
bool IsModuleActive(string moduleCode);
|
||||
|
||||
/// <summary>Recomputes the licence from the database and the environment.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new state.</returns>
|
||||
Task<LicenseState> RefreshAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Where the gate reads the licence from the environment.</summary>
|
||||
/// <param name="EnvironmentLicense">The text of <c>KHAEMHAT_LICENSE</c>, if set.</param>
|
||||
/// <param name="Mode">The licence mode.</param>
|
||||
public sealed record LicenseSettings(string? EnvironmentLicense, LicenseMode Mode);
|
||||
|
||||
/// <summary>
|
||||
/// Computes the licence (SPEC §8): the best signed licence (environment or installed) bound to this instance, else the
|
||||
/// trial; plus the module activation codes; plus, in test mode only, the fictitious codes. Every signature is checked
|
||||
/// again at each refresh, so a row changed in the database does not grant anything.
|
||||
/// </summary>
|
||||
public sealed class LicenseGate : ILicenseGate
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly SystemSettingsStore _settings;
|
||||
private readonly LicenseVerifier _verifier;
|
||||
private readonly LicenseSettings _licenseSettings;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly ILogger<LicenseGate> _logger;
|
||||
private volatile LicenseState _current;
|
||||
|
||||
/// <summary>Creates the gate. Until the first refresh the state is the trial.</summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="settings">The instance settings.</param>
|
||||
/// <param name="verifier">Checks signatures.</param>
|
||||
/// <param name="licenseSettings">The environment licence and mode.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public LicenseGate(
|
||||
IUnitOfWorkFactory factory, SystemSettingsStore settings, LicenseVerifier verifier, LicenseSettings licenseSettings,
|
||||
TimeProvider clock, ILogger<LicenseGate> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
ArgumentNullException.ThrowIfNull(verifier);
|
||||
ArgumentNullException.ThrowIfNull(licenseSettings);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_factory = factory;
|
||||
_settings = settings;
|
||||
_verifier = verifier;
|
||||
_licenseSettings = licenseSettings;
|
||||
_clock = clock;
|
||||
_logger = logger;
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
_current = Trial(now, now, 0, [], 0, licenseSettings.Mode == LicenseMode.Test);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public LicenseState Current => _current;
|
||||
|
||||
/// <summary>The instance identifier read at the last refresh.</summary>
|
||||
public string? InstanceId { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsModuleActive(string moduleCode) => _current.Includes(moduleCode);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<LicenseState> RefreshAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
var testMode = _licenseSettings.Mode == LicenseMode.Test;
|
||||
InstanceId = await _settings.GetAsync(SystemSettingsStore.InstanceIdKey, cancellationToken).ConfigureAwait(false);
|
||||
var trialStart = DateTime.TryParse(
|
||||
await _settings.GetAsync(SystemSettingsStore.TrialStartedKey, cancellationToken).ConfigureAwait(false),
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
|
||||
out var started) ? started : now;
|
||||
|
||||
IReadOnlyList<LicenseRecord> records;
|
||||
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
records = (await unitOfWork.Repository<LicenseRecord, long>()
|
||||
.ListAsync(Query.For<LicenseRecord>().Where(r => r.IsActive).OrderBy(r => r.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
var documents = records.Where(r => r.Source == LicenseSource.File).Select(r => r.Payload).ToList();
|
||||
if (_licenseSettings.EnvironmentLicense is { } environment)
|
||||
{
|
||||
documents.Insert(0, environment);
|
||||
}
|
||||
|
||||
var license = documents
|
||||
.Select(text => _verifier.Verify(text).Document)
|
||||
.Where(d => d is not null && (d.InstanceId is null || string.Equals(d.InstanceId, InstanceId, StringComparison.OrdinalIgnoreCase)))
|
||||
.OrderByDescending(d => d!.ExpiresAt ?? DateTime.MaxValue)
|
||||
.FirstOrDefault();
|
||||
|
||||
var extraModules = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var record in records.Where(r => r.Source == LicenseSource.ActivationCode))
|
||||
{
|
||||
var (code, _) = _verifier.VerifyActivationCode(record.Payload);
|
||||
if (code is not null && code.ExpiresAt > now && (InstanceId is null || code.IsFor(InstanceId)))
|
||||
{
|
||||
extraModules.Add(code.Module);
|
||||
}
|
||||
}
|
||||
|
||||
var testUsers = 0;
|
||||
var trialExtension = 0;
|
||||
if (testMode)
|
||||
{
|
||||
foreach (var test in records.Where(r => r.Source == LicenseSource.TestCode).Select(r => TestLicenseCatalog.Find(r.Payload)).OfType<TestCode>())
|
||||
{
|
||||
extraModules.UnionWith(test.Modules);
|
||||
testUsers = Math.Max(testUsers, test.ConcurrentUsers);
|
||||
trialExtension += test.TrialExtensionDays;
|
||||
}
|
||||
}
|
||||
|
||||
var state = license is null
|
||||
? Trial(now, trialStart, trialExtension, extraModules, testUsers, testMode)
|
||||
: Licensed(now, license, extraModules, testUsers, testMode);
|
||||
if (state.Status != _current.Status || state.Kind != _current.Kind)
|
||||
{
|
||||
_logger.LogInformation("Licence {Kind} {Status}: modules {Modules}, {Users} users.", state.Kind, state.Status, string.Join(',', state.Modules), state.MaxConcurrentUsers);
|
||||
}
|
||||
|
||||
_current = state;
|
||||
return state;
|
||||
}
|
||||
|
||||
private static LicenseState Trial(DateTime now, DateTime trialStart, int extensionDays, IEnumerable<string> extra, int testUsers, bool testMode)
|
||||
{
|
||||
var modules = new HashSet<string>(LicenseState.TrialModules, StringComparer.Ordinal);
|
||||
modules.UnionWith(extra);
|
||||
var expires = trialStart + LicenseState.TrialLength + TimeSpan.FromDays(extensionDays);
|
||||
return new LicenseState
|
||||
{
|
||||
Kind = LicenseKind.Trial,
|
||||
Status = now <= expires ? LicenseStatus.Valid : LicenseStatus.Expired,
|
||||
Modules = modules,
|
||||
MaxConcurrentUsers = Math.Max(LicenseState.TrialUsers, testUsers),
|
||||
MaxCompanies = modules.Contains(ModuleCodes.MultiCompany) ? int.MaxValue : 1,
|
||||
ExpiresAt = expires,
|
||||
GraceEndsAt = expires,
|
||||
IsTestMode = testMode,
|
||||
};
|
||||
}
|
||||
|
||||
private static LicenseState Licensed(DateTime now, LicenseDocument license, IEnumerable<string> extra, int testUsers, bool testMode)
|
||||
{
|
||||
var modules = new HashSet<string>(license.Modules.Select(m => m.Trim().ToUpperInvariant()), StringComparer.Ordinal) { ModuleCodes.Core };
|
||||
modules.UnionWith(extra);
|
||||
var graceEnds = license.ExpiresAt?.AddDays(license.GracePeriodDays);
|
||||
var status = license.ExpiresAt is not { } expires || now <= expires
|
||||
? LicenseStatus.Valid
|
||||
: now <= graceEnds ? LicenseStatus.Grace : LicenseStatus.Expired;
|
||||
return new LicenseState
|
||||
{
|
||||
Kind = LicenseKind.Licensed,
|
||||
Status = status,
|
||||
Licensee = license.Licensee,
|
||||
Modules = modules,
|
||||
MaxConcurrentUsers = Math.Max(license.MaxConcurrentUsers, testUsers),
|
||||
MaxCompanies = modules.Contains(ModuleCodes.MultiCompany) ? (license.MaxCompanies > 1 ? license.MaxCompanies : int.MaxValue) : 1,
|
||||
ExpiresAt = license.ExpiresAt,
|
||||
GraceEndsAt = graceEnds,
|
||||
IsTestMode = testMode,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The outcome of an activation.</summary>
|
||||
/// <param name="Succeeded">Whether the licence or code was installed.</param>
|
||||
/// <param name="Outcome">The outcome code: <c>ok</c> or one of <see cref="LicenseErrors"/>.</param>
|
||||
/// <param name="State">The licence in force afterwards.</param>
|
||||
public sealed record ActivationResult(bool Succeeded, string Outcome, LicenseState State);
|
||||
|
||||
/// <summary>Installs and removes licences (SPEC §8.2). Today offline; a remote activation server may come later.</summary>
|
||||
public interface ILicenseActivationService
|
||||
{
|
||||
/// <summary>Installs a <c>.khl</c> licence, a module activation code or, in test mode, a fictitious code.</summary>
|
||||
/// <param name="actor">Who acts: only the super user.</param>
|
||||
/// <param name="input">The licence text or the code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The outcome.</returns>
|
||||
Task<ActivationResult> ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Removes an installed licence or code (it stays in the history).</summary>
|
||||
/// <param name="actor">Who acts: only the super user.</param>
|
||||
/// <param name="licenseId">The row of <c>sys_licenses</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The licence in force afterwards.</returns>
|
||||
Task<LicenseState> DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Activation checked locally with the public key: no network involved.</summary>
|
||||
public sealed class OfflineActivationService(
|
||||
IUnitOfWorkFactory factory, LicenseGate gate, LicenseVerifier verifier, LicenseSettings settings, ModuleRegistry modules,
|
||||
ISecurityAuditLog audit, TimeProvider clock) : ILicenseActivationService
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<ActivationResult> ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
RequireSuperUser(actor);
|
||||
var text = (input ?? string.Empty).Trim();
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
if (gate.InstanceId is null)
|
||||
{
|
||||
await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var (record, outcome) = Prepare(text, now);
|
||||
await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
if (record is not null)
|
||||
{
|
||||
var licenses = unitOfWork.Repository<LicenseRecord, long>();
|
||||
if (record.Source == LicenseSource.File)
|
||||
{
|
||||
// A new instance licence replaces the previous one; codes stay.
|
||||
foreach (var old in (await licenses.ListAsync(
|
||||
Query.For<LicenseRecord>().Where(r => r.IsActive && r.Source == LicenseSource.File), ct).ConfigureAwait(false)).Items)
|
||||
{
|
||||
old.IsActive = false;
|
||||
await licenses.UpdateAsync(old, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await licenses.InsertAsync(record, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await unitOfWork.Repository<LicenseActivation, long>().InsertAsync(
|
||||
new LicenseActivation
|
||||
{
|
||||
Action = record is null ? "rejected" : "activated",
|
||||
Source = record?.Source ?? SourceOf(text),
|
||||
Modules = record?.Modules,
|
||||
Outcome = outcome,
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await audit.WriteAsync(
|
||||
new SecurityEvent(record is null ? "license.rejected" : "license.activated", actor.UserName, Target: record?.Modules, Details: new { outcome }),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var state = await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new ActivationResult(record is not null, outcome, state);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<LicenseState> DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
RequireSuperUser(actor);
|
||||
string? modules;
|
||||
await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var licenses = unitOfWork.Repository<LicenseRecord, long>();
|
||||
var record = await licenses.GetAsync(licenseId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException("No installed licence has this identifier.");
|
||||
record.IsActive = false;
|
||||
modules = record.Modules;
|
||||
await licenses.UpdateAsync(record, cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.Repository<LicenseActivation, long>().InsertAsync(
|
||||
new LicenseActivation { Action = "deactivated", Source = record.Source, Modules = record.Modules, Outcome = "ok" }, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await audit.WriteAsync(new SecurityEvent("license.deactivated", actor.UserName, Target: modules), cancellationToken).ConfigureAwait(false);
|
||||
return await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private (LicenseRecord? Record, string Outcome) Prepare(string text, DateTime now)
|
||||
{
|
||||
if (TestLicenseCatalog.LooksLikeTestCode(text))
|
||||
{
|
||||
if (settings.Mode != LicenseMode.Test)
|
||||
{
|
||||
return (null, LicenseErrors.TestOnly);
|
||||
}
|
||||
|
||||
var test = TestLicenseCatalog.Find(text);
|
||||
return test is null
|
||||
? (null, LicenseErrors.FormatInvalid)
|
||||
: (new LicenseRecord { Source = LicenseSource.TestCode, Payload = text.ToUpperInvariant(), Modules = string.Join(',', test.Modules), Licensee = "Test" }, "ok");
|
||||
}
|
||||
|
||||
if (text.StartsWith(ModuleActivationCode.Prefix + "-", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var (code, error) = verifier.VerifyActivationCode(text);
|
||||
if (code is null)
|
||||
{
|
||||
return (null, error!);
|
||||
}
|
||||
|
||||
if (modules.FindModule(code.Module) is null)
|
||||
{
|
||||
return (null, LicenseErrors.UnknownModule);
|
||||
}
|
||||
|
||||
if (code.ExpiresAt <= now)
|
||||
{
|
||||
return (null, LicenseErrors.Expired);
|
||||
}
|
||||
|
||||
if (gate.InstanceId is { } instance && !code.IsFor(instance))
|
||||
{
|
||||
return (null, LicenseErrors.WrongInstance);
|
||||
}
|
||||
|
||||
return (new LicenseRecord { Source = LicenseSource.ActivationCode, Payload = text.ToUpperInvariant(), Modules = code.Module, ExpiresAt = code.ExpiresAt }, "ok");
|
||||
}
|
||||
|
||||
var verification = verifier.Verify(text);
|
||||
if (verification.Document is not { } document)
|
||||
{
|
||||
return (null, verification.Error!);
|
||||
}
|
||||
|
||||
if (document.InstanceId is not null && !string.Equals(document.InstanceId, gate.InstanceId, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return (null, LicenseErrors.WrongInstance);
|
||||
}
|
||||
|
||||
if (document.ExpiresAt is { } expires && expires.AddDays(document.GracePeriodDays) <= now)
|
||||
{
|
||||
return (null, LicenseErrors.Expired);
|
||||
}
|
||||
|
||||
return (new LicenseRecord
|
||||
{
|
||||
Source = LicenseSource.File,
|
||||
Payload = text,
|
||||
Licensee = document.Licensee.Length > 200 ? document.Licensee[..200] : document.Licensee,
|
||||
Modules = string.Join(',', document.Modules),
|
||||
MaxConcurrentUsers = document.MaxConcurrentUsers,
|
||||
MaxCompanies = document.MaxCompanies,
|
||||
IssuedAt = document.IssuedAt,
|
||||
ExpiresAt = document.ExpiresAt,
|
||||
GracePeriodDays = document.GracePeriodDays,
|
||||
}, "ok");
|
||||
}
|
||||
|
||||
private static LicenseSource SourceOf(string text) =>
|
||||
TestLicenseCatalog.LooksLikeTestCode(text) ? LicenseSource.TestCode
|
||||
: text.StartsWith(ModuleActivationCode.Prefix + "-", StringComparison.OrdinalIgnoreCase) ? LicenseSource.ActivationCode
|
||||
: LicenseSource.File;
|
||||
|
||||
private static void RequireSuperUser(Actor actor)
|
||||
{
|
||||
if (!actor.IsSuperUser)
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user activates licences and modules.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user