using System.Globalization;
using System.Net.Mail;
using Khaemhat.Application.Security;
using Khaemhat.Data;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Configuration;
/// How the licences behave (KHAEMHAT_LICENSE_MODE).
public enum LicenseMode
{
/// Only signed licences count.
Production = 0,
/// The fictitious codes of SPEC §8.3 are accepted too. Never in production.
Test = 1,
}
/// The connection security of the mail server.
public enum SmtpSecurity
{
/// STARTTLS on a plain connection (port 587).
StartTls = 0,
/// TLS from the start (port 465).
Ssl = 1,
/// No encryption: only for a local relay.
None = 2,
}
/// A configuration that does not let the instance start. The message lists every problem, never a value.
public sealed class ConfigurationException : Exception
{
/// Creates the exception.
public ConfigurationException()
: this([])
{
}
/// Creates the exception.
/// The message.
public ConfigurationException(string message)
: base(message) => Errors = [message];
/// Creates the exception.
/// The message.
/// The cause.
public ConfigurationException(string message, Exception innerException)
: base(message, innerException) => Errors = [message];
/// Creates the exception from a list of problems.
/// The problems.
public ConfigurationException(IReadOnlyList errors)
: base(Describe(errors)) => Errors = errors;
/// The problems, one per line of the message.
public IReadOnlyList Errors { get; }
private static string Describe(IReadOnlyList 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));
}
///
/// The instance configuration of SPEC §6, read from the environment by .
/// Values stay in memory: nothing is written to disk. checks everything before the host starts;
/// the typed accessors (, ...) are meant for a validated instance.
///
public sealed class KhaemhatOptions
{
/// KHAEMHAT_SYSTEM_DB: the system database URL (required).
public string? SystemDb { get; init; }
/// KHAEMHAT_DB_SERVER: the PostgreSQL server where company databases are created.
public string? DbServer { get; init; }
/// KHAEMHAT_SECRET_KEY: base64 of at least 32 bytes (required).
public string? SecretKey { get; init; }
/// KHAEMHAT_SECRET_KEY_NEW: the new key during a rotation (SPEC §12.9).
public string? RotationSecretKey { get; init; }
/// KHAEMHAT_SUPERUSER: the super user name, read only while sys_users is empty.
public string? SuperUser { get; init; }
/// KHAEMHAT_SUPERUSER_PASSWORD: its first password, to change at the first access.
public string? SuperUserPassword { get; init; }
/// KHAEMHAT_SUPERUSER_EMAIL: its e-mail address.
public string? SuperUserEmail { get; init; }
/// KHAEMHAT_COMPANY_CODE: the first company, read only while sys_companies is empty.
public string? CompanyCode { get; init; }
/// KHAEMHAT_COMPANY_NAME: its name.
public string? CompanyName { get; init; }
/// KHAEMHAT_COUNTRY: the fiscal package of the first company (default IT).
public string Country { get; init; } = "IT";
/// KHAEMHAT_LICENSE_MODE: production (default) or test.
public string LicenseMode { get; init; } = "production";
/// KHAEMHAT_LICENSE: the text of a .khl licence; absent means Trial.
public string? License { get; init; }
/// KHAEMHAT_REDIS: redis:// or rediss://; absent means in-memory cache.
public string? Redis { get; init; }
/// KHAEMHAT_DATA_DIR: the only folder the instance writes to (default /data).
public string DataDir { get; init; } = "/data";
/// KHAEMHAT_URLS: the listening addresses.
public string? Urls { get; init; }
/// KHAEMHAT_PUBLIC_URL: the address users reach, for links in e-mails.
public string? PublicUrl { get; init; }
/// KHAEMHAT_SMTP_HOST.
public string? SmtpHost { get; init; }
/// KHAEMHAT_SMTP_PORT.
public string? SmtpPort { get; init; }
/// KHAEMHAT_SMTP_USER.
public string? SmtpUser { get; init; }
/// KHAEMHAT_SMTP_PASSWORD.
public string? SmtpPassword { get; init; }
/// KHAEMHAT_SMTP_FROM.
public string? SmtpFrom { get; init; }
/// KHAEMHAT_SMTP_SECURITY: starttls (default), ssl or none.
public string? SmtpSecurity { get; init; }
/// KHAEMHAT_LOG_LEVEL: the minimum level on stdout.
public string? LogLevel { get; init; }
/// KHAEMHAT_SEED_BASE: load the base tables when a company is created (default true).
public string? SeedBase { get; init; }
/// KHAEMHAT_SEED_DEMO: load the demo data into an empty company (default false).
public string? SeedDemo { get; init; }
/// KHAEMHAT_UPDATE_FEED: the package list read by the update check.
public string? UpdateFeed { get; init; }
/// KHAEMHAT_UPDATE_TOKEN: a read-only token for the feed.
public string? UpdateToken { get; init; }
///
/// KHAEMHAT_HELP_URL: the online wiki opened by "Apri nel wiki" (default the project wiki). The help itself
/// is the copy of the wiki shipped in the image, so it works offline.
///
public string? HelpUrl { get; init; }
/// TZ: the time zone of the container.
public string? TimeZone { get; init; }
/// The problems met while reading (both X and X_FILE, unreadable files).
public IReadOnlyList ReadErrors { get; init; } = [];
/// The system database, parsed.
public DatabaseUrl SystemDatabase => DatabaseUrl.Parse(SystemDb ?? throw new ConfigurationException("KHAEMHAT_SYSTEM_DB is not set."));
///
/// Where company databases are created: when set, otherwise the server (PostgreSQL) or the
/// folder (SQLite) of the system database.
///
public DatabaseUrl CompanyServer => DbServer is { } server ? DatabaseUrl.Parse(server) : SystemDatabase;
/// The licence mode, parsed.
public LicenseMode Mode => string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase)
? Configuration.LicenseMode.Test
: Configuration.LicenseMode.Production;
/// Whether base data is loaded into new companies.
public bool SeedBaseEnabled => ParseBool(SeedBase) ?? true;
/// Whether demo data is loaded into new, empty companies.
public bool SeedDemoEnabled => ParseBool(SeedDemo) ?? false;
/// The SMTP port, defaulting by security mode.
public int SmtpPortNumber => int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port)
? port
: SmtpSecurityMode == Configuration.SmtpSecurity.Ssl ? 465 : 587;
/// The SMTP security, parsed.
public SmtpSecurity SmtpSecurityMode => SmtpSecurity?.ToUpperInvariant() switch
{
"SSL" or "TLS" => Configuration.SmtpSecurity.Ssl,
"NONE" => Configuration.SmtpSecurity.None,
_ => Configuration.SmtpSecurity.StartTls,
};
///
/// 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.
///
/// The problems; empty when the instance can start.
public IReadOnlyList Validate()
{
var errors = new List(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 (HelpUrl is not null && !IsHttpUrl(HelpUrl))
{
errors.Add("KHAEMHAT_HELP_URL must be an absolute http or https address, for example https://gitea.example.com/owner/khaemhat/wiki/.");
}
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, 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;
}
/// Throws when finds problems.
/// The configuration is not valid.
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 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();
}