using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; 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"]; 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 Deployment => Path.Combine(Temporary, "deployment"); public string AdminFile => Path.Combine(Temporary, "admin.connection"); public string Root => Path.Combine(Temporary, "installed"); public Dictionary Urls { get; } = new(); public Dictionary> Settings { get; } = new(); public Dictionary Processes { get; } = new(); private readonly List databases = []; public string Admin { get; private set; } = ""; public string Password { get; private set; } = ""; private readonly List roles = []; public async Task InitializeAsync() { Directory.CreateDirectory(Temporary); 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.Output); var ports = new Dictionary(); foreach (var service in Services) { using var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); ports[service] = ((IPEndPoint)listener.LocalEndpoint).Port; } 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 ReadEnvironment(string root, string service) => File.ReadAllLines(Path.Combine(root, "etc/healthapp", service, "service.env")).ToDictionary( line => line[..line.IndexOf('=')], line => JsonSerializer.Deserialize(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, "--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 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 = HttpClient(); 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? 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(); } 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); } }