Record Architecture B approval and verified pinned baseline

This commit is contained in:
Steffen committed 2026-10-14 10:58:43 +02:00
1 parent 20ab461c01
commit cee98e7035
158 files changed
+33575

No files matched your search

@@ -0,0 +1,41 @@
using System.Text.Json;
namespace HealthApp.Provisioning;
public static class ConfigurationWriter
{
public static void Configure(string serviceDirectory, string root, string platform)
{
if (platform is not ("linux" or "windows" or "macos")) throw new InvalidOperationException("Unknown configuration platform.");
var service = Deployment.ReadService(serviceDirectory);
var directory = platform == "linux" ? Path.Combine(root, "etc", "healthapp", service.Name) : Path.Combine(root, "config", service.Name);
Directory.CreateDirectory(directory);
var destination = Path.Combine(directory, platform == "windows" ? "appsettings.Production.json" : "service.env");
if (File.Exists(destination)) throw new InvalidOperationException("Service configuration already exists; it was not overwritten.");
var env = new Dictionary<string, string>(service.Environment);
env["Kestrel__Certificates__Default__Path"] = Path.Combine(directory, "service.pfx");
if (service.Name == "api-gateway") env["Authentication__KeyDirectory"] = platform == "linux" ?
Path.Combine(root, "var", "lib", "healthapp-api-gateway", "keys") : Path.Combine(root, "state", "api-gateway", "keys");
File.Copy(Path.Combine(serviceDirectory, "service.pfx"), Path.Combine(directory, "service.pfx"));
if (platform == "windows")
{
var json = new Dictionary<string, object>();
foreach (var (key, value) in env)
{
if (key == "ASPNETCORE_ENVIRONMENT") continue; // Native service command line explicitly selects Production.
var parts = (key == "ASPNETCORE_URLS" ? "urls" : key).Split("__");
var current = json;
foreach (var part in parts[..^1])
{
if (!current.TryGetValue(part, out var child)) current[part] = child = new Dictionary<string, object>();
current = (Dictionary<string, object>)child;
}
current[parts[^1]] = value;
}
File.WriteAllText(destination, JsonSerializer.Serialize(json, Deployment.Json));
}
else File.WriteAllLines(destination, env.Select(p => p.Key + "=\"" + p.Value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""));
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
foreach (var file in Directory.GetFiles(directory)) File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
}
@@ -0,0 +1,72 @@
using System.Diagnostics;
using System.Text.RegularExpressions;
using Npgsql;
namespace HealthApp.Provisioning;
public static class DatabaseProvisioning
{
public static async Task Create(string serviceDirectory, string? adminFile)
{
var service = Deployment.ReadService(serviceDirectory);
var database = service.Database ?? throw new InvalidOperationException("This service owns no database.");
if (!Regex.IsMatch(database.Name, "^[a-z][a-z0-9_]{1,62}$") || !Regex.IsMatch(database.User, "^[a-z][a-z0-9_]{1,62}$") ||
!Regex.IsMatch(database.Password, "^[A-F0-9]{64}$")) throw new InvalidOperationException("Generated database settings are invalid.");
var adminConnection = adminFile is null ? null : File.ReadAllText(adminFile).Trim();
async Task<string> Sql(string sql, string target = "postgres")
{
if (adminConnection is not null)
{
var settings = new NpgsqlConnectionStringBuilder(adminConnection) { Database = target, Pooling = false };
await using var connection = new NpgsqlConnection(settings.ConnectionString);
await connection.OpenAsync();
await using var command = new NpgsqlCommand(sql, connection);
var result = await command.ExecuteScalarAsync();
return result?.ToString() ?? "";
}
var start = new ProcessStartInfo("runuser") { RedirectStandardInput = true, RedirectStandardOutput = true,
RedirectStandardError = true, UseShellExecute = false };
foreach (var argument in new[] { "-u", "postgres", "--", "psql", "--no-psqlrc", "--set=ON_ERROR_STOP=1", "--tuples-only", "--no-align", "--dbname", target })
start.ArgumentList.Add(argument);
using var process = Process.Start(start) ?? throw new InvalidOperationException("Could not run PostgreSQL administration.");
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
await process.StandardInput.WriteAsync(sql);
process.StandardInput.Close();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try { await process.WaitForExitAsync(timeout.Token); }
catch (OperationCanceledException) { process.Kill(true); throw; }
await stderr; // Never print SQL or passwords, including PostgreSQL error echoes.
if (process.ExitCode != 0) throw new InvalidOperationException("PostgreSQL administration failed; existing data was retained.");
return (await stdout).Trim();
}
static bool True(string value) => value is "t" or "True";
var userExists = True(await Sql($"SELECT EXISTS(SELECT FROM pg_roles WHERE rolname='{database.User}');"));
if (!userExists)
await Sql($"CREATE ROLE {database.User} LOGIN PASSWORD '{database.Password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;");
var exists = True(await Sql($"SELECT EXISTS(SELECT FROM pg_database WHERE datname='{database.Name}');"));
if (exists && !True(await Sql($"SELECT pg_get_userbyid(datdba)='{database.User}' FROM pg_database WHERE datname='{database.Name}';")))
throw new InvalidOperationException("Existing database has another owner; it was not changed.");
if (!exists) await Sql($"CREATE DATABASE {database.Name} OWNER {database.User};");
await Sql($"REVOKE ALL ON DATABASE {database.Name} FROM PUBLIC;");
await Sql($"REVOKE ALL ON SCHEMA public FROM PUBLIC; ALTER SCHEMA public OWNER TO {database.User}; GRANT USAGE, CREATE ON SCHEMA public TO {database.User};", database.Name);
// With an external PostgreSQL admin connection, preserve that endpoint in generated application config.
if (adminConnection is not null)
{
var admin = new NpgsqlConnectionStringBuilder(adminConnection);
database = database with { Host = admin.Host!, Port = admin.Port };
service = service with { Database = database };
var key = service.Name == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase";
service.Environment[key] = Deployment.ConnectionString(database);
File.WriteAllText(Path.Combine(serviceDirectory, "service.json"), System.Text.Json.JsonSerializer.Serialize(service, Deployment.Json));
}
await Check(database);
}
public static async Task Check(DatabaseSettings database)
{
await using var connection = new NpgsqlConnection(Deployment.ConnectionString(database));
await connection.OpenAsync();
await using var command = new NpgsqlCommand("SELECT current_user", connection);
if ((string?)await command.ExecuteScalarAsync() != database.User) throw new InvalidOperationException("Database service identity does not match.");
}
}
@@ -0,0 +1,157 @@
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<string, string> Hosts { get; set; } = new();
public Dictionary<string, int> Ports { get; set; } = new();
public Dictionary<string, string> 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<string, string> Environment, string Platform = "linux");
public sealed record Deployment(string Id, Dictionary<string, ServiceSettings> Services, List<Account> Accounts)
{
public static readonly string[] Names = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"];
public static readonly Dictionary<string, string> 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<Deployment>(
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<Topology>(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<string, ServiceSettings>();
var defaults = new Dictionary<string, int> { ["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<Account> { 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<Account>().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<X509Certificate2>().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<ServiceSettings>(
File.ReadAllText(Path.Combine(directory, "service.json")), Json) ?? throw new InvalidOperationException("Service configuration is invalid.");
}
@@ -0,0 +1,93 @@
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace HealthApp.Provisioning;
public static class Distribution
{
public static async Task Deploy(string bundle, string directory, string user, string[] selected)
{
if (!Regex.IsMatch(user, "^[a-zA-Z_][a-zA-Z0-9_-]*$")) throw new InvalidOperationException("SSH user is invalid.");
var deployment = Deployment.Load(directory);
async Task Run(string command, params string[] args)
{
var start = new ProcessStartInfo(command) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in args) start.ArgumentList.Add(argument);
using var process = Process.Start(start) ?? throw new InvalidOperationException("Could not run deployment transport.");
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(20));
try { await process.WaitForExitAsync(timeout.Token); }
catch (OperationCanceledException) { process.Kill(true); throw; }
await stdout;
var errors = await stderr;
if (process.ExitCode != 0)
{
var reportedStep = errors.Split('\n').LastOrDefault(line => line.StartsWith("Installation failed at ", StringComparison.Ordinal));
throw new InvalidOperationException(reportedStep ?? "SSH deployment transport failed; check administrative SSH access and node installation logs.");
}
}
var temporary = Path.Combine(Path.GetTempPath(), "healthapp-distribution-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(temporary);
if (OperatingSystem.IsLinux()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
try
{
foreach (var group in selected.GroupBy(n => deployment.Services[n].Host, StringComparer.OrdinalIgnoreCase))
{
var names = group.ToArray();
var node = Path.Combine(temporary, "node-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(node);
var material = Path.Combine(node, "deployment");
Directory.CreateDirectory(material);
foreach (var script in Directory.GetFiles(bundle).Where(p => p.EndsWith(".sh") || p.EndsWith(".ps1"))) File.Copy(script, Path.Combine(node, Path.GetFileName(script)));
CopyDirectory(Path.Combine(bundle, "provisioner"), Path.Combine(node, "provisioner"));
Directory.CreateDirectory(Path.Combine(node, "services"));
Directory.CreateDirectory(Path.Combine(node, "systemd"));
foreach (var name in names)
{
CopyDirectory(Path.Combine(bundle, "services", name), Path.Combine(node, "services", name));
CopyDirectory(Path.Combine(directory, name), Path.Combine(material, name));
File.Copy(Path.Combine(bundle, "systemd", "healthapp-" + name + ".service"), Path.Combine(node, "systemd", "healthapp-" + name + ".service"));
}
// Retain remote origins, but do not give a node unrelated service/database/private-key credentials.
var scoped = deployment with
{
Services = deployment.Services.ToDictionary(p => p.Key, p => names.Contains(p.Key) ? p.Value :
p.Value with { IncomingKey = "", OutgoingKey = null, CertificatePassword = "", Database = null, Environment = new() }),
Accounts = names.Contains("api-gateway") ? deployment.Accounts : []
};
File.WriteAllText(Path.Combine(material, "deployment.json"), JsonSerializer.Serialize(scoped, Deployment.Json));
if (names.Contains("api-gateway")) File.Copy(Path.Combine(directory, "accounts.json"), Path.Combine(material, "accounts.json"));
File.Copy(Path.Combine(directory, "healthapp-ca.crt"), Path.Combine(material, "healthapp-ca.crt"));
var target = user + "@" + group.Key;
var windows = names.All(n => deployment.Services[n].Platform == "windows");
if (names.Any(n => deployment.Services[n].Platform == "windows") && !windows)
throw new InvalidOperationException("One host cannot use two native service managers.");
var remote = windows ? "C:/ProgramData/healthapp-install-" + deployment.Id : "/var/tmp/healthapp-install-" + deployment.Id;
Console.WriteLine("Install selected node: " + group.Key);
if (windows)
await Run("ssh", target, "powershell", "-NoProfile", "-NonInteractive", "-Command",
"New-Item -ItemType Directory -Path '" + remote + "' | Out-Null");
else await Run("ssh", target, "mkdir", "-m", "0700", remote);
var scpHost = group.Key.Contains(':') ? user + "@[" + group.Key + "]" : target;
await Run("scp", "-r", node + "/.", scpHost + ":" + remote + "/");
if (windows)
await Run("ssh", target, "powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", remote + "/install.ps1", "-Services", string.Join(',', names),
"-Deployment", remote + "/deployment", "-DeferTopologyCheck");
else await Run("ssh", target, "sudo", "-n", "bash", remote + "/install.sh", "--services", string.Join(',', names),
"--deployment", remote + "/deployment", "--defer-topology-check");
}
// Services communicate through the actual HTTPS origins on their installed hosts.
await InstallationVerification.Verify(directory, selected, selected.Length == Deployment.Names.Length);
Console.WriteLine("Distributed topology verification passed.");
}
finally { Directory.Delete(temporary, true); }
}
private static void CopyDirectory(string source, string destination)
{
Directory.CreateDirectory(destination);
foreach (var file in Directory.GetFiles(source)) File.Copy(file, Path.Combine(destination, Path.GetFileName(file)));
foreach (var child in Directory.GetDirectories(source)) CopyDirectory(child, Path.Combine(destination, Path.GetFileName(child)));
}
}
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Npgsql" Version="10.0.3" />
</ItemGroup>
</Project>
@@ -0,0 +1,126 @@
using System.Net;
using System.Security.Cryptography;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
namespace HealthApp.Provisioning;
public static class InstallationVerification
{
public static async Task Verify(string deploymentDirectory, string[] selected, bool complete, bool startupOnly = false)
{
var deployment = Deployment.Load(deploymentDirectory);
using var root = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(deploymentDirectory, "healthapp-ca.crt"));
using var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, certificate, _, errors) =>
{
if (certificate 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;
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1"));
return chain.Build(certificate);
}
};
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15), BaseAddress = new Uri(Deployment.Url(deployment.Services["api-gateway"])) };
async Task<HttpResponseMessage> Probe(Func<HttpRequestMessage> create, string name)
{
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(30));
while (true)
{
try
{
using var request = create();
var response = await client.SendAsync(request, deadline.Token);
if (response.StatusCode is not (HttpStatusCode.BadGateway or HttpStatusCode.ServiceUnavailable or HttpStatusCode.GatewayTimeout)) return response;
response.Dispose();
}
catch (HttpRequestException) { }
catch (OperationCanceledException) when (!deadline.IsCancellationRequested) { }
try { await Task.Delay(500, deadline.Token); }
catch (OperationCanceledException) { throw new InvalidOperationException("HTTPS startup/dependency probe timed out for " + name + "."); }
}
}
foreach (var name in selected)
{
var service = deployment.Services[name];
if (Deployment.ReadService(Path.Combine(deploymentDirectory, name)).Database is { } database)
{
try { await DatabaseProvisioning.Check(database); }
catch { throw new InvalidOperationException("Dedicated database reachability verification failed for " + name + "."); }
}
// Correct incoming credentials prove network/TLS and the configured service trust boundary.
var path = Deployment.Url(service) +
(name == "api-gateway" ? "api/measurement-guidance" : startupOnly ? "" : "api/patients/00000000-0000-0000-0000-000000000001" +
(name == "insights" ? "/insights?from=2026-01-01&to=2026-01-02" :
name == "health-overview" ? "/overview?from=2026-01-01&to=2026-01-02" :
name == "observation" ? "/observations?from=2026-01-01&to=2026-01-02" : ""));
using var response = await Probe(() =>
{
var request = new HttpRequestMessage(HttpMethod.Get, path);
if (name != "api-gateway") request.Headers.Add("X-Gateway-Key", service.IncomingKey);
return request;
}, name);
if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.NotFound))
throw new InvalidOperationException("HTTPS/dependency verification failed for " + name + " (HTTP " + (int)response.StatusCode + ").");
}
if (startupOnly) return;
// Exercise each installed service's configured outgoing gateway credentials using its actual network API.
foreach (var name in selected.Where(n => n is "observation" or "insights" or "health-overview"))
{
var service = deployment.Services[name];
using var request = new HttpRequestMessage(HttpMethod.Get, Deployment.Url(deployment.Services["api-gateway"]) +
"api/patients/00000000-0000-0000-0000-000000000001" + (name == "insights" ? "/observations?from=2026-01-01&to=2026-01-02" : ""));
request.Headers.Add("X-Service-Key", service.OutgoingKey);
using var response = await client.SendAsync(request);
if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.NotFound))
throw new InvalidOperationException("Gateway service-credential verification failed for " + name + ".");
}
if (!complete) return;
var account = deployment.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 token = JsonDocument.Parse(await login.Content.ReadAsStringAsync());
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.RootElement.GetProperty("accessToken").GetString());
using var current = await client.GetAsync("api/patients/me");
Guid patient;
if (current.StatusCode == HttpStatusCode.NotFound)
{
using var created = await client.PostAsJsonAsync("api/patients", new { name = "Installer verification (synthetic)", dateOfBirth = "1980-01-01" });
created.EnsureSuccessStatusCode();
using var profile = JsonDocument.Parse(await created.Content.ReadAsStringAsync());
patient = profile.RootElement.GetProperty("patientId").GetGuid();
}
else
{
current.EnsureSuccessStatusCode();
using var profile = JsonDocument.Parse(await current.Content.ReadAsStringAsync());
patient = profile.RootElement.GetProperty("patientId").GetGuid();
}
using var latest = await client.GetAsync($"api/patients/{patient}/observations/latest");
if (latest.StatusCode == HttpStatusCode.NotFound)
{
using var record = await client.PostAsJsonAsync($"api/patients/{patient}/observations", new
{
measuredAt = DateTime.UtcNow, systolic = 120, diastolic = 80, pulse = 60,
note = "Installer verification; synthetic data", measurementContext = new { setting = "Home", activityCondition = "AtRest" }
});
record.EnsureSuccessStatusCode();
}
else latest.EnsureSuccessStatusCode();
var bounds = $"from=2000-01-01&to={Uri.EscapeDataString(DateTime.UtcNow.AddDays(1).ToString("O"))}&setting=Home&activityCondition=AtRest";
using var overview = await client.GetAsync($"api/patients/{patient}/overview?{bounds}");
overview.EnsureSuccessStatusCode();
using var result = JsonDocument.Parse(await overview.Content.ReadAsStringAsync());
if (result.RootElement.GetProperty("patient").GetProperty("patientId").GetGuid() != patient ||
result.RootElement.GetProperty("latestObservation").ValueKind != JsonValueKind.Object ||
result.RootElement.GetProperty("insight").ValueKind != JsonValueKind.Object ||
result.RootElement.GetProperty("insightContributingCount").GetInt32() < 1)
throw new InvalidOperationException("Representative complete-system workflow did not return profile, latest observation and insight.");
}
}
@@ -0,0 +1,32 @@
using System.Text.Json;
using System.Xml.Linq;
namespace HealthApp.Provisioning;
public static class LaunchdWriter
{
public static void Write(string service, string root, string dotnet, string output)
{
if (!Deployment.Names.Contains(service)) throw new InvalidOperationException("Unknown service.");
var directory = Path.Combine(root, "services", service);
var assembly = service switch { "api-gateway" => "ApiGateway", "patient-profile" => "PatientProfileService",
"observation" => "ObservationService", "insights" => "InsightsService", _ => "HealthOverviewService" };
var environment = new XElement("dict");
foreach (var line in File.ReadAllLines(Path.Combine(root, "config", service, "service.env")))
{
var position = line.IndexOf('=');
environment.Add(new XElement("key", line[..position]), new XElement("string", JsonSerializer.Deserialize<string>(line[(position + 1)..])));
}
var document = new XDocument(new XDeclaration("1.0", "utf-8", null),
new XDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null),
new XElement("plist", new XAttribute("version", "1.0"), new XElement("dict",
new XElement("key", "Label"), new XElement("string", "healthapp-" + service),
new XElement("key", "ProgramArguments"), new XElement("array", new XElement("string", dotnet), new XElement("string", Path.Combine(directory, assembly + ".dll"))),
new XElement("key", "WorkingDirectory"), new XElement("string", directory),
new XElement("key", "UserName"), new XElement("string", "_healthapp_" + service.Replace('-', '_')),
new XElement("key", "EnvironmentVariables"), environment,
new XElement("key", "RunAtLoad"), new XElement("true"), new XElement("key", "KeepAlive"), new XElement("true"))));
document.Save(output);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(output, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
}
@@ -0,0 +1,83 @@
using System.Text.Json;
namespace HealthApp.Provisioning;
public static class Program
{
public static async Task<int> Main(string[] args)
{
var command = args.FirstOrDefault() ?? "";
try
{
var options = new Dictionary<string, string>();
for (var index = 1; index < args.Length; index += 2)
{
if (index + 1 >= args.Length || !args[index].StartsWith("--") || !options.TryAdd(args[index][2..], args[index + 1]))
throw new InvalidOperationException("Invalid provisioning arguments.");
}
string Required(string key) => options.GetValueOrDefault(key) ?? throw new InvalidOperationException("Missing argument: " + key);
switch (command)
{
case "launchd":
LaunchdWriter.Write(Required("service"), Required("root"), Required("dotnet"), Required("output"));
break;
case "secret":
File.WriteAllText(Required("output"), Deployment.Secret());
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(Required("output"), UnixFileMode.UserRead | UnixFileMode.UserWrite);
break;
case "admin-connection":
var admin = new Npgsql.NpgsqlConnectionStringBuilder { Host = "localhost", Port = int.Parse(Required("port")),
Username = "postgres", Database = "postgres", Password = File.ReadAllText(Required("password-file")).Trim(), Pooling = false };
File.WriteAllText(Required("output"), admin.ConnectionString);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(Required("output"), UnixFileMode.UserRead | UnixFileMode.UserWrite);
break;
case "execute":
var native = options.GetValueOrDefault("platform", "macos");
var serviceName = Required("service");
if (!Deployment.Names.Contains(serviceName)) throw new InvalidOperationException("Unknown selected service.");
var rootPath = Required("root");
var config = Path.Combine(rootPath, "config", serviceName, "service.env");
var start = new System.Diagnostics.ProcessStartInfo(Required("dotnet")) { UseShellExecute = false,
WorkingDirectory = Path.Combine(rootPath, "services", serviceName) };
start.ArgumentList.Add(Required("assembly"));
start.ArgumentList.Add("--migrate");
foreach (var line in File.ReadAllLines(config))
start.Environment[line[..line.IndexOf('=')]] = JsonSerializer.Deserialize<string>(line[(line.IndexOf('=') + 1)..])!;
using (var process = System.Diagnostics.Process.Start(start)!)
{
await process.WaitForExitAsync();
if (process.ExitCode != 0) throw new InvalidOperationException("Selected service migration failed.");
}
break;
case "prepare":
Deployment.Prepare(Required("output"), options.GetValueOrDefault("host", "localhost"), options.GetValueOrDefault("topology"), options.GetValueOrDefault("certificates"));
break;
case "database":
await DatabaseProvisioning.Create(Required("service-dir"), options.GetValueOrDefault("admin-file"));
break;
case "configure":
ConfigurationWriter.Configure(Required("service-dir"), Required("root"), options.GetValueOrDefault("platform", "linux"));
break;
case "distribute":
var names = Required("services").Split(',');
if (names.Any(n => !Deployment.Names.Contains(n))) throw new InvalidOperationException("Unknown distribution service.");
await Distribution.Deploy(Required("bundle"), Required("deployment"), Required("ssh-user"), names);
break;
case "verify-startup":
case "verify":
var selected = Required("services").Split(',');
if (selected.Any(n => !Deployment.Names.Contains(n))) throw new InvalidOperationException("Unknown verification service.");
await InstallationVerification.Verify(Required("deployment"), selected, options.GetValueOrDefault("complete") == "true", command == "verify-startup");
break;
default: throw new InvalidOperationException("Unknown provisioning command.");
}
return 0;
}
catch (Exception error)
{
Console.Error.WriteLine($"Provisioning step '{command}' failed: " + (error is InvalidOperationException ? error.Message : error.GetType().Name) +
" No credentials are printed; inspect the relevant service logs.");
return 1;
}
}
}