Provision US-16 dependencies credentials HTTPS and native service configurations
This commit is contained in:
1 parent
950f67d8b7
commit
eedf2a941b
34 files changed
+1692
-362
No files matched your search
@@ -0,0 +1,38 @@
|
|||||||
|
name: Prototype native installation
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
jobs:
|
||||||
|
native-install:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: [ubuntu-24.04, windows-latest, macos-14]
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
timeout-minutes: 40
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-dotnet@v4
|
||||||
|
with:
|
||||||
|
dotnet-version: '10.0.x'
|
||||||
|
- name: Build portable release on Unix
|
||||||
|
if: runner.os != 'Windows'
|
||||||
|
shell: bash
|
||||||
|
run: bash deploy/build-release.sh --output "$RUNNER_TEMP/healthapp-release"
|
||||||
|
- name: Build portable release on Windows
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
shell: pwsh
|
||||||
|
run: ./deploy/build-release.ps1 -Output "$env:RUNNER_TEMP/healthapp-release"
|
||||||
|
- name: Provision and verify Ubuntu/systemd
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
shell: bash
|
||||||
|
run: sudo bash "$RUNNER_TEMP/healthapp-release/install.sh" --services all --host localhost --dotnet "$(command -v dotnet)"
|
||||||
|
- name: Provision and verify Windows Services
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
shell: pwsh
|
||||||
|
run: '& "$env:RUNNER_TEMP/healthapp-release/install.ps1" -Services all -HostName localhost'
|
||||||
|
- name: Provision and verify macOS/launchd
|
||||||
|
if: runner.os == 'macOS'
|
||||||
|
shell: bash
|
||||||
|
run: sudo bash "$RUNNER_TEMP/healthapp-release/install.sh" --services all --host localhost
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
<Solution>
|
<Solution>
|
||||||
|
<Folder Name="/deploy/">
|
||||||
|
<Project Path="deploy/HealthApp.Provisioning/HealthApp.Provisioning.csproj" />
|
||||||
|
</Folder>
|
||||||
<Folder Name="/src/">
|
<Folder Name="/src/">
|
||||||
<Project Path="src/HealthOverviewService/HealthOverviewService.csproj" />
|
<Project Path="src/HealthOverviewService/HealthOverviewService.csproj" />
|
||||||
<Project Path="src/InsightsService/InsightsService.csproj" />
|
<Project Path="src/InsightsService/InsightsService.csproj" />
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+217
-163
@@ -1,198 +1,252 @@
|
|||||||
# US-16 — Independent Linux installation
|
# US-16 — Provision and install HealthApp
|
||||||
|
|
||||||
The installer supports one service, a comma-separated subset, or `all`. The same
|
The installer provisions a working prototype topology. A normal installation no longer
|
||||||
published application executables work for colocated and distributed deployments.
|
requires prepared application configuration, database roles/passwords, service keys,
|
||||||
Each service retains its own process, environment file and systemd registration.
|
or HTTPS certificates. Select one service, a comma-separated subset, or `all`.
|
||||||
No additional service, shared persistence, shared application library or communication
|
|
||||||
shortcut is introduced. Application services continue communicating through the API Gateway.
|
|
||||||
|
|
||||||
## Supported host and prerequisites
|
The application DLLs and shared C# provisioning utility are portable. OS adapters
|
||||||
|
perform package installation and native service registration: systemd on supported
|
||||||
|
Linux hosts, Windows Services on Windows, and launchd on macOS. Deployment location
|
||||||
|
and OS do not combine services, introduce shared persistence or change gateway-routed
|
||||||
|
communication. There is no container/orchestration requirement.
|
||||||
|
|
||||||
Use a Linux host with Bash 4 or later, GNU core utilities/grep/sed, a running systemd
|
## Build the release
|
||||||
system manager with systemd-run, and the .NET 10 ASP.NET Core runtime. Live installation
|
|
||||||
requires root and the standard `getent`, `groupadd`, `useradd` and `id` tools. Network
|
|
||||||
verification additionally requires curl. Building a release requires the .NET 10 SDK
|
|
||||||
and the repository's NuGet dependencies; deployment hosts do not need the SDK/source.
|
|
||||||
|
|
||||||
Provision PostgreSQL for Patient/Profile and Observation separately, with independent
|
A build machine needs the .NET 10 SDK and package access. It is distinct from a target
|
||||||
database names/users and credentials matching each service's configuration. The DBs
|
machine, where the installer supplies missing runtime/dependencies.
|
||||||
may be on remote hosts. Insights and Health Overview have no databases. Provision
|
|
||||||
trusted HTTPS certificates and the externally configured accounts/service credentials
|
|
||||||
before starting production services. The installer does not install an identity
|
|
||||||
provider, PostgreSQL, runtime packages or certificates and does not generate accounts.
|
|
||||||
These remain administrator-supplied prerequisites, as in the existing deployment model.
|
|
||||||
|
|
||||||
## Build a release
|
|
||||||
|
|
||||||
From the repository root:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash deploy/build-release.sh --output /tmp/healthapp-release
|
bash deploy/build-release.sh --output /tmp/healthapp-release
|
||||||
# Or publish only the service(s) needed on a particular host:
|
# Optional: build just a selected application's payload plus the provisioning utility.
|
||||||
bash deploy/build-release.sh --output /tmp/healthapp-insights-release --services insights
|
bash deploy/build-release.sh --output /tmp/healthapp-insights --services insights
|
||||||
```
|
```
|
||||||
|
|
||||||
Output must be a new directory. Optionally set `HEALTHAPP_DOTNET` to the SDK executable.
|
On a Windows build machine, use `deploy/build-release.ps1 -Output NEW_DIRECTORY`
|
||||||
The release contains selected payloads under `services/`, their systemd units,
|
from PowerShell with the same optional `-Services` selection.
|
||||||
configuration examples, installation/verification scripts and this guide. Transfer it
|
|
||||||
to the target Linux host using your normal deployment transport. Release contents
|
|
||||||
are trusted executable deployment input; configuration secrets are not part of it.
|
|
||||||
|
|
||||||
## Prepare independent configuration
|
The bundle includes the application DLLs, provisioning utility, OS installers, units,
|
||||||
|
examples and this guide. Windows services invoke `dotnet Application.dll`, so they do
|
||||||
|
not depend on a Linux-generated apphost executable. The small Microsoft WindowsServices
|
||||||
|
hosting dependency lets the same ASP.NET Core applications respond to Windows service
|
||||||
|
control; it is inactive on Linux/macOS. No production service references another service.
|
||||||
|
|
||||||
Copy each selected `examples/NAME.env.example` to a protected administrator directory
|
Transfer the release by normal administrative deployment transport. Public release
|
||||||
as `NAME.env`. Replace placeholders with actual values. Existing examples deliberately
|
files contain no generated secrets. Build output must be a new directory.
|
||||||
use remote hostnames and separate DB credentials; they are not usable credentials.
|
|
||||||
|
|
||||||
Service names and resulting paths:
|
## Normal Ubuntu/Debian installation
|
||||||
|
|
||||||
| Selection name | Application | Configuration | systemd unit |
|
Automatic Linux package provisioning currently supports Ubuntu 24.04 and Debian 12/13,
|
||||||
| --- | --- | --- | --- |
|
with a running systemd manager and administrative access. This is the implemented
|
||||||
| api-gateway | ApiGateway.dll | /etc/healthapp/api-gateway.env | healthapp-api-gateway.service |
|
Linux adapter's supported set, not a restriction in the application binaries. Other
|
||||||
| patient-profile | PatientProfileService.dll | /etc/healthapp/patient-profile.env | healthapp-patient-profile.service |
|
Linux distributions need corresponding package-manager integration before the installer
|
||||||
| observation | ObservationService.dll | /etc/healthapp/observation.env | healthapp-observation.service |
|
can claim native dependency provisioning there. Internet access to the signed OS/.NET
|
||||||
| insights | InsightsService.dll | /etc/healthapp/insights.env | healthapp-insights.service |
|
package feeds is needed when dependencies are absent.
|
||||||
| health-overview | HealthOverviewService.dll | /etc/healthapp/health-overview.env | healthapp-health-overview.service |
|
|
||||||
|
|
||||||
Supply each service's own network binding via `ASPNETCORE_URLS`, its needed endpoints,
|
From the release directory:
|
||||||
credentials and (where applicable) DB connection string. The gateway needs all service
|
|
||||||
origins/keys even when their services are deployed on other machines. Other services
|
|
||||||
need only their documented dependencies; installation does not require them locally.
|
|
||||||
|
|
||||||
Use distinct service credentials in both directions, matching the gateway and service
|
|
||||||
settings described in `src/AUTHENTICATION.md`. Never reuse example placeholders.
|
|
||||||
Keep production `ASPNETCORE_ENVIRONMENT=Production` and configure HTTPS origins,
|
|
||||||
certificate path/password and trust chains on each host. Certificate files must be
|
|
||||||
readable by the `healthapp` service identity. For example, externally provision files
|
|
||||||
under `/etc/healthapp` with group `healthapp` and mode `0640`. The installer makes that
|
|
||||||
directory root-owned with group access, and environment files root-only `0600`;
|
|
||||||
systemd reads environment files and passes values into the relevant process.
|
|
||||||
|
|
||||||
`Authentication__KeyDirectory` belongs to the gateway host alone. The gateway unit's
|
|
||||||
StateDirectory creates `/var/lib/healthapp-api-gateway`; its `keys` child is created
|
|
||||||
by data protection. Other machines never require that directory or another service's
|
|
||||||
local application/configuration files. Only configured network APIs cross machines.
|
|
||||||
|
|
||||||
For local development tests, Development permits HTTP; production still requires
|
|
||||||
HTTPS. No deployment path/hostname is hard-coded in an application.
|
|
||||||
|
|
||||||
## Install selected services
|
|
||||||
|
|
||||||
From the transferred release directory, assuming prepared config in `/root/healthapp-config`:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# One service, with dependencies running on independently configured hosts:
|
sudo bash install.sh --services all --host 192.168.1.20
|
||||||
sudo bash install.sh --services insights --config-dir /root/healthapp-config
|
|
||||||
|
|
||||||
# A subset (use this instead of the preceding command on a fresh host):
|
|
||||||
sudo bash install.sh --services patient-profile,observation --config-dir /root/healthapp-config --migrate
|
|
||||||
|
|
||||||
# Complete fresh installation:
|
|
||||||
sudo bash install.sh --services all --config-dir /root/healthapp-config --migrate --start
|
|
||||||
```
|
```
|
||||||
|
|
||||||
`--bundle DIRECTORY` selects a release explicitly. `--dotnet /absolute/runtime/path`
|
Use the target's reachable DNS name/IP for `--host`. The default `localhost` is useful
|
||||||
changes only ExecStart in selected units, when dotnet is not installed at `/usr/bin/dotnet`.
|
for a wholly local prototype; use a reachable address for another computer to access
|
||||||
The installer checks the .NET 10 ASP.NET Core runtime on a live host.
|
it. No later application-file editing is required.
|
||||||
|
|
||||||
Installation creates the conventional `healthapp` service user/group if absent,
|
For an individual service, use its name and an existing matching generated deployment
|
||||||
copies selected independent applications to `/opt/healthapp/NAME`, copies selected
|
from the overall topology, which already specifies its remote dependencies/keys:
|
||||||
configurations to `/etc/healthapp/NAME.env`, registers selected units under
|
|
||||||
`/etc/systemd/system`, reloads systemd and enables only those units for boot.
|
|
||||||
It preflights the full selection before writing files. Unselected service files,
|
|
||||||
configuration and registrations are untouched; no service dependency/PartOf/BindsTo
|
|
||||||
relationships are introduced between HealthApp units.
|
|
||||||
|
|
||||||
Default installation does not start services or modify schemas. `--migrate` explicitly
|
|
||||||
runs the selected Patient/Profile and/or Observation application's existing migration
|
|
||||||
mode, under its service identity/configuration, using a transient systemd unit. It
|
|
||||||
never migrates Insights/Overview or another service's DB. `--start` explicitly starts
|
|
||||||
the selected units after successful installation/migrations. For migrations run
|
|
||||||
separately, use the existing published `--migrate` commands with that service's
|
|
||||||
configuration, then start its unit.
|
|
||||||
|
|
||||||
Existing installation directories, env files or units cause refusal before writes.
|
|
||||||
This is a first-install mechanism, not an upgrade/uninstall tool. It never overwrites
|
|
||||||
existing configuration, removes persistent data or guesses how to rotate credentials.
|
|
||||||
A live copy/migration/systemd error can leave installed files or earlier selected units
|
|
||||||
configured; the command fails and those files/data are retained for administrator
|
|
||||||
inspection. There is no cross-service deployment transaction or automatic rollback.
|
|
||||||
|
|
||||||
`--root /absolute/staging/directory` stages an offline filesystem tree without root,
|
|
||||||
user creation, runtime checks or systemctl calls. It is for testing/image preparation,
|
|
||||||
not a completed live installation. It refuses `--start`/`--migrate`. Provision the
|
|
||||||
runtime, healthapp user/group, config-directory group/certificate access and gateway
|
|
||||||
state-directory ownership on the target, then reload/enable/start the selected units.
|
|
||||||
The paths *inside* each unit refer to the target's `/opt` and `/etc`, not to the
|
|
||||||
staging directory. Never mistake successful staging for successful startup.
|
|
||||||
|
|
||||||
## Manage and verify installation
|
|
||||||
|
|
||||||
Each unit can be independently managed using, for example:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo systemctl start healthapp-insights.service
|
sudo bash install.sh --services insights --deployment /secure/generated-deployment
|
||||||
sudo systemctl stop healthapp-insights.service
|
|
||||||
sudo systemctl restart healthapp-insights.service
|
|
||||||
sudo journalctl -u healthapp-insights.service
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Stopping a dependency may cause application requests needing it to fail; it does not
|
Names: `api-gateway`, `patient-profile`, `observation`, `insights`, `health-overview`.
|
||||||
stop peer processes. Services need no local process-start ordering or shared memory.
|
|
||||||
|
|
||||||
Prepare a protected probe directory with `NAME.curl` files for each selected service.
|
The installer:
|
||||||
These are curl data configuration files (not shell scripts), containing the actual
|
|
||||||
HTTPS URL, trusted CA and credentials appropriate for a *read-only* HTTP 200 request.
|
|
||||||
For example, Insights can use a configured patient/period that has observation data:
|
|
||||||
|
|
||||||
```text
|
1. Detects .NET 10 ASP.NET Core runtime and local PostgreSQL availability; installs
|
||||||
url = "https://insights.example.test:5083/api/patients/PATIENT_ID/insights?from=2026-09-01&to=2026-09-10"
|
missing dependencies from supported package feeds. PostgreSQL is provisioned only
|
||||||
header = "X-Gateway-Key: ACTUAL_INSIGHTS_GATEWAY_CREDENTIAL"
|
when Patient/Profile or Observation is selected.
|
||||||
cacert = "/etc/healthapp/trusted-ca.pem"
|
2. Generates a private deployment plan, independent service keys and synthetic
|
||||||
|
prototype accounts. No hard-coded passwords or hand-written password hashes are used.
|
||||||
|
3. Creates a private prototype CA and separate service certificates, installs the
|
||||||
|
public CA into OS trust, and configures Production HTTPS endpoints.
|
||||||
|
4. Creates separate PostgreSQL databases and login roles for the selected persistent
|
||||||
|
services. Roles cannot administer the server/create roles/databases or connect to
|
||||||
|
the other service's database. Schema ownership supports that service's migrations.
|
||||||
|
5. Creates independent service identities, application/configuration directories and
|
||||||
|
service registrations. Runs the selected persistent services' migrations, enables
|
||||||
|
and starts every selected application, then verifies startup and topology.
|
||||||
|
|
||||||
|
Linux application/configuration paths are `/opt/healthapp/NAME` and
|
||||||
|
`/etc/healthapp/NAME/service.env`. Env files are root-only; systemd passes their values
|
||||||
|
to the owning process. Certificate private keys are readable only by root and the
|
||||||
|
respective service identity. Units use `healthapp-NAME` users/groups, not a shared
|
||||||
|
application identity. Gateway key state remains gateway-owned.
|
||||||
|
|
||||||
|
Generated material normally resides at `/var/lib/healthapp-installation/deployment`
|
||||||
|
with a private directory and private files. `accounts.json` contains generated
|
||||||
|
`prototype-patient`, `prototype-professional` and `installation-check` passwords.
|
||||||
|
The professional starts without assignments. Do not put generated material in Git.
|
||||||
|
Only the CA's public certificate is installed/exported publicly; its signing private
|
||||||
|
key is not retained. Certificates expire after one year; the prototype CA after two.
|
||||||
|
|
||||||
|
## Topology and distributed installation
|
||||||
|
|
||||||
|
A topology specifies addresses, ports and native platforms, not credentials. Defaults
|
||||||
|
are HTTPS ports 5443/5081/5082/5083/5084. Colocated applications need different ports.
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"hosts": {
|
||||||
|
"api-gateway": "192.168.1.20",
|
||||||
|
"patient-profile": "192.168.1.21",
|
||||||
|
"observation": "192.168.1.22",
|
||||||
|
"insights": "192.168.1.23",
|
||||||
|
"health-overview": "192.168.1.24"
|
||||||
|
},
|
||||||
|
"platforms": {
|
||||||
|
"api-gateway": "linux",
|
||||||
|
"patient-profile": "linux",
|
||||||
|
"observation": "linux",
|
||||||
|
"insights": "macos",
|
||||||
|
"health-overview": "windows"
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Use corresponding profile GET, latest-observation GET and Overview GET probes on
|
Optional `ports` uses the same service keys and integer values. Hostnames/IPs must
|
||||||
those services. For API Gateway use a bearer-authenticated Overview GET. For a
|
resolve/reach the corresponding target. Supply existing administrative SSH access;
|
||||||
complete installation that probe must select a prepared patient/period with profile,
|
Unix hosts need passwordless sudo for the installer, Windows SSH sessions must be
|
||||||
latest reading and calculated insight, thereby exercising the documented gateway
|
elevated administrators. Host administration credentials are distinct from generated
|
||||||
and all four application services. Ensure representative records exist through the
|
HealthApp/database credentials and are not invented by the application installer.
|
||||||
normal APIs before verification. Public guidance alone cannot verify dependencies.
|
|
||||||
Keep probes root-only; their credentials do not belong in the release or repository.
|
Generate one consistent deployment and automatically distribute matching, scoped
|
||||||
Do not disable certificate verification. Select test/deployment data appropriate to
|
material to each host:
|
||||||
the environment rather than letting installation create patient information.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo bash verify.sh --services all --probe-dir /root/healthapp-probes
|
sudo bash install.sh --services all --prepare-only --topology topology.json \
|
||||||
# Explicitly permits independently stopping/starting/restarting every selected unit:
|
--deployment /secure/healthapp-deployment --dotnet /path/to/available/dotnet
|
||||||
sudo bash verify.sh --services all --probe-dir /root/healthapp-probes --cycle
|
bash distribute.sh --deployment /secure/healthapp-deployment --ssh-user administrator
|
||||||
```
|
```
|
||||||
|
|
||||||
Verification checks active units, distinct real PIDs and each configured network
|
Use an administrative session able to read the protected deployment material. The
|
||||||
probe's HTTP 200 response. `--cycle` checks peer units stay active during each stop,
|
preparation machine needs an available .NET 10 runtime/SDK for the C# utility.
|
||||||
then starts/restarts that service and probes it again. HTTP response bodies and
|
Distribution uses SSH/SCP, installs only selected applications per host, and exports
|
||||||
credentials are suppressed. Probes fail on connection errors, unexpected status or
|
only their private material plus necessary remote origins. It starts nodes first,
|
||||||
an exited process. Verification fails rather than treating unavailable sources as
|
then verifies the complete topology over its real HTTPS endpoints. No credentials
|
||||||
missing data. Use the same mechanism on every host for a distributed deployment;
|
are manually invented, copied into application files or distributed individually.
|
||||||
the complete-system gateway probe checks the configured remote communication paths.
|
Services never depend on a shared runtime directory/file across machines.
|
||||||
|
|
||||||
## Automated evidence and limits
|
A node started with the orchestrator's `--defer-topology-check` has verified local
|
||||||
|
process/HTTPS/database readiness but pending cross-node verification. It is not
|
||||||
|
reported as a verified complete topology until the orchestrator's final check passes.
|
||||||
|
For incremental installation, reuse the same deployment; independently generated
|
||||||
|
plans deliberately have different keys and cannot authenticate to each other.
|
||||||
|
|
||||||
`tests/Deployment.AcceptanceTests` publishes a release, installs into temporary roots,
|
## Windows and macOS adapters
|
||||||
and launches the installed assemblies as separate OS processes against temporary,
|
|
||||||
independent PostgreSQL databases. It covers selection, preflight failures, independent
|
|
||||||
config files/permissions/units, standalone startup for every service, multiple/all
|
|
||||||
processes, authenticated profile/observation/Overview workflow, per-service graceful
|
|
||||||
stop/restart, retained data and separate persistence. There are no production service
|
|
||||||
project references in this test project and no test authentication replacement.
|
|
||||||
|
|
||||||
Run with Linux, Bash, .NET 10 SDK, and `TEST_POSTGRES_CONNECTION` referencing a DB
|
On Windows, from an elevated PowerShell session in the release:
|
||||||
account allowed to create isolated test databases. `HEALTHAPP_DOTNET` may select the
|
|
||||||
SDK/runtime executable. Ordinary acceptance tests remain available in the solution.
|
|
||||||
|
|
||||||
This development execution environment has no running systemd manager. Automated
|
```powershell
|
||||||
process tests therefore use direct process launch and SIGINT (the same configured
|
powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -Services all -HostName 192.168.1.20
|
||||||
stop signal); live systemctl registration/boot cycling and production certificates
|
```
|
||||||
must be verified with the supplied verifier on a supported target Linux host. The
|
|
||||||
suite does not claim that localhost testing alone proves a deployment on separate
|
The adapter installs the .NET runtime automatically, resolves and checksum-verifies
|
||||||
physical machines. Remote origins and independent configuration are preserved by
|
an EDB PostgreSQL installer from Microsoft's package manifest, creates an owned
|
||||||
installation, and the target-host gateway probe is the distributed-system check.
|
PostgreSQL service when needed, and generates its administrator secret in protected
|
||||||
|
files. Existing application/data files are not overwritten. An existing externally
|
||||||
|
managed PostgreSQL server can instead be used with `-PostgresAdminFile`; the installer
|
||||||
|
still generates application database roles/passwords automatically.
|
||||||
|
|
||||||
|
Applications have separate native Windows Services and virtual service identities,
|
||||||
|
protected per-service JSON configuration, state and certificate ACLs. Their Production
|
||||||
|
configuration is installed automatically; certificates are trusted in LocalMachine
|
||||||
|
Root. HTTPS firewall rules cover only selected application ports. No IIS is required.
|
||||||
|
Windows uses `-Deployment`, `-Topology`, `-Certificates` for the same shared material.
|
||||||
|
Default application root is `%ProgramData%\HealthApp`.
|
||||||
|
|
||||||
|
On macOS, from a sudo administrator session:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo bash install.sh --services all --host 192.168.1.20
|
||||||
|
```
|
||||||
|
|
||||||
|
The Darwin adapter installs the ASP.NET Core runtime, provisions Homebrew/PostgreSQL
|
||||||
|
and required Apple build tools where available through softwareupdate, initializes
|
||||||
|
an installer-owned PostgreSQL cluster with SCRAM passwords, and creates separate
|
||||||
|
hidden service identities and launchd daemons. It configures system-keychain CA trust,
|
||||||
|
private environment/launchd files and selected migrations automatically. Default root
|
||||||
|
is `/Library/Application Support/HealthApp`. macOS package/tool installation requires
|
||||||
|
an administrator user session, network access, and acceptance of OS/vendor licensing.
|
||||||
|
|
||||||
|
The adapters target supported .NET desktop/server operating systems. Portability does
|
||||||
|
not claim support for every OS/kernel/version/CPU where .NET itself is unavailable.
|
||||||
|
The live Windows/macOS registration paths need native-host validation; see evidence
|
||||||
|
limits below. The Linux execution environment cannot run Windows SCM or macOS launchd.
|
||||||
|
|
||||||
|
## Verification and management
|
||||||
|
|
||||||
|
Installation verifies distinct native processes, configured HTTPS endpoints, selected
|
||||||
|
databases using their dedicated credentials, actual service keys and outgoing gateway
|
||||||
|
access. The complete-system check logs in with the generated `installation-check`
|
||||||
|
account and exercises profile/observation/Overview through all deployed services.
|
||||||
|
It creates at most one clearly labelled synthetic check profile/observation if absent.
|
||||||
|
This is prototype test data, not a clinical reading; repeated verification reuses it.
|
||||||
|
|
||||||
|
The verifier trusts the generated public CA, validates certificate chains/server names,
|
||||||
|
and never disables TLS validation. Existing HTTPS trust is retained. All step failures
|
||||||
|
identify the failed operation/service and retain existing data/material for inspection.
|
||||||
|
Sensitive SQL/credentials are not printed. Existing applications/configuration cause
|
||||||
|
refusal rather than silent replacement; this remains a first-install mechanism,
|
||||||
|
not an upgrade/uninstall/data-removal tool. Deployment is not a cross-service transaction.
|
||||||
|
|
||||||
|
Linux may rerun `sudo bash verify.sh --services all --deployment DIRECTORY` from the
|
||||||
|
bundle. Manage selected units with `systemctl start/stop/restart healthapp-NAME`.
|
||||||
|
Windows uses `Start-Service`, `Stop-Service`, `Restart-Service`; macOS uses
|
||||||
|
`launchctl bootstrap`, `bootout`, `kickstart` on `healthapp-NAME` labels. Stopping a
|
||||||
|
service does not directly stop peer processes; requests needing it may fail.
|
||||||
|
|
||||||
|
External trusted certificates can be supplied during preparation with `--certificates`
|
||||||
|
or `-Certificates`. The directory supplies `NAME.pfx`, `NAME.password` for all five
|
||||||
|
planned services and `healthapp-ca.crt`. Supplied PFX certificate chains are retained;
|
||||||
|
private keys/passwords are protected and configured automatically. Prototype browser
|
||||||
|
clients may import the exported public CA for trust; server-side service trust is
|
||||||
|
configured automatically by installation.
|
||||||
|
|
||||||
|
`--root DIRECTORY` on Linux is explicitly offline staging: it generates the same
|
||||||
|
settings/material but cannot install host packages or register/start systemd. It is
|
||||||
|
not reported as a live verified installation. `--postgres-admin-file` allows automated
|
||||||
|
DB provisioning against an externally managed/test server, not manual application
|
||||||
|
DB/user preparation. Normal Linux installation administers local PostgreSQL through
|
||||||
|
its OS postgres identity without inventing a PostgreSQL administrator password.
|
||||||
|
|
||||||
|
## Evidence and dependencies
|
||||||
|
|
||||||
|
The xUnit deployment suite builds the release, calls the actual provisioner/installer,
|
||||||
|
creates database roles/databases in an isolated PostgreSQL server and runs all five
|
||||||
|
installed services in separate Production-mode HTTPS processes. Tests cover generated
|
||||||
|
key matching/uniqueness, certificate private-key output, private configuration, database
|
||||||
|
isolation/permissions, migrations, native-format configuration, independent restart,
|
||||||
|
representative functionality and repeated non-destructive verification. Package command
|
||||||
|
contracts are tested with controlled command doubles; no host package installation
|
||||||
|
is performed by the tests. The ordinary application tests remain unchanged.
|
||||||
|
|
||||||
|
Linux HTTPS/interservice/database execution is verified here. Live systemd package/
|
||||||
|
registration behaviour needs a supported Linux host; Windows/macOS service registration
|
||||||
|
needs those native hosts. Native configuration formats are exercised by the shared
|
||||||
|
utility tests; shell/PowerShell syntax validation is separate from a native end-to-end
|
||||||
|
run. The manual `.github/workflows/prototype-native-install.yml` workflow provisions
|
||||||
|
and verifies fresh Ubuntu, Windows and macOS runners; it is supplied for native
|
||||||
|
validation and has not been executed remotely in this session. These limits must not be described as verified production deployment on every OS.
|
||||||
|
|
||||||
|
The provisioning tool uses standard .NET X.509/password hashing and Npgsql for creating
|
||||||
|
and checking databases. Its dependency is not a shared service runtime library.
|
||||||
|
Microsoft.Extensions.Hosting.WindowsServices is added to the five services solely for
|
||||||
|
native Windows service lifetime integration; Linux/macOS responsibilities are unchanged.
|
||||||
|
|
||||||
|
Package/lifetime references reviewed during implementation:
|
||||||
|
[Ubuntu runtime installation](https://learn.microsoft.com/en-us/dotnet/core/install/linux-ubuntu-install),
|
||||||
|
[Debian runtime installation](https://learn.microsoft.com/en-us/dotnet/core/install/linux-debian),
|
||||||
|
[Windows service hosting](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-10.0),
|
||||||
|
[EDB unattended installer parameters](https://www.enterprisedb.com/docs/supported-open-source/postgresql/installing/command_line_parameters/).
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param([Parameter(Mandatory=$true)][string]$Output, [string]$Services='all')
|
||||||
|
$ErrorActionPreference='Stop'
|
||||||
|
$assemblies=@{ 'api-gateway'='ApiGateway'; 'patient-profile'='PatientProfileService'; 'observation'='ObservationService'; 'insights'='InsightsService'; 'health-overview'='HealthOverviewService' }
|
||||||
|
$selected=if ($Services -eq 'all') { @('api-gateway','patient-profile','observation','insights','health-overview') } else { @($Services.Split(',')) }
|
||||||
|
if ((Test-Path $Output) -or @($selected | Select-Object -Unique).Count -ne $selected.Count) { throw 'Use a new output directory and unique service names.' }
|
||||||
|
foreach ($name in $selected) { if (-not $assemblies.ContainsKey($name)) { throw "Unknown service: $name" } }
|
||||||
|
New-Item -ItemType Directory -Path $Output | Out-Null
|
||||||
|
$destination=(Resolve-Path $Output).Path
|
||||||
|
$repository=Split-Path $PSScriptRoot -Parent
|
||||||
|
foreach ($directory in @('services','systemd','examples')) { New-Item -ItemType Directory -Path "$destination\$directory" | Out-Null }
|
||||||
|
Copy-Item "$PSScriptRoot\installer\*.sh","$PSScriptRoot\installer\*.ps1","$PSScriptRoot\INSTALLATION.md" $destination
|
||||||
|
foreach ($name in $selected) {
|
||||||
|
& dotnet publish "$repository\src\$($assemblies[$name])\$($assemblies[$name]).csproj" --configuration Release --self-contained false '-p:UseAppHost=false' --output "$destination\services\$name"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "Publish failed: $name" }
|
||||||
|
Copy-Item "$PSScriptRoot\systemd\healthapp-$name.service" "$destination\systemd"
|
||||||
|
Copy-Item "$PSScriptRoot\$name.env.example" "$destination\examples"
|
||||||
|
}
|
||||||
|
& dotnet publish "$PSScriptRoot\HealthApp.Provisioning\HealthApp.Provisioning.csproj" --configuration Release --self-contained false '-p:UseAppHost=false' --output "$destination\provisioner"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'Publish failed: provisioning utility' }
|
||||||
|
$selected | Set-Content "$destination\services.list"
|
||||||
|
Write-Host "Portable release created: $destination"
|
||||||
@@ -21,12 +21,14 @@ command -v "$dotnet_command" >/dev/null || fail '.NET 10 SDK is required to buil
|
|||||||
mkdir -p -- "$output/services" "$output/systemd" "$output/examples"
|
mkdir -p -- "$output/services" "$output/systemd" "$output/examples"
|
||||||
output=$(cd -- "$output" && pwd)
|
output=$(cd -- "$output" && pwd)
|
||||||
cp -- "$script_dir/installer/"*.sh "$output/"
|
cp -- "$script_dir/installer/"*.sh "$output/"
|
||||||
|
cp -- "$script_dir/installer/"*.ps1 "$output/"
|
||||||
cp -- "$script_dir/INSTALLATION.md" "$output/"
|
cp -- "$script_dir/INSTALLATION.md" "$output/"
|
||||||
for service in "${selected_services[@]}"; do
|
for service in "${selected_services[@]}"; do
|
||||||
assembly=$(assembly_for "$service")
|
assembly=$(assembly_for "$service")
|
||||||
"$dotnet_command" publish "$repo_dir/src/$assembly/$assembly.csproj" --configuration Release --output "$output/services/$service"
|
"$dotnet_command" publish "$repo_dir/src/$assembly/$assembly.csproj" --configuration Release --self-contained false -p:UseAppHost=false --output "$output/services/$service"
|
||||||
cp -- "$script_dir/systemd/healthapp-$service.service" "$output/systemd/"
|
cp -- "$script_dir/systemd/healthapp-$service.service" "$output/systemd/"
|
||||||
cp -- "$script_dir/$service.env.example" "$output/examples/"
|
cp -- "$script_dir/$service.env.example" "$output/examples/"
|
||||||
done
|
done
|
||||||
|
"$dotnet_command" publish "$script_dir/HealthApp.Provisioning/HealthApp.Provisioning.csproj" --configuration Release --self-contained false -p:UseAppHost=false --output "$output/provisioner"
|
||||||
printf '%s\n' "${selected_services[@]}" > "$output/services.list"
|
printf '%s\n' "${selected_services[@]}" > "$output/services.list"
|
||||||
printf 'Release created: %s\n' "$output"
|
printf 'Release created: %s\n' "$output"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Source from install.sh. Package commands use the supported distribution's signed feeds.
|
||||||
|
ensure_dependencies() {
|
||||||
|
local distribution=$1 version=$2 runtime=$3 persistence=$4
|
||||||
|
case "$distribution:$version" in ubuntu:24.04|debian:12|debian:13) ;; *) fail 'Automatic provisioning supports Ubuntu 24.04 and Debian 12/13.';; esac
|
||||||
|
step='install base dependencies'
|
||||||
|
if ! command -v curl >/dev/null || ! command -v update-ca-certificates >/dev/null; then
|
||||||
|
apt-get update
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates curl
|
||||||
|
fi
|
||||||
|
if [[ ! -x "$runtime" ]] || ! "$runtime" --list-runtimes | grep -q 'Microsoft.AspNetCore.App 10\.'; then
|
||||||
|
step='install .NET 10 ASP.NET Core runtime'
|
||||||
|
apt-get update
|
||||||
|
if [[ "$distribution" == debian ]]; then
|
||||||
|
local package_dir
|
||||||
|
package_dir=$(mktemp -d)
|
||||||
|
curl --fail --silent --show-error "https://packages.microsoft.com/config/debian/$version/packages-microsoft-prod.deb" -o "$package_dir/microsoft.deb"
|
||||||
|
dpkg -i "$package_dir/microsoft.deb"
|
||||||
|
rm -f -- "$package_dir/microsoft.deb"
|
||||||
|
rmdir -- "$package_dir"
|
||||||
|
apt-get update
|
||||||
|
fi
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y aspnetcore-runtime-10.0
|
||||||
|
fi
|
||||||
|
[[ -x "$runtime" ]] && "$runtime" --list-runtimes | grep -q 'Microsoft.AspNetCore.App 10\.' || fail 'The .NET 10 ASP.NET Core runtime could not be provisioned.'
|
||||||
|
if [[ "$persistence" == true ]]; then
|
||||||
|
step='provision PostgreSQL server'
|
||||||
|
if ! command -v pg_isready >/dev/null || ! pg_isready -q -h localhost -p 5432; then
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y postgresql
|
||||||
|
systemctl enable --now postgresql
|
||||||
|
fi
|
||||||
|
local ready=false attempt
|
||||||
|
for attempt in {1..30}; do
|
||||||
|
if pg_isready -q -h localhost -p 5432; then ready=true; break; fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
[[ "$ready" == true ]] || fail 'PostgreSQL did not become available on localhost:5432.'
|
||||||
|
fi
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
|
fail() { printf 'Distribution failed: %s\n' "$*" >&2; exit 1; }
|
||||||
|
source "$script_dir/services.sh"
|
||||||
|
deployment=
|
||||||
|
requested=all
|
||||||
|
ssh_user=
|
||||||
|
dotnet_path=/usr/bin/dotnet
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--deployment|--services|--ssh-user|--dotnet)
|
||||||
|
[[ $# -gt 1 ]] || fail 'Missing argument.'
|
||||||
|
case "$1" in --deployment) deployment=$2;; --services) requested=$2;; --ssh-user) ssh_user=$2;; --dotnet) dotnet_path=$2;; esac
|
||||||
|
shift 2;;
|
||||||
|
--help) printf '%s\n' 'Usage: bash distribute.sh --deployment GENERATED_DIRECTORY --ssh-user ADMIN_USER [--services all|NAME[,NAME]] [--dotnet PATH]' 'Uses configured SSH access and passwordless sudo on the topology hosts. Generates no new credentials; installs matching scoped material and verifies the topology.'; exit 0;;
|
||||||
|
*) fail "Unknown argument: $1";;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
select_services "$requested"
|
||||||
|
[[ -n "$deployment" && -n "$ssh_user" ]] || fail 'Deployment directory and SSH administrator are required.'
|
||||||
|
"$dotnet_path" "$script_dir/provisioner/HealthApp.Provisioning.dll" distribute --bundle "$script_dir" \
|
||||||
|
--deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")" --ssh-user "$ssh_user"
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
umask 077
|
||||||
|
step=arguments
|
||||||
|
fail() { printf 'Installation failed at %s: %s\n' "$step" "$*" >&2; exit 1; }
|
||||||
|
trap 'printf "Installation failed at %s (line %s). Existing data was retained.\n" "$step" "$LINENO" >&2' ERR
|
||||||
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
|
source "$script_dir/services.sh"
|
||||||
|
requested=
|
||||||
|
root='/Library/Application Support/HealthApp'
|
||||||
|
host=localhost
|
||||||
|
topology=
|
||||||
|
deployment=
|
||||||
|
external_certificates=
|
||||||
|
admin_file=
|
||||||
|
prepare_only=false
|
||||||
|
defer=false
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--services|--host|--topology|--deployment|--certificates|--root|--postgres-admin-file)
|
||||||
|
[[ $# -gt 1 ]] || fail 'Missing value.'
|
||||||
|
case "$1" in --services) requested=$2;; --host) host=$2;; --topology) topology=$2;; --deployment) deployment=$2;;
|
||||||
|
--certificates) external_certificates=$2;; --root) root=$2;; --postgres-admin-file) admin_file=$2;; esac
|
||||||
|
shift 2;;
|
||||||
|
--prepare-only) prepare_only=true; shift;;
|
||||||
|
--defer-topology-check) defer=true; shift;;
|
||||||
|
--help) printf '%s\n' 'Usage: sudo bash install.sh --services all|NAME[,NAME] [--host DNS_OR_IP] [--topology FILE] [--deployment GENERATED_DIRECTORY]' 'macOS installs the runtime/PostgreSQL and independent launchd daemons using the same application DLLs and provisioning utility.'; exit 0;;
|
||||||
|
*) fail "Unknown argument: $1";;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
[[ $(uname -s) == Darwin && $EUID -eq 0 ]] || fail 'Run under sudo on macOS.'
|
||||||
|
select_services "$requested"
|
||||||
|
for service in "${selected_services[@]}"; do
|
||||||
|
[[ ! -e "$root/services/$service" && ! -e "/Library/LaunchDaemons/healthapp-$service.plist" ]] || fail "Already installed: $service."
|
||||||
|
done
|
||||||
|
mkdir -p "$root"
|
||||||
|
chmod 0711 "$root"
|
||||||
|
step='install .NET 10 ASP.NET Core runtime'
|
||||||
|
dotnet_path="$root/runtime/dotnet"
|
||||||
|
if command -v dotnet >/dev/null && dotnet --list-runtimes | grep -q 'Microsoft.AspNetCore.App 10\.'; then dotnet_path=$(command -v dotnet); fi
|
||||||
|
if [[ ! -x "$dotnet_path" ]]; then
|
||||||
|
curl --fail --silent --show-error https://dot.net/v1/dotnet-install.sh -o "$root/dotnet-install.sh"
|
||||||
|
bash "$root/dotnet-install.sh" --channel 10.0 --runtime aspnetcore --install-dir "$root/runtime" --no-path
|
||||||
|
chmod -R a+rX "$root/runtime"
|
||||||
|
fi
|
||||||
|
provision=("$dotnet_path" "$script_dir/provisioner/HealthApp.Provisioning.dll")
|
||||||
|
step='generate credentials and HTTPS certificates'
|
||||||
|
[[ -n "$deployment" ]] || deployment="$root/deployment"
|
||||||
|
if [[ ! -f "$deployment/deployment.json" ]]; then
|
||||||
|
args=(prepare --output "$deployment" --host "$host")
|
||||||
|
[[ -z "$topology" ]] || args+=(--topology "$topology")
|
||||||
|
[[ -z "$external_certificates" ]] || args+=(--certificates "$external_certificates")
|
||||||
|
"${provision[@]}" "${args[@]}"
|
||||||
|
fi
|
||||||
|
[[ "$prepare_only" == false ]] || { printf 'Generated deployment in %s\n' "$deployment"; exit 0; }
|
||||||
|
step='configure HTTPS trust'
|
||||||
|
security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$deployment/healthapp-ca.crt"
|
||||||
|
create_identity() {
|
||||||
|
local name=$1 uid=300
|
||||||
|
if id "$name" >/dev/null 2>&1; then return; fi
|
||||||
|
while dscl . -search /Users UniqueID "$uid" | grep -q . || dscl . -search /Groups PrimaryGroupID "$uid" | grep -q .; do uid=$((uid+1)); done
|
||||||
|
dscl . -create "/Groups/$name"
|
||||||
|
dscl . -create "/Groups/$name" PrimaryGroupID "$uid"
|
||||||
|
dscl . -create "/Users/$name"
|
||||||
|
dscl . -create "/Users/$name" UniqueID "$uid"
|
||||||
|
dscl . -create "/Users/$name" PrimaryGroupID "$uid"
|
||||||
|
dscl . -create "/Users/$name" UserShell /usr/bin/false
|
||||||
|
dscl . -create "/Users/$name" NFSHomeDirectory /var/empty
|
||||||
|
dscl . -create "/Users/$name" IsHidden 1
|
||||||
|
}
|
||||||
|
persistence=false
|
||||||
|
for service in "${selected_services[@]}"; do case "$service" in patient-profile|observation) persistence=true;; esac; done
|
||||||
|
if [[ "$persistence" == true && -z "$admin_file" ]]; then
|
||||||
|
step='install PostgreSQL binaries'
|
||||||
|
brew_user=${SUDO_USER:-}
|
||||||
|
[[ -n "$brew_user" && "$brew_user" != root ]] || fail 'Run sudo from an administrator account so Homebrew can run as that user.'
|
||||||
|
if ! xcode-select -p >/dev/null 2>&1; then
|
||||||
|
touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
|
||||||
|
label=$(softwareupdate --list 2>&1 | sed -n 's/^.*Label: \(Command Line Tools.*\)/\1/p' | tail -n 1)
|
||||||
|
[[ -n "$label" ]] || fail 'Apple did not offer Command Line Tools through softwareupdate.'
|
||||||
|
softwareupdate --install "$label" --agree-to-license
|
||||||
|
rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
|
||||||
|
fi
|
||||||
|
brew_path=/opt/homebrew/bin/brew
|
||||||
|
[[ -x "$brew_path" ]] || brew_path=/usr/local/bin/brew
|
||||||
|
if [[ ! -x "$brew_path" ]]; then
|
||||||
|
curl --fail --silent --show-error https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh -o "$root/homebrew-install.sh"
|
||||||
|
chmod 0644 "$root/homebrew-install.sh"
|
||||||
|
sudo -u "$brew_user" env NONINTERACTIVE=1 bash "$root/homebrew-install.sh"
|
||||||
|
[[ -x /opt/homebrew/bin/brew ]] && brew_path=/opt/homebrew/bin/brew || brew_path=/usr/local/bin/brew
|
||||||
|
fi
|
||||||
|
sudo -u "$brew_user" "$brew_path" install postgresql@17
|
||||||
|
pg_prefix=$(sudo -u "$brew_user" "$brew_path" --prefix postgresql@17)
|
||||||
|
step='create installer-owned PostgreSQL cluster'
|
||||||
|
pg_identity=_healthapp_postgres
|
||||||
|
create_identity "$pg_identity"
|
||||||
|
admin_file="$root/postgres-admin.connection"
|
||||||
|
if [[ ! -f "$admin_file" ]]; then
|
||||||
|
port=5432
|
||||||
|
while nc -z localhost "$port" >/dev/null 2>&1; do port=$((port+1)); done
|
||||||
|
"${provision[@]}" secret --output "$root/postgres.password"
|
||||||
|
mkdir -p "$root/postgresql-data"
|
||||||
|
chown "$pg_identity:$pg_identity" "$root/postgresql-data" "$root/postgres.password"
|
||||||
|
sudo -u "$pg_identity" "$pg_prefix/bin/initdb" -D "$root/postgresql-data" -U postgres --auth-local=scram-sha-256 --auth-host=scram-sha-256 --pwfile "$root/postgres.password"
|
||||||
|
printf '\nport = %s\n' "$port" >> "$root/postgresql-data/postgresql.conf"
|
||||||
|
"${provision[@]}" admin-connection --password-file "$root/postgres.password" --port "$port" --output "$admin_file"
|
||||||
|
pg_plist=/Library/LaunchDaemons/healthapp-postgresql.plist
|
||||||
|
cat > "$pg_plist" <<PLIST
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0"><dict><key>Label</key><string>healthapp-postgresql</string><key>ProgramArguments</key><array><string>$pg_prefix/bin/postgres</string><string>-D</string><string>$root/postgresql-data</string></array><key>UserName</key><string>$pg_identity</string><key>RunAtLoad</key><true/><key>KeepAlive</key><true/></dict></plist>
|
||||||
|
PLIST
|
||||||
|
chmod 0644 "$pg_plist"
|
||||||
|
launchctl bootstrap system "$pg_plist"
|
||||||
|
fi
|
||||||
|
port=$(sed -n 's/.*Port=\([0-9]*\).*/\1/p' "$admin_file")
|
||||||
|
[[ -n "$port" ]] || port=5432
|
||||||
|
for attempt in {1..30}; do if "$pg_prefix/bin/pg_isready" -q -p "$port"; then break; fi; sleep 1; done
|
||||||
|
fi
|
||||||
|
for service in "${selected_services[@]}"; do
|
||||||
|
step="configure $service"
|
||||||
|
identity="_healthapp_${service//-/_}"
|
||||||
|
create_identity "$identity"
|
||||||
|
case "$service" in patient-profile|observation)
|
||||||
|
"${provision[@]}" database --service-dir "$deployment/$service" --admin-file "$admin_file";;
|
||||||
|
esac
|
||||||
|
"${provision[@]}" configure --service-dir "$deployment/$service" --root "$root" --platform macos
|
||||||
|
mkdir -p "$root/services" "$root/config" "$root/state"
|
||||||
|
chmod 0711 "$root/services" "$root/config" "$root/state"
|
||||||
|
cp -R "$script_dir/services/$service" "$root/services/$service"
|
||||||
|
chmod -R a+rX "$root/services/$service"
|
||||||
|
chgrp -R "$identity" "$root/config/$service"
|
||||||
|
chmod 0750 "$root/config/$service"
|
||||||
|
chmod 0640 "$root/config/$service/"*
|
||||||
|
if [[ "$service" == api-gateway ]]; then
|
||||||
|
mkdir -p "$root/state/api-gateway/keys"
|
||||||
|
chown -R "$identity:$identity" "$root/state/api-gateway"
|
||||||
|
chmod 0700 "$root/state/api-gateway"
|
||||||
|
fi
|
||||||
|
case "$service" in patient-profile|observation)
|
||||||
|
"${provision[@]}" execute --service "$service" --assembly "$root/services/$service/$(assembly_for "$service").dll" --dotnet "$dotnet_path" --root "$root";;
|
||||||
|
esac
|
||||||
|
# plutil converts the JSON object to an XML plist without treating configuration as shell code.
|
||||||
|
"$dotnet_path" "$script_dir/provisioner/HealthApp.Provisioning.dll" launchd --service "$service" --root "$root" --dotnet "$dotnet_path" --output "/Library/LaunchDaemons/healthapp-$service.plist"
|
||||||
|
chmod 0600 "/Library/LaunchDaemons/healthapp-$service.plist"
|
||||||
|
launchctl bootstrap system "/Library/LaunchDaemons/healthapp-$service.plist"
|
||||||
|
done
|
||||||
|
step='verify startup and HTTPS'
|
||||||
|
for service in "${selected_services[@]}"; do launchctl print "system/healthapp-$service" >/dev/null; done
|
||||||
|
"${provision[@]}" verify-startup --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")"
|
||||||
|
if [[ "$defer" == false ]]; then
|
||||||
|
args=(verify --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")")
|
||||||
|
[[ "$requested" != all ]] || args+=(--complete true)
|
||||||
|
"${provision[@]}" "${args[@]}"
|
||||||
|
fi
|
||||||
|
printf 'Installation completed. Account credentials: %s/accounts.json\n' "$deployment"
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory=$true)][string]$Services,
|
||||||
|
[string]$HostName = 'localhost',
|
||||||
|
[string]$Topology,
|
||||||
|
[string]$Deployment,
|
||||||
|
[string]$Certificates,
|
||||||
|
[string]$PostgresAdminFile,
|
||||||
|
[string]$Root = "$env:ProgramData\HealthApp",
|
||||||
|
[switch]$PrepareOnly,
|
||||||
|
[switch]$DeferTopologyCheck
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$step = 'arguments'
|
||||||
|
function Check-Exit([string]$Operation) { if ($LASTEXITCODE -ne 0) { throw "$Operation failed (exit $LASTEXITCODE)." } }
|
||||||
|
function Protect-Private([string]$Path) {
|
||||||
|
& icacls.exe $Path /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null
|
||||||
|
Check-Exit 'Protect private deployment files'
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||||
|
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
|
||||||
|
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run from an elevated PowerShell session.' }
|
||||||
|
$assemblies = @{ 'api-gateway'='ApiGateway'; 'patient-profile'='PatientProfileService'; 'observation'='ObservationService'; 'insights'='InsightsService'; 'health-overview'='HealthOverviewService' }
|
||||||
|
$selected = if ($Services -eq 'all') { @('api-gateway','patient-profile','observation','insights','health-overview') } else { @($Services.Split(',')) }
|
||||||
|
if (@($selected | Select-Object -Unique).Count -ne $selected.Count) { throw 'Repeated service selection.' }
|
||||||
|
foreach ($name in $selected) {
|
||||||
|
if (-not $assemblies.ContainsKey($name)) { throw "Unknown service: $name" }
|
||||||
|
if (-not (Test-Path "$PSScriptRoot\services\$name\$($assemblies[$name]).dll")) { throw "Missing release: $name" }
|
||||||
|
if ((Test-Path "$Root\services\$name") -or (Get-Service "healthapp-$name" -ErrorAction SilentlyContinue)) { throw "Already installed: $name. Existing files were not changed." }
|
||||||
|
}
|
||||||
|
New-Item -ItemType Directory -Force $Root | Out-Null
|
||||||
|
Protect-Private $Root
|
||||||
|
$step = 'install .NET 10 ASP.NET Core runtime'
|
||||||
|
$dotnet = "$Root\runtime\dotnet.exe"
|
||||||
|
if (Get-Command dotnet.exe -ErrorAction SilentlyContinue) {
|
||||||
|
$candidate = (Get-Command dotnet.exe).Source
|
||||||
|
if ((& $candidate --list-runtimes) -match 'Microsoft.AspNetCore.App 10\.') { $dotnet = $candidate }
|
||||||
|
}
|
||||||
|
if (-not (Test-Path $dotnet)) {
|
||||||
|
$script = "$Root\dotnet-install.ps1"
|
||||||
|
Invoke-WebRequest 'https://dot.net/v1/dotnet-install.ps1' -OutFile $script -UseBasicParsing
|
||||||
|
& $script -Channel '10.0' -Runtime 'aspnetcore' -InstallDir "$Root\runtime" -NoPath
|
||||||
|
if (-not (Test-Path $dotnet)) { throw 'Runtime installation did not produce dotnet.exe.' }
|
||||||
|
}
|
||||||
|
$utility = "$PSScriptRoot\provisioner\HealthApp.Provisioning.dll"
|
||||||
|
$step = 'generate deployment material'
|
||||||
|
if (-not $Deployment) { $Deployment = "$Root\deployment" }
|
||||||
|
if (-not (Test-Path "$Deployment\deployment.json")) {
|
||||||
|
$prepare = @($utility,'prepare','--output',$Deployment,'--host',$HostName)
|
||||||
|
if ($Topology) { $prepare += @('--topology',$Topology) }
|
||||||
|
if ($Certificates) { $prepare += @('--certificates',$Certificates) }
|
||||||
|
& $dotnet @prepare
|
||||||
|
Check-Exit 'Generate credentials and HTTPS certificates'
|
||||||
|
}
|
||||||
|
Protect-Private $Deployment
|
||||||
|
if ($PrepareOnly) { Write-Host "Generated protected deployment material in $Deployment"; return }
|
||||||
|
$step = 'install prototype HTTPS trust'
|
||||||
|
Import-Certificate -FilePath "$Deployment\healthapp-ca.crt" -CertStoreLocation Cert:\LocalMachine\Root | Out-Null
|
||||||
|
$needsPostgres = ($selected -contains 'patient-profile') -or ($selected -contains 'observation')
|
||||||
|
if ($needsPostgres -and -not $PostgresAdminFile) {
|
||||||
|
$PostgresAdminFile = "$Root\postgres-admin.connection"
|
||||||
|
if (-not (Test-Path $PostgresAdminFile)) {
|
||||||
|
$step = 'install PostgreSQL'
|
||||||
|
# Resolve the maintained Microsoft package manifest, verify the vendor binary checksum,
|
||||||
|
# and pass the generated administrator secret through a protected options file.
|
||||||
|
$headers = @{ 'User-Agent'='HealthApp-Prototype-Installer' }
|
||||||
|
$manifestBase = 'https://api.github.com/repos/microsoft/winget-pkgs/contents/manifests/p/PostgreSQL/PostgreSQL/17'
|
||||||
|
$versions = Invoke-RestMethod $manifestBase -Headers $headers
|
||||||
|
$latest = $versions | Sort-Object @{Expression={[version]($_.name.Split('-')[0])}}, @{Expression={[int]($_.name.Split('-')[-1])}} -Descending | Select-Object -First 1
|
||||||
|
$files = Invoke-RestMethod $latest.url -Headers $headers
|
||||||
|
$manifest = $files | Where-Object { $_.name -like '*.installer.yaml' } | Select-Object -First 1
|
||||||
|
$yaml = (Invoke-WebRequest $manifest.download_url -UseBasicParsing).Content
|
||||||
|
$download = [regex]::Match($yaml,'(?m)^\s*InstallerUrl:\s*(\S+)').Groups[1].Value
|
||||||
|
$checksum = [regex]::Match($yaml,'(?m)^\s*InstallerSha256:\s*([A-Fa-f0-9]{64})').Groups[1].Value
|
||||||
|
if (-not $download.StartsWith('https://get.enterprisedb.com/') -or -not $checksum) { throw 'PostgreSQL package manifest is invalid.' }
|
||||||
|
$installer = "$Root\postgresql-installer.exe"
|
||||||
|
Invoke-WebRequest $download -OutFile $installer -UseBasicParsing
|
||||||
|
if ((Get-FileHash $installer -Algorithm SHA256).Hash -ne $checksum) { throw 'PostgreSQL installer checksum does not match.' }
|
||||||
|
$random = New-Object byte[] 32
|
||||||
|
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
|
||||||
|
$rng.GetBytes($random); $rng.Dispose()
|
||||||
|
$adminPassword = [BitConverter]::ToString($random).Replace('-','') + 'a!'
|
||||||
|
$port = 5432
|
||||||
|
$listener = New-Object Net.Sockets.TcpListener([Net.IPAddress]::Loopback,$port)
|
||||||
|
try { $listener.Start() } catch { $listener = New-Object Net.Sockets.TcpListener([Net.IPAddress]::Loopback,0); $listener.Start(); $port = $listener.LocalEndpoint.Port }
|
||||||
|
finally { $listener.Stop() }
|
||||||
|
$options = "$Root\postgresql.options"
|
||||||
|
@('mode=unattended','unattendedmodeui=none','debuglevel=0','enable-components=server,commandlinetools',
|
||||||
|
"prefix=$Root\postgresql","datadir=$Root\postgresql-data","serverport=$port",'servicename=healthapp-postgresql',
|
||||||
|
'serviceaccount=NT AUTHORITY\NetworkService',"superpassword=$adminPassword") | Set-Content $options -Encoding UTF8
|
||||||
|
Protect-Private $options
|
||||||
|
$installed = Start-Process $installer -ArgumentList @('--optionfile',('"'+$options+'"')) -Wait -PassThru
|
||||||
|
if ($installed.ExitCode -ne 0) { throw 'PostgreSQL unattended installation failed.' }
|
||||||
|
"Host=localhost;Port=$port;Database=postgres;Username=postgres;Password=$adminPassword" | Set-Content $PostgresAdminFile -Encoding UTF8
|
||||||
|
Protect-Private $PostgresAdminFile
|
||||||
|
Remove-Item $options
|
||||||
|
}
|
||||||
|
Start-Service 'healthapp-postgresql'
|
||||||
|
}
|
||||||
|
foreach ($name in $selected) {
|
||||||
|
$step = "configure $name"
|
||||||
|
if ($name -eq 'patient-profile' -or $name -eq 'observation') {
|
||||||
|
& $dotnet $utility database --service-dir "$Deployment\$name" --admin-file $PostgresAdminFile
|
||||||
|
Check-Exit "Create dedicated $name database and credentials"
|
||||||
|
}
|
||||||
|
& $dotnet $utility configure --service-dir "$Deployment\$name" --root $Root --platform windows
|
||||||
|
Check-Exit "Configure $name"
|
||||||
|
New-Item -ItemType Directory -Force "$Root\services" | Out-Null
|
||||||
|
$application = "$Root\services\$name"
|
||||||
|
Copy-Item "$PSScriptRoot\services\$name" $application -Recurse
|
||||||
|
Copy-Item "$Root\config\$name\appsettings.Production.json" "$application\appsettings.Production.json"
|
||||||
|
$dll = "$application\$($assemblies[$name]).dll"
|
||||||
|
if ($name -eq 'patient-profile' -or $name -eq 'observation') {
|
||||||
|
& $dotnet $dll --migrate --contentRoot $application --environment Production
|
||||||
|
Check-Exit "Migrate $name database"
|
||||||
|
}
|
||||||
|
$serviceName = "healthapp-$name"
|
||||||
|
$binary = '"'+$dotnet+'" "'+$dll+'" --contentRoot "'+$application+'" --environment Production'
|
||||||
|
New-Service -Name $serviceName -BinaryPathName $binary -StartupType Automatic -Description "HealthApp $name" | Out-Null
|
||||||
|
& sc.exe config $serviceName obj= "NT SERVICE\$serviceName" | Out-Null
|
||||||
|
Check-Exit "Configure independent $name virtual service account"
|
||||||
|
& icacls.exe $application /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null
|
||||||
|
& icacls.exe "$Root\config\$name" /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null
|
||||||
|
if ($name -eq 'api-gateway') {
|
||||||
|
New-Item -ItemType Directory -Force "$Root\state\api-gateway\keys" | Out-Null
|
||||||
|
& icacls.exe "$Root\state\api-gateway" /grant "NT SERVICE\${serviceName}:(OI)(CI)M" /T | Out-Null
|
||||||
|
}
|
||||||
|
# Service identities need traversal/runtime access, not other services' private configuration.
|
||||||
|
foreach ($parent in @("$Root\services","$Root\config","$Root\state")) {
|
||||||
|
if (Test-Path $parent) { & icacls.exe $parent /grant "NT SERVICE\${serviceName}:RX" | Out-Null }
|
||||||
|
}
|
||||||
|
& icacls.exe $Root /grant "NT SERVICE\${serviceName}:RX" | Out-Null
|
||||||
|
if ($dotnet.StartsWith($Root)) { & icacls.exe "$Root\runtime" /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null }
|
||||||
|
& sc.exe failure $serviceName reset= 86400 actions= restart/5000 | Out-Null
|
||||||
|
$settings = Get-Content "$Deployment\$name\service.json" -Raw | ConvertFrom-Json
|
||||||
|
New-NetFirewallRule -DisplayName "HealthApp $name HTTPS" -Direction Inbound -Action Allow -Protocol TCP -LocalPort $settings.Port -Program $dotnet | Out-Null
|
||||||
|
Start-Service $serviceName
|
||||||
|
}
|
||||||
|
$step = 'verify running processes and HTTPS'
|
||||||
|
$processIds = @()
|
||||||
|
foreach ($name in $selected) {
|
||||||
|
$native = Get-CimInstance Win32_Service -Filter "Name='healthapp-$name'"
|
||||||
|
if ($native.State -ne 'Running' -or $native.ProcessId -eq 0 -or ($processIds -contains $native.ProcessId)) { throw "$name is not an independent running service." }
|
||||||
|
$processIds += $native.ProcessId
|
||||||
|
}
|
||||||
|
& $dotnet $utility verify-startup --deployment $Deployment --services ($selected -join ',')
|
||||||
|
Check-Exit 'HTTPS startup verification'
|
||||||
|
if (-not $DeferTopologyCheck) {
|
||||||
|
$verify = @($utility,'verify','--deployment',$Deployment,'--services',($selected -join ','))
|
||||||
|
if ($Services -eq 'all') { $verify += @('--complete','true') }
|
||||||
|
& $dotnet @verify
|
||||||
|
Check-Exit 'Dependency and representative workflow verification'
|
||||||
|
}
|
||||||
|
Write-Host "Installation completed. Generated account credentials are protected in $Deployment\accounts.json"
|
||||||
|
} catch {
|
||||||
|
Write-Error "Installation failed at ${step}: $($_.Exception.Message). Existing data and deployment material were retained."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
+118
-56
@@ -1,88 +1,150 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
umask 077
|
umask 077
|
||||||
fail() { printf 'Error: %s\n' "$*" >&2; exit 1; }
|
step=arguments
|
||||||
|
fail() { printf 'Installation failed at %s: %s\n' "$step" "$*" >&2; exit 1; }
|
||||||
|
trap 'printf "Installation failed at %s (line %s). Existing data and generated material were retained.\n" "$step" "$LINENO" >&2' ERR
|
||||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
|
if [[ $(uname -s) == Darwin ]]; then exec bash "$script_dir/install-macos.sh" "$@"; fi
|
||||||
source "$script_dir/services.sh"
|
source "$script_dir/services.sh"
|
||||||
|
source "$script_dir/bootstrap.sh"
|
||||||
bundle=$script_dir
|
bundle=$script_dir
|
||||||
requested=
|
requested=
|
||||||
config_dir=
|
|
||||||
target_root=/
|
target_root=/
|
||||||
dotnet_path=/usr/bin/dotnet
|
dotnet_path=/usr/bin/dotnet
|
||||||
start=false
|
host=localhost
|
||||||
migrate=false
|
topology=
|
||||||
|
deployment=
|
||||||
|
external_certificates=
|
||||||
|
admin_file=
|
||||||
|
prepare_only=false
|
||||||
|
defer_verification=false
|
||||||
while [[ $# -gt 0 ]]; do
|
while [[ $# -gt 0 ]]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
--bundle) [[ $# -gt 1 ]] || fail 'Missing bundle directory.'; bundle=$2; shift 2;;
|
--bundle|--services|--root|--dotnet|--host|--topology|--deployment|--certificates|--postgres-admin-file)
|
||||||
--services) [[ $# -gt 1 ]] || fail 'Missing services.'; requested=$2; shift 2;;
|
[[ $# -gt 1 ]] || fail "Missing value for $1."
|
||||||
--config-dir) [[ $# -gt 1 ]] || fail 'Missing configuration directory.'; config_dir=$2; shift 2;;
|
case "$1" in --bundle) bundle=$2;; --services) requested=$2;; --root) target_root=$2;; --dotnet) dotnet_path=$2;;
|
||||||
--root) [[ $# -gt 1 ]] || fail 'Missing staging root.'; target_root=$2; shift 2;;
|
--host) host=$2;; --topology) topology=$2;; --deployment) deployment=$2;; --certificates) external_certificates=$2;;
|
||||||
--dotnet) [[ $# -gt 1 ]] || fail 'Missing runtime path.'; dotnet_path=$2; shift 2;;
|
--postgres-admin-file) admin_file=$2;; esac
|
||||||
--start) start=true; shift;;
|
shift 2;;
|
||||||
--migrate) migrate=true; shift;;
|
--prepare-only) prepare_only=true; shift;;
|
||||||
--help) printf '%s\n' 'Usage: bash install.sh --services all|NAME[,NAME] --config-dir DIRECTORY [--bundle DIRECTORY] [--dotnet /absolute/path] [--migrate] [--start]' 'Optional --root DIRECTORY stages an offline filesystem image; it does not start or verify services.' 'Names: api-gateway,patient-profile,observation,insights,health-overview' 'Existing installations/configuration are never overwritten. Databases and certificates must be provisioned externally.'; exit 0;;
|
--defer-topology-check) defer_verification=true; shift;;
|
||||||
|
--help) printf '%s\n' 'Usage: bash install.sh --services all|NAME[,NAME] [--host DNS_OR_IP] [--topology topology.json] [--deployment generated-directory]' 'Provisioning installs runtime/PostgreSQL as needed and generates credentials, HTTPS, configuration, migrations and running systemd services.' 'Optional --root DIRECTORY stages generated files offline; --dotnet PATH selects the available runtime.' '--prepare-only generates a deployment for automatic distribution with distribute.sh. --certificates DIR accepts external certificates.'; exit 0;;
|
||||||
*) fail "Unknown argument: $1";;
|
*) fail "Unknown argument: $1";;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
[[ $(uname -s) == Linux ]] || fail 'Only Linux is supported.'
|
|
||||||
select_services "$requested"
|
select_services "$requested"
|
||||||
[[ -d "$bundle" && -d "$config_dir" ]] || fail 'Bundle and prepared configuration directories are required.'
|
[[ $(uname -s) == Linux ]] || fail 'Only Linux is supported.'
|
||||||
[[ "$target_root" == /* && "$target_root" != *$'\n'* && "$target_root" != *'/../'* && "$target_root" != */.. ]] || fail 'Root must be an absolute filesystem path without parent traversal.'
|
[[ "$target_root" == /* && "$target_root" != *$'\n'* ]] || fail 'Root must be an absolute path.'
|
||||||
[[ "$dotnet_path" =~ ^/[A-Za-z0-9_./+-]+$ ]] || fail 'Runtime must be an absolute path using letters, digits, slash, dot, underscore, plus or hyphen.'
|
[[ "$dotnet_path" =~ ^/[A-Za-z0-9_./+-]+$ ]] || fail 'Runtime path is invalid.'
|
||||||
target_root=$(realpath -m -- "$target_root")
|
target_root=$(realpath -m -- "$target_root")
|
||||||
if [[ "$target_root" != / ]]; then
|
step=preflight
|
||||||
[[ "$start" == false && "$migrate" == false ]] || fail 'Cannot start services or migrate databases in an offline staging root.'
|
|
||||||
else
|
|
||||||
[[ $EUID -eq 0 ]] || fail 'Live system installation requires root.'
|
|
||||||
[[ -d /run/systemd/system ]] || fail 'A running systemd system manager is required.'
|
|
||||||
[[ -x "$dotnet_path" ]] || fail 'Install the .NET 10 ASP.NET Core runtime first.'
|
|
||||||
runtime_list=$("$dotnet_path" --list-runtimes)
|
|
||||||
[[ "$runtime_list" == *'Microsoft.AspNetCore.App 10.'* ]] || fail 'The .NET 10 ASP.NET Core runtime is required.'
|
|
||||||
fi
|
|
||||||
# Preflight all selected services before copying anything or registering units.
|
|
||||||
for service in "${selected_services[@]}"; do
|
for service in "${selected_services[@]}"; do
|
||||||
assembly=$(assembly_for "$service")
|
assembly=$(assembly_for "$service")
|
||||||
[[ -f "$bundle/services/$service/$assembly.dll" && -f "$bundle/services/$service/$assembly.runtimeconfig.json" && -f "$bundle/services/$service/$assembly.deps.json" ]] || fail "Missing published application: $service"
|
[[ -f "$bundle/services/$service/$assembly.dll" && -f "$bundle/systemd/healthapp-$service.service" ]] || fail "Missing release payload: $service"
|
||||||
[[ -f "$bundle/systemd/healthapp-$service.service" && -f "$config_dir/$service.env" ]] || fail "Missing unit or prepared configuration: $service"
|
[[ ! -e "$target_root/opt/healthapp/$service" && ! -e "$target_root/etc/healthapp/$service" && ! -e "$target_root/etc/systemd/system/healthapp-$service.service" ]] || fail "Already installed: $service; existing configuration was not changed."
|
||||||
[[ ! -e "$target_root/opt/healthapp/$service" && ! -e "$target_root/etc/healthapp/$service.env" && ! -e "$target_root/etc/systemd/system/healthapp-$service.service" ]] || fail "Already installed or configured: $service. Existing files were not changed."
|
|
||||||
if grep -q 'REPLACE_ME\|REPLACE_WITH' "$config_dir/$service.env"; then fail "Replace example configuration placeholders for $service."; fi
|
|
||||||
done
|
done
|
||||||
if [[ "$target_root" == / ]]; then
|
[[ -f "$bundle/provisioner/HealthApp.Provisioning.dll" ]] || fail 'Missing release provisioning utility.'
|
||||||
getent group healthapp >/dev/null || groupadd --system healthapp
|
persistence=false
|
||||||
id healthapp >/dev/null 2>&1 || useradd --system --gid healthapp --home-dir /nonexistent --shell /usr/sbin/nologin healthapp
|
for service in "${selected_services[@]}"; do case "$service" in patient-profile|observation) persistence=true;; esac; done
|
||||||
|
if [[ "$target_root" == / && "$prepare_only" == false ]]; then
|
||||||
|
[[ $EUID -eq 0 && -d /run/systemd/system ]] || fail 'Live installation requires root and a running systemd manager.'
|
||||||
|
source /etc/os-release
|
||||||
|
ensure_dependencies "$ID" "$VERSION_ID" "$dotnet_path" "$persistence"
|
||||||
|
else
|
||||||
|
[[ -x "$dotnet_path" ]] || fail 'Offline preparation needs an available .NET 10 runtime.'
|
||||||
fi
|
fi
|
||||||
install -d -m 0755 -- "$target_root/opt/healthapp" "$target_root/etc/systemd/system"
|
provision=("$dotnet_path" "$bundle/provisioner/HealthApp.Provisioning.dll")
|
||||||
install -d -m 0750 -- "$target_root/etc/healthapp"
|
step='generate deployment credentials and HTTPS certificates'
|
||||||
if [[ "$target_root" == / ]]; then chgrp healthapp -- "$target_root/etc/healthapp"; fi
|
if [[ -z "$deployment" || ! -f "$deployment/deployment.json" ]]; then
|
||||||
for service in "${selected_services[@]}"; do
|
[[ -n "$deployment" ]] || deployment="$target_root/var/lib/healthapp-installation/deployment"
|
||||||
install -d -m 0755 -- "$target_root/opt/healthapp/$service"
|
arguments=(prepare --output "$deployment" --host "$host")
|
||||||
cp -R -- "$bundle/services/$service/." "$target_root/opt/healthapp/$service/"
|
[[ -z "$topology" ]] || arguments+=(--topology "$topology")
|
||||||
chmod -R a+rX,go-w -- "$target_root/opt/healthapp/$service"
|
[[ -z "$external_certificates" ]] || arguments+=(--certificates "$external_certificates")
|
||||||
install -m 0600 -- "$config_dir/$service.env" "$target_root/etc/healthapp/$service.env"
|
"${provision[@]}" "${arguments[@]}"
|
||||||
sed "s|ExecStart=/usr/bin/dotnet |ExecStart=$dotnet_path |" "$bundle/systemd/healthapp-$service.service" > "$target_root/etc/systemd/system/healthapp-$service.service"
|
fi
|
||||||
chmod 0644 -- "$target_root/etc/systemd/system/healthapp-$service.service"
|
if [[ "$prepare_only" == true ]]; then
|
||||||
printf 'Installed %s\n' "$service"
|
printf 'Deployment material generated in %s. It contains secrets; distribute.sh installs the scoped material on each host.\n' "$deployment"
|
||||||
done
|
exit 0
|
||||||
|
fi
|
||||||
|
install -d -m 0755 "$target_root/opt/healthapp" "$target_root/etc/systemd/system"
|
||||||
|
install -d -m 0711 "$target_root/etc/healthapp"
|
||||||
|
install -d -m 0755 "$target_root/usr/local/share/ca-certificates"
|
||||||
|
ca_id=$(sha256sum "$deployment/healthapp-ca.crt" | cut -c1-16)
|
||||||
|
install -m 0644 "$deployment/healthapp-ca.crt" "$target_root/usr/local/share/ca-certificates/healthapp-prototype-$ca_id.crt"
|
||||||
if [[ "$target_root" == / ]]; then
|
if [[ "$target_root" == / ]]; then
|
||||||
|
step='install local HTTPS trust'
|
||||||
|
update-ca-certificates
|
||||||
|
fi
|
||||||
|
for service in "${selected_services[@]}"; do
|
||||||
|
step="configure $service"
|
||||||
|
if [[ "$target_root" == / ]]; then
|
||||||
|
user="healthapp-$service"
|
||||||
|
getent group "$user" >/dev/null || groupadd --system "$user"
|
||||||
|
id "$user" >/dev/null 2>&1 || useradd --system --gid "$user" --home-dir /nonexistent --shell /usr/sbin/nologin "$user"
|
||||||
|
fi
|
||||||
|
if [[ "$service" == patient-profile || "$service" == observation ]]; then
|
||||||
|
if [[ "$target_root" == / || -n "$admin_file" ]]; then
|
||||||
|
step="create dedicated database and role for $service"
|
||||||
|
args=(database --service-dir "$deployment/$service")
|
||||||
|
[[ -z "$admin_file" ]] || args+=(--admin-file "$admin_file")
|
||||||
|
"${provision[@]}" "${args[@]}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
"${provision[@]}" configure --service-dir "$deployment/$service" --root "$target_root"
|
||||||
|
install -d -m 0755 "$target_root/opt/healthapp/$service"
|
||||||
|
cp -R "$bundle/services/$service/." "$target_root/opt/healthapp/$service/"
|
||||||
|
chmod -R a+rX,go-w "$target_root/opt/healthapp/$service"
|
||||||
|
sed -e "s|ExecStart=/usr/bin/dotnet |ExecStart=$dotnet_path |" \
|
||||||
|
-e "s|EnvironmentFile=/etc/healthapp/$service.env|EnvironmentFile=/etc/healthapp/$service/service.env|" \
|
||||||
|
-e "s/^User=healthapp$/User=healthapp-$service/" -e "s/^Group=healthapp$/Group=healthapp-$service/" \
|
||||||
|
"$bundle/systemd/healthapp-$service.service" > "$target_root/etc/systemd/system/healthapp-$service.service"
|
||||||
|
chmod 0644 "$target_root/etc/systemd/system/healthapp-$service.service"
|
||||||
|
if [[ "$target_root" == / ]]; then
|
||||||
|
chmod 0750 "/etc/healthapp/$service"
|
||||||
|
chgrp "$user" "/etc/healthapp/$service" "/etc/healthapp/$service/service.pfx"
|
||||||
|
chmod 0640 "/etc/healthapp/$service/service.pfx"
|
||||||
|
fi
|
||||||
|
printf 'Installed selected application: %s\n' "$service"
|
||||||
|
done
|
||||||
|
if [[ "$target_root" != / ]]; then
|
||||||
|
printf 'Offline deployment staged in %s. Package installation, systemd startup and live verification were not performed.\n' "$target_root"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
step='register independent systemd services'
|
||||||
systemctl daemon-reload
|
systemctl daemon-reload
|
||||||
if [[ "$migrate" == true ]]; then
|
|
||||||
for service in "${selected_services[@]}"; do
|
for service in "${selected_services[@]}"; do
|
||||||
case "$service" in patient-profile|observation)
|
case "$service" in patient-profile|observation)
|
||||||
|
step="migrate $service database"
|
||||||
assembly=$(assembly_for "$service")
|
assembly=$(assembly_for "$service")
|
||||||
systemd-run --quiet --wait --pipe --collect --unit="healthapp-$service-migrate" \
|
systemd-run --quiet --wait --pipe --collect --unit="healthapp-$service-migrate" \
|
||||||
--property=User=healthapp --property=Group=healthapp \
|
--property="User=healthapp-$service" --property="Group=healthapp-$service" \
|
||||||
--property="EnvironmentFile=/etc/healthapp/$service.env" \
|
--property="EnvironmentFile=/etc/healthapp/$service/service.env" --property="WorkingDirectory=/opt/healthapp/$service" \
|
||||||
--property="WorkingDirectory=/opt/healthapp/$service" \
|
"$dotnet_path" "/opt/healthapp/$service/$assembly.dll" --migrate;;
|
||||||
"$dotnet_path" "/opt/healthapp/$service/$assembly.dll" --migrate
|
|
||||||
;;
|
|
||||||
esac
|
esac
|
||||||
|
|
||||||
done
|
done
|
||||||
fi
|
systemctl daemon-reload
|
||||||
for service in "${selected_services[@]}"; do
|
for service in "${selected_services[@]}"; do
|
||||||
systemctl enable "healthapp-$service.service"
|
step="enable/start $service"
|
||||||
if [[ "$start" == true ]]; then systemctl start "healthapp-$service.service"; fi
|
systemctl enable --now "healthapp-$service.service"
|
||||||
done
|
done
|
||||||
printf '%s\n' 'Installation complete. Run verify.sh with the selected services and HTTP probe configuration.'
|
step='verify startup and HTTPS listening'
|
||||||
|
pids=()
|
||||||
|
for service in "${selected_services[@]}"; do
|
||||||
|
systemctl is-active --quiet "healthapp-$service.service" || fail "$service is not running."
|
||||||
|
pid=$(systemctl show --property MainPID --value "healthapp-$service.service")
|
||||||
|
[[ "$pid" =~ ^[1-9][0-9]*$ && -d "/proc/$pid" ]] || fail "$service has no running process."
|
||||||
|
for peer in "${pids[@]}"; do [[ "$pid" != "$peer" ]] || fail 'Selected services share a process.'; done
|
||||||
|
pids+=("$pid")
|
||||||
|
done
|
||||||
|
"${provision[@]}" verify-startup --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")"
|
||||||
|
if [[ "$defer_verification" == true ]]; then
|
||||||
|
printf '%s\n' 'Node started. Distributed topology verification is pending until all nodes have started.'
|
||||||
else
|
else
|
||||||
printf '%s\n' 'Offline files staged. Provision the runtime/service account and enable units on the target host before verification.'
|
step='verify configured dependencies and representative functionality'
|
||||||
|
arguments=(verify --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")")
|
||||||
|
[[ "$requested" != all ]] || arguments+=(--complete true)
|
||||||
|
"${provision[@]}" "${arguments[@]}"
|
||||||
|
printf 'Installation and topology verification completed. Account credentials: %s/accounts.json\n' "$deployment"
|
||||||
fi
|
fi
|
||||||
@@ -10,11 +10,11 @@ select_services() {
|
|||||||
fi
|
fi
|
||||||
IFS=',' read -r -a selected_services <<< "$requested"
|
IFS=',' read -r -a selected_services <<< "$requested"
|
||||||
[[ ${#selected_services[@]} -gt 0 && "$requested" != *, ]] || fail "Select services by comma-separated name or all."
|
[[ ${#selected_services[@]} -gt 0 && "$requested" != *, ]] || fail "Select services by comma-separated name or all."
|
||||||
local -A seen=()
|
local seen=,
|
||||||
for item in "${selected_services[@]}"; do
|
for item in "${selected_services[@]}"; do
|
||||||
case "$item" in api-gateway|patient-profile|observation|insights|health-overview) ;; *) fail "Unknown service: $item" ;; esac
|
case "$item" in api-gateway|patient-profile|observation|insights|health-overview) ;; *) fail "Unknown service: $item" ;; esac
|
||||||
[[ ! ${seen[$item]+exists} ]] || fail "Repeated service: $item"
|
case "$seen" in *,$item,*) fail "Repeated service: $item";; esac
|
||||||
seen[$item]=1
|
seen+="$item,"
|
||||||
done
|
done
|
||||||
}
|
}
|
||||||
assembly_for() {
|
assembly_for() {
|
||||||
|
|||||||
+16
-35
@@ -1,50 +1,31 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
fail() { printf 'Error: %s\n' "$*" >&2; exit 1; }
|
|
||||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||||
|
fail() { printf 'Verification failed: %s\n' "$*" >&2; exit 1; }
|
||||||
source "$script_dir/services.sh"
|
source "$script_dir/services.sh"
|
||||||
requested=
|
requested=
|
||||||
probe_dir=
|
deployment=/var/lib/healthapp-installation/deployment
|
||||||
cycle=false
|
dotnet_path=/usr/bin/dotnet
|
||||||
while [[ $# -gt 0 ]]; do
|
while [[ $# -gt 0 ]]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
--services) [[ $# -gt 1 ]] || fail 'Missing services.'; requested=$2; shift 2;;
|
--services|--deployment|--dotnet)
|
||||||
--probe-dir) [[ $# -gt 1 ]] || fail 'Missing probe directory.'; probe_dir=$2; shift 2;;
|
[[ $# -gt 1 ]] || fail 'Missing argument.'
|
||||||
--cycle) cycle=true; shift;;
|
case "$1" in --services) requested=$2;; --deployment) deployment=$2;; --dotnet) dotnet_path=$2;; esac
|
||||||
--help) printf '%s\n' 'Usage: bash verify.sh --services all|NAME[,NAME] --probe-dir DIRECTORY [--cycle]' 'Each NAME.curl contains curl configuration for a configured HTTPS endpoint and the required credentials.' 'Probes must return HTTP 200 (no redirects). --cycle explicitly permits stop/start/restart of each selected service.'; exit 0;;
|
shift 2;;
|
||||||
|
--help) printf '%s\n' 'Usage: bash verify.sh --services all|NAME[,NAME] [--deployment GENERATED_DIRECTORY] [--dotnet PATH]' 'Checks systemd processes, HTTPS, dedicated databases, service credentials and the complete-system synthetic workflow.'; exit 0;;
|
||||||
*) fail "Unknown argument: $1";;
|
*) fail "Unknown argument: $1";;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
select_services "$requested"
|
select_services "$requested"
|
||||||
[[ -d "$probe_dir" ]] || fail 'Provide service-specific curl probe configuration.'
|
|
||||||
command -v curl >/dev/null || fail 'curl is required for network verification.'
|
|
||||||
[[ -d /run/systemd/system ]] || fail 'Verification requires a running systemd system manager.'
|
|
||||||
for service in "${selected_services[@]}"; do
|
|
||||||
[[ -f "$probe_dir/$service.curl" ]] || fail "Missing probe configuration: $service"
|
|
||||||
done
|
|
||||||
pids=()
|
pids=()
|
||||||
for service in "${selected_services[@]}"; do
|
for service in "${selected_services[@]}"; do
|
||||||
unit="healthapp-$service.service"
|
systemctl is-active --quiet "healthapp-$service.service" || fail "$service is not running."
|
||||||
systemctl is-active --quiet "$unit" || fail "$service is not active."
|
pid=$(systemctl show --property MainPID --value "healthapp-$service.service")
|
||||||
pid=$(systemctl show --property MainPID --value "$unit")
|
[[ "$pid" =~ ^[1-9][0-9]*$ && -d "/proc/$pid" ]] || fail "$service has no process."
|
||||||
[[ "$pid" =~ ^[1-9][0-9]*$ && -d "/proc/$pid" ]] || fail "$service has no running process."
|
for peer in "${pids[@]}"; do [[ "$pid" != "$peer" ]] || fail 'Services share a process.'; done
|
||||||
for other in "${pids[@]}"; do [[ "$pid" != "$other" ]] || fail 'Services share a process.'; done
|
|
||||||
pids+=("$pid")
|
pids+=("$pid")
|
||||||
if [[ "$cycle" == true ]]; then
|
|
||||||
# Confirm stopping this service does not directly stop another selected unit.
|
|
||||||
systemctl stop "$unit"
|
|
||||||
systemctl is-active --quiet "$unit" && fail "$service did not stop."
|
|
||||||
for peer in "${selected_services[@]}"; do
|
|
||||||
[[ "$peer" == "$service" ]] || systemctl is-active --quiet "healthapp-$peer.service" || fail "Stopping $service stopped $peer."
|
|
||||||
done
|
done
|
||||||
systemctl start "$unit"
|
args=(verify --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")")
|
||||||
systemctl restart "$unit"
|
[[ "$requested" != all ]] || args+=(--complete true)
|
||||||
systemctl is-active --quiet "$unit" || fail "$service did not restart."
|
"$dotnet_path" "$script_dir/provisioner/HealthApp.Provisioning.dll" "${args[@]}"
|
||||||
fi
|
printf '%s\n' 'Installation verification passed.'
|
||||||
# curl settings are data, not sourced shell code; suppress bodies and credentials.
|
|
||||||
status=$(curl --config "$probe_dir/$service.curl" --silent --output /dev/null --write-out '%{http_code}' --max-time 15 --max-redirs 0 --retry 5 --retry-delay 1 --retry-connrefused) || fail "Network probe failed for $service."
|
|
||||||
[[ "$status" == 200 ]] || fail "Unexpected HTTP status for $service: $status"
|
|
||||||
systemctl is-active --quiet "$unit" || fail "$service exited during its network probe."
|
|
||||||
printf 'Verified process and configured network probe: %s\n' "$service"
|
|
||||||
done
|
|
||||||
printf '%s\n' 'Verification passed. For a complete system also run the representative API workflow documented in INSTALLATION.md.'
|
|
||||||
@@ -4,4 +4,7 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -12,6 +12,7 @@ public class Program
|
|||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-api-gateway");
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
builder.Services.AddProblemDetails();
|
builder.Services.AddProblemDetails();
|
||||||
builder.Services.AddSingleton<PrototypeAccounts>();
|
builder.Services.AddSingleton<PrototypeAccounts>();
|
||||||
|
|||||||
@@ -4,4 +4,7 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -10,6 +10,7 @@ public class Program
|
|||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-health-overview");
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
builder.Services.AddProblemDetails();
|
builder.Services.AddProblemDetails();
|
||||||
builder.Services.AddScoped<HealthOverviewApplicationService>();
|
builder.Services.AddScoped<HealthOverviewApplicationService>();
|
||||||
|
|||||||
@@ -4,4 +4,7 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -11,6 +11,7 @@ public class Program
|
|||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-insights");
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
builder.Services.AddProblemDetails();
|
builder.Services.AddProblemDetails();
|
||||||
builder.Services.AddScoped<InsightsApplicationService>();
|
builder.Services.AddScoped<InsightsApplicationService>();
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ public class Program
|
|||||||
public static async Task Main(string[] args)
|
public static async Task Main(string[] args)
|
||||||
{
|
{
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-observation");
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
builder.Services.AddProblemDetails();
|
builder.Services.AddProblemDetails();
|
||||||
builder.Services.AddDbContext<ObservationDbContext>((services, options) =>
|
builder.Services.AddDbContext<ObservationDbContext>((services, options) =>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ public class Program
|
|||||||
public static async Task Main(string[] args)
|
public static async Task Main(string[] args)
|
||||||
{
|
{
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-patient-profile");
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
builder.Services.AddProblemDetails();
|
builder.Services.AddProblemDetails();
|
||||||
builder.Services.AddDbContext<PatientDbContext>((services, options) =>
|
builder.Services.AddDbContext<PatientDbContext>((services, options) =>
|
||||||
|
|||||||
+13
-13
@@ -295,21 +295,21 @@ US-04 tests use real HTTP between the hosts and separate temporary patient and o
|
|||||||
|
|
||||||
Dependencies: Npgsql's EF Core PostgreSQL provider supplies persistence; EF Core Relational is pinned to the same patch as EF Core Design to keep runtime/tooling versions aligned; EF Core Design supports migration maintenance. xUnit, its Visual Studio runner, Microsoft.NET.Test.Sdk, and ASP.NET Core MVC Testing are used only for automated tests. The gateway uses the platform's HttpClient and has no extra package dependency.
|
Dependencies: Npgsql's EF Core PostgreSQL provider supplies persistence; EF Core Relational is pinned to the same patch as EF Core Design to keep runtime/tooling versions aligned; EF Core Design supports migration maintenance. xUnit, its Visual Studio runner, Microsoft.NET.Test.Sdk, and ASP.NET Core MVC Testing are used only for automated tests. The gateway uses the platform's HttpClient and has no extra package dependency.
|
||||||
|
|
||||||
## Linux installer (US-16)
|
## Provisioning installer (US-16)
|
||||||
|
|
||||||
Use `bash deploy/build-release.sh --output NEW_DIRECTORY` to create an independent
|
Build a portable release using `bash deploy/build-release.sh --output NEW_DIRECTORY`.
|
||||||
release bundle, then its `install.sh --services all|NAME[,NAME] --config-dir DIRECTORY`
|
A normal supported Linux installation is `sudo bash install.sh --services all --host
|
||||||
on a Linux/systemd host. Single, subset and complete installs retain separate
|
DNS_OR_IP`; it provisions missing runtime/PostgreSQL dependencies, separate databases
|
||||||
applications, configurations and units. Optional `--migrate` and `--start` explicitly
|
and roles, generated service/account credentials, HTTPS/trust, independent configuration,
|
||||||
apply selected service migrations/startup. Existing installations are never overwritten.
|
migrations, service registration/startup and installation verification. No prepared env
|
||||||
See [INSTALLATION.md](../deploy/INSTALLATION.md) for prerequisites, service selections,
|
files, service passwords or prototype certificates are required.
|
||||||
external configuration, offline staging, verification and independent management.
|
|
||||||
|
|
||||||
US-16 adds xUnit deployment tests that launch installed executables as separate OS
|
Shared C# provisioning also generates Windows/macOS configuration. Native adapters use
|
||||||
processes and exercise the authenticated complete-system workflow and independent
|
Windows Services or launchd without changing application binaries/service boundaries.
|
||||||
stop/restart. Live systemd/HTTPS verification uses the supplied target-host verifier.
|
See [INSTALLATION.md](../deploy/INSTALLATION.md) for supported hosts, native commands,
|
||||||
The earlier test-alignment suggestions remain deferred except where US-16 itself
|
automatic SSH topology distribution, generated credentials and test evidence/limitations.
|
||||||
requires independent-process installation verification.
|
The existing `deploy/*.env.example` files remain useful for advanced/manual development;
|
||||||
|
they are no longer prerequisites for the normal installer.
|
||||||
|
|
||||||
## Linux deployment
|
## Linux deployment
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
using System.Runtime.Versioning;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Deployment.AcceptanceTests;
|
||||||
|
|
||||||
|
[SupportedOSPlatform("linux")]
|
||||||
|
public sealed class BootstrapTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("ubuntu", "24.04", false, false, false)]
|
||||||
|
[InlineData("ubuntu", "24.04", true, true, false)]
|
||||||
|
[InlineData("ubuntu", "24.04", true, true, true)]
|
||||||
|
[InlineData("debian", "12", true, false, false)]
|
||||||
|
[InlineData("debian", "13", false, true, false)]
|
||||||
|
public async Task Package_provisioning_detects_runtime_and_postgresql_and_installs_only_needed_dependencies(
|
||||||
|
string distribution, string version, bool runtimeAvailable, bool databaseRequired, bool databaseAvailable)
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "healthapp-bootstrap-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var log = Path.Combine(directory, "commands");
|
||||||
|
await File.WriteAllTextAsync(log, "");
|
||||||
|
var installed = Path.Combine(directory, "runtime-installed");
|
||||||
|
var script = Path.Combine(directory, "test.sh");
|
||||||
|
await File.WriteAllTextAsync(script, """
|
||||||
|
set -euo pipefail
|
||||||
|
fail() { exit 1; }
|
||||||
|
runtime() { if [[ "$RUNTIME_PRESENT" == true || -f "$RUNTIME_INSTALLED" ]]; then printf '%s\n' 'Microsoft.AspNetCore.App 10.0.12 [runtime]'; else return 1; fi; }
|
||||||
|
apt-get() { printf '%s\n' "apt-get $*" >> "$COMMAND_LOG"; if [[ "$*" == *aspnetcore-runtime-10.0* ]]; then touch "$RUNTIME_INSTALLED"; fi; }
|
||||||
|
curl() { printf '%s\n' "curl $*" >> "$COMMAND_LOG"; }
|
||||||
|
update-ca-certificates() { :; }
|
||||||
|
dpkg() { printf '%s\n' "dpkg $*" >> "$COMMAND_LOG"; }
|
||||||
|
pg_isready() { [[ -f "$DATABASE_READY" ]]; }
|
||||||
|
systemctl() { printf '%s\n' "systemctl $*" >> "$COMMAND_LOG"; touch "$DATABASE_READY"; }
|
||||||
|
source "$BOOTSTRAP"
|
||||||
|
ensure_dependencies "$DISTRO" "$VERSION" /bin/true "$DATABASE_REQUIRED"
|
||||||
|
""");
|
||||||
|
// Runtime is an executable stub; installed packages switch its simulated inventory.
|
||||||
|
var runtime = Path.Combine(directory, "dotnet");
|
||||||
|
await File.WriteAllTextAsync(runtime, "#!/bin/bash\nif [[ \"$RUNTIME_PRESENT\" == true || -f \"$RUNTIME_INSTALLED\" ]]; then printf '%s\\n' 'Microsoft.AspNetCore.App 10.0.12 [runtime]'; else exit 1; fi\n");
|
||||||
|
File.SetUnixFileMode(runtime, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||||
|
var body = (await File.ReadAllTextAsync(script)).Replace("/bin/true", "\"$RUNTIME_EXECUTABLE\"");
|
||||||
|
await File.WriteAllTextAsync(script, body);
|
||||||
|
var environment = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["COMMAND_LOG"] = log, ["RUNTIME_INSTALLED"] = installed,
|
||||||
|
["RUNTIME_PRESENT"] = runtimeAvailable ? "true" : "false", ["RUNTIME_EXECUTABLE"] = runtime,
|
||||||
|
["DATABASE_READY"] = Path.Combine(directory, "pg-ready"), ["DATABASE_REQUIRED"] = databaseRequired ? "true" : "false",
|
||||||
|
["BOOTSTRAP"] = Path.Combine(DeploymentFixture.Repository, "deploy/installer/bootstrap.sh"), ["DISTRO"] = distribution, ["VERSION"] = version
|
||||||
|
};
|
||||||
|
if (databaseAvailable) await File.WriteAllTextAsync(environment["DATABASE_READY"], "ready");
|
||||||
|
var result = await DeploymentFixture.Run("bash", [script], environment);
|
||||||
|
Assert.Equal(0, result.Code);
|
||||||
|
var commands = await File.ReadAllTextAsync(log);
|
||||||
|
Assert.Equal(!runtimeAvailable, commands.Contains("install -y aspnetcore-runtime-10.0"));
|
||||||
|
Assert.Equal(databaseRequired && !databaseAvailable, commands.Contains("install -y postgresql"));
|
||||||
|
Assert.Equal(databaseRequired && !databaseAvailable, commands.Contains("systemctl enable --now postgresql"));
|
||||||
|
Assert.Equal(!runtimeAvailable && distribution == "debian", commands.Contains("packages.microsoft.com/config/debian/" + version));
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,12 +2,16 @@ using System.Diagnostics;
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using Microsoft.AspNetCore.Identity;
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Runtime.Versioning;
|
||||||
using Npgsql;
|
using Npgsql;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace Deployment.AcceptanceTests;
|
namespace Deployment.AcceptanceTests;
|
||||||
|
|
||||||
|
[SupportedOSPlatform("linux")]
|
||||||
public sealed class DeploymentFixture : IAsyncLifetime
|
public sealed class DeploymentFixture : IAsyncLifetime
|
||||||
{
|
{
|
||||||
public static readonly string[] Services = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"];
|
public static readonly string[] Services = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"];
|
||||||
@@ -29,92 +33,100 @@ public sealed class DeploymentFixture : IAsyncLifetime
|
|||||||
Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
|
Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
|
||||||
public string Temporary { get; } = Path.Combine(Path.GetTempPath(), "healthapp-us16-" + Guid.NewGuid().ToString("N"));
|
public string Temporary { get; } = Path.Combine(Path.GetTempPath(), "healthapp-us16-" + Guid.NewGuid().ToString("N"));
|
||||||
public string Bundle => Path.Combine(Temporary, "release");
|
public string Bundle => Path.Combine(Temporary, "release");
|
||||||
public string Configuration => Path.Combine(Temporary, "configuration");
|
public string Deployment => Path.Combine(Temporary, "deployment");
|
||||||
|
public string AdminFile => Path.Combine(Temporary, "admin.connection");
|
||||||
public string Root => Path.Combine(Temporary, "installed");
|
public string Root => Path.Combine(Temporary, "installed");
|
||||||
public Dictionary<string, string> Urls { get; } = new();
|
public Dictionary<string, string> Urls { get; } = new();
|
||||||
public Dictionary<string, Dictionary<string, string>> Settings { get; } = new();
|
public Dictionary<string, Dictionary<string, string>> Settings { get; } = new();
|
||||||
public Dictionary<string, Process> Processes { get; } = new();
|
public Dictionary<string, Process> Processes { get; } = new();
|
||||||
private readonly List<string> databases = [];
|
private readonly List<string> databases = [];
|
||||||
public string Admin { get; private set; } = "";
|
public string Admin { get; private set; } = "";
|
||||||
public const string Password = "synthetic-deployment-password";
|
public string Password { get; private set; } = "";
|
||||||
|
private readonly List<string> roles = [];
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
public async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
Directory.CreateDirectory(Temporary);
|
Directory.CreateDirectory(Temporary);
|
||||||
Directory.CreateDirectory(Configuration);
|
|
||||||
Admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION") ?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION is required.");
|
Admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION") ?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION is required.");
|
||||||
var release = await Run("bash", [Path.Combine(Repository, "deploy/build-release.sh"), "--output", Bundle],
|
var release = await Run("bash", [Path.Combine(Repository, "deploy/build-release.sh"), "--output", Bundle],
|
||||||
new() { ["HEALTHAPP_DOTNET"] = Dotnet });
|
new() { ["HEALTHAPP_DOTNET"] = Dotnet });
|
||||||
Assert.True(release.Code == 0, "Release publishing failed; no secret configuration was used.");
|
Assert.True(release.Code == 0, release.Output);
|
||||||
|
var ports = new Dictionary<string, int>();
|
||||||
foreach (var service in Services)
|
foreach (var service in Services)
|
||||||
{
|
{
|
||||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||||
listener.Start();
|
listener.Start();
|
||||||
Urls[service] = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/";
|
ports[service] = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||||
Settings[service] = new()
|
|
||||||
{
|
|
||||||
["ASPNETCORE_ENVIRONMENT"] = "Development", ["ASPNETCORE_URLS"] = Urls[service],
|
|
||||||
["InternalAccess__GatewayKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)),
|
|
||||||
["Logging__LogLevel__Default"] = "Warning", ["Logging__LogLevel__Microsoft.AspNetCore"] = "Warning"
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
foreach (var service in new[] { "patient-profile", "observation" })
|
var hosts = Services.Select((name, index) => (name, index)).ToDictionary(p => p.name, p => "127.0.0." + (p.index + 1));
|
||||||
{
|
var topology = Path.Combine(Temporary, "topology.json");
|
||||||
var database = "us16_" + Guid.NewGuid().ToString("N");
|
await File.WriteAllTextAsync(topology, JsonSerializer.Serialize(new { hosts, ports }));
|
||||||
await using var connection = new NpgsqlConnection(Admin);
|
var prepared = await Provision("prepare", "--output", Deployment, "--topology", topology);
|
||||||
await connection.OpenAsync();
|
Assert.True(prepared.Code == 0, prepared.Output);
|
||||||
await using var create = new NpgsqlCommand("CREATE DATABASE " + database, connection);
|
await File.WriteAllTextAsync(AdminFile, Admin);
|
||||||
await create.ExecuteNonQueryAsync();
|
File.SetUnixFileMode(AdminFile, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||||
databases.Add(database);
|
var installation = await Run("bash", [Path.Combine(Bundle, "install.sh"), "--services", "all", "--deployment", Deployment,
|
||||||
Settings[service][service == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase"] =
|
"--postgres-admin-file", AdminFile, "--root", Root, "--dotnet", Dotnet]);
|
||||||
new NpgsqlConnectionStringBuilder(Admin) { Database = database }.ConnectionString;
|
|
||||||
}
|
|
||||||
var names = new Dictionary<string, string> { ["patient-profile"] = "PatientProfile", ["observation"] = "Observation",
|
|
||||||
["insights"] = "Insights", ["health-overview"] = "HealthOverview" };
|
|
||||||
foreach (var (service, name) in names)
|
|
||||||
{
|
|
||||||
Settings["api-gateway"][$"Services__{name}__BaseUrl"] = Urls[service];
|
|
||||||
Settings["api-gateway"][$"Services__{name}__Key"] = Settings[service]["InternalAccess__GatewayKey"];
|
|
||||||
if (service == "patient-profile") continue;
|
|
||||||
var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
|
||||||
Settings["api-gateway"][$"InternalAccess__{name}__Key"] = key;
|
|
||||||
Settings[service]["Services__ApiGateway__Key"] = key;
|
|
||||||
Settings[service]["Services__ApiGateway__BaseUrl"] = Urls["api-gateway"];
|
|
||||||
}
|
|
||||||
var gateway = Settings["api-gateway"];
|
|
||||||
gateway["Authentication__KeyDirectory"] = Path.Combine(Temporary, "keys");
|
|
||||||
gateway["Authentication__Accounts__0__AccountId"] = "deployment-patient";
|
|
||||||
gateway["Authentication__Accounts__0__Role"] = "Patient";
|
|
||||||
gateway["Authentication__Accounts__0__PasswordHash"] = new PasswordHasher<string>().HashPassword("deployment-patient", Password);
|
|
||||||
foreach (var service in Services)
|
|
||||||
await File.WriteAllLinesAsync(Path.Combine(Configuration, service + ".env"), Settings[service]
|
|
||||||
.Select(p => $"{p.Key}=\"{p.Value.Replace("\\", "\\\\").Replace("\"", "\\\"")}\""));
|
|
||||||
var installation = await Install(Root, "all");
|
|
||||||
Assert.Equal(0, installation.Code);
|
Assert.Equal(0, installation.Code);
|
||||||
|
using var accounts = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(Deployment, "accounts.json")));
|
||||||
|
Password = accounts.RootElement.EnumerateArray().Single(a => a.GetProperty("AccountId").GetString() == "prototype-patient").GetProperty("Password").GetString()!;
|
||||||
|
foreach (var service in Services)
|
||||||
|
{
|
||||||
|
Settings[service] = ReadEnvironment(Root, service);
|
||||||
|
Settings[service]["SSL_CERT_FILE"] = Path.Combine(Deployment, "healthapp-ca.crt");
|
||||||
|
Settings[service]["Logging__LogLevel__Default"] = "Warning";
|
||||||
|
Settings[service]["Logging__LogLevel__Microsoft.AspNetCore"] = "Warning";
|
||||||
|
Urls[service] = $"https://{hosts[service]}:{ports[service]}/";
|
||||||
|
}
|
||||||
foreach (var service in new[] { "patient-profile", "observation" })
|
foreach (var service in new[] { "patient-profile", "observation" })
|
||||||
{
|
{
|
||||||
|
var key = service == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase";
|
||||||
|
var db = new NpgsqlConnectionStringBuilder(Settings[service][key]);
|
||||||
|
databases.Add(db.Database!); roles.Add(db.Username!);
|
||||||
var migrated = await Run(Dotnet, [InstalledAssembly(service), "--migrate"], Settings[service]);
|
var migrated = await Run(Dotnet, [InstalledAssembly(service), "--migrate"], Settings[service]);
|
||||||
Assert.True(migrated.Code == 0, "Deployment database migration failed.");
|
Assert.True(migrated.Code == 0, "Deployment database migration failed.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task<(int Code, string Output)> Provision(params string[] arguments) => Run(Dotnet,
|
||||||
|
[Path.Combine(Bundle, "provisioner/HealthApp.Provisioning.dll"), .. arguments]);
|
||||||
|
public static Dictionary<string, string> ReadEnvironment(string root, string service) =>
|
||||||
|
File.ReadAllLines(Path.Combine(root, "etc/healthapp", service, "service.env")).ToDictionary(
|
||||||
|
line => line[..line.IndexOf('=')], line => JsonSerializer.Deserialize<string>(line[(line.IndexOf('=') + 1)..])!);
|
||||||
|
public HttpClient HttpClient()
|
||||||
|
{
|
||||||
|
var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, certificate, _, errors) =>
|
||||||
|
{
|
||||||
|
if (certificate is null || (errors & (SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable)) != 0) return false;
|
||||||
|
using var root = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(Deployment, "healthapp-ca.crt"));
|
||||||
|
using var chain = new X509Chain();
|
||||||
|
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||||
|
chain.ChainPolicy.CustomTrustStore.Add(root);
|
||||||
|
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||||
|
return chain.Build(certificate);
|
||||||
|
}};
|
||||||
|
return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(10) };
|
||||||
|
}
|
||||||
|
|
||||||
public string InstalledAssembly(string service) => Path.Combine(Root, "opt/healthapp", service, Assembly(service) + ".dll");
|
public string InstalledAssembly(string service) => Path.Combine(Root, "opt/healthapp", service, Assembly(service) + ".dll");
|
||||||
public Task<(int Code, string Output)> Install(string root, string services) => Run("bash",
|
public Task<(int Code, string Output)> Install(string root, string services) => Run("bash",
|
||||||
[Path.Combine(Bundle, "install.sh"), "--services", services, "--config-dir", Configuration, "--root", root]);
|
[Path.Combine(Bundle, "install.sh"), "--services", services, "--deployment", Deployment, "--root", root, "--dotnet", Dotnet]);
|
||||||
|
|
||||||
public async Task Start(string service, string? root = null)
|
public async Task Start(string service, string? root = null)
|
||||||
{
|
{
|
||||||
var start = new ProcessStartInfo(Dotnet) { WorkingDirectory = Path.Combine(root ?? Root, "opt/healthapp", service),
|
var start = new ProcessStartInfo(Dotnet) { WorkingDirectory = Path.Combine(root ?? Root, "opt/healthapp", service),
|
||||||
RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
|
RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
|
||||||
start.ArgumentList.Add(Path.Combine(root ?? Root, "opt/healthapp", service, Assembly(service) + ".dll"));
|
start.ArgumentList.Add(Path.Combine(root ?? Root, "opt/healthapp", service, Assembly(service) + ".dll"));
|
||||||
foreach (var (key, value) in Settings[service]) start.Environment[key] = value;
|
foreach (var (key, value) in ReadEnvironment(root ?? Root, service)) start.Environment[key] = value;
|
||||||
|
start.Environment["SSL_CERT_FILE"] = Path.Combine(Deployment, "healthapp-ca.crt");
|
||||||
|
start.Environment["Logging__LogLevel__Default"] = "Warning";
|
||||||
var process = Process.Start(start)!;
|
var process = Process.Start(start)!;
|
||||||
// Do not emit application logs containing potentially sensitive deployment information.
|
// Do not emit application logs containing potentially sensitive deployment information.
|
||||||
process.OutputDataReceived += (_, _) => { };
|
process.OutputDataReceived += (_, _) => { };
|
||||||
process.ErrorDataReceived += (_, _) => { };
|
process.ErrorDataReceived += (_, _) => { };
|
||||||
process.BeginOutputReadLine(); process.BeginErrorReadLine();
|
process.BeginOutputReadLine(); process.BeginErrorReadLine();
|
||||||
Processes[service] = process;
|
Processes[service] = process;
|
||||||
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(1) };
|
using var client = HttpClient();
|
||||||
for (var attempt = 0; attempt < 100; attempt++)
|
for (var attempt = 0; attempt < 100; attempt++)
|
||||||
{
|
{
|
||||||
Assert.False(process.HasExited, $"{service} exited during startup.");
|
Assert.False(process.HasExited, $"{service} exited during startup.");
|
||||||
@@ -174,6 +186,11 @@ public sealed class DeploymentFixture : IAsyncLifetime
|
|||||||
await using var drop = new NpgsqlCommand("DROP DATABASE IF EXISTS " + database + " WITH (FORCE)", connection);
|
await using var drop = new NpgsqlCommand("DROP DATABASE IF EXISTS " + database + " WITH (FORCE)", connection);
|
||||||
await drop.ExecuteNonQueryAsync();
|
await drop.ExecuteNonQueryAsync();
|
||||||
}
|
}
|
||||||
|
foreach (var role in roles)
|
||||||
|
{
|
||||||
|
await using var dropRole = new NpgsqlCommand("DROP ROLE IF EXISTS " + role, connection);
|
||||||
|
await dropRole.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (Directory.Exists(Temporary)) Directory.Delete(Temporary, true);
|
if (Directory.Exists(Temporary)) Directory.Delete(Temporary, true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ using System.Net.Http.Headers;
|
|||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Npgsql;
|
using Npgsql;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace Deployment.AcceptanceTests;
|
namespace Deployment.AcceptanceTests;
|
||||||
@@ -39,12 +40,18 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
|
|||||||
Assert.Equal(expected.Order(), payloads);
|
Assert.Equal(expected.Order(), payloads);
|
||||||
foreach (var service in expected)
|
foreach (var service in expected)
|
||||||
{
|
{
|
||||||
var env = Path.Combine(root, "etc/healthapp", service + ".env");
|
var env = Path.Combine(root, "etc/healthapp", service, "service.env");
|
||||||
Assert.Equal(await File.ReadAllTextAsync(Path.Combine(fixture.Configuration, service + ".env")), await File.ReadAllTextAsync(env));
|
var generated = DeploymentFixture.ReadEnvironment(root, service);
|
||||||
|
Assert.Equal("Production", generated["ASPNETCORE_ENVIRONMENT"]);
|
||||||
|
Assert.StartsWith("https://", generated["ASPNETCORE_URLS"]);
|
||||||
|
Assert.NotEmpty(generated["InternalAccess__GatewayKey"]);
|
||||||
|
Assert.True(File.Exists(generated["Kestrel__Certificates__Default__Path"]));
|
||||||
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(env));
|
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(env));
|
||||||
var unit = await File.ReadAllTextAsync(Path.Combine(root, "etc/systemd/system", "healthapp-" + service + ".service"));
|
var unit = await File.ReadAllTextAsync(Path.Combine(root, "etc/systemd/system", "healthapp-" + service + ".service"));
|
||||||
Assert.Contains("ExecStart=/usr/bin/dotnet /opt/healthapp/" + service + "/" + DeploymentFixture.Assembly(service) + ".dll", unit);
|
Assert.Contains("ExecStart=" + fixture.Dotnet + " /opt/healthapp/" + service + "/" + DeploymentFixture.Assembly(service) + ".dll", unit);
|
||||||
Assert.Contains("EnvironmentFile=/etc/healthapp/" + service + ".env", unit);
|
Assert.Contains("EnvironmentFile=/etc/healthapp/" + service + "/service.env", unit);
|
||||||
|
Assert.Contains("User=healthapp-" + service, unit);
|
||||||
|
Assert.Contains("Group=healthapp-" + service, unit);
|
||||||
Assert.DoesNotContain("Requires=healthapp-", unit);
|
Assert.DoesNotContain("Requires=healthapp-", unit);
|
||||||
Assert.DoesNotContain("PartOf=", unit);
|
Assert.DoesNotContain("PartOf=", unit);
|
||||||
Assert.DoesNotContain("BindsTo=", unit);
|
Assert.DoesNotContain("BindsTo=", unit);
|
||||||
@@ -56,24 +63,108 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Remote_configuration_is_preserved_as_data_without_executing_shell_text()
|
public async Task Configuration_and_certificates_are_generated_with_matching_credentials_and_private_permissions()
|
||||||
{
|
{
|
||||||
var config = Path.Combine(fixture.Temporary, "remote-config");
|
Assert.Equal(5, fixture.Settings.Values.Select(s => s["InternalAccess__GatewayKey"]).Distinct().Count());
|
||||||
Directory.CreateDirectory(config);
|
foreach (var service in DeploymentFixture.Services)
|
||||||
var marker = Path.Combine(fixture.Temporary, "must-not-exist");
|
{
|
||||||
var text = "ASPNETCORE_ENVIRONMENT=Production\n" +
|
var settings = fixture.Settings[service];
|
||||||
"Services__ApiGateway__BaseUrl=https://remote-gateway.example.test:5443/\n" +
|
Assert.Equal("Production", settings["ASPNETCORE_ENVIRONMENT"]);
|
||||||
"Services__ApiGateway__Key=externally-provisioned-credential-with-at-least-32-characters\n" +
|
Assert.StartsWith("https://", settings["ASPNETCORE_URLS"]);
|
||||||
"InternalAccess__GatewayKey=another-externally-provisioned-credential-with-at-least-32-characters\n" +
|
using var certificate = X509CertificateLoader.LoadPkcs12FromFile(settings["Kestrel__Certificates__Default__Path"], settings["Kestrel__Certificates__Default__Password"]);
|
||||||
$"UninterpretedValue=\"$(touch {marker})\"\n";
|
Assert.True(certificate.HasPrivateKey);
|
||||||
await File.WriteAllTextAsync(Path.Combine(config, "insights.env"), text);
|
Assert.True(certificate.NotAfter > DateTime.UtcNow);
|
||||||
var root = Path.Combine(fixture.Temporary, "remote-root");
|
var env = Path.Combine(fixture.Root, "etc/healthapp", service, "service.env");
|
||||||
var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights",
|
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(env));
|
||||||
"--config-dir", config, "--root", root]);
|
}
|
||||||
Assert.Equal(0, result.Code);
|
Assert.Equal(fixture.Settings["observation"]["Services__ApiGateway__Key"], fixture.Settings["api-gateway"]["InternalAccess__Observation__Key"]);
|
||||||
Assert.Equal(text, await File.ReadAllTextAsync(Path.Combine(root, "etc/healthapp/insights.env")));
|
Assert.Equal(fixture.Settings["insights"]["InternalAccess__GatewayKey"], fixture.Settings["api-gateway"]["Services__Insights__Key"]);
|
||||||
Assert.False(File.Exists(marker));
|
}
|
||||||
Assert.Single(Directory.GetDirectories(Path.Combine(root, "opt/healthapp")));
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Dedicated_database_roles_cannot_access_each_others_data_or_administer_the_server()
|
||||||
|
{
|
||||||
|
var profile = new NpgsqlConnectionStringBuilder(fixture.Settings["patient-profile"]["ConnectionStrings__PatientDatabase"]);
|
||||||
|
var observation = new NpgsqlConnectionStringBuilder(fixture.Settings["observation"]["ConnectionStrings__ObservationDatabase"]);
|
||||||
|
Assert.NotEqual(profile.Database, observation.Database);
|
||||||
|
Assert.NotEqual(profile.Username, observation.Username);
|
||||||
|
Assert.NotEqual(profile.Password, observation.Password);
|
||||||
|
await using var own = new NpgsqlConnection(profile.ConnectionString);
|
||||||
|
await own.OpenAsync();
|
||||||
|
await using var privileges = new NpgsqlCommand("SELECT rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication FROM pg_roles WHERE rolname = current_user", own);
|
||||||
|
Assert.Equal(false, await privileges.ExecuteScalarAsync());
|
||||||
|
await using var other = new NpgsqlConnection(new NpgsqlConnectionStringBuilder(profile.ConnectionString) { Database = observation.Database }.ConnectionString);
|
||||||
|
var failure = await Assert.ThrowsAsync<PostgresException>(() => other.OpenAsync());
|
||||||
|
Assert.Equal("42501", failure.SqlState);
|
||||||
|
var retried = await fixture.Provision("database", "--service-dir", Path.Combine(fixture.Deployment, "patient-profile"), "--admin-file", fixture.AdminFile);
|
||||||
|
Assert.True(retried.Code == 0, retried.Output);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task New_deployments_get_new_secrets_and_do_not_overwrite_existing_material()
|
||||||
|
{
|
||||||
|
var output = Path.Combine(fixture.Temporary, "another-deployment");
|
||||||
|
Assert.Equal(0, (await fixture.Provision("prepare", "--output", output, "--host", "localhost")).Code);
|
||||||
|
using var first = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(fixture.Deployment, "deployment.json")));
|
||||||
|
using var second = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(output, "deployment.json")));
|
||||||
|
Assert.NotEqual(first.RootElement.GetProperty("Services").GetProperty("insights").GetProperty("IncomingKey").GetString(),
|
||||||
|
second.RootElement.GetProperty("Services").GetProperty("insights").GetProperty("IncomingKey").GetString());
|
||||||
|
Assert.NotEqual(0, (await fixture.Provision("prepare", "--output", output)).Code);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Native_configuration_adapters_use_the_same_service_values_and_independent_paths()
|
||||||
|
{
|
||||||
|
var nativeRoot = Path.Combine(fixture.Temporary, "native-settings");
|
||||||
|
var windows = await fixture.Provision("configure", "--service-dir", Path.Combine(fixture.Deployment, "api-gateway"),
|
||||||
|
"--root", nativeRoot, "--platform", "windows");
|
||||||
|
Assert.True(windows.Code == 0, windows.Output);
|
||||||
|
using var json = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(nativeRoot, "config/api-gateway/appsettings.Production.json")));
|
||||||
|
Assert.StartsWith("https://", json.RootElement.GetProperty("urls").GetString());
|
||||||
|
Assert.Equal(fixture.Settings["api-gateway"]["Services__Observation__Key"], json.RootElement.GetProperty("Services").GetProperty("Observation").GetProperty("Key").GetString());
|
||||||
|
var mac = await fixture.Provision("configure", "--service-dir", Path.Combine(fixture.Deployment, "insights"),
|
||||||
|
"--root", nativeRoot, "--platform", "macos");
|
||||||
|
Assert.True(mac.Code == 0, mac.Output);
|
||||||
|
var plist = Path.Combine(nativeRoot, "insights.plist");
|
||||||
|
var launch = await fixture.Provision("launchd", "--service", "insights", "--root", nativeRoot, "--dotnet", fixture.Dotnet, "--output", plist);
|
||||||
|
Assert.True(launch.Code == 0, launch.Output);
|
||||||
|
var document = System.Xml.Linq.XDocument.Load(plist);
|
||||||
|
Assert.Contains(document.Descendants("string"), element => element.Value == "_healthapp_insights");
|
||||||
|
Assert.Contains(document.Descendants("string"), element => element.Value.EndsWith("InsightsService.dll"));
|
||||||
|
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(plist));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task VerifyScopedTopologyDistribution()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(fixture.Temporary, "distribution-contract");
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
var commands = Path.Combine(directory, "commands");
|
||||||
|
var captured = Path.Combine(directory, "captured");
|
||||||
|
Directory.CreateDirectory(captured);
|
||||||
|
var transport = Path.Combine(directory, "bin");
|
||||||
|
Directory.CreateDirectory(transport);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(transport, "ssh"), "#!/bin/bash\nprintf '%s\\n' \"$*\" >> \"$TRANSPORT_LOG\"\n");
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(transport, "scp"), "#!/bin/bash\ntarget=\"${3%%:*}\"\nname=\"${target#*@}\"\nmkdir -p \"$CAPTURE/$name\"\ncp -R \"$2\" \"$CAPTURE/$name/\"\n");
|
||||||
|
foreach (var script in Directory.GetFiles(transport)) File.SetUnixFileMode(script, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||||
|
var environment = new Dictionary<string, string> { ["PATH"] = transport + ":" + Environment.GetEnvironmentVariable("PATH"), ["TRANSPORT_LOG"] = commands, ["CAPTURE"] = captured };
|
||||||
|
var result = await DeploymentFixture.Run(fixture.Dotnet, [Path.Combine(fixture.Bundle, "provisioner/HealthApp.Provisioning.dll"),
|
||||||
|
"distribute", "--bundle", fixture.Bundle, "--deployment", fixture.Deployment, "--ssh-user", "administrator", "--services", string.Join(',', DeploymentFixture.Services)], environment);
|
||||||
|
Assert.True(result.Code == 0, result.Output);
|
||||||
|
Assert.Equal(5, Directory.GetDirectories(captured).Length);
|
||||||
|
foreach (var node in Directory.GetDirectories(captured))
|
||||||
|
{
|
||||||
|
var installed = Assert.Single(Directory.GetDirectories(Path.Combine(node, "services")));
|
||||||
|
var selected = Path.GetFileName(installed);
|
||||||
|
Assert.Single(Directory.GetDirectories(Path.Combine(node, "deployment")));
|
||||||
|
using var scope = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(node, "deployment/deployment.json")));
|
||||||
|
foreach (var name in DeploymentFixture.Services.Where(n => n != selected))
|
||||||
|
{
|
||||||
|
Assert.Equal("", scope.RootElement.GetProperty("Services").GetProperty(name).GetProperty("IncomingKey").GetString());
|
||||||
|
Assert.Equal(JsonValueKind.Null, scope.RootElement.GetProperty("Services").GetProperty(name).GetProperty("Database").ValueKind);
|
||||||
|
}
|
||||||
|
if (selected != "api-gateway") Assert.Empty(scope.RootElement.GetProperty("Accounts").EnumerateArray());
|
||||||
|
}
|
||||||
|
Assert.Contains("--defer-topology-check", await File.ReadAllTextAsync(commands));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -89,16 +180,14 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Missing_configuration_for_any_selected_service_rejects_the_whole_install_before_writes()
|
public async Task Invalid_topology_fails_before_generating_configuration_or_credentials()
|
||||||
{
|
{
|
||||||
var config = Path.Combine(fixture.Temporary, "partial-config");
|
var topology = Path.Combine(fixture.Temporary, "invalid-topology.json");
|
||||||
Directory.CreateDirectory(config);
|
await File.WriteAllTextAsync(topology, "{\"hosts\":{\"insights\":\"https://not-a-host/path\"}}");
|
||||||
File.Copy(Path.Combine(fixture.Configuration, "insights.env"), Path.Combine(config, "insights.env"));
|
var output = Path.Combine(fixture.Temporary, "invalid-topology-result");
|
||||||
var root = Path.Combine(fixture.Temporary, "partial-root");
|
var result = await fixture.Provision("prepare", "--output", output, "--topology", topology);
|
||||||
var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights,observation",
|
|
||||||
"--config-dir", config, "--root", root]);
|
|
||||||
Assert.NotEqual(0, result.Code);
|
Assert.NotEqual(0, result.Code);
|
||||||
Assert.False(Directory.Exists(root));
|
Assert.False(Directory.Exists(output));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -121,18 +210,6 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
|
|||||||
Assert.Empty(fixture.Processes);
|
Assert.Empty(fixture.Processes);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("--start")]
|
|
||||||
[InlineData("--migrate")]
|
|
||||||
public async Task Offline_staging_rejects_live_actions_without_writing_files(string action)
|
|
||||||
{
|
|
||||||
var root = Path.Combine(fixture.Temporary, "offline-action-" + Guid.NewGuid().ToString("N"));
|
|
||||||
var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights",
|
|
||||||
"--config-dir", fixture.Configuration, "--root", root, action]);
|
|
||||||
Assert.NotEqual(0, result.Code);
|
|
||||||
Assert.False(Directory.Exists(root));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Two_colocated_installed_services_run_with_independent_configuration_and_processes()
|
public async Task Two_colocated_installed_services_run_with_independent_configuration_and_processes()
|
||||||
{
|
{
|
||||||
@@ -143,7 +220,7 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
|
|||||||
await fixture.Start("patient-profile", root);
|
await fixture.Start("patient-profile", root);
|
||||||
await fixture.Start("observation", root);
|
await fixture.Start("observation", root);
|
||||||
Assert.Equal(2, fixture.Processes.Values.Select(p => p.Id).Distinct().Count());
|
Assert.Equal(2, fixture.Processes.Values.Select(p => p.Id).Distinct().Count());
|
||||||
using var client = new HttpClient();
|
using var client = fixture.HttpClient();
|
||||||
using var request = new HttpRequestMessage(HttpMethod.Get, fixture.Urls["observation"] +
|
using var request = new HttpRequestMessage(HttpMethod.Get, fixture.Urls["observation"] +
|
||||||
"api/patients/00000000-0000-0000-0000-000000000001/observations?from=2026-09-01&to=2026-09-10");
|
"api/patients/00000000-0000-0000-0000-000000000001/observations?from=2026-09-01&to=2026-09-10");
|
||||||
request.Headers.Add("X-Gateway-Key", fixture.Settings["observation"]["InternalAccess__GatewayKey"]);
|
request.Headers.Add("X-Gateway-Key", fixture.Settings["observation"]["InternalAccess__GatewayKey"]);
|
||||||
@@ -167,9 +244,10 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
|
|||||||
{
|
{
|
||||||
foreach (var service in DeploymentFixture.Services) await fixture.Start(service);
|
foreach (var service in DeploymentFixture.Services) await fixture.Start(service);
|
||||||
Assert.Equal(5, fixture.Processes.Values.Select(p => p.Id).Distinct().Count());
|
Assert.Equal(5, fixture.Processes.Values.Select(p => p.Id).Distinct().Count());
|
||||||
using var client = new HttpClient { BaseAddress = new Uri(fixture.Urls["api-gateway"]), Timeout = TimeSpan.FromSeconds(10) };
|
using var client = fixture.HttpClient();
|
||||||
|
client.BaseAddress = new Uri(fixture.Urls["api-gateway"]);
|
||||||
using var login = await client.PostAsJsonAsync("api/authentication/login", new
|
using var login = await client.PostAsJsonAsync("api/authentication/login", new
|
||||||
{ accountId = "deployment-patient", password = DeploymentFixture.Password });
|
{ accountId = "prototype-patient", password = fixture.Password });
|
||||||
Assert.Equal(HttpStatusCode.OK, login.StatusCode);
|
Assert.Equal(HttpStatusCode.OK, login.StatusCode);
|
||||||
using var tokenJson = JsonDocument.Parse(await login.Content.ReadAsStringAsync());
|
using var tokenJson = JsonDocument.Parse(await login.Content.ReadAsStringAsync());
|
||||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenJson.RootElement.GetProperty("accessToken").GetString());
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenJson.RootElement.GetProperty("accessToken").GetString());
|
||||||
@@ -204,6 +282,9 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
|
|||||||
using var fresh = await client.GetAsync(overviewPath);
|
using var fresh = await client.GetAsync(overviewPath);
|
||||||
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode);
|
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode);
|
||||||
}
|
}
|
||||||
|
var verified = await fixture.Provision("verify", "--deployment", fixture.Deployment, "--services", string.Join(',', DeploymentFixture.Services), "--complete", "true");
|
||||||
|
Assert.True(verified.Code == 0, verified.Output);
|
||||||
|
await VerifyScopedTopologyDistribution();
|
||||||
// Each DB owns only its documented service's tables; aggregation services have no DB configuration.
|
// Each DB owns only its documented service's tables; aggregation services have no DB configuration.
|
||||||
foreach (var (service, key, owned, absent) in new[]
|
foreach (var (service, key, owned, absent) in new[]
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in new issue
Block a user