Provision US-16 dependencies credentials HTTPS and native service configurations

This commit is contained in:
Steffen committed 2026-10-06 09:11:28 +02:00
1 parent 950f67d8b7
commit eedf2a941b
34 files changed
+1703 -373

No files matched your search

@@ -4,6 +4,7 @@ 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;
@@ -39,12 +40,18 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
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));
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=/usr/bin/dotnet /opt/healthapp/" + service + "/" + DeploymentFixture.Assembly(service) + ".dll", unit);
Assert.Contains("EnvironmentFile=/etc/healthapp/" + service + ".env", unit);
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);
@@ -56,24 +63,108 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
}
[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");
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")));
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]
@@ -89,16 +180,14 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
}
[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");
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]);
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(root));
Assert.False(Directory.Exists(output));
}
[Theory]
@@ -121,18 +210,6 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
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()
{
@@ -143,7 +220,7 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
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 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"]);
@@ -167,9 +244,10 @@ public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture
{
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 client = fixture.HttpClient();
client.BaseAddress = new Uri(fixture.Urls["api-gateway"]);
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);
using var tokenJson = JsonDocument.Parse(await login.Content.ReadAsStringAsync());
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);
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[]
{