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,141 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Security;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Execution;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.PostgreSql;
using Khaemhat.Data.Sqlite;
using Khaemhat.Infrastructure.Caching;
using Khaemhat.Infrastructure.Licensing;
using Khaemhat.Infrastructure.Logging;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Security;
namespace Khaemhat.Web.Hosting;
/// <summary>
/// The composition of the instance (SPEC §3): data access on the configured databases, security, licences, log and
/// the start sequence. Services are singletons: they hold no per-request state and open a unit of work per call.
/// </summary>
internal static class KhaemhatServices
{
/// <summary>Registers every service of the instance.</summary>
/// <param name="services">The container.</param>
/// <param name="options">The validated variables.</param>
/// <param name="logSink">The database log queue, already plugged into the logging pipeline.</param>
/// <returns>The container.</returns>
public static IServiceCollection AddKhaemhat(this IServiceCollection services, KhaemhatOptions options, DbLogSink logSink)
{
var dataAssembly = typeof(CompanyRegistry).Assembly;
services.AddSingleton(options);
services.AddSingleton(logSink);
services.AddSingleton(TimeProvider.System);
services.AddSingleton<BootstrapState>();
services.AddHttpContextAccessor();
services.AddSingleton<CurrentUserName>();
// Secrets and data access.
services.AddSingleton(SecretKey.FromBase64(options.SecretKey!));
services.AddSingleton<SecretProtector>();
services.AddSingleton<ISecretProtector>(sp => sp.GetRequiredService<SecretProtector>());
services.AddSingleton(new DbProviderCatalog(new SqliteProvider(), new PostgresProvider()));
services.AddSingleton(new MapRegistry().AddFromAssembly(dataAssembly));
services.AddSingleton(sp =>
{
var slow = sp.GetRequiredService<ILoggerFactory>().CreateLogger("Khaemhat.Performance.SlowQueries");
var user = sp.GetRequiredService<CurrentUserName>();
return new DataAccessContext(sp.GetRequiredService<TimeProvider>(), user.Get)
{
SlowQueryObserver = query =>
{
using var section = slow.BeginScope(LogSections.Scope(LogSection.Performance));
slow.LogWarning(
"Slow query on {Database}: {Milliseconds} ms. {Sql}",
query.Database, (long)query.Duration.TotalMilliseconds, query.Sql.Length > 2000 ? query.Sql[..2000] : query.Sql);
},
};
});
services.AddSingleton(sp => sp.GetRequiredService<DbProviderCatalog>().Resolve(options.SystemDatabase));
services.AddSingleton<ICompanyRegistry>(sp => new CompanyRegistry(
sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<ISecretProtector>(),
sp.GetRequiredService<MapRegistry>(), sp.GetRequiredService<DataAccessContext>()));
services.AddSingleton<IDatabaseLocator>(sp => new DatabaseLocator(sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<ICompanyRegistry>()));
services.AddSingleton<IUnitOfWorkFactory, UnitOfWorkFactory>();
services.AddSingleton<MigrationRunner>();
services.AddSingleton(new InstanceDatabases(
options.SystemDatabase, options.CompanyServer, MigrationCatalog.ForSystem(dataAssembly), MigrationCatalog.ForCompany(dataAssembly)));
// Cache: in memory, or on Redis when KHAEMHAT_REDIS is set (falling back to memory while Redis is down).
if (options.Redis is { } redis)
{
services.AddSingleton(new RedisClient(RedisEndpoint.Parse(redis)));
services.AddSingleton<ICacheProvider>(sp => new RedisCacheProvider(
sp.GetRequiredService<RedisClient>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<RedisCacheProvider>>()));
}
else
{
services.AddSingleton<ICacheProvider>(sp => new MemoryCacheProvider(sp.GetRequiredService<TimeProvider>()));
}
// Security.
services.AddSingleton(new SecurityPolicyOptions());
services.AddSingleton<PasswordPolicy>();
services.AddSingleton<AccountSecurity>();
services.AddSingleton<ISecurityAuditLog, SecurityAuditLog>();
services.AddSingleton<SystemSettingsStore>();
services.AddSingleton(ModuleRegistry.Default);
services.AddSingleton(LicenseVerifier.Product);
services.AddSingleton(new LicenseSettings(options.License, options.Mode));
services.AddSingleton<LicenseGate>();
services.AddSingleton<ILicenseGate>(sp => sp.GetRequiredService<LicenseGate>());
services.AddSingleton<ILicenseActivationService, OfflineActivationService>();
services.AddSingleton<PermissionService>();
services.AddSingleton<RoleService>();
services.AddSingleton<SystemUserService>();
services.AddSingleton<UserService>();
services.AddSingleton<SessionStore>();
services.AddSingleton<NotificationDispatcher>();
services.AddSingleton<SignInService>();
// Companies and start.
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
services.AddSingleton(sp => new StartupOrchestrator(
sp.GetRequiredService<InstanceDatabases>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<MigrationRunner>(),
sp.GetRequiredService<SystemSettingsStore>(), sp.GetRequiredService<RoleService>(), sp.GetRequiredService<ILicenseGate>(),
sp.GetRequiredService<SystemUserService>(), sp.GetRequiredService<CompanyService>(), options, sp.GetRequiredService<IUnitOfWorkFactory>(),
logSink, sp.GetRequiredService<BootstrapState>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<StartupOrchestrator>>()));
services.AddHostedService<BootstrapService>();
// History of the records and scheduled tasks.
services.AddSingleton<AuditTrail>();
services.AddSingleton<IScheduledJob, SessionCleanupJob>();
services.AddSingleton<IScheduledJob, LicenseCheckJob>();
services.AddSingleton<IScheduledJob, LogRetentionJob>();
services.AddSingleton<JobScheduler>();
services.AddHostedService<JobSchedulerService>();
return services;
}
}
/// <summary>The user name written in the audit columns: the signed-in user of the current request, else <c>system</c>.</summary>
/// <param name="accessor">The current request.</param>
internal sealed class CurrentUserName(IHttpContextAccessor accessor)
{
/// <summary>The name.</summary>
/// <returns>The user name, or <see langword="null"/> outside requests.</returns>
public string? Get() => accessor.HttpContext?.User.Identity is { IsAuthenticated: true, Name: { } name } ? name : null;
}