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

@@ -2,12 +2,16 @@ using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
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 Xunit;
namespace Deployment.AcceptanceTests;
[SupportedOSPlatform("linux")]
public sealed class DeploymentFixture : IAsyncLifetime
{
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";
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 Deployment => Path.Combine(Temporary, "deployment");
public string AdminFile => Path.Combine(Temporary, "admin.connection");
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 string Password { get; private set; } = "";
private readonly List<string> roles = [];
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.");
Assert.True(release.Code == 0, release.Output);
var ports = new Dictionary<string, int>();
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"
};
ports[service] = ((IPEndPoint)listener.LocalEndpoint).Port;
}
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");
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");
await File.WriteAllTextAsync(topology, JsonSerializer.Serialize(new { hosts, ports }));
var prepared = await Provision("prepare", "--output", Deployment, "--topology", topology);
Assert.True(prepared.Code == 0, prepared.Output);
await File.WriteAllTextAsync(AdminFile, Admin);
File.SetUnixFileMode(AdminFile, UnixFileMode.UserRead | UnixFileMode.UserWrite);
var installation = await Run("bash", [Path.Combine(Bundle, "install.sh"), "--services", "all", "--deployment", Deployment,
"--postgres-admin-file", AdminFile, "--root", Root, "--dotnet", Dotnet]);
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" })
{
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]);
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 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)
{
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;
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)!;
// 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) };
using var client = HttpClient();
for (var attempt = 0; attempt < 100; attempt++)
{
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 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);
}