Provision US-16 dependencies credentials HTTPS and native service configurations
This commit is contained in:
1 parent
950f67d8b7
commit
eedf2a941b
34 files changed
+1703
-373
No files matched your search
@@ -0,0 +1,63 @@
|
||||
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("debian", "12", true, false, false)]
|
||||
[InlineData("debian", "13", false, true, false)]
|
||||
public async Task Package_provisioning_detects_runtime_and_postgresql_and_installs_only_needed_dependencies(
|
||||
string distribution, string version, bool runtimeAvailable, bool databaseRequired, bool databaseAvailable)
|
||||
{
|
||||
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() { 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; }
|
||||
curl() { printf '%s\n' "curl $*" >> "$COMMAND_LOG"; }
|
||||
update-ca-certificates() { :; }
|
||||
dpkg() { printf '%s\n' "dpkg $*" >> "$COMMAND_LOG"; }
|
||||
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"
|
||||
""");
|
||||
// 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",
|
||||
["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);
|
||||
Assert.Equal(0, result.Code);
|
||||
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 && distribution == "debian", commands.Contains("packages.microsoft.com/config/debian/" + version));
|
||||
}
|
||||
finally { Directory.Delete(directory, true); }
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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[]
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user