diff --git a/federation-shared.example.env b/federation-shared.example.env index 44b71ebf1..4f4c66c7a 100644 --- a/federation-shared.example.env +++ b/federation-shared.example.env @@ -3,6 +3,11 @@ # FEDERATION_SYNC_DRF_TOKEN: DRF Token for GET /users/get-federation-sync-api-key/ (required). # FEDERATION_SYNC_SERVER_API_KEY: optional export Api-Key override. When empty, the sync # service mints one at startup via the DRF token and caches it in-process. +# FEDERATION_SYNC_ADMIN_TOKEN: Bearer token for sync /internal/registry/* (gateway staff UI). +# Generated by gateway/scripts/generate-secrets.sh into this file. +# NOT for applicant domain verify — that uses FEDERATION_REGISTRY_CHALLENGE_TOKEN on the +# applicant's sync (.env.peer) or gateway (django.env); see federation/env.peer.example. FEDERATION_SYNC_DRF_TOKEN= FEDERATION_SYNC_SERVER_API_KEY= +FEDERATION_SYNC_ADMIN_TOKEN= diff --git a/federation/.gitignore b/federation/.gitignore index 66e725428..9a245f4ac 100644 --- a/federation/.gitignore +++ b/federation/.gitignore @@ -6,5 +6,14 @@ federation.toml federation.peer.toml site.env +# Registry signing key (flagship sync) — see secrets/registry/README.md +secrets/registry/sign.pem +secrets/registry/*.pem +!secrets/registry/README.md +!secrets/registry/.gitkeep + # Local live-test secrets only (keep README + env.example tracked) scripts/local_e2e/.env +.env.peer +.env.local +peer.env diff --git a/federation/README.md b/federation/README.md index 89aa9d423..805087c3f 100644 --- a/federation/README.md +++ b/federation/README.md @@ -20,7 +20,8 @@ Set `[site].sync_service_url` / `FEDERATION_SYNC_SERVICE_URL` to that public HTT (not `:8001`). Production compose loads sync URL and related vars from gitignored `site.env` (see `site.example.env`). -See also: [scripts/local_e2e/README.md](scripts/local_e2e/README.md), +See also: [docs/federation-registry-deploy.md](docs/federation-registry-deploy.md), +[scripts/local_e2e/README.md](scripts/local_e2e/README.md), [docs/peer-remote-test.md](docs/peer-remote-test.md). --- @@ -95,11 +96,26 @@ SDS_ENV=production just federation-add-peer \ --gateway-api-base https://peer.example.edu/api/v1 ``` -Each gateway serves `GET https:///.well-known/sds-federation.json` (unsigned site identity). -During registry apply, set `FEDERATION_REGISTRY_CHALLENGE_TOKEN` on the applicant gateway so that -document includes `registry_challenge` for mothership verification. +Each site exposes `GET https:///.well-known/sds-federation.json` from **federation +sync** when Traefik routes that path to sync (recommended for production, sync-only peers, +and local lab with `compose.local.yaml`). Set the applicant challenge token on **sync**, +not the gateway django process. -Step-by-step (apply, env token, verify, local HTTPS caveats): +**Registry operator runbook:** [docs/federation-registry-deploy.md](docs/federation-registry-deploy.md) + +**`FEDERATION_REGISTRY_CHALLENGE_TOKEN`** (applicant only — not mothership, not +`federation-shared.env`): + +| Applicant deployment | Env file | After edit | +|---------------------|----------|------------| +| Local flagship / lab sync | `federation/.env.local` or env for `compose.local.yaml` | recreate `sds-federation-local-sync` | +| Sync-only peer (e.g. sds-fed1) | `federation/.env.peer` from `env.peer.example` | `compose.peer.*.yaml` recreate sync | +| Production site sync | `federation/site.env` | production compose recreate sync | + +Use `cp federation/env.peer.example federation/.env.peer`; do **not** use `federation/peer.env` +(compose does not load it). + +Verify UI and troubleshooting: [`gateway/docs/federation-registry-verify.md`](../gateway/docs/federation-registry-verify.md). Optional `--ca-cert-path` (file under `federation/certs/` in the sync container). @@ -145,6 +161,7 @@ docker compose -f compose.local.yaml exec sds-gateway-local-app \ cd ../federation cp federation.example.toml federation.toml # [site] matches gateway +# Flagship registry: cp signing key to secrets/registry/sign.pem (see secrets/registry/README.md) just build && just up curl -s http://localhost:8001/sync/health | jq . ``` @@ -152,6 +169,19 @@ curl -s http://localhost:8001/sync/health | jq . Leave `FEDERATION_SYNC_SERVER_API_KEY` empty in `federation-shared.env` so sync mints the export key. Optional: `FEDERATION_SKIP_SYNC_HEALTH_PROBE=true` until sync is up. +### Flagship registry (sync-owned manifest) + +| Item | Location | +|------|----------| +| Signing key | `federation/secrets/registry/sign.pem` → container `/etc/sds/secrets/registry/sign.pem` | +| Published manifest | Docker volume `sds-federation-*-registry-publish` → `/var/lib/sds/registry-publish` | +| Public key + fingerprint | `federation/certs/sds-registry.pub.pem`; set `FEDERATION_REGISTRY_PUBKEY_FINGERPRINT` in `site.env` or `.env.local` | +| Gateway intake | Apply + **Verify domain** UI (→ sync internal API), staff approve, **Publish registry** | +| Sync internal API | `FEDERATION_SYNC_ADMIN_TOKEN` in `federation-shared.env`; gateway `FEDERATION_SYNC_INTERNAL_URL` | + +Render/onboard with publish block: `FEDERATION_REGISTRY_PUBLISH_ENABLED=true` (see `site.example.env`). +Preflight: `just federation-doctor` or `FEDERATION_DOCTOR_CHECK=registry ./scripts/federation-doctor.sh`. + **Local peer mesh:** ```bash diff --git a/federation/compose.local.yaml b/federation/compose.local.yaml index 0c488d0ee..e17eb6bca 100644 --- a/federation/compose.local.yaml +++ b/federation/compose.local.yaml @@ -16,13 +16,23 @@ services: env_file: - ../gateway/.envs/local/opensearch.env - ../federation-shared.env + # Optional applicant / lab overrides (see env.local.example); gitignored when copied to .env.local + - path: ./.env.local + required: false environment: FEDERATION_CONFIG_PATH: /etc/sds/federation.toml GATEWAY_INTERNAL_BASE_URL: http://sds-gateway-local-app:8000/api/v1 REDIS_URL: redis://sds-gateway-local-redis:6379/0 + # Same interpolation pattern as compose.peer.* — values from shell, project .env, or compose --env-file + FEDERATION_REGISTRY_CHALLENGE_TOKEN: ${FEDERATION_REGISTRY_CHALLENGE_TOKEN:-} + FEDERATION_REGISTRY_WELL_KNOWN_URL: ${FEDERATION_REGISTRY_WELL_KNOWN_URL:-} + FEDERATION_REGISTRY_PUBKEY_FINGERPRINT: ${FEDERATION_REGISTRY_PUBKEY_FINGERPRINT:-} volumes: - ./federation.toml:/etc/sds/federation.toml:ro - ./certs:/etc/sds/certs:ro + - ./secrets/registry:/etc/sds/secrets/registry:ro + - sds-federation-local-registry-publish:/var/lib/sds/registry-publish + - sds-federation-local-registry-cache:/var/lib/sds/registry ports: - "8001:8000" healthcheck: @@ -41,3 +51,7 @@ services: networks: - sds-network-local - sds-gateway-local-opensearch-net + +volumes: + sds-federation-local-registry-publish: + sds-federation-local-registry-cache: diff --git a/federation/compose.peer.local.yaml b/federation/compose.peer.local.yaml index d5d1c2695..0a1cbab45 100644 --- a/federation/compose.peer.local.yaml +++ b/federation/compose.peer.local.yaml @@ -51,8 +51,10 @@ services: OPENSEARCH_VERIFY_CERTS: "false" # No mint: leave FEDERATION_SYNC_* unset FEDERATION_SITE_NAME: peer + FEDERATION_REGISTRY_CHALLENGE_TOKEN: ${FEDERATION_REGISTRY_CHALLENGE_TOKEN:-} volumes: - ./federation.peer.toml:/etc/sds/federation.toml:ro + - ./certs:/etc/sds/certs:ro ports: - "8002:8000" depends_on: diff --git a/federation/compose.peer.remote.yaml b/federation/compose.peer.remote.yaml index 8b577a148..5c9a67338 100644 --- a/federation/compose.peer.remote.yaml +++ b/federation/compose.peer.remote.yaml @@ -63,6 +63,7 @@ services: OPENSEARCH_VERIFY_CERTS: "false" FEDERATION_SITE_NAME: ${PEER_SITE_NAME:-fed1} FEDERATION_BOOTSTRAP_ON_START: ${FEDERATION_BOOTSTRAP_ON_START:-true} + FEDERATION_REGISTRY_CHALLENGE_TOKEN: ${FEDERATION_REGISTRY_CHALLENGE_TOKEN:-} volumes: - ./federation.peer.toml:/etc/sds/federation.toml:ro - ./certs:/etc/sds/certs:ro diff --git a/federation/compose.production.yaml b/federation/compose.production.yaml index e3a695085..c98fc6f1d 100644 --- a/federation/compose.production.yaml +++ b/federation/compose.production.yaml @@ -22,8 +22,11 @@ services: volumes: - ./federation.toml:/etc/sds/federation.toml:ro - ./certs:/etc/sds/certs:ro + - ./secrets/registry:/etc/sds/secrets/registry:ro + - sds-federation-prod-registry-publish:/var/lib/sds/registry-publish + - sds-federation-prod-registry-cache:/var/lib/sds/registry ports: - - "8001:8000" + - "127.0.0.1:8001:8000" healthcheck: test: [ @@ -40,3 +43,7 @@ services: networks: - sds-network-prod - sds-gateway-prod-opensearch-net + +volumes: + sds-federation-prod-registry-publish: + sds-federation-prod-registry-cache: diff --git a/federation/docs/federation-registry-deploy.md b/federation/docs/federation-registry-deploy.md new file mode 100644 index 000000000..c8eb65be4 --- /dev/null +++ b/federation/docs/federation-registry-deploy.md @@ -0,0 +1,239 @@ +# Federation registry deploy (operator runbook) + +End-to-end guide: a new peer applies on the **mothership gateway**, proves domain control, +staff approve and publish a **signed registry manifest** on **flagship sync**, and every +member site **polls** the manifest to federate automatically. + +--- + +## Architecture (one page) + +```text +Applicant site Mothership (e.g. sds.crc.nd.edu) +-------------- --------------------------------- +sync serves gateway: intake UI + RegistryApplication DB + GET /.well-known/sds-federation.json staff approve / Publish registry + (env FEDERATION_REGISTRY_CHALLENGE_TOKEN) | + ^ v + | flagship sync: + | POST /internal/registry/verify (fetch applicant) + | POST /internal/registry/publish (sign manifest) + +-- HTTPS well-known ------------- GET /.well-known/sds-registry/sites.json(.sig) + +Member sites (existing + new peer): [registry].url → poll manifest → merge peers → bootstrap +``` + +| Component | Owns | +|-----------|------| +| **Gateway** | Applications, challenges (hash only), staff UI, email to staff, HTTP client to sync | +| **Flagship sync** | Verify fetch, Ed25519 sign, manifest files, public well-known + registry URLs | +| **Applicant sync** | Site identity well-known + challenge token env | +| **All member sync** | Poll registry, trust signature, add peers, site-hello + list backfill | + +Internal API: `POST /internal/registry/*` on sync (Docker network + `FEDERATION_SYNC_ADMIN_TOKEN`). +Traefik must **not** route `/internal` on the public hostname. + +--- + +## Roles + +| Role | You are… | Main actions | +|------|-----------|----------------| +| **Flagship operator** | Host `FLAGSHIP_GATEWAY_HOST` (default `sds.crc.nd.edu`) | One-time signing key, compose, Traefik, intake env | +| **Applicant operator** | New peer joining the mesh | Apply, set challenge on **your** sync, verify | +| **Flagship staff** | `is_staff` on mothership gateway | Approve, **Publish registry** | +| **Member site** | Already federating | Usually nothing (poll timer); optional `[registry]` bootstrap | + +--- + +## Flagship first-time setup + +Prerequisites: Traefik, gateway, federation sync on the mothership host (see +[federation/README.md](../README.md) production start order). + +### 1. Registry intake (gateway) + +In `gateway/.envs//django.env` (see `gateway/.envs/example/django.env`): + ++ `SDS_SITE_FQDN` = `FLAGSHIP_GATEWAY_HOST` (e.g. `sds.crc.nd.edu`) ++ `FEDERATION_REGISTRY_INTAKE_ENABLED=true` ++ `FEDERATION_SYNC_INTERNAL_URL` — Docker DNS to flagship sync, e.g. `http://sds-federation-prod-sync:8000` ++ `FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS` — comma-separated staff inboxes (optional; else staff users / `ADMINS`) + +`FEDERATION_SYNC_ADMIN_TOKEN` lives in repo-root **`federation-shared.env`** (loaded by gateway + sync compose). + +### 2. Publish on sync (flagship only) + +| Step | Action | +|------|--------| +| Signing key | `federation/secrets/registry/sign.pem` → mount read-only (see [secrets/registry/README.md](../secrets/registry/README.md)) | +| Config | `[registry.publish] enabled = true` in `federation.toml` / `FEDERATION_REGISTRY_PUBLISH_ENABLED=true` in `site.env` | +| Volume | Named volume for `manifest_dir` (e.g. `sds-federation-prod-registry-publish`) | +| Public key | `federation/certs/sds-registry.pub.pem` + `FEDERATION_REGISTRY_PUBKEY_FINGERPRINT` on sync | +| Traefik | Route flagship host `/.well-known/sds-federation.json` and `/.well-known/sds-registry/*` → sync (see `network/traefik/conf.d/00-federation-sync.toml`) | + +Generate keys (from `federation/`): + +```bash +uv run sds-federation-registry keygen --out-dir secrets/registry +# Move/sign paths per secrets/registry/README.md; publish .pub.pem to certs/ +uv run sds-federation-registry fingerprint --public-key-path certs/sds-registry.pub.pem +``` + +### 3. Preflight + +```bash +cd federation +just federation-doctor +# or: FEDERATION_DOCTOR_CHECK=registry ./scripts/federation-doctor.sh +``` + +Doctor checks: signing key readable, well-known 200, `/internal` not exposed on public host, fingerprint match. + +--- + +## Applicant onboarding (manual steps) + +These steps **require human action**; automation cannot replace them today. + +### Checklist + ++ [ ] Site is on the public internet with **HTTPS** on the application FQDN ++ [ ] Federation sync (or Traefik→sync) serves `GET https:///.well-known/sds-federation.json` ++ [ ] `[site].fqdn` / `SDS_SITE_FQDN` on applicant sync **equals** the FQDN you will apply with + +### 1. Apply (gateway UI) + +1. Sign in to mothership gateway → **`/users/federation/registry/`** → **New application** +2. Enter **FQDN**, display name, proposed site id +3. Copy the **verification token** (shown **once** in the modal) + +### 2. Publish challenge (applicant sync env) + +Set on the **applicant** sync process only (never mothership `django.env` or `federation-shared.env`): + +```bash +FEDERATION_REGISTRY_CHALLENGE_TOKEN= +``` + +Helper (writes env + prints recreate command): + +```bash +cd federation +chmod +x scripts/set-registry-challenge.sh +./scripts/set-registry-challenge.sh --token "" --peer +# or: --env-file .env.local | --site-env +``` + +| Deployment | Env file | Recreate | +|------------|----------|----------| +| Local lab sync | `federation/.env.local` (from `env.local.example`; loaded by `compose.local.yaml` `env_file`) | `docker compose -f compose.local.yaml up -d --force-recreate sds-federation-local-sync` | +| Sync-only peer (e.g. fed1) | `federation/.env.peer` from `env.peer.example` | `compose.peer.local.yaml` / `compose.peer.remote.yaml` | +| Production applicant | `federation/site.env` | production compose for that host | + +Sync injects `registry_challenge` into well-known JSON (`well_known.py`); you do **not** edit JSON by hand. + +Confirm: + +```bash +docker compose ... exec printenv FEDERATION_REGISTRY_CHALLENGE_TOKEN +curl -sS "https:///.well-known/sds-federation.json" | jq '{fqdn, registry_challenge}' +``` + +### 3. Verify (applicant UI) + +On the application detail page → **Verify domain**. On success: **`pending_approval`**; staff get email. + +### 4. Wait for staff + +No applicant action until approved and manifest published. + +--- + +## Flagship staff workflow + +Requires **`is_staff`**. Open **`/users/federation/registry/`**. + +| Status | Action | +|--------|--------| +| `pending_approval` | Open application → **Approve** (confirm site id) or **Reject** | +| `approved` (+ any already `published` peers) | **Publish registry** on list page (enabled when sync reports `publish_enabled`) | + +**Publish registry** builds the site list from approved/published applications, calls sync internal publish, and marks rows **`published`** with the new manifest serial. + +Optional: `FEDERATION_REGISTRY_AUTO_PUBLISH_ON_APPROVE=true` on the gateway runs publish immediately after each **Approve** (default `false`). + +Break-glass (no UI): `sds-federation-registry publish --sites-json ...` on flagship sync; then reconcile DB manually if needed. + +--- + +## New peer after publish (join the mesh) + +After staff publish, the applicant (and all members) should trust the mothership manifest. + +### On the new peer sync + +1. **`[registry]`** in `federation.toml` (or render via onboard): + + ```toml + [registry] + url = "https://sds.crc.nd.edu/.well-known/sds-registry" + public_key_path = "/etc/sds/certs/sds-registry.pub.pem" + refresh_secs = 900 + required = false + ``` + +2. Copy **`sds-registry.pub.pem`** from flagship (`federation/certs/`) into peer `federation/certs/` (compose mount). +3. Set **`FEDERATION_REGISTRY_PUBKEY_FINGERPRINT`** on peer sync (optional in well-known; use for operator verification). +4. Set **`FEDERATION_REGISTRY_WELL_KNOWN_URL`** on peer if you want identity JSON to advertise the registry URL. +5. Restart sync; confirm poll in logs (`registry added peer …`) or: + + ```bash + curl -sS "https://sds.crc.nd.edu/.well-known/sds-registry/sites.json" | jq '.sites[].fqdn' + ``` + +Existing members pick up the new peer on their **`registry.refresh_secs`** timer without editing `[[peers]]` (unless they use static overrides). + +--- + +## Manual-only checklist (summary) + +| Who | Manual step | +|-----|-------------| +| Applicant | Copy one-time token; set `FEDERATION_REGISTRY_CHALLENGE_TOKEN`; **recreate** sync container | +| Applicant | Click **Verify domain** | +| Staff | **Approve** / **Reject** | +| Staff | **Publish registry** | +| Flagship (once) | Signing key, Traefik routes, doctor green | +| New peer (once) | Registry URL, public key, `[registry]` in toml | + +--- + +## Troubleshooting + +Use the full table in [gateway/docs/federation-registry-verify.md#troubleshooting](../../gateway/docs/federation-registry-verify.md#troubleshooting). + +Quick hits: + +| Symptom | Fix | +|---------|-----| +| `registry_challenge` null | Token missing on **applicant** sync or container not recreated | +| Staff email missing | Celery worker up; `FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS` or staff accounts | +| **Publish registry** hidden | Sync `publish_enabled` false — key + `[registry.publish]` | +| Peers never see new site | Staff did not publish; wrong `registry.url`; signature / serial trust failure in sync logs | + +--- + +## Local lab pointer + +Mothership lab: `SDS_SITE_FQDN` = `FLAGSHIP_GATEWAY_HOST` = `sds.localhost`, gateway `:8000`, sync `:8001`. +Same flow as above; verify doc covers loopback curls and `FEDERATION_REGISTRY_LOCAL_LAB` on sync when applicable. + +Registry intake is **separate** from two-peer sync E2E: [scripts/local_e2e/README.md](../scripts/local_e2e/README.md). + +--- + +## Related + ++ [gateway/docs/federation-registry-verify.md](../../gateway/docs/federation-registry-verify.md) — verify UI and troubleshooting ++ [peer-remote-test.md](./peer-remote-test.md) — remote sync-only peer diff --git a/federation/docs/peer-remote-test.md b/federation/docs/peer-remote-test.md index 89dffaf1c..b56dbc2a2 100644 --- a/federation/docs/peer-remote-test.md +++ b/federation/docs/peer-remote-test.md @@ -117,3 +117,31 @@ Fallback if Traefik/TLS is not ready on fed1: open host **:8000** and use Same idea on one machine: `just deploy-local-peer-2-peer` then `just seed-peer` (see [../README.md](../README.md) and [../scripts/local_e2e/README.md](../scripts/local_e2e/README.md)). + +## Registry apply from a sync-only peer + +Domain verification reads `GET /.well-known/sds-federation.json` from the **applicant** +public hostname (Traefik routes that path to **this** peer’s sync — not the mothership gateway). + +1. On the mothership, create a registry application and copy the **one-time verification token**. +2. On **sds-fed1**, set the token on the peer sync container env (not on mothership django.env): + +```bash +cd federation +cp env.peer.example .env.peer +# Edit .env.peer: +FEDERATION_REGISTRY_CHALLENGE_TOKEN= +docker compose -f compose.peer.remote.yaml --env-file .env.peer up -d --force-recreate sds-federation-peer-sync +``` + +3. Preflight: + +```bash +curl -sS https://sds-fed1.crc.nd.edu/.well-known/sds-federation.json | jq '{fqdn, registry_challenge}' +``` + +4. Run domain verify via the mothership UI (**Verify domain**) or curl against flagship sync. + Set `FEDERATION_SYNC_INTERNAL_URL=http://sds-federation-local-sync:8000` on gateway django env. + +Do not put `FEDERATION_REGISTRY_CHALLENGE_TOKEN` in `federation-shared.env` or on the +mothership sync unless the mothership is also the applicant. diff --git a/federation/env.local.example b/federation/env.local.example new file mode 100644 index 000000000..c0df2b454 --- /dev/null +++ b/federation/env.local.example @@ -0,0 +1,10 @@ +# Optional overrides for compose.local.yaml (flagship lab sync on :8001). +# Copy to .env.local (gitignored); compose.local.yaml loads it via env_file (required: false). +# You may still pass --env-file .env.local for ${VAR} interpolation in compose environment:. +# +# Applicant challenge when THIS host's sync serves /.well-known/sds-federation.json +# FEDERATION_REGISTRY_CHALLENGE_TOKEN= +# +# Well-known registry metadata when sync serves signed manifest (flagship lab with [registry.publish]): +# FEDERATION_REGISTRY_WELL_KNOWN_URL=http://sds.localhost/.well-known/sds-registry +# FEDERATION_REGISTRY_PUBKEY_FINGERPRINT=sha256:... diff --git a/federation/env.peer.example b/federation/env.peer.example index 31baa2665..7fa401121 100644 --- a/federation/env.peer.example +++ b/federation/env.peer.example @@ -1,10 +1,21 @@ -# Optional env for compose.peer.remote.yaml (copy to .env.peer; do not commit secrets). +# Optional env for compose.peer.remote.yaml / compose.peer.local.yaml +# Copy to .env.peer in this directory (gitignored). Do not commit secrets. +# +# cp env.peer.example .env.peer +# docker compose -f compose.peer.remote.yaml --env-file .env.peer up -d --build +# +# Do not use federation/peer.env — compose reads .env.peer only. PEER_SITE_NAME=fed1 PEER_OPENSEARCH_PORT=9200 -# Public URL sds-dev puts in federation.toml [[peers]].sync_service_url -# Peers use Traefik :443 PathPrefix(/sync) — not a host-published sync port. +# Public URL the mothership puts in federation.toml [[peers]].sync_service_url PEER_SYNC_PUBLIC_URL=https://sds-fed1.crc.nd.edu/sync FEDERATION_BOOTSTRAP_ON_START=true + +# Applicant registry verify: paste the ONE-TIME raw token from the mothership application UI +# (mothership stores sha256 in DB). Sync serves it as registry_challenge in +# GET /.well-known/sds-federation.json when Traefik routes that path to this container. +# Recreate sync after changing: docker compose ... up -d --force-recreate sds-federation-peer-sync +FEDERATION_REGISTRY_CHALLENGE_TOKEN= diff --git a/federation/federation.example.toml b/federation/federation.example.toml index db687d174..a671b603f 100644 --- a/federation/federation.example.toml +++ b/federation/federation.example.toml @@ -2,10 +2,15 @@ name = "your-site" fqdn = "your-site.domain" display_name = "Your Site" +# Optional; defaults to https://{fqdn}/api/v1 in well-known and manifest flagship entry. +# gateway_api_base = "https://your-site.domain/api/v1" # Advertised in site-hello. Use the Traefik HTTPS /sync URL (not host :8001). # Defaults to http://{fqdn}/sync/ if unset. # sync_service_url = "https://your-site.domain/sync" +# registry_challenge for domain verify is NOT in this file — set FEDERATION_REGISTRY_CHALLENGE_TOKEN +# on the process that serves /.well-known/sds-federation.json (gateway django.env or .env.peer). + [[peers]] # Notre Dame SDS site is the original site deployment # and is included as a peer by default. @@ -15,3 +20,10 @@ display_name = "Notre Dame CRC" gateway_api_base = "https://sds.crc.nd.edu/api/v1" sync_service_url = "https://sds.crc.nd.edu/sync/" ca_cert_path = "/etc/sds/certs/crc-ca.pem" + +# Flagship registry signing (sync only; peers omit [registry.publish]) +# [registry.publish] +# enabled = true +# signing_key_path = "/etc/sds/secrets/registry/sign.pem" +# manifest_dir = "/var/lib/sds/registry-publish" +# ttl_hours = 168 diff --git a/federation/pyproject.toml b/federation/pyproject.toml index 2d63ffc2f..649a233c6 100644 --- a/federation/pyproject.toml +++ b/federation/pyproject.toml @@ -23,6 +23,9 @@ module-root = "" "uvicorn[standard]>=0.34.0", ] +[project.scripts] +sds-federation-registry = "sds_federation.cli.registry:main" + [project.optional-dependencies] dev = [ "deptry>=0.24.0", @@ -134,17 +137,26 @@ dev = [ [tool.ruff.lint.pylint] max-args = 9 + [tool.ruff.lint.flake8-type-checking] + runtime-evaluated-base-classes = ["pydantic.BaseModel"] + [tool.ruff.lint.per-file-ignores] "**/tests/**" = [ "FBT001", "FBT002", + "FBT003", "PLR2004", "E501", "PT011", "B017", "PLC0415", + "S105", + "ASYNC109", + "TC003", ] "**/scripts/**" = ["T201", "EXE001", "E501"] + "sds_federation/services/registry_verify.py" = ["ASYNC109"] + "**/cli/**" = ["T201", "PLC0415", "E501"] [tool.ruff.format] indent-style = "space" diff --git a/federation/scripts/federation-doctor.sh b/federation/scripts/federation-doctor.sh index d2be2da00..d7e407465 100755 --- a/federation/scripts/federation-doctor.sh +++ b/federation/scripts/federation-doctor.sh @@ -152,6 +152,102 @@ check_sync_url() { fi } +registry_publish_enabled() { + local flag + flag="$(env_value "${SITE_ENV}" FEDERATION_REGISTRY_PUBLISH_ENABLED)" + case "${flag}" in + true | 1 | yes | TRUE) printf 'true\n'; return 0 ;; + esac + if awk '/^\[registry\.publish\]/{found=1; next} /^\[/{found=0} found && /^enabled[[:space:]]*=[[:space:]]*true/{print "true"; exit}' \ + "${FEDERATION_TOML}" 2>/dev/null | grep -qx true; then + printf 'true\n' + return 0 + fi + printf 'false\n' +} + +toml_registry_signing_key_path() { + awk '/^\[registry\.publish\]/{found=1; next} /^\[/{found=0} found && /^signing_key_path/{ + sub(/^[^=]+=[[:space:]]*"/, ""); sub(/".*$/, ""); print; exit + }' "${FEDERATION_TOML}" 2>/dev/null +} + +sync_container_name() { + "${ENV_SELECTION}" sync_container +} + +check_registry() { + if [[ "${FEDERATION_DOCTOR_SKIP_REGISTRY:-0}" == "1" ]]; then + return 0 + fi + local fqdn sync_container publish_enabled signing_path host_path admin_token backend + fqdn="$(toml_site_value fqdn)" + [[ -n "${fqdn}" ]] || return 0 + sync_container="$(sync_container_name)" + publish_enabled="$(registry_publish_enabled)" + + if [[ "${publish_enabled}" == "true" ]]; then + signing_path="$(toml_registry_signing_key_path)" + if [[ -z "${signing_path}" ]]; then + signing_path="/etc/sds/secrets/registry/sign.pem" + fi + host_path="${FEDERATION_ROOT}/secrets/registry/sign.pem" + if [[ ! -r "${host_path}" ]]; then + record_fail "registry publish enabled but ${host_path} is not readable on the host" + fi + if docker ps --format '{{.Names}}' | grep -qx "${sync_container}"; then + if ! docker exec "${sync_container}" test -r "${signing_path}" 2>/dev/null; then + record_fail "signing key not readable in ${sync_container} at ${signing_path}" + fi + else + info "Skipping in-container signing key check (${sync_container} not running)" + fi + fi + + if docker ps --format '{{.Names}}' | grep -qx "${sync_container}"; then + if ! docker exec "${sync_container}" uv run python -c " +import sys, httpx +r = httpx.get('http://127.0.0.1:8000/.well-known/sds-federation.json', timeout=8) +sys.exit(0 if r.status_code == 200 else 1) +" 2>/dev/null; then + record_fail "sync well-known /.well-known/sds-federation.json did not return 200 in ${sync_container}" + fi + else + info "Skipping sync well-known probe (${sync_container} not running)" + fi + + if [[ "${FEDERATION_DOCTOR_SKIP_DNS:-0}" != "1" && "${SDS_ENV_TYPE}" == "production" ]]; then + local code + code="$(curl -ksS -o /dev/null -w '%{http_code}' \ + "https://${fqdn}/internal/registry/capabilities" 2>/dev/null || printf '000')" + if [[ "${code}" == "200" || "${code}" == "401" || "${code}" == "503" ]]; then + record_fail "/internal/registry exposed on public hostname ${fqdn} (HTTP ${code})" + fi + fi + + local env_fp pub_path computed_fp + env_fp="$(env_value "${SITE_ENV}" FEDERATION_REGISTRY_PUBKEY_FINGERPRINT)" + if [[ -z "${env_fp}" ]]; then + env_fp="$(env_value "${SHARED_ENV}" FEDERATION_REGISTRY_PUBKEY_FINGERPRINT)" + fi + pub_path="/etc/sds/certs/sds-registry.pub.pem" + if [[ -n "${env_fp}" && -r "${FEDERATION_ROOT}/certs/sds-registry.pub.pem" ]]; then + if docker ps --format '{{.Names}}' | grep -qx "${sync_container}"; then + computed_fp="$(docker exec "${sync_container}" uv run sds-federation-registry fingerprint --public-key-path "${pub_path}" 2>/dev/null || true)" + if [[ -n "${computed_fp}" && "${computed_fp}" != "${env_fp}" ]]; then + record_fail "FEDERATION_REGISTRY_PUBKEY_FINGERPRINT mismatch (env ${env_fp} vs ${computed_fp})" + fi + fi + fi + + if [[ "${publish_enabled}" == "true" ]]; then + admin_token="$(env_value "${SHARED_ENV}" FEDERATION_SYNC_ADMIN_TOKEN)" + if [[ -z "${admin_token}" ]]; then + record_fail "registry publish enabled but FEDERATION_SYNC_ADMIN_TOKEN missing in federation-shared.env (sync internal API)" + fi + fi +} + check_doc_site() { local fqdn short fqdn="$(toml_site_value fqdn)" @@ -181,7 +277,7 @@ main() { if [[ -n "${only}" ]]; then run_check "${only}" else - for c in identity token db_token networks dns ca sync_url doc_site; do + for c in identity token db_token networks dns ca sync_url registry doc_site; do run_check "${c}" done fi diff --git a/federation/scripts/render-site-config.sh b/federation/scripts/render-site-config.sh index 67c2085da..8b3c2c062 100755 --- a/federation/scripts/render-site-config.sh +++ b/federation/scripts/render-site-config.sh @@ -39,6 +39,10 @@ default_sync_health_url() { printf 'http://%s:8000/sync/health\n' "${FEDERATION_SYNC_CONTAINER}" } +default_sync_internal_url() { + printf 'http://%s:8000\n' "${FEDERATION_SYNC_CONTAINER}" +} + default_peer_values() { case "${SDS_ENV_TYPE}" in production) @@ -65,8 +69,18 @@ export_vars_for_render() { export GATEWAY_INTERNAL_BASE_URL="${GATEWAY_INTERNAL_BASE_URL:-$(default_gateway_internal)}" export REDIS_URL="${REDIS_URL:-$(default_redis_url)}" export FEDERATION_SYNC_HEALTH_URL="${FEDERATION_SYNC_HEALTH_URL:-$(default_sync_health_url)}" + export FEDERATION_SYNC_INTERNAL_URL="${FEDERATION_SYNC_INTERNAL_URL:-$(default_sync_internal_url)}" export FEDERATION_SYNC_USER_EMAIL="${FEDERATION_SYNC_USER_EMAIL:-federation-sync@internal.local}" export FEDERATION_PEER_CA_PATH="${FEDERATION_PEER_CA_PATH:-}" + export FEDERATION_REGISTRY_PUBLISH_ENABLED="${FEDERATION_REGISTRY_PUBLISH_ENABLED:-false}" + case "${FEDERATION_REGISTRY_PUBLISH_ENABLED}" in + true | 1 | yes | TRUE) + export FEDERATION_REGISTRY_PUBLISH_TOML=$'[registry.publish]\nenabled = true\nsigning_key_path = "/etc/sds/secrets/registry/sign.pem"\nmanifest_dir = "/var/lib/sds/registry-publish"\nttl_hours = 168\n' + ;; + *) + export FEDERATION_REGISTRY_PUBLISH_TOML="" + ;; + esac default_peer_values } diff --git a/federation/scripts/set-registry-challenge.sh b/federation/scripts/set-registry-challenge.sh new file mode 100755 index 000000000..8610e3fd7 --- /dev/null +++ b/federation/scripts/set-registry-challenge.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# Set FEDERATION_REGISTRY_CHALLENGE_TOKEN on applicant sync env and print recreate steps. +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: set-registry-challenge.sh --token TOKEN (--env-file PATH | --peer | --site-env) + +Writes or updates FEDERATION_REGISTRY_CHALLENGE_TOKEN=... in the target env file. +Does not recreate containers; prints the compose command to run next. + +Examples: + ./scripts/set-registry-challenge.sh --token "$TOKEN" --peer + ./scripts/set-registry-challenge.sh --token "$TOKEN" --env-file .env.local + ./scripts/set-registry-challenge.sh --token "$TOKEN" --site-env + +EOF +} + +FEDERATION_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TOKEN="" +ENV_FILE="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --token) + TOKEN="${2:-}" + shift 2 + ;; + --env-file) + ENV_FILE="${2:-}" + shift 2 + ;; + --peer) + ENV_FILE="${FEDERATION_ROOT}/.env.peer" + shift + ;; + --site-env) + ENV_FILE="${FEDERATION_ROOT}/site.env" + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) + echo "Unknown argument: $1" >&2 + usage + exit 1 + ;; + esac +done + +if [[ -z "${TOKEN}" ]]; then + echo "ERROR: --token is required" >&2 + exit 1 +fi + +if [[ -z "${ENV_FILE}" ]]; then + echo "ERROR: specify --env-file, --peer, or --site-env" >&2 + exit 1 +fi + +if [[ ! -f "${ENV_FILE}" ]]; then + echo "Target file missing: ${ENV_FILE}" >&2 + echo "Hint: cp env.peer.example .env.peer or create site.env from site.example.env" >&2 + exit 1 +fi + +VAR_NAME="FEDERATION_REGISTRY_CHALLENGE_TOKEN" +LINE="${VAR_NAME}=${TOKEN}" + +if grep -q "^${VAR_NAME}=" "${ENV_FILE}"; then + if [[ "$(uname -s)" == "Darwin" ]]; then + sed -i '' "s|^${VAR_NAME}=.*|${LINE}|" "${ENV_FILE}" + else + sed -i "s|^${VAR_NAME}=.*|${LINE}|" "${ENV_FILE}" + fi +else + printf '\n%s\n' "${LINE}" >>"${ENV_FILE}" +fi + +echo "Updated ${ENV_FILE}" + +case "${ENV_FILE}" in +*"\.env\.peer") + echo "" + echo "Recreate peer sync:" + echo " cd ${FEDERATION_ROOT}" + echo " docker compose -f compose.peer.remote.yaml --env-file .env.peer up -d --force-recreate" + echo " # local peer lab: compose.peer.local.yaml" + ;; +*"site.env") + echo "" + echo "Recreate production sync (example):" + echo " cd ${FEDERATION_ROOT} && SDS_ENV=production just up" + ;; +*) + echo "" + echo "Recreate local flagship/applicant sync:" + echo " cd ${FEDERATION_ROOT}" + echo " docker compose -f compose.local.yaml up -d --force-recreate sds-federation-local-sync" + ;; +esac + +echo "" +echo "Preflight:" +echo ' curl -sS "https:///.well-known/sds-federation.json" | jq '"'"'{fqdn, registry_challenge}'"'" diff --git a/federation/scripts/write_site_env.py b/federation/scripts/write_site_env.py index 97a1e1d02..e3d4902ed 100644 --- a/federation/scripts/write_site_env.py +++ b/federation/scripts/write_site_env.py @@ -15,6 +15,9 @@ "GATEWAY_INTERNAL_BASE_URL", "REDIS_URL", "FEDERATION_PEER_CA_PATH", + "FEDERATION_REGISTRY_PUBLISH_ENABLED", + "FEDERATION_REGISTRY_WELL_KNOWN_URL", + "FEDERATION_REGISTRY_PUBKEY_FINGERPRINT", ) diff --git a/federation/sds_federation/cli/__init__.py b/federation/sds_federation/cli/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/federation/sds_federation/cli/registry.py b/federation/sds_federation/cli/registry.py new file mode 100644 index 000000000..02be85b1d --- /dev/null +++ b/federation/sds_federation/cli/registry.py @@ -0,0 +1,110 @@ +"""Registry CLI: fingerprint, publish from JSON, optional key generation.""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from sds_federation.models import load_federation_config +from sds_federation.schemas.registry import RegistrySite +from sds_federation.services.registry_publish import publish_manifest +from sds_federation.services.registry_sign import RegistrySignError +from sds_federation.services.registry_sign import registry_public_key_fingerprint + + +def _cmd_fingerprint(args: argparse.Namespace) -> int: + path = args.public_key_path + if not path: + config = load_federation_config() + path = config.registry.public_key_path.strip() + if not path: + print("public key path is required", file=sys.stderr) + return 1 + try: + print(registry_public_key_fingerprint(path)) + except RegistrySignError as exc: + print(str(exc), file=sys.stderr) + return 1 + return 0 + + +def _cmd_publish(args: argparse.Namespace) -> int: + config = load_federation_config() + raw = Path(args.sites_json).read_text(encoding="utf-8") + payload = json.loads(raw) + if not isinstance(payload, list): + print("sites JSON must be a list of site objects", file=sys.stderr) + return 1 + sites = [RegistrySite.model_validate(item) for item in payload] + try: + result = publish_manifest( + config, + sites, + args.min_serial, + dry_run=args.dry_run, + ) + except RegistrySignError as exc: + print(str(exc), file=sys.stderr) + return 1 + print(json.dumps(result, indent=2)) + return 0 + + +def _cmd_keygen(args: argparse.Namespace) -> int: + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + private_key = Ed25519PrivateKey.generate() + sign_path = out_dir / "sign.pem" + pub_path = out_dir / "registry.pub.pem" + sign_path.write_bytes( + private_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + pub_path.write_bytes( + private_key.public_key().public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + ) + print(f"wrote {sign_path} and {pub_path}") + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="sds_federation.cli.registry") + sub = parser.add_subparsers(dest="command", required=True) + + fp = sub.add_parser( + "fingerprint", help="Print sha256 fingerprint of registry public key" + ) + fp.add_argument("--public-key-path", default="") + fp.set_defaults(func=_cmd_fingerprint) + + pub = sub.add_parser( + "publish", help="Sign and write registry manifest on this sync host" + ) + pub.add_argument( + "--sites-json", required=True, help="JSON file: list of RegistrySite objects" + ) + pub.add_argument("--min-serial", type=int, default=None) + pub.add_argument("--dry-run", action="store_true") + pub.set_defaults(func=_cmd_publish) + + kg = sub.add_parser("keygen", help="Generate Ed25519 sign.pem + registry.pub.pem") + kg.add_argument("--out-dir", required=True) + kg.set_defaults(func=_cmd_keygen) + + args = parser.parse_args(argv) + return int(args.func(args)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/federation/sds_federation/main.py b/federation/sds_federation/main.py index 0347277ea..ab3175c95 100644 --- a/federation/sds_federation/main.py +++ b/federation/sds_federation/main.py @@ -12,14 +12,17 @@ from sds_federation.models import load_federation_config from sds_federation.routes.health import health_router +from sds_federation.routes.internal_registry import internal_registry_router from sds_federation.routes.sites import sites_router from sds_federation.routes.webhooks import webhooks_router +from sds_federation.routes.well_known import well_known_router from sds_federation.services.bootstrap import run_bootstrap from sds_federation.services.fed_index import FederatedAssetIndexer from sds_federation.services.fed_index import ensure_fed_indices from sds_federation.services.local_events import run_federation_subscriber from sds_federation.services.peer_http import build_peer_http_client from sds_federation.services.peer_registry import PeerRegistry +from sds_federation.services.site_registry import RegistryTrustError from sds_federation.services.site_registry import apply_peers from sds_federation.services.site_registry import resolve_peers from sds_federation.services.site_registry import run_registry_refresh @@ -54,7 +57,12 @@ def _env_flag(key: str) -> bool: async def lifespan(app: FastAPI): config = load_federation_config() http = build_peer_http_client() - await apply_peers(config, await resolve_peers(http, config)) + try: + peers = await resolve_peers(http, config) + except RegistryTrustError as exc: + logger.error("Federation registry trust failure at startup: {}", exc) + raise + await apply_peers(config, peers) os_client = build_opensearch_client( host=get_setting("OPENSEARCH_HOST", "opensearch"), @@ -113,7 +121,9 @@ async def lifespan(app: FastAPI): run_registry_refresh(http, config, fed_indexer, stop), ) app.state.subscriber_task = sub_task + app.state.registry_task = registry_task sync_app.state.subscriber_task = sub_task + sync_app.state.registry_task = registry_task yield @@ -129,4 +139,6 @@ async def lifespan(app: FastAPI): app = FastAPI(title="SDS Federation", lifespan=lifespan) +app.include_router(well_known_router) +app.include_router(internal_registry_router) app.mount(SYNC_PREFIX, sync_app) diff --git a/federation/sds_federation/models.py b/federation/sds_federation/models.py index 193eba9dc..2ab766d92 100644 --- a/federation/sds_federation/models.py +++ b/federation/sds_federation/models.py @@ -13,6 +13,7 @@ class SiteInfo(BaseModel): name: str fqdn: str display_name: str + gateway_api_base: AnyHttpUrl | None = None sync_service_url: AnyHttpUrl | None = None @@ -31,6 +32,13 @@ def site_name_for_federation(site: SiteInfo | PeerInfo) -> str: return site.fqdn +class RegistryPublishPolicy(BaseModel): + enabled: bool = False + signing_key_path: str = "" + manifest_dir: str = "/var/lib/sds/registry-publish" + ttl_hours: int = Field(default=168, ge=1) + + class RegistryPolicy(BaseModel): url: AnyHttpUrl | None = None public_key_path: str = "" @@ -39,6 +47,7 @@ class RegistryPolicy(BaseModel): refresh_secs: int = 900 required: bool = False deny: list[str] = Field(default_factory=list) + publish: RegistryPublishPolicy = Field(default_factory=RegistryPublishPolicy) class FederationConfig(BaseModel): @@ -66,8 +75,16 @@ def allowed_federated_origin_fqdns(config: FederationConfig) -> set[str]: return {peer.fqdn for peer in snapshot_runtime_peers(config)} | {config.site.fqdn} +def env_bool(key: str) -> bool | None: + raw = os.environ.get(key, "").strip().lower() + if not raw: + return None + return raw in ("1", "true", "yes") + + def _registry_policy(data: dict) -> RegistryPolicy: table = dict(data.get("registry", {})) + publish_table = dict(table.pop("publish", {})) for key, env in ( ("url", "FEDERATION_REGISTRY_URL"), ("public_key_path", "FEDERATION_REGISTRY_PUBKEY_PATH"), @@ -76,6 +93,20 @@ def _registry_policy(data: dict) -> RegistryPolicy: value = os.environ.get(env, "").strip() if value: table[key] = value + for key, env in ( + ("signing_key_path", "FEDERATION_REGISTRY_SIGNING_KEY_PATH"), + ("manifest_dir", "FEDERATION_REGISTRY_MANIFEST_STORAGE_DIR"), + ): + value = os.environ.get(env, "").strip() + if value: + publish_table[key] = value + enabled = env_bool("FEDERATION_REGISTRY_PUBLISH_ENABLED") + if enabled is not None: + publish_table["enabled"] = enabled + ttl = os.environ.get("FEDERATION_REGISTRY_MANIFEST_TTL_HOURS", "").strip() + if ttl: + publish_table["ttl_hours"] = ttl # pydantic coerces/validates (ge=1) + table["publish"] = publish_table return RegistryPolicy.model_validate(table) diff --git a/federation/sds_federation/routes/internal_registry.py b/federation/sds_federation/routes/internal_registry.py new file mode 100644 index 000000000..8f0796c6d --- /dev/null +++ b/federation/sds_federation/routes/internal_registry.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import asyncio +import hmac +import os +from pathlib import Path + +from fastapi import APIRouter +from fastapi import Depends +from fastapi import HTTPException +from fastapi import Request +from loguru import logger +from pydantic import BaseModel +from pydantic import Field + +from sds_federation.schemas.registry import RegistrySite +from sds_federation.services.registry_challenge import CHALLENGE_MISMATCH_MESSAGE +from sds_federation.services.registry_challenge import challenge_matches +from sds_federation.services.registry_publish import publish_manifest +from sds_federation.services.registry_sign import RegistrySignError +from sds_federation.services.registry_verify import RegistryVerifyFetchError +from sds_federation.services.registry_verify import fetch_well_known_json + + +def require_admin_token(request: Request) -> None: + expected = os.environ.get("FEDERATION_SYNC_ADMIN_TOKEN", "").strip() + if not expected: + raise HTTPException(status_code=503, detail="admin token not configured") + header = request.headers.get("Authorization", "") + scheme, _, supplied = header.partition(" ") + if scheme.lower() != "bearer" or not hmac.compare_digest( + supplied.strip().encode("utf-8"), expected.encode("utf-8") + ): + raise HTTPException(status_code=401, detail="unauthorized") + + +internal_registry_router = APIRouter( + prefix="/internal/registry", + dependencies=[Depends(require_admin_token)], + tags=["internal-registry"], +) + + +class CapabilitiesOut(BaseModel): + publish_enabled: bool + site_fqdn: str + key_configured: bool + + +class VerifyIn(BaseModel): + fqdn: str + challenge_hash: str + + +class VerifyOut(BaseModel): + ok: bool + error: str | None = None + well_known: dict | None = None + + +class PublishIn(BaseModel): + sites: list[RegistrySite] = Field(default_factory=list) + min_serial: int | None = None + dry_run: bool = False + + +class PublishOut(BaseModel): + serial: int + issued_at: str + expires_at: str + site_names: list[str] + dry_run: bool + + +@internal_registry_router.get("/capabilities", response_model=CapabilitiesOut) +async def get_registry_capabilities(request: Request) -> CapabilitiesOut: + config = request.app.state.config + publish = config.registry.publish + key_path = publish.signing_key_path.strip() + key_ok = bool(key_path) and await asyncio.to_thread(Path(key_path).is_file) + return CapabilitiesOut( + publish_enabled=publish.enabled and key_ok, + site_fqdn=config.site.fqdn, + key_configured=key_ok, + ) + + +@internal_registry_router.post("/verify", response_model=VerifyOut) +async def verify(body: VerifyIn, request: Request) -> VerifyOut: + config = request.app.state.config + try: + doc = await fetch_well_known_json(body.fqdn, config) + except RegistryVerifyFetchError as exc: + return VerifyOut(ok=False, error=str(exc)) + if not challenge_matches(doc, body.challenge_hash): + return VerifyOut(ok=False, error=CHALLENGE_MISMATCH_MESSAGE) + if str(doc.get("fqdn", "")).strip().lower().rstrip( + "." + ) != body.fqdn.strip().lower().rstrip("."): + return VerifyOut( + ok=False, + error="fqdn in well-known JSON does not match this application.", + ) + return VerifyOut(ok=True, well_known=doc) + + +@internal_registry_router.post("/publish", response_model=PublishOut) +async def publish(body: PublishIn, request: Request) -> PublishOut: + config = request.app.state.config + if not config.registry.publish.enabled: + raise HTTPException( + status_code=409, detail="publish is not enabled on this site" + ) + try: + result = await asyncio.to_thread( + publish_manifest, + config, + body.sites, + body.min_serial, + dry_run=body.dry_run, + ) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + except RegistrySignError as exc: + logger.error("registry publish failed: {}", exc) + raise HTTPException( + status_code=500, detail="registry publish failed; see sync logs" + ) from exc + return PublishOut(**result) diff --git a/federation/sds_federation/routes/well_known.py b/federation/sds_federation/routes/well_known.py new file mode 100644 index 000000000..8a36d3389 --- /dev/null +++ b/federation/sds_federation/routes/well_known.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING + +from fastapi import APIRouter +from fastapi import HTTPException +from fastapi import Request +from fastapi.responses import JSONResponse +from fastapi.responses import Response + +from sds_federation.services.registry_publish import read_published_manifest_bytes +from sds_federation.services.registry_publish import read_published_signature_bytes +from sds_federation.services.registry_sign import RegistrySignError +from sds_federation.services.well_known import WELL_KNOWN_SDS_FEDERATION_PATH +from sds_federation.services.well_known import build_site_document +from sds_federation.services.well_known import document_ready + +if TYPE_CHECKING: + from collections.abc import Callable + + from sds_federation.models import FederationConfig + +well_known_router = APIRouter(tags=["well-known"]) + +REGISTRY_SITES_PATH = "/.well-known/sds-registry/sites.json" +REGISTRY_SIG_PATH = "/.well-known/sds-registry/sites.json.sig" + + +@well_known_router.get(WELL_KNOWN_SDS_FEDERATION_PATH) +async def sds_federation_well_known(request: Request) -> JSONResponse: + config = request.app.state.config + doc = build_site_document(config) + if not document_ready(doc): + raise HTTPException( + status_code=503, detail="well-known document is not configured" + ) + return JSONResponse(content=doc, headers={"Cache-Control": "no-store"}) + + +async def _serve_published( + request: Request, + reader: Callable[[FederationConfig], bytes | None], + media_type: str, +) -> Response: + config = request.app.state.config + payload = None + if config.registry.publish.enabled: + try: + payload = await asyncio.to_thread(reader, config) + except RegistrySignError: + payload = None + if payload is None: + raise HTTPException( + status_code=404, detail="registry manifest is not published" + ) + return Response( + content=payload, + media_type=media_type, + headers={"Cache-Control": "public, max-age=60"}, + ) + + +@well_known_router.get(REGISTRY_SITES_PATH) +async def registry_sites_json(request: Request) -> Response: + return await _serve_published( + request, read_published_manifest_bytes, "application/json" + ) + + +@well_known_router.get(REGISTRY_SIG_PATH) +async def registry_sites_sig(request: Request) -> Response: + return await _serve_published(request, read_published_signature_bytes, "text/plain") diff --git a/federation/sds_federation/services/registry_challenge.py b/federation/sds_federation/services/registry_challenge.py new file mode 100644 index 000000000..f00fb6758 --- /dev/null +++ b/federation/sds_federation/services/registry_challenge.py @@ -0,0 +1,22 @@ +"""Registry domain-verification challenge hash compare (no token generation here).""" + +from __future__ import annotations + +import hashlib +import hmac + +CHALLENGE_MISMATCH_MESSAGE = ( + "registry_challenge is missing or does not match your verification token." +) + + +def hash_registry_challenge_token(raw_token: str) -> str: + return hashlib.sha256(raw_token.encode("utf-8")).hexdigest() + + +def challenge_matches(well_known: dict, stored_hash: str) -> bool: + raw = well_known.get("registry_challenge") + if not isinstance(raw, str) or not raw.strip() or not stored_hash: + return False + candidate = hash_registry_challenge_token(raw.strip()) + return hmac.compare_digest(candidate, stored_hash.strip()) diff --git a/federation/sds_federation/services/registry_publish.py b/federation/sds_federation/services/registry_publish.py new file mode 100644 index 000000000..67b11f7f9 --- /dev/null +++ b/federation/sds_federation/services/registry_publish.py @@ -0,0 +1,212 @@ +"""Build, sign, and write registry manifest files on the flagship sync host.""" + +from __future__ import annotations + +import fcntl +import json +from contextlib import suppress +from datetime import UTC +from datetime import datetime +from datetime import timedelta +from pathlib import Path +from typing import Any + +from sds_federation.models import FederationConfig # noqa: TC001 +from sds_federation.schemas.registry import REGISTRY_SCHEMA_VERSION +from sds_federation.schemas.registry import RegistrySite +from sds_federation.schemas.registry import SiteStatusEnum +from sds_federation.services.registry_sign import MANIFEST_FILENAME +from sds_federation.services.registry_sign import SERIAL_FILENAME +from sds_federation.services.registry_sign import SIGNATURE_FILENAME +from sds_federation.services.registry_sign import RegistrySignError +from sds_federation.services.registry_sign import atomic_write_bytes +from sds_federation.services.registry_sign import canonical_manifest_json_bytes +from sds_federation.services.registry_sign import encode_signature_for_well_known +from sds_federation.services.registry_sign import load_signing_private_key +from sds_federation.services.registry_sign import sign_manifest_payload +from sds_federation.services.well_known import default_gateway_api_base +from sds_federation.services.well_known import default_sync_service_url + +_SITE_STATUS_ACTIVE = SiteStatusEnum.ACTIVE + + +def _format_manifest_datetime(dt: datetime) -> str: + if dt.tzinfo is None: + dt = dt.replace(tzinfo=UTC) + return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _flagship_site(config: FederationConfig) -> RegistrySite: + site = config.site + return RegistrySite( + name=site.name, + fqdn=site.fqdn, + display_name=site.display_name, + status=_SITE_STATUS_ACTIVE, + gateway_api_base=default_gateway_api_base(config), + sync_service_url=default_sync_service_url(config), + ) + + +def _normalized_fqdn(fqdn: str) -> str: + return fqdn.strip().lower().rstrip(".") + + +def _site_to_manifest_entry(site: RegistrySite) -> dict[str, Any]: + return { + "name": site.name, + "fqdn": site.fqdn, + "display_name": site.display_name, + "status": site.status.value, + "gateway_api_base": str(site.gateway_api_base), + "sync_service_url": str(site.sync_service_url), + "ca_cert_file": site.ca_cert_file, + "client_cert_fingerprints": list(site.client_cert_fingerprints), + } + + +def build_manifest_sites( + config: FederationConfig, + extra_sites: list[RegistrySite], +) -> list[dict[str, Any]]: + """Flagship first-class entry plus extras, keyed by FQDN (matches peer merge).""" + flagship = _flagship_site(config) + by_fqdn: dict[str, RegistrySite] = {_normalized_fqdn(flagship.fqdn): flagship} + for site in extra_sites: + key = _normalized_fqdn(site.fqdn) + if key == _normalized_fqdn(flagship.fqdn) or site.name == flagship.name: + continue # flagship identity cannot be overridden by an extra site + by_fqdn[key] = site + names = [site.name for site in by_fqdn.values()] + if len(names) != len(set(names)): + msg = "registry sites must have unique names" + raise ValueError(msg) + return [ + _site_to_manifest_entry(site) + for site in sorted(by_fqdn.values(), key=lambda s: s.name) + ] + + +def build_manifest_dict( + config: FederationConfig, + *, + serial: int, + extra_sites: list[RegistrySite], + issued_at: datetime | None = None, + ttl_hours: int | None = None, +) -> dict[str, Any]: + if serial < 0: + msg = "manifest serial must be non-negative" + raise ValueError(msg) + issued = issued_at or datetime.now(UTC) + hours = ttl_hours if ttl_hours is not None else config.registry.publish.ttl_hours + expires = issued + timedelta(hours=hours) + return { + "schema_version": REGISTRY_SCHEMA_VERSION, + "serial": serial, + "issued_at": _format_manifest_datetime(issued), + "expires_at": _format_manifest_datetime(expires), + "sites": build_manifest_sites(config, extra_sites), + } + + +def _manifest_dir(config: FederationConfig) -> Path: + raw = config.registry.publish.manifest_dir.strip() + if not raw: + msg = "registry publish manifest_dir is not configured" + raise RegistrySignError(msg) + return Path(raw) + + +def read_published_serial(config: FederationConfig) -> int: + """Last published serial; -1 if nothing published. + + Falls back to the serial inside ``sites.json`` when the ``serial`` file is + missing or corrupt, so a damaged file can never roll the serial back. + """ + storage_dir = _manifest_dir(config) + serial_path = storage_dir / SERIAL_FILENAME + if serial_path.is_file(): + with suppress(ValueError, OSError): + return int(serial_path.read_text(encoding="utf-8").strip()) + manifest_path = storage_dir / MANIFEST_FILENAME + if manifest_path.is_file(): + with suppress(ValueError, OSError, TypeError): + return int(json.loads(manifest_path.read_bytes())["serial"]) + return -1 + + +def _write_manifest_files( + storage_dir: Path, + payload: bytes, + signature_b64: bytes, + serial: int, +) -> None: + storage_dir.mkdir(parents=True, exist_ok=True) + atomic_write_bytes(storage_dir / MANIFEST_FILENAME, payload) + atomic_write_bytes(storage_dir / SIGNATURE_FILENAME, signature_b64) + atomic_write_bytes(storage_dir / SERIAL_FILENAME, str(serial).encode("utf-8")) + + +def read_published_manifest_bytes(config: FederationConfig) -> bytes | None: + path = _manifest_dir(config) / MANIFEST_FILENAME + if not path.is_file(): + return None + return path.read_bytes() + + +def read_published_signature_bytes(config: FederationConfig) -> bytes | None: + path = _manifest_dir(config) / SIGNATURE_FILENAME + if not path.is_file(): + return None + return path.read_bytes() + + +def publish_manifest( + config: FederationConfig, + sites: list[RegistrySite], + min_serial: int | None, + *, + dry_run: bool, +) -> dict[str, Any]: + publish = config.registry.publish + key_path = publish.signing_key_path.strip() + if not key_path: + msg = "registry signing key path is not configured" + raise RegistrySignError(msg) + + storage_dir = _manifest_dir(config) + if dry_run: + # No directory/lock side effects: read-only preview of the next manifest. + result, _, _ = _build_and_sign(config, sites, min_serial, key_path) + return {**result, "dry_run": True} + + storage_dir.mkdir(parents=True, exist_ok=True) + with (storage_dir / ".lock").open("a+b") as lock_file: + fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) + result, payload, signature_b64 = _build_and_sign( + config, sites, min_serial, key_path + ) + _write_manifest_files(storage_dir, payload, signature_b64, result["serial"]) + return result + + +def _build_and_sign( + config: FederationConfig, + sites: list[RegistrySite], + min_serial: int | None, + key_path: str, +) -> tuple[dict[str, Any], bytes, bytes]: + floor = (min_serial or 0) - 1 + serial = max(read_published_serial(config), floor) + 1 + manifest = build_manifest_dict(config, serial=serial, extra_sites=sites) + payload = canonical_manifest_json_bytes(manifest) + signature = sign_manifest_payload(payload, load_signing_private_key(key_path)) + result = { + "serial": serial, + "issued_at": manifest["issued_at"], + "expires_at": manifest["expires_at"], + "site_names": [str(s["name"]) for s in manifest["sites"]], + "dry_run": False, + } + return result, payload, encode_signature_for_well_known(signature) diff --git a/federation/sds_federation/services/registry_sign.py b/federation/sds_federation/services/registry_sign.py new file mode 100644 index 000000000..91519184c --- /dev/null +++ b/federation/sds_federation/services/registry_sign.py @@ -0,0 +1,116 @@ +"""Ed25519 signing for federation registry sites.json (raw bytes + base64 .sig).""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +from pathlib import Path +from typing import Any + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey +from cryptography.hazmat.primitives.serialization import Encoding +from cryptography.hazmat.primitives.serialization import PublicFormat +from cryptography.hazmat.primitives.serialization import load_pem_private_key +from cryptography.hazmat.primitives.serialization import load_pem_public_key + +MANIFEST_FILENAME = "sites.json" +SIGNATURE_FILENAME = "sites.json.sig" +SERIAL_FILENAME = "serial" + + +class RegistrySignError(Exception): + """Invalid key material or signature verification failure.""" + + +def canonical_manifest_json_bytes(manifest: dict[str, Any]) -> bytes: + return json.dumps( + manifest, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + ).encode("utf-8") + + +def load_signing_private_key(path: str | Path) -> Ed25519PrivateKey: + pem_path = Path(path) + if not pem_path.is_file(): + msg = f"registry signing key not found: {pem_path}" + raise RegistrySignError(msg) + try: + key = load_pem_private_key(pem_path.read_bytes(), password=None) + except (ValueError, TypeError) as exc: + msg = f"registry signing key at {pem_path.name} is not a valid PEM key" + raise RegistrySignError(msg) from exc + if not isinstance(key, Ed25519PrivateKey): + msg = f"registry signing key at {pem_path} is not Ed25519" + raise RegistrySignError(msg) + return key + + +def load_verifying_public_key(path: str | Path) -> Ed25519PublicKey: + pem_path = Path(path) + if not pem_path.is_file(): + msg = f"registry public key not found: {pem_path}" + raise RegistrySignError(msg) + try: + key = load_pem_public_key(pem_path.read_bytes()) + except (ValueError, TypeError) as exc: + msg = f"registry public key at {pem_path.name} is not a valid PEM key" + raise RegistrySignError(msg) from exc + if not isinstance(key, Ed25519PublicKey): + msg = f"registry public key at {pem_path} is not Ed25519" + raise RegistrySignError(msg) + return key + + +def sign_manifest_payload(payload: bytes, private_key: Ed25519PrivateKey) -> bytes: + return private_key.sign(payload) + + +def encode_signature_for_well_known(signature: bytes) -> bytes: + return base64.b64encode(signature) + + +def decode_signature_from_well_known(raw: bytes) -> bytes: + try: + return base64.b64decode(raw.strip(), validate=True) + except ValueError as exc: # binascii.Error subclasses ValueError + msg = "registry signature is not valid base64" + raise RegistrySignError(msg) from exc + + +def verify_manifest_payload( + payload: bytes, + signature_b64: bytes, + public_key_pem_path: str | Path, +) -> None: + public_key = load_verifying_public_key(public_key_pem_path) + signature = decode_signature_from_well_known(signature_b64) + try: + public_key.verify(signature, payload) + except InvalidSignature as exc: + msg = "registry signature verification failed" + raise RegistrySignError(msg) from exc + + +def registry_public_key_fingerprint(public_key_pem_path: str | Path) -> str: + public_key = load_verifying_public_key(public_key_pem_path) + der = public_key.public_bytes( + encoding=Encoding.DER, + format=PublicFormat.SubjectPublicKeyInfo, + ) + return f"sha256:{hashlib.sha256(der).hexdigest()}" + + +def atomic_write_bytes(path: Path, data: bytes) -> None: + """Write via tmp file + fsync + rename so readers never see partial files.""" + tmp_path = path.with_name(f"{path.name}.tmp") + with tmp_path.open("wb") as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + tmp_path.replace(path) diff --git a/gateway/sds_gateway/api_methods/federation/registry_verify_fetch.py b/federation/sds_federation/services/registry_verify.py similarity index 51% rename from gateway/sds_gateway/api_methods/federation/registry_verify_fetch.py rename to federation/sds_federation/services/registry_verify.py index 4618e0039..795581939 100644 --- a/gateway/sds_gateway/api_methods/federation/registry_verify_fetch.py +++ b/federation/sds_federation/services/registry_verify.py @@ -2,20 +2,23 @@ from __future__ import annotations +import asyncio import http.client import ipaddress import json +import os import re import socket +import ssl from typing import Any from urllib.parse import urlparse -import requests -from django.conf import settings +import httpx from loguru import logger -from sds_gateway.api_methods.federation.well_known import _is_local_federation_lab -from sds_gateway.api_methods.federation.well_known import resolve_well_known_fetch_url +from sds_federation.models import FederationConfig +from sds_federation.models import env_bool +from sds_federation.services.well_known import WELL_KNOWN_SDS_FEDERATION_PATH _DEFAULT_FETCH_TIMEOUT_SECONDS = 30 _MAX_RESPONSE_BYTES = 1_000_000 @@ -45,15 +48,48 @@ def _normalized_host(fqdn: str) -> str: return fqdn.strip().lower().rstrip(".") -def _is_lab_self_fetch(fqdn: str) -> bool: - if not _is_local_federation_lab(): +def _local_lab_enabled() -> bool: + return bool(env_bool("FEDERATION_REGISTRY_LOCAL_LAB")) + + +def _is_self_site_fetch(fqdn: str, config: FederationConfig) -> bool: + site_fqdn = _normalized_host(config.site.fqdn) + if not site_fqdn: + return False + if _normalized_host(fqdn) != site_fqdn: return False - site_fqdn = str(getattr(settings, "SDS_SITE_FQDN", "") or "").strip().lower() - return bool(site_fqdn) and _normalized_host(fqdn) == site_fqdn + if os.environ.get("FEDERATION_REGISTRY_VERIFY_FETCH_BASE", "").strip(): + return True + return _local_lab_enabled() + + +def resolve_well_known_fetch_url(fqdn: str, config: FederationConfig) -> str: + normalized = _normalized_host(fqdn) + if _is_self_site_fetch(fqdn, config): + base = ( + os.environ.get("FEDERATION_REGISTRY_VERIFY_FETCH_BASE", "").strip() + or "http://127.0.0.1:8000" + ) + return f"{base.rstrip('/')}{WELL_KNOWN_SDS_FEDERATION_PATH}" + return f"https://{normalized}{WELL_KNOWN_SDS_FEDERATION_PATH}" + + +def validate_applicant_hostname_for_verify(fqdn: str) -> None: + """Reject private, link-local, and non-public resolved targets.""" + _resolve_global_addresses_for_verify(fqdn) + + +def _require_global(address: str) -> str: + try: + addr = ipaddress.ip_address(address.split("%", 1)[0]) + except ValueError: + raise RegistryVerifyFetchError(_APPLICANT_HOSTNAME_NOT_ALLOWED) from None + if not addr.is_global: + raise RegistryVerifyFetchError(_APPLICANT_HOSTNAME_NOT_ALLOWED) + return address def _resolve_global_addresses_for_verify(fqdn: str) -> list[str]: - """Resolve once; reject private targets; return global address strings.""" host = _normalized_host(fqdn) if not host or "%" in host or "/" in host or "@" in host or ":" in host: raise RegistryVerifyFetchError(_INVALID_APPLICANT_HOSTNAME) @@ -77,37 +113,32 @@ def _resolve_global_addresses_for_verify(fqdn: str) -> list[str]: if not infos: raise RegistryVerifyFetchError(_COULD_NOT_RESOLVE_HOSTNAME) - addresses: list[str] = [] - for *_, sockaddr in infos: - addr = ipaddress.ip_address(sockaddr[0]) - if not addr.is_global: - raise RegistryVerifyFetchError(_APPLICANT_HOSTNAME_NOT_ALLOWED) - addresses.append(sockaddr[0]) + addresses = [_require_global(str(sockaddr[0])) for *_, sockaddr in infos] return list(dict.fromkeys(addresses)) -def validate_applicant_hostname_for_verify(fqdn: str) -> None: - """Reject private, link-local, and non-public resolved targets.""" - _resolve_global_addresses_for_verify(fqdn) - - -class _PinnedHTTPSConnection(http.client.HTTPSConnection): - """TLS to ``host`` while TCP connects to a pre-validated address.""" - - def __init__(self, host: str, pinned_address: str, *, timeout: float) -> None: - self._pinned_address = pinned_address - super().__init__(host, port=443, timeout=timeout) - - def connect(self) -> None: - self.sock = self._create_connection( - (self._pinned_address, self.port), - self.timeout, - self.source_address, - ) - server_hostname = self._tunnel_host or self.host - self.sock = self._context.wrap_socket( - self.sock, server_hostname=server_hostname +def _pinned_https_request( + hostname: str, + pinned_address: str, + path: str, + timeout: float, +) -> tuple[int, bytes]: + """GET over TLS to ``hostname`` while TCP connects to a pre-validated address.""" + conn = http.client.HTTPSConnection(host=hostname, port=443, timeout=timeout) + raw_sock = socket.create_connection((pinned_address, 443), timeout=timeout) + try: + tls_sock = ssl.create_default_context().wrap_socket( + raw_sock, + server_hostname=hostname, ) + conn.sock = tls_sock + conn.request("GET", path, headers={"Accept": "application/json"}) + response = conn.getresponse() + body = _read_response_body_limited(response, _MAX_RESPONSE_BYTES) + return response.status, body + finally: + conn.close() + raw_sock.close() def _read_response_body_limited( @@ -132,8 +163,7 @@ def _pinned_https_get( hostname: str, pinned_addresses: list[str], timeout: int, -) -> tuple[int, bytes]: - """GET over HTTPS using only addresses from verify DNS resolution.""" +) -> bytes: parsed = urlparse(url) path = parsed.path or "/" if parsed.query: @@ -141,71 +171,69 @@ def _pinned_https_get( last_error: BaseException | None = None for pinned in pinned_addresses: - conn = _PinnedHTTPSConnection(hostname, pinned, timeout=timeout) try: - conn.request("GET", path, headers={"Accept": "application/json"}) - response = conn.getresponse() - body = _read_response_body_limited(response, _MAX_RESPONSE_BYTES) + response_status, body = _pinned_https_request( + hostname, + pinned, + path, + float(timeout), + ) except RegistryVerifyFetchError: raise - except (OSError, TimeoutError, http.client.HTTPException) as exc: + except (OSError, http.client.HTTPException) as exc: last_error = exc else: - return response.status, body - finally: - conn.close() + if ( + response_status < _HTTP_SUCCESS_STATUS_MIN + or response_status > _HTTP_SUCCESS_STATUS_MAX + ): + raise RegistryVerifyFetchError(_COULD_NOT_FETCH_WELL_KNOWN) from None + return body if last_error is not None: - raise last_error - raise OSError(_NO_PINNED_ADDRESSES) + raise RegistryVerifyFetchError(_COULD_NOT_FETCH_WELL_KNOWN) from last_error + raise RegistryVerifyFetchError(_COULD_NOT_FETCH_WELL_KNOWN) -def fetch_well_known_json( +def _fetch_well_known_json_sync( fqdn: str, + config: FederationConfig, timeout: int = _DEFAULT_FETCH_TIMEOUT_SECONDS, ) -> dict[str, Any]: - """GET applicant well-known JSON (HTTPS; local lab may use internal HTTP).""" - url = resolve_well_known_fetch_url(fqdn) expected_host = _normalized_host(fqdn) - pinned_addresses: list[str] | None = None - if not _is_lab_self_fetch(fqdn): - pinned_addresses = _resolve_global_addresses_for_verify(fqdn) - parsed = urlparse(url) - if ( - parsed.scheme != "https" - or _normalized_host(parsed.hostname or "") != expected_host - ): - raise RegistryVerifyFetchError(_INVALID_VERIFY_FETCH_URL) + use_pinned = not _is_self_site_fetch(fqdn, config) + url = resolve_well_known_fetch_url(fqdn, config) try: - if pinned_addresses is not None: - status, content = _pinned_https_get( - url, - expected_host, - pinned_addresses, - timeout, - ) - if status < _HTTP_SUCCESS_STATUS_MIN or status > _HTTP_SUCCESS_STATUS_MAX: - http_error_msg = f"HTTP {status}" - raise requests.HTTPError(http_error_msg) + if use_pinned: + pinned = _resolve_global_addresses_for_verify(fqdn) + parsed = urlparse(url) + if ( + parsed.scheme != "https" + or _normalized_host(parsed.hostname or "") != expected_host + ): + raise RegistryVerifyFetchError(_INVALID_VERIFY_FETCH_URL) + content = _pinned_https_get(url, expected_host, pinned, timeout) else: - response = requests.get( + response = httpx.get( url, timeout=timeout, - allow_redirects=False, + follow_redirects=False, headers={"Accept": "application/json"}, ) response.raise_for_status() content = response.content if len(content) > _MAX_RESPONSE_BYTES: raise RegistryVerifyFetchError(_WELL_KNOWN_TOO_LARGE) - payload = json.loads(content) - except ( - requests.RequestException, - OSError, - TimeoutError, - http.client.HTTPException, - ): + except httpx.HTTPError as exc: + logger.warning( + "registry verify HTTP failed fqdn={} url={}", + fqdn, + url, + exc_info=True, + ) + raise RegistryVerifyFetchError(_COULD_NOT_FETCH_WELL_KNOWN) from exc + except (OSError, http.client.HTTPException): logger.warning( "registry verify HTTP failed fqdn={} url={}", fqdn, @@ -213,10 +241,25 @@ def fetch_well_known_json( exc_info=True, ) raise RegistryVerifyFetchError(_COULD_NOT_FETCH_WELL_KNOWN) from None + + try: + payload = json.loads(content) except ValueError: logger.warning("registry verify JSON parse failed fqdn={}", fqdn, exc_info=True) raise RegistryVerifyFetchError(_WELL_KNOWN_INVALID_JSON) from None - if not isinstance(payload, dict): raise RegistryVerifyFetchError(_WELL_KNOWN_NOT_OBJECT) return payload + + +async def fetch_well_known_json( + fqdn: str, + config: FederationConfig, + fetch_timeout_seconds: int = _DEFAULT_FETCH_TIMEOUT_SECONDS, +) -> dict[str, Any]: + return await asyncio.to_thread( + _fetch_well_known_json_sync, + fqdn, + config, + fetch_timeout_seconds, + ) diff --git a/federation/sds_federation/services/site_registry.py b/federation/sds_federation/services/site_registry.py index 2bc0583a8..e3dbae9a3 100644 --- a/federation/sds_federation/services/site_registry.py +++ b/federation/sds_federation/services/site_registry.py @@ -1,7 +1,6 @@ from __future__ import annotations import asyncio -import base64 import json from contextlib import suppress from pathlib import Path @@ -9,8 +8,6 @@ import httpx from cryptography.exceptions import InvalidSignature -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey -from cryptography.hazmat.primitives.serialization import load_pem_public_key from loguru import logger from sds_federation.models import PeerInfo @@ -20,6 +17,14 @@ from sds_federation.schemas.registry import RegistrySite from sds_federation.services.bootstrap import bootstrap_peer_sync_list from sds_federation.services.bootstrap import push_site_hello_to_peer +from sds_federation.services.registry_sign import MANIFEST_FILENAME +from sds_federation.services.registry_sign import SERIAL_FILENAME +from sds_federation.services.registry_sign import SIGNATURE_FILENAME +from sds_federation.services.registry_sign import RegistrySignError +from sds_federation.services.registry_sign import atomic_write_bytes +from sds_federation.services.registry_sign import decode_signature_from_well_known +from sds_federation.services.registry_sign import encode_signature_for_well_known +from sds_federation.services.registry_sign import load_verifying_public_key if TYPE_CHECKING: from datetime import datetime @@ -28,32 +33,32 @@ from sds_federation.models import RegistryPolicy from sds_federation.services.fed_index import FederatedAssetIndexer -_MANIFEST_NAME = "sites.json" -_SIGNATURE_NAME = "sites.json.sig" -_SERIAL_NAME = "serial" - class RegistryTrustError(Exception): """Manifest failed signature, freshness, or rollback checks.""" -def _public_key(policy: RegistryPolicy) -> Ed25519PublicKey: - key = load_pem_public_key(Path(policy.public_key_path).read_bytes()) - if not isinstance(key, Ed25519PublicKey): - msg = f"registry key at {policy.public_key_path} is not Ed25519" - raise RegistryTrustError(msg) - return key - - def _verify(policy: RegistryPolicy, payload: bytes, signature: bytes) -> None: try: - _public_key(policy).verify(signature, payload) + public_key = load_verifying_public_key(policy.public_key_path) + except RegistrySignError as exc: + raise RegistryTrustError(str(exc)) from exc + try: + public_key.verify(signature, payload) except InvalidSignature as exc: - raise RegistryTrustError("registry signature verification failed") from exc + msg = "registry signature verification failed" + raise RegistryTrustError(msg) from exc + + +def _decode_signature(raw: bytes) -> bytes: + try: + return decode_signature_from_well_known(raw) + except RegistrySignError as exc: + raise RegistryTrustError(str(exc)) from exc def _last_serial(policy: RegistryPolicy) -> int: - path = Path(policy.cache_dir) / _SERIAL_NAME + path = Path(policy.cache_dir) / SERIAL_FILENAME if not path.is_file(): return -1 try: @@ -62,6 +67,13 @@ def _last_serial(policy: RegistryPolicy) -> int: return -1 +def _cached_manifest_payload(policy: RegistryPolicy) -> bytes | None: + path = Path(policy.cache_dir) / MANIFEST_FILENAME + if not path.is_file(): + return None + return path.read_bytes() + + def _accept( policy: RegistryPolicy, payload: bytes, @@ -85,31 +97,42 @@ def _accept( if manifest.serial < last: msg = f"registry serial {manifest.serial} older than accepted {last}" raise RegistryTrustError(msg) + if manifest.serial == last: + previous = _cached_manifest_payload(policy) + if previous is not None and previous != payload: + msg = ( + f"registry serial {manifest.serial} reused with " + "different manifest bytes" + ) + raise RegistryTrustError(msg) return manifest def _cache( policy: RegistryPolicy, payload: bytes, signature: bytes, serial: int ) -> None: + """Persist manifest bytes and base64-encoded Ed25519 signature (gateway .sig).""" cache_dir = Path(policy.cache_dir) cache_dir.mkdir(parents=True, exist_ok=True) - (cache_dir / _MANIFEST_NAME).write_bytes(payload) - (cache_dir / _SIGNATURE_NAME).write_bytes(base64.b64encode(signature)) - (cache_dir / _SERIAL_NAME).write_text(str(serial), encoding="utf-8") + atomic_write_bytes(cache_dir / MANIFEST_FILENAME, payload) + atomic_write_bytes( + cache_dir / SIGNATURE_FILENAME, encode_signature_for_well_known(signature) + ) + atomic_write_bytes(cache_dir / SERIAL_FILENAME, str(serial).encode("utf-8")) def load_cached_manifest(policy: RegistryPolicy) -> RegistryManifest | None: """Last-known-good manifest, still subject to signature and expiry checks.""" cache_dir = Path(policy.cache_dir) - payload_path = cache_dir / _MANIFEST_NAME - signature_path = cache_dir / _SIGNATURE_NAME + payload_path = cache_dir / MANIFEST_FILENAME + signature_path = cache_dir / SIGNATURE_FILENAME if not (payload_path.is_file() and signature_path.is_file()): return None try: return _accept( policy, payload_path.read_bytes(), - base64.b64decode(signature_path.read_bytes(), validate=True), + _decode_signature(signature_path.read_bytes()), ) except (RegistryTrustError, ValueError) as exc: logger.error("cached registry manifest rejected: {}", exc) @@ -121,9 +144,10 @@ async def fetch_manifest( policy: RegistryPolicy, ) -> RegistryManifest: base = str(policy.url).rstrip("/") - payload = (await http.get(f"{base}/{_MANIFEST_NAME}")).raise_for_status().content - raw_sig = (await http.get(f"{base}/{_SIGNATURE_NAME}")).raise_for_status().content - signature = base64.b64decode(raw_sig.strip(), validate=True) + manifest_resp = await http.get(f"{base}/{MANIFEST_FILENAME}") + sig_resp = await http.get(f"{base}/{SIGNATURE_FILENAME}") + payload = manifest_resp.raise_for_status().content + signature = _decode_signature(sig_resp.raise_for_status().content) manifest = _accept(policy, payload, signature) _cache(policy, payload, signature, manifest.serial) return manifest diff --git a/federation/sds_federation/services/well_known.py b/federation/sds_federation/services/well_known.py new file mode 100644 index 000000000..a64c848cf --- /dev/null +++ b/federation/sds_federation/services/well_known.py @@ -0,0 +1,76 @@ +"""Site self-description at /.well-known/sds-federation.json.""" + +from __future__ import annotations + +import os +from typing import Any + +from sds_federation.models import FederationConfig # noqa: TC001 + +SDS_FEDERATION_WELL_KNOWN_SCHEMA_VERSION = 1 +WELL_KNOWN_SDS_FEDERATION_PATH = "/.well-known/sds-federation.json" + + +def _env(name: str, default: str = "") -> str: + return os.environ.get(name, default).strip() + + +def default_gateway_api_base(config: FederationConfig) -> str: + if config.site.gateway_api_base is not None: + return str(config.site.gateway_api_base).rstrip("/") + explicit = _env("FEDERATION_GATEWAY_API_BASE") + if explicit: + return explicit.rstrip("/") + fqdn = config.site.fqdn.strip() + api_version = _env("API_VERSION", "v1") + return f"https://{fqdn}/api/{api_version}" + + +def default_sync_service_url(config: FederationConfig) -> str: + if config.site.sync_service_url is not None: + return str(config.site.sync_service_url).rstrip("/") + explicit = _env("FEDERATION_SYNC_SERVICE_URL") + if explicit: + return explicit.rstrip("/") + fqdn = config.site.fqdn.strip() + return f"https://{fqdn}/sync" + + +def build_site_document(config: FederationConfig) -> dict[str, Any]: + site = config.site + doc: dict[str, Any] = { + "schema_version": SDS_FEDERATION_WELL_KNOWN_SCHEMA_VERSION, + "name": site.name, + "fqdn": site.fqdn, + "display_name": site.display_name, + "gateway_api_base": default_gateway_api_base(config), + "sync_service_url": default_sync_service_url(config), + } + challenge = _env("FEDERATION_REGISTRY_CHALLENGE_TOKEN") + if challenge: + doc["registry_challenge"] = challenge + registry_url = _env("FEDERATION_REGISTRY_WELL_KNOWN_URL") + if registry_url: + doc["registry_url"] = registry_url + fingerprint = _env("FEDERATION_REGISTRY_PUBKEY_FINGERPRINT") + if fingerprint: + doc["registry_pubkey_fingerprint"] = fingerprint + contact = _env("SDS_FEDERATION_WELL_KNOWN_CONTACT") + if contact: + doc["contact"] = contact + return doc + + +def document_ready(doc: dict[str, Any]) -> bool: + for key in ( + "schema_version", + "name", + "fqdn", + "display_name", + "gateway_api_base", + "sync_service_url", + ): + value = doc.get(key) + if value is None or (isinstance(value, str) and not value.strip()): + return False + return True diff --git a/federation/secrets/registry/.gitkeep b/federation/secrets/registry/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/federation/secrets/registry/README.md b/federation/secrets/registry/README.md new file mode 100644 index 000000000..ef4d0a4ff --- /dev/null +++ b/federation/secrets/registry/README.md @@ -0,0 +1,16 @@ +# Registry signing key (flagship sync only) + +Place the Ed25519 **private** signing key here as `sign.pem` (mode `600` on the host). + +- **Container path:** `/etc/sds/secrets/registry/sign.pem` (see `[registry.publish]` in `federation.toml`) +- **Generate:** `uv run sds-federation-registry keygen --out-dir .` (from `federation/`, writes `sign.pem` and `registry.pub.pem`; place keys per paths below) +- **Migrate from gateway:** copy the same PEM previously mounted at `FEDERATION_REGISTRY_SIGNING_KEY_PATH` on the gateway app container. + +Publish the public key to `federation/certs/sds-registry.pub.pem` (or your site name) and set +`FEDERATION_REGISTRY_PUBKEY_FINGERPRINT` on the sync process: + +```bash +uv run sds-federation-registry fingerprint --public-key-path certs/sds-registry.pub.pem +``` + +This directory is gitignored; never commit `sign.pem`. diff --git a/federation/site.example.env b/federation/site.example.env index b8cc77e4e..39bbf37c9 100644 --- a/federation/site.example.env +++ b/federation/site.example.env @@ -6,3 +6,8 @@ GATEWAY_INTERNAL_BASE_URL="http://sds-gateway-prod-app:18000/api/v1" REDIS_URL="redis://sds-gateway-prod-redis:6379/0" # Optional PEM under federation/certs/ for bootstrap peer TLS FEDERATION_PEER_CA_PATH="" +# Flagship registry signing on sync (omit or false for peer-only hosts) +FEDERATION_REGISTRY_PUBLISH_ENABLED="true" +# Sync env (compose site.env / optional .env.local): well-known registry metadata +# FEDERATION_REGISTRY_WELL_KNOWN_URL=https://sds.crc.nd.edu/.well-known/sds-registry +# FEDERATION_REGISTRY_PUBKEY_FINGERPRINT=sha256:... diff --git a/federation/templates/federation.toml.tmpl b/federation/templates/federation.toml.tmpl index a8c400ebe..d2581964d 100644 --- a/federation/templates/federation.toml.tmpl +++ b/federation/templates/federation.toml.tmpl @@ -2,8 +2,10 @@ name = "${SDS_SITE_NAME}" fqdn = "${SDS_SITE_FQDN}" display_name = "${SDS_SITE_DISPLAY_NAME}" +# gateway_api_base = "https://${SDS_SITE_FQDN}/api/v1" sync_service_url = "${FEDERATION_SYNC_SERVICE_URL}" +${FEDERATION_REGISTRY_PUBLISH_TOML} [[peers]] name = "${FEDERATION_PEER_NAME}" fqdn = "${FEDERATION_PEER_FQDN}" diff --git a/federation/templates/gateway-federation.env.tmpl b/federation/templates/gateway-federation.env.tmpl index 2a67bd693..eb8b4339b 100644 --- a/federation/templates/gateway-federation.env.tmpl +++ b/federation/templates/gateway-federation.env.tmpl @@ -4,8 +4,8 @@ SDS_SITE_FQDN=${SDS_SITE_FQDN} SDS_SITE_DISPLAY_NAME=${SDS_SITE_DISPLAY_NAME} FEDERATION_SYNC_SERVICE_URL=${FEDERATION_SYNC_SERVICE_URL} FEDERATION_SYNC_HEALTH_URL=${FEDERATION_SYNC_HEALTH_URL} +FEDERATION_SYNC_INTERNAL_URL=${FEDERATION_SYNC_INTERNAL_URL} FEDERATION_SYNC_USER_EMAIL=${FEDERATION_SYNC_USER_EMAIL} -# Registry intake UI only when SDS_SITE_FQDN matches FLAGSHIP_GATEWAY_HOST (default CRC). -# Peers: false. CRC flagship: set true in django.env when SDS_SITE_FQDN is sds.crc.nd.edu. +# Registry intake UI (applications DB). Verify/publish run on federation sync — not django. FLAGSHIP_GATEWAY_HOST=sds.crc.nd.edu FEDERATION_REGISTRY_INTAKE_ENABLED=false diff --git a/federation/templates/traefik-sync.toml.tmpl b/federation/templates/traefik-sync.toml.tmpl index f95cf8ba9..06ea39868 100644 --- a/federation/templates/traefik-sync.toml.tmpl +++ b/federation/templates/traefik-sync.toml.tmpl @@ -10,3 +10,12 @@ [[http.services.${TRAEFIK_SYNC_ROUTER_ID}.loadBalancer.servers]] url = "http://${FEDERATION_SYNC_CONTAINER}:8000" + +[http.routers.${TRAEFIK_SYNC_ROUTER_ID}-wellknown] + entryPoints = ["web", "web-secure"] + rule = "Host(`${SDS_SITE_FQDN}`) && (Path(`/.well-known/sds-federation.json`) || PathPrefix(`/.well-known/sds-registry/`))" + service = "${TRAEFIK_SYNC_ROUTER_ID}" + priority = 100 + + [http.routers.${TRAEFIK_SYNC_ROUTER_ID}-wellknown.tls] + certResolver = "letsencrypt" diff --git a/federation/tests/conftest.py b/federation/tests/conftest.py index 0969b1c1d..c91123437 100644 --- a/federation/tests/conftest.py +++ b/federation/tests/conftest.py @@ -31,6 +31,28 @@ PEER_SYNC_BASE = PEER_ONE_SYNC_ORIGIN +def build_registry_root_app(config: FederationConfig) -> FastAPI: + """Root FastAPI app with /sync mount (matches production layout for registry tests).""" + from sds_federation.routes.health import health_router + from sds_federation.routes.internal_registry import internal_registry_router + from sds_federation.routes.sites import sites_router + from sds_federation.routes.webhooks import webhooks_router + from sds_federation.routes.well_known import well_known_router + + sync_app = FastAPI() + sync_app.state.config = config + sync_app.include_router(health_router) + sync_app.include_router(webhooks_router, prefix=API_PREFIX) + sync_app.include_router(sites_router, prefix=API_PREFIX) + + root = FastAPI() + root.state.config = config + root.include_router(well_known_router) + root.include_router(internal_registry_router) + root.mount("/sync", sync_app) + return root + + def make_peer_config(*, site_name: str = "peer-one") -> FederationConfig: """Receiver sync: allows webhooks whose site_name is listed in peers.""" config = peer_one_config() @@ -75,6 +97,13 @@ def test_site_config() -> FederationConfig: return testsite_config() +@pytest.fixture +def admin_token(monkeypatch: pytest.MonkeyPatch) -> str: + token = "test-sync-admin-token" + monkeypatch.setenv("FEDERATION_SYNC_ADMIN_TOKEN", token) + return token + + def seed_federated_dataset_in_opensearch( opensearch: RecordingOpenSearch, site_name: str, diff --git a/federation/tests/test_internal_auth.py b/federation/tests/test_internal_auth.py new file mode 100644 index 000000000..f901941f7 --- /dev/null +++ b/federation/tests/test_internal_auth.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import httpx +import pytest +from sds_federation.services.registry_challenge import hash_registry_challenge_token + +from tests.conftest import build_registry_root_app + + +@pytest.mark.asyncio +async def test_internal_capabilities_requires_bearer( + test_site_config, + admin_token: str, +) -> None: + app = build_registry_root_app(test_site_config) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + unauth = await client.get("/internal/registry/capabilities") + assert unauth.status_code == 401 + wrong = await client.get( + "/internal/registry/capabilities", + headers={"Authorization": "Bearer wrong-token"}, + ) + assert wrong.status_code == 401 + ok = await client.get( + "/internal/registry/capabilities", + headers={"Authorization": f"Bearer {admin_token}"}, + ) + assert ok.status_code == 200 + body = ok.json() + assert body["site_fqdn"] == test_site_config.site.fqdn + assert body["publish_enabled"] is False + + +@pytest.mark.asyncio +async def test_internal_capabilities_503_when_token_unset( + test_site_config, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("FEDERATION_SYNC_ADMIN_TOKEN", raising=False) + app = build_registry_root_app(test_site_config) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + response = await client.get( + "/internal/registry/capabilities", + headers={"Authorization": "Bearer anything"}, + ) + assert response.status_code == 503 + + +@pytest.mark.asyncio +async def test_internal_verify_success( + test_site_config, + admin_token: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from sds_federation.services.well_known import build_site_document + + raw = "verify-me" + monkeypatch.setenv("FEDERATION_REGISTRY_CHALLENGE_TOKEN", raw) + + async def _local_fetch(fqdn: str, config, **_kwargs: object): + return build_site_document(config) + + monkeypatch.setattr( + "sds_federation.routes.internal_registry.fetch_well_known_json", + _local_fetch, + ) + app = build_registry_root_app(test_site_config) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + response = await client.post( + "/internal/registry/verify", + headers={"Authorization": f"Bearer {admin_token}"}, + json={ + "fqdn": "localhost", + "challenge_hash": hash_registry_challenge_token(raw), + }, + ) + assert response.status_code == 200 + body = response.json() + assert body["ok"] is True + assert body["well_known"]["fqdn"] == "localhost" diff --git a/federation/tests/test_internal_mount.py b/federation/tests/test_internal_mount.py new file mode 100644 index 000000000..081422c59 --- /dev/null +++ b/federation/tests/test_internal_mount.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import httpx +import pytest + +from tests.conftest import build_registry_root_app + + +@pytest.mark.asyncio +async def test_internal_paths_not_under_sync_mount( + test_site_config, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("FEDERATION_SYNC_ADMIN_TOKEN", "secret") + app = build_registry_root_app(test_site_config) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + sync_cap = await client.get( + "/sync/internal/registry/capabilities", + headers={"Authorization": "Bearer secret"}, + ) + sync_api = await client.get( + "/sync/api/v1/internal/registry/capabilities", + headers={"Authorization": "Bearer secret"}, + ) + assert sync_cap.status_code == 404 + assert sync_api.status_code == 404 diff --git a/federation/tests/test_registry_challenge.py b/federation/tests/test_registry_challenge.py new file mode 100644 index 000000000..623c4aae9 --- /dev/null +++ b/federation/tests/test_registry_challenge.py @@ -0,0 +1,13 @@ +from sds_federation.services.registry_challenge import challenge_matches +from sds_federation.services.registry_challenge import hash_registry_challenge_token + + +def test_registry_challenge_hash_roundtrip() -> None: + raw = "challenge-token-value" + stored = hash_registry_challenge_token(raw) + assert challenge_matches({"registry_challenge": raw}, stored) + assert not challenge_matches({"registry_challenge": "wrong"}, stored) + + +def test_registry_challenge_missing_field() -> None: + assert not challenge_matches({}, hash_registry_challenge_token("x")) diff --git a/federation/tests/test_registry_publish.py b/federation/tests/test_registry_publish.py new file mode 100644 index 000000000..d96f27024 --- /dev/null +++ b/federation/tests/test_registry_publish.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +import json +from datetime import UTC +from datetime import datetime +from pathlib import Path + +import pytest +from pydantic import AnyHttpUrl +from sds_federation.models import FederationConfig +from sds_federation.models import RegistryPolicy +from sds_federation.models import RegistryPublishPolicy +from sds_federation.models import SiteInfo +from sds_federation.schemas.registry import RegistrySite +from sds_federation.services.registry_publish import publish_manifest +from sds_federation.services.registry_sign import MANIFEST_FILENAME +from sds_federation.services.registry_sign import SERIAL_FILENAME +from sds_federation.services.registry_sign import SIGNATURE_FILENAME +from sds_federation.services.registry_sign import RegistrySignError +from sds_federation.services.registry_sign import verify_manifest_payload +from sds_federation.services.site_registry import _accept + +from tests.test_registry_sign import write_ed25519_keypair + + +def _flagship_config( + tmp_path: Path, + *, + private_path: Path, + enabled: bool = True, +) -> FederationConfig: + manifest_dir = tmp_path / "publish" + return FederationConfig( + site=SiteInfo( + name="crc", + fqdn="sds.crc.nd.edu", + display_name="CRC SDS", + gateway_api_base=AnyHttpUrl("https://sds.crc.nd.edu/api/v1"), + sync_service_url=AnyHttpUrl("https://sds.crc.nd.edu/sync"), + ), + gateway_api_base="https://sds.crc.nd.edu/api/v1", + sync_service_url="https://sds.crc.nd.edu/sync", + peers=[], + registry=RegistryPolicy( + public_key_path=str(tmp_path / "registry.pub.pem"), + cache_dir=str(tmp_path / "cache"), + publish=RegistryPublishPolicy( + enabled=enabled, + signing_key_path=str(private_path), + manifest_dir=str(manifest_dir), + ttl_hours=168, + ), + ), + ) + + +def test_publish_writes_files_and_includes_flagship_and_peer( + tmp_path: Path, +) -> None: + private_path, public_path = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + peer = RegistrySite( + name="peer", + fqdn="peer.example.edu", + display_name="Peer", + gateway_api_base=AnyHttpUrl("https://peer.example.edu/api/v1"), + sync_service_url=AnyHttpUrl("https://peer.example.edu/sync"), + ) + result = publish_manifest(config, [peer], min_serial=None, dry_run=False) + assert result["serial"] == 0 + assert set(result["site_names"]) == {"crc", "peer"} + + manifest_path = Path(config.registry.publish.manifest_dir) / MANIFEST_FILENAME + sig_path = Path(config.registry.publish.manifest_dir) / SIGNATURE_FILENAME + serial_path = Path(config.registry.publish.manifest_dir) / SERIAL_FILENAME + payload = manifest_path.read_bytes() + sig_b64 = sig_path.read_bytes() + verify_manifest_payload(payload, sig_b64, public_path) + assert serial_path.read_text(encoding="utf-8") == "0" + data = json.loads(payload.decode()) + assert data["serial"] == 0 + + +def test_publish_increments_serial(tmp_path: Path) -> None: + private_path, _ = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + first = publish_manifest(config, [], None, dry_run=False) + second = publish_manifest(config, [], None, dry_run=False) + assert first["serial"] == 0 + assert second["serial"] == 1 + + +def test_publish_min_serial_seeding(tmp_path: Path) -> None: + private_path, _ = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + result = publish_manifest(config, [], min_serial=5, dry_run=False) + assert result["serial"] == 5 + + +def test_publish_dry_run_writes_nothing(tmp_path: Path) -> None: + private_path, _ = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + publish_manifest(config, [], None, dry_run=True) + manifest_path = Path(config.registry.publish.manifest_dir) / MANIFEST_FILENAME + assert not manifest_path.is_file() + + +def test_publish_missing_key_raises(tmp_path: Path) -> None: + private_path, _ = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + config.registry.publish.signing_key_path = str(tmp_path / "missing.pem") + with pytest.raises(RegistrySignError, match="not found"): + publish_manifest(config, [], None, dry_run=False) + + +def test_published_manifest_passes_site_registry_accept(tmp_path: Path) -> None: + private_path, _public_path = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + publish_manifest(config, [], None, dry_run=False) + manifest_path = Path(config.registry.publish.manifest_dir) / MANIFEST_FILENAME + sig_path = Path(config.registry.publish.manifest_dir) / SIGNATURE_FILENAME + payload = manifest_path.read_bytes() + import base64 + + signature = base64.b64decode(sig_path.read_bytes().strip(), validate=True) + manifest = _accept( + config.registry, payload, signature, now=datetime(2020, 1, 1, tzinfo=UTC) + ) + assert manifest.serial == 0 + + +def _extra_site(name: str, fqdn: str) -> RegistrySite: + return RegistrySite( + name=name, + fqdn=fqdn, + display_name=name, + gateway_api_base=AnyHttpUrl(f"https://{fqdn}/api/v1"), + sync_service_url=AnyHttpUrl(f"https://{fqdn}/sync"), + ) + + +def test_extra_site_cannot_override_flagship_by_name(tmp_path: Path) -> None: + private_path, _ = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + result = publish_manifest( + config, [_extra_site("crc", "evil.example.edu")], None, dry_run=False + ) + assert result["site_names"] == ["crc"] + manifest_dir = Path(config.registry.publish.manifest_dir) + data = json.loads((manifest_dir / MANIFEST_FILENAME).read_bytes()) + assert data["sites"][0]["fqdn"] == "sds.crc.nd.edu" + + +def test_duplicate_site_names_rejected(tmp_path: Path) -> None: + private_path, _ = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + sites = [_extra_site("dup", "a.example.edu"), _extra_site("dup", "b.example.edu")] + with pytest.raises(ValueError, match="unique names"): + publish_manifest(config, sites, None, dry_run=False) + + +def test_corrupt_serial_file_does_not_roll_back_serial(tmp_path: Path) -> None: + private_path, _ = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + publish_manifest(config, [], min_serial=7, dry_run=False) + manifest_dir = Path(config.registry.publish.manifest_dir) + (manifest_dir / SERIAL_FILENAME).write_text("", encoding="utf-8") + assert publish_manifest(config, [], None, dry_run=False)["serial"] == 8 + + +def test_dry_run_has_no_filesystem_side_effects(tmp_path: Path) -> None: + private_path, _ = write_ed25519_keypair(tmp_path) + config = _flagship_config(tmp_path, private_path=private_path) + result = publish_manifest(config, [], None, dry_run=True) + assert result["dry_run"] is True + assert not Path(config.registry.publish.manifest_dir).exists() diff --git a/federation/tests/test_registry_serve.py b/federation/tests/test_registry_serve.py new file mode 100644 index 000000000..f7848d8d1 --- /dev/null +++ b/federation/tests/test_registry_serve.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from pathlib import Path + +import httpx +import pytest +from sds_federation.models import FederationConfig +from sds_federation.models import RegistryPolicy +from sds_federation.models import RegistryPublishPolicy +from sds_federation.models import SiteInfo +from sds_federation.services.registry_publish import publish_manifest + +from tests.conftest import build_registry_root_app +from tests.test_registry_sign import write_ed25519_keypair + + +def _published_config(tmp_path: Path) -> FederationConfig: + private_path, _ = write_ed25519_keypair(tmp_path) + manifest_dir = tmp_path / "manifest" + config = FederationConfig( + site=SiteInfo( + name="crc", + fqdn="sds.crc.nd.edu", + display_name="CRC", + ), + gateway_api_base="https://sds.crc.nd.edu/api/v1", + sync_service_url="https://sds.crc.nd.edu/sync", + peers=[], + registry=RegistryPolicy( + publish=RegistryPublishPolicy( + enabled=True, + signing_key_path=str(private_path), + manifest_dir=str(manifest_dir), + ), + ), + ) + publish_manifest(config, [], None, dry_run=False) + return config + + +@pytest.mark.asyncio +async def test_registry_manifest_routes_return_bytes(tmp_path: Path) -> None: + config = _published_config(tmp_path) + app = build_registry_root_app(config) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + manifest = await client.get("/.well-known/sds-registry/sites.json") + sig = await client.get("/.well-known/sds-registry/sites.json.sig") + assert manifest.status_code == 200 + assert manifest.headers["cache-control"] == "public, max-age=60" + assert manifest.headers["content-type"].startswith("application/json") + assert sig.status_code == 200 + assert sig.headers["content-type"].startswith("text/plain") + assert len(manifest.content) > 10 + assert len(sig.content) > 10 + + +@pytest.mark.asyncio +async def test_registry_manifest_404_when_publish_disabled(tmp_path: Path) -> None: + config = _published_config(tmp_path) + config.registry.publish.enabled = False + app = build_registry_root_app(config) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + response = await client.get("/.well-known/sds-registry/sites.json") + assert response.status_code == 404 diff --git a/federation/tests/test_registry_sign.py b/federation/tests/test_registry_sign.py new file mode 100644 index 000000000..06fb0fac7 --- /dev/null +++ b/federation/tests/test_registry_sign.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from sds_federation.services.registry_sign import RegistrySignError +from sds_federation.services.registry_sign import canonical_manifest_json_bytes +from sds_federation.services.registry_sign import encode_signature_for_well_known +from sds_federation.services.registry_sign import load_signing_private_key +from sds_federation.services.registry_sign import registry_public_key_fingerprint +from sds_federation.services.registry_sign import sign_manifest_payload +from sds_federation.services.registry_sign import verify_manifest_payload + + +def write_ed25519_keypair(directory: Path) -> tuple[Path, Path]: + private_key = Ed25519PrivateKey.generate() + private_path = directory / "registry-sign.pem" + public_path = directory / "registry.pub.pem" + private_path.write_bytes( + private_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + public_path.write_bytes( + private_key.public_key().public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + ) + return private_path, public_path + + +def test_canonical_manifest_json_is_stable() -> None: + manifest = { + "schema_version": 1, + "serial": 1, + "issued_at": "2026-01-01T00:00:00Z", + "expires_at": "2026-01-08T00:00:00Z", + "sites": [], + } + first = canonical_manifest_json_bytes(manifest) + second = canonical_manifest_json_bytes(manifest) + assert first == second + + +def test_sign_and_verify_round_trip(tmp_path: Path) -> None: + private_path, public_path = write_ed25519_keypair(tmp_path) + payload = canonical_manifest_json_bytes( + {"schema_version": 1, "serial": 0, "sites": []}, + ) + private_key = load_signing_private_key(private_path) + signature = sign_manifest_payload(payload, private_key) + sig_b64 = encode_signature_for_well_known(signature) + verify_manifest_payload(payload, sig_b64, public_path) + + +def test_load_signing_private_key_missing(tmp_path: Path) -> None: + with pytest.raises(RegistrySignError, match="not found"): + load_signing_private_key(tmp_path / "missing.pem") + + +def test_fingerprint_prefix(tmp_path: Path) -> None: + _, public_path = write_ed25519_keypair(tmp_path) + fingerprint = registry_public_key_fingerprint(public_path) + assert fingerprint.startswith("sha256:") diff --git a/gateway/sds_gateway/api_methods/tests/test_registry_verify_fetch.py b/federation/tests/test_registry_verify.py similarity index 57% rename from gateway/sds_gateway/api_methods/tests/test_registry_verify_fetch.py rename to federation/tests/test_registry_verify.py index 190dba370..310793c65 100644 --- a/gateway/sds_gateway/api_methods/tests/test_registry_verify_fetch.py +++ b/federation/tests/test_registry_verify.py @@ -1,3 +1,5 @@ +"""Tests ported from gateway registry verify fetch (SSRF boundary).""" + from __future__ import annotations import socket @@ -5,19 +7,24 @@ from unittest.mock import patch import pytest -from django.test import override_settings - -from sds_gateway.api_methods.federation.registry_verify_fetch import ( - RegistryVerifyFetchError, -) -from sds_gateway.api_methods.federation.registry_verify_fetch import ( - fetch_well_known_json, -) -from sds_gateway.api_methods.federation.registry_verify_fetch import ( +from sds_federation.models import FederationConfig +from sds_federation.models import SiteInfo +from sds_federation.services.registry_verify import RegistryVerifyFetchError +from sds_federation.services.registry_verify import fetch_well_known_json +from sds_federation.services.registry_verify import ( validate_applicant_hostname_for_verify, ) +def _mothership_config() -> FederationConfig: + return FederationConfig( + site=SiteInfo(name="crc", fqdn="sds.crc.nd.edu", display_name="CRC"), + gateway_api_base="https://sds.crc.nd.edu/api/v1", + sync_service_url="https://sds.crc.nd.edu/sync", + peers=[], + ) + + def test_rejects_private_literal_ip() -> None: with pytest.raises(RegistryVerifyFetchError, match="not allowed"): validate_applicant_hostname_for_verify("10.0.0.1") @@ -31,7 +38,7 @@ def test_rejects_loopback_literal_ip() -> None: def test_rejects_private_resolved_ip() -> None: with ( patch( - "sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo", + "sds_federation.services.registry_verify.socket.getaddrinfo", return_value=[ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", 443)), ], @@ -41,13 +48,12 @@ def test_rejects_private_resolved_ip() -> None: validate_applicant_hostname_for_verify("evil.example.edu") -@override_settings(ADMIN_CONSOLE_ENV="production", SDS_SITE_FQDN="sds.crc.nd.edu") @patch( - "sds_gateway.api_methods.federation.registry_verify_fetch._pinned_https_get", - return_value=(200, b'{"fqdn":"public.example.edu"}'), + "sds_federation.services.registry_verify._pinned_https_get", + return_value=b'{"fqdn":"public.example.edu"}', ) @patch( - "sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo", + "sds_federation.services.registry_verify.socket.getaddrinfo", return_value=[ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)), ], @@ -56,28 +62,33 @@ def test_fetch_uses_pinned_https( mock_getaddrinfo: MagicMock, mock_pinned_get: MagicMock, ) -> None: - payload = fetch_well_known_json("public.example.edu") + import asyncio + + config = _mothership_config() + payload = asyncio.run(fetch_well_known_json("public.example.edu", config)) assert payload["fqdn"] == "public.example.edu" mock_pinned_get.assert_called_once() assert mock_pinned_get.call_args.args[2] == ["93.184.216.34"] -@override_settings(ADMIN_CONSOLE_ENV="production", SDS_SITE_FQDN="sds.crc.nd.edu") @patch( - "sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo", + "sds_federation.services.registry_verify.socket.getaddrinfo", ) def test_fetch_dns_rebind_does_not_use_second_resolution( mock_getaddrinfo: MagicMock, ) -> None: + import asyncio + mock_getaddrinfo.return_value = [ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)), ] + config = _mothership_config() with patch( - "sds_gateway.api_methods.federation.registry_verify_fetch._pinned_https_get", - return_value=(200, b'{"fqdn":"public.example.edu"}'), + "sds_federation.services.registry_verify._pinned_https_get", + return_value=b'{"fqdn":"public.example.edu"}', ) as mock_pinned_get: - fetch_well_known_json("public.example.edu") + asyncio.run(fetch_well_known_json("public.example.edu", config)) assert mock_getaddrinfo.call_count == 1 mock_pinned_get.assert_called_once_with( @@ -88,20 +99,22 @@ def test_fetch_dns_rebind_does_not_use_second_resolution( ) -@override_settings(ADMIN_CONSOLE_ENV="production", SDS_SITE_FQDN="sds.crc.nd.edu") @patch( - "sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo", + "sds_federation.services.registry_verify.socket.getaddrinfo", return_value=[ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)), ], ) def test_fetch_error_message_is_generic(mock_getaddrinfo: MagicMock) -> None: + import asyncio + + config = _mothership_config() with ( patch( - "sds_gateway.api_methods.federation.registry_verify_fetch._pinned_https_get", + "sds_federation.services.registry_verify._pinned_https_get", side_effect=OSError("connection refused"), ), pytest.raises(RegistryVerifyFetchError, match="Could not fetch"), ): - fetch_well_known_json("public.example.edu") + asyncio.run(fetch_well_known_json("public.example.edu", config)) assert mock_getaddrinfo.called diff --git a/federation/tests/test_site_registry_accept.py b/federation/tests/test_site_registry_accept.py new file mode 100644 index 000000000..4e098c0d2 --- /dev/null +++ b/federation/tests/test_site_registry_accept.py @@ -0,0 +1,196 @@ +"""Unit tests for registry manifest trust checks (_accept, cache round-trip).""" + +from __future__ import annotations + +import json +from datetime import UTC +from datetime import datetime +from datetime import timedelta +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from sds_federation.models import RegistryPolicy +from sds_federation.schemas.registry import REGISTRY_SCHEMA_VERSION +from sds_federation.services.site_registry import RegistryTrustError +from sds_federation.services.site_registry import _accept +from sds_federation.services.site_registry import _cache +from sds_federation.services.site_registry import load_cached_manifest + + +def _write_ed25519_keypair(directory: Path) -> tuple[Path, Path]: + private_key = Ed25519PrivateKey.generate() + private_path = directory / "registry-sign.pem" + public_path = directory / "registry.pub.pem" + private_path.write_bytes( + private_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + public_path.write_bytes( + private_key.public_key().public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + ) + return private_path, public_path + + +def _manifest_payload( + *, + serial: int, + extra_site: dict | None = None, + issued: datetime | None = None, +) -> bytes: + anchor = issued or datetime.now(UTC) + sites = [ + { + "name": "crc", + "fqdn": "sds.crc.nd.edu", + "display_name": "CRC", + "status": "active", + "gateway_api_base": "https://sds.crc.nd.edu/api/v1", + "sync_service_url": "https://sds.crc.nd.edu/sync", + } + ] + if extra_site: + sites.append(extra_site) + body = { + "schema_version": REGISTRY_SCHEMA_VERSION, + "serial": serial, + "issued_at": anchor.strftime("%Y-%m-%dT%H:%M:%SZ"), + "expires_at": (anchor + timedelta(days=7)).strftime("%Y-%m-%dT%H:%M:%SZ"), + "sites": sites, + } + return json.dumps(body, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def _sign(payload: bytes, private_path: Path) -> bytes: + private_key = serialization.load_pem_private_key( + private_path.read_bytes(), + password=None, + ) + assert isinstance(private_key, Ed25519PrivateKey) + return private_key.sign(payload) + + +def _policy(tmp_path: Path, public_path: Path) -> RegistryPolicy: + cache = tmp_path / "cache" + cache.mkdir() + return RegistryPolicy( + public_key_path=str(public_path), + cache_dir=str(cache), + ) + + +def test_accept_valid_manifest_and_cache_round_trip(tmp_path: Path) -> None: + _, public_path = _write_ed25519_keypair(tmp_path) + private_path = tmp_path / "registry-sign.pem" + policy = _policy(tmp_path, public_path) + payload = _manifest_payload(serial=0) + signature = _sign(payload, private_path) + + manifest = _accept(policy, payload, signature, now=datetime.now(UTC)) + assert manifest.serial == 0 + + _cache(policy, payload, signature, manifest.serial) + restored = load_cached_manifest(policy) + assert restored is not None + assert restored.serial == 0 + + +def test_accept_rejects_serial_rollback(tmp_path: Path) -> None: + _, public_path = _write_ed25519_keypair(tmp_path) + private_path = tmp_path / "registry-sign.pem" + policy = _policy(tmp_path, public_path) + payload0 = _manifest_payload(serial=0) + sig0 = _sign(payload0, private_path) + _cache(policy, payload0, sig0, 0) + + payload1 = _manifest_payload(serial=1) + sig1 = _sign(payload1, private_path) + _accept(policy, payload1, sig1, now=datetime.now(UTC)) + _cache(policy, payload1, sig1, 1) + + with pytest.raises(RegistryTrustError, match="older than accepted"): + _accept(policy, payload0, sig0, now=datetime.now(UTC)) + + +def test_accept_rejects_equal_serial_with_different_bytes(tmp_path: Path) -> None: + _, public_path = _write_ed25519_keypair(tmp_path) + private_path = tmp_path / "registry-sign.pem" + policy = _policy(tmp_path, public_path) + issued = datetime.now(UTC) + payload = _manifest_payload(serial=1, issued=issued) + signature = _sign(payload, private_path) + _cache(policy, payload, signature, 1) + + tampered = _manifest_payload( + serial=1, + issued=issued, + extra_site={ + "name": "fed1", + "fqdn": "fed1.test", + "display_name": "Fed1", + "status": "active", + "gateway_api_base": "https://fed1.test/api/v1", + "sync_service_url": "https://fed1.test/sync", + }, + ) + bad_sig = _sign(tampered, private_path) + check_now = issued + timedelta(hours=1) + + with pytest.raises( + RegistryTrustError, match="reused with different manifest bytes" + ): + _accept(policy, tampered, bad_sig, now=check_now) + + +def test_accept_allows_equal_serial_with_identical_bytes(tmp_path: Path) -> None: + _, public_path = _write_ed25519_keypair(tmp_path) + private_path = tmp_path / "registry-sign.pem" + policy = _policy(tmp_path, public_path) + payload = _manifest_payload(serial=2) + signature = _sign(payload, private_path) + _cache(policy, payload, signature, 2) + + again = _accept(policy, payload, signature, now=datetime.now(UTC)) + assert again.serial == 2 + + +def test_accept_rejects_bad_signature(tmp_path: Path) -> None: + _, public_path = _write_ed25519_keypair(tmp_path) + private_path = tmp_path / "registry-sign.pem" + policy = _policy(tmp_path, public_path) + payload = _manifest_payload(serial=0) + signature = _sign(payload, private_path) + + with pytest.raises(RegistryTrustError, match="signature verification failed"): + _accept(policy, payload + b"x", signature, now=datetime.now(UTC)) + + +def test_accept_rejects_expired_manifest(tmp_path: Path) -> None: + _, public_path = _write_ed25519_keypair(tmp_path) + private_path = tmp_path / "registry-sign.pem" + policy = _policy(tmp_path, public_path) + past = datetime(2020, 1, 1, 0, 0, 0, tzinfo=UTC) + body = { + "schema_version": REGISTRY_SCHEMA_VERSION, + "serial": 0, + "issued_at": past.strftime("%Y-%m-%dT%H:%M:%SZ"), + "expires_at": (past + timedelta(hours=1)).strftime("%Y-%m-%dT%H:%M:%SZ"), + "sites": [], + } + payload = json.dumps(body, sort_keys=True, separators=(",", ":")).encode("utf-8") + signature = _sign(payload, private_path) + + with pytest.raises(RegistryTrustError, match="expired"): + _accept( + policy, + payload, + signature, + now=datetime(2026, 1, 1, tzinfo=UTC), + ) diff --git a/federation/tests/test_well_known_route.py b/federation/tests/test_well_known_route.py new file mode 100644 index 000000000..031a072dd --- /dev/null +++ b/federation/tests/test_well_known_route.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import httpx +import pytest +from sds_federation.models import FederationConfig +from sds_federation.models import SiteInfo + +from tests.conftest import build_registry_root_app + +GATEWAY_WELL_KNOWN_KEYS = frozenset( + { + "schema_version", + "name", + "fqdn", + "display_name", + "gateway_api_base", + "sync_service_url", + "registry_challenge", + "registry_url", + "registry_pubkey_fingerprint", + "contact", + }, +) + + +def _config_with_site(**site_kwargs: object) -> FederationConfig: + site = SiteInfo( + name="fed1", + fqdn="sds-fed1.crc.nd.edu", + display_name="Fed1 test peer", + **site_kwargs, + ) + return FederationConfig( + site=site, + gateway_api_base="http://127.0.0.1:9/api/v1", + sync_service_url="https://sds-fed1.crc.nd.edu/sync", + peers=[], + ) + + +@pytest.mark.asyncio +async def test_well_known_fields_from_site_config() -> None: + config = _config_with_site( + gateway_api_base="https://sds-fed1.crc.nd.edu/api/v1", + sync_service_url="https://sds-fed1.crc.nd.edu/sync", + ) + app = build_registry_root_app(config) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + response = await client.get("/.well-known/sds-federation.json") + assert response.status_code == 200 + assert response.headers.get("cache-control") == "no-store" + doc = response.json() + assert doc["name"] == "fed1" + assert doc["fqdn"] == "sds-fed1.crc.nd.edu" + assert doc["gateway_api_base"] == "https://sds-fed1.crc.nd.edu/api/v1" + assert doc["sync_service_url"] == "https://sds-fed1.crc.nd.edu/sync" + assert "registry_challenge" not in doc + + +@pytest.mark.asyncio +async def test_well_known_includes_challenge_when_env_set( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("FEDERATION_REGISTRY_CHALLENGE_TOKEN", "plain-token") + app = build_registry_root_app(_config_with_site()) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + response = await client.get("/.well-known/sds-federation.json") + assert response.json()["registry_challenge"] == "plain-token" + + +@pytest.mark.asyncio +async def test_well_known_503_when_site_incomplete() -> None: + config = FederationConfig( + site=SiteInfo(name="", fqdn="", display_name=""), + gateway_api_base="http://127.0.0.1:9/api/v1", + sync_service_url="https://example.edu/sync", + peers=[], + ) + app = build_registry_root_app(config) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + response = await client.get("/.well-known/sds-federation.json") + assert response.status_code == 503 + + +@pytest.mark.asyncio +async def test_well_known_key_set_matches_gateway_contract( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("FEDERATION_REGISTRY_CHALLENGE_TOKEN", "t") + monkeypatch.setenv("FEDERATION_REGISTRY_WELL_KNOWN_URL", "https://x/registry") + monkeypatch.setenv("FEDERATION_REGISTRY_PUBKEY_FINGERPRINT", "sha256:abc") + monkeypatch.setenv("SDS_FEDERATION_WELL_KNOWN_CONTACT", "ops@example.edu") + app = build_registry_root_app(_config_with_site()) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + doc = (await client.get("/.well-known/sds-federation.json")).json() + assert set(doc) <= GATEWAY_WELL_KNOWN_KEYS + assert set(doc) >= { + "schema_version", + "name", + "fqdn", + "display_name", + "gateway_api_base", + "sync_service_url", + "registry_challenge", + "registry_url", + "registry_pubkey_fingerprint", + "contact", + } diff --git a/gateway/.envs/example/django.env b/gateway/.envs/example/django.env index 8c2f5f12b..577bf803b 100644 --- a/gateway/.envs/example/django.env +++ b/gateway/.envs/example/django.env @@ -39,10 +39,18 @@ API_KEY= # FEDERATION_REGISTRY_INTAKE_ENABLED=false # CRC flagship production: SDS_SITE_FQDN=sds.crc.nd.edu and FEDERATION_REGISTRY_INTAKE_ENABLED=true # Local lab as mothership (dev only): SDS_SITE_FQDN=sds.localhost, FLAGSHIP_GATEWAY_HOST=sds.localhost, intake true -# Applicant site during domain verify (not mothership): FEDERATION_REGISTRY_CHALLENGE_TOKEN= -# FEDERATION_REGISTRY_VERIFY_FETCH_BASE=http://sds-gateway-local-app:8000 -# FEDERATION_REGISTRY_WELL_KNOWN_URL=https://sds.crc.nd.edu/.well-known/sds-registry -# FEDERATION_REGISTRY_PUBKEY_FINGERPRINT= +# +# Gateway → sync: registry verify UI calls sync internal API (not django verify logic). +# FEDERATION_SYNC_INTERNAL_URL=http://sds-federation-local-sync:8000 +# FEDERATION_SYNC_ADMIN_TOKEN is in repo-root federation-shared.env (compose env_file). +# +# Staff email when an application reaches pending_approval (comma-separated). If unset, +# uses active Django staff users, then ADMINS in settings. +# FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS=sds-admins@example.edu +# FEDERATION_REGISTRY_AUTO_PUBLISH_ON_APPROVE=false +# +# Gateway → sync export/health only (no registry internal API on django): +# FEDERATION_SYNC_HEALTH_URL=http://sds-federation-local-sync:8000/sync/health # AUTH0 # ------------------------------------------------------------------------------ diff --git a/gateway/.envs/example/django.prod-example.env b/gateway/.envs/example/django.prod-example.env index 8a3236542..d6582ef21 100644 --- a/gateway/.envs/example/django.prod-example.env +++ b/gateway/.envs/example/django.prod-example.env @@ -122,8 +122,12 @@ FLAGSHIP_GATEWAY_HOST=sds.crc.nd.edu FEDERATION_REGISTRY_INTAKE_ENABLED=false # CRC production flagship only (with SDS_SITE_FQDN=sds.crc.nd.edu below or in SITE_DOMAIN): # FEDERATION_REGISTRY_INTAKE_ENABLED=true -# FEDERATION_REGISTRY_WELL_KNOWN_URL=https://sds.crc.nd.edu/.well-known/sds-registry -# FEDERATION_REGISTRY_PUBKEY_FINGERPRINT= +# registry_url / pubkey fingerprint / signing key: federation sync (site.env, .env.local) — not django. +# +# Registry verify/publish (gateway UI → sync): +# FEDERATION_SYNC_INTERNAL_URL=http://sds-federation-prod-sync:8000 +# FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS=crc-sds-list@nd.edu +# Applicant challenge token: on applicant sync or gateway — see gateway/docs/federation-registry-verify.md # BRANDING # ------------------------------------------------------------------------------ diff --git a/gateway/.gitignore b/gateway/.gitignore index b3d68f346..2de66d44e 100644 --- a/gateway/.gitignore +++ b/gateway/.gitignore @@ -4,6 +4,7 @@ data/* opensearch/data/* version.json +secrets/* # data dirs data/* diff --git a/gateway/config/settings/base.py b/gateway/config/settings/base.py index f0ab43f70..d71caa1b2 100644 --- a/gateway/config/settings/base.py +++ b/gateway/config/settings/base.py @@ -770,23 +770,13 @@ def _strip_endpoint_scheme(endpoint_url: str) -> str: FEDERATION_SYNC_SERVICE_URL: str = env.str( "FEDERATION_SYNC_SERVICE_URL", default="" ).strip() -FEDERATION_REGISTRY_CHALLENGE_TOKEN: str = env.str( - "FEDERATION_REGISTRY_CHALLENGE_TOKEN", - default="", +# Docker/internal base for sync registry admin API (verify/publish). +# Not the public /sync URL. +FEDERATION_SYNC_INTERNAL_URL: str = env.str( + "FEDERATION_SYNC_INTERNAL_URL", default="" ).strip() -# Local lab: registry verify fetch base when application FQDN == SDS_SITE_FQDN. -# Default http://sds-gateway-local-app:8000. Production uses https://{fqdn}/... -FEDERATION_REGISTRY_VERIFY_FETCH_BASE: str = env.str( - "FEDERATION_REGISTRY_VERIFY_FETCH_BASE", - default="", -).strip() -FEDERATION_REGISTRY_WELL_KNOWN_URL: str = env.str( - "FEDERATION_REGISTRY_WELL_KNOWN_URL", - default="", -).strip() -FEDERATION_REGISTRY_PUBKEY_FINGERPRINT: str = env.str( - "FEDERATION_REGISTRY_PUBKEY_FINGERPRINT", - default="", +FEDERATION_SYNC_ADMIN_TOKEN: str = env.str( + "FEDERATION_SYNC_ADMIN_TOKEN", default="" ).strip() SDS_FEDERATION_WELL_KNOWN_CONTACT: str = env.str( "SDS_FEDERATION_WELL_KNOWN_CONTACT", @@ -804,6 +794,15 @@ def _strip_endpoint_scheme(endpoint_url: str) -> str: flagship_gateway_host=FLAGSHIP_GATEWAY_HOST, intake_requested=env.bool("FEDERATION_REGISTRY_INTAKE_ENABLED", default=False), ) +FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS: list[str] = [ + str(item).strip() + for item in env.list("FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS", default=[]) + if str(item).strip() +] +FEDERATION_REGISTRY_AUTO_PUBLISH_ON_APPROVE: bool = env.bool( + "FEDERATION_REGISTRY_AUTO_PUBLISH_ON_APPROVE", + default=False, +) _federation_events_channel_override: str = env.str( "FEDERATION_EVENTS_CHANNEL", default="", diff --git a/gateway/config/settings/utils.py b/gateway/config/settings/utils.py index 18d66d345..1512a405b 100644 --- a/gateway/config/settings/utils.py +++ b/gateway/config/settings/utils.py @@ -78,6 +78,23 @@ def guess_admin_console_env(*, is_debug: bool) -> str: return "production" +def is_flagship_gateway_deployment( + *, + site_fqdn: str | None = None, + flagship_gateway_host: str | None = None, +) -> bool: + """True when this gateway's public FQDN is the federation mothership.""" + normalized_site = (site_fqdn or os.getenv("SDS_SITE_FQDN", "")).strip().lower() + normalized_flagship = ( + (flagship_gateway_host or os.getenv("FLAGSHIP_GATEWAY_HOST", "sds.crc.nd.edu")) + .strip() + .lower() + ) + if not normalized_site or not normalized_flagship: + return False + return normalized_site == normalized_flagship + + def resolve_federation_registry_intake_enabled( *, site_fqdn: str, @@ -87,8 +104,7 @@ def resolve_federation_registry_intake_enabled( """True only when intake is requested and this deployment is the flagship host.""" if not intake_requested: return False - normalized_site = site_fqdn.strip().lower() - normalized_flagship = flagship_gateway_host.strip().lower() - if not normalized_site or not normalized_flagship: - return False - return normalized_site == normalized_flagship + return is_flagship_gateway_deployment( + site_fqdn=site_fqdn, + flagship_gateway_host=flagship_gateway_host, + ) diff --git a/gateway/config/urls.py b/gateway/config/urls.py index 5d2b565e2..650b95dee 100644 --- a/gateway/config/urls.py +++ b/gateway/config/urls.py @@ -10,19 +10,13 @@ from loguru import logger as log from rest_framework.authtoken.views import obtain_auth_token from rest_framework.permissions import AllowAny -from sds_gateway.api_methods.views.federation_well_known import ( - sds_federation_well_known_view, -) from sds_gateway.users.views import home_page_view from sds_gateway.users.views import spx_dac_dataset_alt_view urlpatterns = [ path("", home_page_view, name="home"), - path( - ".well-known/sds-federation.json", - sds_federation_well_known_view, - name="sds_federation_well_known", - ), + # Site identity + signed registry: federation sync + # (see network/traefik and federation compose). # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # User management diff --git a/gateway/docs/federation-registry-verify.md b/gateway/docs/federation-registry-verify.md index 605a4466e..1ace26901 100644 --- a/gateway/docs/federation-registry-verify.md +++ b/gateway/docs/federation-registry-verify.md @@ -1,7 +1,11 @@ # Federation registry: domain verification -How to apply for federation registry membership on the gateway (mothership intake), -publish a domain-control challenge on the applicant site, and run **Verify domain**. +How to apply for federation registry membership on the mothership, publish a +domain-control challenge on the **applicant sync**, and click **Verify domain** (sync +performs the well-known fetch). + +**Full operator runbook** (flagship setup, staff publish, peer `[registry]` bootstrap): +[`federation/docs/federation-registry-deploy.md`](../../federation/docs/federation-registry-deploy.md). + [Federation registry: domain verification](#federation-registry-domain-verification) + [Overview](#overview) @@ -12,7 +16,7 @@ publish a domain-control challenge on the applicant site, and run **Verify domai + [2. Create a registry application](#2-create-a-registry-application) + [3. Publish the challenge on the applicant site](#3-publish-the-challenge-on-the-applicant-site) + [4. Preflight the well-known document](#4-preflight-the-well-known-document) - + [5. Verify domain](#5-verify-domain) + + [5. Verify domain (UI)](#5-verify-domain-ui) + [Local development](#local-development) + [Automated tests](#automated-tests) + [Troubleshooting](#troubleshooting) @@ -25,36 +29,33 @@ Registry **domain verification** proves that the applicant controls the hostname registered. The mothership gateway: 1. Stores a **hashed** challenge when the user applies (raw token shown once in the UI). -2. On **Verify domain**, fetches `https://{fqdn}/.well-known/sds-federation.json` from - the app container. -3. Checks `registry_challenge` against the stored hash and `fqdn` against the application. -4. On success, sets status to **`pending_approval`** (human approval and signed registry - manifest are separate work). +2. On **Verify domain**, the gateway calls federation sync `POST /internal/registry/verify` + (challenge hash only; sync fetches applicant well-known). +3. On success, status becomes **`pending_approval`** (staff approval and manifest publish are separate). + +Gateway django does **not** fetch well-known JSON, sign manifests, or publish locally. ## Roles | Role | Responsibility | |------|----------------| -| **Mothership** | Logged-in users apply and click **Verify domain** (e.g. CRC gateway). | -| **Applicant** | Serves well-known JSON at the **public FQDN** with the one-time challenge token. | +| **Mothership** | Registry intake UI; applicants click **Verify domain** (gateway → sync internal API). | +| **Applicant** | Serves well-known JSON at the **public FQDN** with the one-time challenge token (via **sync** env). | +| **Staff** | Approve applications; **Publish registry** on the list page (gateway → sync). | -The same physical gateway can be both mothership and applicant (typical for a single-site -lab test). +The same physical host can be mothership gateway + applicant sync (typical lab). ## Prerequisites + **Flagship host only:** `SDS_SITE_FQDN` must equal **`FLAGSHIP_GATEWAY_HOST`** (default `sds.crc.nd.edu`) **and** `FEDERATION_REGISTRY_INTAKE_ENABLED=true`. - Setting the env var on a peer host has no effect — intake stays off. Peer gateways - use `FEDERATION_ENABLED` for sync only. -+ Local lab acting as mothership: align `SDS_SITE_FQDN` with `FLAGSHIP_GATEWAY_HOST` - (e.g. both `sds.localhost` by setting `FLAGSHIP_GATEWAY_HOST=sds.localhost` only on - that dev machine — never on production peers). -+ Gateway running with migration `0022_registry_application` applied. -+ [OAuth (Auth0) setup](./oauth-setup.md) so you can sign in. -+ Applicant **`SDS_SITE_FQDN`** matches the FQDN on the registry application. -+ **HTTPS** on the applicant FQDN, reachable from the **mothership app container** - (see [Local development](#local-development)). ++ Local lab mothership: align `SDS_SITE_FQDN` with `FLAGSHIP_GATEWAY_HOST` + (e.g. both `sds.localhost` on that dev machine only). ++ Gateway migration `0022_registry_application` applied; [OAuth](./oauth-setup.md) for sign-in. ++ Gateway `FEDERATION_SYNC_INTERNAL_URL` (e.g. `http://sds-federation-local-sync:8000`) and + `FEDERATION_SYNC_ADMIN_TOKEN` in `federation-shared.env` (compose loads both on app + sync). ++ Applicant **`SDS_SITE_FQDN`** matches the registry application FQDN. ++ **HTTPS** on the applicant FQDN, reachable from the **sync** container doing verify. ## Step-by-step @@ -67,119 +68,88 @@ cd gateway just up ``` -> On macOS, `generate-secrets.sh` may warn on `chmod --changes`; env files are still -> valid. Use `just up` if the script exits before starting compose. - ### 2. Create a registry application -1. Sign in and open **`/users/federation/registry/`** (or use the user menu link when - `FEDERATION_ENABLED` is true). -2. **New application** — enter **Site FQDN** (hostname only, no `https://`), display - name, and proposed site id. -3. On the detail page, copy the **verification token** (shown **once**; not stored in - the database). +1. Sign in and open **`/users/federation/registry/`**. +2. **New application** — **Site FQDN**, display name, proposed site id. +3. Copy the **verification token** (shown **once**). ### 3. Publish the challenge on the applicant site -On the **applicant** gateway, set in **`gateway/.envs/local/django.env`** (or production -`django.env`): +Set `FEDERATION_REGISTRY_CHALLENGE_TOKEN` on the process that serves +`GET /.well-known/sds-federation.json` at the application **FQDN** — almost always +**federation sync** (`federation/.env.local`, `.env.peer`, or production `site.env`). + +#### Local lab (sync serves well-known) ```bash -FEDERATION_REGISTRY_CHALLENGE_TOKEN= +cd federation +# FEDERATION_REGISTRY_CHALLENGE_TOKEN= in .env.local or env file for compose +docker compose -f compose.local.yaml up -d --force-recreate sds-federation-local-sync ``` -Ensure **`SDS_SITE_FQDN`** equals the application FQDN. +#### Sync-only peer -Recreate the app container so Compose reloads `env_file` ( **`restart` is not enough** ): +See [`federation/env.peer.example`](../../federation/env.peer.example) and +[`federation/docs/peer-remote-test.md`](../../federation/docs/peer-remote-test.md). -```bash -cd gateway -docker compose -f compose.local.yaml up -d --force-recreate sds-gateway-local-app -``` +Do **not** put the applicant token in mothership `django.env` or `federation-shared.env`. -Confirm the variable inside the container: +Confirm inside the serving container: ```bash -docker compose -f compose.local.yaml exec sds-gateway-local-app \ +docker compose -f compose.local.yaml exec sds-federation-local-sync \ printenv FEDERATION_REGISTRY_CHALLENGE_TOKEN ``` -The well-known builder only includes `registry_challenge` when that setting is non-empty -(see `build_sds_federation_document()` in `api_methods/federation/well_known.py`). +Well-known JSON is built in `federation/sds_federation/services/well_known.py` (includes +`registry_challenge` when the env var is set). ### 4. Preflight the well-known document -**HTTP on port 8000** (sanity check only; verify does not use this URL): +From a host that can reach the applicant FQDN (or from sync): ```bash -curl -sS http://localhost:8000/.well-known/sds-federation.json \ +curl -sS "https:///.well-known/sds-federation.json" \ | jq '{fqdn, registry_challenge}' ``` -**HTTPS on the application FQDN** (what verify actually uses — run from the mothership -container): +Expect matching `fqdn` and the same challenge string as in sync env. + +Local sync port (sanity check on loopback): ```bash -docker compose -f compose.local.yaml exec sds-gateway-local-app \ - curl -sS "https:///.well-known/sds-federation.json" \ - | jq '{fqdn, registry_challenge}' +curl -sS http://localhost:8001/.well-known/sds-federation.json | jq '{fqdn, registry_challenge}' ``` -Expect matching `fqdn` and the same challenge string as in `django.env`. - -### 5. Verify domain - -On the mothership UI, open the application detail page and click **Verify domain**. +### 5. Verify domain (UI) -+ **Success:** status **`pending_approval`**, message that the domain is verified. -+ **Failure:** status **`verification_failed`** (retry allowed); see - [Troubleshooting](#troubleshooting). - -## Local development +On the application detail page, click **Verify domain** (applicant only). -Default lab: **`SDS_SITE_FQDN=sds.localhost`**, **`ADMIN_CONSOLE_ENV=local`** (default when -`DJANGO_DEBUG=true`), gateway on **`http://localhost:8000`**. +The gateway calls flagship sync internal verify; sync fetches `https://{fqdn}/.well-known/sds-federation.json`. -### Local verify without Traefik (same gateway) ++ **Success:** status **`pending_approval`**; staff receive HTML email (`templates/emails/registry_application_pending_approval.*`; recipients: `FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS` or active staff / `ADMINS`). ++ **Failure:** status **`verification_failed`**; message on the page — fix well-known and retry. -When **`ADMIN_CONSOLE_ENV` is `local`** and the application **FQDN equals `SDS_SITE_FQDN`**, -verify fetches well-known over **HTTP** from the app container: +Optional manual curl (same API the UI uses): -```text -http://sds-gateway-local-app:8000/.well-known/sds-federation.json +```bash +curl -sS -X POST "http://localhost:8001/internal/registry/verify" \ + -H "Authorization: Bearer $(grep '^FEDERATION_SYNC_ADMIN_TOKEN=' ../federation-shared.env | cut -d= -f2-)" \ + -H "Content-Type: application/json" \ + -d '{"fqdn":"","challenge_hash":""}' ``` -No HTTPS or `/etc/hosts` entry is required for that case. Requirements: - -1. Registry application FQDN = **`sds.localhost`** (or whatever `SDS_SITE_FQDN` is). -2. `FEDERATION_REGISTRY_CHALLENGE_TOKEN` set and app container **recreated** (see step 3). -3. Rebuild/restart the gateway app image so it includes current code. - -Optional override: `FEDERATION_REGISTRY_VERIFY_FETCH_BASE` (e.g. second local gateway -container for `peer.local`). - -### Other FQDNs or production-like verify - -Applications for **other** hostnames still use **`https://{fqdn}/...`** from the -container. Use Traefik ([`network/README.md`](../../network/README.md)), a tunnel, or a -real staging host. +## Local development -### Continue to federation peer E2E +Default lab: **`SDS_SITE_FQDN=sds.localhost`**, gateway **`http://localhost:8000`**, sync +**`http://localhost:8001`**. -Registry **`pending_approval`** is separate from **sync peer** testing. After verify -succeeds (or even if you skip registry for sync-only work): +1. Start gateway + federation sync (`cd federation && just up`). +2. Application FQDN = applicant `SDS_SITE_FQDN` in sync/federation config. +3. Challenge token on **sync**, recreate sync after env edits. -```bash -cd federation -just up # or just deploy-local-peer-2-peer -# see federation/scripts/local_e2e/README.md -just verify-federation-live -``` - -Align `federation.toml` `[site].fqdn` with `SDS_SITE_FQDN` and `FEDERATION_SITE_NAME` -with `django.env`. - -For federation **sync** live tests (export/webhook), see +Registry **`pending_approval`** is separate from sync **peer** E2E; see [`federation/scripts/local_e2e/README.md`](../../federation/scripts/local_e2e/README.md). ## Automated tests @@ -188,73 +158,48 @@ From `gateway/`: ```bash just test-py sds_gateway/api_methods/tests/test_registry_application_verify.py \ + sds_gateway/api_methods/tests/test_federation_sync_client.py \ sds_gateway/api_methods/tests/test_registry_challenge.py \ - sds_gateway/api_methods/tests/test_federation_well_known.py \ + sds_gateway/users/tests/test_registry_application_verify_view.py \ sds_gateway/users/tests/test_registry_application_form.py ``` -Quote the `-k` expression so the shell does not split on `or`: - -```bash -just test-py -k 'registry_application or federation_well_known' -``` +Federation verify engine tests: `federation/tests/test_registry_verify.py`. ## Troubleshooting | Message / behavior | What to check | |------------------|----------------| -| `registry_challenge` is null in JSON | Token not in `django.env`, or container not **recreated** after edit. | -| Challenge mismatch | Token in env ≠ token from apply; re-apply and update env. | -| `fqdn` mismatch | `SDS_SITE_FQDN` and JSON `fqdn` ≠ application FQDN. | -| Challenge expired | Default ~72h; use **Issue new verification token** on the application page. | -| Could not fetch well-known | HTTPS/DNS/TLS from app container to `https:///...`. | +| `registry_challenge` is null in JSON | Token not set on **applicant sync**, or container not **recreated** after edit. | +| Challenge mismatch | Token in env ≠ token from apply; re-apply and update sync env. | +| `fqdn` mismatch | Sync/federation `SDS_SITE_FQDN` and JSON `fqdn` ≠ application FQDN. | +| Challenge expired | Default ~72h; **Issue new verification token** on the application page. | +| Sync verify fetch error | HTTPS/DNS/TLS from **sync** container to `https:///...`. | | Duplicate FQDN | Another open application exists for that hostname. | -**Lost the one-time token:** create a new application (or clear the old row) and set a -new `FEDERATION_REGISTRY_CHALLENGE_TOKEN`. - -## Staff approval - -Requires a user with **`is_staff`** (e.g. `createsuperuser`). - -1. Open **`/users/federation/registry/`** — staff see **all** applications in the list. -2. Open a row with status **`pending_approval`**. -3. On the detail page, use the **Staff review** card: **Approve application** (optional site id) or **Reject application**. - -URL: `/users/federation/registry/applications//`. - -Approval sets status **`approved`** and `site_name`; it does **not** publish the signed registry manifest automatically. - -## Publish signed registry (flagship) - -After one or more applications are **`approved`**, staff publish the manifest: - -1. Set **`FEDERATION_REGISTRY_SIGNING_KEY_PATH`** (Ed25519 private PEM) and optional - **`FEDERATION_REGISTRY_MANIFEST_STORAGE_DIR`** (default: `{BASE_DIR}/registry_manifest`). -2. On **`/users/federation/registry/`**, click **Publish signed registry** (staff, flagship host only), **or** run: - `python manage.py publish_registry_manifest` -3. Peers fetch: - + `/.well-known/sds-registry/sites.json` - + `/.well-known/sds-registry/sites.json.sig` (base64 Ed25519 over the raw JSON bytes) +**Lost the one-time token:** new application (or withdraw old) and set a new challenge on sync. -Publish bumps **`serial`**, writes the files, and moves **`approved`** rows to **`published`**. +## Staff approval and publish -Fingerprint for well-known / peers: `python manage.py registry_pubkey_fingerprint`. +See [federation-registry-deploy.md](../../federation/docs/federation-registry-deploy.md#flagship-staff-workflow) +for approve → **Publish registry** → peer `[registry]` bootstrap. ## Challenge reissue and withdraw -On the application detail page (before staff approval), applicants can: +Applicants (before staff approval): -+ **Issue new verification token** — new `registry_challenge` hash and 72h expiry; token shown once in the modal. -+ **Withdraw application** — releases the FQDN so a new application can be submitted. ++ **Issue new verification token** — new hash and 72h expiry; update sync env with new token. ++ **Withdraw application** — releases the FQDN. ## Not implemented yet + `well_known_path` challenge method (ACME-style path). + DRF API for applications (UI only today). ++ Dry-run publish in the UI (staff CLI/API only today). ## Related docs -+ [Federation README](../../federation/README.md) (peers, well-known, `--discover`) ++ [Federation registry deploy runbook](../../federation/docs/federation-registry-deploy.md) ++ [Federation README](../../federation/README.md) + [Network / Traefik / TLS](../../network/README.md) + [OAuth setup](./oauth-setup.md) diff --git a/gateway/justfile b/gateway/justfile index b9a81f387..bdce3a22c 100644 --- a/gateway/justfile +++ b/gateway/justfile @@ -309,6 +309,20 @@ test *args: just test-js fi +# creates sds-network-local when missing (compose.local declares it external) +[group('setup')] +ensure-local-docker-network: + #!/usr/bin/env bash + set -euo pipefail + if [[ "{{ env }}" != "local" ]]; then + exit 0 + fi + if docker network inspect sds-network-local >/dev/null 2>&1; then + exit 0 + fi + echo "Creating docker network sds-network-local (required by compose.local.yaml)" + docker network create --driver bridge sds-network-local + # ensures federation-shared.env exists (copies from example if missing) [group('qa')] ensure-federation-shared-env: @@ -324,6 +338,7 @@ ensure-federation-shared-env: test-py *args: #!/usr/bin/env bash set -euo pipefail + just ensure-local-docker-network just ensure-federation-shared-env echo "Validating templates" {{ uv_runner }} manage.py validate_templates @@ -348,6 +363,7 @@ test-js *args: up *args: #!/usr/bin/env bash set -euo pipefail + just ensure-local-docker-network echo "Starting sds-gateway in detached mode" echo "Environment: '{{ env }}'" echo "Compose file: '{{ compose_file }}'" diff --git a/gateway/pyproject.toml b/gateway/pyproject.toml index ae1e1dbfa..f0ad9bdb8 100644 --- a/gateway/pyproject.toml +++ b/gateway/pyproject.toml @@ -651,6 +651,7 @@ max-args = 9 [tool.ruff.lint.per-file-ignores] + "**/tests/**" = ["TC003", "PLR2004", "S106"] "sds_gateway/api_methods/tests/test_composite_capture_serialization.py" = [ "PLR2004", ] diff --git a/gateway/scripts/generate-secrets.sh b/gateway/scripts/generate-secrets.sh index 68cfbd1c1..dfbb7cbcf 100755 --- a/gateway/scripts/generate-secrets.sh +++ b/gateway/scripts/generate-secrets.sh @@ -24,6 +24,7 @@ SECONDARY_ACCESS_KEY_ID="" SECONDARY_SECRET_ACCESS_KEY="" FEDERATION_SYNC_DRF_TOKEN="" +FEDERATION_SYNC_ADMIN_TOKEN="" function ensure_federation_sync_drf_token() { local env_type="$1" @@ -37,6 +38,18 @@ function ensure_federation_sync_drf_token() { fi } +function ensure_federation_sync_admin_token() { + local env_type="$1" + if [[ -n "${FEDERATION_SYNC_ADMIN_TOKEN}" ]]; then + return 0 + fi + if [[ "${env_type}" == "ci" ]]; then + FEDERATION_SYNC_ADMIN_TOKEN="ci-federation-sync-admin-token" + else + FEDERATION_SYNC_ADMIN_TOKEN=$(generate_secret 48) + fi +} + function usage() { cat < @@ -191,7 +204,9 @@ function process_env_file() { if [[ "${filename}" == "federation-shared.example.env" ]]; then ensure_federation_sync_drf_token "${env_type}" + ensure_federation_sync_admin_token "${env_type}" content="${content//FEDERATION_SYNC_DRF_TOKEN=/FEDERATION_SYNC_DRF_TOKEN=${FEDERATION_SYNC_DRF_TOKEN}}" + content="${content//FEDERATION_SYNC_ADMIN_TOKEN=/FEDERATION_SYNC_ADMIN_TOKEN=${FEDERATION_SYNC_ADMIN_TOKEN}}" fi if [[ "${filename}" == "storage.env" ]]; then diff --git a/gateway/sds_gateway/api_methods/federation/registry_application_helpers.py b/gateway/sds_gateway/api_methods/federation/registry_application_helpers.py new file mode 100644 index 000000000..d8365a6fc --- /dev/null +++ b/gateway/sds_gateway/api_methods/federation/registry_application_helpers.py @@ -0,0 +1,36 @@ +"""Shared registry application helpers (no sync HTTP).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing import Any + +from sds_gateway.api_methods.models import RegistryApplicationStatus + +if TYPE_CHECKING: + from sds_gateway.api_methods.models import RegistryApplication + +VERIFYABLE_STATUSES = frozenset( + { + RegistryApplicationStatus.PENDING_VERIFICATION.value, + RegistryApplicationStatus.VERIFICATION_FAILED.value, + }, +) + + +def backfill_urls_from_well_known( + application: RegistryApplication, + well_known: dict[str, Any], +) -> list[str]: + updated: list[str] = [] + for field, key in ( + ("gateway_api_base", "gateway_api_base"), + ("sync_service_url", "sync_service_url"), + ): + if getattr(application, field): + continue + value = well_known.get(key) + if isinstance(value, str) and value.strip(): + setattr(application, field, value.strip()) + updated.append(field) + return updated diff --git a/gateway/sds_gateway/api_methods/federation/registry_application_notify.py b/gateway/sds_gateway/api_methods/federation/registry_application_notify.py new file mode 100644 index 000000000..cc13865f5 --- /dev/null +++ b/gateway/sds_gateway/api_methods/federation/registry_application_notify.py @@ -0,0 +1,196 @@ +"""Staff notification when a registry application awaits approval.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing import Any + +from celery import shared_task +from django.conf import settings +from django.db import transaction +from django.urls import reverse +from loguru import logger + +from sds_gateway.api_methods.models import RegistryApplication +from sds_gateway.api_methods.models import RegistryApplicationStatus + +if TYPE_CHECKING: + import uuid + +_PLAIN_TEMPLATE = "emails/registry_application_pending_approval.txt" +_HTML_TEMPLATE = "emails/registry_application_pending_approval.html" + + +def registry_staff_notify_recipients() -> list[str]: + """Explicit env list, else active staff users, else ADMINS.""" + configured = ( + getattr(settings, "FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS", None) or [] + ) + emails = sorted({str(addr).strip() for addr in configured if str(addr).strip()}) + if emails: + return emails + + from sds_gateway.users.models import User + + staff_emails = ( + User.objects.filter(is_staff=True, is_active=True) + .exclude(email="") + .values_list("email", flat=True) + ) + emails = sorted({addr.strip() for addr in staff_emails if str(addr).strip()}) + if emails: + return emails + + return sorted( + {str(addr).strip() for _name, addr in settings.ADMINS if str(addr).strip()} + ) + + +def _application_detail_url(application: RegistryApplication) -> str: + path = reverse( + "users:registry_application_detail", + kwargs={"pk": application.pk}, + ) + site_url = str(getattr(settings, "SITE_URL", "") or "").rstrip("/") + if not site_url: + return path + return f"{site_url}{path}" + + +def _resolved_service_urls( + application: RegistryApplication, +) -> tuple[str, str]: + gateway_api = (application.gateway_api_base or "").strip() + sync_url = (application.sync_service_url or "").strip() + well_known = application.verified_well_known + if isinstance(well_known, dict): + if not gateway_api: + value = well_known.get("gateway_api_base") + if isinstance(value, str): + gateway_api = value.strip() + if not sync_url: + value = well_known.get("sync_service_url") + if isinstance(value, str): + sync_url = value.strip() + return gateway_api, sync_url + + +def build_pending_approval_staff_context( + application: RegistryApplication, +) -> dict[str, Any]: + """Template context for staff pending-approval email.""" + applicant_email = ( + application.contact_email + or getattr(application.contact, "email", "") + or "(unknown)" + ) + proposed = (application.proposed_site_name or "").strip() or "(not set)" + gateway_api, sync_url = _resolved_service_urls(application) + return { + "fqdn": application.fqdn, + "display_name": application.display_name, + "proposed_site_name": proposed, + "applicant_email": applicant_email, + "review_url": _application_detail_url(application), + "gateway_api_base": gateway_api, + "sync_service_url": sync_url, + "site_url": settings.SITE_URL, + "debug": settings.DEBUG, + } + + +def build_pending_approval_staff_email_subject( + application: RegistryApplication, +) -> str: + return ( + f"Federation registry: domain verified — pending approval ({application.fqdn})" + ) + + +def build_pending_approval_staff_email( + application: RegistryApplication, +) -> tuple[str, str]: + """Plain-text body (used in tests and as alt content).""" + ctx = build_pending_approval_staff_context(application) + subject = build_pending_approval_staff_email_subject(application) + lines = [ + ( + "A federation registry application passed domain verification " + "and needs staff review." + ), + "", + f"FQDN: {ctx['fqdn']}", + f"Display name: {ctx['display_name']}", + f"Proposed site id: {ctx['proposed_site_name']}", + f"Applicant email: {ctx['applicant_email']}", + f"Review: {ctx['review_url']}", + ] + if ctx["gateway_api_base"]: + lines.append(f"Gateway API base: {ctx['gateway_api_base']}") + if ctx["sync_service_url"]: + lines.append(f"Sync service URL: {ctx['sync_service_url']}") + lines.extend( + [ + "", + "Approve or reject the application in the gateway registry UI.", + ] + ) + return subject, "\n".join(lines) + + +def schedule_registry_pending_approval_staff_notify( + application_pk: uuid.UUID | str, +) -> None: + """Enqueue staff email after the current DB transaction commits.""" + pk = str(application_pk) + + def _enqueue() -> None: + notify_registry_pending_approval_staff.delay(pk) + + transaction.on_commit(_enqueue) + + +@shared_task +def notify_registry_pending_approval_staff(application_id: str) -> int: + """Send staff email; returns number of recipients mailed.""" + from sds_gateway.api_methods.tasks import send_email + + try: + application = RegistryApplication.objects.select_related("contact").get( + pk=application_id + ) + except RegistryApplication.DoesNotExist: + logger.warning( + "registry staff notify: application {} not found", + application_id, + ) + return 0 + + if application.status != RegistryApplicationStatus.PENDING_APPROVAL.value: + logger.info( + "registry staff notify: skip application {} status={}", + application_id, + application.status, + ) + return 0 + + recipients = registry_staff_notify_recipients() + if not recipients: + logger.warning("registry staff notify: no staff recipients configured") + return 0 + + context = build_pending_approval_staff_context(application) + subject = build_pending_approval_staff_email_subject(application) + send_email( + subject=subject, + recipient_list=recipients, + plain_template=_PLAIN_TEMPLATE, + html_template=_HTML_TEMPLATE, + context=context, + ) + logger.info( + "registry staff notify: mailed {} recipients for {}", + len(recipients), + application.fqdn, + ) + return len(recipients) diff --git a/gateway/sds_gateway/api_methods/federation/registry_application_review.py b/gateway/sds_gateway/api_methods/federation/registry_application_review.py index 9d439248a..019466086 100644 --- a/gateway/sds_gateway/api_methods/federation/registry_application_review.py +++ b/gateway/sds_gateway/api_methods/federation/registry_application_review.py @@ -1,12 +1,17 @@ from __future__ import annotations +import json from dataclasses import dataclass from typing import TYPE_CHECKING +from django.conf import settings from django.utils import timezone -from sds_gateway.api_methods.federation.registry_application_verify import ( - _backfill_urls_from_well_known, +from sds_gateway.api_methods.federation.registry_application_helpers import ( + backfill_urls_from_well_known, +) +from sds_gateway.api_methods.federation.registry_application_staff_ops import ( + publish_registry_manifest, ) from sds_gateway.api_methods.models import RegistryApplication from sds_gateway.api_methods.models import RegistryApplicationStatus @@ -39,6 +44,28 @@ def _resolve_site_name( return site_name +def parse_client_cert_fingerprints(raw: str) -> list[str]: + """Accept JSON array or comma/newline-separated sha256 fingerprints.""" + text = (raw or "").strip() + if not text: + return [] + if text.startswith("["): + try: + parsed = json.loads(text) + except json.JSONDecodeError as exc: + msg = "client_cert_fingerprints must be a JSON array of strings." + raise ValueError(msg) from exc + if not isinstance(parsed, list): + msg = "client_cert_fingerprints must be a JSON array." + raise ValueError(msg) + return [str(item).strip() for item in parsed if str(item).strip()] + separators = [",", "\n"] + for sep in separators: + if sep in text: + return [part.strip() for part in text.split(sep) if part.strip()] + return [text] + + def site_name_taken(site_name: str, *, exclude_pk: str | None = None) -> bool: qs = RegistryApplication.objects.filter( site_name=site_name, @@ -54,6 +81,8 @@ def approve_registry_application( reviewer: User, *, site_name: str | None = None, + ca_cert_file: str | None = None, + client_cert_fingerprints: list[str] | None = None, ) -> ReviewResult: if application.status != _APPROVABLE_STATUS: return ReviewResult( @@ -88,16 +117,28 @@ def approve_registry_application( "rejected_reason", "updated_at", ] + if ca_cert_file is not None: + application.ca_cert_file = ca_cert_file.strip() + update_fields.append("ca_cert_file") + if client_cert_fingerprints is not None: + application.client_cert_fingerprints = client_cert_fingerprints + update_fields.append("client_cert_fingerprints") if application.verified_well_known: update_fields.extend( - _backfill_urls_from_well_known(application, application.verified_well_known) + backfill_urls_from_well_known(application, application.verified_well_known) ) application.save(update_fields=list(dict.fromkeys(update_fields))) - return ReviewResult( - ok=True, - message=f"Approved {application.fqdn} as site '{assigned_name}'.", - ) + message = f"Approved {application.fqdn} as site '{assigned_name}'." + + if getattr(settings, "FEDERATION_REGISTRY_AUTO_PUBLISH_ON_APPROVE", False): + publish = publish_registry_manifest() + if publish.ok: + message = f"{message} {publish.message}" + else: + message = f"{message} Registry publish failed: {publish.message}" + + return ReviewResult(ok=True, message=message) def reject_registry_application( diff --git a/gateway/sds_gateway/api_methods/federation/registry_application_staff_ops.py b/gateway/sds_gateway/api_methods/federation/registry_application_staff_ops.py new file mode 100644 index 000000000..81428007c --- /dev/null +++ b/gateway/sds_gateway/api_methods/federation/registry_application_staff_ops.py @@ -0,0 +1,148 @@ +"""Staff workflow: publish signed registry manifest via federation sync.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from django.core.cache import cache +from django.db import transaction +from django.utils import timezone + +from sds_gateway.api_methods.federation.registry_manifest import ManifestBuildError +from sds_gateway.api_methods.federation.registry_manifest import ( + build_manifest_site_list, +) +from sds_gateway.api_methods.federation.registry_manifest import manifest_min_serial +from sds_gateway.api_methods.federation.registry_manifest import ( + manifest_peer_site_names, +) +from sds_gateway.api_methods.federation.sync_client import FederationSyncClient +from sds_gateway.api_methods.federation.sync_client import SyncUnavailableError +from sds_gateway.api_methods.models import RegistryApplication +from sds_gateway.api_methods.models import RegistryApplicationStatus + +_PUBLISH_ENABLED_CACHE_KEY = "federation_registry_publish_enabled" +_PUBLISH_ENABLED_CACHE_SECS = 30 + +_PUBLISH_DISABLED_MESSAGE = ( + "Registry publish is not enabled on federation sync " + "(signing key or [registry.publish] missing)." +) +_SYNC_UNAVAILABLE_MESSAGE = ( + "Federation sync is unavailable. Try again after sync is healthy." +) + + +@dataclass(frozen=True, slots=True) +class StaffOpResult: + ok: bool + message: str + serial: int | None = None + site_names: tuple[str, ...] = () + + +@dataclass(frozen=True, slots=True) +class StaffPublishUIState: + """Staff list-page publish control (visible vs enabled).""" + + show_controls: bool + publish_enabled: bool + disabled_hint: str + + +def _sync_publish_capabilities(*, force_refresh: bool) -> tuple[bool, str]: + if not force_refresh: + cached = cache.get(_PUBLISH_ENABLED_CACHE_KEY) + if cached is not None: + return bool(cached), "" + disabled_hint = "" + try: + client = FederationSyncClient.from_settings() + payload = client.capabilities() + enabled = bool(payload.get("publish_enabled")) + if not enabled: + disabled_hint = _PUBLISH_DISABLED_MESSAGE + except SyncUnavailableError: + enabled = False + disabled_hint = _SYNC_UNAVAILABLE_MESSAGE + cache.set(_PUBLISH_ENABLED_CACHE_KEY, enabled, _PUBLISH_ENABLED_CACHE_SECS) + return enabled, disabled_hint + + +def registry_sync_publish_enabled(*, force_refresh: bool = False) -> bool: + """Whether flagship sync can sign and publish the registry manifest.""" + enabled, _hint = _sync_publish_capabilities(force_refresh=force_refresh) + return enabled + + +def registry_staff_publish_ui(*, is_staff: bool) -> StaffPublishUIState: + if not is_staff: + return StaffPublishUIState( + show_controls=False, + publish_enabled=False, + disabled_hint="", + ) + enabled, hint = _sync_publish_capabilities(force_refresh=False) + return StaffPublishUIState( + show_controls=True, + publish_enabled=enabled, + disabled_hint=hint, + ) + + +def publish_registry_manifest(*, dry_run: bool = False) -> StaffOpResult: # noqa: PLR0911 + """Build site list from DB, publish on sync, mark approved rows published.""" + if not registry_sync_publish_enabled(force_refresh=True): + return StaffOpResult(ok=False, message=_PUBLISH_DISABLED_MESSAGE) + + try: + sites = build_manifest_site_list() + except ManifestBuildError as exc: + return StaffOpResult(ok=False, message=str(exc)) + + peer_names = manifest_peer_site_names(sites) + if not peer_names: + return StaffOpResult( + ok=False, + message=( + "No approved or published registry applications with a site id. " + "Approve an application before publishing." + ), + ) + + min_serial = manifest_min_serial() + try: + client = FederationSyncClient.from_settings() + payload = client.publish(sites, min_serial=min_serial, dry_run=dry_run) + except SyncUnavailableError as exc: + return StaffOpResult(ok=False, message=str(exc) or _SYNC_UNAVAILABLE_MESSAGE) + + serial = int(payload["serial"]) + names = tuple(str(n) for n in payload.get("site_names") or peer_names) + if dry_run: + name_list = ", ".join(names) if names else "(none)" + return StaffOpResult( + ok=True, + message=f"Dry run: manifest serial would be {serial} ({name_list}).", + serial=serial, + site_names=names, + ) + + now = timezone.now() + with transaction.atomic(): + updated = RegistryApplication.objects.filter(site_name__in=peer_names).update( + status=RegistryApplicationStatus.PUBLISHED.value, + published_manifest_serial=serial, + published_at=now, + ) + if updated == 0: + msg = "Manifest published on sync but no matching applications were updated." + return StaffOpResult(ok=False, message=msg, serial=serial, site_names=names) + + name_list = ", ".join(names) + return StaffOpResult( + ok=True, + message=f"Published registry manifest serial {serial} ({name_list}).", + serial=serial, + site_names=names, + ) diff --git a/gateway/sds_gateway/api_methods/federation/registry_application_verify.py b/gateway/sds_gateway/api_methods/federation/registry_application_verify.py index 162635fbc..209aa992d 100644 --- a/gateway/sds_gateway/api_methods/federation/registry_application_verify.py +++ b/gateway/sds_gateway/api_methods/federation/registry_application_verify.py @@ -1,33 +1,35 @@ +"""Domain verification via federation sync internal API (gateway UI orchestration).""" + from __future__ import annotations from dataclasses import dataclass from typing import Any from django.utils import timezone +from loguru import logger -from sds_gateway.api_methods.federation.registry_challenge import ( - verify_registry_challenge_token, +from sds_gateway.api_methods.federation.registry_application_helpers import ( + VERIFYABLE_STATUSES, ) -from sds_gateway.api_methods.federation.registry_verify_fetch import ( - RegistryVerifyFetchError, +from sds_gateway.api_methods.federation.registry_application_helpers import ( + backfill_urls_from_well_known, ) -from sds_gateway.api_methods.federation.registry_verify_fetch import ( - fetch_well_known_json, +from sds_gateway.api_methods.federation.registry_application_notify import ( + schedule_registry_pending_approval_staff_notify, ) +from sds_gateway.api_methods.federation.sync_client import FederationSyncClient +from sds_gateway.api_methods.federation.sync_client import SyncUnavailableError from sds_gateway.api_methods.models import RegistryApplication from sds_gateway.api_methods.models import RegistryApplicationStatus -_VERIFYABLE_STATUSES = frozenset( - { - RegistryApplicationStatus.PENDING_VERIFICATION.value, - RegistryApplicationStatus.VERIFICATION_FAILED.value, - }, -) - _MAX_ERROR_LENGTH = 2000 -_CHALLENGE_MISMATCH_MESSAGE = ( - "registry_challenge is missing or does not match your verification token." +_SYNC_UNAVAILABLE_MESSAGE = ( + "Domain verification is temporarily unavailable. Please try again later." +) +_VERIFY_SUCCESS_MESSAGE = ( + "Domain verified. Your application is awaiting admin approval." ) +_WELL_KNOWN_NOT_OBJECT_MESSAGE = "Well-known response was not a JSON object." @dataclass(frozen=True, slots=True) @@ -36,40 +38,6 @@ class VerifyResult: message: str -def parse_and_match_challenge(payload: dict[str, Any], stored_hash: str) -> bool: - raw = payload.get("registry_challenge") - if not isinstance(raw, str): - return False - return verify_registry_challenge_token(raw.strip(), stored_hash) - - -def validate_site_identity( - payload: dict[str, Any], application: RegistryApplication -) -> bool: - doc_fqdn = payload.get("fqdn") - if not isinstance(doc_fqdn, str): - return False - return doc_fqdn.strip().lower() == application.fqdn.strip().lower() - - -def _backfill_urls_from_well_known( - application: RegistryApplication, - well_known: dict[str, Any], -) -> list[str]: - updated: list[str] = [] - for field, key in ( - ("gateway_api_base", "gateway_api_base"), - ("sync_service_url", "sync_service_url"), - ): - if getattr(application, field): - continue - value = well_known.get(key) - if isinstance(value, str) and value.strip(): - setattr(application, field, value.strip()) - updated.append(field) - return updated - - def apply_verification_result( application: RegistryApplication, *, @@ -77,6 +45,7 @@ def apply_verification_result( message: str, well_known: dict[str, Any] | None = None, ) -> VerifyResult: + previous_status = application.status update_fields = [ "status", "last_verification_error", @@ -92,19 +61,33 @@ def apply_verification_result( application.last_verification_error = "" update_fields.extend(["verified_at", "verified_well_known"]) if well_known: - update_fields.extend( - _backfill_urls_from_well_known(application, well_known) - ) + update_fields.extend(backfill_urls_from_well_known(application, well_known)) else: application.status = RegistryApplicationStatus.VERIFICATION_FAILED.value application.last_verification_error = message[:_MAX_ERROR_LENGTH] application.save(update_fields=list(dict.fromkeys(update_fields))) + if ok and previous_status != RegistryApplicationStatus.PENDING_APPROVAL.value: + schedule_registry_pending_approval_staff_notify(application.pk) return VerifyResult(ok=ok, message=message) -def verify_registry_application(application: RegistryApplication) -> VerifyResult: - if application.status not in _VERIFYABLE_STATUSES: +def _validate_sync_payload( + payload: dict[str, Any], application: RegistryApplication +) -> tuple[dict[str, Any] | None, str | None]: + """Return ``(well_known, None)`` on success or ``(None, error_message)``.""" + if not payload.get("ok"): + return None, str(payload.get("error") or "Domain verification failed.") + well_known = payload.get("well_known") + if not isinstance(well_known, dict): + return None, _WELL_KNOWN_NOT_OBJECT_MESSAGE + return well_known, None + + +def verify_registry_application( + application: RegistryApplication, +) -> VerifyResult: + if application.status not in VERIFYABLE_STATUSES: return VerifyResult( ok=False, message="This application cannot be verified in its current status.", @@ -119,31 +102,20 @@ def verify_registry_application(application: RegistryApplication) -> VerifyResul fqdn = application.fqdn try: - well_known_json = fetch_well_known_json(fqdn) - except RegistryVerifyFetchError as exc: - return apply_verification_result( - application, - ok=False, - message=str(exc), - ) - - if not parse_and_match_challenge(well_known_json, application.challenge_token_hash): - return apply_verification_result( - application, - ok=False, - message=_CHALLENGE_MISMATCH_MESSAGE, - ) - - if not validate_site_identity(well_known_json, application): - return apply_verification_result( - application, - ok=False, - message="fqdn in well-known JSON does not match this application.", - ) - + client = FederationSyncClient.from_settings() + payload = client.verify_domain(fqdn, application.challenge_token_hash) + except SyncUnavailableError: + # Infrastructure failure: not the applicant's fault, so keep state + # unchanged and do not expose internal config details. + logger.exception("registry verify: federation sync unavailable") + return VerifyResult(ok=False, message=_SYNC_UNAVAILABLE_MESSAGE) + + well_known_json, error = _validate_sync_payload(payload, application) + if error: + return apply_verification_result(application, ok=False, message=error) return apply_verification_result( application, ok=True, - message="Domain verified. Your application is awaiting admin approval.", + message=_VERIFY_SUCCESS_MESSAGE, well_known=well_known_json, ) diff --git a/gateway/sds_gateway/api_methods/federation/registry_challenge.py b/gateway/sds_gateway/api_methods/federation/registry_challenge.py index e73d84f73..2b8d33e30 100644 --- a/gateway/sds_gateway/api_methods/federation/registry_challenge.py +++ b/gateway/sds_gateway/api_methods/federation/registry_challenge.py @@ -1,25 +1,12 @@ -"""Registry domain-verification challenge tokens (generate, hash, verify).""" - -from __future__ import annotations - import hashlib -import hmac import secrets def generate_registry_challenge_token() -> str: - """Return a one-time secret shown to the applicant (not stored in the DB).""" + """Return a URL-safe random token for one-time display to the applicant.""" return secrets.token_urlsafe(32) def hash_registry_challenge_token(raw_token: str) -> str: - """Persisted form of the challenge token.""" + """SHA-256 hex digest stored on RegistryApplication (never store raw token).""" return hashlib.sha256(raw_token.encode("utf-8")).hexdigest() - - -def verify_registry_challenge_token(raw_token: str, stored_hash: str) -> bool: - """Constant-time compare of a candidate token to the stored hash.""" - if not raw_token or not stored_hash: - return False - candidate = hash_registry_challenge_token(raw_token) - return hmac.compare_digest(candidate, stored_hash) diff --git a/gateway/sds_gateway/api_methods/federation/registry_manifest.py b/gateway/sds_gateway/api_methods/federation/registry_manifest.py new file mode 100644 index 000000000..43bfc9b43 --- /dev/null +++ b/gateway/sds_gateway/api_methods/federation/registry_manifest.py @@ -0,0 +1,125 @@ +"""Build signed registry manifest site entries from RegistryApplication rows.""" + +from __future__ import annotations + +from typing import Any + +from sds_gateway.api_methods.models import RegistryApplication +from sds_gateway.api_methods.models import RegistryApplicationStatus + +_PUBLISHABLE_STATUSES = ( + RegistryApplicationStatus.APPROVED.value, + RegistryApplicationStatus.PUBLISHED.value, +) + + +class ManifestBuildError(Exception): + """Site list cannot be built for sync publish.""" + + +def _default_gateway_api_base(fqdn: str) -> str: + return f"https://{fqdn.strip().lower()}/api/v1" + + +def _default_sync_service_url(fqdn: str) -> str: + return f"https://{fqdn.strip().lower()}/sync" + + +def _resolve_service_urls(application: RegistryApplication) -> tuple[str, str]: + gateway = (application.gateway_api_base or "").strip() + sync_url = (application.sync_service_url or "").strip() + well_known = application.verified_well_known + if isinstance(well_known, dict): + if not gateway: + value = well_known.get("gateway_api_base") + if isinstance(value, str) and value.strip(): + gateway = value.strip() + if not sync_url: + value = well_known.get("sync_service_url") + if isinstance(value, str) and value.strip(): + sync_url = value.strip() + fqdn = application.fqdn.strip() + if not gateway: + gateway = _default_gateway_api_base(fqdn) + if not sync_url: + sync_url = _default_sync_service_url(fqdn) + return gateway, sync_url + + +def site_entry_from_application(application: RegistryApplication) -> dict[str, Any]: + """JSON object matching federation sync ``RegistrySite`` (status omitted).""" + site_name = (application.site_name or "").strip() + if not site_name: + msg = f"{application.fqdn}: site id is not set (approve the application first)." + raise ManifestBuildError(msg) + fqdn = (application.fqdn or "").strip() + if not fqdn: + msg = "Registry application is missing FQDN." + raise ManifestBuildError(msg) + display_name = (application.display_name or "").strip() + if not display_name: + msg = f"{site_name}: display name is required." + raise ManifestBuildError(msg) + + gateway_api_base, sync_service_url = _resolve_service_urls(application) + fingerprints = application.client_cert_fingerprints + if fingerprints is None: + fingerprints = [] + elif not isinstance(fingerprints, list): + msg = f"{site_name}: client_cert_fingerprints must be a list." + raise ManifestBuildError(msg) + + return { + "name": site_name, + "fqdn": fqdn, + "display_name": display_name, + "gateway_api_base": gateway_api_base, + "sync_service_url": sync_service_url, + "ca_cert_file": (application.ca_cert_file or "").strip(), + "client_cert_fingerprints": [str(item) for item in fingerprints], + } + + +def build_manifest_site_list() -> list[dict[str, Any]]: + """All approved and published applications for the next manifest snapshot.""" + applications = list( + RegistryApplication.objects.filter( + status__in=_PUBLISHABLE_STATUSES, + ) + .exclude(site_name="") + .order_by("site_name") + ) + entries: list[dict[str, Any]] = [] + seen_names: set[str] = set() + seen_fqdns: set[str] = set() + for application in applications: + entry = site_entry_from_application(application) + name = entry["name"] + fqdn = entry["fqdn"].strip().lower() + if name in seen_names: + msg = f"Duplicate site id '{name}' in registry applications." + raise ManifestBuildError(msg) + if fqdn in seen_fqdns: + msg = f"Duplicate FQDN '{fqdn}' in registry applications." + raise ManifestBuildError(msg) + seen_names.add(name) + seen_fqdns.add(fqdn) + entries.append(entry) + return entries + + +def manifest_min_serial() -> int: + """Lower bound for sync manifest serial from gateway DB.""" + from django.db.models import Max + + agg = RegistryApplication.objects.aggregate( + max_serial=Max("published_manifest_serial") + ) + max_serial = agg["max_serial"] + if max_serial is None: + return 0 + return int(max_serial) + 1 + + +def manifest_peer_site_names(sites: list[dict[str, Any]]) -> list[str]: + return [str(site["name"]) for site in sites] diff --git a/gateway/sds_gateway/api_methods/federation/sync_client.py b/gateway/sds_gateway/api_methods/federation/sync_client.py new file mode 100644 index 000000000..2d32a35de --- /dev/null +++ b/gateway/sds_gateway/api_methods/federation/sync_client.py @@ -0,0 +1,123 @@ +"""HTTP client for federation sync internal registry API.""" + +from __future__ import annotations + +from http import HTTPStatus +from typing import Any + +import requests +from django.conf import settings + + +class SyncUnavailableError(Exception): + """Sync internal registry API is unreachable or returned a server error.""" + + +class FederationSyncClient: + def __init__( + self, + base_url: str, + admin_token: str, + *, + verify_timeout: float = 45.0, + publish_timeout: float = 30.0, + ) -> None: + self._base_url = base_url.rstrip("/") + self._admin_token = admin_token.strip() + self._verify_timeout = verify_timeout + self._publish_timeout = publish_timeout + + @classmethod + def from_settings(cls) -> FederationSyncClient: + base_url = str( + getattr(settings, "FEDERATION_SYNC_INTERNAL_URL", "") or "" + ).strip() + token = str(getattr(settings, "FEDERATION_SYNC_ADMIN_TOKEN", "") or "").strip() + if not base_url: + msg = "FEDERATION_SYNC_INTERNAL_URL is not configured" + raise SyncUnavailableError(msg) + if not token: + msg = "FEDERATION_SYNC_ADMIN_TOKEN is not configured" + raise SyncUnavailableError(msg) + return cls(base_url, token) + + def _headers(self) -> dict[str, str]: + return { + "Authorization": f"Bearer {self._admin_token}", + "Accept": "application/json", + } + + def _request( + self, + method: str, + path: str, + *, + timeout: float, + json_body: dict[str, Any] | None = None, + ) -> dict[str, Any]: + url = f"{self._base_url}{path}" + try: + response = requests.request( + method, + url, + headers=self._headers(), + json=json_body, + timeout=timeout, + ) + except requests.RequestException as exc: + msg = "Federation sync is unavailable." + raise SyncUnavailableError(msg) from exc + if response.status_code == HTTPStatus.SERVICE_UNAVAILABLE: + msg = "Federation sync admin API is not configured." + raise SyncUnavailableError(msg) + if response.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR: + msg = "Federation sync is unavailable." + raise SyncUnavailableError(msg) + if response.status_code == HTTPStatus.UNAUTHORIZED: + msg = "Federation sync rejected the admin token." + raise SyncUnavailableError(msg) + try: + payload = response.json() + except ValueError as exc: + msg = "Federation sync returned an invalid response." + raise SyncUnavailableError(msg) from exc + if not isinstance(payload, dict): + msg = "Federation sync returned an invalid response." + raise SyncUnavailableError(msg) + if response.status_code >= HTTPStatus.BAD_REQUEST and "ok" not in payload: + detail = payload.get("detail") or response.text + raise SyncUnavailableError(str(detail)) + return payload + + def verify_domain(self, fqdn: str, challenge_hash: str) -> dict[str, Any]: + return self._request( + "POST", + "/internal/registry/verify", + timeout=self._verify_timeout, + json_body={"fqdn": fqdn, "challenge_hash": challenge_hash}, + ) + + def capabilities(self) -> dict[str, Any]: + return self._request( + "GET", + "/internal/registry/capabilities", + timeout=self._publish_timeout, + ) + + def publish( + self, + sites: list[dict[str, Any]], + *, + min_serial: int | None = None, + dry_run: bool = False, + ) -> dict[str, Any]: + return self._request( + "POST", + "/internal/registry/publish", + timeout=self._publish_timeout, + json_body={ + "sites": sites, + "min_serial": min_serial, + "dry_run": dry_run, + }, + ) diff --git a/gateway/sds_gateway/api_methods/federation/well_known.py b/gateway/sds_gateway/api_methods/federation/well_known.py deleted file mode 100644 index ad6778bf0..000000000 --- a/gateway/sds_gateway/api_methods/federation/well_known.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Site self-description at /.well-known/sds-federation.json (RFC 8615).""" - -from __future__ import annotations - -from typing import Any - -from django.conf import settings - -SDS_FEDERATION_WELL_KNOWN_SCHEMA_VERSION = 1 -WELL_KNOWN_SDS_FEDERATION_PATH = "/.well-known/sds-federation.json" - -_LOCAL_GATEWAY_HOST = "sds-gateway-local-app" -_LOCAL_SYNC_HOST = "sds-federation-local-sync" - - -def _setting_str(name: str, default: str = "") -> str: - return str(getattr(settings, name, default) or "").strip() - - -def _is_local_federation_lab() -> bool: - """Lab defaults match federation.toml Docker DNS (not public HTTPS).""" - return getattr(settings, "ADMIN_CONSOLE_ENV", "") == "local" - - -def default_public_gateway_api_base(fqdn: str) -> str: - api_version = _setting_str("API_VERSION", "v1") - return f"https://{fqdn}/api/{api_version}" - - -def default_public_sync_service_url(fqdn: str) -> str: - return f"https://{fqdn}/sync/" - - -def default_local_gateway_api_base() -> str: - api_version = _setting_str("API_VERSION", "v1") - return f"http://{_LOCAL_GATEWAY_HOST}:8000/api/{api_version}" - - -def default_local_sync_service_url() -> str: - return f"http://{_LOCAL_SYNC_HOST}:8000/sync" - - -def resolve_gateway_api_base(fqdn: str) -> str: - explicit = _setting_str("FEDERATION_GATEWAY_API_BASE") - if explicit: - return explicit - if _is_local_federation_lab(): - return default_local_gateway_api_base() - return default_public_gateway_api_base(fqdn) if fqdn else "" - - -def resolve_sync_service_url(fqdn: str) -> str: - explicit = _setting_str("FEDERATION_SYNC_SERVICE_URL") - if explicit: - return explicit - if _is_local_federation_lab(): - return default_local_sync_service_url() - return default_public_sync_service_url(fqdn) if fqdn else "" - - -def default_local_well_known_fetch_base() -> str: - """Docker DNS for registry verify in the local lab (same compose stack).""" - return f"http://{_LOCAL_GATEWAY_HOST}:8000" - - -def resolve_well_known_fetch_url(fqdn: str) -> str: - """URL mothership verify uses to fetch an applicant's well-known JSON. - - Production/staging: always ``https://{fqdn}/.well-known/...``. - - Local lab: when the application FQDN matches ``SDS_SITE_FQDN``, fetch over HTTP - from the gateway container (no Traefik/TLS required). Optional - ``FEDERATION_REGISTRY_VERIFY_FETCH_BASE`` overrides that base URL. - """ - normalized = fqdn.strip().lower() - if _is_local_federation_lab(): - site_fqdn = _setting_str("SDS_SITE_FQDN").lower() - if site_fqdn and normalized == site_fqdn: - base = ( - _setting_str("FEDERATION_REGISTRY_VERIFY_FETCH_BASE") - or default_local_well_known_fetch_base() - ) - return f"{base.rstrip('/')}{WELL_KNOWN_SDS_FEDERATION_PATH}" - if not normalized: - return f"https://{normalized}{WELL_KNOWN_SDS_FEDERATION_PATH}" - return f"https://{normalized}{WELL_KNOWN_SDS_FEDERATION_PATH}" - - -def build_sds_federation_document( - *, - registry_challenge: str | None = None, -) -> dict[str, Any]: - """Unsigned federation identity document for this gateway host.""" - fqdn = _setting_str("SDS_SITE_FQDN") - name = _setting_str("FEDERATION_SITE_NAME") - display_name = _setting_str("SDS_SITE_DISPLAY_NAME") or name - - doc: dict[str, Any] = { - "schema_version": SDS_FEDERATION_WELL_KNOWN_SCHEMA_VERSION, - "name": name, - "fqdn": fqdn, - "display_name": display_name, - "gateway_api_base": resolve_gateway_api_base(fqdn), - "sync_service_url": resolve_sync_service_url(fqdn), - } - - challenge = ( - registry_challenge or _setting_str("FEDERATION_REGISTRY_CHALLENGE_TOKEN") - ).strip() - if challenge: - doc["registry_challenge"] = challenge - - registry_url = _setting_str("FEDERATION_REGISTRY_WELL_KNOWN_URL") - if registry_url: - doc["registry_url"] = registry_url - - registry_fingerprint = _setting_str("FEDERATION_REGISTRY_PUBKEY_FINGERPRINT") - if registry_fingerprint: - doc["registry_pubkey_fingerprint"] = registry_fingerprint - - contact = _setting_str("SDS_FEDERATION_WELL_KNOWN_CONTACT") - if contact: - doc["contact"] = contact - - return doc - - -def well_known_document_ready(doc: dict[str, Any]) -> bool: - """Minimum fields required for discovery and domain verification.""" - for key in ( - "schema_version", - "name", - "fqdn", - "display_name", - "gateway_api_base", - "sync_service_url", - ): - value = doc.get(key) - if value is None or (isinstance(value, str) and not value.strip()): - return False - return True diff --git a/gateway/sds_gateway/api_methods/migrations/0024_registry_application_drop_verified_status.py b/gateway/sds_gateway/api_methods/migrations/0024_registry_application_drop_verified_status.py new file mode 100644 index 000000000..2359782b0 --- /dev/null +++ b/gateway/sds_gateway/api_methods/migrations/0024_registry_application_drop_verified_status.py @@ -0,0 +1,35 @@ +"""Drop unused ``verified`` status from unique FQDN constraint.""" + +from django.db import migrations +from django.db import models + + +class Migration(migrations.Migration): + dependencies = [ + ("api_methods", "0023_registry_application_service_urls_charfield"), + ] + + operations = [ + migrations.RemoveConstraint( + model_name="registryapplication", + name="unique_active_registry_application_per_fqdn", + ), + migrations.AddConstraint( + model_name="registryapplication", + constraint=models.UniqueConstraint( + condition=models.Q( + ( + "status__in", + [ + "pending_verification", + "verification_failed", + "pending_approval", + "approved", + ], + ), + ), + fields=("fqdn",), + name="unique_active_registry_application_per_fqdn", + ), + ), + ] diff --git a/gateway/sds_gateway/api_methods/migrations/max_migration.txt b/gateway/sds_gateway/api_methods/migrations/max_migration.txt index 9ab7525b4..035233804 100644 --- a/gateway/sds_gateway/api_methods/migrations/max_migration.txt +++ b/gateway/sds_gateway/api_methods/migrations/max_migration.txt @@ -1 +1 @@ -0023_registry_application_service_urls_charfield +0024_registry_application_drop_verified_status diff --git a/gateway/sds_gateway/api_methods/models.py b/gateway/sds_gateway/api_methods/models.py index db522b018..a249cc461 100644 --- a/gateway/sds_gateway/api_methods/models.py +++ b/gateway/sds_gateway/api_methods/models.py @@ -152,7 +152,6 @@ class RegistryApplicationStatus(StrEnum): PENDING_VERIFICATION = "pending_verification" VERIFICATION_FAILED = "verification_failed" - VERIFIED = "verified" PENDING_APPROVAL = "pending_approval" APPROVED = "approved" REJECTED = "rejected" @@ -1758,7 +1757,6 @@ def _default_registry_challenge_expires_at() -> dt.datetime: REGISTRY_APPLICATION_OPEN_FQDN_STATUSES = ( RegistryApplicationStatus.PENDING_VERIFICATION.value, RegistryApplicationStatus.VERIFICATION_FAILED.value, - RegistryApplicationStatus.VERIFIED.value, RegistryApplicationStatus.PENDING_APPROVAL.value, RegistryApplicationStatus.APPROVED.value, ) diff --git a/gateway/sds_gateway/api_methods/tasks.py b/gateway/sds_gateway/api_methods/tasks.py index 040f00778..da4c48033 100644 --- a/gateway/sds_gateway/api_methods/tasks.py +++ b/gateway/sds_gateway/api_methods/tasks.py @@ -19,6 +19,10 @@ from loguru import logger as log from redis import Redis +# Federation registry tasks (defined in federation package; import registers Celery) +from sds_gateway.api_methods.federation.registry_application_notify import ( # noqa: F401 + notify_registry_pending_approval_staff, +) from sds_gateway.api_methods.models import Capture from sds_gateway.api_methods.models import CaptureType from sds_gateway.api_methods.models import Dataset diff --git a/gateway/sds_gateway/api_methods/tests/test_asset_access_control.py b/gateway/sds_gateway/api_methods/tests/test_asset_access_control.py index 4257aac9c..f67418148 100644 --- a/gateway/sds_gateway/api_methods/tests/test_asset_access_control.py +++ b/gateway/sds_gateway/api_methods/tests/test_asset_access_control.py @@ -31,17 +31,17 @@ def setUp(self): """Set up test data.""" self.owner = User.objects.create_user( email="owner@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="Asset Owner", ) self.viewer = User.objects.create_user( email="viewer@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="Asset Viewer", ) self.other_user = User.objects.create_user( email="other@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="Other User", ) diff --git a/gateway/sds_gateway/api_methods/tests/test_authenticate.py b/gateway/sds_gateway/api_methods/tests/test_authenticate.py index 7a0737720..c580db6f1 100644 --- a/gateway/sds_gateway/api_methods/tests/test_authenticate.py +++ b/gateway/sds_gateway/api_methods/tests/test_authenticate.py @@ -16,7 +16,7 @@ def setUp(self) -> None: """Set up any necessary data or state for the tests.""" self.user = User.objects.create( email="test@example.com", - password="password", # noqa: S106 + password="password", ) self.api_key, self.key = UserAPIKey.objects.create_key( name="test-key", diff --git a/gateway/sds_gateway/api_methods/tests/test_capture_endpoints.py b/gateway/sds_gateway/api_methods/tests/test_capture_endpoints.py index 7a40883c0..a8e2388ec 100644 --- a/gateway/sds_gateway/api_methods/tests/test_capture_endpoints.py +++ b/gateway/sds_gateway/api_methods/tests/test_capture_endpoints.py @@ -94,7 +94,7 @@ def setUp(self) -> None: self._temp_files: list[File] = [] self.user = User.objects.create( email="testuser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, # allows creating API keys ) @@ -961,7 +961,7 @@ def test_retrieve_not_accessible_capture_403(self) -> None: """Test that retrieving a capture not accessible to the user returns 403.""" other_user = User.objects.create( email="otheruser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) other_capture = Capture.objects.create( @@ -1715,7 +1715,7 @@ def test_list_captures_includes_shared_captures(self) -> None: # Create another user other_user = User.objects.create( email="otheruser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) @@ -1766,7 +1766,7 @@ def test_retrieve_shared_capture_200(self) -> None: # Create another user other_user = User.objects.create( email="otheruser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) @@ -1803,7 +1803,7 @@ def test_disabled_share_permission_blocks_access(self) -> None: # Create another user other_user = User.objects.create( email="otheruser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) @@ -1937,12 +1937,12 @@ def test_waterfall_slices_success(self) -> None: assert response.status_code == status.HTTP_200_OK data = response.json() assert "slices" in data - assert len(data["slices"]) == 5 # noqa: PLR2004 - assert data["total_slices"] == 10 # noqa: PLR2004 + assert len(data["slices"]) == 5 + assert data["total_slices"] == 10 assert data["start_index"] == 0 - assert data["end_index"] == 5 # noqa: PLR2004 + assert data["end_index"] == 5 assert "metadata" in data - assert data["metadata"]["total_slices"] == 10 # noqa: PLR2004 + assert data["metadata"]["total_slices"] == 10 # Verify slice indices for i, slice_data in enumerate(data["slices"]): @@ -2110,8 +2110,8 @@ def test_waterfall_slices_end_index_clamping(self) -> None: assert response.status_code == status.HTTP_200_OK data = response.json() - assert data["end_index"] == 5 # noqa: PLR2004 # Clamped to total_slices - assert len(data["slices"]) == 3 # noqa: PLR2004 # Only slices 2, 3, 4 + assert data["end_index"] == 5 # Clamped to total_slices + assert len(data["slices"]) == 3 # Only slices 2, 3, 4 def test_waterfall_slices_custom_processing_type(self) -> None: """Test waterfall_slices with custom processing_type.""" @@ -2152,14 +2152,14 @@ def test_waterfall_slices_custom_processing_type(self) -> None: assert response.status_code == status.HTTP_200_OK data = response.json() - assert len(data["slices"]) == 2 # noqa: PLR2004 + assert len(data["slices"]) == 2 def test_waterfall_slices_other_user_capture(self) -> None: """Test that users cannot access waterfall slices for other users' captures.""" # Create another user other_user = User.objects.create( email="otheruser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) @@ -2302,7 +2302,7 @@ def test_waterfall_slices_stream_other_user_capture(self) -> None: """Test that users cannot access stream endpoint for other users' captures.""" other_user = User.objects.create( email="otherstream@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) other_capture = Capture.objects.create( @@ -2373,10 +2373,10 @@ def test_waterfall_slices_stream_success( assert response.status_code == status.HTTP_200_OK data = response.json() assert "slices" in data - assert len(data["slices"]) == 5 # noqa: PLR2004 - assert data["total_slices"] == 10 # noqa: PLR2004 + assert len(data["slices"]) == 5 + assert data["total_slices"] == 10 assert data["start_index"] == 0 - assert data["end_index"] == 5 # noqa: PLR2004 + assert data["end_index"] == 5 mock_reconstruct_drf_files.assert_called_once() mock_compute_slices_on_demand.assert_called_once() assert stream_file.capture_id == capture.pk @@ -2389,7 +2389,7 @@ def setUp(self) -> None: self.client = APIClient() self.user = User.objects.create( email="storage-error-user@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) _api_key, key = UserAPIKey.objects.create_key( @@ -2456,7 +2456,7 @@ def setUp(self) -> None: self.client = APIClient() self.user = User.objects.create( email="testuser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) _api_key, key = UserAPIKey.objects.create_key( @@ -2541,7 +2541,7 @@ class CaptureBulkMetadataLoadingTests(APITestCase): def setUp(self) -> None: self.user = User.objects.create( email="bulk-test@example.com", - password="testpass123", # noqa: S106 + password="testpass123", is_approved=True, ) api_key, key = UserAPIKey.objects.create_key( @@ -2589,10 +2589,10 @@ def test_set_bulk_metadata_cache_attaches_to_instances(self) -> None: Capture.set_bulk_metadata_cache([cap1, cap2], bulk_meta) - assert cap1._opensearch_metadata_cache["center_frequency"] == 1_000_000_000.0 # noqa: PLR2004,SLF001 - assert cap1._opensearch_metadata_cache["start_time"] == 1_000_000_000 # noqa: PLR2004,SLF001 - assert cap2._opensearch_metadata_cache["center_frequency"] == 2_000_000_000.0 # noqa: PLR2004,SLF001 - assert cap2._opensearch_metadata_cache["start_time"] == 1_000_000_010 # noqa: PLR2004,SLF001 + assert cap1._opensearch_metadata_cache["center_frequency"] == 1_000_000_000.0 # noqa: SLF001 + assert cap1._opensearch_metadata_cache["start_time"] == 1_000_000_000 # noqa: SLF001 + assert cap2._opensearch_metadata_cache["center_frequency"] == 2_000_000_000.0 # noqa: SLF001 + assert cap2._opensearch_metadata_cache["start_time"] == 1_000_000_010 # noqa: SLF001 def test_set_bulk_metadata_cache_handles_missing_uuid(self) -> None: """Missing UUIDs get empty dict, not KeyError.""" @@ -2645,8 +2645,8 @@ def test_get_opensearch_metadata_hits_bulk_cache( # Now call get_opensearch_metadata - should NOT hit OpenSearch meta = cap.get_opensearch_metadata() - assert meta["center_frequency"] == 3_000_000_000.0 # noqa: PLR2004 - assert meta["sample_rate"] == 15_000_000 # noqa: PLR2004 + assert meta["center_frequency"] == 3_000_000_000.0 + assert meta["sample_rate"] == 15_000_000 assert mock_get_client.return_value.search.call_count == 0 @patch( @@ -2774,8 +2774,8 @@ def test_thread_local_cache_hits_with_fresh_instance( # Should hit thread-local cache, not OpenSearch meta = fresh_cap.get_opensearch_metadata() - assert meta["center_frequency"] == 3_000_000_000.0 # noqa: PLR2004 - assert meta["sample_rate"] == 15_000_000 # noqa: PLR2004 + assert meta["center_frequency"] == 3_000_000_000.0 + assert meta["sample_rate"] == 15_000_000 assert mock_get_client.return_value.search.call_count == 0 @patch( @@ -2928,7 +2928,7 @@ class CaptureListWithBulkMetadataTests(APITestCase): def setUp(self) -> None: self.user = User.objects.create( email="bulk-int@example.com", - password="testpass123", # noqa: S106 + password="testpass123", is_approved=True, ) api_key, key = UserAPIKey.objects.create_key( diff --git a/gateway/sds_gateway/api_methods/tests/test_celery_tasks.py b/gateway/sds_gateway/api_methods/tests/test_celery_tasks.py index ee4143370..777f31414 100644 --- a/gateway/sds_gateway/api_methods/tests/test_celery_tasks.py +++ b/gateway/sds_gateway/api_methods/tests/test_celery_tasks.py @@ -73,7 +73,7 @@ def setUp(self): self.user = User.objects.create_user( email="test@example.com", - password="testpass123", # noqa: S106 + password="testpass123", is_approved=True, ) diff --git a/gateway/sds_gateway/api_methods/tests/test_composite_capture_serialization.py b/gateway/sds_gateway/api_methods/tests/test_composite_capture_serialization.py index 1fca6d4c0..32fe0bf4f 100644 --- a/gateway/sds_gateway/api_methods/tests/test_composite_capture_serialization.py +++ b/gateway/sds_gateway/api_methods/tests/test_composite_capture_serialization.py @@ -32,7 +32,7 @@ def _two_drf_captures_same_group() -> tuple[Capture, Capture]: """Two DRF captures sharing ``top_level_dir`` (multi-channel group).""" user = User.objects.create( email="composite-ser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) top = _normalize_top_level_dir("test-composite-serialization-group") diff --git a/gateway/sds_gateway/api_methods/tests/test_federation_hardening.py b/gateway/sds_gateway/api_methods/tests/test_federation_hardening.py index f535018ba..6ee775e2d 100644 --- a/gateway/sds_gateway/api_methods/tests/test_federation_hardening.py +++ b/gateway/sds_gateway/api_methods/tests/test_federation_hardening.py @@ -182,7 +182,7 @@ def test_refresh_sets_settings_flags(self) -> None: class TestFederationExportCidrParsing: def test_parse_cidrs_skips_blank_tokens(self) -> None: networks = _parse_cidrs(["10.0.0.0/8", "", " ", "192.168.0.0/16"]) - assert len(networks) == 2 # noqa: PLR2004 + assert len(networks) == 2 def test_coerce_empty_env_tokens_to_defaults(self) -> None: with patch( diff --git a/gateway/sds_gateway/api_methods/tests/test_federation_sync_client.py b/gateway/sds_gateway/api_methods/tests/test_federation_sync_client.py new file mode 100644 index 000000000..9124e0bb3 --- /dev/null +++ b/gateway/sds_gateway/api_methods/tests/test_federation_sync_client.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +from unittest.mock import MagicMock +from unittest.mock import patch + +import pytest +import requests +from django.test import override_settings + +from sds_gateway.api_methods.federation.sync_client import FederationSyncClient +from sds_gateway.api_methods.federation.sync_client import SyncUnavailableError + +_SYNC_TEST_URL = "http://sync.test:8000" + + +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_verify_returns_ok_payload() -> None: + client = FederationSyncClient.from_settings() + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + "ok": True, + "well_known": {"fqdn": "peer.example.edu"}, + } + with patch( + "sds_gateway.api_methods.federation.sync_client.requests.request", + return_value=mock_response, + ) as mock_req: + data = client.verify_domain("peer.example.edu", "abc123") + assert data["ok"] is True + assert mock_req.call_args.kwargs["json"]["challenge_hash"] == "abc123" + + +@override_settings(FEDERATION_SYNC_INTERNAL_URL="", FEDERATION_SYNC_ADMIN_TOKEN="") +def test_from_settings_requires_url() -> None: + with pytest.raises(SyncUnavailableError): + FederationSyncClient.from_settings() + + +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_connection_error_raises_sync_unavailable() -> None: + client = FederationSyncClient.from_settings() + with ( + patch( + "sds_gateway.api_methods.federation.sync_client.requests.request", + side_effect=requests.ConnectionError("down"), + ), + pytest.raises(SyncUnavailableError, match="unavailable"), + ): + client.verify_domain("peer.example.edu", "abc123") + + +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_capabilities() -> None: + client = FederationSyncClient.from_settings() + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + "publish_enabled": True, + "site_fqdn": "sds.crc.nd.edu", + "key_configured": True, + } + with patch( + "sds_gateway.api_methods.federation.sync_client.requests.request", + return_value=mock_response, + ) as mock_req: + data = client.capabilities() + assert data["publish_enabled"] is True + assert mock_req.call_args.args[0] == "GET" + + +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_publish_posts_sites() -> None: + client = FederationSyncClient.from_settings() + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + "serial": 2, + "issued_at": "2026-01-01T00:00:00Z", + "expires_at": "2026-01-08T00:00:00Z", + "site_names": ["crc", "peer"], + "dry_run": False, + } + sites = [ + { + "name": "peer", + "fqdn": "peer.example.edu", + "display_name": "Peer", + "gateway_api_base": "https://peer.example.edu/api/v1", + "sync_service_url": "https://peer.example.edu/sync", + "ca_cert_file": "", + "client_cert_fingerprints": [], + } + ] + with patch( + "sds_gateway.api_methods.federation.sync_client.requests.request", + return_value=mock_response, + ) as mock_req: + data = client.publish(sites, min_serial=2, dry_run=False) + assert data["serial"] == 2 + body = mock_req.call_args.kwargs["json"] + assert body["min_serial"] == 2 + assert body["sites"] == sites + + +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_503_reports_admin_api_not_configured() -> None: + client = FederationSyncClient.from_settings() + response = MagicMock(status_code=503) + with ( + patch( + "sds_gateway.api_methods.federation.sync_client.requests.request", + return_value=response, + ), + pytest.raises(SyncUnavailableError, match="not configured"), + ): + client.verify_domain("peer.example.edu", "abc123") diff --git a/gateway/sds_gateway/api_methods/tests/test_federation_well_known.py b/gateway/sds_gateway/api_methods/tests/test_federation_well_known.py deleted file mode 100644 index 1beafc698..000000000 --- a/gateway/sds_gateway/api_methods/tests/test_federation_well_known.py +++ /dev/null @@ -1,131 +0,0 @@ -from __future__ import annotations - -import json -from http import HTTPStatus -from typing import TYPE_CHECKING - -import pytest -from django.urls import reverse - -from sds_gateway.api_methods.federation.well_known import build_sds_federation_document -from sds_gateway.api_methods.federation.well_known import resolve_well_known_fetch_url - -if TYPE_CHECKING: - from django.test import Client - - -@pytest.mark.django_db -def test_sds_federation_well_known_endpoint(settings, client: Client) -> None: - settings.ADMIN_CONSOLE_ENV = "production" - settings.SDS_SITE_FQDN = "sds.example.edu" - settings.FEDERATION_SITE_NAME = "example" - settings.SDS_SITE_DISPLAY_NAME = "Example SDS" - settings.API_VERSION = "v1" - # Local compose often sets Docker DNS overrides; derive from FQDN for this case. - settings.FEDERATION_GATEWAY_API_BASE = "" - settings.FEDERATION_SYNC_SERVICE_URL = "" - - response = client.get(reverse("sds_federation_well_known")) - - assert response.status_code == HTTPStatus.OK - payload = json.loads(response.content) - assert payload["fqdn"] == "sds.example.edu" - assert payload["name"] == "example" - assert payload["display_name"] == "Example SDS" - assert payload["gateway_api_base"] == "https://sds.example.edu/api/v1" - assert payload["sync_service_url"] == "https://sds.example.edu/sync/" - assert response.headers["Cache-Control"] == "no-store" - - -@pytest.mark.django_db -def test_sds_federation_well_known_local_lab_defaults(client: Client, settings) -> None: - settings.ADMIN_CONSOLE_ENV = "local" - settings.SDS_SITE_FQDN = "sds.localhost" - settings.FEDERATION_SITE_NAME = "crc" - settings.SDS_SITE_DISPLAY_NAME = "Local CRC" - settings.FEDERATION_GATEWAY_API_BASE = "" - settings.FEDERATION_SYNC_SERVICE_URL = "" - - response = client.get(reverse("sds_federation_well_known")) - - assert response.status_code == HTTPStatus.OK - payload = json.loads(response.content) - assert payload["gateway_api_base"] == "http://sds-gateway-local-app:8000/api/v1" - assert payload["sync_service_url"] == "http://sds-federation-local-sync:8000/sync" - - -@pytest.mark.django_db -def test_sds_federation_well_known_explicit_overrides(client: Client, settings) -> None: - settings.ADMIN_CONSOLE_ENV = "production" - settings.SDS_SITE_FQDN = "sds.example.edu" - settings.FEDERATION_SITE_NAME = "example" - settings.SDS_SITE_DISPLAY_NAME = "Example" - settings.FEDERATION_GATEWAY_API_BASE = "https://custom.example/api/v1" - settings.FEDERATION_SYNC_SERVICE_URL = "https://custom.example/sync/" - - response = client.get(reverse("sds_federation_well_known")) - - payload = json.loads(response.content) - assert payload["gateway_api_base"] == "https://custom.example/api/v1" - assert payload["sync_service_url"] == "https://custom.example/sync/" - - -def test_resolve_well_known_fetch_url_local_self_site(settings) -> None: - settings.ADMIN_CONSOLE_ENV = "local" - settings.SDS_SITE_FQDN = "sds.localhost" - settings.FEDERATION_REGISTRY_VERIFY_FETCH_BASE = "" - - assert ( - resolve_well_known_fetch_url("sds.localhost") - == "http://sds-gateway-local-app:8000/.well-known/sds-federation.json" - ) - assert ( - resolve_well_known_fetch_url("peer.example.edu") - == "https://peer.example.edu/.well-known/sds-federation.json" - ) - - -def test_resolve_well_known_fetch_url_local_fetch_base_override(settings) -> None: - settings.ADMIN_CONSOLE_ENV = "local" - settings.SDS_SITE_FQDN = "sds.localhost" - settings.FEDERATION_REGISTRY_VERIFY_FETCH_BASE = "http://custom-gateway:9000" - - assert ( - resolve_well_known_fetch_url("sds.localhost") - == "http://custom-gateway:9000/.well-known/sds-federation.json" - ) - - -def test_resolve_well_known_fetch_url_production(settings) -> None: - settings.ADMIN_CONSOLE_ENV = "production" - settings.SDS_SITE_FQDN = "sds.example.edu" - - assert ( - resolve_well_known_fetch_url("sds.example.edu") - == "https://sds.example.edu/.well-known/sds-federation.json" - ) - - -def test_build_sds_federation_document_includes_optional_registry_challenge( - settings, -) -> None: - settings.SDS_SITE_FQDN = "sds.crc.nd.edu" - settings.FEDERATION_SITE_NAME = "crc" - settings.FEDERATION_REGISTRY_CHALLENGE_TOKEN = "challenge-token" # noqa: S105 - - doc = build_sds_federation_document() - - assert doc["registry_challenge"] == "challenge-token" - - -@pytest.mark.django_db -def test_sds_federation_well_known_503_when_unconfigured( - client: Client, settings -) -> None: - settings.SDS_SITE_FQDN = "" - settings.FEDERATION_SITE_NAME = "" - settings.SDS_SITE_DISPLAY_NAME = "" - - response = client.get(reverse("sds_federation_well_known")) - - assert response.status_code == HTTPStatus.SERVICE_UNAVAILABLE diff --git a/gateway/sds_gateway/api_methods/tests/test_file_endpoints.py b/gateway/sds_gateway/api_methods/tests/test_file_endpoints.py index afa6218e6..9fd521c05 100644 --- a/gateway/sds_gateway/api_methods/tests/test_file_endpoints.py +++ b/gateway/sds_gateway/api_methods/tests/test_file_endpoints.py @@ -84,7 +84,7 @@ def setUp(self) -> None: self.client = APIClient() self.user = User.objects.create( email="testuser@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, # allows creating API keys ) @@ -159,7 +159,7 @@ def test_retrieve_not_owned_file_403(self) -> None: """A user should not see a file that they do not have access to.""" user_mallory = User.objects.create( email="mallory@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) _, key = UserAPIKey.objects.create_key( @@ -191,7 +191,7 @@ def test_retrieve_latest_file_not_accessible_404(self) -> None: """A user should not see files that they do not have access to.""" user = User.objects.create( email="john-doe@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) _, key = UserAPIKey.objects.create_key( @@ -432,7 +432,7 @@ def test_download_file_no_access_403(self): # Create another user other_user = User.objects.create( email="other@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) @@ -528,7 +528,7 @@ def test_list_files_includes_shared_files(self) -> None: # Create another user other_user = User.objects.create( email="other@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) @@ -586,7 +586,7 @@ def test_retrieve_shared_file_200(self) -> None: # Create another user other_user = User.objects.create( email="other@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) @@ -634,7 +634,7 @@ def test_disabled_share_permission_blocks_file_access(self) -> None: # Create another user other_user = User.objects.create( email="other@example.com", - password="testpassword", # noqa: S106 + password="testpassword", is_approved=True, ) diff --git a/gateway/sds_gateway/api_methods/tests/test_permission_updates.py b/gateway/sds_gateway/api_methods/tests/test_permission_updates.py index dbf8bf6d0..22914667b 100644 --- a/gateway/sds_gateway/api_methods/tests/test_permission_updates.py +++ b/gateway/sds_gateway/api_methods/tests/test_permission_updates.py @@ -29,17 +29,17 @@ def setUp(self): # Create test users self.owner = User.objects.create_user( email="owner@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="Dataset Owner", ) self.user1 = User.objects.create_user( email="user1@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="User One", ) self.user2 = User.objects.create_user( email="user2@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="User Two", ) diff --git a/gateway/sds_gateway/api_methods/tests/test_permissions.py b/gateway/sds_gateway/api_methods/tests/test_permissions.py index 10f0ea241..0bdce79f6 100644 --- a/gateway/sds_gateway/api_methods/tests/test_permissions.py +++ b/gateway/sds_gateway/api_methods/tests/test_permissions.py @@ -21,22 +21,22 @@ def setUp(self): """Set up test data.""" self.owner = User.objects.create_user( email="owner@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="Dataset Owner", ) self.viewer = User.objects.create_user( email="viewer@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="Dataset Viewer", ) self.contributor = User.objects.create_user( email="contributor@example.com", - password="testpass123", # noqa: S106 # noqa: S106 + password="testpass123", name="Dataset Contributor", ) self.co_owner = User.objects.create_user( email="coowner@example.com", - password="testpass123", # noqa: S106 + password="testpass123", name="Dataset Co-Owner", ) diff --git a/gateway/sds_gateway/api_methods/tests/test_registry_application_notify.py b/gateway/sds_gateway/api_methods/tests/test_registry_application_notify.py new file mode 100644 index 000000000..4112318fb --- /dev/null +++ b/gateway/sds_gateway/api_methods/tests/test_registry_application_notify.py @@ -0,0 +1,184 @@ +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from django.core import mail +from django.test import override_settings + +from sds_gateway.api_methods.federation.registry_application_notify import ( + build_pending_approval_staff_context, +) +from sds_gateway.api_methods.federation.registry_application_notify import ( + build_pending_approval_staff_email, +) +from sds_gateway.api_methods.federation.registry_application_notify import ( + notify_registry_pending_approval_staff, +) +from sds_gateway.api_methods.federation.registry_application_notify import ( + registry_staff_notify_recipients, +) +from sds_gateway.api_methods.federation.registry_application_verify import ( + apply_verification_result, +) +from sds_gateway.api_methods.federation.registry_application_verify import ( + verify_registry_application, +) +from sds_gateway.api_methods.federation.registry_challenge import ( + hash_registry_challenge_token, +) +from sds_gateway.api_methods.models import RegistryApplication +from sds_gateway.api_methods.models import RegistryApplicationStatus + +_SYNC_TEST_URL = "http://sync.test:8000" + + +@pytest.mark.django_db +@override_settings(FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS=["notify@example.com"]) +def test_registry_staff_notify_recipients_uses_setting() -> None: + assert registry_staff_notify_recipients() == ["notify@example.com"] + + +@pytest.mark.django_db +@override_settings( + FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS=[], + ADMINS=[("Admin", "fallback@example.com")], +) +def test_registry_staff_notify_recipients_falls_back_to_admins(user) -> None: + assert registry_staff_notify_recipients() == ["fallback@example.com"] + + +@pytest.mark.django_db +@override_settings( + SITE_URL="http://testserver", + EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend", + FEDERATION_REGISTRY_STAFF_NOTIFY_EMAILS=["staff@example.com"], + DEFAULT_FROM_EMAIL="noreply@test", + STATIC_ROOT="", +) +def test_notify_task_sends_email(user) -> None: + application = RegistryApplication.objects.create( + fqdn="peer.example.edu", + display_name="Peer", + contact=user, + contact_email=user.email, + proposed_site_name="peer-id", + gateway_api_base="https://peer.example.edu/api/v1", + sync_service_url="https://peer.example.edu/sync", + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.PENDING_APPROVAL.value, + ) + mailed = notify_registry_pending_approval_staff(str(application.pk)) + assert mailed == 1 + assert len(mail.outbox) == 1 + message = mail.outbox[0] + assert "peer.example.edu" in message.subject + assert "peer-id" in message.body + assert user.email in message.body + assert "/users/federation/registry/applications/" in message.body + + +@pytest.mark.django_db +def test_build_pending_approval_staff_email_includes_urls(user) -> None: + application = RegistryApplication.objects.create( + fqdn="peer.example.edu", + display_name="Peer", + contact=user, + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.PENDING_APPROVAL.value, + verified_well_known={ + "sync_service_url": "https://peer.example.edu/sync", + "gateway_api_base": "https://peer.example.edu/api/v1", + }, + ) + ctx = build_pending_approval_staff_context(application) + assert ctx["sync_service_url"] == "https://peer.example.edu/sync" + _subject, body = build_pending_approval_staff_email(application) + assert "https://peer.example.edu/sync" in body + + +@pytest.mark.django_db +def test_apply_verification_result_schedules_notify_on_transition(user) -> None: + application = RegistryApplication.objects.create( + fqdn="site.example.edu", + display_name="Site", + contact=user, + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.PENDING_VERIFICATION.value, + ) + with patch( + "sds_gateway.api_methods.federation.registry_application_verify." + "schedule_registry_pending_approval_staff_notify", + ) as mock_schedule: + apply_verification_result( + application, + ok=True, + message="ok", + well_known={"fqdn": "site.example.edu"}, + ) + mock_schedule.assert_called_once_with(application.pk) + + +@pytest.mark.django_db +def test_apply_verification_result_skips_notify_on_failure(user) -> None: + application = RegistryApplication.objects.create( + fqdn="site.example.edu", + display_name="Site", + contact=user, + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.PENDING_VERIFICATION.value, + ) + with patch( + "sds_gateway.api_methods.federation.registry_application_verify." + "schedule_registry_pending_approval_staff_notify", + ) as mock_schedule: + apply_verification_result(application, ok=False, message="nope") + mock_schedule.assert_not_called() + + +@pytest.mark.django_db +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_verify_success_schedules_notify(user) -> None: + application = RegistryApplication.objects.create( + fqdn="site.example.edu", + display_name="Site", + contact=user, + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.PENDING_VERIFICATION.value, + ) + with ( + patch( + "sds_gateway.api_methods.federation.registry_application_verify." + "FederationSyncClient.from_settings", + ) as mock_factory, + patch( + "sds_gateway.api_methods.federation.registry_application_verify." + "schedule_registry_pending_approval_staff_notify", + ) as mock_schedule, + ): + mock_factory.return_value.verify_domain.return_value = { + "ok": True, + "well_known": {"fqdn": "site.example.edu"}, + } + verify_registry_application(application) + mock_schedule.assert_called_once_with(application.pk) + + +@pytest.mark.django_db +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_notify_task_skips_when_not_pending_approval(user) -> None: + application = RegistryApplication.objects.create( + fqdn="site.example.edu", + display_name="Site", + contact=user, + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.APPROVED.value, + ) + assert notify_registry_pending_approval_staff(str(application.pk)) == 0 + assert len(mail.outbox) == 0 diff --git a/gateway/sds_gateway/api_methods/tests/test_registry_application_review.py b/gateway/sds_gateway/api_methods/tests/test_registry_application_review.py index e8b723b76..97bfbd0e1 100644 --- a/gateway/sds_gateway/api_methods/tests/test_registry_application_review.py +++ b/gateway/sds_gateway/api_methods/tests/test_registry_application_review.py @@ -1,13 +1,22 @@ from __future__ import annotations +from unittest.mock import patch + import pytest +from django.test import override_settings from sds_gateway.api_methods.federation.registry_application_review import ( approve_registry_application, ) +from sds_gateway.api_methods.federation.registry_application_review import ( + parse_client_cert_fingerprints, +) from sds_gateway.api_methods.federation.registry_application_review import ( reject_registry_application, ) +from sds_gateway.api_methods.federation.registry_application_staff_ops import ( + StaffOpResult, +) from sds_gateway.api_methods.federation.registry_challenge import ( hash_registry_challenge_token, ) @@ -74,6 +83,61 @@ def test_approve_registry_application_rejects_duplicate_site_name(user) -> None: assert application.status == RegistryApplicationStatus.PENDING_APPROVAL.value +def test_parse_client_cert_fingerprints_comma_separated() -> None: + assert parse_client_cert_fingerprints("sha256:a, sha256:b") == [ + "sha256:a", + "sha256:b", + ] + + +@pytest.mark.django_db +def test_approve_stores_ca_and_fingerprints(user) -> None: + application = RegistryApplication.objects.create( + fqdn="site.example.edu", + display_name="Site", + contact=user, + proposed_site_name="mysite", + challenge_token_hash=_REVIEW_HASH_A, + status=RegistryApplicationStatus.PENDING_APPROVAL.value, + ) + user.is_staff = True + user.save(update_fields=["is_staff"]) + result = approve_registry_application( + application, + user, + ca_cert_file="peer-ca.pem", + client_cert_fingerprints=["sha256:abc"], + ) + assert result.ok + application.refresh_from_db() + assert application.ca_cert_file == "peer-ca.pem" + assert application.client_cert_fingerprints == ["sha256:abc"] + + +@pytest.mark.django_db +@override_settings(FEDERATION_REGISTRY_AUTO_PUBLISH_ON_APPROVE=True) +def test_approve_auto_publish_when_enabled(user) -> None: + application = RegistryApplication.objects.create( + fqdn="site.example.edu", + display_name="Site", + contact=user, + proposed_site_name="mysite", + gateway_api_base="https://site.example.edu/api/v1", + sync_service_url="https://site.example.edu/sync", + challenge_token_hash=_REVIEW_HASH_A, + status=RegistryApplicationStatus.PENDING_APPROVAL.value, + ) + user.is_staff = True + user.save(update_fields=["is_staff"]) + with patch( + "sds_gateway.api_methods.federation.registry_application_review.publish_registry_manifest", + return_value=StaffOpResult(ok=True, message="Published serial 1."), + ): + result = approve_registry_application(application, user) + assert result.ok + assert "Published serial 1" in result.message + + @pytest.mark.django_db def test_reject_registry_application(user) -> None: application = RegistryApplication.objects.create( diff --git a/gateway/sds_gateway/api_methods/tests/test_registry_application_staff_ops.py b/gateway/sds_gateway/api_methods/tests/test_registry_application_staff_ops.py new file mode 100644 index 000000000..e9294dff7 --- /dev/null +++ b/gateway/sds_gateway/api_methods/tests/test_registry_application_staff_ops.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from django.core.cache import cache + +from sds_gateway.api_methods.federation.registry_application_staff_ops import ( + publish_registry_manifest, +) +from sds_gateway.api_methods.federation.registry_challenge import ( + hash_registry_challenge_token, +) +from sds_gateway.api_methods.federation.sync_client import SyncUnavailableError +from sds_gateway.api_methods.models import RegistryApplication +from sds_gateway.api_methods.models import RegistryApplicationStatus + +_MANIFEST_SERIAL = 5 + + +@pytest.mark.django_db +def test_publish_registry_manifest_marks_approved_published(user, settings) -> None: + settings.FEDERATION_SYNC_INTERNAL_URL = "http://sync.test:8000" + settings.FEDERATION_SYNC_ADMIN_TOKEN = "test-sync-admin-token" # noqa: S105 + cache.clear() + + published = RegistryApplication.objects.create( + fqdn="old.example.edu", + display_name="Old", + contact=user, + site_name="old", + gateway_api_base="https://old.example.edu/api/v1", + sync_service_url="https://old.example.edu/sync", + challenge_token_hash=hash_registry_challenge_token("o"), + status=RegistryApplicationStatus.PUBLISHED.value, + published_manifest_serial=2, + ) + approved = RegistryApplication.objects.create( + fqdn="peer.example.edu", + display_name="Peer", + contact=user, + site_name="peer", + gateway_api_base="https://peer.example.edu/api/v1", + sync_service_url="https://peer.example.edu/sync", + challenge_token_hash=hash_registry_challenge_token("p"), + status=RegistryApplicationStatus.APPROVED.value, + ) + + with ( + patch( + "sds_gateway.api_methods.federation.registry_application_staff_ops." + "FederationSyncClient.from_settings" + ) as mock_from_settings, + patch( + "sds_gateway.api_methods.federation.registry_application_staff_ops." + "registry_sync_publish_enabled", + return_value=True, + ), + ): + client = mock_from_settings.return_value + client.publish.return_value = { + "serial": _MANIFEST_SERIAL, + "site_names": ["crc", "old", "peer"], + } + result = publish_registry_manifest() + + assert result.ok + assert result.serial == _MANIFEST_SERIAL + approved.refresh_from_db() + published.refresh_from_db() + assert approved.status == RegistryApplicationStatus.PUBLISHED.value + assert approved.published_manifest_serial == _MANIFEST_SERIAL + assert published.published_manifest_serial == _MANIFEST_SERIAL + call = client.publish.call_args + assert call.kwargs["min_serial"] == 3 + sites = call.args[0] + assert {s["name"] for s in sites} == {"old", "peer"} + + +@pytest.mark.django_db +def test_publish_registry_manifest_skips_pending(user) -> None: + with ( + patch( + "sds_gateway.api_methods.federation.registry_application_staff_ops." + "registry_sync_publish_enabled", + return_value=True, + ), + patch( + "sds_gateway.api_methods.federation.registry_application_staff_ops." + "FederationSyncClient.from_settings", + ), + ): + result = publish_registry_manifest() + assert not result.ok + assert "Approve" in result.message + + +@pytest.mark.django_db +def test_publish_registry_manifest_sync_unavailable(user) -> None: + RegistryApplication.objects.create( + fqdn="peer.example.edu", + display_name="Peer", + contact=user, + site_name="peer", + gateway_api_base="https://peer.example.edu/api/v1", + sync_service_url="https://peer.example.edu/sync", + challenge_token_hash=hash_registry_challenge_token("p"), + status=RegistryApplicationStatus.APPROVED.value, + ) + with ( + patch( + "sds_gateway.api_methods.federation.registry_application_staff_ops." + "registry_sync_publish_enabled", + return_value=True, + ), + patch( + "sds_gateway.api_methods.federation.registry_application_staff_ops." + "FederationSyncClient.from_settings" + ) as mock_from_settings, + ): + mock_from_settings.return_value.publish.side_effect = SyncUnavailableError( + "down" + ) + result = publish_registry_manifest() + assert not result.ok diff --git a/gateway/sds_gateway/api_methods/tests/test_registry_application_verify.py b/gateway/sds_gateway/api_methods/tests/test_registry_application_verify.py index ba1d172e1..8cc2971e1 100644 --- a/gateway/sds_gateway/api_methods/tests/test_registry_application_verify.py +++ b/gateway/sds_gateway/api_methods/tests/test_registry_application_verify.py @@ -3,6 +3,7 @@ from unittest.mock import patch import pytest +from django.test import override_settings from django.utils import timezone from sds_gateway.api_methods.federation.registry_application_verify import ( @@ -11,11 +12,18 @@ from sds_gateway.api_methods.federation.registry_challenge import ( hash_registry_challenge_token, ) +from sds_gateway.api_methods.federation.sync_client import SyncUnavailableError from sds_gateway.api_methods.models import RegistryApplication from sds_gateway.api_methods.models import RegistryApplicationStatus +_SYNC_TEST_URL = "http://sync.test:8000" + @pytest.mark.django_db +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) def test_verify_registry_application_success(user) -> None: raw = "test-challenge-token-value" application = RegistryApplication.objects.create( @@ -32,9 +40,13 @@ def test_verify_registry_application_success(user) -> None: "sync_service_url": "https://site.example.edu/sync", } with patch( - "sds_gateway.api_methods.federation.registry_application_verify.fetch_well_known_json", - return_value=well_known, - ): + "sds_gateway.api_methods.federation.registry_application_verify.FederationSyncClient.from_settings", + ) as mock_factory: + mock_client = mock_factory.return_value + mock_client.verify_domain.return_value = { + "ok": True, + "well_known": well_known, + } result = verify_registry_application(application) assert result.ok @@ -43,14 +55,18 @@ def test_verify_registry_application_success(user) -> None: assert application.verified_well_known == well_known assert application.gateway_api_base == "https://site.example.edu/api/v1" assert application.verification_attempts == 1 + mock_client.verify_domain.assert_called_once_with( + "site.example.edu", + application.challenge_token_hash, + ) @pytest.mark.django_db -def test_verify_fetch_failure_stores_generic_message(user) -> None: - from sds_gateway.api_methods.federation.registry_verify_fetch import ( - RegistryVerifyFetchError, - ) - +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_verify_sync_unavailable(user) -> None: application = RegistryApplication.objects.create( fqdn="site.example.edu", display_name="Site", @@ -59,36 +75,44 @@ def test_verify_fetch_failure_stores_generic_message(user) -> None: status=RegistryApplicationStatus.PENDING_VERIFICATION.value, ) with patch( - "sds_gateway.api_methods.federation.registry_application_verify.fetch_well_known_json", - side_effect=RegistryVerifyFetchError("Could not fetch well-known JSON."), + "sds_gateway.api_methods.federation.registry_application_verify.FederationSyncClient.from_settings", + side_effect=SyncUnavailableError("Federation sync is unavailable."), ): result = verify_registry_application(application) assert not result.ok application.refresh_from_db() - assert application.last_verification_error == "Could not fetch well-known JSON." - assert "Traceback" not in application.last_verification_error + assert application.status == RegistryApplicationStatus.PENDING_VERIFICATION.value + assert application.verification_attempts == 0 + assert "unavailable" in result.message.lower() @pytest.mark.django_db -def test_verify_registry_application_wrong_challenge(user) -> None: +@override_settings( + FEDERATION_SYNC_INTERNAL_URL=_SYNC_TEST_URL, + FEDERATION_SYNC_ADMIN_TOKEN="admin-token", +) +def test_verify_sync_returns_error(user) -> None: application = RegistryApplication.objects.create( fqdn="site.example.edu", display_name="Site", contact=user, - challenge_token_hash=hash_registry_challenge_token("correct"), + challenge_token_hash=hash_registry_challenge_token("token"), status=RegistryApplicationStatus.PENDING_VERIFICATION.value, ) with patch( - "sds_gateway.api_methods.federation.registry_application_verify.fetch_well_known_json", - return_value={"fqdn": "site.example.edu", "registry_challenge": "wrong"}, - ): + "sds_gateway.api_methods.federation.registry_application_verify.FederationSyncClient.from_settings", + ) as mock_factory: + mock_client = mock_factory.return_value + mock_client.verify_domain.return_value = { + "ok": False, + "error": "Could not fetch well-known JSON.", + } result = verify_registry_application(application) assert not result.ok application.refresh_from_db() - assert application.status == RegistryApplicationStatus.VERIFICATION_FAILED.value - assert application.last_verification_error + assert application.last_verification_error == "Could not fetch well-known JSON." @pytest.mark.django_db diff --git a/gateway/sds_gateway/api_methods/tests/test_registry_challenge.py b/gateway/sds_gateway/api_methods/tests/test_registry_challenge.py index 26afab3f1..6793dd5a3 100644 --- a/gateway/sds_gateway/api_methods/tests/test_registry_challenge.py +++ b/gateway/sds_gateway/api_methods/tests/test_registry_challenge.py @@ -4,13 +4,14 @@ from sds_gateway.api_methods.federation.registry_challenge import ( hash_registry_challenge_token, ) -from sds_gateway.api_methods.federation.registry_challenge import ( - verify_registry_challenge_token, -) -def test_registry_challenge_hash_roundtrip() -> None: +def test_hash_is_deterministic() -> None: raw = generate_registry_challenge_token() - stored = hash_registry_challenge_token(raw) - assert verify_registry_challenge_token(raw, stored) - assert not verify_registry_challenge_token("wrong", stored) + assert hash_registry_challenge_token(raw) == hash_registry_challenge_token(raw) + + +def test_hash_differs_for_different_tokens() -> None: + a = generate_registry_challenge_token() + b = generate_registry_challenge_token() + assert hash_registry_challenge_token(a) != hash_registry_challenge_token(b) diff --git a/gateway/sds_gateway/api_methods/tests/test_registry_manifest.py b/gateway/sds_gateway/api_methods/tests/test_registry_manifest.py new file mode 100644 index 000000000..d5b65e450 --- /dev/null +++ b/gateway/sds_gateway/api_methods/tests/test_registry_manifest.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import pytest + +from sds_gateway.api_methods.federation.registry_challenge import ( + hash_registry_challenge_token, +) +from sds_gateway.api_methods.federation.registry_manifest import ManifestBuildError +from sds_gateway.api_methods.federation.registry_manifest import ( + build_manifest_site_list, +) +from sds_gateway.api_methods.federation.registry_manifest import manifest_min_serial +from sds_gateway.api_methods.federation.registry_manifest import ( + site_entry_from_application, +) +from sds_gateway.api_methods.models import RegistryApplication +from sds_gateway.api_methods.models import RegistryApplicationStatus + + +@pytest.mark.django_db +def test_site_entry_from_application_uses_urls_and_certs(user) -> None: + application = RegistryApplication.objects.create( + fqdn="peer.example.edu", + display_name="Peer Site", + contact=user, + site_name="peer", + gateway_api_base="https://peer.example.edu/api/v1", + sync_service_url="https://peer.example.edu/sync", + ca_cert_file="peer-ca.pem", + client_cert_fingerprints=["sha256:abc"], + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.APPROVED.value, + ) + entry = site_entry_from_application(application) + assert entry["name"] == "peer" + assert entry["fqdn"] == "peer.example.edu" + assert entry["ca_cert_file"] == "peer-ca.pem" + assert entry["client_cert_fingerprints"] == ["sha256:abc"] + + +@pytest.mark.django_db +def test_site_entry_defaults_urls_from_fqdn(user) -> None: + application = RegistryApplication.objects.create( + fqdn="peer.example.edu", + display_name="Peer", + contact=user, + site_name="peer", + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.APPROVED.value, + verified_well_known={ + "fqdn": "peer.example.edu", + }, + ) + entry = site_entry_from_application(application) + assert entry["gateway_api_base"] == "https://peer.example.edu/api/v1" + assert entry["sync_service_url"] == "https://peer.example.edu/sync" + + +@pytest.mark.django_db +def test_site_entry_requires_site_name(user) -> None: + application = RegistryApplication.objects.create( + fqdn="peer.example.edu", + display_name="Peer", + contact=user, + challenge_token_hash=hash_registry_challenge_token("t"), + status=RegistryApplicationStatus.APPROVED.value, + ) + with pytest.raises(ManifestBuildError, match="site id"): + site_entry_from_application(application) + + +@pytest.mark.django_db +def test_build_manifest_site_list_includes_approved_and_published(user) -> None: + RegistryApplication.objects.create( + fqdn="a.example.edu", + display_name="A", + contact=user, + site_name="site-a", + challenge_token_hash=hash_registry_challenge_token("a"), + status=RegistryApplicationStatus.PUBLISHED.value, + published_manifest_serial=1, + ) + RegistryApplication.objects.create( + fqdn="b.example.edu", + display_name="B", + contact=user, + site_name="site-b", + challenge_token_hash=hash_registry_challenge_token("b"), + status=RegistryApplicationStatus.APPROVED.value, + ) + sites = build_manifest_site_list() + assert {s["name"] for s in sites} == {"site-a", "site-b"} + + +@pytest.mark.django_db +def test_manifest_min_serial(user) -> None: + assert manifest_min_serial() == 0 + RegistryApplication.objects.create( + fqdn="a.example.edu", + display_name="A", + contact=user, + site_name="site-a", + challenge_token_hash=hash_registry_challenge_token("a"), + status=RegistryApplicationStatus.PUBLISHED.value, + published_manifest_serial=3, + ) + assert manifest_min_serial() == 4 diff --git a/gateway/sds_gateway/api_methods/views/federation_well_known.py b/gateway/sds_gateway/api_methods/views/federation_well_known.py deleted file mode 100644 index 3552a9628..000000000 --- a/gateway/sds_gateway/api_methods/views/federation_well_known.py +++ /dev/null @@ -1,31 +0,0 @@ -from __future__ import annotations - -from django.http import HttpRequest -from django.http import HttpResponse -from django.http import JsonResponse -from django.views import View - -from sds_gateway.api_methods.federation.well_known import build_sds_federation_document -from sds_gateway.api_methods.federation.well_known import well_known_document_ready - - -class SdsFederationWellKnownView(View): - """Public site identity for federation discovery and registry verification.""" - - def get(self, request: HttpRequest) -> HttpResponse: - document = build_sds_federation_document() - if not well_known_document_ready(document): - return JsonResponse( - { - "error": ( - "federation well-known document is not configured on this host" - ) - }, - status=503, - ) - response = JsonResponse(document) - response["Cache-Control"] = "no-store" - return response - - -sds_federation_well_known_view = SdsFederationWellKnownView.as_view() diff --git a/gateway/sds_gateway/templates/emails/registry_application_pending_approval.html b/gateway/sds_gateway/templates/emails/registry_application_pending_approval.html new file mode 100644 index 000000000..8e08f1b49 --- /dev/null +++ b/gateway/sds_gateway/templates/emails/registry_application_pending_approval.html @@ -0,0 +1,101 @@ +{# djlint:off #} + + + + + + Federation registry — pending approval + + + + + + +
+ + + + + + + + + + +
+
🌐
+

Peer pending approval

+

Federation registry intake

+
+ + + + +
+

Domain verified

+

+ The applicant proved control of {{ fqdn }}. Please approve or reject before publishing the signed registry manifest. +

+
+ + + + +
+

Application details

+ + + + + + + + + + + + + + + + + + {% if gateway_api_base %} + + + + + {% endif %} + {% if sync_service_url %} + + + + + {% endif %} +
FQDN{{ fqdn }}
Display name{{ display_name }}
Proposed site id{{ proposed_site_name }}
Applicant{{ applicant_email }}
Gateway API{{ gateway_api_base }}
Sync URL{{ sync_service_url }}
+
+ + + + +
+ + + + +
+ + Review application + +
+
+
+ SpectrumX Logo +

This is an automated message from the SpectrumX Data System.

+

If you have any questions, please contact our support team.

+
+
+ + +{# djlint:on #} diff --git a/gateway/sds_gateway/templates/emails/registry_application_pending_approval.txt b/gateway/sds_gateway/templates/emails/registry_application_pending_approval.txt new file mode 100644 index 000000000..e555af6ca --- /dev/null +++ b/gateway/sds_gateway/templates/emails/registry_application_pending_approval.txt @@ -0,0 +1,17 @@ +Federation registry: peer pending approval + +A new site passed domain verification and is awaiting staff approval before it can be published in the signed registry manifest. + +FQDN: {{ fqdn }} +Display name: {{ display_name }} +Proposed site id: {{ proposed_site_name }} +Applicant email: {{ applicant_email }} +{% if gateway_api_base %}Gateway API base: {{ gateway_api_base }} +{% endif %}{% if sync_service_url %}Sync service URL: {{ sync_service_url }} +{% endif %} +Review and approve or reject: +{{ review_url }} + +--- +This is an automated message from the SpectrumX Data System. +If you have any questions, please contact our support team. diff --git a/gateway/sds_gateway/templates/users/registry_application_detail.html b/gateway/sds_gateway/templates/users/registry_application_detail.html index 4005ed13f..fc2329322 100644 --- a/gateway/sds_gateway/templates/users/registry_application_detail.html +++ b/gateway/sds_gateway/templates/users/registry_application_detail.html @@ -95,17 +95,15 @@

{% translate "Registry Application" %}

+
+ {% csrf_token %} + +
- {% endif %} - {% if can_verify_domain %} -
- {% csrf_token %} -

- {% translate "After publishing registry_challenge on your well-known URL, run verification." %} -

- -
+

+ {% translate "Set FEDERATION_REGISTRY_CHALLENGE_TOKEN on applicant federation sync (see federation docs), recreate sync, then click Verify domain." %} +

{% endif %} {% if can_staff_review %}
@@ -129,6 +127,26 @@

{% translate "Registry Application" %}

value="{{ application.proposed_site_name }}" placeholder="{% translate "Defaults to proposed site id" %}" />
+
+ + +
+
+ + +
@@ -170,7 +188,7 @@

{% translate "Registry Application" %}