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;
/// The licence in force and the modules it activates.
public interface ILicenseGate
{
/// The licence computed at the last refresh.
LicenseState Current { get; }
/// Whether a module is licensed.
/// The module code.
/// if active.
bool IsModuleActive(string moduleCode);
/// Recomputes the licence from the database and the environment.
/// Cancellation.
/// The new state.
Task RefreshAsync(CancellationToken cancellationToken = default);
}
/// Where the gate reads the licence from the environment.
/// The text of KHAEMHAT_LICENSE, if set.
/// The licence mode.
public sealed record LicenseSettings(string? EnvironmentLicense, LicenseMode Mode);
///
/// 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.
///
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 _logger;
private volatile LicenseState _current;
/// Creates the gate. Until the first refresh the state is the trial.
/// Opens the system database.
/// The instance settings.
/// Checks signatures.
/// The environment licence and mode.
/// The clock.
/// The log.
public LicenseGate(
IUnitOfWorkFactory factory, SystemSettingsStore settings, LicenseVerifier verifier, LicenseSettings licenseSettings,
TimeProvider clock, ILogger 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);
}
///
public LicenseState Current => _current;
/// The instance identifier read at the last refresh.
public string? InstanceId { get; private set; }
///
public bool IsModuleActive(string moduleCode) => _current.Includes(moduleCode);
///
public async Task 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 records;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
records = (await unitOfWork.Repository()
.ListAsync(Query.For().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(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())
{
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 extra, int testUsers, bool testMode)
{
var modules = new HashSet(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 extra, int testUsers, bool testMode)
{
var modules = new HashSet(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,
};
}
}
/// The outcome of an activation.
/// Whether the licence or code was installed.
/// The outcome code: ok or one of .
/// The licence in force afterwards.
public sealed record ActivationResult(bool Succeeded, string Outcome, LicenseState State);
/// Installs and removes licences (SPEC §8.2). Today offline; a remote activation server may come later.
public interface ILicenseActivationService
{
/// Installs a .khl licence, a module activation code or, in test mode, a fictitious code.
/// Who acts: only the super user.
/// The licence text or the code.
/// Cancellation.
/// The outcome.
Task ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default);
/// Removes an installed licence or code (it stays in the history).
/// Who acts: only the super user.
/// The row of sys_licenses.
/// Cancellation.
/// The licence in force afterwards.
Task DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default);
}
/// Activation checked locally with the public key: no network involved.
public sealed class OfflineActivationService(
IUnitOfWorkFactory factory, LicenseGate gate, LicenseVerifier verifier, LicenseSettings settings, ModuleRegistry modules,
ISecurityAuditLog audit, TimeProvider clock) : ILicenseActivationService
{
///
public async Task 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();
if (record.Source == LicenseSource.File)
{
// A new instance licence replaces the previous one; codes stay.
foreach (var old in (await licenses.ListAsync(
Query.For().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().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);
}
///
public async Task 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();
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().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.");
}
}
}