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

@@ -0,0 +1,126 @@
using System.Net;
using System.Security.Cryptography;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
namespace HealthApp.Provisioning;
public static class InstallationVerification
{
public static async Task Verify(string deploymentDirectory, string[] selected, bool complete, bool startupOnly = false)
{
var deployment = Deployment.Load(deploymentDirectory);
using var root = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(deploymentDirectory, "healthapp-ca.crt"));
using var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, certificate, _, errors) =>
{
if (certificate is null || (errors & (SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable)) != 0) return false;
using var chain = new X509Chain();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Add(root);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1"));
return chain.Build(certificate);
}
};
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15), BaseAddress = new Uri(Deployment.Url(deployment.Services["api-gateway"])) };
async Task<HttpResponseMessage> Probe(Func<HttpRequestMessage> create, string name)
{
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(30));
while (true)
{
try
{
using var request = create();
var response = await client.SendAsync(request, deadline.Token);
if (response.StatusCode is not (HttpStatusCode.BadGateway or HttpStatusCode.ServiceUnavailable or HttpStatusCode.GatewayTimeout)) return response;
response.Dispose();
}
catch (HttpRequestException) { }
catch (OperationCanceledException) when (!deadline.IsCancellationRequested) { }
try { await Task.Delay(500, deadline.Token); }
catch (OperationCanceledException) { throw new InvalidOperationException("HTTPS startup/dependency probe timed out for " + name + "."); }
}
}
foreach (var name in selected)
{
var service = deployment.Services[name];
if (Deployment.ReadService(Path.Combine(deploymentDirectory, name)).Database is { } database)
{
try { await DatabaseProvisioning.Check(database); }
catch { throw new InvalidOperationException("Dedicated database reachability verification failed for " + name + "."); }
}
// Correct incoming credentials prove network/TLS and the configured service trust boundary.
var path = Deployment.Url(service) +
(name == "api-gateway" ? "api/measurement-guidance" : startupOnly ? "" : "api/patients/00000000-0000-0000-0000-000000000001" +
(name == "insights" ? "/insights?from=2026-01-01&to=2026-01-02" :
name == "health-overview" ? "/overview?from=2026-01-01&to=2026-01-02" :
name == "observation" ? "/observations?from=2026-01-01&to=2026-01-02" : ""));
using var response = await Probe(() =>
{
var request = new HttpRequestMessage(HttpMethod.Get, path);
if (name != "api-gateway") request.Headers.Add("X-Gateway-Key", service.IncomingKey);
return request;
}, name);
if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.NotFound))
throw new InvalidOperationException("HTTPS/dependency verification failed for " + name + " (HTTP " + (int)response.StatusCode + ").");
}
if (startupOnly) return;
// Exercise each installed service's configured outgoing gateway credentials using its actual network API.
foreach (var name in selected.Where(n => n is "observation" or "insights" or "health-overview"))
{
var service = deployment.Services[name];
using var request = new HttpRequestMessage(HttpMethod.Get, Deployment.Url(deployment.Services["api-gateway"]) +
"api/patients/00000000-0000-0000-0000-000000000001" + (name == "insights" ? "/observations?from=2026-01-01&to=2026-01-02" : ""));
request.Headers.Add("X-Service-Key", service.OutgoingKey);
using var response = await client.SendAsync(request);
if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.NotFound))
throw new InvalidOperationException("Gateway service-credential verification failed for " + name + ".");
}
if (!complete) return;
var account = deployment.Accounts.Single(a => a.AccountId == "installation-check");
using var login = await client.PostAsJsonAsync("api/authentication/login", new { accountId = account.AccountId, password = account.Password });
login.EnsureSuccessStatusCode();
using var token = JsonDocument.Parse(await login.Content.ReadAsStringAsync());
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.RootElement.GetProperty("accessToken").GetString());
using var current = await client.GetAsync("api/patients/me");
Guid patient;
if (current.StatusCode == HttpStatusCode.NotFound)
{
using var created = await client.PostAsJsonAsync("api/patients", new { name = "Installer verification (synthetic)", dateOfBirth = "1980-01-01" });
created.EnsureSuccessStatusCode();
using var profile = JsonDocument.Parse(await created.Content.ReadAsStringAsync());
patient = profile.RootElement.GetProperty("patientId").GetGuid();
}
else
{
current.EnsureSuccessStatusCode();
using var profile = JsonDocument.Parse(await current.Content.ReadAsStringAsync());
patient = profile.RootElement.GetProperty("patientId").GetGuid();
}
using var latest = await client.GetAsync($"api/patients/{patient}/observations/latest");
if (latest.StatusCode == HttpStatusCode.NotFound)
{
using var record = await client.PostAsJsonAsync($"api/patients/{patient}/observations", new
{
measuredAt = DateTime.UtcNow, systolic = 120, diastolic = 80, pulse = 60,
note = "Installer verification; synthetic data", measurementContext = new { setting = "Home", activityCondition = "AtRest" }
});
record.EnsureSuccessStatusCode();
}
else latest.EnsureSuccessStatusCode();
var bounds = $"from=2000-01-01&to={Uri.EscapeDataString(DateTime.UtcNow.AddDays(1).ToString("O"))}&setting=Home&activityCondition=AtRest";
using var overview = await client.GetAsync($"api/patients/{patient}/overview?{bounds}");
overview.EnsureSuccessStatusCode();
using var result = JsonDocument.Parse(await overview.Content.ReadAsStringAsync());
if (result.RootElement.GetProperty("patient").GetProperty("patientId").GetGuid() != patient ||
result.RootElement.GetProperty("latestObservation").ValueKind != JsonValueKind.Object ||
result.RootElement.GetProperty("insight").ValueKind != JsonValueKind.Object ||
result.RootElement.GetProperty("insightContributingCount").GetInt32() < 1)
throw new InvalidOperationException("Representative complete-system workflow did not return profile, latest observation and insight.");
}
}