Record Architecture B approval and verified pinned baseline

This commit is contained in:
Steffen committed 2026-10-14 10:58:43 +02:00
1 parent 20ab461c01
commit cee98e7035
158 files changed
+33575

No files matched your search

@@ -0,0 +1,38 @@
name: Prototype native installation
on:
workflow_dispatch:
permissions:
contents: read
jobs:
native-install:
strategy:
fail-fast: false
matrix:
os: [ubuntu-24.04, windows-latest, macos-14]
runs-on: ${{ matrix.os }}
timeout-minutes: 40
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- name: Build portable release on Unix
if: runner.os != 'Windows'
shell: bash
run: bash deploy/build-release.sh --output "$RUNNER_TEMP/healthapp-release"
- name: Build portable release on Windows
if: runner.os == 'Windows'
shell: pwsh
run: ./deploy/build-release.ps1 -Output "$env:RUNNER_TEMP/healthapp-release"
- name: Provision and verify Ubuntu/systemd
if: runner.os == 'Linux'
shell: bash
run: sudo bash "$RUNNER_TEMP/healthapp-release/install.sh" --services all --host localhost --dotnet "$(command -v dotnet)"
- name: Provision and verify Windows Services
if: runner.os == 'Windows'
shell: pwsh
run: '& "$env:RUNNER_TEMP/healthapp-release/install.ps1" -Services all -HostName localhost'
- name: Provision and verify macOS/launchd
if: runner.os == 'macOS'
shell: bash
run: sudo bash "$RUNNER_TEMP/healthapp-release/install.sh" --services all --host localhost
+15
View File
@@ -0,0 +1,15 @@
**/bin/
**/obj/
TestResults/
.env
*.user
# Draw.io backup files
Docs/Architecture/.*.bkp
# Private workload credentials and generated measurement results
tools/energy-jmeter/.private/
tools/energy-jmeter/results/
tools/energy-jmeter/hash-tool/
jmeter.log
__pycache__/
+17
View File
@@ -0,0 +1,17 @@
<Solution>
<Folder Name="/deploy/">
<Project Path="deploy/HealthApp.Provisioning/HealthApp.Provisioning.csproj" />
</Folder>
<Folder Name="/src/">
<Project Path="src/HealthOverviewService/HealthOverviewService.csproj" />
<Project Path="src/InsightsService/InsightsService.csproj" />
<Project Path="src/ApiGateway/ApiGateway.csproj" />
<Project Path="src/PatientProfileService/PatientProfileService.csproj" />
<Project Path="src/ObservationService/ObservationService.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Deployment.AcceptanceTests/Deployment.AcceptanceTests.csproj" />
<Project Path="tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj" />
<Project Path="tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj" />
</Folder>
</Solution>
@@ -0,0 +1,41 @@
using System.Text.Json;
namespace HealthApp.Provisioning;
public static class ConfigurationWriter
{
public static void Configure(string serviceDirectory, string root, string platform)
{
if (platform is not ("linux" or "windows" or "macos")) throw new InvalidOperationException("Unknown configuration platform.");
var service = Deployment.ReadService(serviceDirectory);
var directory = platform == "linux" ? Path.Combine(root, "etc", "healthapp", service.Name) : Path.Combine(root, "config", service.Name);
Directory.CreateDirectory(directory);
var destination = Path.Combine(directory, platform == "windows" ? "appsettings.Production.json" : "service.env");
if (File.Exists(destination)) throw new InvalidOperationException("Service configuration already exists; it was not overwritten.");
var env = new Dictionary<string, string>(service.Environment);
env["Kestrel__Certificates__Default__Path"] = Path.Combine(directory, "service.pfx");
if (service.Name == "api-gateway") env["Authentication__KeyDirectory"] = platform == "linux" ?
Path.Combine(root, "var", "lib", "healthapp-api-gateway", "keys") : Path.Combine(root, "state", "api-gateway", "keys");
File.Copy(Path.Combine(serviceDirectory, "service.pfx"), Path.Combine(directory, "service.pfx"));
if (platform == "windows")
{
var json = new Dictionary<string, object>();
foreach (var (key, value) in env)
{
if (key == "ASPNETCORE_ENVIRONMENT") continue; // Native service command line explicitly selects Production.
var parts = (key == "ASPNETCORE_URLS" ? "urls" : key).Split("__");
var current = json;
foreach (var part in parts[..^1])
{
if (!current.TryGetValue(part, out var child)) current[part] = child = new Dictionary<string, object>();
current = (Dictionary<string, object>)child;
}
current[parts[^1]] = value;
}
File.WriteAllText(destination, JsonSerializer.Serialize(json, Deployment.Json));
}
else File.WriteAllLines(destination, env.Select(p => p.Key + "=\"" + p.Value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""));
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
foreach (var file in Directory.GetFiles(directory)) File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
}
@@ -0,0 +1,72 @@
using System.Diagnostics;
using System.Text.RegularExpressions;
using Npgsql;
namespace HealthApp.Provisioning;
public static class DatabaseProvisioning
{
public static async Task Create(string serviceDirectory, string? adminFile)
{
var service = Deployment.ReadService(serviceDirectory);
var database = service.Database ?? throw new InvalidOperationException("This service owns no database.");
if (!Regex.IsMatch(database.Name, "^[a-z][a-z0-9_]{1,62}$") || !Regex.IsMatch(database.User, "^[a-z][a-z0-9_]{1,62}$") ||
!Regex.IsMatch(database.Password, "^[A-F0-9]{64}$")) throw new InvalidOperationException("Generated database settings are invalid.");
var adminConnection = adminFile is null ? null : File.ReadAllText(adminFile).Trim();
async Task<string> Sql(string sql, string target = "postgres")
{
if (adminConnection is not null)
{
var settings = new NpgsqlConnectionStringBuilder(adminConnection) { Database = target, Pooling = false };
await using var connection = new NpgsqlConnection(settings.ConnectionString);
await connection.OpenAsync();
await using var command = new NpgsqlCommand(sql, connection);
var result = await command.ExecuteScalarAsync();
return result?.ToString() ?? "";
}
var start = new ProcessStartInfo("runuser") { RedirectStandardInput = true, RedirectStandardOutput = true,
RedirectStandardError = true, UseShellExecute = false };
foreach (var argument in new[] { "-u", "postgres", "--", "psql", "--no-psqlrc", "--set=ON_ERROR_STOP=1", "--tuples-only", "--no-align", "--dbname", target })
start.ArgumentList.Add(argument);
using var process = Process.Start(start) ?? throw new InvalidOperationException("Could not run PostgreSQL administration.");
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
await process.StandardInput.WriteAsync(sql);
process.StandardInput.Close();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try { await process.WaitForExitAsync(timeout.Token); }
catch (OperationCanceledException) { process.Kill(true); throw; }
await stderr; // Never print SQL or passwords, including PostgreSQL error echoes.
if (process.ExitCode != 0) throw new InvalidOperationException("PostgreSQL administration failed; existing data was retained.");
return (await stdout).Trim();
}
static bool True(string value) => value is "t" or "True";
var userExists = True(await Sql($"SELECT EXISTS(SELECT FROM pg_roles WHERE rolname='{database.User}');"));
if (!userExists)
await Sql($"CREATE ROLE {database.User} LOGIN PASSWORD '{database.Password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;");
var exists = True(await Sql($"SELECT EXISTS(SELECT FROM pg_database WHERE datname='{database.Name}');"));
if (exists && !True(await Sql($"SELECT pg_get_userbyid(datdba)='{database.User}' FROM pg_database WHERE datname='{database.Name}';")))
throw new InvalidOperationException("Existing database has another owner; it was not changed.");
if (!exists) await Sql($"CREATE DATABASE {database.Name} OWNER {database.User};");
await Sql($"REVOKE ALL ON DATABASE {database.Name} FROM PUBLIC;");
await Sql($"REVOKE ALL ON SCHEMA public FROM PUBLIC; ALTER SCHEMA public OWNER TO {database.User}; GRANT USAGE, CREATE ON SCHEMA public TO {database.User};", database.Name);
// With an external PostgreSQL admin connection, preserve that endpoint in generated application config.
if (adminConnection is not null)
{
var admin = new NpgsqlConnectionStringBuilder(adminConnection);
database = database with { Host = admin.Host!, Port = admin.Port };
service = service with { Database = database };
var key = service.Name == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase";
service.Environment[key] = Deployment.ConnectionString(database);
File.WriteAllText(Path.Combine(serviceDirectory, "service.json"), System.Text.Json.JsonSerializer.Serialize(service, Deployment.Json));
}
await Check(database);
}
public static async Task Check(DatabaseSettings database)
{
await using var connection = new NpgsqlConnection(Deployment.ConnectionString(database));
await connection.OpenAsync();
await using var command = new NpgsqlCommand("SELECT current_user", connection);
if ((string?)await command.ExecuteScalarAsync() != database.User) throw new InvalidOperationException("Database service identity does not match.");
}
}
@@ -0,0 +1,157 @@
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Identity;
using Npgsql;
namespace HealthApp.Provisioning;
public sealed class Topology
{
public Dictionary<string, string> Hosts { get; set; } = new();
public Dictionary<string, int> Ports { get; set; } = new();
public Dictionary<string, string> Platforms { get; set; } = new();
}
public sealed record DatabaseSettings(string Name, string User, string Password, string Host = "localhost", int Port = 5432);
public sealed record Account(string AccountId, string Role, string Password);
public sealed record ServiceSettings(string Name, string Host, int Port, string IncomingKey, string? OutgoingKey,
string CertificatePassword, DatabaseSettings? Database, Dictionary<string, string> Environment, string Platform = "linux");
public sealed record Deployment(string Id, Dictionary<string, ServiceSettings> Services, List<Account> Accounts)
{
public static readonly string[] Names = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"];
public static readonly Dictionary<string, string> ContractNames = new()
{
["patient-profile"] = "PatientProfile", ["observation"] = "Observation",
["insights"] = "Insights", ["health-overview"] = "HealthOverview"
};
public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true, WriteIndented = true };
public static string Secret() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
public static string Url(ServiceSettings service) => new UriBuilder("https", service.Host, service.Port).Uri.ToString();
public static Deployment Load(string directory) => JsonSerializer.Deserialize<Deployment>(
File.ReadAllText(Path.Combine(directory, "deployment.json")), Json) ?? throw new InvalidOperationException("Deployment is invalid.");
public static void Prepare(string output, string host, string? topologyFile, string? certificates)
{
if (Directory.Exists(output) || File.Exists(output)) throw new InvalidOperationException("Deployment output already exists; existing credentials were not changed.");
var topology = topologyFile is null ? new Topology() : JsonSerializer.Deserialize<Topology>(File.ReadAllText(topologyFile), Json)
?? throw new InvalidOperationException("Topology is invalid.");
foreach (var name in topology.Hosts.Keys.Concat(topology.Ports.Keys).Concat(topology.Platforms.Keys))
if (!Names.Contains(name)) throw new InvalidOperationException("Topology has an unknown service.");
var id = Guid.NewGuid().ToString("N")[..12];
var services = new Dictionary<string, ServiceSettings>();
var defaults = new Dictionary<string, int> { ["api-gateway"] = 5443, ["patient-profile"] = 5081,
["observation"] = 5082, ["insights"] = 5083, ["health-overview"] = 5084 };
foreach (var name in Names)
{
var hostname = topology.Hosts.GetValueOrDefault(name, host);
if (Uri.CheckHostName(hostname) == UriHostNameType.Unknown || hostname.Contains('%'))
throw new InvalidOperationException("Provide a valid DNS name or IP address for each service host.");
var port = topology.Ports.GetValueOrDefault(name, defaults[name]);
if (port < 1024 || port > 65535) throw new InvalidOperationException("HTTPS ports must be between 1024 and 65535.");
DatabaseSettings? database = name switch
{
"patient-profile" => new("healthapp_" + id + "_profile", "healthapp_" + id + "_profile", Secret()),
"observation" => new("healthapp_" + id + "_observation", "healthapp_" + id + "_observation", Secret()), _ => null
};
var platform = topology.Platforms.GetValueOrDefault(name, OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linux");
if (platform is not ("linux" or "windows" or "macos")) throw new InvalidOperationException("Unsupported node platform.");
services[name] = new(name, hostname, port, Secret(), name is "api-gateway" or "patient-profile" ? null : Secret(),
Secret(), database, new(), platform);
}
if (services.Values.GroupBy(s => (s.Host.ToLowerInvariant(), s.Port)).Any(g => g.Count() > 1))
throw new InvalidOperationException("Colocated services need distinct HTTPS ports.");
var accounts = new List<Account> { new("prototype-patient", "Patient", Secret()),
new("prototype-professional", "HealthcareProfessional", Secret()), new("installation-check", "Patient", Secret()) };
var deployment = new Deployment(id, services, accounts);
foreach (var service in services.Values)
{
var env = service.Environment;
env["ASPNETCORE_ENVIRONMENT"] = "Production";
env["ASPNETCORE_URLS"] = "https://0.0.0.0:" + service.Port;
env["InternalAccess__GatewayKey"] = service.IncomingKey;
env["Kestrel__Certificates__Default__Path"] = $"/etc/healthapp/{service.Name}/service.pfx";
env["Kestrel__Certificates__Default__Password"] = service.CertificatePassword;
if (service.Name == "api-gateway")
{
env["Authentication__KeyDirectory"] = "/var/lib/healthapp-api-gateway/keys";
foreach (var (name, contract) in ContractNames)
{
env[$"Services__{contract}__BaseUrl"] = Url(services[name]);
env[$"Services__{contract}__Key"] = services[name].IncomingKey;
if (services[name].OutgoingKey is { } key) env[$"InternalAccess__{contract}__Key"] = key;
}
for (var index = 0; index < accounts.Count; index++)
{
var account = accounts[index];
env[$"Authentication__Accounts__{index}__AccountId"] = account.AccountId;
env[$"Authentication__Accounts__{index}__Role"] = account.Role;
env[$"Authentication__Accounts__{index}__PasswordHash"] = new PasswordHasher<Account>().HashPassword(account, account.Password);
}
}
else if (service.OutgoingKey is not null)
{
env["Services__ApiGateway__BaseUrl"] = Url(services["api-gateway"]);
env["Services__ApiGateway__Key"] = service.OutgoingKey;
}
if (service.Database is { } db)
env[service.Name == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase"] = ConnectionString(db);
}
Directory.CreateDirectory(output);
if ((OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())) File.SetUnixFileMode(output, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
using var caKey = RSA.Create(3072);
var caRequest = new CertificateRequest("CN=HealthApp prototype " + id, caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true));
caRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(caRequest.PublicKey, false));
using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(2));
// Only the public CA is needed on installed nodes; no signing key is retained.
File.WriteAllText(Path.Combine(output, "healthapp-ca.crt"), certificates is null ? ca.ExportCertificatePem() :
File.ReadAllText(Path.Combine(certificates, "healthapp-ca.crt")));
foreach (var service in services.Values)
{
var directory = Path.Combine(output, service.Name);
Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, "service.json"), JsonSerializer.Serialize(service, Json));
File.WriteAllLines(Path.Combine(directory, "service.env"), service.Environment.Select(e => e.Key + "=" + Quote(e.Value)));
byte[] pfx;
if (certificates is not null)
{
var password = File.ReadAllText(Path.Combine(certificates, service.Name + ".password")).TrimEnd('\r', '\n');
var supplied = X509CertificateLoader.LoadPkcs12CollectionFromFile(Path.Combine(certificates, service.Name + ".pfx"), password);
if (!supplied.Cast<X509Certificate2>().Any(c => c.HasPrivateKey)) throw new InvalidOperationException("Supplied certificate has no private key.");
pfx = supplied.Export(X509ContentType.Pfx, service.CertificatePassword)!;
foreach (var certificate in supplied) certificate.Dispose();
}
else
{
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=" + service.Host, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new System.Security.Cryptography.OidCollection { new("1.3.6.1.5.5.7.3.1") }, true));
var san = new SubjectAlternativeNameBuilder();
if (IPAddress.TryParse(service.Host, out var ip)) san.AddIpAddress(ip); else san.AddDnsName(service.Host);
request.CertificateExtensions.Add(san.Build());
using var leaf = request.Create(ca, DateTimeOffset.UtcNow.AddMinutes(-2), DateTimeOffset.UtcNow.AddYears(1), RandomNumberGenerator.GetBytes(16));
using var withKey = leaf.CopyWithPrivateKey(key);
pfx = withKey.Export(X509ContentType.Pfx, service.CertificatePassword);
}
File.WriteAllBytes(Path.Combine(directory, "service.pfx"), pfx);
}
File.WriteAllText(Path.Combine(output, "deployment.json"), JsonSerializer.Serialize(deployment, Json));
File.WriteAllText(Path.Combine(output, "accounts.json"), JsonSerializer.Serialize(accounts, Json));
if ((OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()))
foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories))
File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
public static string ConnectionString(DatabaseSettings db) => new NpgsqlConnectionStringBuilder
{
Host = db.Host, Port = db.Port, Database = db.Name, Username = db.User, Password = db.Password,
SslMode = SslMode.Prefer, Timeout = 10, Pooling = false
}.ConnectionString;
private static string Quote(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
public static ServiceSettings ReadService(string directory) => JsonSerializer.Deserialize<ServiceSettings>(
File.ReadAllText(Path.Combine(directory, "service.json")), Json) ?? throw new InvalidOperationException("Service configuration is invalid.");
}
@@ -0,0 +1,93 @@
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace HealthApp.Provisioning;
public static class Distribution
{
public static async Task Deploy(string bundle, string directory, string user, string[] selected)
{
if (!Regex.IsMatch(user, "^[a-zA-Z_][a-zA-Z0-9_-]*$")) throw new InvalidOperationException("SSH user is invalid.");
var deployment = Deployment.Load(directory);
async Task Run(string command, params string[] args)
{
var start = new ProcessStartInfo(command) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in args) start.ArgumentList.Add(argument);
using var process = Process.Start(start) ?? throw new InvalidOperationException("Could not run deployment transport.");
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(20));
try { await process.WaitForExitAsync(timeout.Token); }
catch (OperationCanceledException) { process.Kill(true); throw; }
await stdout;
var errors = await stderr;
if (process.ExitCode != 0)
{
var reportedStep = errors.Split('\n').LastOrDefault(line => line.StartsWith("Installation failed at ", StringComparison.Ordinal));
throw new InvalidOperationException(reportedStep ?? "SSH deployment transport failed; check administrative SSH access and node installation logs.");
}
}
var temporary = Path.Combine(Path.GetTempPath(), "healthapp-distribution-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(temporary);
if (OperatingSystem.IsLinux()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
try
{
foreach (var group in selected.GroupBy(n => deployment.Services[n].Host, StringComparer.OrdinalIgnoreCase))
{
var names = group.ToArray();
var node = Path.Combine(temporary, "node-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(node);
var material = Path.Combine(node, "deployment");
Directory.CreateDirectory(material);
foreach (var script in Directory.GetFiles(bundle).Where(p => p.EndsWith(".sh") || p.EndsWith(".ps1"))) File.Copy(script, Path.Combine(node, Path.GetFileName(script)));
CopyDirectory(Path.Combine(bundle, "provisioner"), Path.Combine(node, "provisioner"));
Directory.CreateDirectory(Path.Combine(node, "services"));
Directory.CreateDirectory(Path.Combine(node, "systemd"));
foreach (var name in names)
{
CopyDirectory(Path.Combine(bundle, "services", name), Path.Combine(node, "services", name));
CopyDirectory(Path.Combine(directory, name), Path.Combine(material, name));
File.Copy(Path.Combine(bundle, "systemd", "healthapp-" + name + ".service"), Path.Combine(node, "systemd", "healthapp-" + name + ".service"));
}
// Retain remote origins, but do not give a node unrelated service/database/private-key credentials.
var scoped = deployment with
{
Services = deployment.Services.ToDictionary(p => p.Key, p => names.Contains(p.Key) ? p.Value :
p.Value with { IncomingKey = "", OutgoingKey = null, CertificatePassword = "", Database = null, Environment = new() }),
Accounts = names.Contains("api-gateway") ? deployment.Accounts : []
};
File.WriteAllText(Path.Combine(material, "deployment.json"), JsonSerializer.Serialize(scoped, Deployment.Json));
if (names.Contains("api-gateway")) File.Copy(Path.Combine(directory, "accounts.json"), Path.Combine(material, "accounts.json"));
File.Copy(Path.Combine(directory, "healthapp-ca.crt"), Path.Combine(material, "healthapp-ca.crt"));
var target = user + "@" + group.Key;
var windows = names.All(n => deployment.Services[n].Platform == "windows");
if (names.Any(n => deployment.Services[n].Platform == "windows") && !windows)
throw new InvalidOperationException("One host cannot use two native service managers.");
var remote = windows ? "C:/ProgramData/healthapp-install-" + deployment.Id : "/var/tmp/healthapp-install-" + deployment.Id;
Console.WriteLine("Install selected node: " + group.Key);
if (windows)
await Run("ssh", target, "powershell", "-NoProfile", "-NonInteractive", "-Command",
"New-Item -ItemType Directory -Path '" + remote + "' | Out-Null");
else await Run("ssh", target, "mkdir", "-m", "0700", remote);
var scpHost = group.Key.Contains(':') ? user + "@[" + group.Key + "]" : target;
await Run("scp", "-r", node + "/.", scpHost + ":" + remote + "/");
if (windows)
await Run("ssh", target, "powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", remote + "/install.ps1", "-Services", string.Join(',', names),
"-Deployment", remote + "/deployment", "-DeferTopologyCheck");
else await Run("ssh", target, "sudo", "-n", "bash", remote + "/install.sh", "--services", string.Join(',', names),
"--deployment", remote + "/deployment", "--defer-topology-check");
}
// Services communicate through the actual HTTPS origins on their installed hosts.
await InstallationVerification.Verify(directory, selected, selected.Length == Deployment.Names.Length);
Console.WriteLine("Distributed topology verification passed.");
}
finally { Directory.Delete(temporary, true); }
}
private static void CopyDirectory(string source, string destination)
{
Directory.CreateDirectory(destination);
foreach (var file in Directory.GetFiles(source)) File.Copy(file, Path.Combine(destination, Path.GetFileName(file)));
foreach (var child in Directory.GetDirectories(source)) CopyDirectory(child, Path.Combine(destination, Path.GetFileName(child)));
}
}
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Npgsql" Version="10.0.3" />
</ItemGroup>
</Project>
@@ -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.");
}
}
@@ -0,0 +1,32 @@
using System.Text.Json;
using System.Xml.Linq;
namespace HealthApp.Provisioning;
public static class LaunchdWriter
{
public static void Write(string service, string root, string dotnet, string output)
{
if (!Deployment.Names.Contains(service)) throw new InvalidOperationException("Unknown service.");
var directory = Path.Combine(root, "services", service);
var assembly = service switch { "api-gateway" => "ApiGateway", "patient-profile" => "PatientProfileService",
"observation" => "ObservationService", "insights" => "InsightsService", _ => "HealthOverviewService" };
var environment = new XElement("dict");
foreach (var line in File.ReadAllLines(Path.Combine(root, "config", service, "service.env")))
{
var position = line.IndexOf('=');
environment.Add(new XElement("key", line[..position]), new XElement("string", JsonSerializer.Deserialize<string>(line[(position + 1)..])));
}
var document = new XDocument(new XDeclaration("1.0", "utf-8", null),
new XDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null),
new XElement("plist", new XAttribute("version", "1.0"), new XElement("dict",
new XElement("key", "Label"), new XElement("string", "healthapp-" + service),
new XElement("key", "ProgramArguments"), new XElement("array", new XElement("string", dotnet), new XElement("string", Path.Combine(directory, assembly + ".dll"))),
new XElement("key", "WorkingDirectory"), new XElement("string", directory),
new XElement("key", "UserName"), new XElement("string", "_healthapp_" + service.Replace('-', '_')),
new XElement("key", "EnvironmentVariables"), environment,
new XElement("key", "RunAtLoad"), new XElement("true"), new XElement("key", "KeepAlive"), new XElement("true"))));
document.Save(output);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(output, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
}
@@ -0,0 +1,83 @@
using System.Text.Json;
namespace HealthApp.Provisioning;
public static class Program
{
public static async Task<int> Main(string[] args)
{
var command = args.FirstOrDefault() ?? "";
try
{
var options = new Dictionary<string, string>();
for (var index = 1; index < args.Length; index += 2)
{
if (index + 1 >= args.Length || !args[index].StartsWith("--") || !options.TryAdd(args[index][2..], args[index + 1]))
throw new InvalidOperationException("Invalid provisioning arguments.");
}
string Required(string key) => options.GetValueOrDefault(key) ?? throw new InvalidOperationException("Missing argument: " + key);
switch (command)
{
case "launchd":
LaunchdWriter.Write(Required("service"), Required("root"), Required("dotnet"), Required("output"));
break;
case "secret":
File.WriteAllText(Required("output"), Deployment.Secret());
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(Required("output"), UnixFileMode.UserRead | UnixFileMode.UserWrite);
break;
case "admin-connection":
var admin = new Npgsql.NpgsqlConnectionStringBuilder { Host = "localhost", Port = int.Parse(Required("port")),
Username = "postgres", Database = "postgres", Password = File.ReadAllText(Required("password-file")).Trim(), Pooling = false };
File.WriteAllText(Required("output"), admin.ConnectionString);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(Required("output"), UnixFileMode.UserRead | UnixFileMode.UserWrite);
break;
case "execute":
var native = options.GetValueOrDefault("platform", "macos");
var serviceName = Required("service");
if (!Deployment.Names.Contains(serviceName)) throw new InvalidOperationException("Unknown selected service.");
var rootPath = Required("root");
var config = Path.Combine(rootPath, "config", serviceName, "service.env");
var start = new System.Diagnostics.ProcessStartInfo(Required("dotnet")) { UseShellExecute = false,
WorkingDirectory = Path.Combine(rootPath, "services", serviceName) };
start.ArgumentList.Add(Required("assembly"));
start.ArgumentList.Add("--migrate");
foreach (var line in File.ReadAllLines(config))
start.Environment[line[..line.IndexOf('=')]] = JsonSerializer.Deserialize<string>(line[(line.IndexOf('=') + 1)..])!;
using (var process = System.Diagnostics.Process.Start(start)!)
{
await process.WaitForExitAsync();
if (process.ExitCode != 0) throw new InvalidOperationException("Selected service migration failed.");
}
break;
case "prepare":
Deployment.Prepare(Required("output"), options.GetValueOrDefault("host", "localhost"), options.GetValueOrDefault("topology"), options.GetValueOrDefault("certificates"));
break;
case "database":
await DatabaseProvisioning.Create(Required("service-dir"), options.GetValueOrDefault("admin-file"));
break;
case "configure":
ConfigurationWriter.Configure(Required("service-dir"), Required("root"), options.GetValueOrDefault("platform", "linux"));
break;
case "distribute":
var names = Required("services").Split(',');
if (names.Any(n => !Deployment.Names.Contains(n))) throw new InvalidOperationException("Unknown distribution service.");
await Distribution.Deploy(Required("bundle"), Required("deployment"), Required("ssh-user"), names);
break;
case "verify-startup":
case "verify":
var selected = Required("services").Split(',');
if (selected.Any(n => !Deployment.Names.Contains(n))) throw new InvalidOperationException("Unknown verification service.");
await InstallationVerification.Verify(Required("deployment"), selected, options.GetValueOrDefault("complete") == "true", command == "verify-startup");
break;
default: throw new InvalidOperationException("Unknown provisioning command.");
}
return 0;
}
catch (Exception error)
{
Console.Error.WriteLine($"Provisioning step '{command}' failed: " + (error is InvalidOperationException ? error.Message : error.GetType().Name) +
" No credentials are printed; inspect the relevant service logs.");
return 1;
}
}
}
@@ -0,0 +1,258 @@
# US-16 — Provision and install HealthApp
The installer provisions a working prototype topology. A normal installation no longer
requires prepared application configuration, database roles/passwords, service keys,
or HTTPS certificates. Select one service, a comma-separated subset, or `all`.
The application DLLs and shared C# provisioning utility are portable. OS adapters
perform package installation and native service registration: systemd on supported
Linux hosts, Windows Services on Windows, and launchd on macOS. Deployment location
and OS do not combine services, introduce shared persistence or change gateway-routed
communication. There is no container/orchestration requirement.
## Build the release
A build machine needs the .NET 10 SDK and package access. It is distinct from a target
machine, where the installer supplies missing runtime/dependencies.
```bash
bash deploy/build-release.sh --output /tmp/healthapp-release
# Optional: build just a selected application's payload plus the provisioning utility.
bash deploy/build-release.sh --output /tmp/healthapp-insights --services insights
```
On a Windows build machine, use `deploy/build-release.ps1 -Output NEW_DIRECTORY`
from PowerShell with the same optional `-Services` selection.
The bundle includes the application DLLs, provisioning utility, OS installers, units,
examples and this guide. Windows services invoke `dotnet Application.dll`, so they do
not depend on a Linux-generated apphost executable. The small Microsoft WindowsServices
hosting dependency lets the same ASP.NET Core applications respond to Windows service
control; it is inactive on Linux/macOS. No production service references another service.
Transfer the release by normal administrative deployment transport. Public release
files contain no generated secrets. Build output must be a new directory.
## Normal Ubuntu/Debian installation
Automatic Linux provisioning accepts Debian/Ubuntu ancestry (`ID` or `ID_LIKE`),
with apt, a running systemd manager and administrative access. It checks actual package
availability rather than a fixed distribution/version list. Internet access to configured
package feeds is needed when dependencies are absent. Existing .NET 10 ASP.NET Core
runtime and PostgreSQL installations are reused where available.
The installer prefers configured distribution feeds. On Debian itself, if the runtime
package is absent, it attempts Microsoft's repository for that Debian VERSION_ID.
Derivatives use their own configured feeds; their version numbers are never passed to
an upstream repository. If no compatible runtime source or PostgreSQL package is
available, installation stops with a specific dependency error. Debian ancestry alone
does not guarantee .NET/CPU compatibility; startup and topology verification still apply.
From the release directory:
```bash
sudo bash install.sh --services all --host 192.168.1.20
```
Use the target's reachable DNS name/IP for `--host`. The default `localhost` is useful
for a wholly local prototype; use a reachable address for another computer to access
it. No later application-file editing is required.
For an individual service, use its name and an existing matching generated deployment
from the overall topology, which already specifies its remote dependencies/keys:
```bash
sudo bash install.sh --services insights --deployment /secure/generated-deployment
```
Names: `api-gateway`, `patient-profile`, `observation`, `insights`, `health-overview`.
The installer:
1. Detects .NET 10 ASP.NET Core runtime and local PostgreSQL availability; installs
missing dependencies from supported package feeds. PostgreSQL is provisioned only
when Patient/Profile or Observation is selected.
2. Generates a private deployment plan, independent service keys and synthetic
prototype accounts. No hard-coded passwords or hand-written password hashes are used.
3. Creates a private prototype CA and separate service certificates, installs the
public CA into OS trust, and configures Production HTTPS endpoints.
4. Creates separate PostgreSQL databases and login roles for the selected persistent
services. Roles cannot administer the server/create roles/databases or connect to
the other service's database. Schema ownership supports that service's migrations.
5. Creates independent service identities, application/configuration directories and
service registrations. Runs the selected persistent services' migrations, enables
and starts every selected application, then verifies startup and topology.
Linux application/configuration paths are `/opt/healthapp/NAME` and
`/etc/healthapp/NAME/service.env`. Env files are root-only; systemd passes their values
to the owning process. Certificate private keys are readable only by root and the
respective service identity. Units use `healthapp-NAME` users/groups, not a shared
application identity. Gateway key state remains gateway-owned.
Generated material normally resides at `/var/lib/healthapp-installation/deployment`
with a private directory and private files. `accounts.json` contains generated
`prototype-patient`, `prototype-professional` and `installation-check` passwords.
The professional starts without assignments. Do not put generated material in Git.
Only the CA's public certificate is installed/exported publicly; its signing private
key is not retained. Certificates expire after one year; the prototype CA after two.
## Topology and distributed installation
A topology specifies addresses, ports and native platforms, not credentials. Defaults
are HTTPS ports 5443/5081/5082/5083/5084. Colocated applications need different ports.
For example:
```json
{
"hosts": {
"api-gateway": "192.168.1.20",
"patient-profile": "192.168.1.21",
"observation": "192.168.1.22",
"insights": "192.168.1.23",
"health-overview": "192.168.1.24"
},
"platforms": {
"api-gateway": "linux",
"patient-profile": "linux",
"observation": "linux",
"insights": "macos",
"health-overview": "windows"
}
}
```
Optional `ports` uses the same service keys and integer values. Hostnames/IPs must
resolve/reach the corresponding target. Supply existing administrative SSH access;
Unix hosts need passwordless sudo for the installer, Windows SSH sessions must be
elevated administrators. Host administration credentials are distinct from generated
HealthApp/database credentials and are not invented by the application installer.
Generate one consistent deployment and automatically distribute matching, scoped
material to each host:
```bash
sudo bash install.sh --services all --prepare-only --topology topology.json \
--deployment /secure/healthapp-deployment --dotnet /path/to/available/dotnet
bash distribute.sh --deployment /secure/healthapp-deployment --ssh-user administrator
```
Use an administrative session able to read the protected deployment material. The
preparation machine needs an available .NET 10 runtime/SDK for the C# utility.
Distribution uses SSH/SCP, installs only selected applications per host, and exports
only their private material plus necessary remote origins. It starts nodes first,
then verifies the complete topology over its real HTTPS endpoints. No credentials
are manually invented, copied into application files or distributed individually.
Services never depend on a shared runtime directory/file across machines.
A node started with the orchestrator's `--defer-topology-check` has verified local
process/HTTPS/database readiness but pending cross-node verification. It is not
reported as a verified complete topology until the orchestrator's final check passes.
For incremental installation, reuse the same deployment; independently generated
plans deliberately have different keys and cannot authenticate to each other.
## Windows and macOS adapters
On Windows, from an elevated PowerShell session in the release:
```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -Services all -HostName 192.168.1.20
```
The adapter installs the .NET runtime automatically, resolves and checksum-verifies
an EDB PostgreSQL installer from Microsoft's package manifest, creates an owned
PostgreSQL service when needed, and generates its administrator secret in protected
files. Existing application/data files are not overwritten. An existing externally
managed PostgreSQL server can instead be used with `-PostgresAdminFile`; the installer
still generates application database roles/passwords automatically.
Applications have separate native Windows Services and virtual service identities,
protected per-service JSON configuration, state and certificate ACLs. Their Production
configuration is installed automatically; certificates are trusted in LocalMachine
Root. HTTPS firewall rules cover only selected application ports. No IIS is required.
Windows uses `-Deployment`, `-Topology`, `-Certificates` for the same shared material.
Default application root is `%ProgramData%\HealthApp`.
On macOS, from a sudo administrator session:
```bash
sudo bash install.sh --services all --host 192.168.1.20
```
The Darwin adapter installs the ASP.NET Core runtime, provisions Homebrew/PostgreSQL
and required Apple build tools where available through softwareupdate, initializes
an installer-owned PostgreSQL cluster with SCRAM passwords, and creates separate
hidden service identities and launchd daemons. It configures system-keychain CA trust,
private environment/launchd files and selected migrations automatically. Default root
is `/Library/Application Support/HealthApp`. macOS package/tool installation requires
an administrator user session, network access, and acceptance of OS/vendor licensing.
The adapters target supported .NET desktop/server operating systems. Portability does
not claim support for every OS/kernel/version/CPU where .NET itself is unavailable.
The live Windows/macOS registration paths need native-host validation; see evidence
limits below. The Linux execution environment cannot run Windows SCM or macOS launchd.
## Verification and management
Installation verifies distinct native processes, configured HTTPS endpoints, selected
databases using their dedicated credentials, actual service keys and outgoing gateway
access. The complete-system check logs in with the generated `installation-check`
account and exercises profile/observation/Overview through all deployed services.
It creates at most one clearly labelled synthetic check profile/observation if absent.
This is prototype test data, not a clinical reading; repeated verification reuses it.
The verifier trusts the generated public CA, validates certificate chains/server names,
and never disables TLS validation. Existing HTTPS trust is retained. All step failures
identify the failed operation/service and retain existing data/material for inspection.
Sensitive SQL/credentials are not printed. Existing applications/configuration cause
refusal rather than silent replacement; this remains a first-install mechanism,
not an upgrade/uninstall/data-removal tool. Deployment is not a cross-service transaction.
Linux may rerun `sudo bash verify.sh --services all --deployment DIRECTORY` from the
bundle. Manage selected units with `systemctl start/stop/restart healthapp-NAME`.
Windows uses `Start-Service`, `Stop-Service`, `Restart-Service`; macOS uses
`launchctl bootstrap`, `bootout`, `kickstart` on `healthapp-NAME` labels. Stopping a
service does not directly stop peer processes; requests needing it may fail.
External trusted certificates can be supplied during preparation with `--certificates`
or `-Certificates`. The directory supplies `NAME.pfx`, `NAME.password` for all five
planned services and `healthapp-ca.crt`. Supplied PFX certificate chains are retained;
private keys/passwords are protected and configured automatically. Prototype browser
clients may import the exported public CA for trust; server-side service trust is
configured automatically by installation.
`--root DIRECTORY` on Linux is explicitly offline staging: it generates the same
settings/material but cannot install host packages or register/start systemd. It is
not reported as a live verified installation. `--postgres-admin-file` allows automated
DB provisioning against an externally managed/test server, not manual application
DB/user preparation. Normal Linux installation administers local PostgreSQL through
its OS postgres identity without inventing a PostgreSQL administrator password.
## Evidence and dependencies
The xUnit deployment suite builds the release, calls the actual provisioner/installer,
creates database roles/databases in an isolated PostgreSQL server and runs all five
installed services in separate Production-mode HTTPS processes. Tests cover generated
key matching/uniqueness, certificate private-key output, private configuration, database
isolation/permissions, migrations, native-format configuration, independent restart,
representative functionality and repeated non-destructive verification. Package command
contracts are tested with controlled command doubles; no host package installation
is performed by the tests. The ordinary application tests remain unchanged.
Linux HTTPS/interservice/database execution is verified here. Live systemd package/
registration behaviour needs a supported Linux host; Windows/macOS service registration
needs those native hosts. Native configuration formats are exercised by the shared
utility tests; shell/PowerShell syntax validation is separate from a native end-to-end
run. The manual `.github/workflows/prototype-native-install.yml` workflow provisions
and verifies fresh Ubuntu, Windows and macOS runners; it is supplied for native
validation and has not been executed remotely in this session. These limits must not be described as verified production deployment on every OS.
The provisioning tool uses standard .NET X.509/password hashing and Npgsql for creating
and checking databases. Its dependency is not a shared service runtime library.
Microsoft.Extensions.Hosting.WindowsServices is added to the five services solely for
native Windows service lifetime integration; Linux/macOS responsibilities are unchanged.
Package/lifetime references reviewed during implementation:
[Ubuntu runtime installation](https://learn.microsoft.com/en-us/dotnet/core/install/linux-ubuntu-install),
[Debian runtime installation](https://learn.microsoft.com/en-us/dotnet/core/install/linux-debian),
[Windows service hosting](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-10.0),
[EDB unattended installer parameters](https://www.enterprisedb.com/docs/supported-open-source/postgresql/installing/command_line_parameters/).
@@ -0,0 +1,33 @@
ASPNETCORE_ENVIRONMENT=Production
Services__PatientProfile__BaseUrl=https://patient-profile.example.test:5081/
ASPNETCORE_URLS=https://0.0.0.0:5443
Kestrel__Certificates__Default__Path=/etc/healthapp/gateway.pfx
Kestrel__Certificates__Default__Password=REPLACE_ME
Services__Observation__BaseUrl=https://observation.example.test:5082/
Services__Insights__BaseUrl=https://insights.example.test:5083/
Authentication__KeyDirectory=/var/lib/healthapp-api-gateway/keys
Authentication__TokenLifetimeMinutes=30
# Account identifiers support ASCII letters, digits, hyphen and underscore.
Authentication__Accounts__0__AccountId=example-patient
Authentication__Accounts__0__Role=Patient
Authentication__Accounts__0__PasswordHash=REPLACE_WITH_ASPNET_CORE_PASSWORD_HASH
# Use distinct randomly generated credentials of at least 32 characters.
Services__PatientProfile__Key=REPLACE_ME
Services__Observation__Key=REPLACE_ME
Services__Insights__Key=REPLACE_ME
InternalAccess__Observation__Key=REPLACE_ME
InternalAccess__Insights__Key=REPLACE_ME
# Pre-created professional credentials and read-only patient assignments.
Authentication__Accounts__1__AccountId=example_professional
Authentication__Accounts__1__Role=HealthcareProfessional
Authentication__Accounts__1__PasswordHash=REPLACE_WITH_ASPNET_CORE_PASSWORD_HASH
# Replace the synthetic identifier below with a created patient's identifier.
# Restart the gateway after changing assignments. Omit assignments for an empty list.
Access__ProfessionalAssignments__example_professional__0=00000000-0000-0000-0000-000000000001
Services__HealthOverview__BaseUrl=https://health-overview.example.test:5084/
Services__HealthOverview__Key=REPLACE_ME
InternalAccess__HealthOverview__Key=REPLACE_ME
@@ -0,0 +1,22 @@
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$Output, [string]$Services='all')
$ErrorActionPreference='Stop'
$assemblies=@{ 'api-gateway'='ApiGateway'; 'patient-profile'='PatientProfileService'; 'observation'='ObservationService'; 'insights'='InsightsService'; 'health-overview'='HealthOverviewService' }
$selected=if ($Services -eq 'all') { @('api-gateway','patient-profile','observation','insights','health-overview') } else { @($Services.Split(',')) }
if ((Test-Path $Output) -or @($selected | Select-Object -Unique).Count -ne $selected.Count) { throw 'Use a new output directory and unique service names.' }
foreach ($name in $selected) { if (-not $assemblies.ContainsKey($name)) { throw "Unknown service: $name" } }
New-Item -ItemType Directory -Path $Output | Out-Null
$destination=(Resolve-Path $Output).Path
$repository=Split-Path $PSScriptRoot -Parent
foreach ($directory in @('services','systemd','examples')) { New-Item -ItemType Directory -Path "$destination\$directory" | Out-Null }
Copy-Item "$PSScriptRoot\installer\*.sh","$PSScriptRoot\installer\*.ps1","$PSScriptRoot\INSTALLATION.md" $destination
foreach ($name in $selected) {
& dotnet publish "$repository\src\$($assemblies[$name])\$($assemblies[$name]).csproj" --configuration Release --self-contained false '-p:UseAppHost=false' --output "$destination\services\$name"
if ($LASTEXITCODE -ne 0) { throw "Publish failed: $name" }
Copy-Item "$PSScriptRoot\systemd\healthapp-$name.service" "$destination\systemd"
Copy-Item "$PSScriptRoot\$name.env.example" "$destination\examples"
}
& dotnet publish "$PSScriptRoot\HealthApp.Provisioning\HealthApp.Provisioning.csproj" --configuration Release --self-contained false '-p:UseAppHost=false' --output "$destination\provisioner"
if ($LASTEXITCODE -ne 0) { throw 'Publish failed: provisioning utility' }
$selected | Set-Content "$destination\services.list"
Write-Host "Portable release created: $destination"
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
fail() { printf 'Error: %s\n' "$*" >&2; exit 1; }
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
repo_dir=$(cd -- "$script_dir/.." && pwd)
source "$script_dir/installer/services.sh"
requested=all
output=
while [[ $# -gt 0 ]]; do
case "$1" in
--output) [[ $# -gt 1 ]] || fail 'Missing output directory.'; output=$2; shift 2;;
--services) [[ $# -gt 1 ]] || fail 'Missing services.'; requested=$2; shift 2;;
--help) printf '%s\n' 'Usage: bash deploy/build-release.sh --output NEW_DIRECTORY [--services all|api-gateway,patient-profile,observation,insights,health-overview]' 'Requires .NET 10 SDK. HEALTHAPP_DOTNET may select its executable.'; exit 0;;
*) fail "Unknown argument: $1";;
esac
done
select_services "$requested"
[[ -n "$output" && ! -e "$output" ]] || fail 'Provide a new, non-existing output directory.'
dotnet_command=${HEALTHAPP_DOTNET:-dotnet}
command -v "$dotnet_command" >/dev/null || fail '.NET 10 SDK is required to build a release.'
mkdir -p -- "$output/services" "$output/systemd" "$output/examples"
output=$(cd -- "$output" && pwd)
cp -- "$script_dir/installer/"*.sh "$output/"
cp -- "$script_dir/installer/"*.ps1 "$output/"
cp -- "$script_dir/INSTALLATION.md" "$output/"
for service in "${selected_services[@]}"; do
assembly=$(assembly_for "$service")
"$dotnet_command" publish "$repo_dir/src/$assembly/$assembly.csproj" --configuration Release --self-contained false -p:UseAppHost=false --output "$output/services/$service"
cp -- "$script_dir/systemd/healthapp-$service.service" "$output/systemd/"
cp -- "$script_dir/$service.env.example" "$output/examples/"
done
"$dotnet_command" publish "$script_dir/HealthApp.Provisioning/HealthApp.Provisioning.csproj" --configuration Release --self-contained false -p:UseAppHost=false --output "$output/provisioner"
printf '%s\n' "${selected_services[@]}" > "$output/services.list"
printf 'Release created: %s\n' "$output"
@@ -0,0 +1,8 @@
ASPNETCORE_ENVIRONMENT=Production
ASPNETCORE_URLS=https://0.0.0.0:5084
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
InternalAccess__GatewayKey=REPLACE_ME
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
Kestrel__Certificates__Default__Password=REPLACE_ME
Services__ApiGateway__Key=REPLACE_ME
@@ -0,0 +1,8 @@
ASPNETCORE_ENVIRONMENT=Production
ASPNETCORE_URLS=https://0.0.0.0:5083
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
InternalAccess__GatewayKey=REPLACE_ME
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
Kestrel__Certificates__Default__Password=REPLACE_ME
Services__ApiGateway__Key=REPLACE_ME
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Source from install.sh. Package commands use the supported distribution's signed feeds.
package_available() {
local policy
policy=$(LC_ALL=C apt-cache policy "$1") || return 1
[[ "$policy" =~ Candidate:[[:space:]]+([^[:space:]]+) && "${BASH_REMATCH[1]}" != '(none)' ]]
}
ensure_dependencies() {
local distribution=$1 version=$2 runtime=$3 persistence=$4 ancestry=${5:-}
case " $distribution $ancestry " in
*" debian "*|*" ubuntu "*) ;;
*) fail 'Automatic Linux provisioning requires a Debian/Ubuntu-based distribution (ID or ID_LIKE).';;
esac
command -v apt-get >/dev/null && command -v apt-cache >/dev/null || fail 'Debian/Ubuntu provisioning requires apt-get and apt-cache.'
step='refresh dependency package availability'
apt-get update || fail 'Could not refresh package feeds; check network access and configured repositories.'
step='install base dependencies'
if ! command -v curl >/dev/null || ! command -v update-ca-certificates >/dev/null; then
DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates curl
fi
if [[ ! -x "$runtime" ]] || ! "$runtime" --list-runtimes | grep -q 'Microsoft.AspNetCore.App 10\.'; then
step='install .NET 10 ASP.NET Core runtime'
if ! package_available aspnetcore-runtime-10.0 && [[ "$distribution" == debian ]]; then
[[ "$version" =~ ^[0-9]+$ ]] || fail 'Cannot identify a compatible Microsoft Debian package repository from VERSION_ID.'
local package_dir
package_dir=$(mktemp -d)
if ! curl --fail --silent --show-error --location "https://packages.microsoft.com/config/debian/$version/packages-microsoft-prod.deb" -o "$package_dir/microsoft.deb"; then
rm -f -- "$package_dir/microsoft.deb"
rmdir -- "$package_dir"
fail "No accessible Microsoft Debian $version repository; aspnetcore-runtime-10.0 is unavailable in configured feeds."
fi
dpkg -i "$package_dir/microsoft.deb"
rm -f -- "$package_dir/microsoft.deb"
rmdir -- "$package_dir"
apt-get update
fi
package_available aspnetcore-runtime-10.0 || fail "Required package aspnetcore-runtime-10.0 is unavailable for $distribution $version in configured feeds; no compatible runtime repository could be identified automatically."
DEBIAN_FRONTEND=noninteractive apt-get install -y aspnetcore-runtime-10.0 || fail 'Failed to install aspnetcore-runtime-10.0 from configured feeds.'
fi
[[ -x "$runtime" ]] && "$runtime" --list-runtimes | grep -q 'Microsoft.AspNetCore.App 10\.' || fail 'The .NET 10 ASP.NET Core runtime could not be provisioned.'
if [[ "$persistence" == true ]]; then
step='provision PostgreSQL server'
if ! command -v pg_isready >/dev/null || ! pg_isready -q -h localhost -p 5432; then
package_available postgresql || fail "Required package postgresql is unavailable for $distribution $version in configured feeds."
DEBIAN_FRONTEND=noninteractive apt-get install -y postgresql || fail 'Failed to install PostgreSQL from configured feeds.'
systemctl enable --now postgresql
fi
local ready=false attempt
for attempt in {1..30}; do
if pg_isready -q -h localhost -p 5432; then ready=true; break; fi
sleep 1
done
[[ "$ready" == true ]] || fail 'PostgreSQL did not become available on localhost:5432.'
fi
}
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
fail() { printf 'Distribution failed: %s\n' "$*" >&2; exit 1; }
source "$script_dir/services.sh"
deployment=
requested=all
ssh_user=
dotnet_path=/usr/bin/dotnet
while [[ $# -gt 0 ]]; do
case "$1" in
--deployment|--services|--ssh-user|--dotnet)
[[ $# -gt 1 ]] || fail 'Missing argument.'
case "$1" in --deployment) deployment=$2;; --services) requested=$2;; --ssh-user) ssh_user=$2;; --dotnet) dotnet_path=$2;; esac
shift 2;;
--help) printf '%s\n' 'Usage: bash distribute.sh --deployment GENERATED_DIRECTORY --ssh-user ADMIN_USER [--services all|NAME[,NAME]] [--dotnet PATH]' 'Uses configured SSH access and passwordless sudo on the topology hosts. Generates no new credentials; installs matching scoped material and verifies the topology.'; exit 0;;
*) fail "Unknown argument: $1";;
esac
done
select_services "$requested"
[[ -n "$deployment" && -n "$ssh_user" ]] || fail 'Deployment directory and SSH administrator are required.'
"$dotnet_path" "$script_dir/provisioner/HealthApp.Provisioning.dll" distribute --bundle "$script_dir" \
--deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")" --ssh-user "$ssh_user"
@@ -0,0 +1,156 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
step=arguments
fail() { printf 'Installation failed at %s: %s\n' "$step" "$*" >&2; exit 1; }
trap 'printf "Installation failed at %s (line %s). Existing data was retained.\n" "$step" "$LINENO" >&2' ERR
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
source "$script_dir/services.sh"
requested=
root='/Library/Application Support/HealthApp'
host=localhost
topology=
deployment=
external_certificates=
admin_file=
prepare_only=false
defer=false
while [[ $# -gt 0 ]]; do
case "$1" in
--services|--host|--topology|--deployment|--certificates|--root|--postgres-admin-file)
[[ $# -gt 1 ]] || fail 'Missing value.'
case "$1" in --services) requested=$2;; --host) host=$2;; --topology) topology=$2;; --deployment) deployment=$2;;
--certificates) external_certificates=$2;; --root) root=$2;; --postgres-admin-file) admin_file=$2;; esac
shift 2;;
--prepare-only) prepare_only=true; shift;;
--defer-topology-check) defer=true; shift;;
--help) printf '%s\n' 'Usage: sudo bash install.sh --services all|NAME[,NAME] [--host DNS_OR_IP] [--topology FILE] [--deployment GENERATED_DIRECTORY]' 'macOS installs the runtime/PostgreSQL and independent launchd daemons using the same application DLLs and provisioning utility.'; exit 0;;
*) fail "Unknown argument: $1";;
esac
done
[[ $(uname -s) == Darwin && $EUID -eq 0 ]] || fail 'Run under sudo on macOS.'
select_services "$requested"
for service in "${selected_services[@]}"; do
[[ ! -e "$root/services/$service" && ! -e "/Library/LaunchDaemons/healthapp-$service.plist" ]] || fail "Already installed: $service."
done
mkdir -p "$root"
chmod 0711 "$root"
step='install .NET 10 ASP.NET Core runtime'
dotnet_path="$root/runtime/dotnet"
if command -v dotnet >/dev/null && dotnet --list-runtimes | grep -q 'Microsoft.AspNetCore.App 10\.'; then dotnet_path=$(command -v dotnet); fi
if [[ ! -x "$dotnet_path" ]]; then
curl --fail --silent --show-error https://dot.net/v1/dotnet-install.sh -o "$root/dotnet-install.sh"
bash "$root/dotnet-install.sh" --channel 10.0 --runtime aspnetcore --install-dir "$root/runtime" --no-path
chmod -R a+rX "$root/runtime"
fi
provision=("$dotnet_path" "$script_dir/provisioner/HealthApp.Provisioning.dll")
step='generate credentials and HTTPS certificates'
[[ -n "$deployment" ]] || deployment="$root/deployment"
if [[ ! -f "$deployment/deployment.json" ]]; then
args=(prepare --output "$deployment" --host "$host")
[[ -z "$topology" ]] || args+=(--topology "$topology")
[[ -z "$external_certificates" ]] || args+=(--certificates "$external_certificates")
"${provision[@]}" "${args[@]}"
fi
[[ "$prepare_only" == false ]] || { printf 'Generated deployment in %s\n' "$deployment"; exit 0; }
step='configure HTTPS trust'
security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$deployment/healthapp-ca.crt"
create_identity() {
local name=$1 uid=300
if id "$name" >/dev/null 2>&1; then return; fi
while dscl . -search /Users UniqueID "$uid" | grep -q . || dscl . -search /Groups PrimaryGroupID "$uid" | grep -q .; do uid=$((uid+1)); done
dscl . -create "/Groups/$name"
dscl . -create "/Groups/$name" PrimaryGroupID "$uid"
dscl . -create "/Users/$name"
dscl . -create "/Users/$name" UniqueID "$uid"
dscl . -create "/Users/$name" PrimaryGroupID "$uid"
dscl . -create "/Users/$name" UserShell /usr/bin/false
dscl . -create "/Users/$name" NFSHomeDirectory /var/empty
dscl . -create "/Users/$name" IsHidden 1
}
persistence=false
for service in "${selected_services[@]}"; do case "$service" in patient-profile|observation) persistence=true;; esac; done
if [[ "$persistence" == true && -z "$admin_file" ]]; then
step='install PostgreSQL binaries'
brew_user=${SUDO_USER:-}
[[ -n "$brew_user" && "$brew_user" != root ]] || fail 'Run sudo from an administrator account so Homebrew can run as that user.'
if ! xcode-select -p >/dev/null 2>&1; then
touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
label=$(softwareupdate --list 2>&1 | sed -n 's/^.*Label: \(Command Line Tools.*\)/\1/p' | tail -n 1)
[[ -n "$label" ]] || fail 'Apple did not offer Command Line Tools through softwareupdate.'
softwareupdate --install "$label" --agree-to-license
rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
fi
brew_path=/opt/homebrew/bin/brew
[[ -x "$brew_path" ]] || brew_path=/usr/local/bin/brew
if [[ ! -x "$brew_path" ]]; then
curl --fail --silent --show-error https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh -o "$root/homebrew-install.sh"
chmod 0644 "$root/homebrew-install.sh"
sudo -u "$brew_user" env NONINTERACTIVE=1 bash "$root/homebrew-install.sh"
[[ -x /opt/homebrew/bin/brew ]] && brew_path=/opt/homebrew/bin/brew || brew_path=/usr/local/bin/brew
fi
sudo -u "$brew_user" "$brew_path" install postgresql@17
pg_prefix=$(sudo -u "$brew_user" "$brew_path" --prefix postgresql@17)
step='create installer-owned PostgreSQL cluster'
pg_identity=_healthapp_postgres
create_identity "$pg_identity"
admin_file="$root/postgres-admin.connection"
if [[ ! -f "$admin_file" ]]; then
port=5432
while nc -z localhost "$port" >/dev/null 2>&1; do port=$((port+1)); done
"${provision[@]}" secret --output "$root/postgres.password"
mkdir -p "$root/postgresql-data"
chown "$pg_identity:$pg_identity" "$root/postgresql-data" "$root/postgres.password"
sudo -u "$pg_identity" "$pg_prefix/bin/initdb" -D "$root/postgresql-data" -U postgres --auth-local=scram-sha-256 --auth-host=scram-sha-256 --pwfile "$root/postgres.password"
printf '\nport = %s\n' "$port" >> "$root/postgresql-data/postgresql.conf"
"${provision[@]}" admin-connection --password-file "$root/postgres.password" --port "$port" --output "$admin_file"
pg_plist=/Library/LaunchDaemons/healthapp-postgresql.plist
cat > "$pg_plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict><key>Label</key><string>healthapp-postgresql</string><key>ProgramArguments</key><array><string>$pg_prefix/bin/postgres</string><string>-D</string><string>$root/postgresql-data</string></array><key>UserName</key><string>$pg_identity</string><key>RunAtLoad</key><true/><key>KeepAlive</key><true/></dict></plist>
PLIST
chmod 0644 "$pg_plist"
launchctl bootstrap system "$pg_plist"
fi
port=$(sed -n 's/.*Port=\([0-9]*\).*/\1/p' "$admin_file")
[[ -n "$port" ]] || port=5432
for attempt in {1..30}; do if "$pg_prefix/bin/pg_isready" -q -p "$port"; then break; fi; sleep 1; done
fi
for service in "${selected_services[@]}"; do
step="configure $service"
identity="_healthapp_${service//-/_}"
create_identity "$identity"
case "$service" in patient-profile|observation)
"${provision[@]}" database --service-dir "$deployment/$service" --admin-file "$admin_file";;
esac
"${provision[@]}" configure --service-dir "$deployment/$service" --root "$root" --platform macos
mkdir -p "$root/services" "$root/config" "$root/state"
chmod 0711 "$root/services" "$root/config" "$root/state"
cp -R "$script_dir/services/$service" "$root/services/$service"
chmod -R a+rX "$root/services/$service"
chgrp -R "$identity" "$root/config/$service"
chmod 0750 "$root/config/$service"
chmod 0640 "$root/config/$service/"*
if [[ "$service" == api-gateway ]]; then
mkdir -p "$root/state/api-gateway/keys"
chown -R "$identity:$identity" "$root/state/api-gateway"
chmod 0700 "$root/state/api-gateway"
fi
case "$service" in patient-profile|observation)
"${provision[@]}" execute --service "$service" --assembly "$root/services/$service/$(assembly_for "$service").dll" --dotnet "$dotnet_path" --root "$root";;
esac
# plutil converts the JSON object to an XML plist without treating configuration as shell code.
"$dotnet_path" "$script_dir/provisioner/HealthApp.Provisioning.dll" launchd --service "$service" --root "$root" --dotnet "$dotnet_path" --output "/Library/LaunchDaemons/healthapp-$service.plist"
chmod 0600 "/Library/LaunchDaemons/healthapp-$service.plist"
launchctl bootstrap system "/Library/LaunchDaemons/healthapp-$service.plist"
done
step='verify startup and HTTPS'
for service in "${selected_services[@]}"; do launchctl print "system/healthapp-$service" >/dev/null; done
"${provision[@]}" verify-startup --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")"
if [[ "$defer" == false ]]; then
args=(verify --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")")
[[ "$requested" != all ]] || args+=(--complete true)
"${provision[@]}" "${args[@]}"
fi
printf 'Installation completed. Account credentials: %s/accounts.json\n' "$deployment"
@@ -0,0 +1,159 @@
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$Services,
[string]$HostName = 'localhost',
[string]$Topology,
[string]$Deployment,
[string]$Certificates,
[string]$PostgresAdminFile,
[string]$Root = "$env:ProgramData\HealthApp",
[switch]$PrepareOnly,
[switch]$DeferTopologyCheck
)
$ErrorActionPreference = 'Stop'
$step = 'arguments'
function Check-Exit([string]$Operation) { if ($LASTEXITCODE -ne 0) { throw "$Operation failed (exit $LASTEXITCODE)." } }
function Protect-Private([string]$Path) {
& icacls.exe $Path /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null
Check-Exit 'Protect private deployment files'
}
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run from an elevated PowerShell session.' }
$assemblies = @{ 'api-gateway'='ApiGateway'; 'patient-profile'='PatientProfileService'; 'observation'='ObservationService'; 'insights'='InsightsService'; 'health-overview'='HealthOverviewService' }
$selected = if ($Services -eq 'all') { @('api-gateway','patient-profile','observation','insights','health-overview') } else { @($Services.Split(',')) }
if (@($selected | Select-Object -Unique).Count -ne $selected.Count) { throw 'Repeated service selection.' }
foreach ($name in $selected) {
if (-not $assemblies.ContainsKey($name)) { throw "Unknown service: $name" }
if (-not (Test-Path "$PSScriptRoot\services\$name\$($assemblies[$name]).dll")) { throw "Missing release: $name" }
if ((Test-Path "$Root\services\$name") -or (Get-Service "healthapp-$name" -ErrorAction SilentlyContinue)) { throw "Already installed: $name. Existing files were not changed." }
}
New-Item -ItemType Directory -Force $Root | Out-Null
Protect-Private $Root
$step = 'install .NET 10 ASP.NET Core runtime'
$dotnet = "$Root\runtime\dotnet.exe"
if (Get-Command dotnet.exe -ErrorAction SilentlyContinue) {
$candidate = (Get-Command dotnet.exe).Source
if ((& $candidate --list-runtimes) -match 'Microsoft.AspNetCore.App 10\.') { $dotnet = $candidate }
}
if (-not (Test-Path $dotnet)) {
$script = "$Root\dotnet-install.ps1"
Invoke-WebRequest 'https://dot.net/v1/dotnet-install.ps1' -OutFile $script -UseBasicParsing
& $script -Channel '10.0' -Runtime 'aspnetcore' -InstallDir "$Root\runtime" -NoPath
if (-not (Test-Path $dotnet)) { throw 'Runtime installation did not produce dotnet.exe.' }
}
$utility = "$PSScriptRoot\provisioner\HealthApp.Provisioning.dll"
$step = 'generate deployment material'
if (-not $Deployment) { $Deployment = "$Root\deployment" }
if (-not (Test-Path "$Deployment\deployment.json")) {
$prepare = @($utility,'prepare','--output',$Deployment,'--host',$HostName)
if ($Topology) { $prepare += @('--topology',$Topology) }
if ($Certificates) { $prepare += @('--certificates',$Certificates) }
& $dotnet @prepare
Check-Exit 'Generate credentials and HTTPS certificates'
}
Protect-Private $Deployment
if ($PrepareOnly) { Write-Host "Generated protected deployment material in $Deployment"; return }
$step = 'install prototype HTTPS trust'
Import-Certificate -FilePath "$Deployment\healthapp-ca.crt" -CertStoreLocation Cert:\LocalMachine\Root | Out-Null
$needsPostgres = ($selected -contains 'patient-profile') -or ($selected -contains 'observation')
if ($needsPostgres -and -not $PostgresAdminFile) {
$PostgresAdminFile = "$Root\postgres-admin.connection"
if (-not (Test-Path $PostgresAdminFile)) {
$step = 'install PostgreSQL'
# Resolve the maintained Microsoft package manifest, verify the vendor binary checksum,
# and pass the generated administrator secret through a protected options file.
$headers = @{ 'User-Agent'='HealthApp-Prototype-Installer' }
$manifestBase = 'https://api.github.com/repos/microsoft/winget-pkgs/contents/manifests/p/PostgreSQL/PostgreSQL/17'
$versions = Invoke-RestMethod $manifestBase -Headers $headers
$latest = $versions | Sort-Object @{Expression={[version]($_.name.Split('-')[0])}}, @{Expression={[int]($_.name.Split('-')[-1])}} -Descending | Select-Object -First 1
$files = Invoke-RestMethod $latest.url -Headers $headers
$manifest = $files | Where-Object { $_.name -like '*.installer.yaml' } | Select-Object -First 1
$yaml = (Invoke-WebRequest $manifest.download_url -UseBasicParsing).Content
$download = [regex]::Match($yaml,'(?m)^\s*InstallerUrl:\s*(\S+)').Groups[1].Value
$checksum = [regex]::Match($yaml,'(?m)^\s*InstallerSha256:\s*([A-Fa-f0-9]{64})').Groups[1].Value
if (-not $download.StartsWith('https://get.enterprisedb.com/') -or -not $checksum) { throw 'PostgreSQL package manifest is invalid.' }
$installer = "$Root\postgresql-installer.exe"
Invoke-WebRequest $download -OutFile $installer -UseBasicParsing
if ((Get-FileHash $installer -Algorithm SHA256).Hash -ne $checksum) { throw 'PostgreSQL installer checksum does not match.' }
$random = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($random); $rng.Dispose()
$adminPassword = [BitConverter]::ToString($random).Replace('-','') + 'a!'
$port = 5432
$listener = New-Object Net.Sockets.TcpListener([Net.IPAddress]::Loopback,$port)
try { $listener.Start() } catch { $listener = New-Object Net.Sockets.TcpListener([Net.IPAddress]::Loopback,0); $listener.Start(); $port = $listener.LocalEndpoint.Port }
finally { $listener.Stop() }
$options = "$Root\postgresql.options"
@('mode=unattended','unattendedmodeui=none','debuglevel=0','enable-components=server,commandlinetools',
"prefix=$Root\postgresql","datadir=$Root\postgresql-data","serverport=$port",'servicename=healthapp-postgresql',
'serviceaccount=NT AUTHORITY\NetworkService',"superpassword=$adminPassword") | Set-Content $options -Encoding UTF8
Protect-Private $options
$installed = Start-Process $installer -ArgumentList @('--optionfile',('"'+$options+'"')) -Wait -PassThru
if ($installed.ExitCode -ne 0) { throw 'PostgreSQL unattended installation failed.' }
"Host=localhost;Port=$port;Database=postgres;Username=postgres;Password=$adminPassword" | Set-Content $PostgresAdminFile -Encoding UTF8
Protect-Private $PostgresAdminFile
Remove-Item $options
}
Start-Service 'healthapp-postgresql'
}
foreach ($name in $selected) {
$step = "configure $name"
if ($name -eq 'patient-profile' -or $name -eq 'observation') {
& $dotnet $utility database --service-dir "$Deployment\$name" --admin-file $PostgresAdminFile
Check-Exit "Create dedicated $name database and credentials"
}
& $dotnet $utility configure --service-dir "$Deployment\$name" --root $Root --platform windows
Check-Exit "Configure $name"
New-Item -ItemType Directory -Force "$Root\services" | Out-Null
$application = "$Root\services\$name"
Copy-Item "$PSScriptRoot\services\$name" $application -Recurse
Copy-Item "$Root\config\$name\appsettings.Production.json" "$application\appsettings.Production.json"
$dll = "$application\$($assemblies[$name]).dll"
if ($name -eq 'patient-profile' -or $name -eq 'observation') {
& $dotnet $dll --migrate --contentRoot $application --environment Production
Check-Exit "Migrate $name database"
}
$serviceName = "healthapp-$name"
$binary = '"'+$dotnet+'" "'+$dll+'" --contentRoot "'+$application+'" --environment Production'
New-Service -Name $serviceName -BinaryPathName $binary -StartupType Automatic -Description "HealthApp $name" | Out-Null
& sc.exe config $serviceName obj= "NT SERVICE\$serviceName" | Out-Null
Check-Exit "Configure independent $name virtual service account"
& icacls.exe $application /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null
& icacls.exe "$Root\config\$name" /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null
if ($name -eq 'api-gateway') {
New-Item -ItemType Directory -Force "$Root\state\api-gateway\keys" | Out-Null
& icacls.exe "$Root\state\api-gateway" /grant "NT SERVICE\${serviceName}:(OI)(CI)M" /T | Out-Null
}
# Service identities need traversal/runtime access, not other services' private configuration.
foreach ($parent in @("$Root\services","$Root\config","$Root\state")) {
if (Test-Path $parent) { & icacls.exe $parent /grant "NT SERVICE\${serviceName}:RX" | Out-Null }
}
& icacls.exe $Root /grant "NT SERVICE\${serviceName}:RX" | Out-Null
if ($dotnet.StartsWith($Root)) { & icacls.exe "$Root\runtime" /grant "NT SERVICE\${serviceName}:(OI)(CI)RX" /T | Out-Null }
& sc.exe failure $serviceName reset= 86400 actions= restart/5000 | Out-Null
$settings = Get-Content "$Deployment\$name\service.json" -Raw | ConvertFrom-Json
New-NetFirewallRule -DisplayName "HealthApp $name HTTPS" -Direction Inbound -Action Allow -Protocol TCP -LocalPort $settings.Port -Program $dotnet | Out-Null
Start-Service $serviceName
}
$step = 'verify running processes and HTTPS'
$processIds = @()
foreach ($name in $selected) {
$native = Get-CimInstance Win32_Service -Filter "Name='healthapp-$name'"
if ($native.State -ne 'Running' -or $native.ProcessId -eq 0 -or ($processIds -contains $native.ProcessId)) { throw "$name is not an independent running service." }
$processIds += $native.ProcessId
}
& $dotnet $utility verify-startup --deployment $Deployment --services ($selected -join ',')
Check-Exit 'HTTPS startup verification'
if (-not $DeferTopologyCheck) {
$verify = @($utility,'verify','--deployment',$Deployment,'--services',($selected -join ','))
if ($Services -eq 'all') { $verify += @('--complete','true') }
& $dotnet @verify
Check-Exit 'Dependency and representative workflow verification'
}
Write-Host "Installation completed. Generated account credentials are protected in $Deployment\accounts.json"
} catch {
Write-Error "Installation failed at ${step}: $($_.Exception.Message). Existing data and deployment material were retained."
exit 1
}
@@ -0,0 +1,150 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
step=arguments
fail() { printf 'Installation failed at %s: %s\n' "$step" "$*" >&2; exit 1; }
trap 'printf "Installation failed at %s (line %s). Existing data and generated material were retained.\n" "$step" "$LINENO" >&2' ERR
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
if [[ $(uname -s) == Darwin ]]; then exec bash "$script_dir/install-macos.sh" "$@"; fi
source "$script_dir/services.sh"
source "$script_dir/bootstrap.sh"
bundle=$script_dir
requested=
target_root=/
dotnet_path=/usr/bin/dotnet
host=localhost
topology=
deployment=
external_certificates=
admin_file=
prepare_only=false
defer_verification=false
while [[ $# -gt 0 ]]; do
case "$1" in
--bundle|--services|--root|--dotnet|--host|--topology|--deployment|--certificates|--postgres-admin-file)
[[ $# -gt 1 ]] || fail "Missing value for $1."
case "$1" in --bundle) bundle=$2;; --services) requested=$2;; --root) target_root=$2;; --dotnet) dotnet_path=$2;;
--host) host=$2;; --topology) topology=$2;; --deployment) deployment=$2;; --certificates) external_certificates=$2;;
--postgres-admin-file) admin_file=$2;; esac
shift 2;;
--prepare-only) prepare_only=true; shift;;
--defer-topology-check) defer_verification=true; shift;;
--help) printf '%s\n' 'Usage: bash install.sh --services all|NAME[,NAME] [--host DNS_OR_IP] [--topology topology.json] [--deployment generated-directory]' 'Provisioning installs runtime/PostgreSQL as needed and generates credentials, HTTPS, configuration, migrations and running systemd services.' 'Optional --root DIRECTORY stages generated files offline; --dotnet PATH selects the available runtime.' '--prepare-only generates a deployment for automatic distribution with distribute.sh. --certificates DIR accepts external certificates.'; exit 0;;
*) fail "Unknown argument: $1";;
esac
done
select_services "$requested"
[[ $(uname -s) == Linux ]] || fail 'Only Linux is supported.'
[[ "$target_root" == /* && "$target_root" != *$'\n'* ]] || fail 'Root must be an absolute path.'
[[ "$dotnet_path" =~ ^/[A-Za-z0-9_./+-]+$ ]] || fail 'Runtime path is invalid.'
target_root=$(realpath -m -- "$target_root")
step=preflight
for service in "${selected_services[@]}"; do
assembly=$(assembly_for "$service")
[[ -f "$bundle/services/$service/$assembly.dll" && -f "$bundle/systemd/healthapp-$service.service" ]] || fail "Missing release payload: $service"
[[ ! -e "$target_root/opt/healthapp/$service" && ! -e "$target_root/etc/healthapp/$service" && ! -e "$target_root/etc/systemd/system/healthapp-$service.service" ]] || fail "Already installed: $service; existing configuration was not changed."
done
[[ -f "$bundle/provisioner/HealthApp.Provisioning.dll" ]] || fail 'Missing release provisioning utility.'
persistence=false
for service in "${selected_services[@]}"; do case "$service" in patient-profile|observation) persistence=true;; esac; done
if [[ "$target_root" == / && "$prepare_only" == false ]]; then
[[ $EUID -eq 0 && -d /run/systemd/system ]] || fail 'Live installation requires root and a running systemd manager.'
source /etc/os-release
ensure_dependencies "$ID" "${VERSION_ID:-}" "$dotnet_path" "$persistence" "${ID_LIKE:-}"
else
[[ -x "$dotnet_path" ]] || fail 'Offline preparation needs an available .NET 10 runtime.'
fi
provision=("$dotnet_path" "$bundle/provisioner/HealthApp.Provisioning.dll")
step='generate deployment credentials and HTTPS certificates'
if [[ -z "$deployment" || ! -f "$deployment/deployment.json" ]]; then
[[ -n "$deployment" ]] || deployment="$target_root/var/lib/healthapp-installation/deployment"
arguments=(prepare --output "$deployment" --host "$host")
[[ -z "$topology" ]] || arguments+=(--topology "$topology")
[[ -z "$external_certificates" ]] || arguments+=(--certificates "$external_certificates")
"${provision[@]}" "${arguments[@]}"
fi
if [[ "$prepare_only" == true ]]; then
printf 'Deployment material generated in %s. It contains secrets; distribute.sh installs the scoped material on each host.\n' "$deployment"
exit 0
fi
install -d -m 0755 "$target_root/opt/healthapp" "$target_root/etc/systemd/system"
install -d -m 0711 "$target_root/etc/healthapp"
install -d -m 0755 "$target_root/usr/local/share/ca-certificates"
ca_id=$(sha256sum "$deployment/healthapp-ca.crt" | cut -c1-16)
install -m 0644 "$deployment/healthapp-ca.crt" "$target_root/usr/local/share/ca-certificates/healthapp-prototype-$ca_id.crt"
if [[ "$target_root" == / ]]; then
step='install local HTTPS trust'
update-ca-certificates
fi
for service in "${selected_services[@]}"; do
step="configure $service"
if [[ "$target_root" == / ]]; then
user="healthapp-$service"
getent group "$user" >/dev/null || groupadd --system "$user"
id "$user" >/dev/null 2>&1 || useradd --system --gid "$user" --home-dir /nonexistent --shell /usr/sbin/nologin "$user"
fi
if [[ "$service" == patient-profile || "$service" == observation ]]; then
if [[ "$target_root" == / || -n "$admin_file" ]]; then
step="create dedicated database and role for $service"
args=(database --service-dir "$deployment/$service")
[[ -z "$admin_file" ]] || args+=(--admin-file "$admin_file")
"${provision[@]}" "${args[@]}"
fi
fi
"${provision[@]}" configure --service-dir "$deployment/$service" --root "$target_root"
install -d -m 0755 "$target_root/opt/healthapp/$service"
cp -R "$bundle/services/$service/." "$target_root/opt/healthapp/$service/"
chmod -R a+rX,go-w "$target_root/opt/healthapp/$service"
sed -e "s|ExecStart=/usr/bin/dotnet |ExecStart=$dotnet_path |" \
-e "s|EnvironmentFile=/etc/healthapp/$service.env|EnvironmentFile=/etc/healthapp/$service/service.env|" \
-e "s/^User=healthapp$/User=healthapp-$service/" -e "s/^Group=healthapp$/Group=healthapp-$service/" \
"$bundle/systemd/healthapp-$service.service" > "$target_root/etc/systemd/system/healthapp-$service.service"
chmod 0644 "$target_root/etc/systemd/system/healthapp-$service.service"
if [[ "$target_root" == / ]]; then
chmod 0750 "/etc/healthapp/$service"
chgrp "$user" "/etc/healthapp/$service" "/etc/healthapp/$service/service.pfx"
chmod 0640 "/etc/healthapp/$service/service.pfx"
fi
printf 'Installed selected application: %s\n' "$service"
done
if [[ "$target_root" != / ]]; then
printf 'Offline deployment staged in %s. Package installation, systemd startup and live verification were not performed.\n' "$target_root"
exit 0
fi
step='register independent systemd services'
systemctl daemon-reload
for service in "${selected_services[@]}"; do
case "$service" in patient-profile|observation)
step="migrate $service database"
assembly=$(assembly_for "$service")
systemd-run --quiet --wait --pipe --collect --unit="healthapp-$service-migrate" \
--property="User=healthapp-$service" --property="Group=healthapp-$service" \
--property="EnvironmentFile=/etc/healthapp/$service/service.env" --property="WorkingDirectory=/opt/healthapp/$service" \
"$dotnet_path" "/opt/healthapp/$service/$assembly.dll" --migrate;;
esac
done
systemctl daemon-reload
for service in "${selected_services[@]}"; do
step="enable/start $service"
systemctl enable --now "healthapp-$service.service"
done
step='verify startup and HTTPS listening'
pids=()
for service in "${selected_services[@]}"; do
systemctl is-active --quiet "healthapp-$service.service" || fail "$service is not running."
pid=$(systemctl show --property MainPID --value "healthapp-$service.service")
[[ "$pid" =~ ^[1-9][0-9]*$ && -d "/proc/$pid" ]] || fail "$service has no running process."
for peer in "${pids[@]}"; do [[ "$pid" != "$peer" ]] || fail 'Selected services share a process.'; done
pids+=("$pid")
done
"${provision[@]}" verify-startup --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")"
if [[ "$defer_verification" == true ]]; then
printf '%s\n' 'Node started. Distributed topology verification is pending until all nodes have started.'
else
step='verify configured dependencies and representative functionality'
arguments=(verify --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")")
[[ "$requested" != all ]] || arguments+=(--complete true)
"${provision[@]}" "${arguments[@]}"
printf 'Installation and topology verification completed. Account credentials: %s/accounts.json\n' "$deployment"
fi
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Deployment metadata only; each application remains independently published and configured.
all_services=(api-gateway patient-profile observation insights health-overview)
select_services() {
local requested="$1" item
selected_services=()
if [[ "$requested" == all ]]; then
selected_services=("${all_services[@]}")
return
fi
IFS=',' read -r -a selected_services <<< "$requested"
[[ ${#selected_services[@]} -gt 0 && "$requested" != *, ]] || fail "Select services by comma-separated name or all."
local seen=,
for item in "${selected_services[@]}"; do
case "$item" in api-gateway|patient-profile|observation|insights|health-overview) ;; *) fail "Unknown service: $item" ;; esac
case "$seen" in *,$item,*) fail "Repeated service: $item";; esac
seen+="$item,"
done
}
assembly_for() {
case "$1" in
api-gateway) printf '%s' ApiGateway;;
patient-profile) printf '%s' PatientProfileService;;
observation) printf '%s' ObservationService;;
insights) printf '%s' InsightsService;;
health-overview) printf '%s' HealthOverviewService;;
esac
}
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
set -euo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
fail() { printf 'Verification failed: %s\n' "$*" >&2; exit 1; }
source "$script_dir/services.sh"
requested=
deployment=/var/lib/healthapp-installation/deployment
dotnet_path=/usr/bin/dotnet
while [[ $# -gt 0 ]]; do
case "$1" in
--services|--deployment|--dotnet)
[[ $# -gt 1 ]] || fail 'Missing argument.'
case "$1" in --services) requested=$2;; --deployment) deployment=$2;; --dotnet) dotnet_path=$2;; esac
shift 2;;
--help) printf '%s\n' 'Usage: bash verify.sh --services all|NAME[,NAME] [--deployment GENERATED_DIRECTORY] [--dotnet PATH]' 'Checks systemd processes, HTTPS, dedicated databases, service credentials and the complete-system synthetic workflow.'; exit 0;;
*) fail "Unknown argument: $1";;
esac
done
select_services "$requested"
pids=()
for service in "${selected_services[@]}"; do
systemctl is-active --quiet "healthapp-$service.service" || fail "$service is not running."
pid=$(systemctl show --property MainPID --value "healthapp-$service.service")
[[ "$pid" =~ ^[1-9][0-9]*$ && -d "/proc/$pid" ]] || fail "$service has no process."
for peer in "${pids[@]}"; do [[ "$pid" != "$peer" ]] || fail 'Services share a process.'; done
pids+=("$pid")
done
args=(verify --deployment "$deployment" --services "$(IFS=,; echo "${selected_services[*]}")")
[[ "$requested" != all ]] || args+=(--complete true)
"$dotnet_path" "$script_dir/provisioner/HealthApp.Provisioning.dll" "${args[@]}"
printf '%s\n' 'Installation verification passed.'
@@ -0,0 +1,9 @@
ASPNETCORE_ENVIRONMENT=Production
ASPNETCORE_URLS=https://0.0.0.0:5082
ConnectionStrings__ObservationDatabase="Host=database.example.test;Port=5432;Database=observations;Username=observations;Password=REPLACE_ME"
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
InternalAccess__GatewayKey=REPLACE_ME
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
Kestrel__Certificates__Default__Password=REPLACE_ME
Services__ApiGateway__Key=REPLACE_ME
@@ -0,0 +1,7 @@
ASPNETCORE_ENVIRONMENT=Production
ASPNETCORE_URLS=https://0.0.0.0:5081
ConnectionStrings__PatientDatabase="Host=database.example.test;Port=5432;Database=patient_profile;Username=patient_profile;Password=REPLACE_ME"
InternalAccess__GatewayKey=REPLACE_ME
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
Kestrel__Certificates__Default__Password=REPLACE_ME
@@ -0,0 +1,22 @@
[Unit]
Description=HealthApp API gateway
Wants=network-online.target
After=network-online.target
[Service]
StateDirectory=healthapp-api-gateway
StateDirectoryMode=0700
Type=simple
User=healthapp
Group=healthapp
WorkingDirectory=/opt/healthapp/api-gateway
ExecStart=/usr/bin/dotnet /opt/healthapp/api-gateway/ApiGateway.dll
EnvironmentFile=/etc/healthapp/api-gateway.env
Restart=on-failure
RestartSec=5
KillSignal=SIGINT
TimeoutStopSec=30
SyslogIdentifier=healthapp-api-gateway
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,20 @@
[Unit]
Description=HealthApp Health Overview service
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=healthapp
Group=healthapp
WorkingDirectory=/opt/healthapp/health-overview
ExecStart=/usr/bin/dotnet /opt/healthapp/health-overview/HealthOverviewService.dll
EnvironmentFile=/etc/healthapp/health-overview.env
Restart=on-failure
RestartSec=5
KillSignal=SIGINT
TimeoutStopSec=30
SyslogIdentifier=healthapp-health-overview
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,20 @@
[Unit]
Description=HealthApp Insights service
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=healthapp
Group=healthapp
WorkingDirectory=/opt/healthapp/insights
ExecStart=/usr/bin/dotnet /opt/healthapp/insights/InsightsService.dll
EnvironmentFile=/etc/healthapp/insights.env
Restart=on-failure
RestartSec=5
KillSignal=SIGINT
TimeoutStopSec=30
SyslogIdentifier=healthapp-insights
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,20 @@
[Unit]
Description=HealthApp Observation service
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=healthapp
Group=healthapp
WorkingDirectory=/opt/healthapp/observation
ExecStart=/usr/bin/dotnet /opt/healthapp/observation/ObservationService.dll
EnvironmentFile=/etc/healthapp/observation.env
Restart=on-failure
RestartSec=5
KillSignal=SIGINT
TimeoutStopSec=30
SyslogIdentifier=healthapp-observation
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,20 @@
[Unit]
Description=HealthApp Patient/Profile service
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=healthapp
Group=healthapp
WorkingDirectory=/opt/healthapp/patient-profile
ExecStart=/usr/bin/dotnet /opt/healthapp/patient-profile/PatientProfileService.dll
EnvironmentFile=/etc/healthapp/patient-profile.env
Restart=on-failure
RestartSec=5
KillSignal=SIGINT
TimeoutStopSec=30
SyslogIdentifier=healthapp-patient-profile
[Install]
WantedBy=multi-user.target
+6
View File
@@ -0,0 +1,6 @@
{
"sdk": {
"version": "10.0.100",
"rollForward": "latestFeature"
}
}
@@ -0,0 +1,200 @@
# US-13 prototype authentication
The API gateway authenticates pre-created externally configured accounts. Login is
`POST /api/authentication/login` with `accountId` and `password`. A successful JSON
response contains `accessToken`, `tokenType: Bearer`, `expiresIn`, `accountId` and
trusted `role`; it contains no patient data or refresh token. Send the access token
as `Authorization: Bearer <token>` on subsequent patient-data requests. Invalid
credentials return the same `401` response for unknown accounts and wrong passwords.
Login responses cannot be cached. General measurement guidance remains public.
## Mechanism and configuration
Use ASP.NET Core's built-in bearer authentication and ticket protection, with
Data Protection's application name `HealthApp.ApiGateway` and the bearer purpose.
Tokens are opaque protected authentication tickets, not JWTs. The configured key
ring and framework purpose enforce the gateway trust boundary; only account ID,
role and authentication properties are protected inside a token. Do not share the
key ring with other applications/services. No custom cryptography, identity
microservice, account database or refresh-token mechanism is introduced.
The gateway verifies passwords with ASP.NET Core `PasswordHasher` against
`Authentication:Accounts:<index>:{AccountId,Role,PasswordHash}`. Roles are `Patient`
or `HealthcareProfessional`, from trusted configuration. IDs support ASCII letters,
digits, hyphen and underscore, up to 128 characters. This keeps the internal account
lookup contract unambiguous. Provision credentials externally; no registration or
administration API is exposed. For provisioning, `tools/PasswordHash` reads a
password from standard input and emits its ASP.NET Core hash. Supply input securely
(e.g. redirect a permission-restricted temporary file), and protect the resulting
hash/configuration; neither belongs in Git. The tool needs no NuGet dependency.
`Authentication:TokenLifetimeMinutes` defaults to 30; supported range is 1–1440.
`Authentication:KeyDirectory` is required. Keep its contents persistent through
restart/deployment and readable only by the gateway service account. The systemd
unit provides a mode-0700 state directory; example configuration points into it.
Keys are protected by filesystem permissions in this Linux prototype. Removing
keys invalidates tokens; preserve them for restart continuity. Accounts and
configuration are loaded at startup; after disabling accounts or changing roles,
old tokens can remain valid until their expiry. Immediate revocation is outside
this story. Missing/invalid/expired tokens return `401`; authenticate again after
expiry. Credential validation is not repeated for each operation.
Before thesis measurement, record the lifetime, account/role mix, key persistence,
login frequency and expiry handling. Normally obtain tokens during workload setup
and reuse them; state explicitly whether login is measured. If tokens expire,
re-authentication is required. Keep these choices identical across variants. The
automated test helper logs in using real password verification and caches tokens;
its account-per-resource setup is not a prescribed measurement workload.
## Ownership and profile creation
The patient service owns the account association as `patient.account_id` with a
unique index. It remains application access data, outside tokens. The gateway
queries its protected `GET /api/patients/by-account/{accountId}` service API on each
request; that API is not forwarded as a public account-lookup route. An account
without a profile may log in and create one; its other own-data requests return
`404`. Patient operations are subject to the standard Patient authorization policy.
`GET /api/patients/me` retrieves the caller’s own associated profile without needing
to know its generated identifier, including after a creation response was lost.
It returns `404` before profile creation.
Profile creation derives `X-Account-Id` from the authenticated principal. The
gateway overwrites client input; the service accepts it only behind its gateway
credential. The profile and association are inserted in one atomic database save,
so failure rolls both back. The unique index arbitrates concurrent creation. A
completed creation, a retry after a lost response and a competing request cannot
create another profile; later attempts receive `409`. A retry after a failed
transaction may create the first profile. Profile identity remains persistent
through restarts. US-01's authenticated creation is included because US-13 depends
on a persistent, recoverable association.
Apply the new patient migration before startup. Existing profiles retain a null
account association rather than being assigned to an arbitrary account. They are
not accessible to patient accounts until a trusted deployment operator explicitly
associates them with pre-created accounts. For synthetic experiments, provision a
fresh database via the authenticated creation flow. Do not infer ownership from
caller-supplied IDs or automatically assign historical profiles.
For observation-ID requests, the gateway reads the observation through its service
API to obtain the actual patient, then compares that owner with the account's
profile. Requests for another patient's information receive an empty `404`, the
same as missing data, without forwarding writes or revealing existence. Failed
ownership lookups fail closed with `502`/`504`. Tokens do not cache ownership.
Healthcare-professional logins establish a trusted role. US-14 now permits reads
of assigned patients and the caller’s own assignment list; all professional writes
are rejected before forwarding. Trend/overview endpoints remain unimplemented; the
gateway's default authentication policy also protects future patient endpoints,
which must retain ownership checks when added.
## Service and transport protection
Use HTTPS for client and service traffic. Outside Development, gateway and service
requests over HTTP are rejected and outgoing service endpoints must be HTTPS.
Certificates use ordinary Kestrel configuration and normal platform validation;
no insecure certificate handler is provided. Configure DNS names/certificates for
separate machines. Development permits plain HTTP for local automated tests only.
Use network firewall rules to restrict service ports to trusted hosts as an
additional deployment control; the application credential checks still enforce
protection if a client reaches a service directly.
Each service requires `InternalAccess:GatewayKey`, a random credential of at least
32 characters, matched by the gateway's `Services:<service>:Key`. Services reject
missing/wrong keys and client bearer tokens. Use distinct per-service gateway keys
in deployment. The gateway forwards only its own configured key; arbitrary client
identity headers are not propagated. Do not log these headers or tokens.
Observation and Insights each have a separate `Services:ApiGateway:Key`, matched
by the gateway's `InternalAccess:Observation:Key` or `InternalAccess:Insights:Key`.
Their `X-Service-Key` authenticates an internal principal using an ASP.NET Core
handler. The Observation principal can only GET a patient profile by patient ID;
the Insights principal can only GET observation history by patient ID. Neither
can create/update/delete profiles or observations, query account associations or
call other protected routes. Both internal read paths still pass through the
gateway. Service credentials are separate from patient tokens and token keys.
Use independent random values, restrictive configuration-file permissions and
HTTPS; placeholder values in deployment examples deliberately fail validation.
## Verification
The acceptance suite exercises real HTTP hosts and PostgreSQL migrations. It covers
US-13's login, own access, missing/invalid/expired tokens, no-profile behaviour,
cross-patient reads/writes and observation ownership. Additional checks cover
caller-supplied account spoofing, persistent tokens/associations after restart,
duplicate/concurrent creation, unavailable-service recovery, direct service bypass,
internal-credential route restrictions, professional creation rejection and public
US-15 guidance. Existing functional assertions run through real token login rather
than a production authentication bypass.
Framework reference:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.bearertoken.bearertokenoptions?view=aspnetcore-10.0
## US-14 professional assignments
Predefine assignments in the gateway's external `Access:ProfessionalAssignments`
configuration, keyed by the stable professional account identifier. For example:
```json
{
"Access": {
"ProfessionalAssignments": {
"example_professional": [
"00000000-0000-0000-0000-000000000001",
"00000000-0000-0000-0000-000000000002"
]
}
}
}
```
Use actual patient identifiers returned by authenticated profile creation. The
example UUIDs are placeholders. A professional can have several patients, and
several professionals can share a patient. Duplicate identifiers are treated as
one assignment. Empty identifiers are rejected at startup. An omitted account
entry means no assignments. Configure that account's role and password hash
separately under `Authentication:Accounts`; assignments never grant a role.
`GET /api/professionals/me/patients` requires the HealthcareProfessional policy and
returns an array of `{ "patientId": "..." }` entries, in deterministic identifier
order. It lists only the caller's configured assignments, without fetching patient
records. No assignments returns `[]`. Missing profiles remain assigned identifiers;
retrieving their data follows the existing missing-resource behaviour. Caller
query parameters or identity headers cannot select another professional's list.
Patient accounts cannot use this endpoint.
Professional GET requests to existing patient profiles, observations (including
recorded legacy context), history, latest observations and numerical insight
require membership in the caller's assignment set. Observation-ID requests resolve
the actual owning patient via the protected Observation API; a supplied patient ID
is not evidence of assignment. Unassigned reads return an empty `404`, preserving
the same non-disclosure convention as patient access. Assigned missing data follows
the existing retrieval contracts. All professional POST/PUT/PATCH/DELETE requests
are rejected with `403` before ownership lookups or forwarding. There is no
assignment-management API or additional database/service.
Assignments are loaded at gateway startup, outside tokens and credential
validation. Restart the gateway after changing its external configuration. Existing
valid tokens then use the new assignment data. Empty lists need no upstream service;
observation-owner lookup failures fail closed with `502`/`504`.
The US-14 tests exercise actual login, multiple and shared assignments, empty lists,
assigned/unassigned reads, preserved context, missing resources, every existing
write route, invalid and expired credentials, patient-role rejection, assignment
changes across restart and unavailable ownership lookup. Trend and overview
endpoints now have equivalent owner/assignment routing and integration tests under
US-11/US-12. Structured observation context is included in authorized reads.
## US-12 Overview service access
The gateway requires `Services:HealthOverview:BaseUrl` and `Services:HealthOverview:Key`.
The latter matches Overview's `InternalAccess:GatewayKey` and protects direct access.
Overview's outgoing `Services:ApiGateway:Key` matches `InternalAccess:HealthOverview:Key`
on the gateway. Use distinct randomly generated credentials of at least 32 characters
for each direction and service; load them externally. Production endpoints use HTTPS.
The HealthOverview service identity is restricted to GET patient profiles, GET latest
overall observations and GET numerical insights. It cannot retrieve history, trends or
another overview, or perform writes. It establishes no client identity. The gateway
checks client ownership/professional assignment before forwarding the outer request.
Internal credentials are trusted service credentials and must remain inaccessible to clients.
Overview adds no authentication framework, shared runtime library or persistence.
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
</ItemGroup>
</Project>
@@ -0,0 +1,39 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using ApiGateway.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api/authentication")]
public sealed class AuthenticationController(PrototypeAccounts accounts,
IOptionsMonitor<BearerTokenOptions> options) : ControllerBase
{
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login(LoginRequest request)
{
var account = accounts.Verify(request.AccountId, request.Password);
if (account is null) return Unauthorized(new { title = "Invalid credentials." });
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, account.AccountId),
new Claim(ClaimTypes.Role, account.Role)
}, "Bearer"));
var settings = options.Get("Bearer");
var expiry = settings.TimeProvider!.GetUtcNow().Add(settings.BearerTokenExpiration);
// Use the framework's ticket protector and bearer validation. No refresh endpoint/token.
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties { ExpiresUtc = expiry }, "Bearer");
Response.Headers.CacheControl = "no-store";
Response.Headers.Pragma = "no-cache";
return Ok(new { accessToken = settings.BearerTokenProtector.Protect(ticket), tokenType = "Bearer",
expiresIn = (long)settings.BearerTokenExpiration.TotalSeconds, accountId = account.AccountId, role = account.Role });
}
public sealed record LoginRequest([Required] string AccountId, [Required] string Password);
}
@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api")]
public sealed class HealthOverviewController(IHttpClientFactory clients) : ControllerBase
{
[HttpGet("patients/{patientId:guid}/overview")]
public Task GetOverview(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/overview{Request.QueryString}", cancellationToken);
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(method, path);
try
{
using var upstream = await clients.CreateClient("HealthOverview")
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
Response.StatusCode = (int)upstream.StatusCode;
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
if (upstream.Headers.Location is { } location)
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
}
catch (HttpRequestException)
{
await WriteFailureAsync(StatusCodes.Status502BadGateway);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
}
}
private Task WriteFailureAsync(int status)
{
if (Response.HasStarted)
{
HttpContext.Abort();
return Task.CompletedTask;
}
Response.Clear();
return Results.Problem(statusCode: status, title: "Health overview service is unavailable.")
.ExecuteAsync(HttpContext);
}
}
@@ -0,0 +1,52 @@
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api")]
public sealed class InsightsController(IHttpClientFactory clients) : ControllerBase
{
[HttpGet("patients/{patientId:guid}/insights")]
public Task GetSummary(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/insights{Request.QueryString}", cancellationToken);
[HttpGet("patients/{patientId:guid}/trends")]
public Task GetTrend(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/trends{Request.QueryString}", cancellationToken);
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(method, path);
try
{
using var upstream = await clients.CreateClient("Insights")
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
Response.StatusCode = (int)upstream.StatusCode;
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
if (upstream.Headers.Location is { } location)
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
}
catch (HttpRequestException)
{
await WriteFailureAsync(StatusCodes.Status502BadGateway);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
}
}
private Task WriteFailureAsync(int status)
{
if (Response.HasStarted)
{
HttpContext.Abort();
return Task.CompletedTask;
}
Response.Clear();
return Results.Problem(statusCode: status, title: "Insights service is unavailable.")
.ExecuteAsync(HttpContext);
}
}
@@ -0,0 +1,62 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[AllowAnonymous]
[Route("api/measurement-guidance")]
public sealed class MeasurementGuidanceController : ControllerBase
{
[HttpGet]
public IActionResult Get([FromQuery] string? setting, [FromQuery] string? activityCondition)
{
var requestedSetting = string.IsNullOrWhiteSpace(setting) ? "Unknown" : setting.Trim();
var requestedActivity = string.IsNullOrWhiteSpace(activityCondition) ? "Unknown" : activityCondition.Trim();
if (!new[] { "Home", "Clinic", "Other", "Unknown" }.Contains(requestedSetting, StringComparer.OrdinalIgnoreCase))
return Problem(statusCode: 400, title: "Unsupported measurement setting.");
if (!new[] { "AtRest", "DuringActivity", "AfterActivity", "Unknown" }.Contains(requestedActivity, StringComparer.OrdinalIgnoreCase))
return Problem(statusCode: 400, title: "Unsupported activity condition.");
var available = requestedSetting.Equals("Home", StringComparison.OrdinalIgnoreCase)
|| requestedSetting.Equals("Unknown", StringComparison.OrdinalIgnoreCase);
return Ok(new
{
available,
requestedSetting,
requestedActivityCondition = requestedActivity,
applicableSetting = available ? "Home" : null,
applicableActivityCondition = available ? "AtRest" : null,
reviewedOn = available ? "2026-10-04" : null,
explanation = available
? "These instructions apply to resting home self-measurement, not a clinical measurement protocol. Unknown conditions remain unknown; requesting guidance does not record a setting or certify compliance."
: "Verified guidance is unavailable for the requested setting. Home instructions have not been substituted for clinical or other-setting instructions.",
steps = available ? new[]
{
new GuidanceStep(1, "Equipment", "Use a validated upper-arm device with a cuff suited to your arm. Follow its instructions for placement and maintenance; incorrect cuff size can distort readings."),
new GuidanceStep(2, "Preparation", "Choose a quiet place. Avoid smoking for 30 minutes beforehand and rest seated for five minutes."),
new GuidanceStep(3, "Position", "Sit with back and arm supported and legs uncrossed. Put the cuff on bare skin, clear of tight clothing, and keep the arm relaxed and still during measurement."),
new GuidanceStep(4, "Measure", "Use the device as instructed. Reproduce your setting, posture and preparation when possible to help later comparisons."),
new GuidanceStep(5, "Planned monitoring", "The cited Danish home protocol uses three readings in the morning before breakfast and three in the evening before dinner, over three consecutive days. This planned series differs from saving one observation; follow individually supplied clinical instructions."),
new GuidanceStep(6, "Record", "Save actual blood-pressure values in mmHg, device-reported pulse in beats/minute, and measurement time. Record setting, activity and preparation where known, including departures from routine. Do not discard, change or invent values to fit guidance.")
} : Array.Empty<GuidanceStep>(),
pulseExplanation = available
? "Rest and activity affect the context of pulse readings. One device-reported pulse value does not assess rhythm regularity."
: null,
activityExplanation = available
? "During-activity and after-activity measurements differ from resting measurements. Record the actual conditions; do not relabel them as resting. Such observations remain valid to record."
: null,
limitations = available
? "Guidance does not guarantee accuracy or replace device or individual clinical instructions. It does not recommend medication changes. Viewing or declining it does not save or alter observations, certify a procedure, or prevent a valid submission."
: null,
sources = available ? new[]
{
new GuidanceSource("Sundhed.dk — Højt blodtryk", "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/", "2024-09-25"),
new GuidanceSource("Sundhed.dk — Blodtryksmåling", "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/undersoegelser-og-proever/kliniske-procedurer/hjertekar/blodtryksmaaling/", "2025-03-13")
} : Array.Empty<GuidanceSource>()
});
}
private sealed record GuidanceStep(int Order, string Topic, string Instruction);
private sealed record GuidanceSource(string Title, string Url, string UpdatedOn);
}
@@ -0,0 +1,81 @@
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api")]
public sealed class ObservationController(IHttpClientFactory clients) : ControllerBase
{
[HttpPost("patients/{patientId:guid}/observations")]
public Task RecordObservation(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Post, $"api/patients/{patientId}/observations", cancellationToken);
[HttpDelete("observations/{observationId:guid}")]
public Task DeleteObservation(Guid observationId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Delete, $"api/observations/{observationId}", cancellationToken);
[HttpPut("observations/{observationId:guid}")]
public Task UpdateObservation(Guid observationId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Put, $"api/observations/{observationId}", cancellationToken);
[HttpPatch("observations/{observationId:guid}")]
public Task PatchObservation(Guid observationId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Patch, $"api/observations/{observationId}", cancellationToken);
[HttpGet("observations/{observationId:guid}")]
public Task GetObservation(Guid observationId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/observations/{observationId}", cancellationToken);
[HttpGet("patients/{patientId:guid}/observations/latest")]
public Task GetLatest(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations/latest", cancellationToken);
[HttpGet("patients/{patientId:guid}/observations")]
public Task GetByPeriod(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations{Request.QueryString}", cancellationToken);
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(method, path);
if (method == HttpMethod.Post || method == HttpMethod.Put || method == HttpMethod.Patch)
{
request.Content = new StreamContent(Request.Body);
if (Request.ContentType is not null)
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
}
try
{
using var upstream = await clients.CreateClient("Observation")
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
Response.StatusCode = (int)upstream.StatusCode;
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
foreach (var header in new[] { "X-Measurement-Setting", "X-Activity-Condition" })
if (upstream.Headers.TryGetValues(header, out var values))
Response.Headers[header] = values.ToArray();
if (upstream.Headers.Location is { } location)
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
}
catch (HttpRequestException)
{
await WriteFailureAsync(StatusCodes.Status502BadGateway);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
}
}
private Task WriteFailureAsync(int status)
{
if (Response.HasStarted)
{
HttpContext.Abort();
return Task.CompletedTask;
}
Response.Clear();
return Results.Problem(statusCode: status, title: "Observation service is unavailable.")
.ExecuteAsync(HttpContext);
}
}
@@ -0,0 +1,69 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api/patients")]
public sealed class PatientController(IHttpClientFactory clients) : ControllerBase
{
[HttpPost]
public Task CreatePatient(CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Post, "api/patients", cancellationToken);
[HttpGet("me")]
public Task GetOwnPatient(CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, "api/patients/by-account/" + Uri.EscapeDataString(User.FindFirstValue(ClaimTypes.NameIdentifier)!), cancellationToken);
[HttpGet("{patientId:guid}")]
public Task GetPatient(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken);
[HttpPut("{patientId:guid}")]
public Task UpdatePatient(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Put, $"api/patients/{patientId}", cancellationToken);
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(method, path);
if (method == HttpMethod.Post)
request.Headers.Add("X-Account-Id", User.FindFirstValue(ClaimTypes.NameIdentifier));
if (method == HttpMethod.Post || method == HttpMethod.Put)
{
request.Content = new StreamContent(Request.Body);
if (Request.ContentType is not null)
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
}
try
{
using var upstream = await clients.CreateClient("PatientProfile")
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
Response.StatusCode = (int)upstream.StatusCode;
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
if (upstream.Headers.Location is { } location)
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
}
catch (HttpRequestException)
{
await WriteFailureAsync(StatusCodes.Status502BadGateway);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
}
}
private Task WriteFailureAsync(int status)
{
if (Response.HasStarted)
{
HttpContext.Abort();
return Task.CompletedTask;
}
Response.Clear();
return Results.Problem(statusCode: status, title: "Patient/Profile service is unavailable.")
.ExecuteAsync(HttpContext);
}
}
@@ -0,0 +1,17 @@
using System.Security.Claims;
using ApiGateway.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[Authorize(Policy = "HealthcareProfessional")]
[Route("api/professionals/me/patients")]
public sealed class ProfessionalController(ProfessionalAssignments assignments) : ControllerBase
{
[HttpGet]
public IActionResult GetAssignedPatients() =>
Ok(assignments.GetPatients(User.FindFirstValue(ClaimTypes.NameIdentifier)!)
.Select(patientId => new { patientId }));
}
@@ -0,0 +1,116 @@
using ApiGateway.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.DataProtection.Repositories;
namespace ApiGateway;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-api-gateway");
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<PrototypeAccounts>();
builder.Services.AddSingleton<ProfessionalAssignments>();
builder.Services.AddAuthentication("ClientOrService")
.AddPolicyScheme("ClientOrService", null, options => options.ForwardDefaultSelector = context =>
context.Request.Headers.ContainsKey("X-Service-Key") ? "InternalService" : "Bearer")
.AddBearerToken("Bearer", options =>
{
options.BearerTokenExpiration = TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30));
})
.AddScheme<AuthenticationSchemeOptions, InternalServiceAuthenticationHandler>("InternalService", null);
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.AddPolicy("Patient", policy => policy.RequireRole("Patient").RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
options.AddPolicy("HealthcareProfessional", policy => policy.RequireRole("HealthcareProfessional")
.RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
});
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
builder.Services.AddOptions<KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((options, configuration, logger) =>
{
var keyDirectory = configuration["Authentication:KeyDirectory"];
if (string.IsNullOrWhiteSpace(keyDirectory)) throw new InvalidOperationException("Authentication:KeyDirectory is required.");
options.XmlRepository = new FileSystemXmlRepository(new DirectoryInfo(keyDirectory), logger);
});
builder.Services.AddHttpClient("PatientProfile", (services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetBaseUri(configuration, "PatientProfile");
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:PatientProfile:Key"]);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
builder.Services.AddHttpClient("Observation", (services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetBaseUri(configuration, "Observation");
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Observation:Key"]);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
builder.Services.AddHttpClient("Insights", (services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetBaseUri(configuration, "Insights");
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Insights:Key"]);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
builder.Services.AddHttpClient("HealthOverview", (services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetBaseUri(configuration, "HealthOverview");
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:HealthOverview:Key"]);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
var app = builder.Build();
_ = GetBaseUri(app.Configuration, "PatientProfile");
_ = GetBaseUri(app.Configuration, "Observation");
_ = GetBaseUri(app.Configuration, "Insights");
_ = GetBaseUri(app.Configuration, "HealthOverview");
foreach (var key in new[] { "Services:PatientProfile:Key", "Services:Observation:Key", "Services:Insights:Key", "Services:HealthOverview:Key", "InternalAccess:HealthOverview:Key", "InternalAccess:Observation:Key", "InternalAccess:Insights:Key" })
if (string.IsNullOrWhiteSpace(app.Configuration[key]) || app.Configuration[key]!.Length < 32)
throw new InvalidOperationException($"{key} must contain at least 32 characters.");
if (string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"]))
throw new InvalidOperationException("Authentication:KeyDirectory is required.");
var lifetime = app.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30);
if (lifetime <= 0 || lifetime > 1440) throw new InvalidOperationException("Token lifetime must be between 1 and 1440 minutes.");
if (!app.Environment.IsDevelopment())
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
if (GetBaseUri(app.Configuration, service).Scheme != "https")
throw new InvalidOperationException("Production service endpoints must use HTTPS.");
_ = app.Services.GetRequiredService<PrototypeAccounts>();
_ = app.Services.GetRequiredService<ProfessionalAssignments>();
app.UseExceptionHandler();
app.Use(async (context, next) =>
{
if (!app.Environment.IsDevelopment() && !context.Request.IsHttps) { context.Response.StatusCode = 400; return; }
await next(context);
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<PatientAccessMiddleware>();
app.MapControllers();
app.Run();
}
private static Uri GetBaseUri(IConfiguration configuration, string service)
{
var endpoint = configuration[$"Services:{service}:BaseUrl"];
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var baseUri) ||
(baseUri.Scheme != "http" && baseUri.Scheme != "https") ||
baseUri.AbsolutePath != "/" || !string.IsNullOrEmpty(baseUri.Query) ||
!string.IsNullOrEmpty(baseUri.Fragment) || !string.IsNullOrEmpty(baseUri.UserInfo))
throw new InvalidOperationException($"Services:{service}:BaseUrl must be an HTTP(S) origin URL.");
return baseUri;
}
}
@@ -0,0 +1,29 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
namespace ApiGateway.Security;
public sealed class InternalServiceAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var supplied = Request.Headers["X-Service-Key"].ToString();
foreach (var service in new[] { "Observation", "Insights", "HealthOverview" })
{
var expected = configuration[$"InternalAccess:{service}:Key"]!;
if (CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(expected)))
{
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, "Service"),
new Claim(ClaimTypes.NameIdentifier, service) }, Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name)));
}
}
return Task.FromResult(AuthenticateResult.Fail("Invalid service credential."));
}
}
@@ -0,0 +1,92 @@
using System.Net;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
namespace ApiGateway.Security;
public sealed class PatientAccessMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, IHttpClientFactory clients, IAuthorizationService authorization,
ProfessionalAssignments assignments)
{
if (context.GetEndpoint()?.Metadata.GetMetadata<IAllowAnonymous>() is not null)
{
await next(context);
return;
}
if (context.User.Identity?.IsAuthenticated != true) { context.Response.StatusCode = 401; return; }
var route = context.Request.Path.Value ?? "";
var segments = route.Trim('/').Split('/');
if (context.User.IsInRole("Service"))
{
var service = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
var patientRoute = segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
&& Guid.TryParse(segments[2], out _);
var allowed = context.Request.Method == "GET" && patientRoute && (service switch
{
"Observation" => segments.Length == 3,
"Insights" => segments.Length == 4 && segments[3] == "observations",
"HealthOverview" => segments.Length == 3 ||
(segments.Length == 4 && segments[3] == "insights") ||
(segments.Length == 5 && segments[3] == "observations" && segments[4] == "latest"),
_ => false
});
if (!allowed) { context.Response.StatusCode = 403; return; }
await next(context);
return;
}
var professional = (await authorization.AuthorizeAsync(context.User, "HealthcareProfessional")).Succeeded;
if (professional)
{
if (context.Request.Method != "GET") { context.Response.StatusCode = 403; return; }
if (route.Equals("/api/professionals/me/patients", StringComparison.OrdinalIgnoreCase))
{
await next(context);
return;
}
}
else if (!(await authorization.AuthorizeAsync(context.User, "Patient")).Succeeded)
{ context.Response.StatusCode = 403; return; }
if (!professional &&
((route.Equals("/api/patients", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "POST")
|| (route.Equals("/api/patients/me", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "GET")))
{
await next(context);
return;
}
try
{
var accountId = context.User.FindFirstValue(ClaimTypes.NameIdentifier)!;
Guid? patientId = null;
if (!professional)
{
using var ownResponse = await clients.CreateClient("PatientProfile").GetAsync(
"api/patients/by-account/" + Uri.EscapeDataString(accountId), context.RequestAborted);
if (ownResponse.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; }
ownResponse.EnsureSuccessStatusCode();
using var own = JsonDocument.Parse(await ownResponse.Content.ReadAsStringAsync(context.RequestAborted));
patientId = own.RootElement.GetProperty("patientId").GetGuid();
}
Guid requestedPatient;
if (segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
&& Guid.TryParse(segments[2], out requestedPatient)) { }
else if (segments.Length == 3 && segments[0] == "api" && segments[1] == "observations"
&& Guid.TryParse(segments[2], out var observationId))
{
using var response = await clients.CreateClient("Observation").GetAsync($"api/observations/{observationId}", context.RequestAborted);
if (response.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; }
response.EnsureSuccessStatusCode();
using var observation = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.RequestAborted));
requestedPatient = observation.RootElement.GetProperty("patientId").GetGuid();
}
else { context.Response.StatusCode = 404; return; }
var permitted = professional ? assignments.IsAssigned(accountId, requestedPatient) : requestedPatient == patientId;
if (!permitted) { context.Response.StatusCode = 404; return; }
await next(context);
}
catch (HttpRequestException) { await Results.Problem(statusCode: 502, title: "Ownership lookup is unavailable.").ExecuteAsync(context); }
catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested)
{ await Results.Problem(statusCode: 504, title: "Ownership lookup timed out.").ExecuteAsync(context); }
}
}
@@ -0,0 +1,24 @@
namespace ApiGateway.Security;
// Application access data, separate from credentials and token contents.
public sealed class ProfessionalAssignments
{
private readonly Dictionary<string, Guid[]> assignments;
public ProfessionalAssignments(IConfiguration configuration)
{
assignments = configuration.GetSection("Access:ProfessionalAssignments")
.Get<Dictionary<string, Guid[]>>() ?? new(StringComparer.Ordinal);
foreach (var accountId in assignments.Keys.ToArray())
{
if (string.IsNullOrWhiteSpace(accountId) || assignments[accountId].Any(id => id == Guid.Empty))
throw new InvalidOperationException("Professional assignments require an account identifier and nonempty patient identifiers.");
assignments[accountId] = assignments[accountId].Distinct().Order().ToArray();
}
}
public IReadOnlyList<Guid> GetPatients(string accountId) =>
assignments.TryGetValue(accountId, out var patients) ? Array.AsReadOnly(patients) : Array.Empty<Guid>();
public bool IsAssigned(string accountId, Guid patientId) => GetPatients(accountId).Contains(patientId);
}
@@ -0,0 +1,39 @@
using Microsoft.AspNetCore.Identity;
namespace ApiGateway.Security;
public sealed class PrototypeAccount
{
public string AccountId { get; set; } = "";
public string Role { get; set; } = "Patient";
public string PasswordHash { get; set; } = "";
}
public sealed class PrototypeAccounts
{
private readonly Dictionary<string, PrototypeAccount> accounts;
private readonly PasswordHasher<PrototypeAccount> hasher = new();
private readonly PrototypeAccount dummy = new() { AccountId = "invalid" };
public PrototypeAccounts(IConfiguration configuration)
{
var configured = configuration.GetSection("Authentication:Accounts").Get<PrototypeAccount[]>() ?? [];
if (configured.Length == 0 || configured.Any(a => string.IsNullOrWhiteSpace(a.AccountId) || a.AccountId.Length > 128 || a.AccountId.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('-' or '_')) || string.IsNullOrWhiteSpace(a.PasswordHash)
|| a.Role is not ("Patient" or "HealthcareProfessional")))
throw new InvalidOperationException("Authentication accounts require an identifier, password hash and supported role.");
accounts = configured.ToDictionary(a => a.AccountId, StringComparer.Ordinal);
dummy.PasswordHash = hasher.HashPassword(dummy, Guid.NewGuid().ToString());
}
public PrototypeAccount? Verify(string accountId, string password)
{
var known = accounts.TryGetValue(accountId, out var account);
account ??= dummy;
try
{
var result = hasher.VerifyHashedPassword(account, account.PasswordHash, password);
return known && result != PasswordVerificationResult.Failed ? account : null;
}
catch (FormatException) { return null; }
}
}
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
@@ -0,0 +1,30 @@
using System.ComponentModel.DataAnnotations;
using HealthOverviewService.Clients;
using HealthOverviewService.Contracts;
namespace HealthOverviewService.Application;
public sealed class HealthOverviewApplicationService(PatientProfileServiceClient patients,
ObservationServiceClient observations, InsightsServiceClient insights)
{
public async Task<HealthOverviewDto?> GetOverviewAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken)
{
from = NormalizeTimestamp(from);
to = NormalizeTimestamp(to);
if (to < from) throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
var patient = await patients.GetPatientAsync(patientId, cancellationToken);
if (patient is null) return null;
var latest = await observations.GetLatestAsync(patientId, cancellationToken);
var insight = await insights.GetSummaryAsync(patientId, from, to, selection, cancellationToken);
return new(patient, latest, insight, from, to, selection, insight?.ContributingCount ?? 0,
"Latest overall observation for the patient, independent of the insight period and context selections. " +
"Its recorded context applies only to that observation, not to the insight's contributing observations.",
insight is null ? "No calculated insight is available: no observations match the requested period and insight selection." :
"The insight uses the requested period and context selection only. " + insight.ContextExplanation);
}
private static DateTime NormalizeTimestamp(DateTime value) => DateTime.SpecifyKind(
value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(), DateTimeKind.Unspecified);
}
@@ -0,0 +1,28 @@
using System.Globalization;
using System.Net;
using System.Text.Json;
using HealthOverviewService.Contracts;
namespace HealthOverviewService.Clients;
public abstract class InsightsServiceClient
{
public abstract Task<HealthInsightDto?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to, ContextSelection selection, CancellationToken cancellationToken);
}
public sealed class HttpInsightsServiceClient(HttpClient client) : InsightsServiceClient
{
public override async Task<HealthInsightDto?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to, ContextSelection selection, CancellationToken cancellationToken)
{
var path = $"api/patients/{patientId}/insights";
path += $"?from={Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture))}&to={Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture))}";
if (selection.Setting is not null) path += "&setting=" + Uri.EscapeDataString(selection.Setting);
if (selection.ActivityCondition is not null) path += "&activityCondition=" + Uri.EscapeDataString(selection.ActivityCondition);
using var response = await client.GetAsync(path, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound) return null;
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<HealthInsightDto>(cancellationToken)
?? throw new JsonException("Empty upstream response.");
}
}
@@ -0,0 +1,24 @@
using System.Globalization;
using System.Net;
using System.Text.Json;
using HealthOverviewService.Contracts;
namespace HealthOverviewService.Clients;
public abstract class ObservationServiceClient
{
public abstract Task<ObservationDto?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken);
}
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
{
public override async Task<ObservationDto?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken)
{
var path = $"api/patients/{patientId}/observations/latest";
using var response = await client.GetAsync(path, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound) return null;
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<ObservationDto>(cancellationToken)
?? throw new JsonException("Empty upstream response.");
}
}
@@ -0,0 +1,24 @@
using System.Globalization;
using System.Net;
using System.Text.Json;
using HealthOverviewService.Contracts;
namespace HealthOverviewService.Clients;
public abstract class PatientProfileServiceClient
{
public abstract Task<PatientDto?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken);
}
public sealed class HttpPatientProfileServiceClient(HttpClient client) : PatientProfileServiceClient
{
public override async Task<PatientDto?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken)
{
var path = $"api/patients/{patientId}";
using var response = await client.GetAsync(path, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound) return null;
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<PatientDto>(cancellationToken)
?? throw new JsonException("Empty upstream response.");
}
}
@@ -0,0 +1,24 @@
using System.ComponentModel.DataAnnotations;
namespace HealthOverviewService.Contracts;
public sealed record ContextSelection
{
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
public string? Setting { get; init; }
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
public string? ActivityCondition { get; init; }
}
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
public sealed record MeasurementContextDto(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, MeasurementContextDto MeasurementContext);
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
public sealed record HealthOverviewDto(PatientDto Patient, ObservationDto? LatestObservation, HealthInsightDto? Insight,
DateTime PeriodStart, DateTime PeriodEnd, ContextSelection InsightSelection, int InsightContributingCount,
string LatestObservationBasis, string InsightExplanation);
@@ -0,0 +1,34 @@
using HealthOverviewService.Application;
using HealthOverviewService.Contracts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace HealthOverviewService.Controllers;
[ApiController]
[Route("api/patients/{patientId:guid}/overview")]
public sealed class HealthOverviewController(HealthOverviewApplicationService service) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<HealthOverviewDto>> GetOverview(Guid patientId,
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{
try
{
var result = await service.GetOverviewAsync(patientId, from, to, selection, cancellationToken);
return result is null ? Problem(statusCode: 404, title: "Patient does not exist.") : Ok(result);
}
catch (ArgumentException)
{
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
return ValidationProblem(ModelState);
}
catch (HttpRequestException)
{ return Problem(statusCode: 502, title: "Overview source service is unavailable."); }
catch (System.Text.Json.JsonException)
{ return Problem(statusCode: 502, title: "Overview source response is invalid."); }
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{ return Problem(statusCode: 504, title: "Overview source request timed out."); }
}
}
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
</ItemGroup>
</Project>
@@ -0,0 +1,79 @@
using System.Security.Cryptography;
using System.Text;
using HealthOverviewService.Application;
using HealthOverviewService.Clients;
namespace HealthOverviewService;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-health-overview");
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddScoped<HealthOverviewApplicationService>();
builder.Services.AddHttpClient<PatientProfileServiceClient, HttpPatientProfileServiceClient>((services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetGatewayUri(configuration);
var serviceKey = configuration["Services:ApiGateway:Key"];
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetGatewayUri(configuration);
var serviceKey = configuration["Services:ApiGateway:Key"];
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
builder.Services.AddHttpClient<InsightsServiceClient, HttpInsightsServiceClient>((services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetGatewayUri(configuration);
var serviceKey = configuration["Services:ApiGateway:Key"];
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
var app = builder.Build();
if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https")
throw new InvalidOperationException("Production gateway endpoints must use HTTPS.");
_ = GetGatewayUri(app.Configuration);
var outgoingKey = app.Configuration["Services:ApiGateway:Key"];
if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32)
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
app.UseExceptionHandler();
app.Use(async (context, next) =>
{
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
{ context.Response.StatusCode = 401; return; }
await next(context);
});
app.MapControllers();
app.Run();
}
private static Uri GetGatewayUri(IConfiguration configuration)
{
var endpoint = configuration["Services:ApiGateway:BaseUrl"];
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
(uri.Scheme != "http" && uri.Scheme != "https") || uri.AbsolutePath != "/" ||
!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) || !string.IsNullOrEmpty(uri.UserInfo))
throw new InvalidOperationException("Services:ApiGateway:BaseUrl must be an HTTP(S) origin URL.");
return uri;
}
}
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
@@ -0,0 +1,36 @@
using System.ComponentModel.DataAnnotations;
using InsightsService.Clients;
using InsightsService.Domain;
namespace InsightsService.Application;
public sealed class InsightsApplicationService(ObservationServiceClient observations, InsightCalculator calculator)
{
public async Task<HealthInsight?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken)
{
from = NormalizeTimestamp(from);
to = NormalizeTimestamp(to);
if (to < from)
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
var history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
return calculator.CalculateSummary(patientId, from, to, history, selection);
}
public async Task<TrendAssessment> GetTrendAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken)
{
from = NormalizeTimestamp(from);
to = NormalizeTimestamp(to);
if (to < from)
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
var history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
return calculator.CalculateTrend(patientId, from, to, history, selection);
}
private static DateTime NormalizeTimestamp(DateTime value) =>
DateTime.SpecifyKind(value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(),
DateTimeKind.Unspecified);
}
@@ -0,0 +1,23 @@
using InsightsService.Domain;
using System.Globalization;
using InsightsService.Contracts;
namespace InsightsService.Clients;
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
{
public async Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken)
{
var start = Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture));
var end = Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture));
var filters = "";
if (selection.Setting is not null) filters += "&setting=" + Uri.EscapeDataString(selection.Setting);
if (selection.ActivityCondition is not null) filters += "&activityCondition=" + Uri.EscapeDataString(selection.ActivityCondition);
using var response = await client.GetAsync($"api/patients/{patientId}/observations?from={start}&to={end}{filters}",
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken)
?? throw new HttpRequestException("Observation history response was empty.");
}
}
@@ -0,0 +1,10 @@
using InsightsService.Domain;
using InsightsService.Contracts;
namespace InsightsService.Clients;
public interface ObservationServiceClient
{
Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken);
}
@@ -0,0 +1,8 @@
using InsightsService.Domain;
namespace InsightsService.Contracts;
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
@@ -0,0 +1,8 @@
namespace InsightsService.Contracts;
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, MeasurementContextDto? MeasurementContext = null,
string? Context = null, string? Note = null);
public sealed record MeasurementContextDto(string? Setting, string? ActivityCondition, decimal? RestDurationMinutes,
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
@@ -0,0 +1,74 @@
using InsightsService.Domain;
using InsightsService.Application;
using InsightsService.Contracts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace InsightsService.Controllers;
[ApiController]
[Route("api/patients/{patientId:guid}/insights")]
public sealed class InsightsController(InsightsApplicationService service) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<HealthInsightDto>> GetSummary(Guid patientId,
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{
try
{
var insight = await service.GetSummaryAsync(patientId, from, to, selection, cancellationToken);
return insight is null
? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.")
: Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd,
insight.AverageSystolic, insight.AverageDiastolic, insight.AveragePulse,
insight.MinSystolic, insight.MaxSystolic, insight.MinDiastolic, insight.MaxDiastolic,
insight.AppliedSelection, insight.ContributingCount, insight.ContextExplanation));
}
catch (ArgumentException)
{
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
return ValidationProblem(ModelState);
}
catch (HttpRequestException)
{
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history is unavailable.");
}
catch (System.Text.Json.JsonException)
{
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history response is invalid.");
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
}
}
[HttpGet("/api/patients/{patientId:guid}/trends")]
public async Task<ActionResult<TrendAssessment>> GetTrend(Guid patientId,
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{
try
{
return Ok(await service.GetTrendAsync(patientId, from, to, selection, cancellationToken));
}
catch (ArgumentException)
{
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
return ValidationProblem(ModelState);
}
catch (HttpRequestException)
{
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history is unavailable.");
}
catch (System.Text.Json.JsonException)
{
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history response is invalid.");
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
}
}
}
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace InsightsService.Domain;
public sealed record ContextSelection
{
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
public string? Setting { get; init; }
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
public string? ActivityCondition { get; init; }
}
@@ -0,0 +1,6 @@
namespace InsightsService.Domain;
public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
@@ -0,0 +1,223 @@
using System.Globalization;
using InsightsService.Contracts;
namespace InsightsService.Domain;
public sealed partial class InsightCalculator
{
private const string GeneralLimits = "General reference thresholds are not individual treatment targets. " +
"This is a descriptive assessment, not a diagnosis or medication recommendation. " +
"Symptoms, treatment, training, risk factors and measurement technique are not established by these observations.";
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to,
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
{
var comparability = AssessComparability(observations);
return new(patientId, from, to, selection, observations.Count, comparability,
AssessMeasurement("Systolic", "mmHg", observations, o => o.Systolic, comparability),
AssessMeasurement("Diastolic", "mmHg", observations, o => o.Diastolic, comparability),
AssessMeasurement("Pulse", "beats/min", observations, o => o.Pulse, comparability));
}
private static MeasurementAssessment AssessMeasurement(string metric, string unit,
IReadOnlyList<ObservationDto> observations, Func<ObservationDto, int> value,
ComparabilityAssessment comparability)
{
if (observations.Count == 0)
return new(metric, unit, null, null, null, null, 0, "Unavailable", "Unavailable", null, 0,
null, "No matching observations; insufficient observation data for trend calculation.",
null, "Unavailable: no matching observations.", "CannotInterpret", GeneralLimits);
// Collapse timestamp ties for temporal calculations only; descriptive levels retain every observation.
var points = observations.GroupBy(o => o.MeasuredAt).OrderBy(g => g.Key)
.Select(g => (Time: g.Key, Value: g.Average(o => (decimal)value(o)))).ToArray();
var minimum = observations.Min(value);
var maximum = observations.Max(value);
var mean = observations.Average(o => (decimal)value(o));
var signs = points.Zip(points.Skip(1), (a, b) => Math.Sign(b.Value - a.Value))
.Where(s => s != 0).ToArray();
var reversals = signs.Zip(signs.Skip(1), (a, b) => a != b ? 1 : 0).Sum();
var direction = points.Length < 2 ? "Unavailable" : signs.Length == 0 ? "NoClearDirection" :
reversals > 0 ? "Mixed" : signs[0] > 0 ? "Increasing" : "Decreasing";
decimal? slope = null;
var overall = "Unavailable";
decimal? totalChange = null;
if (points.Length >= 2)
{
// Scale time to [0,1] before OLS, avoiding extreme timestamp magnitudes.
var span = (decimal)(points[^1].Time.Ticks - points[0].Time.Ticks);
var xs = points.Select(p => (p.Time.Ticks - points[0].Time.Ticks) / span).ToArray();
var xMean = xs.Average();
var yMean = points.Average(p => p.Value);
var numerator = points.Select((p, i) => (xs[i] - xMean) * (p.Value - yMean)).Sum();
var denominator = xs.Sum(x => (x - xMean) * (x - xMean));
var scaledSlope = numerator / denominator;
slope = scaledSlope / (span / TimeSpan.TicksPerDay);
overall = scaledSlope > 0 ? "Increasing" : scaledSlope < 0 ? "Decreasing" : "NoClearDirection";
totalChange = points.Zip(points.Skip(1), (a, b) => Math.Abs(b.Value - a.Value)).Sum();
}
var numerical = $"All {observations.Count} observations: mean {Format(mean)}, minimum {minimum}, maximum {maximum}, " +
$"range {maximum - minimum} {unit}. " + (points.Length < 2
? "Direction is unavailable: at least two distinct measurement timestamps are required."
: $"Temporal direction: {direction}; full-period least-squares direction: {overall}; " +
$"{reversals} reversal(s). Timestamp ties use arithmetic means. " +
$"Total successive change is {Format(totalChange!.Value)} {unit}.") +
" Range and successive change describe observed variation; no clinical stability classification is made.";
var reference = SelectReference(metric, observations, comparability);
var comparison = "Unavailable: known, non-conflicting resting conditions" +
(metric == "Pulse" ? "" : " and a single Home or Clinic setting") + " are required; recorded inadequate preparation also limits applicability.";
var interpretation = "CannotInterpret";
var hint = "Numerical changes alone do not establish favourable or concerning development.";
if (reference is not null)
{
var above = observations.Count(o => IsHigh(value(o), reference));
var below = observations.Count(o => IsLow(value(o), reference));
comparison = $"Descriptive mean {Format(mean)} {unit}; {above} observation(s) " +
$"{reference.UpperComparison} {Format(reference.UpperBoundary)} {unit}" +
(reference.LowerBoundary is { } lower ? $"; {below} observation(s) < {Format(lower)} {unit}." : ".") +
" This period does not establish a guideline diagnostic measurement protocol. " + reference.Limitation;
if (points.Length >= 2 && comparability.Status == "SupportedRecordedComparability")
{
var first = points[0].Value;
var last = points[^1].Value;
if (reversals > 0 && (above > 0 || below > 0))
{
interpretation = "Mixed";
hint = "Reversing movements and excursions outside the cited reference boundaries coexist; " +
"an overall slope does not establish consistent improvement or deterioration.";
}
else if (direction == "Decreasing" && IsHigh(first, reference) &&
!IsLow(last, reference) && below == 0 && (metric == "Pulse" || IsHigh(last, reference)))
{
interpretation = "PotentiallyFavourable";
hint = "Movement away from initially high levels towards the cited reference boundary may be favourable. " +
"This is a cautious inference from the source's reference comparison, not a clinical decision rule. " +
(IsHigh(last, reference) ? "The latest timestamp mean remains above or at the high boundary." :
"Reaching the reference interval does not establish an individual treatment target or good health.");
}
else if (metric == "Pulse" && direction == "Increasing" && IsLow(first, reference) &&
!IsHigh(last, reference) && above == 0)
{
interpretation = "PotentiallyFavourable";
hint = "Movement away from initially low resting pulse towards the reference interval may be favourable, " +
"but low pulse may be physiological in trained people. This is a cautious inference, not a clinical rule. " +
(IsLow(last, reference) ? "The latest timestamp mean remains below the lower boundary." :
"Being within these boundaries does not establish good health.");
}
else if (above > 0 || below > 0)
{
interpretation = "PotentiallyConcerning";
hint = "Observed levels outside the cited reference boundaries may warrant clinical review. " +
"Limited variation does not establish healthy levels, and a decrease into low resting pulse " +
"is not automatically favourable. The cause and individual significance cannot be determined here.";
}
}
else
hint = "The recorded context supports this limited reference comparison, but " +
(points.Length < 2 ? "temporal direction is unavailable. " :
"missing or differing conditions limit interpretation of the combined trajectory. ") +
"An outside-reference value is not dismissed because preparation information is incomplete.";
}
return new(metric, unit, Round(mean), minimum, maximum, maximum - minimum, points.Length,
direction, overall, slope is { } s ? Math.Round(s, 6, MidpointRounding.AwayFromZero) : null,
reversals, totalChange is { } change ? Round(change) : null, numerical, reference,
comparison, interpretation, hint + " " + comparability.Explanation + " " + GeneralLimits);
}
private static ClinicalReference? SelectReference(string metric, IReadOnlyList<ObservationDto> observations,
ComparabilityAssessment comparability)
{
if (comparability.Conflicts.Count > 0 ||
observations.Any(o => o.MeasurementContext?.ActivityCondition != "AtRest")) return null;
if (metric == "Pulse")
return new("Recorded resting pulse", 50, "<", 100, ">",
[new("Patienthåndbogen: Bradykardi (langsom puls)",
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/",
"2025-09-02", "2026-10-05"),
new("Patienthåndbogen: Hurtig puls (takykardi)",
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/",
"2025-05-12", "2026-10-05")],
"These are resting-rate reference boundaries, not a diagnosis, a universal normal range or a treatment target. " +
"Low pulse can be physiological in trained people; age, fitness, symptoms and medicines affect applicability.");
var settings = observations.Select(o => o.MeasurementContext?.Setting).Distinct().ToArray();
if (settings.Length != 1 || settings[0] is not ("Home" or "Clinic")) return null;
// Known inadequate rest prevents even a provisional resting-pressure comparison.
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5)) return null;
if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) &&
!new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase)))
return null;
var threshold = metric == "Systolic" ? (settings[0] == "Home" ? 135 : 140) :
(settings[0] == "Home" ? 85 : 90);
return new($"Recorded {settings[0]} resting blood pressure", null, null, threshold, ">=",
[new("Lægehåndbogen: Højt blodtryk",
"https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/",
"2024-09-25", "2026-10-05")],
"Setting-specific high-pressure reference threshold. Missing preparation details make this comparison provisional; " +
"five minutes of rest, appropriate technique and repeated measurements are not inferred. " +
"Being below a high-pressure threshold does not establish an appropriate lower level or a personalised goal.");
}
private static bool IsHigh(decimal value, ClinicalReference reference) =>
reference.UpperComparison == ">=" ? value >= reference.UpperBoundary : value > reference.UpperBoundary;
private static bool IsLow(decimal value, ClinicalReference reference) =>
reference.LowerBoundary is { } lower && value < lower;
private static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
private static string Format(decimal value) => Round(value).ToString("0.##", CultureInfo.InvariantCulture);
private static ComparabilityAssessment AssessComparability(IReadOnlyList<ObservationDto> observations)
{
List<string> similarities = [], differences = [], missing = [], conflicts = [];
if (observations.Count == 0)
return new("InsufficientContext", similarities, differences, missing, conflicts,
"No matching observations are available to assess comparability.");
var details = new (string Name, string?[] Values)[]
{
("setting", observations.Select(o => o.MeasurementContext?.Setting).ToArray()),
("activity condition", observations.Select(o => o.MeasurementContext?.ActivityCondition).ToArray()),
("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray())
};
foreach (var (name, values) in details)
{
var known = values.Where(v => !string.IsNullOrWhiteSpace(v) && v != "Unknown")
.Select(v => v!.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
if (values.Any(v => string.IsNullOrWhiteSpace(v) || v == "Unknown")) missing.Add(name);
if (known.Length > 1) differences.Add($"{name}: {string.Join(" / ", known)}");
else if (known.Length == 1 && !missing.Contains(name)) similarities.Add($"{name}: {known[0]}");
}
var circumstances = observations.Select(o => o.MeasurementContext?.AdditionalCircumstances)
.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s!.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
if (circumstances.Length > 1) differences.Add("additional circumstances differ");
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5))
differences.Add("recorded rest duration is below the five-minute blood-pressure preparation recommendation");
foreach (var observation in observations)
{
var context = observation.MeasurementContext;
var narrative = string.Join(" ", observation.Context, observation.Note, context?.AdditionalCircumstances,
context?.BodyPosition, context?.DeviceDetails, context?.CuffDetails).ToLowerInvariant();
if (context?.ActivityCondition == "AtRest" && new[]
{ "during exercise", "during activity", "after exercise", "after activity", "under motion", "under træning", "efter motion", "efter træning" }
.Any(narrative.Contains)) conflicts.Add("AtRest conflicts with an activity description in recorded text.");
if (context?.Setting == "Home" && new[] { "at clinic", "in clinic", "at the clinic", "på klinik", "hos lægen" }.Any(narrative.Contains))
conflicts.Add("Home conflicts with a clinic description in recorded text.");
if (context?.Setting == "Clinic" && new[] { "at home", "hjemme" }.Any(narrative.Contains))
conflicts.Add("Clinic conflicts with a home description in recorded text.");
}
var status = conflicts.Count > 0 ? "ConflictingContext" : differences.Count > 0 ? "KnownDifferences" :
missing.Count > 0 ? "InsufficientContext" : "SupportedRecordedComparability";
var explanation = $"Recorded comparability: {status}. " +
(missing.Count > 0 ? $"Unknown or missing: {string.Join(", ", missing)}. " : "") +
(differences.Count > 0 ? $"Known differences: {string.Join("; ", differences)}. " : "") +
(conflicts.Count > 0 ? $"Conflicts: {string.Join("; ", conflicts.Distinct())} " : "") +
"Matching recorded details support comparability only of those details; they do not certify identical " +
"conditions, validated equipment or guideline-compliant technique. Narrative conflict detection is limited " +
"to documented phrases; other text is not proof of comparability. A difference between Home and Clinic " +
"selections alone is not improvement or deterioration over time.";
return new(status, similarities, differences, missing, conflicts.Distinct().Order(StringComparer.Ordinal).ToArray(), explanation);
}
}
@@ -0,0 +1,50 @@
using System.Globalization;
using InsightsService.Contracts;
namespace InsightsService.Domain;
public sealed partial class InsightCalculator
{
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
{
if (observations.Count == 0)
return null;
return new HealthInsight(patientId, from, to,
Math.Round(observations.Average(o => (decimal)o.Systolic), 2, MidpointRounding.AwayFromZero),
Math.Round(observations.Average(o => (decimal)o.Diastolic), 2, MidpointRounding.AwayFromZero),
Math.Round(observations.Average(o => (decimal)o.Pulse), 2, MidpointRounding.AwayFromZero),
observations.Min(o => o.Systolic), observations.Max(o => o.Systolic),
observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic),
selection, observations.Count, DescribeContext(observations));
}
private static string DescribeContext(IReadOnlyList<ObservationDto> observations)
{
var settings = observations.Select(o => o.MeasurementContext?.Setting ?? "Unknown").ToArray();
var activities = observations.Select(o => o.MeasurementContext?.ActivityCondition ?? "Unknown").ToArray();
var explanation = $"Recorded settings: {Counts(settings)}. Recorded activity conditions: {Counts(activities)}.";
if (settings.Distinct().Count() > 1 || activities.Distinct().Count() > 1)
explanation += " This numerical summary pools mixed settings or activity conditions.";
if (settings.Contains("Unknown") || activities.Contains("Unknown"))
explanation += " Some setting or activity information is unknown.";
var details = new (string Name, string?[] Values)[]
{
("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray()),
("additional circumstances", observations.Select(o => o.MeasurementContext?.AdditionalCircumstances).ToArray())
};
var missing = details.Where(d => d.Values.Any(string.IsNullOrWhiteSpace)).Select(d => d.Name).ToArray();
var differing = details.Where(d => d.Values.Where(v => !string.IsNullOrWhiteSpace(v)).Distinct().Count() > 1)
.Select(d => d.Name).ToArray();
if (missing.Length > 0) explanation += $" Optional details are unrecorded for some observations: {string.Join(", ", missing)}.";
if (differing.Length > 0) explanation += $" Recorded detail values differ: {string.Join(", ", differing)}.";
return explanation + " These are descriptive statistics, not a diagnostic monitoring protocol; recorded categories alone do not establish clinically comparable conditions. Legacy narrative text does not establish a category.";
}
private static string Counts(IEnumerable<string> values) => string.Join(", ", values.GroupBy(v => v)
.OrderBy(g => g.Key, StringComparer.Ordinal).Select(g => $"{g.Key} ({g.Count()})"));
}
@@ -0,0 +1,21 @@
namespace InsightsService.Domain;
public sealed record TrendAssessment(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
ContextSelection AppliedSelection, int ContributingCount, ComparabilityAssessment Comparability,
MeasurementAssessment Systolic, MeasurementAssessment Diastolic, MeasurementAssessment Pulse);
public sealed record ComparabilityAssessment(string Status, IReadOnlyList<string> KnownSimilarities,
IReadOnlyList<string> KnownDifferences, IReadOnlyList<string> MissingDetails,
IReadOnlyList<string> Conflicts, string Explanation);
public sealed record MeasurementAssessment(string Metric, string Unit, decimal? Mean, int? Minimum,
int? Maximum, int? Range, int DistinctTimestampCount, string Direction, string OverallDirection,
decimal? SlopePerDay, int ReversalCount, decimal? TotalSuccessiveChange,
string NumericalExplanation, ClinicalReference? Reference, string ReferenceComparison,
string Interpretation, string Hint);
public sealed record ClinicalReference(string Scope, decimal? LowerBoundary, string? LowerComparison,
decimal UpperBoundary, string UpperComparison, IReadOnlyList<ReferenceSource> Sources,
string Limitation);
public sealed record ReferenceSource(string Title, string Url, string Updated, string Reviewed);
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
</ItemGroup>
</Project>
@@ -0,0 +1,61 @@
using System.Security.Cryptography;
using System.Text;
using InsightsService.Application;
using InsightsService.Clients;
using InsightsService.Domain;
namespace InsightsService;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-insights");
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddScoped<InsightsApplicationService>();
builder.Services.AddSingleton<InsightCalculator>();
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetGatewayUri(configuration);
var serviceKey = configuration["Services:ApiGateway:Key"];
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
var app = builder.Build();
if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https")
throw new InvalidOperationException("Production gateway endpoints must use HTTPS.");
_ = GetGatewayUri(app.Configuration);
var outgoingKey = app.Configuration["Services:ApiGateway:Key"];
if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32)
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
app.UseExceptionHandler();
app.Use(async (context, next) =>
{
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
{ context.Response.StatusCode = 401; return; }
await next(context);
});
app.MapControllers();
app.Run();
}
private static Uri GetGatewayUri(IConfiguration configuration)
{
var endpoint = configuration["Services:ApiGateway:BaseUrl"];
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
(uri.Scheme != "http" && uri.Scheme != "https") || uri.AbsolutePath != "/" ||
!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) || !string.IsNullOrEmpty(uri.UserInfo))
throw new InvalidOperationException("Services:ApiGateway:BaseUrl must be an HTTP(S) origin URL.");
return uri;
}
}
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
+64
View File
@@ -0,0 +1,64 @@
# US-12 health overview
`GET /api/patients/{patientId}/overview?from=...&to=...&setting=Home&activityCondition=AtRest`
requires the patient's authenticated account or an assigned read-only professional.
Dates use the existing inclusive measurement-instant convention. Offset-free timestamps
mean UTC; equivalent offsets identify the same instant. From and to are required,
equal bounds are valid, reversed/malformed/missing bounds return 400. Both selected
context dimensions must match for insight; `Unknown` is an explicit selectable category.
Omitted dimensions are unrestricted. Unsupported selections return 400 validation details.
The independent ASP.NET Core Health Overview Service loads the profile, latest overall
observation and US-10 numerical insight through three HTTP clients routed through the
gateway. It has no production project references to another service, database, stored
aggregate or cache. The renamed Overview ER illustration explicitly denotes data needed
from other services rather than overview persistence; the current class model governs.
## Response
A successful request returns 200 with:
- `patient`: the current profile, including ID, name, birth date and contact information.
- `latestObservation`: latest overall reading, including original text, note and all recorded
structured context, or null when no observations exist. Latest retains US-06 timestamp,
original recording-time and deterministic ID ordering. The insight period and filters
never limit latest-observation selection.
- `insight`: the existing US-10 response or null when no observations match the insight
period/context. Its rounded means, extrema, selection, contributing count and context
explanation are preserved. No trend component is added.
- `periodStart`, `periodEnd`, `insightSelection`, `insightContributingCount`: explicit insight
basis even when insight is absent (count zero).
- `latestObservationBasis`: explains that latest context belongs to that reading only.
- `insightExplanation`: preserves the insight's context limitations or explains why no
selected-period insight is available. Empty insight does not remove profile/latest.
An authorized missing patient returns 404 with `Patient does not exist.` Access rejection
retains the gateway's non-disclosing empty 404 convention; unauthenticated clients get 401.
Professional writes remain forbidden. Upstream connection/status/invalid-JSON failures
return 502; local upstream timeouts return 504. These are not reported as absent data.
Only upstream 404 responses on the appropriate profile/latest/insight routes represent
missing data. Requests are cancelled on client disconnect.
Every overview request fetches current source data, including profile updates, corrected
measurement/context, and deletions. Reads occur separately across services, so concurrent
writes may occur between them; the overview does not promise a cross-service snapshot.
There is no extra transaction, refresh mechanism, synchronisation process or persisted
copy to invalidate.
## Deployment and verification
The service builds/publishes independently with .NET 10 and starts from external
configuration. See `deploy/health-overview.env.example`, the independent systemd unit,
[README.md](README.md) and [AUTHENTICATION.md](AUTHENTICATION.md). It requires only the
gateway origin and incoming/outgoing service credentials; no database configuration or
migration is needed. Production uses HTTPS; local HTTP is limited to Development.
Addresses, network binding, credentials and certificates are configurable for separate
machines. Standard stdout/stderr logging, graceful shutdown and restart follow the other
service units. No new package dependencies are introduced.
US-12 acceptance tests run five actual HTTP hosts against separate patient/observation
PostgreSQL databases. They cover all story scenarios, boundaries/offsets, patient scope,
latest tie rules, context preservation, independent filters, unknown/mixed context,
empty selected insight, corrections/deletions/restart, profile updates, missing patients,
validation, owner/assignment enforcement, direct bypass rejection, restricted internal
service reads and unavailable upstream/Overview services.
@@ -0,0 +1,89 @@
using System.ComponentModel.DataAnnotations;
using System.Net;
using ObservationService.Contracts;
using ObservationService.Domain;
namespace ObservationService.Application;
public sealed class ObservationApplicationService(ObservationRepository repository, IHttpClientFactory clients)
{
public Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken) =>
repository.DeleteAsync(observationId, cancellationToken);
public Task<BloodPressureObservation?> UpdateAsync(Guid observationId, UpdateObservationRequest request,
CancellationToken cancellationToken)
{
if (request.Systolic is null or <= 0 || request.Diastolic is null or <= 0 || request.Pulse is null or <= 0)
throw new ArgumentException("Positive measured values are required.", nameof(request));
return PatchAsync(observationId, new PatchObservationRequest { Systolic = request.Systolic, Diastolic = request.Diastolic, Pulse = request.Pulse }, cancellationToken);
}
public Task<BloodPressureObservation?> PatchAsync(Guid observationId, PatchObservationRequest request,
CancellationToken cancellationToken)
{
Validator.ValidateObject(request, new ValidationContext(request), validateAllProperties: true);
if (request.MeasurementContext is not null)
Validator.ValidateObject(request.MeasurementContext, new ValidationContext(request.MeasurementContext), validateAllProperties: true);
return repository.UpdateAsync(observationId, request, DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified), cancellationToken);
}
public async Task<BloodPressureObservation?> RecordAsync(Guid patientId, RecordObservationRequest request,
CancellationToken cancellationToken)
{
if (request.MeasuredAt is null || request.Systolic is null or <= 0 ||
request.Diastolic is null or <= 0 || request.Pulse is null or <= 0)
throw new ArgumentException("A timestamp and positive measured values are required.", nameof(request));
var suppliedContext = request.MeasurementContext ?? new MeasurementContext();
var measurementContext = suppliedContext with
{
Setting = suppliedContext.Setting ?? "Unknown",
ActivityCondition = suppliedContext.ActivityCondition ?? "Unknown"
};
Validator.ValidateObject(measurementContext, new ValidationContext(measurementContext), validateAllProperties: true);
using var patient = await clients.CreateClient("ApiGateway").GetAsync($"api/patients/{patientId}",
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (patient.StatusCode == HttpStatusCode.NotFound)
return null;
// Upstream failures must never be interpreted as an existing patient.
patient.EnsureSuccessStatusCode();
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
var measuredAt = request.MeasuredAt.Value;
if (measuredAt.Kind != DateTimeKind.Unspecified)
measuredAt = measuredAt.ToUniversalTime();
return await repository.SaveAsync(new BloodPressureObservation
{
ObservationId = Guid.NewGuid(), PatientId = patientId,
MeasuredAt = DateTime.SpecifyKind(measuredAt, DateTimeKind.Unspecified),
Systolic = request.Systolic.Value, Diastolic = request.Diastolic.Value,
Pulse = request.Pulse.Value, Context = request.Context, Note = request.Note,
MeasurementContext = measurementContext,
CreatedAt = now, UpdatedAt = now
}, cancellationToken);
}
public Task<BloodPressureObservation?> GetByIdAsync(Guid observationId, CancellationToken cancellationToken) =>
repository.FindByIdAsync(observationId, cancellationToken);
public Task<BloodPressureObservation?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken) =>
repository.FindLatestByPatientIdAsync(patientId, cancellationToken);
public Task<List<BloodPressureObservation>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken)
{
from = NormalizeTimestamp(from);
to = NormalizeTimestamp(to);
if (to < from)
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
return repository.FindByPatientIdAndPeriodAsync(patientId, from, to, selection, cancellationToken);
}
private static DateTime NormalizeTimestamp(DateTime timestamp) =>
DateTime.SpecifyKind(timestamp.Kind == DateTimeKind.Unspecified ? timestamp : timestamp.ToUniversalTime(),
DateTimeKind.Unspecified);
}
@@ -0,0 +1,16 @@
using ObservationService.Contracts;
using ObservationService.Domain;
namespace ObservationService.Application;
public interface ObservationRepository
{
Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken);
Task<BloodPressureObservation?> UpdateAsync(Guid observationId, PatchObservationRequest request,
DateTime updatedAt, CancellationToken cancellationToken);
Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken);
Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken);
Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken);
Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken);
}
@@ -0,0 +1,87 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace ObservationService.Contracts;
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public sealed record MeasurementContextPatch
{
private string? setting;
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
public string? Setting
{
get => setting;
init { setting = value; SettingSpecified = true; }
}
[JsonIgnore]
public bool SettingSpecified { get; private set; }
private string? activityCondition;
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
public string? ActivityCondition
{
get => activityCondition;
init { activityCondition = value; ActivityConditionSpecified = true; }
}
[JsonIgnore]
public bool ActivityConditionSpecified { get; private set; }
private decimal? restDurationMinutes;
[Range(0, double.MaxValue)]
public decimal? RestDurationMinutes
{
get => restDurationMinutes;
init { restDurationMinutes = value; RestDurationMinutesSpecified = true; }
}
[JsonIgnore]
public bool RestDurationMinutesSpecified { get; private set; }
private string? bodyPosition;
public string? BodyPosition
{
get => bodyPosition;
init { bodyPosition = value; BodyPositionSpecified = true; }
}
[JsonIgnore]
public bool BodyPositionSpecified { get; private set; }
private string? measuredArm;
public string? MeasuredArm
{
get => measuredArm;
init { measuredArm = value; MeasuredArmSpecified = true; }
}
[JsonIgnore]
public bool MeasuredArmSpecified { get; private set; }
private string? deviceDetails;
public string? DeviceDetails
{
get => deviceDetails;
init { deviceDetails = value; DeviceDetailsSpecified = true; }
}
[JsonIgnore]
public bool DeviceDetailsSpecified { get; private set; }
private string? cuffDetails;
public string? CuffDetails
{
get => cuffDetails;
init { cuffDetails = value; CuffDetailsSpecified = true; }
}
[JsonIgnore]
public bool CuffDetailsSpecified { get; private set; }
private string? additionalCircumstances;
public string? AdditionalCircumstances
{
get => additionalCircumstances;
init { additionalCircumstances = value; AdditionalCircumstancesSpecified = true; }
}
[JsonIgnore]
public bool AdditionalCircumstancesSpecified { get; private set; }
[JsonIgnore]
public bool HasChanges => SettingSpecified || ActivityConditionSpecified || RestDurationMinutesSpecified ||
BodyPositionSpecified || MeasuredArmSpecified || DeviceDetailsSpecified || CuffDetailsSpecified || AdditionalCircumstancesSpecified;
}
@@ -0,0 +1,6 @@
using ObservationService.Domain;
namespace ObservationService.Contracts;
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, MeasurementContext MeasurementContext);
@@ -0,0 +1,78 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace ObservationService.Contracts;
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public sealed record PatchObservationRequest : IValidatableObject
{
private int? systolic;
[Range(1, int.MaxValue)]
public int? Systolic
{
get => systolic;
init { systolic = value; SystolicSpecified = true; }
}
[JsonIgnore]
public bool SystolicSpecified { get; private set; }
private int? diastolic;
[Range(1, int.MaxValue)]
public int? Diastolic
{
get => diastolic;
init { diastolic = value; DiastolicSpecified = true; }
}
[JsonIgnore]
public bool DiastolicSpecified { get; private set; }
private int? pulse;
[Range(1, int.MaxValue)]
public int? Pulse
{
get => pulse;
init { pulse = value; PulseSpecified = true; }
}
[JsonIgnore]
public bool PulseSpecified { get; private set; }
private MeasurementContextPatch? measurementContext;
public MeasurementContextPatch? MeasurementContext
{
get => measurementContext;
init { measurementContext = value; MeasurementContextSpecified = true; }
}
[JsonIgnore]
public bool MeasurementContextSpecified { get; private set; }
private string? context;
public string? Context
{
get => context;
init { context = value; ContextSpecified = true; }
}
[JsonIgnore]
public bool ContextSpecified { get; private set; }
private string? note;
public string? Note
{
get => note;
init { note = value; NoteSpecified = true; }
}
[JsonIgnore]
public bool NoteSpecified { get; private set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (SystolicSpecified && Systolic is null)
yield return new ValidationResult("Systolic cannot be cleared.", [nameof(Systolic)]);
if (DiastolicSpecified && Diastolic is null)
yield return new ValidationResult("Diastolic cannot be cleared.", [nameof(Diastolic)]);
if (PulseSpecified && Pulse is null)
yield return new ValidationResult("Pulse cannot be cleared.", [nameof(Pulse)]);
if (!SystolicSpecified && !DiastolicSpecified && !PulseSpecified && !ContextSpecified && !NoteSpecified &&
!(MeasurementContextSpecified && (MeasurementContext is null || MeasurementContext.HasChanges)))
yield return new ValidationResult("Supply at least one supported field to update.");
}
}
@@ -0,0 +1,24 @@
using System.ComponentModel.DataAnnotations;
using ObservationService.Domain;
namespace ObservationService.Contracts;
public sealed record RecordObservationRequest
{
[Required]
public DateTime? MeasuredAt { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Systolic { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Diastolic { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Pulse { get; init; }
public MeasurementContext? MeasurementContext { get; init; }
public string? Context { get; init; }
public string? Note { get; init; }
}
@@ -0,0 +1,17 @@
using System.Text.Json.Serialization;
using System.ComponentModel.DataAnnotations;
namespace ObservationService.Contracts;
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public sealed record UpdateObservationRequest
{
[Required, Range(1, int.MaxValue)]
public int? Systolic { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Diastolic { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Pulse { get; init; }
}
@@ -0,0 +1,90 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using ObservationService.Application;
using ObservationService.Contracts;
using ObservationService.Domain;
namespace ObservationService.Controllers;
[ApiController]
[Route("api")]
public sealed class ObservationController(ObservationApplicationService service) : ControllerBase
{
[HttpPost("patients/{patientId:guid}/observations")]
public async Task<ActionResult<ObservationDto>> RecordObservation(Guid patientId, RecordObservationRequest request,
CancellationToken cancellationToken)
{
try
{
var observation = await service.RecordAsync(patientId, request, cancellationToken);
return observation is null
? NotFound()
: CreatedAtAction(nameof(GetObservation), new { observationId = observation.ObservationId }, ToDto(observation));
}
catch (HttpRequestException)
{
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Patient lookup is unavailable.");
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Patient lookup timed out.");
}
}
[HttpDelete("observations/{observationId:guid}")]
public async Task<IActionResult> DeleteObservation(Guid observationId, CancellationToken cancellationToken) =>
await service.DeleteAsync(observationId, cancellationToken) ? NoContent() : NotFound();
[HttpPut("observations/{observationId:guid}")]
public async Task<ActionResult<ObservationDto>> UpdateObservation(Guid observationId, UpdateObservationRequest request,
CancellationToken cancellationToken)
{
var observation = await service.UpdateAsync(observationId, request, cancellationToken);
return observation is null ? NotFound() : Ok(ToDto(observation));
}
[HttpPatch("observations/{observationId:guid}")]
public async Task<ActionResult<ObservationDto>> PatchObservation(Guid observationId, PatchObservationRequest request,
CancellationToken cancellationToken)
{
var observation = await service.PatchAsync(observationId, request, cancellationToken);
return observation is null ? NotFound() : Ok(ToDto(observation));
}
[HttpGet("observations/{observationId:guid}")]
public async Task<ActionResult<ObservationDto>> GetObservation(Guid observationId, CancellationToken cancellationToken)
{
var observation = await service.GetByIdAsync(observationId, cancellationToken);
return observation is null ? NotFound() : Ok(ToDto(observation));
}
[HttpGet("patients/{patientId:guid}/observations/latest")]
public async Task<ActionResult<ObservationDto>> GetLatest(Guid patientId, CancellationToken cancellationToken)
{
var observation = await service.GetLatestAsync(patientId, cancellationToken);
return observation is null ? NotFound() : Ok(ToDto(observation));
}
[HttpGet("patients/{patientId:guid}/observations")]
public async Task<ActionResult<List<ObservationDto>>> GetByPeriod(Guid patientId,
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{
try
{
var observations = await service.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
Response.Headers["X-Measurement-Setting"] = selection.Setting ?? "All";
Response.Headers["X-Activity-Condition"] = selection.ActivityCondition ?? "All";
return Ok(observations.Select(ToDto).ToList());
}
catch (ArgumentException)
{
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
return ValidationProblem(ModelState);
}
}
private static ObservationDto ToDto(BloodPressureObservation observation) =>
new(observation.ObservationId, observation.PatientId, observation.MeasuredAt, observation.Systolic,
observation.Diastolic, observation.Pulse, observation.Context, observation.Note, observation.MeasurementContext);
}
@@ -0,0 +1,16 @@
namespace ObservationService.Domain;
public sealed class BloodPressureObservation
{
public Guid ObservationId { get; set; }
public Guid PatientId { get; set; }
public DateTime MeasuredAt { get; set; }
public int Systolic { get; set; }
public int Diastolic { get; set; }
public int Pulse { get; set; }
public MeasurementContext MeasurementContext { get; set; } = new();
public string? Context { get; set; }
public string? Note { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace ObservationService.Domain;
public sealed record ContextSelection
{
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
public string? Setting { get; init; }
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
public string? ActivityCondition { get; init; }
}
@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
namespace ObservationService.Domain;
public sealed record MeasurementContext
{
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
public string? Setting { get; init; } = "Unknown";
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
public string? ActivityCondition { get; init; } = "Unknown";
[Range(0, double.MaxValue)]
public decimal? RestDurationMinutes { get; init; }
public string? BodyPosition { get; init; }
public string? MeasuredArm { get; init; }
public string? DeviceDetails { get; init; }
public string? CuffDetails { get; init; }
public string? AdditionalCircumstances { get; init; }
}
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
</ItemGroup>
</Project>
@@ -0,0 +1,77 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using ObservationService.Persistence;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
[DbContext(typeof(ObservationDbContext))]
[Migration("20261001095222_InitialObservationSchema")]
partial class InitialObservationSchema
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.Property<Guid>("ObservationId")
.HasColumnType("uuid")
.HasColumnName("observation_id");
b.Property<string>("Context")
.HasColumnType("character varying")
.HasColumnName("context");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<int>("Diastolic")
.HasColumnType("integer")
.HasColumnName("diastolic");
b.Property<DateTime>("MeasuredAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("measured_at");
b.Property<string>("Note")
.HasColumnType("character varying")
.HasColumnName("note");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<int>("Pulse")
.HasColumnType("integer")
.HasColumnName("pulse");
b.Property<int>("Systolic")
.HasColumnType("integer")
.HasColumnName("systolic");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("ObservationId");
b.ToTable("blood_pressure_observation", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,42 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
/// <inheritdoc />
public partial class InitialObservationSchema : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "blood_pressure_observation",
columns: table => new
{
observation_id = table.Column<Guid>(type: "uuid", nullable: false),
patient_id = table.Column<Guid>(type: "uuid", nullable: false),
measured_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
systolic = table.Column<int>(type: "integer", nullable: false),
diastolic = table.Column<int>(type: "integer", nullable: false),
pulse = table.Column<int>(type: "integer", nullable: false),
context = table.Column<string>(type: "character varying", nullable: true),
note = table.Column<string>(type: "character varying", nullable: true),
created_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
updated_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_blood_pressure_observation", x => x.observation_id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "blood_pressure_observation");
}
}
}
@@ -0,0 +1,134 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using ObservationService.Persistence;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
[DbContext(typeof(ObservationDbContext))]
[Migration("20261005094632_RecordedMeasurementContext")]
partial class RecordedMeasurementContext
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.Property<Guid>("ObservationId")
.HasColumnType("uuid")
.HasColumnName("observation_id");
b.Property<string>("Context")
.HasColumnType("character varying")
.HasColumnName("context");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<int>("Diastolic")
.HasColumnType("integer")
.HasColumnName("diastolic");
b.Property<DateTime>("MeasuredAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("measured_at");
b.Property<string>("Note")
.HasColumnType("character varying")
.HasColumnName("note");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<int>("Pulse")
.HasColumnType("integer")
.HasColumnName("pulse");
b.Property<int>("Systolic")
.HasColumnType("integer")
.HasColumnName("systolic");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("ObservationId");
b.ToTable("blood_pressure_observation", (string)null);
});
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.OwnsOne("ObservationService.Domain.MeasurementContext", "MeasurementContext", b1 =>
{
b1.Property<Guid>("BloodPressureObservationObservationId")
.HasColumnType("uuid");
b1.Property<string>("ActivityCondition")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("Unknown")
.HasColumnName("activity_condition");
b1.Property<string>("AdditionalCircumstances")
.HasColumnType("text")
.HasColumnName("additional_circumstances");
b1.Property<string>("BodyPosition")
.HasColumnType("text")
.HasColumnName("body_position");
b1.Property<string>("CuffDetails")
.HasColumnType("text")
.HasColumnName("cuff_details");
b1.Property<string>("DeviceDetails")
.HasColumnType("text")
.HasColumnName("device_details");
b1.Property<string>("MeasuredArm")
.HasColumnType("text")
.HasColumnName("measured_arm");
b1.Property<decimal?>("RestDurationMinutes")
.HasColumnType("numeric")
.HasColumnName("rest_duration_minutes");
b1.Property<string>("Setting")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("Unknown")
.HasColumnName("setting");
b1.HasKey("BloodPressureObservationObservationId");
b1.ToTable("blood_pressure_observation");
b1.WithOwner()
.HasForeignKey("BloodPressureObservationObservationId");
});
b.Navigation("MeasurementContext")
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,100 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
/// <inheritdoc />
public partial class RecordedMeasurementContext : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "activity_condition",
table: "blood_pressure_observation",
type: "text",
nullable: false,
defaultValue: "Unknown");
migrationBuilder.AddColumn<string>(
name: "additional_circumstances",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "body_position",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "cuff_details",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "device_details",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "measured_arm",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<decimal>(
name: "rest_duration_minutes",
table: "blood_pressure_observation",
type: "numeric",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "setting",
table: "blood_pressure_observation",
type: "text",
nullable: false,
defaultValue: "Unknown");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "activity_condition",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "additional_circumstances",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "body_position",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "cuff_details",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "device_details",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "measured_arm",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "rest_duration_minutes",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "setting",
table: "blood_pressure_observation");
}
}
}
@@ -0,0 +1,131 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using ObservationService.Persistence;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
[DbContext(typeof(ObservationDbContext))]
partial class ObservationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.Property<Guid>("ObservationId")
.HasColumnType("uuid")
.HasColumnName("observation_id");
b.Property<string>("Context")
.HasColumnType("character varying")
.HasColumnName("context");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<int>("Diastolic")
.HasColumnType("integer")
.HasColumnName("diastolic");
b.Property<DateTime>("MeasuredAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("measured_at");
b.Property<string>("Note")
.HasColumnType("character varying")
.HasColumnName("note");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<int>("Pulse")
.HasColumnType("integer")
.HasColumnName("pulse");
b.Property<int>("Systolic")
.HasColumnType("integer")
.HasColumnName("systolic");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("ObservationId");
b.ToTable("blood_pressure_observation", (string)null);
});
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.OwnsOne("ObservationService.Domain.MeasurementContext", "MeasurementContext", b1 =>
{
b1.Property<Guid>("BloodPressureObservationObservationId")
.HasColumnType("uuid");
b1.Property<string>("ActivityCondition")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("Unknown")
.HasColumnName("activity_condition");
b1.Property<string>("AdditionalCircumstances")
.HasColumnType("text")
.HasColumnName("additional_circumstances");
b1.Property<string>("BodyPosition")
.HasColumnType("text")
.HasColumnName("body_position");
b1.Property<string>("CuffDetails")
.HasColumnType("text")
.HasColumnName("cuff_details");
b1.Property<string>("DeviceDetails")
.HasColumnType("text")
.HasColumnName("device_details");
b1.Property<string>("MeasuredArm")
.HasColumnType("text")
.HasColumnName("measured_arm");
b1.Property<decimal?>("RestDurationMinutes")
.HasColumnType("numeric")
.HasColumnName("rest_duration_minutes");
b1.Property<string>("Setting")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("Unknown")
.HasColumnName("setting");
b1.HasKey("BloodPressureObservationObservationId");
b1.ToTable("blood_pressure_observation");
b1.WithOwner()
.HasForeignKey("BloodPressureObservationObservationId");
});
b.Navigation("MeasurementContext")
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore;
using ObservationService.Domain;
namespace ObservationService.Persistence;
public sealed class ObservationDbContext(DbContextOptions<ObservationDbContext> options) : DbContext(options)
{
public DbSet<BloodPressureObservation> Observations => Set<BloodPressureObservation>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var observation = modelBuilder.Entity<BloodPressureObservation>();
observation.ToTable("blood_pressure_observation");
observation.HasKey(o => o.ObservationId);
observation.Property(o => o.ObservationId).HasColumnName("observation_id").ValueGeneratedNever();
// An external patient identifier, not a cross-database foreign key.
observation.Property(o => o.PatientId).HasColumnName("patient_id");
observation.Property(o => o.MeasuredAt).HasColumnName("measured_at").HasColumnType("timestamp without time zone");
observation.Property(o => o.Systolic).HasColumnName("systolic");
observation.Property(o => o.Diastolic).HasColumnName("diastolic");
observation.Property(o => o.Pulse).HasColumnName("pulse");
observation.Property(o => o.Context).HasColumnName("context").HasColumnType("character varying");
observation.Property(o => o.Note).HasColumnName("note").HasColumnType("character varying");
observation.OwnsOne(o => o.MeasurementContext, context =>
{
context.Property(c => c.Setting).HasColumnName("setting").HasDefaultValue("Unknown").IsRequired();
context.Property(c => c.ActivityCondition).HasColumnName("activity_condition").HasDefaultValue("Unknown").IsRequired();
context.Property(c => c.RestDurationMinutes).HasColumnName("rest_duration_minutes");
context.Property(c => c.BodyPosition).HasColumnName("body_position");
context.Property(c => c.MeasuredArm).HasColumnName("measured_arm");
context.Property(c => c.DeviceDetails).HasColumnName("device_details");
context.Property(c => c.CuffDetails).HasColumnName("cuff_details");
context.Property(c => c.AdditionalCircumstances).HasColumnName("additional_circumstances");
});
observation.Navigation(o => o.MeasurementContext).IsRequired();
observation.Property(o => o.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
observation.Property(o => o.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
}
}
@@ -0,0 +1,79 @@
using ObservationService.Contracts;
using Microsoft.EntityFrameworkCore;
using ObservationService.Application;
using ObservationService.Domain;
namespace ObservationService.Persistence;
public sealed class SqlObservationRepository(ObservationDbContext db) : ObservationRepository
{
public async Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken) =>
await db.Observations.Where(o => o.ObservationId == observationId)
.ExecuteDeleteAsync(cancellationToken) > 0;
public async Task<BloodPressureObservation?> UpdateAsync(Guid observationId, PatchObservationRequest request,
DateTime updatedAt, CancellationToken cancellationToken)
{
var observation = await db.Observations.SingleOrDefaultAsync(o => o.ObservationId == observationId,
cancellationToken);
if (observation is null)
return null;
if (request.SystolicSpecified) observation.Systolic = request.Systolic!.Value;
if (request.DiastolicSpecified) observation.Diastolic = request.Diastolic!.Value;
if (request.PulseSpecified) observation.Pulse = request.Pulse!.Value;
if (request.ContextSpecified) observation.Context = request.Context;
if (request.NoteSpecified) observation.Note = request.Note;
if (request.MeasurementContextSpecified)
{
if (request.MeasurementContext is null) observation.MeasurementContext = new();
else
{
var patch = request.MeasurementContext;
var current = observation.MeasurementContext;
observation.MeasurementContext = current with
{
Setting = patch.SettingSpecified ? patch.Setting ?? "Unknown" : current.Setting,
ActivityCondition = patch.ActivityConditionSpecified ? patch.ActivityCondition ?? "Unknown" : current.ActivityCondition,
RestDurationMinutes = patch.RestDurationMinutesSpecified ? patch.RestDurationMinutes : current.RestDurationMinutes,
BodyPosition = patch.BodyPositionSpecified ? patch.BodyPosition : current.BodyPosition,
MeasuredArm = patch.MeasuredArmSpecified ? patch.MeasuredArm : current.MeasuredArm,
DeviceDetails = patch.DeviceDetailsSpecified ? patch.DeviceDetails : current.DeviceDetails,
CuffDetails = patch.CuffDetailsSpecified ? patch.CuffDetails : current.CuffDetails,
AdditionalCircumstances = patch.AdditionalCircumstancesSpecified ? patch.AdditionalCircumstances : current.AdditionalCircumstances
};
}
}
observation.UpdatedAt = updatedAt;
await db.SaveChangesAsync(cancellationToken);
return observation;
}
public async Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken)
{
db.Observations.Add(observation);
await db.SaveChangesAsync(cancellationToken);
return observation;
}
public Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken) =>
db.Observations.AsNoTracking().SingleOrDefaultAsync(o => o.ObservationId == observationId, cancellationToken);
public Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken) =>
db.Observations.AsNoTracking().Where(o => o.PatientId == patientId)
.OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.CreatedAt)
.ThenByDescending(o => o.ObservationId)
.FirstOrDefaultAsync(cancellationToken);
public Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken)
{
var query = db.Observations.AsNoTracking()
.Where(o => o.PatientId == patientId && o.MeasuredAt >= from && o.MeasuredAt <= to);
if (selection.Setting is not null)
query = query.Where(o => o.MeasurementContext.Setting == selection.Setting);
if (selection.ActivityCondition is not null)
query = query.Where(o => o.MeasurementContext.ActivityCondition == selection.ActivityCondition);
return query.OrderBy(o => o.MeasuredAt).ThenBy(o => o.ObservationId).ToListAsync(cancellationToken);
}
}
@@ -0,0 +1,74 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore;
using ObservationService.Application;
using ObservationService.Persistence;
namespace ObservationService;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-observation");
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddDbContext<ObservationDbContext>((services, options) =>
options.UseNpgsql(services.GetRequiredService<IConfiguration>().GetConnectionString("ObservationDatabase")));
builder.Services.AddScoped<ObservationRepository, SqlObservationRepository>();
builder.Services.AddScoped<ObservationApplicationService>();
builder.Services.AddHttpClient("ApiGateway", (services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetGatewayUri(configuration);
var serviceKey = configuration["Services:ApiGateway:Key"];
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
var app = builder.Build();
if (string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("ObservationDatabase")))
throw new InvalidOperationException("ConnectionStrings:ObservationDatabase must be configured.");
if (args.Contains("--migrate"))
{
await using var scope = app.Services.CreateAsyncScope();
await scope.ServiceProvider.GetRequiredService<ObservationDbContext>().Database.MigrateAsync();
return;
}
if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https")
throw new InvalidOperationException("Production gateway endpoints must use HTTPS.");
_ = GetGatewayUri(app.Configuration);
var outgoingKey = app.Configuration["Services:ApiGateway:Key"];
if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32)
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
app.UseExceptionHandler();
app.Use(async (context, next) =>
{
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
{ context.Response.StatusCode = 401; return; }
await next(context);
});
app.MapControllers();
await app.RunAsync();
}
private static Uri GetGatewayUri(IConfiguration configuration)
{
var endpoint = configuration["Services:ApiGateway:BaseUrl"];
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
(uri.Scheme != "http" && uri.Scheme != "https") || uri.AbsolutePath != "/" ||
!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) || !string.IsNullOrEmpty(uri.UserInfo))
throw new InvalidOperationException("Services:ApiGateway:BaseUrl must be an HTTP(S) origin URL.");
return uri;
}
}
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
}
}
@@ -0,0 +1,45 @@
using PatientProfileService.Contracts;
using PatientProfileService.Domain;
namespace PatientProfileService.Application;
public sealed class PatientApplicationService(PatientRepository repository)
{
public async Task<Patient> CreatePatientAsync(CreatePatientRequest request, string accountId, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
ArgumentException.ThrowIfNullOrWhiteSpace(accountId);
if (await repository.FindByAccountIdAsync(accountId, cancellationToken) is not null)
throw new ProfileAlreadyExistsException();
if (request.DateOfBirth is null)
throw new ArgumentException("A date of birth is required.", nameof(request));
// The documented TIMESTAMP columns store UTC without a time-zone component.
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
return await repository.SaveAsync(new Patient
{
PatientId = Guid.NewGuid(),
AccountId = accountId,
Name = request.Name,
DateOfBirth = request.DateOfBirth.Value,
ContactInfo = request.ContactInfo,
CreatedAt = now,
UpdatedAt = now
}, cancellationToken);
}
public Task<Patient?> GetByAccountAsync(string accountId, CancellationToken cancellationToken) =>
repository.FindByAccountIdAsync(accountId, cancellationToken);
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
repository.FindByIdAsync(patientId, cancellationToken);
public async Task<Patient?> UpdatePatientAsync(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
if (!await repository.UpdateProfileAsync(patientId, request.Name, request.ContactInfo, cancellationToken))
return null;
return await repository.FindByIdAsync(patientId, cancellationToken);
}
}
@@ -0,0 +1,11 @@
using PatientProfileService.Domain;
namespace PatientProfileService.Application;
public interface PatientRepository
{
Task<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken);
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken);
}
@@ -0,0 +1,5 @@
namespace PatientProfileService.Application;
public sealed class ProfileAlreadyExistsException : Exception
{
}
@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
namespace PatientProfileService.Contracts;
public sealed record CreatePatientRequest
{
[Required]
public string? Name { get; init; }
[Required]
public DateOnly? DateOfBirth { get; init; }
public string? ContactInfo { get; init; }
}
@@ -0,0 +1,3 @@
namespace PatientProfileService.Contracts;
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;
namespace PatientProfileService.Contracts;
public sealed record UpdatePatientRequest
{
[Required]
public string? Name { get; init; }
public string? ContactInfo { get; init; }
}
@@ -0,0 +1,51 @@
using Microsoft.AspNetCore.Mvc;
using PatientProfileService.Application;
using PatientProfileService.Contracts;
using PatientProfileService.Domain;
namespace PatientProfileService.Controllers;
[ApiController]
[Route("api/patients")]
public sealed class PatientController(PatientApplicationService service) : ControllerBase
{
[HttpPost]
public async Task<ActionResult<PatientDto>> CreatePatient(CreatePatientRequest request, CancellationToken cancellationToken)
{
var accountId = Request.Headers["X-Account-Id"].ToString();
if (string.IsNullOrWhiteSpace(accountId)) return BadRequest();
try
{
var patient = await service.CreatePatientAsync(request, accountId, cancellationToken);
return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient));
}
catch (ProfileAlreadyExistsException)
{
return Conflict(new { title = "A profile already exists for this account." });
}
}
[HttpGet("by-account/{accountId}")]
public async Task<ActionResult<PatientDto>> GetByAccount(string accountId, CancellationToken cancellationToken)
{
var patient = await service.GetByAccountAsync(accountId, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
[HttpGet("{patientId:guid}")]
public async Task<ActionResult<PatientDto>> GetPatient(Guid patientId, CancellationToken cancellationToken)
{
var patient = await service.GetPatientAsync(patientId, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
[HttpPut("{patientId:guid}")]
public async Task<ActionResult<PatientDto>> UpdatePatient(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken)
{
var patient = await service.UpdatePatientAsync(patientId, request, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
private static PatientDto ToDto(Patient patient) =>
new(patient.PatientId, patient.Name, patient.DateOfBirth, patient.ContactInfo);
}
@@ -0,0 +1,12 @@
namespace PatientProfileService.Domain;
public sealed class Patient
{
public string? AccountId { get; set; }
public Guid PatientId { get; set; }
public string Name { get; set; } = "";
public DateOnly DateOfBirth { get; set; }
public string? ContactInfo { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more