Record Architecture B approval and verified pinned baseline
This commit is contained in:
1 parent
20ab461c01
commit
cee98e7035
158 files changed
+33575
No files matched your search
@@ -0,0 +1,92 @@
|
||||
using System.Runtime.Versioning;
|
||||
using Xunit;
|
||||
|
||||
namespace Deployment.AcceptanceTests;
|
||||
|
||||
[SupportedOSPlatform("linux")]
|
||||
public sealed class BootstrapTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("ubuntu", "24.04", false, false, false)]
|
||||
[InlineData("ubuntu", "24.04", true, true, false)]
|
||||
[InlineData("ubuntu", "24.04", true, true, true)]
|
||||
[InlineData("ubuntu", "26.04", false, true, false)]
|
||||
[InlineData("ubuntu", "26.04", true, true, true)]
|
||||
[InlineData("debian", "12", true, false, false)]
|
||||
[InlineData("debian", "13", false, true, false)]
|
||||
[InlineData("linuxmint", "22", false, true, false, "ubuntu debian")]
|
||||
[InlineData("pop", "future", false, false, false, "ubuntu")]
|
||||
[InlineData("ubuntu", "future", false, false, false)]
|
||||
[InlineData("debian", "13", false, false, false, "", false)]
|
||||
[InlineData("linuxmint", "22", false, false, false, "ubuntu debian", false, true, true, "aspnetcore-runtime-10.0 is unavailable")]
|
||||
[InlineData("debian", "99", false, false, false, "", false, true, false, "No accessible Microsoft Debian 99 repository")]
|
||||
[InlineData("ubuntu", "26.04", true, true, false, "", true, false, true, "Required package postgresql is unavailable")]
|
||||
[InlineData("fedora", "44", true, false, false, "", true, true, true, "requires a Debian/Ubuntu-based distribution")]
|
||||
public async Task Package_provisioning_detects_runtime_and_postgresql_and_installs_only_needed_dependencies(
|
||||
string distribution, string version, bool runtimeAvailable, bool databaseRequired, bool databaseAvailable,
|
||||
string ancestry = "", bool runtimePackage = true, bool postgresPackage = true,
|
||||
bool repositoryAvailable = true, string expectedError = "")
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), "healthapp-bootstrap-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
var log = Path.Combine(directory, "commands");
|
||||
await File.WriteAllTextAsync(log, "");
|
||||
var installed = Path.Combine(directory, "runtime-installed");
|
||||
var script = Path.Combine(directory, "test.sh");
|
||||
await File.WriteAllTextAsync(script, """
|
||||
set -euo pipefail
|
||||
fail() { printf '%s\n' "$*" >&2; exit 1; }
|
||||
runtime() { if [[ "$RUNTIME_PRESENT" == true || -f "$RUNTIME_INSTALLED" ]]; then printf '%s\n' 'Microsoft.AspNetCore.App 10.0.12 [runtime]'; else return 1; fi; }
|
||||
apt-get() { printf '%s\n' "apt-get $*" >> "$COMMAND_LOG"; if [[ "$*" == *aspnetcore-runtime-10.0* ]]; then touch "$RUNTIME_INSTALLED"; fi; }
|
||||
apt-cache() {
|
||||
if [[ "$2" == aspnetcore-runtime-10.0 && ( "$RUNTIME_PACKAGE" == true || -f "$REPOSITORY_ADDED" ) || "$2" == postgresql && "$POSTGRES_PACKAGE" == true ]]; then
|
||||
printf '%s\n' ' Candidate: 10.0.1';
|
||||
else printf '%s\n' ' Candidate: (none)'; fi
|
||||
}
|
||||
curl() { [[ "$REPOSITORY_AVAILABLE" == true ]] || return 22; printf '%s\n' "curl $*" >> "$COMMAND_LOG"; }
|
||||
update-ca-certificates() { :; }
|
||||
dpkg() { printf '%s\n' "dpkg $*" >> "$COMMAND_LOG"; touch "$REPOSITORY_ADDED"; }
|
||||
pg_isready() { [[ -f "$DATABASE_READY" ]]; }
|
||||
systemctl() { printf '%s\n' "systemctl $*" >> "$COMMAND_LOG"; touch "$DATABASE_READY"; }
|
||||
source "$BOOTSTRAP"
|
||||
ensure_dependencies "$DISTRO" "$VERSION" /bin/true "$DATABASE_REQUIRED" "$ANCESTRY"
|
||||
""");
|
||||
// Runtime is an executable stub; installed packages switch its simulated inventory.
|
||||
var runtime = Path.Combine(directory, "dotnet");
|
||||
await File.WriteAllTextAsync(runtime, "#!/bin/bash\nif [[ \"$RUNTIME_PRESENT\" == true || -f \"$RUNTIME_INSTALLED\" ]]; then printf '%s\\n' 'Microsoft.AspNetCore.App 10.0.12 [runtime]'; else exit 1; fi\n");
|
||||
File.SetUnixFileMode(runtime, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
var body = (await File.ReadAllTextAsync(script)).Replace("/bin/true", "\"$RUNTIME_EXECUTABLE\"");
|
||||
await File.WriteAllTextAsync(script, body);
|
||||
var environment = new Dictionary<string, string>
|
||||
{
|
||||
["COMMAND_LOG"] = log, ["RUNTIME_INSTALLED"] = installed,
|
||||
["RUNTIME_PRESENT"] = runtimeAvailable ? "true" : "false", ["RUNTIME_EXECUTABLE"] = runtime,
|
||||
["DATABASE_READY"] = Path.Combine(directory, "pg-ready"), ["DATABASE_REQUIRED"] = databaseRequired ? "true" : "false",
|
||||
["ANCESTRY"] = ancestry, ["RUNTIME_PACKAGE"] = runtimePackage ? "true" : "false",
|
||||
["POSTGRES_PACKAGE"] = postgresPackage ? "true" : "false", ["REPOSITORY_AVAILABLE"] = repositoryAvailable ? "true" : "false",
|
||||
["REPOSITORY_ADDED"] = Path.Combine(directory, "repository-added"),
|
||||
["BOOTSTRAP"] = Path.Combine(DeploymentFixture.Repository, "deploy/installer/bootstrap.sh"), ["DISTRO"] = distribution, ["VERSION"] = version
|
||||
};
|
||||
if (databaseAvailable) await File.WriteAllTextAsync(environment["DATABASE_READY"], "ready");
|
||||
var result = await DeploymentFixture.Run("bash", [script], environment);
|
||||
if (expectedError.Length > 0)
|
||||
{
|
||||
Assert.NotEqual(0, result.Code);
|
||||
Assert.Contains(expectedError, result.Output);
|
||||
var failedCommands = await File.ReadAllTextAsync(log);
|
||||
Assert.DoesNotContain("install -y aspnetcore-runtime-10.0", failedCommands);
|
||||
Assert.DoesNotContain("install -y postgresql", failedCommands);
|
||||
return;
|
||||
}
|
||||
Assert.True(result.Code == 0, result.Output);
|
||||
var commands = await File.ReadAllTextAsync(log);
|
||||
Assert.Equal(!runtimeAvailable, commands.Contains("install -y aspnetcore-runtime-10.0"));
|
||||
Assert.Equal(databaseRequired && !databaseAvailable, commands.Contains("install -y postgresql"));
|
||||
Assert.Equal(databaseRequired && !databaseAvailable, commands.Contains("systemctl enable --now postgresql"));
|
||||
Assert.Equal(!runtimeAvailable && !runtimePackage && distribution == "debian", commands.Contains("packages.microsoft.com/config/debian/" + version));
|
||||
}
|
||||
finally { Directory.Delete(directory, true); }
|
||||
}
|
||||
}
|
||||
+16
@@ -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,197 @@
|
||||
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<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 string Password { get; private set; } = "";
|
||||
private readonly List<string> 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<string, int>();
|
||||
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<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, "--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<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();
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
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); }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user