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,116 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
namespace Khaemhat.Application.Instance;
/// <summary>The outcome of choosing the company a request or a circuit works in.</summary>
public enum CompanyAccess
{
/// <summary>The company can be used.</summary>
Granted = 0,
/// <summary>No company chosen (an instance account on instance pages).</summary>
None = 1,
/// <summary>The company does not exist.</summary>
NotFound = 2,
/// <summary>A company account asked for another company.</summary>
Forbidden = 3,
/// <summary>The company is in maintenance and the account is not an instance account.</summary>
Maintenance = 4,
/// <summary>The company is disabled.</summary>
Disabled = 5,
}
/// <summary>The company of the current request or Blazor circuit (SPEC §5.4).</summary>
/// <param name="Access">Whether the company can be used.</param>
/// <param name="Company">The company, when it exists.</param>
public sealed record CompanyContextResult(CompanyAccess Access, Company? Company)
{
/// <summary>No company.</summary>
public static CompanyContextResult None { get; } = new(CompanyAccess.None, null);
/// <summary>The company code, when granted.</summary>
public string? Code => Access == CompanyAccess.Granted ? Company!.Code : null;
/// <summary>Whether writes are refused (company in <see cref="CompanyStatus.ReadOnly"/>).</summary>
public bool IsReadOnly => Company?.Status == CompanyStatus.ReadOnly;
/// <summary>Whether the company is temporarily unavailable (the API answers 503).</summary>
public bool IsUnavailable => Access is CompanyAccess.Maintenance or CompanyAccess.Disabled;
/// <summary>The database scope of the company.</summary>
/// <returns>The scope.</returns>
/// <exception cref="InvalidOperationException">No company is granted.</exception>
public DatabaseScope Scope() =>
Access == CompanyAccess.Granted ? DatabaseScope.Company(Company!.Code) : throw new InvalidOperationException("No company is available in this context.");
}
/// <summary>The company the current user works in. Scoped: one per request and one per Blazor circuit.</summary>
public interface ICompanyContext
{
/// <summary>Resolves (once) and returns the company.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The result.</returns>
ValueTask<CompanyContextResult> GetAsync(CancellationToken cancellationToken = default);
}
/// <summary>
/// The rules that choose the company (SPEC §1.4, §5.4): company accounts work only in their own company; instance
/// accounts choose it (session company, or the <c>X-Company</c> header of an API call). A company in maintenance is open
/// only to instance accounts; a disabled company to nobody.
/// </summary>
/// <param name="companies">The company registry.</param>
public sealed class CompanyContextResolver(ICompanyRegistry companies)
{
/// <summary>The header naming the company of an API call.</summary>
public const string Header = "X-Company";
/// <summary>Chooses the company.</summary>
/// <param name="actor">The signed-in user, or <see langword="null"/>.</param>
/// <param name="requested">The company asked by the request (header), or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The result.</returns>
public async Task<CompanyContextResult> ResolveAsync(Actor? actor, string? requested, CancellationToken cancellationToken = default)
{
if (actor is null)
{
return CompanyContextResult.None;
}
requested = string.IsNullOrWhiteSpace(requested) ? null : requested.Trim().ToUpperInvariant();
string? code;
if (actor.IsInstanceAccount)
{
code = requested ?? actor.CompanyCode;
}
else
{
if (requested is not null && !string.Equals(requested, actor.CompanyCode, StringComparison.OrdinalIgnoreCase))
{
return new CompanyContextResult(CompanyAccess.Forbidden, null);
}
code = actor.CompanyCode;
}
if (code is null)
{
return CompanyContextResult.None;
}
var company = await companies.FindAsync(code, cancellationToken).ConfigureAwait(false);
return company switch
{
null => new CompanyContextResult(CompanyAccess.NotFound, null),
{ Status: CompanyStatus.Disabled } => new CompanyContextResult(CompanyAccess.Disabled, company),
{ Status: CompanyStatus.Maintenance } when !actor.IsInstanceAccount => new CompanyContextResult(CompanyAccess.Maintenance, company),
_ => new CompanyContextResult(CompanyAccess.Granted, company),
};
}
}
@@ -0,0 +1,314 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Logging;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Migrations;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Instance;
/// <summary>Where the databases of the instance are and which migrations they get.</summary>
/// <param name="System">The system database (<c>KHAEMHAT_SYSTEM_DB</c>).</param>
/// <param name="CompanyServer">Where new company databases are created (<c>KHAEMHAT_DB_SERVER</c>, or next to the system one).</param>
/// <param name="SystemMigrations">The migrations of the system database.</param>
/// <param name="CompanyMigrations">The migrations of every company database.</param>
public sealed record InstanceDatabases(DatabaseUrl System, DatabaseUrl CompanyServer, MigrationCatalog SystemMigrations, MigrationCatalog CompanyMigrations);
/// <summary>A company to create.</summary>
/// <param name="Code">The code (database <c>khaemhat_&lt;code&gt;</c>).</param>
/// <param name="Name">The company name.</param>
/// <param name="IsDefault">Whether it becomes the default company.</param>
/// <param name="Notes">Notes for administrators.</param>
/// <param name="SeedDemo">Whether to load the demo data.</param>
public sealed record NewCompany(string Code, string Name, bool IsDefault = false, string? Notes = null, bool SeedDemo = false);
/// <summary>
/// Fills a new or migrated company database. Modules register their own: base data at creation (plan of accounts, VAT
/// codes) and demo data when asked (SPEC §5.5). Seeders must be idempotent: they run again at every start.
/// </summary>
public interface ICompanySeeder
{
/// <summary>The order among seeders (lower first).</summary>
int Order { get; }
/// <summary>Fills the database.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="context">What to load.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default);
}
/// <summary>What a seeder is asked to load.</summary>
/// <param name="IsNew">Whether the database was just created.</param>
/// <param name="Base">Whether the base data is wanted (<c>KHAEMHAT_SEED_BASE</c>).</param>
/// <param name="Demo">Whether the demo data is wanted.</param>
public sealed record CompanySeedContext(bool IsNew, bool Base, bool Demo);
/// <summary>The predefined roles of SPEC §7.2, kept equal to their templates in every company.</summary>
/// <param name="roles">The role service.</param>
public sealed class PredefinedRolesSeeder(RoleService roles) : ICompanySeeder
{
/// <inheritdoc />
public int Order => 0;
/// <inheritdoc />
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) =>
roles.SyncPredefinedRolesAsync(companyCode, cancellationToken);
}
/// <summary>
/// Creates, attaches and migrates company databases (SPEC §5.4, §12.1; mockup 080). Creating a company is an
/// instance administration task: super user or administrators. The number of companies is limited by the licence
/// (module MULTI).
/// </summary>
public sealed class CompanyService
{
private readonly ICompanyRegistry _registry;
private readonly DbProviderCatalog _providers;
private readonly MigrationRunner _migrations;
private readonly InstanceDatabases _databases;
private readonly ILicenseGate _licenses;
private readonly SessionStore _sessions;
private readonly ISecurityAuditLog _audit;
private readonly IReadOnlyList<ICompanySeeder> _seeders;
private readonly ILogger<CompanyService> _logger;
/// <summary>Creates the service.</summary>
/// <param name="registry">The company registry.</param>
/// <param name="providers">The database providers.</param>
/// <param name="migrations">Applies migrations.</param>
/// <param name="databases">Where databases are.</param>
/// <param name="licenses">The licence in force.</param>
/// <param name="sessions">The sessions (revoked when a company goes into maintenance).</param>
/// <param name="audit">The security audit.</param>
/// <param name="seeders">The seeders of the modules.</param>
/// <param name="logger">The log.</param>
public CompanyService(
ICompanyRegistry registry, DbProviderCatalog providers, MigrationRunner migrations, InstanceDatabases databases, ILicenseGate licenses,
SessionStore sessions, ISecurityAuditLog audit, IEnumerable<ICompanySeeder> seeders, ILogger<CompanyService> logger)
{
ArgumentNullException.ThrowIfNull(registry);
ArgumentNullException.ThrowIfNull(providers);
ArgumentNullException.ThrowIfNull(migrations);
ArgumentNullException.ThrowIfNull(databases);
ArgumentNullException.ThrowIfNull(licenses);
ArgumentNullException.ThrowIfNull(sessions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(seeders);
ArgumentNullException.ThrowIfNull(logger);
_registry = registry;
_providers = providers;
_migrations = migrations;
_databases = databases;
_licenses = licenses;
_sessions = sessions;
_audit = audit;
_seeders = [.. seeders.OrderBy(s => s.Order)];
_logger = logger;
}
/// <summary>The companies of the instance.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The companies by code.</returns>
public Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default) => _registry.ListAsync(cancellationToken);
/// <summary>
/// Creates a company: a new database <c>khaemhat_&lt;code&gt;</c> on the company server, registered, migrated and
/// filled by the seeders.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The registered company.</returns>
/// <exception cref="AccessDeniedException">The actor is not an instance account, or the licence allows no more companies.</exception>
public async Task<Company> CreateAsync(Actor actor, NewCompany company, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(company);
RequireInstanceAdministrator(actor);
var code = Validate(company.Code, company.Name);
await RequireRoomAsync(cancellationToken).ConfigureAwait(false);
var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code));
var target = _providers.Resolve(url);
if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException([$"Il database {url.DatabaseName} esiste già: usa «Collega database esistente»."]);
}
await target.Provider.EnsureDatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false);
var registered = await _registry.RegisterAsync(new CompanyRegistration(code, company.Name, url, company.IsDefault, company.Notes), cancellationToken)
.ConfigureAwait(false);
await PrepareAsync(registered, new CompanySeedContext(IsNew: true, Base: true, Demo: company.SeedDemo), cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("company.created", actor.UserName, Target: code), cancellationToken).ConfigureAwait(false);
return registered;
}
/// <summary>
/// Attaches an existing company database (restored from a backup or moved from another instance) and migrates it.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="code">The company code.</param>
/// <param name="name">The company name.</param>
/// <param name="database">Where the database is.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The registered company.</returns>
public async Task<Company> AttachAsync(Actor actor, string code, string name, DatabaseUrl database, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(database);
RequireInstanceAdministrator(actor);
var normalized = Validate(code, name);
await RequireRoomAsync(cancellationToken).ConfigureAwait(false);
var target = _providers.Resolve(database);
if (!await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException(["Il database indicato non esiste o non è raggiungibile."]);
}
var registered = await _registry.RegisterAsync(new CompanyRegistration(normalized, name, database), cancellationToken).ConfigureAwait(false);
await PrepareAsync(registered, new CompanySeedContext(IsNew: false, Base: false, Demo: false), cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("company.attached", actor.UserName, Target: normalized), cancellationToken).ConfigureAwait(false);
return registered;
}
/// <summary>
/// Changes the state of a company. Maintenance and disabling sign out its users at once; instance accounts can still
/// open a company in maintenance.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="code">The company.</param>
/// <param name="status">The new state.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetStatusAsync(Actor actor, string code, CompanyStatus status, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
RequireInstanceAdministrator(actor);
await _registry.SetStatusAsync(code, status, cancellationToken).ConfigureAwait(false);
if (status is CompanyStatus.Maintenance or CompanyStatus.Disabled)
{
var revoked = await _sessions.RevokeCompanyAsync(code, "company-" + status.ToString().ToLowerInvariant(), cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Company {Company} is now {Status}: {Count} sessions closed.", code, status, revoked);
}
await _audit.WriteAsync(
new SecurityEvent("company.status", actor.UserName, Target: CompanyCodes.Normalize(code), Details: status.ToString()), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Migrates every company that is not disabled and runs the seeders again (at each start). A company whose
/// migration fails is put in maintenance and logged; the others go on.
/// </summary>
/// <param name="seedDemo">Whether demo data is wanted (<c>KHAEMHAT_SEED_DEMO</c>).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The companies that failed.</returns>
public async Task<IReadOnlyList<string>> PrepareAllAsync(bool seedDemo, CancellationToken cancellationToken = default)
{
var failed = new List<string>();
foreach (var company in await _registry.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status == CompanyStatus.Disabled)
{
continue;
}
try
{
await PrepareAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: seedDemo), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failed.Add(company.Code);
using (_logger.BeginScope(LogSections.Scope(LogSection.Migrations)))
{
_logger.LogError(ex, "Company {Company} could not be migrated: it is put in maintenance.", company.Code);
}
await _registry.SetStatusAsync(company.Code, CompanyStatus.Maintenance, cancellationToken).ConfigureAwait(false);
}
}
return failed;
}
private async Task PrepareAsync(Company company, CompanySeedContext context, CancellationToken cancellationToken)
{
var target = await _registry.ResolveAsync(company.Code, cancellationToken).ConfigureAwait(false);
var report = await _migrations.RunAsync(target, _databases.CompanyMigrations, cancellationToken).ConfigureAwait(false);
LogMigrations(_logger, report, company.Code);
foreach (var seeder in _seeders)
{
await seeder.SeedAsync(company.Code, context, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Writes a migration report in the section <i>Migrazioni</i>.</summary>
/// <param name="logger">The log.</param>
/// <param name="report">The report.</param>
/// <param name="companyCode">The company, or <see langword="null"/> for the system database.</param>
public static void LogMigrations(ILogger logger, MigrationReport report, string? companyCode)
{
ArgumentNullException.ThrowIfNull(logger);
ArgumentNullException.ThrowIfNull(report);
using var section = logger.BeginScope(LogSections.Scope(LogSection.Migrations));
using var company = logger.BeginScope(new Dictionary<string, object?> { [LogSections.CompanyKey] = companyCode });
foreach (var (migration, duration) in report.Applied)
{
logger.LogInformation("Migration {Migration} applied to {Database} in {Milliseconds} ms.", migration.ToString(), report.Database, (long)duration.TotalMilliseconds);
}
foreach (var warning in report.Warnings)
{
logger.LogWarning("Database {Database}: {Warning}", report.Database, warning);
}
if (report.Applied.Count == 0)
{
logger.LogDebug("Database {Database} is up to date ({Count} migrations).", report.Database, report.AlreadyApplied);
}
}
private static string Validate(string code, string name)
{
var errors = new List<string>();
if (!CompanyCodes.IsValid((code ?? string.Empty).Trim().ToUpperInvariant()))
{
errors.Add("Il codice azienda deve avere da 1 a 20 caratteri tra lettere, cifre e trattino basso.");
}
if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > 200)
{
errors.Add("La ragione sociale è obbligatoria (al massimo 200 caratteri).");
}
return errors.Count > 0 ? throw new ValidationFailedException(errors) : CompanyCodes.Normalize(code!);
}
private async Task RequireRoomAsync(CancellationToken cancellationToken)
{
var limit = _licenses.Current.MaxCompanies;
var count = (await _registry.ListAsync(cancellationToken).ConfigureAwait(false)).Count;
if (count >= limit)
{
throw new AccessDeniedException(
SecurityErrors.LicenseLimitReached,
limit <= 1
? "La licenza consente una sola azienda: per gestirne altre serve il modulo Multi-azienda (MULTI)."
: $"La licenza consente al massimo {limit} aziende.");
}
}
private static void RequireInstanceAdministrator(Actor actor)
{
if (!actor.IsInstanceAccount)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Solo gli account di istanza possono gestire le aziende.");
}
}
}
@@ -0,0 +1,264 @@
using System.Globalization;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Core.Logging;
using Khaemhat.Data;
using Khaemhat.Data.Migrations;
using Khaemhat.Infrastructure.Logging;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Instance;
/// <summary>Where the start of the instance is.</summary>
public enum BootstrapPhase
{
/// <summary>Migrations and first-start setup in progress: <c>/health/ready</c> answers 503.</summary>
Starting = 0,
/// <summary>Ready to serve.</summary>
Ready = 1,
/// <summary>The start failed; the process is stopping.</summary>
Failed = 2,
}
/// <summary>The start state, read by the readiness endpoint and the middleware.</summary>
public sealed class BootstrapState
{
private volatile BootstrapPhase _phase;
/// <summary>The phase.</summary>
public BootstrapPhase Phase => _phase;
/// <summary>Whether the instance serves requests.</summary>
public bool IsReady => _phase == BootstrapPhase.Ready;
/// <summary>Why the start failed (no secrets).</summary>
public string? Error { get; private set; }
/// <summary>Companies put in maintenance because their migration failed.</summary>
public IReadOnlyList<string> FailedCompanies { get; private set; } = [];
/// <summary>Marks the start as completed.</summary>
/// <param name="failedCompanies">The companies that could not be migrated.</param>
public void MarkReady(IReadOnlyList<string> failedCompanies)
{
FailedCompanies = failedCompanies ?? [];
_phase = BootstrapPhase.Ready;
}
/// <summary>Marks the start as failed.</summary>
/// <param name="error">Why.</param>
public void MarkFailed(string error)
{
Error = error;
_phase = BootstrapPhase.Failed;
}
}
/// <summary>
/// The start sequence (SPEC §5.3, §7.1, §8, §23): migrate the system database, start writing the log there, fix the
/// instance identifier and the trial start, seed the role templates, compute the licence, create the super user and the
/// first company from the variables when the tables are empty, then migrate every company. Every step is idempotent: a
/// second start, or two instances starting together, change nothing.
/// </summary>
public sealed class StartupOrchestrator
{
private readonly InstanceDatabases _databases;
private readonly DbProviderCatalog _providers;
private readonly MigrationRunner _migrations;
private readonly SystemSettingsStore _settings;
private readonly RoleService _roles;
private readonly ILicenseGate _licenses;
private readonly SystemUserService _systemUsers;
private readonly CompanyService _companies;
private readonly KhaemhatOptions _options;
private readonly IUnitOfWorkFactory _factory;
private readonly DbLogSink? _logSink;
private readonly BootstrapState _state;
private readonly TimeProvider _clock;
private readonly ILogger<StartupOrchestrator> _logger;
private bool _systemReady;
/// <summary>Creates the orchestrator.</summary>
/// <param name="databases">Where databases are.</param>
/// <param name="providers">The providers.</param>
/// <param name="migrations">Applies migrations.</param>
/// <param name="settings">The instance settings.</param>
/// <param name="roles">The role templates.</param>
/// <param name="licenses">The licence.</param>
/// <param name="systemUsers">The instance accounts.</param>
/// <param name="companies">The companies.</param>
/// <param name="options">The variables.</param>
/// <param name="factory">Opens the databases.</param>
/// <param name="logSink">The database log, started once the system database is ready (absent in some tests).</param>
/// <param name="state">The start state.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public StartupOrchestrator(
InstanceDatabases databases, DbProviderCatalog providers, MigrationRunner migrations, SystemSettingsStore settings, RoleService roles,
ILicenseGate licenses, SystemUserService systemUsers, CompanyService companies, KhaemhatOptions options, IUnitOfWorkFactory factory,
DbLogSink? logSink, BootstrapState state, TimeProvider clock, ILogger<StartupOrchestrator> logger)
{
ArgumentNullException.ThrowIfNull(databases);
ArgumentNullException.ThrowIfNull(providers);
ArgumentNullException.ThrowIfNull(migrations);
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(roles);
ArgumentNullException.ThrowIfNull(licenses);
ArgumentNullException.ThrowIfNull(systemUsers);
ArgumentNullException.ThrowIfNull(companies);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(state);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_databases = databases;
_providers = providers;
_migrations = migrations;
_settings = settings;
_roles = roles;
_licenses = licenses;
_systemUsers = systemUsers;
_companies = companies;
_options = options;
_factory = factory;
_logSink = logSink;
_state = state;
_clock = clock;
_logger = logger;
}
/// <summary>
/// Creates (when missing) and migrates the system database, then starts writing the log there. It runs before the
/// host starts serving, because DataProtection and sessions read the system database from the first request.
/// </summary>
/// <param name="cancellationToken">Cancellation (host stopping).</param>
/// <returns>A task.</returns>
public async Task PrepareSystemDatabaseAsync(CancellationToken cancellationToken = default)
{
if (_systemReady)
{
return;
}
using var section = _logger.BeginScope(LogSections.Scope(LogSection.System));
var system = _providers.Resolve(_databases.System);
await system.Provider.EnsureDatabaseExistsAsync(system.ConnectionString, cancellationToken).ConfigureAwait(false);
var report = await _migrations.RunAsync(system, _databases.SystemMigrations, cancellationToken).ConfigureAwait(false);
CompanyService.LogMigrations(_logger, report, null);
_logSink?.Start(_factory);
_systemReady = true;
}
/// <summary>Runs the start sequence and marks the state ready.</summary>
/// <param name="cancellationToken">Cancellation (host stopping).</param>
/// <returns>A task.</returns>
/// <exception cref="ConfigurationException">First start without the variables it needs.</exception>
public async Task RunAsync(CancellationToken cancellationToken = default)
{
// 1. System database: created when missing (SQLite file, PostgreSQL database if the role may), then migrated.
await PrepareSystemDatabaseAsync(cancellationToken).ConfigureAwait(false);
using var section = _logger.BeginScope(LogSections.Scope(LogSection.System));
// 2. Instance identity and trial start, fixed at the first start and never changed.
await _settings.GetOrAddAsync(SystemSettingsStore.InstanceIdKey, Guid.NewGuid().ToString("D"), cancellationToken).ConfigureAwait(false);
await _settings.GetOrAddAsync(
SystemSettingsStore.TrialStartedKey, _clock.GetUtcNow().UtcDateTime.ToString("O", CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false);
// 3. Role templates and licence.
await _roles.SeedTemplatesAsync(cancellationToken).ConfigureAwait(false);
var license = await _licenses.RefreshAsync(cancellationToken).ConfigureAwait(false);
_logger.LogInformation(
"License: {Kind} {Status}, modules {Modules}, {Users} concurrent users, {Companies} companies.",
license.Kind, license.Status, string.Join(',', license.Modules.Order(StringComparer.Ordinal)), license.MaxConcurrentUsers, license.MaxCompanies);
// 4. Super user, only when there is no instance account at all.
if (!await _systemUsers.AnyAsync(cancellationToken).ConfigureAwait(false))
{
await CreateSuperUserAsync(cancellationToken).ConfigureAwait(false);
}
// 5. First company, only when the registry is empty.
if ((await _companies.ListAsync(cancellationToken).ConfigureAwait(false)).Count == 0)
{
await CreateFirstCompanyAsync(cancellationToken).ConfigureAwait(false);
}
// 6. Every company migrated and seeded again.
var failed = await _companies.PrepareAllAsync(_options.SeedDemoEnabled, cancellationToken).ConfigureAwait(false);
_state.MarkReady(failed);
_logger.LogInformation("Khaemhat is ready.");
}
private async Task CreateSuperUserAsync(CancellationToken cancellationToken)
{
var missing = new List<string>();
if (_options.SuperUser is null)
{
missing.Add("KHAEMHAT_SUPERUSER is required at the first start: the user name of the super user.");
}
if (_options.SuperUserPassword is null)
{
missing.Add("KHAEMHAT_SUPERUSER_PASSWORD (or KHAEMHAT_SUPERUSER_PASSWORD_FILE) is required at the first start: the first password of the super user.");
}
if (missing.Count > 0)
{
throw new ConfigurationException(missing);
}
try
{
var user = await _systemUsers.CreateSuperUserAsync(
new NewSystemUser(_options.SuperUser!, _options.SuperUser!, _options.SuperUserEmail), _options.SuperUserPassword!, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Super user {UserName} created: change the password and set up the two-step verification at the first access.", user.UserName);
}
catch (ValidationFailedException ex)
{
throw new ConfigurationException([.. ex.Errors.Select(e => "KHAEMHAT_SUPERUSER_PASSWORD does not satisfy the password policy: " + e)]);
}
catch (InvalidOperationException)
{
// Another instance created it a moment ago.
}
}
private async Task CreateFirstCompanyAsync(CancellationToken cancellationToken)
{
var code = _options.CompanyCode?.Trim().ToUpperInvariant();
if (code is null)
{
_logger.LogWarning("No company exists and KHAEMHAT_COMPANY_CODE is not set: create the first company from Amministrazione > Aziende.");
return;
}
try
{
var name = string.IsNullOrWhiteSpace(_options.CompanyName) ? code : _options.CompanyName.Trim();
var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code));
var target = _providers.Resolve(url);
if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
{
// The system database was recreated but the company one survived: attach it instead of refusing.
await _companies.AttachAsync(Actor.System, code, name, url, cancellationToken).ConfigureAwait(false);
_logger.LogWarning("Company database {Database} already existed: attached as company {Company}.", url.DatabaseName, code);
return;
}
await _companies.CreateAsync(Actor.System, new NewCompany(code, name, IsDefault: true, SeedDemo: _options.SeedDemoEnabled), cancellationToken)
.ConfigureAwait(false);
_logger.LogInformation("Company {Company} created.", code);
}
catch (InvalidOperationException)
{
// Another instance registered it a moment ago; anything else is a real failure.
if ((await _companies.ListAsync(cancellationToken).ConfigureAwait(false)).Count == 0)
{
throw;
}
}
}
}
@@ -0,0 +1,82 @@
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Instance;
/// <summary>
/// Instance settings in <c>sys_settings</c>. Secret values are encrypted with the instance key and the purpose
/// <c>setting:&lt;key&gt;</c>.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="protector">Encrypts secret values.</param>
public sealed class SystemSettingsStore(IUnitOfWorkFactory factory, ISecretProtector protector)
{
/// <summary>The identifier of the instance, created at first start.</summary>
public const string InstanceIdKey = "instance.id";
/// <summary>When the trial started (ISO 8601 UTC), set at first start.</summary>
public const string TrialStartedKey = "license.trial-started-at";
/// <summary>Reads a setting.</summary>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value (decrypted when secret), or <see langword="null"/>.</returns>
public async Task<string?> GetAsync(string key, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var setting = await unitOfWork.Repository<SystemSetting, long>().FindAsync(Query.For<SystemSetting>().Where(s => s.Key == key), cancellationToken)
.ConfigureAwait(false);
if (setting?.Value is null)
{
return null;
}
return setting.IsSecret ? protector.Unprotect(setting.Value, Purpose(key)) : setting.Value;
}
/// <summary>Writes a setting.</summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="secret">Whether to encrypt it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetAsync(string key, string? value, bool secret = false, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var settings = unitOfWork.Repository<SystemSetting, long>();
var stored = value is null || !secret ? value : protector.Protect(value, Purpose(key));
var setting = await settings.FindAsync(Query.For<SystemSetting>().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false);
if (setting is null)
{
await settings.InsertAsync(new SystemSetting { Key = key, Value = stored, IsSecret = secret }, cancellationToken).ConfigureAwait(false);
return;
}
setting.Value = stored;
setting.IsSecret = secret;
await settings.UpdateAsync(setting, cancellationToken).ConfigureAwait(false);
}
/// <summary>Writes a setting only if it does not exist yet (bootstrap values such as the instance id).</summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value now stored.</returns>
public async Task<string> GetOrAddAsync(string key, string value, CancellationToken cancellationToken = default)
{
var existing = await GetAsync(key, cancellationToken).ConfigureAwait(false);
if (existing is not null)
{
return existing;
}
await SetAsync(key, value, secret: false, cancellationToken).ConfigureAwait(false);
return value;
}
private static string Purpose(string key) => "setting:" + key;
}