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,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_<code></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_<code></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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user