Implement US-16 independent Linux service installation

This commit is contained in:
Steffen committed 2026-10-05 16:12:33 +02:00
1 parent b6342afdad
commit 950f67d8b7
10 files changed
+837

No files matched your search

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all" />
<PackageReference Include="Npgsql" Version="10.0.3" />
</ItemGroup>
</Project>
@@ -0,0 +1,180 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Identity;
using Npgsql;
using Xunit;
namespace Deployment.AcceptanceTests;
public sealed class DeploymentFixture : IAsyncLifetime
{
public static readonly string[] Services = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"];
public static string Assembly(string service) => service switch
{
"api-gateway" => "ApiGateway", "patient-profile" => "PatientProfileService",
"observation" => "ObservationService", "insights" => "InsightsService", _ => "HealthOverviewService"
};
public static string Repository
{
get
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "HealthApp.slnx"))) directory = directory.Parent;
return directory?.FullName ?? throw new InvalidOperationException("Repository root not found.");
}
}
public string Dotnet { get; } = Environment.GetEnvironmentVariable("HEALTHAPP_DOTNET") ??
Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
public string Temporary { get; } = Path.Combine(Path.GetTempPath(), "healthapp-us16-" + Guid.NewGuid().ToString("N"));
public string Bundle => Path.Combine(Temporary, "release");
public string Configuration => Path.Combine(Temporary, "configuration");
public string Root => Path.Combine(Temporary, "installed");
public Dictionary<string, string> Urls { get; } = new();
public Dictionary<string, Dictionary<string, string>> Settings { get; } = new();
public Dictionary<string, Process> Processes { get; } = new();
private readonly List<string> databases = [];
public string Admin { get; private set; } = "";
public const string Password = "synthetic-deployment-password";
public async Task InitializeAsync()
{
Directory.CreateDirectory(Temporary);
Directory.CreateDirectory(Configuration);
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],
new() { ["HEALTHAPP_DOTNET"] = Dotnet });
Assert.True(release.Code == 0, "Release publishing failed; no secret configuration was used.");
foreach (var service in Services)
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
Urls[service] = $"http://127.0.0.1:{((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 database = "us16_" + Guid.NewGuid().ToString("N");
await using var connection = new NpgsqlConnection(Admin);
await connection.OpenAsync();
await using var create = new NpgsqlCommand("CREATE DATABASE " + database, connection);
await create.ExecuteNonQueryAsync();
databases.Add(database);
Settings[service][service == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase"] =
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);
foreach (var service in new[] { "patient-profile", "observation" })
{
var migrated = await Run(Dotnet, [InstalledAssembly(service), "--migrate"], Settings[service]);
Assert.True(migrated.Code == 0, "Deployment database migration failed.");
}
}
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",
[Path.Combine(Bundle, "install.sh"), "--services", services, "--config-dir", Configuration, "--root", root]);
public async Task Start(string service, string? root = null)
{
var start = new ProcessStartInfo(Dotnet) { WorkingDirectory = Path.Combine(root ?? Root, "opt/healthapp", service),
RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
start.ArgumentList.Add(Path.Combine(root ?? Root, "opt/healthapp", service, Assembly(service) + ".dll"));
foreach (var (key, value) in Settings[service]) start.Environment[key] = value;
var process = Process.Start(start)!;
// Do not emit application logs containing potentially sensitive deployment information.
process.OutputDataReceived += (_, _) => { };
process.ErrorDataReceived += (_, _) => { };
process.BeginOutputReadLine(); process.BeginErrorReadLine();
Processes[service] = process;
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(1) };
for (var attempt = 0; attempt < 100; attempt++)
{
Assert.False(process.HasExited, $"{service} exited during startup.");
try { using var response = await client.GetAsync(Urls[service]); return; }
catch (HttpRequestException) { }
catch (TaskCanceledException) { }
await Task.Delay(100);
}
throw new TimeoutException($"{service} did not accept configured network traffic.");
}
public async Task Stop(string service)
{
if (!Processes.Remove(service, out var process)) return;
try
{
if (!process.HasExited)
{
// SIGINT is also the committed systemd unit's graceful stop signal.
var sent = await Run("kill", ["-INT", process.Id.ToString()]);
Assert.Equal(0, sent.Code);
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));
try { await process.WaitForExitAsync(deadline.Token); }
catch (OperationCanceledException) { process.Kill(true); await process.WaitForExitAsync(); throw; }
Assert.Equal(0, process.ExitCode);
}
}
finally { process.Dispose(); }
}
public static async Task<(int Code, string Output)> Run(string executable, string[] arguments,
Dictionary<string, string>? environment = null, string? workingDirectory = null)
{
var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
if (workingDirectory is not null) start.WorkingDirectory = workingDirectory;
foreach (var argument in arguments) start.ArgumentList.Add(argument);
if (environment is not null) foreach (var (key, value) in environment) start.Environment[key] = value;
using var process = Process.Start(start)!;
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(3));
try { await process.WaitForExitAsync(deadline.Token); }
catch (OperationCanceledException) { process.Kill(true); await process.WaitForExitAsync(); throw; }
return (process.ExitCode, await stdout + await stderr);
}
public async Task DisposeAsync()
{
foreach (var service in Processes.Keys.ToArray()) await Stop(service);
NpgsqlConnection.ClearAllPools();
if (!string.IsNullOrEmpty(Admin))
{
await using var connection = new NpgsqlConnection(Admin);
await connection.OpenAsync();
foreach (var database in databases)
{
await using var drop = new NpgsqlCommand("DROP DATABASE IF EXISTS " + database + " WITH (FORCE)", connection);
await drop.ExecuteNonQueryAsync();
}
}
if (Directory.Exists(Temporary)) Directory.Delete(Temporary, true);
}
}
@@ -0,0 +1,228 @@
using System.Net;
using System.Runtime.Versioning;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Npgsql;
using Xunit;
namespace Deployment.AcceptanceTests;
[SupportedOSPlatform("linux")]
public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture<DeploymentFixture>
{
[Fact]
public async Task A_selected_service_release_can_be_built_into_a_relative_output_directory()
{
var result = await DeploymentFixture.Run("bash", [Path.Combine(DeploymentFixture.Repository, "deploy/build-release.sh"),
"--output", "single-release", "--services", "insights"], new() { ["HEALTHAPP_DOTNET"] = fixture.Dotnet }, fixture.Temporary);
Assert.Equal(0, result.Code);
var release = Path.Combine(fixture.Temporary, "single-release");
Assert.True(File.Exists(Path.Combine(release, "services/insights/InsightsService.dll")));
Assert.Single(Directory.GetDirectories(Path.Combine(release, "services")));
Assert.True(File.Exists(Path.Combine(release, "install.sh")));
Assert.True(File.Exists(Path.Combine(release, "INSTALLATION.md")));
}
[Theory]
[InlineData("insights", 1)]
[InlineData("patient-profile,observation", 2)]
[InlineData("all", 5)]
public async Task Only_selected_payloads_configuration_and_independent_units_are_installed(string selection, int count)
{
var root = Path.Combine(fixture.Temporary, "selection-" + Guid.NewGuid().ToString("N"));
var installed = await fixture.Install(root, selection);
Assert.Equal(0, installed.Code);
var payloads = Directory.GetDirectories(Path.Combine(root, "opt/healthapp")).Select(Path.GetFileName).Order().ToArray();
var expected = selection == "all" ? DeploymentFixture.Services : selection.Split(',');
Assert.Equal(count, payloads.Length);
Assert.Equal(expected.Order(), payloads);
foreach (var service in expected)
{
var env = Path.Combine(root, "etc/healthapp", service + ".env");
Assert.Equal(await File.ReadAllTextAsync(Path.Combine(fixture.Configuration, service + ".env")), await File.ReadAllTextAsync(env));
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(env));
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("EnvironmentFile=/etc/healthapp/" + service + ".env", unit);
Assert.DoesNotContain("Requires=healthapp-", unit);
Assert.DoesNotContain("PartOf=", unit);
Assert.DoesNotContain("BindsTo=", unit);
}
// A repeated install must not overwrite live configuration or application files.
var repeated = await fixture.Install(root, selection);
Assert.NotEqual(0, repeated.Code);
Assert.Contains("Already installed", repeated.Output);
}
[Fact]
public async Task Remote_configuration_is_preserved_as_data_without_executing_shell_text()
{
var config = Path.Combine(fixture.Temporary, "remote-config");
Directory.CreateDirectory(config);
var marker = Path.Combine(fixture.Temporary, "must-not-exist");
var text = "ASPNETCORE_ENVIRONMENT=Production\n" +
"Services__ApiGateway__BaseUrl=https://remote-gateway.example.test:5443/\n" +
"Services__ApiGateway__Key=externally-provisioned-credential-with-at-least-32-characters\n" +
"InternalAccess__GatewayKey=another-externally-provisioned-credential-with-at-least-32-characters\n" +
$"UninterpretedValue=\"$(touch {marker})\"\n";
await File.WriteAllTextAsync(Path.Combine(config, "insights.env"), text);
var root = Path.Combine(fixture.Temporary, "remote-root");
var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights",
"--config-dir", config, "--root", root]);
Assert.Equal(0, result.Code);
Assert.Equal(text, await File.ReadAllTextAsync(Path.Combine(root, "etc/healthapp/insights.env")));
Assert.False(File.Exists(marker));
Assert.Single(Directory.GetDirectories(Path.Combine(root, "opt/healthapp")));
}
[Theory]
[InlineData("unknown")]
[InlineData("insights,insights")]
[InlineData("insights,")]
public async Task Invalid_service_selection_is_rejected_without_creating_an_installation(string selection)
{
var root = Path.Combine(fixture.Temporary, "invalid-" + Guid.NewGuid().ToString("N"));
var result = await fixture.Install(root, selection);
Assert.NotEqual(0, result.Code);
Assert.False(Directory.Exists(root));
}
[Fact]
public async Task Missing_configuration_for_any_selected_service_rejects_the_whole_install_before_writes()
{
var config = Path.Combine(fixture.Temporary, "partial-config");
Directory.CreateDirectory(config);
File.Copy(Path.Combine(fixture.Configuration, "insights.env"), Path.Combine(config, "insights.env"));
var root = Path.Combine(fixture.Temporary, "partial-root");
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.False(Directory.Exists(root));
}
[Theory]
[InlineData("patient-profile")]
[InlineData("observation")]
[InlineData("insights")]
[InlineData("health-overview")]
[InlineData("api-gateway")]
public async Task A_single_installed_service_starts_and_stops_without_other_local_service_processes(string service)
{
var root = Path.Combine(fixture.Temporary, "single-" + service);
Assert.Equal(0, (await fixture.Install(root, service)).Code);
try
{
await fixture.Start(service, root);
Assert.Single(fixture.Processes);
Assert.False(fixture.Processes[service].HasExited);
}
finally { await fixture.Stop(service); }
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]
public async Task Two_colocated_installed_services_run_with_independent_configuration_and_processes()
{
var root = Path.Combine(fixture.Temporary, "two-services");
Assert.Equal(0, (await fixture.Install(root, "patient-profile,observation")).Code);
try
{
await fixture.Start("patient-profile", root);
await fixture.Start("observation", root);
Assert.Equal(2, fixture.Processes.Values.Select(p => p.Id).Distinct().Count());
using var client = new HttpClient();
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");
request.Headers.Add("X-Gateway-Key", fixture.Settings["observation"]["InternalAccess__GatewayKey"]);
using var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("[]", await response.Content.ReadAsStringAsync());
var observationPid = fixture.Processes["observation"].Id;
await fixture.Stop("patient-profile");
Assert.False(fixture.Processes["observation"].HasExited);
Assert.Equal(observationPid, fixture.Processes["observation"].Id);
await fixture.Start("patient-profile", root);
Assert.Equal(observationPid, fixture.Processes["observation"].Id);
}
finally { foreach (var service in fixture.Processes.Keys.ToArray()) await fixture.Stop(service); }
}
[Fact]
public async Task Installed_complete_system_runs_in_five_processes_and_preserves_network_and_persistence_boundaries()
{
try
{
foreach (var service in DeploymentFixture.Services) await fixture.Start(service);
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 login = await client.PostAsJsonAsync("api/authentication/login", new
{ accountId = "deployment-patient", password = DeploymentFixture.Password });
Assert.Equal(HttpStatusCode.OK, login.StatusCode);
using var tokenJson = JsonDocument.Parse(await login.Content.ReadAsStringAsync());
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenJson.RootElement.GetProperty("accessToken").GetString());
using var profile = await client.PostAsJsonAsync("api/patients", new { name = "Deployed patient", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, profile.StatusCode);
using var profileJson = JsonDocument.Parse(await profile.Content.ReadAsStringAsync());
var patient = profileJson.RootElement.GetProperty("patientId").GetGuid();
using var recorded = await client.PostAsJsonAsync($"api/patients/{patient}/observations", new
{ measuredAt = "2026-09-05T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
measurementContext = new { setting = "Home", activityCondition = "AtRest" } });
Assert.Equal(HttpStatusCode.Created, recorded.StatusCode);
var overviewPath = $"api/patients/{patient}/overview?from=2026-09-01&to=2026-09-10&setting=Home&activityCondition=AtRest";
using var overview = await client.GetAsync(overviewPath);
Assert.Equal(HttpStatusCode.OK, overview.StatusCode);
using var overviewJson = JsonDocument.Parse(await overview.Content.ReadAsStringAsync());
Assert.Equal(patient, overviewJson.RootElement.GetProperty("patient").GetProperty("patientId").GetGuid());
Assert.Equal(128, overviewJson.RootElement.GetProperty("latestObservation").GetProperty("systolic").GetInt32());
Assert.Equal(128m, overviewJson.RootElement.GetProperty("insight").GetProperty("averageSystolic").GetDecimal());
Assert.Equal(1, overviewJson.RootElement.GetProperty("insightContributingCount").GetInt32());
foreach (var service in DeploymentFixture.Services)
{
var peers = fixture.Processes.Where(p => p.Key != service).ToDictionary(p => p.Key, p => p.Value.Id);
var oldId = fixture.Processes[service].Id;
await fixture.Stop(service);
foreach (var (peer, id) in peers)
{
Assert.Equal(id, fixture.Processes[peer].Id);
Assert.False(fixture.Processes[peer].HasExited);
}
await fixture.Start(service);
Assert.NotEqual(oldId, fixture.Processes[service].Id);
using var fresh = await client.GetAsync(overviewPath);
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode);
}
// Each DB owns only its documented service's tables; aggregation services have no DB configuration.
foreach (var (service, key, owned, absent) in new[]
{
("patient-profile", "ConnectionStrings__PatientDatabase", "patient", "blood_pressure_observation"),
("observation", "ConnectionStrings__ObservationDatabase", "blood_pressure_observation", "patient")
})
{
await using var connection = new NpgsqlConnection(fixture.Settings[service][key]);
await connection.OpenAsync();
await using var command = new NpgsqlCommand("SELECT tablename FROM pg_tables WHERE schemaname = 'public'", connection);
await using var reader = await command.ExecuteReaderAsync();
List<string> tables = [];
while (await reader.ReadAsync()) tables.Add(reader.GetString(0));
Assert.Contains(owned, tables);
Assert.DoesNotContain(absent, tables);
}
Assert.DoesNotContain(fixture.Settings["insights"].Keys, k => k.StartsWith("ConnectionStrings__"));
Assert.DoesNotContain(fixture.Settings["health-overview"].Keys, k => k.StartsWith("ConnectionStrings__"));
}
finally { foreach (var service in fixture.Processes.Keys.ToArray()) await fixture.Stop(service); }
}
}