From e2717de83be08e822c9b4cbb8c76bdafb3d757a0 Mon Sep 17 00:00:00 2001 From: Denimworld12 <166978100+Denimworld12@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:32:26 +0530 Subject: [PATCH 01/16] feat(enroll): per-hospital join codes for remote hospitals, next to the kits A hospital on another laptop can now join with a one-time join code instead of a kit made and emailed by the organiser: - directory: POST /enroll checks the code (single use, expiring, stored as its SHA-256, revoked after 5 wrong proofs), issues a CA-signed certificate for the node's own TLS key (from a CSR), a node id and a per-hospital observer token; /admin/join-codes creates, lists and revokes codes with the hub's admin token. Every attempt and code change is audited (directory store + Postgres audit_logs). An enrolled hospital may only register with the keys it enrolled with. - node/enroll.py: makes the keys locally (private keys never leave), proves the code with an HMAC keyed by its hash, verifies the hub's HMAC'd answer, nonce and TLS pin, and writes a kit laid out like provision.py's (secret in pki/network/shared_secret via SHARED_SECRET_FILE, never printed). - observer: accepts a hospital's own token, which only writes as that hospital, checked against hospital_keys (written only by the directory, never /ingest). - provision.py: the hub kit carries the CA key; kits and make up are unchanged. - image v1.1.0 default (ships deploy/node.yml for the enrolled kit). --- README.md | 42 ++++- config/directory.yaml | 14 ++ deploy/hub.env.example | 2 +- deploy/hub.yml | 17 +- deploy/node.env.example | 2 +- deploy/node.yml | 2 +- directory/app.py | 164 ++++++++++++++++- directory/enroll.py | 216 ++++++++++++++++++++++ directory/store.py | 95 +++++++++- docker-compose.yml | 12 +- node/Dockerfile | 2 + node/config.py | 11 ++ node/db.py | 43 ++++- node/enroll.py | 346 +++++++++++++++++++++++++++++++++++ node/security.py | 34 +++- node/settings.py | 5 +- node/writer.py | 4 +- observer/app.py | 42 ++++- scripts/pki.py | 25 +-- scripts/provision.py | 27 +-- tests/unit/chain_harness.py | 4 +- tests/unit/test_enroll.py | 230 +++++++++++++++++++++++ tests/unit/test_observer.py | 48 +++++ tests/unit/test_provision.py | 4 + tests/unit/test_settings.py | 9 +- 25 files changed, 1330 insertions(+), 70 deletions(-) create mode 100644 directory/enroll.py create mode 100644 node/enroll.py create mode 100644 tests/unit/test_enroll.py diff --git a/README.md b/README.md index 480376e..853a559 100644 --- a/README.md +++ b/README.md @@ -411,8 +411,8 @@ epsilon on four or more. ### The directory -`directory/` is a small FastAPI service with three calls: `POST /register`, -`POST /leave` and `GET /membership`. Be clear about what it is: it **does +`directory/` is a small FastAPI service with three membership calls: `POST /register`, +`POST /leave` and `GET /membership` (plus `POST /enroll` for join codes, below). Be clear about what it is: it **does coordinate membership**. It decides where a new hospital goes in the chain and tells the existing hospitals who to connect to, so it is more than a phone book. It is a **single point of failure for joins and leaves, not for @@ -615,7 +615,7 @@ is never re-keyed. Every hospital kit holds: - `README.md`, with the exact commands, including how to leave the chain. `--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`. +default the kits use the published `ghcr.io/denimworld12/medchain-node:v1.1.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 @@ -672,6 +672,42 @@ with `-` and other characters turned into `_`. runs next to Postgres. It never coordinates training. A node with no observer still trains and still serves `/status` and `/metrics`. +### Join with a code instead of a kit + +A kit has to be made, zipped and sent, and it carries the network's shared secret. +For a hospital on another laptop there is a second way in, next to the kits (which +keep working unchanged): a **join code**. + +1. The organiser creates a code on the dashboard's admin page. It works **once** and + **expires** (30 minutes by default); the organiser can revoke it. The directory + keeps only its SHA-256. +2. On the hospital's laptop, `python -m node.enroll` (run by the install script in + `deploy/install/`, inside the published image) makes the hospital's keys **on that + laptop**: a TLS key, an Ed25519 signing key and a directory credential. It sends the + hub only a certificate signing request, the public signing key and the credential's + hash, with the display name the person typed, to `POST /enroll` on the directory. + It proves it holds the code with an HMAC keyed by the code's hash, so the code itself + never crosses the network. +3. The directory checks the code (known, unused, unrevoked, unexpired, the right + secret; five wrong tries revoke it), marks it used, and answers with: a certificate + for the hospital's key from the network CA, the CA certificate, the directory's + document key and certificate, the observer's certificate and port, an **observer + token for this hospital alone**, a generated node id, the engine settings, a data + slice, and the network secret. Its answer carries an HMAC under the same key, and + the node checks it, the nonce, and that the TLS key that answered is the + directory's, before trusting any of it. +4. The node writes a kit folder with the same layout as a provisioned one, so + `deploy/node.yml` runs it. The secret goes to `pki/network/shared_secret` + (`SHARED_SECRET_FILE`): nobody types it, nothing prints it. + +Every attempt is in the audit log (`enrolled`, `enroll_rejected`, +`join_code_created`, `join_code_revoked`). An enrolled hospital may only register +with the keys it enrolled with. Its observer token only writes rows as that hospital; +the observer checks it against `hospital_keys`, which only the directory writes. The +directory needs the CA key for this: `provision.py` puts it in the hub kit +(`pki/ca.key`), and `deploy/hub.yml` mounts `data/slices/` and +`config/hospital-a.yaml` (the engine settings) into it. + ### Prove it `scripts/verify_multihost.py` is the acceptance test, on real laptops or on one diff --git a/config/directory.yaml b/config/directory.yaml index 9b182ff..aaa78c2 100644 --- a/config/directory.yaml +++ b/config/directory.yaml @@ -14,3 +14,17 @@ tls: cert: /pki/directory/tls.crt key: /pki/directory/tls.key ca: /pki/ca.crt +# the hub's admin token, for the dashboard's admin page (join codes): made on first start; the +# dashboard reads the same file +admin_token_file: /hub/admin_token +# Join codes (directory/enroll.py): a hospital on another laptop enrolls with a one-time code +# from the dashboard instead of a kit. Its own keys stay on its laptop; the directory issues +# its certificate with the network CA, so it needs the CA key. +enrollment: + ca_cert: /pki/ca.crt + ca_key: /pki/ca.key + observer_cert: /pki/observer/tls.crt # enrolled hospitals pin the observer's key + observer_port: 8200 + slices_dir: /slices # the data slices a code hands out + node_template: /templates/node.yaml # its engine settings are every hospital's + code_ttl_minutes: 30 diff --git a/deploy/hub.env.example b/deploy/hub.env.example index dc9a2f3..15b1448 100644 --- a/deploy/hub.env.example +++ b/deploy/hub.env.example @@ -6,7 +6,7 @@ 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 +IMAGE_VERSION=v1.1.0 # The ports in the directory's and the observer's addresses (provision.py --directory / --observer) DIRECTORY_PORT=8100 OBSERVER_PORT=8200 diff --git a/deploy/hub.yml b/deploy/hub.yml index 75b7770..c320449 100644 --- a/deploy/hub.yml +++ b/deploy/hub.yml @@ -1,7 +1,8 @@ # 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 +# directory membership only: where a hospital sits in the chain, who bridges a leave; +# and join codes, for hospitals that enroll instead of getting a kit # 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 @@ -16,7 +17,7 @@ name: medchain-hub x-medchain: &medchain - image: ${MEDCHAIN_IMAGE:-ghcr.io/denimworld12/medchain-node}:${IMAGE_VERSION:-v1.0.0} + image: ${MEDCHAIN_IMAGE:-ghcr.io/denimworld12/medchain-node}:${IMAGE_VERSION:-v1.1.0} restart: unless-stopped services: @@ -42,10 +43,21 @@ services: command: ["python", "-m", "directory"] environment: DIRECTORY_CONFIG: /config/directory.yaml + # the audit log and the hospitals' keys on record (the observer checks per-hospital tokens against them) + DATABASE_URL: postgresql://medchain:medchain@postgres:5432/medchain + # handed to hospitals that enroll with a join code, so nobody types it + MEDCHAIN_SHARED_SECRET: ${MEDCHAIN_SHARED_SECRET:?set MEDCHAIN_SHARED_SECRET (the kits' shared secret) in hub.env} 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 + - hub-secrets:/hub # the admin token the dashboard's admin page uses (made on first start) + # join codes hand out a data slice and the engine settings every hospital shares + - ./data/slices:/slices:ro + - ./config/hospital-a.yaml:/templates/node.yaml:ro + depends_on: + postgres: + condition: service_healthy 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}" @@ -102,3 +114,4 @@ services: volumes: postgres-data: directory-data: + hub-secrets: diff --git a/deploy/node.env.example b/deploy/node.env.example index ada32ec..3d6850d 100644 --- a/deploy/node.env.example +++ b/deploy/node.env.example @@ -22,7 +22,7 @@ OBSERVER_URL=https://organiser-laptop.tail1234.ts.net: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 +IMAGE_VERSION=v1.1.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 diff --git a/deploy/node.yml b/deploy/node.yml index 3ac776a..b731489 100644 --- a/deploy/node.yml +++ b/deploy/node.yml @@ -20,7 +20,7 @@ name: medchain-${NODE_ID:?set NODE_ID in .env, and run from your kit folder with services: node: - image: ${MEDCHAIN_IMAGE:-ghcr.io/denimworld12/medchain-node}:${IMAGE_VERSION:-v1.0.0} + image: ${MEDCHAIN_IMAGE:-ghcr.io/denimworld12/medchain-node}:${IMAGE_VERSION:-v1.1.0} env_file: .env # where the kit's files are inside the container (these win over `.env`) environment: diff --git a/directory/app.py b/directory/app.py index 5c1040c..7818e64 100644 --- a/directory/app.py +++ b/directory/app.py @@ -11,6 +11,10 @@ POST /leave planned departure: the hospital is taken out and its two neighbours are told to bridge to each other. GET /membership the current signed membership document. + POST /enroll a new hospital joins the network with a one-time join code instead of a + kit: it gets its certificate, pins and node id (directory/enroll.py). + /admin/join-codes create, list and revoke join codes; for the dashboard's admin page, with + the hub's admin token (`admin_token_file`, made on first start). So it does coordinate membership: it decides where a new hospital goes and tells the existing hospitals who to connect to. Placement: while no run is in progress, @@ -25,6 +29,12 @@ keep training. Its storage (directory/store.py, SQLite) is separate from the Postgres the dashboard reads. Every document it issues is signed with its Ed25519 key, so nodes can pass documents to each other and nobody can forge one. + +Who may register: the kit hospitals in `hospitals_file` (scripts/provision.py) and the +hospitals that enrolled with a join code (its store). An enrolled hospital must register +with the keys it enrolled with. With DATABASE_URL set, every enrollment attempt and join-code +change also goes to the dashboard's audit log, and each hospital's keys on record go to +Postgres (`hospital_keys`), where the observer checks per-hospital tokens and signatures. """ from __future__ import annotations @@ -32,8 +42,10 @@ import asyncio import hashlib import hmac +import json import logging import os +import secrets from collections import Counter from contextlib import asynccontextmanager from dataclasses import dataclass @@ -45,9 +57,12 @@ from pydantic import BaseModel from node import pinning, security +from node.db import Database, NullDatabase from node.discovery import push_membership from node.membership import Member, Membership +from node.writer import DbWriter +from .enroll import Enroller, EnrollmentConfig, EnrollmentError from .store import Store log = logging.getLogger("medchain.directory") @@ -67,6 +82,8 @@ class DirectoryConfig: tls_cert: str | None = None tls_key: str | None = None ca: str | None = None # verifies the nodes' certificates when it calls them + admin_token_file: str | None = None # the dashboard's admin API token (created on first start) + enrollment: EnrollmentConfig | None = None # join codes (directory/enroll.py); needs `tls:` and the CA key def load_config(path: str | os.PathLike | None = None) -> DirectoryConfig: @@ -81,7 +98,9 @@ def load_config(path: str | os.PathLike | None = None) -> DirectoryConfig: return DirectoryConfig(port=int(raw["port"]), signing_key=str(raw["signing_key"]), hospitals_file=str(raw["hospitals_file"]), db_path=str(raw["db_path"]), host=str(raw.get("host", "0.0.0.0")), margin_rounds=int(raw.get("margin_rounds", 3)), - tls_cert=tls.get("cert"), tls_key=tls.get("key"), ca=tls.get("ca")) + tls_cert=tls.get("cert"), tls_key=tls.get("key"), ca=tls.get("ca"), + admin_token_file=raw.get("admin_token_file"), + enrollment=EnrollmentConfig.from_yaml(raw.get("enrollment"))) def credential_hash(credential: str) -> str: @@ -101,25 +120,79 @@ class LeaveRequest(BaseModel): node_id: str -def create_app(cfg: DirectoryConfig | None = None) -> FastAPI: +class NewCode(BaseModel): + created_by: str | None = None + ttl_minutes: int | None = None + data_slice: str | None = None + + +class Revoke(BaseModel): + revoked_by: str | None = None + + +MAX_ENROLL_BYTES = 64 * 1024 + + +def admin_token(path: str) -> str: + """The hub's admin token: made on first start, read by the dashboard from the same file.""" + p = Path(path) + if not p.is_file(): + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(secrets.token_urlsafe(32) + "\n") + p.chmod(0o600) + return p.read_text().strip() + + +def create_app(cfg: DirectoryConfig | None = None, database: Database | None = None) -> FastAPI: cfg = cfg or load_config() key = security.load_signing_key(cfg.signing_key) store = Store(cfg.db_path) lock = asyncio.Lock() state: dict = {} + dsn = os.environ.get("DATABASE_URL") + db = DbWriter(database or (Database(dsn) if dsn else NullDatabase())) # queued: never waited for + admin = admin_token(cfg.admin_token_file) if cfg.admin_token_file else None - def hospitals() -> list[dict]: - """Re-read on every request, so the operator can add a hospital's credential without a restart.""" + def configured() -> list[dict]: + """The kit hospitals, re-read on every request, so the operator can add one without a restart.""" return list(yaml.safe_load(Path(cfg.hospitals_file).read_text()) or []) - def authenticate(request: Request, node_id: str) -> int: - """The caller must hold `node_id`'s own credential. Returns that hospital's placement rank.""" + def hospitals() -> list[dict]: + """Everyone who may register, in placement order: the kit hospitals, then the enrolled ones.""" + return configured() + [{"id": r["node_id"], "credential_sha256": r["credential_sha256"], "enrolled": r} + for r in store.enrolled()] + + enroller = (Enroller(cfg.enrollment, store, signing_key=key, directory_cert=cfg.tls_cert, + configured_ids=lambda: [str(h["id"]) for h in configured()]) + if cfg.enrollment and cfg.tls_cert else None) + + def audit(event: str, node_id: str | None, detail: dict, sender: str | None = None) -> None: + """The directory's own log, and the dashboard's audit log.""" + store.log(event, node_id, detail) + db.audit(node_id="directory", event=event, sender=sender or node_id, detail=detail) + + def require_admin(request: Request) -> None: + auth = request.headers.get("Authorization", "") + given = auth[7:] if auth.startswith("Bearer ") else "" + if admin is None: + raise HTTPException(503, detail="this directory has no admin API (set admin_token_file)") + if not given or not hmac.compare_digest(given.encode(), admin.encode()): + raise HTTPException(401, detail="the hub's admin token is required") + + def require_enrollment() -> Enroller: + if enroller is None: + raise HTTPException(503, detail="this hub does not take join codes (its directory config has no " + "`enrollment:` block, or no `tls:`)") + return enroller + + def authenticate(request: Request, node_id: str) -> tuple[int, dict | None]: + """The caller must hold `node_id`'s own credential. Returns its placement rank (and its enrollment).""" auth = request.headers.get("Authorization", "") given = auth[7:] if auth.startswith("Bearer ") else "" for rank, h in enumerate(hospitals()): if str(h["id"]) == node_id: if given and hmac.compare_digest(credential_hash(given), str(h["credential_sha256"])): - return rank + return rank, h.get("enrolled") store.log("auth_failed", node_id, {"reason": "bad credential"}) raise HTTPException(401, detail=f"bad credential for {node_id}") store.log("auth_failed", node_id, {"reason": "unknown hospital"}) @@ -198,12 +271,15 @@ async def lifespan(app: FastAPI): timeout = httpx.Timeout(3.0, connect=1.5) state["client"] = (pinning.pinned_client(cfg.ca, cfg.tls_cert, cfg.tls_key, expected_pins, timeout) if cfg.ca else httpx.AsyncClient(timeout=timeout)) - log.info("directory up on :%d (%s), %d hospitals known", cfg.port, "https" if cfg.tls_cert else "http", - len(hospitals())) + db.start() + db.ensure_schema() + log.info("directory up on :%d (%s), %d hospitals known%s", cfg.port, "https" if cfg.tls_cert else "http", + len(hospitals()), ", taking join codes" if enroller else "") try: yield finally: await state["client"].aclose() + db.stop() app = FastAPI(title="MedChain directory", lifespan=lifespan) app.state.store = store @@ -225,7 +301,7 @@ async def membership(request: Request): @app.post("/register") async def register(req: RegisterRequest, request: Request): - rank = authenticate(request, req.node_id) + rank, enrolled = authenticate(request, req.node_id) if req.public_key: try: security.parse_public_key(req.public_key) @@ -238,7 +314,13 @@ async def register(req: RegisterRequest, request: Request): require_own_key(request, req) if not req.url.startswith(("http://", "https://")): raise HTTPException(400, detail="url must be http(s)://") + if enrolled and (req.public_key, req.tls_spki_sha256) != (enrolled["signing_public_key"], enrolled["tls_pin"]): + store.log("auth_failed", req.node_id, {"reason": "keys differ from the ones it enrolled with"}) + raise HTTPException(403, detail=f"{req.node_id} must register with the keys it enrolled with; to change " + "them, enroll again with a new join code") me = Member(req.node_id, req.url.rstrip("/"), req.public_key, req.display_name, req.tls_spki_sha256) + db.hospital_key(node_id=req.node_id, display_name=req.display_name or req.node_id, + signing_public_key=req.public_key, tls_pin=req.tls_spki_sha256) async with lock: latest = store.latest() chain = list(latest.chain) if latest else [] @@ -289,4 +371,66 @@ async def events(request: Request, limit: int = 100): require_any_hospital(request) return {"events": store.events(limit)} + # -- join codes ----------------------------------------------------------------------------- + @app.post("/enroll") + async def enroll(request: Request): + """A new hospital, with a join code (directory/enroll.py). No credential: the code is the credential.""" + e = require_enrollment() + raw = await request.body() + req: dict = {} + try: + if len(raw) > MAX_ENROLL_BYTES: + raise EnrollmentError(413, "enrollment request too large") + try: + req = json.loads(raw) + except ValueError: + req = None + if not isinstance(req, dict): + req = {} + raise EnrollmentError(400, "the enrollment request is not a JSON object") + answer, record = e.enroll(req) + except EnrollmentError as exc: + audit("enroll_rejected", None, {"code_id": str(req.get("code_id", ""))[:8], + "display_name": " ".join(str(req.get("display_name", "")).split())[:80], + "reason": exc.detail, "client": request.client.host if request.client else None}) + raise HTTPException(exc.status, detail=exc.detail) + audit("enrolled", record["node_id"], {"code_id": record["code_id"], "display_name": record["display_name"], + "data_slice": record["data_slice"], "tls_pin": record["tls_pin"], + "client": request.client.host if request.client else None}) + db.hospital_key(node_id=record["node_id"], display_name=record["display_name"], + signing_public_key=record["signing_public_key"], tls_pin=record["tls_pin"], + observer_token_sha256=record["observer_token_sha256"], enrolled=True) + log.info("enrolled %s as %s (code %s)", record["display_name"], record["node_id"], record["code_id"]) + return answer + + @app.post("/admin/join-codes") + async def create_code(req: NewCode, request: Request): + require_admin(request) + e = require_enrollment() + try: + out = e.create_code(req.created_by, req.ttl_minutes, req.data_slice) + except EnrollmentError as exc: + raise HTTPException(exc.status, detail=exc.detail) + audit("join_code_created", None, {"code_id": out["code_id"], "expires_at": out["expires_at"], + "data_slice": out["data_slice"], "by": req.created_by}, sender=req.created_by) + return out + + @app.get("/admin/join-codes") + async def list_codes(request: Request): + require_admin(request) + e = require_enrollment() + return {"codes": [{**c, "state": e.state(c)} for c in store.codes()], "slices": e.slices(), + "ttl_minutes": e.cfg.code_ttl_minutes, + "hospitals": [{k: r[k] for k in ("node_id", "display_name", "data_slice", "code_id", "enrolled_at")} + for r in store.enrolled()]} + + @app.post("/admin/join-codes/{code_id}/revoke") + async def revoke_code(code_id: str, req: Revoke, request: Request): + require_admin(request) + require_enrollment() + if not store.revoke_code(code_id, req.revoked_by): + raise HTTPException(409, detail=f"join code {code_id} is not active (unknown, used or already revoked)") + audit("join_code_revoked", None, {"code_id": code_id, "by": req.revoked_by}, sender=req.revoked_by) + return {"code_id": code_id, "state": "revoked"} + return app diff --git a/directory/enroll.py b/directory/enroll.py new file mode 100644 index 0000000..a223e1e --- /dev/null +++ b/directory/enroll.py @@ -0,0 +1,216 @@ +"""The hub's side of join-code enrollment (the node's side and the protocol: node/enroll.py). + +The organiser creates a join code from the dashboard's admin page (the directory's admin +API, directory/app.py): single use, expiring (30 minutes by default), stored only as its +SHA-256. A hospital POSTs /enroll with the code's id, a proof that it holds the code, its +display name, a certificate signing request for its own TLS key, the public half of its +update-signing key and the hash of a directory credential it made itself. Its private keys +never leave it. + +If the code is valid, the directory marks it used (atomically: one winner), issues the +node a certificate from the network CA, generates its node id and an observer ingest token +for it alone, and answers with everything a kit would hold except private keys. Every +attempt, accepted or not, is written to the audit log. +""" + +from __future__ import annotations + +import hashlib +import os +import re +import secrets +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +import yaml +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from node import enroll as protocol +from node import pinning, security +from node.config import engine_settings + +from .store import Store + +DEFAULT_TTL_MINUTES = 30 +MAX_TTL_MINUTES = 24 * 60 +NAME = re.compile(r"^[^\x00-\x1f\x7f]{2,60}$") +HEX64 = re.compile(r"^[0-9a-f]{64}$") + + +@dataclass(frozen=True) +class EnrollmentConfig: + """The `enrollment:` block of the directory's config. Without one, /enroll answers 503.""" + + ca_cert: str + ca_key: str + observer_cert: str # the observer's TLS certificate: enrolled nodes pin its key + slices_dir: str # the data slices a code may hand out (*.csv) + node_template: str # a node config: its engine settings are the ones every hospital of this network shares + observer_port: int = 8200 + code_ttl_minutes: int = DEFAULT_TTL_MINUTES + shared_secret_file: str | None = None # the network secret; default $MEDCHAIN_SHARED_SECRET + + @classmethod + def from_yaml(cls, raw: dict | None) -> "EnrollmentConfig | None": + if not raw: + return None + missing = [k for k in ("ca_cert", "ca_key", "observer_cert", "slices_dir", "node_template") if not raw.get(k)] + if missing: + raise ValueError(f"directory enrollment block: missing {missing}") + return cls(**{k: raw[k] for k in cls.__dataclass_fields__ if k in raw}) + + @property + def shared_secret(self) -> str: + secret = (Path(self.shared_secret_file).read_text().strip() if self.shared_secret_file + else os.environ.get("MEDCHAIN_SHARED_SECRET", "")) + if not secret: + raise EnrollmentError(503, "the hub has no network secret to hand out (set MEDCHAIN_SHARED_SECRET for " + "the directory)") + return secret + + +class EnrollmentError(Exception): + def __init__(self, status: int, detail: str): + super().__init__(detail) + self.status, self.detail = status, detail + + +def _pem(cert: x509.Certificate) -> str: + return cert.public_bytes(serialization.Encoding.PEM).decode() + + +class Enroller: + def __init__(self, cfg: EnrollmentConfig, store: Store, *, signing_key, directory_cert: str, + configured_ids: Callable[[], list[str]]): + self.cfg, self.store, self.signing_key = cfg, store, signing_key + self.directory_cert = directory_cert + self.configured_ids = configured_ids # the kit hospitals (hospitals.yaml), whose ids are taken + + # -- join codes ----------------------------------------------------------------------------- + def slices(self) -> list[str]: + return sorted(p.name for p in Path(self.cfg.slices_dir).glob("*.csv")) + + def create_code(self, created_by: str | None, ttl_minutes: int | None = None, + data_slice: str | None = None) -> dict: + """A new single-use code. The full code is only ever in this answer: the store keeps its hash.""" + ttl = int(ttl_minutes or self.cfg.code_ttl_minutes) + if not 1 <= ttl <= MAX_TTL_MINUTES: + raise EnrollmentError(400, f"a join code lasts 1 to {MAX_TTL_MINUTES} minutes") + if data_slice and data_slice not in self.slices(): + raise EnrollmentError(400, f"no data slice {data_slice!r} on the hub (have {self.slices()})") + expires_at = time.time() + 60 * ttl + for _ in range(20): # the id is the first group: retry on the rare collision + code = protocol.new_code() + if self.store.add_code(protocol.code_id(code), protocol.code_key(code), created_by, expires_at, + data_slice or None): + return {"code": code, "code_id": protocol.code_id(code), "expires_at": expires_at, + "data_slice": data_slice or None} + raise EnrollmentError(503, "could not find a free join code id") + + @staticmethod + def state(row: dict, now: float | None = None) -> str: + now = time.time() if now is None else now + if row["used_at"]: + return "used" + if row["revoked_at"]: + return "revoked" + return "expired" if row["expires_at"] <= now else "active" + + # -- enrollment ------------------------------------------------------------------------------- + def new_node_id(self) -> str: + taken = {*self.configured_ids(), *(r["node_id"] for r in self.store.enrolled()), "directory", "observer"} + while True: + node_id = f"node-{secrets.token_hex(4)}" + if node_id not in taken: + return node_id + + def pick_slice(self, wanted: str | None) -> str: + """The code's slice, else the one the fewest enrolled hospitals have (kit hospitals' own slices last).""" + names = self.slices() + if wanted: + if wanted not in names: + raise EnrollmentError(503, f"the join code's data slice {wanted} is not on the hub") + return wanted + if not names: + raise EnrollmentError(503, "the hub has no data slices to hand out") + used = [r["data_slice"] for r in self.store.enrolled()] + configured = {f"{i}.csv" for i in self.configured_ids()} + return min(names, key=lambda n: (used.count(n), n in configured, n)) + + def check(self, req: dict) -> tuple[dict, str, x509.CertificateSigningRequest, list[str]]: + """Validate the request's shape and the join code. Returns (the code's row and key, the CSR, the addresses).""" + found = self.store.code(str(req.get("code_id", ""))) + if found is None: + raise EnrollmentError(403, "unknown join code: check it with the organiser") + row, key = found + state = self.state(row) + if state != "active": + raise EnrollmentError(403, f"this join code has {'been ' if state != 'expired' else ''}{state}: " + "ask the organiser for a new one") + proof = req.get("proof") + if not protocol.check_mac(key, "request", {k: v for k, v in req.items() if k != "proof"}, proof): + revoked = self.store.code_failure(row["code_id"]) + raise EnrollmentError(403, "the join code is wrong (check every character)" + + ("; it was revoked after too many wrong attempts" if revoked else "")) + try: + csr = x509.load_pem_x509_csr(str(req.get("csr", "")).encode()) + if not csr.is_signature_valid: + raise ValueError("the certificate request's signature does not verify") + if not isinstance(csr.public_key(), ec.EllipticCurvePublicKey): + raise ValueError("the TLS key must be an EC key") + security.parse_public_key(str(req.get("signing_public_key", ""))) + if not HEX64.match(str(req.get("credential_sha256", ""))): + raise ValueError("credential_sha256 must be 64 lowercase hex digits") + addresses = [protocol.check_address(a) for a in req.get("addresses") or []] + if not 1 <= len(addresses) <= 8: + raise ValueError("give 1 to 8 addresses this node is reached at") + if not isinstance(req.get("nonce"), str) or not 16 <= len(req["nonce"]) <= 128: + raise ValueError("nonce must be 16 to 128 characters") + except (ValueError, TypeError) as exc: + raise EnrollmentError(400, f"malformed enrollment: {exc}") from exc + name = " ".join(str(req.get("display_name", "")).split()) + if not NAME.match(name): + raise EnrollmentError(400, "the display name must be 2 to 60 characters") + return row, key, csr, addresses + + def enroll(self, req: dict) -> tuple[dict, dict]: + """(the answer for the node, the hospital's enrolled record). Raises EnrollmentError.""" + code_row, key, csr, addresses = self.check(req) + name = " ".join(str(req["display_name"]).split()) + data_slice = self.pick_slice(code_row["data_slice"]) + secret = self.cfg.shared_secret + ca_cert = x509.load_pem_x509_certificate(Path(self.cfg.ca_cert).read_bytes()) + ca_key = serialization.load_pem_private_key(Path(self.cfg.ca_key).read_bytes(), password=None) + node_id = self.new_node_id() + if not self.store.consume_code(code_row["code_id"], node_id): # someone else used it a moment ago + raise EnrollmentError(403, "this join code has just been used: ask the organiser for a new one") + cert = security.issue_certificate(ca_cert, ca_key, csr.public_key(), node_id, + [*addresses, node_id, "localhost", "127.0.0.1"]) + token = secrets.token_urlsafe(32) + record = {"node_id": node_id, "display_name": name, "credential_sha256": req["credential_sha256"], + "signing_public_key": req["signing_public_key"], "tls_pin": pinning.spki_sha256(cert), + "observer_token_sha256": hashlib.sha256(token.encode()).hexdigest(), "data_slice": data_slice, + "code_id": code_row["code_id"], "enrolled_at": time.time()} + self.store.add_enrolled(record) + engine = engine_settings(yaml.safe_load(Path(self.cfg.node_template).read_text()) or {}) + engine.pop("display_name", None) + answer = { + "node_id": node_id, + "display_name": name, + "certificate": _pem(cert), + "ca_certificate": _pem(ca_cert), + "directory": {"signing_public_key": security.public_key_b64(self.signing_key), + "tls_certificate": Path(self.directory_cert).read_text()}, + "observer": {"port": self.cfg.observer_port, "tls_certificate": Path(self.cfg.observer_cert).read_text(), + "token": token}, + "shared_secret": secret, + "engine": engine, + "data_slice": {"name": data_slice, "csv": (Path(self.cfg.slices_dir) / data_slice).read_text()}, + "nonce": req.get("nonce"), + } + answer["mac"] = protocol.mac(key, "response", answer) + return answer, record diff --git a/directory/store.py b/directory/store.py index 74678cf..736f7d5 100644 --- a/directory/store.py +++ b/directory/store.py @@ -1,8 +1,9 @@ """The directory's own datastore: one SQLite file, nothing shared with the Postgres the dashboard reads. It holds every membership document the directory has issued (the latest one is the -current chain) and a log of registrations, joins and leaves. No model state, no -metrics, no patient data: the directory never receives any of it. +current chain), a log of registrations, joins and leaves, the join codes the organiser +created (only a hash of each), and the hospitals that enrolled with one (directory/enroll.py). +No model state, no metrics, no patient data: the directory never receives any of it. """ from __future__ import annotations @@ -28,8 +29,38 @@ node_id TEXT, detail TEXT NOT NULL DEFAULT '{}' ); +CREATE TABLE IF NOT EXISTS join_codes ( + code_id TEXT PRIMARY KEY, -- the code's first group, how it is looked up + code_key TEXT NOT NULL, -- SHA-256 of the whole code (node/enroll.py code_key); never the code + created_at REAL NOT NULL, + created_by TEXT, + expires_at REAL NOT NULL, + data_slice TEXT, -- the data slice it hands out (NULL: the least used one) + used_at REAL, + used_by TEXT, + revoked_at REAL, + revoked_by TEXT, + failures INTEGER NOT NULL DEFAULT 0 +); +CREATE TABLE IF NOT EXISTS enrolled ( + node_id TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + credential_sha256 TEXT NOT NULL, + signing_public_key TEXT NOT NULL, + tls_pin TEXT NOT NULL, + observer_token_sha256 TEXT NOT NULL, + data_slice TEXT NOT NULL, + code_id TEXT NOT NULL, + enrolled_at REAL NOT NULL +); """ +CODE_COLUMNS = ("code_id", "created_at", "created_by", "expires_at", "data_slice", "used_at", "used_by", "revoked_at", + "revoked_by", "failures") +ENROLLED_COLUMNS = ("node_id", "display_name", "credential_sha256", "signing_public_key", "tls_pin", + "observer_token_sha256", "data_slice", "code_id", "enrolled_at") +MAX_FAILURES = 5 # wrong proofs for one code before it is revoked + class Store: def __init__(self, path: str | Path): @@ -66,3 +97,63 @@ def events(self, limit: int = 100) -> list[dict]: rows = self._conn.execute("SELECT ts, event, node_id, detail FROM events ORDER BY id DESC LIMIT ?", (limit,)).fetchall() return [{"ts": ts, "event": e, "node_id": n, "detail": json.loads(d)} for ts, e, n, d in rows] + + # -- join codes --------------------------------------------------------------------------- + def add_code(self, code_id: str, code_key: str, created_by: str | None, expires_at: float, + data_slice: str | None) -> bool: + """False if a code with this id already exists.""" + with self._lock: + try: + self._conn.execute("INSERT INTO join_codes (code_id, code_key, created_at, created_by, expires_at, " + "data_slice) VALUES (?, ?, ?, ?, ?, ?)", + (code_id, code_key, time.time(), created_by, expires_at, data_slice)) + return True + except sqlite3.IntegrityError: + return False + + def code(self, code_id: str) -> tuple[dict, str] | None: + """(the code's row without its key, its key), or None.""" + with self._lock: + row = self._conn.execute(f"SELECT {', '.join(CODE_COLUMNS)}, code_key FROM join_codes WHERE code_id = ?", + (code_id,)).fetchone() + return (dict(zip(CODE_COLUMNS, row[:-1])), row[-1]) if row else None + + def codes(self, limit: int = 50) -> list[dict]: + with self._lock: + rows = self._conn.execute(f"SELECT {', '.join(CODE_COLUMNS)} FROM join_codes ORDER BY created_at DESC " + "LIMIT ?", (limit,)).fetchall() + return [dict(zip(CODE_COLUMNS, r)) for r in rows] + + def consume_code(self, code_id: str, node_id: str) -> bool: + """Mark the code used by `node_id`, only if it is still usable (one winner if two race).""" + with self._lock: + cur = self._conn.execute("UPDATE join_codes SET used_at = ?, used_by = ? WHERE code_id = ? AND used_at IS " + "NULL AND revoked_at IS NULL AND expires_at > ?", + (time.time(), node_id, code_id, time.time())) + return cur.rowcount == 1 + + def revoke_code(self, code_id: str, by: str | None) -> bool: + with self._lock: + cur = self._conn.execute("UPDATE join_codes SET revoked_at = ?, revoked_by = ? WHERE code_id = ? AND " + "used_at IS NULL AND revoked_at IS NULL", (time.time(), by, code_id)) + return cur.rowcount == 1 + + def code_failure(self, code_id: str) -> bool: + """Count a wrong proof for the code; True if that revoked it.""" + with self._lock: + self._conn.execute("UPDATE join_codes SET failures = failures + 1 WHERE code_id = ?", (code_id,)) + cur = self._conn.execute("UPDATE join_codes SET revoked_at = ?, revoked_by = 'too many wrong attempts' " + "WHERE code_id = ? AND failures >= ? AND revoked_at IS NULL AND used_at IS NULL", + (time.time(), code_id, MAX_FAILURES)) + return cur.rowcount == 1 + + # -- hospitals enrolled with a join code ------------------------------------------------------ + def add_enrolled(self, row: dict) -> None: + with self._lock: + self._conn.execute(f"INSERT INTO enrolled ({', '.join(ENROLLED_COLUMNS)}) VALUES " + f"({', '.join('?' for _ in ENROLLED_COLUMNS)})", [row[c] for c in ENROLLED_COLUMNS]) + + def enrolled(self) -> list[dict]: + with self._lock: + rows = self._conn.execute(f"SELECT {', '.join(ENROLLED_COLUMNS)} FROM enrolled ORDER BY enrolled_at").fetchall() + return [dict(zip(ENROLLED_COLUMNS, r)) for r in rows] diff --git a/docker-compose.yml b/docker-compose.yml index d1f1058..6045609 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -74,18 +74,27 @@ services: restart: "no" # Membership only: decides where a hospital goes and who bridges when one leaves. Its own - # SQLite store (the directory-data volume), not the dashboard's Postgres. + # SQLite store (the directory-data volume), not the dashboard's Postgres; it only writes the + # audit log and the hospitals' keys on record there. It also takes join codes (POST /enroll). directory: image: medchain-node:latest container_name: directory command: ["python", "-m", "directory"] environment: DIRECTORY_CONFIG: /config/directory.yaml + DATABASE_URL: postgresql://medchain:medchain@postgres:5432/medchain + # handed to hospitals that enroll with a join code (must match shared_secret in config/hospital-*.yaml) + MEDCHAIN_SHARED_SECRET: ${MEDCHAIN_SHARED_SECRET:-medchain-demo-secret} volumes: - ./config/directory.yaml:/config/directory.yaml:ro - ./.pki:/pki:ro - directory-data:/data + - hub-secrets:/hub + - ./data/slices:/slices:ro + - ./config/hospital-a.yaml:/templates/node.yaml:ro depends_on: + postgres: + condition: service_healthy pki: condition: service_completed_successfully ports: @@ -225,6 +234,7 @@ services: volumes: directory-data: + hub-secrets: checkpoints-a: checkpoints-b: checkpoints-c: diff --git a/node/Dockerfile b/node/Dockerfile index c3abc7b..17ef2d5 100644 --- a/node/Dockerfile +++ b/node/Dockerfile @@ -23,6 +23,8 @@ 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 +# python -m node.enroll writes a kit around it (join-code enrollment, deploy/install/) +COPY deploy/node.yml /app/deploy/node.yml 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 diff --git a/node/config.py b/node/config.py index d9050a9..9c74e59 100644 --- a/node/config.py +++ b/node/config.py @@ -143,6 +143,17 @@ class TimingConfig: DEFAULT_PORT = 8000 +# where a node runs, who it is and its keys: everything a config holds that is not the shared engine settings +DEPLOYMENT_KEYS = ("node_id", "port", "host", "advertise_url", "chain", "neighbours", "directory", "observer", "tls", + "signing_key", "shared_secret", "data_slice", "data_path", "checkpoint_dir") + + +def engine_settings(raw: dict) -> dict: + """A node config without its deployment keys: what every hospital of one network must share (the engine, + rho, bits, timing...). A kit's config/node.yaml, from scripts/provision.py or a join-code enrollment.""" + return {k: v for k, v in raw.items() if k not in DEPLOYMENT_KEYS} + + def peer_url_env(node_id: str) -> str: """The environment variable that overrides neighbour `node_id`'s URL.""" return f"MEDCHAIN_PEER_{re.sub(r'[^A-Za-z0-9]+', '_', node_id).upper()}_URL" diff --git a/node/db.py b/node/db.py index 7312a27..e8cd807 100644 --- a/node/db.py +++ b/node/db.py @@ -7,8 +7,11 @@ nodes.epoch / chain / in_chain / membership_round (each node's current view of the chain, so the dashboard can draw it; the directory's own store is separate). -Nodes are the only writers. The dashboard reads these tables and never writes -them. Writes are best-effort: a database outage is logged and training carries +Nodes are the only writers of the training tables. `hospital_keys` is the directory's: +each hospital's keys as the directory has them on record (its update-signing key, TLS pin, +and, for a hospital that enrolled with a join code, the hash of its own observer token), so +the observer can tell hospitals apart without trusting what they say about themselves. +The dashboard reads these tables and never writes them. Writes are best-effort: a database outage is logged and training carries on, because the database is an observation channel, not a coordinator. """ @@ -104,6 +107,16 @@ ALTER TABLE nodes ADD COLUMN IF NOT EXISTS chain JSONB; ALTER TABLE nodes ADD COLUMN IF NOT EXISTS in_chain BOOLEAN; ALTER TABLE nodes ADD COLUMN IF NOT EXISTS membership_round INTEGER; +-- written by the directory only (never through the observer's /ingest): keys on record per hospital +CREATE TABLE IF NOT EXISTS hospital_keys ( + node_id TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + signing_public_key TEXT, + tls_pin TEXT, + observer_token_sha256 TEXT UNIQUE, + enrolled BOOLEAN NOT NULL DEFAULT false, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); """ SCHEMA_LOCK_KEY = 4242_0001 @@ -125,6 +138,13 @@ def _connect(self): return conn def _execute(self, sql: str, params: tuple | dict | None = None) -> None: + self._run(sql, params, fetch=False) + + def fetch(self, sql: str, params: tuple | dict | None = None) -> list[tuple]: + """Rows of a query ([] if the database cannot be reached).""" + return self._run(sql, params, fetch=True) or [] + + def _run(self, sql: str, params, fetch: bool): with self._lock: for attempt in (1, 2): try: @@ -132,7 +152,7 @@ def _execute(self, sql: str, params: tuple | dict | None = None) -> None: self._conn = self._connect() with self._conn.cursor() as cur: cur.execute(sql, params) - return + return cur.fetchall() if fetch else None except Exception as exc: # noqa: BLE001 - best-effort observation channel try: if self._conn is not None: @@ -236,13 +256,28 @@ def audit(self, *, node_id: str, event: str, run_id: str | None = None, round_nu ) + def hospital_key(self, *, node_id: str, display_name: str, signing_public_key: str | None, tls_pin: str | None, + observer_token_sha256: str | None = None, enrolled: bool = False) -> None: + """The directory's record of a hospital's keys (a token hash, once set, is kept until re-enrollment).""" + self._execute( + """INSERT INTO hospital_keys (node_id, display_name, signing_public_key, tls_pin, observer_token_sha256, enrolled) + VALUES (%s, %s, %s, %s, %s, %s) + ON CONFLICT (node_id) DO UPDATE SET + display_name = EXCLUDED.display_name, signing_public_key = EXCLUDED.signing_public_key, + tls_pin = EXCLUDED.tls_pin, enrolled = hospital_keys.enrolled OR EXCLUDED.enrolled, + observer_token_sha256 = COALESCE(EXCLUDED.observer_token_sha256, hospital_keys.observer_token_sha256), + updated_at = now()""", + (node_id, display_name, signing_public_key, tls_pin, observer_token_sha256, enrolled), + ) + + class NullDatabase(Database): """Used when no DATABASE_URL is set (unit tests, local experiments).""" def __init__(self): super().__init__("") - def _execute(self, sql, params=None): # noqa: D401 + def _run(self, sql, params, fetch): # noqa: D401 return None def wait_until_ready(self, timeout_s: float = 60) -> bool: diff --git a/node/enroll.py b/node/enroll.py new file mode 100644 index 0000000..a0905e5 --- /dev/null +++ b/node/enroll.py @@ -0,0 +1,346 @@ +"""Join a MedChain network with a one-time join code, instead of a kit made and sent by the organiser. + + python -m node.enroll --hub 100.101.1.99 --name "St Mary's" --advertise 100.101.1.20 --out /kit + (the code comes from --code or $MEDCHAIN_JOIN_CODE) + +The organiser creates a join code on the dashboard's admin page: single use, expires after +30 minutes. This node then: + +1. makes its own keys, here, and never sends a private one anywhere: a TLS key (sent only + as a certificate signing request), an Ed25519 update-signing key (its public half) and + a directory credential (its SHA-256); +2. POSTs them to the hub's directory (`POST /enroll`) with its chosen display name and a + proof that it holds the join code (an HMAC keyed by a hash of the code; the code itself + never goes over the wire, so a machine answering in the hub's place learns nothing); +3. checks the answer before trusting anything in it: it must carry an HMAC under the same + key (only the real hub, which holds that hash, can make one), echo this request's nonce, + and name the TLS key that answered this very connection as the directory's; +4. writes a kit folder laid out exactly like a scripts/provision.py kit (`.env`, `pki/`, + `data/`, `config/node.yaml`, `deploy/node.yml`), so `docker compose --project-directory + -f deploy/node.yml up -d` runs it like any other hospital. + +The hub answers with: a certificate for this node's TLS key, signed by the network CA; the +CA certificate; the directory's document key and TLS certificate (pinned from then on); the +observer's TLS certificate and port and an ingest token for this hospital alone; the +network secret (written to `pki/network/shared_secret`, never printed); the engine settings +every hospital shares; the data slice the organiser assigned; and a generated node id. The +node id, not the display name, is the hospital's identity on the wire. + +Nothing secret is printed. Running it again on an enrolled kit does nothing (`--force` +re-enrolls with a new join code and new keys). +""" + +from __future__ import annotations + +import argparse +import hashlib +import hmac +import http.client +import ipaddress +import json +import os +import re +import secrets +import shutil +import ssl +import sys +import textwrap +from dataclasses import dataclass +from pathlib import Path + +import yaml +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.x509.oid import NameOID + +from .pinning import spki_sha256 +from .security import public_key_b64 + +# join codes: 5 groups of 4 from an alphabet without look-alikes (no 0/O, 1/I/L, U). The first group names +# the code (the hub looks it up by it); the other 16 characters (~78 bits) are the secret. +ALPHABET = "ABCDEFGHJKMNPQRSTVWXYZ23456789" +CODE_LEN, ID_LEN = 20, 4 +DIRECTORY_PORT = 8100 +NODE_PORT = 8000 +IMAGE_VERSION = "v1.1.0" # the published node image that has this module (.github/workflows/image.yml) +NODE_COMPOSE = Path(__file__).resolve().parents[1] / "deploy" / "node.yml" +SECRET_FILE = "/pki/network/shared_secret" # inside the node's container (deploy/node.yml mounts ./pki at /pki) +HOSTNAME = re.compile(r"^(?=.{1,253}$)[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$") + + +class EnrollError(Exception): + """Why enrollment failed, in words for the person running it.""" + + +# -- the protocol (shared with the hub, directory/enroll.py) ------------------------------------- + + +def new_code() -> str: + raw = "".join(secrets.choice(ALPHABET) for _ in range(CODE_LEN)) + return "-".join(raw[i:i + 4] for i in range(0, CODE_LEN, 4)) + + +def normalize_code(code: str) -> str: + raw = re.sub(r"[^A-Za-z0-9]", "", str(code)).upper() + if len(raw) != CODE_LEN or any(c not in ALPHABET for c in raw): + raise ValueError("a join code is 20 letters and digits in groups of four, like ABCD-EFGH-JKMN-PQRS-TVWX") + return raw + + +def code_id(code: str) -> str: + """The public part of a code: how the hub finds it (the rest is the secret).""" + return normalize_code(code)[:ID_LEN] + + +def code_key(code: str) -> str: + """The SHA-256 of the code: all the hub stores, and the HMAC key both sides prove themselves with.""" + return hashlib.sha256(b"medchain-join/v1\n" + normalize_code(code).encode()).hexdigest() + + +def canonical(obj: dict) -> bytes: + return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() + + +def mac(key: str, context: str, obj: dict) -> str: + """HMAC-SHA256 of `obj` (without its mac/proof field) under the code key, for `context` request|response.""" + return hmac.new(bytes.fromhex(key), f"medchain-enroll-{context}/v1\n".encode() + canonical(obj), + hashlib.sha256).hexdigest() + + +def check_mac(key: str, context: str, obj: dict, given: str | None) -> bool: + return bool(given) and hmac.compare_digest(mac(key, context, obj), str(given)) + + +def check_address(host: str) -> str: + """An address peers reach this node at: an IP or a DNS name, nothing else.""" + host = str(host).strip().strip("[]") + try: + return str(ipaddress.ip_address(host)) + except ValueError: + if not HOSTNAME.match(host): + raise ValueError(f"not an IP address or a host name: {host!r}") from None + return host.lower() + + +# -- this node's side -------------------------------------------------------------------------- + + +@dataclass +class Keys: + tls: ec.EllipticCurvePrivateKey + signing: Ed25519PrivateKey + credential: str + + @classmethod + def generate(cls) -> "Keys": + return cls(ec.generate_private_key(ec.SECP256R1()), Ed25519PrivateKey.generate(), secrets.token_urlsafe(24)) + + def csr(self, addresses: list[str]) -> str: + from .security import san + + req = (x509.CertificateSigningRequestBuilder() + .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "medchain-enrollment")])) + .add_extension(x509.SubjectAlternativeName([san(a) for a in addresses]), critical=False) + .sign(self.tls, hashes.SHA256())) + return req.public_bytes(serialization.Encoding.PEM).decode() + + +def split_hub(hub: str) -> tuple[str, int]: + hub = hub.strip().removeprefix("https://").rstrip("/") + host, sep, port = hub.rpartition(":") + if sep and port.isdigit() and "]" not in port: + return check_address(host), int(port) + return check_address(hub), DIRECTORY_PORT + + +def post_enroll(host: str, port: int, body: dict, timeout: float) -> tuple[int, dict, str | None]: + """POST /enroll. The hub's certificate cannot be checked yet (this node has no CA certificate): the answer's + HMAC authenticates it instead, and the TLS key that answered is returned so the caller can pin it.""" + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + conn = http.client.HTTPSConnection(host, port, timeout=timeout, context=ctx) + try: + conn.request("POST", "/enroll", body=canonical(body), headers={"Content-Type": "application/json"}) + der = conn.sock.getpeercert(True) if conn.sock else None + resp = conn.getresponse() + raw = resp.read() + except (OSError, http.client.HTTPException) as exc: + raise EnrollError(f"cannot reach the hub at {host}:{port} ({type(exc).__name__}: {exc}). Check that the " + "organiser's hub is running and that this computer is on their Tailscale network.") from exc + finally: + conn.close() + try: + data = json.loads(raw) if raw else {} + except ValueError: + data = {"detail": raw[:200].decode(errors="replace")} + return resp.status, data, spki_sha256(der) if der else None + + +def request_enrollment(hub: str, display_name: str, code: str, addresses: list[str], keys: Keys, + timeout: float = 30) -> dict: + """Enroll with the hub; returns its verified answer (raises EnrollError with a plain reason).""" + try: + key = code_key(code) + addresses = list(dict.fromkeys(check_address(a) for a in addresses)) + except ValueError as exc: + raise EnrollError(str(exc)) from exc + host, port = split_hub(hub) + body = {"code_id": code_id(code), "display_name": display_name, "csr": keys.csr(addresses), + "signing_public_key": public_key_b64(keys.signing), + "credential_sha256": hashlib.sha256(keys.credential.encode()).hexdigest(), + "addresses": addresses, "nonce": secrets.token_hex(16)} + body["proof"] = mac(key, "request", body) + status, answer, server_pin = post_enroll(host, port, body, timeout) + if status != 200: + raise EnrollError(f"the hub refused: {answer.get('detail', f'HTTP {status}')}") + given = answer.pop("mac", None) + if not check_mac(key, "response", answer, given) or answer.get("nonce") != body["nonce"]: + raise EnrollError("the answer is not from the hub that issued your join code (it does not carry the code's " + "signature). Check the hub address with the organiser.") + try: + directory_cert = x509.load_pem_x509_certificate(answer["directory"]["tls_certificate"].encode()) + ca = x509.load_pem_x509_certificate(answer["ca_certificate"].encode()) + cert = x509.load_pem_x509_certificate(answer["certificate"].encode()) + cert.verify_directly_issued_by(ca) + except (KeyError, TypeError, ValueError) as exc: + raise EnrollError(f"the hub's answer is incomplete or malformed ({exc})") from exc + if server_pin != spki_sha256(directory_cert): + raise EnrollError("the TLS key that answered is not the directory's own key: something else is in the way") + spki = (serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) + if cert.public_key().public_bytes(*spki) != keys.tls.public_key().public_bytes(*spki): + raise EnrollError("the hub issued a certificate for a different key than this node's") + return answer + + +def _pem_key(key) -> bytes: + return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()) + + +def _write(path: Path, data: str | bytes, private: bool = False) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data.encode() if isinstance(data, str) else data) + if private: + try: + path.chmod(0o600) + except OSError: # a Windows folder shared into the container + pass + + +def kit_env(answer: dict, hub_host: str, hub_port: int, advertise: str, port: int, image_version: str, + image: str | None) -> str: + host = f"[{hub_host}]" if ":" in hub_host else hub_host + lines = [ + f"# MedChain hospital node settings for {answer['display_name']} ({answer['node_id']}), written by", + "# `python -m node.enroll` (join-code enrollment). Read by deploy/node.yml. The keys are in pki/;", + "# the network's shared secret is in pki/network/shared_secret. Nothing here needs editing.", + "", + f"NODE_ID={answer['node_id']}", + f"NODE_PORT={port}", + f"ADVERTISE_ADDR={advertise}:{port}", + f"DIRECTORY_URL=https://{host}:{hub_port}", + f"OBSERVER_URL=https://{host}:{answer['observer']['port']}", + f"SHARED_SECRET_FILE={SECRET_FILE}", + f"IMAGE_VERSION={image_version}", + *([f"MEDCHAIN_IMAGE={image}"] if image else []), + "# 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", + ] + return "\n".join(lines) + "\n" + + +def write_kit(out: Path, answer: dict, keys: Keys, env: str) -> None: + """The same layout as a scripts/provision.py kit, so deploy/node.yml runs it unchanged.""" + node_id = answer["node_id"] + pki = out / "pki" + _write(pki / node_id / "tls.key", _pem_key(keys.tls), private=True) + _write(pki / node_id / "tls.crt", answer["certificate"]) + _write(pki / node_id / "signing.key", _pem_key(keys.signing), private=True) + _write(pki / node_id / "signing.pub", public_key_b64(keys.signing) + "\n") + _write(pki / node_id / "credential", keys.credential + "\n", private=True) + _write(pki / "ca.crt", answer["ca_certificate"]) + _write(pki / "directory" / "signing.pub", answer["directory"]["signing_public_key"] + "\n") + _write(pki / "directory" / "tls.crt", answer["directory"]["tls_certificate"]) + _write(pki / "observer" / "tls.crt", answer["observer"]["tls_certificate"]) + _write(pki / "observer" / "token", answer["observer"]["token"] + "\n", private=True) + _write(pki / "network" / "shared_secret", answer["shared_secret"] + "\n", private=True) + _write(out / "data" / f"{node_id}.csv", answer["data_slice"]["csv"]) + engine = {"display_name": answer["display_name"], **answer["engine"]} + _write(out / "config" / "node.yaml", f"# {answer['display_name']} ({node_id}): the engine settings every hospital " + "of this network shares, from the hub.\n" + yaml.safe_dump(engine, sort_keys=False)) + (out / "deploy").mkdir(parents=True, exist_ok=True) + shutil.copyfile(NODE_COMPOSE, out / "deploy" / "node.yml") + _write(out / "README.md", textwrap.dedent(f"""\ + # MedChain hospital: {answer['display_name']} (`{node_id}`) + + Enrolled with a join code. This folder holds this hospital's private keys: don't share it. + The node trains on `data/{node_id}.csv`, which never leaves this computer. + + ```sh + docker compose --project-directory . -f deploy/node.yml up -d # start (or restart) + docker compose --project-directory . -f deploy/node.yml logs -f # watch + docker compose --project-directory . -f deploy/node.yml exec node python -m node.leave + docker compose --project-directory . -f deploy/node.yml down # stop + ``` + """)) + _write(out / ".env", env) + + +def enrolled_id(out: Path) -> str | None: + """The node id of the kit already in `out` (None if there is none).""" + env = out / ".env" + if not env.is_file(): + return None + for line in env.read_text().splitlines(): + if line.startswith("NODE_ID="): + node_id = line.partition("=")[2].strip() + return node_id if (out / "pki" / node_id / "tls.crt").is_file() else None + return None + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--hub", required=True, help=f"the hub's directory: host[:port] (default port {DIRECTORY_PORT})") + ap.add_argument("--name", required=True, help="this hospital's display name, shown on the dashboard") + ap.add_argument("--code", help="the join code (default: $MEDCHAIN_JOIN_CODE)") + ap.add_argument("--advertise", required=True, help="the address the other hospitals reach this computer at " + "(its Tailscale IP)") + ap.add_argument("--also", action="append", default=[], help="another name for this computer for its certificate " + "(e.g. its MagicDNS name; repeatable)") + ap.add_argument("--port", type=int, default=NODE_PORT, help=f"the port this node listens on (default {NODE_PORT})") + ap.add_argument("--out", type=Path, default=Path("/kit"), help="where to write the kit (default /kit)") + ap.add_argument("--image-version", default=os.environ.get("IMAGE_VERSION") or IMAGE_VERSION) + ap.add_argument("--image", default=os.environ.get("MEDCHAIN_IMAGE") or None, help="the node image repository") + ap.add_argument("--force", action="store_true", help="enroll again even if --out already holds an enrolled kit") + args = ap.parse_args(argv) + + existing = enrolled_id(args.out) + if existing and not args.force: + print(f"already enrolled as {existing} in {args.out}; nothing to do (--force enrolls again)") + return 0 + code = args.code or os.environ.get("MEDCHAIN_JOIN_CODE", "") + name = " ".join(args.name.split()) + try: + if not code: + raise EnrollError("no join code: pass --code or set MEDCHAIN_JOIN_CODE") + advertise = check_address(args.advertise) + hub_host, hub_port = split_hub(args.hub) + keys = Keys.generate() + answer = request_enrollment(f"{hub_host}:{hub_port}", name, code, [advertise, *args.also], keys) + except (EnrollError, ValueError) as exc: + print(f"enroll: {exc}", file=sys.stderr) + return 2 + write_kit(args.out, answer, keys, kit_env(answer, hub_host, hub_port, advertise, args.port, args.image_version, + args.image)) + print(f"enrolled {answer['display_name']} as {answer['node_id']} (data: {answer['data_slice']['name']}); " + f"kit written to {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/node/security.py b/node/security.py index 3b273b7..685d67e 100644 --- a/node/security.py +++ b/node/security.py @@ -17,13 +17,17 @@ from __future__ import annotations import base64 +import datetime as dt import hashlib +import ipaddress from pathlib import Path -from typing import Mapping +from typing import Iterable, Mapping +from cryptography import x509 from cryptography.exceptions import InvalidSignature -from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID from .wire import H_SIGNATURE @@ -31,6 +35,9 @@ _UNSIGNED = {H_SIGNATURE.lower(), "x-medchain-secret"} # the signature itself; the secret never goes in a log +CERT_VALID_DAYS = 3650 + + class SignatureError(Exception): pass @@ -87,3 +94,26 @@ def verify(pub: Ed25519PublicKey, signature: str | None, body: bytes, headers: M except (InvalidSignature, ValueError, TypeError) as exc: raise SignatureError("signature does not verify") from exc + + +def san(host: str) -> x509.GeneralName: + try: + return x509.IPAddress(ipaddress.ip_address(host)) + except ValueError: + return x509.DNSName(host) + + +def issue_certificate(ca_cert: x509.Certificate, ca_key, public_key, name: str, hosts: Iterable[str], + days: int = CERT_VALID_DAYS) -> x509.Certificate: + """A TLS certificate for `public_key`, signed by the network CA: CN `name`, SAN `hosts` (scripts/pki.py and + the directory's join-code enrollment, directory/enroll.py, both issue them).""" + now = dt.datetime.now(dt.timezone.utc) + return (x509.CertificateBuilder() + .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])) + .issuer_name(ca_cert.subject).public_key(public_key).serial_number(x509.random_serial_number()) + .not_valid_before(now - dt.timedelta(minutes=5)).not_valid_after(now + dt.timedelta(days=days)) + .add_extension(x509.SubjectAlternativeName([san(h) for h in dict.fromkeys(hosts)]), critical=False) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH]), + critical=False) + .sign(ca_key, hashes.SHA256())) diff --git a/node/settings.py b/node/settings.py index 73d1ce7..0a7b568 100644 --- a/node/settings.py +++ b/node/settings.py @@ -27,6 +27,7 @@ TLS_CERT, TLS_KEY, TLS_CA this node's certificate and key, and the network CA SIGNING_KEY this node's Ed25519 update-signing key SHARED_SECRET the network's X-MedChain-Secret + SHARED_SECRET_FILE ... read from this file instead (a join-code enrollment writes it, node/enroll.py) IMAGE_VERSION the image's version, reported by /health MEDCHAIN_PEER__URL a static neighbour's address (node/config.py) @@ -81,6 +82,7 @@ class NodeSettings(BaseSettings): tls_ca: str | None = _env("TLS_CA") signing_key: str | None = _env("SIGNING_KEY") shared_secret: str | None = _env("SHARED_SECRET") + shared_secret_file: str | None = _env("SHARED_SECRET_FILE") image_version: str | None = _env("IMAGE_VERSION") @@ -97,7 +99,8 @@ def apply_env(raw: dict, s: NodeSettings, source: str) -> dict: top = {"node_id": s.node_id, "host": s.bind_host, "port": s.node_port, "advertise_url": s.advertise_addr, "data_path": s.data_path, "data_slice": s.data_slice, "checkpoint_dir": s.checkpoint_dir, "engine": s.algorithm, "bits": s.bits, "epsilon": s.epsilon, "signing_key": s.signing_key, - "shared_secret": s.shared_secret, "image_version": s.image_version} + "shared_secret": Path(s.shared_secret_file).read_text().strip() if s.shared_secret_file else s.shared_secret, + "image_version": s.image_version} raw.update({k: v for k, v in top.items() if v is not None}) _block(raw, "timing", {"round_timeout_s": s.round_timeout_s, "round_pause_s": s.round_pause_s}) _block(raw, "http", {"connect_timeout_s": s.http_connect_timeout_s, "read_timeout_s": s.http_read_timeout_s}) diff --git a/node/writer.py b/node/writer.py index da195ed..f5f63c3 100644 --- a/node/writer.py +++ b/node/writer.py @@ -37,8 +37,10 @@ WRITE_METHODS = { "ensure_schema", "register_node", "heartbeat", "create_run", "round_started", "round_finished", - "update_sent", "record_metrics", "audit", "membership", + "update_sent", "record_metrics", "audit", "membership", "hospital_key", } +# writes only the hub's own services make: never accepted from a node through the observer's /ingest +HUB_ONLY = {"ensure_schema", "hospital_key"} BATCH = 200 diff --git a/observer/app.py b/observer/app.py index 1767bed..d2f1344 100644 --- a/observer/app.py +++ b/observer/app.py @@ -1,7 +1,9 @@ """MedChain observer: the one place telemetry lands. Nodes push to it; it never calls them. POST /ingest a batch of a node's writes, {"node_id", "items": [{"kind", "payload"}, ...]}, with - `Authorization: Bearer `. Each item is one Database write + `Authorization: Bearer `: the network's OBSERVER_TOKEN (kit hospitals), or + the token a hospital got when it enrolled with a join code, which only ever + writes as that hospital (directory/enroll.py). Each item is one Database write (node/db.py: heartbeat, audit, record_metrics, ...), applied with the same methods, so the Postgres schema and the dashboard are unchanged. GET /health liveness @@ -19,8 +21,10 @@ from __future__ import annotations import asyncio +import hashlib import hmac import logging +import time from contextlib import asynccontextmanager from pathlib import Path @@ -29,11 +33,11 @@ from pydantic_settings import BaseSettings, SettingsConfigDict from node.db import Database, NullDatabase -from node.writer import WRITE_METHODS +from node.writer import HUB_ONLY, WRITE_METHODS log = logging.getLogger("medchain.observer") -KINDS = WRITE_METHODS - {"ensure_schema"} # the observer owns the schema; a node never runs DDL through it +KINDS = WRITE_METHODS - HUB_ONLY # the observer owns the schema and the directory the keys: never a node def _env(*names: str, default=None): @@ -71,6 +75,14 @@ class Batch(BaseModel): items: list[Item] = Field(max_length=1000) +OWNER_CACHE_S = 30.0 + + +def own_writes(items: list[Item], node_id: str) -> bool: + """A hospital's own token writes only as that hospital: no item may name another node (as node_id or sender).""" + return all(item.payload.get(k, node_id) == node_id for item in items for k in ("node_id", "sender")) + + def create_app(settings: ObserverSettings | None = None, database: Database | None = None) -> FastAPI: settings = settings or ObserverSettings() token = settings.token.encode() @@ -86,11 +98,29 @@ async def lifespan(app: FastAPI): app = FastAPI(title="MedChain observer", lifespan=lifespan) - def authorize(request: Request) -> None: + owners: dict[str, tuple[float, str | None]] = {} # token hash -> (when looked up, its hospital) + + def token_owner(digest: str) -> str | None: + """The enrolled hospital this token hash belongs to (hospital_keys, written by the directory).""" + hit = owners.get(digest) + if hit and time.monotonic() - hit[0] < OWNER_CACHE_S: + return hit[1] + rows = db.fetch("SELECT node_id FROM hospital_keys WHERE observer_token_sha256 = %s", (digest,)) + if len(owners) > 1024: # bounded: unknown tokens are remembered too + owners.clear() + owners[digest] = (time.monotonic(), rows[0][0] if rows else None) + return owners[digest][1] + + async def authorize(request: Request, batch: Batch) -> None: auth = request.headers.get("Authorization", "") given = auth[7:].encode() if auth.startswith("Bearer ") else b"" - if not given or not hmac.compare_digest(given, token): + if given and hmac.compare_digest(given, token): + return # the network token (kit hospitals, the single-machine stack) + owner = await asyncio.to_thread(token_owner, hashlib.sha256(given).hexdigest()) if given else None + if owner is None: raise HTTPException(401, detail="a valid observer token is required") + if owner != batch.node_id or not own_writes(batch.items, owner): + raise HTTPException(403, detail=f"this token belongs to {owner}: it writes only as {owner}") def apply(batch: Batch) -> tuple[int, list[str]]: applied, rejected = 0, [] @@ -111,7 +141,7 @@ async def health(): @app.post("/ingest") async def ingest(batch: Batch, request: Request): - authorize(request) + await authorize(request, batch) async with write_lock: # one batch at a time, in arrival order applied, rejected = await asyncio.to_thread(apply, batch) if rejected: diff --git a/scripts/pki.py b/scripts/pki.py index 3c12eea..afcbbee 100644 --- a/scripts/pki.py +++ b/scripts/pki.py @@ -28,7 +28,6 @@ import argparse import datetime as dt import hashlib -import ipaddress import secrets import sys from pathlib import Path @@ -38,14 +37,14 @@ from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey -from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +from cryptography.x509.oid import NameOID ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) -from node.security import public_key_b64 # noqa: E402 +from node.security import CERT_VALID_DAYS, issue_certificate, public_key_b64 # noqa: E402 -VALID_DAYS = 3650 +VALID_DAYS = CERT_VALID_DAYS def _pem_key(key) -> bytes: @@ -79,13 +78,6 @@ def ensure_ca(out: Path) -> tuple[x509.Certificate, ec.EllipticCurvePrivateKey]: return cert, k -def _san(host: str) -> x509.GeneralName: - try: - return x509.IPAddress(ipaddress.ip_address(host)) - except ValueError: - return x509.DNSName(host) - - def _covers(crt: Path, names: list[str]) -> bool: san = x509.load_pem_x509_certificate(crt.read_bytes()).extensions.get_extension_for_class(x509.SubjectAlternativeName) have = {str(v) for v in san.value.get_values_for_type(x509.DNSName)} @@ -102,16 +94,7 @@ def ensure_identity(out: Path, name: str, hosts: list[str], *, credential: bool) # a new address keeps the party's TLS key: peers pin the key (node/pinning.py), not the address k = (serialization.load_pem_private_key((d / "tls.key").read_bytes(), password=None) if (d / "tls.key").is_file() else ec.generate_private_key(ec.SECP256R1())) - now = dt.datetime.now(dt.timezone.utc) - cert = (x509.CertificateBuilder() - .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])) - .issuer_name(ca_cert.subject).public_key(k.public_key()).serial_number(x509.random_serial_number()) - .not_valid_before(now - dt.timedelta(minutes=5)).not_valid_after(now + dt.timedelta(days=VALID_DAYS)) - .add_extension(x509.SubjectAlternativeName([_san(h) for h in names]), critical=False) - .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) - .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH]), - critical=False) - .sign(ca_key, hashes.SHA256())) + cert = issue_certificate(ca_cert, ca_key, k.public_key(), name, names, VALID_DAYS) _write(d / "tls.key", _pem_key(k), private=True) _write(d / "tls.crt", cert.public_bytes(serialization.Encoding.PEM)) if not (d / "signing.key").is_file(): diff --git a/scripts/provision.py b/scripts/provision.py index 0dd74ba..24a884a 100644 --- a/scripts/provision.py +++ b/scripts/provision.py @@ -15,8 +15,9 @@ 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. +directory kit is the hub's: the directory's config and keys, the network CA's key (it +issues certificates to hospitals that enroll with a join code instead of a kit), 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 \\ @@ -54,12 +55,12 @@ sys.path.insert(0, str(ROOT / "scripts")) import pki # noqa: E402 -from node.config import build_config # noqa: E402 +from node.config import build_config, engine_settings # noqa: E402 from node.settings import NodeSettings, apply_env # noqa: E402 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) +IMAGE_VERSION = "v1.1.0" # the published node image's tag (.github/workflows/image.yml) DIRECTORY = "directory" OBSERVER = "observer" OBSERVER_PORT = 8200 @@ -112,16 +113,12 @@ def listen_port(node_id: str, url: str, template: Path) -> int: return int(raw["port"]) -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) - raw = {k: v for k, v in raw.items() if k not in ENGINE_ONLY_DROP} + raw = engine_settings(raw) raw["display_name"] = raw.get("display_name") if own else node_id return raw @@ -232,6 +229,9 @@ def copy_keys(pki_dir: Path, kit: Path, party: str) -> None: shutil.copyfile(pki_dir / DIRECTORY / "signing.pub", dst / DIRECTORY / "signing.pub") if party != DIRECTORY: # the directory's certificate: this kit pins its key (out of band, not from the directory) shutil.copyfile(pki_dir / DIRECTORY / "tls.crt", dst / DIRECTORY / "tls.crt") + else: # the hub issues certificates to hospitals that enroll with a join code (directory/enroll.py) + shutil.copyfile(pki_dir / "ca.key", dst / "ca.key") + (dst / "ca.key").chmod(0o600) # the observer's certificate (pinned) and ingest token; the hub kit also gets its TLS key to run it (dst / OBSERVER).mkdir() for f in ("tls.crt", "token", *(("tls.key",) if party == DIRECTORY else ())): @@ -385,6 +385,8 @@ def build_directory_kit(url: str, out: Path, *, pki_dir: Path, observer_url: str 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") + if cfg.get("enrollment"): + cfg["enrollment"]["observer_port"] = urlsplit(observer_url).port or OBSERVER_PORT (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) @@ -409,8 +411,11 @@ def build_directory_kit(url: str, out: Path, *, pki_dir: Path, observer_url: str `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. + from the provisioning run. Or skip kits altogether: create a join code on the + dashboard's admin page and the hospital enrolls itself with it (its install + script runs `python -m node.enroll`). Keep `pki/ca.key` (the directory signs + enrolled hospitals' certificates with it), `pki/directory/signing.key` (it signs + every membership document) and `pki/observer/tls.key` private. """)) if make_zip: shutil.make_archive(str(out / DIRECTORY), "zip", root_dir=out, base_dir=DIRECTORY) diff --git a/tests/unit/chain_harness.py b/tests/unit/chain_harness.py index a61ac6f..8912649 100644 --- a/tests/unit/chain_harness.py +++ b/tests/unit/chain_harness.py @@ -175,9 +175,9 @@ def stop(self, *, abrupt: bool = False) -> None: class DirectoryServer(_Server): - def __init__(self, config_path: Path): + def __init__(self, config_path: Path, database=None): self.cfg = load_directory_config(config_path) - self.app = create_directory_app(self.cfg) + self.app = create_directory_app(self.cfg, database=database) self.verify = self.cfg.ca or True self._serve(self.app, self.cfg.port, self.cfg.tls_cert, self.cfg.tls_key, self.cfg.ca) diff --git a/tests/unit/test_enroll.py b/tests/unit/test_enroll.py new file mode 100644 index 0000000..0cc6031 --- /dev/null +++ b/tests/unit/test_enroll.py @@ -0,0 +1,230 @@ +"""Join-code enrollment (node/enroll.py, directory/enroll.py) over real HTTPS, end to end. + +A hospital enrolls with a one-time code instead of a kit: it makes its own keys, the +directory issues its certificate and node id, and the kit it writes runs as a node that +registers and joins the chain like any provisioned one. +""" + +import hashlib +import time + +import httpx +import pytest + +import pki +from chain_harness import (ROOT, DirectoryServer, NodeServer, RecordingDatabase, directory_configs, free_ports, + wait_until) +from node import enroll +from node.pinning import cert_file_pin + +ADMIN = "test-admin-token" + + +class HubDatabase(RecordingDatabase): + def __init__(self): + super().__init__() + self.keys: dict[str, dict] = {} + + def hospital_key(self, **kw): + self.keys[kw["node_id"]] = {**self.keys.get(kw["node_id"], {}), + **{k: v for k, v in kw.items() if v is not None}} + + +class Hub: + """A directory that takes join codes, beside one kit hospital (hospital-a).""" + + def __init__(self, tmp_path, monkeypatch): + self.tmp = tmp_path + self.dir_cfg, self.cfgs = directory_configs(tmp_path, ["hospital-a"], rho=5.0) + self.pki = tmp_path / "pki" + pki.ensure_identity(self.pki, "observer", ["127.0.0.1", "localhost"], credential=False) + self.dir_cfg.write_text(self.dir_cfg.read_text() + f"""admin_token_file: {tmp_path / 'hub' / 'admin_token'} +enrollment: + ca_cert: {self.pki / 'ca.crt'} + ca_key: {self.pki / 'ca.key'} + observer_cert: {self.pki / 'observer' / 'tls.crt'} + observer_port: 8200 + slices_dir: {ROOT / 'data' / 'slices'} + node_template: {ROOT / 'config' / 'hospital-a.yaml'} +""") + (tmp_path / "hub").mkdir() + (tmp_path / "hub" / "admin_token").write_text(ADMIN + "\n") + monkeypatch.setenv("MEDCHAIN_SHARED_SECRET", "chain-test-secret") + self.db = HubDatabase() + self.directory = DirectoryServer(self.dir_cfg, database=self.db).start() + self.hub = f"127.0.0.1:{self.directory.cfg.port}" + self.nodes: list[NodeServer] = [] + + def admin(self, method: str, path: str, token: str = ADMIN, **kw) -> httpx.Response: + return httpx.request(method, f"{self.directory.url}{path}", headers={"Authorization": f"Bearer {token}"}, + verify=str(self.pki / "ca.crt"), timeout=10, **kw) + + def code(self, **kw) -> str: + r = self.admin("POST", "/admin/join-codes", json={"created_by": "admin", **kw}) + assert r.status_code == 200, r.text + return r.json()["code"] + + def stop(self): + for s in [*self.nodes, self.directory]: + s.stop(abrupt=True) + + +@pytest.fixture +def hub(tmp_path, monkeypatch): + h = Hub(tmp_path, monkeypatch) + yield h + h.stop() + + +def kit_env(monkeypatch, kit): + """Run an enrolled kit outside Docker: deploy/node.yml's container paths, mapped onto the kit (like make node-native).""" + env = {k: v for k, v in (line.split("=", 1) for line in (kit / ".env").read_text().splitlines() + if line and not line.startswith("#"))} + node_id = env["NODE_ID"] + for k, v in env.items(): + monkeypatch.setenv(k, v) + for k, v in {"NODE_CONFIG": kit / "config" / "node.yaml", "DATA_PATH": kit / "data", + "TLS_CERT": kit / "pki" / node_id / "tls.crt", "TLS_KEY": kit / "pki" / node_id / "tls.key", + "TLS_CA": kit / "pki" / "ca.crt", "SIGNING_KEY": kit / "pki" / node_id / "signing.key", + "DIRECTORY_CREDENTIAL_FILE": kit / "pki" / node_id / "credential", + "DIRECTORY_PUBLIC_KEY": f"file:{kit / 'pki' / 'directory' / 'signing.pub'}", + "DIRECTORY_TLS_PIN": f"file:{kit / 'pki' / 'directory' / 'tls.crt'}", + "SHARED_SECRET_FILE": kit / "pki" / "network" / "shared_secret", + "OBSERVER_URL": ""}.items(): + monkeypatch.setenv(k, str(v)) + return node_id + + +def test_codes_are_normalized_and_only_their_hash_identifies_them(): + code = enroll.new_code() + assert len(code) == 24 and code.count("-") == 4 + messy = " " + code.lower().replace("-", " ") + " " + assert enroll.normalize_code(messy) == code.replace("-", "") + assert enroll.code_id(messy) == code[:4] and enroll.code_key(messy) == enroll.code_key(code) + for bad in ("ABCD-EFGH", code[:-1] + "0", code[:-1] + "O"): + with pytest.raises(ValueError): + enroll.normalize_code(bad) + body = {"a": 1, "b": "x"} + tag = enroll.mac(enroll.code_key(code), "response", body) + assert enroll.check_mac(enroll.code_key(code), "response", body, tag) + assert not enroll.check_mac(enroll.code_key(code), "response", {**body, "b": "y"}, tag), "a changed answer" + assert not enroll.check_mac(enroll.code_key(code), "request", body, tag), "the other direction" + assert not enroll.check_mac(enroll.code_key(enroll.new_code()), "response", body, tag), "another code" + + +def test_a_hospital_enrolls_with_a_join_code_and_joins_the_chain(hub, tmp_path, monkeypatch): + code = hub.code(data_slice="hospital-d.csv") + stored = hub.directory.store.code(enroll.code_id(code)) + assert stored[1] == enroll.code_key(code) and code not in str(stored), "only the code's hash is stored" + (port,) = free_ports(1) + kit = tmp_path / "kit" + assert enroll.main(["--hub", hub.hub, "--name", " St Mary's Leeds ", "--code", code, "--advertise", "127.0.0.1", + "--port", str(port), "--out", str(kit)]) == 0 + hub.nodes.append(NodeServer(hub.cfgs["hospital-a"]).start()) # a kit hospital, before the kit's env is set + + node_id = kit_env(monkeypatch, kit) + record = hub.directory.store.enrolled()[0] + assert (record["node_id"], record["display_name"], record["data_slice"]) == (node_id, "St Mary's Leeds", + "hospital-d.csv") + # its own keys: the hub has only the public halves and hashes + assert record["tls_pin"] == cert_file_pin(kit / "pki" / node_id / "tls.crt") + assert record["signing_public_key"] == (kit / "pki" / node_id / "signing.pub").read_text().strip() + credential = (kit / "pki" / node_id / "credential").read_text().strip() + assert record["credential_sha256"] == hashlib.sha256(credential.encode()).hexdigest() + token = (kit / "pki" / "observer" / "token").read_text().strip() + assert record["observer_token_sha256"] == hashlib.sha256(token.encode()).hexdigest() + assert hub.db.keys[node_id]["observer_token_sha256"] == record["observer_token_sha256"] + # the kit pins what the hub has, and is laid out like a provisioned one + assert cert_file_pin(kit / "pki" / "directory" / "tls.crt") == cert_file_pin(hub.pki / "directory" / "tls.crt") + assert (kit / "pki" / "observer" / "tls.crt").read_text() == (hub.pki / "observer" / "tls.crt").read_text() + assert (kit / "data" / f"{node_id}.csv").read_text() == (ROOT / "data" / "slices" / "hospital-d.csv").read_text() + assert (kit / "deploy" / "node.yml").is_file() and "SHARED_SECRET=" not in (kit / ".env").read_text() + assert (kit / "pki" / "network" / "shared_secret").read_text().strip() == "chain-test-secret" + wait_until(lambda: hub.db.events("enrolled"), 5, "the enrollment in the audit log") + + # it runs as a node: registers with its credential and keys, and joins the kit hospital's chain + node = NodeServer(kit / "config" / "node.yaml").start() + hub.nodes.append(node) + wait_until(lambda: node.status()["chain"] == ["hospital-a", node_id], 20, "both hospitals in the chain") + assert node.status()["display_name"] == "St Mary's Leeds" + assert node.status()["patients"] == 62 # hospital-d.csv + + # running it again changes nothing + assert enroll.main(["--hub", hub.hub, "--name", "x", "--code", code, "--advertise", "127.0.0.1", + "--out", str(kit)]) == 0 + assert len(hub.directory.store.enrolled()) == 1 + + +def test_a_join_code_works_once_and_every_refusal_is_audited(hub): + code = hub.code() + enroll.request_enrollment(hub.hub, "Hospital One", code, ["127.0.0.1"], enroll.Keys.generate()) + with pytest.raises(enroll.EnrollError, match="has been used"): + enroll.request_enrollment(hub.hub, "Hospital Two", code, ["127.0.0.1"], enroll.Keys.generate()) + + revoked = hub.code() + assert hub.admin("POST", f"/admin/join-codes/{enroll.code_id(revoked)}/revoke", json={}).status_code == 200 + with pytest.raises(enroll.EnrollError, match="has been revoked"): + enroll.request_enrollment(hub.hub, "Hospital Three", revoked, ["127.0.0.1"], enroll.Keys.generate()) + + expired = hub.code(ttl_minutes=1) + with hub.directory.store._lock: + hub.directory.store._conn.execute("UPDATE join_codes SET expires_at = ? WHERE code_id = ?", + (time.time() - 1, enroll.code_id(expired))) + with pytest.raises(enroll.EnrollError, match="has expired"): + enroll.request_enrollment(hub.hub, "Hospital Four", expired, ["127.0.0.1"], enroll.Keys.generate()) + + with pytest.raises(enroll.EnrollError, match="unknown join code"): + enroll.request_enrollment(hub.hub, "Hospital Five", enroll.new_code(), ["127.0.0.1"], enroll.Keys.generate()) + + # the right id with the wrong secret: refused, and five of those revoke the code + target = hub.code() + wrong = target[:5] + ("B" if target[5] != "B" else "C") + target[6:] + for i in range(5): + with pytest.raises(enroll.EnrollError, match="join code is wrong"): + enroll.request_enrollment(hub.hub, "Guesser", wrong, ["127.0.0.1"], enroll.Keys.generate()) + with pytest.raises(enroll.EnrollError, match="has been revoked"): + enroll.request_enrollment(hub.hub, "Hospital Six", target, ["127.0.0.1"], enroll.Keys.generate()) + + states = {c["code_id"]: c["state"] for c in hub.admin("GET", "/admin/join-codes").json()["codes"]} + assert states[enroll.code_id(code)] == "used" and states[enroll.code_id(target)] == "revoked" + wait_until(lambda: len(hub.db.events("enroll_rejected")) == 10, 5, "every refusal in the audit log") + assert {a["detail"]["display_name"] for a in hub.db.events("enroll_rejected")} >= {"Hospital Two", "Guesser"} + assert len(hub.db.events("join_code_created")) == 4 and len(hub.db.events("join_code_revoked")) == 1 + + +def test_the_admin_api_needs_the_hubs_admin_token(hub): + assert hub.admin("POST", "/admin/join-codes", token="nope", json={}).status_code == 401 + assert httpx.get(f"{hub.directory.url}/admin/join-codes", verify=str(hub.pki / "ca.crt")).status_code == 401 + listing = hub.admin("GET", "/admin/join-codes").json() + assert "hospital-a.csv" in listing["slices"] and listing["ttl_minutes"] == 30 + assert hub.admin("POST", "/admin/join-codes", json={"data_slice": "../config/directory.yaml"}).status_code == 400 + + +def test_an_enrolled_hospital_must_register_with_the_keys_it_enrolled_with(hub, tmp_path, monkeypatch): + kit = tmp_path / "kit" + (port,) = free_ports(1) + assert enroll.main(["--hub", hub.hub, "--name", "Rekeyed", "--code", hub.code(), "--advertise", "127.0.0.1", + "--port", str(port), "--out", str(kit)]) == 0 + node_id = kit_env(monkeypatch, kit) + # someone with the credential but another signing key + pki.ensure_identity(tmp_path / "other", "x", ["127.0.0.1"], credential=False) + monkeypatch.setenv("SIGNING_KEY", str(tmp_path / "other" / "x" / "signing.key")) + node = NodeServer(kit / "config" / "node.yaml").start() + hub.nodes.append(node) + wait_until(lambda: any(e["event"] == "auth_failed" and e["node_id"] == node_id + for e in hub.directory.store.events()), 10, "the registration refused") + assert not node.status()["in_chain"] + + +def test_the_hub_must_prove_it_issued_the_code(hub, monkeypatch): + """An answer that does not carry the code's HMAC (someone else answering at the hub's address) is refused.""" + real = enroll.post_enroll + + def tampered(host, port, body, timeout): + status, answer, pin = real(host, port, body, timeout) + answer["observer"]["port"] = 9999 + return status, answer, pin + + monkeypatch.setattr(enroll, "post_enroll", tampered) + with pytest.raises(enroll.EnrollError, match="not from the hub"): + enroll.request_enrollment(hub.hub, "Hospital", hub.code(), ["127.0.0.1"], enroll.Keys.generate()) diff --git a/tests/unit/test_observer.py b/tests/unit/test_observer.py index 416c067..081d68f 100644 --- a/tests/unit/test_observer.py +++ b/tests/unit/test_observer.py @@ -99,3 +99,51 @@ def test_a_node_pushes_its_telemetry_to_the_observer_over_pinned_tls(tmp_path): finally: node.stop(abrupt=True) observer.stop(abrupt=True) + + +class KeysDatabase(RecordingDatabase): + """hospital_keys as the directory wrote them: one enrolled hospital with its own token.""" + + def __init__(self, owners: dict[str, str]): + super().__init__() + self.owners = owners + + def fetch(self, sql, params=None): + return [(self.owners[params[0]],)] if "hospital_keys" in sql and params[0] in self.owners else [] + + def heartbeat(self, node_id, run_id, run_state, current_round): + self.audits.append({"event": "heartbeat", "node_id": node_id}) + + +def test_an_enrolled_hospitals_own_token_writes_only_as_that_hospital(tmp_path): + import hashlib + + from chain_harness import free_ports, issue_pki + + pki_dir = issue_pki(tmp_path, ["hospital-a"]) + pki.ensure_identity(pki_dir, "observer", ["127.0.0.1", "localhost"], credential=False) + own = "node-1-own-token" + db = KeysDatabase({hashlib.sha256(own.encode()).hexdigest(): "node-1"}) + (port,) = free_ports(1) + observer = ObserverServer(port, pki_dir, db).start() + try: + url, ca = f"{observer.url}/ingest", str(pki_dir / "ca.crt") + + def post(token, node_id, items): + return httpx.post(url, json={"node_id": node_id, "items": items}, verify=ca, timeout=5, + headers={"Authorization": f"Bearer {token}"}) + + beat = lambda n: {"kind": "heartbeat", "payload": {"node_id": n, "run_id": None, "run_state": "idle", # noqa: E731 + "current_round": 0}} + assert post(own, "node-1", [beat("node-1")]).json()["applied"] == 1 + assert post(own, "hospital-a", [beat("hospital-a")]).status_code == 403, "another hospital's batch" + assert post(own, "node-1", [beat("hospital-a")]).status_code == 403, "another hospital's row" + assert post("not-a-token", "node-1", [beat("node-1")]).status_code == 401 + # the network token still works for kit hospitals; neither token can write the directory's key records + assert post(TOKEN, "hospital-a", [beat("hospital-a")]).json()["applied"] == 1 + keys = {"kind": "hospital_key", "payload": {"node_id": "node-1", "display_name": "x", + "signing_public_key": None, "tls_pin": None}} + assert post(own, "node-1", [keys]).json()["applied"] == 0 + assert post(TOKEN, "hospital-a", [keys]).json()["applied"] == 0 + finally: + observer.stop(abrupt=True) diff --git a/tests/unit/test_provision.py b/tests/unit/test_provision.py index 1fa7669..8ebfbbd 100644 --- a/tests/unit/test_provision.py +++ b/tests/unit/test_provision.py @@ -129,6 +129,10 @@ def test_one_run_provisions_every_hospital_and_the_hub(tmp_path, monkeypatch): 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" + # the hub signs join-code hospitals' certificates: its kit, and only its kit, holds the CA key + assert dcfg["enrollment"]["ca_key"] == "/pki/ca.key" and dcfg["enrollment"]["observer_port"] == 8200 + assert (d / "pki/ca.key").read_bytes() == (tmp_path / ".pki/ca.key").read_bytes() + assert not any((tmp_path / n / "pki/ca.key").exists() for n in ids) 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()) diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index dcea8fe..445e258 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -9,7 +9,7 @@ ROOT = Path(__file__).resolve().parents[2] SETTINGS = ["NODE_CONFIG", "NODE_ID", "BIND_HOST", "NODE_PORT", "ADVERTISE_ADDR", "MEDCHAIN_ADVERTISE_URL", "DIRECTORY_URL", "MEDCHAIN_DIRECTORY_URL", "OBSERVER_URL", "OBSERVER_TOKEN", "OBSERVER_TLS_PIN", "DATA_PATH", - "ALGORITHM", "BITS", "EPSILON", "ROUND_TIMEOUT_S", "IMAGE_VERSION", "SHARED_SECRET", "TLS_CERT", "TLS_KEY", + "ALGORITHM", "BITS", "EPSILON", "ROUND_TIMEOUT_S", "IMAGE_VERSION", "SHARED_SECRET", "SHARED_SECRET_FILE", "TLS_CERT", "TLS_KEY", "TLS_CA", "SIGNING_KEY", "DIRECTORY_CREDENTIAL_FILE", "DIRECTORY_PUBLIC_KEY", "DIRECTORY_TLS_PIN", "HTTP_CONNECT_TIMEOUT_S", "HTTP_READ_TIMEOUT_S", "ROUND_PAUSE_S", "CHECKPOINT_DIR", "DATA_SLICE"] @@ -95,3 +95,10 @@ def test_missing_yaml_named_by_node_config_is_an_error(monkeypatch, tmp_path): monkeypatch.setenv("NODE_CONFIG", str(tmp_path / "nope.yaml")) with pytest.raises(FileNotFoundError): load_config() + + +def test_the_shared_secret_can_come_from_a_file(monkeypatch, tmp_path): + """A join-code enrollment writes it to pki/network/shared_secret, so nobody types it (node/enroll.py).""" + (tmp_path / "secret").write_text("from-the-hub\n") + monkeypatch.setenv("SHARED_SECRET_FILE", str(tmp_path / "secret")) + assert load_config(ROOT / "config" / "hospital-b.yaml").shared_secret == "from-the-hub" From 812ddb1f049f09d766ca75c4c54342a7bad33e76 Mon Sep 17 00:00:00 2001 From: Denimworld12 <166978100+Denimworld12@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:34:12 +0530 Subject: [PATCH 02/16] feat(naming): free-text display names, generated stable node ids for enrolled hospitals - The directory generates an enrolled hospital's node id as a slug of its display name plus random hex (st-marys-leeds-3f9a); identity (TLS pins, signatures, chain placement) stays keyed on the id and keys. - Display names are unique, compared case/space-insensitively, against enrolled hospitals and every hospital in the directory's documents; a clash is a 409 and the code stays valid. An enrolled hospital always appears under the name it enrolled with, whatever its node's config says. - Dashboard audit log shows display names (id in the tooltip); node start-up log names the hospital. hospital-a..e are unchanged for make up and kits. --- README.md | 9 ++++++++ dashboard/src/pages/AuditLog.jsx | 11 +++++++-- directory/app.py | 12 +++++++--- directory/enroll.py | 39 ++++++++++++++++++++++++++++---- directory/store.py | 3 ++- node/enroll.py | 6 ++++- node/main.py | 4 ++-- tests/unit/test_enroll.py | 33 +++++++++++++++++++++++++++ 8 files changed, 103 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 853a559..f8a54f1 100644 --- a/README.md +++ b/README.md @@ -700,6 +700,15 @@ keep working unchanged): a **join code**. `deploy/node.yml` runs it. The secret goes to `pki/network/shared_secret` (`SHARED_SECRET_FILE`): nobody types it, nothing prints it. +**Names.** The person enrolling types the hospital's display name as free text; it +is what the dashboard, the node's logs and the audit log show. No two hospitals may +share one (compared ignoring case and spacing; the code stays valid for another try). +The node id is separate and generated by the directory, a slug of the name plus random +hex (`st-marys-leeds-3f9a`). TLS pins, signatures and chain placement stay keyed on the +id and its keys, never on the name, and an enrolled hospital always appears under the +name it enrolled with. `hospital-a` ... `hospital-e` stay as they are for `make up` +and the kits. + Every attempt is in the audit log (`enrolled`, `enroll_rejected`, `join_code_created`, `join_code_revoked`). An enrolled hospital may only register with the keys it enrolled with. Its observer token only writes rows as that hospital; diff --git a/dashboard/src/pages/AuditLog.jsx b/dashboard/src/pages/AuditLog.jsx index 9897ccd..2e07e22 100644 --- a/dashboard/src/pages/AuditLog.jsx +++ b/dashboard/src/pages/AuditLog.jsx @@ -5,8 +5,15 @@ function time(ts) { return Number.isNaN(d.getTime()) ? ts : d.toISOString().replace("T", " ").slice(0, 23) + "Z"; } +// Hospitals by their display name (the node id, their stable identity, is in the tooltip). +function Party({ id, names }) { + if (!id) return "-"; + return names[id] && names[id] !== id ? {names[id]} : id; +} + export default function AuditLog({ snapshot }) { const rows = snapshot?.audit || []; + const names = Object.fromEntries((snapshot?.nodes || []).map((n) => [n.node_id, n.display_name])); return (
@@ -30,8 +37,8 @@ export default function AuditLog({ snapshot }) { {time(r.ts)} {r.event.replaceAll("_", " ")} {r.round ?? "-"} - {r.sender || "-"} - {r.receiver || "-"} + + {r.payload_bytes != null ? formatBytes(r.payload_bytes) : "-"} {r.checksum ? `${r.checksum.slice(0, 16)}...` : "-"} diff --git a/directory/app.py b/directory/app.py index 7818e64..2d11c5a 100644 --- a/directory/app.py +++ b/directory/app.py @@ -162,8 +162,12 @@ def hospitals() -> list[dict]: return configured() + [{"id": r["node_id"], "credential_sha256": r["credential_sha256"], "enrolled": r} for r in store.enrolled()] + def member_names() -> dict[str, str]: + """{id: display name} of every hospital in the directory's documents (the current and earlier chains).""" + return {m.id: m.display_name or m.id for doc in reversed(store.recent(1000)) for m in doc.members.values()} + enroller = (Enroller(cfg.enrollment, store, signing_key=key, directory_cert=cfg.tls_cert, - configured_ids=lambda: [str(h["id"]) for h in configured()]) + configured_ids=lambda: [str(h["id"]) for h in configured()], member_names=member_names) if cfg.enrollment and cfg.tls_cert else None) def audit(event: str, node_id: str | None, detail: dict, sender: str | None = None) -> None: @@ -318,8 +322,10 @@ async def register(req: RegisterRequest, request: Request): store.log("auth_failed", req.node_id, {"reason": "keys differ from the ones it enrolled with"}) raise HTTPException(403, detail=f"{req.node_id} must register with the keys it enrolled with; to change " "them, enroll again with a new join code") - me = Member(req.node_id, req.url.rstrip("/"), req.public_key, req.display_name, req.tls_spki_sha256) - db.hospital_key(node_id=req.node_id, display_name=req.display_name or req.node_id, + # an enrolled hospital goes by the name it enrolled with, whatever its node says + name = enrolled["display_name"] if enrolled else req.display_name + me = Member(req.node_id, req.url.rstrip("/"), req.public_key, name, req.tls_spki_sha256) + db.hospital_key(node_id=req.node_id, display_name=name or req.node_id, signing_public_key=req.public_key, tls_pin=req.tls_spki_sha256) async with lock: latest = store.latest() diff --git a/directory/enroll.py b/directory/enroll.py index a223e1e..5d5631b 100644 --- a/directory/enroll.py +++ b/directory/enroll.py @@ -11,6 +11,12 @@ node a certificate from the network CA, generates its node id and an observer ingest token for it alone, and answers with everything a kit would hold except private keys. Every attempt, accepted or not, is written to the audit log. + +Names: the display name is free text, chosen by the person enrolling, and it is what the +dashboard, the logs and the audit trail show. No two hospitals may share one (compared +case- and space-insensitively). The node id is separate and stable: a slug of the name +plus random hex (`st-marys-leeds-3f9a`), generated here and never chosen by the node. TLS +pins, signatures and chain placement are keyed on the id and its keys, never the name. """ from __future__ import annotations @@ -20,6 +26,7 @@ import re import secrets import time +import unicodedata from dataclasses import dataclass from pathlib import Path from typing import Callable @@ -73,6 +80,17 @@ def shared_secret(self) -> str: return secret +def name_key(name: str) -> str: + """What two display names are compared by: "St Mary's" and "st mary's" are the same name.""" + return " ".join(unicodedata.normalize("NFKC", name).casefold().split()) + + +def slug(name: str, size: int = 20) -> str: + """The readable part of a node id: lowercase ASCII letters, digits and single dashes.""" + ascii_name = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode().lower() + return re.sub(r"[^a-z0-9]+", "-", ascii_name).strip("-")[:size].strip("-") or "hospital" + + class EnrollmentError(Exception): def __init__(self, status: int, detail: str): super().__init__(detail) @@ -85,10 +103,11 @@ def _pem(cert: x509.Certificate) -> str: class Enroller: def __init__(self, cfg: EnrollmentConfig, store: Store, *, signing_key, directory_cert: str, - configured_ids: Callable[[], list[str]]): + configured_ids: Callable[[], list[str]], member_names: Callable[[], dict[str, str]]): self.cfg, self.store, self.signing_key = cfg, store, signing_key self.directory_cert = directory_cert self.configured_ids = configured_ids # the kit hospitals (hospitals.yaml), whose ids are taken + self.member_names = member_names # {node id: display name} of the hospitals the directory has registered # -- join codes ----------------------------------------------------------------------------- def slices(self) -> list[str]: @@ -121,13 +140,18 @@ def state(row: dict, now: float | None = None) -> str: return "expired" if row["expires_at"] <= now else "active" # -- enrollment ------------------------------------------------------------------------------- - def new_node_id(self) -> str: + def new_node_id(self, name: str) -> str: taken = {*self.configured_ids(), *(r["node_id"] for r in self.store.enrolled()), "directory", "observer"} while True: - node_id = f"node-{secrets.token_hex(4)}" + node_id = f"{slug(name)}-{secrets.token_hex(2)}" if node_id not in taken: return node_id + def name_taken_by(self, name: str) -> str | None: + """The node id of the hospital that already goes by this display name (None if it is free).""" + names = {**self.member_names(), **{r["node_id"]: r["display_name"] for r in self.store.enrolled()}} + return next((i for i, n in names.items() if name_key(n or i) == name_key(name)), None) + def pick_slice(self, wanted: str | None) -> str: """The code's slice, else the one the fewest enrolled hospitals have (kit hospitals' own slices last).""" names = self.slices() @@ -175,6 +199,10 @@ def check(self, req: dict) -> tuple[dict, str, x509.CertificateSigningRequest, l name = " ".join(str(req.get("display_name", "")).split()) if not NAME.match(name): raise EnrollmentError(400, "the display name must be 2 to 60 characters") + taken = self.name_taken_by(name) + if taken: + raise EnrollmentError(409, f"another hospital ({taken}) is already called {name!r}: choose another name " + "(your join code is still valid)") return row, key, csr, addresses def enroll(self, req: dict) -> tuple[dict, dict]: @@ -185,13 +213,14 @@ def enroll(self, req: dict) -> tuple[dict, dict]: secret = self.cfg.shared_secret ca_cert = x509.load_pem_x509_certificate(Path(self.cfg.ca_cert).read_bytes()) ca_key = serialization.load_pem_private_key(Path(self.cfg.ca_key).read_bytes(), password=None) - node_id = self.new_node_id() + node_id = self.new_node_id(name) if not self.store.consume_code(code_row["code_id"], node_id): # someone else used it a moment ago raise EnrollmentError(403, "this join code has just been used: ask the organiser for a new one") cert = security.issue_certificate(ca_cert, ca_key, csr.public_key(), node_id, [*addresses, node_id, "localhost", "127.0.0.1"]) token = secrets.token_urlsafe(32) - record = {"node_id": node_id, "display_name": name, "credential_sha256": req["credential_sha256"], + record = {"node_id": node_id, "display_name": name, "name_key": name_key(name), + "credential_sha256": req["credential_sha256"], "signing_public_key": req["signing_public_key"], "tls_pin": pinning.spki_sha256(cert), "observer_token_sha256": hashlib.sha256(token.encode()).hexdigest(), "data_slice": data_slice, "code_id": code_row["code_id"], "enrolled_at": time.time()} diff --git a/directory/store.py b/directory/store.py index 736f7d5..5342f53 100644 --- a/directory/store.py +++ b/directory/store.py @@ -45,6 +45,7 @@ CREATE TABLE IF NOT EXISTS enrolled ( node_id TEXT PRIMARY KEY, display_name TEXT NOT NULL, + name_key TEXT NOT NULL UNIQUE, -- two hospitals never share a display name (directory/enroll.py) credential_sha256 TEXT NOT NULL, signing_public_key TEXT NOT NULL, tls_pin TEXT NOT NULL, @@ -57,7 +58,7 @@ CODE_COLUMNS = ("code_id", "created_at", "created_by", "expires_at", "data_slice", "used_at", "used_by", "revoked_at", "revoked_by", "failures") -ENROLLED_COLUMNS = ("node_id", "display_name", "credential_sha256", "signing_public_key", "tls_pin", +ENROLLED_COLUMNS = ("node_id", "display_name", "name_key", "credential_sha256", "signing_public_key", "tls_pin", "observer_token_sha256", "data_slice", "code_id", "enrolled_at") MAX_FAILURES = 5 # wrong proofs for one code before it is revoked diff --git a/node/enroll.py b/node/enroll.py index a0905e5..3f09b2c 100644 --- a/node/enroll.py +++ b/node/enroll.py @@ -19,7 +19,9 @@ `data/`, `config/node.yaml`, `deploy/node.yml`), so `docker compose --project-directory -f deploy/node.yml up -d` runs it like any other hospital. -The hub answers with: a certificate for this node's TLS key, signed by the network CA; the +The display name is free text and is what the dashboard, the logs and the audit trail +show; the hub refuses one another hospital already has. The hub answers with: a +certificate for this node's TLS key, signed by the network CA; the CA certificate; the directory's document key and TLS certificate (pinned from then on); the observer's TLS certificate and port and an ingest token for this hospital alone; the network secret (written to `pki/network/shared_secret`, never printed); the engine settings @@ -328,6 +330,8 @@ def main(argv: list[str] | None = None) -> int: try: if not code: raise EnrollError("no join code: pass --code or set MEDCHAIN_JOIN_CODE") + if not 2 <= len(name) <= 60: + raise EnrollError("the hospital's name must be 2 to 60 characters") advertise = check_address(args.advertise) hub_host, hub_port = split_hub(args.hub) keys = Keys.generate() diff --git a/node/main.py b/node/main.py index 6659a60..ffeebfd 100644 --- a/node/main.py +++ b/node/main.py @@ -232,8 +232,8 @@ async def lifespan(app: FastAPI): state["rejoin"] = asyncio.create_task(register_with_directory(runner)) elif cfg.is_admm: # a checkpoint on the volume means we were killed mid-run: rejoin it state["rejoin"] = asyncio.create_task(runner.rejoin()) - log.info("%s up on :%d (%s) with %d patients, neighbours=%s, engine=%s", cfg.node_id, cfg.port, cfg.scheme, - trainer.n_patients, nbs, engine.label) + log.info("%s (%s) up on :%d (%s) with %d patients, neighbours=%s, engine=%s", cfg.display_name, cfg.node_id, + cfg.port, cfg.scheme, trainer.n_patients, nbs, engine.label) try: yield finally: diff --git a/tests/unit/test_enroll.py b/tests/unit/test_enroll.py index 0cc6031..4bf8323 100644 --- a/tests/unit/test_enroll.py +++ b/tests/unit/test_enroll.py @@ -126,6 +126,7 @@ def test_a_hospital_enrolls_with_a_join_code_and_joins_the_chain(hub, tmp_path, record = hub.directory.store.enrolled()[0] assert (record["node_id"], record["display_name"], record["data_slice"]) == (node_id, "St Mary's Leeds", "hospital-d.csv") + assert node_id.startswith("st-mary-s-leeds-") and len(node_id) == len("st-mary-s-leeds-") + 4 # its own keys: the hub has only the public halves and hashes assert record["tls_pin"] == cert_file_pin(kit / "pki" / node_id / "tls.crt") assert record["signing_public_key"] == (kit / "pki" / node_id / "signing.pub").read_text().strip() @@ -228,3 +229,35 @@ def tampered(host, port, body, timeout): monkeypatch.setattr(enroll, "post_enroll", tampered) with pytest.raises(enroll.EnrollError, match="not from the hub"): enroll.request_enrollment(hub.hub, "Hospital", hub.code(), ["127.0.0.1"], enroll.Keys.generate()) + + +def test_display_names_are_free_text_but_never_shared_and_ids_stay_stable(hub, tmp_path, monkeypatch): + from directory.enroll import name_key, slug + + assert slug(" Hôpital Saint-Éloi (Paris) ") == "hopital-saint-eloi-p" + assert slug("医院") == "hospital" and name_key("St MARY'S") == name_key("st mary's") + hub.nodes.append(NodeServer(hub.cfgs["hospital-a"]).start()) # no display_name in its config: "hospital-a" + wait_until(lambda: hub.nodes[0].status()["in_chain"], 20, "hospital-a registered") + + code = hub.code() + with pytest.raises(enroll.EnrollError, match=r"\(hospital-a\) is already called 'HOSPITAL-A'"): + enroll.request_enrollment(hub.hub, "HOSPITAL-A", code, ["127.0.0.1"], enroll.Keys.generate()) + first = enroll.request_enrollment(hub.hub, "Leeds General", code, ["127.0.0.1"], enroll.Keys.generate()) + with pytest.raises(enroll.EnrollError, match="already called"): + enroll.request_enrollment(hub.hub, "LEEDS general", hub.code(), ["127.0.0.1"], enroll.Keys.generate()) + second = enroll.request_enrollment(hub.hub, "Leeds General 2", hub.code(), ["127.0.0.1"], enroll.Keys.generate()) + assert first["node_id"] != second["node_id"] and first["node_id"].startswith("leeds-general-") + + # the name it enrolled with is the one the chain shows, whatever its node's config says + kit = tmp_path / "kit" + (port,) = free_ports(1) + assert enroll.main(["--hub", hub.hub, "--name", "Royal Infirmary", "--code", hub.code(), "--advertise", + "127.0.0.1", "--port", str(port), "--out", str(kit)]) == 0 + node_id = kit_env(monkeypatch, kit) + config = kit / "config" / "node.yaml" + config.write_text(config.read_text().replace("display_name: Royal Infirmary", "display_name: hospital-a")) + node = NodeServer(config).start() + hub.nodes.append(node) + wait_until(lambda: node_id in hub.nodes[0].status()["chain"], 20, "the enrolled node in the chain") + assert hub.directory.store.latest().members[node_id].display_name == "Royal Infirmary" + wait_until(lambda: hub.db.keys.get(node_id, {}).get("display_name") == "Royal Infirmary", 5, "its key record") From c15113f6c65cb1cf4e1906e59face1ca0bdf66a2 Mon Sep 17 00:00:00 2001 From: Denimworld12 <166978100+Denimworld12@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:40:18 +0530 Subject: [PATCH 03/16] feat(proof): signed proof-of-origin messages, verified by the hub, on a Nodes page - node/proof.py: every 10 s each node with a signing key POSTs the observer a message signed with its update-signing Ed25519 key (context "proof"): host name, OS and version, uptime, Tailscale device (from the install script via MEDCHAIN_HOST_*; else the container's own, labelled), live RTT to each chain neighbour over the pinned TLS client, data row count, boot id + sequence. - observer POST /proof: verifies against hospital_keys (the directory's record), refuses unknown keys, bad signatures, replays and >10 min skew, and audits each refusal (proof_rejected); stores the latest in node_proofs (not via /ingest). - dashboard: snapshot.proofs (verified / rejected / stale / none) and a Nodes page with a Signature verified badge, key fingerprint and the facts. Start/Pause unchanged. - node.enroll takes --host-name/--host-os/--host-booted-at/--tailscale-device. --- README.md | 20 ++++++ dashboard/server/snapshot.js | 40 +++++++++++ dashboard/server/snapshot.test.js | 31 ++++++++- dashboard/src/App.jsx | 3 + dashboard/src/pages/Nodes.jsx | 109 ++++++++++++++++++++++++++++++ dashboard/src/styles.css | 8 +++ node/db.py | 32 +++++++++ node/enroll.py | 22 +++++- node/main.py | 24 ++++++- node/proof.py | 105 ++++++++++++++++++++++++++++ observer/app.py | 61 ++++++++++++++++- tests/unit/test_enroll.py | 6 +- tests/unit/test_observer.py | 105 +++++++++++++++++++++++++++- 13 files changed, 553 insertions(+), 13 deletions(-) create mode 100644 dashboard/src/pages/Nodes.jsx create mode 100644 node/proof.py diff --git a/README.md b/README.md index f8a54f1..132d4d8 100644 --- a/README.md +++ b/README.md @@ -717,6 +717,26 @@ directory needs the CA key for this: `provision.py` puts it in the hub kit (`pki/ca.key`), and `deploy/hub.yml` mounts `data/slices/` and `config/hospital-a.yaml` (the engine settings) into it. +### Proof of origin on the dashboard + +Every node with a signing key and an observer sends the observer a status message every +10 seconds (`node/proof.py`, `POST /proof`), signed with the Ed25519 key that signs its +training updates. It holds the computer's hostname, OS and version, uptime and Tailscale +device name (read on the host by the install script; without it, what the container +sees, labelled as such), the round-trip time it measures right then to each chain +neighbour over the pinned TLS links training uses, and how many data rows it holds (the +count only). It also carries a per-start boot id and a rising sequence number. + +The observer checks the signature against the key the directory has on record for that +hospital (`hospital_keys`, written by the directory when the hospital registers or +enrolls). It refuses a message that does not verify, comes from a hospital with no key +on record, is a replay or is more than 10 minutes old, and writes each refusal to the +audit log (`proof_rejected`). The dashboard's **Nodes** page shows each hospital's facts +with a **Signature verified** badge and the key's fingerprint, or **Rejected** with the +reason. This is in addition to the Start/Pause controls. One limit: the host's uptime +counts from the boot time the install script saw, so after a reboot, run the installer +again to refresh it. The round-trip times and data rows are always live. + ### Prove it `scripts/verify_multihost.py` is the acceptance test, on real laptops or on one diff --git a/dashboard/server/snapshot.js b/dashboard/server/snapshot.js index 87cb4dd..a29110e 100644 --- a/dashboard/server/snapshot.js +++ b/dashboard/server/snapshot.js @@ -8,6 +8,8 @@ // pure functions below, which are unit-tested (snapshot.test.js). export const STALE_AFTER_S = Number(process.env.HEARTBEAT_STALE_S || 7); +// node/proof.py sends a signed proof-of-origin message every 10 s; older than this, it no longer counts as live +export const PROOF_STALE_S = Number(process.env.PROOF_STALE_S || 35); const AUDIT_ROWS = Number(process.env.AUDIT_ROWS || 80); const edgeKey = (a, b) => `${a}|${b}`; @@ -153,6 +155,43 @@ export function commFrom(perRoundRows, topology, hospitals = new Map()) { }; } +// Proof of origin per hospital (node/proof.py, checked by the observer): "verified" while its newest signed +// message is fresh and newer than any refused one, "rejected" when the newest thing it sent was refused, +// "stale" once it goes quiet, "none" if the observer never accepted one from it. +export function proofsFrom(rows, staleAfter = PROOF_STALE_S) { + return rows.map((r) => { + const since = r.seconds_since_proof; + const rejectedSince = r.seconds_since_rejection; + let status = "none"; + if (rejectedSince != null && (since == null || rejectedSince < since)) status = "rejected"; + else if (since != null) status = since <= staleAfter ? "verified" : "stale"; + return { + node_id: r.node_id, + display_name: r.display_name || r.node_id, + enrolled: !!r.enrolled, + status, + seconds_since_proof: since, + key_fingerprint: r.key_fingerprint || null, + rejection: status === "rejected" ? r.rejection : null, + message: r.message || null, + }; + }); +} + +async function proofRows(pool) { + try { + const { rows } = await pool.query( + `SELECT p.node_id, p.message, p.key_fingerprint, p.rejection, k.display_name, k.enrolled, + EXTRACT(EPOCH FROM (now() - p.received_at))::float AS seconds_since_proof, + EXTRACT(EPOCH FROM (now() - p.rejected_at))::float AS seconds_since_rejection + FROM node_proofs p LEFT JOIN hospital_keys k USING (node_id) ORDER BY p.node_id`, + ); + return rows; + } catch { + return []; // an observer older than node_proofs has not created the table + } +} + export async function buildSnapshot(pool) { const nodesRes = await pool.query( `SELECT node_id, display_name, url, patients, neighbours, engine, run_id, run_state, current_round, @@ -230,6 +269,7 @@ export async function buildSnapshot(pool) { consensus, comm, audit: auditRes.rows, + proofs: proofsFrom(await proofRows(pool)), }; } diff --git a/dashboard/server/snapshot.test.js b/dashboard/server/snapshot.test.js index 79abd31..e3100c0 100644 --- a/dashboard/server/snapshot.test.js +++ b/dashboard/server/snapshot.test.js @@ -5,7 +5,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { commFrom, consensusFrom, currentTopology, hospitalsByRound, networkLossFrom } from "./snapshot.js"; +import { commFrom, consensusFrom, currentTopology, hospitalsByRound, networkLossFrom, proofsFrom } from "./snapshot.js"; import { W, chainLinks, chainMembers, layout } from "../src/topologyLayout.js"; const EPS = 1e-3; @@ -149,7 +149,12 @@ test("network training loss: a round counts only once every member of its chain assert.ok(!rounds.includes(7) && !rounds.includes(12)); assert.ok(rounds.includes(6) && rounds.includes(11)); // rows from before chain_size existed fall back to the registered member count - const legacy = metricsRows(3).map(({ chain_size, epoch, ...r }) => r); + const legacy = metricsRows(3).map((row) => { + const r = { ...row }; + delete r.chain_size; + delete r.epoch; + return r; + }); assert.equal(networkLossFrom(legacy, 4).length, 3); assert.equal(networkLossFrom(legacy, 5).length, 0); }); @@ -204,3 +209,25 @@ test("topology layout: a member without a node row yet still gets a placeholder" assert.equal(placed[1].node_id, "hospital-e"); assert.equal(placed[1].status, "down"); }); + +test("proof of origin: verified only while the newest signed message is fresh and was accepted", () => { + const msg = { host: { hostname: "alex-laptop" }, data_rows: 62 }; + const rows = [ + { node_id: "st-marys-3f9a", display_name: "St Mary's", enrolled: true, seconds_since_proof: 4, message: msg, + key_fingerprint: "ab12" }, + { node_id: "hospital-b", seconds_since_proof: 120, message: msg }, + { node_id: "hospital-c", seconds_since_proof: 20, seconds_since_rejection: 3, rejection: "signature: does not verify" }, + { node_id: "hospital-d", seconds_since_rejection: 9, rejection: "no signing key is on record" }, + { node_id: "hospital-e", seconds_since_proof: 2, seconds_since_rejection: 50, rejection: "old" }, + ]; + const out = Object.fromEntries(proofsFrom(rows, 35).map((p) => [p.node_id, p])); + assert.equal(out["st-marys-3f9a"].status, "verified"); + assert.equal(out["st-marys-3f9a"].display_name, "St Mary's"); + assert.equal(out["hospital-b"].status, "stale"); + assert.equal(out["hospital-b"].display_name, "hospital-b"); + assert.equal(out["hospital-c"].status, "rejected"); + assert.equal(out["hospital-c"].rejection, "signature: does not verify"); + assert.equal(out["hospital-d"].status, "rejected"); + assert.equal(out["hospital-e"].status, "verified", "a later accepted message clears an older refusal"); + assert.equal(out["hospital-e"].rejection, null); +}); diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 2d75340..b3c3351 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -7,12 +7,14 @@ import TrainingMonitor from "./pages/TrainingMonitor.jsx"; import Communication from "./pages/Communication.jsx"; import AuditLog from "./pages/AuditLog.jsx"; import Assessment from "./pages/Assessment.jsx"; +import Nodes from "./pages/Nodes.jsx"; import { control, useSnapshot } from "./useSnapshot.js"; const ROUTES = [ { hash: "#/", label: "Topology" }, { hash: "#/training", label: "Training monitor" }, { hash: "#/communication", label: "Communication" }, + { hash: "#/nodes", label: "Nodes" }, { hash: "#/audit", label: "Audit log" }, { hash: "#/assessment", label: "Risk assessment" }, ]; @@ -112,6 +114,7 @@ export default function App() { )} {route === "#/training" && } {route === "#/communication" && } + {route === "#/nodes" && } {route === "#/audit" && } {route === "#/assessment" && } diff --git a/dashboard/src/pages/Nodes.jsx b/dashboard/src/pages/Nodes.jsx new file mode 100644 index 0000000..7cdcd79 --- /dev/null +++ b/dashboard/src/pages/Nodes.jsx @@ -0,0 +1,109 @@ +import { SectionHeading } from "../components/ui.jsx"; + +// Proof of origin: what each hospital's own machine says about itself, in messages signed with the +// key that signs its training updates and checked by the observer against the key the directory has +// on record (node/proof.py). Nothing here comes from the dashboard or from a button press. + +const BADGE = { + verified: { cls: "status-pill--sage", text: "Signature verified" }, + rejected: { cls: "status-pill--orange", text: "Rejected" }, + stale: { cls: "status-pill--grey", text: "No recent message" }, + none: { cls: "status-pill--grey", text: "Never verified" }, +}; + +function duration(s) { + if (s == null) return "-"; + const d = Math.floor(s / 86400); + const h = Math.floor((s % 86400) / 3600); + const m = Math.floor((s % 3600) / 60); + return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : `${m}m ${Math.floor(s % 60)}s`; +} + +function ago(s) { + return s == null ? "-" : s < 60 ? `${Math.round(s)} s ago` : `${duration(s)} ago`; +} + +function Rtts({ rtts, names }) { + const entries = Object.entries(rtts || {}); + if (!entries.length) return "no neighbours yet"; + return entries.map(([id, ms]) => ( +
+ {names[id] || id}: {ms == null ? no answer : `${ms} ms`} +
+ )); +} + +export default function Nodes({ snapshot }) { + const proofs = snapshot?.proofs || []; + const names = Object.fromEntries((snapshot?.nodes || []).map((n) => [n.node_id, n.display_name])); + return ( +
+
+ +

+ Every node sends the observer a status message every 10 seconds, signed with the Ed25519 key that signs its + training updates. The observer checks the signature against the key the directory has on record for that + hospital and refuses (and audits) anything else. Host facts come from the install script on that computer; + round-trip times and uptime are measured live. +

+
+ + + + + + + + + + + + + + + + {proofs.map((p) => { + const m = p.message || {}; + const host = m.host || {}; + const badge = BADGE[p.status]; + return ( + + + + + + + + + + + + ); + })} + {proofs.length === 0 && ( + + + + )} + +
HospitalSignatureComputerOperating systemUptimeTailscale deviceRound trip to neighboursData rowsLast signed message
+ {names[p.node_id] || p.display_name} +
{p.node_id}
+
+ {badge.text} + {p.key_fingerprint &&
key {p.key_fingerprint}
} + {p.rejection &&
{p.rejection}
} +
{host.hostname || "-"}{host.os || "-"}{duration(host.uptime_s)}{host.tailscale_device || "-"} + + {m.data_rows ?? "-"}{ago(p.seconds_since_proof)}
+ No signed status message yet. A node sends its first one about 10 seconds after it starts. +
+
+
+
+ ); +} diff --git a/dashboard/src/styles.css b/dashboard/src/styles.css index 9ae8669..083fccb 100644 --- a/dashboard/src/styles.css +++ b/dashboard/src/styles.css @@ -660,6 +660,14 @@ a { background: var(--color-mint-sage); } +.status-pill--orange { + background: var(--color-burnt-orange); +} + +.status-pill--grey { + background: var(--color-soft-shadow); +} + /* ---- Consensus panel ------------------------------------------------------- */ .consensus { diff --git a/node/db.py b/node/db.py index e8cd807..693c9b5 100644 --- a/node/db.py +++ b/node/db.py @@ -117,6 +117,18 @@ enrolled BOOLEAN NOT NULL DEFAULT false, updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); +-- written by the observer only: each hospital's latest proof-of-origin message (node/proof.py), signature checked +CREATE TABLE IF NOT EXISTS node_proofs ( + node_id TEXT PRIMARY KEY, + received_at TIMESTAMPTZ, + sent_at DOUBLE PRECISION, + boot_id TEXT, + seq INTEGER, + message JSONB, + key_fingerprint TEXT, + rejected_at TIMESTAMPTZ, + rejection TEXT +); """ SCHEMA_LOCK_KEY = 4242_0001 @@ -271,6 +283,26 @@ def hospital_key(self, *, node_id: str, display_name: str, signing_public_key: s ) + def proof_accepted(self, *, node_id: str, sent_at: float, boot_id: str, seq: int, message: dict, + key_fingerprint: str) -> None: + """The observer verified this hospital's proof-of-origin message (never written through /ingest).""" + self._execute( + """INSERT INTO node_proofs (node_id, received_at, sent_at, boot_id, seq, message, key_fingerprint) + VALUES (%s, now(), %s, %s, %s, %s::jsonb, %s) + ON CONFLICT (node_id) DO UPDATE SET received_at = now(), sent_at = EXCLUDED.sent_at, + boot_id = EXCLUDED.boot_id, seq = EXCLUDED.seq, message = EXCLUDED.message, + key_fingerprint = EXCLUDED.key_fingerprint""", + (node_id, sent_at, boot_id, seq, json.dumps(message), key_fingerprint), + ) + + def proof_rejected(self, *, node_id: str, reason: str) -> None: + self._execute( + """INSERT INTO node_proofs (node_id, rejected_at, rejection) VALUES (%s, now(), %s) + ON CONFLICT (node_id) DO UPDATE SET rejected_at = now(), rejection = EXCLUDED.rejection""", + (node_id, reason), + ) + + class NullDatabase(Database): """Used when no DATABASE_URL is set (unit tests, local experiments).""" diff --git a/node/enroll.py b/node/enroll.py index 3f09b2c..77770b8 100644 --- a/node/enroll.py +++ b/node/enroll.py @@ -232,8 +232,19 @@ def _write(path: Path, data: str | bytes, private: bool = False) -> None: pass +def host_env(facts: dict[str, str | None]) -> list[str]: + """The host's facts for the proof-of-origin messages (node/proof.py), as the install script read them.""" + from .proof import HOST_ENV + + clean = {k: " ".join(str(v).split()) for k, v in facts.items() if v} + if not clean: + return [] + return ["# This computer, as the install script read it (node/proof.py signs and sends these to the hub)", + *(f"{HOST_ENV[k]}={v}" for k, v in clean.items())] + + def kit_env(answer: dict, hub_host: str, hub_port: int, advertise: str, port: int, image_version: str, - image: str | None) -> str: + image: str | None, facts: dict[str, str | None] | None = None) -> str: host = f"[{hub_host}]" if ":" in hub_host else hub_host lines = [ f"# MedChain hospital node settings for {answer['display_name']} ({answer['node_id']}), written by", @@ -252,6 +263,7 @@ def kit_env(answer: dict, hub_host: str, hub_port: int, advertise: str, port: in "ROUND_TIMEOUT_S=15", "HTTP_CONNECT_TIMEOUT_S=5", "HTTP_READ_TIMEOUT_S=10", + *host_env(facts or {}), ] return "\n".join(lines) + "\n" @@ -319,6 +331,10 @@ def main(argv: list[str] | None = None) -> int: ap.add_argument("--image-version", default=os.environ.get("IMAGE_VERSION") or IMAGE_VERSION) ap.add_argument("--image", default=os.environ.get("MEDCHAIN_IMAGE") or None, help="the node image repository") ap.add_argument("--force", action="store_true", help="enroll again even if --out already holds an enrolled kit") + ap.add_argument("--host-name", help="this computer's name (for the dashboard's proof of origin)") + ap.add_argument("--host-os", help="its operating system and version") + ap.add_argument("--host-booted-at", help="when it booted, Unix seconds (its uptime is counted from this)") + ap.add_argument("--tailscale-device", help="its Tailscale device name") args = ap.parse_args(argv) existing = enrolled_id(args.out) @@ -339,8 +355,10 @@ def main(argv: list[str] | None = None) -> int: except (EnrollError, ValueError) as exc: print(f"enroll: {exc}", file=sys.stderr) return 2 + host = {"hostname": args.host_name, "os": args.host_os, "booted_at": args.host_booted_at, + "tailscale_device": args.tailscale_device} write_kit(args.out, answer, keys, kit_env(answer, hub_host, hub_port, advertise, args.port, args.image_version, - args.image)) + args.image, host)) print(f"enrolled {answer['display_name']} as {answer['node_id']} (data: {answer['data_slice']['name']}); " f"kit written to {args.out}") return 0 diff --git a/node/main.py b/node/main.py index ffeebfd..cce9f08 100644 --- a/node/main.py +++ b/node/main.py @@ -42,7 +42,7 @@ from fastapi import Depends, FastAPI, HTTPException, Request, Response from pydantic import BaseModel, Field -from . import discovery, pinning, rejoin, security, wire +from . import discovery, pinning, proof, rejoin, security, wire from .assess.routes import Assessor, build_router as build_assess_router from .config import NodeConfig, load_config from .db import Database, NullDatabase @@ -55,6 +55,8 @@ log = logging.getLogger("medchain.node") +PROOF_INTERVAL_S = float(os.environ.get("PROOF_INTERVAL_S", "10")) + class StartRequest(BaseModel): run_id: str | None = None @@ -112,6 +114,8 @@ def create_app(cfg: NodeConfig | None = None, database: Database | None = None) def expected_pins(host: str, port: int) -> list[pinning.Pin]: """Whose key may answer at host:port: the directory (pinned by my kit) or a member of my signed chain.""" parties = [("directory", "the directory", cfg.directory.url, directory_pin)] if cfg.directory else [] + if cfg.observer and cfg.tls: # the proof-of-origin messages go to the observer on this client + parties.append(("observer", "the observer", cfg.observer.url, cfg.observer.tls_pin)) if "runner" in state: parties += state["runner"].known_parties() return pinning.pins_at(host, port, parties) @@ -135,6 +139,19 @@ async def heartbeat_loop(runner: Runner) -> None: db.heartbeat(cfg.node_id, runner.run_id, runner.state, runner.current_round) await asyncio.sleep(cfg.timing.heartbeat_interval_s) + async def proof_loop(runner: Runner, prover: proof.Prover) -> None: + """Signed facts about this machine, for the dashboard (node/proof.py). Never waited for by training.""" + while True: + try: + body, headers = prover.message(await proof.neighbour_rtts(runner.client, runner.neighbours)) + resp = await runner.client.post(f"{cfg.observer.url}/proof", content=body, + headers={**headers, "Authorization": f"Bearer {cfg.observer.token}"}) + if resp.status_code != 200: + log.warning("observer refused my proof-of-origin message: %s %s", resp.status_code, resp.text[:200]) + except httpx.HTTPError as exc: + log.debug("proof-of-origin message not delivered: %s", exc) + await asyncio.sleep(PROOF_INTERVAL_S) + def take_membership(doc: Membership, via: str) -> str: """Verify the directory's signature, then apply or schedule the document.""" if directory_key is None: @@ -228,6 +245,9 @@ async def lifespan(app: FastAPI): "directory": cfg.directory.url if cfg.directory else None, "tls": bool(cfg.tls), "signed_updates": signing_key is not None}) hb = asyncio.create_task(heartbeat_loop(runner)) + if cfg.observer and signing_key is not None: + state["proof"] = asyncio.create_task(proof_loop(runner, proof.Prover( + cfg.node_id, signing_key, trainer.n_patients, cfg.image_version))) if cfg.directory: state["rejoin"] = asyncio.create_task(register_with_directory(runner)) elif cfg.is_admm: # a checkpoint on the volume means we were killed mid-run: rejoin it @@ -238,7 +258,7 @@ async def lifespan(app: FastAPI): yield finally: hb.cancel() - for t in (state.get("rejoin"), state.get("fetch")): + for t in (state.get("rejoin"), state.get("fetch"), state.get("proof")): if t: t.cancel() await runner.shutdown() diff --git a/node/proof.py b/node/proof.py new file mode 100644 index 0000000..23747ff --- /dev/null +++ b/node/proof.py @@ -0,0 +1,105 @@ +"""Proof of origin: a signed status message, every few seconds, about the machine this node really runs on. + +The dashboard's Start/Pause buttons prove nothing about where a hospital is. So each node +periodically POSTs the observer (POST /proof) a small JSON document, signed with the same +Ed25519 key that signs its training updates (node/security.py, context "proof"): + + host hostname, OS and version, uptime, Tailscale device name. In Docker these + come from the install script, which reads them on the host and puts them in + the kit's .env (MEDCHAIN_HOST_*); uptime is counted from the host's boot time. + Without them (make up, a kit), the container's own values, labelled as such. + container the kernel and uptime the node itself sees + neighbours the round-trip time of a GET /health to each chain neighbour, measured now + over the same pinned TLS connections training uses + data_rows how many rows its local data slice holds (the count, never the data) + +plus its node id, the time, a per-start boot id and a sequence number (so an old message +cannot be replayed). The observer checks the signature against the key the directory has +on record for that hospital and audits any message that fails (observer/app.py). +""" + +from __future__ import annotations + +import asyncio +import json +import os +import platform +import secrets +import time + +import httpx + +from . import security, wire + +HOST_ENV = {"hostname": "MEDCHAIN_HOST_NAME", "os": "MEDCHAIN_HOST_OS", "booted_at": "MEDCHAIN_HOST_BOOTED_AT", + "tailscale_device": "MEDCHAIN_TAILSCALE_DEVICE"} + + +def _uptime() -> float | None: + try: + with open("/proc/uptime") as f: + return float(f.read().split()[0]) + except (OSError, ValueError, IndexError): + return None + + +def host_facts(now: float | None = None) -> dict: + """The machine's facts: from the install script when it set them, else what this process sees.""" + now = time.time() if now is None else now + env = {k: os.environ.get(v, "").strip() for k, v in HOST_ENV.items()} + try: + booted = float(env["booted_at"]) if env["booted_at"] else None + except ValueError: + booted = None + if env["hostname"]: + return {"source": "host, read by the install script", "hostname": env["hostname"], "os": env["os"] or None, + "uptime_s": round(now - booted) if booted else None, "tailscale_device": env["tailscale_device"] or None} + return {"source": "this process (no install script facts)", "hostname": platform.node(), + "os": f"{platform.system()} {platform.release()}", "uptime_s": _uptime(), + "tailscale_device": env["tailscale_device"] or None} + + +async def neighbour_rtts(client: httpx.AsyncClient, neighbours) -> dict[str, float | None]: + """Milliseconds for a GET /health to each neighbour (None when it does not answer).""" + + async def one(n): + t0 = time.perf_counter() + try: + r = await client.get(f"{n.url}/health", timeout=3) + return n.id, round((time.perf_counter() - t0) * 1000, 1) if r.status_code == 200 else None + except httpx.HTTPError: + return n.id, None + + return dict(await asyncio.gather(*(one(n) for n in neighbours))) + + +class Prover: + """Builds and signs this node's proof messages (one boot id per start, a rising sequence number).""" + + def __init__(self, node_id: str, signing_key, data_rows: int, image_version: str): + self.node_id, self.key, self.data_rows, self.image_version = node_id, signing_key, data_rows, image_version + self.boot_id = secrets.token_hex(8) + self.started = time.time() + self.seq = 0 + + def message(self, rtts: dict[str, float | None]) -> tuple[bytes, dict[str, str]]: + self.seq += 1 + now = time.time() + body = json.dumps({ + "node_id": self.node_id, "boot_id": self.boot_id, "seq": self.seq, "sent_at": now, + "host": host_facts(now), + "container": {"kernel": f"{platform.system()} {platform.release()}", "uptime_s": round(now - self.started)}, + "neighbours_rtt_ms": rtts, "data_rows": self.data_rows, "image_version": self.image_version, + }, sort_keys=True).encode() + headers = {wire.H_SENDER: self.node_id, "Content-Type": "application/json"} + headers[wire.H_SIGNATURE] = security.sign(self.key, body, headers, "proof") + return body, headers + + +def verify(public_key_b64: str, body: bytes, headers) -> dict: + """The verified message (raises security.SignatureError or ValueError).""" + security.verify(security.parse_public_key(public_key_b64), headers.get(wire.H_SIGNATURE), body, headers, "proof") + msg = json.loads(body) + if not isinstance(msg, dict) or msg.get("node_id") != headers.get(wire.H_SENDER): + raise ValueError("the message is not about the hospital that signed it") + return msg diff --git a/observer/app.py b/observer/app.py index d2f1344..a59364d 100644 --- a/observer/app.py +++ b/observer/app.py @@ -6,6 +6,9 @@ writes as that hospital (directory/enroll.py). Each item is one Database write (node/db.py: heartbeat, audit, record_metrics, ...), applied with the same methods, so the Postgres schema and the dashboard are unchanged. + POST /proof a node's signed proof-of-origin message (node/proof.py): accepted only if its + Ed25519 signature verifies against the key the directory has on record for that + hospital (hospital_keys); anything else is refused and written to the audit log GET /health liveness Nodes on other machines need only this service's URL and token, never Postgres @@ -32,6 +35,7 @@ from pydantic import AliasChoices, BaseModel, Field from pydantic_settings import BaseSettings, SettingsConfigDict +from node import proof, security, wire from node.db import Database, NullDatabase from node.writer import HUB_ONLY, WRITE_METHODS @@ -76,6 +80,8 @@ class Batch(BaseModel): OWNER_CACHE_S = 30.0 +PROOF_MAX_BYTES = 16 * 1024 +PROOF_MAX_SKEW_S = 600 # a message older (or newer) than this is refused, whatever the laptops' clocks say def own_writes(items: list[Item], node_id: str) -> bool: @@ -111,7 +117,7 @@ def token_owner(digest: str) -> str | None: owners[digest] = (time.monotonic(), rows[0][0] if rows else None) return owners[digest][1] - async def authorize(request: Request, batch: Batch) -> None: + async def authorize(request: Request, node_id: str, items: list[Item] = ()) -> None: auth = request.headers.get("Authorization", "") given = auth[7:].encode() if auth.startswith("Bearer ") else b"" if given and hmac.compare_digest(given, token): @@ -119,9 +125,29 @@ async def authorize(request: Request, batch: Batch) -> None: owner = await asyncio.to_thread(token_owner, hashlib.sha256(given).hexdigest()) if given else None if owner is None: raise HTTPException(401, detail="a valid observer token is required") - if owner != batch.node_id or not own_writes(batch.items, owner): + if owner != node_id or not own_writes(items, owner): raise HTTPException(403, detail=f"this token belongs to {owner}: it writes only as {owner}") + last_seen: dict[str, tuple[str, int]] = {} # node -> (boot id, seq) of its last accepted proof + + def check_proof(sender: str, body: bytes, headers) -> tuple[dict, str]: + """The verified message and the fingerprint of the key that signed it (raises ValueError with why not).""" + rows = db.fetch("SELECT signing_public_key FROM hospital_keys WHERE node_id = %s", (sender,)) + if not rows or not rows[0][0]: + raise ValueError(f"no signing key is on record for {sender} (it has not registered with the directory)") + try: + msg = proof.verify(rows[0][0], body, headers) + except security.SignatureError as exc: + raise ValueError(f"signature: {exc} with {sender}'s key on record") from exc + if abs(time.time() - float(msg.get("sent_at", 0))) > PROOF_MAX_SKEW_S: + raise ValueError("the message is more than 10 minutes old (or from the future)") + boot, seq = str(msg.get("boot_id")), int(msg.get("seq", 0)) + prev = last_seen.get(sender) + if prev and prev[0] == boot and seq <= prev[1]: + raise ValueError(f"replayed message (sequence {seq}, already had {prev[1]})") + last_seen[sender] = (boot, seq) + return msg, hashlib.sha256(rows[0][0].encode()).hexdigest()[:16] + def apply(batch: Batch) -> tuple[int, list[str]]: applied, rejected = 0, [] for i, item in enumerate(batch.items): @@ -141,11 +167,40 @@ async def health(): @app.post("/ingest") async def ingest(batch: Batch, request: Request): - await authorize(request, batch) + await authorize(request, batch.node_id, batch.items) async with write_lock: # one batch at a time, in arrival order applied, rejected = await asyncio.to_thread(apply, batch) if rejected: log.warning("batch from %s: %d rejected (%s)", batch.node_id, len(rejected), "; ".join(rejected[:3])) return {"applied": applied, "rejected": rejected} + @app.post("/proof") + async def proof_of_origin(request: Request): + sender = request.headers.get(wire.H_SENDER, "") + body = await request.body() + if not sender or len(body) > PROOF_MAX_BYTES: + raise HTTPException(400, detail="a proof needs an X-MedChain-Sender header and at most 16 KiB") + + def audit_refusal(reason: str) -> None: + log.warning("proof from %s rejected: %s", sender, reason) + db.audit(node_id=sender, event="proof_rejected", sender=sender, + detail={"reason": reason, "client": request.client.host if request.client else None}) + if db.fetch("SELECT 1 FROM hospital_keys WHERE node_id = %s", (sender,)): + db.proof_rejected(node_id=sender, reason=reason) + + try: + await authorize(request, sender) + msg, fingerprint = await asyncio.to_thread(check_proof, sender, body, request.headers) + except HTTPException as exc: + await asyncio.to_thread(audit_refusal, f"token: {exc.detail}") + raise + except (ValueError, TypeError) as exc: + await asyncio.to_thread(audit_refusal, str(exc)) + raise HTTPException(403, detail=str(exc)) + async with write_lock: + await asyncio.to_thread(lambda: db.proof_accepted( + node_id=sender, sent_at=float(msg["sent_at"]), boot_id=str(msg["boot_id"]), seq=int(msg["seq"]), + message=msg, key_fingerprint=fingerprint)) + return {"verified": True, "node_id": sender, "key_fingerprint": fingerprint} + return app diff --git a/tests/unit/test_enroll.py b/tests/unit/test_enroll.py index 4bf8323..cab804b 100644 --- a/tests/unit/test_enroll.py +++ b/tests/unit/test_enroll.py @@ -119,7 +119,11 @@ def test_a_hospital_enrolls_with_a_join_code_and_joins_the_chain(hub, tmp_path, (port,) = free_ports(1) kit = tmp_path / "kit" assert enroll.main(["--hub", hub.hub, "--name", " St Mary's Leeds ", "--code", code, "--advertise", "127.0.0.1", - "--port", str(port), "--out", str(kit)]) == 0 + "--port", str(port), "--out", str(kit), "--host-name", "ALEX-LAPTOP", + "--host-os", "Microsoft Windows 11 Home 10.0.22631", "--tailscale-device", "alex-laptop"]) == 0 + env = (kit / ".env").read_text() + assert "MEDCHAIN_HOST_NAME=ALEX-LAPTOP\n" in env and "MEDCHAIN_HOST_OS=Microsoft Windows 11 Home 10.0.22631\n" in env + assert "MEDCHAIN_HOST_BOOTED_AT" not in env hub.nodes.append(NodeServer(hub.cfgs["hospital-a"]).start()) # a kit hospital, before the kit's env is set node_id = kit_env(monkeypatch, kit) diff --git a/tests/unit/test_observer.py b/tests/unit/test_observer.py index 081d68f..8708ccc 100644 --- a/tests/unit/test_observer.py +++ b/tests/unit/test_observer.py @@ -104,12 +104,24 @@ def test_a_node_pushes_its_telemetry_to_the_observer_over_pinned_tls(tmp_path): class KeysDatabase(RecordingDatabase): """hospital_keys as the directory wrote them: one enrolled hospital with its own token.""" - def __init__(self, owners: dict[str, str]): + def __init__(self, owners: dict[str, str], keys: dict[str, str] | None = None): super().__init__() - self.owners = owners + self.owners, self.keys = owners, keys or {} + self.proofs: list[dict] = [] + self.rejections: list[dict] = [] def fetch(self, sql, params=None): - return [(self.owners[params[0]],)] if "hospital_keys" in sql and params[0] in self.owners else [] + if "observer_token_sha256" in sql: + return [(self.owners[params[0]],)] if params[0] in self.owners else [] + if "signing_public_key" in sql: + return [(self.keys[params[0]],)] if params[0] in self.keys else [] + return [(1,)] if params[0] in self.keys else [] + + def proof_accepted(self, **kw): + self.proofs.append(kw) + + def proof_rejected(self, **kw): + self.rejections.append(kw) def heartbeat(self, node_id, run_id, run_state, current_round): self.audits.append({"event": "heartbeat", "node_id": node_id}) @@ -147,3 +159,90 @@ def post(token, node_id, items): assert post(TOKEN, "hospital-a", [keys]).json()["applied"] == 0 finally: observer.stop(abrupt=True) + + +def test_proof_of_origin_is_accepted_only_with_the_hospitals_key_on_record(tmp_path): + import json + + from chain_harness import free_ports, issue_pki + from node import proof, security, wire + + pki_dir = issue_pki(tmp_path, ["hospital-a", "hospital-b"]) + pki.ensure_identity(pki_dir, "observer", ["127.0.0.1", "localhost"], credential=False) + key_a = security.load_signing_key(pki_dir / "hospital-a" / "signing.key") + key_b = security.load_signing_key(pki_dir / "hospital-b" / "signing.key") + db = KeysDatabase({}, {"hospital-a": security.public_key_b64(key_a)}) + (port,) = free_ports(1) + observer = ObserverServer(port, pki_dir, db).start() + try: + url, ca = f"{observer.url}/proof", str(pki_dir / "ca.crt") + auth = {"Authorization": f"Bearer {TOKEN}"} + + def post(body, headers): + return httpx.post(url, content=body, headers={**headers, **auth}, verify=ca, timeout=5) + + prover = proof.Prover("hospital-a", key_a, 303, "v1.1.0") + body, headers = prover.message({"hospital-b": 4.2}) + r = post(body, headers) + assert r.status_code == 200 and r.json()["verified"], r.text + msg = db.proofs[-1]["message"] + assert msg["data_rows"] == 303 and msg["neighbours_rtt_ms"] == {"hospital-b": 4.2} and msg["host"]["hostname"] + assert post(body, headers).status_code == 403, "the same message twice is a replay" + # a changed fact, a message signed by another hospital's key, a hospital with no key on record + body, headers = prover.message({}) + assert post(body.replace(b'"data_rows": 303', b'"data_rows": 999'), headers).status_code == 403 + forged, fh = proof.Prover("hospital-a", key_b, 1, "x").message({}) + assert post(forged, fh).status_code == 403 + unknown, uh = proof.Prover("hospital-b", key_b, 1, "x").message({}) + assert post(unknown, uh).status_code == 403 + reasons = [a["detail"]["reason"] for a in db.events("proof_rejected")] + assert len(reasons) == 4 and "replayed" in reasons[0] and "signature" in reasons[1] and "signature" in reasons[2] + assert "no signing key is on record for hospital-b" in reasons[3] + assert [r["node_id"] for r in db.rejections] == ["hospital-a"] * 3, "shown on the dashboard for a known hospital" + stale = json.loads(prover.message({})[0]) + stale["sent_at"] -= 3600 + sb = json.dumps(stale).encode() + sh = {wire.H_SENDER: "hospital-a"} + sh[wire.H_SIGNATURE] = security.sign(key_a, sb, sh, "proof") + assert "10 minutes" in post(sb, sh).json()["detail"] + finally: + observer.stop(abrupt=True) + + +def test_a_node_sends_signed_proof_of_origin_with_its_host_facts(tmp_path, monkeypatch): + import node.main as node_main + from chain_harness import free_ports + from node import security + + monkeypatch.setattr(node_main, "PROOF_INTERVAL_S", 0.2) + monkeypatch.setenv("MEDCHAIN_HOST_NAME", "ALEX-LAPTOP") + monkeypatch.setenv("MEDCHAIN_HOST_OS", "Microsoft Windows 11 Home 10.0.22631") + monkeypatch.setenv("MEDCHAIN_HOST_BOOTED_AT", str(time.time() - 7200)) + monkeypatch.setenv("MEDCHAIN_TAILSCALE_DEVICE", "alex-laptop.tail1234.ts.net") + cfgs = write_configs(tmp_path, ["hospital-a", "hospital-b"], engine="gossip", secure=True) + pki_dir = tmp_path / "pki" + pki.ensure_identity(pki_dir, "observer", ["127.0.0.1", "localhost"], credential=False) + keys = {n: security.public_key_b64(security.load_signing_key(pki_dir / n / "signing.key")) for n in cfgs} + db = KeysDatabase({}, keys) + (port,) = free_ports(1) + observer = ObserverServer(port, pki_dir, db).start() + nodes = [] + try: + for cfg in cfgs.values(): + cfg.write_text(cfg.read_text() + f"observer: {{url: {observer.url}, token: {TOKEN}, " + f"tls_pin: 'file:{pki_dir / 'observer' / 'tls.crt'}'}}\n") + for cfg in cfgs.values(): + n = NodeServer(cfg) + n.app = create_node_app(n.cfg) + n._serve(n.app, n.cfg.port, n.cfg.tls.cert, n.cfg.tls.key, n.cfg.tls.ca) + nodes.append(n.start()) + wait_until(lambda: any(p["node_id"] == "hospital-a" and p["message"]["neighbours_rtt_ms"].get("hospital-b") + for p in db.proofs), 15, "a proof from hospital-a with a measured RTT to hospital-b") + msg = next(p["message"] for p in db.proofs if p["node_id"] == "hospital-a") + assert msg["host"]["hostname"] == "ALEX-LAPTOP" and msg["host"]["tailscale_device"].startswith("alex-laptop") + assert 7190 < msg["host"]["uptime_s"] < 7300 and msg["data_rows"] == 303 + assert not db.events("proof_rejected") + finally: + for n in nodes: + n.stop(abrupt=True) + observer.stop(abrupt=True) From ee713b6510c1f55d02b73a29f1fb951ebbb9e772 Mon Sep 17 00:00:00 2001 From: Denimworld12 <166978100+Denimworld12@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:46:04 +0530 Subject: [PATCH 04/16] feat(dashboard): admin login in front of the whole dashboard, and a join-codes page - One admin account, created on first run (from MEDCHAIN_ADMIN_PASSWORD, or by the first visitor's setup screen while none exists; the table holds at most one), password stored as a bcrypt hash (cost 12). - Sessions: random 32-byte token in an httpOnly SameSite=Strict cookie, only its SHA-256 in Postgres, 12 h, logout deletes it; 5 failed logins lock an address out for 5 minutes; cross-site Origin refused on state-changing requests. - Every /api route (snapshot, Start/Pause, assess relay, admin) and the /ws snapshot stream need the session; the UI shows the login screen first. The existing pages are unchanged; a Log out button and a Join codes page are added. - Join codes page relays to the directory's admin API with the hub admin token (shared hub-secrets volume): create (validity, data slice), shown once; list; revoke; and the hospitals that enrolled. - Integration tests and CI log in (MEDCHAIN_ADMIN_PASSWORD). --- .github/workflows/ci.yml | 3 + README.md | 15 ++- dashboard/package-lock.json | 7 ++ dashboard/package.json | 1 + dashboard/server/admin.js | 32 ++++++ dashboard/server/auth.js | 183 ++++++++++++++++++++++++++++++ dashboard/server/auth.test.js | 39 +++++++ dashboard/server/index.js | 80 ++++++++++++- dashboard/src/App.jsx | 8 +- dashboard/src/auth.js | 56 +++++++++ dashboard/src/main.jsx | 12 +- dashboard/src/pages/JoinCodes.jsx | 161 ++++++++++++++++++++++++++ dashboard/src/pages/Login.jsx | 76 +++++++++++++ dashboard/src/styles.css | 35 ++++++ dashboard/src/useSnapshot.js | 6 + deploy/hub.yml | 6 + docker-compose.yml | 6 + tests/integration/test_stack.py | 69 +++++++++-- 18 files changed, 775 insertions(+), 20 deletions(-) create mode 100644 dashboard/server/admin.js create mode 100644 dashboard/server/auth.js create mode 100644 dashboard/server/auth.test.js create mode 100644 dashboard/src/auth.js create mode 100644 dashboard/src/pages/JoinCodes.jsx create mode 100644 dashboard/src/pages/Login.jsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3a9abd..6eed415 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,6 +70,9 @@ jobs: docker-stack: name: docker build + pytest (live stack, kill, join and leave tests) - engine ${{ matrix.engine }} runs-on: ubuntu-latest + env: + # the dashboard's admin account for this throwaway stack (compose creates it; the tests log in with it) + MEDCHAIN_ADMIN_PASSWORD: ci-dashboard-admin-password strategy: fail-fast: false matrix: diff --git a/README.md b/README.md index 132d4d8..0519154 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,20 @@ curl --cacert .pki/ca.crt https://localhost:8002/metrics ### 2. Open the dashboard -Open in a browser. +Open in a browser and log in. The dashboard has one admin +account and shows nothing, not even the live snapshot, to anyone without its session +(`dashboard/server/auth.js`). The account is created on first run: + +- from `MEDCHAIN_ADMIN_PASSWORD` (user `admin`) if you set it before `make up` / `make hub`; +- otherwise the first person to open the dashboard is asked to create it (pick the + username and a password of at least 10 characters). + +The password is stored as a bcrypt hash. The session is an httpOnly, SameSite=Strict +cookie (12 hours; **LOG OUT** in the top bar ends it), and Postgres keeps only its +SHA-256. Five wrong passwords from one address lock it out for 5 minutes. **JOIN CODES** +(admin) creates and revokes the one-time codes hospitals enroll with (see +[Join with a code instead of a kit](#join-with-a-code-instead-of-a-kit)). **NODES** +shows each hospital's signed proof of origin. - Press **START TRAINING ROUND** in the top bar. The button changes to show `TRAINING: ROUND n OF 400`, and a **PAUSE** button becomes active. diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json index 7027fc6..6df334a 100644 --- a/dashboard/package-lock.json +++ b/dashboard/package-lock.json @@ -8,6 +8,7 @@ "name": "medchain-dashboard", "version": "0.1.0", "dependencies": { + "bcryptjs": "^2.4.3", "pg": "^8.13.1", "ws": "^8.18.0" }, @@ -1893,6 +1894,12 @@ "node": ">=6.0.0" } }, + "node_modules/bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==", + "license": "MIT" + }, "node_modules/brace-expansion": { "version": "1.1.21", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", diff --git a/dashboard/package.json b/dashboard/package.json index 7356fcd..7486c42 100644 --- a/dashboard/package.json +++ b/dashboard/package.json @@ -12,6 +12,7 @@ "test": "node --test server/*.test.js" }, "dependencies": { + "bcryptjs": "^2.4.3", "pg": "^8.13.1", "ws": "^8.18.0" }, diff --git a/dashboard/server/admin.js b/dashboard/server/admin.js new file mode 100644 index 0000000..777eba3 --- /dev/null +++ b/dashboard/server/admin.js @@ -0,0 +1,32 @@ +// The admin page's join codes: relayed to the directory's admin API (directory/app.py, /admin/join-codes) +// with the hub's admin token, which the directory writes on first start to a volume the dashboard reads. +// The full code exists only in the answer to "create"; the directory keeps its hash. + +import fs from "node:fs"; + +const DIRECTORY = (process.env.DIRECTORY_ADMIN_URL || "https://directory:8100").replace(/\/$/, ""); +const TOKEN_FILE = process.env.DIRECTORY_ADMIN_TOKEN_FILE || "/hub/admin_token"; + +function token() { + try { + return fs.readFileSync(TOKEN_FILE, "utf8").trim(); + } catch { + return ""; + } +} + +export async function directoryAdmin(method, path, body) { + const t = token(); + if (!t) return { status: 503, body: { detail: `No hub admin token at ${TOKEN_FILE}: is the directory running?` } }; + try { + const resp = await fetch(`${DIRECTORY}/admin${path}`, { + method, + headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(8000), + }); + return { status: resp.status, body: await resp.json().catch(() => ({})) }; + } catch (err) { + return { status: 502, body: { detail: `The directory is unreachable: ${err.message}` } }; + } +} diff --git a/dashboard/server/auth.js b/dashboard/server/auth.js new file mode 100644 index 0000000..4d02217 --- /dev/null +++ b/dashboard/server/auth.js @@ -0,0 +1,183 @@ +// The dashboard's one admin account and its sessions. Everything except the login screen itself +// (the built UI and /api/auth/*) needs a session: the snapshot WebSocket, Start / Pause, the risk +// assessment relay and the admin pages. +// +// - One admin account, created on first run: from DASHBOARD_ADMIN_PASSWORD if it is set, else by +// whoever opens the dashboard first (the setup screen, offered only while no account exists). +// The password is stored as a bcrypt hash (cost 12), never in the clear. +// - A session is a random 32-byte token in an httpOnly, SameSite=Strict cookie; Postgres keeps only +// its SHA-256 and expiry (SESSION_HOURS, default 12). Logout deletes it. +// - Five failed logins from one address lock that address out for 5 minutes. +// - A state-changing request whose Origin is another site is refused (SameSite already keeps the +// cookie off it; this is the second lock). +// +// These tables are the dashboard's own; it still never writes the training tables. + +import crypto from "node:crypto"; +import bcrypt from "bcryptjs"; + +export const COOKIE = "medchain_session"; +const SESSION_HOURS = Number(process.env.SESSION_HOURS || 12); +const BCRYPT_COST = 12; +export const MIN_PASSWORD = 10; +const LOCKOUT = { failures: 5, windowMs: 5 * 60 * 1000 }; +// compared against for an unknown username, so a wrong name and a wrong password take the same time +const NO_SUCH_USER = bcrypt.hashSync(crypto.randomBytes(16).toString("hex"), BCRYPT_COST); + +const SCHEMA = ` +CREATE TABLE IF NOT EXISTS admin_users ( + username TEXT PRIMARY KEY, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + one_admin BOOLEAN NOT NULL DEFAULT true UNIQUE CHECK (one_admin) -- exactly one account +); +CREATE TABLE IF NOT EXISTS admin_sessions ( + token_sha256 TEXT PRIMARY KEY, + username TEXT NOT NULL REFERENCES admin_users (username) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL +);`; + +const sha256 = (s) => crypto.createHash("sha256").update(s).digest("hex"); + +export function parseCookies(header = "") { + const out = {}; + for (const part of header.split(";")) { + const i = part.indexOf("="); + if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim()); + } + return out; +} + +export function sessionCookie(token, { secure = false, maxAge = SESSION_HOURS * 3600 } = {}) { + return `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${secure ? "; Secure" : ""}`; +} + +// A browser sends Origin on cross-site POSTs; when it is there it must be this dashboard. +export function sameOrigin(req) { + const origin = req.headers.origin; + if (!origin) return true; + try { + return new URL(origin).host === req.headers.host; + } catch { + return false; + } +} + +export function checkNewPassword(username, password) { + if (!/^[A-Za-z0-9._-]{3,40}$/.test(username || "")) return "The username is 3 to 40 letters, digits, dots, dashes or underscores."; + if (typeof password !== "string" || password.length < MIN_PASSWORD) return `The password needs at least ${MIN_PASSWORD} characters.`; + if (password.length > 72) return "The password can be at most 72 characters (bcrypt's limit)."; + return null; +} + +// Failed logins per client address (in memory: a restart forgets them, which is fine for a lockout). +export class Lockout { + constructor({ failures, windowMs } = LOCKOUT, now = () => Date.now()) { + Object.assign(this, { failures, windowMs, now, seen: new Map() }); + } + + locked(who) { + const times = (this.seen.get(who) || []).filter((t) => this.now() - t < this.windowMs); + this.seen.set(who, times); + return times.length >= this.failures; + } + + fail(who) { + this.seen.set(who, [...(this.seen.get(who) || []), this.now()]); + } + + clear(who) { + this.seen.delete(who); + } +} + +export class Auth { + constructor(pool, { adminUser = process.env.DASHBOARD_ADMIN_USER || "admin", + adminPassword = process.env.DASHBOARD_ADMIN_PASSWORD || "" } = {}) { + Object.assign(this, { pool, adminUser, adminPassword, ready: null, lockout: new Lockout() }); + } + + // Create the tables (and the account from DASHBOARD_ADMIN_PASSWORD) once Postgres answers. + async init() { + this.ready ||= (async () => { + await this.pool.query(SCHEMA); + if (this.adminPassword) { + const problem = checkNewPassword(this.adminUser, this.adminPassword); + if (problem) throw new Error(`DASHBOARD_ADMIN_PASSWORD: ${problem}`); + const hash = await bcrypt.hash(this.adminPassword, BCRYPT_COST); + await this.pool.query( + `INSERT INTO admin_users (username, password_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING`, + [this.adminUser, hash], + ); + } + })().catch((err) => { + this.ready = null; // try again on the next request + throw err; + }); + return this.ready; + } + + async setupRequired() { + await this.init(); + const { rows } = await this.pool.query(`SELECT count(*)::int AS n FROM admin_users`); + return rows[0].n === 0; + } + + // First run only: the one account. Refused once any account exists (the table holds at most one). + async setup(username, password) { + await this.init(); + const problem = checkNewPassword(username, password); + if (problem) return { ok: false, status: 400, detail: problem }; + const hash = await bcrypt.hash(password, BCRYPT_COST); + const { rowCount } = await this.pool.query( + `INSERT INTO admin_users (username, password_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING`, + [username, hash], + ); + if (!rowCount) return { ok: false, status: 409, detail: "The admin account already exists: log in instead." }; + return { ok: true, ...(await this.newSession(username)) }; + } + + async login(username, password, who) { + await this.init(); + if (this.lockout.locked(who)) { + return { ok: false, status: 429, detail: "Too many failed logins from here: wait 5 minutes and try again." }; + } + const { rows } = await this.pool.query(`SELECT password_hash FROM admin_users WHERE username = $1`, [username || ""]); + const good = await bcrypt.compare(String(password || ""), rows[0]?.password_hash || NO_SUCH_USER); + if (!rows.length || !good) { + this.lockout.fail(who); + return { ok: false, status: 401, detail: "Wrong username or password." }; + } + this.lockout.clear(who); + return { ok: true, ...(await this.newSession(username)) }; + } + + async newSession(username) { + const token = crypto.randomBytes(32).toString("base64url"); + await this.pool.query( + `INSERT INTO admin_sessions (token_sha256, username, expires_at) + VALUES ($1, $2, now() + make_interval(hours => $3))`, + [sha256(token), username, SESSION_HOURS], + ); + await this.pool.query(`DELETE FROM admin_sessions WHERE expires_at < now()`); + return { token, username }; + } + + // The logged-in username for this request's cookie, or null. + async user(req) { + const token = parseCookies(req.headers.cookie)[COOKIE]; + if (!token) return null; + await this.init(); + const { rows } = await this.pool.query( + `SELECT username FROM admin_sessions WHERE token_sha256 = $1 AND expires_at > now()`, + [sha256(token)], + ); + return rows[0]?.username || null; + } + + async logout(req) { + const token = parseCookies(req.headers.cookie)[COOKIE]; + if (token) await this.pool.query(`DELETE FROM admin_sessions WHERE token_sha256 = $1`, [sha256(token)]); + } +} diff --git a/dashboard/server/auth.test.js b/dashboard/server/auth.test.js new file mode 100644 index 0000000..1ec999b --- /dev/null +++ b/dashboard/server/auth.test.js @@ -0,0 +1,39 @@ +// node --test: the pieces of the admin login that need no database (server/auth.js). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { COOKIE, Lockout, checkNewPassword, parseCookies, sameOrigin, sessionCookie } from "./auth.js"; + +test("the session cookie is httpOnly, SameSite=Strict, and Secure over HTTPS", () => { + const c = sessionCookie("tok", { secure: false, maxAge: 60 }); + assert.match(c, new RegExp(`^${COOKIE}=tok; HttpOnly; SameSite=Strict; Path=/; Max-Age=60$`)); + assert.match(sessionCookie("tok", { secure: true }), /; Secure$/); + assert.equal(parseCookies(`a=1; ${COOKIE}=x%2By; b`)[COOKIE], "x+y"); +}); + +test("a request from another site is refused, one from the dashboard or without Origin is not", () => { + const req = (origin) => ({ headers: { host: "localhost:8080", ...(origin ? { origin } : {}) } }); + assert.ok(sameOrigin(req())); + assert.ok(sameOrigin(req("http://localhost:8080"))); + assert.ok(!sameOrigin(req("http://evil.example"))); + assert.ok(!sameOrigin(req("not a url"))); +}); + +test("five failed logins lock an address out for the window, and only that address", () => { + let now = 0; + const l = new Lockout({ failures: 5, windowMs: 1000 }, () => now); + for (let i = 0; i < 5; i++) { + assert.ok(!l.locked("a")); + l.fail("a"); + } + assert.ok(l.locked("a") && !l.locked("b")); + now = 1001; + assert.ok(!l.locked("a"), "the window passed"); +}); + +test("the admin account needs a sensible username and a 10-72 character password", () => { + assert.equal(checkNewPassword("admin", "correct horse"), null); + assert.match(checkNewPassword("ad", "correct horse"), /username/); + assert.match(checkNewPassword("admin", "short"), /at least 10/); + assert.match(checkNewPassword("admin", "x".repeat(73)), /72/); +}); diff --git a/dashboard/server/index.js b/dashboard/server/index.js index ef5ad39..a18f82d 100644 --- a/dashboard/server/index.js +++ b/dashboard/server/index.js @@ -5,6 +5,9 @@ // the nodes; killing this process does not affect it. It also relays risk // assessment requests to the hospital node the user picks (inference only; the // patient inputs pass straight through and are not stored). +// +// Everything but the login screen needs the admin's session (server/auth.js): the snapshot +// WebSocket, the buttons, the relay and the admin page's join codes (server/admin.js). import http from "node:http"; import fs from "node:fs"; @@ -13,6 +16,8 @@ import { fileURLToPath } from "node:url"; import pg from "pg"; import { WebSocketServer } from "ws"; import { buildSnapshot, latestUpdateId, STALE_AFTER_S, updatesSince } from "./snapshot.js"; +import { Auth, sameOrigin, sessionCookie } from "./auth.js"; +import { directoryAdmin } from "./admin.js"; const PORT = Number(process.env.PORT || 8080); const DIST = process.env.DASHBOARD_DIST || fileURLToPath(new URL("../dist", import.meta.url)); @@ -22,6 +27,8 @@ const SHARED_SECRET = process.env.MEDCHAIN_SHARED_SECRET || ""; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 4 }); pool.on("error", (err) => console.warn("postgres pool error:", err.message)); +const auth = new Auth(pool); +auth.init().catch((err) => console.warn("admin accounts not ready yet:", err.message)); const TYPES = { ".html": "text/html; charset=utf-8", @@ -33,8 +40,8 @@ const TYPES = { ".json": "application/json", }; -function send(res, status, body, type = "application/json") { - res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store" }); +function send(res, status, body, type = "application/json", headers = {}) { + res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store", ...headers }); res.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body)); } @@ -128,9 +135,60 @@ function serveStatic(req, res) { fs.createReadStream(file).pipe(res); } +// /api/auth/*: who is logged in, the first-run setup, login and logout. +async function authRoute(req, res, action) { + const cookie = (token, maxAge) => ({ "Set-Cookie": sessionCookie(token, { secure: !!req.socket.encrypted, maxAge }) }); + if (action === "me" && req.method === "GET") { + const user = await auth.user(req); + return send(res, 200, { authenticated: !!user, username: user, setup_required: !user && (await auth.setupRequired()) }); + } + if (req.method !== "POST") return send(res, 405, { detail: "method not allowed" }); + if (action === "logout") { + await auth.logout(req); + return send(res, 200, { authenticated: false }, "application/json", cookie("", 0)); + } + const body = await readJson(req); + const out = action === "setup" ? await auth.setup(body.username, body.password) + : action === "login" ? await auth.login(body.username, body.password, req.socket.remoteAddress) + : { ok: false, status: 404, detail: "not found" }; + if (!out.ok) return send(res, out.status, { detail: out.detail }); + return send(res, 200, { authenticated: true, username: out.username }, "application/json", cookie(out.token)); +} + +// /api/admin/join-codes...: create, list and revoke join codes (the directory does the work). +async function adminRoute(req, res, url, user) { + if (url.pathname === "/api/admin/join-codes" && req.method === "GET") { + const out = await directoryAdmin("GET", "/join-codes"); + return send(res, out.status, out.body); + } + if (url.pathname === "/api/admin/join-codes" && req.method === "POST") { + const body = await readJson(req); + const ttl = Number.isInteger(body.ttl_minutes) ? body.ttl_minutes : undefined; + const out = await directoryAdmin("POST", "/join-codes", { + created_by: user, ttl_minutes: ttl, data_slice: typeof body.data_slice === "string" && body.data_slice ? body.data_slice : null, + }); + return send(res, out.status, out.body); + } + const r = url.pathname.match(/^\/api\/admin\/join-codes\/([A-Z0-9]{4})\/revoke$/); + if (r && req.method === "POST") { + const out = await directoryAdmin("POST", `/join-codes/${r[1]}/revoke`, { revoked_by: user }); + return send(res, out.status, out.body); + } + return send(res, 404, { detail: "not found" }); +} + const server = http.createServer(async (req, res) => { try { if (req.url === "/healthz") return send(res, 200, { status: "ok" }); + if (req.url.startsWith("/api/") && req.method !== "GET" && !sameOrigin(req)) { + return send(res, 403, { detail: "cross-site request refused" }); + } + const login = req.url.match(/^\/api\/auth\/(me|setup|login|logout)$/); + if (login) return await authRoute(req, res, login[1]); + if (!req.url.startsWith("/api/")) return serveStatic(req, res); + const user = await auth.user(req); + if (!user) return send(res, 401, { detail: "Log in first." }); + if (req.url.startsWith("/api/admin/")) return await adminRoute(req, res, new URL(req.url, "http://x"), user); if (req.url === "/api/snapshot" && req.method === "GET") return send(res, 200, await buildSnapshot(pool)); const m = req.url.match(/^\/api\/round\/(start|pause|resume)$/); if (m && req.method === "POST") { @@ -142,15 +200,27 @@ const server = http.createServer(async (req, res) => { const url = new URL(req.url, "http://x"); const a = url.pathname.match(/^\/api\/assess(\/pdf|\/ecg|\/ecg\/pdf)?$/); if (a && req.method === "POST") return await relayAssess(req, res, a[1] || "", url.searchParams.get("node")); - if (req.url.startsWith("/api/")) return send(res, 404, { detail: "not found" }); - return serveStatic(req, res); + return send(res, 404, { detail: "not found" }); } catch (err) { console.warn("request failed:", err.message); return send(res, 503, { detail: err.message }); } }); -const wss = new WebSocketServer({ server, path: "/ws" }); +// The snapshot stream is for the logged-in admin only: the upgrade is refused without a session. +const wss = new WebSocketServer({ noServer: true }); +server.on("upgrade", async (req, socket, head) => { + try { + if (new URL(req.url, "http://x").pathname !== "/ws" || !sameOrigin(req) || !(await auth.user(req))) { + socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n"); + return; + } + wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req)); + } catch (err) { + console.warn("websocket upgrade failed:", err.message); + socket.destroy(); + } +}); let latest = null; async function tick() { diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index b3c3351..1727a14 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -8,6 +8,7 @@ import Communication from "./pages/Communication.jsx"; import AuditLog from "./pages/AuditLog.jsx"; import Assessment from "./pages/Assessment.jsx"; import Nodes from "./pages/Nodes.jsx"; +import JoinCodes from "./pages/JoinCodes.jsx"; import { control, useSnapshot } from "./useSnapshot.js"; const ROUTES = [ @@ -17,6 +18,7 @@ const ROUTES = [ { hash: "#/nodes", label: "Nodes" }, { hash: "#/audit", label: "Audit log" }, { hash: "#/assessment", label: "Risk assessment" }, + { hash: "#/join-codes", label: "Join codes" }, ]; function useHashRoute() { @@ -81,7 +83,7 @@ function ControlStrip({ snapshot }) { ); } -export default function App() { +export default function App({ username, onLogout }) { const route = useHashRoute(); const { snapshot, connection } = useSnapshot(); @@ -101,6 +103,9 @@ export default function App() { ))} {connection === "live" ? "Live" : connection} +
@@ -117,6 +122,7 @@ export default function App() { {route === "#/nodes" && } {route === "#/audit" && } {route === "#/assessment" && } + {route === "#/join-codes" && }