Files

310 lines
20 KiB
C#

using System.Net;
using System.Runtime.Versioning;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Npgsql;
using System.Security.Cryptography.X509Certificates;
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, "service.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));
var unit = await File.ReadAllTextAsync(Path.Combine(root, "etc/systemd/system", "healthapp-" + service + ".service"));
Assert.Contains("ExecStart=" + fixture.Dotnet + " /opt/healthapp/" + service + "/" + DeploymentFixture.Assembly(service) + ".dll", 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("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 Configuration_and_certificates_are_generated_with_matching_credentials_and_private_permissions()
{
Assert.Equal(5, fixture.Settings.Values.Select(s => s["InternalAccess__GatewayKey"]).Distinct().Count());
foreach (var service in DeploymentFixture.Services)
{
var settings = fixture.Settings[service];
Assert.Equal("Production", settings["ASPNETCORE_ENVIRONMENT"]);
Assert.StartsWith("https://", settings["ASPNETCORE_URLS"]);
using var certificate = X509CertificateLoader.LoadPkcs12FromFile(settings["Kestrel__Certificates__Default__Path"], settings["Kestrel__Certificates__Default__Password"]);
Assert.True(certificate.HasPrivateKey);
Assert.True(certificate.NotAfter > DateTime.UtcNow);
var env = Path.Combine(fixture.Root, "etc/healthapp", service, "service.env");
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(env));
}
Assert.Equal(fixture.Settings["observation"]["Services__ApiGateway__Key"], fixture.Settings["api-gateway"]["InternalAccess__Observation__Key"]);
Assert.Equal(fixture.Settings["insights"]["InternalAccess__GatewayKey"], fixture.Settings["api-gateway"]["Services__Insights__Key"]);
}
[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]
[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 Invalid_topology_fails_before_generating_configuration_or_credentials()
{
var topology = Path.Combine(fixture.Temporary, "invalid-topology.json");
await File.WriteAllTextAsync(topology, "{\"hosts\":{\"insights\":\"https://not-a-host/path\"}}");
var output = Path.Combine(fixture.Temporary, "invalid-topology-result");
var result = await fixture.Provision("prepare", "--output", output, "--topology", topology);
Assert.NotEqual(0, result.Code);
Assert.False(Directory.Exists(output));
}
[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);
}
[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 = fixture.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 = fixture.HttpClient();
client.BaseAddress = new Uri(fixture.Urls["api-gateway"]);
using var login = await client.PostAsJsonAsync("api/authentication/login", new
{ accountId = "prototype-patient", password = fixture.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);
}
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.
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); }
}
}