diff --git a/HealthApp.slnx b/HealthApp.slnx index b99c2cf..d133651 100644 --- a/HealthApp.slnx +++ b/HealthApp.slnx @@ -7,6 +7,7 @@ + diff --git a/deploy/INSTALLATION.md b/deploy/INSTALLATION.md new file mode 100644 index 0000000..c30188c --- /dev/null +++ b/deploy/INSTALLATION.md @@ -0,0 +1,198 @@ +# US-16 — Independent Linux installation + +The installer supports one service, a comma-separated subset, or `all`. The same +published application executables work for colocated and distributed deployments. +Each service retains its own process, environment file and systemd registration. +No additional service, shared persistence, shared application library or communication +shortcut is introduced. Application services continue communicating through the API Gateway. + +## Supported host and prerequisites + +Use a Linux host with Bash 4 or later, GNU core utilities/grep/sed, a running systemd +system manager with systemd-run, and the .NET 10 ASP.NET Core runtime. Live installation +requires root and the standard `getent`, `groupadd`, `useradd` and `id` tools. Network +verification additionally requires curl. Building a release requires the .NET 10 SDK +and the repository's NuGet dependencies; deployment hosts do not need the SDK/source. + +Provision PostgreSQL for Patient/Profile and Observation separately, with independent +database names/users and credentials matching each service's configuration. The DBs +may be on remote hosts. Insights and Health Overview have no databases. Provision +trusted HTTPS certificates and the externally configured accounts/service credentials +before starting production services. The installer does not install an identity +provider, PostgreSQL, runtime packages or certificates and does not generate accounts. +These remain administrator-supplied prerequisites, as in the existing deployment model. + +## Build a release + +From the repository root: + +```bash +bash deploy/build-release.sh --output /tmp/healthapp-release +# Or publish only the service(s) needed on a particular host: +bash deploy/build-release.sh --output /tmp/healthapp-insights-release --services insights +``` + +Output must be a new directory. Optionally set `HEALTHAPP_DOTNET` to the SDK executable. +The release contains selected payloads under `services/`, their systemd units, +configuration examples, installation/verification scripts and this guide. Transfer it +to the target Linux host using your normal deployment transport. Release contents +are trusted executable deployment input; configuration secrets are not part of it. + +## Prepare independent configuration + +Copy each selected `examples/NAME.env.example` to a protected administrator directory +as `NAME.env`. Replace placeholders with actual values. Existing examples deliberately +use remote hostnames and separate DB credentials; they are not usable credentials. + +Service names and resulting paths: + +| Selection name | Application | Configuration | systemd unit | +| --- | --- | --- | --- | +| api-gateway | ApiGateway.dll | /etc/healthapp/api-gateway.env | healthapp-api-gateway.service | +| patient-profile | PatientProfileService.dll | /etc/healthapp/patient-profile.env | healthapp-patient-profile.service | +| observation | ObservationService.dll | /etc/healthapp/observation.env | healthapp-observation.service | +| insights | InsightsService.dll | /etc/healthapp/insights.env | healthapp-insights.service | +| health-overview | HealthOverviewService.dll | /etc/healthapp/health-overview.env | healthapp-health-overview.service | + +Supply each service's own network binding via `ASPNETCORE_URLS`, its needed endpoints, +credentials and (where applicable) DB connection string. The gateway needs all service +origins/keys even when their services are deployed on other machines. Other services +need only their documented dependencies; installation does not require them locally. + +Use distinct service credentials in both directions, matching the gateway and service +settings described in `src/AUTHENTICATION.md`. Never reuse example placeholders. +Keep production `ASPNETCORE_ENVIRONMENT=Production` and configure HTTPS origins, +certificate path/password and trust chains on each host. Certificate files must be +readable by the `healthapp` service identity. For example, externally provision files +under `/etc/healthapp` with group `healthapp` and mode `0640`. The installer makes that +directory root-owned with group access, and environment files root-only `0600`; +systemd reads environment files and passes values into the relevant process. + +`Authentication__KeyDirectory` belongs to the gateway host alone. The gateway unit's +StateDirectory creates `/var/lib/healthapp-api-gateway`; its `keys` child is created +by data protection. Other machines never require that directory or another service's +local application/configuration files. Only configured network APIs cross machines. + +For local development tests, Development permits HTTP; production still requires +HTTPS. No deployment path/hostname is hard-coded in an application. + +## Install selected services + +From the transferred release directory, assuming prepared config in `/root/healthapp-config`: + +```bash +# One service, with dependencies running on independently configured hosts: +sudo bash install.sh --services insights --config-dir /root/healthapp-config + +# A subset (use this instead of the preceding command on a fresh host): +sudo bash install.sh --services patient-profile,observation --config-dir /root/healthapp-config --migrate + +# Complete fresh installation: +sudo bash install.sh --services all --config-dir /root/healthapp-config --migrate --start +``` + +`--bundle DIRECTORY` selects a release explicitly. `--dotnet /absolute/runtime/path` +changes only ExecStart in selected units, when dotnet is not installed at `/usr/bin/dotnet`. +The installer checks the .NET 10 ASP.NET Core runtime on a live host. + +Installation creates the conventional `healthapp` service user/group if absent, +copies selected independent applications to `/opt/healthapp/NAME`, copies selected +configurations to `/etc/healthapp/NAME.env`, registers selected units under +`/etc/systemd/system`, reloads systemd and enables only those units for boot. +It preflights the full selection before writing files. Unselected service files, +configuration and registrations are untouched; no service dependency/PartOf/BindsTo +relationships are introduced between HealthApp units. + +Default installation does not start services or modify schemas. `--migrate` explicitly +runs the selected Patient/Profile and/or Observation application's existing migration +mode, under its service identity/configuration, using a transient systemd unit. It +never migrates Insights/Overview or another service's DB. `--start` explicitly starts +the selected units after successful installation/migrations. For migrations run +separately, use the existing published `--migrate` commands with that service's +configuration, then start its unit. + +Existing installation directories, env files or units cause refusal before writes. +This is a first-install mechanism, not an upgrade/uninstall tool. It never overwrites +existing configuration, removes persistent data or guesses how to rotate credentials. +A live copy/migration/systemd error can leave installed files or earlier selected units +configured; the command fails and those files/data are retained for administrator +inspection. There is no cross-service deployment transaction or automatic rollback. + +`--root /absolute/staging/directory` stages an offline filesystem tree without root, +user creation, runtime checks or systemctl calls. It is for testing/image preparation, +not a completed live installation. It refuses `--start`/`--migrate`. Provision the +runtime, healthapp user/group, config-directory group/certificate access and gateway +state-directory ownership on the target, then reload/enable/start the selected units. +The paths *inside* each unit refer to the target's `/opt` and `/etc`, not to the +staging directory. Never mistake successful staging for successful startup. + +## Manage and verify installation + +Each unit can be independently managed using, for example: + +```bash +sudo systemctl start healthapp-insights.service +sudo systemctl stop healthapp-insights.service +sudo systemctl restart healthapp-insights.service +sudo journalctl -u healthapp-insights.service +``` + +Stopping a dependency may cause application requests needing it to fail; it does not +stop peer processes. Services need no local process-start ordering or shared memory. + +Prepare a protected probe directory with `NAME.curl` files for each selected service. +These are curl data configuration files (not shell scripts), containing the actual +HTTPS URL, trusted CA and credentials appropriate for a *read-only* HTTP 200 request. +For example, Insights can use a configured patient/period that has observation data: + +```text +url = "https://insights.example.test:5083/api/patients/PATIENT_ID/insights?from=2026-09-01&to=2026-09-10" +header = "X-Gateway-Key: ACTUAL_INSIGHTS_GATEWAY_CREDENTIAL" +cacert = "/etc/healthapp/trusted-ca.pem" +``` + +Use corresponding profile GET, latest-observation GET and Overview GET probes on +those services. For API Gateway use a bearer-authenticated Overview GET. For a +complete installation that probe must select a prepared patient/period with profile, +latest reading and calculated insight, thereby exercising the documented gateway +and all four application services. Ensure representative records exist through the +normal APIs before verification. Public guidance alone cannot verify dependencies. +Keep probes root-only; their credentials do not belong in the release or repository. +Do not disable certificate verification. Select test/deployment data appropriate to +the environment rather than letting installation create patient information. + +```bash +sudo bash verify.sh --services all --probe-dir /root/healthapp-probes +# Explicitly permits independently stopping/starting/restarting every selected unit: +sudo bash verify.sh --services all --probe-dir /root/healthapp-probes --cycle +``` + +Verification checks active units, distinct real PIDs and each configured network +probe's HTTP 200 response. `--cycle` checks peer units stay active during each stop, +then starts/restarts that service and probes it again. HTTP response bodies and +credentials are suppressed. Probes fail on connection errors, unexpected status or +an exited process. Verification fails rather than treating unavailable sources as +missing data. Use the same mechanism on every host for a distributed deployment; +the complete-system gateway probe checks the configured remote communication paths. + +## Automated evidence and limits + +`tests/Deployment.AcceptanceTests` publishes a release, installs into temporary roots, +and launches the installed assemblies as separate OS processes against temporary, +independent PostgreSQL databases. It covers selection, preflight failures, independent +config files/permissions/units, standalone startup for every service, multiple/all +processes, authenticated profile/observation/Overview workflow, per-service graceful +stop/restart, retained data and separate persistence. There are no production service +project references in this test project and no test authentication replacement. + +Run with Linux, Bash, .NET 10 SDK, and `TEST_POSTGRES_CONNECTION` referencing a DB +account allowed to create isolated test databases. `HEALTHAPP_DOTNET` may select the +SDK/runtime executable. Ordinary acceptance tests remain available in the solution. + +This development execution environment has no running systemd manager. Automated +process tests therefore use direct process launch and SIGINT (the same configured +stop signal); live systemctl registration/boot cycling and production certificates +must be verified with the supplied verifier on a supported target Linux host. The +suite does not claim that localhost testing alone proves a deployment on separate +physical machines. Remote origins and independent configuration are preserved by +installation, and the target-host gateway probe is the distributed-system check. diff --git a/deploy/build-release.sh b/deploy/build-release.sh new file mode 100644 index 0000000..c9a469d --- /dev/null +++ b/deploy/build-release.sh @@ -0,0 +1,32 @@ +#!/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/INSTALLATION.md" "$output/" +for service in "${selected_services[@]}"; do + assembly=$(assembly_for "$service") + "$dotnet_command" publish "$repo_dir/src/$assembly/$assembly.csproj" --configuration Release --output "$output/services/$service" + cp -- "$script_dir/systemd/healthapp-$service.service" "$output/systemd/" + cp -- "$script_dir/$service.env.example" "$output/examples/" +done +printf '%s\n' "${selected_services[@]}" > "$output/services.list" +printf 'Release created: %s\n' "$output" diff --git a/deploy/installer/install.sh b/deploy/installer/install.sh new file mode 100644 index 0000000..0e1e94c --- /dev/null +++ b/deploy/installer/install.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 +fail() { printf 'Error: %s\n' "$*" >&2; exit 1; } +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +source "$script_dir/services.sh" +bundle=$script_dir +requested= +config_dir= +target_root=/ +dotnet_path=/usr/bin/dotnet +start=false +migrate=false +while [[ $# -gt 0 ]]; do + case "$1" in + --bundle) [[ $# -gt 1 ]] || fail 'Missing bundle directory.'; bundle=$2; shift 2;; + --services) [[ $# -gt 1 ]] || fail 'Missing services.'; requested=$2; shift 2;; + --config-dir) [[ $# -gt 1 ]] || fail 'Missing configuration directory.'; config_dir=$2; shift 2;; + --root) [[ $# -gt 1 ]] || fail 'Missing staging root.'; target_root=$2; shift 2;; + --dotnet) [[ $# -gt 1 ]] || fail 'Missing runtime path.'; dotnet_path=$2; shift 2;; + --start) start=true; shift;; + --migrate) migrate=true; shift;; + --help) printf '%s\n' 'Usage: bash install.sh --services all|NAME[,NAME] --config-dir DIRECTORY [--bundle DIRECTORY] [--dotnet /absolute/path] [--migrate] [--start]' 'Optional --root DIRECTORY stages an offline filesystem image; it does not start or verify services.' 'Names: api-gateway,patient-profile,observation,insights,health-overview' 'Existing installations/configuration are never overwritten. Databases and certificates must be provisioned externally.'; exit 0;; + *) fail "Unknown argument: $1";; + esac +done +[[ $(uname -s) == Linux ]] || fail 'Only Linux is supported.' +select_services "$requested" +[[ -d "$bundle" && -d "$config_dir" ]] || fail 'Bundle and prepared configuration directories are required.' +[[ "$target_root" == /* && "$target_root" != *$'\n'* && "$target_root" != *'/../'* && "$target_root" != */.. ]] || fail 'Root must be an absolute filesystem path without parent traversal.' +[[ "$dotnet_path" =~ ^/[A-Za-z0-9_./+-]+$ ]] || fail 'Runtime must be an absolute path using letters, digits, slash, dot, underscore, plus or hyphen.' +target_root=$(realpath -m -- "$target_root") +if [[ "$target_root" != / ]]; then + [[ "$start" == false && "$migrate" == false ]] || fail 'Cannot start services or migrate databases in an offline staging root.' +else + [[ $EUID -eq 0 ]] || fail 'Live system installation requires root.' + [[ -d /run/systemd/system ]] || fail 'A running systemd system manager is required.' + [[ -x "$dotnet_path" ]] || fail 'Install the .NET 10 ASP.NET Core runtime first.' + runtime_list=$("$dotnet_path" --list-runtimes) + [[ "$runtime_list" == *'Microsoft.AspNetCore.App 10.'* ]] || fail 'The .NET 10 ASP.NET Core runtime is required.' +fi +# Preflight all selected services before copying anything or registering units. +for service in "${selected_services[@]}"; do + assembly=$(assembly_for "$service") + [[ -f "$bundle/services/$service/$assembly.dll" && -f "$bundle/services/$service/$assembly.runtimeconfig.json" && -f "$bundle/services/$service/$assembly.deps.json" ]] || fail "Missing published application: $service" + [[ -f "$bundle/systemd/healthapp-$service.service" && -f "$config_dir/$service.env" ]] || fail "Missing unit or prepared configuration: $service" + [[ ! -e "$target_root/opt/healthapp/$service" && ! -e "$target_root/etc/healthapp/$service.env" && ! -e "$target_root/etc/systemd/system/healthapp-$service.service" ]] || fail "Already installed or configured: $service. Existing files were not changed." + if grep -q 'REPLACE_ME\|REPLACE_WITH' "$config_dir/$service.env"; then fail "Replace example configuration placeholders for $service."; fi +done +if [[ "$target_root" == / ]]; then + getent group healthapp >/dev/null || groupadd --system healthapp + id healthapp >/dev/null 2>&1 || useradd --system --gid healthapp --home-dir /nonexistent --shell /usr/sbin/nologin healthapp +fi +install -d -m 0755 -- "$target_root/opt/healthapp" "$target_root/etc/systemd/system" +install -d -m 0750 -- "$target_root/etc/healthapp" +if [[ "$target_root" == / ]]; then chgrp healthapp -- "$target_root/etc/healthapp"; fi +for service in "${selected_services[@]}"; do + 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" + install -m 0600 -- "$config_dir/$service.env" "$target_root/etc/healthapp/$service.env" + sed "s|ExecStart=/usr/bin/dotnet |ExecStart=$dotnet_path |" "$bundle/systemd/healthapp-$service.service" > "$target_root/etc/systemd/system/healthapp-$service.service" + chmod 0644 -- "$target_root/etc/systemd/system/healthapp-$service.service" + printf 'Installed %s\n' "$service" +done +if [[ "$target_root" == / ]]; then + systemctl daemon-reload + if [[ "$migrate" == true ]]; then + for service in "${selected_services[@]}"; do + case "$service" in patient-profile|observation) + assembly=$(assembly_for "$service") + systemd-run --quiet --wait --pipe --collect --unit="healthapp-$service-migrate" \ + --property=User=healthapp --property=Group=healthapp \ + --property="EnvironmentFile=/etc/healthapp/$service.env" \ + --property="WorkingDirectory=/opt/healthapp/$service" \ + "$dotnet_path" "/opt/healthapp/$service/$assembly.dll" --migrate + ;; + esac + done + fi + for service in "${selected_services[@]}"; do + systemctl enable "healthapp-$service.service" + if [[ "$start" == true ]]; then systemctl start "healthapp-$service.service"; fi + done + printf '%s\n' 'Installation complete. Run verify.sh with the selected services and HTTP probe configuration.' +else + printf '%s\n' 'Offline files staged. Provision the runtime/service account and enable units on the target host before verification.' +fi diff --git a/deploy/installer/services.sh b/deploy/installer/services.sh new file mode 100644 index 0000000..8ac9a65 --- /dev/null +++ b/deploy/installer/services.sh @@ -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 -A seen=() + for item in "${selected_services[@]}"; do + case "$item" in api-gateway|patient-profile|observation|insights|health-overview) ;; *) fail "Unknown service: $item" ;; esac + [[ ! ${seen[$item]+exists} ]] || fail "Repeated service: $item" + seen[$item]=1 + 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 +} diff --git a/deploy/installer/verify.sh b/deploy/installer/verify.sh new file mode 100644 index 0000000..399faf5 --- /dev/null +++ b/deploy/installer/verify.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -euo pipefail +fail() { printf 'Error: %s\n' "$*" >&2; exit 1; } +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +source "$script_dir/services.sh" +requested= +probe_dir= +cycle=false +while [[ $# -gt 0 ]]; do + case "$1" in + --services) [[ $# -gt 1 ]] || fail 'Missing services.'; requested=$2; shift 2;; + --probe-dir) [[ $# -gt 1 ]] || fail 'Missing probe directory.'; probe_dir=$2; shift 2;; + --cycle) cycle=true; shift;; + --help) printf '%s\n' 'Usage: bash verify.sh --services all|NAME[,NAME] --probe-dir DIRECTORY [--cycle]' 'Each NAME.curl contains curl configuration for a configured HTTPS endpoint and the required credentials.' 'Probes must return HTTP 200 (no redirects). --cycle explicitly permits stop/start/restart of each selected service.'; exit 0;; + *) fail "Unknown argument: $1";; + esac +done +select_services "$requested" +[[ -d "$probe_dir" ]] || fail 'Provide service-specific curl probe configuration.' +command -v curl >/dev/null || fail 'curl is required for network verification.' +[[ -d /run/systemd/system ]] || fail 'Verification requires a running systemd system manager.' +for service in "${selected_services[@]}"; do + [[ -f "$probe_dir/$service.curl" ]] || fail "Missing probe configuration: $service" +done +pids=() +for service in "${selected_services[@]}"; do + unit="healthapp-$service.service" + systemctl is-active --quiet "$unit" || fail "$service is not active." + pid=$(systemctl show --property MainPID --value "$unit") + [[ "$pid" =~ ^[1-9][0-9]*$ && -d "/proc/$pid" ]] || fail "$service has no running process." + for other in "${pids[@]}"; do [[ "$pid" != "$other" ]] || fail 'Services share a process.'; done + pids+=("$pid") + if [[ "$cycle" == true ]]; then + # Confirm stopping this service does not directly stop another selected unit. + systemctl stop "$unit" + systemctl is-active --quiet "$unit" && fail "$service did not stop." + for peer in "${selected_services[@]}"; do + [[ "$peer" == "$service" ]] || systemctl is-active --quiet "healthapp-$peer.service" || fail "Stopping $service stopped $peer." + done + systemctl start "$unit" + systemctl restart "$unit" + systemctl is-active --quiet "$unit" || fail "$service did not restart." + fi + # curl settings are data, not sourced shell code; suppress bodies and credentials. + status=$(curl --config "$probe_dir/$service.curl" --silent --output /dev/null --write-out '%{http_code}' --max-time 15 --max-redirs 0 --retry 5 --retry-delay 1 --retry-connrefused) || fail "Network probe failed for $service." + [[ "$status" == 200 ]] || fail "Unexpected HTTP status for $service: $status" + systemctl is-active --quiet "$unit" || fail "$service exited during its network probe." + printf 'Verified process and configured network probe: %s\n' "$service" +done +printf '%s\n' 'Verification passed. For a complete system also run the representative API workflow documented in INSTALLATION.md.' diff --git a/src/README.md b/src/README.md index d28ae82..ca3d9b9 100644 --- a/src/README.md +++ b/src/README.md @@ -295,6 +295,22 @@ US-04 tests use real HTTP between the hosts and separate temporary patient and o Dependencies: Npgsql's EF Core PostgreSQL provider supplies persistence; EF Core Relational is pinned to the same patch as EF Core Design to keep runtime/tooling versions aligned; EF Core Design supports migration maintenance. xUnit, its Visual Studio runner, Microsoft.NET.Test.Sdk, and ASP.NET Core MVC Testing are used only for automated tests. The gateway uses the platform's HttpClient and has no extra package dependency. +## Linux installer (US-16) + +Use `bash deploy/build-release.sh --output NEW_DIRECTORY` to create an independent +release bundle, then its `install.sh --services all|NAME[,NAME] --config-dir DIRECTORY` +on a Linux/systemd host. Single, subset and complete installs retain separate +applications, configurations and units. Optional `--migrate` and `--start` explicitly +apply selected service migrations/startup. Existing installations are never overwritten. +See [INSTALLATION.md](../deploy/INSTALLATION.md) for prerequisites, service selections, +external configuration, offline staging, verification and independent management. + +US-16 adds xUnit deployment tests that launch installed executables as separate OS +processes and exercise the authenticated complete-system workflow and independent +stop/restart. Live systemd/HTTPS verification uses the supplied target-host verifier. +The earlier test-alignment suggestions remain deferred except where US-16 itself +requires independent-process installation verification. + ## Linux deployment Publish each service separately: diff --git a/tests/Deployment.AcceptanceTests/Deployment.AcceptanceTests.csproj b/tests/Deployment.AcceptanceTests/Deployment.AcceptanceTests.csproj new file mode 100644 index 0000000..460fac6 --- /dev/null +++ b/tests/Deployment.AcceptanceTests/Deployment.AcceptanceTests.csproj @@ -0,0 +1,16 @@ + + + net10.0 + enable + enable + false + true + + + + + + + + + diff --git a/tests/Deployment.AcceptanceTests/DeploymentFixture.cs b/tests/Deployment.AcceptanceTests/DeploymentFixture.cs new file mode 100644 index 0000000..4f59972 --- /dev/null +++ b/tests/Deployment.AcceptanceTests/DeploymentFixture.cs @@ -0,0 +1,180 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using Microsoft.AspNetCore.Identity; +using Npgsql; +using Xunit; + +namespace Deployment.AcceptanceTests; + +public sealed class DeploymentFixture : IAsyncLifetime +{ + public static readonly string[] Services = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"]; + public static string Assembly(string service) => service switch + { + "api-gateway" => "ApiGateway", "patient-profile" => "PatientProfileService", + "observation" => "ObservationService", "insights" => "InsightsService", _ => "HealthOverviewService" + }; + public static string Repository + { + get + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "HealthApp.slnx"))) directory = directory.Parent; + return directory?.FullName ?? throw new InvalidOperationException("Repository root not found."); + } + } + public string Dotnet { get; } = Environment.GetEnvironmentVariable("HEALTHAPP_DOTNET") ?? + Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet"; + public string Temporary { get; } = Path.Combine(Path.GetTempPath(), "healthapp-us16-" + Guid.NewGuid().ToString("N")); + public string Bundle => Path.Combine(Temporary, "release"); + public string Configuration => Path.Combine(Temporary, "configuration"); + public string Root => Path.Combine(Temporary, "installed"); + public Dictionary Urls { get; } = new(); + public Dictionary> Settings { get; } = new(); + public Dictionary Processes { get; } = new(); + private readonly List databases = []; + public string Admin { get; private set; } = ""; + public const string Password = "synthetic-deployment-password"; + + public async Task InitializeAsync() + { + Directory.CreateDirectory(Temporary); + Directory.CreateDirectory(Configuration); + Admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION") ?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION is required."); + var release = await Run("bash", [Path.Combine(Repository, "deploy/build-release.sh"), "--output", Bundle], + new() { ["HEALTHAPP_DOTNET"] = Dotnet }); + Assert.True(release.Code == 0, "Release publishing failed; no secret configuration was used."); + foreach (var service in Services) + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + Urls[service] = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/"; + Settings[service] = new() + { + ["ASPNETCORE_ENVIRONMENT"] = "Development", ["ASPNETCORE_URLS"] = Urls[service], + ["InternalAccess__GatewayKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), + ["Logging__LogLevel__Default"] = "Warning", ["Logging__LogLevel__Microsoft.AspNetCore"] = "Warning" + }; + } + foreach (var service in new[] { "patient-profile", "observation" }) + { + var database = "us16_" + Guid.NewGuid().ToString("N"); + await using var connection = new NpgsqlConnection(Admin); + await connection.OpenAsync(); + await using var create = new NpgsqlCommand("CREATE DATABASE " + database, connection); + await create.ExecuteNonQueryAsync(); + databases.Add(database); + Settings[service][service == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase"] = + new NpgsqlConnectionStringBuilder(Admin) { Database = database }.ConnectionString; + } + var names = new Dictionary { ["patient-profile"] = "PatientProfile", ["observation"] = "Observation", + ["insights"] = "Insights", ["health-overview"] = "HealthOverview" }; + foreach (var (service, name) in names) + { + Settings["api-gateway"][$"Services__{name}__BaseUrl"] = Urls[service]; + Settings["api-gateway"][$"Services__{name}__Key"] = Settings[service]["InternalAccess__GatewayKey"]; + if (service == "patient-profile") continue; + var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + Settings["api-gateway"][$"InternalAccess__{name}__Key"] = key; + Settings[service]["Services__ApiGateway__Key"] = key; + Settings[service]["Services__ApiGateway__BaseUrl"] = Urls["api-gateway"]; + } + var gateway = Settings["api-gateway"]; + gateway["Authentication__KeyDirectory"] = Path.Combine(Temporary, "keys"); + gateway["Authentication__Accounts__0__AccountId"] = "deployment-patient"; + gateway["Authentication__Accounts__0__Role"] = "Patient"; + gateway["Authentication__Accounts__0__PasswordHash"] = new PasswordHasher().HashPassword("deployment-patient", Password); + foreach (var service in Services) + await File.WriteAllLinesAsync(Path.Combine(Configuration, service + ".env"), Settings[service] + .Select(p => $"{p.Key}=\"{p.Value.Replace("\\", "\\\\").Replace("\"", "\\\"")}\"")); + var installation = await Install(Root, "all"); + Assert.Equal(0, installation.Code); + foreach (var service in new[] { "patient-profile", "observation" }) + { + var migrated = await Run(Dotnet, [InstalledAssembly(service), "--migrate"], Settings[service]); + Assert.True(migrated.Code == 0, "Deployment database migration failed."); + } + } + + public string InstalledAssembly(string service) => Path.Combine(Root, "opt/healthapp", service, Assembly(service) + ".dll"); + public Task<(int Code, string Output)> Install(string root, string services) => Run("bash", + [Path.Combine(Bundle, "install.sh"), "--services", services, "--config-dir", Configuration, "--root", root]); + + public async Task Start(string service, string? root = null) + { + var start = new ProcessStartInfo(Dotnet) { WorkingDirectory = Path.Combine(root ?? Root, "opt/healthapp", service), + RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; + start.ArgumentList.Add(Path.Combine(root ?? Root, "opt/healthapp", service, Assembly(service) + ".dll")); + foreach (var (key, value) in Settings[service]) start.Environment[key] = value; + var process = Process.Start(start)!; + // Do not emit application logs containing potentially sensitive deployment information. + process.OutputDataReceived += (_, _) => { }; + process.ErrorDataReceived += (_, _) => { }; + process.BeginOutputReadLine(); process.BeginErrorReadLine(); + Processes[service] = process; + using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(1) }; + for (var attempt = 0; attempt < 100; attempt++) + { + Assert.False(process.HasExited, $"{service} exited during startup."); + try { using var response = await client.GetAsync(Urls[service]); return; } + catch (HttpRequestException) { } + catch (TaskCanceledException) { } + await Task.Delay(100); + } + throw new TimeoutException($"{service} did not accept configured network traffic."); + } + + public async Task Stop(string service) + { + if (!Processes.Remove(service, out var process)) return; + try + { + if (!process.HasExited) + { + // SIGINT is also the committed systemd unit's graceful stop signal. + var sent = await Run("kill", ["-INT", process.Id.ToString()]); + Assert.Equal(0, sent.Code); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + try { await process.WaitForExitAsync(deadline.Token); } + catch (OperationCanceledException) { process.Kill(true); await process.WaitForExitAsync(); throw; } + Assert.Equal(0, process.ExitCode); + } + } + finally { process.Dispose(); } + } + + public static async Task<(int Code, string Output)> Run(string executable, string[] arguments, + Dictionary? environment = null, string? workingDirectory = null) + { + var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + if (workingDirectory is not null) start.WorkingDirectory = workingDirectory; + foreach (var argument in arguments) start.ArgumentList.Add(argument); + if (environment is not null) foreach (var (key, value) in environment) start.Environment[key] = value; + using var process = Process.Start(start)!; + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + try { await process.WaitForExitAsync(deadline.Token); } + catch (OperationCanceledException) { process.Kill(true); await process.WaitForExitAsync(); throw; } + return (process.ExitCode, await stdout + await stderr); + } + + public async Task DisposeAsync() + { + foreach (var service in Processes.Keys.ToArray()) await Stop(service); + NpgsqlConnection.ClearAllPools(); + if (!string.IsNullOrEmpty(Admin)) + { + await using var connection = new NpgsqlConnection(Admin); + await connection.OpenAsync(); + foreach (var database in databases) + { + await using var drop = new NpgsqlCommand("DROP DATABASE IF EXISTS " + database + " WITH (FORCE)", connection); + await drop.ExecuteNonQueryAsync(); + } + } + if (Directory.Exists(Temporary)) Directory.Delete(Temporary, true); + } +} diff --git a/tests/Deployment.AcceptanceTests/InstallationTests.cs b/tests/Deployment.AcceptanceTests/InstallationTests.cs new file mode 100644 index 0000000..7aad5eb --- /dev/null +++ b/tests/Deployment.AcceptanceTests/InstallationTests.cs @@ -0,0 +1,228 @@ +using System.Net; +using System.Runtime.Versioning; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Npgsql; +using Xunit; + +namespace Deployment.AcceptanceTests; + +[SupportedOSPlatform("linux")] +public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture +{ + [Fact] + public async Task A_selected_service_release_can_be_built_into_a_relative_output_directory() + { + var result = await DeploymentFixture.Run("bash", [Path.Combine(DeploymentFixture.Repository, "deploy/build-release.sh"), + "--output", "single-release", "--services", "insights"], new() { ["HEALTHAPP_DOTNET"] = fixture.Dotnet }, fixture.Temporary); + Assert.Equal(0, result.Code); + var release = Path.Combine(fixture.Temporary, "single-release"); + Assert.True(File.Exists(Path.Combine(release, "services/insights/InsightsService.dll"))); + Assert.Single(Directory.GetDirectories(Path.Combine(release, "services"))); + Assert.True(File.Exists(Path.Combine(release, "install.sh"))); + Assert.True(File.Exists(Path.Combine(release, "INSTALLATION.md"))); + } + + [Theory] + [InlineData("insights", 1)] + [InlineData("patient-profile,observation", 2)] + [InlineData("all", 5)] + public async Task Only_selected_payloads_configuration_and_independent_units_are_installed(string selection, int count) + { + var root = Path.Combine(fixture.Temporary, "selection-" + Guid.NewGuid().ToString("N")); + var installed = await fixture.Install(root, selection); + Assert.Equal(0, installed.Code); + var payloads = Directory.GetDirectories(Path.Combine(root, "opt/healthapp")).Select(Path.GetFileName).Order().ToArray(); + var expected = selection == "all" ? DeploymentFixture.Services : selection.Split(','); + Assert.Equal(count, payloads.Length); + Assert.Equal(expected.Order(), payloads); + foreach (var service in expected) + { + var env = Path.Combine(root, "etc/healthapp", service + ".env"); + Assert.Equal(await File.ReadAllTextAsync(Path.Combine(fixture.Configuration, service + ".env")), await File.ReadAllTextAsync(env)); + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(env)); + var unit = await File.ReadAllTextAsync(Path.Combine(root, "etc/systemd/system", "healthapp-" + service + ".service")); + Assert.Contains("ExecStart=/usr/bin/dotnet /opt/healthapp/" + service + "/" + DeploymentFixture.Assembly(service) + ".dll", unit); + Assert.Contains("EnvironmentFile=/etc/healthapp/" + service + ".env", unit); + Assert.DoesNotContain("Requires=healthapp-", unit); + Assert.DoesNotContain("PartOf=", unit); + Assert.DoesNotContain("BindsTo=", unit); + } + // A repeated install must not overwrite live configuration or application files. + var repeated = await fixture.Install(root, selection); + Assert.NotEqual(0, repeated.Code); + Assert.Contains("Already installed", repeated.Output); + } + + [Fact] + public async Task Remote_configuration_is_preserved_as_data_without_executing_shell_text() + { + var config = Path.Combine(fixture.Temporary, "remote-config"); + Directory.CreateDirectory(config); + var marker = Path.Combine(fixture.Temporary, "must-not-exist"); + var text = "ASPNETCORE_ENVIRONMENT=Production\n" + + "Services__ApiGateway__BaseUrl=https://remote-gateway.example.test:5443/\n" + + "Services__ApiGateway__Key=externally-provisioned-credential-with-at-least-32-characters\n" + + "InternalAccess__GatewayKey=another-externally-provisioned-credential-with-at-least-32-characters\n" + + $"UninterpretedValue=\"$(touch {marker})\"\n"; + await File.WriteAllTextAsync(Path.Combine(config, "insights.env"), text); + var root = Path.Combine(fixture.Temporary, "remote-root"); + var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights", + "--config-dir", config, "--root", root]); + Assert.Equal(0, result.Code); + Assert.Equal(text, await File.ReadAllTextAsync(Path.Combine(root, "etc/healthapp/insights.env"))); + Assert.False(File.Exists(marker)); + Assert.Single(Directory.GetDirectories(Path.Combine(root, "opt/healthapp"))); + } + + [Theory] + [InlineData("unknown")] + [InlineData("insights,insights")] + [InlineData("insights,")] + public async Task Invalid_service_selection_is_rejected_without_creating_an_installation(string selection) + { + var root = Path.Combine(fixture.Temporary, "invalid-" + Guid.NewGuid().ToString("N")); + var result = await fixture.Install(root, selection); + Assert.NotEqual(0, result.Code); + Assert.False(Directory.Exists(root)); + } + + [Fact] + public async Task Missing_configuration_for_any_selected_service_rejects_the_whole_install_before_writes() + { + var config = Path.Combine(fixture.Temporary, "partial-config"); + Directory.CreateDirectory(config); + File.Copy(Path.Combine(fixture.Configuration, "insights.env"), Path.Combine(config, "insights.env")); + var root = Path.Combine(fixture.Temporary, "partial-root"); + var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights,observation", + "--config-dir", config, "--root", root]); + Assert.NotEqual(0, result.Code); + Assert.False(Directory.Exists(root)); + } + + [Theory] + [InlineData("patient-profile")] + [InlineData("observation")] + [InlineData("insights")] + [InlineData("health-overview")] + [InlineData("api-gateway")] + public async Task A_single_installed_service_starts_and_stops_without_other_local_service_processes(string service) + { + var root = Path.Combine(fixture.Temporary, "single-" + service); + Assert.Equal(0, (await fixture.Install(root, service)).Code); + try + { + await fixture.Start(service, root); + Assert.Single(fixture.Processes); + Assert.False(fixture.Processes[service].HasExited); + } + finally { await fixture.Stop(service); } + Assert.Empty(fixture.Processes); + } + + [Theory] + [InlineData("--start")] + [InlineData("--migrate")] + public async Task Offline_staging_rejects_live_actions_without_writing_files(string action) + { + var root = Path.Combine(fixture.Temporary, "offline-action-" + Guid.NewGuid().ToString("N")); + var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights", + "--config-dir", fixture.Configuration, "--root", root, action]); + Assert.NotEqual(0, result.Code); + Assert.False(Directory.Exists(root)); + } + + [Fact] + public async Task Two_colocated_installed_services_run_with_independent_configuration_and_processes() + { + var root = Path.Combine(fixture.Temporary, "two-services"); + Assert.Equal(0, (await fixture.Install(root, "patient-profile,observation")).Code); + try + { + await fixture.Start("patient-profile", root); + await fixture.Start("observation", root); + Assert.Equal(2, fixture.Processes.Values.Select(p => p.Id).Distinct().Count()); + using var client = new HttpClient(); + using var request = new HttpRequestMessage(HttpMethod.Get, fixture.Urls["observation"] + + "api/patients/00000000-0000-0000-0000-000000000001/observations?from=2026-09-01&to=2026-09-10"); + request.Headers.Add("X-Gateway-Key", fixture.Settings["observation"]["InternalAccess__GatewayKey"]); + using var response = await client.SendAsync(request); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("[]", await response.Content.ReadAsStringAsync()); + var observationPid = fixture.Processes["observation"].Id; + await fixture.Stop("patient-profile"); + Assert.False(fixture.Processes["observation"].HasExited); + Assert.Equal(observationPid, fixture.Processes["observation"].Id); + await fixture.Start("patient-profile", root); + Assert.Equal(observationPid, fixture.Processes["observation"].Id); + } + finally { foreach (var service in fixture.Processes.Keys.ToArray()) await fixture.Stop(service); } + } + + [Fact] + public async Task Installed_complete_system_runs_in_five_processes_and_preserves_network_and_persistence_boundaries() + { + try + { + foreach (var service in DeploymentFixture.Services) await fixture.Start(service); + Assert.Equal(5, fixture.Processes.Values.Select(p => p.Id).Distinct().Count()); + using var client = new HttpClient { BaseAddress = new Uri(fixture.Urls["api-gateway"]), Timeout = TimeSpan.FromSeconds(10) }; + using var login = await client.PostAsJsonAsync("api/authentication/login", new + { accountId = "deployment-patient", password = DeploymentFixture.Password }); + Assert.Equal(HttpStatusCode.OK, login.StatusCode); + using var tokenJson = JsonDocument.Parse(await login.Content.ReadAsStringAsync()); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenJson.RootElement.GetProperty("accessToken").GetString()); + using var profile = await client.PostAsJsonAsync("api/patients", new { name = "Deployed patient", dateOfBirth = "1980-01-01" }); + Assert.Equal(HttpStatusCode.Created, profile.StatusCode); + using var profileJson = JsonDocument.Parse(await profile.Content.ReadAsStringAsync()); + var patient = profileJson.RootElement.GetProperty("patientId").GetGuid(); + using var recorded = await client.PostAsJsonAsync($"api/patients/{patient}/observations", new + { measuredAt = "2026-09-05T08:00:00", systolic = 128, diastolic = 82, pulse = 68, + measurementContext = new { setting = "Home", activityCondition = "AtRest" } }); + Assert.Equal(HttpStatusCode.Created, recorded.StatusCode); + var overviewPath = $"api/patients/{patient}/overview?from=2026-09-01&to=2026-09-10&setting=Home&activityCondition=AtRest"; + using var overview = await client.GetAsync(overviewPath); + Assert.Equal(HttpStatusCode.OK, overview.StatusCode); + using var overviewJson = JsonDocument.Parse(await overview.Content.ReadAsStringAsync()); + Assert.Equal(patient, overviewJson.RootElement.GetProperty("patient").GetProperty("patientId").GetGuid()); + Assert.Equal(128, overviewJson.RootElement.GetProperty("latestObservation").GetProperty("systolic").GetInt32()); + Assert.Equal(128m, overviewJson.RootElement.GetProperty("insight").GetProperty("averageSystolic").GetDecimal()); + Assert.Equal(1, overviewJson.RootElement.GetProperty("insightContributingCount").GetInt32()); + foreach (var service in DeploymentFixture.Services) + { + var peers = fixture.Processes.Where(p => p.Key != service).ToDictionary(p => p.Key, p => p.Value.Id); + var oldId = fixture.Processes[service].Id; + await fixture.Stop(service); + foreach (var (peer, id) in peers) + { + Assert.Equal(id, fixture.Processes[peer].Id); + Assert.False(fixture.Processes[peer].HasExited); + } + await fixture.Start(service); + Assert.NotEqual(oldId, fixture.Processes[service].Id); + using var fresh = await client.GetAsync(overviewPath); + Assert.Equal(HttpStatusCode.OK, fresh.StatusCode); + } + // Each DB owns only its documented service's tables; aggregation services have no DB configuration. + foreach (var (service, key, owned, absent) in new[] + { + ("patient-profile", "ConnectionStrings__PatientDatabase", "patient", "blood_pressure_observation"), + ("observation", "ConnectionStrings__ObservationDatabase", "blood_pressure_observation", "patient") + }) + { + await using var connection = new NpgsqlConnection(fixture.Settings[service][key]); + await connection.OpenAsync(); + await using var command = new NpgsqlCommand("SELECT tablename FROM pg_tables WHERE schemaname = 'public'", connection); + await using var reader = await command.ExecuteReaderAsync(); + List tables = []; + while (await reader.ReadAsync()) tables.Add(reader.GetString(0)); + Assert.Contains(owned, tables); + Assert.DoesNotContain(absent, tables); + } + Assert.DoesNotContain(fixture.Settings["insights"].Keys, k => k.StartsWith("ConnectionStrings__")); + Assert.DoesNotContain(fixture.Settings["health-overview"].Keys, k => k.StartsWith("ConnectionStrings__")); + } + finally { foreach (var service in fixture.Processes.Keys.ToArray()) await fixture.Stop(service); } + } +}