From ea3b5953ed14afe88e8ae98e5d9068ad7cb42450 Mon Sep 17 00:00:00 2001 From: Denimworld12 <166978100+Denimworld12@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:56:05 +0530 Subject: [PATCH 1/2] fix(install): Windows re-runs work again; organiser setup needs only Docker (#11) - install.ps1: keep --force-recreate an array (@(if ...)) so a re-run no longer hands Docker "- - f o r c e ..." ("no such service: -"); the removed-laptop check after it now surfaces, and ends "has been stopped", not "nothing changed" - install.ps1: exit 1 on every failure (run as a file or a one-off -Command); pasted into an open window it sets $LASTEXITCODE instead of closing it - install.ps1 / install.sh: ask for and check the name and the join code's format before the 2 GB image download - tests/unit/test_install_ps1.py: runs the installer in real pwsh with a docker stub that records the exact argv and rejects unknown services like Compose - provision.py: one hospital is enough when join codes add the rest; documented running it inside the published image, and the plain docker compose command next to make hub - Join codes page: copy buttons for the code and both install commands - Node image workflow: check the manifest's architectures with jq (the JSON is pretty-printed, so the grep never matched) - README: kit hospitals show their container's facts on Nodes (known limit) --- .github/workflows/image.yml | 3 +- README.md | 26 ++++- dashboard/src/pages/JoinCodes.jsx | 52 ++++++++- deploy/install/install.ps1 | 151 ++++++++++++++++++--------- deploy/install/install.sh | 58 ++++++++--- docs/MULTI_LAPTOP.md | 31 ++++-- scripts/provision.py | 13 ++- tests/unit/test_install_ps1.py | 168 ++++++++++++++++++++++++++++++ tests/unit/test_install_sh.py | 14 +++ tests/unit/test_provision.py | 11 +- 10 files changed, 446 insertions(+), 81 deletions(-) create mode 100644 tests/unit/test_install_ps1.py diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index b156c9d..0cccf89 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -116,8 +116,9 @@ jobs: sources=() for digest in *; do sources+=("$IMAGE@sha256:$digest"); done docker buildx imagetools create -t "$IMAGE:$VERSION" "${sources[@]}" + # the JSON comes pretty-printed ("architecture": "arm64", with a space): read it with jq, not grep - name: check it run: | docker buildx imagetools inspect "$IMAGE:$VERSION" docker buildx imagetools inspect "$IMAGE:$VERSION" --format '{{json .Manifest.Manifests}}' \ - | grep -q '"architecture":"arm64"' + | jq -e '[.[].platform.architecture] | (index("amd64") != null) and (index("arm64") != null)' diff --git a/README.md b/README.md index 55a1ec9..8bccada 100644 --- a/README.md +++ b/README.md @@ -604,7 +604,19 @@ python scripts/provision.py --zip \ `--peers` lists every hospital with the address the others reach it at: a LAN IP, a Tailscale name or a domain. Every address is HTTPS (a bare `host:port` gets `https://`; `http://` is rejected). The order is the directory's placement -order between runs. The command writes `kits/hospital-a/` ... `kits/hospital-d/` +order between runs. One hospital (your own) is enough when everyone else will +join with a code from the dashboard. + +**Only Docker installed (no Python)?** Run `provision.py` inside the published node +image, from the repository folder (a clone or the release's source zip). The same +command works in PowerShell and in a Mac or Linux terminal: + +```sh +docker run --rm -v "${PWD}:/src" -w /src ghcr.io/denimworld12/medchain-node:v1.1.0 \ + python scripts/provision.py --zip --peers hospital-a=sam-laptop.tail1234.ts.net:8001 --directory sam-laptop.tail1234.ts.net:8100 +``` + +On Linux, add `--user "$(id -u):$(id -g)"` after `--rm` so the kits belong to you, not root. The command writes `kits/hospital-a/` ... `kits/hospital-d/` and `kits/directory/`, plus a `.zip` of each. The network's CA and keys live in `kits/.pki/` (or `--pki DIR`) and are reused on every later run, so the network is never re-keyed. Every hospital kit holds: @@ -641,6 +653,13 @@ make hub # on the hub, docker compose --project-directory . -f deploy/node.yml up -d # on each hospital machine, in its kit ``` +No `make` (a stock Windows laptop has none)? `make hub` is exactly this, run from the +repository folder: + +```sh +docker compose --project-directory . --env-file kits/directory/hub.env -f deploy/hub.yml up -d --wait +``` + Start training from any one node (`POST /round/start`, as above). The start floods along the chain. @@ -769,7 +788,10 @@ else's hospital rejected. The dashboard's **Nodes** page shows each hospital's f with a **Signature verified** badge and the key's fingerprint, or **Rejected** with the reason. This is in addition to the Start/Pause controls. One limit: the host's uptime counts from the boot time the install script saw, so after a reboot, run the installer -again to refresh it. The round-trip times and data rows are always live. +again to refresh it. Another: a hospital started from a kit (such as the organiser's own) +had no install script to read the laptop's facts, so it shows what its container sees, +the container's hostname and the Docker VM's Linux. The round-trip times and data rows +are always live. ### Prove it diff --git a/dashboard/src/pages/JoinCodes.jsx b/dashboard/src/pages/JoinCodes.jsx index e2468c8..29d3775 100644 --- a/dashboard/src/pages/JoinCodes.jsx +++ b/dashboard/src/pages/JoinCodes.jsx @@ -7,18 +7,65 @@ import { notAuthorized } from "../auth.js"; const RAW = "https://raw.githubusercontent.com/Denimworld12/Hospital-Chain"; +// navigator.clipboard exists only in a secure context (https, or localhost): a dashboard opened at the hub's +// Tailscale IP over http falls back to the older selection copy +async function copyText(text) { + if (navigator.clipboard && window.isSecureContext) { + await navigator.clipboard.writeText(text); + return; + } + const area = document.createElement("textarea"); + area.value = text; + area.setAttribute("readonly", ""); + area.style.position = "fixed"; + area.style.opacity = "0"; + document.body.appendChild(area); + area.select(); + try { + if (!document.execCommand("copy")) throw new Error("copy refused"); + } finally { + document.body.removeChild(area); + } +} + +function CopyButton({ text, label = "Copy", testId }) { + const [state, setState] = useState("idle"); + useEffect(() => { + if (state === "idle") return undefined; + const t = setTimeout(() => setState("idle"), 2000); + return () => clearTimeout(t); + }, [state]); + const copy = async () => { + try { + await copyText(text); + setState("copied"); + } catch { + setState("failed"); + } + }; + return ( + + {state === "copied" ? "Copied" : state === "failed" ? "Select and copy by hand" : label} + + ); +} + // The one command a friend runs (Docker Desktop and Tailscale already installed, on this tailnet). function InstallCommands({ install }) { if (!install) return null; const hub = install.hub || ""; const base = `${RAW}/${install.version}/deploy/install`; + const windows = `$env:MEDCHAIN_HUB = "${hub}"; irm ${base}/install.ps1 | iex`; + const unix = `curl -fsSL ${base}/install.sh | MEDCHAIN_HUB=${hub} bash`; return (

On the hospital's laptop

Windows (PowerShell):

-
{`$env:MEDCHAIN_HUB = "${hub}"; irm ${base}/install.ps1 | iex`}
+
{windows}
+

macOS or Linux (Terminal):

-
{`curl -fsSL ${base}/install.sh | MEDCHAIN_HUB=${hub} bash`}
+
{unix}
+

It asks for the hospital's name and the join code, checks Docker, Tailscale, this hub and disk space, and starts the hospital.

); @@ -120,6 +167,7 @@ export default function JoinCodes() { <>

Give this code to one hospital. It is shown only now.

{created.code}

+

Expires {when(created.expires_at)}. Works once.

) : ( diff --git a/deploy/install/install.ps1 b/deploy/install/install.ps1 index 8b4a5e7..bea4624 100644 --- a/deploy/install/install.ps1 +++ b/deploy/install/install.ps1 @@ -16,8 +16,12 @@ # MEDCHAIN_IMAGE (ghcr.io/denimworld12/medchain-node), MEDCHAIN_IMAGE_VERSION (this installer's). # MEDCHAIN_DISPLAY_NAME and MEDCHAIN_JOIN_CODE, if set, are used instead of asking (unattended runs). # Works in Windows PowerShell 5.1 and PowerShell 7. +# +# A failure exits 1 when run as a file (powershell -File install.ps1) or as a one-off +# `powershell -Command`; pasted into an open window (irm ... | iex) it sets $LASTEXITCODE to 1 +# instead, so that window stays open. -function Install-MedChain { +function Install-MedChain($Outcome) { $InstallerVersion = "1.1.0" $Image = if ($env:MEDCHAIN_IMAGE) { $env:MEDCHAIN_IMAGE } else { "ghcr.io/denimworld12/medchain-node" } $Version = if ($env:MEDCHAIN_IMAGE_VERSION) { $env:MEDCHAIN_IMAGE_VERSION } else { "v$InstallerVersion" } @@ -28,14 +32,27 @@ function Install-MedChain { function Say($text) { Write-Host $text } function Ok($text) { Write-Host " [ok] $text" -ForegroundColor Green } - function Problem($what, $fix) { + function Problem($what, $fix, $after = "Fix that, then run the same command again. Nothing has been changed on this laptop.") { + $Outcome.Failed = $true # a folder this run created and left empty goes again, so "nothing has been changed" stays true if ($createdDir -and (Test-Path $Dir) -and -not (Get-ChildItem -Force $Dir)) { Remove-Item $Dir } Write-Host "" Write-Host " [!] $what" -ForegroundColor Red Write-Host " What to do: $fix" -ForegroundColor Yellow Write-Host "" - Write-Host " Fix that, then run the same command again. Nothing has been changed on this laptop." -ForegroundColor Yellow + Write-Host " $after" -ForegroundColor Yellow + } + # the name and the join code are asked for (and checked) before the 2 GB download, not after it + function Read-Name { + $typed = Read-Host "Your hospital's name, as the dashboard should show it (2 to 60 characters)" + if ($null -eq $typed) { return $null } # no one to ask (no input at all) + return [string]$typed + } + function Test-Name($text) { return ($text.Trim() -match '^[^\x00-\x1f\x7f]{2,60}$') } + # node/enroll.py's normalize_code: 20 letters and digits from its alphabet, any dashes or spaces dropped + function Test-JoinCode($text) { + $raw = ($text -replace '[^A-Za-z0-9]', '').ToUpperInvariant() + return ($raw.Length -eq 20 -and $raw -cmatch '^[ABCDEFGHJKMNPQRSTVWXYZ23456789]+$') } Say "" @@ -99,7 +116,7 @@ function Install-MedChain { if ($wait.AsyncWaitHandle.WaitOne(5000) -and $tcp.Connected) { $reachable = $true } } catch { } finally { $tcp.Close() } if (-not $reachable) { - Problem "The organiser's hub at ${hubHost}:${hubPort} does not answer." "Check the address with the organiser, check that their hub is running ('make hub'), and that their laptop shows as connected in your Tailscale menu. A work VPN can block Tailscale: disconnect it." + Problem "The organiser's hub at ${hubHost}:${hubPort} does not answer." "Check the address with the organiser, check that their hub is running, and that their laptop shows as connected in your Tailscale menu. A work VPN can block Tailscale: disconnect it." return } Ok "The hub at ${hubHost}:${hubPort} answers" @@ -114,7 +131,57 @@ function Install-MedChain { } Ok "$freeGB GB free on $root" - # ---- 5. The MedChain image -------------------------------------------------------------------- + # ---- 5. Enrolled already? If not: the hospital's name and the join code, checked before the download ---- + $envFile = Join-Path $Dir ".env" + $id = $null + if (Test-Path $envFile) { + $idLine = Select-String -Path $envFile -Pattern '^NODE_ID=(.+)$' | Select-Object -First 1 + if ($idLine -and (Test-Path ([IO.Path]::Combine($Dir, "pki", $idLine.Matches[0].Groups[1].Value, "tls.crt")))) { + $id = $idLine.Matches[0].Groups[1].Value + } + } + $rerun = [bool]$id + if ($rerun) { + Ok "This laptop is already enrolled ($id); keeping its keys" + } else { + Say "" + Say "Enrolling this laptop. The organiser gives you a join code (it works once, for 30 minutes)." + # unattended (the name given in MEDCHAIN_DISPLAY_NAME): never fall back to asking, as install.sh + $unattended = [bool]$env:MEDCHAIN_DISPLAY_NAME + $name = if ($env:MEDCHAIN_DISPLAY_NAME) { [string]$env:MEDCHAIN_DISPLAY_NAME } else { "" } + $joinCode = if ($env:MEDCHAIN_JOIN_CODE) { [string]$env:MEDCHAIN_JOIN_CODE } else { "" } + if ($unattended -and -not (Test-Name $name)) { + Problem "The hospital name in `$env:MEDCHAIN_DISPLAY_NAME must be 2 to 60 characters." "Set `$env:MEDCHAIN_DISPLAY_NAME to the hospital's name, then run the same command again." + return + } + while (-not (Test-Name $name)) { + $name = Read-Name + if ($null -eq $name) { + Problem "No hospital name given." "Run it in a PowerShell window and type the name, or set `$env:MEDCHAIN_DISPLAY_NAME." + return + } + } + if (-not $joinCode -and $unattended) { # unattended: never prompt (on 5.1 -AsSecureString would wait forever) + Problem "No join code given." "Set `$env:MEDCHAIN_JOIN_CODE to the code the organiser gave you, then run the same command again." + return + } + if (-not $joinCode) { + $secure = Read-Host "The join code (like ABCD-EFGH-JKMN-PQRS-TVWX; hidden as you type)" -AsSecureString + if ($null -eq $secure -or $secure.Length -eq 0) { + Problem "No join code given." "Ask the organiser for a join code and type it when asked, or set `$env:MEDCHAIN_JOIN_CODE." + return + } + $ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure) + try { $joinCode = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) } + finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } + } + if (-not (Test-JoinCode $joinCode)) { + Problem "That is not a join code: a join code is 20 letters and digits in groups of four, like ABCD-EFGH-JKMN-PQRS-TVWX." "Check it with the organiser (or ask for a new one), then run the same command again." + return + } + } + + # ---- 6. The MedChain image -------------------------------------------------------------------- Say "" Say "Downloading the MedChain program ($Image`:$Version, about 2 GB the first time)..." docker pull "${Image}:${Version}" @@ -127,27 +194,18 @@ function Install-MedChain { Say " (could not check for a newer copy; using the one already on this laptop)" } - # ---- 6. This computer's facts, for the dashboard's proof of origin -------------------------- - $os = Get-CimInstance Win32_OperatingSystem + # ---- 7. This computer's facts, for the dashboard's proof of origin -------------------------- + # (no CIM, as in PowerShell 7 off Windows: the version string, and no boot time) + $os = if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue } $env:MEDCHAIN_HOST_NAME = if ($env:COMPUTERNAME) { $env:COMPUTERNAME } else { [Environment]::MachineName } - $env:MEDCHAIN_HOST_OS = "$($os.Caption) $($os.Version)" - $env:MEDCHAIN_HOST_BOOTED_AT = [string][int64](([DateTimeOffset]$os.LastBootUpTime).ToUnixTimeSeconds()) + $env:MEDCHAIN_HOST_OS = if ($os) { "$($os.Caption) $($os.Version)" } else { [Environment]::OSVersion.VersionString } + $env:MEDCHAIN_HOST_BOOTED_AT = if ($os) { [string][int64](([DateTimeOffset]$os.LastBootUpTime).ToUnixTimeSeconds()) } else { "" } $env:MEDCHAIN_TAILSCALE_DEVICE = $device - # ---- 7. Enroll (once) --------------------------------------------------------------------------- + # ---- 8. Enroll (once), or refresh an enrolled laptop's settings ----------------------------------- $createdDir = -not (Test-Path $Dir) New-Item -ItemType Directory -Force -Path $Dir | Out-Null - $envFile = Join-Path $Dir ".env" - $enrolled = $false - if (Test-Path $envFile) { - $idLine = Select-String -Path $envFile -Pattern '^NODE_ID=(.+)$' | Select-Object -First 1 - if ($idLine -and (Test-Path ([IO.Path]::Combine($Dir, "pki", $idLine.Matches[0].Groups[1].Value, "tls.crt")))) { - $enrolled = $true - } - } - $rerun = $enrolled - if ($enrolled) { - Ok "This laptop is already enrolled ($($idLine.Matches[0].Groups[1].Value)); keeping its keys" + if ($rerun) { # refresh what can change: this laptop's Tailscale address, its facts, and its port when MEDCHAIN_PORT asks # for another one (peers pin the key, not the address: no new join code is needed) $keep = Get-Content $envFile | Where-Object { $_ -notmatch '^(NODE_PORT|ADVERTISE_ADDR|MEDCHAIN_HOST_NAME|MEDCHAIN_HOST_OS|MEDCHAIN_HOST_BOOTED_AT|MEDCHAIN_TAILSCALE_DEVICE)=' } @@ -159,34 +217,14 @@ function Install-MedChain { "MEDCHAIN_TAILSCALE_DEVICE=$env:MEDCHAIN_TAILSCALE_DEVICE") [System.IO.File]::WriteAllLines($envFile, $lines) # no BOM: Docker Compose reads it } else { - Say "" - Say "Enrolling this laptop. The organiser gives you a join code (it works once, for 30 minutes)." - # unattended (the name given in MEDCHAIN_DISPLAY_NAME): never fall back to asking, as install.sh - $unattended = [bool]$env:MEDCHAIN_DISPLAY_NAME - $name = if ($env:MEDCHAIN_DISPLAY_NAME) { [string]$env:MEDCHAIN_DISPLAY_NAME } else { "" } - $joinCode = if ($env:MEDCHAIN_JOIN_CODE) { $env:MEDCHAIN_JOIN_CODE } else { "" } + $enrolled = $false for ($try = 1; $try -le 3; $try++) { - while ($name.Trim().Length -lt 2 -or $name.Trim().Length -gt 60) { - $typed = Read-Host "Your hospital's name, as the dashboard should show it (2 to 60 characters)" - if ($null -eq $typed) { # no one to ask (no input at all) + while (-not (Test-Name $name)) { + $name = Read-Name + if ($null -eq $name) { Problem "No hospital name given." "Run it in a PowerShell window and type the name, or set `$env:MEDCHAIN_DISPLAY_NAME." return } - $name = [string]$typed - } - if (-not $joinCode -and $unattended) { # unattended: never prompt (on 5.1 -AsSecureString would wait forever) - Problem "No join code given." "Set `$env:MEDCHAIN_JOIN_CODE to the code the organiser gave you, then run the same command again." - return - } - if (-not $joinCode) { - $secure = Read-Host "The join code (like ABCD-EFGH-JKMN-PQRS-TVWX; hidden as you type)" -AsSecureString - if ($null -eq $secure -or $secure.Length -eq 0) { - Problem "No join code given." "Ask the organiser for a join code and type it when asked, or set `$env:MEDCHAIN_JOIN_CODE." - return - } - $ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure) - try { $joinCode = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) } - finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } } $env:MEDCHAIN_JOIN_CODE = $joinCode $env:MEDCHAIN_DISPLAY_NAME = $name.Trim() @@ -214,21 +252,23 @@ function Install-MedChain { Problem "No free name after three tries." "Pick a name no other hospital uses, then run the same command again." return } + $id = (Select-String -Path $envFile -Pattern '^NODE_ID=(.+)$' | Select-Object -First 1).Matches[0].Groups[1].Value } - # ---- 8. Start (or restart) the hospital -------------------------------------------------------- + # ---- 9. Start (or restart) the hospital -------------------------------------------------------- Say "" $compose = [IO.Path]::Combine($Dir, "deploy", "node.yml") # the node checks in with the hub only when it starts: on a re-run recreate it, so step 9 sees the hub's answer of now - $recreate = if ($rerun) { @("--force-recreate") } else { @() } + # @(if ...) keeps it an array: `if` alone unwraps a one-element array into a string, and splatting a + # string passes it one character at a time ("no such service: -") + $recreate = @(if ($rerun) { "--force-recreate" }) docker compose --project-directory $Dir -f $compose up -d @recreate if ($LASTEXITCODE -ne 0) { Problem "Docker could not start the hospital." "If it says 'port is already allocated', another program uses port ${Port}: close it, or set `$env:MEDCHAIN_PORT to another port and run the same command again (no new join code needed). Otherwise restart Docker Desktop and run this again." return } - $id = (Select-String -Path $envFile -Pattern '^NODE_ID=(.+)$' | Select-Object -First 1).Matches[0].Groups[1].Value - # ---- 9. Did the hub let it in? ------------------------------------------------------------------- + # ---- 10. Did the hub let it in? ------------------------------------------------------------------- $tries = if ($env:MEDCHAIN_REGISTER_TRIES) { [int]$env:MEDCHAIN_REGISTER_TRIES } else { 20 } Say "" Say "Waiting for the hub to place this hospital (up to $($tries * 3)s)..." @@ -239,7 +279,7 @@ function Install-MedChain { if ($code -eq 0) { $registered = $true; break } if ($code -eq 3) { docker compose --project-directory $Dir -f $compose down *> $null # it would only retry, refused, forever - Problem "The organiser removed this laptop from the network: the hub refuses its keys." "Delete the folder $Dir, ask the organiser for a new join code, then run the same command again." + Problem "The organiser removed this laptop from the network: the hub refuses its keys." "Delete the folder $Dir, ask the organiser for a new join code, then run the same command again." "This laptop's hospital has been stopped; nothing else was changed." return } Start-Sleep -Seconds 3 @@ -258,4 +298,13 @@ function Install-MedChain { Say " Stop: $up down" } -Install-MedChain +$medchainOutcome = @{ Failed = $false } +Install-MedChain $medchainOutcome +if ($medchainOutcome.Failed) { + # exit (so a caller sees the failure) unless this runs in a window someone keeps using: `exit` would close it + $cli = @([Environment]::GetCommandLineArgs() | Select-Object -Skip 1) + $oneShot = @($cli | Where-Object { $_ -match '^[-/]{1,2}(c|com\w*|e|ec|enc\w*|f|fi\w*|noni\w*)$' }).Count -gt 0 + $keepOpen = @($cli | Where-Object { $_ -match '^[-/]{1,2}noe\w*$' }).Count -gt 0 + if ($PSCommandPath -or ($oneShot -and -not $keepOpen)) { exit 1 } + $global:LASTEXITCODE = 1 +} diff --git a/deploy/install/install.sh b/deploy/install/install.sh index 062381c..d609775 100755 --- a/deploy/install/install.sh +++ b/deploy/install/install.sh @@ -33,9 +33,16 @@ CREATED_DIR="" problem() { # a folder this run created and left empty goes again, so "nothing has been changed" stays true [ -n "$CREATED_DIR" ] && rmdir "$DIR" 2>/dev/null - printf '\n [!] %s\n What to do: %s\n\n Fix that, then run the same command again. Nothing has been changed on this computer.\n' "$1" "$2" >&2 + printf '\n [!] %s\n What to do: %s\n\n %s\n' "$1" "$2" \ + "${3:-Fix that, then run the same command again. Nothing has been changed on this computer.}" >&2 exit 1 } +# node/enroll.py's normalize_code: 20 letters and digits from its alphabet, any dashes or spaces dropped +valid_code() { + local raw + raw=$(printf '%s' "$1" | tr -cd 'A-Za-z0-9' | tr 'a-z' 'A-Z') + [ "${#raw}" -eq 20 ] && [ -z "$(printf '%s' "$raw" | tr -d 'ABCDEFGHJKMNPQRSTVWXYZ23456789')" ] +} # read from the terminal even when this script itself arrives on stdin (curl ... | bash) ask() { local reply; IFS= read -r -p "$1" reply /dev/tty; printf '%s' "$reply"; } @@ -74,7 +81,7 @@ HUB=$(printf '%s' "$HUB" | tr -d '[:space:]') case "$HUB" in *:*) HUB_HOST=${HUB%:*}; HUB_PORT=${HUB##*:} ;; *) HUB_HOST=$HUB; HUB_PORT=$DIRECTORY_PORT ;; esac curl -sk --max-time 6 "https://$HUB_HOST:$HUB_PORT/health" 2>/dev/null | grep -q '"directory"' || problem "The organiser's hub at $HUB_HOST:$HUB_PORT does not answer." \ - "Check the address with the organiser, that their hub is running ('make hub'), and that their computer shows as connected in your Tailscale menu. A work VPN can block Tailscale: disconnect it." + "Check the address with the organiser, that their hub is running, and that their computer shows as connected in your Tailscale menu. A work VPN can block Tailscale: disconnect it." ok "The hub at $HUB_HOST:$HUB_PORT answers" # ---- 4. Disk space ----------------------------------------------------------------------------- @@ -86,7 +93,33 @@ FREE_KB=$(df -Pk "$DIR" | awk 'NR==2 {print $4}') "Free some space, or set MEDCHAIN_DIR to a folder on another disk." ok "$((FREE_KB / 1024 / 1024)) GB free" -# ---- 5. The MedChain image --------------------------------------------------------------------- +# ---- 5. Enrolled already? If not: the hospital's name and the join code, checked before the download ---- +ENV_FILE="$DIR/.env" +NODE_ID=$(sed -n 's/^NODE_ID=//p' "$ENV_FILE" 2>/dev/null | head -n 1) +RERUN="" +if [ -n "$NODE_ID" ] && [ -f "$DIR/pki/$NODE_ID/tls.crt" ]; then + RERUN=1 + ok "This computer is already enrolled ($NODE_ID); keeping its keys" +else + printf '\nEnrolling this computer. The organiser gives you a join code (it works once, for 30 minutes).\n' + NAME=${MEDCHAIN_DISPLAY_NAME:-} + CODE=${MEDCHAIN_JOIN_CODE:-} + if [ -n "$NAME" ] && { [ "${#NAME}" -lt 2 ] || [ "${#NAME}" -gt 60 ]; }; then + problem "The hospital name in MEDCHAIN_DISPLAY_NAME must be 2 to 60 characters." \ + "Set MEDCHAIN_DISPLAY_NAME to the hospital's name, then run the same command again." + fi + while [ "${#NAME}" -lt 2 ] || [ "${#NAME}" -gt 60 ]; do + ( : /dev/null || problem "No hospital name given." "Set MEDCHAIN_DISPLAY_NAME, or run it in a terminal and type the name." + NAME=$(ask "Your hospital's name, as the dashboard should show it (2 to 60 characters): ") + done + [ -n "$CODE" ] || CODE=$(ask_hidden "The join code (like ABCD-EFGH-JKMN-PQRS-TVWX; hidden as you type): ") + [ -n "$CODE" ] || problem "No join code given." "Set MEDCHAIN_JOIN_CODE to the code the organiser gave you (or type it when asked), then run the same command again." + valid_code "$CODE" || + problem "That is not a join code: a join code is 20 letters and digits in groups of four, like ABCD-EFGH-JKMN-PQRS-TVWX." \ + "Check it with the organiser (or ask for a new one), then run the same command again." +fi + +# ---- 6. The MedChain image --------------------------------------------------------------------- printf '\nDownloading the MedChain program (%s:%s, about 2 GB the first time)...\n' "$IMAGE" "$VERSION" if ! docker pull "$IMAGE:$VERSION"; then docker image inspect "$IMAGE:$VERSION" >/dev/null 2>&1 || @@ -95,7 +128,7 @@ if ! docker pull "$IMAGE:$VERSION"; then printf ' (could not check for a newer copy; using the one already on this computer)\n' fi -# ---- 6. This computer's facts, for the dashboard's proof of origin ----------------------------- +# ---- 7. This computer's facts, for the dashboard's proof of origin ----------------------------- if [ "$(uname)" = Darwin ]; then OS="$(sw_vers -productName) $(sw_vers -productVersion)" BOOTED=$(sysctl -n kern.boottime | sed -n 's/^{ sec = \([0-9]*\),.*/\1/p') # "{ sec = 1712345678, usec = ... }" @@ -110,14 +143,11 @@ MEDCHAIN_HOST_OS=$OS MEDCHAIN_HOST_BOOTED_AT=$BOOTED MEDCHAIN_TAILSCALE_DEVICE=$DEVICE -# ---- 7. Enroll (once) -------------------------------------------------------------------------- -ENV_FILE="$DIR/.env" -NODE_ID=$(sed -n 's/^NODE_ID=//p' "$ENV_FILE" 2>/dev/null | head -n 1) +# ---- 8. Enroll (once), or refresh an enrolled computer's settings ------------------------------- USER_FLAG=() RECREATE=() [ "$(uname)" = Linux ] && USER_FLAG=(--user "$(id -u):$(id -g)") # the kit's files belong to you, not root -if [ -n "$NODE_ID" ] && [ -f "$DIR/pki/$NODE_ID/tls.crt" ]; then - ok "This computer is already enrolled ($NODE_ID); keeping its keys" +if [ -n "$RERUN" ]; then # the node checks in with the hub only when it starts: recreate it, so step 9 sees the hub's answer of now RECREATE=(--force-recreate) # refresh what can change: this computer's Tailscale address, its facts, and its port when MEDCHAIN_PORT asks @@ -129,10 +159,7 @@ if [ -n "$NODE_ID" ] && [ -f "$DIR/pki/$NODE_ID/tls.crt" ]; then "$NODE_PORT" "$TS_IP" "$NODE_PORT" "$MEDCHAIN_HOST_NAME" "$MEDCHAIN_HOST_OS" "$MEDCHAIN_HOST_BOOTED_AT" "$MEDCHAIN_TAILSCALE_DEVICE" } >"$ENV_FILE.new" && mv "$ENV_FILE.new" "$ENV_FILE" else - printf '\nEnrolling this computer. The organiser gives you a join code (it works once, for 30 minutes).\n' enrolled="" - NAME=${MEDCHAIN_DISPLAY_NAME:-} - CODE=${MEDCHAIN_JOIN_CODE:-} for _ in 1 2 3; do while [ "${#NAME}" -lt 2 ] || [ "${#NAME}" -gt 60 ]; do NAME=$(ask "Your hospital's name, as the dashboard should show it (2 to 60 characters): ") @@ -164,14 +191,14 @@ else NODE_ID=$(sed -n 's/^NODE_ID=//p' "$ENV_FILE" | head -n 1) fi -# ---- 8. Start (or restart) the hospital -------------------------------------------------------- +# ---- 9. Start (or restart) the hospital -------------------------------------------------------- printf '\n' docker compose --project-directory "$DIR" -f "$DIR/deploy/node.yml" up -d ${RECREATE[@]+"${RECREATE[@]}"} || problem "Docker could not start the hospital." \ "If it says 'port is already allocated', another program uses port $PORT: stop it, or set MEDCHAIN_PORT to another port and run the same command again (no new join code needed). Otherwise restart Docker and run this again." UP="docker compose --project-directory \"$DIR\" -f \"$DIR/deploy/node.yml\"" -# ---- 9. Did the hub let it in? ------------------------------------------------------------------- +# ---- 10. Did the hub let it in? ------------------------------------------------------------------- printf '\nWaiting for the hub to place this hospital (up to %ss)...\n' "$((REGISTER_TRIES * 3))" registered="" for _ in $(seq 1 "$REGISTER_TRIES"); do @@ -181,7 +208,8 @@ for _ in $(seq 1 "$REGISTER_TRIES"); do [ $code -eq 3 ] && { docker compose --project-directory "$DIR" -f "$DIR/deploy/node.yml" down >/dev/null 2>&1 problem "The organiser removed this computer from the network: the hub refuses its keys (${line#the hub refuses this hospital: })." \ - "Delete the folder $DIR, ask the organiser for a new join code, then run the same command again." + "Delete the folder $DIR, ask the organiser for a new join code, then run the same command again." \ + "This computer's hospital has been stopped; nothing else was changed." } sleep 3 done diff --git a/docs/MULTI_LAPTOP.md b/docs/MULTI_LAPTOP.md index 19270fc..9b00ae9 100644 --- a/docs/MULTI_LAPTOP.md +++ b/docs/MULTI_LAPTOP.md @@ -278,8 +278,9 @@ to hit. "Preflight says" is the text after `unreachable`; "logs say" is from the ## For the organiser -**Join codes (the quick way).** Start the hub (`make hub`, step 2 below; the hub kit -from `provision.py` is still how the hub gets its keys), open the dashboard and log in +**Join codes (the quick way).** Make your kits with only your own hospital in +`--peers` (step 1 below: the hub kit from `provision.py` is still how the hub gets +its keys; everyone else joins with a code), start the hub (step 2), open the dashboard and log in as `admin` (set `MEDCHAIN_ADMIN_PASSWORD`, at least 10 characters, in `hub.env` first: without it nobody can log in). On **JOIN CODES**, press **Create a join code**: it is shown once. Give it to one friend with the install command the page shows (it has your hub's @@ -316,7 +317,8 @@ code needed. **Postgres already running on the hub laptop?** Set `POSTGRES_PORT` `hub.env`. You run the **hub** (the directory, the observer, Postgres and the dashboard) from -a checkout of this repository. Run it with Docker on your own laptop. +a checkout of this repository, or the release's source zip, unpacked. Run it with +Docker on your own laptop. Docker is all you need: no Python, no `make`. 1. **Make the kits.** List every hospital with the address the others will reach it at (including any you run yourself, like `hospital-d` here), and your @@ -328,16 +330,33 @@ a checkout of this repository. Run it with Docker on your own laptop. --directory sam-laptop.tail1234.ts.net:8100 ``` + If everyone else will join with a join code, list only your own hospital: + `--peers hospital-d=sam-laptop.tail1234.ts.net:8004`. + + **No Python?** Run the same command inside the published image, from the + repository folder (it works in PowerShell and in a Mac or Linux terminal; on + Linux add `--user "$(id -u):$(id -g)"` after `--rm` so the kits belong to you): + + ```sh + docker run --rm -v "${PWD}:/src" -w /src ghcr.io/denimworld12/medchain-node:v1.1.0 python scripts/provision.py --zip --peers hospital-d=sam-laptop.tail1234.ts.net:8004 --directory sam-laptop.tail1234.ts.net:8100 + ``` + This writes `kits/hospital-a.zip` and so on, plus `kits/directory/`, your hub kit with a filled `hub.env`. It also prints the network's shared secret; keep it. Send each hospital its own zip privately. A kit holds that hospital's keys. -2. **Start the hub:** `make hub`. This is - `docker compose --project-directory . --env-file kits/directory/hub.env -f deploy/hub.yml up -d --wait`. +2. **Start the hub:** `make hub`. Without `make` (a stock Windows laptop has none), + run what it runs, from the repository folder: + + ```sh + docker compose --project-directory . --env-file kits/directory/hub.env -f deploy/hub.yml up -d --wait + ``` + The dashboard is at . Postgres listens on this laptop only. The directory and the observer listen on `HUB_BIND_IP`: your Tailscale IP, if `--directory` was one, or every interface otherwise. 3. **Run a hospital yourself**, for example the mid-run joiner: - `make node KIT=kits/hospital-d`. This is the same `deploy/node.yml` a friend runs. + `make node KIT=kits/hospital-d`. This is the same `deploy/node.yml` a friend runs; + without `make`: `docker compose --project-directory kits/hospital-d -f kits/hospital-d/deploy/node.yml up -d`. 4. **Start training** from the dashboard, or from any hospital with the `curl` command in its kit's `README.md`. diff --git a/scripts/provision.py b/scripts/provision.py index 21f02cc..5cea4c4 100644 --- a/scripts/provision.py +++ b/scripts/provision.py @@ -25,7 +25,14 @@ `--peers` lists every hospital with the address its neighbours reach it at (a LAN IP, a Tailscale MagicDNS name, a domain); the order is the directory's placement order while -no run is in progress. Every link is HTTPS: each address goes into that hospital's +no run is in progress. One hospital is enough (the organiser's own) when the others will +enroll with join codes from the dashboard. + +Only Docker installed (no Python)? Run it inside the published node image, from the +repository (or its source zip) folder; the kits land in ./kits as usual: + + docker run --rm -v "${PWD}:/src" -w /src ghcr.io/denimworld12/medchain-node:v1.1.0 \ + python scripts/provision.py --zip --peers ... --directory ... Every link is HTTPS: each address goes into that hospital's certificate, issued by the network CA kept in `--pki` (default kits/.pki). Nodes push their telemetry to the observer (`--observer`, default the directory's host on port 8200) with its token and pin its key; no kit holds database credentials. Re-running @@ -91,8 +98,8 @@ def parse_peers(spec: str) -> dict[str, str]: if node_id in peers or node_id in (DIRECTORY, OBSERVER): raise ValueError(f"--peers lists {node_id} twice" if node_id in peers else f"{node_id!r} is reserved") peers[node_id] = parse_url(node_id, addr) - if len(peers) < 2: - raise ValueError("--peers needs at least two hospitals (a chain)") + if not peers: + raise ValueError("--peers needs at least one hospital (your own; join codes add the others later)") return peers diff --git a/tests/unit/test_install_ps1.py b/tests/unit/test_install_ps1.py new file mode 100644 index 0000000..2ffc3f9 --- /dev/null +++ b/tests/unit/test_install_ps1.py @@ -0,0 +1,168 @@ +"""deploy/install/install.ps1, run for real by PowerShell 7 (pwsh) with docker and tailscale stubbed on PATH. + +The docker stub records the exact arguments each call receives, one argv entry per field, and answers +`compose ... up` the way Docker Compose does: anything after `up` that is not a flag it knows is a service +name, and an unknown service fails with "no such service". A splatting slip that hands Docker a string one +character at a time therefore fails here exactly as it does on a real laptop. +""" + +import os +import shutil +import socket +import subprocess +import textwrap +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +INSTALLER = ROOT / "deploy" / "install" / "install.ps1" +CODE = "ABCD-EFGH-JKMN-PQRS-TVWX" + +pytestmark = pytest.mark.skipif(shutil.which("pwsh") is None or shutil.which("bash") is None, + reason="needs pwsh (PowerShell 7) and bash") + +SEP = "\x1f" +STUBS = { + "docker": f"""\ + {{ printf '%s{SEP}' "$@"; printf '\\n'; }} >>"$STUB_LOG" + case " $* " in *" exec "*) echo "registration"; exit "${{REGISTER_EXIT:-0}}" ;; esac + case " $* " in *" down "*) exit 0 ;; esac + if [ "$1" = compose ]; then + seen_up="" + for a in "$@"; do + if [ -n "$seen_up" ]; then + case "$a" in -d|--detach|--force-recreate|--wait) ;; *) echo "no such service: $a" >&2; exit 1 ;; esac + fi + [ "$a" = up ] && seen_up=1 + done + exit 0 + fi + case "$1" in + run) + kit=$(printf '%s\\n' "$@" | sed -n 's/:\\/kit$//p') + if [ "${{ENROLL_EXIT:-0}}" = 0 ]; then + mkdir -p "$kit/pki/$ENROLLED_ID" && echo cert >"$kit/pki/$ENROLLED_ID/tls.crt" + printf 'NODE_ID=%s\\nNODE_PORT=8000\\n' "$ENROLLED_ID" >"$kit/.env" + fi + exit "${{ENROLL_EXIT:-0}}" ;; + esac + exit 0""", + "tailscale": """\ + echo '{"BackendState": "Running", "Self": {"TailscaleIPs": ["100.101.1.7", "fd7a::7"], + "DNSName": "friend-laptop.tail1234.ts.net.", "HostName": "friend-laptop"}}'""", +} + + +@pytest.fixture +def hub(): + """Something listening where the hub would be: the installer only checks that it answers a TCP connect.""" + s = socket.socket() + s.bind(("127.0.0.1", 0)) + s.listen(16) + yield f"127.0.0.1:{s.getsockname()[1]}" + s.close() + + +def stub_env(tmp_path, hub, env): + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + for name, body in STUBS.items(): + (bin_dir / name).write_text("#!/usr/bin/env bash\n" + textwrap.dedent(body) + "\n") + (bin_dir / name).chmod(0o755) + clean = {k: v for k, v in os.environ.items() if not k.startswith("MEDCHAIN_")} + return {**clean, "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", "HOME": str(tmp_path), + "STUB_LOG": str(tmp_path / "calls.log"), "MEDCHAIN_DIR": str(tmp_path / "MedChain"), "MEDCHAIN_HUB": hub, + "MEDCHAIN_REGISTER_TRIES": "1", "ENROLLED_ID": "st-marys-3f9a", **env} + + +def calls(tmp_path): + log = tmp_path / "calls.log" + return [line.split(SEP)[:-1] for line in log.read_text().splitlines()] if log.exists() else [] + + +def run_installer(tmp_path, hub, *, how=("-File", str(INSTALLER)), **env): + r = subprocess.run(["pwsh", "-NoProfile", "-NonInteractive", *how], env=stub_env(tmp_path, hub, env), + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120) + return r, calls(tmp_path) + + +def enrolled_kit(tmp_path): + kit = tmp_path / "MedChain" + (kit / "pki" / "st-marys-3f9a").mkdir(parents=True) + (kit / "pki" / "st-marys-3f9a" / "tls.crt").write_text("cert") + (kit / ".env").write_text("NODE_ID=st-marys-3f9a\nNODE_PORT=8000\nSHARED_SECRET_FILE=/pki/x\n") + return kit + + +def compose_up(argvs): + ups = [a for a in argvs if a[:1] == ["compose"] and "up" in a] + assert len(ups) == 1, argvs + return ups[0][ups[0].index("up"):] + + +def test_a_rerun_passes_force_recreate_to_docker_as_one_argument(tmp_path, hub): + """The bug from issue #11: `--force-recreate` reached Docker as - - f o r c e ... and every re-run failed.""" + kit = enrolled_kit(tmp_path) + r, argvs = run_installer(tmp_path, hub) + assert r.returncode == 0, r.stdout + r.stderr + assert compose_up(argvs) == ["up", "-d", "--force-recreate"] + assert "no such service" not in r.stdout + r.stderr and "Done. This laptop is running hospital st-marys-3f9a" in r.stdout + assert not any(a[:1] == ["run"] for a in argvs), "no new enrollment" + env = dict(line.split("=", 1) for line in (kit / ".env").read_text().splitlines()) + assert env["ADVERTISE_ADDR"] == "100.101.1.7:8000" and env["SHARED_SECRET_FILE"] == "/pki/x" + + +def test_a_first_install_enrolls_then_starts_without_recreating(tmp_path, hub): + r, argvs = run_installer(tmp_path, hub, MEDCHAIN_DISPLAY_NAME="St Mary's", MEDCHAIN_JOIN_CODE=CODE) + assert r.returncode == 0, r.stdout + r.stderr + assert compose_up(argvs) == ["up", "-d"] + verbs = [a[0] for a in argvs] + assert verbs.index("pull") < verbs.index("run"), "it downloads the image it enrolls with" + assert "Done. This laptop is running hospital st-marys-3f9a" in r.stdout + assert CODE not in r.stdout + r.stderr, "it never prints the join code" + + +def test_a_removed_laptop_rerun_is_told_so_and_stopped(tmp_path, hub): + enrolled_kit(tmp_path) + r, argvs = run_installer(tmp_path, hub, REGISTER_EXIT="3") + assert r.returncode == 1, r.stdout + r.stderr + out = r.stdout + r.stderr + assert "organiser removed this laptop" in out and "new join code" in out and "Done" not in out + assert "has been stopped" in out and "Nothing has been changed" not in out + up = next(i for i, a in enumerate(argvs) if a[:1] == ["compose"] and "up" in a) + check = next(i for i, a in enumerate(argvs) if "node.registered" in a) + assert "--force-recreate" in argvs[up] and up < check + assert argvs[-1][-1] == "down", "the refused node is stopped, not left retrying" + + +@pytest.mark.parametrize("env, says", [ + ({"MEDCHAIN_DISPLAY_NAME": "St Mary's"}, "No join code given"), + ({"MEDCHAIN_DISPLAY_NAME": "St Mary's", "MEDCHAIN_JOIN_CODE": "ABCD-EFGH"}, "That is not a join code"), + ({"MEDCHAIN_DISPLAY_NAME": "S", "MEDCHAIN_JOIN_CODE": CODE}, "2 to 60 characters"), +]) +def test_a_bad_name_or_code_fails_before_the_download(tmp_path, hub, env, says): + r, argvs = run_installer(tmp_path, hub, **env) + assert r.returncode == 1, r.stdout + r.stderr + assert says in r.stdout + r.stderr + assert not any(a[:1] in (["pull"], ["run"]) for a in argvs), "nothing is downloaded or enrolled" + assert not (tmp_path / "MedChain").exists() + + +def test_every_failure_exits_non_zero(tmp_path, hub): + r, argvs = run_installer(tmp_path, hub, MEDCHAIN_DISPLAY_NAME="St Mary's", MEDCHAIN_JOIN_CODE=CODE, ENROLL_EXIT="1") + assert r.returncode == 1 and "Enrollment failed" in r.stdout + r.stderr + assert not any(a[:1] == ["compose"] and "up" in a for a in argvs), "nothing is started" + # a one-off `pwsh -Command` piping it into iex, as a script would run the dashboard's command + r, _ = run_installer(tmp_path, hub, how=("-Command", f"Get-Content -Raw '{INSTALLER}' | Invoke-Expression"), + MEDCHAIN_DISPLAY_NAME="St Mary's") + assert r.returncode == 1 and "No join code given" in r.stdout + r.stderr + + +def test_pasted_into_an_open_window_it_sets_lastexitcode_instead_of_closing_it(tmp_path, hub): + r = subprocess.run(["pwsh", "-NoProfile", "-NoExit", "-Command", + f"Get-Content -Raw '{INSTALLER}' | Invoke-Expression; Write-Host \"still open, LASTEXITCODE=$LASTEXITCODE\""], + env=stub_env(tmp_path, hub, {"MEDCHAIN_DISPLAY_NAME": "St Mary's"}), + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120) + assert "No join code given" in r.stdout + r.stderr + assert "still open, LASTEXITCODE=1" in r.stdout, r.stdout + r.stderr diff --git a/tests/unit/test_install_sh.py b/tests/unit/test_install_sh.py index 9920b2e..e4c51b8 100644 --- a/tests/unit/test_install_sh.py +++ b/tests/unit/test_install_sh.py @@ -74,6 +74,19 @@ def test_an_unattended_install_with_a_taken_name_stops_instead_of_asking(tmp_pat assert [c.split()[1] for c in calls.splitlines()].count("run") == 1 +@pytest.mark.parametrize("env, says", [ + ({"MEDCHAIN_DISPLAY_NAME": "St Mary's"}, "No join code given"), + ({"MEDCHAIN_DISPLAY_NAME": "St Mary's", "MEDCHAIN_JOIN_CODE": "ABCD-EFGH"}, "That is not a join code"), + ({"MEDCHAIN_DISPLAY_NAME": "S", "MEDCHAIN_JOIN_CODE": "ABCD-EFGH-JKMN-PQRS-TVWX"}, "2 to 60 characters"), + ({"MEDCHAIN_JOIN_CODE": "ABCD-EFGH-JKMN-PQRS-TVWX"}, "No hospital name given"), +]) +def test_a_bad_name_or_code_fails_before_the_download(tmp_path, env, says): + r, calls = run_installer(tmp_path, **env) + assert r.returncode == 1 and says in r.stderr + assert not any(c.split()[1] in ("pull", "run") for c in calls.splitlines()), "nothing is downloaded or enrolled" + assert not (tmp_path / "MedChain").exists() + + def test_a_rerun_with_medchain_port_moves_the_enrolled_node_without_a_new_code(tmp_path): kit = tmp_path / "MedChain" (kit / "pki" / "st-marys-3f9a").mkdir(parents=True) @@ -100,6 +113,7 @@ def test_a_hospital_the_organiser_removed_is_told_so_instead_of_done(tmp_path): r, calls = run_installer(tmp_path, REGISTER_EXIT="3") assert r.returncode == 1 and "Done" not in r.stdout assert "organiser removed this computer" in r.stderr and "new join code" in r.stderr + assert "has been stopped" in r.stderr and "Nothing has been changed" not in r.stderr assert calls.splitlines()[-1].endswith("down"), "the refused node is stopped, not left retrying" # the node checks in with the hub only when it starts: a re-run recreates it before asking, so a node that # kept running since before the removal is not reported as registered diff --git a/tests/unit/test_provision.py b/tests/unit/test_provision.py index 217bb04..8ce3b7b 100644 --- a/tests/unit/test_provision.py +++ b/tests/unit/test_provision.py @@ -226,8 +226,17 @@ def test_a_changed_address_gets_a_new_certificate(tmp_path): assert "100.101.1.77" in sans(tmp_path / "hospital-a" / "pki/hospital-a/tls.crt") +def test_the_organisers_own_hospital_alone_is_enough_when_join_codes_add_the_rest(tmp_path, monkeypatch): + assert provision.main(["--peers", "hospital-a=100.101.1.99:8001", "--directory", DIRECTORY, + "--out", str(tmp_path)]) == 0 + assert kit_config(tmp_path / "hospital-a", monkeypatch).port == 8001 + d = tmp_path / "directory" + assert [h["id"] for h in yaml.safe_load((d / "pki/directory/hospitals.yaml").read_text())] == ["hospital-a"] + assert yaml.safe_load((d / "config/directory.yaml").read_text())["enrollment"]["ca_key"] == "/pki/ca.key" + + @pytest.mark.parametrize("peers, extra", [ - ("hospital-a=10.0.0.1:8001", []), # not a chain + (" , ", []), # no hospital at all ("hospital-a=10.0.0.1:8001,hospital-a=10.0.0.2:8001", []), # duplicate id ("hospital-a=ftp://10.0.0.1:8001,hospital-b=10.0.0.2:8002", []), # not https ("hospital-a=http://10.0.0.1:8001,hospital-b=10.0.0.2:8002", []), # plain HTTP is not allowed From 23ce65db2235ca279747a93a99932e8dd8d189ad Mon Sep 17 00:00:00 2001 From: Denimworld12 <166978100+Denimworld12@users.noreply.github.com> Date: Sun, 11 Oct 2026 20:02:18 +0530 Subject: [PATCH 2/2] no-mistakes(review): Fix PowerShell provision command and provision.py docstring example --- README.md | 3 +-- scripts/provision.py | 6 ++++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8bccada..729b82d 100644 --- a/README.md +++ b/README.md @@ -612,8 +612,7 @@ image, from the repository folder (a clone or the release's source zip). The sam command works in PowerShell and in a Mac or Linux terminal: ```sh -docker run --rm -v "${PWD}:/src" -w /src ghcr.io/denimworld12/medchain-node:v1.1.0 \ - python scripts/provision.py --zip --peers hospital-a=sam-laptop.tail1234.ts.net:8001 --directory sam-laptop.tail1234.ts.net:8100 +docker run --rm -v "${PWD}:/src" -w /src ghcr.io/denimworld12/medchain-node:v1.1.0 python scripts/provision.py --zip --peers hospital-a=sam-laptop.tail1234.ts.net:8001 --directory sam-laptop.tail1234.ts.net:8100 ``` On Linux, add `--user "$(id -u):$(id -g)"` after `--rm` so the kits belong to you, not root. The command writes `kits/hospital-a/` ... `kits/hospital-d/` diff --git a/scripts/provision.py b/scripts/provision.py index 5cea4c4..e87c830 100644 --- a/scripts/provision.py +++ b/scripts/provision.py @@ -31,8 +31,10 @@ Only Docker installed (no Python)? Run it inside the published node image, from the repository (or its source zip) folder; the kits land in ./kits as usual: - docker run --rm -v "${PWD}:/src" -w /src ghcr.io/denimworld12/medchain-node:v1.1.0 \ - python scripts/provision.py --zip --peers ... --directory ... Every link is HTTPS: each address goes into that hospital's + docker run --rm -v "${PWD}:/src" -w /src ghcr.io/denimworld12/medchain-node:v1.1.0 \\ + python scripts/provision.py --zip --peers ... --directory ... + +Every link is HTTPS: each address goes into that hospital's certificate, issued by the network CA kept in `--pki` (default kits/.pki). Nodes push their telemetry to the observer (`--observer`, default the directory's host on port 8200) with its token and pin its key; no kit holds database credentials. Re-running