Deliver portable native Architecture B deployment and final verification
This commit is contained in:
1 parent
f451b55de1
commit
36740d2492
92 files changed
+10939
-926
No files matched your search
@@ -0,0 +1 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net10.0</TargetFramework><OutputType>Exe</OutputType><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,145 @@
|
||||
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<Account> Accounts, Dictionary<string, string> 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<InstallationPlan>(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<Account> { new("prototype-patient", "Patient", Secret()), new("prototype-professional", "HealthcareProfessional", Secret()), new("installation-check", "Patient", Secret()) };
|
||||
var settings = new Dictionary<string, string> { ["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"), ["Resources:MaxPoolSize"] = "32", ["Resources:MaxConcurrentRequests"] = "32", ["Resources:MaxConcurrentAssessments"] = "4", ["Resources:RequestDeadlineSeconds"] = "30" };
|
||||
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<Account>().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<string> 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Text.Json;
|
||||
namespace HealthApp.Provisioning;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static async Task<int> Main(string[] args)
|
||||
{
|
||||
var stage = "arguments";
|
||||
try
|
||||
{
|
||||
if (args.Length == 0) throw new ArgumentException();
|
||||
var options = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
for (var i = 1; i < args.Length; i += 2) { if (i + 1 >= args.Length || !args[i].StartsWith("--") || !options.TryAdd(args[i][2..], args[i + 1])) throw new ArgumentException(); }
|
||||
string Required(string key) => options.GetValueOrDefault(key) ?? throw new ArgumentException();
|
||||
stage = args[0]; var plan = Required("plan");
|
||||
switch (stage)
|
||||
{
|
||||
case "prepare": Installation.Prepare(plan, Required("host"), int.Parse(options.GetValueOrDefault("port", "5443")), Required("root"), options.GetValueOrDefault("certificate"), options.GetValueOrDefault("certificate-password-file"), options.GetValueOrDefault("ca")); break;
|
||||
case "database": await Installation.DatabaseAsync(plan, Required("migrations"), options.GetValueOrDefault("admin-file")); break;
|
||||
case "configure": Installation.Configure(plan, Required("root")); break;
|
||||
case "verify-database": await Installation.VerifyDatabaseAsync(plan); break;
|
||||
case "verify": await Installation.VerifyAsync(plan); break;
|
||||
default: throw new ArgumentException();
|
||||
}
|
||||
Console.WriteLine("Completed " + stage + "."); return 0;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Never print SQL, password/token values, health payloads or exception text.
|
||||
Console.Error.WriteLine("Provisioning failed at " + stage + " (" + e.GetType().Name + "). Existing data and diagnostics retained."); return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# Architecture B native Linux installation
|
||||
|
||||
Build with the .NET 10 SDK: `HEALTHAPP_DOTNET=/path/to/dotnet bash deploy/build-release.sh --output NEW_DIRECTORY`. The bundle is independently deployable: one app, transient provisioner, module-owned migrations, dependency adapters and one systemd unit. No source checkout, container engine or other Health App services are required on the target.
|
||||
|
||||
Normal local installation, from the bundle: `sudo bash install.sh --host DNS_OR_IP`. It supplies missing dependencies, a fresh database, separate NOLOGIN schema owners and a restricted DML login role, generated account/database secrets, HTTPS certificate, protected configuration/key ring, migrations and a native application service. No manual database, password or certificate creation is required. Synthetic installer checks remain as clearly named prototype records; generated professional has no assignments. Assigned reads require predefined configuration, not an assignment-management API.
|
||||
|
||||
Existing `/opt/healthapp-b`, `/etc/healthapp-b`, `/var/lib/healthapp-b`, installation state or unit prevents installation before overwriting anything. Partial failures retain protected material and report the stage; there is no transactional installer rollback or automatic resume. Architecture A paths/databases are not modified. No production-data import is included.
|
||||
|
||||
## Distribution support
|
||||
|
||||
The installer is distribution-aware, not Ubuntu-only. Intended systemd x86_64 targets: Debian 12/13, Ubuntu 24.04, Fedora 43/44, RHEL-family systems with compatible native feeds, and current Arch/Manjaro. Actual package/runtime availability and systemd must pass preflight. Rolling-distribution dependency installation performs a full package update to avoid partial upgrades. Derivative version numbers are not silently substituted into unrelated upstream feeds. No universal Linux support is claimed.
|
||||
|
||||
APT uses native feeds, with identified Microsoft Debian or official Ubuntu .NET backports where necessary; DNF uses configured distribution feeds; pacman uses native repositories. PostgreSQL initialization/startup follows each family. In remote mode none of these adapters installs or starts local PostgreSQL.
|
||||
|
||||
Package choices follow [Microsoft Debian](https://learn.microsoft.com/en-us/dotnet/core/install/linux-debian), [Ubuntu](https://learn.microsoft.com/en-us/dotnet/core/install/linux-ubuntu-install), [Fedora](https://learn.microsoft.com/en-us/dotnet/core/install/linux-fedora), and [Arch ASP.NET package](https://archlinux.org/packages/extra/x86_64/aspnet-runtime/) documentation. Supported in design does not mean installation has been executed on every family. Verified: Debian 12 bookworm systemd local installation (PostgreSQL 15.19) and remote installation (PostgreSQL 18.6 with VerifyFull), .NET/ASP.NET 10.0.13. These are actual native services inside isolated Linux test environments sharing the Manjaro kernel; bare-metal/VM and other distributions are not independently verified. The implementation evidence register records this boundary.
|
||||
|
||||
## Remote PostgreSQL
|
||||
|
||||
Provide administrator-controlled reachable PostgreSQL, certificate/CA trust and restrictive network access. Put its administrative connection in an owner-only file (mode 600/400), including `SslMode=VerifyFull` and `RootCertificate=/path/to/trusted-db-ca.crt` when a private CA is used. Use a DNS name matching the DB certificate (or matching IP SAN), not an unverified alias. Credentials never go on a command line.
|
||||
|
||||
Run `sudo bash install.sh --mode remote --host APP_DNS --postgres-admin-file /secure/admin.connection`. The tool creates a new B database/roles/schemas remotely. Runtime config inherits verified encryption/hostname checks, replaces administrative identity with the generated restricted role, and copies an explicit DB CA into installed protected configuration. No local PostgreSQL dependency is installed. The database administrator supplies the existing remote host/administrative access; application database/user/secret setup is automated.
|
||||
|
||||
## Native runtime and trust
|
||||
|
||||
`healthapp-b.service` runs as `healthapp-b`, listens on one HTTPS endpoint (default 5443), and loads `/etc/healthapp-b/appsettings.json`. Its private key/config are root-owned and readable only by the service group. Token keys persist under `/var/lib/healthapp-b/keys` (service-owned mode 700). Migration identities are not runtime credentials. The runtime cannot create/drop schemas/tables or administer PostgreSQL. Local provisioning generates SCRAM credentials and adds a loopback authentication rule scoped only to the new B database/role, retaining existing rules and a protected backup. This handles distributions whose PostgreSQL defaults use ident authentication without weakening host-wide access.
|
||||
|
||||
The verifier validates certificate chain and hostname using the generated/supplied trust root. Export `/etc/healthapp-b/healthapp-ca.crt` to establish client trust separately; never disable certificate validation. Supplied certificate options: `--certificate PFX --certificate-password-file OWNER_ONLY_FILE --ca ROOT_CA_PEM`. Certificate replacement is an administrative operation: preserve backups, change PFX/password configuration with restrictive permissions, restart and verify trusted HTTPS. Prototype leaf validity is one year; CA two years; automatic renewal is outside scope.
|
||||
|
||||
The installer checks PID/HTTPS/configured DB/representative login/profile/observation/history/insight/overview, stops the app while PostgreSQL stays ready, restarts with a new PID and repeats verification. Liveness and readiness require a valid bearer ticket and disclose no patient information. Readiness checks keys, reference content and both migration versions; guidance/login can operate during DB-only outages.
|
||||
|
||||
`--dotnet /absolute/runtime/path` may reuse an existing .NET 10 ASP.NET runtime. Use a system-readable path outside `/tmp` and protected home directories because the service uses PrivateTmp and ProtectHome. Logs omit credentials/tokens/health payloads and identifying route values. Configuration controls pool size, request/assessment concurrency, deadline, accounts, assignments and token lifetime. Defaults are deployment starting values, not measured capacity or energy claims.
|
||||
|
||||
Before future upgrades: back up the B database, protected configuration and token keys; retain source/target revisions; stop or explicitly coordinate app access while privileged module migrations run; verify integrity and HTTPS/workflows before switching. No backup SLA, HA, live A import, automatic rollback or production/clinical certification is promised. Measurement host/data/workload equivalence must be controlled separately from installation evidence.
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"ConnectionStrings": {"HealthDatabase": "Host=127.0.0.1;Database=YOUR_FRESH_B_DB;Username=YOUR_RUNTIME_ROLE;Password=LOAD_EXTERNALLY"},
|
||||
"Authentication": {"KeyDirectory": "/var/lib/healthapp-b/keys", "TokenLifetimeMinutes": 30, "Accounts": []},
|
||||
"Access": {"ProfessionalAssignments": {}},
|
||||
"Resources": {"MaxPoolSize": 32, "MaxConcurrentRequests": 32, "MaxConcurrentAssessments": 4, "RequestDeadlineSeconds": 30},
|
||||
"Database": {"Remote": false}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
output=''
|
||||
while (($#)); do case "$1" in --output) output=$2; shift 2;; *) echo 'Usage: build-release.sh --output NEW_DIRECTORY' >&2; exit 2;; esac; done
|
||||
[[ -n "$output" && ! -e "$output" ]] || { echo 'A new output directory is required.' >&2; exit 2; }
|
||||
repository=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
runtime=${HEALTHAPP_DOTNET:-dotnet}
|
||||
output=$(realpath -m "$output")
|
||||
mkdir -p "$output/app" "$output/provisioner" "$output/migrations"
|
||||
"$runtime" publish "$repository/src/HealthApp/HealthApp.csproj" -c Release -o "$output/app" --nologo
|
||||
"$runtime" publish "$repository/deploy/HealthApp.Provisioning/HealthApp.Provisioning.csproj" -c Release -o "$output/provisioner" --nologo
|
||||
for module in Profile Observations; do mkdir -p "$output/migrations/$module"; cp "$repository/src/Modules/$module/Migrations/"*.sql "$output/migrations/$module/"; done
|
||||
cp "$repository/deploy/installer/"*.sh "$output/"
|
||||
cp "$repository/deploy/systemd/healthapp-b.service" "$output/"
|
||||
cp "$repository/deploy/INSTALLATION.md" "$output/"
|
||||
echo 'Release bundle prepared; no generated installation secrets included.'
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
# Distribution package adapters; normal installation uses signed native package feeds.
|
||||
has_runtime() { [[ -x "$dotnet" ]] && "$dotnet" --list-runtimes | rg_runtime; }
|
||||
rg_runtime() { grep -q 'Microsoft.AspNetCore.App 10\.'; }
|
||||
ensure_dependencies() {
|
||||
local family=''
|
||||
source "${HEALTHAPP_OS_RELEASE:-/etc/os-release}"
|
||||
case " $ID ${ID_LIKE:-} " in
|
||||
*' debian '*|*' ubuntu '*) family=apt;;
|
||||
*' fedora '*|*' rhel '*) family=dnf;;
|
||||
*' arch '*|*' manjaro '*) family=pacman;;
|
||||
*) fail 'No supported dependency adapter for this systemd distribution.';;
|
||||
esac
|
||||
stage='distribution dependencies'
|
||||
case "$family" in
|
||||
apt)
|
||||
apt-get update
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates curl
|
||||
if ! has_runtime; then
|
||||
if ! apt-cache policy aspnetcore-runtime-10.0 | grep -Eq 'Candidate: [0-9]'; then
|
||||
if [[ "$ID" == debian && "$VERSION_ID" =~ ^(12|13)$ ]]; then
|
||||
local feed; feed=$(mktemp -d)
|
||||
curl --fail --silent --show-error --location "https://packages.microsoft.com/config/debian/$VERSION_ID/packages-microsoft-prod.deb" -o "$feed/feed.deb"
|
||||
dpkg -i "$feed/feed.deb"; apt-get update
|
||||
elif [[ "$ID" == ubuntu && "$VERSION_ID" == 24.04 ]]; then
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y software-properties-common
|
||||
add-apt-repository -y ppa:dotnet/backports; apt-get update
|
||||
else fail 'No identified .NET 10 feed; derivative versions are not mapped to an unrelated upstream.'; fi
|
||||
fi
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y aspnetcore-runtime-10.0
|
||||
fi
|
||||
if [[ "$mode" == local ]]; then DEBIAN_FRONTEND=noninteractive apt-get install -y postgresql; systemctl enable --now postgresql; fi
|
||||
;;
|
||||
dnf)
|
||||
dnf install -y ca-certificates curl
|
||||
has_runtime || dnf install -y aspnetcore-runtime-10.0
|
||||
if [[ "$mode" == local ]]; then
|
||||
dnf install -y postgresql-server postgresql
|
||||
[[ -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb
|
||||
systemctl enable --now postgresql
|
||||
fi
|
||||
;;
|
||||
pacman)
|
||||
# Avoid partial rolling-distribution upgrades when installing dependencies.
|
||||
pacman -Syu --noconfirm --needed ca-certificates curl
|
||||
has_runtime || pacman -S --noconfirm --needed aspnet-runtime
|
||||
if [[ "$mode" == local ]]; then
|
||||
pacman -S --noconfirm --needed postgresql
|
||||
if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
|
||||
install -d -o postgres -g postgres -m 700 /var/lib/postgres/data
|
||||
runuser -u postgres -- initdb -D /var/lib/postgres/data --auth-local=peer --auth-host=scram-sha-256
|
||||
fi
|
||||
systemctl enable --now postgresql
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
has_runtime || fail '.NET 10 ASP.NET Core runtime is unavailable after dependency provisioning.'
|
||||
if [[ "$mode" == local ]]; then
|
||||
stage='local PostgreSQL readiness'
|
||||
local ready=false attempt
|
||||
for attempt in {1..30}; do if pg_isready -q -h 127.0.0.1 -p 5432; then ready=true; break; fi; sleep 1; done
|
||||
[[ "$ready" == true ]] || fail 'Local PostgreSQL is not ready on port 5432.'
|
||||
fi
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
stage=preflight
|
||||
fail() { echo "Installation failed at $stage: $1 Existing installation material retained." >&2; exit 1; }
|
||||
trap 'fail "Command failed; consult protected stage diagnostics."' ERR
|
||||
bundle=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||
mode=local host=localhost port=5443 admin_file='' certificate='' certificate_password_file='' ca=''
|
||||
dotnet=${HEALTHAPP_DOTNET:-/usr/bin/dotnet}
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--mode) mode=$2; shift 2;; --host) host=$2; shift 2;; --port) port=$2; shift 2;;
|
||||
--postgres-admin-file) admin_file=$2; shift 2;; --dotnet) dotnet=$2; shift 2;;
|
||||
--certificate) certificate=$2; shift 2;; --certificate-password-file) certificate_password_file=$2; shift 2;; --ca) ca=$2; shift 2;;
|
||||
*) fail 'Unknown installation option.';;
|
||||
esac
|
||||
done
|
||||
[[ $EUID -eq 0 ]] || fail 'Administrative/root access is required.'
|
||||
[[ "$mode" == local || "$mode" == remote ]] || fail 'Select local or remote database mode.'
|
||||
[[ -d /run/systemd/system ]] || fail 'A running systemd host is required.'
|
||||
[[ -f "$bundle/app/HealthApp.dll" && -f "$bundle/provisioner/HealthApp.Provisioning.dll" ]] || fail 'Release payload missing.'
|
||||
for path in /opt/healthapp-b /etc/healthapp-b /var/lib/healthapp-b /var/lib/healthapp-b-installation /etc/systemd/system/healthapp-b.service; do [[ ! -e "$path" ]] || fail 'Existing target path would be overwritten.'; done
|
||||
if [[ "$mode" == remote ]]; then [[ -n "$admin_file" && -f "$admin_file" ]] || fail 'Remote mode needs a protected administrative connection file with VerifyFull and trusted CA.'; fi
|
||||
if [[ -n "$admin_file" ]]; then [[ $(stat -c '%a' "$admin_file") == 600 || $(stat -c '%a' "$admin_file") == 400 ]] || fail 'Administrative connection file must be owner-only.'; fi
|
||||
install -d -m 700 /var/lib/healthapp-b-installation
|
||||
exec > >(tee -a /var/lib/healthapp-b-installation/install.log) 2>&1
|
||||
source "$bundle/bootstrap.sh"
|
||||
ensure_dependencies
|
||||
stage='protected preparation'
|
||||
install -d -m 700 /var/lib/healthapp-b-installation
|
||||
plan=/var/lib/healthapp-b-installation/deployment
|
||||
prepare=(prepare --plan "$plan" --host "$host" --port "$port" --root /)
|
||||
if [[ -n "$certificate" ]]; then prepare+=(--certificate "$certificate" --certificate-password-file "$certificate_password_file" --ca "$ca"); fi
|
||||
"$dotnet" "$bundle/provisioner/HealthApp.Provisioning.dll" "${prepare[@]}"
|
||||
stage='database roles schemas and migration'
|
||||
database=(database --plan "$plan" --migrations "$bundle/migrations")
|
||||
if [[ "$mode" == remote ]]; then database+=(--admin-file "$admin_file"); fi
|
||||
"$dotnet" "$bundle/provisioner/HealthApp.Provisioning.dll" "${database[@]}"
|
||||
stage='application configuration and identity'
|
||||
id -u healthapp-b >/dev/null 2>&1 || useradd --system --user-group --home-dir /var/lib/healthapp-b --shell /usr/sbin/nologin healthapp-b
|
||||
install -d -m 755 /opt/healthapp-b
|
||||
cp -a "$bundle/app/." /opt/healthapp-b/
|
||||
"$dotnet" "$bundle/provisioner/HealthApp.Provisioning.dll" configure --plan "$plan" --root /
|
||||
chown -R root:healthapp-b /etc/healthapp-b
|
||||
chmod 750 /etc/healthapp-b
|
||||
chmod 640 /etc/healthapp-b/appsettings.json /etc/healthapp-b/application.pfx
|
||||
chmod 644 /etc/healthapp-b/*.crt
|
||||
chown -R healthapp-b:healthapp-b /var/lib/healthapp-b
|
||||
chmod 700 /var/lib/healthapp-b /var/lib/healthapp-b/keys
|
||||
stage='native systemd registration'
|
||||
[[ "$dotnet" =~ ^/[a-zA-Z0-9_./-]+$ ]] || fail 'The runtime must have a safe absolute executable path.'
|
||||
sed "s|@DOTNET@|$dotnet|g" "$bundle/healthapp-b.service" > /etc/systemd/system/healthapp-b.service
|
||||
chmod 644 /etc/systemd/system/healthapp-b.service
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now healthapp-b.service
|
||||
stage='HTTPS database and representative workflow verification'
|
||||
ready=false
|
||||
for attempt in {1..30}; do if "$dotnet" "$bundle/provisioner/HealthApp.Provisioning.dll" verify --plan "$plan"; then ready=true; break; fi; sleep 1; done
|
||||
[[ "$ready" == true ]] || fail 'Representative verification did not complete.'
|
||||
stage='independent stop restart verification'
|
||||
before_pid=$(systemctl show healthapp-b.service --property MainPID --value)
|
||||
[[ "$before_pid" =~ ^[1-9][0-9]*$ ]] || fail 'Application PID is missing.'
|
||||
if [[ "$mode" == local ]]; then pg_isready -q -h 127.0.0.1 -p 5432 || fail 'Database was unavailable before application stop.'; fi
|
||||
systemctl stop healthapp-b.service
|
||||
"$dotnet" "$bundle/provisioner/HealthApp.Provisioning.dll" verify-database --plan "$plan"
|
||||
if [[ "$mode" == local ]]; then pg_isready -q -h 127.0.0.1 -p 5432 || fail 'Application stop affected PostgreSQL.'; fi
|
||||
systemctl start healthapp-b.service
|
||||
ready=false
|
||||
for attempt in {1..30}; do if "$dotnet" "$bundle/provisioner/HealthApp.Provisioning.dll" verify --plan "$plan"; then ready=true; break; fi; sleep 1; done
|
||||
[[ "$ready" == true ]] || fail 'Workflow did not recover after restart.'
|
||||
after_pid=$(systemctl show healthapp-b.service --property MainPID --value)
|
||||
[[ "$after_pid" =~ ^[1-9][0-9]*$ && "$after_pid" != "$before_pid" ]] || fail 'Restarted application PID not verified.'
|
||||
stage=complete
|
||||
printf 'Architecture B installed and verified: one HTTPS application, independent PostgreSQL lifecycle.\n'
|
||||
printf 'Protected generated account material: /var/lib/healthapp-b-installation/deployment/accounts.json\n'
|
||||
printf 'Export /etc/healthapp-b/healthapp-ca.crt to establish client trust.\n'
|
||||
@@ -0,0 +1,28 @@
|
||||
[Unit]
|
||||
Description=Health App Architecture B
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=healthapp-b
|
||||
Group=healthapp-b
|
||||
WorkingDirectory=/opt/healthapp-b
|
||||
Environment=ASPNETCORE_ENVIRONMENT=Production
|
||||
Environment=HEALTHAPP_CONFIGURATION_FILE=/etc/healthapp-b/appsettings.json
|
||||
ExecStart=@DOTNET@ /opt/healthapp-b/HealthApp.dll
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
KillSignal=SIGINT
|
||||
TimeoutStopSec=30
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/var/lib/healthapp-b
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Reference in new issue
Block a user