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>
357 lines
15 KiB
C#
357 lines
15 KiB
C#
using System.Globalization;
|
|
using System.Net.Mail;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Data;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Khaemhat.Application.Configuration;
|
|
|
|
/// <summary>How the licences behave (<c>KHAEMHAT_LICENSE_MODE</c>).</summary>
|
|
public enum LicenseMode
|
|
{
|
|
/// <summary>Only signed licences count.</summary>
|
|
Production = 0,
|
|
|
|
/// <summary>The fictitious codes of SPEC §8.3 are accepted too. Never in production.</summary>
|
|
Test = 1,
|
|
}
|
|
|
|
/// <summary>The connection security of the mail server.</summary>
|
|
public enum SmtpSecurity
|
|
{
|
|
/// <summary>STARTTLS on a plain connection (port 587).</summary>
|
|
StartTls = 0,
|
|
|
|
/// <summary>TLS from the start (port 465).</summary>
|
|
Ssl = 1,
|
|
|
|
/// <summary>No encryption: only for a local relay.</summary>
|
|
None = 2,
|
|
}
|
|
|
|
/// <summary>A configuration that does not let the instance start. The message lists every problem, never a value.</summary>
|
|
public sealed class ConfigurationException : Exception
|
|
{
|
|
/// <summary>Creates the exception.</summary>
|
|
public ConfigurationException()
|
|
: this([])
|
|
{
|
|
}
|
|
|
|
/// <summary>Creates the exception.</summary>
|
|
/// <param name="message">The message.</param>
|
|
public ConfigurationException(string message)
|
|
: base(message) => Errors = [message];
|
|
|
|
/// <summary>Creates the exception.</summary>
|
|
/// <param name="message">The message.</param>
|
|
/// <param name="innerException">The cause.</param>
|
|
public ConfigurationException(string message, Exception innerException)
|
|
: base(message, innerException) => Errors = [message];
|
|
|
|
/// <summary>Creates the exception from a list of problems.</summary>
|
|
/// <param name="errors">The problems.</param>
|
|
public ConfigurationException(IReadOnlyList<string> errors)
|
|
: base(Describe(errors)) => Errors = errors;
|
|
|
|
/// <summary>The problems, one per line of the message.</summary>
|
|
public IReadOnlyList<string> Errors { get; }
|
|
|
|
private static string Describe(IReadOnlyList<string> errors) =>
|
|
"Khaemhat cannot start: the configuration is not valid (see docs/DEPLOY.md and the wiki page Installazione-Docker)."
|
|
+ string.Concat((errors ?? []).Select(e => Environment.NewLine + " - " + e));
|
|
}
|
|
|
|
/// <summary>
|
|
/// The instance configuration of SPEC §6, read from the environment by <see cref="EnvironmentConfigurationReader"/>.
|
|
/// Values stay in memory: nothing is written to disk. <see cref="Validate"/> checks everything before the host starts;
|
|
/// the typed accessors (<see cref="SystemDatabase"/>, <see cref="Mode"/>...) are meant for a validated instance.
|
|
/// </summary>
|
|
public sealed class KhaemhatOptions
|
|
{
|
|
/// <summary><c>KHAEMHAT_SYSTEM_DB</c>: the system database URL (required).</summary>
|
|
public string? SystemDb { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_DB_SERVER</c>: the PostgreSQL server where company databases are created.</summary>
|
|
public string? DbServer { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SECRET_KEY</c>: base64 of at least 32 bytes (required).</summary>
|
|
public string? SecretKey { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SECRET_KEY_NEW</c>: the new key during a rotation (SPEC §12.9).</summary>
|
|
public string? RotationSecretKey { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SUPERUSER</c>: the super user name, read only while <c>sys_users</c> is empty.</summary>
|
|
public string? SuperUser { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SUPERUSER_PASSWORD</c>: its first password, to change at the first access.</summary>
|
|
public string? SuperUserPassword { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SUPERUSER_EMAIL</c>: its e-mail address.</summary>
|
|
public string? SuperUserEmail { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_COMPANY_CODE</c>: the first company, read only while <c>sys_companies</c> is empty.</summary>
|
|
public string? CompanyCode { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_COMPANY_NAME</c>: its name.</summary>
|
|
public string? CompanyName { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_COUNTRY</c>: the fiscal package of the first company (default <c>IT</c>).</summary>
|
|
public string Country { get; init; } = "IT";
|
|
|
|
/// <summary><c>KHAEMHAT_LICENSE_MODE</c>: <c>production</c> (default) or <c>test</c>.</summary>
|
|
public string LicenseMode { get; init; } = "production";
|
|
|
|
/// <summary><c>KHAEMHAT_LICENSE</c>: the text of a <c>.khl</c> licence; absent means Trial.</summary>
|
|
public string? License { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_REDIS</c>: <c>redis://</c> or <c>rediss://</c>; absent means in-memory cache.</summary>
|
|
public string? Redis { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_DATA_DIR</c>: the only folder the instance writes to (default <c>/data</c>).</summary>
|
|
public string DataDir { get; init; } = "/data";
|
|
|
|
/// <summary><c>KHAEMHAT_URLS</c>: the listening addresses.</summary>
|
|
public string? Urls { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_PUBLIC_URL</c>: the address users reach, for links in e-mails.</summary>
|
|
public string? PublicUrl { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_HOST</c>.</summary>
|
|
public string? SmtpHost { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_PORT</c>.</summary>
|
|
public string? SmtpPort { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_USER</c>.</summary>
|
|
public string? SmtpUser { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_PASSWORD</c>.</summary>
|
|
public string? SmtpPassword { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_FROM</c>.</summary>
|
|
public string? SmtpFrom { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_SECURITY</c>: <c>starttls</c> (default), <c>ssl</c> or <c>none</c>.</summary>
|
|
public string? SmtpSecurity { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_LOG_LEVEL</c>: the minimum level on stdout.</summary>
|
|
public string? LogLevel { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SEED_BASE</c>: load the base tables when a company is created (default true).</summary>
|
|
public string? SeedBase { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SEED_DEMO</c>: load the demo data into an empty company (default false).</summary>
|
|
public string? SeedDemo { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_UPDATE_FEED</c>: the package list read by the update check.</summary>
|
|
public string? UpdateFeed { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_UPDATE_TOKEN</c>: a read-only token for the feed.</summary>
|
|
public string? UpdateToken { get; init; }
|
|
|
|
/// <summary><c>TZ</c>: the time zone of the container.</summary>
|
|
public string? TimeZone { get; init; }
|
|
|
|
/// <summary>The problems met while reading (both <c>X</c> and <c>X_FILE</c>, unreadable files).</summary>
|
|
public IReadOnlyList<string> ReadErrors { get; init; } = [];
|
|
|
|
/// <summary>The system database, parsed.</summary>
|
|
public DatabaseUrl SystemDatabase => DatabaseUrl.Parse(SystemDb ?? throw new ConfigurationException("KHAEMHAT_SYSTEM_DB is not set."));
|
|
|
|
/// <summary>
|
|
/// Where company databases are created: <see cref="DbServer"/> when set, otherwise the server (PostgreSQL) or the
|
|
/// folder (SQLite) of the system database.
|
|
/// </summary>
|
|
public DatabaseUrl CompanyServer => DbServer is { } server ? DatabaseUrl.Parse(server) : SystemDatabase;
|
|
|
|
/// <summary>The licence mode, parsed.</summary>
|
|
public LicenseMode Mode => string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase)
|
|
? Configuration.LicenseMode.Test
|
|
: Configuration.LicenseMode.Production;
|
|
|
|
/// <summary>Whether base data is loaded into new companies.</summary>
|
|
public bool SeedBaseEnabled => ParseBool(SeedBase) ?? true;
|
|
|
|
/// <summary>Whether demo data is loaded into new, empty companies.</summary>
|
|
public bool SeedDemoEnabled => ParseBool(SeedDemo) ?? false;
|
|
|
|
/// <summary>The SMTP port, defaulting by security mode.</summary>
|
|
public int SmtpPortNumber => int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port)
|
|
? port
|
|
: SmtpSecurityMode == Configuration.SmtpSecurity.Ssl ? 465 : 587;
|
|
|
|
/// <summary>The SMTP security, parsed.</summary>
|
|
public SmtpSecurity SmtpSecurityMode => SmtpSecurity?.ToUpperInvariant() switch
|
|
{
|
|
"SSL" or "TLS" => Configuration.SmtpSecurity.Ssl,
|
|
"NONE" => Configuration.SmtpSecurity.None,
|
|
_ => Configuration.SmtpSecurity.StartTls,
|
|
};
|
|
|
|
/// <summary>
|
|
/// Checks the whole configuration. Messages name the variable and the expected form, never its value.
|
|
/// The variables needed only at first start (super user, first company) are checked by the bootstrap, which knows
|
|
/// whether the tables are still empty; here only their form is checked when they are set.
|
|
/// </summary>
|
|
/// <returns>The problems; empty when the instance can start.</returns>
|
|
public IReadOnlyList<string> Validate()
|
|
{
|
|
var errors = new List<string>(ReadErrors);
|
|
|
|
if (SystemDb is null)
|
|
{
|
|
if (!ReadErrors.Any(e => e.StartsWith("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal)))
|
|
{
|
|
errors.Add("KHAEMHAT_SYSTEM_DB is required: postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db.");
|
|
}
|
|
}
|
|
else if (!DatabaseUrl.TryParse(SystemDb, out _))
|
|
{
|
|
errors.Add("KHAEMHAT_SYSTEM_DB is not a valid database URL: use postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db.");
|
|
}
|
|
|
|
if (DbServer is not null && (!DatabaseUrl.TryParse(DbServer, out var server) || server.Engine != DbEngine.PostgreSql))
|
|
{
|
|
errors.Add("KHAEMHAT_DB_SERVER must be a PostgreSQL server URL: postgres://user:password@host:5432/ (a role with CREATEDB).");
|
|
}
|
|
|
|
CheckKey("KHAEMHAT_SECRET_KEY", SecretKey, required: true, errors);
|
|
CheckKey("KHAEMHAT_SECRET_KEY_NEW", RotationSecretKey, required: false, errors);
|
|
|
|
if (SuperUser is not null && !UserNames.IsValid(SuperUser))
|
|
{
|
|
errors.Add("KHAEMHAT_SUPERUSER must be 3 to 50 characters: letters, digits, dot, dash or underscore.");
|
|
}
|
|
|
|
if (SuperUserEmail is not null && !IsEmail(SuperUserEmail))
|
|
{
|
|
errors.Add("KHAEMHAT_SUPERUSER_EMAIL is not a valid e-mail address.");
|
|
}
|
|
|
|
if (CompanyCode is not null && !CompanyCodes.IsValid(CompanyCode.Trim().ToUpperInvariant()))
|
|
{
|
|
errors.Add("KHAEMHAT_COMPANY_CODE must be 1 to 20 characters: letters, digits or underscore, starting with a letter.");
|
|
}
|
|
|
|
if (CompanyName is { Length: > 200 })
|
|
{
|
|
errors.Add("KHAEMHAT_COMPANY_NAME is longer than 200 characters.");
|
|
}
|
|
|
|
if (!string.Equals(Country, "IT", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
errors.Add("KHAEMHAT_COUNTRY: the only fiscal package available is IT.");
|
|
}
|
|
|
|
if (!string.Equals(LicenseMode, "production", StringComparison.OrdinalIgnoreCase)
|
|
&& !string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
errors.Add("KHAEMHAT_LICENSE_MODE must be production or test.");
|
|
}
|
|
|
|
if (Redis is not null && !(Uri.TryCreate(Redis, UriKind.Absolute, out var redis) && redis.Scheme is "redis" or "rediss"))
|
|
{
|
|
errors.Add("KHAEMHAT_REDIS must be redis://[:password@]host:6379/0 or rediss:// for TLS.");
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(DataDir) || !Path.IsPathFullyQualified(DataDir))
|
|
{
|
|
errors.Add("KHAEMHAT_DATA_DIR must be an absolute path (default /data).");
|
|
}
|
|
|
|
if (PublicUrl is not null && !IsHttpUrl(PublicUrl))
|
|
{
|
|
errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com.");
|
|
}
|
|
|
|
if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536))
|
|
{
|
|
errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535.");
|
|
}
|
|
|
|
if (SmtpSecurity is not null && SmtpSecurity.ToUpperInvariant() is not ("STARTTLS" or "SSL" or "TLS" or "NONE"))
|
|
{
|
|
errors.Add("KHAEMHAT_SMTP_SECURITY must be starttls, ssl or none.");
|
|
}
|
|
|
|
if (SmtpFrom is not null && !IsEmail(SmtpFrom))
|
|
{
|
|
errors.Add("KHAEMHAT_SMTP_FROM is not a valid e-mail address.");
|
|
}
|
|
|
|
if (LogLevel is not null && !(Enum.TryParse<LogLevel>(LogLevel, ignoreCase: true, out var level) && Enum.IsDefined(level)))
|
|
{
|
|
errors.Add("KHAEMHAT_LOG_LEVEL must be Trace, Debug, Information, Warning, Error, Critical or None.");
|
|
}
|
|
|
|
if (SeedBase is not null && ParseBool(SeedBase) is null)
|
|
{
|
|
errors.Add("KHAEMHAT_SEED_BASE must be true or false.");
|
|
}
|
|
|
|
if (SeedDemo is not null && ParseBool(SeedDemo) is null)
|
|
{
|
|
errors.Add("KHAEMHAT_SEED_DEMO must be true or false.");
|
|
}
|
|
|
|
if (UpdateFeed is not null && !IsHttpUrl(UpdateFeed))
|
|
{
|
|
errors.Add("KHAEMHAT_UPDATE_FEED must be an absolute http or https address.");
|
|
}
|
|
|
|
if (TimeZone is not null && !TimeZoneInfo.TryFindSystemTimeZoneById(TimeZone, out _))
|
|
{
|
|
errors.Add("TZ is not a known time zone, for example Europe/Rome.");
|
|
}
|
|
|
|
return errors;
|
|
}
|
|
|
|
/// <summary>Throws when <see cref="Validate"/> finds problems.</summary>
|
|
/// <exception cref="ConfigurationException">The configuration is not valid.</exception>
|
|
public void EnsureValid()
|
|
{
|
|
var errors = Validate();
|
|
if (errors.Count > 0)
|
|
{
|
|
throw new ConfigurationException(errors);
|
|
}
|
|
}
|
|
|
|
private static void CheckKey(string name, string? value, bool required, List<string> errors)
|
|
{
|
|
if (value is null)
|
|
{
|
|
if (required)
|
|
{
|
|
errors.Add($"{name} is required: the base64 of at least 32 random bytes (for example: openssl rand -base64 32).");
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
_ = Infrastructure.Security.SecretKey.FromBase64(value);
|
|
}
|
|
catch (FormatException ex)
|
|
{
|
|
errors.Add(ex.Message.Replace("KHAEMHAT_SECRET_KEY", name, StringComparison.Ordinal));
|
|
}
|
|
}
|
|
|
|
private static bool? ParseBool(string? value) => value?.Trim().ToUpperInvariant() switch
|
|
{
|
|
null => null,
|
|
"TRUE" or "1" or "YES" or "SI" => true,
|
|
"FALSE" or "0" or "NO" => false,
|
|
_ => null,
|
|
};
|
|
|
|
private static bool IsHttpUrl(string value) =>
|
|
Uri.TryCreate(value, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
|
|
|
|
private static bool IsEmail(string value) => MailAddress.TryCreate(value, out var address) && address.Address == value.Trim();
|
|
}
|