Provision US-16 dependencies credentials HTTPS and native service configurations

This commit is contained in:
Steffen committed 2026-10-06 09:11:28 +02:00
1 parent 950f67d8b7
commit eedf2a941b
34 files changed
+1703 -373

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Source from install.sh. Package commands use the supported distribution's signed feeds.
ensure_dependencies() {
local distribution=$1 version=$2 runtime=$3 persistence=$4
case "$distribution:$version" in ubuntu:24.04|debian:12|debian:13) ;; *) fail 'Automatic provisioning supports Ubuntu 24.04 and Debian 12/13.';; esac
step='install base dependencies'
if ! command -v curl >/dev/null || ! command -v update-ca-certificates >/dev/null; then
apt-get update
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'
apt-get update
if [[ "$distribution" == debian ]]; then
local package_dir
package_dir=$(mktemp -d)
curl --fail --silent --show-error "https://packages.microsoft.com/config/debian/$version/packages-microsoft-prod.deb" -o "$package_dir/microsoft.deb"
dpkg -i "$package_dir/microsoft.deb"
rm -f -- "$package_dir/microsoft.deb"
rmdir -- "$package_dir"
apt-get update
fi
DEBIAN_FRONTEND=noninteractive apt-get install -y aspnetcore-runtime-10.0
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
DEBIAN_FRONTEND=noninteractive apt-get install -y postgresql
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
}
+23
View File
@@ -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"
+156
View File
@@ -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"
+159
View File
@@ -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
}
+129 -67
View File
@@ -1,88 +1,150 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
fail() { printf 'Error: %s\n' "$*" >&2; exit 1; }
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=
config_dir=
target_root=/
dotnet_path=/usr/bin/dotnet
start=false
migrate=false
host=localhost
topology=
deployment=
external_certificates=
admin_file=
prepare_only=false
defer_verification=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;;
--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
[[ $(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.'
[[ $(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")
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.
step=preflight
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
[[ -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
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.'
[[ -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"
else
printf '%s\n' 'Offline files staged. Provision the runtime/service account and enable units on the target host before verification.'
[[ -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
+3 -3
View File
@@ -10,11 +10,11 @@ select_services() {
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=()
local 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
case "$seen" in *,$item,*) fail "Repeated service: $item";; esac
seen+="$item,"
done
}
assembly_for() {
+16 -35
View File
@@ -1,50 +1,31 @@
#!/usr/bin/env bash
set -euo pipefail
fail() { printf 'Error: %s\n' "$*" >&2; exit 1; }
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
fail() { printf 'Verification failed: %s\n' "$*" >&2; exit 1; }
source "$script_dir/services.sh"
requested=
probe_dir=
cycle=false
deployment=/var/lib/healthapp-installation/deployment
dotnet_path=/usr/bin/dotnet
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;;
--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"
[[ -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
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")
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.'
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.'