diff --git a/.dockerignore b/.dockerignore index 208feb0..35d8284 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,6 @@ .git .venv +.venv-node .claude **/node_modules **/__pycache__ diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml new file mode 100644 index 0000000..b156c9d --- /dev/null +++ b/.github/workflows/image.yml @@ -0,0 +1,123 @@ +name: Node image + +# The multi-arch node image deploy/node.yml and deploy/hub.yml run: +# ghcr.io/denimworld12/medchain-node: linux/amd64 + linux/arm64, IMAGE_VERSION= baked in +# Published when a release tag is pushed (git tag v1.0.0 && git push origin v1.0.0) or run by hand +# (Actions > Node image > Run workflow, with the tag). Pull requests that touch the image only build +# it, on both architectures, without publishing. +# +# Each architecture builds on its own native runner (ubuntu-24.04-arm for arm64): the image trains the +# risk model and installs torch at build time, which is very slow under QEMU emulation. Each job +# pushes its image by digest, then `merge` ties the two into one tag. + +on: + push: + tags: ["v*"] + workflow_dispatch: + inputs: + version: + description: "the tag to publish, e.g. v1.0.0" + required: true + default: v1.0.0 + pull_request: + paths: + - node/Dockerfile + - node/requirements.txt + - .github/workflows/image.yml + +env: + IMAGE: ghcr.io/denimworld12/medchain-node + VERSION: ${{ github.event.inputs.version || (github.ref_type == 'tag' && github.ref_name) || format('pr-{0}', github.event.pull_request.number) }} + PUBLISH: ${{ github.event_name != 'pull_request' }} + +permissions: + contents: read + +jobs: + build: + name: build ${{ matrix.platform }} + strategy: + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-24.04 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v4 + - name: platform slug + run: echo "SLUG=${PLATFORM//\//-}" >> "$GITHUB_ENV" + env: + PLATFORM: ${{ matrix.platform }} + - uses: docker/setup-buildx-action@v3 + - if: env.PUBLISH == 'true' + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - id: build + uses: docker/build-push-action@v6 + with: + context: . + file: node/Dockerfile + platforms: ${{ matrix.platform }} + build-args: IMAGE_VERSION=${{ env.VERSION }} + labels: | + org.opencontainers.image.version=${{ env.VERSION }} + org.opencontainers.image.revision=${{ github.sha }} + outputs: ${{ env.PUBLISH == 'true' && format('type=image,name={0},push-by-digest=true,name-canonical=true,push=true', env.IMAGE) || 'type=cacheonly' }} + cache-from: type=gha,scope=node-${{ env.SLUG }} + cache-to: type=gha,mode=max,scope=node-${{ env.SLUG }} + - if: env.PUBLISH == 'true' + name: export digest + run: | + mkdir -p /tmp/digests + touch "/tmp/digests/${DIGEST#sha256:}" + env: + DIGEST: ${{ steps.build.outputs.digest }} + - if: env.PUBLISH == 'true' + uses: actions/upload-artifact@v4 + with: + name: digest-${{ env.SLUG }} + path: /tmp/digests/* + if-no-files-found: error + retention-days: 1 + + merge: + name: publish ${{ github.event.inputs.version || github.ref_name }} + if: github.event_name != 'pull_request' + needs: build + runs-on: ubuntu-24.04 + permissions: + contents: read + packages: write + steps: + - uses: actions/download-artifact@v4 + with: + path: /tmp/digests + pattern: digest-* + merge-multiple: true + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: tag both architectures as ${{ env.VERSION }} + working-directory: /tmp/digests + run: | + sources=() + for digest in *; do sources+=("$IMAGE@sha256:$digest"); done + docker buildx imagetools create -t "$IMAGE:$VERSION" "${sources[@]}" + - name: check it + run: | + docker buildx imagetools inspect "$IMAGE:$VERSION" + docker buildx imagetools inspect "$IMAGE:$VERSION" --format '{{json .Manifest.Manifests}}' \ + | grep -q '"architecture":"arm64"' diff --git a/.gitignore b/.gitignore index 6c46c9a..664704b 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ data/ecg-images/ kits/ # keys and certificates issued by scripts/pki.py (the compose stack writes them on first start) .pki/ +# make node-native builds its own venv +.venv-node/ diff --git a/Makefile b/Makefile index fd7a744..a69f776 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,5 @@ # MedChain shortcuts. `make up` is exactly the single-machine command from the README. +# `make hub`, `make node` and `make node-native` run the multi-laptop deployment (docs/MULTI_LAPTOP.md). # what `make lint` compares against: the branch point with main (override: make lint BASE=) BASE ?= $(shell git merge-base HEAD origin/main 2>/dev/null || git merge-base HEAD main) @@ -8,11 +9,53 @@ CHANGED_PY = $(filter %.py,$(CHANGED)) CHANGED_JS = $(patsubst dashboard/%,%,$(filter dashboard/%.js dashboard/%.jsx,$(CHANGED))) PYTHON ?= $(if $(wildcard .venv/bin/python),.venv/bin/python,python3) -.PHONY: up lint +# a hospital's kit folder from scripts/provision.py (its .env, pki/, data/, config/) +KIT ?= +KIT_DIR = $(abspath $(KIT)) +# the hub's settings: provision.py writes them into the directory kit (template: deploy/hub.env.example) +HUB_ENV ?= kits/directory/hub.env +# make node-native: a Python 3.10+ to build its own venv from node/requirements.txt +NATIVE_PYTHON ?= $(shell command -v python3.12 || command -v python3.13 || command -v python3) +NATIVE_VENV ?= .venv-node + +.PHONY: up hub node node-native check-kit lint up: docker compose up -d --build --wait +# the organiser's laptop: directory, observer, postgres (loopback only) and the dashboard +hub: + @test -f "$(HUB_ENV)" || { echo "no $(HUB_ENV): run scripts/provision.py first, or copy deploy/hub.env.example there and fill it in"; exit 2; } + docker compose --project-directory . --env-file "$(HUB_ENV)" -f deploy/hub.yml up -d --wait + +# one hospital node in Docker, from its kit (the same as `docker compose --project-directory . -f deploy/node.yml up` inside the kit) +node: check-kit + docker compose --project-directory "$(KIT_DIR)" -f deploy/node.yml up + +# the same node without Docker (when Docker's networking misbehaves): its own venv, the kit's .env, +# and the kit's folders in place of the container paths deploy/node.yml mounts +node-native: check-kit $(NATIVE_VENV)/.installed models/heart-risk.joblib + set -a && . "$(KIT_DIR)/.env" && set +a && \ + export NODE_CONFIG="$(KIT_DIR)/config/node.yaml" DATA_PATH="$(KIT_DIR)/data" \ + TLS_CERT="$(KIT_DIR)/pki/$$NODE_ID/tls.crt" TLS_KEY="$(KIT_DIR)/pki/$$NODE_ID/tls.key" TLS_CA="$(KIT_DIR)/pki/ca.crt" \ + SIGNING_KEY="$(KIT_DIR)/pki/$$NODE_ID/signing.key" DIRECTORY_CREDENTIAL_FILE="$(KIT_DIR)/pki/$$NODE_ID/credential" \ + DIRECTORY_PUBLIC_KEY="file:$(KIT_DIR)/pki/directory/signing.pub" DIRECTORY_TLS_PIN="file:$(KIT_DIR)/pki/directory/tls.crt" \ + OBSERVER_TOKEN_FILE="$(KIT_DIR)/pki/observer/token" OBSERVER_TLS_PIN="file:$(KIT_DIR)/pki/observer/tls.crt" && \ + exec $(NATIVE_VENV)/bin/python -m node + +check-kit: + @test -n "$(KIT)" -a -f "$(KIT_DIR)/.env" || { echo "name a kit folder that has a .env, e.g. make $(MAKECMDGOALS) KIT=kits/hospital-b"; exit 2; } + +$(NATIVE_VENV)/.installed: node/requirements.txt + @"$(NATIVE_PYTHON)" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else "make node-native needs Python 3.10 or newer: pass NATIVE_PYTHON=/path/to/python3.12")' + "$(NATIVE_PYTHON)" -m venv $(NATIVE_VENV) + $(NATIVE_VENV)/bin/pip install -r node/requirements.txt + touch $@ + +# the risk-assessment model the image trains at build time (node/Dockerfile); the ECG model is committed +models/heart-risk.joblib: | $(NATIVE_VENV)/.installed + $(NATIVE_VENV)/bin/python -m node.assess.train_tabular --csv data/cardio/cardio_train.csv --out $@ + # ruff and eslint on changed files only (no repo-wide pass, no reformatting) lint: @if [ -n "$(strip $(CHANGED_PY))" ]; then echo "ruff: $(words $(CHANGED_PY)) file(s)"; $(PYTHON) -m ruff check $(CHANGED_PY); else echo "ruff: no changed Python files"; fi diff --git a/README.md b/README.md index 58e308a..480376e 100644 --- a/README.md +++ b/README.md @@ -550,14 +550,36 @@ behind home and hospital NAT without port forwarding and gives each machine a stable name such as `hospital-b.tail1234.ts.net`. MedChain encrypts and authenticates its own traffic (TLS plus signed updates), so the mesh is for reachability, not for security. Do not expose node ports to the public internet. -A kit's `--bind-ip` publishes the port on one address only, for example the -machine's Tailscale IP. +The hub listens for the hospitals on `HUB_BIND_IP` (its `hub.env`), for example +the hub machine's Tailscale IP. + +**Step by step for a friend's laptop:** [`docs/MULTI_LAPTOP.md`](docs/MULTI_LAPTOP.md) +is the guide for someone who has never used Docker: installing Docker Desktop and +Tailscale, the kit, the preflight, the hotspot fallback and a troubleshooting table. + +### The deployment: one file per laptop + +- `deploy/node.yml` runs one hospital node: a single `node` service from the + published image `ghcr.io/denimworld12/medchain-node:${IMAGE_VERSION}`, configured by + the `.env` next to it. It mounts `./data` at `DATA_PATH` (the slice, checkpoints, + saved membership, `audit.db`), `./pki` read-only and `./config` (the engine settings). + It publishes `NODE_PORT` on every interface. It has no `container_name` and relies on + no Compose DNS: every address comes from `.env` and the directory. +- `deploy/hub.yml` runs the organiser's laptop: the directory, the observer, Postgres + (on `127.0.0.1` only) and the dashboard. +- `deploy/node.env.example` and `deploy/hub.env.example` list their settings, each + with a Tailscale block and a hotspot block that differ only in addresses. +- `make node KIT=kits/hospital-b` and `make hub` run them from a repository checkout. + `make node-native KIT=...` runs the same node without Docker, in its own venv + (`.venv-node`, from `node/requirements.txt`), with the kit's `.env` and folders. +- `.github/workflows/image.yml` builds the image for `linux/amd64` and `linux/arm64`, + each on a native runner, and publishes it to GHCR when a `v*` tag is pushed, with + `IMAGE_VERSION` baked in (`/health` reports it). ### Provision one kit per hospital `scripts/provision.py` follows NVIDIA FLARE's "startup kit" idea. It writes one -self-contained folder (and optionally a zip) per hospital, plus one for the -directory: +self-contained folder (and optionally a zip) per hospital, plus one for the hub: ```sh python scripts/provision.py --zip \ @@ -574,33 +596,36 @@ 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: -- `config/hospital-X.yaml`: its own address, the directory's address, the - observer's address, and one freshly generated shared secret (the same for every kit from the same run; pass - it with `--secret` to provision a hospital later). There is no chain in it: the - directory places the hospital. Engine settings come from the repository's - `config/hospital-X.yaml`. +- `.env`: filled in. `NODE_ID`, `NODE_PORT`, its own address (`ADVERTISE_ADDR`), the + directory's and the observer's, and one freshly generated shared secret (the same + for every kit from the same run; pass it with `--secret` to provision a hospital + later). The hotspot block is there to switch to. There is no chain in it: the + directory places the hospital. +- `deploy/node.yml`, a copy of the repository's. +- `config/node.yaml`: the hospital's display name and engine settings, from the + repository's `config/hospital-X.yaml`. Nothing about where it runs. - `pki/`: only this hospital's own TLS certificate and key (issued for its address), its update-signing key and its directory credential, plus the CA certificate, the directory's public key and the directory's certificate (whose key the node pins), and the observer's certificate (also pinned) and ingest token (`pki/observer/token`). No other party's private key, and no database credentials. -- `docker-compose.hospital.yaml`, which runs only that node. - `data/hospital-X.csv`, that hospital's slice. Pass `--data hospital-X=path.csv` to use different data. -- `source/`, the node's build context. With `--image `, the kit uses a - prebuilt image instead. - `README.md`, with the exact commands, including how to leave the chain. -The directory kit holds the directory's config, its TLS certificate, its -document-signing key and `hospitals.yaml` (who may register: ids and credential -hashes only), plus the observer's TLS certificate, key and token so the hub can -run the observer (its README has the command). Send each kit privately to its operator. Start the directory, then -each hospital, each with one command: +`--image repo[:tag]` names a different image (for example a private registry). By +default the kits use the published `ghcr.io/denimworld12/medchain-node:v1.0.0`. + +The directory kit is the hub's. It holds the directory's config, its TLS certificate, +its document-signing key and `hospitals.yaml` (who may register: ids and credential +hashes only), the observer's TLS certificate, key and token, and a filled `hub.env` +for `deploy/hub.yml`. Send each hospital kit privately to its operator. Start the hub, +then each hospital, each with one command: ```sh -docker compose -f docker-compose.directory.yaml up -d --build --wait # on the directory machine -docker compose -f docker-compose.hospital.yaml up -d --build --wait # on each hospital machine +make hub # on the hub, from the repository +docker compose --project-directory . -f deploy/node.yml up -d # on each hospital machine, in its kit ``` Start training from any one node (`POST /round/start`, as above). The start @@ -612,27 +637,28 @@ it and start it: ```sh python scripts/provision.py --hospital hospital-e --secret \ --peers ,hospital-e=hospital-e.tail1234.ts.net:8005 --directory directory.tail1234.ts.net:8100 -# copy kits/.pki/directory/hospitals.yaml to the directory machine's kits/directory/pki/directory/ +# copy kits/.pki/directory/hospitals.yaml to the hub's kits/directory/pki/directory/ # (re-read on every registration, no restart); send kits/hospital-e/ to its operator, who runs: -docker compose -f docker-compose.hospital.yaml up -d --build --wait +docker compose --project-directory . -f deploy/node.yml up -d ``` The node registers; if a run is going, the directory appends it at the end of the chain from a round boundary a few rounds ahead, and it joins the run. -**Removing a hospital for real.** On that hospital's machine: +**Removing a hospital for real.** On that hospital's machine, in its kit: ```sh -docker compose -f docker-compose.hospital.yaml exec hospital-b python -m node.leave -docker compose -f docker-compose.hospital.yaml down +docker compose --project-directory . -f deploy/node.yml exec node python -m node.leave +docker compose --project-directory . -f deploy/node.yml down ``` The directory takes it out at the next boundary and its neighbours bridge. To stop it from ever registering again, delete its line from `hospitals.yaml`. -**Changing an address without re-provisioning.** `ADVERTISE_ADDR` (alias -`MEDCHAIN_ADVERTISE_URL`) replaces a node's own address and `DIRECTORY_URL` -(alias `MEDCHAIN_DIRECTORY_URL`) the directory's, from the environment. On restart the node re-registers its new address and the +**Changing an address without re-provisioning.** Edit `ADVERTISE_ADDR` (alias +`MEDCHAIN_ADVERTISE_URL`), a node's own address, or `DIRECTORY_URL` (alias +`MEDCHAIN_DIRECTORY_URL`), the directory's, in the kit's `.env` and run `up -d` again. +That is all the hotspot fallback does. On restart the node re-registers its new address and the directory passes it to its neighbours. Node-to-node links pin the certificate's key, not its address, so they keep working. Only the dashboard's relay checks the address. For the relay, re-run `provision.py` for that hospital with the new @@ -641,17 +667,9 @@ in its YAML, no `directory:`, as the tests use) still takes `MEDCHAIN_PEER__URL` for each neighbour: `` is the node id upper-cased, with `-` and other characters turned into `_`. -**The observer is optional.** The dashboard and its Postgres can run on any one -machine: - -```sh -MEDCHAIN_SHARED_SECRET= NODE_EXTRA_CA_CERTS=kits/.pki/ca.crt docker compose up -d postgres dashboard -``` - -Kit nodes push their telemetry to the observer (`--observer`, by default the -directory's host on port 8200), which the hub runs next to Postgres from the -directory kit; `--observer-db` instead points the nodes straight at a Postgres -URL, as a fallback. It never coordinates training. A node with no observer still +**The observer only observes.** Kit nodes push their telemetry to the observer +(`--observer`, by default the directory's host on port 8200), which `deploy/hub.yml` +runs next to Postgres. It never coordinates training. A node with no observer still trains and still serves `/status` and `/metrics`. ### Prove it @@ -896,13 +914,15 @@ docs/screenshots/ models/ scripts/ Makefile - `make up` runs the single-machine stack (`docker compose up -d --build --wait`). `make lint` runs ruff (`ruff.toml`) and eslint (`dashboard/eslint.config.js`) on the files changed since the branch point with main only. CI does the same - for each change. There is no repo-wide reformatting. + for each change. There is no repo-wide reformatting. `make hub`, `make node` and + `make node-native` run the multi-laptop deployment in `deploy/` + ([`docs/MULTI_LAPTOP.md`](docs/MULTI_LAPTOP.md)). - `observer/` is the telemetry ingest service (`python -m observer`, same image). - `directory/` is the membership directory (`python -m directory`, same image as the nodes). `scripts/pki.py` issues the CA, certificates, signing keys and directory credentials (the compose `pki` service runs it). -- `scripts/provision.py` writes the per-hospital and directory kits, +- `scripts/provision.py` writes the per-hospital and hub kits for `deploy/`, `scripts/preflight.py` reports each neighbour's path (direct or DERP-relayed), and `scripts/verify_multihost.py` checks a run across real addresses (see [Running on separate machines](#running-on-separate-machines)). diff --git a/deploy/hub.env.example b/deploy/hub.env.example new file mode 100644 index 0000000..dc9a2f3 --- /dev/null +++ b/deploy/hub.env.example @@ -0,0 +1,25 @@ +# MedChain hub settings, read by deploy/hub.yml (`make hub`). scripts/provision.py writes a +# filled copy to /directory/hub.env; docs/MULTI_LAPTOP.md walks through it. + +# The directory kit from scripts/provision.py (its config/ and pki/): ./ and relative to the repo +# root, or an absolute path +HUB_KIT=./kits/directory +# The network's shared secret, printed by provision.py (the dashboard's Start / Pause relay sends it) +MEDCHAIN_SHARED_SECRET=change-me-the-provisioned-secret +IMAGE_VERSION=v1.0.0 +# The ports in the directory's and the observer's addresses (provision.py --directory / --observer) +DIRECTORY_PORT=8100 +OBSERVER_PORT=8200 +# The dashboard, on this laptop only: http://localhost:8080 +DASHBOARD_BIND_IP=127.0.0.1 +DASHBOARD_PORT=8080 + +# ======== Tailscale (the normal way) ======== +# Listen for the hospitals on this laptop's Tailscale IP only (`tailscale ip -4`). +# 0.0.0.0 (every interface) also works. +HUB_BIND_IP=100.101.1.99 + +# ======== Phone hotspot (fallback) ======== +# To switch: put a # in front of the Tailscale line above and remove it below. The hotspot +# hands out addresses that can change, so listen on every interface. +#HUB_BIND_IP=0.0.0.0 diff --git a/deploy/hub.yml b/deploy/hub.yml new file mode 100644 index 0000000..75b7770 --- /dev/null +++ b/deploy/hub.yml @@ -0,0 +1,104 @@ +# The MedChain hub: what the organiser's laptop runs (docs/MULTI_LAPTOP.md). The hospitals +# run deploy/node.yml on their own laptops. +# +# directory membership only: where a hospital sits in the chain, who bridges a leave +# observer takes the nodes' pushed telemetry into Postgres (training never waits for it) +# postgres the dashboard's database, on this machine's loopback only +# dashboard http://localhost:8080 +# +# From the repository root, after `python scripts/provision.py ...` wrote kits/ (the +# directory kit holds the directory's and observer's keys and a filled `hub.env`): +# +# make hub # = docker compose --project-directory . --env-file kits/directory/hub.env -f deploy/hub.yml up -d --wait +# +# deploy/hub.env.example lists the settings. HUB_KIT is the directory kit's folder. + +name: medchain-hub + +x-medchain: &medchain + image: ${MEDCHAIN_IMAGE:-ghcr.io/denimworld12/medchain-node}:${IMAGE_VERSION:-v1.0.0} + restart: unless-stopped + +services: + postgres: + image: postgres:16-alpine + environment: + POSTGRES_USER: medchain + POSTGRES_PASSWORD: medchain + POSTGRES_DB: medchain + ports: + - "127.0.0.1:5432:5432" # loopback only: hospitals never connect to Postgres, the observer does + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U medchain -d medchain"] + interval: 2s + timeout: 3s + retries: 30 + restart: unless-stopped + + directory: + <<: *medchain + command: ["python", "-m", "directory"] + environment: + DIRECTORY_CONFIG: /config/directory.yaml + volumes: + - ${HUB_KIT:?set HUB_KIT (the directory kit folder) in hub.env}/config/directory.yaml:/config/directory.yaml:ro + - ${HUB_KIT}/pki:/pki:ro + - directory-data:/data + ports: + # must be the port in the directory's address (its kit's config/directory.yaml) + - "${HUB_BIND_IP:-0.0.0.0}:${DIRECTORY_PORT:-8100}:${DIRECTORY_PORT:-8100}" + healthcheck: + test: ["CMD", "python", "-c", "import ssl,urllib.request,yaml;p=yaml.safe_load(open('/config/directory.yaml'))['port'];urllib.request.urlopen(f'https://127.0.0.1:{p}/health',timeout=2,context=ssl._create_unverified_context())"] + interval: 5s + timeout: 3s + retries: 10 + + observer: + <<: *medchain + command: ["python", "-m", "observer"] + environment: + DATABASE_URL: postgresql://medchain:medchain@postgres:5432/medchain + OBSERVER_PORT: ${OBSERVER_PORT:-8200} + OBSERVER_TOKEN_FILE: /pki/observer/token + TLS_CERT: /pki/observer/tls.crt + TLS_KEY: /pki/observer/tls.key + TLS_CA: /pki/ca.crt + volumes: + - ${HUB_KIT}/pki:/pki:ro + depends_on: + postgres: + condition: service_healthy + ports: + - "${HUB_BIND_IP:-0.0.0.0}:${OBSERVER_PORT:-8200}:${OBSERVER_PORT:-8200}" + healthcheck: + test: ["CMD", "python", "-c", "import os,ssl,urllib.request;urllib.request.urlopen(f\"https://127.0.0.1:{os.environ['OBSERVER_PORT']}/health\",timeout=2,context=ssl._create_unverified_context())"] + interval: 5s + timeout: 3s + retries: 10 + + dashboard: + build: + context: . + dockerfile: dashboard/Dockerfile + image: medchain-dashboard:latest + environment: + DATABASE_URL: postgresql://medchain:medchain@postgres:5432/medchain + HEARTBEAT_STALE_S: "15" + # the network's shared secret (from provision.py), for the Start / Pause / Assess relay + MEDCHAIN_SHARED_SECRET: ${MEDCHAIN_SHARED_SECRET:?set MEDCHAIN_SHARED_SECRET (the kits' shared secret) in hub.env} + # the relay reaches the hospitals over HTTPS at their registered addresses: trust the network CA + NODE_EXTRA_CA_CERTS: /pki/ca.crt + volumes: + - ${HUB_KIT}/pki/ca.crt:/pki/ca.crt:ro + depends_on: + postgres: + condition: service_healthy + ports: + - "${DASHBOARD_BIND_IP:-127.0.0.1}:${DASHBOARD_PORT:-8080}:8080" + restart: unless-stopped + +volumes: + postgres-data: + directory-data: diff --git a/deploy/node.env.example b/deploy/node.env.example new file mode 100644 index 0000000..ada32ec --- /dev/null +++ b/deploy/node.env.example @@ -0,0 +1,29 @@ +# MedChain hospital node settings, read by deploy/node.yml (and by `make node-native`). +# A kit from scripts/provision.py comes with this file already filled in as `.env`; +# docs/MULTI_LAPTOP.md walks through it. node/settings.py lists every variable. + +# ---- Which hospital this laptop is: check it matches what the organiser told you ---- +NODE_ID=hospital-b +NODE_PORT=8002 + +# ======== Tailscale (the normal way) ======== +# This laptop's MagicDNS name (or Tailscale IP, `tailscale ip -4`), with NODE_PORT: +ADVERTISE_ADDR=hospital-b-laptop.tail1234.ts.net:8002 +# The organiser's laptop (the hub), which runs the directory and the observer: +DIRECTORY_URL=https://organiser-laptop.tail1234.ts.net:8100 +OBSERVER_URL=https://organiser-laptop.tail1234.ts.net:8200 + +# ======== Phone hotspot (fallback) ======== +# To switch: put a # in front of the three Tailscale lines above, remove the # from the +# three lines below, and use the IP addresses the hotspot gave each laptop. +#ADVERTISE_ADDR=192.168.43.21:8002 +#DIRECTORY_URL=https://192.168.43.10:8100 +#OBSERVER_URL=https://192.168.43.10:8200 + +# ---- The network: filled in by the kit, the same on every laptop. Don't change. ---- +SHARED_SECRET=change-me-the-kit-fills-this-in +IMAGE_VERSION=v1.0.0 +# Rounds over a real network take longer than on one machine: give each one time. +ROUND_TIMEOUT_S=15 +HTTP_CONNECT_TIMEOUT_S=5 +HTTP_READ_TIMEOUT_S=10 diff --git a/deploy/node.yml b/deploy/node.yml new file mode 100644 index 0000000..3ac776a --- /dev/null +++ b/deploy/node.yml @@ -0,0 +1,48 @@ +# One MedChain hospital node: the file a hospital's laptop runs (docs/MULTI_LAPTOP.md). +# +# Run it from the folder that holds `.env`, `pki/`, `data/` and `config/` (an unzipped kit +# from scripts/provision.py): +# +# docker compose --project-directory . -f deploy/node.yml up +# +# `--project-directory .` makes `.env`, `./data`, `./pki` and `./config` mean the kit's +# folders (Compose otherwise resolves them next to this file). From a repo checkout, +# `make node KIT=kits/hospital-b` runs the same thing. +# +# Everything about this hospital and the network comes from `.env` (node/settings.py lists +# every variable). The node publishes NODE_PORT on every interface of this machine, and +# that same NODE_PORT is the port it binds inside the container and the one it advertises, +# so the three can never disagree. Neighbours, the directory and the observer are reached +# at the addresses in `.env` and the directory's documents: there is no container name and +# no Compose network DNS in any of them. + +name: medchain-${NODE_ID:?set NODE_ID in .env, and run from your kit folder with --project-directory .} + +services: + node: + image: ${MEDCHAIN_IMAGE:-ghcr.io/denimworld12/medchain-node}:${IMAGE_VERSION:-v1.0.0} + env_file: .env + # where the kit's files are inside the container (these win over `.env`) + environment: + NODE_CONFIG: /config/node.yaml + DATA_PATH: ${DATA_PATH:-/data} + TLS_CERT: /pki/${NODE_ID}/tls.crt + TLS_KEY: /pki/${NODE_ID}/tls.key + TLS_CA: /pki/ca.crt + SIGNING_KEY: /pki/${NODE_ID}/signing.key + DIRECTORY_CREDENTIAL_FILE: /pki/${NODE_ID}/credential + DIRECTORY_PUBLIC_KEY: file:/pki/directory/signing.pub + DIRECTORY_TLS_PIN: file:/pki/directory/tls.crt + OBSERVER_TOKEN_FILE: /pki/observer/token + OBSERVER_TLS_PIN: file:/pki/observer/tls.crt + volumes: + # this hospital's data slice, checkpoints, saved membership and audit.db + - ./data:${DATA_PATH:-/data} + - ./pki:/pki:ro + - ./config:/config:ro + ports: + - "${NODE_PORT:?set NODE_PORT in .env}:${NODE_PORT}" + # Docker Desktop's DNS cannot always resolve Tailscale MagicDNS names (*.ts.net) inside a + # container. If the preflight or the logs say a .ts.net name does not resolve, use the + # Tailscale IPs (100.x.y.z) in `.env` instead. + restart: unless-stopped diff --git a/docs/MULTI_LAPTOP.md b/docs/MULTI_LAPTOP.md new file mode 100644 index 0000000..1e72096 --- /dev/null +++ b/docs/MULTI_LAPTOP.md @@ -0,0 +1,270 @@ +# Running a MedChain hospital on your laptop + +MedChain trains one shared heart-disease model across several "hospitals" without +any hospital sending its patient data anywhere. For this test, each hospital is a +laptop. Your laptop runs one hospital. It trains on the small data file in your kit, +and the only thing it sends out is model updates, to the one or two laptops next to +it in the chain. + +You do not need to know Docker or programming. You will install two apps, unzip a +folder, check one file, and type three commands. Allow about 30 minutes the first +time, most of it downloads. + +**What the organiser gives you:** + +- a zip file (your **kit**), for example `hospital-b.zip`. It contains your + hospital's private keys, so don't share it. +- an invite to their Tailscale network (a "tailnet"), by email or as a link. +- the names to check in your `.env` file (step 2). + +**What you need:** a laptop (Mac, Windows 10/11 or Linux) with at least 8 GB of +memory, about 5 GB of free disk space, and permission to install apps. Keep it +plugged in. + +## 1. Install Docker Desktop and Tailscale + +**Docker Desktop** runs the hospital program in a sealed box (a "container"), so +you don't have to install Python or anything else. + +1. Download it from . On a Mac, + choose the "Apple silicon" download for M1/M2/M3/M4 Macs, "Intel chip" otherwise + ( > About This Mac tells you which). +2. **Windows only:** Docker Desktop needs **WSL 2** (Windows' built-in Linux). Leave + "Use WSL 2 instead of Hyper-V" ticked in the installer. If Docker Desktop later + says WSL is missing or out of date, open **PowerShell as administrator**, run + `wsl --install` (or `wsl --update`), and restart the laptop. +3. Open Docker Desktop and wait until the bottom-left corner says **Engine running**. + You can skip signing in to Docker. + +**Tailscale** connects the laptops to each other privately, wherever they are, +without touching your router. + +1. Download it from and sign in. +2. Open the organiser's invite and accept it. Your laptop is now on their tailnet. +3. In the Tailscale menu (menu bar on a Mac, system tray on Windows), you should see + the organiser's laptop listed. Your own laptop's **MagicDNS name** is shown under + "This device", something like `alex-laptop.tail1234.ts.net`. If the organiser + asks for it, send it to them. + +## 2. Unzip your kit and check `.env` + +Unzip the kit somewhere easy to find, for example your Documents folder. You get a +folder like `hospital-b` containing: + +| In the folder | What it is | +| --- | --- | +| `.env` | your hospital's settings: the only file you may need to touch | +| `deploy/node.yml` | tells Docker how to run your hospital | +| `pki/` | your hospital's keys and certificates. Don't share them | +| `data/` | your hospital's data file. The node also saves its progress here | +| `config/node.yaml` | the training settings, the same for every hospital | +| `README.md` | a short version of this guide | + +`.env` starts with a dot, so it is hidden: + +- **Mac:** in Finder press Cmd+Shift+. to show hidden + files. Right-click `.env` > Open With > TextEdit. +- **Windows:** right-click `.env` > Open with > Notepad. + +The kit has already filled in everything. Check only these lines against what the +organiser told you, and correct them if they differ: + +```ini +NODE_ID=hospital-b # your hospital +ADVERTISE_ADDR=alex-laptop.tail1234.ts.net:8002 # YOUR laptop's MagicDNS name, then the port +DIRECTORY_URL=https://sam-laptop.tail1234.ts.net:8100 # the organiser's laptop +OBSERVER_URL=https://sam-laptop.tail1234.ts.net:8200 # the organiser's laptop +``` + +Keep the `:8002`-style port numbers exactly as the kit wrote them. Don't change +anything under "The network". Save the file. In TextEdit, if it asks, keep the name +`.env` and plain text. Don't let it add `.txt`. + +## 3. Start your hospital and run the preflight + +Open a terminal: **Terminal** on a Mac (Applications > Utilities), **PowerShell** on +Windows. Go into your kit folder: type `cd ` (with a space), drag the kit folder +onto the terminal window, and press Enter. + +**Start the hospital** (the first time, this downloads the MedChain program, a +couple of gigabytes): + +```sh +docker compose --project-directory . -f deploy/node.yml up -d +``` + +**Run the preflight**, which checks that your hospital can reach its neighbours: + +```sh +docker compose --project-directory . -f deploy/node.yml exec node python scripts/preflight.py +``` + +The preflight asks your running hospital who its neighbours are, then tries to reach +each one from inside the container, the same way training will. That's why the +hospital has to be started first. + +- `hospital-b: chain (not placed yet)` and `no neighbours yet`: the organiser hasn't + started the other hospitals yet, or the directory hasn't placed you yet. Wait a + minute and run it again. +- `hospital-b <-> hospital-a unknown no tailscale command on this PATH ...`: **good.** The + neighbour answered. ("unknown" only means the preflight can't see from inside the + container whether Tailscale goes direct or through a relay.) +- `hospital-b <-> hospital-a unreachable ConnectError: ...`: **not good.** The + text after "unreachable" says why. Look it up in [Troubleshooting](#troubleshooting). + +**Watch it work** (press Ctrl+C to stop watching; the +hospital keeps running): + +```sh +docker compose --project-directory . -f deploy/node.yml logs -f +``` + +The organiser starts training for everyone and watches it on their dashboard. + +## 4. Keep the laptop awake + +A hospital that falls asleep drops out of the chain. Its neighbours carry on, but +training gets worse until it comes back. + +- Keep the laptop **plugged in** and the **lid open**. +- **Mac:** System Settings > Battery > Options: turn on "Prevent automatic sleeping on + power adapter when the display is off". Or leave a Terminal window running + `caffeinate -dis` for the session. +- **Windows:** Settings > System > Power & battery > Screen and sleep: set "When + plugged in, put my device to sleep after" to **Never**. +- Leave Docker Desktop and Tailscale running. + +If it does sleep, wake it up. Docker restarts the hospital by itself and it rejoins +using the progress saved in `data/`. You don't need to do anything else. + +## When you're done + +To leave the chain politely (your neighbours connect to each other directly), then +stop: + +```sh +docker compose --project-directory . -f deploy/node.yml exec node python -m node.leave +docker compose --project-directory . -f deploy/node.yml down +``` + +To start again later, run the `up -d` command from step 3 again. + +## Hotspot fallback + +If Tailscale can't be used (a network that blocks it, or no internet at all), all +the laptops can join **one phone's hotspot** instead. Only the addresses in `.env` +change; the kit, keys and commands stay the same. Your hospital is recognised by +its key, not its address. + +1. Connect your laptop to the hotspot the organiser names. +2. Find your laptop's address on the hotspot: + - **Mac:** System Settings > Wi-Fi > Details (next to the hotspot) > IP address, + or run `ipconfig getifaddr en0` in Terminal. + - **Windows:** run `ipconfig` in PowerShell and look for "IPv4 Address" under + "Wireless LAN adapter Wi-Fi". +3. The organiser tells you the hub's hotspot address (their laptop's). +4. In `.env`, put a `#` in front of the three Tailscale address lines and remove the + `#` from the three hotspot lines. Then replace the placeholders. With your + address `172.20.10.4` and the hub's `172.20.10.2`, the lines go from: + + ```ini + ADVERTISE_ADDR=alex-laptop.tail1234.ts.net:8002 + DIRECTORY_URL=https://sam-laptop.tail1234.ts.net:8100 + OBSERVER_URL=https://sam-laptop.tail1234.ts.net:8200 + + #ADVERTISE_ADDR=THIS-LAPTOPS-HOTSPOT-IP:8002 + #DIRECTORY_URL=https://HUB-HOTSPOT-IP:8100 + #OBSERVER_URL=https://HUB-HOTSPOT-IP:8200 + ``` + + to: + + ```ini + #ADVERTISE_ADDR=alex-laptop.tail1234.ts.net:8002 + #DIRECTORY_URL=https://sam-laptop.tail1234.ts.net:8100 + #OBSERVER_URL=https://sam-laptop.tail1234.ts.net:8200 + + ADVERTISE_ADDR=172.20.10.4:8002 + DIRECTORY_URL=https://172.20.10.2:8100 + OBSERVER_URL=https://172.20.10.2:8200 + ``` + + Nothing else in `.env` changes. The port numbers stay as they were. +5. Run the `up -d` command from step 3 again. Docker restarts the hospital with the + new addresses, and it tells the directory where it is now. Then run the preflight. + +If the phone gives your laptop a different address later (after a reconnect, for +example), repeat steps 2, 4 and 5 with the new address. To go back to Tailscale, +swap the `#`s back. + +## Troubleshooting + +Each row is a failure that the multi-laptop audit found or that this setup is known +to hit. "Preflight says" is the text after `unreachable`; "logs say" is from the +`logs -f` command. + +| What you see | Why it happens | What to do | +| --- | --- | --- | +| Preflight says `ConnectError ... Name or service not known` (or `nodename nor servname`, `Temporary failure in name resolution`) for a `*.ts.net` neighbour | **Container DNS (audit H15).** Docker Desktop doesn't always pass Tailscale's MagicDNS through to containers, so a `.ts.net` name that works in your browser doesn't resolve inside the hospital's container. | Use Tailscale **IP addresses** (`100.x.y.z`) instead of names. Each laptop's IP is in the Tailscale menu, or run `tailscale ip -4`. Put yours in `ADVERTISE_ADDR` and the hub's in `DIRECTORY_URL`/`OBSERVER_URL`, then run `up -d` again. Your neighbours' addresses are whatever *they* wrote in their `.env`, so tell the organiser; usually everyone switches to IPs. | +| Preflight says `ConnectTimeout` for a neighbour, the neighbour's own preflight says `ConnectTimeout` for you, and the organiser's dashboard shows your hospital never placed in the chain | **Firewall (audit H14).** Your neighbours and the organiser's directory have to connect *in* to your laptop on your port (`NODE_PORT`). A firewall that blocks incoming connections stops them, even though your outgoing connections work. | **Mac:** System Settings > Network > Firewall > Options: allow incoming connections for Docker (`com.docker.backend`). **Windows:** when the "Windows Defender Firewall has blocked some features" box appears for Docker Desktop Backend, tick **Private networks** and allow. Also mark the Wi-Fi network as **Private**. A company-managed laptop may not allow this: use another laptop. | +| On a phone hotspot, **every** neighbour is `ConnectTimeout`, though the internet works | **Hotspot client isolation (audit H16).** Some phones (many Android ones) don't let devices on their hotspot talk to each other ("AP isolation" / "client isolation"). Nothing on the laptops can fix that. | Turn off "AP isolation" / "client isolation" in the phone's hotspot settings if it has the option, or use a different phone (iPhone hotspots let devices talk to each other), or go back to Tailscale. | +| The dashboard shows your hospital as down after a while; the logs stop, then pick up again later | **Sleep (audit ยง3).** A sleeping laptop is a crashed hospital: its neighbours run "degraded" rounds without it. It rejoins on wake from the chain it saved in `data/`, even if the organiser's directory is down. | Step 4: plugged in, lid open, sleep off. After waking, run `docker compose --project-directory . -f deploy/node.yml ps`. If the hospital isn't "running" (Docker Desktop itself quit), open Docker Desktop and run the `up -d` command again. | +| Tailscale is connected but neighbours are `ConnectTimeout`, or `tailscale status` shows the other laptops offline; or rounds are often slow | **Another VPN.** A work or personal VPN (Cisco AnyConnect, GlobalProtect, NordVPN, ...) can take over the routes Tailscale uses (`100.x` addresses) or block it. Tailscale then relays traffic through its servers (DERP, audit H5) or not at all. | Disconnect the other VPN for the session. In the Tailscale menu, check the organiser's laptop shows as connected. A relayed connection still works, just slower. If rounds keep timing out, the organiser can raise `ROUND_TIMEOUT_S` for everyone. | +| Logs say `certificate is not yet valid` or `certificate has expired`; every connection fails | **Clock skew.** The kit's certificates are valid from five minutes before the organiser made them. A laptop clock that is more than about five minutes behind theirs rejects them, and theirs rejects yours. (A wrong clock doesn't make the dashboard mark you down: it uses the hub's own clock.) | Turn on automatic time. **Mac:** System Settings > General > Date & Time > "Set time and date automatically". **Windows:** Settings > Time & language > Date & time > "Set time automatically", then **Sync now**. Then run the `up -d` command again. | +| Logs say `directory registration failed (...); retrying` | The organiser's hub isn't reachable yet: it's not started, it's on another network, or `DIRECTORY_URL` is wrong. | Check `DIRECTORY_URL` with the organiser. The hospital keeps retrying by itself. If it was already training, it carries on meanwhile. | +| Logs or preflight say `TLS key changed` / `tls_pin_mismatch` | Your kit's keys don't match what the directory has on record, usually because you have an older kit than the organiser's latest. | Ask the organiser for your current kit. Don't mix files from two kits. | +| `required variable NODE_ID is missing a value` | The command ran outside the kit folder, or without `--project-directory .`. | `cd` into the kit folder (step 3) and copy the command exactly. | +| `port is already allocated` / `address already in use` | Another program is using your hospital's port. | Quit it, or ask the organiser. Changing the port means changing `NODE_PORT` and the port at the end of `ADVERTISE_ADDR` together. | +| `denied` or `unauthorized` when Docker downloads `ghcr.io/denimworld12/medchain-node` | The MedChain image isn't public. | Ask the organiser: they either make the image public or give you a login (`docker login ghcr.io`). | + +## For the organiser + +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. + +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 + laptop as the directory: + + ```sh + python scripts/provision.py --zip \ + --peers hospital-a=alex-laptop.tail1234.ts.net:8001,hospital-b=kim-laptop.tail1234.ts.net:8002,hospital-c=lee-laptop.tail1234.ts.net:8003,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`. + 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. +4. **Start training** from the dashboard, or from any hospital with the `curl` + command in its kit's `README.md`. + +**Hotspot:** in `kits/directory/hub.env`, swap the `HUB_BIND_IP` lines as the comments +say and run `make hub` again. Then give each friend your hotspot address. The +hospitals' links to each other and to the hub check keys, not addresses, so nobody +needs a new kit. The dashboard's Start/Pause buttons are the exception. They reach +each hospital at its registered address and check that address against the +hospital's certificate, which was issued for its Tailscale name. On a hotspot those +buttons can fail with a certificate error. Start the run with the `curl` command +from a kit's `README.md` instead. Or re-run `provision.py` for that hospital with +its hotspot IP: the key is kept, so the pin is unchanged. + +**Without Docker** (when Docker's networking misbehaves on a laptop): from a checkout of +this repository, with Python 3.10 or newer and `make` (on Windows, inside WSL), +`make node-native KIT=/path/to/the/unzipped/kit`. It creates a virtual environment +`.venv-node`, installs `node/requirements.txt`, trains the risk-assessment model +into `models/` once, and runs the hospital directly with the kit's `.env`, using +the kit's `pki/`, `data/` and `config/` folders in place of the container's. + +**The image** is `ghcr.io/denimworld12/medchain-node:`. It is built for +both Intel/AMD and ARM (Apple silicon) laptops by `.github/workflows/image.yml` when +a `v*` tag is pushed (`git tag v1.0.0 && git push origin v1.0.0`), or from +Actions > Node image > Run workflow. Friends can only download it without a login if +the package is public. To make it public: GitHub > your profile > Packages > +`medchain-node` > Package settings > Change visibility. diff --git a/node/Dockerfile b/node/Dockerfile index 4f18a72..c3abc7b 100644 --- a/node/Dockerfile +++ b/node/Dockerfile @@ -21,8 +21,15 @@ COPY node /app/node COPY directory /app/directory COPY observer /app/observer COPY scripts/pki.py /app/scripts/pki.py +# run inside a node's container: docker compose ... exec node python scripts/preflight.py +COPY scripts/preflight.py /app/scripts/preflight.py COPY models/ecg-resnet18.onnx /app/models/ecg-resnet18.onnx COPY --from=risk-model /app/models/heart-risk.joblib /app/models/heart-risk.joblib +# the release this image was built as (.github/workflows/image.yml), reported by /health +ARG IMAGE_VERSION=dev +ENV IMAGE_VERSION=${IMAGE_VERSION} +LABEL org.opencontainers.image.version=${IMAGE_VERSION} \ + org.opencontainers.image.source=https://github.com/Denimworld12/Hospital-Chain # No training data, no config and no keys baked in: docker-compose mounts this node's # own config, only this node's own data slice, and the keys from scripts/pki.py. # The healthcheck is local liveness only (127.0.0.1), so it skips certificate checks. diff --git a/node/config.py b/node/config.py index dbf78e1..d9050a9 100644 --- a/node/config.py +++ b/node/config.py @@ -148,12 +148,16 @@ def peer_url_env(node_id: str) -> str: return f"MEDCHAIN_PEER_{re.sub(r'[^A-Za-z0-9]+', '_', node_id).upper()}_URL" +# the repository's models/ (in the image, /app/models): the same default in Docker and for `make node-native` +MODELS_DIR = Path(__file__).resolve().parents[1] / "models" + + @dataclass(frozen=True) class AssessConfig: """Model files for the per-patient risk assessment endpoints (inference only).""" - tabular_model: str = "/app/models/heart-risk.joblib" - ecg_model: str = "/app/models/ecg-resnet18.onnx" + tabular_model: str = str(MODELS_DIR / "heart-risk.joblib") + ecg_model: str = str(MODELS_DIR / "ecg-resnet18.onnx") @dataclass(frozen=True) diff --git a/scripts/preflight.py b/scripts/preflight.py index 371cec0..be057ee 100644 --- a/scripts/preflight.py +++ b/scripts/preflight.py @@ -2,7 +2,14 @@ python scripts/preflight.py --node https://localhost:8001 --ca pki/ca.crt -Run it on each hospital's machine. For every neighbour the local node reports (GET +Run it on each hospital's machine, with its node running. Inside the node's own container +(deploy/node.yml) it needs no arguments, since it reads NODE_PORT and TLS_CA there: + + docker compose --project-directory . -f deploy/node.yml exec node python scripts/preflight.py + +From inside the container it dials the neighbours exactly as the node does, so a name the +container cannot resolve (a Tailscale MagicDNS name under Docker Desktop) shows up as +"unreachable" with the reason. For every neighbour the local node reports (GET /status), it prints how this machine reaches that neighbour's address: direct a direct path: a Tailscale peer reached peer-to-peer, or an address @@ -13,7 +20,8 @@ unreachable the neighbour's node does not answer /health Tailscale's view comes from `tailscale ping` (which also establishes the path) and -`tailscale status --json`, both read on the host. Containers cannot see it. The +`tailscale status --json`, both read on the host. Containers cannot see it: there the path +is reported as "unknown" and only reachability is checked. The dialled address must be the neighbour's Tailscale IP or MagicDNS name for the path to be reported. """ @@ -23,6 +31,7 @@ import argparse import ipaddress import json +import os import re import shutil import ssl @@ -84,6 +93,8 @@ def tailscale(*args: str) -> str | None: def path_to(host: str, *, ping: bool) -> tuple[str, str]: + if not shutil.which("tailscale"): + return "unknown", "no tailscale command on this PATH (as inside a container): reachability only" raw = tailscale("status", "--json") status = json.loads(raw) if raw else {} peer = find_peer(status, host) if status else None @@ -100,8 +111,11 @@ def path_to(host: str, *, ping: bool) -> tuple[str, str]: def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--node", required=True, help="this machine's node, e.g. https://localhost:8001") - ap.add_argument("--ca", help="the network CA (pki/ca.crt) to check the node's certificate") + port = os.environ.get("NODE_PORT") + ap.add_argument("--node", required=not port, default=f"https://localhost:{port}" if port else None, + help="this machine's node, e.g. https://localhost:8001 (default: NODE_PORT's, in its container)") + ap.add_argument("--ca", default=os.environ.get("TLS_CA") or None, + help="the network CA (pki/ca.crt) to check the node's certificate (default: TLS_CA)") ap.add_argument("--no-ping", action="store_true", help="read `tailscale status` only, without pinging") args = ap.parse_args(argv) verify: ssl.SSLContext | bool = True @@ -119,11 +133,12 @@ def main(argv: list[str] | None = None) -> int: host = urlsplit(n["url"]).hostname or "" kind, how = path_to(host, ping=not args.no_ping) try: - alive = httpx.get(f"{n['url']}/health", timeout=5, verify=verify).status_code == 200 - except httpx.HTTPError: - alive = False - if not alive: - kind, worst = "unreachable", 1 + code = httpx.get(f"{n['url']}/health", timeout=5, verify=verify).status_code + why = "" if code == 200 else f"/health answered {code}" + except httpx.HTTPError as exc: + why = f"{type(exc).__name__}: {exc}" + if why: + kind, how, worst = "unreachable", why, 1 print(f" {st['node_id']} <-> {n['id']:<14} {kind:<11} {how} ({n['url']}, last send: {n.get('last_send')})") if not st.get("neighbours"): print(" no neighbours yet") diff --git a/scripts/provision.py b/scripts/provision.py index 43c6133..0dd74ba 100644 --- a/scripts/provision.py +++ b/scripts/provision.py @@ -1,10 +1,22 @@ -"""Generate MedChain kits: one folder (optionally one zip) per hospital, plus one for the directory. +"""Generate MedChain kits: one folder (optionally one zip) per hospital, plus one for the hub. A hospital kit is everything one collaborator needs to run their node on their own -machine: its config (the directory's address, its own credential, TLS and signing -keys), a compose file that runs only that node, its own data slice, its own keys and -certificate, the node's build context (or a prebuilt image reference) and a README with -the exact commands. The directory kit runs the membership directory. Unpack, run one command. +laptop, laid out for deploy/node.yml (docs/MULTI_LAPTOP.md): + + deploy/node.yml the one-service compose file (a copy of the repo's) + .env this hospital's settings, filled in: NODE_ID, NODE_PORT, its address and + the hub's (a Tailscale block, and a hotspot block to switch to), the network secret + pki/ only its own TLS and signing keys and directory credential, plus the public + material it pins (CA, the directory's and the observer's certificates, the + directory's document key) and the observer's ingest token + data/ its data slice; the node keeps its checkpoints, saved membership and + audit.db here too + config/node.yaml its display name and the engine settings (from config/.yaml) + README.md the commands + +Unzip, check `.env`, run `docker compose --project-directory . -f deploy/node.yml up`. The +directory kit is the hub's: the directory's config and keys, the observer's keys, and a +filled `hub.env` for `make hub` (deploy/hub.yml) from the repository. python scripts/provision.py \\ --peers hospital-a=100.101.1.10:8001,hospital-b=100.101.1.11:8002,hospital-c=100.101.1.12:8003 \\ @@ -25,6 +37,9 @@ from __future__ import annotations import argparse +import ipaddress +import os +import re import secrets import shutil import sys @@ -39,15 +54,17 @@ sys.path.insert(0, str(ROOT / "scripts")) import pki # noqa: E402 -from node.config import ADVERTISE_URL_ENV, DIRECTORY_URL_ENV, load_config # noqa: E402 +from node.config import build_config # noqa: E402 +from node.settings import NodeSettings, apply_env # noqa: E402 -COMPOSE_FILE = "docker-compose.hospital.yaml" +NODE_COMPOSE = ROOT / "deploy" / "node.yml" +UP = "docker compose --project-directory . -f deploy/node.yml" +IMAGE_VERSION = "v1.0.0" # the published node image's tag (.github/workflows/image.yml) DIRECTORY = "directory" OBSERVER = "observer" OBSERVER_PORT = 8200 DEFAULT_TEMPLATE = ROOT / "config" / "hospital-a.yaml" -# the node image's build context, laid out as node/Dockerfile expects it (the same image runs the directory) -SOURCE_FILES = ("node", "directory", "observer", "scripts/pki.py", "models/ecg-resnet18.onnx", "data/cardio/cardio_train.csv") +TAILSCALE = ipaddress.ip_network("100.64.0.0/10") def parse_url(name: str, addr: str) -> str: @@ -95,30 +112,109 @@ def listen_port(node_id: str, url: str, template: Path) -> int: return int(raw["port"]) -def node_yaml(node_id: str, url: str, directory_url: str, secret: str, template: Path, - observer_url: str | None) -> dict: +ENGINE_ONLY_DROP = ("node_id", "port", "host", "advertise_url", "chain", "neighbours", "directory", "observer", "tls", + "signing_key", "shared_secret", "data_slice", "data_path", "checkpoint_dir") + + +def engine_yaml(node_id: str, template: Path) -> dict: + """The kit's config/node.yaml: the hospital's name and the engine settings, nothing about where it runs. + + Identity, addresses, keys and the secret come from the kit's `.env` and deploy/node.yml instead.""" raw, own = base_config(node_id, template) - for k in ("chain", "neighbours"): - raw.pop(k, None) - raw.update( - node_id=node_id, - display_name=raw.get("display_name") if own else node_id, - port=listen_port(node_id, url, template), - host="0.0.0.0", - advertise_url=url, - directory={"url": directory_url, "credential_file": f"/pki/{node_id}/credential", - "public_key": "file:/pki/directory/signing.pub", "tls_pin": "file:/pki/directory/tls.crt"}, - tls={"cert": f"/pki/{node_id}/tls.crt", "key": f"/pki/{node_id}/tls.key", "ca": "/pki/ca.crt"}, - signing_key=f"/pki/{node_id}/signing.key", - shared_secret=secret, - data_slice=f"/data/{node_id}.csv", - ) - if observer_url: - raw["observer"] = {"url": observer_url, "token_file": f"/pki/{OBSERVER}/token", - "tls_pin": f"file:/pki/{OBSERVER}/tls.crt"} + raw = {k: v for k, v in raw.items() if k not in ENGINE_ONLY_DROP} + raw["display_name"] = raw.get("display_name") if own else node_id return raw +def hostport(url: str) -> str: + parts = urlsplit(url) + return f"{parts.hostname}:{parts.port}" if parts.port else str(parts.hostname) + + +def split_image(image: str | None) -> tuple[str | None, str]: + """`--image repo[:tag]` -> (MEDCHAIN_IMAGE, IMAGE_VERSION); none -> the published image's default tag.""" + if not image: + return None, IMAGE_VERSION + repo, sep, tag = image.rpartition(":") + if not sep or "/" in tag: # no tag (a ':' in a registry port is not one) + return image, "latest" + return repo, tag + + +def node_env(node_id: str, port: int, url: str, directory_url: str, observer_url: str, secret: str, + image: str | None) -> str: + """The kit's `.env`, laid out like deploy/node.env.example: a Tailscale block and a hotspot block.""" + repo, version = split_image(image) + d, o = urlsplit(directory_url), urlsplit(observer_url) + return textwrap.dedent(f"""\ + # MedChain hospital node settings for {node_id}, generated by scripts/provision.py. + # Read by deploy/node.yml (and by `make node-native`). docs/MULTI_LAPTOP.md walks through it. + + # ---- Which hospital this laptop is: check it matches what the organiser told you ---- + NODE_ID={node_id} + NODE_PORT={port} + + # ======== Tailscale (the normal way) ======== + # This laptop's MagicDNS name (or Tailscale IP, `tailscale ip -4`), with NODE_PORT: + ADVERTISE_ADDR={hostport(url)} + # The organiser's laptop (the hub), which runs the directory and the observer: + DIRECTORY_URL={directory_url} + OBSERVER_URL={observer_url} + + # ======== Phone hotspot (fallback) ======== + # To switch: put a # in front of the three Tailscale lines above, remove the # from the + # three lines below, and put in the IP addresses the hotspot gave each laptop. + #ADVERTISE_ADDR=THIS-LAPTOPS-HOTSPOT-IP:{port} + #DIRECTORY_URL=https://HUB-HOTSPOT-IP:{d.port or 443} + #OBSERVER_URL=https://HUB-HOTSPOT-IP:{o.port or 443} + + # ---- The network: filled in by the kit, the same on every laptop. Don't change. ---- + SHARED_SECRET={secret} + IMAGE_VERSION={version} + """) + (f"MEDCHAIN_IMAGE={repo}\n" if repo else "") + textwrap.dedent("""\ + # Rounds over a real network take longer than on one machine: give each one time. + ROUND_TIMEOUT_S=15 + HTTP_CONNECT_TIMEOUT_S=5 + HTTP_READ_TIMEOUT_S=10 + """) + + +def read_env(text: str) -> dict[str, str]: + """The variables an `.env` sets (KEY=value lines; # comments and blank lines skipped).""" + env = {} + for line in text.splitlines(): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + k, _, v = line.partition("=") + env[k.strip()] = v.strip() + return env + + +def interpolate(value: str, env: dict[str, str]) -> str: + """Compose's ${VAR}, ${VAR:-default} and ${VAR:?message} against `env`.""" + def sub(m: re.Match) -> str: + name, op, arg = m.group(1), m.group(2), m.group(3) or "" + if env.get(name): + return env[name] + if op == ":?": + raise ValueError(f"{name} is not set: {arg}") + return arg if op == ":-" else "" + return re.sub(r"\$\{(\w+)(?:(:-|:\?)([^}]*))?\}", sub, value) + + +def container_env(env: dict[str, str]) -> dict[str, str]: + """What the node sees inside deploy/node.yml's container: the `.env` plus the file's own `environment:`.""" + service = yaml.safe_load(NODE_COMPOSE.read_text())["services"]["node"] + return {**env, **{k: interpolate(str(v), env) for k, v in (service.get("environment") or {}).items()}} + + +def check_kit(kit: Path, env: dict[str, str]) -> None: + """Validate the kit as its node will load it in deploy/node.yml (container paths, not read here).""" + settings = NodeSettings(**container_env(env)) + raw = yaml.safe_load((kit / "config" / "node.yaml").read_text()) or {} + build_config(apply_env(raw, settings, str(kit / ".env")), str(kit / ".env")) + + def ensure_observer_token(pki_dir: Path, token: str | None) -> None: """The observer's ingest token, kept with the network's keys so every kit from this network shares it.""" path = pki_dir / OBSERVER / "token" @@ -142,31 +238,6 @@ def copy_keys(pki_dir: Path, kit: Path, party: str) -> None: shutil.copyfile(pki_dir / OBSERVER / f, dst / OBSERVER / f) -def compose_yaml(name: str, port: int, *, image: str | None, env: dict, volumes: list[str], bind_ip: str | None, - command: list[str] | None = None, extra_volumes: dict | None = None) -> dict: - service: dict = {} - if image: - service["image"] = image - else: - service["build"] = {"context": "./source", "dockerfile": "node/Dockerfile"} - service["image"] = "medchain-node:latest" - if command: - service["command"] = command - service.update(environment=env, volumes=volumes, - ports=[f"{bind_ip}:{port}:{port}" if bind_ip else f"{port}:{port}"], restart="unless-stopped") - return {"name": f"medchain-{name}", "services": {name: service}, "volumes": extra_volumes or {}} - - -def copy_source(kit: Path) -> None: - for rel in SOURCE_FILES: - src, dst = ROOT / rel, kit / "source" / rel - dst.parent.mkdir(parents=True, exist_ok=True) - if src.is_dir(): - shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) - else: - shutil.copyfile(src, dst) - - def fresh(out: Path, name: str, force: bool) -> Path: kit = out / name if kit.exists(): @@ -177,203 +248,170 @@ def fresh(out: Path, name: str, force: bool) -> Path: return kit -def kit_readme(node_id: str, display: str, url: str, directory_url: str, port: int, secret: str, *, - image: str | None, observer_url: str | None, observer_db: str | None) -> str: - up = f"docker compose -f {COMPOSE_FILE} up -d{'' if image else ' --build'} --wait" - observer = (f"Training telemetry goes to the observer database at `{observer_db}` (read by the\n" - "MedChain dashboard). It only observes; training does not depend on it." - if observer_db else - f"Training telemetry is pushed to the observer at `{observer_url}` over HTTPS with\n" - f"its token (`pki/{OBSERVER}/token`), pinned to its key (`pki/{OBSERVER}/tls.crt`); the\n" - "MedChain dashboard reads it from there. This node never holds database credentials,\n" - "and training never waits for the observer.") +def kit_readme(node_id: str, display: str, url: str, directory_url: str, port: int, secret: str, + observer_url: str) -> str: curl = f"curl --cacert pki/ca.crt https://localhost:{port}" return textwrap.dedent("""\ # MedChain node kit: {display} (`{node_id}`) - This folder runs one MedChain hospital node on this machine. It trains on - `data/{node_id}.csv`, which never leaves this machine; only model updates - travel, only to this node's chain neighbours, over TLS, each one signed with - this node's key (`pki/{node_id}/signing.key`). There is no central training - server. - - Where this node sits in the chain is decided by the MedChain directory at - `{directory_url}`: on start the node registers there with its own credential - (`pki/{node_id}/credential`), and the directory tells it, and its new - neighbours, who to connect to. The directory only coordinates membership. If it - is down, a node already in the chain keeps training; only joining and leaving - wait for it. + This folder runs one MedChain hospital node on this laptop. The step-by-step guide, + written for someone who has never used Docker, is docs/MULTI_LAPTOP.md in the + MedChain repository (the organiser can send it to you). The short version: - This kit contains this hospital's private keys, its directory credential and the - network's shared secret. Treat it like a password: send it to {display}'s - operator only, over a private channel. + 1. Install Docker Desktop and Tailscale, and join the organiser's tailnet. + 2. Open `.env` in a text editor and check `NODE_ID` and the addresses + (`ADVERTISE_ADDR`, `DIRECTORY_URL`, `OBSERVER_URL`) against what the organiser told you. + 3. In a terminal, in this folder: - ## Before you start + ```sh + {up} up -d + {up} exec node python scripts/preflight.py + {up} logs -f + ``` - - Docker with the Compose v2 plugin. - - Port {port} free on this machine, and reachable at `{url}` from the other - hospitals and the directory. The simplest way is a private mesh network such as - Tailscale on every machine: it works through NAT and needs no port forwarding. - Peers pin this node's TLS key (registered with the directory), not its address. - - To train on your own patients instead of the demo slice, replace - `data/{node_id}.csv` with a file that has the same columns. + The node trains on `data/{node_id}.csv`, which never leaves this laptop; only model + updates travel, only to this node's chain neighbours, over TLS, each signed with + this node's key (`pki/{node_id}/signing.key`). Its place in the chain comes from + the directory at `{directory_url}`; its telemetry goes to the observer at + `{observer_url}`. Training never waits for either of them. - ## Run (this is also how the hospital joins) - - ```sh - {up} - ``` + This kit contains this hospital's private keys, its directory credential and the + network's shared secret. Treat it like a password. - The node registers with the directory. If a training run is in progress, the - directory appends this hospital at the end of the chain from a round boundary a - few rounds ahead; it then exchanges one full model snapshot with its new - neighbour and joins the run. Check it is up and placed: + ## Check it ```sh {curl}/health {curl}/status # chain, position, head/tail group, neighbours ``` - ## Start training - - Once the hospitals are up, start a run from any one of them; it floods the - start to the others: + ## Start training (any one hospital; it floods to the others) ```sh - {curl}/round/start -X POST \\ - -H 'Content-Type: application/json' \\ - -H 'X-MedChain-Secret: {secret}' \\ - -d '{{}}' - {curl}/metrics # per-round loss and neighbours heard + {curl}/round/start -X POST -H 'Content-Type: application/json' \\ + -H 'X-MedChain-Secret: {secret}' -d '{{}}' ``` - {observer} - - ## Leave the chain (planned) + ## Leave the chain, then stop ```sh - docker compose -f {COMPOSE_FILE} exec {node_id} python -m node.leave + {up} exec node python -m node.leave + {up} down ``` - The directory takes this hospital out at the next round boundary and tells its - two neighbours, which bridge directly to each other (a new link, a fresh - snapshot exchange) so the chain heals instead of splitting. Then stop the node. - (Stopping it without leaving is treated as a crash: its neighbours skip it and - wait for it to come back.) + The directory takes this hospital out at the next round boundary and its two + neighbours bridge to each other. Stopping without leaving counts as a crash: the + neighbours skip it and wait for it to come back. `data/` keeps its checkpoints. - ## Stop + ## Switching to a phone hotspot - ```sh - docker compose -f {COMPOSE_FILE} down # add -v to also delete this node's checkpoints - ``` - - ## If an address changes - - Override it without touching the config by adding to the `environment:` block in - `{COMPOSE_FILE}`: - - ```yaml - {ADVERTISE}: https://new-address-of-{node_id}:{port} - {DIRECTORY_ENV}: https://new-address-of-the-directory:PORT - ``` - - Then run the `up` command again; the node re-registers its new address and the - directory passes it to its neighbours. Other hospitals pin this node's TLS key, - not its address, so their links keep working. Only the dashboard checks the - address: for it, ask whoever provisioned the network to re-run - `scripts/provision.py` for this hospital with the new address (same key). - """).format(display=display, node_id=node_id, url=url, directory_url=directory_url, port=port, up=up, - curl=curl, secret=secret, observer=observer, ADVERTISE=ADVERTISE_URL_ENV, - DIRECTORY_ENV=DIRECTORY_URL_ENV, COMPOSE_FILE=COMPOSE_FILE) + Edit only `.env`: comment out the three Tailscale address lines and fill in the + hotspot block (this laptop's hotspot IP, and the hub's), then run the `up` command + again. Peers pin this node's TLS key, not its address, so nothing else changes. + This node is reachable at `{url}` on Tailscale. + """).format(display=display, node_id=node_id, url=url, directory_url=directory_url, port=port, up=UP, + curl=curl, secret=secret, observer_url=observer_url) def build_kit(node_id: str, url: str, out: Path, *, directory_url: str, pki_dir: Path, secret: str, data: Path, - template: Path, image: str | None, observer_url: str, observer_db: str | None, bind_ip: str | None, - make_zip: bool, force: bool) -> Path: + template: Path, image: str | None, observer_url: str, make_zip: bool, force: bool) -> Path: kit = fresh(out, node_id, force) - (kit / "config").mkdir() - (kit / "data").mkdir() - cfg = node_yaml(node_id, url, directory_url, secret, template, None if observer_db else observer_url) - cfg_path = kit / "config" / f"{node_id}.yaml" - cfg_path.write_text(f"# MedChain node config for {node_id}, generated by scripts/provision.py.\n" - + yaml.safe_dump(cfg, sort_keys=False)) - load_config(cfg_path) # the same validation the node runs at start + for d in ("deploy", "config", "data"): + (kit / d).mkdir() + shutil.copyfile(NODE_COMPOSE, kit / "deploy" / "node.yml") + port = listen_port(node_id, url, template) + cfg = engine_yaml(node_id, template) + (kit / "config" / "node.yaml").write_text( + f"# {node_id}'s name and engine settings, generated by scripts/provision.py. Where it runs, its keys\n" + "# and the network secret are in ../.env (node/settings.py lists every variable).\n" + + yaml.safe_dump(cfg, sort_keys=False)) + env = node_env(node_id, port, url, directory_url, observer_url, secret, image) + (kit / ".env").write_text(env) + check_kit(kit, read_env(env)) # the same validation the node runs at start shutil.copyfile(data, kit / "data" / f"{node_id}.csv") copy_keys(pki_dir, kit, node_id) - - port = cfg["port"] - env = {"NODE_CONFIG": f"/config/{node_id}.yaml"} | ({"DATABASE_URL": observer_db} if observer_db else {}) - compose = compose_yaml(node_id, port, image=image, env=env, bind_ip=bind_ip, - volumes=[f"./config/{node_id}.yaml:/config/{node_id}.yaml:ro", - f"./data/{node_id}.csv:/data/{node_id}.csv:ro", "./pki:/pki:ro", - "checkpoints:/checkpoints"], extra_volumes={"checkpoints": {}}) - (kit / COMPOSE_FILE).write_text( - f"# Runs only {node_id}. See README.md: docker compose -f {COMPOSE_FILE} up -d{'' if image else ' --build'} --wait\n" - + yaml.safe_dump(compose, sort_keys=False)) (kit / "README.md").write_text(kit_readme(node_id, str(cfg["display_name"]), url, directory_url, port, secret, - image=image, observer_url=observer_url, observer_db=observer_db)) - if not image: - copy_source(kit) + observer_url)) if make_zip: shutil.make_archive(str(out / node_id), "zip", root_dir=out, base_dir=node_id) return kit -def build_directory_kit(url: str, out: Path, *, pki_dir: Path, observer_url: str, image: str | None, +def hub_env(kit: Path, directory_url: str, observer_url: str, secret: str, image: str | None, + bind_ip: str | None) -> str: + """The directory kit's `hub.env` for deploy/hub.yml, laid out like deploy/hub.env.example.""" + repo, version = split_image(image) + host = urlsplit(directory_url).hostname or "" + try: + tailscale_ip = host if ipaddress.ip_address(host) in TAILSCALE else None + except ValueError: + tailscale_ip = None + kit_path = "./" + os.path.relpath(kit.resolve(), ROOT) if kit.resolve().is_relative_to(ROOT) else str(kit.resolve()) + tailscale = (f"HUB_BIND_IP={bind_ip}" if bind_ip else f"HUB_BIND_IP={tailscale_ip}" if tailscale_ip else + "# (the directory's address is not a Tailscale IP: put `tailscale ip -4` here to listen on the\n" + "# tailnet only)\nHUB_BIND_IP=0.0.0.0") + return textwrap.dedent(f"""\ + # MedChain hub settings, generated by scripts/provision.py. From the repository root: make hub + # (deploy/hub.yml; docs/MULTI_LAPTOP.md walks through it). + + # This directory kit (its config/ and pki/): ./ and relative to the repo root, or absolute + HUB_KIT={kit_path} + # The network's shared secret (the dashboard's Start / Pause relay sends it) + MEDCHAIN_SHARED_SECRET={secret} + IMAGE_VERSION={version} + """) + (f"MEDCHAIN_IMAGE={repo}\n" if repo else "") + textwrap.dedent(f"""\ + # The ports in the directory's and the observer's addresses + DIRECTORY_PORT={urlsplit(directory_url).port or 443} + OBSERVER_PORT={urlsplit(observer_url).port or OBSERVER_PORT} + # The dashboard, on this laptop only: http://localhost:8080 + DASHBOARD_BIND_IP=127.0.0.1 + DASHBOARD_PORT=8080 + + # ======== Tailscale (the normal way) ======== + # Listen for the hospitals on this laptop's Tailscale IP only. 0.0.0.0 (every interface) also works. + """) + tailscale + textwrap.dedent(""" + + # ======== Phone hotspot (fallback) ======== + # To switch: put a # in front of the Tailscale line above and remove it below. The hotspot + # hands out addresses that can change, so listen on every interface. + #HUB_BIND_IP=0.0.0.0 + """) + + +def build_directory_kit(url: str, out: Path, *, pki_dir: Path, observer_url: str, secret: str, image: str | None, bind_ip: str | None, make_zip: bool, force: bool) -> Path: kit = fresh(out, DIRECTORY, force) (kit / "config").mkdir() - port = urlsplit(url).port or 8100 + port = urlsplit(url).port or 443 cfg = yaml.safe_load((ROOT / "config" / "directory.yaml").read_text()) cfg.update(port=port, host="0.0.0.0", db_path="/data/directory.sqlite") (kit / "config" / "directory.yaml").write_text("# MedChain directory config, generated by scripts/provision.py.\n" + yaml.safe_dump(cfg, sort_keys=False)) copy_keys(pki_dir, kit, DIRECTORY) - compose = compose_yaml(DIRECTORY, port, image=image, env={"DIRECTORY_CONFIG": "/config/directory.yaml"}, - bind_ip=bind_ip, command=["python", "-m", "directory"], - volumes=["./config/directory.yaml:/config/directory.yaml:ro", "./pki:/pki:ro", - "directory-data:/data"], extra_volumes={"directory-data": {}}) - (kit / COMPOSE_FILE.replace("hospital", "directory")).write_text( - "# Runs the MedChain membership directory. See README.md.\n" + yaml.safe_dump(compose, sort_keys=False)) + (kit / "hub.env").write_text(hub_env(kit, url, observer_url, secret, image, bind_ip)) (kit / "README.md").write_text(textwrap.dedent(f"""\ - # MedChain directory kit + # MedChain hub kit (directory + observer) - Runs the membership directory at `{url}`. It decides where each hospital sits in - the chain and tells hospitals who to connect to when one joins or leaves. It - never receives model weights and never runs or influences training. It is a - single point of failure for joins and leaves only: if it is down, hospitals - already in the chain keep training. + The organiser's laptop runs the hub from the MedChain repository, with this kit's + settings (`hub.env`): ```sh - docker compose -f docker-compose.directory.yaml up -d{'' if image else ' --build'} --wait + make hub # = docker compose --project-directory . --env-file {os.path.relpath(kit / "hub.env", ROOT) if kit.resolve().is_relative_to(ROOT) else kit / "hub.env"} -f deploy/hub.yml up -d --wait ``` - Its state lives in its own SQLite file (the `directory-data` volume), separate - from the dashboard's Postgres. `pki/directory/hospitals.yaml` lists which - hospitals may register (an id and the SHA-256 of that hospital's own - credential, in placement order). It is re-read on every registration: to admit - a new hospital, replace it with the refreshed file from the provisioning machine. - Keep `pki/directory/signing.key` private: it signs every membership document. - - ## The observer - - The hospitals push their telemetry to the observer at `{observer_url}`, which - writes it to the dashboard's Postgres. This kit holds its TLS certificate and key - (`pki/observer/`, which the hospitals pin) and its ingest token - (`pki/observer/token`, also in every hospital kit). Run it on this machine next - to Postgres, from the node image or `source/`: - - ```sh - OBSERVER_PORT={urlsplit(observer_url).port or OBSERVER_PORT} OBSERVER_TOKEN_FILE=pki/observer/token \\ - TLS_CERT=pki/observer/tls.crt TLS_KEY=pki/observer/tls.key TLS_CA=pki/ca.crt \\ - DATABASE_URL=postgresql://medchain:medchain@127.0.0.1:5432/medchain \\ - PYTHONPATH=source python -m observer - ``` - - Keep `pki/observer/tls.key` private. Training never waits for the observer. + - The directory, at `{url}`, decides where each hospital sits in the chain and + tells hospitals who to connect to when one joins or leaves. It never receives + model weights. If it is down, hospitals already in the chain keep training. + - The observer, at `{observer_url}`, takes the hospitals' pushed telemetry into + Postgres for the dashboard (http://localhost:8080). Training never waits for it. + - Postgres listens on this laptop's loopback only. + + `pki/directory/hospitals.yaml` lists which hospitals may register (an id and the + SHA-256 of that hospital's credential, in placement order). It is re-read on + every registration: to admit a new hospital, replace it with the refreshed file + from the provisioning run. Keep `pki/directory/signing.key` (it signs every + membership document) and `pki/observer/tls.key` private. """)) - if not image: - copy_source(kit) if make_zip: shutil.make_archive(str(out / DIRECTORY), "zip", root_dir=out, base_dir=DIRECTORY) return kit @@ -393,12 +431,13 @@ def main(argv: list[str] | None = None) -> int: help="this hospital's data CSV (repeatable; default: data/slices/.csv)") ap.add_argument("--template", type=Path, default=DEFAULT_TEMPLATE, help="engine settings for a hospital without its own config/.yaml") - ap.add_argument("--image", help="use this prebuilt node image instead of bundling the build context") + ap.add_argument("--image", help=f"the node image, repo[:tag] (default: the published " + f"ghcr.io/denimworld12/medchain-node:{IMAGE_VERSION})") ap.add_argument("--observer", help="the observer's address, host:port (https; default: the directory's host, " f"port {OBSERVER_PORT})") ap.add_argument("--observer-token", help="the observer's ingest token (default: the network's, else a new one)") - ap.add_argument("--observer-db", help="fallback: postgresql:// URL the nodes write to directly instead of the observer") - ap.add_argument("--bind-ip", help="publish the port on this host IP only (e.g. the machine's Tailscale IP)") + ap.add_argument("--bind-ip", help="the hub listens for the hospitals on this IP only (HUB_BIND_IP in hub.env; " + "default: the directory's address when it is a Tailscale IP)") ap.add_argument("--zip", action="store_true", help="also write /.zip for each kit") ap.add_argument("--force", action="store_true", help="replace kits that already exist") args = ap.parse_args(argv) @@ -432,12 +471,11 @@ def main(argv: list[str] | None = None) -> int: for h in hospitals: kit = build_kit(h, peers[h], args.out, directory_url=directory_url, pki_dir=pki_dir, secret=secret, data=data[h], template=args.template, image=args.image, observer_url=observer_url, - observer_db=args.observer_db, - bind_ip=args.bind_ip, make_zip=args.zip, force=args.force) + make_zip=args.zip, force=args.force) print(f"{h}: {kit}{' (+ ' + kit.name + '.zip)' if args.zip else ''}") if DIRECTORY in wanted: kit = build_directory_kit(directory_url, args.out, pki_dir=pki_dir, observer_url=observer_url, - image=args.image, + secret=secret, image=args.image, bind_ip=args.bind_ip, make_zip=args.zip, force=args.force) print(f"{DIRECTORY}: {kit}{' (+ directory.zip)' if args.zip else ''}") else: diff --git a/tests/integration/test_stack.py b/tests/integration/test_stack.py index c50cfbd..2b1593b 100644 --- a/tests/integration/test_stack.py +++ b/tests/integration/test_stack.py @@ -460,6 +460,12 @@ def compose(*args: str) -> None: subprocess.run([*COMPOSE, *args], check=True, capture_output=True, text=True, cwd=ROOT) +def loss_rounds(s: dict) -> set[int]: + """Rounds in the dashboard's network loss: a round shows once every member's metrics row reached the observer, + which each node pushes from its own queue, so it can trail the round's comm counts by a moment.""" + return {p["round"] for p in s["network_loss"]} + + @admm_only @pytest.mark.skipif(JOINER is None, reason="no spare hospital config to join") def test_a_hospital_joins_mid_run_then_a_middle_hospital_leaves_and_the_dashboard_follows(): @@ -490,7 +496,8 @@ def test_a_hospital_joins_mid_run_then_a_middle_hospital_leaves_and_the_dashboar def after_join(): s = snapshot() - return s if s["topology"]["chain"] == grown and s["comm"]["hospitals_this_round"] == n + 1 else None + return s if (s["topology"]["chain"] == grown and s["comm"]["hospitals_this_round"] == n + 1 + and loss_rounds(s) >= {join_round - 1, join_round}) else None s = wait_until(after_join, 60, what=f"the dashboard shows {n + 1} hospitals") assert s["topology"]["links"] == [f"{a}|{b}" for a, b in zip(grown, grown[1:])] @@ -515,7 +522,8 @@ def after_join(): def after_leave(): s = snapshot() - return s if s["topology"]["chain"] == shrunk and s["comm"]["hospitals_this_round"] == n else None + return s if (s["topology"]["chain"] == shrunk and s["comm"]["hospitals_this_round"] == n + and loss_rounds(s) >= {leave_round - 1, leave_round}) else None s = wait_until(after_leave, 60, what="the dashboard shows the bridged chain") assert leaver in s["topology"]["left"] diff --git a/tests/unit/test_preflight.py b/tests/unit/test_preflight.py index 77a8bf8..7f0f7bd 100644 --- a/tests/unit/test_preflight.py +++ b/tests/unit/test_preflight.py @@ -26,3 +26,27 @@ def test_status_finds_the_peer_by_ip_or_magicdns_name_and_reads_its_path(): assert preflight.classify_status(preflight.find_peer(STATUS, "100.101.1.11")) == ("relayed", "DERP lhr") assert preflight.find_peer(STATUS, "192.168.1.20") is None assert preflight.is_tailscale_ip("100.101.1.11") and not preflight.is_tailscale_ip("192.168.1.20") + + +def test_inside_the_node_container_it_needs_no_arguments_and_says_why_a_neighbour_is_unreachable(monkeypatch, capsys): + """In deploy/node.yml's container there is no tailscale command; NODE_PORT and TLS_CA name the node and CA.""" + import httpx + + monkeypatch.setenv("NODE_PORT", "8002") + monkeypatch.delenv("TLS_CA", raising=False) + monkeypatch.setattr(preflight.shutil, "which", lambda _: None) + calls = [] + + def get(url, **_): + calls.append(url) + if url == "https://localhost:8002/status": + return httpx.Response(200, json={"node_id": "hospital-b", "chain": ["hospital-a", "hospital-b"], + "neighbours": [{"id": "hospital-a", "url": "https://a.tail1234.ts.net:8001"}]}) + raise httpx.ConnectError("[Errno -2] Name or service not known") + + monkeypatch.setattr(preflight.httpx, "get", get) + assert preflight.main([]) == 1 + out = capsys.readouterr().out + assert calls[0] == "https://localhost:8002/status" + assert "unreachable" in out and "Name or service not known" in out + assert preflight.path_to("100.101.1.10", ping=False)[0] == "unknown" diff --git a/tests/unit/test_provision.py b/tests/unit/test_provision.py index ed04886..1fa7669 100644 --- a/tests/unit/test_provision.py +++ b/tests/unit/test_provision.py @@ -1,6 +1,7 @@ """scripts/provision.py: one self-contained kit per hospital plus the directory's, all on TLS.""" import hashlib +import shutil import zipfile from pathlib import Path @@ -32,18 +33,26 @@ def sans(crt: Path) -> set[str]: str(v) for v in ext.value.get_values_for_type(x509.IPAddress)} -def test_kit_has_every_file_with_the_real_addresses_and_only_its_own_keys(tmp_path): +def kit_config(kit: Path, monkeypatch): + """The config the kit's node loads inside deploy/node.yml: its `.env` plus the file's container paths.""" + env = provision.container_env(provision.read_env((kit / ".env").read_text())) + for k, v in env.items(): + monkeypatch.setenv(k, v) + return load_config(kit / "config" / "node.yaml") + + +def test_kit_has_every_file_with_the_real_addresses_and_only_its_own_keys(tmp_path, monkeypatch): assert run(tmp_path, "--hospital", "hospital-b", "--zip") == 0 kit = tmp_path / "hospital-b" - for rel in ("README.md", "docker-compose.hospital.yaml", "config/hospital-b.yaml", "data/hospital-b.csv", + for rel in ("README.md", ".env", "deploy/node.yml", "config/node.yaml", "data/hospital-b.csv", "pki/ca.crt", "pki/directory/signing.pub", "pki/hospital-b/tls.crt", "pki/hospital-b/tls.key", "pki/hospital-b/signing.key", "pki/hospital-b/credential", - "pki/observer/tls.crt", "pki/observer/token", - "source/node/Dockerfile", "source/node/requirements.txt", "source/node/__main__.py", - "source/directory/app.py", "source/scripts/pki.py", - "source/models/ecg-resnet18.onnx", "source/data/cardio/cardio_train.csv"): + "pki/observer/tls.crt", "pki/observer/token"): assert (kit / rel).is_file(), rel - assert not list(kit.rglob("__pycache__")) + # the one-file deployment, not a compose file of its own, and no build context: the image is published + assert sorted(p.name for p in kit.iterdir()) == [".env", "README.md", "config", "data", "deploy", "pki"] + assert (kit / "deploy/node.yml").read_bytes() == (ROOT / "deploy/node.yml").read_bytes() + assert [p.name for p in (kit / "data").iterdir()] == ["hospital-b.csv"], "only its own slice" assert not (tmp_path / "hospital-a").exists() and not (tmp_path / "directory").exists() # no other party's private key, and not the CA key or the directory's signing key assert sorted(p.name for p in (kit / "pki").iterdir()) == ["ca.crt", "directory", "hospital-b", "observer"] @@ -53,7 +62,17 @@ def test_kit_has_every_file_with_the_real_addresses_and_only_its_own_keys(tmp_pa assert sorted(p.name for p in (kit / "pki" / "observer").iterdir()) == ["tls.crt", "token"] assert (kit / "data" / "hospital-b.csv").read_bytes() == (ROOT / "data/slices/hospital-b.csv").read_bytes() - cfg = load_config(kit / "config" / "hospital-b.yaml") + # `.env` is laid out like deploy/node.env.example: the same variables, a Tailscale and a hotspot block + env = provision.read_env((kit / ".env").read_text()) + assert set(env) == set(provision.read_env((ROOT / "deploy/node.env.example").read_text())) + assert env["NODE_ID"] == "hospital-b" and env["NODE_PORT"] == "8002" + assert env["ADVERTISE_ADDR"] == "hospital-b.tail1234.ts.net:8002" + assert env["IMAGE_VERSION"] == provision.IMAGE_VERSION and "MEDCHAIN_IMAGE" not in env + text = (kit / ".env").read_text() + assert "Tailscale" in text and "#DIRECTORY_URL=https://HUB-HOTSPOT-IP:8100" in text + assert "#ADVERTISE_ADDR=THIS-LAPTOPS-HOTSPOT-IP:8002" in text + + cfg = kit_config(kit, monkeypatch) assert cfg.node_id == "hospital-b" and cfg.display_name == "Hospital B" assert cfg.advertise_url == "https://hospital-b.tail1234.ts.net:8002" assert cfg.port == 8002 and cfg.host == "0.0.0.0" @@ -63,44 +82,43 @@ def test_kit_has_every_file_with_the_real_addresses_and_only_its_own_keys(tmp_pa assert cfg.directory.tls_pin_ref == "file:/pki/directory/tls.crt" assert cfg.tls.ca == "/pki/ca.crt" and cfg.signing_key == "/pki/hospital-b/signing.key" assert cfg.shared_secret == SECRET and cfg.data_slice == "/data/hospital-b.csv" + assert cfg.checkpoint_dir == "/data/checkpoints" and cfg.state_dir == "/data" + assert cfg.image_version == provision.IMAGE_VERSION # telemetry is pushed to the observer on the hub (the directory's host by default), pinned, with its token assert cfg.observer.url == "https://100.101.1.99:8200" assert cfg.observer.token_ref == "file:/pki/observer/token" assert cfg.observer.tls_pin_ref == "file:/pki/observer/tls.crt" assert {"100.101.1.99", "localhost"} <= sans(kit / "pki/observer/tls.crt") repo = load_config(ROOT / "config" / "hospital-b.yaml") - assert (cfg.engine, cfg.rho, cfg.bits, cfg.training, cfg.timing) == ( - repo.engine, repo.rho, repo.bits, repo.training, repo.timing) + assert (cfg.engine, cfg.rho, cfg.bits, cfg.training) == (repo.engine, repo.rho, repo.bits, repo.training) + assert cfg.timing.round_timeout_s == 15, "a real network gets a longer round timeout" + # config/node.yaml carries the engine only: nothing about where the node runs or its keys + engine = yaml.safe_load((kit / "config/node.yaml").read_text()) + assert not set(engine) & {"node_id", "port", "advertise_url", "directory", "tls", "shared_secret", "data_slice"} # its certificate is for the address its peers use; its signing key pair matches assert {"hospital-b.tail1234.ts.net", "localhost", "127.0.0.1"} <= sans(kit / "pki/hospital-b/tls.crt") key = load_signing_key(kit / "pki/hospital-b/signing.key") assert public_key_b64(key) == public_key_b64(load_public_key(kit / "pki/hospital-b/signing.pub")) - compose = yaml.safe_load((kit / "docker-compose.hospital.yaml").read_text()) - svc = compose["services"]["hospital-b"] - assert list(compose["services"]) == ["hospital-b"] - assert svc["build"] == {"context": "./source", "dockerfile": "node/Dockerfile"} and svc["ports"] == ["8002:8002"] - assert svc["environment"] == {"NODE_CONFIG": "/config/hospital-b.yaml"}, "no database credentials" - assert {"./config/hospital-b.yaml:/config/hospital-b.yaml:ro", "./data/hospital-b.csv:/data/hospital-b.csv:ro", - "./pki:/pki:ro"} <= set(svc["volumes"]) - readme = (kit / "README.md").read_text() - assert "docker compose -f docker-compose.hospital.yaml up -d --build --wait" in readme - assert "python -m node.leave" in readme and "MEDCHAIN_DIRECTORY_URL" in readme - for text in ("https://hospital-b.tail1234.ts.net:8002", "https://100.101.1.99:8100", "https://100.101.1.99:8200", - SECRET): + assert "docker compose --project-directory . -f deploy/node.yml up -d" in readme + assert "exec node python scripts/preflight.py" in readme and "exec node python -m node.leave" in readme + for text in ("https://100.101.1.99:8100", "https://100.101.1.99:8200", SECRET, "docs/MULTI_LAPTOP.md"): assert text in readme with zipfile.ZipFile(tmp_path / "hospital-b.zip") as z: - assert {"hospital-b/README.md", "hospital-b/pki/hospital-b/signing.key"} <= set(z.namelist()) + assert {"hospital-b/README.md", "hospital-b/.env", "hospital-b/deploy/node.yml", + "hospital-b/pki/hospital-b/signing.key"} <= set(z.namelist()) -def test_one_run_provisions_every_hospital_and_the_directory(tmp_path): +def test_one_run_provisions_every_hospital_and_the_hub(tmp_path, monkeypatch): assert provision.main(["--peers", PEERS, "--directory", DIRECTORY, "--out", str(tmp_path), - "--image", "registry.example/medchain-node:1", "--bind-ip", "100.101.1.10"]) == 0 + "--image", "registry.example:5000/medchain-node:1"]) == 0 ids = ("hospital-a", "hospital-b", "hospital-c") - cfgs = {n: load_config(tmp_path / n / "config" / f"{n}.yaml") for n in ids} + cfgs = {n: kit_config(tmp_path / n, monkeypatch) for n in ids} assert len({c.shared_secret for c in cfgs.values()}) == 1 and cfgs["hospital-a"].shared_secret != "medchain-demo-secret" assert cfgs["hospital-c"].port == 9443 + env = provision.read_env((tmp_path / "hospital-a/.env").read_text()) + assert (env["MEDCHAIN_IMAGE"], env["IMAGE_VERSION"]) == ("registry.example:5000/medchain-node", "1") creds = {n: (tmp_path / n / "pki" / n / "credential").read_text().strip() for n in ids} assert len(set(creds.values())) == 3, "each hospital has its own credential" # the directory kit: its allow-list holds only hashes, in placement order @@ -111,16 +129,17 @@ def test_one_run_provisions_every_hospital_and_the_directory(tmp_path): assert not any((d / "pki" / n).exists() for n in ids), "the directory gets no hospital's private keys" dcfg = yaml.safe_load((d / "config/directory.yaml").read_text()) assert dcfg["port"] == 8100 and dcfg["hospitals_file"] == "/pki/directory/hospitals.yaml" - svc = yaml.safe_load((d / "docker-compose.directory.yaml").read_text())["services"]["directory"] - assert svc["command"] == ["python", "-m", "directory"] and svc["image"] == "registry.example/medchain-node:1" assert {"100.101.1.99", "localhost"} <= sans(d / "pki/directory/tls.crt") + # its hub.env runs deploy/hub.yml: laid out like the example, listening on the hub's Tailscale IP + hub = provision.read_env((d / "hub.env").read_text()) + assert set(hub) - {"MEDCHAIN_IMAGE"} == set(provision.read_env((ROOT / "deploy/hub.env.example").read_text())) + assert hub["HUB_KIT"] == str(d.resolve()) and hub["MEDCHAIN_SHARED_SECRET"] == cfgs["hospital-a"].shared_secret + assert (hub["DIRECTORY_PORT"], hub["OBSERVER_PORT"], hub["HUB_BIND_IP"]) == ("8100", "8200", "100.101.1.99") + assert "#HUB_BIND_IP=0.0.0.0" in (d / "hub.env").read_text() + assert not list(d.glob("*.yaml")) and not (d / "source").exists(), "the hub runs deploy/hub.yml from the repo" # every kit trusts the same CA and the same directory key assert len({(tmp_path / n / "pki/ca.crt").read_bytes() for n in [*ids, "directory"]}) == 1 assert len({(tmp_path / n / "pki/directory/signing.pub").read_bytes() for n in [*ids, "directory"]}) == 1 - svc = yaml.safe_load((tmp_path / "hospital-a" / "docker-compose.hospital.yaml").read_text())["services"]["hospital-a"] - assert svc["image"] == "registry.example/medchain-node:1" and "build" not in svc - assert svc["ports"] == ["100.101.1.10:8001:8001"] and "DATABASE_URL" not in svc["environment"] - assert not (tmp_path / "hospital-a" / "source").exists(), "--image ships no build context" # every kit shares one observer token and pins one observer key; only the hub kit can run the observer tokens = {(tmp_path / n / "pki/observer/token").read_text() for n in [*ids, "directory"]} assert len(tokens) == 1 and tokens != {""} @@ -128,40 +147,64 @@ def test_one_run_provisions_every_hospital_and_the_directory(tmp_path): assert (d / "pki/observer/tls.key").is_file() and not (tmp_path / "hospital-a" / "pki/observer/tls.key").exists() -def test_observer_address_and_token_flags_and_the_database_fallback(tmp_path): - assert run(tmp_path, "--hospital", "hospital-a", "--image", "x", "--observer", "hub.tail1234.ts.net:9200", +def test_hub_kit_inside_the_repo_is_named_relative_to_it_and_a_magicdns_hub_listens_everywhere(tmp_path): + out = ROOT / "kits" / f"test-{tmp_path.name}" + try: + assert provision.main(["--peers", PEERS, "--directory", "hub.tail1234.ts.net:8100", "--out", str(out), + "--hospital", "directory", "--pki", str(tmp_path / "pki")]) == 0 + hub = provision.read_env((out / "directory/hub.env").read_text()) + assert hub["HUB_KIT"] == f"./kits/test-{tmp_path.name}/directory" + assert hub["HUB_BIND_IP"] == "0.0.0.0", "a name is not an address to listen on" + assert provision.main(["--peers", PEERS, "--directory", "hub.tail1234.ts.net:8100", "--out", str(out), + "--hospital", "directory", "--pki", str(tmp_path / "pki"), "--force", + "--bind-ip", "100.101.1.99"]) == 0 + assert provision.read_env((out / "directory/hub.env").read_text())["HUB_BIND_IP"] == "100.101.1.99" + finally: + shutil.rmtree(out, ignore_errors=True) + + +def test_observer_address_and_token_flags(tmp_path, monkeypatch): + assert run(tmp_path, "--hospital", "hospital-a", "--observer", "hub.tail1234.ts.net:9200", "--observer-token", "tok-1") == 0 kit = tmp_path / "hospital-a" - cfg = load_config(kit / "config" / "hospital-a.yaml") + cfg = kit_config(kit, monkeypatch) assert cfg.observer.url == "https://hub.tail1234.ts.net:9200" assert (kit / "pki/observer/token").read_text().strip() == "tok-1" assert "hub.tail1234.ts.net" in sans(kit / "pki/observer/tls.crt") # the token is kept with the network: a later run without --observer-token reuses it - assert run(tmp_path / "again", "--hospital", "hospital-b", "--image", "x", "--pki", str(tmp_path / ".pki")) == 0 + assert run(tmp_path / "again", "--hospital", "hospital-b", "--pki", str(tmp_path / ".pki")) == 0 assert (tmp_path / "again/hospital-b/pki/observer/token").read_text().strip() == "tok-1" - # --observer-db is an explicit fallback: the node writes Postgres directly instead of pushing - dsn = "postgresql://medchain:medchain@127.0.0.1:5432/medchain" - assert run(tmp_path / "db", "--hospital", "hospital-a", "--image", "x", "--observer-db", dsn) == 0 - assert load_config(tmp_path / "db/hospital-a/config/hospital-a.yaml").observer is None - svc = yaml.safe_load((tmp_path / "db/hospital-a/docker-compose.hospital.yaml").read_text())["services"]["hospital-a"] - assert svc["environment"]["DATABASE_URL"] == dsn assert provision.main(["--peers", PEERS, "--directory", DIRECTORY, "--observer", "http://hub:8200", - "--out", str(tmp_path / "bad"), "--image", "x"]) == 2 + "--out", str(tmp_path / "bad")]) == 2 + + +def test_the_node_yml_environment_and_the_example_env_load_as_a_node(monkeypatch): + """deploy/node.yml + deploy/node.env.example, as Compose would hand them to the node (no files are read).""" + env = provision.container_env(provision.read_env((ROOT / "deploy/node.env.example").read_text())) + assert env["TLS_CERT"] == "/pki/hospital-b/tls.crt" and env["DATA_PATH"] == "/data" + for k, v in env.items(): + monkeypatch.setenv(k, v) + monkeypatch.delenv("NODE_CONFIG") # the kit's config/node.yaml only adds the engine settings + cfg = load_config() + assert cfg.advertise_url == "https://hospital-b-laptop.tail1234.ts.net:8002" and cfg.port == 8002 + assert cfg.directory.url == "https://organiser-laptop.tail1234.ts.net:8100" and cfg.observer is not None + with pytest.raises(ValueError, match="NODE_ID"): + provision.interpolate("${NODE_ID:?set NODE_ID}", {}) -def test_adding_a_hospital_later_reuses_the_network_and_admits_it(tmp_path): - assert run(tmp_path, "--image", "x") == 0 +def test_adding_a_hospital_later_reuses_the_network_and_admits_it(tmp_path, monkeypatch): + assert run(tmp_path) == 0 ca = (tmp_path / ".pki" / "ca.crt").read_bytes() a_key = (tmp_path / ".pki" / "hospital-a" / "signing.key").read_bytes() data = tmp_path / "e.csv" data.write_bytes((ROOT / "data/slices/hospital-e.csv").read_bytes()) peers = PEERS + ",hospital-e=10.0.0.5:8105" assert provision.main(["--peers", peers, "--directory", DIRECTORY, "--hospital", "hospital-e", "--secret", SECRET, - "--data", f"hospital-e={data}", "--image", "x", "--out", str(tmp_path)]) == 0 + "--data", f"hospital-e={data}", "--out", str(tmp_path)]) == 0 assert (tmp_path / ".pki" / "ca.crt").read_bytes() == ca, "same CA" assert (tmp_path / ".pki" / "hospital-a" / "signing.key").read_bytes() == a_key, "nobody else is re-keyed" assert (tmp_path / "hospital-e" / "pki" / "ca.crt").read_bytes() == ca - cfg = load_config(tmp_path / "hospital-e" / "config" / "hospital-e.yaml") + cfg = kit_config(tmp_path / "hospital-e", monkeypatch) assert (cfg.node_id, cfg.port, cfg.engine) == ("hospital-e", 8105, "qgadmm") allowed = yaml.safe_load((tmp_path / ".pki" / "directory" / "hospitals.yaml").read_text()) assert [h["id"] for h in allowed] == ["hospital-a", "hospital-b", "hospital-c", "hospital-e"] @@ -171,10 +214,10 @@ def test_adding_a_hospital_later_reuses_the_network_and_admits_it(tmp_path): def test_a_changed_address_gets_a_new_certificate(tmp_path): - assert run(tmp_path, "--hospital", "hospital-a", "--image", "x") == 0 + assert run(tmp_path, "--hospital", "hospital-a") == 0 moved = PEERS.replace("100.101.1.10", "100.101.1.77") assert provision.main(["--peers", moved, "--directory", DIRECTORY, "--secret", SECRET, "--hospital", "hospital-a", - "--image", "x", "--out", str(tmp_path), "--force"]) == 0 + "--out", str(tmp_path), "--force"]) == 0 assert "100.101.1.77" in sans(tmp_path / "hospital-a" / "pki/hospital-a/tls.crt") @@ -187,7 +230,7 @@ def test_a_changed_address_gets_a_new_certificate(tmp_path): ("hospital-a=10.0.0.1:8001,hospital-b=10.0.0.2:8002", ["--hospital", "hospital-c"]), ]) def test_rejects_bad_peer_lists(tmp_path, peers, extra): - assert provision.main(["--peers", peers, "--directory", DIRECTORY, "--out", str(tmp_path), "--image", "x", + assert provision.main(["--peers", peers, "--directory", DIRECTORY, "--out", str(tmp_path), *extra]) == 2 @@ -196,6 +239,6 @@ def test_rejects_a_plain_http_directory(tmp_path): def test_refuses_to_overwrite_a_kit_unless_forced(tmp_path): - assert run(tmp_path, "--hospital", "hospital-a", "--image", "x") == 0 - assert run(tmp_path, "--hospital", "hospital-a", "--image", "x") == 2 - assert run(tmp_path, "--hospital", "hospital-a", "--image", "x", "--force") == 0 + assert run(tmp_path, "--hospital", "hospital-a") == 0 + assert run(tmp_path, "--hospital", "hospital-a") == 2 + assert run(tmp_path, "--hospital", "hospital-a", "--force") == 0