using System.Net; 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 class Topology { public Dictionary Hosts { get; set; } = new(); public Dictionary Ports { get; set; } = new(); public Dictionary Platforms { get; set; } = new(); } public sealed record DatabaseSettings(string Name, string User, string Password, string Host = "localhost", int Port = 5432); public sealed record Account(string AccountId, string Role, string Password); public sealed record ServiceSettings(string Name, string Host, int Port, string IncomingKey, string? OutgoingKey, string CertificatePassword, DatabaseSettings? Database, Dictionary Environment, string Platform = "linux"); public sealed record Deployment(string Id, Dictionary Services, List Accounts) { public static readonly string[] Names = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"]; public static readonly Dictionary ContractNames = new() { ["patient-profile"] = "PatientProfile", ["observation"] = "Observation", ["insights"] = "Insights", ["health-overview"] = "HealthOverview" }; public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true, WriteIndented = true }; public static string Secret() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); public static string Url(ServiceSettings service) => new UriBuilder("https", service.Host, service.Port).Uri.ToString(); public static Deployment Load(string directory) => JsonSerializer.Deserialize( File.ReadAllText(Path.Combine(directory, "deployment.json")), Json) ?? throw new InvalidOperationException("Deployment is invalid."); public static void Prepare(string output, string host, string? topologyFile, string? certificates) { if (Directory.Exists(output) || File.Exists(output)) throw new InvalidOperationException("Deployment output already exists; existing credentials were not changed."); var topology = topologyFile is null ? new Topology() : JsonSerializer.Deserialize(File.ReadAllText(topologyFile), Json) ?? throw new InvalidOperationException("Topology is invalid."); foreach (var name in topology.Hosts.Keys.Concat(topology.Ports.Keys).Concat(topology.Platforms.Keys)) if (!Names.Contains(name)) throw new InvalidOperationException("Topology has an unknown service."); var id = Guid.NewGuid().ToString("N")[..12]; var services = new Dictionary(); var defaults = new Dictionary { ["api-gateway"] = 5443, ["patient-profile"] = 5081, ["observation"] = 5082, ["insights"] = 5083, ["health-overview"] = 5084 }; foreach (var name in Names) { var hostname = topology.Hosts.GetValueOrDefault(name, host); if (Uri.CheckHostName(hostname) == UriHostNameType.Unknown || hostname.Contains('%')) throw new InvalidOperationException("Provide a valid DNS name or IP address for each service host."); var port = topology.Ports.GetValueOrDefault(name, defaults[name]); if (port < 1024 || port > 65535) throw new InvalidOperationException("HTTPS ports must be between 1024 and 65535."); DatabaseSettings? database = name switch { "patient-profile" => new("healthapp_" + id + "_profile", "healthapp_" + id + "_profile", Secret()), "observation" => new("healthapp_" + id + "_observation", "healthapp_" + id + "_observation", Secret()), _ => null }; var platform = topology.Platforms.GetValueOrDefault(name, OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linux"); if (platform is not ("linux" or "windows" or "macos")) throw new InvalidOperationException("Unsupported node platform."); services[name] = new(name, hostname, port, Secret(), name is "api-gateway" or "patient-profile" ? null : Secret(), Secret(), database, new(), platform); } if (services.Values.GroupBy(s => (s.Host.ToLowerInvariant(), s.Port)).Any(g => g.Count() > 1)) throw new InvalidOperationException("Colocated services need distinct HTTPS ports."); var accounts = new List { new("prototype-patient", "Patient", Secret()), new("prototype-professional", "HealthcareProfessional", Secret()), new("installation-check", "Patient", Secret()) }; var deployment = new Deployment(id, services, accounts); foreach (var service in services.Values) { var env = service.Environment; env["ASPNETCORE_ENVIRONMENT"] = "Production"; env["ASPNETCORE_URLS"] = "https://0.0.0.0:" + service.Port; env["InternalAccess__GatewayKey"] = service.IncomingKey; env["Kestrel__Certificates__Default__Path"] = $"/etc/healthapp/{service.Name}/service.pfx"; env["Kestrel__Certificates__Default__Password"] = service.CertificatePassword; if (service.Name == "api-gateway") { env["Authentication__KeyDirectory"] = "/var/lib/healthapp-api-gateway/keys"; foreach (var (name, contract) in ContractNames) { env[$"Services__{contract}__BaseUrl"] = Url(services[name]); env[$"Services__{contract}__Key"] = services[name].IncomingKey; if (services[name].OutgoingKey is { } key) env[$"InternalAccess__{contract}__Key"] = key; } for (var index = 0; index < accounts.Count; index++) { var account = accounts[index]; env[$"Authentication__Accounts__{index}__AccountId"] = account.AccountId; env[$"Authentication__Accounts__{index}__Role"] = account.Role; env[$"Authentication__Accounts__{index}__PasswordHash"] = new PasswordHasher().HashPassword(account, account.Password); } } else if (service.OutgoingKey is not null) { env["Services__ApiGateway__BaseUrl"] = Url(services["api-gateway"]); env["Services__ApiGateway__Key"] = service.OutgoingKey; } if (service.Database is { } db) env[service.Name == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase"] = ConnectionString(db); } Directory.CreateDirectory(output); if ((OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())) File.SetUnixFileMode(output, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); using var caKey = RSA.Create(3072); var caRequest = new CertificateRequest("CN=HealthApp 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)); // Only the public CA is needed on installed nodes; no signing key is retained. File.WriteAllText(Path.Combine(output, "healthapp-ca.crt"), certificates is null ? ca.ExportCertificatePem() : File.ReadAllText(Path.Combine(certificates, "healthapp-ca.crt"))); foreach (var service in services.Values) { var directory = Path.Combine(output, service.Name); Directory.CreateDirectory(directory); File.WriteAllText(Path.Combine(directory, "service.json"), JsonSerializer.Serialize(service, Json)); File.WriteAllLines(Path.Combine(directory, "service.env"), service.Environment.Select(e => e.Key + "=" + Quote(e.Value))); byte[] pfx; if (certificates is not null) { var password = File.ReadAllText(Path.Combine(certificates, service.Name + ".password")).TrimEnd('\r', '\n'); var supplied = X509CertificateLoader.LoadPkcs12CollectionFromFile(Path.Combine(certificates, service.Name + ".pfx"), password); if (!supplied.Cast().Any(c => c.HasPrivateKey)) throw new InvalidOperationException("Supplied certificate has no private key."); pfx = supplied.Export(X509ContentType.Pfx, service.CertificatePassword)!; foreach (var certificate in supplied) certificate.Dispose(); } else { using var key = RSA.Create(2048); var request = new CertificateRequest("CN=" + service.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 System.Security.Cryptography.OidCollection { new("1.3.6.1.5.5.7.3.1") }, true)); var san = new SubjectAlternativeNameBuilder(); if (IPAddress.TryParse(service.Host, out var ip)) san.AddIpAddress(ip); else san.AddDnsName(service.Host); request.CertificateExtensions.Add(san.Build()); using var leaf = request.Create(ca, DateTimeOffset.UtcNow.AddMinutes(-2), DateTimeOffset.UtcNow.AddYears(1), RandomNumberGenerator.GetBytes(16)); using var withKey = leaf.CopyWithPrivateKey(key); pfx = withKey.Export(X509ContentType.Pfx, service.CertificatePassword); } File.WriteAllBytes(Path.Combine(directory, "service.pfx"), pfx); } File.WriteAllText(Path.Combine(output, "deployment.json"), JsonSerializer.Serialize(deployment, Json)); File.WriteAllText(Path.Combine(output, "accounts.json"), JsonSerializer.Serialize(accounts, Json)); if ((OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())) foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories)) File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite); } public static string ConnectionString(DatabaseSettings db) => new NpgsqlConnectionStringBuilder { Host = db.Host, Port = db.Port, Database = db.Name, Username = db.User, Password = db.Password, SslMode = SslMode.Prefer, Timeout = 10, Pooling = false }.ConnectionString; private static string Quote(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; public static ServiceSettings ReadService(string directory) => JsonSerializer.Deserialize( File.ReadAllText(Path.Combine(directory, "service.json")), Json) ?? throw new InvalidOperationException("Service configuration is invalid."); }