using System.Diagnostics; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Net.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text.Json; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Identity; using Npgsql; namespace HealthApp.Provisioning; public sealed record Account(string AccountId, string Role, string Password); public sealed record InstallationPlan(string Database, string RuntimeRole, string RuntimePassword, string ProfileOwner, string ObservationOwner, string Host, int Port, string CertificatePassword, List Accounts, Dictionary Settings); public static class Installation { private static readonly JsonSerializerOptions Json = new() { WriteIndented = true, PropertyNameCaseInsensitive = true }; private static string Secret() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); private static string PathAt(string root, string path) => Path.Combine(root, path); private static void PrivateFile(string path, string text) { File.WriteAllText(path, text); if (OperatingSystem.IsLinux()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); } private static InstallationPlan Load(string directory) => JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(directory, "installation.json")), Json) ?? throw new InvalidOperationException(); public static void Prepare(string directory, string host, int port, string root, string? certificate, string? passwordFile, string? caFile) { if (Directory.Exists(directory) || File.Exists(directory)) throw new InvalidOperationException("refuse overwrite"); if (Uri.CheckHostName(host) == UriHostNameType.Unknown || host.Contains('%') || port is < 1024 or > 65535) throw new ArgumentException(); var id = Guid.NewGuid().ToString("N")[..12]; var prefix = "healthapp_b_" + id; var accounts = new List { new("prototype-patient", "Patient", Secret()), new("prototype-professional", "HealthcareProfessional", Secret()), new("installation-check", "Patient", Secret()) }; var settings = new Dictionary { ["urls"] = "https://0.0.0.0:" + port, ["Authentication:KeyDirectory"] = PathAt(root, "var/lib/healthapp-b/keys"), ["Authentication:TokenLifetimeMinutes"] = "30", ["Kestrel:Certificates:Default:Path"] = PathAt(root, "etc/healthapp-b/application.pfx") }; var plan = new InstallationPlan(prefix, prefix + "_runtime", Secret(), prefix + "_profile", prefix + "_observations", host, port, Secret(), accounts, settings); settings["Kestrel:Certificates:Default:Password"] = plan.CertificatePassword; for (var i = 0; i < accounts.Count; i++) { var a = accounts[i]; settings[$"Authentication:Accounts:{i}:AccountId"] = a.AccountId; settings[$"Authentication:Accounts:{i}:Role"] = a.Role; settings[$"Authentication:Accounts:{i}:PasswordHash"] = new PasswordHasher().HashPassword(a, a.Password); } Directory.CreateDirectory(directory); if (OperatingSystem.IsLinux()) File.SetUnixFileMode(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); if (certificate is not null) { if (passwordFile is null || caFile is null) throw new ArgumentException(); using var supplied = X509CertificateLoader.LoadPkcs12FromFile(certificate, File.ReadAllText(passwordFile).Trim()); if (!supplied.HasPrivateKey) throw new InvalidOperationException(); File.WriteAllBytes(Path.Combine(directory, "application.pfx"), supplied.Export(X509ContentType.Pfx, plan.CertificatePassword)); File.Copy(caFile, Path.Combine(directory, "healthapp-ca.crt")); } else { // Same framework certificate primitives and prototype trust model as pinned installer. using var caKey = RSA.Create(3072); var caRequest = new CertificateRequest("CN=HealthApp B prototype " + id, caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); caRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(caRequest.PublicKey, false)); using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(2)); using var key = RSA.Create(3072); var request = new CertificateRequest("CN=" + host, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true)); request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, true)); var san = new SubjectAlternativeNameBuilder(); if (IPAddress.TryParse(host, out var ip)) san.AddIpAddress(ip); else san.AddDnsName(host); request.CertificateExtensions.Add(san.Build()); using var leaf = request.Create(ca, DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(1), RandomNumberGenerator.GetBytes(16)); using var withKey = leaf.CopyWithPrivateKey(key); File.WriteAllBytes(Path.Combine(directory, "application.pfx"), withKey.Export(X509ContentType.Pfx, plan.CertificatePassword)); File.WriteAllText(Path.Combine(directory, "healthapp-ca.crt"), ca.ExportCertificatePem()); } PrivateFile(Path.Combine(directory, "installation.json"), JsonSerializer.Serialize(plan, Json)); PrivateFile(Path.Combine(directory, "accounts.json"), JsonSerializer.Serialize(accounts, Json)); if (OperatingSystem.IsLinux()) File.SetUnixFileMode(Path.Combine(directory, "application.pfx"), UnixFileMode.UserRead | UnixFileMode.UserWrite); } public static async Task DatabaseAsync(string directory, string migrations, string? adminFile) { var p = Load(directory); foreach (var identifier in new[] { p.Database, p.RuntimeRole, p.ProfileOwner, p.ObservationOwner }) if (!Regex.IsMatch(identifier, "^[a-z][a-z0-9_]{1,62}$")) throw new ArgumentException(); if (!Regex.IsMatch(p.RuntimePassword, "^[A-F0-9]{64}$")) throw new ArgumentException(); string? admin = adminFile is null ? null : File.ReadAllText(adminFile).Trim(); if (admin is not null) { var remote = new NpgsqlConnectionStringBuilder(admin); if (remote.SslMode != SslMode.VerifyFull) throw new InvalidOperationException("Remote admin requires VerifyFull."); var db = new NpgsqlConnectionStringBuilder(admin) { Database = p.Database, Username = p.RuntimeRole, Password = p.RuntimePassword, Pooling = true, IncludeErrorDetail = false }; p.Settings["ConnectionStrings:HealthDatabase"] = db.ConnectionString; p.Settings["Database:Remote"] = "true"; } else p.Settings["ConnectionStrings:HealthDatabase"] = new NpgsqlConnectionStringBuilder { Host = "127.0.0.1", Database = p.Database, Username = p.RuntimeRole, Password = p.RuntimePassword, Pooling = true, SslMode = SslMode.Disable, IncludeErrorDetail = false }.ConnectionString; async Task Sql(string sql, string? database = null) { if (admin is not null) { var options = new NpgsqlConnectionStringBuilder(admin) { Pooling = false, IncludeErrorDetail = false }; if (database is not null) options.Database = database; await using var connection = new NpgsqlConnection(options.ConnectionString); await connection.OpenAsync(); await using var command = new NpgsqlCommand(sql, connection); return (await command.ExecuteScalarAsync())?.ToString() ?? ""; } var start = new ProcessStartInfo("runuser") { UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; foreach (var arg in new[] { "-u", "postgres", "--", "psql", "--no-psqlrc", "--set=ON_ERROR_STOP=1", "--tuples-only", "--no-align", "--dbname", database ?? "postgres" }) start.ArgumentList.Add(arg); using var process = Process.Start(start) ?? throw new InvalidOperationException(); var output = process.StandardOutput.ReadToEndAsync(); var error = process.StandardError.ReadToEndAsync(); await process.StandardInput.WriteAsync(sql); process.StandardInput.Close(); using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(60)); await process.WaitForExitAsync(deadline.Token); await error; if (process.ExitCode != 0) throw new InvalidOperationException("administration failed"); return (await output).Trim(); } if (await Sql($"SELECT EXISTS(SELECT FROM pg_database WHERE datname='{p.Database}');") is "t" or "True") throw new InvalidOperationException("existing database retained"); await Sql($"SET password_encryption='scram-sha-256'; CREATE ROLE {p.RuntimeRole} LOGIN PASSWORD '{p.RuntimePassword}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION; CREATE ROLE {p.ProfileOwner} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE; CREATE ROLE {p.ObservationOwner} NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE;"); await Sql($"CREATE DATABASE {p.Database};"); await Sql($"REVOKE ALL ON DATABASE {p.Database} FROM PUBLIC; GRANT CONNECT ON DATABASE {p.Database} TO {p.RuntimeRole};", p.Database); await Sql($"REVOKE ALL ON SCHEMA public FROM PUBLIC; CREATE SCHEMA profile AUTHORIZATION {p.ProfileOwner}; CREATE SCHEMA observations AUTHORIZATION {p.ObservationOwner};", p.Database); foreach (var module in new[] { ("Profile", p.ProfileOwner), ("Observations", p.ObservationOwner) }) { if (module.Item1 == "Observations") await Sql($"GRANT USAGE ON SCHEMA profile TO {p.ObservationOwner}; GRANT REFERENCES ON profile.patient TO {p.ObservationOwner};", p.Database); foreach (var script in Directory.GetFiles(Path.Combine(migrations, module.Item1), "*.sql").Order()) await Sql($"BEGIN; SET LOCAL ROLE {module.Item2};\n" + Regex.Replace(await File.ReadAllTextAsync(script), @"^CREATE SCHEMA IF NOT EXISTS \w+;\s*", "") + "\nCOMMIT;", p.Database); } await Sql($"GRANT USAGE ON SCHEMA profile,observations TO {p.RuntimeRole}; GRANT SELECT,INSERT,UPDATE ON profile.patient TO {p.RuntimeRole}; GRANT SELECT,INSERT,UPDATE,DELETE ON observations.observation TO {p.RuntimeRole}; GRANT SELECT ON profile.schema_version,observations.schema_version TO {p.RuntimeRole};", p.Database); if (admin is null) { // RHEL/Fedora may default to ident. Add only the new B database/role rule; // retain every existing rule and a protected backup, rather than weaken host-wide auth. var hbaPath = (await Sql("SHOW hba_file;")).Trim(); var original = await File.ReadAllTextAsync(hbaPath); PrivateFile(Path.Combine(directory, "pg_hba.before.conf"), original); var rule = $"host {p.Database} {p.RuntimeRole} 127.0.0.1/32 scram-sha-256\n"; await File.WriteAllTextAsync(hbaPath, rule + original); await Sql("SELECT pg_reload_conf();"); } PrivateFile(Path.Combine(directory, "installation.json"), JsonSerializer.Serialize(p, Json)); await using var runtime = new NpgsqlConnection(p.Settings["ConnectionStrings:HealthDatabase"]); await runtime.OpenAsync(); await using var check = new NpgsqlCommand("SELECT current_user,has_schema_privilege(current_user,'profile','CREATE') OR has_schema_privilege(current_user,'observations','CREATE')", runtime); await using var reader = await check.ExecuteReaderAsync(); await reader.ReadAsync(); if (reader.GetString(0) != p.RuntimeRole || reader.GetBoolean(1)) throw new InvalidOperationException("runtime privilege verification failed"); } public static void Configure(string directory, string root) { var plan = Load(directory); var config = PathAt(root, "etc/healthapp-b"); if (Directory.Exists(config) || File.Exists(config)) throw new InvalidOperationException("configuration exists"); Directory.CreateDirectory(config); File.Copy(Path.Combine(directory, "application.pfx"), Path.Combine(config, "application.pfx")); File.Copy(Path.Combine(directory, "healthapp-ca.crt"), Path.Combine(config, "healthapp-ca.crt")); var connection = new NpgsqlConnectionStringBuilder(plan.Settings["ConnectionStrings:HealthDatabase"]); if (!string.IsNullOrWhiteSpace(connection.RootCertificate)) { var destination = Path.Combine(config, "database-ca.crt"); File.Copy(connection.RootCertificate, destination); connection.RootCertificate = destination; plan.Settings["ConnectionStrings:HealthDatabase"] = connection.ConnectionString; } PrivateFile(Path.Combine(config, "appsettings.json"), JsonSerializer.Serialize(plan.Settings, Json)); PrivateFile(Path.Combine(directory, "installation.json"), JsonSerializer.Serialize(plan, Json)); var keys = PathAt(root, "var/lib/healthapp-b/keys"); Directory.CreateDirectory(keys); if (OperatingSystem.IsLinux()) { File.SetUnixFileMode(config, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); File.SetUnixFileMode(keys, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); File.SetUnixFileMode(Path.Combine(config, "application.pfx"), UnixFileMode.UserRead | UnixFileMode.UserWrite); } } public static async Task VerifyDatabaseAsync(string directory) { var plan = Load(directory); await using var connection = new NpgsqlConnection(plan.Settings["ConnectionStrings:HealthDatabase"]); await connection.OpenAsync(); await using var command = new NpgsqlCommand("SELECT (SELECT max(version) FROM profile.schema_version)=1 AND (SELECT max(version) FROM observations.schema_version)=1", connection); if (await command.ExecuteScalarAsync() is not true) throw new InvalidOperationException("schema readiness failed"); } public static async Task VerifyAsync(string directory) { var plan = Load(directory); using var root = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "healthapp-ca.crt")); using var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, cert, peerChain, errors) => { if (cert is null || (errors & (SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable)) != 0) return false; using var chain = new X509Chain(); chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.CustomTrustStore.Add(root); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; if (peerChain is not null) foreach (var element in peerChain.ChainElements) chain.ChainPolicy.ExtraStore.Add(element.Certificate); return chain.Build(cert); } }; using var client = new HttpClient(handler) { BaseAddress = new UriBuilder("https", plan.Host, plan.Port).Uri, Timeout = TimeSpan.FromSeconds(15) }; var account = plan.Accounts.Single(a => a.AccountId == "installation-check"); using var login = await client.PostAsJsonAsync("api/authentication/login", new { accountId = account.AccountId, password = account.Password }); login.EnsureSuccessStatusCode(); using var ticket = JsonDocument.Parse(await login.Content.ReadAsStringAsync()); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ticket.RootElement.GetProperty("accessToken").GetString()); using var ready = await client.GetAsync("health/ready"); ready.EnsureSuccessStatusCode(); using var profile = await client.PostAsJsonAsync("api/patients", new { name = "Synthetic installation check", dateOfBirth = "1980-01-01" }); if (profile.StatusCode is not (HttpStatusCode.Created or HttpStatusCode.Conflict)) throw new InvalidOperationException(); using var me = await client.GetAsync("api/patients/me"); me.EnsureSuccessStatusCode(); using var p = JsonDocument.Parse(await me.Content.ReadAsStringAsync()); var id = p.RootElement.GetProperty("patientId").GetGuid(); if (profile.StatusCode == HttpStatusCode.Created) { using var observation = await client.PostAsJsonAsync($"api/patients/{id}/observations", new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68, measurementContext = new { setting = "Home", activityCondition = "AtRest" } }); observation.EnsureSuccessStatusCode(); } foreach (var path in new[] { "observations/latest", "observations?from=2026-09-01&to=2026-09-30", "insights?from=2026-09-01&to=2026-09-30", "overview?from=2026-09-01&to=2026-09-30" }) { using var result = await client.GetAsync($"api/patients/{id}/{path}"); result.EnsureSuccessStatusCode(); } await using var connection = new NpgsqlConnection(plan.Settings["ConnectionStrings:HealthDatabase"]); await connection.OpenAsync(); } }