diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f87765d..08c8dcb0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,11 +102,19 @@ jobs: - run: scripts/install-railpack.sh - run: cargo test --locked --workspace # Row security and teams against a real Postgres: what a person's - # requests may see and change, signing up, creating and joining teams. + # requests may see and change, signing up, creating and joining teams, + # and the Cloudflare Tunnel loop against a fake Cloudflare. - name: Teams and row security (Postgres) env: DATABASE_URL: postgres://postgres:pyo@localhost:5432/pyo - run: cargo test --locked -p pyo-api --lib -- --ignored rls::tests teams_rls_tests teamsec_tests auth::key_tests auth::invite_tests + run: cargo test --locked -p pyo-api --lib -- --ignored rls::tests teams_rls_tests teamsec_tests auth::key_tests auth::invite_tests cloudflare::http_tests + # What a Compose sync writes. A run of its own: the tests above set a + # secret key for the whole process, and its one vault then keeps its + # data keys in whichever test's database came first. + - name: Compose sync (Postgres) + env: + DATABASE_URL: postgres://postgres:pyo@localhost:5432/pyo + run: cargo test --locked -p pyo-api --lib -- --ignored compose_sync::db_tests # Known CVEs in the locked dependencies: Cargo.lock, bun.lock (with the # dashboard's dev dependencies) and the WAF's go.mod. A CRITICAL one diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 48c6ce27..00522cf5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,13 +2,17 @@ name: Release # Pushing a tag like v0.1.0 publishes that version: signed images at # ghcr.io/upsetdev/pyo, and a GitHub release with the CLI for each -# platform, the sandbox server files, the install scripts and release.json -# (what the dashboard's updates apply). Then pyo.dev is rebuilt, to serve -# the release's install scripts. See RELEASING.md. +# platform, the verifier, the sandbox server files, the install scripts +# and release.json (what the dashboard's updates apply). Then pyo.dev is +# rebuilt, to serve the release's install scripts. See RELEASING.md. +# +# A tag like v0.1.0-rc.1 is a release candidate, for testing the verifier: +# the same build, published as a pre-release (never GitHub's latest, so +# installations and pyo.dev don't see it), and pyo.dev isn't rebuilt. on: push: - tags: ["v[0-9]+.[0-9]+.[0-9]+"] + tags: ["v[0-9]+.[0-9]+.[0-9]+", "v[0-9]+.[0-9]+.[0-9]+-rc.[0-9]+"] permissions: contents: read @@ -22,6 +26,7 @@ jobs: runs-on: ubuntu-24.04 outputs: version: ${{ steps.version.outputs.version }} + rc: ${{ steps.version.outputs.rc }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: The tag matches Cargo.toml @@ -33,6 +38,7 @@ jobs: exit 1 fi echo "version=$version" >> "$GITHUB_OUTPUT" + case "$version" in *-rc.*) echo "rc=true" ;; *) echo "rc=false" ;; esac >> "$GITHUB_OUTPUT" - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1 with: toolchain: 1.99.1 @@ -92,6 +98,41 @@ jobs: needs: verify uses: ./.github/workflows/cli.yml + # The verifier for Linux on Arm, built on an Arm runner like the CLI + # (cli.yml). Linux x86-64's comes from pyo.Dockerfile's `verify` target, + # in the release job. Static (musl): it runs on any customer's server. + verifier: + name: Verifier (Linux on Arm) + needs: verify + runs-on: ubuntu-24.04-arm + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1 + with: + toolchain: 1.99.1 + targets: aarch64-unknown-linux-musl + - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends musl-tools + - name: Build + env: + CC_aarch64_unknown_linux_musl: musl-gcc + run: | + cargo build --release --locked -p pyo-verify --target aarch64-unknown-linux-musl + mkdir out + cp target/aarch64-unknown-linux-musl/release/pyo-verify out/pyo-verify-linux-aarch64 + # It runs on the platform it's for, and says the tag's version: a + # server's verifier compares it with the release it took. + - name: Check it runs + env: + VERSION: ${{ needs.verify.outputs.version }} + run: | + got=$(out/pyo-verify-linux-aarch64 version) + [ "$got" = "$VERSION" ] || { echo "::error::pyo-verify version says \"$got\", not $VERSION."; exit 1; } + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: verifier-linux-aarch64 + path: out/ + if-no-files-found: error + # A sandbox server's files for each architecture (sandbox.yml). sandbox: name: Sandbox @@ -215,7 +256,7 @@ jobs: release: name: GitHub release - needs: [verify, images, cli, sandbox] + needs: [verify, images, cli, verifier, sandbox] runs-on: ubuntu-24.04 permissions: contents: write @@ -252,11 +293,42 @@ jobs: sha256sum -c "pyo-sandbox-linux-$a.tar.gz.sha256" sha256sum -c "pyo-sandbox-gvisor-linux-$a.tar.gz.sha256" done + # The verifier for each architecture: Linux x86-64's from the binaries + # this run built (pyo.Dockerfile's `verify` target), Linux on Arm's + # from the verifier job. release.json lists their sums, so they're + # signed with it, and connect.sh gets the same sums on its + # pyo:verify-pin lines. + - name: Build the verifier + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: deploy/images/pyo.Dockerfile + target: verify + platforms: linux/amd64 + cache-from: type=gha,scope=rust-${{ github.run_id }} + outputs: type=local,dest=verify-build + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: verifier-linux-aarch64 + path: verifier + - name: Check the verifier + env: + VERSION: ${{ needs.verify.outputs.version }} + run: | + cp verify-build/pyo-verify verifier/pyo-verify-linux-x86_64 + chmod 755 verifier/pyo-verify-linux-* + got=$(verifier/pyo-verify-linux-x86_64 version) + [ "$got" = "$VERSION" ] || { echo "::error::pyo-verify version says \"$got\", not $VERSION."; exit 1; } + for a in x86_64 aarch64; do + file -b "verifier/pyo-verify-linux-$a" | grep -qE 'static(-pie)? linked|statically linked' || { echo "::error::pyo-verify-linux-$a isn't static: $(file -b "verifier/pyo-verify-linux-$a")"; exit 1; } + done + sha256sum verifier/pyo-verify-linux-* # What Pyo needs to update itself from the dashboard: the images # pinned by the digests that were just signed, and the manifests. # Also the install scripts as the release publishes them, written to # release-scripts/ (connect.sh, join.sh and sandbox.sh with this - # version on their pyo:release-version line), and their SHA-256: + # version on their pyo:release-version line, connect.sh with the + # verifier's sums on its pyo:verify-pin lines), and their SHA-256: # pyo.dev serves only scripts that match these signed sums. - name: Write release.json env: @@ -270,17 +342,42 @@ jobs: --mysql-operator "$(digest mysql-operator)" --mysql-backup "$(digest mysql-backup)" \ --postgres-16 "$(tagged postgres 16-)" --postgres-17 "$(tagged postgres 17-)" --postgres-18 "$(tagged postgres 18-)" \ --agent-access "$(docker run --rm "$IMAGES/agent:$VERSION@$(digest agent)" access-hash)" \ + --database-pins "$(docker run --rm "$IMAGES/agent:$VERSION@$(digest agent)" database-pins)" \ --sandbox-x86_64 "$(cut -d' ' -f1 sandbox/pyo-sandbox-linux-x86_64.tar.gz.sha256)" \ --sandbox-aarch64 "$(cut -d' ' -f1 sandbox/pyo-sandbox-linux-aarch64.tar.gz.sha256)" \ --sandbox-gvisor-x86_64 "$(cut -d' ' -f1 sandbox/pyo-sandbox-gvisor-linux-x86_64.tar.gz.sha256)" \ --sandbox-gvisor-aarch64 "$(cut -d' ' -f1 sandbox/pyo-sandbox-gvisor-linux-aarch64.tar.gz.sha256)" \ - --scripts release-scripts > release.json - jq '{version, images, k3s, minFrom, manualOnly, beforeYouUpdate, agentAccess, sandbox, sandboxGvisor, scripts, migrations: (.migrations | length)}' release.json + --verifier verifier --scripts release-scripts > release.json + jq '{version, images, k3s, minFrom, manualOnly, beforeYouUpdate, agentAccess, sandbox, sandboxGvisor, verifier, scripts, migrations: (.migrations | length)}' release.json + # The verifier's sums are the files', and connect.sh carries them. + - name: Check release.json's verifier + env: + VERSION: ${{ needs.verify.outputs.version }} + run: | + jq -r '.verifier | to_entries[] | "\(.value) verifier/pyo-verify-\(.key)"' release.json | sha256sum -c + [ "$(jq '.verifier | length' release.json)" = 2 ] + grep -qx "PYO_VERIFY_RELEASE=\"$VERSION\" # pyo:verify-pin release" release-scripts/connect.sh + for a in x86_64 aarch64; do + sum=$(jq -r --arg k "linux-$a" '.verifier[$k]' release.json) + grep -qx "PYO_VERIFY_SHA256_${a^^}=\"$sum\" # pyo:verify-pin $a" release-scripts/connect.sh + done # The release's own upgrader reads it before it's signed: an image # it doesn't accept, or an agentAccess that isn't its agent's roles, # fails the release here, not on installations. + # + # A release candidate's version isn't one installations take, so the + # upgrader checks everything else in it: a copy with the version's + # numbers alone. - name: Check release.json with the release's upgrader - run: docker run --rm -v "$PWD/release.json:/release.json:ro" "$(jq -r .images.agent release.json)" check-release /release.json + env: + RC: ${{ needs.verify.outputs.rc }} + run: | + check=release.json + if [ "$RC" = true ]; then + jq '.version |= sub("-rc\\.[0-9]+$"; "")' release.json > release-check.json + check=release-check.json + fi + docker run --rm -v "$PWD/$check:/release.json:ro" "$(jq -r .images.agent release.json)" check-release /release.json # release.json is signed like the images: keyless, as this workflow # at this tag. install.sh, pyo-up.sh --release and the dashboard's # updates (pyo-api sigstore.rs) check it before using anything in it. @@ -358,6 +455,8 @@ jobs: release-scripts/connect.sh release-scripts/join.sh release-scripts/sandbox.sh + verifier/pyo-verify-linux-x86_64 + verifier/pyo-verify-linux-aarch64 sandbox/pyo-sandbox-linux-x86_64.tar.gz sandbox/pyo-sandbox-linux-x86_64.tar.gz.sha256 sandbox/pyo-sandbox-linux-aarch64.tar.gz @@ -385,8 +484,9 @@ jobs: --notes-file release-notes.md "${files[@]}" ;; esac - # What the draft holds now: each install script as release.json lists it. - - name: Check the draft's install scripts + # What the draft holds now: each install script and verifier as + # release.json lists it. + - name: Check the draft's install scripts and verifier if: steps.draft.outputs.published != 'true' env: GH_TOKEN: ${{ github.token }} @@ -394,11 +494,21 @@ jobs: gh release download "$GITHUB_REF_NAME" --pattern '*.sh' --dir uploaded jq -r '.scripts | to_entries[] | "\(.value) uploaded/\(.key)"' release.json | sha256sum -c [ "$(ls uploaded | wc -l)" = "$(jq '.scripts | length' release.json)" ] + gh release download "$GITHUB_REF_NAME" --pattern 'pyo-verify-*' --dir uploaded-verifier + jq -r '.verifier | to_entries[] | "\(.value) uploaded-verifier/pyo-verify-\(.key)"' release.json | sha256sum -c + [ "$(ls uploaded-verifier | wc -l)" = "$(jq '.verifier | length' release.json)" ] + # A release candidate is a pre-release: never GitHub's latest. - name: Publish the release if: steps.draft.outputs.published != 'true' env: GH_TOKEN: ${{ github.token }} - run: gh release edit "$GITHUB_REF_NAME" --draft=false --latest + RC: ${{ needs.verify.outputs.rc }} + run: | + if [ "$RC" = true ]; then + gh release edit "$GITHUB_REF_NAME" --draft=false --prerelease + else + gh release edit "$GITHUB_REF_NAME" --draft=false --latest + fi # pyo.dev serves the latest release's install scripts, and each release's # at pyo.dev/v//. Its build takes them from the published @@ -407,9 +517,12 @@ jobs: # whose URL is the secret PYO_WEB_DEPLOY_HOOK (Cloudflare dashboard > # Workers & Pages > pyo-web > Settings > Builds > Deploy Hooks). When it # fails, run this job again: the release stays as it is. + # + # Not for a release candidate: pyo.dev serves releases only. site: name: Rebuild pyo.dev - needs: release + needs: [verify, release] + if: needs.verify.outputs.rc != 'true' runs-on: ubuntu-24.04 permissions: {} steps: diff --git a/Cargo.lock b/Cargo.lock index ddebb2fd..6eb348ab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1642,9 +1642,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -3629,6 +3629,7 @@ dependencies = [ "libc", "maxminddb", "pyo-proto", + "pyo-sigstore", "qrcode", "rand 0.10.3", "rcgen", @@ -3695,6 +3696,7 @@ dependencies = [ "pyo-proto", "rand 0.10.3", "reqwest", + "rustls", "schemars 1.2.3", "serde", "serde_json", @@ -3825,6 +3827,19 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "pyo-sigstore" +version = "0.5.5" +dependencies = [ + "anyhow", + "aws-lc-rs", + "base64 0.23.1", + "hex", + "serde_json", + "sha2 0.11.1", + "x509-parser", +] + [[package]] name = "pyo-static" version = "0.5.5" @@ -3846,6 +3861,16 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "pyo-verify" +version = "0.5.5" +dependencies = [ + "hex", + "pyo-sigstore", + "serde_json", + "sha2 0.11.1", +] + [[package]] name = "qrcode" version = "0.14.1" @@ -5660,9 +5685,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/Cargo.toml b/Cargo.toml index 9195ebd0..c4646240 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/pyo-proto", "crates/pyo-api", "crates/pyo-agent", "crates/pyo-builder", "crates/pyo-cli", "crates/pyo-flows", "crates/pyo-resp", "crates/pyo-kv", "crates/pyo-db-controller", "crates/pyo-static", "crates/pyo-envd", "crates/pyo-sandbox"] +members = ["crates/pyo-proto", "crates/pyo-sigstore", "crates/pyo-verify", "crates/pyo-api", "crates/pyo-agent", "crates/pyo-builder", "crates/pyo-cli", "crates/pyo-flows", "crates/pyo-resp", "crates/pyo-kv", "crates/pyo-db-controller", "crates/pyo-static", "crates/pyo-envd", "crates/pyo-sandbox"] [workspace.package] version = "0.5.5" diff --git a/RELEASING.md b/RELEASING.md index 86512c21..3367be8f 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -7,10 +7,23 @@ A version is one number for everything: `version` in the root `Cargo.toml`. 1. Set `version` in `Cargo.toml` and run `cargo check` to update `Cargo.lock`. 2. Write what installations should know in `deploy/release-notices.json` (see [Notices](#notices)), with `"version"` set to the new version. -3. Write the API reference for the docs (see [API reference](#api-reference)): +3. Check whether `agentAccess` changed since the last release: compare + `cargo run -q -p pyo-agent -- access-hash` with `agentAccess` in the last + release's `release.json`. When it changed, the release notes must say + which clusters need the connect command under **Refresh this cluster** + once, and that databases restart once when it runs (see + [Notices](#notices)). For 0.51.0 that's every cluster. After it, a + self-hosted cluster with the self-update role needs it only when the + release adds a role object or changes a chart installed with the agent, + and a cluster without that role (Pyo Cloud's) whenever it changed. The + cluster Pyo itself runs on never needs it from its admin: its server + runs the command by itself (see + [The server Pyo runs on](#the-server-pyo-runs-on)). Say so in the notes, + so an installation with only that cluster knows there's nothing to run. +4. Write the API reference for the docs (see [API reference](#api-reference)): `cargo run -p pyo-api --bin openapi`. -4. Commit that to `main`, and wait for CI to pass. -5. Tag the commit and push the tag: +5. Commit that to `main`, and wait for CI to pass. +6. Tag the commit and push the tag: ```bash git tag v0.1.0 @@ -33,6 +46,9 @@ by `.github/workflows/cli.yml`, which you can also run by hand (Actions › CLI › Run workflow) to try those builds on a branch. That run publishes nothing. It keeps the binaries as the run's artifacts. +The release also carries Pyo's verifier, `pyo-verify-linux-x86_64` and +`pyo-verify-linux-aarch64` (see [The verifier](#the-verifier)). + The release also carries a sandbox server's files for each architecture, `pyo-sandbox-linux-x86_64.tar.gz` and `pyo-sandbox-linux-aarch64.tar.gz`, each with its `.sha256`, beside `deploy/sandbox.sh`, which installs them. @@ -152,19 +168,58 @@ How it reaches installations: **Settings › Updates**, and apply it there. With automatic updates on, it's applied in the maintenance window. `install.sh` updates too. Pyo updates first, then every cluster's agent moves to the new agent image. + A cluster with the self-update role then brings the rest up to date by + itself within a minute, its roles included, and its databases restart + then. 0.51.0 is the last release where every cluster needs the command + under **Refresh this cluster** in the cluster's settings once. After it, + only a release that adds a role object or changes a chart installed with + the agent does. On the cluster Pyo runs on, the server runs that command + by itself within a few minutes, 0.51.0 included. So an installation with + only that cluster has nothing to run after any release. - **Pyo Cloud:** whoever runs it updates the shared Pyo. Each team's agents then follow its version: within a minute for teams with automatic agent updates (the default), or when the team updates a cluster from its page. + A team's databases don't move with either. They restart once the team + runs the command under **Refresh this cluster** in the cluster's settings, + which says "Restarts your databases once" while that's so. Say in the + release's announcement to Cloud teams that this command restarts their + databases once. From 0.51.0 that command also sets up automatic updates + on the cluster's first server. In 0.51.0 they apply nothing yet, so the + command is still needed after each release (see + [Automatic updates on Pyo Cloud](#automatic-updates-on-pyo-cloud)). How databases pick up new images: the databases system on a cluster -updates with Pyo, at the cluster's next heartbeat once its agent is the new -one. pyo-db-controller restarts with the new images and rolls each database +updates with Pyo, at the cluster's next heartbeat once the cluster's +install (its admission policy, which pins the images) is the new Pyo's. +The agent's own image doesn't matter. An agent with the self-update role +brings the install up to date by itself within a minute of Pyo's update, +its roles included (see [Notices](#notices) for what it can't bring). +0.51.0 is the exception: 0.5.5's self-update role can't write roles, so +every cluster stays outdated until the connect command under **Refresh this +cluster** runs once. The server Pyo runs on runs it by itself. Clusters +without that role (Pyo Cloud's, or `PYO_AGENT_SELF_UPDATE=false`) always +wait for the command. +pyo-db-controller then restarts with the new images and rolls each database onto them. A Postgres or MySQL database with replicas restarts a replica first and switches over to it, so the primary stops only for the switchover. A single instance restarts, which is a short outage. New third-party database images (MySQL, valkey-bundle, the Postgres bases) come the same way, since the release's code pins them. +Every release restarts Postgres and KV databases once: their images are +built with the release and tagged with its version, so they're never the +ones before. MySQL databases restart when the release pins another MySQL +image. They restart when the cluster's install becomes the new Pyo's: +within a minute of Pyo's update on a self-hosted cluster with the +self-update role. On every other cluster they restart when the command +under **Refresh this cluster** runs, which on the cluster Pyo runs on is +within a few minutes of the update. Pyo says so by itself, nothing to write in the notices: the update +dialog and the cluster's refresh command show "Restarts your databases +once" when a database runs an image the release changes (compared from +`release.json`'s images and `databasePins`), and each database's restart +is written to its team's activity ("Restarting the database main for an +update"). + ## Release notes `scripts/release-notes.ts` writes each release's text from the Conventional @@ -239,19 +294,30 @@ release carries it as an asset. Installations find it in **Settings › Updates* - `migrations`: the migration files, so an installation can say how many it hasn't run yet - the notices from `deploy/release-notices.json` -- `agentAccess`: a hash of the roles the release's agent is installed with - (see [Notices](#notices)) +- `agentAccess`: a hash of the roles and the admission policy the release's + agent is installed with (see [Notices](#notices)) +- `databasePins`: the database images the release's code pins itself + (`pyo-agent database-pins`: MySQL's and Valkey's with its modules, which + `check-release` verifies). With `images.postgres16` to `postgres18` and + `images.kv` they're what the release's databases run. The workflow writes + it, nothing to set by hand - `k3s`: the k3s a fresh install gets, from `deploy/k3s.env` (see [Bump k3s](#bump-k3s)). - `sandbox`: the SHA-256 of each architecture's sandbox server files. `deploy/sandbox.sh` checks release.json's signature with cosign, as `install.sh` does, then the files against these. +- `verifier`: the SHA-256 of the release's verifier for each architecture, + `{"linux-x86_64": "", "linux-aarch64": ""}`, read from + the files in `--verifier ` (`pyo-verify-linux-`, each a Linux + program for its architecture). A server's verifier checks release.json's + signature, then the next verifier against these. - `scripts`: the SHA-256 of each install script the release publishes (`install.sh`, `cli.sh`, `connect.sh`, `join.sh`, `sandbox.sh`). The script writes them to `--scripts `, with this version on the `pyo:release-version` line of `connect.sh`, `join.sh` and `sandbox.sh`, - and the release uploads them from there. pyo.dev serves only scripts - that match these sums. The release notes list them too. + and the verifier's version and sums on the `pyo:verify-pin` lines of + `connect.sh`. The release uploads them from there. pyo.dev serves only + scripts that match these sums. The release notes list them too. To try it before tagging: @@ -262,11 +328,16 @@ bun run scripts/release-manifest.ts --version 0.1.0 --images ghcr.io/upsetdev/py --mysql-operator sha256:<64 hex> --mysql-backup sha256:<64 hex> \ --postgres-16 sha256:<64 hex> --postgres-17 sha256:<64 hex> --postgres-18 sha256:<64 hex> \ --agent-access "$(cargo run -q -p pyo-agent -- access-hash)" \ + --database-pins "$(cargo run -q -p pyo-agent -- database-pins)" \ --sandbox-x86_64 <64 hex> --sandbox-aarch64 <64 hex> \ --sandbox-gvisor-x86_64 <64 hex> --sandbox-gvisor-aarch64 <64 hex> \ - --scripts /tmp/release-scripts + --verifier /tmp/verifier --scripts /tmp/release-scripts ``` +`/tmp/verifier` holds `pyo-verify-linux-x86_64` and +`pyo-verify-linux-aarch64`. Any Linux program for each architecture will +do for a try. + ### Notices `deploy/release-notices.json` is read only when its `"version"` is the @@ -291,13 +362,199 @@ release's (old notices never carry over): intermediate release has to run first (e.g. a migration in two steps). Older installations are told to update to `minFrom` first. -A change to the agent's roles needs no notice: `release.json` carries the -release agent's `agentAccess` (`pyo-agent access-hash`, which -`check-release` verifies), and an installation whose agent has other roles -adds "After updating, run the connect command shown in each cluster's -settings." to the update dialog by itself. An agent brings its admission -policy and image pins up to date on its own (with the self-update role), but -never its roles. +A change to the agent's roles or to its admission policy's rules needs no +notice for the update dialog: `release.json` carries the release agent's `agentAccess` +(`pyo-agent access-hash`, which `check-release` verifies), and an +installation whose agent has other ones and whose clusters don't have the +self-update role (Pyo Cloud, or `PYO_AGENT_SELF_UPDATE=false`) adds "After +updating, run the connect command shown in each cluster's settings." to the +update dialog by itself. The images in the policy don't count. A +self-hosted installation with the self-update role gets no such line from +0.51.0 on, since its agents bring the roles themselves. So when a release +adds a role object or changes a chart installed with the agent (the two +things a refresh can't bring, see below), write that line yourself as a +`beforeYouUpdate` notice. An installation whose only cluster is the one +Pyo runs on doesn't show that exact line: its server runs the command by +itself. The release notes never get the line by +themselves, so write it there when it applies (step 3 of +[Cut a release](#cut-a-release)): as a `beforeYouUpdate` notice, which the +release notes put first, or in the release's text (see +[Release notes](#release-notes)). + +From 0.51.0 on, an agent with the self-update role writes its own roles. +Its refresh reads each role and binding of the install and updates the ones +that differ, then the admission policy, then the image pins. So a release +that changes rules in roles a cluster already has needs no command there. +0.51.0 itself still does, once: 0.5.5's self-update role may only read the +roles, so every cluster stays outdated until its connect command runs. + +What a refresh can't do, and still needs the connect command for: + +- **A new role object.** The agent updates roles and bindings by name and + never creates one (Kubernetes can't limit a create to a name). Put a new + permission into a role the install already has. A cluster-wide role with + `resourceNames` covers a new namespace too. +- **A chart installed with the agent** (cert-manager, Envoy Gateway). The + agent only reads them. Envoy Gateway's CRDs come from `connect.sh` anyway. +- **A binding to another role.** Kubernetes never changes a binding's role. +- **A cluster without the self-update role** (Pyo Cloud's, one installed + with `PYO_AGENT_SELF_UPDATE=false`, one whose owner deleted the + `pyo-agent-self-update` ClusterRoleBinding) **or read only.** Pyo sends it + no refresh. + +When a refresh can't bring a role, it still brings the rest: the admission +policy (it only narrows what the roles allow, so the new policy is safe +with the roles as they are), the image pins, and with them the databases +system, unless the roles left behind are the bundles' own +(`pyo-agent-bundles`, `pyo-agent-bundle-write`) or a chart. The install's +stamp then names the roles left behind, the cluster's settings show +"Update needed" with "This cluster's agent needs an update for some +features.", and only the features that need those roles wait for the +command (Cloudflare Tunnel is one). This is also what 0.51.0's agent does +on a 0.5.5 install before its owner runs the command. A feature that +needs a new permission must check for it and point to **Refresh this +cluster**, as `install_ready` in +`crates/pyo-api/src/cloudflare/tunnel_ops.rs` does. + +The self-update role holds `update`, `escalate` and `bind` on the agent's +own roles, by name. With it, whoever controls Pyo can give the agent any +permission on the cluster, up to cluster-admin. That was already so while +the role only rewrote the admission policy: the agent takes any policy that +fails closed (`check` in `crates/pyo-agent/src/install.rs` can't pin a later +release's rules), and without the policy's limits the agent's roles run +privileged pods in `pyo-system` and write any rule into the bundles' +ClusterRoles (`cluster_rules` in `crates/pyo-proto/src/bundles.rs`). The +role now says so directly. Pyo Cloud installs without it. Don't widen it: +`self_update_is_narrow` in `crates/pyo-proto/src/rbac.rs` pins its exact +shape. + +The roles are partly +built from the cluster-wide object names in the system bundles +(`cluster_rules` in `crates/pyo-proto/src/bundles.rs`), so a release that +adds or renames such an object changes rules in a role the install +already has, which a refresh brings. A new Service, +network policy or ConfigMap of the gateway in `pyo-gateway` changes no role: +the role there names none of them, and the admission policy +(`gatewayAllowed` in `crates/pyo-proto/src/rbac.rs`) holds each to Pyo's own +by name and content. Add the new object's clause there. A cluster on +Kubernetes older than 1.30 has no admission policy, so nothing but the +agent's own code keeps it to those names in that namespace. A cluster +without the self-update role or read only gets new roles and a new policy +only from its connect command. Until then, the agent writes the gateway's client policies +in the shape the cluster's older policy accepts, and the cluster's settings +say to run the command. + +### The server Pyo runs on + +The cluster Pyo itself runs on needs no command from its admin. Most +self-hosted installations have only this cluster. + +- The server's `pyo-tailnet` timer runs as root every minute + (`host_units` in `deploy/install.sh`). It first brings the running Pyo's + host scripts (`/install/host-units.sh`, when its checksum changes), then + runs `connect-this-machine.sh auto`. +- That asks `GET /install/this-machine` (with the bootstrap key). The + answer has `"refresh": true` while the cluster's install is "outdated" + or "roles", this installation has the self-update role + (`PYO_AGENT_SELF_UPDATE` isn't off), the cluster's own self-update + binding is there and the cluster isn't read only (`host_refreshes` in + `crates/pyo-api/src/install.rs`). +- The server then runs `connect.sh` from Pyo on `127.0.0.1:8000`, the same + command as under **Refresh this cluster**. It brings new role objects, + charts and host settings, and may restart k3s once. +- It runs once per Pyo version and install (`/etc/pyo/refresh-tried`). One + that failed (`/etc/pyo/refresh-failed`) is tried again after an hour. No + more than 4 run in a day (`/etc/pyo/refresh-runs`). A run by hand and the + installer take turns with it (`/run/pyo-connect.lock`). +- Meanwhile the cluster's settings show "Updating". They show "Update + needed" with the command once the run failed, or when the server said + nothing for 10 minutes. +- `install.sh` runs the same refresh at the end of an update. +- Its log: `journalctl -u pyo-tailnet`. + +From 0.5.5 this needs no command either: 0.5.5's timer already brings the +new host scripts within a minute of the update, and the next run refreshes +the cluster. 0.5.5's own update dialog still says "After updating, run the +connect command shown in each cluster's settings." for 0.51.0, since it +writes that line itself. Say in 0.51.0's release notes that the server Pyo +runs on needs nothing, and every other cluster needs the command once. + +A server set up with Pyo 0.4.1 or earlier, and never by `install.sh` since, +has no such timer script. Its cluster shows "Updating" for 10 minutes, +then "Update needed" with the command. Running the command, or +`install.sh` again, brings the timer script. + +Pyo Cloud's clusters are never refreshed this way: Pyo Cloud runs without +the self-update role, and a team's servers have no such timer. They have +a verifier of their own instead. + +### Automatic updates on Pyo Cloud + +Pyo Cloud must never be able to push roles, an admission policy or image +pins to a team's cluster. So a cluster there gets them only from something +the team runs as root on its own server: the connect command, or the +verifier that command sets up. + +- On a Pyo without the self-update role (`PYO_AGENT_SELF_UPDATE=false`), + the connect command and the command under **Refresh this cluster** carry + `--auto-update` (`auto_update_flag` in `crates/pyo-api/src/join.rs`). The + dashboard shows a checkbox with them, "Keep this cluster up to date + automatically", ticked. Unticked, the command shown carries + `--no-auto-update`. Pyo keeps no setting for it: the command the team + runs decides. A self-hosted Pyo with the self-update role shows no + checkbox and adds no flag. +- With `--auto-update`, `connect.sh` installs the verifier (`pyo-verify`) + on the cluster's first server, run as root by a systemd timer. +- The verifier asks `GET /install/version` on Pyo's public address. The + answer is `{"version":"X.Y.Z","install":""}`: the version this Pyo + runs and the hash of the install a cluster without the self-update role + gets (`verifier_install` in `crates/pyo-api/src/install.rs`). It needs no + key and may be cached for a minute. Naming a version is all Pyo does. +- The verifier checks that version's signed release on GitHub and takes + only what that release defines. It never moves to an earlier version. +- It writes its status to the ConfigMap `pyo-system/pyo-verifier` + (`version`, `live`, `checked`, `error`, `hold`, `host`). The agent may + read that ConfigMap by name and the admission policy refuses it any + write. The agent passes the status on with its heartbeat. +- The team's switches are on their side only: `updates: "hold"` in the + ConfigMap `pyo-system/pyo-policy`, and `/etc/pyo/verify.conf` on the + server. Pyo has no switch that turns the verifier on or off or makes it + run. Don't add one. + +**What 0.51.0 ships is the bootstrap only.** Its verifier checks the +signed release, never moves backwards, replaces itself with that release's +verifier and writes its status. It applies nothing to the cluster. So +after 0.51.0 and after the release that follows it, a Pyo Cloud cluster +still shows "Update needed" and still needs the command under **Refresh +this cluster**, as before. Applying a release's roles, admission policy +and image pins is 0.52.0's work. Don't tell Cloud teams their clusters +update by themselves before that ships. + +What the cluster's settings show under **Refresh this cluster**, from the +status (`auto_update` in `crates/pyo-api/src/install.rs`): + +- "Automatic updates are set up on this cluster (version 0.51.0)." With + "This update still needs the command." while the install is outdated. +- "Automatic updates are on hold. They were turned off on the server." Or + "…in this cluster's policy." for `updates: "hold"`. +- "Automatic updates reported a problem: …" with the verifier's own words, + and "Run the command to update this cluster." while the install is + outdated. +- Nothing when there's no verifier, or its last check is more than 48 + hours old. + +The status comes through the agent, so an agent that was broken into can +make it say anything. It only adds `autoUpdate` to what the settings show. +The install's state, the "Update needed" badge, the command and every +feature that waits for a refresh follow from the install's own stamp, never +from the status (`a_lying_verifier_status_only_changes_what_is_shown`). +Keep it that way: never read `AgentScope::verifier` to decide anything. + +This release changes the agent's roles once more: the role +`pyo-agent-policy` also reads `pyo-system/pyo-verifier`. It's a rule in a +role every install has, so a self-hosted cluster gets it with a refresh. A +Pyo Cloud cluster gets it with the command, and until then its agent says +once in its log that it can't read the status. ### How an installation updates @@ -320,6 +577,95 @@ certificates are valid to 2031), `install.sh` with cosign (the machine's, or a pinned download checked by SHA-256). The images' own signatures aren't verified in the cluster. `pyo-up.sh --release` checks them. +## The verifier + +`pyo-verify` (`crates/pyo-verify`) is a small root program on a cluster's +first server, run by a systemd timer. It takes only what a signed Pyo +release defines, for the version Pyo names. `connect.sh --auto-update` +sets it up, `--no-auto-update` and `--uninstall` remove it. The server +Pyo itself runs on never gets one: it updates with Pyo. + +**The assets.** Each release carries `pyo-verify-linux-x86_64` and +`pyo-verify-linux-aarch64`, static (musl), beside `release.json` and +`release.json.sigstore.json`. Linux x86-64's comes from the Rust binaries +job (`pyo.Dockerfile`'s `verify` target). Linux on Arm's is built on an +Arm runner by the release workflow's `verifier` job, the way `cli.yml` +builds the CLI. `pyo-verify version` says the crate's version, which is +`version` in `Cargo.toml`, which the workflow holds equal to the tag. The +workflow checks that each says it, and that each is static. + +**The pins.** `connect.sh` has three `pyo:verify-pin` lines, empty in the +repo: `PYO_VERIFY_RELEASE`, `PYO_VERIFY_SHA256_X86_64` and +`PYO_VERIFY_SHA256_AARCH64`. `scripts/release-manifest.ts` writes the +release's version and the verifier's sums on them in the `connect.sh` the +release publishes, the same sums as in `release.json`'s `verifier`. With +`--auto-update` the script downloads the verifier for its server's +processor from +`https://github.com/upsetdev/pyo/releases/download/v/`, checks it +against its pin and runs `pyo-verify install --url `. So it +installs only that release's verifier, whoever served the script. A copy +without pins (a Pyo's own `/install/connect.sh`, a dev build) installs +none and says "Automatic updates aren't available here." A Pyo that hands +out `--auto-update` (one without the self-update role, like Pyo Cloud) +needs `PYO_SCRIPTS_URL=https://pyo.dev`: its commands then fetch +`https://pyo.dev/v//connect.sh`, the release's stamped copy. +Nothing about the verifier ever fails a connect. + +Before the release is signed, the workflow checks that `release.json`'s +`verifier` sums are the files' and that `connect.sh` carries them. Before +it's published, that the draft's `pyo-verify-*` assets match them. + +**The order for Pyo Cloud.** + +1. Tag the release, and wait until the GitHub release is published and + pyo.dev serves `https://pyo.dev/v//connect.sh`. +2. Only then deploy Pyo Cloud at that version. Pyo Cloud names its own + version to every verifier (`GET /install/version`), and its commands + fetch that version's `connect.sh` from pyo.dev. Deployed before the + release is out, verifiers find no signed release for the version and + report a problem, and new commands fetch a script that isn't there. +3. Customers' verifiers act about a day later: a verifier takes a release + only once its signature is 24 hours old (the soak). Expect their + servers to move a day after the release, not when Pyo Cloud deploys. + +### Release candidates + +A release candidate tests the verifier before a release. It's the same +build, published as a GitHub pre-release. + +1. Branch from `main`, set `version` in `Cargo.toml` to `X.Y.Z-rc.N` (and + `cargo check`), commit it as `chore(release): X.Y.Z-rc.N`. +2. Tag that commit `vX.Y.Z-rc.N` and push the tag. Keep the branch out of + `main`: the release itself is `X.Y.Z`. + +The workflow builds and signs it as usual, then publishes it as a +pre-release, never as latest. So installations, `install.sh`, `pyo +upgrade` and pyo.dev don't see it, and pyo.dev isn't rebuilt. Its +`release.json` keeps the `-rc.N` version. The upgrader's check reads a +copy with the version's numbers alone, since installations never take +a release candidate. A failed candidate isn't fixed in place: tag the next +`-rc.N`. + +Its `connect.sh` comes from the pre-release's own assets, not pyo.dev: + +```bash +curl -fsSL https://github.com/upsetdev/pyo/releases/download/vX.Y.Z-rc.N/connect.sh | bash -s -- --api --token --auto-update +``` + +A candidate Pyo's own commands fetch its scripts from there too, wherever +a release's would come from pyo.dev (`published_scripts_url` in +`crates/pyo-api/src/join.rs`). + +It pins the candidate's verifier and sets it up with `channel=rc` in +`/etc/pyo/verify.conf`, so it takes release candidates too. On a test +server only, `soak_hours=0` there skips the day's wait. A stable verifier +refuses both. + +What doesn't take a release candidate: `--version` in the scripts +(`run_release`), `install.sh --version` and the dashboard's updates. Run +`cargo test --workspace` with the candidate's version before tagging: +code that reads its own version as `X.Y.Z` may not expect `-rc.N`. + ## Install scripts on pyo.dev pyo.dev serves the scripts each release publishes, as they are: @@ -430,6 +776,18 @@ To remove or rename something, split it across releases: CI rejects a contract whose tag doesn't exist yet, because that release has to have shipped first. +### Pending contracts + +Removals waiting for a release that no longer depends on the old thing: + +- `pyo.clusters.public_traffic` (0040): 0.51.0 writes only `traffic`, and + the trigger `clusters_traffic_sync` copies it to `public_traffic` because + v0.5.5 still writes `public_traffic`. In the release after v0.51.0 ships, + drop the trigger and its function, and make `public_traffic` a column + generated from `traffic` (or move its readers to `traffic` and drop it), + with `-- pyo:contract since=v0.51.0 no release since v0.51.0 writes + clusters.public_traffic`. + A migration that an installation already ran can't get that line, because sqlx checksums the file. Its contract goes in `scripts/migration-contracts.json` instead, keyed by the file name, with the same `since` and reason and the diff --git a/crates/pyo-agent/src/actions.rs b/crates/pyo-agent/src/actions.rs index e6ebe393..d291e896 100644 --- a/crates/pyo-agent/src/actions.rs +++ b/crates/pyo-agent/src/actions.rs @@ -165,7 +165,9 @@ pub async fn run(agent: &Agent, command: Command) -> CommandResult { | Command::TailscaleCheckName { .. } | Command::TailscaleRemove { .. } | Command::SandboxCall(_) - | Command::SyncRegistryTokens(_) => { + | Command::SyncRegistryTokens(_) + | Command::TunnelSet { .. } + | Command::TunnelRemove {} => { unreachable!("handled by the command loop") } }; diff --git a/crates/pyo-agent/src/builder.rs b/crates/pyo-agent/src/builder.rs index 3eda0677..9089120f 100644 --- a/crates/pyo-agent/src/builder.rs +++ b/crates/pyo-agent/src/builder.rs @@ -26,7 +26,7 @@ use serde_json::{Value, json}; use crate::{Agent, MANAGER}; const NS: &str = "pyo-system"; -const BUILDKIT_IMAGE: &str = "moby/buildkit:v0.34.1"; +const BUILDKIT_IMAGE: &str = "moby/buildkit:v0.34.2"; fn name(builder_id: &str) -> String { format!("pyo-builder-{}", builder_id.replace('_', "-")) diff --git a/crates/pyo-agent/src/cleanup.rs b/crates/pyo-agent/src/cleanup.rs index 21f68e88..04e10066 100644 --- a/crates/pyo-agent/src/cleanup.rs +++ b/crates/pyo-agent/src/cleanup.rs @@ -12,6 +12,13 @@ //! those, and a cron run's outcome is read from them), and a few at a time //! ([`BATCH`], [`PAUSE`], [`MAX_PER_RUN`]) so neither the API server nor the //! kubelets are flooded. +//! +//! An owner with more than [`STORM`] Failed pods is caught in a loop (a +//! DaemonSet's pod refused by its server over and over, a few a second): +//! its pods past the newest [`KEEP`] go without waiting out the grace +//! period, and the next run comes after [`SOON`] instead of minutes, until +//! no owner is over. Pyo's own DaemonSets are critical (pyo-proto's +//! `system::SERVER_CRITICAL`) so they don't loop: this is for what else may. use std::{collections::BTreeMap, time::Duration}; @@ -33,7 +40,11 @@ pub const BATCH: usize = 25; pub const PAUSE: Duration = Duration::from_secs(5); /// Deletions per run at most: the rest wait for the next run. pub const MAX_PER_RUN: usize = 500; +/// More Failed pods than this for one owner: a loop. +pub const STORM: usize = 50; const EVERY: Duration = Duration::from_secs(5 * 60); +/// The next run, while some owner is over [`STORM`]. +pub const SOON: Duration = Duration::from_secs(30); /// After a start: soon, but after the first heartbeat. const FIRST: Duration = Duration::from_secs(60); @@ -110,9 +121,19 @@ pub fn dead(p: &Pod) -> Option { }) } -/// The pods to delete, oldest first: past the grace period and not among -/// the newest [`KEEP`] of their owner (in their namespace). At most `max`. -pub fn choose(dead: Vec, now: i64, max: usize) -> Vec { +/// What a run deletes, and whether some owner is in a loop. +#[derive(Debug, Default, PartialEq)] +pub struct Choice { + /// Oldest first. + pub pods: Vec, + /// An owner has more than [`STORM`] Failed pods. + pub storm: bool, +} + +/// The pods to delete, oldest first: not among the newest [`KEEP`] of their +/// owner (in their namespace), and past the grace period unless their owner +/// is over [`STORM`]. At most `max`. Pods with no owner are never a loop. +pub fn choose(dead: Vec, now: i64, max: usize) -> Choice { let mut by_owner: BTreeMap<(String, String), Vec> = BTreeMap::new(); for d in dead { by_owner @@ -120,21 +141,25 @@ pub fn choose(dead: Vec, now: i64, max: usize) -> Vec { .or_default() .push(d); } - let mut out: Vec = by_owner - .into_values() - .flat_map(|mut pods| { - pods.sort_by_key(|d| std::cmp::Reverse(d.ended_at)); + let mut storm = false; + let mut out: Vec = vec![]; + for ((_, owner), mut pods) in by_owner { + let looping = !owner.is_empty() && pods.len() > STORM; + storm |= looping; + pods.sort_by_key(|d| std::cmp::Reverse(d.ended_at)); + out.extend( pods.into_iter() .skip(KEEP) - .filter(|d| now - d.ended_at >= GRACE_MS) - }) - .collect(); + .filter(|d| looping || now - d.ended_at >= GRACE_MS), + ); + } out.sort_by_key(|d| d.ended_at); out.truncate(max); - out + Choice { pods: out, storm } } -/// Every few minutes, for good. Not while the cluster's policy is read only. +/// Every few minutes, for good, or [`SOON`] again while pods loop. Not while +/// the cluster's policy is read only. pub async fn run(agent: Agent) { tokio::time::sleep(FIRST).await; loop { @@ -143,19 +168,36 @@ pub async fn run(agent: Agent) { .read() .unwrap_or_else(|e| e.into_inner()) .read_only; + let mut storm = false; if !read_only { - match once(&agent.kube).await { - Ok(0) => {} - Ok(n) => tracing::info!(deleted = n, "cleaned up failed pods"), + match once(&agent.kube, PAUSE).await { + Ok(r) => { + storm = r.storm; + if r.storm { + tracing::warn!( + deleted = r.deleted, + "pods are failing over and over, cleaning up again soon" + ); + } else if r.deleted > 0 { + tracing::info!(deleted = r.deleted, "cleaned up failed pods"); + } + } Err(e) => tracing::warn!(error = %e, "couldn't clean up failed pods"), } } - tokio::time::sleep(EVERY).await; + tokio::time::sleep(if storm { SOON } else { EVERY }).await; } } -/// One run: how many pods it deleted. -async fn once(client: &kube::Client) -> kube::Result { +/// What a run did. +#[derive(Debug, Default, PartialEq)] +struct Run { + deleted: usize, + storm: bool, +} + +/// One run, with `pause` between batches. +async fn once(client: &kube::Client, pause: Duration) -> kube::Result { let namespaces: Vec = Api::::all(client.clone()) .list(&ListParams::default()) .await? @@ -173,7 +215,10 @@ async fn once(client: &kube::Client) -> kube::Result { dead.extend(d); } } - let chosen = choose(dead, pyo_proto::now_ms(), MAX_PER_RUN); + let Choice { + pods: chosen, + storm, + } = choose(dead, pyo_proto::now_ms(), MAX_PER_RUN); let mut deleted = 0; // Namespaces where the agent's roles don't allow deleting. let mut refused: Vec = vec![]; @@ -182,7 +227,7 @@ async fn once(client: &kube::Client) -> kube::Result { continue; } if i > 0 && i % BATCH == 0 { - tokio::time::sleep(PAUSE).await; + tokio::time::sleep(pause).await; } // Only that very pod: a StatefulSet's next one has the same name. let dp = DeleteParams { @@ -207,7 +252,7 @@ async fn once(client: &kube::Client) -> kube::Result { } } } - Ok(deleted) + Ok(Run { deleted, storm }) } /// [`dead`], for a pod listed in `ns` (only ever that namespace's). @@ -244,7 +289,7 @@ mod tests { .map(|i| d("pyo-gateway", rs, &format!("p{i}"), 20 + i)) .collect(); // p0..p2 are the newest; p3..p5 go, oldest first. - assert_eq!(names(&choose(pods, NOW, 100)), ["p5", "p4", "p3"]); + assert_eq!(names(&choose(pods, NOW, 100).pods), ["p5", "p4", "p3"]); } #[test] @@ -257,7 +302,7 @@ mod tests { d("shop", rs, "young", 9), d("shop", rs, "old", 11), ]; - assert_eq!(names(&choose(pods, NOW, 100)), ["old"]); + assert_eq!(names(&choose(pods, NOW, 100).pods), ["old"]); } #[test] @@ -275,7 +320,7 @@ mod tests { d("shop", "", "bare4", 43), ]; // Three or fewer each, except the bare pods (one owner: none). - assert_eq!(names(&choose(pods, NOW, 100)), ["bare4"]); + assert_eq!(names(&choose(pods, NOW, 100).pods), ["bare4"]); } #[test] @@ -284,7 +329,7 @@ mod tests { let pods = (0..4700) .map(|i| d("pyo-gateway", rs, &format!("p{i}"), 20 + i)) .collect(); - let chosen = choose(pods, NOW, MAX_PER_RUN); + let chosen = choose(pods, NOW, MAX_PER_RUN).pods; assert_eq!(chosen.len(), MAX_PER_RUN); assert_eq!(chosen[0].name, "p4699"); assert!( @@ -294,10 +339,257 @@ mod tests { ); } + /// A DaemonSet's pod refused over and over: its young pods go too + /// (all but the newest three), and the next run comes soon. + #[test] + fn a_loop_skips_the_grace_period() { + let ds = "DaemonSet/envoy-pyo-1"; + let pods: Vec = (0..=STORM as i64) + .map(|i| d("pyo-gateway", ds, &format!("p{i}"), i % 5)) + .collect(); + let c = choose(pods.clone(), NOW, MAX_PER_RUN); + assert!(c.storm); + assert_eq!(c.pods.len(), STORM + 1 - KEEP); + // At its limit, not yet a loop: the grace period holds. + let c = choose(pods[..STORM].to_vec(), NOW, MAX_PER_RUN); + assert!(!c.storm); + assert!(c.pods.is_empty(), "{:?}", names(&c.pods)); + } + + /// Only the looping owner skips the grace period, and many pods with no + /// owner aren't a loop. + #[test] + fn a_loop_is_one_owners() { + let mut pods: Vec = (0..60) + .map(|i| d("pyo-system", "DaemonSet/pyo-vector", &format!("v{i}"), 1)) + .collect(); + pods.extend((0..5).map(|i| d("pyo-system", "ReplicaSet/pyo-agent-1", &format!("a{i}"), 1))); + pods.extend((0..5).map(|i| d("shop", "DaemonSet/pyo-vector", &format!("s{i}"), 1))); + let c = choose(pods, NOW, MAX_PER_RUN); + assert!(c.storm); + assert_eq!(c.pods.len(), 57); + assert!( + c.pods.iter().all(|p| p.name.starts_with('v')), + "{:?}", + names(&c.pods) + ); + + let bare: Vec = (0..80) + .map(|i| d("shop", "", &format!("b{i}"), 1)) + .collect(); + let c = choose(bare, NOW, MAX_PER_RUN); + assert!(!c.storm); + assert!(c.pods.is_empty()); + } + fn pod(v: serde_json::Value) -> Pod { serde_json::from_value(v).unwrap() } + /// A fake Kubernetes API: namespaces (name, labels), Failed pods per + /// namespace, and the deletes it got (namespace, name, uid precondition). + mod fake { + use std::sync::{Arc, Mutex}; + + use axum::{ + Json, Router, + body::Bytes, + extract::State, + http::{Method, StatusCode, Uri}, + response::{IntoResponse, Response}, + }; + use serde_json::{Value, json}; + + #[derive(Default)] + pub struct Cluster { + pub namespaces: Vec, + pub pods: Vec, + pub deleted: Vec<(String, String, String)>, + pub lists: Vec, + } + + pub type Shared = Arc>; + + async fn handle( + State(st): State, + method: Method, + uri: Uri, + body: Bytes, + ) -> Response { + let mut c = st.lock().unwrap(); + let path = uri.path().to_owned(); + let parts: Vec<&str> = path.trim_start_matches("/api/v1/").split('/').collect(); + match (method.as_str(), parts.as_slice()) { + ("GET", ["namespaces"]) => Json(json!({ + "apiVersion": "v1", "kind": "NamespaceList", "metadata": {}, "items": c.namespaces, + })) + .into_response(), + ("GET", ["namespaces", ns, "pods"]) => { + c.lists.push(format!("{ns}?{}", uri.query().unwrap_or_default())); + let items: Vec = c + .pods + .iter() + .filter(|p| p["metadata"]["namespace"] == *ns) + .cloned() + .collect(); + Json(json!({ "apiVersion": "v1", "kind": "PodList", "metadata": {}, "items": items })) + .into_response() + } + ("DELETE", ["namespaces", ns, "pods", name]) => { + let opts: Value = serde_json::from_slice(&body).unwrap_or_default(); + let uid = opts["preconditions"]["uid"].as_str().unwrap_or_default().to_owned(); + c.deleted.push(((*ns).to_owned(), (*name).to_owned(), uid)); + let at = c.pods.iter().position(|p| { + p["metadata"]["namespace"] == *ns && p["metadata"]["name"] == *name + }); + match at { + Some(i) => Json(c.pods.remove(i)).into_response(), + None => (StatusCode::NOT_FOUND, Json(json!({ "kind": "Status", "apiVersion": "v1", "status": "Failure", "reason": "NotFound", "code": 404, "message": "not found" }))).into_response(), + } + } + _ => (StatusCode::NOT_FOUND, Json(json!({ "kind": "Status", "apiVersion": "v1", "status": "Failure", "code": 404, "message": "no such path" }))).into_response(), + } + } + + pub async fn serve(cluster: Cluster) -> (kube::Client, Shared) { + // As main does: a workspace build has ring next to aws-lc-rs, + // and kube's client can't guess which one to use. + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let st: Shared = Arc::new(Mutex::new(cluster)); + let app = Router::new().fallback(handle).with_state(st.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let config = kube::Config::new(format!("http://{addr}").parse().unwrap()); + (kube::Client::try_from(config).unwrap(), st) + } + } + + fn failed_pod( + ns: &str, + name: &str, + owner: Option<(&str, &str)>, + ended: &str, + ) -> serde_json::Value { + let owners: Vec = owner + .map(|(kind, n)| json!({ "apiVersion": "apps/v1", "kind": kind, "name": n, "uid": "o", "controller": true })) + .into_iter() + .collect(); + json!({ + "apiVersion": "v1", "kind": "Pod", + "metadata": { "name": name, "namespace": ns, "uid": format!("uid-{name}"), "ownerReferences": owners }, + "status": { "phase": "Failed", "reason": "Evicted", "message": "The node had condition: [DiskPressure]. ", + "conditions": [{ "type": "Ready", "status": "False", "lastTransitionTime": ended }] }, + }) + } + + /// A run against a cluster where the proxy's DaemonSet loops on a + /// server short of disk: its pods go at once, each by its uid, but + /// only in Pyo's namespaces, never another's, and nothing young that + /// isn't looping. + #[tokio::test] + async fn a_run_cleans_up_a_loop_in_pyos_namespaces_only() { + use k8s_openapi::jiff::Timestamp; + let now = Timestamp::from_second(Timestamp::now().as_second()) + .unwrap() + .to_string(); + let ns = |name: &str, labels: serde_json::Value| json!({ "metadata": { "name": name, "labels": labels } }); + let mut cluster = fake::Cluster { + namespaces: vec![ + ns("pyo-gateway", json!({})), + ns("pyo-system", json!({})), + ns("theirs", json!({})), + ns( + "pyo-waf", + json!({ "pyo.dev/bundle": "waf", "pyo.dev/managed": "true" }), + ), + ], + ..Default::default() + }; + let ds = Some(("DaemonSet", "envoy-pyo-1")); + for i in 0..60 { + cluster + .pods + .push(failed_pod("pyo-gateway", &format!("envoy-{i}"), ds, &now)); + cluster.pods.push(failed_pod( + "theirs", + &format!("theirs-{i}"), + Some(("DaemonSet", "theirs")), + &now, + )); + cluster.pods.push(failed_pod( + "pyo-waf", + &format!("waf-{i}"), + Some(("DaemonSet", "pyo-waf")), + &now, + )); + } + // Just evicted, not looping: kept for now. + for i in 0..5 { + cluster.pods.push(failed_pod( + "pyo-system", + &format!("vector-{i}"), + Some(("DaemonSet", "pyo-vector")), + &now, + )); + } + let (client, st) = fake::serve(cluster).await; + + let run = once(&client, Duration::ZERO).await.unwrap(); + assert_eq!( + run, + Run { + deleted: 57, + storm: true + } + ); + { + let c = st.lock().unwrap(); + assert_eq!(c.deleted.len(), 57); + assert!( + c.deleted.iter().all(|(ns, name, uid)| ns == "pyo-gateway" + && name.starts_with("envoy-") + && *uid == format!("uid-{name}")), + "{:?}", + c.deleted + ); + // The newest three of the loop stay, and everything elsewhere. + assert_eq!( + c.pods + .iter() + .filter(|p| p["metadata"]["namespace"] == "pyo-gateway") + .count(), + KEEP + ); + assert_eq!(c.pods.len(), KEEP + 60 + 60 + 5); + // Only Pyo's namespaces are listed, Failed pods only, a page at a time. + let listed: Vec<&str> = c + .lists + .iter() + .map(|l| l.split('?').next().unwrap()) + .collect(); + assert_eq!(listed, ["pyo-gateway", "pyo-system"]); + assert!( + c.lists + .iter() + .all(|l| l.contains("fieldSelector=status.phase%3DFailed") + && l.contains("limit=")), + "{:?}", + c.lists + ); + } + + // Nothing looping any more: the next run is in minutes. + let run = once(&client, Duration::ZERO).await.unwrap(); + assert_eq!( + run, + Run { + deleted: 0, + storm: false + } + ); + } + #[test] fn only_failed_pods_not_jobs_and_not_being_deleted() { let evicted = pod(json!({ diff --git a/crates/pyo-agent/src/fakekube.rs b/crates/pyo-agent/src/fakekube.rs new file mode 100644 index 00000000..108edd66 --- /dev/null +++ b/crates/pyo-agent/src/fakekube.rs @@ -0,0 +1,348 @@ +//! A Kubernetes API server in memory, for tests that run the agent's +//! writes end to end without a cluster: objects by path, server-side apply +//! as a replace, merge patches, deletes, lists with label selectors, and an +//! admission check each test sets (an older admission policy, say). A dry +//! run is checked and not stored. + +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, +}; + +use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, Method, StatusCode, Uri, header}, + response::{IntoResponse, Response}, +}; +use serde_json::{Value, json}; + +/// A write the server was asked for. +#[derive(Debug, Clone)] +pub struct Write { + /// "PATCH", "POST", "PUT" or "DELETE". + pub method: String, + /// The resource, as in its path ("clienttrafficpolicies"). + pub plural: String, + pub name: String, + pub body: Value, +} + +/// The admission check: None lets a write through, Some((code, message)) +/// refuses it with that status. +pub type Admit = Arc Option<(u16, String)> + Send + Sync>; + +/// (API prefix such as "apis/apps/v1", resource, namespace, name). +type Key = (String, String, String, String); + +struct Inner { + objects: BTreeMap, + refused: Vec, + admit: Admit, +} + +#[derive(Clone)] +pub struct FakeKube(Arc>); + +/// A path's (prefix, namespace, resource, name). +fn parse(path: &str) -> Option<(String, String, String, String)> { + let seg: Vec<&str> = path.trim_matches('/').split('/').collect(); + let (prefix, rest) = match *seg.first()? { + "api" if seg.len() >= 2 => (seg[..2].join("/"), &seg[2..]), + "apis" if seg.len() >= 3 => (seg[..3].join("/"), &seg[3..]), + _ => return None, + }; + let at = |i: usize| rest.get(i).map(|s| s.to_string()).unwrap_or_default(); + Some(match rest { + ["namespaces", _, _, ..] => (prefix, at(1), at(2), at(3)), + _ => (prefix, String::new(), at(0), at(1)), + }) +} + +fn decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = vec![]; + let mut i = 0; + while i < b.len() { + match b[i] { + b'%' if i + 2 < b.len() => { + let hex = std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or(""); + match u8::from_str_radix(hex, 16) { + Ok(v) => { + out.push(v); + i += 3; + continue; + } + Err(_) => out.push(b'%'), + } + } + b'+' => out.push(b' '), + c => out.push(c), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn query(uri: &Uri, key: &str) -> Option { + uri.query()?.split('&').find_map(|kv| { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + (decode(k) == key).then(|| decode(v)) + }) +} + +/// Whether an object's labels match a label selector (`a=b`, `a!=b`, `a`, +/// `!a`, joined by commas). +fn selected(obj: &Value, selector: &str) -> bool { + let labels = &obj["metadata"]["labels"]; + selector.split(',').filter(|t| !t.is_empty()).all(|t| { + if let Some((k, v)) = t.split_once("!=") { + labels[k.trim()].as_str() != Some(v.trim()) + } else if let Some((k, v)) = t.split_once('=') { + labels[k.trim()].as_str() == Some(v.trim_start_matches('=').trim()) + } else if let Some(k) = t.strip_prefix('!') { + labels.get(k.trim()).is_none() + } else { + labels.get(t.trim()).is_some() + } + }) +} + +fn json_response(code: u16, body: Value) -> Response { + ( + StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), + [(header::CONTENT_TYPE, "application/json")], + body.to_string(), + ) + .into_response() +} + +fn status(code: u16, reason: &str, message: &str) -> Response { + json_response( + code, + json!({ "kind": "Status", "apiVersion": "v1", "metadata": {}, "status": if code < 400 { "Success" } else { "Failure" }, "message": message, "reason": reason, "code": code }), + ) +} + +/// RFC 7386: `patch` merged into `into`. +fn merge(into: &mut Value, patch: &Value) { + match (into, patch) { + (Value::Object(a), Value::Object(b)) => { + for (k, v) in b { + if v.is_null() { + a.remove(k); + } else { + merge(a.entry(k.clone()).or_insert(Value::Null), v); + } + } + } + (into, patch) => *into = patch.clone(), + } +} + +async fn handle( + State(fake): State, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + if uri.path() == "/version" { + return json_response( + 200, + json!({ "major": "1", "minor": "33", "gitVersion": "v1.33.0" }), + ); + } + let Some((prefix, ns, plural, name)) = parse(uri.path()) else { + return status(404, "NotFound", "no such path"); + }; + let mut inner = fake.0.lock().unwrap(); + let key = (prefix.clone(), plural.clone(), ns.clone(), name.clone()); + if method == Method::GET { + if !name.is_empty() { + return match inner.objects.get(&key) { + Some(o) => json_response(200, o.clone()), + None => status(404, "NotFound", &format!("{plural} \"{name}\" not found")), + }; + } + let selector = query(&uri, "labelSelector").unwrap_or_default(); + let items: Vec = inner + .objects + .iter() + .filter(|((p, r, n, _), _)| *p == prefix && *r == plural && (ns.is_empty() || *n == ns)) + .map(|(_, o)| o.clone()) + .filter(|o| selected(o, &selector)) + .collect(); + return json_response( + 200, + json!({ "apiVersion": "v1", "kind": "List", "metadata": { "resourceVersion": "1" }, "items": items }), + ); + } + let mut obj: Value = serde_json::from_slice(&body).unwrap_or(Value::Null); + let name = if name.is_empty() { + obj["metadata"]["name"].as_str().unwrap_or("").to_owned() + } else { + name + }; + let key = (prefix, plural.clone(), ns.clone(), name.clone()); + let write = Write { + method: method.to_string(), + plural: plural.clone(), + name: name.clone(), + body: obj.clone(), + }; + if method == Method::DELETE { + return match inner.objects.remove(&key) { + Some(_) => status(200, "", "deleted"), + None => status(404, "NotFound", &format!("{plural} \"{name}\" not found")), + }; + } + let merge_patch = headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|t| t.contains("merge-patch")); + if merge_patch { + let Some(have) = inner.objects.get(&key) else { + return status(404, "NotFound", &format!("{plural} \"{name}\" not found")); + }; + let mut merged = have.clone(); + merge(&mut merged, &obj); + obj = merged; + } + let refusal = (inner.admit)(&Write { + body: obj.clone(), + ..write.clone() + }); + if let Some((code, message)) = refusal { + inner.refused.push(write); + return status( + code, + if code == 403 { "Forbidden" } else { "Invalid" }, + &message, + ); + } + obj["metadata"]["name"] = json!(name); + if !ns.is_empty() { + obj["metadata"]["namespace"] = json!(ns); + } + if obj["metadata"]["creationTimestamp"].is_null() { + obj["metadata"]["creationTimestamp"] = json!("2026-01-01T00:00:00Z"); + } + obj["metadata"]["resourceVersion"] = json!("1"); + // A dry run goes through admission and writes nothing. + if query(&uri, "dryRun").is_none() { + inner.objects.insert(key, obj.clone()); + } + json_response(if method == Method::POST { 201 } else { 200 }, obj) +} + +impl FakeKube { + /// The server, and a client of it. Every write goes through until + /// [`FakeKube::admit`] says otherwise. + pub async fn start() -> (FakeKube, kube::Client) { + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let fake = FakeKube(Arc::new(Mutex::new(Inner { + objects: BTreeMap::new(), + refused: vec![], + admit: Arc::new(|_| None), + }))); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let app = Router::new().fallback(handle).with_state(fake.clone()); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + let config = kube::Config::new(url.parse().unwrap()); + (fake, kube::Client::try_from(config).unwrap()) + } + + /// The admission check from now on. + pub fn admit(&self, f: impl Fn(&Write) -> Option<(u16, String)> + Send + Sync + 'static) { + self.0.lock().unwrap().admit = Arc::new(f); + } + + /// Put an object at its path ("apis/apps/v1/namespaces/shop/deployments/web"). + pub fn put(&self, path: &str, mut obj: Value) { + let (prefix, ns, plural, name) = parse(path).expect("a resource path"); + obj["metadata"]["name"] = json!(name); + if !ns.is_empty() { + obj["metadata"]["namespace"] = json!(ns); + } + self.0 + .lock() + .unwrap() + .objects + .insert((prefix, plural, ns, name), obj); + } + + /// The object at a path, as the server has it. + pub fn get(&self, path: &str) -> Option { + let (prefix, ns, plural, name) = parse(path)?; + self.0 + .lock() + .unwrap() + .objects + .get(&(prefix, plural, ns, name)) + .cloned() + } + + /// The writes the admission check refused, oldest first. + pub fn refused(&self) -> Vec { + self.0.lock().unwrap().refused.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_and_selectors() { + assert_eq!( + parse( + "/apis/gateway.envoyproxy.io/v1alpha1/namespaces/pyo-gateway/clienttrafficpolicies/pyo-http" + ), + Some(( + "apis/gateway.envoyproxy.io/v1alpha1".into(), + "pyo-gateway".into(), + "clienttrafficpolicies".into(), + "pyo-http".into() + )) + ); + assert_eq!( + parse("/api/v1/namespaces/shop/services"), + Some(( + "api/v1".into(), + "shop".into(), + "services".into(), + String::new() + )) + ); + assert_eq!( + parse("/api/v1/namespaces/shop"), + Some(( + "api/v1".into(), + String::new(), + "namespaces".into(), + "shop".into() + )) + ); + assert_eq!( + parse("/apis/admissionregistration.k8s.io/v1/validatingadmissionpolicies/pyo-agent"), + Some(( + "apis/admissionregistration.k8s.io/v1".into(), + String::new(), + "validatingadmissionpolicies".into(), + "pyo-agent".into() + )) + ); + assert_eq!(decode("a%3Db%2Cc"), "a=b,c"); + let o = json!({ "metadata": { "labels": { "a": "1", "b": "2" } } }); + assert!(selected(&o, "a=1,b")); + assert!(selected(&o, "a==1,!c")); + assert!(!selected(&o, "a!=1")); + assert!(!selected(&o, "c")); + assert!(selected(&o, "")); + } +} diff --git a/crates/pyo-agent/src/firewall.rs b/crates/pyo-agent/src/firewall.rs index 04ef04c1..81532331 100644 --- a/crates/pyo-agent/src/firewall.rs +++ b/crates/pyo-agent/src/firewall.rs @@ -141,29 +141,17 @@ pub async fn sync(agent: &crate::Agent, sync: FirewallSync) -> anyhow::Result = vec![]; for t in &sync.targets { - // Its workload gone (a delete that ran first: commands on a service - // take turns, main.rs `ordered_keys`): its routes stay gone. - let spec = gateway::target_spec(t, sync.waf)?; - let Some((notes, _)) = gateway::apply_routes(agent, &spec, true).await? else { - skipped += 1; - continue; - }; - for note in notes { - tracing::warn!(service = %t.service.name, "{note}"); - } - // Ports that bypass the gateway: their Service carries the ranges the - // network policy lets in (rollout.rs's set_isolation writes it). - let services: Api = Api::namespaced(client.clone(), &t.service.namespace); - let public = crate::rollout::public_service_name(&t.service.name); - if services.get_opt(&public).await?.is_some() { - let patch = json!({ "metadata": { "annotations": { FIREWALL_ANNOTATION: gateway::ip_blocks_json(&gateway::fw_layers(&spec, None)) } } }); - services - .patch(&public, &PatchParams::default(), &Patch::Merge(&patch)) - .await?; + match apply_target(agent, t, sync.waf).await { + Ok(true) => n += 1, + Ok(false) => skipped += 1, + Err(e) => { + tracing::warn!(service = %t.service.name, error = %format!("{e:#}"), "couldn't apply the firewall to a service"); + failed.push(format!("{}: {e:#}", t.service.name)); + } } - crate::rollout::set_isolation(client, &t.service.namespace, t.network_isolation).await?; - n += 1; } // No service wants it: the routes no longer point at it (above); the // API removes it. @@ -175,8 +163,97 @@ pub async fn sync(agent: &crate::Agent, sync: FirewallSync) -> anyhow::Result format!("Firewall applied to {n} service(s)"), _ => format!("Firewall applied to {n} service(s); {skipped} no longer here"), - }) + }; + if !failed.is_empty() { + anyhow::bail!("{done}. It couldn't be applied to {}", failed.join(". ")); + } + Ok(done) +} + +/// Apply the firewall to one running service: its routes, its public +/// Service's ranges and its network policies. False when its workload is +/// gone (a delete that ran first: commands on a service take turns, main.rs +/// `ordered_keys`), and its routes stay gone. +async fn apply_target( + agent: &crate::Agent, + t: &pyo_proto::FirewallTarget, + waf: bool, +) -> anyhow::Result { + let client = &agent.kube; + let spec = gateway::target_spec(t, waf)?; + let Some((notes, _)) = gateway::apply_routes(agent, &spec, true).await? else { + return Ok(false); + }; + for note in notes { + tracing::warn!(service = %t.service.name, "{note}"); + } + // Ports that bypass the gateway: their Service carries the ranges the + // network policy lets in (rollout.rs's set_isolation writes it). + let services: Api = Api::namespaced(client.clone(), &t.service.namespace); + let public = crate::rollout::public_service_name(&t.service.name); + if services.get_opt(&public).await?.is_some() { + let patch = json!({ "metadata": { "annotations": { FIREWALL_ANNOTATION: gateway::ip_blocks_json(&gateway::fw_layers(&spec, None)) } } }); + services + .patch(&public, &PatchParams::default(), &Patch::Merge(&patch)) + .await?; + } + crate::rollout::set_isolation(client, &t.service.namespace, t.network_isolation).await?; + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A firewall sync goes on past a service whose routes fail: the + /// services after it still get theirs, and the sync says which failed. + #[tokio::test] + async fn one_failing_service_doesnt_stop_the_others() { + let (kube, client) = crate::fakekube::FakeKube::start().await; + let target = |name: &str| -> pyo_proto::FirewallTarget { + serde_json::from_value(json!({ + "service": { "serviceId": format!("svc_{name}"), "name": name, "namespace": format!("ns-{name}"), "workloadKind": "Deployment" }, + "projectId": "prj_1", "routesRevision": 1, "firewall": {}, + "ports": [{ "name": "http", "containerPort": 8080, "protocol": "HTTP", "exposure": "http", "publicPort": null }], + "domains": [{ "hostname": format!("{name}.example.com"), "portName": "http" }], + })) + .unwrap() + }; + let mut targets = vec![]; + for name in ["a", "b", "c"] { + kube.put( + &format!("apis/apps/v1/namespaces/ns-{name}/deployments/{name}"), + json!({ "apiVersion": "apps/v1", "kind": "Deployment", "metadata": { "labels": { crate::observe::SERVICE_LABEL: format!("svc_{name}") } } }), + ); + targets.push(target(name)); + } + // The first service's routes can't be written. + kube.admit(|w| w.body.to_string().contains("svc_a").then(|| (500, "etcd timeout".into()))); + let agent = crate::Agent { + kube: client, + api: crate::api::PyoApi::new("http://127.0.0.1:9", "t").unwrap(), + cancels: Default::default(), + deploying: Default::default(), + routes: Default::default(), + policy: std::sync::Arc::new(std::sync::RwLock::new(Default::default())), + }; + let e = sync(&agent, FirewallSync { targets, waf: false }) + .await + .expect_err("the first service failed"); + let e = format!("{e:#}"); + assert!(e.starts_with("Firewall applied to 2 service(s)."), "{e}"); + assert!(e.contains("a: ") && e.contains("etcd timeout"), "{e}"); + assert!(!e.contains("b: ") && !e.contains("c: "), "{e}"); + let route = |name: &str| { + kube.get(&format!( + "apis/gateway.networking.k8s.io/v1/namespaces/{GATEWAY_NS}/httproutes/ns-{name}-{name}-http-http" + )) + }; + assert!(route("a").is_none()); + assert!(route("b").is_some(), "the service after it"); + assert!(route("c").is_some(), "and the last one"); + } } diff --git a/crates/pyo-agent/src/gateway.rs b/crates/pyo-agent/src/gateway.rs index 3fd7f458..29bfaa11 100644 --- a/crates/pyo-agent/src/gateway.rs +++ b/crates/pyo-agent/src/gateway.rs @@ -25,7 +25,7 @@ use std::{ collections::BTreeMap, - sync::atomic::{AtomicU8, Ordering}, + sync::atomic::{AtomicBool, AtomicU8, Ordering}, }; use k8s_openapi::api::core::v1::Secret; @@ -349,7 +349,7 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { for p in &ports { let hosts: Vec<&str> = secure .iter() - .filter(|d| d.port_name == *p) + .filter(|d| d.port_name == *p && !d.via_tunnel()) .map(|d| d.hostname.as_str()) .collect(); if !hosts.is_empty() { @@ -358,14 +358,46 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { "spec": { "parentRefs": [{ "name": base }], "hostnames": hosts, "rules": [web_rule(p)] }, })); } + // Through the Cloudflare Tunnel: routes of their own, so the + // gate (once switched) and the cf-visitor redirect apply to + // those names only. Grouped by switched or not, and by redirect. + for (only, redirect) in [(true, true), (true, false), (false, true), (false, false)] { + let hosts: Vec<&str> = secure + .iter() + .filter(|d| { + d.port_name == *p + && d.via_tunnel() + && d.tunnel_only() == only + && d.redirect_https == redirect + }) + .map(|d| d.hostname.as_str()) + .collect(); + if hosts.is_empty() { + continue; + } + let mut rules = vec![]; + if redirect { + rules.push(tunnel_redirect_rule()); + } + // X-Forwarded-For is the visitor alone, not the visitor + // and then the connector's pod. + rules.push(system::tunnel_rule(web_rule(p))); + out.objects.push(json!({ + "apiVersion": "gateway.networking.k8s.io/v1", "kind": "HTTPRoute", + "metadata": meta(&tunnel_route_name(&base, only, redirect, p)), + "spec": { "parentRefs": [{ "name": base }], "hostnames": hosts, "rules": rules }, + })); + } } } // HTTP, on the shared :80 listener: redirects, then plain HTTP. let http_parent = json!([{ "name": HTTP_GATEWAY, "sectionName": "http" }]); + // A domain switched to the tunnel has no plain HTTP route: nothing + // reaches it directly any more (cloudflared speaks HTTPS). let redirect: Vec<&str> = secure .iter() - .filter(|d| d.redirect_https) + .filter(|d| d.redirect_https && !d.tunnel_only()) .map(|d| d.hostname.as_str()) .collect(); if !redirect.is_empty() { @@ -381,6 +413,7 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { .filter(reachable) .filter(public) .filter(|d| d.port_name == *p && !(!d.tls.is_empty() && d.redirect_https)) + .filter(|d| !d.tunnel_only()) .map(|d| d.hostname.as_str()) .collect(); if !hosts.is_empty() { @@ -428,11 +461,17 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { .filter(|n| !n.ends_with("-redirect")) .map(str::to_owned) .collect(); + // Switched to the tunnel: only its connectors get through. + let tunnel_auth = Some(pyo_proto::firewall::tunnel_authorization(&fw)); for name in names { - let https = name.starts_with(&format!("{base}-https-")); + let tunnel_on = name.starts_with(&format!("{base}-tunnel-")); + let https = name.starts_with(&format!("{base}-https-")) + || name.starts_with(&format!("{base}-switching-")); let on_tailnet = name.starts_with(system::TAILNET_ROUTE_PREFIX); let (authorization, rate) = if on_tailnet { (&None, rate.as_ref()) + } else if tunnel_on { + (&tunnel_auth, rate.as_ref()) } else if https { (&https_auth, rate.as_ref()) } else { @@ -468,10 +507,11 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { // settings (origin pull, PROXY protocol) are filled in as the cluster // has them when it's applied (`apply`). Without the CDN's ranges // nothing is trusted, so the CDN check above refuses everyone. + let direct: Vec<&&DomainSpec> = secure.iter().filter(|d| !d.via_tunnel()).collect(); if let Some((cdn, ranges)) = fw.behind_ranges().filter(|(_, r)| !r.is_empty()) - && !secure.is_empty() + && !direct.is_empty() { - let sections: Vec = secure + let sections: Vec = direct .iter() .map(|d| format!("h-{}", host_hash(&d.hostname))) .collect(); @@ -484,6 +524,32 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { })); } + // Through the tunnel: those listeners read the visitor from + // X-Forwarded-For only on connections from the tunnel's connectors + // (their pods' addresses, filled in when it's applied). While a domain + // switches, a service behind a CDN also still trusts the CDN, which + // reaches it directly until the record moves. + let tunneled: Vec<&&DomainSpec> = secure.iter().filter(|d| d.via_tunnel()).collect(); + if !tunneled.is_empty() { + let sections: Vec = tunneled + .iter() + .map(|d| format!("h-{}", host_hash(&d.hostname))) + .collect(); + let switching = tunneled.iter().any(|d| !d.tunnel_only()); + let extra: Vec = fw + .behind_ranges() + .filter(|_| switching) + .map(|(_, r)| r) + .unwrap_or_default(); + let name = system::tunnel_policy_name(&base); + let mut m = meta(&name); + m["labels"][system::CDN_LABEL] = json!(system::TUNNEL_CDN); + out.objects.push(json!({ + "apiVersion": "gateway.envoyproxy.io/v1alpha1", "kind": "ClientTrafficPolicy", "metadata": m, + "spec": system::cdn_client_policy_spec(system::TUNNEL_CDN, &base, §ions, system::WebSettings::default(), &pyo_proto::firewall::trusted_or_nothing(extra)), + })); + } + // The WAF: with the service's WAF on, its routes go through the // processor first (its custom rules, then the OWASP rules), failing // closed in block mode. The service's WAF rides on the policy, and the @@ -525,6 +591,30 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { pub use system::WAF_ANNOTATION; +/// A service's route for its tunnel domains on a port: switched ("tunnel") +/// or switching, with or without the redirect to HTTPS ("-plain"). +pub fn tunnel_route_name(base: &str, only: bool, redirect: bool, port: &str) -> String { + format!( + "{base}-{}{}-{port}", + if only { "tunnel" } else { "switching" }, + if redirect { "" } else { "-plain" } + ) +} + +/// The value of `cf-visitor` Cloudflare sets on a request a visitor made +/// over plain HTTP. +pub const CF_VISITOR_HTTP: &str = r#"{"scheme":"http"}"#; + +/// A tunnel route's first rule with the redirect to HTTPS on: a request +/// Cloudflare took over plain HTTP (its `cf-visitor` says so) goes to +/// HTTPS, whatever the zone's own settings. +pub fn tunnel_redirect_rule() -> Value { + json!({ + "matches": [{ "headers": [{ "type": "Exact", "name": "cf-visitor", "value": CF_VISITOR_HTTP }] }], + "filters": [{ "type": "RequestRedirect", "requestRedirect": { "scheme": "https", "statusCode": 301 } }], + }) +} + /// Marks a UDP route with the address ranges its port lets in, for the /// network policy on the proxy's pods ("" when open), and with where the /// proxy listens for it. @@ -677,12 +767,21 @@ pub async fn apply( notes.push(p.clone()); } let mut r = route_objects(spec); - // Behind a CDN: its HTTPS client policy as the cluster's websites have - // theirs otherwise. - if let Some(o) = r.objects.iter_mut().find(|o| { + // Behind a CDN, or through the tunnel: its HTTPS client policy as the + // cluster's websites have theirs otherwise. The tunnel's trusts its + // connectors' pods as they are now. + let mut w = None; + for o in r.objects.iter_mut().filter(|o| { o["kind"] == "ClientTrafficPolicy" && o["metadata"]["labels"][system::CDN_LABEL].is_string() }) { - let w = web_settings(client).await?; + let w = match w { + Some(w) => w, + None => *w.insert(web_settings(client).await?), + }; + if o["metadata"]["labels"][system::CDN_LABEL] == system::TUNNEL_CDN { + let pods = crate::tunnel::trusted_now(); + set_trusted(o, |have| with_pods(have, &[], &pods)); + } rewrite_cdn_policy(o, w); } // New public TCP and UDP ports wait for the servers to free them (a port @@ -765,8 +864,22 @@ pub async fn apply( let kind = o["kind"].as_str().unwrap_or("").to_owned(); let name = o["metadata"]["name"].as_str().unwrap_or("").to_owned(); let api = api_of(client, &kind); - match api.patch(&name, &pp(), &Patch::Apply(o)).await { - Ok(_) => {} + let written = if kind == "ClientTrafficPolicy" { + write_client_policy(&api, &name, o).await + } else { + api.patch(&name, &pp(), &Patch::Apply(o)).await.map(|_| ()) + }; + let tunnel_policy = kind == "ClientTrafficPolicy" + && o["metadata"]["labels"][system::CDN_LABEL] == system::TUNNEL_CDN; + match written { + Ok(()) => {} + // An install older than this agent doesn't know the tunnel's + // policy: the rest of the routes still go on, and it's said. + Err(e) if tunnel_policy && crate::refused::is_refusal(&e) => { + crate::tunnel::refused_now(&e); + notes.push(crate::tunnel::REFUSED.into()); + continue; + } Err(kube::Error::Api(e)) if e.code == 404 && kind == "Certificate" => { notes.push("cert-manager is still being installed on this cluster. HTTPS starts with a later deploy.".into()); } @@ -1479,11 +1592,18 @@ pub async fn remove(client: &Client, service_id: &str) { /// manifest that also allows it) reaches the proxies, which then roll. The /// tailnet Gateway follows the API's wanted list (tailnet.rs). /// One the cluster's install refuses (older than Pyo's, until the -/// cluster's connect command runs) waits for that install to change. +/// cluster's connect command runs) waits for that install to change. So do +/// client policies and the proxies' settings written as an older install +/// accepts them ([`headers_kept`], [`priority_left_out`]): they're written +/// again once it changes. pub async fn ensure(client: Client) { let mut refusals = 0; loop { match ensure_once(&client).await { + Ok(()) if headers_kept() || priority_left_out() => { + refusals += 1; + crate::refused::wait_for_install(&client, refusals).await; + } Ok(()) => { tracing::info!("gateway ready"); return; @@ -1593,15 +1713,8 @@ pub async fn set_public_traffic(client: &Client, on: bool) { { return; } - match proxies - .patch( - "pyo", - &pp(), - &Patch::Apply(system::envoy_proxy(&system::geoip_image_from_env(), on)), - ) - .await - { - Ok(_) => tracing::info!(on, "public traffic"), + match write_envoy_proxy(&proxies, on).await { + Ok(()) => tracing::info!(on, "public traffic"), Err(e) if crate::refused::is_refusal(&e) => { tracing::warn!(error = %e, "couldn't change public traffic (run the cluster's connect command)"); if let Ok(mut r) = PUBLIC_REFUSED.lock() { @@ -1615,6 +1728,46 @@ pub async fn set_public_traffic(client: &Client, on: bool) { /// The public traffic setting the install refused, and that install's stamp. static PUBLIC_REFUSED: std::sync::Mutex> = std::sync::Mutex::new(None); +/// Said once in the agent's log when the cluster's install refuses the +/// proxies' priority. +pub const PRIORITY_LEFT_OUT: &str = "This cluster needs a refresh. Run the command under Refresh this cluster in the cluster's settings so the proxies keep running on a server short of disk."; + +/// Whether the agent last wrote the proxies' settings without their +/// priority because the install refused it. +static LEFT_OUT: AtomicBool = AtomicBool::new(false); + +pub fn priority_left_out() -> bool { + LEFT_OUT.load(Ordering::Relaxed) +} + +/// Write the proxies' settings, published or not. When the cluster's +/// install refuses them (its admission policy is older than this agent's +/// and lists them without their pods' priority), they're written as that +/// install accepts, so the gateway's other settings still follow and +/// public traffic can still be switched. That's said once +/// ([`PRIORITY_LEFT_OUT`]), and [`ensure`] writes them whole once the +/// install changes. +async fn write_envoy_proxy(proxies: &Api, public: bool) -> kube::Result<()> { + let o = system::envoy_proxy(&system::geoip_image_from_env(), public); + let refused = match proxies.patch("pyo", &pp(), &Patch::Apply(&o)).await { + Ok(_) => { + LEFT_OUT.store(false, Ordering::Relaxed); + return Ok(()); + } + Err(e) => e, + }; + let Some(older) = system::envoy_proxy_without_priority(&o) + .filter(|_| crate::refused::is_refusal(&refused)) + else { + return Err(refused); + }; + proxies.patch("pyo", &pp(), &Patch::Apply(&older)).await?; + if !LEFT_OUT.swap(true, Ordering::Relaxed) { + tracing::warn!(error = %refused, "{PRIORITY_LEFT_OUT}"); + } + Ok(()) +} + /// The Tailscale addresses the websites are published on: every server's /// that runs a proxy (all but build-only ones), from what locate.rs found, /// else a node address on the tailnet. Sorted, once each. @@ -1767,6 +1920,123 @@ pub fn public_nat_ips(nodes: &[k8s_openapi::api::core::v1::Node]) -> Vec static PUBLIC_NAT_REFUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// The gateway's public TCP and UDP ports (its `-ports` Gateways' +/// listeners) as (protocol, port). +pub fn l4_ports(gateways: &[DynamicObject]) -> Vec<(String, i32)> { + let mut out: Vec<(String, i32)> = gateways + .iter() + .filter(|g| g.labels().get(GATEWAY_LABEL).map(String::as_str) == Some(system::L4_GATEWAY)) + .flat_map(|g| { + g.data["spec"]["listeners"] + .as_array() + .cloned() + .unwrap_or_default() + }) + .filter_map(|l| { + Some(( + l["protocol"].as_str()?.to_owned(), + i32::try_from(l["port"].as_i64()?).ok()?, + )) + }) + .collect(); + out.sort(); + out.dedup(); + out +} + +static PUBLIC_PORTS_REFUSED: AtomicBool = AtomicBool::new(false); +/// The public ports Service couldn't be read at the last heartbeat: said +/// once, then again only after a read went through. +static PUBLIC_PORTS_UNREAD: AtomicBool = AtomicBool::new(false); + +/// Whether to say that a state holds: only when it starts (`flag` goes on). +/// [`settled`] turns it off again. +pub(crate) fn first_time(flag: &AtomicBool) -> bool { + !flag.swap(true, Ordering::Relaxed) +} + +pub(crate) fn settled(flag: &AtomicBool) { + flag.store(false, Ordering::Relaxed); +} + +/// In tunnel mode with public TCP and UDP ports kept, the proxies' own +/// Service isn't published, so their ports go out through one of their +/// own (system.rs `PUBLIC_PORTS_SERVICE`). Off, or with no such port: none. +/// From each heartbeat's reply. +pub async fn set_public_ports_service(client: &Client, on: bool) { + let services: Api = + Api::namespaced(client.clone(), GATEWAY_NS); + let ports = if on { + match api_of(client, "Gateway").list(&ListParams::default()).await { + Ok(l) => l4_ports(&l.items), + Err(e) => { + tracing::warn!(error = %e, "couldn't list the gateway's ports"); + return; + } + } + } else { + vec![] + }; + let current = match services.get_opt(system::PUBLIC_PORTS_SERVICE).await { + Ok(s) => { + settled(&PUBLIC_PORTS_UNREAD); + s + } + // Every heartbeat asks: an install that refuses the read (one not + // refreshed yet) is said once, not each time. + Err(e) => { + if first_time(&PUBLIC_PORTS_UNREAD) { + tracing::warn!(error = %e, "couldn't read the public ports Service"); + } + return; + } + }; + match system::public_ports_service(&ports) { + None if current.is_none() => {} + None => match services + .delete(system::PUBLIC_PORTS_SERVICE, &DeleteParams::default()) + .await + { + Ok(_) => tracing::info!("no public TCP or UDP ports in tunnel mode"), + Err(e) => tracing::warn!(error = %e, "couldn't remove the public ports Service"), + }, + Some(want) => { + let have = current + .and_then(|s| s.spec) + .and_then(|s| s.ports) + .map(|p| serde_json::to_value(p).unwrap_or_default()); + let same = have.as_ref().is_some_and(|h| { + let strip = |v: &Value| -> Vec { + v.as_array() + .into_iter() + .flatten() + .map(|p| json!([p["name"], p["port"], p["targetPort"], p["protocol"]])) + .collect() + }; + strip(h) == strip(&want["spec"]["ports"]) + }); + if same { + return; + } + match services + .patch(system::PUBLIC_PORTS_SERVICE, &pp(), &Patch::Apply(&want)) + .await + { + Ok(_) => { + PUBLIC_PORTS_REFUSED.store(false, Ordering::Relaxed); + tracing::info!(?ports, "public TCP and UDP ports published in tunnel mode"); + } + Err(e) if crate::refused::is_refusal(&e) => { + if !PUBLIC_PORTS_REFUSED.swap(true, Ordering::Relaxed) { + tracing::warn!(error = %e, "couldn't publish the public ports in tunnel mode (run the cluster's connect command)"); + } + } + Err(e) => tracing::warn!(error = %e, "couldn't write the public ports Service"), + } + } + } +} + /// The cluster's own requests to the public IPs behind the cloud's NAT go /// to the proxies (system.rs `PUBLIC_NAT_SERVICE`), while it takes public /// traffic (from each heartbeat's reply): the Service written or removed @@ -1854,13 +2124,7 @@ async fn ensure_once(client: &Client) -> anyhow::Result<()> { } } let public = wanted_public(heard_public(), current); - proxies - .patch( - "pyo", - &pp(), - &Patch::Apply(system::envoy_proxy(&system::geoip_image_from_env(), public)), - ) - .await?; + write_envoy_proxy(&proxies, public).await?; let classes = Api::::all_with( client.clone(), &resource( @@ -1906,26 +2170,19 @@ async fn web_settings(client: &Client) -> anyhow::Result { async fn write_web(client: &Client, w: system::WebSettings) -> anyhow::Result<()> { let policies = api_of(client, "ClientTrafficPolicy"); - policies - .patch( - "pyo-http", - &pp(), - &Patch::Apply(system::client_policy( - false, - system::WebSettings { - origin_pull: false, - ..w - }, - )), - ) - .await?; - policies - .patch( - "pyo-https", - &pp(), - &Patch::Apply(system::client_policy(true, w)), - ) - .await?; + write_client_policy( + &policies, + "pyo-http", + &system::client_policy( + false, + system::WebSettings { + origin_pull: false, + ..w + }, + ), + ) + .await?; + write_client_policy(&policies, "pyo-https", &system::client_policy(true, w)).await?; // Services behind a CDN: their HTTPS policies follow. let cdn = policies .list(&ListParams::default().labels(system::CDN_LABEL)) @@ -1938,18 +2195,123 @@ async fn write_web(client: &Client, w: system::WebSettings) -> anyhow::Result<() "spec": p.data["spec"].clone(), }); rewrite_cdn_policy(&mut o, w); - policies.patch(&name, &pp(), &Patch::Apply(&o)).await?; + write_client_policy(&policies, &name, &o).await?; + } + Ok(()) +} + +/// Said once in the agent's log when the cluster's install refuses the +/// client policies that remove client-sent visitor headers. +pub const HEADERS_KEPT: &str = "This cluster's install is older than Pyo's. Run the connect command in the cluster's settings so client-sent visitor headers are removed."; + +/// Whether the agent last wrote a client policy without its `headers` +/// because the install refused them. Sent with each heartbeat +/// (`AgentScope::headers_kept`). +static KEPT: AtomicBool = AtomicBool::new(false); + +pub fn headers_kept() -> bool { + KEPT.load(Ordering::Relaxed) +} + +/// A client policy without its `headers`: the shape an install whose +/// admission policy is older than this agent's accepts (it lists the +/// policies as they were before they removed visitor headers). +pub fn without_headers(o: &Value) -> Option { + o["spec"].get("headers")?; + let mut older = o.clone(); + older["spec"].as_object_mut()?.remove("headers"); + Some(older) +} + +/// Write a ClientTrafficPolicy. When the cluster's install refuses one +/// that removes visitor headers (its admission policy is older than this +/// agent's, and the cluster can't refresh it), it's written without them, +/// as that install accepts, so routes, certificates and the rest still go +/// on. That's said once ([`HEADERS_KEPT`]) and reported until such a +/// write goes through. +async fn write_client_policy(api: &Api, name: &str, o: &Value) -> kube::Result<()> { + let refused = match api.patch(name, &pp(), &Patch::Apply(o)).await { + Ok(_) => { + if o["spec"].get("headers").is_some() { + KEPT.store(false, Ordering::Relaxed); + } + return Ok(()); + } + Err(e) => e, + }; + let Some(older) = without_headers(o).filter(|_| crate::refused::is_refusal(&refused)) else { + return Err(refused); + }; + api.patch(name, &pp(), &Patch::Apply(&older)).await?; + if !KEPT.swap(true, Ordering::Relaxed) { + tracing::warn!(policy = name, error = %refused, "{HEADERS_KEPT}"); } Ok(()) } /// A service's CDN client policy with these websites' settings, its CDN, /// listeners and trusted ranges as they are. -fn rewrite_cdn_policy(o: &mut Value, w: system::WebSettings) { +/// A client policy's trusted ranges, changed by `f`. +fn set_trusted(o: &mut Value, f: impl FnOnce(Vec) -> Vec) { + let have: Vec = o["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| c.as_str().map(str::to_owned)) + .collect(); + o["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"] = json!(f(have)); +} + +/// A tunnel policy's trusted ranges with the connectors' pods now `pods` +/// instead of `old`: the rest (a CDN's ranges while a domain switches) +/// stays. Never empty. +pub fn with_pods(have: Vec, old: &[String], pods: &[String]) -> Vec { + let nothing = pyo_proto::firewall::trusted_or_nothing(vec![]); + let mut out: Vec = have + .into_iter() + .filter(|c| !old.contains(c) && !nothing.contains(c)) + .chain(pods.iter().cloned()) + .collect(); + out.truncate(system::MAX_TRUSTED_CIDRS); + pyo_proto::firewall::trusted_or_nothing(out) +} + +/// The connectors' pods moved (`old` → `pods`): every tunnel policy +/// trusts the new ones. Refused by an older install: said, and kept. +pub async fn set_tunnel_pods(client: &Client, old: &[String], pods: &[String]) -> anyhow::Result<()> { + let policies = api_of(client, "ClientTrafficPolicy"); + let found = policies + .list(&ListParams::default().labels(&format!("{}={}", system::CDN_LABEL, system::TUNNEL_CDN))) + .await?; + for p in found { + let name = p.name_any(); + let mut o = json!({ + "apiVersion": "gateway.envoyproxy.io/v1alpha1", "kind": "ClientTrafficPolicy", + "metadata": { "name": name, "namespace": GATEWAY_NS, "labels": p.labels() }, + "spec": p.data["spec"].clone(), + }); + set_trusted(&mut o, |have| with_pods(have, old, pods)); + if let Err(e) = write_client_policy(&policies, &name, &o).await { + if crate::refused::is_refusal(&e) { + crate::tunnel::refused_now(&e); + continue; + } + return Err(e.into()); + } + } + Ok(()) +} + +fn rewrite_cdn_policy(o: &mut Value, mut w: system::WebSettings) { let cdn = o["metadata"]["labels"][system::CDN_LABEL] .as_str() .unwrap_or("") .to_owned(); + // cloudflared has no origin pull certificate: the tunnel's listeners + // never ask for one (only its connectors reach them anyway). + if cdn == system::TUNNEL_CDN { + w.origin_pull = false; + } let spec = &o["spec"]; let gateway = spec["targetRefs"][0]["name"] .as_str() @@ -2004,19 +2366,18 @@ pub async fn set_origin_pull(client: &Client, ca_pem: &str) -> anyhow::Result anyhow::Result = ctp["spec"]["targetRefs"] + .as_array() + .unwrap() + .iter() + .map(|t| t["sectionName"].as_str().unwrap().to_owned()) + .collect(); + let mut want: Vec = ["moving.example.com", "done.example.com", "raw.example.com"] + .iter() + .map(|h| format!("h-{}", host_hash(h))) + .collect(); + want.sort(); + let mut got = sections.clone(); + got.sort(); + assert_eq!(got, want); + assert_eq!( + ctp["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"], + json!(["0.0.0.0/32"]) + ); + assert_eq!( + ctp["spec"]["headers"], + system::visitor_headers(&["cf-connecting-ip", "cf-connecting-ipv6"]) + ); + // No direct-domain CDN policy: the service isn't behind one. + assert!(!r.objects.iter().any(|o| o["metadata"]["name"] == "shop-web-cdn")); + } + + #[test] + fn behind_cloudflare_with_tunnel_domains_splits_the_listeners() { + let cf = vec!["173.245.48.0/20".to_owned()]; + let mut s = spec(vec![ + domain("shop.example.com", "http", "letsencrypt", false), + DomainSpec { + tunnel: pyo_proto::TUNNEL_SWITCHING.into(), + ..domain("blog.example.com", "http", "custom", false) + }, + ]); + s.firewall = Some(Firewall { + rules: vec![], + presets: [("cloudflare".to_owned(), cf.clone())].into(), + behind: Some("cloudflare".into()), + }); + let r = route_objects(&s); + let refs = |name: &str| find(&r, "ClientTrafficPolicy", name)["spec"]["targetRefs"].clone(); + assert_eq!( + refs("shop-web-cdn")[0]["sectionName"], + format!("h-{}", host_hash("shop.example.com")) + ); + assert_eq!(refs("shop-web-cdn").as_array().unwrap().len(), 1); + assert_eq!( + refs("shop-web-tunnel")[0]["sectionName"], + format!("h-{}", host_hash("blog.example.com")) + ); + // While it switches, Cloudflare still reaches it directly too. + assert_eq!( + find(&r, "ClientTrafficPolicy", "shop-web-tunnel")["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"], + json!(cf) + ); + // Switched: only the connectors. + s.domains[1].tunnel = pyo_proto::TUNNEL_ON.into(); + let r = route_objects(&s); + assert_eq!( + find(&r, "ClientTrafficPolicy", "shop-web-tunnel")["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"], + json!(["0.0.0.0/32"]) + ); + // The gate is the tunnel's, not doubled with the service's own. + let rules = find(&r, "SecurityPolicy", "shop-web-tunnel-plain-http")["spec"]["authorization"]["rules"].clone(); + let gates = rules + .as_array() + .unwrap() + .iter() + .filter(|r| **r == pyo_proto::firewall::behind_gate_rule()) + .count(); + assert_eq!(gates, 1); + } + + #[test] + fn tunnel_mode_publishes_the_gateways_own_ports() { + let gw = |name: &str, label: &str, listeners: Value| -> DynamicObject { + serde_json::from_value(json!({ + "apiVersion": "gateway.networking.k8s.io/v1", "kind": "Gateway", + "metadata": { "name": name, "namespace": GATEWAY_NS, "labels": { GATEWAY_LABEL: label } }, + "spec": { "listeners": listeners }, + })) + .unwrap() + }; + let all = [ + gw("shop-db-ports", system::L4_GATEWAY, json!([{ "name": "tcp-5432", "port": 5432, "protocol": "TCP" }, { "name": "udp-27015", "port": 27015, "protocol": "UDP" }])), + gw("shop-mq-ports", system::L4_GATEWAY, json!([{ "name": "tcp-5432", "port": 5432, "protocol": "TCP" }])), + gw("shop-web", "https", json!([{ "name": "h-1", "port": 443, "protocol": "HTTPS" }])), + ]; + assert_eq!( + l4_ports(&all), + [("TCP".to_owned(), 5432), ("UDP".to_owned(), 27015)] + ); + } + + #[test] + fn tunnel_policies_follow_the_connectors_pods() { + let old = vec!["10.42.0.5/32".to_owned()]; + let cf = "173.245.48.0/20".to_owned(); + assert_eq!( + with_pods(vec!["0.0.0.0/32".into()], &[], &["10.42.0.9/32".into()]), + ["10.42.0.9/32"] + ); + assert_eq!( + with_pods(vec![cf.clone(), old[0].clone()], &old, &["10.42.1.2/32".into()]), + ["10.42.1.2/32", cf.as_str()] + ); + // No pods: nobody, never anyone. + assert_eq!(with_pods(old.clone(), &old, &[]), ["0.0.0.0/32"]); + } + + /// An install older than the agent refuses the tunnel's client policy: + /// the rest of the deploy still goes on, and it's said. + #[tokio::test] + async fn a_refused_tunnel_policy_leaves_the_rest_of_the_routes() { + let (kube, client) = crate::fakekube::FakeKube::start().await; + kube.admit(|w| { + (w.plural == "clienttrafficpolicies" && w.name.ends_with("-tunnel")).then(|| (403, "clienttrafficpolicies.gateway.envoyproxy.io \"shop-web-tunnel\" is forbidden: ValidatingAdmissionPolicy 'pyo-agent' with binding 'pyo-agent' denied request".into())) + }); + let b = spec(vec![DomainSpec { + tunnel: pyo_proto::TUNNEL_ON.into(), + ..domain("shop.example.com", "http", "selfsigned", true) + }]); + let pyo = PyoApi::new("http://127.0.0.1:9", "t").unwrap(); + let notes = apply(&client, &pyo, &b).await.expect("the routes"); + assert!(notes.contains(&crate::tunnel::REFUSED.to_owned()), "{notes:?}"); + } + #[test] fn behind_cloudflare_routes() { let mut s = spec(vec![ @@ -4161,4 +4729,246 @@ mod tests { .delete("whoami", &DeleteParams::default()) .await; } + + /// The tests that write as an older install does share what the agent + /// keeps of it (whether visitor headers stayed): one at a time. + static OLDER_INSTALL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + + /// A state that holds at every heartbeat is said when it starts, and + /// again only after it stopped holding. + #[test] + fn a_lasting_state_is_said_once() { + let flag = AtomicBool::new(false); + assert!(first_time(&flag)); + assert!(!first_time(&flag)); + assert!(!first_time(&flag)); + settled(&flag); + assert!(first_time(&flag)); + } + + /// What a cluster still on 0.5.4's admission policy accepts of the + /// client policies: the shared ones only as listed then (before they + /// removed visitor headers), a CDN's only without `headers`, and no + /// tailnet one. Kubernetes' words for a refusal. + pub(crate) fn admission_054(w: &crate::fakekube::Write) -> Option<(u16, String)> { + if w.plural != "clienttrafficpolicies" || w.method == "DELETE" { + return None; + } + let shared: Vec = [false, true] + .into_iter() + .flat_map(system::client_policy_variants) + .filter_map(|v| without_headers(&json!({ "spec": v })).map(|o| o["spec"].clone())) + .collect(); + let spec = &w.body["spec"]; + let ok = match w.name.as_str() { + "pyo-http" | "pyo-https" => shared.contains(spec), + system::TAILNET_GATEWAY => false, + _ => spec.get("headers").is_none(), + }; + (!ok).then(|| (403, format!("clienttrafficpolicies.gateway.envoyproxy.io \"{}\" is forbidden: ValidatingAdmissionPolicy 'pyo-agent' with binding 'pyo-agent' denied request: failed expression: gatewayAllowed", w.name))) + } + + /// A cluster that can't refresh its install (Pyo Cloud, self-update + /// off, read only) keeps 0.5.4's admission policy after the agent + /// moves on. Its client policies go in without the visitor headers' + /// removal, and the rest of a deploy's routes still does: the WAF's + /// policies after the CDN's client policy, the stale route's removal, + /// the gateway's settings. That's reported (the heartbeat's + /// `headersKept`) until the connect command brings the new policy. + #[tokio::test] + async fn an_older_admission_policy_gets_client_policies_without_headers() { + use pyo_proto::{Waf, WafSettings}; + let _one = OLDER_INSTALL.lock().await; + let (kube, client) = crate::fakekube::FakeKube::start().await; + let at = |kind: &str, name: &str| { + let (group, plural) = match kind { + "HTTPRoute" => ("gateway.networking.k8s.io/v1", "httproutes"), + "EnvoyExtensionPolicy" => ("gateway.envoyproxy.io/v1alpha1", "envoyextensionpolicies"), + "SecurityPolicy" => ("gateway.envoyproxy.io/v1alpha1", "securitypolicies"), + _ => ("gateway.envoyproxy.io/v1alpha1", "clienttrafficpolicies"), + }; + format!("apis/{group}/namespaces/{GATEWAY_NS}/{plural}/{name}") + }; + kube.admit(admission_054); + // A route an earlier deploy made, that this one no longer has. + kube.put( + &at("HTTPRoute", "shop-web-old"), + json!({ "apiVersion": "gateway.networking.k8s.io/v1", "kind": "HTTPRoute", "metadata": { "labels": { SERVICE_LABEL: "svc_web" } }, "spec": {} }), + ); + // Behind Cloudflare, with its WAF on. + let mut b = spec(vec![domain("shop.example.com", "http", "letsencrypt", true)]); + b.firewall = Some(Firewall { + behind: Some("cloudflare".into()), + presets: [("cloudflare".to_owned(), vec!["173.245.48.0/20".to_owned()])].into(), + ..Default::default() + }); + b.waf = Some(Waf { + settings: WafSettings { + mode: "block".into(), + level: 1, + ..Default::default() + }, + rules: vec![], + }); + let pyo = PyoApi::new("http://127.0.0.1:9", "t").unwrap(); + let notes = apply(&client, &pyo, &b).await.expect("the deploy's routes"); + assert!(notes.is_empty(), "{notes:?}"); + // Refused with its headers, then written as 0.5.4 wrote it. + assert!( + kube.refused() + .iter() + .any(|w| w.name == "shop-web-cdn" && w.body["spec"]["headers"].is_object()) + ); + let cdn = kube.get(&at("ClientTrafficPolicy", "shop-web-cdn")).expect("the CDN's client policy"); + assert!(cdn["spec"].get("headers").is_none(), "{cdn}"); + assert_eq!( + cdn["spec"]["clientIPDetection"], + json!({ "xForwardedFor": { "trustedCIDRs": ["173.245.48.0/20"] } }) + ); + assert_eq!(cdn["metadata"]["labels"][system::CDN_LABEL], "cloudflare"); + // What comes after it. + for (kind, name) in [ + ("HTTPRoute", "shop-web-https-http"), + ("SecurityPolicy", "shop-web-https-http"), + ("EnvoyExtensionPolicy", "shop-web-https-http"), + ] { + assert!(kube.get(&at(kind, name)).is_some(), "{kind} {name}"); + } + assert!(kube.get(&at("HTTPRoute", "shop-web-old")).is_none(), "the stale route"); + assert!(headers_kept()); + + // The gateway's settings (origin pull, PROXY protocol): the shared + // policies as 0.5.4 lists them, and the CDN's follows. + write_web(&client, system::WebSettings { origin_pull: true, proxy_protocol: true }) + .await + .expect("the gateway's settings"); + for (https, name) in [(false, "pyo-http"), (true, "pyo-https")] { + let p = kube.get(&at("ClientTrafficPolicy", name)).expect(name); + assert!(p["spec"].get("headers").is_none(), "{p}"); + let w = system::WebSettings { origin_pull: https, proxy_protocol: true }; + assert_eq!(Some(p), without_headers(&system::client_policy(https, w)).map(|mut o| { + o["metadata"]["resourceVersion"] = json!("1"); + o["metadata"]["creationTimestamp"] = json!("2026-01-01T00:00:00Z"); + o + })); + } + let cdn = kube.get(&at("ClientTrafficPolicy", "shop-web-cdn")).unwrap(); + assert!(cdn["spec"]["proxyProtocol"].is_object() && cdn["spec"].get("headers").is_none()); + set_web_proxy_protocol(&client, false).await.expect("PROXY protocol off"); + set_origin_pull(&client, "").await.expect("origin pull off"); + assert!(kube.get(&at("ClientTrafficPolicy", "pyo-https")).unwrap()["spec"].get("tls").is_none()); + + // The connect command ran: the new policy takes them whole. + kube.admit(|_| None); + apply(&client, &pyo, &b).await.expect("the deploy's routes"); + let cdn = kube.get(&at("ClientTrafficPolicy", "shop-web-cdn")).unwrap(); + assert_eq!(cdn["spec"]["headers"], system::visitor_headers(system::cdn_own_headers("cloudflare"))); + write_web(&client, system::WebSettings::default()).await.unwrap(); + for name in ["pyo-http", "pyo-https"] { + let p = kube.get(&at("ClientTrafficPolicy", name)).unwrap(); + assert_eq!(p["spec"]["headers"], system::visitor_headers(&[]), "{name}"); + } + assert!(!headers_kept()); + + // Refused for anything else: an error, as before. + kube.admit(|w| { + (w.plural == "clienttrafficpolicies").then(|| (403, "ValidatingAdmissionPolicy 'pyo-agent' denied request".into())) + }); + assert!(write_web(&client, system::WebSettings::default()).await.is_err()); + kube.admit(|w| (w.plural == "clienttrafficpolicies").then(|| (500, "etcd timeout".into()))); + assert!(apply(&client, &pyo, &b).await.is_err()); + assert!(!headers_kept()); + } + + /// What a cluster still on 0.5.5's admission policy accepts of the + /// proxies' settings: exactly as listed then, without their pods' + /// priority, published or not. Kubernetes' words for a refusal. + fn admission_055(w: &crate::fakekube::Write) -> Option<(u16, String)> { + if w.plural != "envoyproxies" || w.method == "DELETE" { + return None; + } + let listed: Vec = [true, false] + .into_iter() + .filter_map(|public| { + let now = system::envoy_proxy(&system::geoip_image_from_env(), public); + system::envoy_proxy_without_priority(&now).map(|o| o["spec"].clone()) + }) + .collect(); + (!listed.contains(&w.body["spec"])).then(|| (403, "envoyproxies.gateway.envoyproxy.io \"pyo\" is forbidden: ValidatingAdmissionPolicy 'pyo-agent' with binding 'pyo-agent' denied request: failed expression: gatewayAllowed".to_owned())) + } + + /// A cluster whose install wasn't refreshed keeps 0.5.5's admission + /// policy after the agent moves on: it lists the proxies without their + /// priority. They're written as it accepts, so public traffic still + /// switches and the gateway's other settings still follow at a start. + /// Once the connect command brings the new policy, they get their + /// priority. + #[tokio::test] + async fn an_older_admission_policy_gets_the_proxies_without_their_priority() { + let _one = OLDER_INSTALL.lock().await; + let (kube, client) = crate::fakekube::FakeKube::start().await; + let at = |group: &str, plural: &str, name: &str| { + format!("apis/{group}/namespaces/{GATEWAY_NS}/{plural}/{name}") + }; + let proxy = at("gateway.envoyproxy.io/v1alpha1", "envoyproxies", "pyo"); + let priority = |o: &Value| { + o["spec"]["provider"]["kubernetes"]["envoyDaemonSet"]["pod"]["priorityClassName"].clone() + }; + // As 0.5.5's agent left them: published, no priority. + let was = system::envoy_proxy_without_priority(&system::envoy_proxy( + &system::geoip_image_from_env(), + true, + )) + .unwrap(); + kube.put(&proxy, was); + kube.admit(admission_055); + + // Public traffic off: refused whole, then written as 0.5.5 listed them. + set_public_traffic(&client, false).await; + let p = kube.get(&proxy).unwrap(); + assert!(!system::envoy_proxy_public(&p["spec"]), "{p}"); + assert!(priority(&p).is_null()); + assert!(priority_left_out()); + assert!( + kube.refused() + .iter() + .any(|w| w.plural == "envoyproxies" && priority(&w.body) == system::SERVER_CRITICAL) + ); + + // A start of the agent: the class, the shared Gateway, the WAF's + // Backend and the client policies still follow the proxies. + ensure_once(&client).await.expect("the gateway's settings"); + assert!(priority_left_out()); + assert!(!system::envoy_proxy_public(&kube.get(&proxy).unwrap()["spec"])); + assert!(kube.get(&at("gateway.networking.k8s.io/v1", "gateways", HTTP_GATEWAY)).is_some()); + assert!(kube.get(&at("gateway.envoyproxy.io/v1alpha1", "backends", system::WAF_NAME)).is_some()); + assert!(kube.get(&at("gateway.envoyproxy.io/v1alpha1", "clienttrafficpolicies", "pyo-https")).is_some()); + + // And back on. + set_public_traffic(&client, true).await; + let p = kube.get(&proxy).unwrap(); + assert!(system::envoy_proxy_public(&p["spec"]) && priority(&p).is_null(), "{p}"); + + // The connect command ran: the new policy takes them whole. + kube.admit(|_| None); + ensure_once(&client).await.expect("the gateway's settings"); + let p = kube.get(&proxy).unwrap(); + assert_eq!(priority(&p), system::SERVER_CRITICAL); + assert!(system::envoy_proxy_public(&p["spec"])); + assert!(!priority_left_out()); + + // Refused either way: left as they are, and an error at a start. + kube.admit(|w| { + (w.plural == "envoyproxies").then(|| (403, "ValidatingAdmissionPolicy 'pyo-agent' denied request".into())) + }); + set_public_traffic(&client, false).await; + assert!(system::envoy_proxy_public(&kube.get(&proxy).unwrap()["spec"])); + let e = ensure_once(&client).await.expect_err("refused"); + assert!(crate::refused::in_chain(&e), "{e:#}"); + // Anything else than a refusal isn't written another way. + kube.admit(|w| (w.plural == "envoyproxies").then(|| (500, "etcd timeout".into()))); + assert!(ensure_once(&client).await.is_err()); + assert_eq!(priority(&kube.get(&proxy).unwrap()), system::SERVER_CRITICAL); + assert!(!priority_left_out()); + } } diff --git a/crates/pyo-agent/src/gpu.rs b/crates/pyo-agent/src/gpu.rs index 4ae2040f..deb48066 100644 --- a/crates/pyo-agent/src/gpu.rs +++ b/crates/pyo-agent/src/gpu.rs @@ -215,7 +215,7 @@ pub fn device_plugin() -> Value { "runtimeClassName": GPU_RUNTIME_CLASS, "nodeSelector": { GPU_LABEL: "nvidia" }, "tolerations": [{ "key": GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }], - "priorityClassName": "system-node-critical", + "priorityClassName": pyo_proto::system::SERVER_CRITICAL, "containers": [{ "name": "nvidia-device-plugin-ctr", "image": DEVICE_PLUGIN_IMAGE, @@ -411,6 +411,12 @@ mod tests { let ds: DaemonSet = serde_json::from_value(device_plugin()).unwrap(); let spec = ds.spec.unwrap().template.spec.unwrap(); assert_eq!(spec.runtime_class_name.as_deref(), Some("nvidia")); + // Kept on a server short of disk, like Pyo's other per-server pods: + // its DaemonSet never replaces it over and over there. + assert_eq!( + spec.priority_class_name.as_deref(), + Some(pyo_proto::system::SERVER_CRITICAL) + ); assert_eq!( spec.node_selector .unwrap() diff --git a/crates/pyo-agent/src/install.rs b/crates/pyo-agent/src/install.rs index 1530297d..d9bdb6db 100644 --- a/crates/pyo-agent/src/install.rs +++ b/crates/pyo-agent/src/install.rs @@ -2,14 +2,30 @@ //! `RefreshInstall`), with the optional self-update role. Pyo sends it when //! the agent's heartbeat reports an older install (after Pyo was updated). //! -//! 1. Its roles must already be as Pyo's: the agent reads each one (it may -//! never write them); if any differs, only the cluster's connect command -//! can bring them up to date, and nothing is changed. +//! 1. Its roles and bindings, as Pyo's are: the agent reads each one and +//! updates those that differ, by name, the self-update role itself +//! last (it's what allows the other writes). It never makes one. If +//! one is missing or it may not update one (an install whose +//! self-update role is older, a role object a release added, a chart +//! installed with the agent that changed), only the cluster's connect +//! command brings that one. The refresh goes on without it: the new +//! policy only narrows what the roles allow, so it's safe under the +//! roles as they are. The stamp then names what was left +//! (`rbac::stamp`), so Pyo knows the install is current except for +//! those and holds back only what needs them. //! 2. The admission policy is replaced as a whole (its binding only if that //! differs), then a dry run of the Deployment change below goes through -//! it. If the new policy refuses that, the old one is put back. -//! 3. Last, after reporting: the Deployment's image pins and its stamp. -//! When the pins change, the agent restarts on them. +//! it. If the new policy refuses that, the old one is put back, and +//! the roles of step 1 with it. +//! 3. Last, after reporting: the Deployment's image pins, its stamp, and +//! its pods' priority and tolerations (pyo-proto's `rbac::AGENT_PRIORITY` +//! and `rbac::agent_tolerations`, the connect command's too). When more +//! than the stamp changes, the agent restarts on it. +//! +//! Roles before the policy, the policy before the pins: the new policy only +//! narrows what the roles allow, so at every step in between the agent +//! holds a working install, and a refresh that stops there is made whole +//! by the next one. //! //! On a small server under load, the API server can take longer to check //! the policy than it gives a write by default (34 s): each write here asks @@ -19,7 +35,8 @@ //! //! Every step finds what's already done, so a refresh that stops halfway //! is simply sent again. The agent's token, Pyo's address, its image and -//! everything else of its Deployment are never touched here. +//! everything else of its Deployment are never touched here, and the +//! admission policy refuses the agent any other change to it. use std::time::{Duration, Instant}; @@ -33,7 +50,7 @@ use serde_json::{Value, json}; use crate::scope::{api_for, same}; -const DEPLOYMENT: &str = "pyo-agent"; +const DEPLOYMENT: &str = rbac::AGENT_DEPLOYMENT; /// What a refresh can't do by itself. const RERUN: &str = "run the cluster's connect command to bring them up to date"; /// What each write of the admission policy (and the dry run through it) @@ -46,6 +63,8 @@ const BUDGET: Duration = Duration::from_secs(300); /// The first wait before trying again; it doubles up to [`MAX_BACKOFF`]. const FIRST_BACKOFF: Duration = Duration::from_secs(5); const MAX_BACKOFF: Duration = Duration::from_secs(30); +/// How long the API server gets to start enforcing a policy just written. +const ENFORCE_WAIT: Duration = Duration::from_secs(if cfg!(test) { 0 } else { 3 }); /// A refresh's progress: logged as it goes, and sent back with its result. #[derive(Default)] @@ -199,130 +218,368 @@ pub fn check(p: &InstallParts) -> Result<(), String> { if rbac::install_hash(&p.access, &unstamped, &p.pins) != p.hash { return Err("its hash doesn't match its content".into()); } + // Its bindings: only to Pyo's own accounts (the admission policy says + // the same of the ones the agent may update). + for o in p.access.iter().filter(|o| is_binding(o)) { + let own = o["subjects"].as_array().is_some_and(|s| { + !s.is_empty() + && s.iter().all(|s| { + s["kind"] == "ServiceAccount" + && s["namespace"] == rbac::NS + && [rbac::SA, rbac::TAILNET_SA].contains(&s["name"].as_str().unwrap_or("")) + }) + }); + if !own { + return Err("a binding isn't to the agent's own accounts".into()); + } + } Ok(()) } -/// The Deployment change: its pins (env by name, the rest kept) and stamp. -fn deployment_patch(p: &InstallParts) -> Value { +fn kind_of(o: &Value) -> &str { + o["kind"].as_str().unwrap_or("") +} + +fn is_binding(o: &Value) -> bool { + matches!(kind_of(o), "RoleBinding" | "ClusterRoleBinding") +} + +/// A role or binding: what a refresh may update. +fn is_role_object(o: &Value) -> bool { + matches!(kind_of(o), "Role" | "ClusterRole") || is_binding(o) +} + +/// A binding the cluster's owner may delete to take servers or their +/// figures away from the agent: missing, it stays missing. +fn optional_binding(o: &Value) -> bool { + kind_of(o) == "ClusterRoleBinding" + && [rbac::NODES_ROLE, rbac::STATS_ROLE].contains(&o["metadata"]["name"].as_str().unwrap_or("")) +} + +/// An object of the install, as a refresh names it: "Kind/name", or +/// "Kind/namespace/name". +pub fn object_key(o: &Value) -> String { + let name = o["metadata"]["name"].as_str().unwrap_or(""); + match o["metadata"]["namespace"].as_str() { + Some(ns) => format!("{}/{ns}/{name}", kind_of(o)), + None => format!("{}/{name}", kind_of(o)), + } +} + +/// The order roles are written in: roles, then bindings, then the +/// self-update role, which allows the writes before it. +fn write_rank(o: &Value) -> u8 { + if kind_of(o) == "ClusterRole" && o["metadata"]["name"] == rbac::SELF_UPDATE_ROLE { + 2 + } else if is_binding(o) { + 1 + } else { + 0 + } +} + +/// What a refresh brought. +#[derive(Debug, Default, PartialEq)] +pub struct Refreshed { + /// The roles, bindings and charts left as they were, for the connect + /// command ([`object_key`]s). None: the install is Pyo's. + pub older: Vec, +} + +impl Refreshed { + /// The install's stamp: its hash, and what was left. + pub fn stamp(&self, p: &InstallParts) -> String { + rbac::stamp(&p.hash, &self.older) + } + + /// The command's result, as the team reads it. + pub fn message(&self, p: &InstallParts) -> String { + if self.older.is_empty() { + format!("This cluster's install is now Pyo's ({}).", p.hash) + } else { + format!( + "This cluster's admission policy and image pins are now Pyo's ({}). Its roles aren't yet: {RERUN}.", + p.hash + ) + } + } +} + +/// The Deployment change: its pins (env by name, the rest kept), stamp, +/// priority and tolerations (the whole list, as a strategic merge replaces +/// a list without a merge key). +fn deployment_patch(p: &InstallParts, stamp: &str) -> Value { let env: Vec = p .pins .iter() .map(|(k, v)| json!({ "name": k, "value": v })) .collect(); json!({ - "metadata": { "annotations": { rbac::INSTALL_ANNOTATION: p.hash } }, - "spec": { "template": { "spec": { "containers": [{ "name": "agent", "env": env }] } } }, + "metadata": { "annotations": { rbac::INSTALL_ANNOTATION: stamp } }, + "spec": { "template": { "spec": { + "priorityClassName": rbac::AGENT_PRIORITY, + "tolerations": rbac::agent_tolerations(), + "containers": [{ "name": "agent", "env": env }], + } } }, }) } -/// Steps 1 and 2. Ok once the admission policy is this install's and lets -/// the Deployment change through; `finish` makes that change. -pub async fn refresh( +/// Why a write of the install didn't happen. +enum WriteFailed { + /// The object isn't there: the agent never makes one. + Missing, + /// The cluster refused it: this agent's roles or its admission policy. + Refused(kube::Error), + Other(anyhow::Error), +} + +/// Replace `name` with `want` (its rules or spec, labels and annotations. +/// Other labels and annotations stay), trying again while the API server +/// is busy. Ok(Some(what was there before)) once written, Ok(None) when it +/// was already so. +async fn put( + client: &Client, + api: &Api, + name: &str, + want: &Value, + progress: &mut Progress, + deadline: Instant, +) -> Result, WriteFailed> { + let kind = kind_of(want); + // What was there before the first write: put back if a later step + // fails, even when that write's answer was lost. + let mut before: Option = None; + let mut tries = 0; + loop { + let old = match api.get_opt(name).await { + Ok(Some(old)) => old, + Ok(None) => return Err(WriteFailed::Missing), + Err(e) if crate::refused::is_refusal(&e) => return Err(WriteFailed::Refused(e)), + Err(e) => return Err(WriteFailed::Other(e.into())), + }; + let old_value = serde_json::to_value(&old).map_err(|e| WriteFailed::Other(e.into()))?; + let stamped = want["metadata"]["annotations"] + .as_object() + .is_none_or(|a| a.iter().all(|(k, v)| old.annotations().get(k).map(String::as_str) == v.as_str())); + if same(want, &old_value) && stamped { + // In place, maybe by an earlier try whose answer didn't come back. + if before.is_some() { + progress.say(format!("The {kind} {name} is in place.")); + } + return Ok(before); + } + let mut new: DynamicObject = + serde_json::from_value(want.clone()).map_err(|e| WriteFailed::Other(e.into()))?; + new.metadata.resource_version = old.resource_version(); + // Other labels and annotations stay (kubectl's own, say). + let mut labels = old.labels().clone(); + labels.extend(new.labels().clone()); + new.metadata.labels = Some(labels); + let mut annotations = old.annotations().clone(); + annotations.extend(new.annotations().clone()); + new.metadata.annotations = Some(annotations); + tries += 1; + progress.say(if tries == 1 { + format!("Updating the {kind} {name}…") + } else { + format!("Updating the {kind} {name} (try {tries})…") + }); + if before.is_none() { + before = Some(old); + } + match replace(client, api, name, &new).await { + Ok(_) => return Ok(before), + // Changed under it (another process of this agent, on its + // way out, making the same refresh): read it again. + Err(kube::Error::Api(e)) if e.code == 409 && tries < 3 => { + tokio::time::sleep(Duration::from_secs(1)).await; + } + Err(e) if crate::refused::is_refusal(&e) => return Err(WriteFailed::Refused(e)), + Err(e) if transient(&e) => { + let left = deadline.saturating_duration_since(Instant::now()); + let Some(wait) = backoff(tries, left) else { + return Err(WriteFailed::Other(anyhow::anyhow!( + "couldn't update {kind} {name} in {} minutes: {e}. The API server may be overloaded; this is tried again later", + BUDGET.as_secs() / 60 + ))); + }; + progress.say(format!( + "The API server didn't take it ({e}). Trying again in {}s…", + wait.as_secs() + )); + tokio::time::sleep(wait).await; + } + Err(e) => { + return Err(WriteFailed::Other(anyhow::anyhow!( + "couldn't update {kind} {name}: {e}" + ))); + } + } + } +} + +/// Put back what a refresh replaced, the last written first. What to say +/// when that failed too (empty when it didn't). +async fn put_back(client: &Client, replaced: Vec<(Api, DynamicObject)>) -> String { + let mut failed = String::new(); + for (api, mut old) in replaced.into_iter().rev() { + let name = old.name_any(); + old.metadata.managed_fields = None; + for attempt in 1..=3 { + old.metadata.resource_version = api + .get(&name) + .await + .ok() + .and_then(|cur| cur.resource_version()); + match replace(client, &api, &name, &old).await { + Ok(_) => break, + Err(e) => { + if attempt < 3 + && (transient(&e) || matches!(&e, kube::Error::Api(s) if s.code == 409)) + { + tokio::time::sleep(FIRST_BACKOFF).await; + } else { + failed = format!(" Putting back the old {name} failed too: {e}."); + break; + } + } + } + } + } + failed +} + +/// What step 1 did. +#[derive(Default)] +struct Roles { + /// Updated: what each was before, to put back if a later step fails. + written: Vec<(Api, DynamicObject)>, + /// Not as Pyo's, and not this agent's to change ([`object_key`]s). + older: Vec, +} + +/// Step 1: the install's roles, bindings and charts read, and the roles +/// and bindings that differ updated where the agent may. +async fn update_roles( client: &Client, p: &InstallParts, progress: &mut Progress, -) -> anyhow::Result<()> { - check(p).map_err(|e| anyhow::anyhow!("Pyo sent an install this agent won't apply: {e}"))?; - let deadline = Instant::now() + BUDGET; - // 1. Its roles, as Pyo's are. + deadline: Instant, +) -> anyhow::Result { + let mut out = Roles::default(); + let mut differ: Vec<&Value> = vec![]; for o in &p.access { - let kind = o["kind"].as_str().unwrap_or(""); + let kind = kind_of(o); // Nothing in these to compare: there by now. if matches!(kind, "Namespace" | "ServiceAccount") { continue; } let (api, name) = api_for(client, o); - let have = api - .get_opt(&name) - .await - .map_err(|e| anyhow::anyhow!("couldn't read its {kind} {name} ({e}); {RERUN}"))?; + let have = match api.get_opt(&name).await { + Ok(h) => h, + // It may not even read it: not this agent's to change. + Err(e) if crate::refused::is_refusal(&e) => { + out.older.push(object_key(o)); + continue; + } + Err(e) => anyhow::bail!("couldn't read its {kind} {name} ({e})"), + }; match have { - None => anyhow::bail!( - "this agent's roles are older than Pyo's ({kind} {name} is missing); {RERUN}" - ), - Some(h) if !same(o, &serde_json::to_value(&h)?) => anyhow::bail!( - "this agent's roles are older than Pyo's ({kind} {name} differs); {RERUN}" - ), - Some(_) => {} + None if optional_binding(o) => {} + None => out.older.push(object_key(o)), + Some(h) => { + let h = serde_json::to_value(&h)?; + if same(o, &h) { + continue; + } + // A chart, or a binding to another role (which Kubernetes + // never changes): the connect command's. + if is_role_object(o) && (!is_binding(o) || same(&json!({ "roleRef": o["roleRef"] }), &h)) { + differ.push(o); + } else { + out.older.push(object_key(o)); + } + } + } + } + differ.sort_by_key(|o| write_rank(o)); + for o in differ { + let (api, name) = api_for(client, o); + match put(client, &api, &name, o, progress, deadline).await { + Ok(Some(before)) => out.written.push((api, before)), + Ok(None) => {} + Err(WriteFailed::Missing) => out.older.push(object_key(o)), + Err(WriteFailed::Refused(e)) => { + progress.say(format!( + "This agent may not update its {} {name} ({e}).", + kind_of(o) + )); + out.older.push(object_key(o)); + } + Err(WriteFailed::Other(e)) => { + let back = put_back(client, std::mem::take(&mut out.written)).await; + anyhow::bail!("{e:#}, so its roles stay as they were.{back}"); + } } } + Ok(out) +} + +/// Steps 1 and 2. Ok once the roles the agent may update and the admission +/// policy are this install's and the policy lets the Deployment change +/// through; `finish` makes that change. +pub async fn refresh( + client: &Client, + p: &InstallParts, + progress: &mut Progress, +) -> anyhow::Result { + check(p).map_err(|e| anyhow::anyhow!("Pyo sent an install this agent won't apply: {e}"))?; + let deadline = Instant::now() + BUDGET; + // 1. Its roles, as Pyo's are. + let roles = update_roles(client, p, progress, deadline).await?; + let refreshed = Refreshed { older: roles.older }; + if !refreshed.older.is_empty() { + progress.say(format!( + "The agent can't bring these up to date: {}. The rest goes on. To bring them, {RERUN}.", + refreshed.older.join(", ") + )); + } + let stamp = refreshed.stamp(p); + let mut replaced = roles.written; + let wrote_roles = !replaced.is_empty(); // 2. The admission policy, then its binding. - let mut replaced: Vec<(Api, DynamicObject)> = vec![]; + let mut wrote_policy = false; for o in &p.admission { let (api, name) = api_for(client, o); - let kind = o["kind"].as_str().unwrap_or(""); - // What was there before the first write: put back if the new policy - // refuses the agent (below), even when that write's answer was lost. - let mut before: Option = None; - let mut tries = 0; - loop { - let Some(old) = api.get_opt(&name).await? else { - anyhow::bail!("this cluster has no admission policy for the agent; {RERUN}") - }; - let stamp = |d: &DynamicObject| d.annotations().get(rbac::INSTALL_ANNOTATION).cloned(); - let old_value = serde_json::to_value(&old)?; - if same(o, &old_value) - && stamp(&old).as_deref() - == o["metadata"]["annotations"][rbac::INSTALL_ANNOTATION].as_str() - { - // In place, by an earlier try whose answer didn't come back. - if let Some(b) = before.take() { - progress.say(format!("The {kind} is in place.")); - replaced.push((api.clone(), b)); - } - break; - } - let mut new: DynamicObject = serde_json::from_value(o.clone())?; - new.metadata.resource_version = old.resource_version(); - // Other labels and annotations stay (kubectl's own, say). - let mut labels = old.labels().clone(); - labels.extend(new.labels().clone()); - new.metadata.labels = Some(labels); - let mut annotations = old.annotations().clone(); - annotations.extend(new.annotations().clone()); - new.metadata.annotations = Some(annotations); - tries += 1; - progress.say(if tries == 1 { - format!("Updating the {kind}…") - } else { - format!("Updating the {kind} (try {tries})…") - }); - if before.is_none() { - before = Some(old); + let kind = kind_of(o); + // The policy carries the stamp: this refresh's. + let mut o = o.clone(); + if !o["metadata"]["annotations"][rbac::INSTALL_ANNOTATION].is_null() { + o["metadata"]["annotations"][rbac::INSTALL_ANNOTATION] = json!(stamp); + } + let o = &o; + match put(client, &api, &name, o, progress, deadline).await { + Ok(Some(before)) => { + replaced.push((api, before)); + wrote_policy = true; } - match replace(client, &api, &name, &new).await { - Ok(_) => { - if let Some(b) = before.take() { - replaced.push((api.clone(), b)); + Ok(None) => {} + Err(failed) => { + let why = match failed { + WriteFailed::Missing => { + format!("this cluster has no admission policy for the agent; {RERUN}") } - break; - } - // Changed under it (another process of this agent, on its - // way out, making the same refresh): read it again. - Err(kube::Error::Api(e)) if e.code == 409 && tries < 3 => { - tokio::time::sleep(Duration::from_secs(1)).await; - } - Err(e) if transient(&e) => { - let left = deadline.saturating_duration_since(Instant::now()); - let Some(wait) = backoff(tries, left) else { - anyhow::bail!( - "couldn't update {kind} {name} in {} minutes: {e}. The API server may be overloaded; this is tried again later", - BUDGET.as_secs() / 60 - ); - }; - progress.say(format!( - "The API server didn't take it ({e}). Trying again in {}s…", - wait.as_secs() - )); - tokio::time::sleep(wait).await; - } - Err(e) => anyhow::bail!("couldn't update {kind} {name}: {e}"), + WriteFailed::Refused(e) => format!("couldn't update {kind} {name}: {e}"), + WriteFailed::Other(e) => format!("{e:#}"), + }; + let back = put_back(client, replaced).await; + anyhow::bail!("{why}{}{back}", if wrote_roles { ", so its roles stay as they were." } else { "" }); } } } - if !replaced.is_empty() { + if wrote_policy { // The API server takes a moment to enforce it. - tokio::time::sleep(Duration::from_secs(3)).await; + tokio::time::sleep(ENFORCE_WAIT).await; } let deployments = Api::::namespaced(client.clone(), rbac::NS); progress.say("Checking the agent's own update against it…".into()); @@ -335,7 +592,7 @@ pub async fn refresh( dry_run: true, ..Default::default() }, - &Patch::Strategic(deployment_patch(p)), + &Patch::Strategic(deployment_patch(p, &stamp)), ); let sent = match req { Ok(req) => send_with_timeout(client, req).await.map(|_| ()), @@ -366,50 +623,23 @@ pub async fn refresh( format!("the new admission policy refused the agent's own update ({e})") }; if !replaced.is_empty() { - progress.say("Putting the old admission policy back…".into()); - } - let mut back = String::new(); - for (api, mut old) in replaced.into_iter().rev() { - let name = old.name_any(); - old.metadata.managed_fields = None; - for attempt in 1..=3 { - old.metadata.resource_version = api - .get(&name) - .await - .ok() - .and_then(|cur| cur.resource_version()); - match replace(client, &api, &name, &old).await { - Ok(_) => { - back.clear(); - break; - } - Err(e) => { - back = format!(" Putting back the old one failed too: {e}."); - if attempt < 3 - && (transient(&e) || matches!(&e, kube::Error::Api(s) if s.code == 409)) - { - tokio::time::sleep(FIRST_BACKOFF).await; - } else { - break; - } - } - } - } + progress.say("Putting the old install back…".into()); } + let back = put_back(client, replaced).await; anyhow::bail!("{why}, so the old one stays.{back}"); } progress.say("The new admission policy lets the agent's own update through.".into()); - Ok(()) + Ok(refreshed) } -/// Step 3: the Deployment's pins and stamp. When the pins change, this -/// agent restarts. -pub async fn finish(client: &Client, p: &InstallParts) -> anyhow::Result<()> { +/// Step 3: the Deployment's pins, stamp (`refreshed`'s), priority and +/// tolerations. When more than the stamp changes, this agent restarts. +pub async fn finish(client: &Client, p: &InstallParts, refreshed: &Refreshed) -> anyhow::Result<()> { Api::::namespaced(client.clone(), rbac::NS) .patch( DEPLOYMENT, &PatchParams::default(), - &Patch::Strategic(deployment_patch(p)), + &Patch::Strategic(deployment_patch(p, &refreshed.stamp(p))), ) .await?; Ok(()) @@ -436,6 +666,297 @@ mod tests { ) } + // ── A refresh against the in-memory API server ─────────────────────── + + use crate::fakekube::FakeKube; + use std::sync::{Arc, Mutex}; + + /// Where the fake server keeps an object of the install. + fn path_of(o: &Value) -> String { + let version = o["apiVersion"].as_str().unwrap(); + let prefix = if version.contains('/') { + format!("apis/{version}") + } else { + format!("api/{version}") + }; + let plural = match kind_of(o) { + "ValidatingAdmissionPolicy" => "validatingadmissionpolicies".to_owned(), + k => format!("{}s", k.to_ascii_lowercase()), + }; + let name = o["metadata"]["name"].as_str().unwrap(); + match o["metadata"]["namespace"].as_str() { + Some(ns) => format!("{prefix}/namespaces/{ns}/{plural}/{name}"), + None => format!("{prefix}/{plural}/{name}"), + } + } + + const DEPLOYMENT_PATH: &str = "apis/apps/v1/namespaces/pyo-system/deployments/pyo-agent"; + + /// A cluster as the connect command left it at install `p`. + fn installed(kube: &FakeKube, p: &InstallParts) { + for o in p.access.iter().chain(p.admission.iter()) { + kube.put(&path_of(o), o.clone()); + } + kube.put( + DEPLOYMENT_PATH, + json!({ + "apiVersion": "apps/v1", "kind": "Deployment", + "metadata": { "annotations": { rbac::INSTALL_ANNOTATION: p.hash } }, + "spec": { "template": { "spec": { "containers": [{ "name": "agent", "image": "agent:1" }] } } }, + }), + ); + } + + /// `p` with its roles changed by `change`, as a later release of Pyo + /// would hand it out (hashed and stamped again). + fn later(p: &InstallParts, change: impl Fn(&mut Vec)) -> InstallParts { + let mut p = p.clone(); + change(&mut p.access); + p.admission[0]["metadata"] + .as_object_mut() + .unwrap() + .remove("annotations"); + p.hash = rbac::install_hash(&p.access, &p.admission, &p.pins); + p.admission[0]["metadata"]["annotations"] = json!({ rbac::INSTALL_ANNOTATION: p.hash }); + check(&p).unwrap(); + p + } + + fn role<'a>(access: &'a mut [Value], kind: &str, name: &str) -> &'a mut Value { + access + .iter_mut() + .find(|o| o["kind"] == kind && o["metadata"]["name"] == name) + .unwrap() + } + + fn stamp_at(kube: &FakeKube, path: &str) -> Value { + kube.get(path).unwrap()["metadata"]["annotations"][rbac::INSTALL_ANNOTATION].clone() + } + + /// What 0.52.0 could bring: a rule added to one role, one removed from + /// another, and a name added to the self-update role. + fn changed_roles(access: &mut [Value]) { + role(access, "ClusterRole", "pyo-agent-cluster")["rules"] + .as_array_mut() + .unwrap() + .push(json!({ "apiGroups": ["example.pyo.dev"], "resources": ["widgets"], "verbs": ["get", "patch"] })); + role(access, "Role", "pyo-agent-policy")["rules"] = json!([]); + role(access, "ClusterRole", rbac::SELF_UPDATE_ROLE)["rules"][1]["resourceNames"] + .as_array_mut() + .unwrap() + .push(json!("pyo-agent-later")); + } + + /// The upgrade path's second half: a cluster whose owner ran the + /// connect command once on 0.51.0 (so it has this release's + /// self-update role). Pyo then moves to a release with other rules in + /// roles the cluster already has. The refresh writes them, then the + /// policy, then the pins, and stamps the install current. No command. + #[tokio::test] + async fn a_later_release_with_changed_roles_refreshes_by_itself() { + let (kube, client) = FakeKube::start().await; + let a = parts(); + installed(&kube, &a); + let b = later(&a, |access| changed_roles(access)); + assert_ne!(a.hash, b.hash); + // Every write, in order. + let writes: Arc>> = Arc::default(); + let seen = writes.clone(); + kube.admit(move |w| { + seen.lock().unwrap().push(format!("{} {}/{}", w.method, w.plural, w.name)); + None + }); + let mut progress = Progress::default(); + let refreshed = refresh(&client, &b, &mut progress).await.unwrap(); + assert_eq!(refreshed, Refreshed::default()); + assert_eq!(refreshed.message(&b), format!("This cluster's install is now Pyo's ({}).", b.hash)); + // Roles first, the self-update role last of them, then the policy, + // then the dry run of the agent's own update. + assert_eq!( + *writes.lock().unwrap(), + [ + "PUT roles/pyo-agent-policy", + "PUT clusterroles/pyo-agent-cluster", + "PUT clusterroles/pyo-agent-self-update", + "PUT validatingadmissionpolicies/pyo-agent", + "PATCH deployments/pyo-agent", + ] + ); + for o in b.access.iter().filter(|o| is_role_object(o)) { + assert!(same(o, &kube.get(&path_of(o)).unwrap()), "{}", object_key(o)); + } + // The removed rule is gone, not merged. + let policy_role = role(&mut b.access.clone(), "Role", "pyo-agent-policy").clone(); + assert_eq!(kube.get(&path_of(&policy_role)).unwrap()["rules"], json!([])); + assert_eq!(stamp_at(&kube, &path_of(&b.admission[0])), json!(b.hash)); + // The Deployment last, after the result is reported. + assert_eq!(stamp_at(&kube, DEPLOYMENT_PATH), json!(a.hash)); + finish(&client, &b, &refreshed).await.unwrap(); + assert_eq!(stamp_at(&kube, DEPLOYMENT_PATH), json!(b.hash)); + let d = kube.get(DEPLOYMENT_PATH).unwrap(); + assert_eq!(d["spec"]["template"]["spec"]["priorityClassName"], rbac::AGENT_PRIORITY); + // Sent again: nothing left to write but the dry run. + writes.lock().unwrap().clear(); + refresh(&client, &b, &mut Progress::default()).await.unwrap(); + assert_eq!(*writes.lock().unwrap(), ["PATCH deployments/pyo-agent"]); + } + + /// A binding the owner deleted to take servers away stays deleted, and + /// the refresh goes through without it. + #[tokio::test] + async fn a_refresh_leaves_a_deleted_optional_binding_alone() { + let (kube, client) = FakeKube::start().await; + let a = parts(); + let mut without = a.clone(); + without + .access + .retain(|o| !(o["kind"] == "ClusterRoleBinding" && o["metadata"]["name"] == rbac::NODES_ROLE)); + installed(&kube, &without); + let b = later(&a, |access| changed_roles(access)); + refresh(&client, &b, &mut Progress::default()).await.unwrap(); + let binding = b.access.iter().find(|o| optional_binding(o)).unwrap(); + assert!(kube.get(&path_of(binding)).is_none()); + assert_eq!(stamp_at(&kube, &path_of(&b.admission[0])), json!(b.hash)); + } + + /// A new policy that refuses the agent's own update: the old policy is + /// put back, and the roles written before it too. The old install + /// stays whole. + #[tokio::test] + async fn a_refused_policy_puts_the_roles_back_too() { + let (kube, client) = FakeKube::start().await; + let a = parts(); + installed(&kube, &a); + let b = later(&a, |access| changed_roles(access)); + kube.admit(|w| { + (w.plural == "deployments").then(|| { + (422, "ValidatingAdmissionPolicy 'pyo-agent' with binding 'pyo-agent' denied request".to_owned()) + }) + }); + let err = refresh(&client, &b, &mut Progress::default()).await.unwrap_err(); + assert!(format!("{err:#}").contains("refused the agent's own update"), "{err:#}"); + assert!(!format!("{err:#}").contains("failed too"), "{err:#}"); + for o in a.access.iter().filter(|o| is_role_object(o)).chain(a.admission.iter()) { + assert!(same(o, &kube.get(&path_of(o)).unwrap()), "{}", object_key(o)); + } + assert_eq!(stamp_at(&kube, &path_of(&a.admission[0])), json!(a.hash)); + assert_eq!(stamp_at(&kube, DEPLOYMENT_PATH), json!(a.hash)); + } + + /// 0.5.5's self-update role may read the roles and update the policy, + /// never write a role. + fn roles_are_read_only(w: &crate::fakekube::Write) -> Option<(u16, String)> { + ["clusterroles", "clusterrolebindings", "roles", "rolebindings"] + .contains(&w.plural.as_str()) + .then(|| { + (403, format!("{} \"{}\" is forbidden: User \"system:serviceaccount:pyo-system:pyo-agent\" cannot update resource \"{}\" in API group \"rbac.authorization.k8s.io\"", w.plural, w.name, w.plural)) + }) + } + + /// The upgrade path's first half: a cluster on 0.5.5's install with + /// this agent. It may not write its roles, so the refresh brings what + /// doesn't need them (the policy, the pins) and stamps the install as + /// current except for those roles. Never as current. + #[tokio::test] + async fn an_install_that_cant_write_its_roles_gets_the_rest() { + let (kube, client) = FakeKube::start().await; + let a = parts(); + installed(&kube, &a); + let b = later(&a, |access| changed_roles(access)); + kube.admit(roles_are_read_only); + let mut progress = Progress::default(); + let refreshed = refresh(&client, &b, &mut progress).await.unwrap(); + let older = [ + "Role/pyo-system/pyo-agent-policy", + "ClusterRole/pyo-agent-cluster", + "ClusterRole/pyo-agent-self-update", + ]; + assert_eq!(refreshed.older, older); + // Each role was tried once, and none changed. + assert_eq!(kube.refused().len(), 3); + for o in a.access.iter().filter(|o| is_role_object(o)) { + assert!(same(o, &kube.get(&path_of(o)).unwrap()), "{}", object_key(o)); + } + // The policy is the new one, stamped with what was left. + let stamp = format!("{} except {}", b.hash, older.join(",")); + assert_eq!(refreshed.stamp(&b), stamp); + let policy = kube.get(&path_of(&b.admission[0])).unwrap(); + assert!(same(&b.admission[0], &policy)); + assert_eq!(policy["metadata"]["annotations"][rbac::INSTALL_ANNOTATION], json!(stamp)); + assert_ne!(json!(stamp), json!(b.hash)); + // The agent reports the install with the roles left behind, which + // Pyo doesn't take as current. + finish(&client, &b, &refreshed).await.unwrap(); + assert_eq!(stamp_at(&kube, DEPLOYMENT_PATH), json!(stamp)); + let (install, roles_older) = rbac::parse_stamp(&stamp); + let scope = rbac::AgentScope { + admission: "enforced".into(), + install, + roles_older, + ..Default::default() + }; + assert_eq!(scope.install, b.hash); + assert!(!rbac::install_current(&scope, &b.hash)); + assert!(!rbac::bundles_held_back(&scope.roles_older)); + // The pins came too. + let d = kube.get(DEPLOYMENT_PATH).unwrap(); + assert_eq!(d["spec"]["template"]["spec"]["containers"][0]["env"].as_array().unwrap().len(), rbac::PINNED_ENV.len()); + // What it says, and where it points. + assert!(refreshed.message(&b).contains("Its roles aren't yet: run the cluster's connect command"), "{}", refreshed.message(&b)); + assert!(progress.lines.iter().any(|l| l.message.starts_with("The agent can't bring these up to date: Role/pyo-system/pyo-agent-policy, "))); + // Sent again, it does the same and no more (Pyo doesn't send it). + let again = refresh(&client, &b, &mut Progress::default()).await.unwrap(); + assert_eq!(again.older, older); + assert_eq!(stamp_at(&kube, &path_of(&b.admission[0])), json!(stamp)); + // The owner runs the connect command: the whole install, stamped + // plainly. A refresh then finds nothing to do. + installed(&kube, &b); + kube.admit(|w| (w.plural != "deployments").then(|| (500, "no write expected".to_owned()))); + assert_eq!(refresh(&client, &b, &mut Progress::default()).await.unwrap(), Refreshed::default()); + } + + /// A release that adds a role object or changes a chart: the agent + /// writes the roles it has, and leaves those two for the command. + #[tokio::test] + async fn a_new_role_object_and_a_chart_wait_for_the_command() { + let (kube, client) = FakeKube::start().await; + let a = parts(); + installed(&kube, &a); + let b = later(&a, |access| { + changed_roles(access); + access.push(json!({ + "apiVersion": "rbac.authorization.k8s.io/v1", "kind": "ClusterRole", + "metadata": { "name": "pyo-agent-later" }, "rules": [], + })); + let chart = access.iter_mut().find(|o| o["kind"] == "HelmChart").unwrap(); + chart["spec"]["version"] = json!("v99.0.0"); + }); + let refreshed = refresh(&client, &b, &mut Progress::default()).await.unwrap(); + let chart = b.access.iter().find(|o| o["kind"] == "HelmChart" && o["spec"]["version"] == "v99.0.0").unwrap(); + assert_eq!(refreshed.older, [object_key(chart), "ClusterRole/pyo-agent-later".to_owned()]); + // Nothing was made, the chart is as it was, the roles it has are new. + assert!(kube.get("apis/rbac.authorization.k8s.io/v1/clusterroles/pyo-agent-later").is_none()); + assert_ne!(kube.get(&path_of(chart)).unwrap()["spec"]["version"], "v99.0.0"); + let cluster = b.access.iter().find(|o| o["metadata"]["name"] == "pyo-agent-cluster" && o["kind"] == "ClusterRole").unwrap(); + assert!(same(cluster, &kube.get(&path_of(cluster)).unwrap())); + // A chart holds the bundles back (they may need the newer one). + assert!(rbac::bundles_held_back(&refreshed.older)); + } + + /// Pyo only sends bindings to the agent's own accounts. + #[test] + fn refuses_a_binding_to_anyone_else() { + let p = later(&parts(), |_| {}); + let mut other = p.clone(); + role(&mut other.access, "ClusterRoleBinding", "pyo-agent-read")["subjects"] = + json!([{ "kind": "User", "name": "someone" }]); + other.admission[0]["metadata"].as_object_mut().unwrap().remove("annotations"); + other.hash = rbac::install_hash(&other.access, &other.admission, &other.pins); + other.admission[0]["metadata"]["annotations"] = json!({ rbac::INSTALL_ANNOTATION: other.hash }); + assert_eq!(check(&other).unwrap_err(), "a binding isn't to the agent's own accounts"); + assert!(check(&p).is_ok()); + } + /// Writes ask the API server for more than its 34 s default. #[test] fn writes_ask_for_a_longer_timeout() { @@ -643,7 +1164,7 @@ mod tests { #[test] fn the_deployment_change_is_its_pins_and_stamp() { let p = parts(); - let patch = deployment_patch(&p); + let patch = deployment_patch(&p, &p.hash); assert_eq!( patch["metadata"]["annotations"][rbac::INSTALL_ANNOTATION], json!(p.hash) @@ -658,6 +1179,99 @@ mod tests { "no image, command or anything else" ); assert_eq!(c["env"].as_array().unwrap().len(), rbac::PINNED_ENV.len()); + let spec = &patch["spec"]["template"]["spec"]; + let mut keys: Vec<&String> = spec.as_object().unwrap().keys().collect(); + keys.sort(); + assert_eq!(keys, ["containers", "priorityClassName", "tolerations"]); + assert_eq!(spec["priorityClassName"], rbac::AGENT_PRIORITY); + assert_eq!(spec["tolerations"], rbac::agent_tolerations()); + } + + /// A strategic merge patch as the API server makes it for these fields: + /// maps merged, `containers` and `env` merged by name, other lists + /// (tolerations) replaced. + fn strategic_merge(target: &mut Value, patch: &Value) { + let (Some(t), Some(p)) = (target.as_object_mut(), patch.as_object()) else { + *target = patch.clone(); + return; + }; + for (k, v) in p { + match (t.get_mut(k), v) { + (Some(Value::Array(have)), Value::Array(new)) + if k == "containers" || k == "env" => + { + for item in new { + match have.iter_mut().find(|h| h["name"] == item["name"]) { + Some(h) => strategic_merge(h, item), + None => have.push(item.clone()), + } + } + } + (Some(have @ Value::Object(_)), Value::Object(_)) => strategic_merge(have, v), + _ => { + t.insert(k.clone(), v.clone()); + } + } + } + } + + /// An agent Deployment as an older connect command made it: no + /// priority, the GPU toleration only, older pins. + fn older_deployment() -> Value { + json!({ + "apiVersion": "apps/v1", "kind": "Deployment", + "metadata": { "name": DEPLOYMENT, "namespace": rbac::NS, "annotations": { rbac::INSTALL_ANNOTATION: "0123456789abcdef" } }, + "spec": { "replicas": 1, "template": { "metadata": { "annotations": { "pyo.dev/token": "t" } }, "spec": { + "serviceAccountName": "pyo-agent", + "tolerations": [{ "key": "nvidia.com/gpu", "operator": "Exists", "effect": "NoSchedule" }], + "containers": [{ "name": "agent", "image": "agent@sha256:00", "envFrom": [{ "secretRef": { "name": "pyo-agent" } }], + "env": [{ "name": "RUST_LOG", "value": "pyo_agent=info" }, { "name": "PYO_WAF_IMAGE", "value": "waf:old" }] }], + } } }, + }) + } + + /// A refresh brings an older Deployment the priority and tolerations + /// (whole, the GPU one kept), and its pins and stamp; the token, Pyo's + /// address and other env stay. Applied again, nothing changes. + #[test] + fn a_refresh_brings_the_priority_and_tolerations() { + let p = parts(); + let patch = deployment_patch(&p, &p.hash); + let mut d = older_deployment(); + strategic_merge(&mut d, &patch); + let spec = &d["spec"]["template"]["spec"]; + assert_eq!(spec["priorityClassName"], rbac::AGENT_PRIORITY); + assert_eq!(spec["tolerations"], rbac::agent_tolerations()); + assert_eq!(spec["serviceAccountName"], "pyo-agent"); + assert_eq!( + d["metadata"]["annotations"][rbac::INSTALL_ANNOTATION], + json!(p.hash) + ); + assert_eq!( + d["spec"]["template"]["metadata"]["annotations"]["pyo.dev/token"], + "t" + ); + let c = &spec["containers"][0]; + assert_eq!(c["image"], "agent@sha256:00"); + assert_eq!( + c["envFrom"], + json!([{ "secretRef": { "name": "pyo-agent" } }]) + ); + let env: std::collections::BTreeMap<&str, &str> = c["env"] + .as_array() + .unwrap() + .iter() + .map(|e| (e["name"].as_str().unwrap(), e["value"].as_str().unwrap())) + .collect(); + assert_eq!(env["RUST_LOG"], "pyo_agent=info"); + for (k, v) in &p.pins { + assert_eq!(env[k.as_str()], v, "{k}"); + } + assert_eq!(env.len(), p.pins.len() + 1); + // Sent again (a refresh that stopped halfway): the same Deployment. + let once = d.clone(); + strategic_merge(&mut d, &patch); + assert_eq!(d, once); } /// Against a throwaway cluster (1.30+), as the agent's own @@ -1044,43 +1658,30 @@ mod tests { .is_err() ); - // A role that differs: nothing changes, and it says to run the connect command. - let roles = api_for( - &admin, - &new.access - .iter() - .find(|o| o["metadata"]["name"] == rbac::STATS_ROLE) - .unwrap() - .clone(), - ) - .0; + // A role that differs: the refresh brings it, then the policy, + // then the pins. No connect command. + let stats = new + .access + .iter() + .find(|o| o["kind"] == "ClusterRole" && o["metadata"]["name"] == rbac::STATS_ROLE) + .unwrap() + .clone(); + let roles = api_for(&admin, &stats).0; roles.patch(rbac::STATS_ROLE, &pp, &Patch::Apply(json!({ "apiVersion": "rbac.authorization.k8s.io/v1", "kind": "ClusterRole", "metadata": { "name": rbac::STATS_ROLE }, "rules": [] }))).await.unwrap(); - let err = refresh(&sa, &new, &mut Progress::default()) - .await - .expect_err("its roles differ"); - assert!(format!("{err:#}").contains("connect command"), "{err:#}"); - assert_eq!(detect().await.install, old.hash, "nothing changed"); - apply( - new.access - .iter() - .find(|o| o["metadata"]["name"] == rbac::STATS_ROLE) - .unwrap() - .clone(), - ) - .await; - - // Its roles as Pyo's: the policy is refreshed, then the pins. let mut progress = Progress::default(); - refresh(&sa, &new, &mut progress).await.unwrap(); + let refreshed = refresh(&sa, &new, &mut progress).await.unwrap(); + assert_eq!(refreshed, Refreshed::default()); let said: Vec<&str> = progress.lines.iter().map(|l| l.message.as_str()).collect(); assert_eq!( said, [ - "Updating the ValidatingAdmissionPolicy…", + "Updating the ClusterRole pyo-agent-stats…", + "Updating the ValidatingAdmissionPolicy pyo-agent…", "Checking the agent's own update against it…", "The new admission policy lets the agent's own update through.", ] ); + assert!(same(&stats, &serde_json::to_value(roles.get(rbac::STATS_ROLE).await.unwrap()).unwrap())); assert_eq!( vaps.get(rbac::ADMISSION_POLICY) .await @@ -1093,7 +1694,7 @@ mod tests { "", "the Deployment isn't stamped yet" ); - finish(&sa, &new).await.unwrap(); + finish(&sa, &new, &Refreshed::default()).await.unwrap(); let after = detect().await; assert_eq!( (after.admission.as_str(), after.install.as_str()), @@ -1114,8 +1715,115 @@ mod tests { .map(|e| (e.name, e.value.unwrap_or_default())) .collect(); assert_eq!(env, new.pins); - // Sent again: nothing to do. + // The stand-in had neither: the refresh brought both. + let d = deployments.get(DEPLOYMENT).await.unwrap(); + let generation = d.metadata.generation; + let pod = serde_json::to_value(d.spec.unwrap().template.spec.unwrap()).unwrap(); + assert_eq!(pod["priorityClassName"], rbac::AGENT_PRIORITY); + assert_eq!(pod["tolerations"], rbac::agent_tolerations()); + // Sent again: nothing to do, and the Deployment is as it was. refresh(&sa, &new, &mut Progress::default()).await.unwrap(); + finish(&sa, &new, &Refreshed::default()).await.unwrap(); + assert_eq!( + deployments + .get(DEPLOYMENT) + .await + .unwrap() + .metadata + .generation, + generation + ); + + // Its own Deployment, through the policy: only what a refresh or + // an update of the agent changes, to exactly this release's. + let own = Api::::namespaced(sa.clone(), rbac::NS); + let try_patch = |patch: Value| { + let own = own.clone(); + async move { + own.patch( + DEPLOYMENT, + &PatchParams { + dry_run: true, + ..Default::default() + }, + &Patch::Strategic(patch), + ) + .await + } + }; + let refused = |r: Result, what: &str| { + assert!( + r.as_ref() + .is_err_and(|e| e.to_string().contains("own Deployment")), + "{what}: {r:?}" + ) + }; + let pod_patch = |spec: Value| json!({ "spec": { "template": { "spec": spec } } }); + try_patch(pod_patch( + json!({ "containers": [{ "name": "agent", "image": "registry.k8s.io/pause:3.9" }] }), + )) + .await + .expect("an update of the agent: its image"); + try_patch(deployment_patch(&new, &new.hash)).await.expect("a refresh"); + refused( + try_patch(pod_patch( + json!({ "priorityClassName": "system-node-critical" }), + )) + .await, + "another priority class", + ); + let mut extra = rbac::agent_tolerations(); + extra + .as_array_mut() + .unwrap() + .push(json!({ "operator": "Exists" })); + refused( + try_patch(pod_patch(json!({ "tolerations": extra }))).await, + "an extra toleration", + ); + refused( + try_patch(pod_patch(json!({ "tolerations": [{ "key": "node.kubernetes.io/disk-pressure", "operator": "Exists", "effect": "NoSchedule" }] }))).await, + "other tolerations", + ); + refused( + try_patch(pod_patch(json!({ "containers": [{ "name": "agent", "env": [{ "name": "PYO_API_URL", "value": "https://elsewhere.example" }] }] }))).await, + "Pyo's address", + ); + refused( + try_patch(pod_patch(json!({ "containers": [{ "name": "agent", "envFrom": [{ "secretRef": { "name": "other" } }] }] }))).await, + "its token", + ); + refused( + try_patch(pod_patch(json!({ "serviceAccountName": "default" }))).await, + "its service account", + ); + refused( + try_patch(pod_patch( + json!({ "volumes": [{ "name": "x", "emptyDir": {} }] }), + )) + .await, + "a volume", + ); + refused( + try_patch(json!({ "spec": { "template": { "metadata": { "annotations": { "pyo.dev/token": "other" } } } } })).await, + "its token stamp", + ); + refused( + try_patch(json!({ "spec": { "replicas": 2 } })).await, + "its replicas", + ); + refused( + own.delete( + DEPLOYMENT, + &kube::api::DeleteParams { + dry_run: true, + ..Default::default() + }, + ) + .await + .map(|_| Deployment::default()), + "deleting it", + ); // Still enforced: a privileged pod is refused. let pod: k8s_openapi::api::core::v1::Pod = serde_json::from_value(json!({ "metadata": { "name": "pyo-test-privileged" }, "spec": { "containers": [{ "name": "x", "image": "registry.k8s.io/pause:3.10", "securityContext": { "privileged": true } }] } })).unwrap(); let refused = Api::::namespaced(sa.clone(), rbac::NS) diff --git a/crates/pyo-agent/src/main.rs b/crates/pyo-agent/src/main.rs index 1905f6d5..ceb327ec 100644 --- a/crates/pyo-agent/src/main.rs +++ b/crates/pyo-agent/src/main.rs @@ -18,6 +18,8 @@ mod dbimport; mod dbmetrics; mod dns; mod drain; +#[cfg(test)] +mod fakekube; mod firewall; mod forward; mod gateway; @@ -43,6 +45,7 @@ mod tailnet; mod tailscale; mod terminal; mod tls; +mod tunnel; mod traffic; mod trust; mod upgrade; @@ -141,6 +144,15 @@ async fn main() -> anyhow::Result<()> { println!("{}", pyo_proto::rbac::access_hash()); return Ok(()); } + // `pyo-agent database-pins`: the database images this release's code + // pins, as release.json's `databasePins` (the release workflow writes it). + if args.get(1).map(String::as_str) == Some("database-pins") { + println!( + "{}", + serde_json::to_string(&pyo_proto::bundles::database_pins())? + ); + return Ok(()); + } // `pyo-agent check-release `: what the upgrader would // refuse in a release (the release workflow runs it before publishing). if args.get(1).map(String::as_str) == Some("check-release") { @@ -259,6 +271,7 @@ async fn heartbeat_loop(agent: Agent) { hb.host_proof = agent.api.host_proof(&agent.kube).await; hb.scope = Some(scope::detect(&agent.kube, policy.clone()).await); hb.tailnet = tailnet::statuses(&agent.kube).await; + hb.tunnel = Some(tunnel::report(&agent.kube).await); match agent.api.heartbeat(&hb).await { Ok(_) if policy.read_only => {} Ok(reply) => { @@ -268,9 +281,14 @@ async fn heartbeat_loop(agent: Agent) { if let Some(on) = reply.public_traffic { gateway::set_public_traffic(&agent.kube, on).await; gateway::set_public_nat(&agent.kube, on).await; - if let Err(e) = rollout::set_public_ports(&agent.kube, on).await { + // TCP and UDP ports: with public traffic, or kept + // in tunnel mode (then the gateway's go through a + // Service of their own). + let ports = reply.public_ports.unwrap_or(on); + if let Err(e) = rollout::set_public_ports(&agent.kube, ports).await { tracing::warn!(error = %format!("{e:#}"), "couldn't change public ports"); } + gateway::set_public_ports_service(&agent.kube, ports && !on).await; } if let Some(address) = &reply.free_domain_address { gateway::set_tailnet_web(&agent.kube, address == "tailscale").await; @@ -279,6 +297,9 @@ async fn heartbeat_loop(agent: Agent) { if let Some(t) = &reply.tailnet { tailnet::apply(&agent.kube, t, agent.api.same_cluster()).await; } + if let Some(w) = &reply.tunnel { + tunnel::follow(&agent.kube, w).await; + } if let Some(p) = &reply.public_dashboard && agent.api.same_cluster() { @@ -411,6 +432,8 @@ fn ordered_keys(c: &Command) -> Vec { | Command::TailscaleSync(_) | Command::TailscaleRemove { .. } => vec!["tailscale".to_owned()], Command::SyncRegistryTokens(_) => vec!["registry-tokens".to_owned()], + // The tunnel's token and connector: in the order sent. + Command::TunnelSet { .. } | Command::TunnelRemove {} => vec!["tunnel".to_owned()], _ => vec![], }; keys.sort(); @@ -602,6 +625,8 @@ async fn run_command(agent: Agent, envelope: CommandEnvelope) { tailscale::run_remove(&agent.kube, &names, &marks).await } Command::SandboxCall(c) => tailscale::sandbox::run(&c).await, + Command::TunnelSet { tunnel_id, token } => tunnel::set(&agent.kube, &tunnel_id, &token).await, + Command::TunnelRemove {} => tunnel::remove(&agent.kube).await, // Answered before switching: the switch stops this process. Command::UpdateAgent { image } => { let result = match upgrade::check_agent_image(&agent.kube, &image).await { @@ -627,22 +652,20 @@ async fn run_command(agent: Agent, envelope: CommandEnvelope) { // The same: the Deployment's pins change last, after reporting. Command::RefreshInstall(parts) => { let mut progress = install::Progress::default(); - let mut result = match install::refresh(&agent.kube, &parts, &mut progress).await { - Ok(()) => ok(&format!( - "This cluster's install is now Pyo's ({}).", - parts.hash - )), + let refreshed = install::refresh(&agent.kube, &parts, &mut progress).await; + let mut result = match &refreshed { + Ok(r) => ok(&r.message(&parts)), Err(e) => failed(format!("{e:#}")), }; result.logs = progress.lines; - let finish = result.ok; + let finish = refreshed.ok(); if let Err(e) = agent.api.command_result(&id, &result).await { tracing::warn!(%id, error = %e, "couldn't report command result; leaving the Deployment as it is"); return; } - if finish { - tracing::info!(install = %parts.hash, "refreshed the admission policy; updating this agent's image pins"); - if let Err(e) = install::finish(&agent.kube, &parts).await { + if let Some(refreshed) = finish { + tracing::info!(install = %parts.hash, left = ?refreshed.older, "refreshed the admission policy; updating this agent's image pins"); + if let Err(e) = install::finish(&agent.kube, &parts, &refreshed).await { tracing::error!(error = %format!("{e:#}"), "couldn't update this agent's image pins"); } } @@ -723,6 +746,8 @@ fn command_kind(c: &Command) -> &'static str { Command::TailscaleRemove { .. } => "tailscale_remove", Command::SandboxCall(_) => "sandbox_call", Command::SyncRegistryTokens(_) => "sync_registry_tokens", + Command::TunnelSet { .. } => "tunnel_set", + Command::TunnelRemove {} => "tunnel_remove", Command::CheckDatabaseImport(_) => "check_database_import", Command::ListSnapshots(_) => "list_snapshots", Command::ForgetSnapshot(_) => "forget_snapshot", diff --git a/crates/pyo-agent/src/observability.rs b/crates/pyo-agent/src/observability.rs index 26239f94..37905a04 100644 --- a/crates/pyo-agent/src/observability.rs +++ b/crates/pyo-agent/src/observability.rs @@ -226,67 +226,74 @@ async fn vector(client: &Client) -> anyhow::Result<()> { ) .await?; Api::::namespaced(client.clone(), NS) - .patch( - VECTOR, - &pp(), - &Patch::Apply(json!({ - "apiVersion": "apps/v1", "kind": "DaemonSet", - "metadata": { "name": VECTOR, "labels": labels }, - "spec": { - "selector": { "matchLabels": { "app.kubernetes.io/name": VECTOR } }, - // Every server's copy moves at once: one on a server that's - // down (it can't be replaced there) would otherwise hold - // the others on their old config for good. A copy is only - // gone for seconds, and picks up where it stopped. - "updateStrategy": { "type": "RollingUpdate", "rollingUpdate": { "maxUnavailable": "100%" } }, - "template": { - "metadata": { - "labels": labels, - // Restart Vector when its config changes. - "annotations": { "pyo/config-hash": format!("{:x}", fxhash(&config)) }, - }, - "spec": { - "serviceAccountName": VECTOR, - "tolerations": [{ "operator": "Exists" }], - "containers": [{ - "name": "vector", - "image": VECTOR_IMAGE, - // Also re-read the config when its Secret changes, in - // case a restart is held up. - "args": ["--config", "/etc/vector/vector.yaml", "--watch-config"], - "env": [ - { "name": "VECTOR_LOG", "value": "warn" }, - { "name": "PYO_NODE_NAME", "valueFrom": { "fieldRef": { "fieldPath": "spec.nodeName" } } }, - // host_metrics reads the server's, not the container's. - { "name": "PROCFS_ROOT", "value": "/host/proc" }, - { "name": "SYSFS_ROOT", "value": "/host/sys" }, - ], - // ~35 MiB at rest (measured). - "resources": { "requests": { "cpu": "10m", "memory": "48Mi" }, "limits": { "memory": "256Mi" } }, - "volumeMounts": [ - { "name": "config", "mountPath": "/etc/vector", "readOnly": true }, - { "name": "data", "mountPath": "/vector-data-dir" }, - { "name": "var-log", "mountPath": "/var/log", "readOnly": true }, - { "name": "host-proc", "mountPath": "/host/proc", "readOnly": true }, - { "name": "host-sys", "mountPath": "/host/sys", "readOnly": true }, - ], - }], - "volumes": [ - { "name": "config", "secret": { "secretName": VECTOR } }, - { "name": "data", "hostPath": { "path": "/var/lib/pyo-vector", "type": "DirectoryOrCreate" } }, - { "name": "var-log", "hostPath": { "path": "/var/log" } }, - { "name": "host-proc", "hostPath": { "path": "/proc" } }, - { "name": "host-sys", "hostPath": { "path": "/sys" } }, - ], - }, - }, - }, - })), - ) + .patch(VECTOR, &pp(), &Patch::Apply(vector_daemonset(&config))) .await?; Ok(()) } +/// Vector's DaemonSet: on every server, restarted when its config changes. +fn vector_daemonset(config: &str) -> serde_json::Value { + let labels = + json!({ "app.kubernetes.io/name": VECTOR, "app.kubernetes.io/managed-by": MANAGER }); + json!({ + "apiVersion": "apps/v1", "kind": "DaemonSet", + "metadata": { "name": VECTOR, "labels": labels }, + "spec": { + "selector": { "matchLabels": { "app.kubernetes.io/name": VECTOR } }, + // Every server's copy moves at once: one on a server that's + // down (it can't be replaced there) would otherwise hold + // the others on their old config for good. A copy is only + // gone for seconds, and picks up where it stopped. + "updateStrategy": { "type": "RollingUpdate", "rollingUpdate": { "maxUnavailable": "100%" } }, + "template": { + "metadata": { + "labels": labels, + // Restart Vector when its config changes. + "annotations": { "pyo/config-hash": format!("{:x}", fxhash(config)) }, + }, + "spec": { + "serviceAccountName": VECTOR, + // Kept on a server short of disk: it reports that + // server's disk, and its DaemonSet mustn't replace it + // over and over there. + "priorityClassName": pyo_proto::system::SERVER_CRITICAL, + "tolerations": [{ "operator": "Exists" }], + "containers": [{ + "name": "vector", + "image": VECTOR_IMAGE, + // Also re-read the config when its Secret changes, in + // case a restart is held up. + "args": ["--config", "/etc/vector/vector.yaml", "--watch-config"], + "env": [ + { "name": "VECTOR_LOG", "value": "warn" }, + { "name": "PYO_NODE_NAME", "valueFrom": { "fieldRef": { "fieldPath": "spec.nodeName" } } }, + // host_metrics reads the server's, not the container's. + { "name": "PROCFS_ROOT", "value": "/host/proc" }, + { "name": "SYSFS_ROOT", "value": "/host/sys" }, + ], + // ~35 MiB at rest (measured). + "resources": { "requests": { "cpu": "10m", "memory": "48Mi" }, "limits": { "memory": "256Mi" } }, + "volumeMounts": [ + { "name": "config", "mountPath": "/etc/vector", "readOnly": true }, + { "name": "data", "mountPath": "/vector-data-dir" }, + { "name": "var-log", "mountPath": "/var/log", "readOnly": true }, + { "name": "host-proc", "mountPath": "/host/proc", "readOnly": true }, + { "name": "host-sys", "mountPath": "/host/sys", "readOnly": true }, + ], + }], + "volumes": [ + { "name": "config", "secret": { "secretName": VECTOR } }, + { "name": "data", "hostPath": { "path": "/var/lib/pyo-vector", "type": "DirectoryOrCreate" } }, + { "name": "var-log", "hostPath": { "path": "/var/log" } }, + { "name": "host-proc", "hostPath": { "path": "/proc" } }, + { "name": "host-sys", "hostPath": { "path": "/sys" } }, + ], + }, + }, + }, + }) +} + /// The traffic store's volume: the kept requests. Asked for once, never /// resized (the store keeps to the team's limit itself) and kept when /// observability is off. @@ -409,3 +416,25 @@ fn fxhash(s: &str) -> u64 { (h ^ b as u64).wrapping_mul(0x100000001b3) }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vector_stays_on_a_server_short_of_disk() { + let ds: DaemonSet = serde_json::from_value(vector_daemonset("a: 1")).unwrap(); + let spec = ds.spec.unwrap().template.spec.unwrap(); + assert_eq!( + spec.priority_class_name.as_deref(), + Some(pyo_proto::system::SERVER_CRITICAL) + ); + assert_eq!(spec.service_account_name.as_deref(), Some(VECTOR)); + // A new config restarts it. + let hash = |c: &str| { + vector_daemonset(c)["spec"]["template"]["metadata"]["annotations"]["pyo/config-hash"] + .clone() + }; + assert_ne!(hash("a: 1"), hash("a: 2")); + } +} diff --git a/crates/pyo-agent/src/observe.rs b/crates/pyo-agent/src/observe.rs index e3a83aeb..43f7776d 100644 --- a/crates/pyo-agent/src/observe.rs +++ b/crates/pyo-agent/src/observe.rs @@ -880,6 +880,8 @@ pub async fn heartbeat(client: &Client) -> anyhow::Result { database_metrics: crate::dbmetrics::report(&pods, &m.pods, &k.volumes), tailnet: Vec::new(), routes_version: crate::gateway::routes_version().into(), + // Filled in by the heartbeat loop (tunnel.rs). + tunnel: None, }) } @@ -985,6 +987,7 @@ async fn capabilities( waf_rejected, waf_active, tailnet_web_ips: tailnet_web_ips(client).await, + tunnel: true, } } diff --git a/crates/pyo-agent/src/rollout.rs b/crates/pyo-agent/src/rollout.rs index 4764b327..27c43da2 100644 --- a/crates/pyo-agent/src/rollout.rs +++ b/crates/pyo-agent/src/rollout.rs @@ -694,6 +694,8 @@ pub async fn set_public_ports(client: &kube::Client, on: bool) -> anyhow::Result ))) .await?; let mut changed: Vec = vec![]; + // One Service that fails doesn't keep the others from theirs. + let mut failed: Vec = vec![]; for svc in &list.items { let (Some(ns), Some(name)) = (svc.metadata.namespace.clone(), svc.metadata.name.clone()) else { @@ -709,10 +711,14 @@ pub async fn set_public_ports(client: &kube::Client, on: bool) -> anyhow::Result }; if let Err(e) = api.patch(&name, &pp, &Patch::Merge(&patch)).await { // Its server ports were taken meanwhile: new ones. - let Some(retry) = public_patch(svc, on, false).filter(|_| on) else { - return Err(e.into()); + let retried = match public_patch(svc, on, false).filter(|_| on) { + Some(retry) => api.patch(&name, &pp, &Patch::Merge(&retry)).await.err(), + None => Some(e), }; - api.patch(&name, &pp, &Patch::Merge(&retry)).await?; + if let Some(e) = retried { + failed.push(format!("{ns}/{name}: {e}")); + continue; + } } tracing::info!(namespace = %ns, service = %name, on, "public ports"); if !changed.contains(&ns) { @@ -721,11 +727,22 @@ pub async fn set_public_ports(client: &kube::Client, on: bool) -> anyhow::Result } // The namespaces' policies follow their public Services. for ns in changed { - let isolated = Api::::namespaced(client.clone(), &ns) + let isolated = match Api::::namespaced(client.clone(), &ns) .get_opt(pyo_proto::ISOLATION_POLICY) - .await? - .is_some(); - set_isolation(client, &ns, isolated).await?; + .await + { + Ok(p) => p.is_some(), + Err(e) => { + failed.push(format!("{ns}: {e}")); + continue; + } + }; + if let Err(e) = set_isolation(client, &ns, isolated).await { + failed.push(format!("{ns}: {e:#}")); + } + } + if !failed.is_empty() { + anyhow::bail!("{}", failed.join(". ")); } Ok(()) } diff --git a/crates/pyo-agent/src/scope.rs b/crates/pyo-agent/src/scope.rs index 50e4fb73..0793c6a0 100644 --- a/crates/pyo-agent/src/scope.rs +++ b/crates/pyo-agent/src/scope.rs @@ -5,8 +5,14 @@ //! a RoleBinding to the write role (`ensure_managed`). //! - Every heartbeat it finds out what it may do (`detect`) and reads the //! policy, which `refusal` applies to commands. +//! - Every heartbeat it also reads what the server's verifier says of its +//! automatic updates (`pyo-system/pyo-verifier`) and passes it on. It +//! never writes there, and nothing it does follows from it. -use std::sync::{Arc, RwLock}; +use std::sync::{ + Arc, RwLock, + atomic::{AtomicBool, AtomicU8, Ordering}, +}; use k8s_openapi::api::{ authorization::v1::{ResourceAttributes, SelfSubjectAccessReview, SelfSubjectAccessReviewSpec}, @@ -19,7 +25,7 @@ use kube::{ }; use pyo_proto::{ Command, - rbac::{self, AgentScope, Policy}, + rbac::{self, AgentScope, Policy, VerifierStatus}, }; use serde_json::Value; @@ -249,6 +255,111 @@ pub async fn read_policy(client: &Client) -> Policy { } } +/// The verifier's status couldn't be read at the last heartbeat: said once, +/// then again only after a read went through. +static VERIFIER_UNREAD: AtomicBool = AtomicBool::new(false); +/// Whether the last heartbeat found a verifier: 0 not looked yet, 1 none, +/// 2 one. Said when it changes. +static VERIFIER_SEEN: AtomicU8 = AtomicU8::new(0); + +/// What a read of the verifier's ConfigMap gave. +#[derive(Debug, PartialEq)] +enum VerifierRead { + /// Its data. + Found(std::collections::BTreeMap), + /// No ConfigMap: no verifier on this cluster. + Missing, + /// The install doesn't let the agent read it (one not refreshed yet). + Refused, + /// Anything else. + Failed(String), +} + +fn verifier_read(r: Result, kube::Error>) -> VerifierRead { + match r { + Ok(Some(cm)) => VerifierRead::Found(cm.data.unwrap_or_default()), + Ok(None) => VerifierRead::Missing, + Err(kube::Error::Api(e)) if e.code == 403 => VerifierRead::Refused, + Err(e) => VerifierRead::Failed(e.to_string()), + } +} + +/// The status a read gave (none unless one was found), and what to log of +/// it: each state is said when it starts, never at every heartbeat. A +/// refusal is expected on an install not refreshed yet, so it's said +/// quietly. +fn verifier_from( + read: VerifierRead, + unread: &AtomicBool, + seen: &AtomicU8, +) -> (Option, Option<(tracing::Level, String)>) { + use crate::gateway::{first_time, settled}; + let mut said = None; + let status = match read { + VerifierRead::Found(data) => { + settled(unread); + let status = VerifierStatus::from_data(&data); + if seen.swap(2, Ordering::Relaxed) != 2 { + said = Some(( + tracing::Level::INFO, + format!( + "the verifier on this cluster's server reports in (version {})", + status.version + ), + )); + } + Some(status) + } + VerifierRead::Missing => { + settled(unread); + if seen.swap(1, Ordering::Relaxed) == 2 { + said = Some(( + tracing::Level::INFO, + "the verifier on this cluster's server no longer reports in".into(), + )); + } + None + } + VerifierRead::Refused => { + if first_time(unread) { + said = Some(( + tracing::Level::INFO, + "this install doesn't let the agent read the verifier's status yet: the cluster's connect command brings that".into(), + )); + } + None + } + VerifierRead::Failed(e) => { + if first_time(unread) { + said = Some(( + tracing::Level::WARN, + format!("couldn't read the verifier's status: {e}"), + )); + } + None + } + }; + (status, said) +} + +/// What the verifier on the cluster's first server last said of its +/// automatic updates: none when there's no ConfigMap (no verifier), or +/// when it can't be read. Passed on with the heartbeat, only to be shown. +pub async fn read_verifier(client: &Client) -> Option { + let read = verifier_read( + Api::::namespaced(client.clone(), rbac::NS) + .get_opt(rbac::VERIFIER_CONFIGMAP) + .await, + ); + let (status, said) = verifier_from(read, &VERIFIER_UNREAD, &VERIFIER_SEEN); + match said { + Some((tracing::Level::WARN, m)) => tracing::warn!("{m}"), + Some((_, m)) => tracing::info!("{m}"), + None => {} + } + status +} + /// What the agent may do, as the cluster answers. pub async fn detect(client: &Client, policy: Policy) -> AgentScope { let full = can(client, "*", "*", "*", None).await; @@ -283,10 +394,13 @@ pub async fn detect(client: &Client, policy: Policy) -> AgentScope { _ => "missing", } }; - // The install it's from: the same stamp on the policy and on its Deployment. - let install = match crate::install::deployment_stamp(client).await { - Some(d) if !installed_policy.is_empty() && d == installed_policy => installed_policy, - _ => String::new(), + // The install it's from: the same stamp on the policy and on its + // Deployment. And the roles a refresh left as they were, if any. + let (install, roles_older) = match crate::install::deployment_stamp(client).await { + Some(d) if !installed_policy.is_empty() && d == installed_policy => { + rbac::parse_stamp(&installed_policy) + } + _ => (String::new(), vec![]), }; let self_update = can_named( client, @@ -305,7 +419,10 @@ pub async fn detect(client: &Client, policy: Policy) -> AgentScope { servers: can(client, "patch", "", "nodes", None).await, policy, install, + roles_older, self_update, + headers_kept: crate::gateway::headers_kept(), + verifier: read_verifier(client).await, } } @@ -404,6 +521,110 @@ mod tests { assert_eq!(tries.load(std::sync::atomic::Ordering::SeqCst), 1); } + fn data(pairs: &[(&str, &str)]) -> std::collections::BTreeMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + } + + fn api_error(code: u16, reason: &str) -> kube::Error { + kube::Error::Api(Box::new( + kube::core::Status::failure(&format!("configmaps \"pyo-verifier\" is {reason}"), reason) + .with_code(code), + )) + } + + /// What the cluster answers for the verifier's ConfigMap: no ConfigMap + /// is no verifier, and an install that refuses the read is told apart + /// from any other failure. + #[test] + fn the_verifiers_configmap_is_read_as_the_cluster_answers() { + assert_eq!(verifier_read(Ok(None)), VerifierRead::Missing); + let cm = ConfigMap { + data: Some(data(&[("version", "0.51.0")])), + ..Default::default() + }; + assert_eq!( + verifier_read(Ok(Some(cm))), + VerifierRead::Found(data(&[("version", "0.51.0")])) + ); + // One without data: a verifier that said nothing yet. + assert_eq!( + verifier_read(Ok(Some(ConfigMap::default()))), + VerifierRead::Found(Default::default()) + ); + assert_eq!(verifier_read(Err(api_error(403, "Forbidden"))), VerifierRead::Refused); + assert!(matches!( + verifier_read(Err(api_error(500, "InternalError"))), + VerifierRead::Failed(_) + )); + } + + /// The status the heartbeat carries: only from a ConfigMap that's + /// there, with missing and odd fields read as they are. + #[test] + fn the_verifiers_status_goes_into_the_scope_only_when_its_there() { + let (unread, seen) = (AtomicBool::new(false), AtomicU8::new(0)); + let status = |read| verifier_from(read, &unread, &seen).0; + assert_eq!(status(VerifierRead::Missing), None); + assert_eq!(status(VerifierRead::Refused), None); + assert_eq!(status(VerifierRead::Failed("timeout".into())), None); + let full = status(VerifierRead::Found(data(&[ + ("version", "0.51.0"), + ("live", "0.51.0"), + ("checked", "2026-11-23T10:00:00Z"), + ("error", ""), + ("hold", "true"), + ("host", "server-1"), + ]))) + .unwrap(); + assert_eq!(full.version, "0.51.0"); + assert_eq!(full.checked, "2026-11-23T10:00:00Z"); + assert!(full.hold && full.error.is_empty()); + // Missing fields: empty. Odd ones: as they are, for Pyo to judge. + assert_eq!(status(VerifierRead::Found(data(&[]))), Some(VerifierStatus::default())); + let odd = status(VerifierRead::Found(data(&[("checked", "soon"), ("hold", "maybe")]))).unwrap(); + assert_eq!(odd.checked, "soon"); + assert!(!odd.hold); + } + + /// Every heartbeat reads it: a refusal (an install not refreshed yet) + /// or a failure is said once, not each time, and so is finding one. + #[test] + fn a_verifier_that_cant_be_read_is_said_once() { + let (unread, seen) = (AtomicBool::new(false), AtomicU8::new(0)); + let said = |read| verifier_from(read, &unread, &seen).1; + // Refused at every heartbeat: one quiet line. + let first = said(VerifierRead::Refused).unwrap(); + assert_eq!(first.0, tracing::Level::INFO); + assert!(first.1.contains("connect command"), "{}", first.1); + for _ in 0..5 { + assert_eq!(said(VerifierRead::Refused), None); + } + // No verifier at all: nothing to say, at any heartbeat. + let (unread, seen) = (AtomicBool::new(false), AtomicU8::new(0)); + let said = |read| verifier_from(read, &unread, &seen).1; + for _ in 0..3 { + assert_eq!(said(VerifierRead::Missing), None); + } + // One appears: said once. A failure after: once, as a warning. + assert_eq!( + said(VerifierRead::Found(data(&[("version", "0.51.0")]))).unwrap().1, + "the verifier on this cluster's server reports in (version 0.51.0)" + ); + assert_eq!(said(VerifierRead::Found(data(&[]))), None); + assert_eq!(said(VerifierRead::Failed("timeout".into())).unwrap().0, tracing::Level::WARN); + assert_eq!(said(VerifierRead::Failed("timeout".into())), None); + assert_eq!(said(VerifierRead::Refused), None); + // Read again, then refused again: said again. + assert_eq!(said(VerifierRead::Found(data(&[]))), None); + assert!(said(VerifierRead::Refused).is_some()); + // And when it's gone. + assert!(said(VerifierRead::Missing).is_some()); + assert_eq!(said(VerifierRead::Missing), None); + } + #[test] fn policy_refusals() { let logs = Command::Cancel { diff --git a/crates/pyo-agent/src/tunnel.rs b/crates/pyo-agent/src/tunnel.rs new file mode 100644 index 00000000..fc8032b7 --- /dev/null +++ b/crates/pyo-agent/src/tunnel.rs @@ -0,0 +1,499 @@ +//! The cluster's Cloudflare Tunnel connector (docs/cloudflare-tunnel.md §7): +//! cloudflared in pyo-system with the tunnel's token, pointed at Pyo +//! Gateway's HTTPS through `system::TUNNEL_ORIGIN_SERVICE`. Pyo's control +//! plane holds the Cloudflare account. The agent only ever gets the +//! tunnel's own token (`TunnelSet`), keeps it in a Secret labelled with the +//! tunnel's id, and follows what each heartbeat reply wants. +//! +//! The connectors' pod addresses are the only ones the tunnel listeners +//! trust to say who the visitor is (gateway.rs, the `tunnel` client +//! policies). They're looked at with each heartbeat and the policies follow. +//! +//! A cluster whose install is older than this agent refuses these objects: +//! what runs is kept, nothing more is written until the install changes, +//! and the heartbeat says so (`TunnelReport::refused`). + +use std::sync::{ + Mutex, + atomic::{AtomicBool, Ordering}, +}; + +use k8s_openapi::api::{ + apps::v1::Deployment, + core::v1::{Pod, Secret, Service}, + policy::v1::PodDisruptionBudget, +}; +use kube::{ + Api, Client, ResourceExt, + api::{DeleteParams, ListParams, Patch, PatchParams}, +}; +use pyo_proto::{CommandResult, TunnelPod, TunnelReport, TunnelWanted, rbac, system}; + +use crate::{MANAGER, failed}; + +/// Said when the cluster's install refuses the tunnel's objects. +pub const REFUSED: &str = "This cluster's install is older than Pyo's. Run the command under Refresh this cluster in the cluster's settings to use Cloudflare Tunnel."; + +/// What the agent keeps between heartbeats. +#[derive(Default)] +struct Kept { + /// The connectors' pod addresses the tunnel policies trust now. + pods: Vec, + /// The connector's objects as last applied (their JSON). + applied: String, + /// The install stamp a write was refused on. + refused_on: Option, +} + +static KEPT: Mutex = Mutex::new(Kept { + pods: vec![], + applied: String::new(), + refused_on: None, +}); +static REFUSED_NOW: AtomicBool = AtomicBool::new(false); + +fn kept() -> std::sync::MutexGuard<'static, Kept> { + KEPT.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The connectors' pod addresses, as the tunnel policies trust them. +pub fn trusted_now() -> Vec { + kept().pods.clone() +} + +/// The install refused a tunnel object: said once, and reported. +pub fn refused_now(e: &kube::Error) { + if !REFUSED_NOW.swap(true, Ordering::Relaxed) { + tracing::warn!(error = %e, "{REFUSED}"); + } +} + +fn pp() -> PatchParams { + PatchParams::apply(MANAGER).force() +} + +/// Tunnel ids are UUIDs (they go into a label). +pub fn id_ok(id: &str) -> bool { + id.len() == 36 + && id.bytes().enumerate().all(|(i, b)| match i { + 8 | 13 | 18 | 23 => b == b'-', + _ => b.is_ascii_hexdigit(), + }) +} + +fn secrets(client: &Client) -> Api { + Api::namespaced(client.clone(), rbac::NS) +} + +/// The tunnel the token here is for, from its Secret's label. +async fn token_for(client: &Client) -> kube::Result> { + Ok(secrets(client) + .get_opt(system::TUNNEL_NAME) + .await? + .and_then(|s| s.labels().get(system::TUNNEL_ID_LABEL).cloned())) +} + +/// The connector's objects, as written. +fn connector() -> [serde_json::Value; 3] { + [ + system::tunnel_deployment(system::CLOUDFLARED_IMAGE), + system::tunnel_budget(), + system::tunnel_origin_service(), + ] +} + +/// Write the connector's objects (only when they changed since the last +/// write here, or are missing). +async fn apply_connector(client: &Client, force: bool) -> kube::Result<()> { + let objects = connector(); + let text = serde_json::to_string(&objects).unwrap_or_default(); + let deployments: Api = Api::namespaced(client.clone(), rbac::NS); + let there = deployments.get_opt(system::TUNNEL_NAME).await?.is_some(); + if !force && there && kept().applied == text { + return Ok(()); + } + let [d, b, s] = &objects; + deployments + .patch(system::TUNNEL_NAME, &pp(), &Patch::Apply(d)) + .await?; + Api::::namespaced(client.clone(), rbac::NS) + .patch(system::TUNNEL_NAME, &pp(), &Patch::Apply(b)) + .await?; + Api::::namespaced(client.clone(), system::GATEWAY_NS) + .patch(system::TUNNEL_ORIGIN_SERVICE, &pp(), &Patch::Apply(s)) + .await?; + kept().applied = text; + Ok(()) +} + +/// A refused write: kept until the install changes. +async fn refused(client: &Client, e: &kube::Error) { + refused_now(e); + kept().refused_on = Some(crate::refused::install_stamp(client).await); +} + +/// `TunnelSet`: keep the token and run the connector with it. +pub async fn set(client: &Client, tunnel_id: &str, token: &str) -> CommandResult { + if !id_ok(tunnel_id) { + return failed("That isn't a tunnel id."); + } + if token.is_empty() || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) { + return failed("That isn't a tunnel token."); + } + let written = async { + secrets(client) + .patch( + system::TUNNEL_NAME, + &pp(), + &Patch::Apply(system::tunnel_secret(tunnel_id, token)), + ) + .await?; + apply_connector(client, true).await + } + .await; + match written { + Ok(()) => { + REFUSED_NOW.store(false, Ordering::Relaxed); + kept().refused_on = None; + CommandResult { + data: serde_json::to_value(report(client).await).ok(), + ..crate::ok("The tunnel's connector is starting.") + } + } + Err(e) if crate::refused::is_refusal(&e) => { + refused(client, &e).await; + failed(REFUSED) + } + Err(e) => failed(format!("Couldn't start the tunnel's connector: {e}")), + } +} + +/// `TunnelRemove`: stop the connector, delete its token and its Service. +pub async fn remove(client: &Client) -> CommandResult { + match remove_all(client).await { + Ok(()) => crate::ok("The tunnel's connector is removed."), + Err(e) => failed(format!("Couldn't remove the tunnel's connector: {e}")), + } +} + +async fn remove_all(client: &Client) -> kube::Result<()> { + let gone = |r: kube::Result<()>| match r { + Err(kube::Error::Api(e)) if e.code == 404 => Ok(()), + other => other, + }; + let dp = DeleteParams::default(); + gone(Api::::namespaced(client.clone(), rbac::NS) + .delete(system::TUNNEL_NAME, &dp) + .await + .map(|_| ()))?; + gone(Api::::namespaced(client.clone(), rbac::NS) + .delete(system::TUNNEL_NAME, &dp) + .await + .map(|_| ()))?; + gone(secrets(client).delete(system::TUNNEL_NAME, &dp).await.map(|_| ()))?; + gone(Api::::namespaced(client.clone(), system::GATEWAY_NS) + .delete(system::TUNNEL_ORIGIN_SERVICE, &dp) + .await + .map(|_| ()))?; + kept().applied.clear(); + Ok(()) +} + +/// What a heartbeat reply wants: the connector for this tunnel (when the +/// token here is for it), or none. Then the tunnel policies follow the +/// connectors' pods. +pub async fn follow(client: &Client, wanted: &TunnelWanted) { + // Refused before: nothing until the install changes. + let waiting = kept().refused_on.clone(); + if let Some(on) = waiting { + if crate::refused::install_stamp(client).await == on { + return; + } + kept().refused_on = None; + REFUSED_NOW.store(false, Ordering::Relaxed); + } + let have = match token_for(client).await { + Ok(h) => h, + Err(e) => { + tracing::warn!(error = %e, "couldn't read the tunnel's token"); + return; + } + }; + let done = match (&wanted.tunnel_id, &have) { + (None, None) => Ok(()), + (None, Some(_)) => remove_all(client).await, + // The token for it is here: the connector runs with it. + (Some(w), Some(h)) if w == h => apply_connector(client, false).await, + // Waiting for `TunnelSet` (the report says which token is here). + (Some(_), _) => Ok(()), + }; + if let Err(e) = done { + if crate::refused::is_refusal(&e) { + refused(client, &e).await; + } else { + tracing::warn!(error = %e, "couldn't apply the tunnel's connector"); + } + return; + } + if let Err(e) = follow_pods(client).await { + tracing::warn!(error = %format!("{e:#}"), "couldn't update the tunnel's trusted addresses"); + } +} + +fn pods(client: &Client) -> Api { + Api::namespaced(client.clone(), rbac::NS) +} + +fn selector() -> ListParams { + ListParams::default().labels(&format!("app.kubernetes.io/name={}", system::TUNNEL_APP)) +} + +/// Every address of the connectors' pods, ready or not, as /32 and /128. +pub fn pod_cidrs(list: &[Pod]) -> Vec { + let ips: Vec = list + .iter() + .filter_map(|p| p.status.as_ref()) + .flat_map(|s| { + s.pod_ips + .iter() + .flatten() + .map(|ip| ip.ip.clone()) + .chain(s.pod_ip.clone()) + }) + .collect(); + system::host_cidrs(&ips) +} + +/// The tunnel policies trust the connectors' pods as they are now. +async fn follow_pods(client: &Client) -> anyhow::Result<()> { + let now = pod_cidrs(&pods(client).list(&selector()).await?.items); + let old = kept().pods.clone(); + if now == old { + return Ok(()); + } + crate::gateway::set_tunnel_pods(client, &old, &now).await?; + tracing::info!(pods = now.len(), "the tunnel's trusted addresses changed"); + kept().pods = now; + Ok(()) +} + +/// Why a pod isn't ready, at most 200 characters: a container's waiting +/// or last terminated reason. +fn not_ready_reason(p: &Pod) -> Option { + let statuses = p.status.as_ref()?.container_statuses.as_ref()?; + statuses.iter().find_map(|c| { + let st = c.state.as_ref()?; + let r = st + .waiting + .as_ref() + .and_then(|w| w.reason.clone()) + .or_else(|| st.terminated.as_ref().and_then(|t| t.reason.clone())) + .or_else(|| { + c.last_state + .as_ref() + .and_then(|l| l.terminated.as_ref()) + .and_then(|t| t.reason.clone()) + })?; + Some(r.chars().take(200).collect()) + }) +} + +/// Each connector pod as reported. +pub fn pod_reports(list: &[Pod]) -> Vec { + let mut out: Vec = list + .iter() + .map(|p| { + let ready = p + .status + .as_ref() + .and_then(|s| s.conditions.as_ref()) + .is_some_and(|cs| cs.iter().any(|c| c.type_ == "Ready" && c.status == "True")); + TunnelPod { + server: p + .spec + .as_ref() + .and_then(|s| s.node_name.clone()) + .unwrap_or_default(), + ready, + restarts: p + .status + .as_ref() + .and_then(|s| s.container_statuses.as_ref()) + .map(|cs| cs.iter().map(|c| c.restart_count).sum()) + .unwrap_or(0), + reason: if ready { None } else { not_ready_reason(p) }, + } + }) + .collect(); + out.sort_by(|a, b| a.server.cmp(&b.server)); + out +} + +/// The connector as it is, for the heartbeat. +pub async fn report(client: &Client) -> TunnelReport { + let tunnel_id = token_for(client).await.ok().flatten(); + let deployment = Api::::namespaced(client.clone(), rbac::NS) + .get_opt(system::TUNNEL_NAME) + .await + .ok() + .flatten(); + let (replicas, ready_replicas) = deployment + .as_ref() + .and_then(|d| d.status.as_ref()) + .map(|s| (s.replicas.unwrap_or(0), s.ready_replicas.unwrap_or(0))) + .unwrap_or((0, 0)); + let list = if deployment.is_some() { + pods(client) + .list(&selector()) + .await + .map(|l| l.items) + .unwrap_or_default() + } else { + vec![] + }; + let origin_ready = Api::::namespaced(client.clone(), system::GATEWAY_NS) + .get_opt(system::TUNNEL_ORIGIN_SERVICE) + .await + .ok() + .flatten() + .is_some(); + TunnelReport { + tunnel_id, + replicas, + ready_replicas, + pods: pod_reports(&list), + origin_ready, + refused: REFUSED_NOW.load(Ordering::Relaxed), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fakekube::FakeKube; + use serde_json::json; + + const ID: &str = "c1744f8b-faa1-48a4-9e5c-02ac921467fa"; + const SECRET: &str = "api/v1/namespaces/pyo-system/secrets/pyo-tunnel"; + const DEPLOYMENT: &str = "apis/apps/v1/namespaces/pyo-system/deployments/pyo-tunnel"; + const BUDGET: &str = "apis/policy/v1/namespaces/pyo-system/poddisruptionbudgets/pyo-tunnel"; + const ORIGIN: &str = "api/v1/namespaces/pyo-gateway/services/pyo-tunnel-origin"; + + /// The tests share the agent's kept state: one at a time. + static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + + fn reset() { + let mut k = kept(); + *k = Kept::default(); + REFUSED_NOW.store(false, Ordering::Relaxed); + } + + /// The token goes into the Secret with its tunnel, the connector + /// starts, the report says so, and removing takes all of it away. + #[tokio::test] + async fn the_connector_runs_with_its_token_and_goes_with_it() { + let _one = SERIAL.lock().await; + let (kube, client) = FakeKube::start().await; + reset(); + assert!(!set(&client, "../x", "tok").await.ok); + assert!(!set(&client, ID, "").await.ok); + let r = set(&client, ID, "eyJhIjoiYiJ9").await; + assert!(r.ok, "{:?}", r.message); + let s = kube.get(SECRET).expect("the token's Secret"); + assert_eq!(s["metadata"]["labels"][system::TUNNEL_ID_LABEL], ID); + assert_eq!(s["stringData"]["token"], "eyJhIjoiYiJ9"); + let d = kube.get(DEPLOYMENT).expect("the connector"); + assert_eq!(d["spec"]["replicas"], 2); + assert!(kube.get(BUDGET).is_some()); + assert!(kube.get(ORIGIN).is_some()); + let rep = report(&client).await; + assert_eq!(rep.tunnel_id.as_deref(), Some(ID)); + assert!(rep.origin_ready && !rep.refused); + // The token never shows in what's reported. + assert!(!serde_json::to_string(&r.data).unwrap().contains("eyJhIjoiYiJ9")); + + // Wanted for another tunnel: left alone, waiting for its token. + follow( + &client, + &TunnelWanted { + tunnel_id: Some("00000000-0000-4000-8000-000000000001".into()), + ports_public: true, + }, + ) + .await; + assert!(kube.get(DEPLOYMENT).is_some()); + // Not wanted any more: gone, token and all. + follow(&client, &TunnelWanted::default()).await; + for path in [SECRET, DEPLOYMENT, BUDGET, ORIGIN] { + assert!(kube.get(path).is_none(), "{path}"); + } + assert_eq!(report(&client).await.tunnel_id, None); + // Removing again is fine. + assert!(remove(&client).await.ok); + } + + /// The connector is put back when it's missing, with the token here. + #[tokio::test] + async fn a_missing_connector_is_put_back() { + let _one = SERIAL.lock().await; + let (kube, client) = FakeKube::start().await; + reset(); + kube.put(SECRET, system::tunnel_secret(ID, "tok")); + let wanted = TunnelWanted { + tunnel_id: Some(ID.into()), + ports_public: true, + }; + follow(&client, &wanted).await; + assert!(kube.get(DEPLOYMENT).is_some()); + } + + /// An install older than this agent refuses the connector: the command + /// says what to run, the report says so, and nothing is tried again + /// until the install changes. + #[tokio::test] + async fn an_older_install_is_reported_and_waited_for() { + let _one = SERIAL.lock().await; + let (kube, client) = FakeKube::start().await; + reset(); + kube.admit(|w| { + (w.plural == "deployments").then(|| (403, "deployments.apps \"pyo-tunnel\" is forbidden: ValidatingAdmissionPolicy 'pyo-agent' with binding 'pyo-agent' denied request".into())) + }); + let r = set(&client, ID, "tok").await; + assert!(!r.ok); + assert_eq!(r.message.as_deref(), Some(REFUSED)); + assert!(report(&client).await.refused); + let before = kube.refused().len(); + follow( + &client, + &TunnelWanted { + tunnel_id: Some(ID.into()), + ports_public: true, + }, + ) + .await; + assert_eq!(kube.refused().len(), before, "not tried again"); + assert!(!REFUSED.contains(';')); + } + + #[test] + fn pods_report_their_server_and_why_they_wait() { + let pod: Pod = serde_json::from_value(json!({ + "metadata": { "name": "pyo-tunnel-1" }, + "spec": { "nodeName": "fal2", "containers": [] }, + "status": { + "podIP": "10.42.1.7", "podIPs": [{ "ip": "10.42.1.7" }, { "ip": "fd00::7" }], + "conditions": [{ "type": "Ready", "status": "False" }], + "containerStatuses": [{ "name": "cloudflared", "ready": false, "restartCount": 3, "image": "x", "imageID": "", + "state": { "waiting": { "reason": "ImagePullBackOff" } } }], + }, + })) + .unwrap(); + let r = pod_reports(std::slice::from_ref(&pod)); + assert_eq!(r[0].server, "fal2"); + assert!(!r[0].ready); + assert_eq!(r[0].restarts, 3); + assert_eq!(r[0].reason.as_deref(), Some("ImagePullBackOff")); + assert_eq!(pod_cidrs(&[pod]), ["10.42.1.7/32", "fd00::7/128"]); + assert!(id_ok(ID) && !id_ok("x")); + } +} diff --git a/crates/pyo-agent/src/upgrade.rs b/crates/pyo-agent/src/upgrade.rs index e9a4bf9e..8f6bee18 100644 --- a/crates/pyo-agent/src/upgrade.rs +++ b/crates/pyo-agent/src/upgrade.rs @@ -463,6 +463,7 @@ pub fn check_release(path: &str) -> anyhow::Result<()> { let release: Release = serde_json::from_slice(&std::fs::read(path)?)?; let mut problems = release.problems(); problems.extend(access_problem(&release)); + problems.extend(database_pins_problem(&release)); if !problems.is_empty() { anyhow::bail!( "Pyo {} can't be applied: {}", @@ -490,6 +491,20 @@ fn access_problem(release: &Release) -> Option { } } +/// A release must name the database images its code pins (this agent's: +/// it's the release's own), so installations know before they update +/// whether their databases restart. +fn database_pins_problem(release: &Release) -> Option { + let ours = pyo_proto::bundles::database_pins(); + match &release.database_pins { + Some(p) if *p == ours => None, + _ => Some( + "databasePins isn't what this release's databases run (pyo-agent database-pins)." + .into(), + ), + } +} + /// `pyo-agent upgrade `. Ends its output with one JSON line /// `{"pyoUpgradeOutcome": {"ok", "message", "rolledBack"}}`. pub async fn run_job(path: &str) -> anyhow::Result<()> { @@ -884,6 +899,21 @@ async fn restore(client: &Client, saved: &[(String, String, Value)]) -> anyhow:: mod tests { use super::*; + /// Nor one that doesn't name (rightly) the database images its code pins. + #[test] + fn a_release_names_the_database_images_its_code_pins() { + let with = |p: Option>| Release { + database_pins: p, + ..Default::default() + }; + let ours = pyo_proto::bundles::database_pins(); + assert_eq!(database_pins_problem(&with(Some(ours.clone()))), None); + assert!(database_pins_problem(&with(None)).is_some()); + let mut other = ours; + other.insert("mysql".into(), "mysql@sha256:00".into()); + assert!(database_pins_problem(&with(Some(other))).is_some()); + } + /// The release workflow can't publish a release.json that doesn't say /// (rightly) which roles its agent has. #[test] diff --git a/crates/pyo-api/Cargo.toml b/crates/pyo-api/Cargo.toml index 89ae724d..8bf09691 100644 --- a/crates/pyo-api/Cargo.toml +++ b/crates/pyo-api/Cargo.toml @@ -13,6 +13,7 @@ axum-extra = { version = "0.12.6", features = ["cookie", "typed-header"] } base64 = "0.23.1" cookie = "0.18" pyo-proto = { version = "0.5.5", path = "../pyo-proto", features = ["openapi", "sandbox-token", "command-signing", "agent-ca"] } +pyo-sigstore = { path = "../pyo-sigstore" } hex = "0.4.3" hmac = "0.13.0" hyper = { version = "1.12.0", features = ["client", "http1"] } @@ -33,7 +34,7 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" utoipa = { version = "5.5.0", features = ["preserve_order", "preserve_path_order"] } sha2 = "0.11.1" -sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "tls-rustls", "postgres", "json", "macros", "migrate"] } +sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "tls-rustls-aws-lc-rs", "postgres", "json", "macros", "migrate"] } thiserror = "2.0.21" tokio = { version = "1.54.1", features = ["full"] } tower-http = { version = "0.7.1", features = ["fs", "trace", "compression-gzip", "compression-br"] } diff --git a/crates/pyo-api/assets/connect.sh b/crates/pyo-api/assets/connect.sh index 47ce8535..b101086b 100644 --- a/crates/pyo-api/assets/connect.sh +++ b/crates/pyo-api/assets/connect.sh @@ -8,12 +8,17 @@ # # --api where the agent reaches Pyo # --token the connect token (works once, within an hour) +# --install-url where this server gets Pyo's install files, when the +# agent reaches Pyo at another address (Pyo Cloud) # --tailscale-key joins your tailnet first (a single-use key from Pyo) # --registry Pyo's registry door, for images Pyo builds # --registry-token this cluster's login there (pull only) # --local-registry a registry in this cluster for the images it builds, # instead of Pyo's (Pyo Cloud: images stay on your servers) # --version runs this Pyo release's connect.sh instead, from pyo.dev +# --auto-update sets up automatic updates on this server: Pyo's verifier, +# which takes only signed Pyo releases +# --no-auto-update turns them off. Without either, the last choice stays # # Or only joins this machine to the tailnet (Pyo's own machine does this # once Tailscale is set up in Pyo): --tailnet-only, with TS_AUTHKEY. @@ -236,17 +241,21 @@ quietly() { set -euo pipefail export DEBIAN_FRONTEND=noninteractive -API="" TOKEN="" TS_AUTHKEY="${TS_AUTHKEY:-}" REGISTRY="" REGISTRY_TOKEN="" LOCAL_REGISTRY="" -UNINSTALL="" KEEP_DATA="" YES="" DRY_RUN="" WITH_PYO="" TAILNET_ONLY="" +# >>> pyo:connect-args (connect.sh only; join.rs tests it) +API="" TOKEN="" TS_AUTHKEY="${TS_AUTHKEY:-}" REGISTRY="" REGISTRY_TOKEN="" LOCAL_REGISTRY="" INSTALL_URL="" +UNINSTALL="" KEEP_DATA="" YES="" DRY_RUN="" WITH_PYO="" TAILNET_ONLY="" AUTO_UPDATE="" while [ $# -gt 0 ]; do case "$1" in --api) API="${2%/}"; shift 2 ;; --token) TOKEN="$2"; shift 2 ;; + --install-url) INSTALL_URL="${2%/}"; shift 2 ;; --tailscale-key) TS_AUTHKEY="$2"; shift 2 ;; --registry) REGISTRY="$2"; shift 2 ;; --registry-token) REGISTRY_TOKEN="$2"; shift 2 ;; --local-registry) LOCAL_REGISTRY=1; shift ;; --tailnet-only) TAILNET_ONLY=1; shift ;; + --auto-update) AUTO_UPDATE=on; shift ;; + --no-auto-update) AUTO_UPDATE=off; shift ;; --uninstall) UNINSTALL=1; shift ;; --keep-data) KEEP_DATA=1; shift ;; --yes | -y) YES=1; shift ;; @@ -258,6 +267,225 @@ while [ $# -gt 0 ]; do *) echo "Unknown option: $1" >&2; exit 2 ;; esac done +# <<< pyo:connect-args +# >>> pyo:connect-lock (connect.sh only; join.rs tests it) +# One Pyo setup at a time on a server: this script and Pyo's verifier +# (`pyo-verify run` skips its turn while the lock is held). On the server +# Pyo runs on, also Pyo's own timers and installer (install.sh +# `host_units`). They hold this lock while they run connect.sh, which then +# has it as file 9. A run by hand waits for them. The lock goes when this +# script ends. The verifier is started without file 9, so nothing that +# stays behind holds the lock. +CONNECT_LOCK=/run/pyo-connect.lock +connect_lock_held() { [ "$(readlink "/proc/$$/fd/9" 2>/dev/null)" = "$CONNECT_LOCK" ]; } +connect_lock() { + [ "$(id -u)" = 0 ] && command -v flock >/dev/null || return 0 + ! connect_lock_held || return 0 + exec 9>"$CONNECT_LOCK" + flock -n 9 && return 0 + echo "Waiting for another Pyo setup on this server to finish." + flock 9 +} +# <<< pyo:connect-lock +# >>> pyo:auto-update (connect.sh only; join.rs tests it) +# Automatic updates on a cluster's first server: Pyo's verifier +# (pyo-verify), a small root program a systemd timer runs. It takes only +# what a signed Pyo release defines, for the version Pyo names. +# --auto-update turns it on, --no-auto-update off. Without either, the +# choice of the last run stays (AUTO_UPDATE_FILE). The server Pyo itself +# runs on has no verifier: it updates with Pyo. +# +# The release workflow writes this script's release and the SHA-256 of that +# release's verifier on the pyo:verify-pin lines, in the copy it publishes +# (scripts/release-manifest.ts). The verifier comes from that GitHub +# release and is installed only when it matches. A copy without the lines +# (Pyo's own at /install/, a dev build) installs no verifier. Nothing +# here stops a connect: a step that fails says so in one line. +PYO_VERIFY_RELEASE="" # pyo:verify-pin release +PYO_VERIFY_SHA256_X86_64="" # pyo:verify-pin x86_64 +PYO_VERIFY_SHA256_AARCH64="" # pyo:verify-pin aarch64 +PYO_VERIFY_RELEASES=https://github.com/upsetdev/pyo/releases/download +AUTO_UPDATE_FILE=/etc/pyo/auto-update +VERIFY_BIN=/usr/local/bin/pyo-verify +VERIFY_UNITS=/etc/systemd/system +OWN_SERVER=/usr/local/lib/pyo/connect-this-machine.sh +# AUTO_UPDATE for this run: the flag, kept for later runs, else the choice +# of the last run. +auto_update_choice() { + if [ -e "$OWN_SERVER" ]; then + AUTO_UPDATE="" + elif [ -n "$AUTO_UPDATE" ]; then + { mkdir -p "$(dirname "$AUTO_UPDATE_FILE")" && echo "$AUTO_UPDATE" > "$AUTO_UPDATE_FILE"; } 2>/dev/null || true + else + AUTO_UPDATE=$(cat "$AUTO_UPDATE_FILE" 2>/dev/null || true) + case "$AUTO_UPDATE" in on | off) ;; *) AUTO_UPDATE="" ;; esac + fi +} +# This machine's processor, as the verifier's files name it. +verify_arch() { + case "$(uname -m)" in + x86_64 | amd64) echo x86_64 ;; + aarch64 | arm64) echo aarch64 ;; + esac +} +verify_pin() { + case "$(verify_arch)" in + x86_64) echo "$PYO_VERIFY_SHA256_X86_64" ;; + aarch64) echo "$PYO_VERIFY_SHA256_AARCH64" ;; + esac +} +verify_version() { [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+(-rc\.[0-9]+)?$ ]]; } +# verify_older A B: release A is older than B. A release candidate +# (X.Y.Z-rc.N) comes before its release. +verify_older() { + local a=${1%%-*} b=${2%%-*} ra=999999999 rb=999999999 x y i + verify_version "$1" && verify_version "$2" || return 1 + [ "$1" = "$a" ] || ra=${1##*-rc.} + [ "$2" = "$b" ] || rb=${2##*-rc.} + IFS=. read -r -a x <<<"$a.$ra" + IFS=. read -r -a y <<<"$b.$rb" + for i in 0 1 2 3; do + [ "${x[i]}" -eq "${y[i]}" ] || { [ "${x[i]}" -lt "${y[i]}" ]; return; } + done + return 1 +} +# verify_step COMMAND...: COMMAND in the background while the step's time +# ticks, quiet, and without the lock's file. +verify_step() { + local pid rc=0 + "$@" >/dev/null 2>&1 &- & + pid=$! + while kill -0 "$pid" 2>/dev/null; do + sleep 1 + progress_tick + done + wait "$pid" || rc=$? + return "$rc" +} +# verify_fetch URL SHA256 FILE: 1 when the download fails, 2 when it isn't +# the pinned file. +verify_fetch() { + local i got="" + for i in 1 2 3; do + curl -fsSL --proto '=https' --max-time 300 --max-filesize 67108864 -o "$3" "$1" && got=1 && break + [ "$i" = 3 ] || sleep 2 + done + [ -n "$got" ] || return 1 + [ "$(sha256sum "$3" | cut -d' ' -f1)" = "$2" ] || return 2 +} +# Sets the verifier up for Pyo at URL, once the agent runs. +auto_update_on() { + local url=$1 arch want have="" dir new rc=0 channel=() + arch=$(verify_arch) + want=$(verify_pin) + if ! verify_version "$PYO_VERIFY_RELEASE" || [[ ! $want =~ ^[0-9a-f]{64}$ ]]; then + [ -x "$VERIFY_BIN" ] || dot_line yellow "Automatic updates aren't available here. They stay off on this server." + return 0 + fi + # The verifier's install doesn't take the lock: this script holds it. + if ! connect_lock_held; then + dot_line yellow "Automatic updates couldn't be set up on this server." + return 0 + fi + [[ $PYO_VERIFY_RELEASE != *-rc.* ]] || channel=(--channel rc) + progress_start "Setting up automatic updates…" + [ ! -x "$VERIFY_BIN" ] || have=$("$VERIFY_BIN" version 2>/dev/null 9>&- || true) + if [ "$have" = "$PYO_VERIFY_RELEASE" ] || verify_older "$PYO_VERIFY_RELEASE" "$have"; then + # This release's verifier, or a later one it moved to: kept. + new=$VERIFY_BIN + else + dir=$(mktemp -d) + verify_step verify_fetch "$PYO_VERIFY_RELEASES/v$PYO_VERIFY_RELEASE/pyo-verify-linux-$arch" "$want" "$dir/pyo-verify" || rc=$? + if [ "$rc" != 0 ]; then + rm -rf "$dir" + if [ "$rc" = 2 ]; then + progress_end wait "Automatic updates aren't set up. The download didn't match its checksum." + else + progress_end wait "Automatic updates aren't set up. The download failed." + fi + return 0 + fi + # Beside its place, not in /tmp, which may not run programs. + new=$(dirname "$VERIFY_BIN")/.pyo-verify.new + install -m 755 "$dir/pyo-verify" "$new" 2>/dev/null || rc=$? + rm -rf "$dir" + fi + [ "$rc" != 0 ] || verify_step "$new" install --url "$url" ${channel[@]+"${channel[@]}"} || rc=$? + [ "$new" = "$VERIFY_BIN" ] || rm -f "$new" + if [ "$rc" = 0 ]; then + progress_end ok "Set up automatic updates" + else + progress_end wait "Automatic updates couldn't be set up on this server." + fi + return 0 +} +# Removes the verifier from this server. When it can't do that itself (a +# file that doesn't run here), its timer and files go anyway. +verify_remove() { + "$VERIFY_BIN" uninstall >/dev/null 2>&1 9>&- && return 0 + systemctl disable --now pyo-verify.timer >/dev/null 2>&1 9>&- || true + rm -f "$VERIFY_UNITS/pyo-verify.timer" "$VERIFY_UNITS/pyo-verify.service" "$VERIFY_BIN" "$VERIFY_BIN.previous" "$VERIFY_BIN.new" "$(dirname "$VERIFY_BIN")/.pyo-verify.new" + systemctl daemon-reload >/dev/null 2>&1 9>&- || true + [ ! -e "$VERIFY_BIN" ] +} +auto_update_off() { + [ -e "$VERIFY_BIN" ] || return 0 + if verify_remove; then + progress_paint 32 ✓ + echo " Turned off automatic updates" + else + dot_line yellow "Automatic updates couldn't be turned off on this server." + fi + return 0 +} +# <<< pyo:auto-update +# >>> pyo:install-url (connect.sh only; join.rs tests it) +# Where this server gets Pyo's install files (the agent's manifest, the +# gateway's CRDs) and where its verifier looks for releases: INSTALL_URL. +# On a Pyo whose agents reach it at an address only they may use (Pyo +# Cloud's), Pyo's commands name its public address with --install-url. It +# is kept for later runs without it (INSTALL_URL_FILE). Elsewhere the +# agent's address serves both. The server Pyo runs on keeps nothing. +INSTALL_URL_FILE=/etc/pyo/install-url +FROM_AGENT="" +agent_secret() { k3s kubectl -n pyo-system get secret pyo-agent -o "jsonpath={.data.$1}" 2>/dev/null | base64 -d 2>/dev/null || true; } +# A refresh: Pyo's address and the token from the agent already here. +agent_settings() { + FROM_AGENT=1 + API=$(agent_secret PYO_API_URL); API="${API%/}"; TOKEN=$(agent_secret PYO_AGENT_TOKEN) + # The cluster Pyo runs on: its agent reaches Pyo inside the cluster, this + # machine at Pyo's local address. + case "$API" in http://*.svc:* | http://*.svc.cluster.local:*) API=http://127.0.0.1:8000 ;; esac + [ -n "$INSTALL_URL" ] || [ -e "$OWN_SERVER" ] || INSTALL_URL=$(install_url_kept) +} +# The address an earlier run kept, when it is one. +install_url_kept() { + local u + u=$(head -n1 "$INSTALL_URL_FILE" 2>/dev/null || true) + case "$u" in https://?* | http://?*) echo "${u%/}" ;; esac +} +# Keeps --install-url for later runs. A connect without it (--api) has one +# address for both, so a kept one goes. +install_url_keep() { + [ ! -e "$OWN_SERVER" ] || return 0 + if [ -n "$INSTALL_URL" ]; then + { mkdir -p "$(dirname "$INSTALL_URL_FILE")" && echo "$INSTALL_URL" > "$INSTALL_URL_FILE"; } 2>/dev/null || true + elif [ -z "$FROM_AGENT" ]; then + rm -f "$INSTALL_URL_FILE" 2>/dev/null || true + fi +} +# An http:// address with its tailnet name as tailnet_hostport has it. +tailnet_url() { + case "$1" in + http://*) + local hostport=${1#http://} + hostport=${hostport%%/*} + echo "http://$(tailnet_hostport "$hostport")${1#"http://$hostport"}" + ;; + *) echo "$1" ;; + esac +} +# <<< pyo:install-url # ── connect.sh --uninstall ────────────────────────────────────────────────── # Deletes only what Pyo made, found by its names and labels: the agent @@ -367,8 +595,14 @@ uninstall() { done < <(kc get pv -o jsonpath='{range .items[*]}{.metadata.name}|{.spec.claimRef.namespace}|{.spec.claimRef.name}|{.spec.persistentVolumeReclaimPolicy}|{.spec.local.path}{.spec.hostPath.path}|{.spec.nodeAffinity.required.nodeSelectorTerms[0].matchExpressions[0].values[0]}{"\n"}{end}' 2>/dev/null || true) fi + # Automatic updates on this server (the verifier), when it's this server + # being cleaned up. + local verify_here="" + [ "${KC[0]}" != k3s ] || [ ! -e "$VERIFY_BIN" ] || verify_here=1 + echo "This removes Pyo from the cluster at ${server:-?}:" echo " - the Pyo agent, its roles and admission policy (namespace pyo-system)" + [ -z "$verify_here" ] || echo " - automatic updates on this server" [ -z "$pyo_here" ] || echo " - Pyo itself, with its own database, registry and backup store (pyo-system)" has namespace pyo-gateway && echo " - Pyo Gateway (namespace pyo-gateway${gateway_chart:+, Envoy Gateway})" for line in "${bundles[@]}"; do @@ -422,7 +656,18 @@ uninstall() { [ "$policy" = Retain ] || act patch pv "$pv" --type=merge -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}' >/dev/null done - # 1. The agent, so it stops putting things back; its admission policy. + # 1. Automatic updates on this server, between the verifier's runs. Then + # the agent, so it stops putting things back; its admission policy. + if [ -n "$verify_here" ]; then + if [ -n "$DRY_RUN" ]; then + echo " would remove automatic updates from this server" >&4 + else + echo "Removing automatic updates…" + connect_lock + verify_remove || echo "Automatic updates couldn't be removed from this server." >&2 + fi + fi + [ "${KC[0]}" != k3s ] || [ -n "$DRY_RUN" ] || rm -f "$AUTO_UPDATE_FILE" "$INSTALL_URL_FILE" echo "Stopping the Pyo agent…" act -n pyo-system delete deployment pyo-agent --ignore-not-found --wait=true --timeout=120s >/dev/null act delete validatingadmissionpolicybinding,validatingadmissionpolicy -l app.kubernetes.io/part-of=pyo-agent --ignore-not-found >/dev/null 2>&1 || true @@ -546,14 +791,11 @@ if [ -n "$UNINSTALL" ]; then uninstall exit 0 fi +[ -n "$TAILNET_ONLY" ] || connect_lock # Without them, on a cluster that's already connected: bring its agent's # install up to date with Pyo (Pyo shows this command when it's older). if [ -z "$TAILNET_ONLY" ] && [ -z "$API" ] && [ -z "$TOKEN" ] && command -v k3s >/dev/null; then - secret() { k3s kubectl -n pyo-system get secret pyo-agent -o "jsonpath={.data.$1}" 2>/dev/null | base64 -d 2>/dev/null || true; } - API=$(secret PYO_API_URL); API="${API%/}"; TOKEN=$(secret PYO_AGENT_TOKEN) - # The cluster Pyo runs on: its agent reaches Pyo inside the cluster, this - # machine at Pyo's local address. - case "$API" in http://*.svc:* | http://*.svc.cluster.local:*) API=http://127.0.0.1:8000 ;; esac + agent_settings [ -z "$API" ] || echo "Updating this cluster's Pyo agent." fi [ -n "$TAILNET_ONLY" ] || { [ -n "$API" ] && [ -n "$TOKEN" ]; } || { echo "Usage: connect.sh --api URL --token TOKEN [--tailscale-key KEY] [--registry HOST:PORT --registry-token TOKEN | --local-registry]" >&2; exit 2; } @@ -589,6 +831,7 @@ api_ok() { return 1 } [ -n "$TAILNET_ONLY" ] || api_ok "$API" || { echo "Pyo's address must be https:// ($API isn't on a private network or the tailnet)." >&2; exit 2; } +[ -n "$TAILNET_ONLY" ] || [ -z "$INSTALL_URL" ] || api_ok "$INSTALL_URL" || { echo "Pyo's address must be https:// ($INSTALL_URL isn't on a private network or the tailnet)." >&2; exit 2; } [ "$(id -u)" = 0 ] || { echo "Run it as root (sudo)." >&2; exit 1; } [ "$(uname -s)" = Linux ] || { echo "Pyo clusters run on Linux, and this is $(uname -s)." >&2; exit 1; } case "$(uname -m)" in @@ -677,7 +920,8 @@ k3s_install() { # sets aside memory for k3s and the system (kube-reserved and # system-reserved, in a k3s config drop-in), so the scheduler only hands # containers what's left: 256 MiB under 1.5 GB, 512 MiB under 3.5 GB, -# 768 MiB under 8 GB, 1 GiB from there. +# 768 MiB under 8 GB, 1 GiB from there. The same drop-in holds when +# kubelet frees disk space (disk_settings in the helper). # K3S_UNIT: k3s's systemd unit, k3s (a server) unless the script sets # k3s-agent first (a server joined to a cluster). K3S_UNIT=${K3S_UNIT:-k3s} @@ -690,7 +934,7 @@ small_machine() { mkdir -p "/etc/systemd/system/$K3S_UNIT.service.d" cat > /usr/local/lib/pyo-memory.sh <<'MEMORY' #!/bin/sh -# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's reservations and compressed +# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's settings and compressed # swap (zram), from this machine's memory at every boot. mem=$(awk '/^MemTotal:/ { print int($2 / 1024) }' "${PYO_MEMINFO:-/proc/meminfo}") # k3s's soft memory limit in MiB: 40% of the memory, at least 768 MiB @@ -715,6 +959,19 @@ reserved() { echo "768 256" fi } +# When kubelet frees disk space, at any size. Under 5% free it deletes +# unused images, then evicts pods, and the server counts as short of disk +# (DiskPressure) until it has 1 GiB more than that. k3s's own 10% more +# kept a server whose disk was filled by something else short of disk +# for hours, evicting nearly every pod for space they didn't hold. +# Unused images go from 85% used down to 75%, well before any of that. +# eviction-hard replaces k3s's whole list, which has these two only: no +# memory or inode limits (the reservations above leave the memory room). +disk_settings() { + printf ' - "%s"\n' 'eviction-hard=imagefs.available<5%,nodefs.available<5%' \ + 'eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi' \ + 'image-gc-high-threshold=85' 'image-gc-low-threshold=75' +} case "$1" in k3s-env) # For k3s's EnvironmentFile: GOMEMLIMIT under 3.5 GB, else nothing. @@ -723,17 +980,20 @@ case "$1" in fi ;; k3s-config) - # k3s's config drop-in ($2): kubelet's reservations; none (no file) - # when the memory can't be read. + # k3s's config drop-in ($2): kubelet's reservations (none when the + # memory can't be read) and its disk settings. [ -n "$2" ] || exit 2 - if [ "${mem:-0}" -gt 0 ]; then - set -- "$2" $(reserved) - mkdir -p "$(dirname "$1")" - printf '%s\n' "# Managed by Pyo: what kubelet sets aside, from this machine's memory at each start." \ - 'kubelet-arg+:' " - \"kube-reserved=memory=$2Mi\"" " - \"system-reserved=memory=$3Mi\"" > "$1.new" && mv -f "$1.new" "$1" - else - rm -f "$2" - fi + out=$2 + mkdir -p "$(dirname "$out")" + { + echo "# Managed by Pyo: kubelet's settings, from this machine's memory at each start." + echo 'kubelet-arg+:' + if [ "${mem:-0}" -gt 0 ]; then + set -- $(reserved) + printf ' - "%s"\n' "kube-reserved=memory=$1Mi" "system-reserved=memory=$2Mi" + fi + disk_settings + } > "$out.new" && mv -f "$out.new" "$out" ;; zram-start) [ "${mem:-0}" -gt 0 ] && [ "$mem" -lt 2816 ] || exit 0 @@ -967,6 +1227,11 @@ if [ -n "$TAILNET_ONLY" ]; then exit 0 fi +# Automatic updates: off now, on once the agent runs (at the end). +auto_update_choice +[ "$AUTO_UPDATE" != off ] || auto_update_off +install_url_keep + # >>> pyo:tailnet-host (the same in connect.sh, join.sh and deploy/sandbox.sh) # A tailnet machine's address, from the MagicDNS name Pyo's commands give # ("..ts.net"): its IPv4 from Tailscale's own list of the @@ -1084,12 +1349,8 @@ web_ports_line() { # Pyo by its tailnet name, now that this machine is on the tailnet: dialled # at its IP, which is also the address the agent is given (pods needn't # resolve MagicDNS names). Its registry door the same way. -case "$API" in - http://*) - api_hostport=${API#http://}; api_hostport=${api_hostport%%/*} - API="http://$(tailnet_hostport "$api_hostport")${API#"http://$api_hostport"}" - ;; -esac +API=$(tailnet_url "$API") +INSTALL_URL=$(tailnet_url "${INSTALL_URL:-$API}") [ -z "$REGISTRY" ] || REGISTRY=$(tailnet_hostport "$REGISTRY") # Ports 80 and 443 already in use here (k3s's Traefik, nginx…), on a first @@ -1104,15 +1365,21 @@ fi # Pyo answers, and knows this token, before anything is installed. MANIFEST=$(mktemp) CRDS=$(mktemp) K3S_DIR=$(mktemp -d) trap 'rm -rf "$MANIFEST" "$CRDS" "$K3S_DIR"' EXIT -code=$(curl -sS -o "$MANIFEST" -w '%{http_code}' --max-time 30 "$API/install/agent.yaml?token=$TOKEN$WEB_QUERY" || true) +# >>> pyo:agent-manifest (connect.sh only; join.rs tests it) +code=$(curl -sS -o "$MANIFEST" -w '%{http_code}' --max-time 30 "$INSTALL_URL/install/agent.yaml?token=$TOKEN$WEB_QUERY" || true) case "$code" in 200) ;; - 404) echo "Pyo at $API doesn't know this token. Was the cluster removed, or the token rotated? Copy a fresh command from Pyo." >&2; exit 1 ;; + 404) echo "Pyo at $INSTALL_URL doesn't know this token. Was the cluster removed, or the token rotated? Copy a fresh command from Pyo." >&2; exit 1 ;; 409) echo "This command was used already. Get a new one in Pyo: open the cluster and show its install command." >&2; exit 1 ;; 410) echo "This command expired. Get a new one in Pyo: open the cluster and show its install command." >&2; exit 1 ;; - 000) echo "Can't reach Pyo at $API from this machine. Is it on the same network (or tailnet), and is port ${API##*:} open?" >&2; exit 1 ;; - *) echo "Pyo at $API answered $code for the agent manifest." >&2; exit 1 ;; + 000) echo "Can't reach Pyo at $INSTALL_URL from this machine. Is it on the same network (or tailnet), and is port ${INSTALL_URL##*:} open?" >&2; exit 1 ;; + *) + echo "Pyo at $INSTALL_URL answered $code for the agent manifest." >&2 + [ -z "$FROM_AGENT" ] || echo "Copy the command from Pyo again and run that." >&2 + exit 1 + ;; esac +# <<< pyo:agent-manifest # Firewall: web traffic from anywhere (unless the sites here have 80 and # 443), cluster traffic over the tailnet. @@ -1373,8 +1640,8 @@ gateway_crds() { # Envoy Gateway already running without its CRDs: restart it once they're in. k3s kubectl get "$crd/backends.gateway.envoyproxy.io" >/dev/null 2>&1 || restart=1 for i in 1 2 3 4; do - curl -fsS --max-time 60 -o "$CRDS" "$API/install/gateway-crds.yaml$q" && break - [ "$i" = 4 ] && { echo "Couldn't get the gateway's CRDs from Pyo at $API." >&2; exit 1; } + curl -fsS --max-time 60 -o "$CRDS" "$INSTALL_URL/install/gateway-crds.yaml$q" && break + [ "$i" = 4 ] && { echo "Couldn't get the gateway's CRDs from Pyo at $INSTALL_URL." >&2; exit 1; } sleep 2 done k3s kubectl apply --server-side --force-conflicts --field-manager=pyo -f "$CRDS" >/dev/null || { echo "Couldn't install the gateway's CRDs (see above)." >&2; exit 1; } @@ -1548,5 +1815,6 @@ if ! quietly "Starting the Pyo agent…" k3s kubectl -n pyo-system rollout statu echo "The Pyo agent didn't start. Run the same command again in a minute." >&2 exit 1 fi +[ "$AUTO_UPDATE" != on ] || auto_update_on "$INSTALL_URL" [ -z "$WEB_QUERY" ] || dot_line yellow "$(web_ports_line)" ok_line "Connected $(hostname). It shows up in Pyo in a few seconds." diff --git a/crates/pyo-api/assets/join.sh b/crates/pyo-api/assets/join.sh index a4bbce7a..bf91307e 100644 --- a/crates/pyo-api/assets/join.sh +++ b/crates/pyo-api/assets/join.sh @@ -330,7 +330,8 @@ K3S_UNIT=k3s-agent # sets aside memory for k3s and the system (kube-reserved and # system-reserved, in a k3s config drop-in), so the scheduler only hands # containers what's left: 256 MiB under 1.5 GB, 512 MiB under 3.5 GB, -# 768 MiB under 8 GB, 1 GiB from there. +# 768 MiB under 8 GB, 1 GiB from there. The same drop-in holds when +# kubelet frees disk space (disk_settings in the helper). # K3S_UNIT: k3s's systemd unit, k3s (a server) unless the script sets # k3s-agent first (a server joined to a cluster). K3S_UNIT=${K3S_UNIT:-k3s} @@ -343,7 +344,7 @@ small_machine() { mkdir -p "/etc/systemd/system/$K3S_UNIT.service.d" cat > /usr/local/lib/pyo-memory.sh <<'MEMORY' #!/bin/sh -# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's reservations and compressed +# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's settings and compressed # swap (zram), from this machine's memory at every boot. mem=$(awk '/^MemTotal:/ { print int($2 / 1024) }' "${PYO_MEMINFO:-/proc/meminfo}") # k3s's soft memory limit in MiB: 40% of the memory, at least 768 MiB @@ -368,6 +369,19 @@ reserved() { echo "768 256" fi } +# When kubelet frees disk space, at any size. Under 5% free it deletes +# unused images, then evicts pods, and the server counts as short of disk +# (DiskPressure) until it has 1 GiB more than that. k3s's own 10% more +# kept a server whose disk was filled by something else short of disk +# for hours, evicting nearly every pod for space they didn't hold. +# Unused images go from 85% used down to 75%, well before any of that. +# eviction-hard replaces k3s's whole list, which has these two only: no +# memory or inode limits (the reservations above leave the memory room). +disk_settings() { + printf ' - "%s"\n' 'eviction-hard=imagefs.available<5%,nodefs.available<5%' \ + 'eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi' \ + 'image-gc-high-threshold=85' 'image-gc-low-threshold=75' +} case "$1" in k3s-env) # For k3s's EnvironmentFile: GOMEMLIMIT under 3.5 GB, else nothing. @@ -376,17 +390,20 @@ case "$1" in fi ;; k3s-config) - # k3s's config drop-in ($2): kubelet's reservations; none (no file) - # when the memory can't be read. + # k3s's config drop-in ($2): kubelet's reservations (none when the + # memory can't be read) and its disk settings. [ -n "$2" ] || exit 2 - if [ "${mem:-0}" -gt 0 ]; then - set -- "$2" $(reserved) - mkdir -p "$(dirname "$1")" - printf '%s\n' "# Managed by Pyo: what kubelet sets aside, from this machine's memory at each start." \ - 'kubelet-arg+:' " - \"kube-reserved=memory=$2Mi\"" " - \"system-reserved=memory=$3Mi\"" > "$1.new" && mv -f "$1.new" "$1" - else - rm -f "$2" - fi + out=$2 + mkdir -p "$(dirname "$out")" + { + echo "# Managed by Pyo: kubelet's settings, from this machine's memory at each start." + echo 'kubelet-arg+:' + if [ "${mem:-0}" -gt 0 ]; then + set -- $(reserved) + printf ' - "%s"\n' "kube-reserved=memory=$1Mi" "system-reserved=memory=$2Mi" + fi + disk_settings + } > "$out.new" && mv -f "$out.new" "$out" ;; zram-start) [ "${mem:-0}" -gt 0 ] && [ "$mem" -lt 2816 ] || exit 0 diff --git a/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql b/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql new file mode 100644 index 00000000..195b78eb --- /dev/null +++ b/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql @@ -0,0 +1,160 @@ +-- pyo:contract since=v0.5.5 dns_records_status_check only widens (adds switching and reverting), so every status v0.5.5 writes (created, exists, conflict, failed) still fits +-- Cloudflare Tunnel (cloudflare/tunnel.rs, docs/cloudflare-tunnel.md). + +-- The cluster's traffic: 'public' (ports 80 and 443 on its servers), +-- 'tailscale' (only the tailnet, or inside the cluster without one) or +-- 'tunnel' (websites through Cloudflare Tunnel, no ports 80 and 443). +ALTER TABLE pyo.clusters ADD COLUMN traffic text NOT NULL DEFAULT 'public' + CHECK (traffic IN ('public', 'tailscale', 'tunnel')); +UPDATE pyo.clusters SET traffic = CASE WHEN public_traffic THEN 'public' ELSE 'tailscale' END; +-- public_traffic stays a plain column while v0.5.5 may still run: it reads +-- it and writes it (setClusterPublicTraffic, install::web_ports_busy). This +-- trigger keeps the two in step, so every reader of public_traffic follows +-- traffic, and v0.5.5 writing public_traffic moves traffic with it. A later +-- release makes it a generated column (RELEASING.md, Pending contracts). +CREATE FUNCTION pyo.clusters_traffic_sync() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.traffic = 'public' AND NOT NEW.public_traffic THEN + NEW.traffic := 'tailscale'; + END IF; + ELSIF NEW.traffic IS DISTINCT FROM OLD.traffic THEN + NULL; + ELSIF NEW.public_traffic IS DISTINCT FROM OLD.public_traffic THEN + NEW.traffic := CASE WHEN NEW.public_traffic THEN 'public' ELSE 'tailscale' END; + END IF; + NEW.public_traffic := NEW.traffic = 'public'; + RETURN NEW; +END +$$; +CREATE TRIGGER clusters_traffic_sync BEFORE INSERT OR UPDATE OF traffic, public_traffic + ON pyo.clusters FOR EACH ROW EXECUTE FUNCTION pyo.clusters_traffic_sync(); + +-- A cluster's Cloudflare Tunnel. Nothing secret: the tunnel token is read +-- from Cloudflare when the agent needs it, and the Origin CA key sits +-- sealed with the team's certificates. +CREATE TABLE pyo.cluster_tunnels ( + cluster_id text PRIMARY KEY REFERENCES pyo.clusters (id) ON DELETE CASCADE, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + account_id text NOT NULL, + account_name text NOT NULL DEFAULT '', + -- Cloudflare's id, once made, and its name there. + tunnel_id text, + tunnel_name text NOT NULL, + state text NOT NULL DEFAULT 'creating' + CHECK (state IN ('creating', 'ready', 'failed', 'removing')), + error text, + -- Its zone apex: '*.' gets a wildcard record and route. + default_domain text, + default_zone_id text, + -- Pyo's wildcard record, when it made it. + default_record_id text, + -- Public TCP and UDP ports while the cluster is in tunnel mode. + ports_public boolean NOT NULL DEFAULT true, + -- The routes Pyo last PUT (a hash), and Cloudflare's version of them. + config_hash text NOT NULL DEFAULT '', + config_version integer, + -- The Origin CA certificate the tunnel's domains use. + certificate_id text REFERENCES pyo.certificates (id) ON DELETE SET NULL, + -- Cloudflare's id for it, and the one it replaced, revoked once + -- cf_certificate_old_at has passed. + cf_certificate_id text, + cf_certificate_old text, + cf_certificate_old_at timestamptz, + -- Rotate was asked for: a new tunnel secret and a new certificate. + rotate boolean NOT NULL DEFAULT false, + -- Restore the records the tunnel's domains replaced while it's removed. + restore_records boolean NOT NULL DEFAULT true, + -- Last reads: Cloudflare's view and the agent's. + cf_status jsonb NOT NULL DEFAULT '{}', + agent_status jsonb NOT NULL DEFAULT '{}', + -- Since when Cloudflare says it's down (for the alert after 5 minutes), + -- and whether that alert went out. + down_since timestamptz, + down_alerted boolean NOT NULL DEFAULT false, + -- When the token last went to the agent (not more than every 5 minutes). + token_sent_at timestamptz, + -- When Cloudflare's view was last read. + checked_at timestamptz, + -- Cloudflare asked to wait (429) until then. + backoff_until timestamptz, + created_by text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX cluster_tunnels_team_idx ON pyo.cluster_tunnels (team_id); +ALTER TABLE pyo.cluster_tunnels ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.cluster_tunnels TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope())); + +-- A domain through the tunnel: its record is a proxied CNAME to the +-- tunnel. `previous` keeps the records it replaced, for Switch back. +-- 'switching' and 'reverting' are the tunnel loop's to finish. +ALTER TABLE pyo.dns_records + ADD COLUMN via text NOT NULL DEFAULT 'direct' CHECK (via IN ('direct', 'tunnel')), + ADD COLUMN previous jsonb NOT NULL DEFAULT '[]', + -- The switch may replace records in the way (an owner or admin said so). + ADD COLUMN replace boolean NOT NULL DEFAULT false, + -- Switching back: put the kept records back (else an A record to the + -- cluster's public IP on a cluster with public ports, else nothing). + ADD COLUMN restore boolean NOT NULL DEFAULT true, + -- The routes sync the switch waits for on the agent (pyo.commands). + ADD COLUMN routes_command text; +ALTER TABLE pyo.dns_records DROP CONSTRAINT dns_records_status_check; +ALTER TABLE pyo.dns_records ADD CONSTRAINT dns_records_status_check + CHECK (status IN ('created', 'exists', 'conflict', 'failed', 'switching', 'reverting')); +CREATE INDEX dns_records_tunnel_idx ON pyo.dns_records (service_id) + WHERE status IN ('switching', 'reverting'); + +-- What's left at Cloudflare once its row is gone: a tunnel record of a +-- deleted service, or the tunnel of a deleted cluster. The tunnel loop +-- deletes them (only Pyo's own records) with the team's token. +CREATE TABLE pyo.tunnel_leftovers ( + id bigserial PRIMARY KEY, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + -- 'record' (zone_id, record_id, hostname) or 'tunnel' (account_id, + -- tunnel_id, cf_certificates, and its wildcard record as a record). + kind text NOT NULL CHECK (kind IN ('record', 'tunnel')), + zone_id text, + record_id text, + hostname text, + account_id text, + tunnel_id text, + cf_certificates text[] NOT NULL DEFAULT '{}', + error text, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX tunnel_leftovers_team_idx ON pyo.tunnel_leftovers (team_id); +ALTER TABLE pyo.tunnel_leftovers ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.tunnel_leftovers TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope())); + +-- Kept when its team is still there (a team deleted takes its token too). +CREATE FUNCTION pyo.keep_tunnel_record() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.via = 'tunnel' AND OLD.record_id IS NOT NULL + AND EXISTS (SELECT 1 FROM pyo.teams WHERE id = OLD.team_id) THEN + INSERT INTO pyo.tunnel_leftovers (team_id, kind, zone_id, record_id, hostname) + VALUES (OLD.team_id, 'record', OLD.zone_id, OLD.record_id, OLD.hostname); + END IF; + RETURN OLD; +END +$$; +CREATE TRIGGER dns_records_tunnel_leftover BEFORE DELETE ON pyo.dns_records + FOR EACH ROW EXECUTE FUNCTION pyo.keep_tunnel_record(); + +CREATE FUNCTION pyo.keep_tunnel() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF (OLD.tunnel_id IS NOT NULL OR OLD.cf_certificate_id IS NOT NULL OR OLD.default_record_id IS NOT NULL) + AND EXISTS (SELECT 1 FROM pyo.teams WHERE id = OLD.team_id) THEN + INSERT INTO pyo.tunnel_leftovers (team_id, kind, zone_id, record_id, hostname, account_id, tunnel_id, cf_certificates) + VALUES (OLD.team_id, 'tunnel', OLD.default_zone_id, OLD.default_record_id, '*.' || OLD.default_domain, + OLD.account_id, OLD.tunnel_id, array_remove(ARRAY[OLD.cf_certificate_id, OLD.cf_certificate_old], NULL)); + END IF; + RETURN OLD; +END +$$; +CREATE TRIGGER cluster_tunnels_leftover BEFORE DELETE ON pyo.cluster_tunnels + FOR EACH ROW EXECUTE FUNCTION pyo.keep_tunnel(); diff --git a/crates/pyo-api/migrations/0041_bundle_images.sql b/crates/pyo-api/migrations/0041_bundle_images.sql new file mode 100644 index 00000000..0a66b487 --- /dev/null +++ b/crates/pyo-api/migrations/0041_bundle_images.sql @@ -0,0 +1,5 @@ +-- The images a cluster's databases run, as its databases system was last +-- applied (pyo-proto's `database_images`): compared with a newer one's, so +-- Pyo knows which databases restart for an update. NULL until the next one +-- is applied. +ALTER TABLE pyo.cluster_bundles ADD COLUMN images jsonb; diff --git a/crates/pyo-api/src/admin_sign_in.rs b/crates/pyo-api/src/admin_sign_in.rs new file mode 100644 index 00000000..ed218983 --- /dev/null +++ b/crates/pyo-api/src/admin_sign_in.rs @@ -0,0 +1,574 @@ +//! Where the installation's admins may sign in from (Settings › Security). +//! +//! An admin has powers over the whole installation, and on Pyo Cloud its +//! staff sign in on the same public page as everyone else. So the admin +//! can limit where admin accounts sign in: from the tailnet, and from +//! addresses or ranges (IPv4 and IPv6). Neither, the default: anywhere. +//! It's kept in `pyo.settings` as 'admin_sign_in'. +//! +//! From anywhere else, an admin account +//! - can't sign in, on any path: a password, a two-factor code, a passkey, +//! a sign-in link, `pyo login`. The answer is the one a wrong password, +//! code or link gets, so it tells nothing of the account or the limit. +//! The account's audit log says so, and its email when Pyo sends email. +//! - has no browser session: its requests are unauthorized, as if signed +//! out. The session stays, for when it's back where it may be. A stolen +//! cookie works nowhere else. +//! - acts as a member only through API keys and assistants (OAuth): it +//! keeps its teams but loses its admin powers. Keys never change the +//! installation anyway (ops.rs `key_access_for`), and scripts and CI run +//! from anywhere. +//! +//! Nobody else is ever affected. +//! +//! Where a request comes from is its visitor (ratelimit.rs `visitor_of`): +//! the TCP peer, unless that's a trusted proxy (Pyo's Gateway, cloudflared, +//! `PYO_TRUSTED_PROXIES`), whose headers alone count. It's on the tailnet +//! when that address is Tailscale's and it asked for a tailnet name +//! (`*.ts.net`): only the tailnet Gateway serves those, and it admits +//! Tailscale's addresses and the servers only. A public Gateway has no +//! route for them, so an address in Tailscale's range that isn't one (a +//! carrier's shared NAT) never counts. pyo-forward's :8000 shows up as a +//! server's own end of the pod network: it also admits local and private +//! peers, so it's never the tailnet. +//! +//! Locked out: a sign-in link from `pyo-reset-login` on the server turns +//! the limit off (recovery.rs). `PYO_ADMIN_SIGNIN_ANYWHERE=1` on Pyo's +//! deployment ignores it while it's set, for Pyo Cloud, which has no +//! server to run that on. + +use std::{convert::Infallible, net::IpAddr}; + +use axum::{ + extract::{ConnectInfo, FromRequestParts}, + http::{HeaderMap, header, request::Parts}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sqlx::PgConnection; + +use crate::{ + AppState, + auth::User, + error::{ApiError, ApiResult}, + ratelimit::Cidr, +}; + +/// The most addresses and ranges the limit takes. +pub const MAX_ADDRESSES: usize = 100; + +/// The env var that ignores the limit while it's set ("1" or "true"). +pub const ANYWHERE_ENV: &str = "PYO_ADMIN_SIGNIN_ANYWHERE"; + +/// Where admin accounts may sign in from. Neither: anywhere. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Limit { + /// From the tailnet. + #[serde(default)] + pub tailnet: bool, + /// From these addresses and ranges ("203.0.113.7", "2001:db8::/48"). + #[serde(default)] + pub addresses: Vec, +} + +impl Limit { + pub fn is_on(&self) -> bool { + self.tailnet || !self.addresses.is_empty() + } + + /// Whether an admin may sign in from `from`. + pub fn allows(&self, from: &Source) -> bool { + if !self.is_on() || (self.tailnet && from.tailnet) { + return true; + } + from.ip.is_some_and(|ip| { + self.addresses + .iter() + .filter_map(|a| Cidr::parse(a)) + .any(|c| c.contains(&ip)) + }) + } + + /// In words, for the activity: "the tailnet and 2 addresses". + fn summary(&self) -> String { + let n = self.addresses.len(); + let addresses = match n { + 0 => None, + 1 => Some(self.addresses[0].clone()), + n => Some(format!("{n} addresses")), + }; + match (self.tailnet, addresses) { + (true, Some(a)) => format!("the tailnet and {a}"), + (true, None) => "the tailnet".into(), + (false, Some(a)) => a, + (false, None) => "anywhere".into(), + } + } +} + +/// Where a request comes from: its visitor's address, and whether it came +/// over the tailnet. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Source { + pub ip: Option, + pub tailnet: bool, +} + +impl Source { + /// From the TCP peer and the request's headers. `authority`: the URI's, + /// for a request without a Host header (HTTP/2). + pub fn of(peer: &str, headers: &HeaderMap, authority: Option<&str>) -> Self { + Self::from_visitor( + &crate::ratelimit::visitor_of(peer, headers), + host_of(headers, authority), + ) + } + + /// From a visitor's address (already worked out from trusted proxies + /// only) and the host name it asked for. + pub fn from_visitor(visitor: &str, host: &str) -> Self { + let ip = visitor + .trim() + .trim_matches(['[', ']']) + .parse::() + .ok() + .map(|a| a.to_canonical()); + let name = host.split(':').next().unwrap_or("").trim_end_matches('.'); + let tailnet = + ip.is_some_and(|a| tailscale_address(&a)) && pyo_proto::system::is_tailnet_host(name); + Source { ip, tailnet } + } + + pub fn from_parts(parts: &Parts) -> Self { + let peer = parts + .extensions + .get::>() + .map(|c| c.0.ip().to_string()) + .unwrap_or_default(); + Self::of( + &peer, + &parts.headers, + parts.uri.authority().map(|a| a.as_str()), + ) + } + + /// The address in words. + pub fn shown(&self) -> String { + self.ip + .map(|a| a.to_string()) + .unwrap_or_else(|| "an unknown address".into()) + } +} + +impl FromRequestParts for Source { + type Rejection = Infallible; + + async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { + Ok(Source::from_parts(parts)) + } +} + +/// The host name a request asked for: its Host header, else (HTTP/2) its +/// URI's authority. +pub fn host_of<'a>(headers: &'a HeaderMap, authority: Option<&'a str>) -> &'a str { + headers + .get(header::HOST) + .and_then(|v| v.to_str().ok()) + .or(authority) + .unwrap_or("") +} + +/// One of Tailscale's addresses (100.64.0.0/10, fd7a:115c:a1e0::/48). +fn tailscale_address(ip: &IpAddr) -> bool { + pyo_proto::system::TAILNET_CIDRS + .iter() + .filter_map(|c| Cidr::parse(c)) + .any(|c| c.contains(ip)) +} + +/// Whether `PYO_ADMIN_SIGNIN_ANYWHERE` is set: the limit is ignored. +pub fn anywhere() -> bool { + static A: std::sync::OnceLock = std::sync::OnceLock::new(); + *A.get_or_init(|| { + let on = matches!( + std::env::var(ANYWHERE_ENV).as_deref().map(str::trim), + Ok("1" | "true") + ); + if on { + tracing::warn!("{ANYWHERE_ENV} is set: admins may sign in from anywhere"); + } + on + }) +} + +/// The installation's limit, as saved. +pub async fn load(db: impl sqlx::PgExecutor<'_>) -> sqlx::Result { + let v: Option = + sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'admin_sign_in'") + .fetch_optional(db) + .await?; + Ok(v.and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default()) +} + +/// Whether an admin account may act from `from`: what the limit allows, +/// or anywhere while `PYO_ADMIN_SIGNIN_ANYWHERE` is set. +pub async fn admits(db: impl sqlx::PgExecutor<'_>, from: &Source) -> sqlx::Result { + if anywhere() { + return Ok(true); + } + Ok(load(db).await?.allows(from)) +} + +/// A limit to save: each address or range checked and written plainly +/// (its network address, no /32 or /128), duplicates dropped. +pub fn checked(tailnet: bool, addresses: &[String]) -> ApiResult { + let mut out: Vec = vec![]; + for a in addresses.iter().map(|a| a.trim()).filter(|a| !a.is_empty()) { + let well_formed = match a.split_once('/') { + Some((_, len)) => !len.is_empty() && len.bytes().all(|b| b.is_ascii_digit()), + None => true, + }; + let cidr = Cidr::parse(a).filter(|_| well_formed).ok_or_else(|| { + ApiError::bad_request(format!("{a} isn't an IP address or range.")) + })?; + let plain = cidr.to_string(); + if !out.contains(&plain) { + out.push(plain); + } + } + if out.len() > MAX_ADDRESSES { + return Err(ApiError::bad_request(format!( + "Add up to {MAX_ADDRESSES} addresses." + ))); + } + Ok(Limit { + tailnet, + addresses: out, + }) +} + +/// A new limit must keep letting in the request that saves it, so its +/// admin can't lock themselves out. +pub fn keeps(limit: &Limit, here: &Source) -> ApiResult<()> { + if limit.allows(here) { + return Ok(()); + } + Err(ApiError::bad_request(match here.ip { + Some(ip) => format!("This would lock you out. Add your address {ip} first."), + None => "This would lock you out. Pyo can't tell your address.".to_owned(), + })) +} + +/// Saves the limit (off when it allows anywhere). Returns what it was. +pub async fn save(conn: &mut PgConnection, limit: &Limit) -> sqlx::Result { + let before = load(&mut *conn).await?; + if limit.is_on() { + sqlx::query( + "INSERT INTO pyo.settings (key, value) VALUES ('admin_sign_in', $1) + ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()", + ) + .bind(json!(limit)) + .execute(&mut *conn) + .await?; + } else { + sqlx::query("DELETE FROM pyo.settings WHERE key = 'admin_sign_in'") + .execute(&mut *conn) + .await?; + } + Ok(before) +} + +/// What the activity says of a change. +pub fn change_title(limit: &Limit) -> String { + if limit.is_on() { + format!("Limited admin sign-in to {}", limit.summary()) + } else { + "Let admins sign in from anywhere".into() + } +} + +/// Turns the limit off (a sign-in link made on the server). Whether it +/// was on. +pub async fn turn_off(conn: &mut PgConnection) -> sqlx::Result { + Ok(save(conn, &Limit::default()).await?.is_on()) +} + +/// Whether `user` may sign in from `from` (`how`: "with a password"). +/// Everyone may, but the installation's admins only from where the limit +/// allows. A refusal goes to the account's audit log, and its email. +/// `user.is_admin` is the account's own (`pyo.users.is_admin`). +pub async fn sign_in_allowed( + state: &AppState, + user: &User, + from: &Source, + how: &str, +) -> ApiResult { + if !user.is_admin || admits(&state.db, from).await? { + return Ok(true); + } + refused(state, user, from, how).await; + Ok(false) +} + +/// A refused admin sign-in, in the audit log and the account's email. +pub async fn refused(state: &AppState, user: &User, from: &Source, how: &str) { + tracing::warn!(user = %user.id, ip = %from.shown(), how, "admin sign-in refused: not from an allowed address"); + crate::audit::account_event( + &state.db, + &user.id, + &crate::audit::Who::person(user), + crate::audit::Entry { + action: "auth.sign_in_refused", + title: &format!("Sign-in {how} refused outside the allowed addresses"), + target: json!({}), + failed: true, + }, + ) + .await; + let (s, to, ip) = (state.clone(), user.email.clone(), from.shown()); + tokio::spawn(async move { + crate::twofactor::mail_user(&s, &to, "/security", |link| { + crate::mail::sign_in_refused(&ip, link) + }) + .await; + }); +} + +/// For the dashboard (its admin): the limit, where this request comes +/// from, whether the tailnet can be chosen, and whether the limit is +/// ignored (`PYO_ADMIN_SIGNIN_ANYWHERE`). +pub async fn snapshot(db: &sqlx::PgPool, here: &Source) -> sqlx::Result { + let limit = load(db).await?; + Ok(json!({ + "tailnet": limit.tailnet, + "addresses": limit.addresses, + "here": here.ip.map(|a| a.to_string()), + "hereTailnet": here.tailnet, + "tailnetAvailable": crate::web::addresses().tailnet.is_some() || here.tailnet, + "anywhere": anywhere(), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::SocketAddr; + + fn src(ip: &str, tailnet: bool) -> Source { + Source { + ip: Some(ip.parse().unwrap()), + tailnet, + } + } + + fn limit(tailnet: bool, addresses: &[&str]) -> Limit { + checked( + tailnet, + &addresses.iter().map(|a| a.to_string()).collect::>(), + ) + .unwrap() + } + + #[test] + fn off_by_default_allows_anywhere() { + let l = Limit::default(); + assert!(!l.is_on()); + assert!(l.allows(&src("203.0.113.7", false))); + assert!(l.allows(&Source::default())); + let saved: Limit = serde_json::from_value(json!({})).unwrap(); + assert_eq!(saved, l); + } + + #[test] + fn addresses_and_ranges_v4_and_v6() { + let l = limit(false, &["203.0.113.7", "198.51.100.0/24", "2001:db8:42::/48"]); + assert!(l.allows(&src("203.0.113.7", false))); + assert!(!l.allows(&src("203.0.113.8", false))); + assert!(l.allows(&src("198.51.100.250", false))); + assert!(!l.allows(&src("198.51.101.1", false))); + assert!(l.allows(&src("2001:db8:42:1::9", false))); + assert!(!l.allows(&src("2001:db8:43::9", false))); + // IPv4 written as IPv6 is the same address. + let mapped = Source { + ip: Some("::ffff:203.0.113.7".parse::().unwrap().to_canonical()), + tailnet: false, + }; + assert!(l.allows(&mapped)); + // No address: nothing to match. + assert!(!l.allows(&Source::default())); + // The tailnet isn't on the list. + assert!(!l.allows(&src("100.101.102.103", true))); + } + + #[test] + fn tailnet_only() { + let l = limit(true, &[]); + assert!(l.is_on()); + assert!(l.allows(&src("100.101.102.103", true))); + // A Tailscale address that didn't come over the tailnet. + assert!(!l.allows(&src("100.101.102.103", false))); + assert!(!l.allows(&src("203.0.113.7", false))); + // Both: either will do. + let both = limit(true, &["203.0.113.7"]); + assert!(both.allows(&src("100.101.102.103", true))); + assert!(both.allows(&src("203.0.113.7", false))); + assert!(!both.allows(&src("203.0.113.9", false))); + } + + #[test] + fn saved_plainly_and_checked() { + let l = limit( + false, + &[" 203.0.113.7/32 ", "198.51.100.9/24", "2001:DB8::1/128", "", "203.0.113.7"], + ); + assert_eq!(l.addresses, ["203.0.113.7", "198.51.100.0/24", "2001:db8::1"]); + for bad in ["nope", "203.0.113.7/33", "203.0.113.7/", "203.0.113.7/abc", "2001:db8::/129", "10.0.0.0/8/8"] { + let e = checked(false, &[bad.to_owned()]).unwrap_err(); + assert!(e.message.contains("isn't an IP address or range"), "{bad}: {}", e.message); + } + let many: Vec = (0..=MAX_ADDRESSES).map(|i| format!("10.0.{}.{}", i / 250, i % 250)).collect(); + assert!(checked(false, &many).is_err()); + assert!(checked(false, &many[..MAX_ADDRESSES]).is_ok()); + } + + #[test] + fn saving_never_locks_out_the_one_saving() { + let here = src("203.0.113.7", false); + assert!(keeps(&limit(false, &["203.0.113.0/24"]), &here).is_ok()); + assert!(keeps(&Limit::default(), &here).is_ok()); + let e = keeps(&limit(true, &[]), &here).unwrap_err(); + assert_eq!(e.message, "This would lock you out. Add your address 203.0.113.7 first."); + assert!(keeps(&limit(false, &["198.51.100.1"]), &here).is_err()); + assert!(keeps(&limit(true, &[]), &src("100.101.102.103", true)).is_ok()); + assert!(keeps(&limit(true, &[]), &Source::default()).is_err()); + } + + #[test] + fn titles() { + assert_eq!(change_title(&Limit::default()), "Let admins sign in from anywhere"); + assert_eq!(change_title(&limit(true, &[])), "Limited admin sign-in to the tailnet"); + assert_eq!( + change_title(&limit(true, &["203.0.113.7"])), + "Limited admin sign-in to the tailnet and 203.0.113.7" + ); + assert_eq!( + change_title(&limit(false, &["203.0.113.7", "2001:db8::/32"])), + "Limited admin sign-in to 2 addresses" + ); + } + + /// A request as Pyo gets it: its TCP peer and headers. + fn parts(peer: &str, host: &str, headers: &[(&str, &str)]) -> Parts { + let mut b = axum::http::Request::builder().uri("/api/auth/login"); + if !host.is_empty() { + b = b.header("host", host); + } + for (k, v) in headers { + b = b.header(*k, *v); + } + let mut r = b.body(()).unwrap(); + r.extensions_mut() + .insert(ConnectInfo(peer.parse::().unwrap())); + r.into_parts().0 + } + + fn source(peer: &str, host: &str, headers: &[(&str, &str)]) -> Source { + Source::from_parts(&parts(peer, host, headers)) + } + + const TS: &str = "pyo.tail1234.ts.net"; + const PUBLIC: &str = "pyo.203-0-113-1.nip.io"; + + #[test] + fn the_tailnet_through_the_tailnet_gateway() { + // The tailnet Gateway (a pod) appends the device's own address. + assert_eq!( + source("10.42.0.7:5000", TS, &[("x-forwarded-for", "100.101.102.103")]), + src("100.101.102.103", true) + ); + assert_eq!( + source("10.42.0.7:5000", TS, &[("x-forwarded-for", "fd7a:115c:a1e0::5")]), + src("fd7a:115c:a1e0::5", true) + ); + // Port and a trailing dot in the host name. + assert_eq!( + source("10.42.0.7:5000", "pyo.tail1234.ts.net.:443", &[("x-forwarded-for", "100.101.102.103")]), + src("100.101.102.103", true) + ); + // HTTP/2: no Host header, the URI's authority. + let mut r = axum::http::Request::builder() + .uri(format!("https://{TS}/api/auth/login")) + .header("x-forwarded-for", "100.101.102.103") + .body(()) + .unwrap(); + r.extensions_mut() + .insert(ConnectInfo("10.42.0.7:5000".parse::().unwrap())); + assert_eq!(Source::from_parts(&r.into_parts().0), src("100.101.102.103", true)); + } + + #[test] + fn spoofed_headers_from_an_untrusted_peer_never_count() { + // Straight from the internet, whatever it claims. + for h in [ + ("x-forwarded-for", "100.101.102.103"), + ("cf-connecting-ip", "100.101.102.103"), + ("x-real-ip", "100.101.102.103"), + ("forwarded", "for=100.101.102.103"), + ] { + assert_eq!(source("203.0.113.9:5000", TS, &[h]), src("203.0.113.9", false), "{h:?}"); + } + // A listed address, claimed. + let l = limit(false, &["198.51.100.7"]); + let s = source("203.0.113.9:5000", PUBLIC, &[("x-forwarded-for", "198.51.100.7"), ("cf-connecting-ip", "198.51.100.7")]); + assert!(!l.allows(&s)); + // Through the public Gateway: what the client wrote sits to the + // left of the address the Gateway appended. + let s = source("10.42.0.7:5000", PUBLIC, &[("x-forwarded-for", "198.51.100.7, 203.0.113.9")]); + assert_eq!(s, src("203.0.113.9", false)); + assert!(!l.allows(&s)); + // And a made-up CF-Connecting-IP from the pod network (the Gateway + // passes on what its client sent) never counts. + let s = source("10.42.0.7:5000", PUBLIC, &[("cf-connecting-ip", "198.51.100.7"), ("x-forwarded-for", "203.0.113.9")]); + assert_eq!(s, src("203.0.113.9", false)); + // A server's own end of the pod network (pyo-forward's :8000, which + // admits local and private peers too) passes on nothing, and isn't + // the tailnet even with a tailnet name. + let s = source("10.42.0.1:5000", TS, &[("x-forwarded-for", "100.101.102.103")]); + assert_eq!(s, src("10.42.0.1", false)); + } + + #[test] + fn a_tailscale_address_off_the_tailnet_isn_t_the_tailnet() { + // A carrier's shared NAT (100.64.0.0/10) on a public name. + assert_eq!( + source("10.42.0.7:5000", PUBLIC, &[("x-forwarded-for", "100.64.1.2")]), + src("100.64.1.2", false) + ); + assert_eq!(source("100.64.1.2:5000", PUBLIC, &[]), src("100.64.1.2", false)); + // A tailnet name with an address that isn't Tailscale's. + assert_eq!( + source("10.42.0.7:5000", TS, &[("x-forwarded-for", "203.0.113.9")]), + src("203.0.113.9", false) + ); + } + + /// Pyo Cloud: cloudflared, then Pyo Ops' Gateway, both pods. The + /// visitor is what Cloudflare's edge put last in X-Forwarded-For, the + /// address it also sends as CF-Connecting-IP. + #[test] + fn behind_cloudflare_s_tunnel() { + let s = source( + "10.42.1.9:5000", + "cloud.pyo.dev", + &[ + ("cf-connecting-ip", "198.51.100.20"), + ("x-forwarded-for", "6.6.6.6, 198.51.100.20, 10.42.0.33"), + ], + ); + assert_eq!(s, src("198.51.100.20", false)); + assert!(limit(false, &["198.51.100.0/24"]).allows(&s)); + assert!(!limit(false, &["6.6.6.6"]).allows(&s)); + } +} diff --git a/crates/pyo-api/src/admin_sign_in_tests.rs b/crates/pyo-api/src/admin_sign_in_tests.rs new file mode 100644 index 00000000..4d8cde81 --- /dev/null +++ b/crates/pyo-api/src/admin_sign_in_tests.rs @@ -0,0 +1,243 @@ +//! Where admins may sign in from, end to end, against a throwaway Postgres +//! (DATABASE_URL): saving the limit (never one that locks out the one +//! saving it), sign-in refused like a wrong password with an audit entry, +//! sessions as if signed out, API keys as a member, and everyone else +//! never affected. Through the real routes, as a browser and a script. + +use std::net::SocketAddr; + +use axum::{ + Router, + body::Body, + extract::ConnectInfo, + http::{Method, Request, StatusCode, header}, +}; +use serde_json::{Value, json}; +use sqlx::PgPool; +use tower::ServiceExt; + +use crate::ids::{random_string, sha256_hex}; +use crate::teamsec_tests::{Client, run_big}; + +const INSIDE: &str = "203.0.113.7"; +const OUTSIDE: &str = "192.0.2.50"; + +/// GET /api/v1/me with an API key, from `ip`. +async fn me_with_key(app: &Router, key: &str, ip: &str) -> (StatusCode, Value) { + let mut req = Request::builder() + .method(Method::GET) + .uri("/api/v1/me") + .header(header::AUTHORIZATION, format!("Bearer {key}")) + .body(Body::empty()) + .unwrap(); + req.extensions_mut().insert(ConnectInfo( + format!("{ip}:4000").parse::().unwrap(), + )); + let res = app.clone().oneshot(req).await.unwrap(); + let st = res.status(); + let bytes = axum::body::to_bytes(res.into_body(), 1 << 20) + .await + .unwrap(); + (st, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) +} + +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn admins_sign_in_only_from_where_the_limit_allows() { + run_big(async { + let db = PgPool::connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL")) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + let state = crate::sandbox::e2e::test_state(db.clone()); + let app = Router::new() + .nest("/api/auth", crate::auth::routes()) + .nest("/api/v1", crate::ops::routes()) + .layer(axum::middleware::from_fn(crate::audit::middleware)) + .with_state(state); + let run = random_string(8).to_lowercase(); + let (adm, mem, team) = ( + format!("usr_adm{run}"), + format!("usr_mem{run}"), + format!("team_acl{run}"), + ); + let email = |who: &str| format!("{who}{run}@acl.test"); + let password = "correct horse battery"; + let hash = crate::auth::hash_password(password).await.unwrap(); + for (u, n, admin) in [(&adm, "adm", true), (&mem, "mem", false)] { + sqlx::query("INSERT INTO pyo.users (id, email, name, password_hash, is_admin) VALUES ($1, $2, $3, $4, $5)") + .bind(u) + .bind(email(n)) + .bind(n) + .bind(&hash) + .bind(admin) + .execute(&db) + .await + .unwrap(); + } + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&db) + .await + .unwrap(); + for (m, u, n, role) in [("a", &adm, "adm", "owner"), ("m", &mem, "mem", "developer")] { + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $4, $5, 'active')") + .bind(format!("mem_{m}{run}")) + .bind(&team) + .bind(u) + .bind(email(n)) + .bind(role) + .execute(&db) + .await + .unwrap(); + } + let key = format!("pyo_acl{run}"); + sqlx::query("INSERT INTO pyo.api_tokens (id, user_id, name, prefix, token_hash, access) VALUES ($1, $2, 'ci', 'pyo_', $3, 'full')") + .bind(format!("tok_acl{run}")) + .bind(&adm) + .bind(sha256_hex(&key)) + .execute(&db) + .await + .unwrap(); + let client = |ip: &'static str| Client { + app: app.clone(), + cookie: None, + ip, + }; + let sign_in = |who: &'static str, ip: &'static str| { + let (mut c, e) = (client(ip), email(who)); + async move { + let (st, body) = c + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": e, "password": password })), + ) + .await; + (st, body, c) + } + }; + + // Off: the admin signs in from anywhere. + let (st, _, mut inside) = sign_in("adm", INSIDE).await; + assert_eq!(st, StatusCode::OK); + let (st, snap) = inside.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(snap["adminSignIn"]["here"], INSIDE); + assert_eq!(snap["adminSignIn"]["addresses"], json!([])); + + // A limit that leaves out the admin's own address: refused. + let (st, body) = inside + .op(json!({ "op": "saveAdminSignIn", "addresses": ["198.51.100.0/24"] })) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST); + assert_eq!( + body["error"], + format!("This would lock you out. Add your address {INSIDE} first.") + ); + let (st, body) = inside + .op(json!({ "op": "saveAdminSignIn", "tailnet": true })) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); + // One that keeps it: saved plainly. + let (st, body) = inside + .op(json!({ "op": "saveAdminSignIn", "addresses": ["203.0.113.9/24", "2001:db8::/48"] })) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(body["addresses"], json!(["203.0.113.0/24", "2001:db8::/48"])); + // A member can't change it. + let (_, _, mut member) = sign_in("mem", INSIDE).await; + let (st, _) = member + .op(json!({ "op": "saveAdminSignIn", "addresses": [] })) + .await; + assert_eq!(st, StatusCode::FORBIDDEN); + + // From outside, the right password answers as a wrong one, and the + // admin's teams see why. + let (st, refused, outside) = sign_in("adm", OUTSIDE).await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + assert!(outside.cookie.is_none()); + let mut wrong = client(OUTSIDE); + let (_, wrong_body) = wrong + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("adm"), "password": "not the password" })), + ) + .await; + assert_eq!(refused, wrong_body); + let (_, nobody) = client(OUTSIDE) + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("nobody"), "password": password })), + ) + .await; + assert_eq!(refused, nobody, "no account: the same answer"); + let refusals: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pyo.audit_events WHERE team_id = $1 AND action = 'auth.sign_in_refused' AND outcome = 'failed' AND ip = $2", + ) + .bind(&team) + .bind(OUTSIDE) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(refusals, 1); + + // The admin's session from outside: as if signed out. Inside, it + // still works. + let mut stolen = Client { + app: app.clone(), + cookie: inside.cookie.clone(), + ip: OUTSIDE, + }; + let (st, _) = stolen.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + let (st, _) = stolen.call(Method::GET, "/api/auth/me", None).await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + let (st, _) = inside.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + + // The admin's API key from outside: a member, not an admin. + let (st, me) = me_with_key(&app, &key, OUTSIDE).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(me["isAdmin"], false); + let (_, me) = me_with_key(&app, &key, INSIDE).await; + assert_eq!(me["isAdmin"], true); + + // Everyone else, from anywhere. + let (st, _, mut member_outside) = sign_in("mem", OUTSIDE).await; + assert_eq!(st, StatusCode::OK); + let (st, _) = member_outside.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + + // Off again: anywhere. + let (st, _) = inside + .op(json!({ "op": "saveAdminSignIn", "tailnet": false, "addresses": [] })) + .await; + assert_eq!(st, StatusCode::OK); + let (st, _) = stolen.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + let saved: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pyo.settings WHERE key = 'admin_sign_in')") + .fetch_one(&db) + .await + .unwrap(); + assert!(!saved); + + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + sqlx::query("DELETE FROM pyo.users WHERE id = ANY ($1)") + .bind(vec![adm.clone(), mem.clone()]) + .execute(&db) + .await + .unwrap(); + }); +} diff --git a/crates/pyo-api/src/agent.rs b/crates/pyo-api/src/agent.rs index a1b93a94..977690b4 100644 --- a/crates/pyo-api/src/agent.rs +++ b/crates/pyo-api/src/agent.rs @@ -349,6 +349,8 @@ async fn heartbeat( "wafRejected": caps.waf_rejected, // And those whose WAF policy it accepted (bundles.rs `waf_shown`). "wafActive": caps.waf_active, + // It runs a Cloudflare Tunnel connector (cloudflare/tunnel_loop.rs). + "tunnel": caps.tunnel, // Whether this agent can update Pyo and itself (updates.rs). "updates": hb.updates, // Its builders and pyo-static sign their requests (agent_auth.rs). @@ -388,6 +390,14 @@ async fn heartbeat( .execute(&mut *tx) .await?; name_from_host(&mut tx, &cluster.id, &cluster.team_id, &hb.servers).await?; + // Its Cloudflare Tunnel connector, as the agent sees it. + if let Some(t) = &hb.tunnel { + sqlx::query("UPDATE pyo.cluster_tunnels SET agent_status = $2 || jsonb_build_object('at', pyo.ms(now())) WHERE cluster_id = $1") + .bind(&cluster.id) + .bind(json!(t)) + .execute(&mut *tx) + .await?; + } // The server Pyo runs on, connecting for the first time: the team's // first builder goes there. Where every cluster keeps its own images // (Pyo Cloud), a team's first cluster to connect gets it. @@ -732,10 +742,43 @@ async fn heartbeat( let tailnet = crate::tailscale::wanted_for(&s.db, &cluster.id, same_cluster).await?; // Pyo's dashboard on the public IP, while it's open. let public_dashboard = crate::publicdash::wanted_for(&s.db, same_cluster).await?; - let reply = json!({ "ok": true, "clusterId": cluster.id, "serverLocations": server_locations, "serverTags": server_tags, "gpuPolicies": gpu_policies, "publicTraffic": public_traffic, "freeDomainAddress": free_domain_address, "projectTeams": project_teams, "observability": observability, "tailnet": tailnet, "publicDashboard": public_dashboard }); + // The Cloudflare Tunnel connector it runs, if any. + let tunnel = tunnel_wanted(&s.db, &cluster.id).await?; + // TCP and UDP ports on the servers: with public traffic, or in tunnel + // mode while the cluster keeps them. + let public_ports: bool = sqlx::query_scalar( + "SELECT c.traffic = 'public' OR (c.traffic = 'tunnel' AND coalesce(t.ports_public, true)) + FROM pyo.clusters c LEFT JOIN pyo.cluster_tunnels t ON t.cluster_id = c.id WHERE c.id = $1", + ) + .bind(&cluster.id) + .fetch_one(&s.db) + .await?; + let reply = json!({ "ok": true, "clusterId": cluster.id, "serverLocations": server_locations, "serverTags": server_tags, "gpuPolicies": gpu_policies, "publicTraffic": public_traffic, "freeDomainAddress": free_domain_address, "projectTeams": project_teams, "observability": observability, "tailnet": tailnet, "publicDashboard": public_dashboard, "tunnel": tunnel, "publicPorts": public_ports }); Ok(Json(signed_reply(&cluster.id, &headers, reply).await)) } +/// The Cloudflare Tunnel connector a cluster runs: its tunnel once +/// Cloudflare made it, none while it's removed or there's none (the agent +/// then removes what it has). Left out while the tunnel is still being +/// made. +async fn tunnel_wanted(db: &sqlx::PgPool, cluster_id: &str) -> ApiResult> { + let row: Option<(Option, String, bool)> = sqlx::query_as( + "SELECT tunnel_id, state, ports_public FROM pyo.cluster_tunnels WHERE cluster_id = $1", + ) + .bind(cluster_id) + .fetch_optional(db) + .await?; + Ok(match row { + None => Some(pyo_proto::TunnelWanted::default()), + Some((_, state, _)) if state == "removing" => Some(pyo_proto::TunnelWanted::default()), + Some((None, _, _)) => None, + Some((Some(id), _, ports_public)) => Some(pyo_proto::TunnelWanted { + tunnel_id: Some(id), + ports_public, + }), + }) +} + /// Which GPU servers are kept for GPU work. A server's own setting wins; /// by default one is, unless it's a control-plane server or the cluster has /// no other ready server for everything else (that would leave regular diff --git a/crates/pyo-api/src/alerts.rs b/crates/pyo-api/src/alerts.rs index 777160a9..5d0224fa 100644 --- a/crates/pyo-api/src/alerts.rs +++ b/crates/pyo-api/src/alerts.rs @@ -74,6 +74,9 @@ pub enum Event { BackupFailed, CertificateExpiring, CertificateFailed, + /// A cluster's Cloudflare Tunnel down for 5 minutes, and back. + TunnelDown, + TunnelUp, /// The Send test button. Test, } @@ -93,6 +96,8 @@ impl Event { match self { Event::DeployFailed => "deploy_failed", Event::ServerOffline | Event::ServerOnline => "server_offline", + // Websites unreachable, as a cluster is: the same setting. + Event::TunnelDown | Event::TunnelUp => "server_offline", Event::ServerPressure | Event::ServerPressureEnded => "server_pressure", Event::BackupFailed => "backup_failed", Event::CertificateExpiring | Event::CertificateFailed => "certificate", @@ -111,6 +116,8 @@ impl Event { Event::BackupFailed => "backup_failed", Event::CertificateExpiring => "certificate_expiring", Event::CertificateFailed => "certificate_failed", + Event::TunnelDown => "tunnel_down", + Event::TunnelUp => "tunnel_up", Event::Test => "test", } } @@ -120,6 +127,7 @@ impl Event { match self { Event::ServerOnline => Some(Event::ServerOffline), Event::ServerPressureEnded => Some(Event::ServerPressure), + Event::TunnelUp => Some(Event::TunnelDown), _ => None, } } @@ -128,7 +136,10 @@ impl Event { /// within the window after it ended is held, and sent if it still holds /// once the window is over. fn lasts(self) -> bool { - matches!(self, Event::ServerOffline | Event::ServerPressure) + matches!( + self, + Event::ServerOffline | Event::ServerPressure | Event::TunnelDown + ) } } @@ -147,6 +158,8 @@ pub fn classify(kind: &str, target: &Value) -> Option { Event::CertificateExpiring } "domain.certificate_failed" => Event::CertificateFailed, + "cluster.tunnel_down" => Event::TunnelDown, + "cluster.tunnel_up" => Event::TunnelUp, _ => return None, }) } @@ -928,6 +941,27 @@ async fn build( format!("/clusters/{name}"), ) } + Event::TunnelDown | Event::TunnelUp => { + let Some(name): Option = + sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(&target_id) + .fetch_optional(&mut **tx) + .await? + else { + return Ok(None); + }; + let title = if event == Event::TunnelDown { + format!("Cloudflare Tunnel of {name} is down") + } else { + format!("Cloudflare Tunnel of {name} is back") + }; + alert( + format!("tunnel:{target_id}"), + title, + vec![], + format!("/clusters/{name}/settings"), + ) + } Event::ServerOffline | Event::ServerOnline => { let cluster_id = s(&context["clusterId"]); let Some(cluster): Option = diff --git a/crates/pyo-api/src/audit.rs b/crates/pyo-api/src/audit.rs index a18585fa..996bed0c 100644 --- a/crates/pyo-api/src/audit.rs +++ b/crates/pyo-api/src/audit.rs @@ -120,6 +120,8 @@ impl Who { /// What a request says about itself, for its entries. struct RequestInfo { ip: String, + /// The same address, and whether it came over the tailnet. + source: crate::admin_sign_in::Source, user_agent: String, actor: Mutex>, } @@ -140,13 +142,25 @@ fn request_info(req: &Request) -> RequestInfo { .get::>() .map(|c| c.0.ip().to_string()) .unwrap_or_default(); + let ip = crate::ratelimit::visitor_of(&peer, req.headers()); + let host = + crate::admin_sign_in::host_of(req.headers(), req.uri().authority().map(|a| a.as_str())); RequestInfo { - ip: crate::ratelimit::visitor_of(&peer, req.headers()), + source: crate::admin_sign_in::Source::from_visitor(&ip, host), + ip, user_agent: user_agent(req.headers()), actor: Mutex::new(None), } } +/// Where the request being handled comes from (admin_sign_in.rs). Outside +/// a request: nowhere known. +pub fn request_source() -> crate::admin_sign_in::Source { + REQUEST + .try_with(|r| r.source.clone()) + .unwrap_or_default() +} + /// A browser's User-Agent, cut to a sane length. pub fn user_agent(headers: &axum::http::HeaderMap) -> String { headers diff --git a/crates/pyo-api/src/auth.rs b/crates/pyo-api/src/auth.rs index 27a3c889..84d730cc 100644 --- a/crates/pyo-api/src/auth.rs +++ b/crates/pyo-api/src/auth.rs @@ -165,7 +165,8 @@ impl FromRequestParts for AnySession { .get(SESSION_COOKIE) .map(|c| c.value().to_owned()) .ok_or_else(ApiError::unauthorized)?; - let user = session_user(&state.db, &token) + let from = crate::admin_sign_in::Source::from_parts(parts); + let user = session_user(&state.db, &token, &from) .await? .ok_or_else(ApiError::unauthorized)?; if parts.method != axum::http::Method::GET @@ -178,14 +179,29 @@ impl FromRequestParts for AnySession { } } +/// A session's user, and whether the account is an admin at all. +#[derive(sqlx::FromRow)] +struct SessionRow { + #[sqlx(flatten)] + user: User, + account_admin: bool, +} + /// The user of a session cookie's token, while the session lasts. In use, /// its idle limit moves on (at most once an hour, never past the absolute /// one). An admin who must set up two-factor first isn't one until then -/// (twofactor.rs). -async fn session_user(db: &sqlx::PgPool, token: &str) -> ApiResult> { +/// (twofactor.rs). An admin account's session works only from where +/// admins may sign in (admin_sign_in.rs): elsewhere it's as if signed out, +/// and it doesn't move on. +async fn session_user( + db: &sqlx::PgPool, + token: &str, + from: &crate::admin_sign_in::Source, +) -> ApiResult> { let hash = sha256_hex(token); - let user = sqlx::query_as::<_, User>( - "SELECT u.id, u.name, u.email, u.timezone, u.is_admin AND NOT pyo.needs_two_factor(u.id, $3) AS is_admin, u.must_set_up + let row = sqlx::query_as::<_, SessionRow>( + "SELECT u.id, u.name, u.email, u.timezone, u.is_admin AND NOT pyo.needs_two_factor(u.id, $3) AS is_admin, u.must_set_up, + u.is_admin AS account_admin FROM pyo.sessions s JOIN pyo.users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now() AND s.created_at > now() - make_interval(days => $2)", ) @@ -194,6 +210,10 @@ async fn session_user(db: &sqlx::PgPool, token: &str) -> ApiResult> .bind(crate::hosted()) .fetch_optional(db) .await?; + let user = match row { + Some(r) if r.account_admin && !crate::admin_sign_in::admits(db, from).await? => None, + r => r.map(|r| r.user), + }; if user.is_some() { let _ = sqlx::query( "UPDATE pyo.sessions SET expires_at = least(created_at + make_interval(days => $2), now() + make_interval(days => $3)) @@ -250,7 +270,19 @@ impl FromRequestParts for TokenUser { })?; let token = token.to_owned(); let Ok(ClientIp(ip)) = ClientIp::from_request_parts(parts, state).await; - Ok(TokenUser(key_user_from(&state.db, &token, &ip).await?)) + let mut user = key_user_from(&state.db, &token, &ip).await?; + // From where admins may not sign in, an admin's key acts as a + // member only (admin_sign_in.rs). + if user.is_admin + && !crate::admin_sign_in::admits( + &state.db, + &crate::admin_sign_in::Source::from_parts(parts), + ) + .await? + { + user.is_admin = false; + } + Ok(TokenUser(user)) } } @@ -774,6 +806,7 @@ struct LoginBody { async fn login( State(state): State, ClientIp(ip): ClientIp, + from: crate::admin_sign_in::Source, headers: HeaderMap, jar: CookieJar, Json(body): Json, @@ -826,16 +859,7 @@ async fn login( ) .await; } - return Err(ApiError::new( - StatusCode::UNAUTHORIZED, - "Wrong email or password.", - )); - } - ratelimit::reset(&state.db, &ratelimit::LOGIN_ACCOUNT, &email).await?; - ratelimit::forgive(&state.db, &ratelimit::LOGIN_IP, &ip).await?; - if crate::twofactor::enabled(&state.db, &id).await? { - let challenge = crate::twofactor::start_challenge(&state.db, &id, "password").await?; - return Ok((jar, Json(crate::twofactor::code_needed(&challenge)))); + return Err(wrong_password()); } let user = User { id, @@ -846,6 +870,17 @@ async fn login( must_set_up, key: None, }; + // An admin from where admins may not sign in: as a wrong password, and + // its slots stay taken. + if !crate::admin_sign_in::sign_in_allowed(&state, &user, &from, "with a password").await? { + return Err(wrong_password()); + } + ratelimit::reset(&state.db, &ratelimit::LOGIN_ACCOUNT, &user.email).await?; + ratelimit::forgive(&state.db, &ratelimit::LOGIN_IP, &ip).await?; + if crate::twofactor::enabled(&state.db, &user.id).await? { + let challenge = crate::twofactor::start_challenge(&state.db, &user.id, "password").await?; + return Ok((jar, Json(crate::twofactor::code_needed(&challenge)))); + } crate::audit::account_event( &state.db, &user.id, @@ -862,6 +897,10 @@ async fn login( Ok((jar, Json(json!(user)))) } +fn wrong_password() -> ApiError { + ApiError::new(StatusCode::UNAUTHORIZED, "Wrong email or password.") +} + /// Is this the account's password? The same check, and the same work, as /// signing in. pub(crate) async fn password_matches( @@ -1224,7 +1263,7 @@ mod invite_tests { let ask = |token: String| { let pool = pool.clone(); async move { - session_user(&pool, &token) + session_user(&pool, &token, &Default::default()) .await .unwrap() .map(|u| u.id) diff --git a/crates/pyo-api/src/bg.rs b/crates/pyo-api/src/bg.rs index 9aa466af..96df85dd 100644 --- a/crates/pyo-api/src/bg.rs +++ b/crates/pyo-api/src/bg.rs @@ -77,6 +77,8 @@ pub const LOCK_UPDATES: i64 = 7_007; /// A hosted Pyo's agent updates (updates.rs `hosted_agents`). pub const LOCK_AGENT_UPDATES: i64 = 7_011; pub const LOCK_TAILSCALE: i64 = 7_009; +/// The Cloudflare Tunnel loop (cloudflare/tunnel_loop.rs). +pub const LOCK_TUNNEL: i64 = 7_012; /// Not a loop's: the backup store's layout, set up by one process at a time. pub const LOCK_BACKUP_STORE: i64 = 7_008; pub const LOCK_DATABASE_IMPORTS: i64 = 7_031; @@ -266,6 +268,7 @@ mod tests { LOCK_UPDATES, LOCK_AGENT_UPDATES, LOCK_TAILSCALE, + LOCK_TUNNEL, LOCK_BACKUP_STORE, LOCK_DATABASE_IMPORTS, crate::geoip::LOCK_GEOIP, diff --git a/crates/pyo-api/src/bundles.rs b/crates/pyo-api/src/bundles.rs index 6f1f0fd3..812d96bc 100644 --- a/crates/pyo-api/src/bundles.rs +++ b/crates/pyo-api/src/bundles.rs @@ -13,7 +13,7 @@ //! there, and updated with Pyo (`sync_databases`, every heartbeat). Never //! removed. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use pyo_proto::{ Command, @@ -45,6 +45,162 @@ fn databases_bundle() -> SystemBundle { pyo_proto::bundles::databases_bundle(&pyo_proto::system::db_images_from_env()) } +/// This Pyo's databases system: its version, and the images its databases +/// run (pyo-proto's `database_images`). +fn databases_now() -> &'static (String, BTreeMap) { + static NOW: std::sync::OnceLock<(String, BTreeMap)> = + std::sync::OnceLock::new(); + NOW.get_or_init(|| { + let b = databases_bundle(); + let images = pyo_proto::bundles::database_images(&b); + (b.version, images) + }) +} + +/// A database, as far as the image it runs goes. +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct Runs { + pub id: String, + pub team_id: String, + pub cluster_id: String, + pub name: String, + pub engine: String, + pub version: String, + /// A KV database that loads modules. + pub modules: bool, +} + +/// Every database with what it runs, then `$filter`. +macro_rules! runs { + ($filter:literal) => { + concat!( + "SELECT id, team_id, cluster_id, name, engine, version, + (engine = 'valkey' AND jsonb_typeof(extensions) = 'array' AND jsonb_array_length(extensions) > 0) AS modules + FROM pyo.databases WHERE state <> 'deleting'", + $filter + ) + }; +} + +/// Those of `dbs` that restart when their databases system goes from the +/// images `applied` to `new`. `applied` is None for a databases system set +/// up before Pyo kept its images: every database then. +pub fn restarting<'a>( + dbs: &'a [Runs], + applied: Option<&BTreeMap>, + new: &BTreeMap, +) -> Vec<&'a Runs> { + dbs.iter() + .filter(|d| { + applied.is_none_or(|old| { + pyo_proto::bundles::database_restarts(&d.engine, &d.version, d.modules, old, new) + }) + }) + .collect() +} + +/// How many of the installation's databases restart when Pyo moves to a +/// release whose databases run `new` (`Release::database_images`). +pub async fn restart_count(db: &sqlx::PgPool, new: &BTreeMap) -> ApiResult { + let dbs: Vec = sqlx::query_as(runs!("")).fetch_all(db).await?; + Ok(restarting(&dbs, Some(&databases_now().1), new).len()) +} + +/// The clusters among these whose databases restart once their databases +/// system is this Pyo's: it's older there (it waits for the cluster's +/// install) and a database runs an image that changed. +pub async fn databases_restart( + db: &mut sqlx::PgConnection, + cluster_ids: &[String], +) -> ApiResult> { + let (version, new) = databases_now(); + let behind: Vec<(String, Option)> = sqlx::query_as( + "SELECT cluster_id, images FROM pyo.cluster_bundles WHERE bundle = $1 AND cluster_id = ANY($2) AND version <> $3", + ) + .bind(DATABASES_ID) + .bind(cluster_ids) + .bind(version) + .fetch_all(&mut *db) + .await?; + if behind.is_empty() { + return Ok(HashSet::new()); + } + let ids: Vec = behind.iter().map(|(c, _)| c.clone()).collect(); + let dbs: Vec = sqlx::query_as(runs!(" AND cluster_id = ANY($1)")) + .bind(&ids) + .fetch_all(&mut *db) + .await?; + Ok(behind + .into_iter() + .filter(|(c, images)| { + let here: Vec = dbs.iter().filter(|d| &d.cluster_id == c).cloned().collect(); + !restarting(&here, applied_images(images.clone()).as_ref(), new).is_empty() + }) + .map(|(c, _)| c) + .collect()) +} + +/// A row's `images` as kept. +fn applied_images(images: Option) -> Option> { + images.and_then(|v| serde_json::from_value(v).ok()) +} + +/// A database's restart for new images, in its team's activity. +fn restart_title(d: &Runs) -> String { + let kind = if d.engine == "valkey" { "KV database" } else { "database" }; + format!("Restarting the {kind} {} for an update", d.name) +} + +/// The agent applied a databases system: its databases that now run another +/// image restart, which their team's activity says (not on first setup), +/// and the row keeps the images for the next update. +async fn databases_applied( + tx: &mut Transaction<'_, Postgres>, + cluster_id: &str, + command: &Value, + first_setup: bool, +) -> ApiResult<()> { + let Ok(b) = serde_json::from_value::(command["bundle"].clone()) else { + return Ok(()); + }; + let new = pyo_proto::bundles::database_images(&b); + if !first_setup { + let applied: Option> = sqlx::query_scalar( + "SELECT images FROM pyo.cluster_bundles WHERE cluster_id = $1 AND bundle = $2", + ) + .bind(cluster_id) + .bind(DATABASES_ID) + .fetch_optional(&mut **tx) + .await?; + let applied = applied_images(applied.flatten()); + let dbs: Vec = + sqlx::query_as(runs!(" AND cluster_id = $1 ORDER BY created_at")) + .bind(cluster_id) + .fetch_all(&mut **tx) + .await?; + for d in restarting(&dbs, applied.as_ref(), &new) { + log_activity( + tx, + &d.team_id, + "pyo", + "database.restarted", + "info", + &restart_title(d), + json!({ "kind": "database", "id": d.id, "label": d.name }), + json!({ "clusterId": cluster_id }), + ) + .await?; + } + } + sqlx::query("UPDATE pyo.cluster_bundles SET images = $3 WHERE cluster_id = $1 AND bundle = $2") + .bind(cluster_id) + .bind(DATABASES_ID) + .bind(serde_json::to_value(&new).map_err(anyhow::Error::from)?) + .execute(&mut **tx) + .await?; + Ok(()) +} + fn known(id: &str) -> Option { match id { WAF_ID => Some(waf_bundle()), @@ -204,15 +360,17 @@ async fn installed( .await?) } -/// Whether the cluster's install (its agent's admission policy) is this -/// Pyo's, as its last heartbeat found (install.rs): an older one refuses -/// this Pyo's bundles, so updates wait for it. +/// Whether the cluster's install lets this Pyo's bundles in, as its last +/// heartbeat found (install.rs `bundles_ready`): its admission policy is +/// this Pyo's, and so are the bundles' own roles. An older policy refuses +/// this Pyo's bundles, so updates wait for it. Other roles a refresh left +/// behind don't hold them back. async fn install_current(tx: &mut Transaction<'_, Postgres>, cluster_id: &str) -> ApiResult { - Ok(sqlx::query_scalar("SELECT coalesce(capabilities->'agentInstall'->>'state', 'current') = 'current' FROM pyo.clusters WHERE id = $1") + let row: Option<(Option, Option)> = sqlx::query_as("SELECT capabilities->'agentInstall'->>'state', (capabilities->'agentInstall'->>'bundles')::boolean FROM pyo.clusters WHERE id = $1") .bind(cluster_id) .fetch_optional(&mut **tx) - .await? - .unwrap_or(true)) + .await?; + Ok(row.is_none_or(|(state, bundles)| crate::install::bundles_ready(state.as_deref(), bundles))) } fn busy(state: &str, stale: bool) -> bool { @@ -300,13 +458,16 @@ pub async fn static_blocked( .bind(STATIC_ID) .fetch_optional(&mut **tx) .await?; - Ok(static_needs_connect(&install, state.as_deref())) + let ready = install_current(tx, cluster_id).await?; + Ok(static_needs_connect(&install, ready, state.as_deref())) } /// [`static_blocked`]'s decision: an install that's updating itself gets -/// there by itself, and one that already runs pyo-static keeps serving. -fn static_needs_connect(install: &str, bundle: Option<&str>) -> bool { - install == "outdated" && bundle != Some("applied") +/// there by itself, one that's current except for roles the bundles don't +/// need (`ready`) takes pyo-static, and one that already runs pyo-static +/// keeps serving. +fn static_needs_connect(install: &str, ready: bool, bundle: Option<&str>) -> bool { + (install == "outdated" || (install == "roles" && !ready)) && bundle != Some("applied") } /// A bundle that runs only while something on the cluster needs it: @@ -542,6 +703,9 @@ pub async fn finished( .await?; return Ok(()); } + if ok && bundle == DATABASES_ID && !removing { + databases_applied(tx, cluster_id, command, first_setup).await?; + } let (state, message) = if ok { ("applied", String::new()) } else { @@ -627,15 +791,83 @@ pub async fn reported( mod tests { use super::*; + fn runs(name: &str, engine: &str, version: &str, modules: bool) -> Runs { + Runs { + id: format!("db_{name}"), + team_id: "team_a".into(), + cluster_id: "cl_a".into(), + name: name.into(), + engine: engine.into(), + version: version.into(), + modules, + } + } + + /// Only the databases whose image a new databases system changes + /// restart, and their team's activity says so in these words. + #[test] + fn databases_restart_for_the_images_that_changed() { + let dbs = [ + runs("pg18", "postgres", "18", false), + runs("pg17", "postgres", "17", false), + runs("shop", "mysql", "8.4", false), + runs("cache", "valkey", "8.1", false), + runs("search", "valkey", "8.1", true), + ]; + let names = |v: Vec<&Runs>| v.iter().map(|d| d.name.clone()).collect::>(); + let old = databases_now().1.clone(); + // This Pyo's own images: nothing restarts. + assert!(restarting(&dbs, Some(&old), &old).is_empty()); + // A release with a new Postgres 18 and a new pyo-kv. + let mut new = old.clone(); + new.insert("postgres18".into(), "pyo/postgres:18-9@sha256:1".into()); + new.insert("kv".into(), "pyo/kv:9@sha256:1".into()); + assert_eq!(names(restarting(&dbs, Some(&old), &new)), ["pg18", "cache", "search"]); + // One that only names MySQL's (a release tells its pins). + let mysql: BTreeMap = + [("mysql".to_owned(), "mysql:9@sha256:1".to_owned())].into(); + assert_eq!(names(restarting(&dbs, Some(&old), &mysql)), ["shop"]); + // A release that names none of the images: not known to restart any. + assert!(restarting(&dbs, Some(&old), &BTreeMap::new()).is_empty()); + // A databases system from before Pyo kept its images: every one. + assert_eq!(restarting(&dbs, None, &old).len(), dbs.len()); + assert!(restarting(&[], None, &old).is_empty()); + + assert_eq!(restart_title(&dbs[0]), "Restarting the database pg18 for an update"); + assert_eq!(restart_title(&dbs[3]), "Restarting the KV database cache for an update"); + assert_eq!(applied_images(None), None); + assert_eq!(applied_images(Some(json!({ "kv": "k" }))).unwrap()["kv"], "k"); + } + + /// What an applied databases system leaves in its row: the images its + /// own controller hands out, read back from the command as sent. + #[test] + fn an_applied_databases_system_names_its_images() { + let b = databases_bundle(); + let command = serde_json::to_value(Command::ApplyBundle { + bundle: Box::new(b.clone()), + prune: vec![], + }) + .unwrap(); + let back: SystemBundle = serde_json::from_value(command["bundle"].clone()).unwrap(); + assert_eq!(pyo_proto::bundles::database_images(&back), databases_now().1); + assert_eq!(b.version, databases_now().0); + assert!(databases_now().1.contains_key("postgres18")); + } + #[test] fn static_deploys_wait_for_the_connect_command_only_when_they_must() { - assert!(static_needs_connect("outdated", None)); - assert!(static_needs_connect("outdated", Some("failed"))); - assert!(static_needs_connect("outdated", Some("installing"))); + assert!(static_needs_connect("outdated", false, None)); + assert!(static_needs_connect("outdated", false, Some("failed"))); + assert!(static_needs_connect("outdated", false, Some("installing"))); + // Current except for roles: only when those are the bundles' own. + assert!(static_needs_connect("roles", false, None)); + assert!(!static_needs_connect("roles", true, None)); + assert!(!static_needs_connect("roles", false, Some("applied"))); // pyo-static from before the update keeps serving. - assert!(!static_needs_connect("outdated", Some("applied"))); - assert!(!static_needs_connect("current", None)); - assert!(!static_needs_connect("updating", None)); + assert!(!static_needs_connect("outdated", false, Some("applied"))); + assert!(!static_needs_connect("current", true, None)); + assert!(!static_needs_connect("updating", false, None)); } #[test] diff --git a/crates/pyo-api/src/cli.rs b/crates/pyo-api/src/cli.rs index e2e50de7..7e7b73c6 100644 --- a/crates/pyo-api/src/cli.rs +++ b/crates/pyo-api/src/cli.rs @@ -274,10 +274,18 @@ struct TokenBody { /// The CLI's poll: `{"status": "pending"}` until the page answers, then /// the key once (approved), or an error that says why not. -async fn token(State(s): State, Json(b): Json) -> ApiResult> { - Ok(Json(match poll_login(&s.db, &b.id, &b.verifier).await? { - None => json!({ "status": "pending" }), - Some((key, user_name, email)) => { +async fn token( + State(s): State, + from: crate::admin_sign_in::Source, + Json(b): Json, +) -> ApiResult> { + Ok(Json(match poll_login(&s.db, &b.id, &b.verifier, &from).await? { + Polled::Pending => json!({ "status": "pending" }), + Polled::Refused(user) => { + crate::admin_sign_in::refused(&s, &user, &from, "with pyo login").await; + return Err(mismatch()); + } + Polled::Key(key, user_name, email) => { let (s2, to) = (s.clone(), email.clone()); tokio::spawn(async move { crate::twofactor::mail_user(&s2, &to, "/api-keys", |link| { @@ -292,16 +300,33 @@ async fn token(State(s): State, Json(b): Json) -> ApiResult /// A request as the poll reads it: challenge, status, who approved it, /// the computer's name and the key's days. -type Polled = (String, String, Option, String, Option); +type RequestRow = (String, String, Option, String, Option); + +/// What a poll finds. +#[derive(Debug)] +enum Polled { + Pending, + /// The new key, and its user's name and email. + Key(String, String, String), + /// Approved by an admin, polled from where admins may not sign in + /// (admin_sign_in.rs): no key, and the request is gone. + Refused(crate::auth::User), +} + +/// What a verifier is told when its request isn't one it may have. +fn mismatch() -> ApiError { + ApiError::bad_request("That login doesn't match. Run pyo login again.") +} -/// None while pending, else the new key and its user's name and email. +/// A poll from `from`: pending, the key, or refused. async fn poll_login( db: &PgPool, id: &str, verifier: &str, -) -> ApiResult> { + from: &crate::admin_sign_in::Source, +) -> ApiResult { let mut tx = db.begin().await?; - let row: Option = sqlx::query_as( + let row: Option = sqlx::query_as( "SELECT challenge, status, user_id, name, key_days FROM pyo.cli_login_requests WHERE id = $1 AND expires_at > now() FOR UPDATE", ) .bind(id) @@ -311,12 +336,10 @@ async fn poll_login( return Err(expired()); }; if sha256_hex(verifier) != challenge { - return Err(ApiError::bad_request( - "That login doesn't match. Run pyo login again.", - )); + return Err(mismatch()); } let user_id = match (status.as_str(), user_id) { - ("pending", _) => return Ok(None), + ("pending", _) => return Ok(Polled::Pending), ("approved", Some(u)) => u, _ => { sqlx::query("DELETE FROM pyo.cli_login_requests WHERE id = $1") @@ -331,6 +354,16 @@ async fn poll_login( .bind(id) .execute(&mut *tx) .await?; + let user = sqlx::query_as::<_, crate::auth::User>( + "SELECT id, name, email, timezone, is_admin, must_set_up FROM pyo.users WHERE id = $1", + ) + .bind(&user_id) + .fetch_one(&mut *tx) + .await?; + if user.is_admin && !crate::admin_sign_in::admits(&mut *tx, from).await? { + tx.commit().await?; + return Ok(Polled::Refused(user)); + } let name = if name.is_empty() { "CLI".to_owned() } else { @@ -346,12 +379,6 @@ async fn poll_login( .bind(days) .execute(&mut *tx) .await?; - let user = sqlx::query_as::<_, crate::auth::User>( - "SELECT id, name, email, timezone, is_admin, must_set_up FROM pyo.users WHERE id = $1", - ) - .bind(&user_id) - .fetch_one(&mut *tx) - .await?; // A new key: the account's teams hear of it (and the account by email, // from `token`). It's the account's doing, through the CLI. crate::audit::set_actor(&user, crate::audit::Via::Api, Some(&name)); @@ -363,7 +390,7 @@ async fn poll_login( ) .await?; tx.commit().await?; - Ok(Some((key, user.name, user.email))) + Ok(Polled::Key(key, user.name, user.email)) } #[cfg(test)] @@ -437,8 +464,9 @@ mod tests { // Approved with its code: the key goes to the verifier, once. let (id, code) = start_login(&pool, &body(Some("30d"))).await.unwrap(); - assert!(poll_login(&pool, &id, &verifier).await.unwrap().is_none()); - assert!(msg(poll_login(&pool, &id, "wrong").await.unwrap_err()).contains("doesn't match")); + let here = crate::admin_sign_in::Source::default(); + assert!(matches!(poll_login(&pool, &id, &verifier, &here).await.unwrap(), Polled::Pending)); + assert!(msg(poll_login(&pool, &id, "wrong", &here).await.unwrap_err()).contains("doesn't match")); assert!( msg(approve_login(&pool, &id, &user, other(&code)) .await @@ -449,7 +477,9 @@ mod tests { .await .unwrap(); assert!(approve_login(&pool, &id, &user, &code).await.is_err()); - let (key, _, email) = poll_login(&pool, &id, &verifier).await.unwrap().unwrap(); + let Polled::Key(key, _, email) = poll_login(&pool, &id, &verifier, &here).await.unwrap() else { + panic!("no key") + }; assert_eq!(email, format!("{user}@cli.test")); let (name, days): (String, f64) = sqlx::query_as( "SELECT name, extract(epoch FROM expires_at - now())::float8 / 86400 FROM pyo.api_tokens WHERE token_hash = $1", @@ -461,7 +491,7 @@ mod tests { assert_eq!(name, "CLI · laptop"); assert!((29.9..=30.0).contains(&days), "{days}"); assert!( - msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("expired"), + msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("expired"), "used" ); @@ -473,8 +503,8 @@ mod tests { .await .unwrap(); assert!(approve_login(&pool, &id, &user, &code).await.is_err()); - assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("refused")); - assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("expired")); + assert!(msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("refused")); + assert!(msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("expired")); // Five wrong codes end it, the right one after them too. let (id, code) = start_login(&pool, &body(None)).await.unwrap(); @@ -486,7 +516,7 @@ mod tests { ); } assert!(approve_login(&pool, &id, &user, &code).await.is_err()); - assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("refused")); + assert!(msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("refused")); // Expired: nothing to approve or poll. let (id, code) = start_login(&pool, &body(None)).await.unwrap(); @@ -500,7 +530,7 @@ mod tests { assert!( msg(approve_login(&pool, &id, &user, &code).await.unwrap_err()).contains("expired") ); - assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("expired")); + assert!(msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("expired")); // A bad challenge or lifetime never starts. let bad = StartBody { diff --git a/crates/pyo-api/src/cloud/hetzner.rs b/crates/pyo-api/src/cloud/hetzner.rs index 6c9f5b81..124a999e 100644 --- a/crates/pyo-api/src/cloud/hetzner.rs +++ b/crates/pyo-api/src/cloud/hetzner.rs @@ -129,14 +129,8 @@ pub fn error_of(status: u16, body: &Value) -> CloudError { (_, "uniqueness_error") => CloudError::NameTaken, (429, _) | (_, "rate_limit_exceeded") => CloudError::RateLimited, (404, _) | (_, "not_found") => CloudError::NotFound, - _ => CloudError::Other { - status, - message: if message.is_empty() { - format!("status {status}") - } else { - message - }, - }, + (410, _) | (_, "deprecated_api_endpoint") => CloudError::Removed(message), + _ => CloudError::Other { status, message }, } } @@ -207,23 +201,6 @@ impl Provider for Hetzner { async fn catalog(&self) -> Result { let locations = self.locations().await?; let types = self.all("/server_types", "server_types").await?; - // Which types each datacenter can make now. - let mut available: BTreeMap> = BTreeMap::new(); - for dc in self.all("/datacenters", "datacenters").await? { - let loc = s(&dc["location"]["name"]); - for id in dc["server_types"]["available"] - .as_array() - .into_iter() - .flatten() - { - if let Some(id) = id.as_u64() { - let l = available.entry(id).or_default(); - if !l.contains(&loc) { - l.push(loc.clone()); - } - } - } - } // The IPv4 address each server gets costs extra. let pricing = self.call(Method::GET, "/pricing", None).await?; let currency = pricing["pricing"]["currency"] @@ -247,11 +224,30 @@ impl Provider for Hetzner { } let mut server_types: Vec = types .iter() - .filter(|t| t["deprecated"] != true && t["deprecation"].is_null()) - .map(|t| { - let id = t["id"].as_u64().unwrap_or(0); + .filter_map(|t| { + // Each type lists the locations that sell it. A location + // where Hetzner is phasing the type out has a `deprecation` + // and is left out, the same as a type phased out everywhere. + // `available` false means sold out for now. + let sold: Vec<(String, bool)> = t["locations"] + .as_array() + .into_iter() + .flatten() + .filter(|l| l["deprecation"].is_null()) + .map(|l| (s(&l["name"]), l["available"] == true)) + .filter(|(name, _)| !name.is_empty()) + .collect(); + if sold.is_empty() { + return None; + } + let mut available: Vec = sold + .iter() + .filter(|(_, now)| *now) + .map(|(name, _)| name.clone()) + .collect(); + available.sort(); let architecture = s(&t["architecture"]); - ServerType { + Some(ServerType { name: s(&t["name"]), description: s(&t["description"]), cores: t["cores"].as_u64().unwrap_or(0) as u32, @@ -266,13 +262,16 @@ impl Provider for Hetzner { .flatten() .filter_map(|p| { let loc = s(&p["location"]); + if !sold.iter().any(|(name, _)| *name == loc) { + return None; + } let m = price(&p["price_monthly"]["net"])?; let ip = ipv4.get(&loc).copied().unwrap_or(0.0); Some((loc, ((m + ip) * 100.0).round() / 100.0)) }) .collect(), - available: available.get(&id).cloned().unwrap_or_default(), - } + available, + }) }) .collect(); server_types.sort_by(|a, b| { @@ -442,25 +441,39 @@ pub mod mock { { "id": 2, "name": "ash", "city": "Ashburn, VA", "country": "US", "network_zone": "us-east" }, ], "meta": page_one }), ), + // The shape since 2026-11-02: availability and deprecation + // per location, and no `deprecated` field. ("GET", "/server_types") => ( 200, json!({ "server_types": [ - { "id": 22, "name": "cx22", "description": "CX22", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "architecture": "x86", "deprecated": false, "deprecation": null, + { "id": 104, "name": "cx23", "description": "CX23", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "category": "Cost-Optimized", "architecture": "x86", "storage_type": "local", "deprecation": null, + "locations": [ + { "id": 1, "name": "fsn1", "deprecation": null, "recommended": true, "available": true }, + { "id": 2, "name": "ash", "deprecation": null, "recommended": false, "available": false } ], + "prices": [ + { "location": "fsn1", "price_hourly": { "net": "0.0061000000", "gross": "0.0072590000" }, "price_monthly": { "net": "3.7900000000", "gross": "4.5101000000" }, "included_traffic": 21990232555520i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.1900000000" } }, + { "location": "ash", "price_hourly": { "net": "0.0080000000", "gross": "0.0080000000" }, "price_monthly": { "net": "4.9900000000", "gross": "4.9900000000" }, "included_traffic": 1099511627776i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.0000000000" } } ] }, + { "id": 45, "name": "cax11", "description": "CAX11", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "category": "Cost-Optimized", "architecture": "arm", "storage_type": "local", "deprecation": null, + "locations": [ { "id": 1, "name": "fsn1", "deprecation": null, "recommended": false, "available": true } ], + "prices": [ { "location": "fsn1", "price_hourly": { "net": "0.0053000000", "gross": "0.0063070000" }, "price_monthly": { "net": "3.2900000000", "gross": "3.9151000000" }, "included_traffic": 21990232555520i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.1900000000" } } ] }, + { "id": 108, "name": "cpx22", "description": "CPX22", "cores": 2, "memory": 4.0, "disk": 80, "cpu_type": "shared", "category": "Regular Purpose", "architecture": "x86", "storage_type": "local", "deprecation": null, + "locations": [ + { "id": 1, "name": "fsn1", "deprecation": { "announced": "2025-10-16T00:00:00Z", "unavailable_after": "2027-01-01T00:00:00Z" }, "recommended": false, "available": true }, + { "id": 2, "name": "ash", "deprecation": null, "recommended": true, "available": true } ], "prices": [ - { "location": "fsn1", "price_monthly": { "net": "3.7900000000", "gross": "4.5101000000" } }, - { "location": "ash", "price_monthly": { "net": "4.9900000000", "gross": "4.9900000000" } } ] }, - { "id": 45, "name": "cax11", "description": "CAX11", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "architecture": "arm", "deprecated": false, "deprecation": null, - "prices": [ { "location": "fsn1", "price_monthly": { "net": "3.2900000000", "gross": "3.9151000000" } } ] }, - { "id": 1, "name": "cx11", "description": "old", "cores": 1, "memory": 2.0, "disk": 20, "cpu_type": "shared", "architecture": "x86", "deprecated": true, - "prices": [ { "location": "fsn1", "price_monthly": { "net": "3.0000000000", "gross": "3.5700000000" } } ] }, + { "location": "fsn1", "price_hourly": { "net": "0.0100000000", "gross": "0.0119000000" }, "price_monthly": { "net": "6.4900000000", "gross": "7.7231000000" }, "included_traffic": 21990232555520i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.1900000000" } }, + { "location": "ash", "price_hourly": { "net": "0.0120000000", "gross": "0.0120000000" }, "price_monthly": { "net": "7.4900000000", "gross": "7.4900000000" }, "included_traffic": 1099511627776i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.0000000000" } } ] }, + { "id": 22, "name": "cx22", "description": "CX22", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "category": "Cost-Optimized", "architecture": "x86", "storage_type": "local", + "deprecation": { "announced": "2025-10-16T00:00:00Z", "unavailable_after": "2026-12-31T00:00:00Z" }, + "locations": [ { "id": 1, "name": "fsn1", "deprecation": { "announced": "2025-10-16T00:00:00Z", "unavailable_after": "2026-12-31T00:00:00Z" }, "recommended": false, "available": true } ], + "prices": [ { "location": "fsn1", "price_hourly": { "net": "0.0050000000", "gross": "0.0059500000" }, "price_monthly": { "net": "3.0000000000", "gross": "3.5700000000" }, "included_traffic": 21990232555520i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.1900000000" } } ] }, ], "meta": page_one }), ), - ("GET", "/datacenters") => ( - 200, - json!({ "datacenters": [ - { "name": "fsn1-dc14", "location": { "name": "fsn1" }, "server_types": { "supported": [22, 45, 1], "available": [22, 45] } }, - { "name": "ash-dc1", "location": { "name": "ash" }, "server_types": { "supported": [22], "available": [] } }, - ], "meta": page_one }), + // Removed on 2026-10-01: Hetzner answers 410 Gone. + ("GET", r) if r.starts_with("/datacenters") => ( + 410, + json!({ "error": { "code": "deprecated_api_endpoint", "message": "API functionality was removed", + "details": { "announcement": "https://docs.hetzner.cloud/changelog" } } }), ), ("GET", "/pricing") => ( 200, diff --git a/crates/pyo-api/src/cloud/mod.rs b/crates/pyo-api/src/cloud/mod.rs index d47300cf..a1db2720 100644 --- a/crates/pyo-api/src/cloud/mod.rs +++ b/crates/pyo-api/src/cloud/mod.rs @@ -77,7 +77,7 @@ pub struct Location { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct ServerType { - /// "cx22" + /// "cx23" pub name: String, pub description: String, pub cores: u32, @@ -177,6 +177,8 @@ pub enum CloudError { /// A server without this installation's label: never deleted. NotOurs, Network(String), + /// A part of Hetzner's API Pyo calls is gone (410): its message. + Removed(String), Other { status: u16, message: String, @@ -195,11 +197,28 @@ impl std::fmt::Display for CloudError { Self::NotFound => f.write_str("Hetzner has no such server."), Self::NotOurs => f.write_str("This server doesn't carry this Pyo's label at Hetzner, so Pyo won't delete it."), Self::Network(e) => write!(f, "Couldn't reach Hetzner. {e}"), - Self::Other { status, message } => write!(f, "Hetzner answered {status}: {message}"), + Self::Removed(message) => { + f.write_str("Hetzner removed a part of its API that Pyo calls")?; + said(f, message) + } + Self::Other { status, message } => { + write!(f, "Hetzner answered with error {status}")?; + said(f, message) + } } } } +/// Hetzner's own words after ours, when it gave some. +fn said(f: &mut std::fmt::Formatter<'_>, message: &str) -> std::fmt::Result { + let message = message.trim().trim_end_matches('.'); + if message.is_empty() { + f.write_str(".") + } else { + write!(f, ". It said: \"{message}\".") + } +} + impl std::error::Error for CloudError {} impl From for ApiError { @@ -213,7 +232,9 @@ impl From for ApiError { | CloudError::NotOurs => StatusCode::CONFLICT, CloudError::RateLimited => StatusCode::TOO_MANY_REQUESTS, CloudError::NotFound => StatusCode::NOT_FOUND, - CloudError::Network(_) | CloudError::Other { .. } => StatusCode::BAD_GATEWAY, + CloudError::Network(_) | CloudError::Removed(_) | CloudError::Other { .. } => { + StatusCode::BAD_GATEWAY + } }; ApiError::new(status, e.to_string()) } @@ -989,29 +1010,76 @@ mod tests { #[tokio::test] async fn catalog_reads_types_prices_and_availability() { - let h = Hetzner::mock(mock::TOKEN, mock::Mock::new()); + let m = mock::Mock::new(); + let h = Hetzner::mock(mock::TOKEN, m.clone()); let c = h.catalog().await.unwrap(); assert_eq!(c.currency, "EUR"); assert_eq!(c.locations.len(), 2); - // The deprecated type is left out; the cheapest comes first. + // The type phased out everywhere is left out. The cheapest comes first. let names: Vec<&str> = c.server_types.iter().map(|t| t.name.as_str()).collect(); - assert_eq!(names, ["cax11", "cx22"]); - let cx = c.server_types.iter().find(|t| t.name == "cx22").unwrap(); + assert_eq!(names, ["cax11", "cx23", "cpx22"]); + let cx = c.server_types.iter().find(|t| t.name == "cx23").unwrap(); // 3.79 for the server, 0.50 for its IPv4 address. assert_eq!(cx.prices.get("fsn1"), Some(&4.29)); + assert_eq!(cx.prices.get("ash"), Some(&4.99)); + assert_eq!(cx.available, ["fsn1"]); assert!(cx.supported && cx.architecture == "x86"); - assert_eq!(c.pick("fsn1", "cx22").unwrap(), 4.29); + assert_eq!(c.pick("fsn1", "cx23").unwrap(), 4.29); // Arm isn't for Pyo's servers. assert!(c.pick("fsn1", "cax11").unwrap_err().message.contains("Arm")); // Sold out in Ashburn. - let e = c.pick("ash", "cx22").unwrap_err(); + let e = c.pick("ash", "cx23").unwrap_err(); assert!( e.message.contains("isn't available in Ashburn"), "{}", e.message ); - assert!(c.pick("nbg1", "cx22").is_err()); + // Phased out in Falkenstein only: sold in Ashburn, no price in Falkenstein. + let cpx = c.server_types.iter().find(|t| t.name == "cpx22").unwrap(); + assert_eq!(cpx.available, ["ash"]); + assert_eq!(cpx.prices.keys().collect::>(), ["ash"]); + assert_eq!(c.pick("ash", "cpx22").unwrap(), 7.49); + assert!(c.pick("fsn1", "cpx22").is_err()); + assert!(c.pick("fsn1", "cx22").is_err()); + assert!(c.pick("nbg1", "cx23").is_err()); assert!(c.pick("fsn1", "cx99").is_err()); + // Only endpoints Hetzner still has: /datacenters answers 410 since 2026-10-01. + let calls = m.0.lock().unwrap().calls.clone(); + assert!( + !calls.iter().any(|c| c.contains("/datacenters")), + "{calls:?}" + ); + } + + #[test] + fn hetzner_errors_keep_its_message() { + let gone = hetzner::error_of( + 410, + &json!({ "error": { "code": "deprecated_api_endpoint", "message": "API functionality was removed", + "details": { "announcement": "https://docs.hetzner.cloud/changelog" } } }), + ); + assert_eq!( + gone, + CloudError::Removed("API functionality was removed".into()) + ); + assert_eq!( + gone.to_string(), + "Hetzner removed a part of its API that Pyo calls. It said: \"API functionality was removed\"." + ); + let api: ApiError = gone.into(); + assert_eq!(api.status, axum::http::StatusCode::BAD_GATEWAY); + assert_eq!( + hetzner::error_of( + 503, + &json!({ "error": { "code": "maintenance", "message": "cannot perform operation due to maintenance." } }) + ) + .to_string(), + "Hetzner answered with error 503. It said: \"cannot perform operation due to maintenance\"." + ); + assert_eq!( + hetzner::error_of(500, &Value::Null).to_string(), + "Hetzner answered with error 500." + ); } #[tokio::test] @@ -1039,7 +1107,7 @@ mod tests { .collect(); assert_eq!(open, ["tcp/80", "tcp/443", "udp/41641"]); } - let mut c = create("web-1", "cx22", "cl_one", "#cloud-config\n"); + let mut c = create("web-1", "cx23", "cl_one", "#cloud-config\n"); c.firewall = Some(&fw); let r = h.create(&c).await.unwrap(); assert_eq!(r.status, "initializing"); @@ -1130,9 +1198,9 @@ mod tests { let m = mock::Mock::new(); m.0.lock().unwrap().limit = 1; let h = Hetzner::mock(mock::TOKEN, m.clone()); - h.create(&create("a", "cx22", "cl_one", "")).await.unwrap(); + h.create(&create("a", "cx23", "cl_one", "")).await.unwrap(); let e = h - .create(&create("b", "cx22", "cl_one", "")) + .create(&create("b", "cx23", "cl_one", "")) .await .unwrap_err(); assert!(matches!(e, CloudError::Quota(_))); @@ -1141,9 +1209,9 @@ mod tests { assert!(api.message.contains("server limit") && api.message.contains("Limits page")); m.0.lock().unwrap().limit = 5; - m.0.lock().unwrap().sold_out = vec!["cx32".into()]; + m.0.lock().unwrap().sold_out = vec!["cx33".into()]; let e = h - .create(&create("c", "cx32", "cl_one", "")) + .create(&create("c", "cx33", "cl_one", "")) .await .unwrap_err(); assert!(matches!(e, CloudError::Unavailable(_))); diff --git a/crates/pyo-api/src/cloudflare.rs b/crates/pyo-api/src/cloudflare.rs index f845651a..fc63cbb1 100644 --- a/crates/pyo-api/src/cloudflare.rs +++ b/crates/pyo-api/src/cloudflare.rs @@ -19,6 +19,9 @@ //! first HTTP-01 check reaches the cluster directly. //! - A proxied record suggests the service's "Behind Cloudflare" firewall //! switch (the dashboard's DNS record line), until it's on. +//! - Cloudflare Tunnel (tunnel.rs): with Cloudflare Tunnel:Edit in the +//! account and SSL and Certificates:Edit in a zone, the zone is +//! tunnel-ready. Both are optional: DNS:Edit alone still connects. use crate::error::Json; use crate::error::Query; @@ -44,6 +47,11 @@ const TIMEOUT: Duration = Duration::from_secs(20); /// Zones looked at in one test, at most. const MAX_ZONES: usize = 200; +pub(crate) mod tunnel; +pub(crate) mod tunnel_loop; +pub(crate) mod tunnel_ops; +use tunnel::TunnelApi; + // ── Zones and records ────────────────────────────────────────────────────── /// A zone the token sees, as stored and shown. @@ -57,6 +65,32 @@ pub struct Zone { /// The permission it lacks, when it can't. #[serde(default, skip_serializing_if = "Option::is_none")] pub missing: Option, + /// The Cloudflare account it's in. A tunnel lives in one account and + /// only takes names from that account's zones. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub account_id: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub account_name: String, + /// Whether it can use Cloudflare Tunnel. + #[serde(default)] + pub tunnel: TunnelAccess, +} + +/// Whether a zone can use Cloudflare Tunnel: the token may edit DNS in it, +/// make tunnels in its account and issue its Origin CA certificates. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct TunnelAccess { + pub ready: bool, + /// The tunnel permissions the token lacks here. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub missing: Vec, +} + +impl Zone { + /// It can take domains through a tunnel. + pub fn tunnel_ready(&self) -> bool { + self.can_edit && self.tunnel.ready + } } /// A DNS record at Cloudflare. @@ -117,8 +151,6 @@ fn api_error(e: CfError) -> ApiError { /// What Pyo asks of Cloudflare. [`Http`] is the real one; the tests use a /// fake account. pub(crate) trait Cloudflare { - /// Every zone the token can read, as (id, name). - async fn zones(&self) -> Result, CfError>; /// The records with exactly this name. async fn records(&self, zone_id: &str, name: &str) -> Result, CfError>; async fn record(&self, zone_id: &str, id: &str) -> Result; @@ -219,13 +251,17 @@ fn hint(t: &str) -> String { /// Whether Pyo can edit DNS in a zone: it reads the records, then makes and /// deletes a TXT record `_pyo-check.` (a token with DNS:Read only can -/// read, not write). The permission it lacks, or None. +/// read, not write). The record's text carries this installation's id: +/// Cloudflare refuses a record identical to one that exists, so with the +/// same text a probe another installation left behind in a shared zone +/// would fail this check. The permission it lacks, or None. pub(crate) async fn missing_in( cf: &C, zone: &(String, String), - marker: &str, + install_id: &str, ) -> Result, CfError> { let (id, name) = zone; + let marker = &marker(install_id); let probe = format!("_pyo-check.{name}"); let found = match cf.records(id, &probe).await { Ok(f) => f, @@ -242,25 +278,31 @@ pub(crate) async fn missing_in( &NewRecord { kind: "TXT".into(), name: probe, - content: "\"pyo-check\"".into(), + content: format!("\"pyo-check-{install_id}\""), proxied: false, comment: marker.to_owned(), }, ) .await; match made { - Ok(r) => { - cf.delete(id, &r.id).await?; - Ok(None) - } + Ok(r) => match cf.delete(id, &r.id).await { + // Already gone (another check by this installation cleaned + // up): nothing is left behind either way. + Ok(()) | Err(CfError::NotFound) => Ok(None), + Err(e) => Err(e), + }, Err(CfError::Denied(_)) => Ok(Some("DNS:Edit".into())), Err(e) => Err(e), } } -/// The zones a token covers, and what it can do in each. -pub(crate) async fn inspect(cf: &C, marker: &str) -> Result, CfError> { - let mut zones = match cf.zones().await { +/// The zones a token covers, and what it can do in each: DNS per zone, +/// tunnels once per account, Origin CA certificates per zone. +pub(crate) async fn inspect( + cf: &C, + install_id: &str, +) -> Result, CfError> { + let mut zones = match cf.zone_accounts().await { Ok(z) => z, Err(CfError::Denied(m)) => { return Err(CfError::Denied(if m.is_empty() { @@ -271,16 +313,38 @@ pub(crate) async fn inspect(cf: &C, marker: &str) -> Result return Err(e), }; - zones.sort_by(|a, b| a.1.cmp(&b.1)); + zones.sort_by(|a, b| a.name.cmp(&b.name)); zones.truncate(MAX_ZONES); + let mut tunnels: HashMap> = HashMap::new(); let mut out = vec![]; for z in &zones { - let missing = missing_in(cf, z, marker).await?; + let missing = missing_in(cf, &(z.id.clone(), z.name.clone()), install_id).await?; + let mut lacks = vec![]; + if z.account_id.is_empty() { + lacks.push(tunnel::TUNNEL_EDIT.to_owned()); + } else { + if !tunnels.contains_key(&z.account_id) { + let m = tunnel::tunnel_missing(cf, &z.account_id, install_id).await?; + tunnels.insert(z.account_id.clone(), m); + } + if let Some(Some(m)) = tunnels.get(&z.account_id) { + lacks.push(m.clone()); + } + } + if let Some(m) = tunnel::certs_missing(cf, &z.id).await? { + lacks.push(m); + } out.push(Zone { - id: z.0.clone(), - name: z.1.to_ascii_lowercase(), + id: z.id.clone(), + name: z.name.to_ascii_lowercase(), can_edit: missing.is_none(), - missing, + missing: missing.clone(), + account_id: z.account_id.clone(), + account_name: z.account_name.clone(), + tunnel: TunnelAccess { + ready: missing.is_none() && lacks.is_empty(), + missing: lacks, + }, }); } Ok(out) @@ -293,14 +357,22 @@ pub fn problems(zones: &[Zone]) -> Vec { "The token can't see any zones. Give it Zone:Read on the zones Pyo may use.".into(), ]; } - zones + let mut out: Vec = zones .iter() .filter_map(|z| { z.missing .as_ref() .map(|m| format!("{}: give the token {m}.", z.name)) }) - .collect() + .collect(); + // Tunnel permissions are optional: a zone with neither is DNS only. + // One of the two means a tunnel was meant, so the other is a problem. + for z in zones.iter().filter(|z| z.can_edit) { + if z.tunnel.missing.len() == 1 { + out.push(format!("{}: give the token {}.", z.name, z.tunnel.missing[0])); + } + } + out } // ── Cloudflare over HTTP ─────────────────────────────────────────────────── @@ -309,6 +381,21 @@ pub fn problems(zones: &[Zone]) -> Vec { pub(crate) struct Http { client: reqwest::Client, token: String, + /// [`API`], or a debug build's fake ([`api_base`]). + base: String, +} + +/// Where Cloudflare's API is: [`API`]. A debug build may point it at a fake +/// with `PYO_DEV_CLOUDFLARE_API` (`http://127.0.0.1:8787/client/v4`, for the +/// dashboard and Pyo Cloud e2e tests). Release builds never read it. +pub(crate) fn api_base() -> String { + #[cfg(debug_assertions)] + if let Ok(b) = std::env::var("PYO_DEV_CLOUDFLARE_API") + && !b.trim().is_empty() + { + return b.trim().trim_end_matches('/').to_owned(); + } + API.to_owned() } // Never print the token. @@ -348,20 +435,37 @@ fn token_code(v: &Value) -> bool { impl Http { pub fn new(token: &str) -> ApiResult { + let base = api_base(); + // Only a debug build's fake is on a private address. + let reach = Reach { + private: base != API, + }; Ok(Self { - client: outbound::client(Reach { private: false }, TIMEOUT) + client: outbound::client(reach, TIMEOUT) .map_err(|e| ApiError::from(anyhow::Error::from(e)))?, token: token.to_owned(), + base, }) } - fn url(path: &str) -> Url { - // Constant base, checked ids: always parses. - Url::parse(&format!("{API}{path}")).expect("Cloudflare URL") + /// A client for the tests' fake Cloudflare (fake.rs). + #[cfg(test)] + pub fn at(token: &str, base: &str) -> Self { + Self { + client: reqwest::Client::new(), + token: token.to_owned(), + base: base.trim_end_matches('/').to_owned(), + } + } + + fn url(&self, path: &str) -> Url { + // A fixed base and checked ids: always parses. + Url::parse(&format!("{}{path}", self.base)).expect("Cloudflare URL") } async fn call(&self, method: Method, url: Url, body: Option) -> Result { - if url.host_str() != Some("api.cloudflare.com") || url.scheme() != "https" { + let real = url.host_str() == Some("api.cloudflare.com") && url.scheme() == "https"; + if !(real || (self.base != API && url.as_str().starts_with(&self.base))) { return Err(CfError::Unreachable); } let mut rq = self.client.request(method, url).bearer_auth(&self.token); @@ -401,30 +505,8 @@ fn record_from(v: &Value) -> Result { } impl Cloudflare for Http { - async fn zones(&self) -> Result, CfError> { - let mut out = vec![]; - for page in 1..=20 { - let mut url = Self::url("/zones"); - url.query_pairs_mut() - .append_pair("per_page", "50") - .append_pair("page", &page.to_string()); - let v = self.call(Method::GET, url, None).await?; - for z in v["result"].as_array().into_iter().flatten() { - if let (Some(id), Some(name)) = (z["id"].as_str(), z["name"].as_str()) - && id_ok(id) - { - out.push((id.to_owned(), name.to_owned())); - } - } - if page >= v["result_info"]["total_pages"].as_i64().unwrap_or(1) { - break; - } - } - Ok(out) - } - async fn records(&self, zone_id: &str, name: &str) -> Result, CfError> { - let mut url = Self::url(&Self::record_path(zone_id, None)?); + let mut url = self.url(&Self::record_path(zone_id, None)?); url.query_pairs_mut() .append_pair("name", name) .append_pair("per_page", "100"); @@ -438,12 +520,12 @@ impl Cloudflare for Http { } async fn record(&self, zone_id: &str, id: &str) -> Result { - let url = Self::url(&Self::record_path(zone_id, Some(id))?); + let url = self.url(&Self::record_path(zone_id, Some(id))?); record_from(&self.call(Method::GET, url, None).await?["result"]) } async fn create(&self, zone_id: &str, r: &NewRecord) -> Result { - let url = Self::url(&Self::record_path(zone_id, None)?); + let url = self.url(&Self::record_path(zone_id, None)?); let body = json!({ "type": r.kind, "name": r.name, "content": r.content, "ttl": 1, "proxied": r.proxied, "comment": r.comment, @@ -452,14 +534,14 @@ impl Cloudflare for Http { } async fn set_proxied(&self, zone_id: &str, id: &str, proxied: bool) -> Result<(), CfError> { - let url = Self::url(&Self::record_path(zone_id, Some(id))?); + let url = self.url(&Self::record_path(zone_id, Some(id))?); self.call(Method::PATCH, url, Some(json!({ "proxied": proxied }))) .await .map(|_| ()) } async fn delete(&self, zone_id: &str, id: &str) -> Result<(), CfError> { - let url = Self::url(&Self::record_path(zone_id, Some(id))?); + let url = self.url(&Self::record_path(zone_id, Some(id))?); self.call(Method::DELETE, url, None).await.map(|_| ()) } } @@ -597,6 +679,7 @@ pub async fn attach( "SELECT service_id, domain_id, jsonb_build_object( 'zone', zone_name, 'type', type, 'content', content, 'proxied', proxied, 'proxy', proxy, 'status', status, 'error', error, 'existing', existing, 'mine', record_id IS NOT NULL, + 'via', via, 'previous', previous, 'updatedAt', pyo.ms(updated_at)) FROM pyo.dns_records WHERE team_id = ANY($1)", ) @@ -621,7 +704,10 @@ pub async fn attach( } /// A service was saved: records of domains it no longer has (or whose -/// hostname changed) are forgotten. What's at Cloudflare stays. +/// hostname changed) are forgotten. What's at Cloudflare stays, except a +/// record through the Cloudflare Tunnel: the tunnel loop deletes Pyo's +/// CNAME. The record it replaced isn't put back (decision 5), unless a +/// switch back that puts it back was already asked for. pub async fn forget_removed( tx: &mut Transaction<'_, Postgres>, service_id: &str, @@ -639,7 +725,19 @@ pub async fn forget_removed( }) .unzip(); sqlx::query( - "DELETE FROM pyo.dns_records r WHERE r.service_id = $1 + "UPDATE pyo.dns_records r SET status = 'reverting', restore = r.status = 'reverting' AND r.restore, + routes_command = NULL, updated_at = now() + WHERE r.service_id = $1 AND r.via = 'tunnel' + AND NOT EXISTS (SELECT 1 FROM unnest($2::text[], $3::text[]) AS d(id, host) + WHERE d.id = r.domain_id AND d.host = lower(r.hostname))", + ) + .bind(service_id) + .bind(&ids) + .bind(&hosts) + .execute(&mut **tx) + .await?; + sqlx::query( + "DELETE FROM pyo.dns_records r WHERE r.service_id = $1 AND r.via <> 'tunnel' AND NOT EXISTS (SELECT 1 FROM unnest($2::text[], $3::text[]) AS d(id, host) WHERE d.id = r.domain_id AND d.host = lower(r.hostname))", ) @@ -651,6 +749,65 @@ pub async fn forget_removed( Ok(()) } +// ── Proof of a domain (Pyo Cloud) ────────────────────────────────────────── + +/// Pyo Cloud's proof of owning `host` (domainproof.rs), written by Pyo: +/// the TXT record `_pyo-verify.` with the team's token, when the +/// team's Cloudflare token can edit DNS in a zone that covers it. So Cloud +/// teams with Cloudflare don't add it by hand. Whether it's there now. +pub(crate) async fn write_proof( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + host: &str, +) -> ApiResult { + let row: Option<(String, Value)> = sqlx::query_as( + "SELECT token_sealed, zones FROM pyo.cloudflare_accounts WHERE team_id = $1", + ) + .bind(team_id) + .fetch_optional(&mut **tx) + .await?; + let Some((sealed, zones)) = row else { + return Ok(false); + }; + let zones: Vec = serde_json::from_value(zones).unwrap_or_default(); + let Some(zone) = zone_for(host, &zones).filter(|z| z.can_edit).cloned() else { + return Ok(false); + }; + // Sealed by the vault, or (older keys) with PYO_SECRET_KEY. + let token = if sealed.starts_with(crate::secrets::PREFIX) { + crate::secrets::Sealer::from_env().open(&sealed) + } else { + crate::vault::get().open(&sealed).await + }; + let Ok(token) = token else { + return Ok(false); + }; + let name = crate::domainproof::record(host); + let value = crate::domainproof::token(team_id, host); + let mark = marker(&install_id(tx).await?); + let cf = Http::new(&token)?; + let found = cf.records(&zone.id, &name).await.map_err(api_error)?; + if found + .iter() + .any(|r| r.kind == "TXT" && r.content.trim_matches('"') == value) + { + return Ok(true); + } + cf.create( + &zone.id, + &NewRecord { + kind: "TXT".into(), + name, + content: format!("\"{value}\""), + proxied: false, + comment: mark, + }, + ) + .await + .map_err(api_error)?; + Ok(true) +} + // ── The connection ───────────────────────────────────────────────────────── /// Connect (or replace) a team's token: checked first, then sealed. @@ -674,8 +831,8 @@ pub async fn connect( "This installation has no PYO_SECRET_KEY, so it can't store keys.", )); } - let marker = marker(&install_id(tx).await?); - let zones = inspect(&Http::new(token)?, &marker) + let install = install_id(tx).await?; + let zones = inspect(&Http::new(token)?, &install) .await .map_err(api_error)?; if zones.is_empty() { @@ -728,8 +885,8 @@ pub async fn test( ) -> ApiResult { require_role(tx, user, team_id, role_for(Action::ManageToken)).await?; let a = account(s, tx, team_id).await?.ok_or_else(no_account)?; - let marker = marker(&install_id(tx).await?); - let zones = match inspect(&Http::new(&a.token)?, &marker).await { + let install = install_id(tx).await?; + let zones = match inspect(&Http::new(&a.token)?, &install).await { Ok(z) => z, Err(e @ CfError::Denied(_)) => { return Ok(json!({ "ok": false, "zones": [], "problems": [e.to_string()] })); @@ -747,13 +904,26 @@ pub async fn test( Ok(json!({ "ok": problems.is_empty(), "zones": zones, "problems": problems })) } -/// Forget the token. Records Pyo made stay at Cloudflare. +/// Forget the token. Records Pyo made stay at Cloudflare. Refused while a +/// cluster of the team has a tunnel. pub async fn remove( tx: &mut Transaction<'_, Postgres>, user: &User, team_id: &str, ) -> ApiResult { require_role(tx, user, team_id, role_for(Action::ManageToken)).await?; + // Without the token, Pyo could no longer change or remove a tunnel. + let tunneled: Option = sqlx::query_scalar( + "SELECT c.name FROM pyo.cluster_tunnels t JOIN pyo.clusters c ON c.id = t.cluster_id WHERE t.team_id = $1 ORDER BY c.name LIMIT 1", + ) + .bind(team_id) + .fetch_optional(&mut **tx) + .await?; + if let Some(name) = tunneled { + return Err(ApiError::conflict(format!( + "Remove the Cloudflare Tunnel of {name} first. Its websites keep working until then." + ))); + } let gone = sqlx::query("DELETE FROM pyo.cloudflare_accounts WHERE team_id = $1") .bind(team_id) .execute(&mut **tx) @@ -791,7 +961,7 @@ pub struct CloudflareQuery { #[utoipa::path(get, path = "/cloudflare", operation_id = "getCloudflare", tag = "Integrations", params(CloudflareQuery), responses( - (status = 200, description = "`connected`, and when connected `zones` (each with `id`, `name`, `canEdit` and, when it can't, `missing`: the permission the token lacks), `createdAt`, `testedAt`, and for owners and admins `hint` and `createdBy`.", body = Object), + (status = 200, description = "`connected`, and when connected `zones` (each with `id`, `name`, `canEdit` and, when it can't, `missing`: the permission the token lacks, `accountId`, `accountName`, and `tunnel`: `ready` and the tunnel permissions it lacks as `missing`), `createdAt`, `testedAt`, and for owners and admins `hint` and `createdBy`.", body = Object), (status = 404, description = "No such team, or you aren't in it.", body = crate::error::ErrorBody), ), extensions(("x-pyo-access" = json!("read"))))] @@ -1246,3 +1416,7 @@ pub async fn proxy_ready(s: &AppState) -> ApiResult<()> { #[cfg(test)] mod tests; +#[cfg(test)] +mod fake; +#[cfg(test)] +mod http_tests; diff --git a/crates/pyo-api/src/cloudflare/fake.rs b/crates/pyo-api/src/cloudflare/fake.rs new file mode 100644 index 00000000..49165c06 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/fake.rs @@ -0,0 +1,312 @@ +//! A fake Cloudflare API over HTTP, for tests (docs/cloudflare-tunnel.md +//! §17.3): zones with their accounts, DNS records, tunnels with their +//! routes, tokens and connections, and Origin CA certificates signed by a +//! test CA. It answers in Cloudflare's envelope (`success`, `errors`, +//! `result`), so the real client ([`super::Http`]) runs against it. +//! +//! [`FakeCf::start`] serves it on a free local port; the client points at +//! [`FakeCf::base`] (`Http::at`, or `PYO_DEV_CLOUDFLARE_API` in a debug +//! build). Every call is kept, as "METHOD /path". + +use std::sync::{Arc, Mutex}; + +use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, Method, StatusCode, Uri}, + response::{IntoResponse, Response}, +}; +use serde_json::{Value, json}; + +/// What the fake account holds. +#[derive(Default)] +pub struct Account { + /// The token it takes. + pub token: String, + /// (id, name, account id, account name). + pub zones: Vec<(String, String, String, String)>, + /// Accounts whose tunnels the token may not touch. + pub no_tunnels: Vec, + /// (zone id, record). + pub records: Vec<(String, Value)>, + /// (account id, tunnel). + pub tunnels: Vec<(String, Value)>, + /// tunnel id → (version, config). + pub configs: Vec<(String, i64, Value)>, + /// (id, hostnames, revoked). + pub certs: Vec<(String, Vec, bool)>, + pub calls: Vec, + next: u64, +} + +#[derive(Clone)] +pub struct FakeCf { + pub state: Arc>, + pub base: String, +} + +fn ok(result: Value) -> Response { + axum::Json(json!({ "success": true, "errors": [], "messages": [], "result": result, "result_info": { "page": 1, "total_pages": 1 } })) + .into_response() +} + +fn err(code: StatusCode, message: &str) -> Response { + ( + code, + axum::Json(json!({ "success": false, "errors": [{ "code": 1000 + code.as_u16(), "message": message }], "result": null })), + ) + .into_response() +} + +fn query(uri: &Uri, key: &str) -> Option { + uri.query()?.split('&').find_map(|kv| { + let (k, v) = kv.split_once('=')?; + (k == key).then(|| v.replace("%2A", "*").replace("%2a", "*")) + }) +} + +impl FakeCf { + /// Serve a fake account with this token and zones (id, name, account). + pub async fn start(token: &str, zones: &[(&str, &str, &str)]) -> FakeCf { + let state = Arc::new(Mutex::new(Account { + token: token.into(), + zones: zones + .iter() + .map(|(i, n, a)| (i.to_string(), n.to_string(), a.to_string(), format!("{a} Co"))) + .collect(), + ..Default::default() + })); + let app = Router::new() + .fallback(handle) + .with_state(state.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + FakeCf { + state, + base: format!("http://{addr}/client/v4"), + } + } + + pub fn calls(&self) -> Vec { + self.state.lock().unwrap().calls.clone() + } + + pub fn records(&self, zone: &str) -> Vec { + self.state + .lock() + .unwrap() + .records + .iter() + .filter(|(z, _)| z == zone) + .map(|(_, r)| r.clone()) + .collect() + } + + pub fn tunnels(&self) -> Vec { + self.state + .lock() + .unwrap() + .tunnels + .iter() + .map(|(_, t)| t.clone()) + .collect() + } + + /// Add a tunnel that's already in the account, made `age_mins` ago. + pub fn put_tunnel(&self, account: &str, name: &str, age_mins: i64) { + let mut a = self.state.lock().unwrap(); + a.next += 1; + let made = jiff::Timestamp::now() - jiff::SignedDuration::from_mins(age_mins); + let t = json!({ "id": uuid(a.next), "name": name, "status": "inactive", "created_at": made.to_string(), "deleted_at": null, "connections": [], "secret": "first" }); + a.tunnels.push((account.into(), t)); + } + + /// Add a record someone made by hand. + pub fn put_record(&self, zone: &str, r: Value) { + self.state.lock().unwrap().records.push((zone.into(), r)); + } + + /// Set a tunnel's status, as its connectors make it. + pub fn set_status(&self, tunnel: &str, status: &str, colos: &[&str]) { + for (_, t) in self.state.lock().unwrap().tunnels.iter_mut() { + if t["id"] == tunnel { + t["status"] = json!(status); + t["connections"] = json!(colos.iter().map(|c| json!({ "colo_name": c, "client_id": "c1", "client_version": "2026.10.7", "opened_at": "2026-11-22T00:00:00Z", "origin_ip": "203.0.113.7" })).collect::>()); + } + } + } +} + +/// A uuid-shaped id, as Cloudflare makes for tunnels. +fn uuid(n: u64) -> String { + format!("00000000-0000-4000-8000-{n:012x}") +} + +/// Sign a CSR with a test CA, as Cloudflare's Origin CA does. +fn sign(csr: &str, days: i64) -> Option { + use rcgen::{CertificateParams, CertificateSigningRequestParams, IsCa, Issuer, KeyPair}; + let ca_key = KeyPair::generate().ok()?; + let mut ca = CertificateParams::new(vec![]).ok()?; + ca.is_ca = IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + let issuer = Issuer::new(ca, ca_key); + let mut req = CertificateSigningRequestParams::from_pem(csr).ok()?; + let now = cookie::time::OffsetDateTime::now_utc(); + req.params.not_before = now - cookie::time::Duration::days(1); + req.params.not_after = now + cookie::time::Duration::days(days); + Some(req.signed_by(&issuer).ok()?.pem()) +} + +async fn handle( + State(s): State>>, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + let mut a = s.lock().unwrap(); + let path = uri.path().trim_start_matches("/client/v4").to_owned(); + a.calls.push(format!("{method} {path}")); + let bearer = headers + .get("authorization") + .and_then(|h| h.to_str().ok()) + .and_then(|h| h.strip_prefix("Bearer ")) + .unwrap_or(""); + if bearer != a.token { + return err(StatusCode::FORBIDDEN, "Authentication error"); + } + let body: Value = serde_json::from_slice(&body).unwrap_or(Value::Null); + let seg: Vec<&str> = path.trim_matches('/').split('/').collect(); + let m = method.as_str(); + a.next += 1; + let n = a.next; + match (m, seg.as_slice()) { + ("GET", ["zones"]) => ok(json!(a + .zones + .iter() + .map(|(i, n, ai, an)| json!({ "id": i, "name": n, "account": { "id": ai, "name": an } })) + .collect::>())), + ("GET", ["zones", zone, "dns_records"]) => { + let name = query(&uri, "name"); + ok(json!(a + .records + .iter() + .filter(|(z, r)| z == zone && name.as_deref().is_none_or(|n| r["name"] == n)) + .map(|(_, r)| r.clone()) + .collect::>())) + } + ("POST", ["zones", zone, "dns_records"]) => { + let mut r = body.clone(); + r["id"] = json!(format!("{n:032x}")); + if r.get("ttl").is_none() { + r["ttl"] = json!(1); + } + a.records.push((zone.to_string(), r.clone())); + ok(r) + } + ("GET" | "PATCH" | "DELETE", ["zones", zone, "dns_records", id]) => { + let Some(i) = a.records.iter().position(|(z, r)| z == zone && r["id"] == *id) else { + return err(StatusCode::NOT_FOUND, "Record not found"); + }; + match m { + "GET" => ok(a.records[i].1.clone()), + "PATCH" => { + if let Some(o) = body.as_object() { + for (k, v) in o { + a.records[i].1[k] = v.clone(); + } + } + ok(a.records[i].1.clone()) + } + _ => { + a.records.remove(i); + ok(json!({ "id": id })) + } + } + } + (_, ["accounts", account, "cfd_tunnel", ..]) if a.no_tunnels.iter().any(|x| x == account) => { + err(StatusCode::FORBIDDEN, "Authentication error") + } + ("GET", ["accounts", account, "cfd_tunnel"]) => { + let name = query(&uri, "name").unwrap_or_default(); + ok(json!(a + .tunnels + .iter() + .filter(|(ac, t)| ac == account && t["name"].as_str().unwrap_or("").starts_with(&name) && t["deleted_at"].is_null()) + .map(|(_, t)| t.clone()) + .collect::>())) + } + ("POST", ["accounts", account, "cfd_tunnel"]) => { + let t = json!({ "id": uuid(n), "name": body["name"], "status": "inactive", "created_at": jiff::Timestamp::now().to_string(), "deleted_at": null, "connections": [], "secret": "first" }); + a.tunnels.push((account.to_string(), t.clone())); + ok(t) + } + (_, ["accounts", account, "cfd_tunnel", id, rest @ ..]) => { + let Some(i) = a.tunnels.iter().position(|(ac, t)| ac == account && t["id"] == *id) else { + return err(StatusCode::NOT_FOUND, "Tunnel not found"); + }; + match (m, rest) { + ("GET", []) => ok(a.tunnels[i].1.clone()), + ("PATCH", []) => { + a.tunnels[i].1["secret"] = body["tunnel_secret"].clone(); + ok(a.tunnels[i].1.clone()) + } + ("DELETE", []) => { + if a.tunnels[i].1["connections"].as_array().is_some_and(|c| !c.is_empty()) { + return err(StatusCode::BAD_REQUEST, "Cannot delete tunnel because it has active connections"); + } + a.tunnels[i].1["deleted_at"] = json!("2026-11-22T00:00:00Z"); + ok(a.tunnels[i].1.clone()) + } + ("GET", ["token"]) => { + let secret = a.tunnels[i].1["secret"].as_str().unwrap_or("").to_owned(); + ok(json!(format!("eyJ{id}{secret}"))) + } + ("PUT", ["configurations"]) => { + let id = id.to_string(); + let v = a.configs.iter().find(|c| c.0 == id).map_or(1, |c| c.1 + 1); + a.configs.retain(|c| c.0 != id); + a.configs.push((id.clone(), v, body["config"].clone())); + ok(json!({ "tunnel_id": id, "version": v, "config": body["config"] })) + } + ("GET", ["configurations"]) => { + let c = a.configs.iter().find(|c| c.0 == *id).cloned(); + ok(c.map_or(json!({ "version": 0, "config": null }), |c| json!({ "version": c.1, "config": c.2 }))) + } + ("DELETE", ["connections"]) => { + a.tunnels[i].1["connections"] = json!([]); + a.tunnels[i].1["status"] = json!("inactive"); + ok(json!(null)) + } + _ => err(StatusCode::NOT_FOUND, "No route"), + } + } + ("GET", ["certificates"]) => ok(json!([])), + ("POST", ["certificates"]) => { + let hosts: Vec = body["hostnames"] + .as_array() + .into_iter() + .flatten() + .filter_map(|h| h.as_str().map(str::to_owned)) + .collect(); + let days = body["requested_validity"].as_i64().unwrap_or(365); + let Some(pem) = sign(body["csr"].as_str().unwrap_or(""), days) else { + return err(StatusCode::BAD_REQUEST, "Invalid CSR"); + }; + let id = format!("{}", 100_000 + n); + a.certs.push((id.clone(), hosts.clone(), false)); + ok(json!({ "id": id, "certificate": pem, "hostnames": hosts, "request_type": body["request_type"] })) + } + ("DELETE", ["certificates", id]) => match a.certs.iter_mut().find(|c| c.0 == *id) { + Some(c) => { + c.2 = true; + ok(json!({ "id": id })) + } + None => err(StatusCode::NOT_FOUND, "Certificate not found"), + }, + _ => err(StatusCode::NOT_FOUND, "No route"), + } +} diff --git a/crates/pyo-api/src/cloudflare/http_tests.rs b/crates/pyo-api/src/cloudflare/http_tests.rs new file mode 100644 index 00000000..a6dc16d3 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/http_tests.rs @@ -0,0 +1,338 @@ +//! The real client against the fake Cloudflare API (fake.rs): what Pyo +//! sends and reads over HTTP for a tunnel, start to end. And, against a +//! throwaway Postgres, the whole tunnel loop: a cluster's tunnel made, a +//! domain switched (both paths, then only the tunnel), switched back, a +//! deleted service's record cleaned up, and the tunnel removed in order. + +use serde_json::{Value, json}; + +use super::fake::FakeCf; +use super::tunnel::{self, TunnelApi}; +use super::tunnel_loop::{Switched, ensure_tunnel, issue, revert_record, switch_record}; +use super::*; + +const TOKEN: &str = "fake-token-0123456789abcdef"; +const MARK: &str = "Made by Pyo (abc123)"; +const INSTALL: &str = "abc123"; +const ZONE: &str = "023e105f4ecef8ad9ca31a8372d0c353"; +const ACCOUNT: &str = "699d98642c564d2e855e9661899b7252"; + +async fn fake() -> (FakeCf, Http) { + let cf = FakeCf::start(TOKEN, &[(ZONE, "example.com", ACCOUNT)]).await; + let http = Http::at(TOKEN, &cf.base); + (cf, http) +} + +#[tokio::test] +async fn a_token_is_checked_over_http() { + let (cf, http) = fake().await; + let zones = inspect(&http, INSTALL).await.unwrap(); + assert_eq!(zones.len(), 1); + assert_eq!(zones[0].account_id, ACCOUNT); + assert_eq!(zones[0].account_name, format!("{ACCOUNT} Co")); + assert!(zones[0].tunnel_ready(), "{zones:?}"); + // The probes leave nothing behind. + assert!(cf.records(ZONE).is_empty()); + assert!(cf.tunnels().iter().all(|t| !t["deleted_at"].is_null())); + // Without tunnel permission in the account: DNS only there. + cf.state.lock().unwrap().no_tunnels = vec![ACCOUNT.into()]; + let zones = inspect(&http, INSTALL).await.unwrap(); + assert!(!zones[0].tunnel_ready()); + assert_eq!(zones[0].tunnel.missing, [tunnel::TUNNEL_EDIT]); + // A wrong token: refused, said plainly. + let wrong = Http::at("another-token-0123456789", &cf.base); + assert!(matches!(inspect(&wrong, INSTALL).await, Err(CfError::Denied(_)))); +} + +#[tokio::test] +async fn a_check_deletes_only_this_installations_old_probes() { + let (cf, http) = fake().await; + // Another installation's probe, someone's own tunnel, this + // installation's probe from a check that stopped halfway, and one from + // a check running right now. + cf.put_tunnel(ACCOUNT, "pyo-check-zzz999-a1b2c3", 60); + cf.put_tunnel(ACCOUNT, "pyo-check-mine", 60); + cf.put_tunnel(ACCOUNT, "pyo-check-abc123-a1b2c3", 60); + cf.put_tunnel(ACCOUNT, "pyo-check-abc123-d4e5f6", 0); + let zones = inspect(&http, INSTALL).await.unwrap(); + assert!(zones[0].tunnel_ready(), "{zones:?}"); + let gone = |name: &str| { + cf.tunnels() + .iter() + .any(|t| t["name"] == name && !t["deleted_at"].is_null()) + }; + assert!(!gone("pyo-check-zzz999-a1b2c3")); + assert!(!gone("pyo-check-mine")); + assert!(gone("pyo-check-abc123-a1b2c3")); + assert!(!gone("pyo-check-abc123-d4e5f6")); + // The check's own probe is named for this installation and is gone. + let ts = cf.tunnels(); + assert_eq!(ts.len(), 5); + let own = ts[4]["name"].as_str().unwrap(); + assert!(own.starts_with("pyo-check-abc123-") && own.len() == 23, "{own}"); + assert!(!ts[4]["deleted_at"].is_null()); + // It only ever listed its own probes. + assert!( + cf.calls() + .iter() + .filter(|c| c.starts_with("DELETE ")) + .count() + == 3 + ); +} + +#[tokio::test] +async fn a_tunnel_runs_its_course_over_http() { + let (cf, http) = fake().await; + let row = tunnel_loop::Row { + cluster_id: "cl_1".into(), + team_id: "team_1".into(), + account_id: ACCOUNT.into(), + ..Default::default() + }; + // Made, with routes and a token for the agent. + let (t, _) = ensure_tunnel(&http, &row, "abc123").await.unwrap(); + assert_eq!(t.name, "pyo-cl_1-abc123"); + let config = tunnel::ingress(&["blog.example.com".into()]); + assert_eq!(http.put_config(ACCOUNT, &t.id, &config).await.unwrap(), 1); + assert_eq!(http.config(ACCOUNT, &t.id).await.unwrap(), (1, config)); + let token = http.tunnel_token(ACCOUNT, &t.id).await.unwrap(); + assert!(token.starts_with("eyJ")); + // Its certificate, issued for a CSR made here, reads as a certificate. + let names = tunnel::cert_names(&[("blog.example.com".into(), "example.com".into())], Some("example.com")).unwrap(); + let (cert, key) = issue(&http, &names).await.unwrap(); + let parsed = crate::certs::parse(&cert.pem, &key, pyo_proto::now_ms() / 1000).expect("a certificate Pyo can use"); + assert!(parsed.hostnames.contains(&"*.example.com".to_owned())); + assert!(parsed.not_after - parsed.not_before > 5000 * 86_400, "15 years"); + // A record by hand is in the way: asked first, then replaced and kept. + cf.put_record(ZONE, json!({ "id": "a1", "type": "A", "name": "blog.example.com", "content": "198.51.100.9", "proxied": true, "ttl": 300, "comment": "by hand" })); + let target = tunnel::cname_target(&t.id); + let out = switch_record(&http, ZONE, "blog.example.com", &target, false, MARK).await.unwrap(); + assert!(matches!(out, Switched::Confirm(ref r) if r[0].content == "198.51.100.9")); + let Switched::Done { record, previous } = switch_record(&http, ZONE, "blog.example.com", &target, true, MARK).await.unwrap() else { + panic!("not switched") + }; + assert_eq!(record.kind, "CNAME"); + assert!(record.proxied); + let now = cf.records(ZONE); + assert_eq!(now.len(), 1); + assert_eq!(now[0]["content"], json!(target)); + // Back exactly as it was. + revert_record(&http, ZONE, "blog.example.com", Some(&record.id), &previous, None, MARK).await.unwrap(); + let back = cf.records(ZONE); + assert_eq!(back.len(), 1); + for (k, v) in [("type", json!("A")), ("content", json!("198.51.100.9")), ("proxied", json!(true)), ("ttl", json!(300)), ("comment", json!("by hand"))] { + assert_eq!(back[0][k], v, "{k}"); + } + // Rotated, then taken apart. + http.rotate_secret(ACCOUNT, &t.id, &tunnel::new_secret()).await.unwrap(); + assert_ne!(http.tunnel_token(ACCOUNT, &t.id).await.unwrap(), token); + cf.set_status(&t.id, "healthy", &["FRA", "AMS"]); + let read = http.tunnel(ACCOUNT, &t.id).await.unwrap(); + assert_eq!((read.status.as_str(), read.connections.len()), ("healthy", 2)); + // Connected: Cloudflare refuses to delete it until they're dropped. + assert!(http.delete_tunnel(ACCOUNT, &t.id).await.is_err()); + http.drop_connections(ACCOUNT, &t.id).await.unwrap(); + http.delete_tunnel(ACCOUNT, &t.id).await.unwrap(); + assert!(http.tunnel(ACCOUNT, &t.id).await.unwrap().deleted); + http.revoke_origin_cert(&cert.id).await.unwrap(); + assert!(cf.state.lock().unwrap().certs.iter().all(|c| c.2)); +} + +// ── The whole loop, against a throwaway Postgres ─────────────────────────── + +fn run_big + Send + 'static>(f: F) { + std::thread::Builder::new() + .stack_size(64 << 20) + .spawn(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + .block_on(f) + }) + .unwrap() + .join() + .unwrap(); +} + +/// The domain as its service has it now. +async fn domain(db: &sqlx::PgPool, service: &str) -> Value { + sqlx::query_scalar("SELECT spec->'domains'->0 FROM pyo.services WHERE id = $1") + .bind(service) + .fetch_one(db) + .await + .unwrap() +} + +/// What the agent was sent, last first. +async fn commands(db: &sqlx::PgPool, cluster: &str) -> Vec { + sqlx::query_scalar("SELECT command->>'kind' FROM pyo.commands WHERE cluster_id = $1 ORDER BY created_at DESC") + .bind(cluster) + .fetch_all(db) + .await + .unwrap() +} + +/// Against a throwaway Postgres and the fake Cloudflare: a cluster in +/// tunnel mode gets its tunnel, routes, certificate and the agent's token; +/// a domain switches with both paths first and only the tunnel once its +/// record moved, goes back with the record it replaced, a deleted +/// service's record is cleaned up, and the tunnel is taken apart. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn the_tunnel_loop_end_to_end() { + run_big(async { + let cf = FakeCf::start(TOKEN, &[(ZONE, "example.com", ACCOUNT)]).await; + // SAFETY: set before anything here reads them; this test owns its runtime. + unsafe { + std::env::set_var("PYO_DEV_CLOUDFLARE_API", &cf.base); + if std::env::var("PYO_SECRET_KEY").is_err() { + std::env::set_var("PYO_SECRET_KEY", "11".repeat(32)); + } + } + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL")) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + crate::vault::init(crate::vault::Vault::new(db.clone(), crate::vault::Provider::from_env())); + let s = crate::rls::tests::state(db.clone()); + let run = crate::ids::random_string(8).to_lowercase(); + let (team, cluster, project, svc, dpl) = ( + format!("team_tun{run}"), + format!("cl_tun{run}"), + format!("prj_tun{run}"), + format!("svc_tun{run}"), + format!("dpl_tun{run}"), + ); + let host = format!("blog-{run}.example.com"); + let q = |sql: &'static str| sqlx::query(sql); + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)").bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash, status, last_seen_at, traffic, capabilities) + VALUES ($1, $2, $1, $1, 'connected', now(), 'tunnel', '{\"tunnel\": true, \"agentInstall\": {\"state\": \"current\"}}')") + .bind(&cluster).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, 'shop', $1)").bind(&project).bind(&team).execute(&db).await.unwrap(); + let domains = json!([{ "id": "dom_1", "hostname": host, "portName": "http", "tlsMode": "auto", "tunnel": "switching", "status": "pending_dns" }]); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web', jsonb_build_object('domains', $5::jsonb), 'running')") + .bind(&svc).bind(&team).bind(&project).bind(&cluster).bind(&domains).execute(&db).await.unwrap(); + let service = pyo_proto::ServiceRef { service_id: svc.clone(), name: "web".into(), namespace: project.clone(), workload_kind: "Deployment".into() }; + let spec = json!({ "service": service, "projectId": project, "ports": [{ "name": "http", "containerPort": 80, "protocol": "HTTP", "exposure": "http", "publicPort": null }] }); + q("INSERT INTO pyo.deployments (id, team_id, project_id, service_id, cluster_id, status, data, spec) VALUES ($1, $2, $3, $4, $5, 'running', '{}', $6)") + .bind(&dpl).bind(&team).bind(&project).bind(&svc).bind(&cluster).bind(&spec).execute(&db).await.unwrap(); + q("UPDATE pyo.services SET current_deployment_id = $2 WHERE id = $1").bind(&svc).bind(&dpl).execute(&db).await.unwrap(); + // The team's Cloudflare, as connecting it leaves it. + let zones = json!([{ "id": ZONE, "name": "example.com", "canEdit": true, "accountId": ACCOUNT, "accountName": "Acme", "tunnel": { "ready": true } }]); + let sealed = crate::vault::get().seal_credential(&team, TOKEN).await.unwrap(); + q("INSERT INTO pyo.cloudflare_accounts (team_id, token_sealed, zones) VALUES ($1, $2, $3)").bind(&team).bind(&sealed).bind(&zones).execute(&db).await.unwrap(); + // Someone's record on the name, then the tunnel and the switch asked for. + cf.put_record(ZONE, json!({ "id": format!("hand{run}"), "type": "A", "name": host, "content": "198.51.100.9", "proxied": false, "ttl": 300 })); + q("INSERT INTO pyo.cluster_tunnels (cluster_id, team_id, account_id, tunnel_name) VALUES ($1, $2, $3, 'pending')") + .bind(&cluster).bind(&team).bind(ACCOUNT).execute(&db).await.unwrap(); + q("INSERT INTO pyo.dns_records (service_id, domain_id, team_id, hostname, zone_id, zone_name, type, status) VALUES ($1, 'dom_1', $2, $3, $4, 'example.com', 'CNAME', 'switching')") + .bind(&svc).bind(&team).bind(&host).bind(ZONE).execute(&db).await.unwrap(); + let record = |db: sqlx::PgPool, svc: String| async move { + sqlx::query_as::<_, (String, String, Value)>("SELECT status, via, previous FROM pyo.dns_records WHERE service_id = $1") + .bind(svc) + .fetch_optional(&db) + .await + .unwrap() + }; + + // A pass: the tunnel, its routes and certificate; the record waits for a yes. + tunnel_loop::pass(&s).await.unwrap(); + let tunnel_id: String = sqlx::query_scalar("SELECT tunnel_id FROM pyo.cluster_tunnels WHERE cluster_id = $1").bind(&cluster).fetch_one(&db).await.unwrap(); + let config = cf.state.lock().unwrap().configs.iter().find(|c| c.0 == tunnel_id).map(|c| c.2.clone()).expect("routes"); + assert_eq!(config["ingress"][0]["hostname"], json!(host)); + let d = domain(&db, &svc).await; + assert_eq!((d["tlsMode"].as_str(), d["tunnel"].as_str()), (Some("custom"), Some("switching")), "the tunnel's certificate before its record moves: {d}"); + assert!(commands(&db, &cluster).await.contains(&"tunnel_set".to_owned()), "the agent's token"); + // The record waits for the agent's routes (both paths answer first). + assert_eq!(record(db.clone(), svc.clone()).await.unwrap().0, "switching"); + let agent_done = |db: sqlx::PgPool, cluster: String| async move { + sqlx::query("UPDATE pyo.commands SET status = 'done' WHERE cluster_id = $1") + .bind(cluster) + .execute(&db) + .await + .unwrap(); + }; + agent_done(db.clone(), cluster.clone()).await; + tunnel_loop::pass(&s).await.unwrap(); + let (status, via, _) = record(db.clone(), svc.clone()).await.unwrap(); + assert_eq!((status.as_str(), via.as_str()), ("conflict", "direct")); + assert_eq!(cf.records(ZONE).len(), 1, "someone's record, untouched"); + + // Replace and switch: kept, then only through the tunnel. + q("UPDATE pyo.dns_records SET status = 'switching', replace = true WHERE service_id = $1").bind(&svc).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + let (status, via, previous) = record(db.clone(), svc.clone()).await.unwrap(); + assert_eq!((status.as_str(), via.as_str()), ("created", "tunnel")); + assert_eq!(previous[0]["content"], "198.51.100.9"); + assert_eq!(domain(&db, &svc).await["tunnel"], "on"); + let now = cf.records(ZONE); + assert_eq!(now.len(), 1); + assert_eq!(now[0]["content"], json!(tunnel::cname_target(&tunnel_id))); + + // Switch back with the kept record: both paths first, then it's back. + q("UPDATE pyo.dns_records SET status = 'reverting', restore = true, routes_command = NULL WHERE service_id = $1").bind(&svc).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + assert!(record(db.clone(), svc.clone()).await.is_none()); + let d = domain(&db, &svc).await; + assert!(d.get("tunnel").is_none() && d["tlsMode"] == "auto", "{d}"); + let back = cf.records(ZONE); + assert_eq!((back.len(), back[0]["content"].as_str(), back[0]["ttl"].as_i64()), (1, Some("198.51.100.9"), Some(300))); + + // Switched again, then the service deleted: its CNAME goes with it. + cf.state.lock().unwrap().records.clear(); + q("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains,0,tunnel}', '\"switching\"') WHERE id = $1").bind(&svc).execute(&db).await.unwrap(); + q("INSERT INTO pyo.dns_records (service_id, domain_id, team_id, hostname, zone_id, zone_name, type, status) VALUES ($1, 'dom_1', $2, $3, $4, 'example.com', 'CNAME', 'switching')") + .bind(&svc).bind(&team).bind(&host).bind(ZONE).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + agent_done(db.clone(), cluster.clone()).await; + tunnel_loop::pass(&s).await.unwrap(); + assert_eq!(cf.records(ZONE).len(), 1); + q("DELETE FROM pyo.services WHERE id = $1").bind(&svc).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + assert!(cf.records(ZONE).is_empty(), "a deleted service's tunnel record goes"); + + // A default domain: its wildcard record, and a free name under it + // goes only through the tunnel, active once the wildcard is there. + let free = format!("web-{run}.example.com"); + let svc2 = format!("svc_tunf{run}"); + let domains = json!([{ "id": "dom_2", "hostname": free, "portName": "http", "tlsMode": "auto", "status": "pending_dns" }]); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web2', jsonb_build_object('domains', $5::jsonb), 'running')") + .bind(&svc2).bind(&team).bind(&project).bind(&cluster).bind(&domains).execute(&db).await.unwrap(); + q("UPDATE pyo.cluster_tunnels SET default_domain = 'example.com', default_zone_id = $2 WHERE cluster_id = $1") + .bind(&cluster).bind(ZONE).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + let wildcard: Vec = cf.records(ZONE).into_iter().filter(|r| r["name"] == "*.example.com").collect(); + assert_eq!(wildcard.len(), 1); + assert_eq!(wildcard[0]["content"], json!(tunnel::cname_target(&tunnel_id))); + let d = domain(&db, &svc2).await; + assert_eq!((d["tunnel"].as_str(), d["status"].as_str()), (Some("on"), Some("active")), "{d}"); + let config = cf.state.lock().unwrap().configs.iter().find(|c| c.0 == tunnel_id).map(|c| c.2.clone()).unwrap(); + let hosts: Vec = config["ingress"].as_array().unwrap().iter().map(|r| r["hostname"].clone()).collect(); + // The free name is routed by name. The wildcard record has no + // wildcard route: any other name gets the tunnel's own 404. + assert_eq!(hosts, [json!(free), Value::Null]); + // The free name has no record of its own: the wildcard covers it. + assert!(cf.records(ZONE).iter().all(|r| r["name"] != json!(free))); + + // Removed: no routes but the catch-all, the tunnel deleted, its certificate revoked. + q("UPDATE pyo.clusters SET traffic = 'public' WHERE id = $1").bind(&cluster).execute(&db).await.unwrap(); + q("UPDATE pyo.cluster_tunnels SET state = 'removing', agent_status = '{}' WHERE cluster_id = $1").bind(&cluster).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + let left: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.cluster_tunnels WHERE cluster_id = $1").bind(&cluster).fetch_one(&db).await.unwrap(); + assert_eq!(left, 0); + let t = cf.tunnels().into_iter().find(|t| t["id"] == json!(tunnel_id)).unwrap(); + assert!(!t["deleted_at"].is_null()); + assert!(cf.state.lock().unwrap().certs.iter().all(|c| c.2), "revoked"); + let calls = cf.calls(); + let at = |c: &str| calls.iter().rposition(|x| x.starts_with(c)).unwrap(); + assert!(at("PUT /accounts") < at("DELETE /accounts"), "routes emptied before the tunnel goes: {calls:?}"); + assert!(cf.records(ZONE).is_empty(), "Pyo's wildcard record goes too"); + let leftovers: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.tunnel_leftovers WHERE team_id = $1").bind(&team).fetch_one(&db).await.unwrap(); + assert_eq!(leftovers, 0); + q("DELETE FROM pyo.teams WHERE id = $1").bind(&team).execute(&db).await.unwrap(); + }); +} diff --git a/crates/pyo-api/src/cloudflare/tests.rs b/crates/pyo-api/src/cloudflare/tests.rs index 6fa01d07..7bf7e1fc 100644 --- a/crates/pyo-api/src/cloudflare/tests.rs +++ b/crates/pyo-api/src/cloudflare/tests.rs @@ -2,22 +2,31 @@ //! only Pyo's own, who may do what, and the HTTP client's handling of //! Cloudflare's answers. Cloudflare itself is a fake account. -use std::sync::Mutex; +use std::{collections::HashMap, sync::Mutex}; +use super::tunnel::{CfZone, Connection, Kept, OriginCert, Tunnel}; use super::*; -const MARK: &str = "Made by Pyo (abc123)"; +pub(super) const MARK: &str = "Made by Pyo (abc123)"; +/// The installation [`MARK`] is the comment of. +pub(super) const INSTALL: &str = "abc123"; -fn zone(id: &str, name: &str) -> Zone { +pub(super) fn zone(id: &str, name: &str) -> Zone { Zone { id: id.into(), name: name.into(), can_edit: true, missing: None, + account_id: "acct1".into(), + account_name: "Acme".into(), + tunnel: TunnelAccess { + ready: true, + missing: vec![], + }, } } -fn rec(id: &str, kind: &str, name: &str, content: &str, comment: Option<&str>) -> Record { +pub(super) fn rec(id: &str, kind: &str, name: &str, content: &str, comment: Option<&str>) -> Record { Record { id: id.into(), kind: kind.into(), @@ -29,24 +38,40 @@ fn rec(id: &str, kind: &str, name: &str, content: &str, comment: Option<&str>) - } #[derive(Clone, Copy, PartialEq)] -enum Dns { +pub(super) enum Dns { None, Read, Edit, } -/// A Cloudflare account: zones, the token's DNS permission in each, and -/// every call made. -struct Fake { - zones: Vec<(String, String, Dns)>, - zone_read: bool, - records: Mutex>, - calls: Mutex>, +/// A Cloudflare account: zones, the token's DNS permission in each, its +/// tunnels and Origin CA certificates, and every call made. +pub(super) struct Fake { + pub zones: Vec<(String, String, Dns)>, + pub zone_read: bool, + pub records: Mutex>, + /// Records' TTLs, by id (1, automatic, when not set). + pub ttls: Mutex>, + pub calls: Mutex>, next: Mutex, + /// Each zone's account (acct1 "Acme" when not set). + pub accounts: HashMap, + /// Accounts where the token can't make tunnels. + pub no_tunnels: Vec, + /// Zones whose Origin CA certificates the token can't read or issue. + pub no_certs: Vec, + /// (account, tunnel). + pub tunnels: Mutex>, + /// Each tunnel's routes: (version, config). + pub configs: Mutex>, + /// Each tunnel's secret. + pub secrets: Mutex>, + /// Issued Origin CA certificates: (id, names, revoked). + pub certs: Mutex, bool)>>, } impl Fake { - fn new(zones: &[(&str, &str, Dns)]) -> Self { + pub fn new(zones: &[(&str, &str, Dns)]) -> Self { Self { zones: zones .iter() @@ -54,17 +79,73 @@ impl Fake { .collect(), zone_read: true, records: Mutex::new(vec![]), + ttls: Mutex::new(HashMap::new()), calls: Mutex::new(vec![]), next: Mutex::new(0), + accounts: HashMap::new(), + no_tunnels: vec![], + no_certs: vec![], + tunnels: Mutex::new(vec![]), + configs: Mutex::new(HashMap::new()), + secrets: Mutex::new(HashMap::new()), + certs: Mutex::new(vec![]), } } - fn with(self, zone: &str, r: Record) -> Self { + pub fn with(self, zone: &str, r: Record) -> Self { self.records.lock().unwrap().push((zone.into(), r)); self } - fn dns(&self, zone: &str) -> Dns { + pub fn account_of(&self, zone: &str) -> (String, String) { + self.accounts + .get(zone) + .cloned() + .unwrap_or_else(|| ("acct1".into(), "Acme".into())) + } + + fn id(&self, prefix: &str) -> String { + let mut n = self.next.lock().unwrap(); + *n += 1; + format!("{prefix}{n}") + } + + /// A tunnel id as Cloudflare makes them (a UUID). + fn uuid(&self) -> String { + let n = self.id(""); + format!("00000000-0000-4000-8000-{:0>12}", n) + } + + pub fn tunnel_list(&self) -> Vec { + self.tunnels + .lock() + .unwrap() + .iter() + .map(|(_, t)| t.clone()) + .collect() + } + + /// Set a tunnel's status and connections, as Cloudflare reports them. + pub fn connect(&self, id: &str, status: &str, colos: &[&str]) { + for (_, t) in self.tunnels.lock().unwrap().iter_mut() { + if t.id == id { + t.status = status.into(); + t.connections = colos + .iter() + .enumerate() + .map(|(i, c)| Connection { + client_id: format!("c{}", i / 2), + colo: (*c).into(), + client_version: "2026.10.7".into(), + opened_at: "2026-11-22T00:00:00Z".into(), + origin_ip: "203.0.113.7".into(), + }) + .collect(); + } + } + } + + pub fn dns(&self, zone: &str) -> Dns { self.zones .iter() .find(|z| z.0 == zone) @@ -72,15 +153,15 @@ impl Fake { .unwrap_or(Dns::None) } - fn log(&self, c: String) { + pub fn log(&self, c: String) { self.calls.lock().unwrap().push(c); } - fn calls(&self) -> Vec { + pub fn calls(&self) -> Vec { self.calls.lock().unwrap().clone() } - fn at(&self, zone: &str) -> Vec { + pub fn at(&self, zone: &str) -> Vec { self.records .lock() .unwrap() @@ -95,8 +176,8 @@ impl Fake { } } -impl Cloudflare for Fake { - async fn zones(&self) -> Result, CfError> { +impl Fake { + fn zone_list(&self) -> Result, CfError> { self.log("zones".into()); if !self.zone_read { return Err(Self::denied()); @@ -107,7 +188,9 @@ impl Cloudflare for Fake { .map(|z| (z.0.clone(), z.1.clone())) .collect()) } +} +impl Cloudflare for Fake { async fn records(&self, zone_id: &str, name: &str) -> Result, CfError> { self.log(format!("list {zone_id} {name}")); if self.dns(zone_id) == Dns::None { @@ -136,10 +219,8 @@ impl Cloudflare for Fake { if self.dns(zone_id) != Dns::Edit { return Err(Self::denied()); } - let mut n = self.next.lock().unwrap(); - *n += 1; let made = Record { - id: format!("r{n}"), + id: self.id("r"), kind: r.kind.clone(), name: r.name.clone(), content: r.content.clone(), @@ -218,7 +299,7 @@ async fn a_test_lists_zones_and_says_what_is_missing() { ("z2", "readonly.dev", Dns::Read), ("z3", "nodns.io", Dns::None), ]); - let zones = inspect(&cf, MARK).await.unwrap(); + let zones = inspect(&cf, INSTALL).await.unwrap(); let got: Vec<(&str, bool, Option<&str>)> = zones .iter() .map(|z| (z.name.as_str(), z.can_edit, z.missing.as_deref())) @@ -242,7 +323,7 @@ async fn a_test_lists_zones_and_says_what_is_missing() { assert!(cf.at("z1").is_empty()); assert!( cf.calls() - .contains(&"create z1 TXT _pyo-check.example.com \"pyo-check\"".to_string()) + .contains(&"create z1 TXT _pyo-check.example.com \"pyo-check-abc123\"".to_string()) ); } @@ -250,11 +331,11 @@ async fn a_test_lists_zones_and_says_what_is_missing() { async fn a_token_without_zone_read_is_refused() { let mut cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); cf.zone_read = false; - let e = inspect(&cf, MARK).await.unwrap_err(); + let e = inspect(&cf, INSTALL).await.unwrap_err(); assert!(matches!(e, CfError::Denied(_))); assert!(e.to_string().starts_with("Cloudflare refused the token")); let none = Fake::new(&[]); - let zones = inspect(&none, MARK).await.unwrap(); + let zones = inspect(&none, INSTALL).await.unwrap(); assert_eq!( problems(&zones), ["The token can't see any zones. Give it Zone:Read on the zones Pyo may use."] @@ -269,14 +350,37 @@ async fn a_probe_left_behind_is_cleaned_up() { "old", "TXT", "_pyo-check.example.com", - "\"pyo-check\"", + "\"pyo-check-abc123\"", Some(MARK), ), ); - inspect(&cf, MARK).await.unwrap(); + inspect(&cf, INSTALL).await.unwrap(); assert!(cf.at("z1").is_empty()); } +#[tokio::test] +async fn another_installations_probe_record_is_left_alone() { + // Two installations share the zone. The other one's check stopped + // halfway and left its probe: this one's check still passes (its own + // record's text differs, so Cloudflare doesn't call it a duplicate), + // and the other's record stays. + let theirs = rec( + "theirs", + "TXT", + "_pyo-check.example.com", + "\"pyo-check-zzz999\"", + Some("Made by Pyo (zzz999)"), + ); + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]).with("z1", theirs.clone()); + let zones = inspect(&cf, INSTALL).await.unwrap(); + assert!(zones[0].can_edit); + assert_eq!(cf.at("z1"), [theirs]); + assert!( + cf.calls() + .contains(&"create z1 TXT _pyo-check.example.com \"pyo-check-abc123\"".to_string()) + ); +} + // ── Records ──────────────────────────────────────────────────────────────── #[test] @@ -656,3 +760,368 @@ fn reads_cloudflares_answers() { .unwrap(); assert!(!ours(&no_comment, MARK, "a.example.com")); } + +impl tunnel::TunnelApi for Fake { + async fn zone_accounts(&self) -> Result, CfError> { + Ok(self + .zone_list()? + .into_iter() + .map(|(id, name)| { + let (account_id, account_name) = self.account_of(&id); + CfZone { + id, + name, + account_id, + account_name, + } + }) + .collect()) + } + + async fn records_kept(&self, zone_id: &str, name: &str) -> Result, CfError> { + let ttls = self.ttls.lock().unwrap().clone(); + Ok(self + .records(zone_id, name) + .await? + .into_iter() + .map(|r| Kept { + ttl: ttls.get(&r.id).copied().unwrap_or(1), + id: r.id, + kind: r.kind, + name: r.name, + content: r.content, + proxied: r.proxied, + comment: r.comment, + }) + .collect()) + } + + async fn create_kept(&self, zone_id: &str, r: &Kept) -> Result { + self.log(format!( + "create {zone_id} {} {} {}", + r.kind, r.name, r.content + )); + if self.dns(zone_id) != Dns::Edit { + return Err(Self::denied()); + } + let made = Record { + id: self.id("r"), + ..r.record() + }; + self.ttls.lock().unwrap().insert(made.id.clone(), r.ttl); + self.records + .lock() + .unwrap() + .push((zone_id.into(), made.clone())); + Ok(made) + } + + async fn tunnels_named(&self, account: &str, name: &str) -> Result, CfError> { + self.log(format!("tunnels {account} {name}")); + if self.no_tunnels.iter().any(|a| a == account) { + return Err(Self::denied()); + } + Ok(self + .tunnels + .lock() + .unwrap() + .iter() + .filter(|(a, t)| a == account && t.name.starts_with(name) && !t.deleted) + .map(|(_, t)| t.clone()) + .collect()) + } + + async fn create_tunnel(&self, account: &str, name: &str) -> Result { + self.log(format!("create tunnel {account} {name}")); + if self.no_tunnels.iter().any(|a| a == account) { + return Err(Self::denied()); + } + let t = Tunnel { + id: self.uuid(), + name: name.into(), + status: "inactive".into(), + created_at: jiff::Timestamp::now().to_string(), + ..Default::default() + }; + self.tunnels + .lock() + .unwrap() + .push((account.into(), t.clone())); + self.secrets + .lock() + .unwrap() + .insert(t.id.clone(), "first".into()); + Ok(t) + } + + async fn tunnel(&self, account: &str, id: &str) -> Result { + self.tunnels + .lock() + .unwrap() + .iter() + .find(|(a, t)| a == account && t.id == id) + .map(|(_, t)| t.clone()) + .ok_or(CfError::NotFound) + } + + async fn delete_tunnel(&self, account: &str, id: &str) -> Result<(), CfError> { + self.log(format!("delete tunnel {id}")); + let mut ts = self.tunnels.lock().unwrap(); + let Some((_, t)) = ts.iter_mut().find(|(a, t)| a == account && t.id == id) else { + return Err(CfError::NotFound); + }; + if !t.connections.is_empty() { + return Err(CfError::Refused( + "Cannot delete tunnel because it has active connections".into(), + )); + } + t.deleted = true; + Ok(()) + } + + async fn tunnel_token(&self, account: &str, id: &str) -> Result { + self.tunnel(account, id).await?; + let secret = self + .secrets + .lock() + .unwrap() + .get(id) + .cloned() + .unwrap_or_default(); + Ok(format!("token-{id}-{secret}")) + } + + async fn put_config(&self, account: &str, id: &str, config: &Value) -> Result { + self.log(format!("put config {id}")); + self.tunnel(account, id).await?; + let mut cs = self.configs.lock().unwrap(); + let v = cs.get(id).map_or(1, |(v, _)| v + 1); + cs.insert(id.into(), (v, config.clone())); + Ok(v) + } + + async fn config(&self, account: &str, id: &str) -> Result<(i64, Value), CfError> { + self.tunnel(account, id).await?; + Ok(self + .configs + .lock() + .unwrap() + .get(id) + .cloned() + .unwrap_or((0, Value::Null))) + } + + async fn rotate_secret(&self, account: &str, id: &str, secret: &str) -> Result<(), CfError> { + self.log(format!("rotate {id}")); + self.tunnel(account, id).await?; + self.secrets + .lock() + .unwrap() + .insert(id.into(), secret.into()); + Ok(()) + } + + async fn drop_connections(&self, account: &str, id: &str) -> Result<(), CfError> { + self.log(format!("drop connections {id}")); + self.tunnel(account, id).await?; + self.connect(id, "inactive", &[]); + Ok(()) + } + + async fn origin_certs(&self, zone_id: &str) -> Result, CfError> { + if self.no_certs.iter().any(|z| z == zone_id) { + return Err(Self::denied()); + } + Ok(vec![]) + } + + async fn issue_origin_cert( + &self, + csr_pem: &str, + hostnames: &[String], + ) -> Result { + self.log(format!("issue {}", hostnames.join(","))); + let zone_denied = self.zones.iter().any(|(id, name, _)| { + self.no_certs.contains(id) + && hostnames + .iter() + .any(|h| h.trim_start_matches("*.").ends_with(name.as_str())) + }); + if zone_denied { + return Err(Self::denied()); + } + assert!(csr_pem.contains("CERTIFICATE REQUEST"), "{csr_pem}"); + let id = format!("{}", 1000 + self.certs.lock().unwrap().len()); + self.certs + .lock() + .unwrap() + .push((id.clone(), hostnames.to_vec(), false)); + Ok(OriginCert { + id, + pem: String::new(), + }) + } + + async fn revoke_origin_cert(&self, id: &str) -> Result<(), CfError> { + self.log(format!("revoke {id}")); + for c in self.certs.lock().unwrap().iter_mut() { + if c.0 == id { + c.2 = true; + return Ok(()); + } + } + Err(CfError::NotFound) + } +} + +// ── Tunnel permissions ───────────────────────────────────────────────────── + +#[tokio::test] +async fn a_test_says_which_zones_can_use_a_tunnel() { + let mut cf = Fake::new(&[ + ("z1", "example.com", Dns::Edit), + ("z2", "other.org", Dns::Edit), + ("z3", "certless.dev", Dns::Edit), + ("z4", "readonly.io", Dns::Read), + ]); + cf.accounts + .insert("z2".into(), ("acct2".into(), "Other Co".into())); + cf.no_tunnels = vec!["acct2".into()]; + cf.no_certs = vec!["z2".into(), "z3".into()]; + let zones = inspect(&cf, INSTALL).await.unwrap(); + let got: Vec<(&str, &str, bool, Vec)> = zones + .iter() + .map(|z| { + ( + z.name.as_str(), + z.account_id.as_str(), + z.tunnel_ready(), + z.tunnel.missing.clone(), + ) + }) + .collect(); + assert_eq!( + got, + [ + ("certless.dev", "acct1", false, vec![tunnel::CERTS_EDIT.to_owned()]), + ("example.com", "acct1", true, vec![]), + ( + "other.org", + "acct2", + false, + vec![tunnel::TUNNEL_EDIT.to_owned(), tunnel::CERTS_EDIT.to_owned()] + ), + ("readonly.io", "acct1", false, vec![]), + ] + ); + assert_eq!(zones[1].account_name, "Acme"); + // A zone that can't edit DNS can't be tunnel-ready either. + assert!(!zones[3].tunnel.ready); + // DNS only (neither tunnel permission) is no problem. Half of them is. + assert_eq!( + problems(&zones), + [ + "readonly.io: give the token DNS:Edit.", + "certless.dev: give the token SSL and Certificates:Edit." + ] + ); + // The tunnel check is once per account, and leaves nothing behind. + let checks = cf + .calls() + .iter() + .filter(|c| c.starts_with("create tunnel acct1 pyo-check-abc123-")) + .count(); + assert_eq!(checks, 1); + assert!(cf.tunnel_list().iter().all(|t| t.deleted)); +} + +#[tokio::test] +async fn only_this_installations_old_probe_tunnels_are_deleted() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let old = (jiff::Timestamp::now() - jiff::SignedDuration::from_mins(30)).to_string(); + let now = jiff::Timestamp::now().to_string(); + let put = |n: u32, name: &str, made: &str| { + cf.tunnels.lock().unwrap().push(( + "acct1".into(), + Tunnel { + id: format!("11111111-2222-4333-8444-{n:012}"), + name: name.into(), + created_at: made.into(), + ..Default::default() + }, + )); + }; + put(1, "pyo-check-abc123-a1b2c3", &old); + put(2, "pyo-check-abc123-d4e5f6", &now); + // Another installation's probe, and people's own tunnels: never touched, + // however old. + put(3, "pyo-check-zzz999-a1b2c3", &old); + put(4, "pyo-check-mine", &old); + put(5, "pyo-check-abc123-mine", &old); + put(6, "pyo-check-a1b2c3", &old); + put(7, "home-lab", &old); + // One with a date Pyo can't read stays too. + put(8, "pyo-check-abc123-0a0b0c", ""); + inspect(&cf, INSTALL).await.unwrap(); + let left: Vec = cf + .tunnel_list() + .into_iter() + .filter(|t| !t.deleted) + .map(|t| t.name) + .collect(); + assert_eq!( + left, + [ + "pyo-check-abc123-d4e5f6", + "pyo-check-zzz999-a1b2c3", + "pyo-check-mine", + "pyo-check-abc123-mine", + "pyo-check-a1b2c3", + "home-lab", + "pyo-check-abc123-0a0b0c", + ] + ); +} + +#[test] +fn zones_stored_before_the_tunnel_read_as_dns_only() { + let z: Zone = + serde_json::from_value(json!({ "id": "z1", "name": "example.com", "canEdit": true })).unwrap(); + assert!(!z.tunnel_ready()); + assert_eq!(z.account_id, ""); + let v = serde_json::to_value(zone("z1", "example.com")).unwrap(); + assert_eq!(v["accountId"], "acct1"); + assert_eq!(v["tunnel"], json!({ "ready": true })); +} + +#[test] +fn tunnel_ids_are_uuids_before_they_go_into_paths() { + use tunnel::uuid_ok; + assert!(uuid_ok("c1744f8b-faa1-48a4-9e5c-02ac921467fa")); + assert!(!uuid_ok("c1744f8b-faa1-48a4-9e5c-02ac921467f")); + assert!(!uuid_ok("../../zones/x-faa1-48a4-9e5c-02ac921467fa")); + assert!(!uuid_ok("c1744f8bxfaa1-48a4-9e5c-02ac921467fa")); +} + +#[test] +fn reads_cloudflares_tunnels() { + let t = tunnel::tunnel_from(&json!({ + "id": "c1744f8b-faa1-48a4-9e5c-02ac921467fa", "name": "pyo-cl_1-abc123", + "status": "healthy", "deleted_at": null, "account_tag": "699d98642c564d2e855e9661899b7252", + "connections": [{ + "colo_name": "FRA", "uuid": "1bedc50d-42b3-473c-b108-ff3d10c0d925", "id": "1bedc50d-42b3-473c-b108-ff3d10c0d925", + "is_pending_reconnect": false, "origin_ip": "203.0.113.7", "opened_at": "2026-11-22T10:00:00Z", + "client_id": "1bedc50d-42b3-473c-b108-ff3d10c0d925", "client_version": "2026.10.7", + }], + })) + .unwrap(); + assert_eq!(t.status, "healthy"); + assert!(!t.deleted); + assert_eq!(t.connections[0].colo, "FRA"); + let gone = tunnel::tunnel_from(&json!({ + "id": "c1744f8b-faa1-48a4-9e5c-02ac921467fa", "name": "x", "deleted_at": "2026-11-22T10:00:00Z", + })) + .unwrap(); + assert!(gone.deleted); + assert!(tunnel::tunnel_from(&json!({ "id": "../x" })).is_err()); +} diff --git a/crates/pyo-api/src/cloudflare/tunnel.rs b/crates/pyo-api/src/cloudflare/tunnel.rs new file mode 100644 index 00000000..702602c2 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/tunnel.rs @@ -0,0 +1,733 @@ +//! Cloudflare Tunnel: what Pyo asks of Cloudflare for a cluster's tunnel +//! (docs/cloudflare-tunnel.md §6). The tunnel itself, its routes (remotely +//! managed ingress), its token for the cluster's connector, the Origin CA +//! certificate Pyo Gateway shows cloudflared, and the token checks that say +//! which zones can use a tunnel. +//! +//! Everything goes through [`Http`]'s pinned client to `api.cloudflare.com` +//! only, with the team's token. The token never leaves the control plane: +//! the cluster only ever gets the tunnel's own token. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +use super::{CfError, Http, Record, id_ok}; +use reqwest::Method; + +/// The permission a tunnel needs in the account. +pub const TUNNEL_EDIT: &str = "Cloudflare Tunnel:Edit"; +/// The permission an Origin CA certificate needs in the zone. +pub const CERTS_EDIT: &str = "SSL and Certificates:Edit"; + +/// What a probe tunnel's name starts with, before this installation's id +/// ([`check_prefix`]). Removed right after the check, and one this +/// installation left behind by a check that stopped halfway is removed by +/// a later one. +pub const CHECK_PREFIX: &str = "pyo-check-"; + +/// How old a probe left behind must be before a check removes it, so two +/// checks at once never remove each other's. +pub const CHECK_STALE_SECS: i64 = 300; + +/// How long the Origin CA certificate is valid: 15 years, Cloudflare's +/// longest (decision 2). Never renewed by age. +pub const CERT_DAYS: u32 = 5475; + +/// The most names one Origin CA certificate takes. +pub const MAX_CERT_NAMES: usize = 200; + +/// Where cloudflared sends requests: Pyo's own Service in front of the +/// Gateway's HTTPS listener (`system::TUNNEL_ORIGIN_SERVICE`). +pub const ORIGIN: &str = "https://pyo-tunnel-origin.pyo-gateway.svc.cluster.local:443"; + +/// A zone as Cloudflare lists it, with the account it's in. +#[derive(Debug, Clone, PartialEq)] +pub struct CfZone { + pub id: String, + pub name: String, + pub account_id: String, + pub account_name: String, +} + +/// A tunnel at Cloudflare. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Tunnel { + pub id: String, + pub name: String, + /// "inactive", "degraded", "healthy" or "down". + pub status: String, + /// Deleted at Cloudflare (it stays listed for a while). + pub deleted: bool, + /// When it was made, as Cloudflare says it (RFC 3339). + pub created_at: String, + pub connections: Vec, +} + +/// One of a tunnel's connections to Cloudflare's edge. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + /// The connector it belongs to (one cloudflared runs four). + pub client_id: String, + pub colo: String, + pub client_version: String, + pub opened_at: String, + pub origin_ip: String, +} + +/// A record as it was, kept to be put back (`dns_records.previous`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Kept { + #[serde(default, skip_serializing)] + pub id: String, + #[serde(rename = "type")] + pub kind: String, + pub name: String, + pub content: String, + #[serde(default)] + pub proxied: bool, + #[serde(default = "auto_ttl")] + pub ttl: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub comment: Option, +} + +fn auto_ttl() -> u32 { + 1 +} + +impl Kept { + pub fn record(&self) -> Record { + Record { + id: self.id.clone(), + kind: self.kind.clone(), + name: self.name.clone(), + content: self.content.clone(), + proxied: self.proxied, + comment: self.comment.clone(), + } + } +} + +/// An Origin CA certificate Cloudflare issued. +#[derive(Debug, Clone, PartialEq)] +pub struct OriginCert { + pub id: String, + pub pem: String, +} + +/// What Pyo asks of Cloudflare for tunnels and their certificates, on top +/// of DNS ([`super::Cloudflare`]). [`Http`] is the real one; the tests use +/// a fake account. +pub(crate) trait TunnelApi { + /// Every zone the token can read, with its account. + async fn zone_accounts(&self) -> Result, CfError>; + /// The records with exactly this name, with what's needed to put them + /// back as they were. + async fn records_kept(&self, zone_id: &str, name: &str) -> Result, CfError>; + /// Create a record as it was. + async fn create_kept(&self, zone_id: &str, r: &Kept) -> Result; + /// The account's tunnels named `name` that aren't deleted. + async fn tunnels_named(&self, account: &str, name: &str) -> Result, CfError>; + /// A remotely managed tunnel (its routes are set through the API). + async fn create_tunnel(&self, account: &str, name: &str) -> Result; + async fn tunnel(&self, account: &str, id: &str) -> Result; + async fn delete_tunnel(&self, account: &str, id: &str) -> Result<(), CfError>; + /// The token a connector runs the tunnel with. + async fn tunnel_token(&self, account: &str, id: &str) -> Result; + /// Replace the tunnel's routes. Cloudflare's version of them comes back. + async fn put_config(&self, account: &str, id: &str, config: &Value) -> Result; + /// Cloudflare's version of the tunnel's routes, and the routes. + async fn config(&self, account: &str, id: &str) -> Result<(i64, Value), CfError>; + /// Give the tunnel a new secret (so a new token). + async fn rotate_secret(&self, account: &str, id: &str, secret: &str) -> Result<(), CfError>; + /// Drop the tunnel's connections (they come back with a current token). + async fn drop_connections(&self, account: &str, id: &str) -> Result<(), CfError>; + /// The zone's Origin CA certificates (proves the token may read them). + async fn origin_certs(&self, zone_id: &str) -> Result, CfError>; + /// Issue an Origin CA certificate for a CSR. + async fn issue_origin_cert( + &self, + csr_pem: &str, + hostnames: &[String], + ) -> Result; + async fn revoke_origin_cert(&self, id: &str) -> Result<(), CfError>; +} + +/// Tunnel ids are UUIDs. +pub fn uuid_ok(id: &str) -> bool { + id.len() == 36 + && id.bytes().enumerate().all(|(i, b)| match i { + 8 | 13 | 18 | 23 => b == b'-', + _ => b.is_ascii_hexdigit(), + }) +} + +/// Origin CA certificate ids: digits (a long serial), nothing else. +fn cert_id_ok(id: &str) -> bool { + !id.is_empty() && id.len() <= 80 && id.bytes().all(|b| b.is_ascii_digit()) +} + +fn tunnel_path(account: &str, id: Option<&str>, rest: &str) -> Result { + if !id_ok(account) || id.is_some_and(|i| !uuid_ok(i)) { + return Err(CfError::NotFound); + } + Ok(match id { + Some(i) => format!("/accounts/{account}/cfd_tunnel/{i}{rest}"), + None => format!("/accounts/{account}/cfd_tunnel{rest}"), + }) +} + +fn unreadable() -> CfError { + CfError::Refused("an answer Pyo can't read".into()) +} + +/// A tunnel as Cloudflare answers with it. Its connections are listed per +/// connection (`connections`, each with its connector's `client_id`). +pub fn tunnel_from(v: &Value) -> Result { + let id = v["id"].as_str().filter(|i| uuid_ok(i)).ok_or_else(unreadable)?; + let s = |v: &Value, k: &str| v[k].as_str().unwrap_or("").to_owned(); + Ok(Tunnel { + id: id.to_owned(), + name: s(v, "name"), + status: s(v, "status"), + deleted: v["deleted_at"].as_str().is_some_and(|d| !d.is_empty()), + created_at: s(v, "created_at"), + connections: v["connections"] + .as_array() + .into_iter() + .flatten() + .map(|c| Connection { + client_id: s(c, "client_id"), + colo: s(c, "colo_name"), + client_version: s(c, "client_version"), + opened_at: s(c, "opened_at"), + origin_ip: s(c, "origin_ip"), + }) + .collect(), + }) +} + +fn kept_from(v: &Value) -> Result { + serde_json::from_value::(v.clone()) + .map(|mut k| { + k.id = v["id"].as_str().unwrap_or("").to_owned(); + k + }) + .map_err(|_| unreadable()) +} + +impl TunnelApi for Http { + async fn zone_accounts(&self) -> Result, CfError> { + let mut out = vec![]; + for page in 1..=20 { + let mut url = self.url("/zones"); + url.query_pairs_mut() + .append_pair("per_page", "50") + .append_pair("page", &page.to_string()); + let v = self.call(Method::GET, url, None).await?; + for z in v["result"].as_array().into_iter().flatten() { + if let (Some(id), Some(name)) = (z["id"].as_str(), z["name"].as_str()) + && id_ok(id) + { + let account = z["account"]["id"].as_str().filter(|a| id_ok(a)); + out.push(CfZone { + id: id.to_owned(), + name: name.to_owned(), + account_id: account.unwrap_or("").to_owned(), + account_name: z["account"]["name"] + .as_str() + .unwrap_or("") + .chars() + .take(100) + .collect(), + }); + } + } + if page >= v["result_info"]["total_pages"].as_i64().unwrap_or(1) { + break; + } + } + Ok(out) + } + + async fn records_kept(&self, zone_id: &str, name: &str) -> Result, CfError> { + let mut url = self.url(&Self::record_path(zone_id, None)?); + url.query_pairs_mut() + .append_pair("name", name) + .append_pair("per_page", "100"); + let v = self.call(Method::GET, url, None).await?; + v["result"] + .as_array() + .into_iter() + .flatten() + .map(kept_from) + .collect() + } + + async fn create_kept(&self, zone_id: &str, r: &Kept) -> Result { + let url = self.url(&Self::record_path(zone_id, None)?); + let mut body = json!({ + "type": r.kind, "name": r.name, "content": r.content, + "ttl": r.ttl, "proxied": r.proxied, + }); + if let Some(c) = &r.comment { + body["comment"] = json!(c); + } + super::record_from(&self.call(Method::POST, url, Some(body)).await?["result"]) + } + + async fn tunnels_named(&self, account: &str, name: &str) -> Result, CfError> { + let mut url = self.url(&tunnel_path(account, None, "")?); + url.query_pairs_mut() + .append_pair("name", name) + .append_pair("is_deleted", "false") + .append_pair("per_page", "50"); + let v = self.call(Method::GET, url, None).await?; + v["result"] + .as_array() + .into_iter() + .flatten() + .map(tunnel_from) + .collect() + } + + async fn create_tunnel(&self, account: &str, name: &str) -> Result { + let url = self.url(&tunnel_path(account, None, "")?); + let body = json!({ "name": name, "config_src": "cloudflare" }); + tunnel_from(&self.call(Method::POST, url, Some(body)).await?["result"]) + } + + async fn tunnel(&self, account: &str, id: &str) -> Result { + let url = self.url(&tunnel_path(account, Some(id), "")?); + tunnel_from(&self.call(Method::GET, url, None).await?["result"]) + } + + async fn delete_tunnel(&self, account: &str, id: &str) -> Result<(), CfError> { + let url = self.url(&tunnel_path(account, Some(id), "")?); + self.call(Method::DELETE, url, None).await.map(|_| ()) + } + + async fn tunnel_token(&self, account: &str, id: &str) -> Result { + let url = self.url(&tunnel_path(account, Some(id), "/token")?); + let v = self.call(Method::GET, url, None).await?; + v["result"] + .as_str() + .filter(|t| !t.is_empty() && t.len() <= 4096 && t.bytes().all(|b| b.is_ascii_graphic())) + .map(str::to_owned) + .ok_or_else(unreadable) + } + + async fn put_config(&self, account: &str, id: &str, config: &Value) -> Result { + let url = self.url(&tunnel_path(account, Some(id), "/configurations")?); + let v = self + .call(Method::PUT, url, Some(json!({ "config": config }))) + .await?; + Ok(v["result"]["version"].as_i64().unwrap_or(0)) + } + + async fn config(&self, account: &str, id: &str) -> Result<(i64, Value), CfError> { + let url = self.url(&tunnel_path(account, Some(id), "/configurations")?); + let v = self.call(Method::GET, url, None).await?; + Ok(( + v["result"]["version"].as_i64().unwrap_or(0), + v["result"]["config"].clone(), + )) + } + + async fn rotate_secret(&self, account: &str, id: &str, secret: &str) -> Result<(), CfError> { + let url = self.url(&tunnel_path(account, Some(id), "")?); + self.call(Method::PATCH, url, Some(json!({ "tunnel_secret": secret }))) + .await + .map(|_| ()) + } + + async fn drop_connections(&self, account: &str, id: &str) -> Result<(), CfError> { + let url = self.url(&tunnel_path(account, Some(id), "/connections")?); + self.call(Method::DELETE, url, None).await.map(|_| ()) + } + + async fn origin_certs(&self, zone_id: &str) -> Result, CfError> { + if !id_ok(zone_id) { + return Err(CfError::NotFound); + } + let mut url = self.url("/certificates"); + url.query_pairs_mut().append_pair("zone_id", zone_id); + let v = self.call(Method::GET, url, None).await?; + Ok(v["result"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| c["id"].as_str().map(str::to_owned)) + .collect()) + } + + async fn issue_origin_cert( + &self, + csr_pem: &str, + hostnames: &[String], + ) -> Result { + let url = self.url("/certificates"); + let body = json!({ + "csr": csr_pem, "hostnames": hostnames, + "request_type": "origin-ecc", "requested_validity": CERT_DAYS, + }); + let v = self.call(Method::POST, url, Some(body)).await?; + let r = &v["result"]; + match (r["id"].as_str(), r["certificate"].as_str()) { + (Some(id), Some(pem)) if cert_id_ok(id) => Ok(OriginCert { + id: id.to_owned(), + pem: pem.to_owned(), + }), + _ => Err(unreadable()), + } + } + + async fn revoke_origin_cert(&self, id: &str) -> Result<(), CfError> { + if !cert_id_ok(id) { + return Err(CfError::NotFound); + } + let url = self.url(&format!("/certificates/{id}")); + self.call(Method::DELETE, url, None).await.map(|_| ()) + } +} + +// ── Checking a token ─────────────────────────────────────────────────────── + +/// What this installation's probe tunnels are named: `pyo-check--`, then six random hex characters. The installation's id is the one +/// in its tunnels' names and its records' comments, so a check never +/// touches another installation's probes or someone's own tunnel. +pub fn check_prefix(install_id: &str) -> String { + format!("{CHECK_PREFIX}{install_id}-") +} + +/// A probe this installation left behind: its name is the prefix and six +/// hex characters, and it was made more than a few minutes ago. One with a +/// date Pyo can't read is left alone. +fn left_behind(t: &Tunnel, prefix: &str, now: jiff::Timestamp) -> bool { + t.name + .strip_prefix(prefix) + .is_some_and(|r| r.len() == 6 && r.bytes().all(|b| b.is_ascii_hexdigit())) + && t.created_at + .parse::() + .is_ok_and(|made| now.as_second() - made.as_second() > CHECK_STALE_SECS) +} + +/// Whether the token may make tunnels in an account: it makes a probe +/// tunnel and deletes it again (a token without Cloudflare Tunnel:Edit is +/// refused the first step). This installation's own probes left behind are +/// deleted first. The permission it lacks, or None. +pub(crate) async fn tunnel_missing( + cf: &C, + account: &str, + install_id: &str, +) -> Result, CfError> { + let prefix = check_prefix(install_id); + let left = match cf.tunnels_named(account, &prefix).await { + Ok(t) => t, + Err(CfError::Denied(_)) => return Ok(Some(TUNNEL_EDIT.into())), + Err(e) => return Err(e), + }; + let now = jiff::Timestamp::now(); + for t in left.iter().filter(|t| left_behind(t, &prefix, now)) { + let _ = cf.delete_tunnel(account, &t.id).await; + } + let mut b = [0u8; 3]; + rand::fill(&mut b); + match cf + .create_tunnel(account, &format!("{prefix}{}", hex::encode(b))) + .await + { + Ok(t) => match cf.delete_tunnel(account, &t.id).await { + // Already gone: nothing is left behind either way. + Ok(()) | Err(CfError::NotFound) => Ok(None), + Err(e) => Err(e), + }, + Err(CfError::Denied(_)) => Ok(Some(TUNNEL_EDIT.into())), + Err(e) => Err(e), + } +} + +/// Whether the token may read a zone's Origin CA certificates. Edit can't +/// be proven without issuing one, so the first issue says plainly when it's +/// missing. The permission it lacks, or None. +pub(crate) async fn certs_missing( + cf: &C, + zone_id: &str, +) -> Result, CfError> { + match cf.origin_certs(zone_id).await { + Ok(_) => Ok(None), + Err(CfError::Denied(_)) => Ok(Some(CERTS_EDIT.into())), + Err(e) => Err(e), + } +} + +// ── The routes ───────────────────────────────────────────────────────────── + +/// One route rule for a hostname, to Pyo Gateway over HTTPS. The visitor's +/// host goes as SNI, so the Origin CA certificate is checked against it +/// (one shape for exact names and the wildcard). +fn rule(hostname: &str) -> Value { + json!({ + "hostname": hostname, + "service": ORIGIN, + "originRequest": { "matchSNItoHost": true, "connectTimeout": 10, "keepAliveTimeout": 90 }, + }) +} + +/// The tunnel's routes: one per hostname the Gateway serves (longest +/// first, then by name), then the catch-all. cloudflared matches top down. +/// +/// The default domain gets no wildcard route. Its wildcard record sends +/// every name under it to the tunnel, but the Gateway only has a listener +/// for names a service has, so a wildcard route would hand it names it +/// resets the connection for (502 at Cloudflare). Each name under the +/// default domain has its own route here (the loop marks it as a tunnel +/// domain), and every other name stops at the catch-all's 404 in +/// cloudflared, before the cluster. +pub fn ingress(hostnames: &[String]) -> Value { + let mut exact: Vec = hostnames + .iter() + .map(|h| h.trim().trim_end_matches('.').to_ascii_lowercase()) + .filter(|h| !h.is_empty()) + .collect(); + exact.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b))); + exact.dedup(); + let mut rules: Vec = exact.iter().map(|h| rule(h)).collect(); + rules.push(json!({ "service": "http_status:404" })); + json!({ "ingress": rules }) +} + +/// Only the catch-all: what's left while a tunnel is removed. +pub fn empty_ingress() -> Value { + ingress(&[]) +} + +/// The routes' hash, to PUT them only when they change. serde_json keeps +/// keys sorted, so the same routes always hash the same. +pub fn config_hash(config: &Value) -> String { + hex::encode(Sha256::digest(config.to_string().as_bytes())) +} + +// ── The certificate's names ──────────────────────────────────────────────── + +/// The name that covers a tunnel hostname on the certificate: the zone's +/// apex itself, else a wildcard one level up (`blog.example.com` → +/// `*.example.com`, `a.b.example.com` → `*.b.example.com`). +pub fn cert_name(host: &str, zone: &str) -> String { + let host = host.trim_end_matches('.').to_ascii_lowercase(); + let zone = zone.trim_end_matches('.').to_ascii_lowercase(); + if host == zone { + return host; + } + match host.split_once('.') { + Some((_, parent)) => format!("*.{parent}"), + None => host, + } +} + +/// Every name the tunnel's certificate needs: one per hostname (each with +/// its zone), the default domain's wildcard. Sorted, deduped. Too many for +/// one certificate: Err. +pub fn cert_names( + hosts: &[(String, String)], + default_domain: Option<&str>, +) -> Result, String> { + let mut names: Vec = hosts.iter().map(|(h, z)| cert_name(h, z)).collect(); + if let Some(d) = default_domain { + names.push(format!("*.{}", d.to_ascii_lowercase())); + } + names.sort(); + names.dedup(); + if names.len() > MAX_CERT_NAMES { + return Err("This tunnel has too many names for one certificate.".into()); + } + Ok(names) +} + +/// Whether a certificate with `have` names covers all of `want`. +pub fn covers_all(have: &[String], want: &[String]) -> bool { + want.iter().all(|w| have.contains(w)) +} + +/// A new key and its CSR for the tunnel's certificate: ECDSA P-256. The +/// key stays on the control plane, sealed with the team's certificates +/// (decision 1). (CSR PEM, key PEM). +pub fn key_and_csr(names: &[String]) -> anyhow::Result<(String, String)> { + use rcgen::{CertificateParams, DistinguishedName, DnType, KeyPair, PKCS_ECDSA_P256_SHA256}; + let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; + let mut p = CertificateParams::new(names.to_vec())?; + let mut dn = DistinguishedName::new(); + dn.push( + DnType::CommonName, + names.first().cloned().unwrap_or_default(), + ); + p.distinguished_name = dn; + let csr = p.serialize_request(&key)?; + Ok((csr.pem()?, key.serialize_pem())) +} + +/// A new tunnel secret, as Cloudflare takes it: 32 random bytes, base64. +pub fn new_secret() -> String { + use base64::Engine; + let mut b = [0u8; 32]; + rand::fill(&mut b); + base64::engine::general_purpose::STANDARD.encode(b) +} + +/// The tunnel's name at Cloudflare: the cluster and this installation, so +/// two installations sharing an account never take each other's. +pub fn tunnel_name(cluster_id: &str, install_id: &str, attempt: u32) -> String { + match attempt { + 0 | 1 => format!("pyo-{cluster_id}-{install_id}"), + n => format!("pyo-{cluster_id}-{install_id}-{n}"), + } +} + +/// Where a tunnel's CNAME points. +pub fn cname_target(tunnel_id: &str) -> String { + format!("{tunnel_id}.cfargotunnel.com") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn routes_are_exact_names_then_404() { + let hosts = vec![ + "blog.example.com".to_owned(), + "a.b.example.com".to_owned(), + "API.example.com.".to_owned(), + "blog.example.com".to_owned(), + ]; + let c = ingress(&hosts); + let names: Vec = c["ingress"] + .as_array() + .unwrap() + .iter() + .map(|r| r["hostname"].clone()) + .collect(); + assert_eq!( + names, + [ + json!("blog.example.com"), + json!("a.b.example.com"), + json!("api.example.com"), + Value::Null + ] + ); + let first = &c["ingress"][0]; + assert_eq!(first["service"], ORIGIN); + assert_eq!(first["originRequest"]["matchSNItoHost"], true); + assert_eq!(c["ingress"][3], json!({ "service": "http_status:404" })); + // The same routes always hash the same, whatever order they came in. + let mut again = hosts.clone(); + again.reverse(); + assert_eq!(config_hash(&ingress(&again)), config_hash(&c)); + assert_ne!(config_hash(&ingress(&hosts[..1])), config_hash(&c)); + assert_eq!( + empty_ingress(), + json!({ "ingress": [{ "service": "http_status:404" }] }) + ); + } + + #[test] + fn a_name_no_service_has_stops_at_the_404_before_the_cluster() { + // The default domain's wildcard record brings every name under it + // to the tunnel. Only names a service has are routed to the + // Gateway: no rule is a wildcard, so anything else falls to the + // catch-all, which is the last rule and has no hostname. + let c = ingress(&["web-shop.example.com".to_owned(), "blog.example.com".to_owned()]); + let rules = c["ingress"].as_array().unwrap(); + assert!(rules.iter().all(|r| !r["hostname"].as_str().unwrap_or("").contains('*')), "{c}"); + let (last, routed) = rules.split_last().unwrap(); + assert_eq!(last, &json!({ "service": "http_status:404" })); + assert!(routed.iter().all(|r| r["service"] == ORIGIN && r["hostname"].is_string())); + assert_eq!(routed.len(), 2); + } + + #[test] + fn certificate_names_cover_each_host_one_level_up() { + assert_eq!(cert_name("example.com", "example.com"), "example.com"); + assert_eq!(cert_name("blog.example.com", "example.com"), "*.example.com"); + assert_eq!(cert_name("a.b.example.com", "example.com"), "*.b.example.com"); + assert_eq!(cert_name("Shop.Example.com.", "example.com"), "*.example.com"); + let hosts = vec![ + ("blog.example.com".to_owned(), "example.com".to_owned()), + ("shop.example.com".to_owned(), "example.com".to_owned()), + ("other.org".to_owned(), "other.org".to_owned()), + ("x.y.other.org".to_owned(), "other.org".to_owned()), + ]; + assert_eq!( + cert_names(&hosts, Some("example.com")).unwrap(), + ["*.example.com", "*.y.other.org", "other.org"] + ); + let many: Vec<(String, String)> = (0..=MAX_CERT_NAMES) + .map(|i| (format!("a.s{i}.example.com"), "example.com".to_owned())) + .collect(); + assert_eq!( + cert_names(&many, None).unwrap_err(), + "This tunnel has too many names for one certificate." + ); + let have = vec!["*.example.com".to_owned(), "other.org".to_owned()]; + assert!(covers_all(&have, &["*.example.com".to_owned()])); + assert!(!covers_all(&have, &["*.b.example.com".to_owned()])); + } + + #[test] + fn a_csr_names_every_host_and_the_key_stays_here() { + let names = vec!["*.example.com".to_owned(), "example.com".to_owned()]; + let (csr, key) = key_and_csr(&names).unwrap(); + assert!(csr.starts_with("-----BEGIN CERTIFICATE REQUEST-----")); + assert!(key.contains("PRIVATE KEY")); + assert!(!csr.contains("PRIVATE KEY")); + } + + #[test] + fn names_secrets_and_targets() { + assert_eq!(tunnel_name("cl_1", "abc123", 0), "pyo-cl_1-abc123"); + assert_eq!(tunnel_name("cl_1", "abc123", 2), "pyo-cl_1-abc123-2"); + assert_eq!( + cname_target("c1744f8b-faa1-48a4-9e5c-02ac921467fa"), + "c1744f8b-faa1-48a4-9e5c-02ac921467fa.cfargotunnel.com" + ); + use base64::Engine; + let s = new_secret(); + assert_eq!( + base64::engine::general_purpose::STANDARD + .decode(&s) + .unwrap() + .len(), + 32 + ); + assert_ne!(new_secret(), s); + assert!(cert_id_ok("123456789012345678901234567890")); + assert!(!cert_id_ok("12/34")); + assert!(!cert_id_ok("")); + } + + #[test] + fn kept_records_round_trip_without_their_id() { + let k = kept_from(&json!({ + "id": "372e67954025e0ba6aaa6d586b9e0b59", "type": "A", "name": "blog.example.com", + "content": "203.0.113.7", "proxied": true, "ttl": 300, "comment": "by hand", + })) + .unwrap(); + assert_eq!(k.id, "372e67954025e0ba6aaa6d586b9e0b59"); + assert_eq!(k.ttl, 300); + let stored = serde_json::to_value(&k).unwrap(); + assert!(stored.get("id").is_none()); + assert_eq!(stored["type"], "A"); + let back: Kept = serde_json::from_value(stored).unwrap(); + assert_eq!(back.ttl, 300); + assert_eq!(back.comment.as_deref(), Some("by hand")); + let auto: Kept = serde_json::from_value( + json!({ "type": "CNAME", "name": "a.example.com", "content": "x.example.net" }), + ) + .unwrap(); + assert_eq!((auto.ttl, auto.proxied), (1, false)); + } +} diff --git a/crates/pyo-api/src/cloudflare/tunnel_loop.rs b/crates/pyo-api/src/cloudflare/tunnel_loop.rs new file mode 100644 index 00000000..da5f8499 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/tunnel_loop.rs @@ -0,0 +1,1599 @@ +//! The tunnel loop (docs/cloudflare-tunnel.md §6.3): every 30 seconds on +//! the leader, each cluster tunnel is brought to what Pyo wants. The +//! tunnel exists at Cloudflare, its routes are the cluster's tunnel +//! domains, its certificate covers them, their records point at it (or +//! back), the agent has its token, and Cloudflare's view of it is read +//! every 2 minutes. A tunnel being removed is taken apart in order. +//! +//! Every step touches Cloudflare only when something differs. Errors are +//! kept on the tunnel (`error`) or the record (`dns_records.error`) in +//! Cloudflare's words, never with the token. +//! +//! The parts that talk to Cloudflare are generic over [`Cloudflare`] and +//! [`TunnelApi`], so the tests run them against the fake account. + +use std::time::Duration; + +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use super::{ + CfError, Cloudflare, Http, NewRecord, Record, delete_ours, install_id, marker, ours, + same_name, + tunnel::{self, Kept, OriginCert, Tunnel, TunnelApi}, + zone_for, +}; +use crate::{AppState, error::ApiResult, ops::log_activity}; + +/// How often the loop runs. +const EVERY: Duration = Duration::from_secs(30); +/// Down this long before the alert goes out. +const DOWN_ALERT_SECS: i64 = 300; +/// How long removal waits for the agent to stop the connector. +const REMOVE_WAIT_SECS: i64 = 600; + +/// The loop, on the leader. +pub async fn run(state: AppState) { + let mut tick = tokio::time::interval(EVERY); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tick.tick().await; + if let Some(Err(e)) = + crate::bg::as_leader(&state.db, crate::bg::LOCK_TUNNEL, || pass(&state)).await + { + tracing::warn!(error = ?e.message, "tunnel loop failed"); + } + } +} + +/// One pass over every tunnel, one at a time. +pub async fn pass(s: &AppState) -> ApiResult<()> { + let ids: Vec = sqlx::query_scalar( + "SELECT cluster_id FROM pyo.cluster_tunnels + WHERE backoff_until IS NULL OR backoff_until < now() ORDER BY cluster_id", + ) + .fetch_all(&s.db) + .await?; + for id in ids { + if let Err(e) = one(s, &id).await { + tracing::warn!(cluster = %id, error = ?e.message, "tunnel pass failed"); + } + } + leftovers(s).await +} + +/// What's left at Cloudflare of a deleted service's tunnel domain or a +/// deleted cluster's tunnel (the migration's triggers keep them): only +/// Pyo's own records are deleted, then the tunnel and its certificates. +#[derive(sqlx::FromRow, Debug)] +struct Leftover { + id: i64, + team_id: String, + kind: String, + zone_id: Option, + record_id: Option, + hostname: Option, + account_id: Option, + tunnel_id: Option, + cf_certificates: Vec, +} + +async fn leftovers(s: &AppState) -> ApiResult<()> { + let rows: Vec = sqlx::query_as( + "SELECT id, team_id, kind, zone_id, record_id, hostname, account_id, tunnel_id, cf_certificates + FROM pyo.tunnel_leftovers ORDER BY id LIMIT 50", + ) + .fetch_all(&s.db) + .await?; + for l in rows { + let mut tx = s.db.begin().await?; + let account = super::account(s, &mut tx, &l.team_id).await.ok().flatten(); + let mark = marker(&install_id(&mut tx).await?); + tx.commit().await?; + let Some(account) = account else { + sqlx::query("UPDATE pyo.tunnel_leftovers SET error = $2 WHERE id = $1") + .bind(l.id) + .bind(TOKEN_GONE) + .execute(&s.db) + .await?; + continue; + }; + let done = clean_up(&Http::new(&account.token)?, &l, &mark).await; + match done { + Ok(()) => { + sqlx::query("DELETE FROM pyo.tunnel_leftovers WHERE id = $1") + .bind(l.id) + .execute(&s.db) + .await?; + } + Err(e) => { + sqlx::query("UPDATE pyo.tunnel_leftovers SET error = $2 WHERE id = $1") + .bind(l.id) + .bind(e.to_string()) + .execute(&s.db) + .await?; + } + } + } + Ok(()) +} + +/// One leftover, taken apart. Gone already counts as done. +async fn clean_up(cf: &C, l: &Leftover, mark: &str) -> Result<(), CfError> { + let gone = |r: Result<(), CfError>| match r { + Ok(()) | Err(CfError::NotFound) => Ok(()), + Err(e) => Err(e), + }; + if let (Some(zone), Some(id), Some(host)) = (&l.zone_id, &l.record_id, &l.hostname) { + delete_ours(cf, zone, id, host, mark).await?; + } + if l.kind == "tunnel" + && let (Some(account), Some(id)) = (&l.account_id, &l.tunnel_id) + { + match cf.put_config(account, id, &tunnel::empty_ingress()).await { + Ok(_) | Err(CfError::NotFound) => {} + Err(e) => return Err(e), + } + gone(cf.drop_connections(account, id).await)?; + gone(cf.delete_tunnel(account, id).await)?; + } + for c in &l.cf_certificates { + gone(cf.revoke_origin_cert(c).await)?; + } + Ok(()) +} + +/// A cluster's tunnel as stored, with what's due. +#[derive(sqlx::FromRow, Debug, Clone, Default)] +pub(crate) struct Row { + pub cluster_id: String, + pub team_id: String, + pub account_id: String, + pub tunnel_id: Option, + pub tunnel_name: String, + pub state: String, + pub default_domain: Option, + pub default_zone_id: Option, + pub default_record_id: Option, + pub config_hash: String, + pub config_version: Option, + pub certificate_id: Option, + pub cf_certificate_id: Option, + pub cf_certificate_old: Option, + pub rotate: bool, + pub restore_records: bool, + pub agent_status: Value, + pub down_alerted: bool, + /// Computed: the old certificate may be revoked. + pub old_due: bool, + /// Computed: the token may go to the agent again. + pub token_due: bool, + /// Computed: Cloudflare's view is due. + pub check_due: bool, + /// Computed: seconds Cloudflare has said it's down. + pub down_secs: Option, + /// Computed: seconds since removal was asked for. + pub removing_secs: i64, + /// Computed: made in the last 5 minutes. + pub young: bool, +} + +const ROW: &str = "SELECT cluster_id, team_id, account_id, tunnel_id, tunnel_name, state, default_domain, default_zone_id, + default_record_id, config_hash, config_version, certificate_id, cf_certificate_id, cf_certificate_old, rotate, + restore_records, agent_status, down_alerted, + coalesce(cf_certificate_old_at < now(), false) AS old_due, + (token_sent_at IS NULL OR token_sent_at < now() - interval '5 minutes') AS token_due, + (checked_at IS NULL OR checked_at < now() - interval '2 minutes') AS check_due, + extract(epoch FROM now() - down_since)::bigint AS down_secs, + extract(epoch FROM now() - updated_at)::bigint AS removing_secs, + (created_at > now() - interval '5 minutes') AS young + FROM pyo.cluster_tunnels WHERE cluster_id = $1"; + +pub(crate) async fn load( + db: impl sqlx::PgExecutor<'_>, + cluster_id: &str, +) -> ApiResult> { + Ok(sqlx::query_as::<_, Row>(ROW) + .bind(cluster_id) + .fetch_optional(db) + .await?) +} + +/// Keep an error on the tunnel (or clear it with None). +async fn set_error(s: &AppState, cluster_id: &str, error: Option) -> ApiResult<()> { + sqlx::query("UPDATE pyo.cluster_tunnels SET error = $2 WHERE cluster_id = $1 AND error IS DISTINCT FROM $2") + .bind(cluster_id) + .bind(error) + .execute(&s.db) + .await?; + Ok(()) +} + +/// Cloudflare asked to slow down: this team's tunnels wait a minute. +async fn back_off(s: &AppState, team_id: &str) -> ApiResult<()> { + sqlx::query("UPDATE pyo.cluster_tunnels SET backoff_until = now() + interval '60 seconds' WHERE team_id = $1") + .bind(team_id) + .execute(&s.db) + .await?; + Ok(()) +} + +/// Cloudflare's 429. +fn slow_down(e: &CfError) -> bool { + matches!(e, CfError::Refused(m) if m.contains("429") || m.to_lowercase().contains("rate limit")) +} + +/// Said when the team's token is gone or refused. +pub const TOKEN_GONE: &str = "Connect Cloudflare again to change the tunnel. Its websites keep working."; + +/// One tunnel, one pass. +async fn one(s: &AppState, cluster_id: &str) -> ApiResult<()> { + let Some(row) = load(&s.db, cluster_id).await? else { + return Ok(()); + }; + let mut tx = s.db.begin().await?; + let account = super::account(s, &mut tx, &row.team_id).await.ok().flatten(); + let mark = marker(&install_id(&mut tx).await?); + tx.commit().await?; + let Some(account) = account else { + return set_error(s, cluster_id, Some(TOKEN_GONE.into())).await; + }; + let cf = Http::new(&account.token)?; + let r = if row.state == "removing" { + remove(s, &cf, &row, &account.zones, &mark).await + } else { + keep(s, &cf, &row, &account.zones, &mark).await + }; + match r { + Ok(()) => Ok(()), + Err(Step::Cf(e)) if slow_down(&e) => back_off(s, &row.team_id).await, + Err(Step::Cf(e @ CfError::Denied(_))) => { + set_error(s, cluster_id, Some(format!("{e} {TOKEN_GONE}"))).await + } + Err(Step::Cf(e)) => set_error(s, cluster_id, Some(e.to_string())).await, + Err(Step::Api(e)) => Err(e), + } +} + +/// Why a step stopped: Cloudflare said no, or Pyo's own trouble. +#[derive(Debug)] +pub(crate) enum Step { + Cf(CfError), + Api(crate::error::ApiError), +} + +impl From for Step { + fn from(e: CfError) -> Self { + Step::Cf(e) + } +} + +impl From for Step { + fn from(e: crate::error::ApiError) -> Self { + Step::Api(e) + } +} + +impl From for Step { + fn from(e: anyhow::Error) -> Self { + Step::Api(e.into()) + } +} + +impl From for Step { + fn from(e: sqlx::Error) -> Self { + Step::Api(e.into()) + } +} + +/// A tunnel domain of the cluster, as its service has it. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct TunnelDomain { + pub service_id: String, + pub domain_id: String, + pub host: String, + /// "switching" or "on". + pub tunnel: String, + pub zone_id: String, + pub zone_name: String, +} + +/// The cluster's domains that go through its tunnel, with their zones (a +/// domain no connected zone covers is left out: it can't be routed). +async fn tunnel_domains( + db: impl sqlx::PgExecutor<'_>, + cluster_id: &str, + zones: &[super::Zone], +) -> ApiResult> { + let rows: Vec<(String, String, String, String)> = sqlx::query_as( + "SELECT a.id, d->>'id', lower(d->>'hostname'), d->>'tunnel' + FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d + WHERE a.cluster_id = $1 AND NOT a.deleting AND d->>'tunnel' IN ('switching', 'on') + ORDER BY 3", + ) + .bind(cluster_id) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .filter_map(|(service_id, domain_id, host, tunnel)| { + let z = zone_for(&host, zones)?; + Some(TunnelDomain { + service_id, + domain_id, + host, + tunnel, + zone_id: z.id.clone(), + zone_name: z.name.clone(), + }) + }) + .collect()) +} + +// ── Keeping a tunnel ─────────────────────────────────────────────────────── + +async fn keep( + s: &AppState, + cf: &C, + row: &Row, + zones: &[super::Zone], + mark: &str, +) -> Result<(), Step> { + let install = mark + .trim_start_matches("Made by Pyo (") + .trim_end_matches(')') + .to_owned(); + // 1. The tunnel itself. + let (t, recreated) = ensure_tunnel(cf, row, &install).await?; + if row.tunnel_id.as_deref() != Some(t.id.as_str()) { + sqlx::query( + "UPDATE pyo.cluster_tunnels SET tunnel_id = $2, tunnel_name = $3, state = 'ready', config_hash = '', token_sent_at = NULL, + default_record_id = NULL, updated_at = now() WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .bind(&t.id) + .bind(&t.name) + .execute(&s.db) + .await?; + if recreated { + // Its records point at the old one: they move to the new one. + sqlx::query( + "UPDATE pyo.dns_records SET status = 'switching', updated_at = now() + WHERE via = 'tunnel' AND status = 'created' + AND service_id IN (SELECT id FROM pyo.services WHERE cluster_id = $1)", + ) + .bind(&row.cluster_id) + .execute(&s.db) + .await?; + let mut tx = s.db.begin().await?; + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "cluster.tunnel_recreated", + "warning", + "The Cloudflare Tunnel was gone, so Pyo made a new one", + json!({ "kind": "cluster", "id": row.cluster_id, "label": t.name }), + json!({}), + ) + .await?; + tx.commit().await?; + } + } + let target = tunnel::cname_target(&t.id); + // Free domains under the default domain: through the tunnel's wildcard. + if let Some(d) = &row.default_domain { + free_domains_follow(s, &row.cluster_id, d, row.default_record_id.is_some()).await?; + } + let domains = tunnel_domains(&s.db, &row.cluster_id, zones).await?; + + // 2. Its routes: every tunnel domain, the free ones under the default + // domain among them. No wildcard route: a name no service has gets + // the tunnel's own 404 (see `tunnel::ingress`). + let hosts: Vec = domains.iter().map(|d| d.host.clone()).collect(); + let config = tunnel::ingress(&hosts); + let hash = tunnel::config_hash(&config); + if hash != row.config_hash || recreated { + let version = cf.put_config(&row.account_id, &t.id, &config).await?; + sqlx::query("UPDATE pyo.cluster_tunnels SET config_hash = $2, config_version = $3 WHERE cluster_id = $1") + .bind(&row.cluster_id) + .bind(&hash) + .bind(version as i32) + .execute(&s.db) + .await?; + } + + // 3. Its certificate: every name covered. + let pairs: Vec<(String, String)> = domains + .iter() + .map(|d| (d.host.clone(), d.zone_name.clone())) + .collect(); + let certificate_id = match tunnel::cert_names(&pairs, row.default_domain.as_deref()) { + Ok(names) => ensure_certificate(s, cf, row, &names).await?, + Err(e) => { + set_error(s, &row.cluster_id, Some(e)).await?; + row.certificate_id.clone() + } + }; + + // 4. Its domains' certificates, and their records. + if let Some(cert) = &certificate_id { + tls_follow(s, &row.cluster_id, cert).await?; + } + records(s, cf, row, &target, zones, mark).await?; + default_record(s, cf, row, &target, mark).await?; + + // 5. The agent's token. + let agent_has = row.agent_status["tunnelId"].as_str(); + if agent_has != Some(t.id.as_str()) && row.token_due && agent_knows_tunnels(s, &row.cluster_id).await? { + let token = cf.tunnel_token(&row.account_id, &t.id).await?; + let mut tx = s.db.begin().await?; + crate::deploy::enqueue( + &mut tx, + &row.cluster_id, + pyo_proto::Command::TunnelSet { + tunnel_id: t.id.clone(), + token, + }, + ) + .await?; + sqlx::query("UPDATE pyo.cluster_tunnels SET token_sent_at = now() WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + s.wake(&row.cluster_id).await; + } + + // 6. Rotate: a new secret, old connections dropped, then the token again. + if row.rotate { + cf.rotate_secret(&row.account_id, &t.id, &tunnel::new_secret()) + .await?; + cf.drop_connections(&row.account_id, &t.id).await?; + sqlx::query( + "UPDATE pyo.cluster_tunnels SET rotate = false, token_sent_at = NULL, + agent_status = agent_status - 'tunnelId' WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .execute(&s.db) + .await?; + } + + // 7. Cloudflare's view, every 2 minutes. + if row.check_due { + let now = cf.tunnel(&row.account_id, &t.id).await?; + status(s, row, &now).await?; + // Its routes changed outside Pyo: Pyo's go back. + if let Ok((version, _)) = cf.config(&row.account_id, &t.id).await + && row.config_version.is_some_and(|v| i64::from(v) != version) + { + sqlx::query("UPDATE pyo.cluster_tunnels SET config_hash = '' WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&s.db) + .await?; + } + } + + // 8. The certificate it replaced, a day later. + if row.old_due + && let Some(old) = &row.cf_certificate_old + { + match cf.revoke_origin_cert(old).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + sqlx::query("UPDATE pyo.cluster_tunnels SET cf_certificate_old = NULL, cf_certificate_old_at = NULL WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&s.db) + .await?; + } + set_error(s, &row.cluster_id, None).await?; + Ok(()) +} + +/// Whether the cluster's agent runs tunnels (an older one would never +/// answer `TunnelSet`). +async fn agent_knows_tunnels(s: &AppState, cluster_id: &str) -> ApiResult { + Ok(sqlx::query_scalar( + "SELECT coalesce((capabilities->>'tunnel')::boolean, false) FROM pyo.clusters WHERE id = $1", + ) + .bind(cluster_id) + .fetch_optional(&s.db) + .await? + .unwrap_or(false)) +} + +/// The tunnel at Cloudflare: the one stored, or (none yet, or deleted at +/// Cloudflare) one made now. A tunnel this installation made earlier under +/// the same name (a pass that stopped halfway) is taken, never someone +/// else's. (tunnel, made again after it was gone). +pub(crate) async fn ensure_tunnel( + cf: &C, + row: &Row, + install: &str, +) -> Result<(Tunnel, bool), CfError> { + if let Some(id) = &row.tunnel_id { + match cf.tunnel(&row.account_id, id).await { + Ok(t) if !t.deleted => return Ok((t, false)), + Ok(_) | Err(CfError::NotFound) => {} + Err(e) => return Err(e), + } + } + let base = tunnel::tunnel_name(&row.cluster_id, install, 0); + let taken = cf.tunnels_named(&row.account_id, &base).await?; + if row.tunnel_id.is_none() + && let Some(t) = taken.iter().find(|t| t.name == base && !t.deleted) + { + return Ok((t.clone(), false)); + } + let recreated = row.tunnel_id.is_some(); + for attempt in 1..=20 { + let name = tunnel::tunnel_name(&row.cluster_id, install, attempt); + if taken.iter().any(|t| t.name == name) { + continue; + } + return Ok((cf.create_tunnel(&row.account_id, &name).await?, recreated)); + } + Err(CfError::Refused( + "Too many tunnels with this cluster's name. Delete the old ones in Cloudflare.".into(), + )) +} + +// ── Records ──────────────────────────────────────────────────────────────── + +/// What became of a switch's record. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Switched { + /// The name points at the tunnel: Pyo's record, and the ones it + /// replaced (kept to put back). + Done { record: Record, previous: Vec }, + /// Records Pyo didn't make answer for the name: these. Nothing changed. + Confirm(Vec), +} + +/// Point `host` at the tunnel with a proxied CNAME. Pyo's own records on +/// the name go without asking. Anyone else's stop it, unless `replace`: +/// then they go and come back as `previous`. Never touches records of +/// other names, or types other than A, AAAA and CNAME. +pub(crate) async fn switch_record( + cf: &C, + zone_id: &str, + host: &str, + target: &str, + replace: bool, + mark: &str, +) -> Result { + let found = cf.records_kept(zone_id, host).await?; + let at: Vec<&Kept> = found + .iter() + .filter(|k| matches!(k.kind.as_str(), "A" | "AAAA" | "CNAME") && same_name(&k.name, host)) + .collect(); + let have = at + .iter() + .find(|k| k.kind == "CNAME" && k.content.eq_ignore_ascii_case(target) && ours(&k.record(), mark, host)) + .map(|k| k.record()); + let others: Vec<&Kept> = at + .iter() + .copied() + .filter(|k| have.as_ref().is_none_or(|h| h.id != k.id)) + .collect(); + let theirs: Vec<&Kept> = others + .iter() + .copied() + .filter(|k| !ours(&k.record(), mark, host)) + .collect(); + if !theirs.is_empty() && !replace { + return Ok(Switched::Confirm(theirs.iter().map(|k| k.record()).collect())); + } + for k in &others { + match cf.delete(zone_id, &k.id).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e), + } + } + let previous: Vec = theirs.into_iter().cloned().collect(); + let record = match have { + Some(r) if r.proxied => r, + Some(r) => { + cf.set_proxied(zone_id, &r.id, true).await?; + Record { proxied: true, ..r } + } + None => { + cf.create( + zone_id, + &NewRecord { + kind: "CNAME".into(), + name: host.to_owned(), + content: target.to_owned(), + proxied: true, + comment: mark.to_owned(), + }, + ) + .await? + } + }; + Ok(Switched::Done { record, previous }) +} + +/// Point `host` back: Pyo's CNAME goes (only if it's still Pyo's), then +/// the kept records come back as they were. With none kept, `fallback` +/// (an A record to the cluster's public IP) is made instead, when given. +/// The record Pyo made, if any. +pub(crate) async fn revert_record( + cf: &C, + zone_id: &str, + host: &str, + record_id: Option<&str>, + previous: &[Kept], + fallback: Option<&str>, + mark: &str, +) -> Result, CfError> { + if let Some(id) = record_id { + delete_ours(cf, zone_id, id, host, mark).await?; + } + for k in previous { + cf.create_kept(zone_id, k).await?; + } + if !previous.is_empty() { + return Ok(None); + } + let Some(ip) = fallback else { + return Ok(None); + }; + Ok(Some( + cf.create( + zone_id, + &NewRecord { + kind: "A".into(), + name: host.to_owned(), + content: ip.to_owned(), + proxied: false, + comment: mark.to_owned(), + }, + ) + .await?, + )) +} + +/// A record row waiting for the loop. +#[derive(sqlx::FromRow, Debug)] +struct Waiting { + service_id: String, + domain_id: String, + hostname: String, + zone_id: String, + record_id: Option, + status: String, + previous: Value, + replace: bool, + restore: bool, + /// The routes sync it waits for: done, failed or still on its way. + routes: Option, + routes_error: Option, +} + +/// Rows switching to the tunnel or back, once the agent has the service's +/// routes for it (both paths answer then). +async fn records( + s: &AppState, + cf: &C, + row: &Row, + target: &str, + zones: &[super::Zone], + mark: &str, +) -> Result<(), Step> { + let waiting: Vec = sqlx::query_as( + "SELECT r.service_id, r.domain_id, r.hostname, r.zone_id, r.record_id, r.status, r.previous, r.replace, r.restore, + c.status AS routes, c.result->>'message' AS routes_error + FROM pyo.dns_records r JOIN pyo.services a ON a.id = r.service_id + LEFT JOIN pyo.commands c ON c.id = r.routes_command + WHERE a.cluster_id = $1 AND NOT a.deleting AND r.status IN ('switching', 'reverting') + ORDER BY r.hostname LIMIT 50", + ) + .bind(&row.cluster_id) + .fetch_all(&s.db) + .await?; + for w in waiting { + // The same name on its way off another tunnel (a domain moved from + // another service or cluster): that one first. + if w.status == "switching" { + let busy: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.dns_records r WHERE lower(r.hostname) = lower($1) AND r.service_id <> $2 + AND (r.status = 'reverting' OR (r.via = 'tunnel' AND r.status = 'created'))) + OR EXISTS (SELECT 1 FROM pyo.tunnel_leftovers l WHERE lower(l.hostname) = lower($1))", + ) + .bind(&w.hostname) + .bind(&w.service_id) + .fetch_one(&s.db) + .await?; + if busy { + continue; + } + } + // The agent's routes first: no record moves before both paths answer. + match w.routes.as_deref() { + None | Some("done") => {} + Some("failed") => { + record_failed( + s, + &w, + &format!( + "The Gateway didn't take the change: {}", + w.routes_error.as_deref().unwrap_or("no reason given") + ), + ) + .await?; + continue; + } + Some(_) => continue, + } + let r = if w.status == "switching" { + switch_one(s, cf, row, &w, target, mark).await + } else { + revert_one(s, cf, row, &w, zones, mark).await + }; + match r { + Ok(()) => {} + Err(Step::Cf(e)) if slow_down(&e) => return Err(Step::Cf(e)), + Err(Step::Cf(e)) => record_failed(s, &w, &e.to_string()).await?, + Err(e) => return Err(e), + } + } + Ok(()) +} + +async fn record_failed(s: &AppState, w: &Waiting, error: &str) -> ApiResult<()> { + sqlx::query("UPDATE pyo.dns_records SET error = $3, updated_at = now() WHERE service_id = $1 AND domain_id = $2") + .bind(&w.service_id) + .bind(&w.domain_id) + .bind(error) + .execute(&s.db) + .await?; + Ok(()) +} + +async fn switch_one( + s: &AppState, + cf: &C, + row: &Row, + w: &Waiting, + target: &str, + mark: &str, +) -> Result<(), Step> { + let out = switch_record(cf, &w.zone_id, &w.hostname, target, w.replace, mark).await?; + let mut tx = s.db.begin().await?; + match out { + Switched::Confirm(existing) => { + sqlx::query( + "UPDATE pyo.dns_records SET status = 'conflict', existing = $3, error = NULL, updated_at = now() + WHERE service_id = $1 AND domain_id = $2", + ) + .bind(&w.service_id) + .bind(&w.domain_id) + .bind(json!(existing)) + .execute(&mut *tx) + .await?; + } + Switched::Done { record, previous } => { + // What it replaced before (a repoint after the tunnel came back) + // stays kept. + let mut kept: Vec = serde_json::from_value(w.previous.clone()).unwrap_or_default(); + kept.extend(previous.iter().cloned()); + sqlx::query( + "UPDATE pyo.dns_records SET status = 'created', via = 'tunnel', record_id = $3, type = 'CNAME', content = $4, + proxied = true, proxy = true, previous = $5, existing = '[]', error = NULL, replace = false, updated_at = now() + WHERE service_id = $1 AND domain_id = $2", + ) + .bind(&w.service_id) + .bind(&w.domain_id) + .bind(&record.id) + .bind(target) + .bind(json!(kept)) + .execute(&mut *tx) + .await?; + // Only through the tunnel now: the gate goes on, plain HTTP goes. + set_domain(&mut tx, &w.service_id, &w.domain_id, |d| { + d["tunnel"] = json!(pyo_proto::TUNNEL_ON); + d["status"] = json!("active"); + }) + .await?; + let wake = crate::routes::changed(&mut tx, &w.service_id, true).await?; + let replaced: Vec = previous + .iter() + .map(|k| format!("{} {}", k.kind, k.content)) + .collect(); + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "domain.tunnel", + "success", + &if replaced.is_empty() { + format!("{} goes through the Cloudflare Tunnel", w.hostname) + } else { + format!( + "{} goes through the Cloudflare Tunnel (replaced {})", + w.hostname, + replaced.join(", ") + ) + }, + json!({ "kind": "service", "id": w.service_id, "label": w.hostname }), + json!({ "serviceId": w.service_id, "replaced": previous }), + ) + .await?; + tx.commit().await?; + if let Some(c) = wake { + s.wake(&c).await; + } + return Ok(()); + } + } + tx.commit().await?; + Ok(()) +} + +async fn revert_one( + s: &AppState, + cf: &C, + row: &Row, + w: &Waiting, + _zones: &[super::Zone], + mark: &str, +) -> Result<(), Step> { + let previous: Vec = if w.restore { + serde_json::from_value(w.previous.clone()).unwrap_or_default() + } else { + vec![] + }; + // Without a kept record, on a cluster with public ports: its own A record. + let mut tx = s.db.begin().await?; + let ip = crate::freedomain::load(&mut tx, &row.cluster_id) + .await? + .and_then(|(_, c)| c.public_ip()) + .map(|ip| ip.to_string()); + tx.commit().await?; + let fallback = ip.as_deref().filter(|_| w.restore); + let made = revert_record( + cf, + &w.zone_id, + &w.hostname, + w.record_id.as_deref(), + &previous, + fallback, + mark, + ) + .await?; + let mut tx = s.db.begin().await?; + match &made { + Some(r) => { + sqlx::query( + "UPDATE pyo.dns_records SET status = 'created', via = 'direct', record_id = $3, type = 'A', content = $4, + proxied = false, proxy = false, previous = '[]', existing = '[]', error = NULL, updated_at = now() + WHERE service_id = $1 AND domain_id = $2", + ) + .bind(&w.service_id) + .bind(&w.domain_id) + .bind(&r.id) + .bind(&r.content) + .execute(&mut *tx) + .await?; + } + None => { + // Pyo's CNAME is gone already: nothing left for the leftovers. + sqlx::query("UPDATE pyo.dns_records SET via = 'direct', record_id = NULL WHERE service_id = $1 AND domain_id = $2") + .bind(&w.service_id) + .bind(&w.domain_id) + .execute(&mut *tx) + .await?; + sqlx::query("DELETE FROM pyo.dns_records WHERE service_id = $1 AND domain_id = $2") + .bind(&w.service_id) + .bind(&w.domain_id) + .execute(&mut *tx) + .await?; + } + } + // Direct again: its route at the tunnel goes with the next pass, and + // its certificate is what it was. + set_domain(&mut tx, &w.service_id, &w.domain_id, |d| { + leave_tunnel(d); + }) + .await?; + let wake = crate::routes::changed(&mut tx, &w.service_id, true).await?; + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "domain.tunnel", + "info", + &format!("{} no longer goes through the Cloudflare Tunnel", w.hostname), + json!({ "kind": "service", "id": w.service_id, "label": w.hostname }), + json!({ "serviceId": w.service_id, "restored": previous }), + ) + .await?; + tx.commit().await?; + if let Some(c) = wake { + s.wake(&c).await; + } + Ok(()) +} + +/// A domain leaves the tunnel: no `tunnel`, and the certificate it had. +pub(crate) fn leave_tunnel(d: &mut Value) { + if let Some(o) = d.as_object_mut() { + o.remove("tunnel"); + if let Some(before) = o.remove("tlsModeBefore") { + o.insert("tlsMode".into(), before); + match o.remove("certificateIdBefore") { + Some(c) => { + o.insert("certificateId".into(), c); + } + None => { + o.remove("certificateId"); + } + } + } + } +} + +/// A tunnel domain takes the tunnel's certificate (the one it had is +/// kept to go back to). While it switches, a certificate already issued +/// for it stays (cloudflared trusts public CAs too, and direct visitors +/// still see a valid one). Whether it changed. +pub(crate) fn take_certificate(d: &mut Value, certificate_id: &str) -> bool { + let switching = d["tunnel"] == json!(pyo_proto::TUNNEL_SWITCHING); + let mode = d["tlsMode"].as_str().unwrap_or("auto").to_owned(); + let host = d["hostname"].as_str().unwrap_or("").to_owned(); + let issuer = crate::deploy::tls_issuer(&mode, &host); + let has_tunnel_cert = + issuer == "custom" && d["certificateId"] == json!(certificate_id); + if has_tunnel_cert { + return false; + } + let valid_now = (issuer == "letsencrypt" && d["tls"] == json!("issued")) || issuer == "custom"; + if switching && valid_now && d.get("tlsModeBefore").is_none() { + return false; + } + if d.get("tlsModeBefore").is_none() { + d["tlsModeBefore"] = json!(mode); + if let Some(c) = d.get("certificateId").cloned() { + d["certificateIdBefore"] = c; + } + } + d["tlsMode"] = json!("custom"); + d["certificateId"] = json!(certificate_id); + true +} + +/// Whether `host` is a free name under the default domain `d`: one label +/// below it (`web-shop.example.com`), as the wildcard covers. +pub fn under_default(host: &str, d: &str) -> bool { + host.to_ascii_lowercase() + .strip_suffix(&format!(".{}", d.to_ascii_lowercase())) + .is_some_and(|label| !label.is_empty() && !label.contains('.')) +} + +/// A cluster's domains one label under its default domain, with no record +/// of their own (Pyo's or anyone's: an explicit record wins over the +/// wildcard), go only through the tunnel: `tunnel: "on"`, and active once +/// the wildcard record is there. +async fn free_domains_follow( + s: &AppState, + cluster_id: &str, + default_domain: &str, + wildcard: bool, +) -> ApiResult<()> { + let services: Vec<(String, Value)> = sqlx::query_as( + "SELECT a.id, coalesce(a.spec->'domains', '[]') FROM pyo.services a + WHERE a.cluster_id = $1 AND NOT a.deleting + AND EXISTS (SELECT 1 FROM jsonb_array_elements(a.spec->'domains') d + WHERE lower(d->>'hostname') LIKE '%.' || lower($2) + AND (NOT d ? 'tunnel' OR (d->>'tunnel' = 'on' AND d->>'status' <> 'active')))", + ) + .bind(cluster_id) + .bind(default_domain) + .fetch_all(&s.db) + .await?; + for (service_id, mut domains) in services { + let own: Vec = sqlx::query_scalar("SELECT domain_id FROM pyo.dns_records WHERE service_id = $1") + .bind(&service_id) + .fetch_all(&s.db) + .await?; + let mut routes = false; + let mut changed = false; + for d in domains.as_array_mut().into_iter().flatten() { + let host = d["hostname"].as_str().unwrap_or("").to_owned(); + let id = d["id"].as_str().unwrap_or("").to_owned(); + if !under_default(&host, default_domain) || own.contains(&id) { + continue; + } + if d.get("tunnel").is_none() { + d["tunnel"] = json!(pyo_proto::TUNNEL_ON); + routes = true; + changed = true; + } + if d["tunnel"] == json!(pyo_proto::TUNNEL_ON) && wildcard && d["status"] != json!("active") { + d["status"] = json!("active"); + changed = true; + } + } + if !changed { + continue; + } + let mut tx = s.db.begin().await?; + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(&service_id) + .bind(&domains) + .execute(&mut *tx) + .await?; + let wake = if routes { + crate::routes::changed(&mut tx, &service_id, true).await? + } else { + None + }; + tx.commit().await?; + if let Some(c) = wake { + s.wake(&c).await; + } + } + Ok(()) +} + +/// Change one domain of a service's spec. +async fn set_domain( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + domain_id: &str, + f: impl FnOnce(&mut Value), +) -> ApiResult<()> { + let domains: Option = sqlx::query_scalar( + "SELECT coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1 FOR UPDATE", + ) + .bind(service_id) + .fetch_optional(&mut **tx) + .await?; + let Some(mut domains) = domains else { + return Ok(()); + }; + if let Some(d) = domains + .as_array_mut() + .and_then(|ds| ds.iter_mut().find(|d| d["id"] == json!(domain_id))) + { + f(d); + } + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(service_id) + .bind(&domains) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Tunnel domains use the tunnel's certificate (see [`take_certificate`]). +/// Services whose domains changed get their routes again, and rows +/// switching for them wait for that sync. +async fn tls_follow(s: &AppState, cluster_id: &str, certificate_id: &str) -> ApiResult<()> { + let services: Vec<(String, Value)> = sqlx::query_as( + "SELECT a.id, coalesce(a.spec->'domains', '[]') FROM pyo.services a + WHERE a.cluster_id = $1 AND NOT a.deleting + AND EXISTS (SELECT 1 FROM jsonb_array_elements(a.spec->'domains') d WHERE d->>'tunnel' IN ('switching', 'on'))", + ) + .bind(cluster_id) + .fetch_all(&s.db) + .await?; + for (service_id, mut domains) in services { + let mut changed = false; + for d in domains.as_array_mut().into_iter().flatten() { + if matches!(d["tunnel"].as_str(), Some(pyo_proto::TUNNEL_SWITCHING | pyo_proto::TUNNEL_ON)) { + changed |= take_certificate(d, certificate_id); + } + } + if !changed { + continue; + } + let mut tx = s.db.begin().await?; + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(&service_id) + .bind(&domains) + .execute(&mut *tx) + .await?; + if let Some((cluster, command)) = crate::routes::changed_waiting(&mut tx, &service_id).await? { + sqlx::query( + "UPDATE pyo.dns_records SET routes_command = $2 WHERE service_id = $1 AND status IN ('switching', 'reverting')", + ) + .bind(&service_id) + .bind(&command) + .execute(&mut *tx) + .await?; + tx.commit().await?; + s.wake(&cluster).await; + } else { + tx.commit().await?; + } + } + Ok(()) +} + +/// The default domain's wildcard record: `*.` to the tunnel, made +/// once. Someone else's record there stops it, and it's said. +async fn default_record( + s: &AppState, + cf: &C, + row: &Row, + target: &str, + mark: &str, +) -> Result<(), Step> { + let (Some(domain), Some(zone)) = (&row.default_domain, &row.default_zone_id) else { + return Ok(()); + }; + if row.default_record_id.is_some() { + return Ok(()); + } + let name = format!("*.{domain}"); + match switch_record(cf, zone, &name, target, false, mark).await? { + Switched::Done { record, .. } => { + sqlx::query("UPDATE pyo.cluster_tunnels SET default_record_id = $2 WHERE cluster_id = $1") + .bind(&row.cluster_id) + .bind(&record.id) + .execute(&s.db) + .await?; + } + Switched::Confirm(existing) => { + let what: Vec = existing + .iter() + .map(|r| format!("{} {}", r.kind, r.content)) + .collect(); + return Err(Step::Cf(CfError::Refused(format!( + "Cloudflare has a record for {name} ({}). Remove it, or pick another default domain.", + what.join(", ") + )))); + } + } + Ok(()) +} + +// ── The certificate ──────────────────────────────────────────────────────── + +/// Issue an Origin CA certificate for `names`, with a key made here. +pub(crate) async fn issue( + cf: &C, + names: &[String], +) -> Result<(OriginCert, String), CfError> { + let (csr, key) = tunnel::key_and_csr(names) + .map_err(|e| CfError::Refused(format!("Pyo couldn't make the certificate's key: {e}")))?; + let cert = match cf.issue_origin_cert(&csr, names).await { + Err(CfError::Denied(_)) => { + return Err(CfError::Denied(format!( + "give the token {} on the tunnel's zones.", + tunnel::CERTS_EDIT + ))); + } + other => other?, + }; + Ok((cert, key)) +} + +/// The tunnel's certificate covers `names` (issued again when it doesn't, +/// or when Rotate asked). Its id in the team's certificates. +async fn ensure_certificate( + s: &AppState, + cf: &C, + row: &Row, + names: &[String], +) -> Result, Step> { + let have: Option> = match &row.certificate_id { + Some(id) => sqlx::query_scalar("SELECT hostnames FROM pyo.certificates WHERE id = $1") + .bind(id) + .fetch_optional(&s.db) + .await?, + None => None, + }; + let covered = have.as_ref().is_some_and(|h| tunnel::covers_all(h, names)); + if covered && !row.rotate { + return Ok(row.certificate_id.clone()); + } + if names.is_empty() { + return Ok(row.certificate_id.clone()); + } + let (cert, key) = issue(cf, names).await?; + let now = pyo_proto::now_ms() / 1000; + let parsed = crate::certs::parse(&cert.pem, &key, now) + .map_err(|e| Step::Cf(CfError::Refused(format!("Cloudflare's certificate: {}", e.message))))?; + let sealed = crate::vault::get() + .seal_credential(&row.team_id, &parsed.key_pem) + .await?; + let id = row + .certificate_id + .clone() + .unwrap_or_else(|| crate::ids::new_id("crt")); + let cluster_name: String = sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(&row.cluster_id) + .fetch_one(&s.db) + .await?; + let mut tx = s.db.begin().await?; + sqlx::query( + "INSERT INTO pyo.certificates (id, team_id, name, hostnames, issuer, not_before, not_after, fingerprint, chain_pem, key_sealed) + VALUES ($1, $2, $3, $4, $5, to_timestamp($6), to_timestamp($7), $8, $9, $10) + ON CONFLICT (id) DO UPDATE SET hostnames = $4, issuer = $5, not_before = to_timestamp($6), not_after = to_timestamp($7), + fingerprint = $8, chain_pem = $9, key_sealed = $10, warned_days = NULL, updated_at = now()", + ) + .bind(&id) + .bind(&row.team_id) + .bind(format!("Cloudflare Tunnel ({cluster_name})")) + .bind(&parsed.hostnames) + .bind("Cloudflare Origin CA") + .bind(parsed.not_before as f64) + .bind(parsed.not_after as f64) + .bind(&parsed.fingerprint) + .bind(&parsed.chain_pem) + .bind(&sealed) + .execute(&mut *tx) + .await?; + sqlx::query( + "UPDATE pyo.cluster_tunnels SET certificate_id = $2, cf_certificate_id = $3, rotate = rotate AND $5, + cf_certificate_old = coalesce($4, cf_certificate_old), + cf_certificate_old_at = CASE WHEN $4 IS NULL THEN cf_certificate_old_at ELSE now() + interval '1 day' END + WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .bind(&id) + .bind(&cert.id) + .bind(&row.cf_certificate_id) + // Rotate also needs the new secret (step 6): only that clears it. + .bind(true) + .execute(&mut *tx) + .await?; + // Services using it get it again (the same id, a new chain and key). + let mut wake = vec![]; + for (service_id, _) in crate::certs::used_by(&mut tx, &id).await? { + if let Some(c) = crate::routes::changed(&mut tx, &service_id, true).await? { + wake.push(c); + } + } + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "domain.certificate_replaced", + "success", + &format!("Got the Cloudflare Tunnel certificate of {cluster_name}"), + json!({ "kind": "certificate", "id": id, "label": format!("Cloudflare Tunnel ({cluster_name})") }), + json!({}), + ) + .await?; + tx.commit().await?; + wake.sort(); + wake.dedup(); + for c in wake { + s.wake(&c).await; + } + Ok(Some(id)) +} + +// ── Health ───────────────────────────────────────────────────────────────── + +/// The tunnel's health from Cloudflare's view and the agent's: +/// "connected", "degraded", "down", "starting" or "unknown". +pub fn health(cf: &Value, agent: &Value, young: bool) -> &'static str { + let status = cf["status"].as_str().unwrap_or(""); + let wanted = agent["replicas"].as_i64().unwrap_or(0); + let ready = agent["readyReplicas"].as_i64().unwrap_or(0); + match status { + "" => "unknown", + "healthy" if wanted > 0 && ready < wanted => "degraded", + "healthy" => "connected", + "degraded" => "degraded", + _ if young => "starting", + _ => "down", + } +} + +/// Keep Cloudflare's view of the tunnel, and say when it's been down for +/// 5 minutes (an alert), and when it's back. +async fn status(s: &AppState, row: &Row, t: &Tunnel) -> ApiResult<()> { + let cf_status = json!({ + "status": t.status, + "connections": t.connections, + "at": pyo_proto::now_ms(), + }); + let down = matches!(t.status.as_str(), "down" | "inactive") && !row.young; + sqlx::query( + "UPDATE pyo.cluster_tunnels SET cf_status = $2, checked_at = now(), + down_since = CASE WHEN $3 THEN coalesce(down_since, now()) ELSE NULL END + WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .bind(&cf_status) + .bind(down) + .execute(&s.db) + .await?; + let alert = if down && !row.down_alerted && row.down_secs.unwrap_or(0) >= DOWN_ALERT_SECS { + Some(true) + } else if !down && row.down_alerted { + Some(false) + } else { + None + }; + if let Some(down) = alert { + let mut tx = s.db.begin().await?; + let name: String = sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(&row.cluster_id) + .fetch_one(&mut *tx) + .await?; + sqlx::query("UPDATE pyo.cluster_tunnels SET down_alerted = $2 WHERE cluster_id = $1") + .bind(&row.cluster_id) + .bind(down) + .execute(&mut *tx) + .await?; + log_activity( + &mut tx, + &row.team_id, + "Pyo", + if down { "cluster.tunnel_down" } else { "cluster.tunnel_up" }, + if down { "failure" } else { "success" }, + &if down { + format!("The Cloudflare Tunnel of {name} is down") + } else { + format!("The Cloudflare Tunnel of {name} is back") + }, + json!({ "kind": "cluster", "id": row.cluster_id, "label": name }), + json!({}), + ) + .await?; + tx.commit().await?; + } + Ok(()) +} + +/// Read Cloudflare's view of a cluster's tunnel again when the last read +/// is older than 30 seconds (the tunnel endpoint's fresh read). Quiet when +/// Cloudflare can't be reached: the stored view is shown then. +pub async fn refresh(s: &AppState, cluster_id: &str) -> ApiResult<()> { + let due: Option<(String, String, Option)> = sqlx::query_as( + "SELECT team_id, account_id, tunnel_id FROM pyo.cluster_tunnels + WHERE cluster_id = $1 AND state <> 'removing' AND tunnel_id IS NOT NULL + AND (checked_at IS NULL OR checked_at < now() - interval '30 seconds')", + ) + .bind(cluster_id) + .fetch_optional(&s.db) + .await?; + let Some((team_id, account_id, Some(tunnel_id))) = due else { + return Ok(()); + }; + let mut tx = s.db.begin().await?; + let account = super::account(s, &mut tx, &team_id).await.ok().flatten(); + tx.commit().await?; + let Some(account) = account else { + return Ok(()); + }; + let Ok(t) = Http::new(&account.token)?.tunnel(&account_id, &tunnel_id).await else { + return Ok(()); + }; + if let Some(row) = load(&s.db, cluster_id).await? { + status(s, &row, &t).await?; + } + Ok(()) +} + +// ── As shown ─────────────────────────────────────────────────────────────── + +/// A tunnel as the dashboard, CLI and API show it: never a token. +pub fn shown(row: &Value) -> Value { + let cf = &row["cfStatus"]; + let agent = &row["agentStatus"]; + let connections = cf["connections"].as_array().cloned().unwrap_or_default(); + let mut colos: Vec = connections + .iter() + .filter_map(|c| c["colo"].as_str().map(str::to_owned)) + .collect(); + colos.sort(); + colos.dedup(); + let pods = agent["pods"].as_array().cloned().unwrap_or_default(); + let connectors: Vec = pods + .iter() + .map(|p| json!({ "server": p["server"], "ready": p["ready"], "reason": p["reason"] })) + .collect(); + json!({ + "state": row["state"], "error": row["error"], + "accountId": row["accountId"], "accountName": row["accountName"], + "tunnelId": row["tunnelId"], "tunnelName": row["tunnelName"], + "defaultDomain": row["defaultDomain"], "portsPublic": row["portsPublic"], + "connectors": connectors, + "colos": colos, + "connections": connections.len(), + "health": if row["state"] == "removing" { "removing" } else { health(cf, agent, row["young"] == json!(true)) }, + // The cluster's install refused the connector: its connect command + // brings the newer one. + "refused": agent["refused"] == json!(true), + "certificate": row["certificate"], + "checkedAt": cf["at"], + }) +} + +/// Each cluster's tunnel, as `tunnel` on the snapshot's clusters. +pub async fn attach( + db: &mut sqlx::PgConnection, + team_ids: &[String], + clusters: &mut [Value], +) -> ApiResult<()> { + let rows: Vec<(String, Value)> = sqlx::query_as(SHOWN).bind(team_ids).fetch_all(&mut *db).await?; + for c in clusters.iter_mut() { + if let Some((_, r)) = rows.iter().find(|(id, _)| c["id"] == json!(id)) { + c["tunnel"] = shown(r); + } + } + Ok(()) +} + +/// One cluster's tunnel, shown. None without one. +pub async fn one_shown(db: impl sqlx::PgExecutor<'_>, cluster_id: &str) -> ApiResult> { + let row: Option<(String, Value)> = sqlx::query_as(SHOWN_ONE) + .bind(cluster_id) + .fetch_optional(db) + .await?; + Ok(row.map(|(_, r)| shown(&r))) +} + +const SHOWN: &str = concat!( + "SELECT t.cluster_id, jsonb_build_object( + 'state', t.state, 'error', t.error, 'accountId', t.account_id, 'accountName', t.account_name, + 'tunnelId', t.tunnel_id, 'tunnelName', t.tunnel_name, 'defaultDomain', t.default_domain, 'portsPublic', t.ports_public, + 'cfStatus', t.cf_status, 'agentStatus', t.agent_status, 'young', t.created_at > now() - interval '5 minutes', + 'certificate', (SELECT jsonb_build_object('id', c.id, 'notAfter', pyo.ms(c.not_after)) FROM pyo.certificates c WHERE c.id = t.certificate_id)) + FROM pyo.cluster_tunnels t", + " WHERE t.team_id = ANY($1)" +); +const SHOWN_ONE: &str = concat!( + "SELECT t.cluster_id, jsonb_build_object( + 'state', t.state, 'error', t.error, 'accountId', t.account_id, 'accountName', t.account_name, + 'tunnelId', t.tunnel_id, 'tunnelName', t.tunnel_name, 'defaultDomain', t.default_domain, 'portsPublic', t.ports_public, + 'cfStatus', t.cf_status, 'agentStatus', t.agent_status, 'young', t.created_at > now() - interval '5 minutes', + 'certificate', (SELECT jsonb_build_object('id', c.id, 'notAfter', pyo.ms(c.not_after)) FROM pyo.certificates c WHERE c.id = t.certificate_id)) + FROM pyo.cluster_tunnels t", + " WHERE t.cluster_id = $1" +); + +// ── Removing a tunnel ────────────────────────────────────────────────────── + +/// Take a tunnel apart, in order: no routes but the catch-all, records +/// back (or only Pyo's deleted), the connector stopped, connections +/// dropped, the tunnel deleted, its certificate revoked. Then the row. +async fn remove( + s: &AppState, + cf: &C, + row: &Row, + zones: &[super::Zone], + mark: &str, +) -> Result<(), Step> { + if let Some(id) = &row.tunnel_id { + match cf + .put_config(&row.account_id, id, &tunnel::empty_ingress()) + .await + { + Ok(_) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + } + // Every record through the tunnel, back. + let rows: Vec = sqlx::query_as( + "SELECT r.service_id, r.domain_id, r.hostname, r.zone_id, r.record_id, r.status, r.previous, r.replace, r.restore, + NULL::text AS routes, NULL::text AS routes_error + FROM pyo.dns_records r JOIN pyo.services a ON a.id = r.service_id + WHERE a.cluster_id = $1 AND (r.via = 'tunnel' OR r.status IN ('switching', 'reverting'))", + ) + .bind(&row.cluster_id) + .fetch_all(&s.db) + .await?; + for mut w in rows { + w.restore = row.restore_records; + revert_one(s, cf, row, &w, zones, mark).await?; + } + // Domains that never had a record: no longer through the tunnel. + let services: Vec = sqlx::query_scalar( + "SELECT a.id FROM pyo.services a WHERE a.cluster_id = $1 + AND EXISTS (SELECT 1 FROM jsonb_array_elements(a.spec->'domains') d WHERE d ? 'tunnel')", + ) + .bind(&row.cluster_id) + .fetch_all(&s.db) + .await?; + for service_id in services { + let mut tx = s.db.begin().await?; + let domains: Value = sqlx::query_scalar("SELECT coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1 FOR UPDATE") + .bind(&service_id) + .fetch_one(&mut *tx) + .await?; + let mut domains = domains; + for d in domains.as_array_mut().into_iter().flatten() { + leave_tunnel(d); + } + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(&service_id) + .bind(&domains) + .execute(&mut *tx) + .await?; + let wake = crate::routes::changed(&mut tx, &service_id, true).await?; + tx.commit().await?; + if let Some(c) = wake { + s.wake(&c).await; + } + } + // The default domain's wildcard, only if it's still Pyo's. + if let (Some(zone), Some(id), Some(domain)) = + (&row.default_zone_id, &row.default_record_id, &row.default_domain) + { + delete_ours(cf, zone, id, &format!("*.{domain}"), mark).await?; + } + // The connector: asked once, then waited for (or 10 minutes). + let agent_has = row.agent_status["tunnelId"].as_str().is_some(); + if agent_has && row.removing_secs < REMOVE_WAIT_SECS { + if row.token_due { + let mut tx = s.db.begin().await?; + crate::deploy::enqueue( + &mut tx, + &row.cluster_id, + pyo_proto::Command::TunnelRemove {}, + ) + .await?; + sqlx::query("UPDATE pyo.cluster_tunnels SET token_sent_at = now() WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + s.wake(&row.cluster_id).await; + } + return Ok(()); + } + if let Some(id) = &row.tunnel_id { + match cf.drop_connections(&row.account_id, id).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + match cf.delete_tunnel(&row.account_id, id).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + } + for c in [&row.cf_certificate_id, &row.cf_certificate_old].into_iter().flatten() { + match cf.revoke_origin_cert(c).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + } + let mut tx = s.db.begin().await?; + // Everything at Cloudflare is gone: nothing left for the leftovers. + sqlx::query( + "UPDATE pyo.cluster_tunnels SET tunnel_id = NULL, cf_certificate_id = NULL, cf_certificate_old = NULL, default_record_id = NULL + WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .execute(&mut *tx) + .await?; + sqlx::query("DELETE FROM pyo.cluster_tunnels WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&mut *tx) + .await?; + if let Some(cert) = &row.certificate_id + && crate::certs::used_by(&mut tx, cert).await?.is_empty() + { + sqlx::query("DELETE FROM pyo.certificates WHERE id = $1") + .bind(cert) + .execute(&mut *tx) + .await?; + } + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "cluster.tunnel_removed", + "info", + "Removed the Cloudflare Tunnel", + json!({ "kind": "cluster", "id": row.cluster_id, "label": row.tunnel_name }), + json!({}), + ) + .await?; + tx.commit().await?; + Ok(()) +} + +#[cfg(test)] +#[path = "tunnel_loop_tests.rs"] +mod tests; diff --git a/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs b/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs new file mode 100644 index 00000000..3769fdc3 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs @@ -0,0 +1,303 @@ +//! The tunnel loop's steps against the fake Cloudflare account: the tunnel +//! made, taken back or made again, records switched and put back exactly, +//! only Pyo's own records deleted, the certificate issued, and the health +//! it shows. + +use serde_json::json; + +use super::*; +use crate::cloudflare::tests::{Dns, Fake, MARK, rec}; + +const TARGET: &str = "00000000-0000-4000-8000-000000000001.cfargotunnel.com"; + +fn row() -> Row { + Row { + cluster_id: "cl_1".into(), + team_id: "team_1".into(), + account_id: "acct1".into(), + tunnel_name: "pyo-cl_1-abc123".into(), + state: "creating".into(), + ..Default::default() + } +} + +#[tokio::test] +async fn a_tunnel_is_made_taken_back_or_made_again() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let mut r = row(); + let (t, again) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert_eq!(t.name, "pyo-cl_1-abc123"); + assert!(!again); + // A pass that stopped before keeping its id: the same tunnel, not a second. + let (same, _) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert_eq!(same.id, t.id); + assert_eq!(cf.tunnel_list().len(), 1); + // Kept: read, not made. + r.tunnel_id = Some(t.id.clone()); + let (kept, again) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert_eq!((kept.id.as_str(), again), (t.id.as_str(), false)); + // Deleted by hand in Cloudflare: a new one, with a name of its own. + cf.tunnels.lock().unwrap()[0].1.deleted = true; + let (new, again) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert!(again); + assert_ne!(new.id, t.id); + // Its name is free again once the old one is deleted. + assert_eq!(new.name, "pyo-cl_1-abc123"); + // Taken by a live one (a pass that stopped halfway): the next name. + r.tunnel_id = Some("00000000-0000-4000-8000-00000000ffff".into()); + let (third, again) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert!(again); + assert_eq!(third.name, "pyo-cl_1-abc123-2"); +} + +#[tokio::test] +async fn someone_elses_tunnel_is_never_taken() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + cf.tunnels.lock().unwrap().push(( + "acct1".into(), + tunnel::Tunnel { + id: "11111111-2222-4333-8444-555555555555".into(), + name: "pyo-cl_1-zzz999".into(), + ..Default::default() + }, + )); + let (t, _) = ensure_tunnel(&cf, &row(), "abc123").await.unwrap(); + assert_eq!(t.name, "pyo-cl_1-abc123"); + assert_ne!(t.id, "11111111-2222-4333-8444-555555555555"); +} + +#[tokio::test] +async fn a_free_name_switches_without_asking() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let out = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + let Switched::Done { record, previous } = out else { + panic!("{out:?}") + }; + assert_eq!( + (record.kind.as_str(), record.content.as_str(), record.proxied), + ("CNAME", TARGET, true) + ); + assert_eq!(record.comment.as_deref(), Some(MARK)); + assert!(previous.is_empty()); + // Again: nothing more to do. + let again = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + assert!(matches!(again, Switched::Done { ref previous, .. } if previous.is_empty())); + assert_eq!(cf.at("z1").len(), 1); +} + +#[tokio::test] +async fn pyos_own_direct_record_goes_without_asking_and_isnt_kept() { + let mine = rec("m1", "A", "blog.example.com", "203.0.113.7", Some(MARK)); + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]).with("z1", mine); + let out = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + assert!(matches!(out, Switched::Done { ref previous, .. } if previous.is_empty())); + let now = cf.at("z1"); + assert_eq!(now.len(), 1); + assert_eq!(now[0].kind, "CNAME"); +} + +#[tokio::test] +async fn someone_elses_record_asks_first_then_is_kept_and_put_back_exactly() { + let mut theirs = rec("t1", "A", "blog.example.com", "198.51.100.9", Some("by hand")); + theirs.proxied = true; + let mx = rec("x1", "MX", "blog.example.com", "mail.example.com", None); + let other = rec("o1", "A", "shop.example.com", "198.51.100.9", None); + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]) + .with("z1", theirs.clone()) + .with("z1", mx.clone()) + .with("z1", other.clone()); + cf.ttls.lock().unwrap().insert("t1".into(), 300); + // Asked first: nothing changes. + let out = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + assert_eq!(out, Switched::Confirm(vec![theirs.clone()])); + assert_eq!(cf.at("z1").len(), 3); + // Replaced: kept as it was, every field. + let Switched::Done { record, previous } = + switch_record(&cf, "z1", "blog.example.com", TARGET, true, MARK) + .await + .unwrap() + else { + panic!("not switched") + }; + assert_eq!(previous.len(), 1); + let k = &previous[0]; + assert_eq!( + (k.kind.as_str(), k.content.as_str(), k.proxied, k.ttl, k.comment.as_deref()), + ("A", "198.51.100.9", true, 300, Some("by hand")) + ); + // Other types and names stay. + let names: Vec = cf.at("z1").iter().map(|r| r.id.clone()).collect(); + assert!(names.contains(&"x1".to_owned()) && names.contains(&"o1".to_owned())); + // Switch back: Pyo's CNAME goes, the kept record comes back as it was. + let made = revert_record(&cf, "z1", "blog.example.com", Some(&record.id), &previous, Some("203.0.113.7"), MARK) + .await + .unwrap(); + assert_eq!(made, None, "a kept record wins over the public IP"); + let back: Vec = cf + .at("z1") + .into_iter() + .filter(|r| r.name == "blog.example.com" && r.kind != "MX") + .collect(); + assert_eq!(back.len(), 1); + assert_eq!( + (back[0].kind.as_str(), back[0].content.as_str(), back[0].proxied, back[0].comment.as_deref()), + ("A", "198.51.100.9", true, Some("by hand")) + ); + assert_eq!(cf.ttls.lock().unwrap().get(&back[0].id), Some(&300)); +} + +#[tokio::test] +async fn switching_back_without_a_kept_record() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let Switched::Done { record, .. } = + switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap() + else { + panic!("not switched") + }; + // Public ports: Pyo's own A record to the cluster. + let made = revert_record(&cf, "z1", "blog.example.com", Some(&record.id), &[], Some("203.0.113.7"), MARK) + .await + .unwrap() + .expect("an A record"); + assert_eq!((made.kind.as_str(), made.content.as_str()), ("A", "203.0.113.7")); + assert_eq!(made.comment.as_deref(), Some(MARK)); + assert_eq!(cf.at("z1").len(), 1); + // Neither: the name is left empty. + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let Switched::Done { record, .. } = + switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap() + else { + panic!("not switched") + }; + assert_eq!( + revert_record(&cf, "z1", "blog.example.com", Some(&record.id), &[], None, MARK) + .await + .unwrap(), + None + ); + assert!(cf.at("z1").is_empty()); +} + +#[tokio::test] +async fn a_cname_changed_by_hand_is_left_when_switching_back() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let Switched::Done { record, .. } = + switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap() + else { + panic!("not switched") + }; + // Someone took the comment off: no longer Pyo's. + for (_, r) in cf.records.lock().unwrap().iter_mut() { + r.comment = Some("mine now".into()); + } + revert_record(&cf, "z1", "blog.example.com", Some(&record.id), &[], None, MARK) + .await + .unwrap(); + assert_eq!(cf.at("z1").len(), 1, "not Pyo's to delete"); +} + +#[tokio::test] +async fn a_cname_to_an_old_tunnel_is_repointed() { + let old = rec("c1", "CNAME", "blog.example.com", "old.cfargotunnel.com", Some(MARK)); + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]).with("z1", old); + let out = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + assert!(matches!(out, Switched::Done { .. })); + let now = cf.at("z1"); + assert_eq!(now.len(), 1); + assert_eq!(now[0].content, TARGET); +} + +#[tokio::test] +async fn the_certificate_is_issued_for_the_names_with_a_key_kept_here() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let names = vec!["*.example.com".to_owned(), "example.com".to_owned()]; + let (cert, key) = issue(&cf, &names).await.unwrap(); + assert!(key.contains("PRIVATE KEY")); + let issued = cf.certs.lock().unwrap().clone(); + assert_eq!(issued, vec![(cert.id.clone(), names.clone(), false)]); + // Without SSL and Certificates:Edit: said plainly. + let mut cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + cf.no_certs = vec!["z1".into()]; + let e = issue(&cf, &names).await.unwrap_err(); + assert_eq!( + e.to_string(), + "Cloudflare refused the token: give the token SSL and Certificates:Edit on the tunnel's zones." + ); +} + +#[test] +fn health_from_both_views() { + let agent = |w: i64, r: i64| json!({ "replicas": w, "readyReplicas": r }); + assert_eq!(health(&json!({}), &agent(2, 2), false), "unknown"); + assert_eq!(health(&json!({ "status": "healthy" }), &agent(2, 2), false), "connected"); + assert_eq!(health(&json!({ "status": "healthy" }), &agent(2, 1), false), "degraded"); + assert_eq!(health(&json!({ "status": "degraded" }), &agent(2, 2), false), "degraded"); + assert_eq!(health(&json!({ "status": "inactive" }), &agent(2, 0), true), "starting"); + assert_eq!(health(&json!({ "status": "down" }), &agent(2, 0), false), "down"); + assert_eq!(health(&json!({ "status": "inactive" }), &json!({}), false), "down"); +} + +#[test] +fn domains_take_the_tunnel_certificate_and_give_it_back() { + // Switching with a certificate already issued: kept, both paths answer. + let mut d = json!({ "id": "dom_1", "hostname": "blog.example.com", "tlsMode": "auto", "tls": "issued", "tunnel": "switching" }); + assert!(!take_certificate(&mut d, "crt_t")); + assert_eq!(d["tlsMode"], "auto"); + // Switched: the tunnel's, the old one kept. + d["tunnel"] = json!("on"); + assert!(take_certificate(&mut d, "crt_t")); + assert_eq!((d["tlsMode"].as_str(), d["certificateId"].as_str()), (Some("custom"), Some("crt_t"))); + assert_eq!(d["tlsModeBefore"], "auto"); + assert!(!take_certificate(&mut d, "crt_t"), "already"); + leave_tunnel(&mut d); + assert_eq!(d["tlsMode"], "auto"); + assert!(d.get("certificateId").is_none() && d.get("tunnel").is_none() && d.get("tlsModeBefore").is_none()); + // Not issued yet (a new domain): the tunnel's at once, even while switching. + let mut d = json!({ "id": "dom_2", "hostname": "new.example.com", "tlsMode": "auto", "tls": "pending", "tunnel": "switching" }); + assert!(take_certificate(&mut d, "crt_t")); + // An uploaded one comes back with its own id. + let mut d = json!({ "id": "dom_3", "hostname": "up.example.com", "tlsMode": "custom", "certificateId": "crt_mine", "tunnel": "on" }); + assert!(take_certificate(&mut d, "crt_t")); + leave_tunnel(&mut d); + assert_eq!((d["tlsMode"].as_str(), d["certificateId"].as_str()), (Some("custom"), Some("crt_mine"))); +} + +#[test] +fn free_names_are_one_label_under_the_default_domain() { + assert!(under_default("web-shop.example.com", "example.com")); + assert!(under_default("Web-Shop.Example.com", "example.com")); + assert!(!under_default("a.web-shop.example.com", "example.com"), "the wildcard covers one level"); + assert!(!under_default("example.com", "example.com")); + assert!(!under_default("web.notexample.com", "example.com")); + assert!(!under_default("web.example.com.evil.net", "example.com")); +} + +#[test] +fn free_names_get_their_own_route_and_no_wildcard() { + // A free name under the default domain is routed by name, like one + // switched by hand. Nothing routes the rest of the default domain. + let routes = tunnel::ingress(&["web-shop.example.com".into(), "blog.example.com".into()]); + let names: Vec<&str> = routes["ingress"] + .as_array() + .unwrap() + .iter() + .filter_map(|r| r["hostname"].as_str()) + .collect(); + assert_eq!(names, ["web-shop.example.com", "blog.example.com"]); +} diff --git a/crates/pyo-api/src/cloudflare/tunnel_ops.rs b/crates/pyo-api/src/cloudflare/tunnel_ops.rs new file mode 100644 index 00000000..da262345 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/tunnel_ops.rs @@ -0,0 +1,901 @@ +//! What people ask of a cluster's Cloudflare Tunnel (docs/cloudflare-tunnel.md +//! §5): the cluster's traffic, a domain through the tunnel or back, Rotate +//! and Remove. These only say what's wanted and return at once. The tunnel +//! loop (tunnel_loop.rs) does the Cloudflare work, so a slow Cloudflare +//! never holds a request. + +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use super::{Action, Zone, account, role_for, tunnel, zone_for}; +use crate::{ + AppState, + auth::User, + error::{ApiError, ApiResult}, + ops::{Role, log_activity, require_role, team_of}, +}; + +/// The traffic choices. +pub const MODES: [&str; 3] = ["public", "tailscale", "tunnel"]; + +/// Said when the cluster's install can't run a tunnel yet. +pub const INSTALL_FIRST: &str = "Run the command under Refresh this cluster in the cluster's settings first."; + +/// Said while the cluster's install is being brought up to date, by its +/// agent or by the server Pyo runs on: there's no command to run. +pub const INSTALL_UPDATING: &str = "This cluster is updating. Try again in a few minutes."; + +fn bad(m: impl Into) -> ApiError { + ApiError::bad_request(m.into()) +} + +/// The zones a tunnel in `account_id` may take: tunnel-ready, in that +/// account. +pub fn tunnel_zones<'a>(zones: &'a [Zone], account_id: &str) -> Vec<&'a Zone> { + zones + .iter() + .filter(|z| z.tunnel_ready() && z.account_id == account_id) + .collect() +} + +/// The account a tunnel goes in: the one asked for, else the default +/// domain's, else the only one with tunnel-ready zones. +pub fn pick_account( + zones: &[Zone], + asked: Option<&str>, + default_domain: Option<&str>, +) -> Result { + let mut accounts: Vec<&str> = zones + .iter() + .filter(|z| z.tunnel_ready() && !z.account_id.is_empty()) + .map(|z| z.account_id.as_str()) + .collect(); + accounts.sort(); + accounts.dedup(); + if accounts.is_empty() { + return Err("Give the Cloudflare token Cloudflare Tunnel:Edit and SSL and Certificates:Edit, then test it under Integrations.".into()); + } + if let Some(a) = asked { + return if accounts.contains(&a) { + Ok(a.to_owned()) + } else { + Err("The token can't make tunnels in that Cloudflare account.".into()) + }; + } + if let Some(d) = default_domain + && let Some(z) = zones.iter().find(|z| z.name == d) + { + return Ok(z.account_id.clone()); + } + match accounts.as_slice() { + [one] => Ok((*one).to_owned()), + _ => Err("Pick the Cloudflare account for the tunnel.".into()), + } +} + +/// The default domain as given: a tunnel-ready zone's own name (its apex), +/// since Cloudflare's free certificate covers only one level below it. +pub fn default_domain<'a>(zones: &'a [&'a Zone], given: &str) -> Result<&'a Zone, String> { + let d = given.trim().trim_end_matches('.').trim_start_matches("*.").to_ascii_lowercase(); + zones + .iter() + .copied() + .find(|z| z.name == d) + .ok_or_else(|| { + if zones.iter().any(|z| d.ends_with(&format!(".{}", z.name))) { + format!("Pick a zone itself, like {}, not a name under it.", zones[0].name) + } else { + "Pick one of your Cloudflare zones that can use the tunnel.".into() + } + }) +} + +/// Whether a cluster's install can run a tunnel: its agent says it can, +/// and its install is this Pyo's, roles included (the admission policy +/// lets the connector in, and the gateway's role its Services). An install +/// that's current except for its roles ("roles") waits too. Why not, when +/// it can't. +pub fn install_ready(capabilities: &Value) -> Result<(), &'static str> { + if capabilities["tunnel"] != json!(true) { + return Err("This cluster's agent doesn't run Cloudflare Tunnel yet. Update the agent first."); + } + match capabilities["agentInstall"]["state"].as_str() { + Some("current") | None => Ok(()), + Some("updating") => Err(INSTALL_UPDATING), + _ => Err(INSTALL_FIRST), + } +} + +/// A domain that can go through the tunnel: a hostname a tunnel-ready zone +/// of the tunnel's account covers. Not a free or tailnet domain. +fn can_tunnel(host: &str, zones: &[Zone], account_id: &str) -> Option { + if crate::freedomain::ip_in(host).is_some() || pyo_proto::system::is_tailnet_host(host) { + return None; + } + zone_for(host, zones) + .filter(|z| z.tunnel_ready() && z.account_id == account_id) + .cloned() +} + +/// What a switch to the tunnel makes of the domain's `tunnel`. A name +/// that's moving from the cluster's public ports takes `"switching"`, so +/// both paths answer while its record moves. One that's already only +/// through the tunnel (`"on"`: under the default domain's wildcard, or +/// switched before) stays as it is, so its gate never opens for a record +/// that changes nothing for direct visitors. None: leave it. +pub(crate) fn switch_state(now: Option<&str>) -> Option<&'static str> { + match now { + Some(pyo_proto::TUNNEL_ON) => None, + _ => Some(pyo_proto::TUNNEL_SWITCHING), + } +} + +/// Whether a name asked onto the tunnel is left to the default domain's +/// wildcard, with no record of its own: it's one level under the default +/// domain (`under`), new to the tunnel (no `tunnel` on the domain yet and +/// no record row), and nothing at Cloudflare answers for that exact name +/// (`found`: the records on it). A record there, Pyo's or anyone's, would +/// answer ahead of the wildcard, so the name takes the switch instead, +/// which replaces Pyo's own and asks before anyone else's. A name already +/// on the tunnel takes the switch too: someone asked for its own record. +pub(crate) fn left_to_wildcard(under: bool, tunnel: bool, has_row: bool, host: &str, found: &[tunnel::Kept]) -> bool { + under + && !tunnel + && !has_row + && !found + .iter() + .any(|k| matches!(k.kind.as_str(), "A" | "AAAA" | "CNAME") && super::same_name(&k.name, host)) +} + +/// What Switch back does for a domain. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) enum Back { + /// It isn't on the tunnel: nothing to do. + Direct, + /// A switch that never moved the record just stops. + Stop, + /// A switch that never moved the record stops, and the name stays on + /// the tunnel through the default domain's wildcard. + Stay, + /// Its record moves back, both paths first. + Revert, + /// The default domain's wildcard would take it straight back: said, + /// and nothing changes. + Refuse, +} + +/// What Switch back does for a domain. `under`: the tunnel's default +/// domain covers the name, so without a record of its own the loop puts +/// it through the wildcard (`free_domains_follow`). `record`: its record +/// row's (via, status). `tunnel`: the domain has `tunnel` set. +/// `puts_back`: a record it replaced comes back, which then answers for +/// the name ahead of the wildcard. +pub(crate) fn back_plan(under: bool, record: Option<(&str, &str)>, tunnel: bool, puts_back: bool) -> Back { + let via_tunnel = record.is_some_and(|(via, _)| via == "tunnel"); + let waiting = record.is_some_and(|(via, status)| via != "tunnel" && matches!(status, "switching" | "conflict")); + match (via_tunnel, tunnel, under) { + (true, _, true) if !puts_back => Back::Refuse, + (true, _, _) => Back::Revert, + (false, false, _) => Back::Direct, + (false, true, false) => Back::Stop, + (false, true, true) if waiting => Back::Stay, + (false, true, true) => Back::Refuse, + } +} + +/// Said when Switch back is asked for a name the default domain covers. +pub fn always_tunnel(host: &str) -> String { + format!("{host} is under the tunnel's default domain, so it always goes through the tunnel.") +} + +/// Ask for a domain's switch to the tunnel: its domain takes +/// `tunnel: "switching"` (both paths answer) unless it's already only +/// through the tunnel ([`switch_state`]), and its record row waits for the +/// loop, which moves the record once the agent has the routes. Whether the +/// domain's routes changed. +#[allow(clippy::too_many_arguments)] +async fn begin_switch( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + service_id: &str, + domain_id: &str, + host: &str, + zone: &Zone, + replace: bool, + now: Option<&str>, +) -> ApiResult { + sqlx::query( + "INSERT INTO pyo.dns_records (service_id, domain_id, team_id, hostname, zone_id, zone_name, type, status, replace, routes_command) + VALUES ($1, $2, $3, $4, $5, $6, 'CNAME', 'switching', $7, NULL) + ON CONFLICT (service_id, domain_id) DO UPDATE SET hostname = $4, zone_id = $5, zone_name = $6, status = 'switching', + replace = $7, error = NULL, existing = '[]', routes_command = NULL, updated_at = now()", + ) + .bind(service_id) + .bind(domain_id) + .bind(team_id) + .bind(host) + .bind(&zone.id) + .bind(&zone.name) + .bind(replace) + .execute(&mut **tx) + .await?; + match switch_state(now) { + Some(state) => { + set_tunnel(tx, service_id, domain_id, Some(state)).await?; + Ok(true) + } + None => Ok(false), + } +} + +async fn set_tunnel( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + domain_id: &str, + state: Option<&str>, +) -> ApiResult<()> { + let domains: Value = sqlx::query_scalar( + "SELECT coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1 FOR UPDATE", + ) + .bind(service_id) + .fetch_one(&mut **tx) + .await?; + let mut domains = domains; + if let Some(d) = domains + .as_array_mut() + .and_then(|ds| ds.iter_mut().find(|d| d["id"] == json!(domain_id))) + { + match state { + Some(s) => { + d["tunnel"] = json!(s); + // Cloudflare's address, not the cluster's: the loop says + // when it's ready. + d["status"] = json!("pending_dns"); + } + None => super::tunnel_loop::leave_tunnel(d), + } + } + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(service_id) + .bind(&domains) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// The service's routes follow, and its waiting rows wait for that sync. +async fn sync( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + wake: &mut Vec, +) -> ApiResult<()> { + if let Some((cluster, command)) = crate::routes::changed_waiting(tx, service_id).await? { + sqlx::query( + "UPDATE pyo.dns_records SET routes_command = $2 WHERE service_id = $1 AND status IN ('switching', 'reverting')", + ) + .bind(service_id) + .bind(&command) + .execute(&mut **tx) + .await?; + wake.push(cluster); + } + Ok(()) +} + +/// A cluster's tunnel as `setClusterTraffic` finds it: (state, account, +/// default domain, its zone, Pyo's wildcard record). +type Existing = (String, String, Option, Option, Option); + +/// `setClusterTraffic`. +#[allow(clippy::too_many_arguments)] +pub async fn set_traffic( + s: &AppState, + tx: &mut Transaction<'_, Postgres>, + user: &User, + cluster_id: &str, + mode: &str, + default_domain_given: Option<&str>, + account_asked: Option<&str>, + ports_public: Option, + wake: &mut Vec, +) -> ApiResult { + let team_id = team_of(tx, "clusters", cluster_id).await?; + require_role(tx, user, &team_id, Role::Admin).await?; + if !MODES.contains(&mode) { + return Err(bad("Pick public, tailscale or tunnel.")); + } + let (name, caps): (String, Value) = + sqlx::query_as("SELECT name, coalesce(capabilities, '{}') FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_one(&mut **tx) + .await?; + if mode != "tunnel" { + sqlx::query("UPDATE pyo.clusters SET traffic = $2 WHERE id = $1") + .bind(cluster_id) + .bind(mode) + .execute(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "cluster.updated", + "info", + &format!( + "{name} takes traffic {}", + if mode == "public" { "on public ports" } else { "from Tailscale only" } + ), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id }), + ) + .await?; + wake.push(cluster_id.to_owned()); + return Ok(json!({ "ok": true, "traffic": mode })); + } + install_ready(&caps).map_err(bad)?; + let a = account(s, tx, &team_id) + .await? + .ok_or_else(|| bad("Connect Cloudflare under Integrations first."))?; + let given = default_domain_given.map(str::trim).filter(|d| !d.is_empty()); + let account_id = pick_account(&a.zones, account_asked, given).map_err(bad)?; + let usable = tunnel_zones(&a.zones, &account_id); + let default = match given { + Some(d) => Some(default_domain(&usable, d).map_err(bad)?.clone()), + None => None, + }; + let account_name = usable + .first() + .map(|z| z.account_name.clone()) + .unwrap_or_default(); + let existing: Option = sqlx::query_as( + "SELECT state, account_id, default_domain, default_zone_id, default_record_id FROM pyo.cluster_tunnels WHERE cluster_id = $1 FOR UPDATE", + ) + .bind(cluster_id) + .fetch_optional(&mut **tx) + .await?; + match existing { + Some((state, _, _, _, _)) if state == "removing" => { + return Err(ApiError::conflict( + "The tunnel is still being removed. Try again in a minute.", + )); + } + Some((_, had_account, _, _, _)) if had_account != account_id => { + return Err(ApiError::conflict( + "This cluster's tunnel is in another Cloudflare account. Remove the tunnel first.", + )); + } + Some((_, _, old_domain, old_zone, old_record)) => { + // Another default domain: Pyo's old wildcard record goes. + if old_domain.as_deref() != default.as_ref().map(|z| z.name.as_str()) + && let (Some(zone), Some(id), Some(d)) = (&old_zone, &old_record, &old_domain) + { + let mark = super::marker(&super::install_id(tx).await?); + super::delete_ours(&super::Http::new(&a.token)?, zone, id, &format!("*.{d}"), &mark) + .await + .map_err(super::api_error)?; + } + sqlx::query( + "UPDATE pyo.cluster_tunnels SET default_domain = $2, default_zone_id = $3, + default_record_id = CASE WHEN default_domain IS DISTINCT FROM $2 THEN NULL ELSE default_record_id END, + ports_public = coalesce($4, ports_public), updated_at = now() + WHERE cluster_id = $1", + ) + .bind(cluster_id) + .bind(default.as_ref().map(|z| &z.name)) + .bind(default.as_ref().map(|z| &z.id)) + .bind(ports_public) + .execute(&mut **tx) + .await?; + } + None => { + let install = super::install_id(tx).await?; + sqlx::query( + "INSERT INTO pyo.cluster_tunnels (cluster_id, team_id, account_id, account_name, tunnel_name, default_domain, default_zone_id, ports_public, created_by) + VALUES ($1, $2, $3, $4, $5, $6, $7, coalesce($8, true), $9)", + ) + .bind(cluster_id) + .bind(&team_id) + .bind(&account_id) + .bind(&account_name) + .bind(tunnel::tunnel_name(cluster_id, &install, 0)) + .bind(default.as_ref().map(|z| &z.name)) + .bind(default.as_ref().map(|z| &z.id)) + .bind(ports_public) + .bind(&user.name) + .execute(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "cluster.tunnel_created", + "info", + &format!("Asked Cloudflare for a tunnel for {name}"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id, "accountId": account_id }), + ) + .await?; + } + } + sqlx::query("UPDATE pyo.clusters SET traffic = 'tunnel' WHERE id = $1") + .bind(cluster_id) + .execute(&mut **tx) + .await?; + // Its domains in the account move to the tunnel. Those with someone + // else's record wait at "confirm" for an owner or admin. + let services: Vec<(String, Value)> = sqlx::query_as( + "SELECT id, coalesce(spec->'domains', '[]') FROM pyo.services WHERE cluster_id = $1 AND NOT deleting ORDER BY id", + ) + .bind(cluster_id) + .fetch_all(&mut **tx) + .await?; + let mut moving = 0; + for (service_id, domains) in services { + let mut any = false; + for d in domains.as_array().into_iter().flatten() { + let host = d["hostname"].as_str().unwrap_or("").to_lowercase(); + if d["tunnel"].is_string() { + continue; + } + let Some(zone) = can_tunnel(&host, &a.zones, &account_id) else { + continue; + }; + let domain_id = d["id"].as_str().unwrap_or(""); + any |= begin_switch(tx, &team_id, &service_id, domain_id, &host, &zone, false, None).await?; + moving += 1; + } + if any { + sync(tx, &service_id, wake).await?; + } + } + log_activity( + tx, + &team_id, + &user.name, + "cluster.updated", + "info", + &format!("{name} takes websites through Cloudflare Tunnel"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id, "moving": moving }), + ) + .await?; + wake.push(cluster_id.to_owned()); + Ok(json!({ "ok": true, "traffic": "tunnel", "moving": moving })) +} + +/// `setDomainTunnel`. +#[allow(clippy::too_many_arguments)] +pub async fn set_domain( + s: &AppState, + tx: &mut Transaction<'_, Postgres>, + user: &User, + service_id: &str, + domain_id: &str, + on: bool, + replace: bool, + restore: bool, + wake: &mut Vec, +) -> ApiResult { + let team_id = team_of(tx, "services", service_id).await?; + let (cluster_id, domains): (String, Value) = sqlx::query_as( + "SELECT cluster_id, coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1 AND NOT deleting", + ) + .bind(service_id) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(|| ApiError::not_found("Service"))?; + let d = domains + .as_array() + .and_then(|ds| ds.iter().find(|d| d["id"] == json!(domain_id))) + .cloned() + .ok_or_else(|| ApiError::not_found("Domain"))?; + let host = d["hostname"].as_str().unwrap_or("").to_lowercase(); + let row: Option<(String, String, Option, Value)> = sqlx::query_as( + "SELECT r.status, r.via, NULL::text, r.previous FROM pyo.dns_records r WHERE r.service_id = $1 AND r.domain_id = $2", + ) + .bind(service_id) + .bind(domain_id) + .fetch_optional(&mut **tx) + .await?; + let kept = row + .as_ref() + .is_some_and(|r| r.3.as_array().is_some_and(|a| !a.is_empty())); + // Replacing someone's record, or putting one back: owners and admins. + let action = if replace || (!on && restore && kept) { + Action::ReplaceRecord + } else { + Action::CreateRecord + }; + require_role(tx, user, &team_id, role_for(action)).await?; + let tunnel_row: Option<(String, String, Option)> = sqlx::query_as( + "SELECT state, account_id, default_domain FROM pyo.cluster_tunnels WHERE cluster_id = $1", + ) + .bind(&cluster_id) + .fetch_optional(&mut **tx) + .await?; + let Some((_, account_id, default_domain)) = tunnel_row.filter(|(st, _, _)| st != "removing") else { + return Err(bad("This cluster has no Cloudflare Tunnel. Pick Cloudflare Tunnel under the cluster's Traffic first.")); + }; + // One level under the tunnel's default domain: its wildcard covers it. + let under = default_domain + .as_deref() + .is_some_and(|dd| super::tunnel_loop::under_default(&host, dd)); + let status = row.as_ref().map(|r| r.0.as_str()).unwrap_or(""); + let via = row.as_ref().map(|r| r.1.as_str()).unwrap_or("direct"); + if on { + let a = account(s, tx, &team_id) + .await? + .ok_or_else(|| bad("Connect Cloudflare under Integrations first."))?; + let Some(zone) = can_tunnel(&host, &a.zones, &account_id) else { + return Err(bad(format!( + "No zone of the tunnel's Cloudflare account can take {host} through the tunnel." + ))); + }; + if via == "tunnel" && status == "created" { + return Ok(json!({ "ok": true, "status": "active" })); + } + // A new name under the default domain: the wildcard record has it, + // so it needs no record of its own, whoever asks (dashboard, CLI, + // MCP, API). Only when Cloudflare says nothing else answers for + // the name. When Cloudflare can't be asked, the switch below finds + // out. + if under && row.is_none() && !d["tunnel"].is_string() { + use tunnel::TunnelApi; + let found = super::Http::new(&a.token)?.records_kept(&zone.id, &host).await; + if found.is_ok_and(|f| left_to_wildcard(under, false, false, &host, &f)) { + set_tunnel(tx, service_id, domain_id, Some(pyo_proto::TUNNEL_ON)).await?; + sync(tx, service_id, wake).await?; + log_activity( + tx, + &team_id, + &user.name, + "domain.tunnel", + "info", + &format!("{host} goes through the Cloudflare Tunnel, under its default domain"), + json!({ "kind": "service", "id": service_id, "label": host }), + json!({ "serviceId": service_id }), + ) + .await?; + return Ok(json!({ "ok": true, "status": "active" })); + } + } + // Already only through the tunnel: it stays gated while its own + // record is made, and the agent has nothing new to apply. + if begin_switch(tx, &team_id, service_id, domain_id, &host, &zone, replace, d["tunnel"].as_str()).await? { + sync(tx, service_id, wake).await?; + } + log_activity( + tx, + &team_id, + &user.name, + "domain.tunnel", + "info", + &format!("Asked to move {host} to the Cloudflare Tunnel"), + json!({ "kind": "service", "id": service_id, "label": host }), + json!({ "serviceId": service_id, "replace": replace }), + ) + .await?; + return Ok(json!({ "ok": true, "status": "switching" })); + } + // Back. A name under the default domain goes through the tunnel's + // wildcard whenever it has no record of its own, so moving it back + // would last until the loop's next pass: refused, unless a record it + // replaced comes back (that one answers ahead of the wildcard). + let plan = back_plan( + under, + row.as_ref().map(|r| (r.1.as_str(), r.0.as_str())), + d["tunnel"].is_string(), + restore && kept, + ); + let stop_waiting = "DELETE FROM pyo.dns_records WHERE service_id = $1 AND domain_id = $2 AND status IN ('switching', 'conflict') AND via = 'direct'"; + match plan { + Back::Refuse => return Err(bad(always_tunnel(&host))), + Back::Direct => return Ok(json!({ "ok": true, "status": "direct" })), + // A switch that never moved the record (still switching, or + // waiting for a yes) just stops. + Back::Stop => { + set_tunnel(tx, service_id, domain_id, None).await?; + sqlx::query(stop_waiting) + .bind(service_id) + .bind(domain_id) + .execute(&mut **tx) + .await?; + sync(tx, service_id, wake).await?; + return Ok(json!({ "ok": true, "status": "direct" })); + } + // The same, but the wildcard has the name: it stays only through + // the tunnel, without a moment off it. + Back::Stay => { + sqlx::query(stop_waiting) + .bind(service_id) + .bind(domain_id) + .execute(&mut **tx) + .await?; + if d["tunnel"] != json!(pyo_proto::TUNNEL_ON) { + set_tunnel(tx, service_id, domain_id, Some(pyo_proto::TUNNEL_ON)).await?; + sync(tx, service_id, wake).await?; + } + return Ok(json!({ "ok": true, "status": "active" })); + } + Back::Revert => {} + } + sqlx::query( + "UPDATE pyo.dns_records SET status = 'reverting', restore = $3, error = NULL, updated_at = now() + WHERE service_id = $1 AND domain_id = $2", + ) + .bind(service_id) + .bind(domain_id) + .bind(restore) + .execute(&mut **tx) + .await?; + // Both paths again before the record moves back. + set_tunnel(tx, service_id, domain_id, Some(pyo_proto::TUNNEL_SWITCHING)).await?; + sync(tx, service_id, wake).await?; + log_activity( + tx, + &team_id, + &user.name, + "domain.tunnel", + "info", + &format!("Asked to move {host} back from the Cloudflare Tunnel"), + json!({ "kind": "service", "id": service_id, "label": host }), + json!({ "serviceId": service_id, "restore": restore }), + ) + .await?; + Ok(json!({ "ok": true, "status": "reverting" })) +} + +/// `removeClusterTunnel`. +pub async fn remove( + tx: &mut Transaction<'_, Postgres>, + user: &User, + cluster_id: &str, + restore_records: bool, + wake: &mut Vec, +) -> ApiResult { + let team_id = team_of(tx, "clusters", cluster_id).await?; + require_role(tx, user, &team_id, Role::Admin).await?; + let (name, traffic): (String, String) = + sqlx::query_as("SELECT name, traffic FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_one(&mut **tx) + .await?; + if traffic == "tunnel" { + return Err(bad( + "Pick Public ports or Tailscale only for the cluster first.", + )); + } + let n = sqlx::query( + "UPDATE pyo.cluster_tunnels SET state = 'removing', restore_records = $2, token_sent_at = NULL, updated_at = now() + WHERE cluster_id = $1 AND state <> 'removing'", + ) + .bind(cluster_id) + .bind(restore_records) + .execute(&mut **tx) + .await? + .rows_affected(); + if n > 0 { + log_activity( + tx, + &team_id, + &user.name, + "cluster.tunnel_removing", + "warning", + &format!("Removing the Cloudflare Tunnel of {name}"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id, "restoreRecords": restore_records }), + ) + .await?; + } + wake.push(cluster_id.to_owned()); + Ok(json!({ "ok": true })) +} + +/// `rotateTunnelToken`. +pub async fn rotate( + tx: &mut Transaction<'_, Postgres>, + user: &User, + cluster_id: &str, +) -> ApiResult { + let team_id = team_of(tx, "clusters", cluster_id).await?; + require_role(tx, user, &team_id, Role::Admin).await?; + let n = sqlx::query( + "UPDATE pyo.cluster_tunnels SET rotate = true WHERE cluster_id = $1 AND state <> 'removing'", + ) + .bind(cluster_id) + .execute(&mut **tx) + .await? + .rows_affected(); + if n == 0 { + return Err(ApiError::not_found("Cloudflare Tunnel")); + } + let name: String = sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_one(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "cluster.tunnel_rotated", + "info", + &format!("Asked for a new Cloudflare Tunnel token and certificate for {name}"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id }), + ) + .await?; + Ok(json!({ "ok": true })) +} + +/// A cluster's Cloudflare Tunnel +/// +/// The cluster's tunnel as Pyo last saw it: its state, Cloudflare's view +/// (`health`, `connections`, `colos`), the connectors in the cluster +/// (`connectors`: each one's server, whether it's ready, and why not), its +/// default domain, its certificate, and `refused` when the cluster's install +/// is older than Pyo's. Never a token. Cloudflare's view is read again when +/// it's older than 30 seconds. +#[utoipa::path(get, path = "/clusters/{id}/tunnel", operation_id = "getClusterTunnel", tag = "Clusters", + params(("id" = String, Path, description = "The cluster's id (`cl_…`).")), + responses( + (status = 200, description = "`tunnel`: the cluster's tunnel, or null without one. `traffic`: \"public\", \"tailscale\" or \"tunnel\".", body = Object), + (status = 404, description = "No such cluster, or it isn't yours to see.", body = crate::error::ErrorBody), + ), + extensions(("x-pyo-access" = json!("read"))))] +pub async fn get( + axum::extract::State(s): axum::extract::State, + crate::auth::SessionUser(user): crate::auth::SessionUser, + axum::extract::Path(id): axum::extract::Path, +) -> ApiResult> { + let mut tx = crate::rls::begin(&s.db, &user).await?; + let team_id = team_of(&mut tx, "clusters", &id).await?; + require_role(&mut tx, &user, &team_id, Role::Viewer).await?; + tx.commit().await?; + // Cloudflare's view as of now (at most 30 seconds old). + super::tunnel_loop::refresh(&s, &id).await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; + let traffic: String = sqlx::query_scalar("SELECT traffic FROM pyo.clusters WHERE id = $1") + .bind(&id) + .fetch_one(&mut *tx) + .await?; + let tunnel = super::tunnel_loop::one_shown(&mut *tx, &id).await?; + tx.commit().await?; + Ok(crate::error::Json(json!({ "traffic": traffic, "tunnel": tunnel }))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cloudflare::tests::zone; + + fn in_account(id: &str, name: &str, account: &str) -> Zone { + Zone { + account_id: account.into(), + ..zone(id, name) + } + } + + #[test] + fn the_account_is_asked_for_only_when_it_isnt_clear() { + let one = [zone("z1", "example.com"), zone("z2", "other.org")]; + assert_eq!(pick_account(&one, None, None).unwrap(), "acct1"); + let two = [in_account("z1", "example.com", "a1"), in_account("z2", "other.org", "a2")]; + assert_eq!(pick_account(&two, None, None).unwrap_err(), "Pick the Cloudflare account for the tunnel."); + assert_eq!(pick_account(&two, None, Some("other.org")).unwrap(), "a2"); + assert_eq!(pick_account(&two, Some("a1"), None).unwrap(), "a1"); + assert!(pick_account(&two, Some("a9"), None).is_err()); + let mut dns_only = zone("z1", "example.com"); + dns_only.tunnel.ready = false; + assert!(pick_account(&[dns_only], None, None).unwrap_err().starts_with("Give the Cloudflare token")); + } + + #[test] + fn the_default_domain_is_a_zone_itself() { + let zones = [zone("z1", "example.com")]; + let usable: Vec<&Zone> = zones.iter().collect(); + assert_eq!(default_domain(&usable, "example.com").unwrap().id, "z1"); + assert_eq!(default_domain(&usable, "*.Example.com.").unwrap().id, "z1"); + assert_eq!( + default_domain(&usable, "apps.example.com").unwrap_err(), + "Pick a zone itself, like example.com, not a name under it." + ); + assert!(default_domain(&usable, "other.org").is_err()); + } + + #[test] + fn tunnel_mode_waits_for_an_install_that_can_run_it() { + assert_eq!(install_ready(&json!({})).unwrap_err(), "This cluster's agent doesn't run Cloudflare Tunnel yet. Update the agent first."); + assert_eq!( + install_ready(&json!({ "tunnel": true, "agentInstall": { "state": "outdated" } })).unwrap_err(), + INSTALL_FIRST + ); + assert_eq!( + install_ready(&json!({ "tunnel": true, "agentInstall": { "state": "updating" } })).unwrap_err(), + INSTALL_UPDATING + ); + assert!(!INSTALL_UPDATING.contains(';') && !INSTALL_UPDATING.contains("command")); + assert!(install_ready(&json!({ "tunnel": true, "agentInstall": { "state": "current" } })).is_ok()); + // A refresh that left the roles behind: the tunnel needs them. + assert_eq!( + install_ready(&json!({ "tunnel": true, "agentInstall": { "state": "roles", "bundles": true } })).unwrap_err(), + INSTALL_FIRST + ); + assert!(!INSTALL_FIRST.contains(';')); + } + + #[test] + fn a_name_already_on_the_tunnel_stays_gated_while_its_record_is_made() { + // Moving from public: both paths while the record moves. + assert_eq!(switch_state(None), Some("switching")); + assert_eq!(switch_state(Some("switching")), Some("switching")); + // Under the wildcard, or switched before: never back to both paths. + assert_eq!(switch_state(Some("on")), None); + } + + #[test] + fn a_new_name_under_the_default_domain_gets_no_record_of_its_own() { + let kept = |kind: &str, name: &str| tunnel::Kept { + id: "r1".into(), + kind: kind.into(), + name: name.into(), + content: "203.0.113.7".into(), + proxied: false, + ttl: 1, + comment: None, + }; + let host = "web-shop.example.com"; + // Nothing on the name: the wildcard has it. + assert!(left_to_wildcard(true, false, false, host, &[])); + // Records that don't answer for a website, or for another name, don't matter. + assert!(left_to_wildcard(true, false, false, host, &[kept("TXT", host), kept("MX", host)])); + assert!(left_to_wildcard(true, false, false, host, &[kept("A", "other.example.com")])); + // A record on that exact name answers ahead of the wildcard: the + // switch takes it (and stops at "conflict" for someone else's). + for kind in ["A", "AAAA", "CNAME"] { + assert!(!left_to_wildcard(true, false, false, host, &[kept(kind, "Web-Shop.example.com.")]), "{kind}"); + } + // Outside the default domain: always its own record. + assert!(!left_to_wildcard(false, false, false, "blog.other.org", &[])); + // Already on the tunnel, or with a record row: someone asked for + // its own record, so it gets one (and stays gated meanwhile). + assert!(!left_to_wildcard(true, true, false, host, &[])); + assert!(!left_to_wildcard(true, false, true, host, &[])); + } + + #[test] + fn switch_back_is_refused_under_the_default_domain() { + let created = Some(("tunnel", "created")); + // Outside the default domain: Switch back as ever. + assert_eq!(back_plan(false, created, true, false), Back::Revert); + assert_eq!(back_plan(false, created, true, true), Back::Revert); + assert_eq!(back_plan(false, Some(("direct", "conflict")), true, false), Back::Stop); + assert_eq!(back_plan(false, Some(("direct", "switching")), true, false), Back::Stop); + assert_eq!(back_plan(false, Some(("direct", "created")), false, false), Back::Direct); + assert_eq!(back_plan(false, None, false, false), Back::Direct); + // Under it, the wildcard takes the name back: refused, with its own + // record or only the wildcard. + assert_eq!(back_plan(true, created, true, false), Back::Refuse); + assert_eq!(back_plan(true, None, true, false), Back::Refuse); + assert_eq!(back_plan(true, None, true, true), Back::Refuse); + // A record it replaced comes back and answers ahead of the wildcard. + assert_eq!(back_plan(true, created, true, true), Back::Revert); + // A switch waiting for a yes can be cancelled: it stays on the tunnel. + assert_eq!(back_plan(true, Some(("direct", "conflict")), true, false), Back::Stay); + assert_eq!(back_plan(true, Some(("direct", "switching")), true, false), Back::Stay); + // A direct record of its own wins over the wildcard: it is direct. + assert_eq!(back_plan(true, Some(("direct", "created")), false, false), Back::Direct); + let said = always_tunnel("web-shop.example.com"); + assert_eq!(said, "web-shop.example.com is under the tunnel's default domain, so it always goes through the tunnel."); + assert!(!said.contains(';') && !said.contains(" - ")); + } + + #[test] + fn free_and_tailnet_domains_stay_direct() { + let zones = [zone("z1", "example.com"), in_account("z2", "other.org", "a2")]; + assert!(can_tunnel("blog.example.com", &zones, "acct1").is_some()); + assert!(can_tunnel("blog.other.org", &zones, "acct1").is_none(), "another account"); + assert!(can_tunnel("web.203.0.113.7.nip.io", &zones, "acct1").is_none()); + assert!(can_tunnel("web.tail1234.ts.net", &zones, "acct1").is_none()); + assert!(can_tunnel("blog.nowhere.dev", &zones, "acct1").is_none()); + } +} diff --git a/crates/pyo-api/src/compose.rs b/crates/pyo-api/src/compose.rs index 29944432..a58c0775 100644 --- a/crates/pyo-api/src/compose.rs +++ b/crates/pyo-api/src/compose.rs @@ -73,6 +73,10 @@ pub struct PlanProject { pub name: String, /// Its slug, used in service addresses: lowercase letters, digits and dashes. pub namespace: String, + /// The Compose file's name, e.g. "compose.yaml". Its services remember + /// it, so a later sync finds them. + #[serde(default)] + pub file: String, } #[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] @@ -94,6 +98,34 @@ pub struct PlanService { pub container: pyo_proto::ContainerOverrides, /// Services it starts after. pub depends_on: Vec, + /// What the file sets, which a sync keeps in line with it: "source", + /// "env", "ports", "volumes", "health", "replicas", "resources.cpuLimit" + /// and the other resources, "container.command" and the other container + /// settings, and the `x-pyo` ones ("domains", "behindCdn", "placement", + /// "secrets"). The rest stays as it is in Pyo. + #[serde(default)] + pub managed: Vec, + /// `x-pyo.domains`: served on its first web port. + #[serde(default)] + pub domains: Vec, + /// `x-pyo.behindCdn`: "cloudflare", or none. + #[serde(default)] + pub behind_cdn: Option, + /// `x-pyo.placement`: `{"servers": [...], "tags": [...]}`. + #[serde(default)] + #[schema(value_type = Option)] + pub placement: Option, + /// `x-pyo.secrets`: secret variables it needs, by name. Their values + /// are set in Pyo, never in the file. + #[serde(default)] + pub secrets: Vec, +} + +impl PlanService { + /// Whether the file sets this (see `managed`). + pub fn manages(&self, field: &str) -> bool { + self.managed.iter().any(|m| m == field) + } } #[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] @@ -722,6 +754,174 @@ const UNSUPPORTED: &[(&str, &str)] = &[ ("oom_score_adj", "Out-of-memory priority isn't changed."), ]; +/// Service keys of `x-pyo` that templates use (pyo-templates' schema.json). +/// The template catalog reads them, so an import leaves them alone. +const TEMPLATE_KEYS: [&str; 3] = ["workload", "gpu", "expose"]; + +/// A service's own `x-pyo`: the settings Compose has no field for. +#[derive(Default)] +struct XPyo { + domains: Vec, + /// Set: `Some(None)` takes it out of a CDN. + behind_cdn: Option>, + health: Option, + replicas: Option, + placement: Option, + secrets: Vec, +} + +/// Text, or a list of it. +fn texts(v: &Value) -> Option> { + match v { + Value::Null => Some(vec![]), + Value::String(s) => Some(vec![s.clone()]), + Value::Array(a) => a.iter().map(|x| x.as_str().map(str::to_owned)).collect(), + _ => None, + } +} + +fn env_name(k: &str) -> bool { + !k.is_empty() + && !k.as_bytes()[0].is_ascii_digit() + && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +} + +fn x_pyo(v: Option<&Value>, sn: Option<&str>, w: &mut Warnings) -> XPyo { + let mut x = XPyo::default(); + let Some(v) = v.filter(|v| !v.is_null()) else { + return x; + }; + let Some(m) = v.as_object() else { + w.add( + sn, + "x-pyo", + "x-pyo holds Pyo's settings by name (domains, replicas…), so it's left out.", + ); + return x; + }; + for (k, v) in m { + let field = format!("x-pyo.{k}"); + match k.as_str() { + "domains" => match texts(v) { + Some(ds) => { + for d in ds { + let d = d.trim().trim_end_matches('.').to_lowercase(); + if d.is_empty() { + continue; + } + if !crate::util::hostname(&d) { + w.add( + sn, + &field, + format!("{d} isn't a domain like app.example.com, so it's left out."), + ); + } else if !x.domains.contains(&d) { + x.domains.push(d); + } + } + } + None => w.add( + sn, + &field, + "domains is a list like [app.example.com], so it's left out.", + ), + }, + "behindCdn" => match v { + Value::Null | Value::Bool(false) => x.behind_cdn = Some(None), + Value::String(c) if c == "none" => x.behind_cdn = Some(None), + Value::String(c) => match crate::firewall::check_behind(Some(c)) { + Ok(c) => x.behind_cdn = Some(c), + Err(_) => w.add( + sn, + &field, + format!("{c} isn't a CDN Pyo knows: use cloudflare or none."), + ), + }, + _ => w.add(sn, &field, "behindCdn is cloudflare or none."), + }, + "health" => match v.as_str() { + Some(h) if h == "tcp" || h == "none" || h.starts_with('/') => { + x.health = Some(h.to_owned()); + } + _ => w.add( + sn, + &field, + "health is a path like /healthz, or tcp or none, so it's left out.", + ), + }, + "replicas" => match v.as_i64().filter(|n| (0..=i64::from(i32::MAX)).contains(n)) { + Some(n) => x.replicas = Some(n as i32), + None => w.add(sn, &field, "replicas is a whole number, 0 or more."), + }, + "placement" => { + let Some(p) = v.as_object() else { + w.add( + sn, + &field, + "placement has servers or tags, like {tags: [eu]}, so it's left out.", + ); + continue; + }; + let mut out = json!({ "servers": [], "tags": [] }); + let mut ok = true; + for (pk, pv) in p { + let list = texts(pv); + match (pk.as_str(), list) { + ("servers", Some(l)) => out["servers"] = json!(l), + ("tags", Some(l)) => { + if let Some(bad) = + l.iter().find(|t| pyo_proto::valid_tag(t).is_none()) + { + w.add(sn, &field, format!("{bad} isn't a tag: tags are lowercase letters, digits and dashes. Placement is left out.")); + ok = false; + } + out["tags"] = json!(l); + } + _ => { + w.add( + sn, + &field, + format!("placement.{pk} isn't used: placement has servers and tags."), + ); + } + } + } + if ok { + x.placement = Some(out); + } + } + "secrets" => match texts(v) { + Some(names) => { + for n in names { + let n = n.trim().to_owned(); + if !env_name(&n) { + w.add( + sn, + &field, + format!("{n:?} isn't a variable name, so it's left out."), + ); + } else if !x.secrets.contains(&n) { + x.secrets.push(n); + } + } + } + None => w.add( + sn, + &field, + "secrets is a list of variable names, so it's left out.", + ), + }, + k if TEMPLATE_KEYS.contains(&k) => {} + _ => w.add( + sn, + &field, + format!("x-pyo.{k} isn't a Pyo setting, so it's left out."), + ), + } + } + x +} + /// The plan for a Compose file. pub fn plan(input: &Input) -> Result { let mut w = Warnings(vec![]); @@ -796,6 +996,11 @@ pub fn plan(input: &Input) -> Result { }, 40, ), + file: input + .repo + .as_ref() + .map(|r| r.path.clone()) + .unwrap_or_default(), }; // Names in Pyo, unique, and what changed. @@ -844,6 +1049,13 @@ pub fn plan(input: &Input) -> Result { w.add(sn, field, *why); } } + let x = x_pyo(svc.get("x-pyo"), sn, &mut w); + let present = |k: &str| { + svc.get(k).is_some_and(|v| { + !v.is_null() && v.as_array().is_none_or(|a| !a.is_empty()) + }) + }; + let mut managed: Vec = vec!["source".into(), "env".into()]; // Source: an image, or a build from the repository. let image = svc @@ -1122,15 +1334,43 @@ pub fn plan(input: &Input) -> Result { "No port is declared: if other services connect to it, add the port it listens on.", ); } + if present("ports") || present("expose") { + managed.push("ports".into()); + } + let mut domains = x.domains.clone(); + if !domains.is_empty() { + let web = ports + .iter() + .position(|p| p.public && p.protocol == "HTTP") + .or_else(|| ports.iter().position(|p| p.protocol == "HTTP")); + match web { + Some(i) => { + for p in &mut ports { + p.domain = None; + } + ports[i].public = true; + ports[i].domain = domains.first().cloned(); + managed.push("domains".into()); + if !managed.iter().any(|m| m == "ports") { + managed.push("ports".into()); + } + } + None => { + w.add(sn, "x-pyo.domains", "It has no web port to serve its domains on: add the port it listens on under ports or expose."); + domains.clear(); + } + } + } if ports.iter().any(|p| p.public && p.protocol == "HTTP") && input.domain_base.is_none() + && domains.is_empty() && first_http { first_http = false; w.add( None, "ports", - "Public web ports need a domain: pick a cluster for a free one, or enter your own.", + "Public web ports need a domain: pick a cluster to get one, or enter your own.", ); } @@ -1199,6 +1439,20 @@ pub fn plan(input: &Input) -> Result { } _ => {} } + // Secrets take no value from the file. + unset.retain(|k| !x.secrets.contains(k)); + let given: Vec = env + .iter() + .filter(|e| x.secrets.contains(&e.key) && !e.value.is_empty()) + .map(|e| e.key.clone()) + .collect(); + if !given.is_empty() { + w.add(sn, "x-pyo.secrets", format!("Secrets take their values from Pyo, not the file, so the file's {} isn't used.", given.join(", "))); + } + env.retain(|e| !x.secrets.contains(&e.key)); + if !x.secrets.is_empty() { + managed.push("secrets".into()); + } if !unset.is_empty() { w.add(sn, "environment", format!("Taken from the shell in Compose and not set here, so left out: {}. Add the ones it needs.", unset.join(", "))); } @@ -1279,6 +1533,10 @@ pub fn plan(input: &Input) -> Result { } } + if present("volumes") { + managed.push("volumes".into()); + } + // Health check. let first_port = ports.first().map(|p| p.container_port); let health = svc.get("healthcheck").and_then(Value::as_object); @@ -1319,7 +1577,7 @@ pub fn plan(input: &Input) -> Result { .and_then(|v| duration_secs(&scalar(v))) .unwrap_or(5) .clamp(0, 600); - let health_check = match (disabled, command, first_port) { + let mut health_check = match (disabled, command, first_port) { (false, Some(c), p) => { json!({ "type": "exec", "command": c, "path": "", "port": p.unwrap_or(0), "initialDelaySeconds": delay, "periodSeconds": period }) } @@ -1331,6 +1589,30 @@ pub fn plan(input: &Input) -> Result { } }; + if health.is_some() { + managed.push("health".into()); + if health.is_some_and(|h| h.contains_key("interval") || h.contains_key("start_period")) { + managed.push("healthTiming".into()); + } + } + if let Some(h) = &x.health { + let web = ports + .iter() + .find(|p| p.protocol == "HTTP") + .or(ports.first()) + .map(|p| p.container_port); + let kind = if h.starts_with('/') { "http" } else { h.as_str() }; + match (kind, web) { + ("none", _) | ("http" | "tcp", Some(_)) => { + health_check = json!({ "type": kind, "command": "", "path": if kind == "http" { h.as_str() } else { "" }, "port": if kind == "none" { 0 } else { web.unwrap_or(0) }, "initialDelaySeconds": delay, "periodSeconds": period }); + if !managed.iter().any(|m| m == "health") { + managed.push("health".into()); + } + } + _ => w.add(sn, "x-pyo.health", "It has no port to check: add the port it listens on under ports or expose."), + } + } + // Replicas and resources. let deploy = svc.get("deploy").and_then(Value::as_object); if deploy @@ -1353,12 +1635,16 @@ pub fn plan(input: &Input) -> Result { ); } } - let replicas = deploy + let compose_replicas = deploy .and_then(|d| d.get("replicas")) .and_then(Value::as_i64) - .or_else(|| svc.get("scale").and_then(Value::as_i64)) - .unwrap_or(1) - .clamp(0, i32::MAX as i64) as i32; + .or_else(|| svc.get("scale").and_then(Value::as_i64)); + if compose_replicas.is_some() || x.replicas.is_some() { + managed.push("replicas".into()); + } + let replicas = x.replicas.unwrap_or_else(|| { + compose_replicas.unwrap_or(1).clamp(0, i32::MAX as i64) as i32 + }); let limits = deploy .and_then(|d| d.get("resources")) .and_then(|r| r.get("limits")); @@ -1415,6 +1701,17 @@ pub fn plan(input: &Input) -> Result { } } } + for (k, set) in [ + ("resources.cpuLimit", cpu_limit.is_some()), + ("resources.memoryLimit", mem_limit.is_some()), + ("resources.cpuRequest", cpu_request.is_some()), + ("resources.memoryRequest", mem_request.is_some()), + ("resources.gpu", !gpu_devices.is_empty()), + ] { + if set { + managed.push(k.into()); + } + } let cpu_request = cpu_request.unwrap_or_else(|| cpu_limit.map(|l| l.min(100)).unwrap_or(100)); let memory_request = @@ -1449,6 +1746,23 @@ pub fn plan(input: &Input) -> Result { } } + for (k, field) in [ + ("entrypoint", "container.entrypoint"), + ("command", "container.command"), + ("working_dir", "container.workingDir"), + ("user", "container.user"), + ] { + if svc.get(k).is_some_and(|v| !v.is_null()) { + managed.push(field.into()); + } + } + if x.behind_cdn.is_some() { + managed.push("behindCdn".into()); + } + if x.placement.is_some() { + managed.push("placement".into()); + } + let depends_on: Vec = match svc.get("depends_on") { Some(Value::Array(a)) => a.iter().map(scalar).collect(), Some(Value::Object(m)) => m.keys().cloned().collect(), @@ -1478,6 +1792,11 @@ pub fn plan(input: &Input) -> Result { resources, container, depends_on: deps, + managed, + domains, + behind_cdn: x.behind_cdn.flatten(), + placement: x.placement, + secrets: x.secrets, }); } @@ -1529,9 +1848,49 @@ pub fn plan(input: &Input) -> Result { }) } +/// A plan port as a service's port. +pub fn port_json(p: &PlanPort, id: String) -> Value { + let exposure = exposure(p); + let mut v = json!({ "id": id, "name": p.name, "protocol": p.protocol, "containerPort": p.container_port, "exposure": exposure }); + if exposure == "loadbalancer" { + // Published TCP and UDP ports go through the gateway. + v["proxy"] = json!(true); + if let Some(pp) = p.public_port { + v["publicPort"] = json!(pp); + } + } + v +} + +/// "internal", "http" (a website) or "loadbalancer" (a public TCP or UDP port). +pub fn exposure(p: &PlanPort) -> &'static str { + match (p.public, p.protocol.as_str()) { + (false, _) => "internal", + (true, "HTTP") => "http", + (true, _) => "loadbalancer", + } +} + +/// A new domain of a service, on its port `port`. +pub fn domain_json(hostname: &str, port: &str, id: String, now: i64) -> Value { + let private = crate::deploy::private_host(hostname); + json!({ "id": id, "hostname": hostname, "portName": port, "status": "pending_dns", "tls": "pending", "tlsMode": "auto", "redirectHttps": !private, "createdAt": now }) +} + +/// What a service made from a Compose file remembers of it: the file, and +/// its name there. +pub fn record(file: &str, compose_name: &str) -> Value { + let file = file.trim(); + json!({ "file": if file.is_empty() { "compose.yaml" } else { file }, "service": compose_name }) +} + /// A plan service as the service object `createService` takes. +#[allow(clippy::too_many_arguments)] pub fn service_spec( s: &PlanService, + // The Compose file it's from, which it remembers. None for a service + // that isn't kept in line with a file (a platform import's). + file: Option<&str>, id: &str, team_id: &str, project_id: &str, @@ -1539,36 +1898,39 @@ pub fn service_spec( now: i64, new_id: &dyn Fn(&str) -> String, ) -> Value { - let env: Vec = s.env.iter().map(|e| json!({ "id": new_id("env"), "key": e.key, "value": e.value, "secret": e.secret, "updatedAt": now })).collect(); + let mut env: Vec = s.env.iter().map(|e| json!({ "id": new_id("env"), "key": e.key, "value": e.value, "secret": e.secret, "updatedAt": now })).collect(); + // Secrets it needs get their values in Pyo. + for k in &s.secrets { + if !s.env.iter().any(|e| &e.key == k) { + env.push(json!({ "id": new_id("env"), "key": k, "value": "", "secret": true, "updatedAt": now })); + } + } let ports: Vec = s .ports .iter() - .map(|p| { - let exposure = match (p.public, p.protocol.as_str()) { - (false, _) => "internal", - (true, "HTTP") => "http", - (true, _) => "loadbalancer", - }; - let mut v = json!({ "id": new_id("port"), "name": p.name, "protocol": p.protocol, "containerPort": p.container_port, "exposure": exposure }); - if exposure == "loadbalancer" { - // Published TCP and UDP ports go through the gateway. - v["proxy"] = json!(true); - if let Some(pp) = p.public_port { - v["publicPort"] = json!(pp); - } - } - v - }) + .map(|p| port_json(p, new_id("port"))) .collect(); - let domains: Vec = s - .ports + let mut hosts: Vec<(String, String)> = vec![]; + for p in s.ports.iter().filter(|p| p.public && p.protocol == "HTTP") { + if let Some(d) = p + .domain + .as_ref() + .map(|d| d.trim().to_lowercase()) + .filter(|d| !d.is_empty()) + { + hosts.push((d, p.name.clone())); + } + } + if let Some(web) = s.ports.iter().find(|p| p.public && p.protocol == "HTTP") { + for d in &s.domains { + if !hosts.iter().any(|(h, _)| h == d) { + hosts.push((d.clone(), web.name.clone())); + } + } + } + let domains: Vec = hosts .iter() - .filter(|p| p.public && p.protocol == "HTTP") - .filter_map(|p| p.domain.as_ref().filter(|d| !d.trim().is_empty()).map(|d| (p, d.trim().to_lowercase()))) - .map(|(p, d)| { - let private = crate::deploy::private_host(&d); - json!({ "id": new_id("dom"), "hostname": d, "portName": p.name, "status": "pending_dns", "tls": "pending", "tlsMode": "auto", "redirectHttps": !private, "createdAt": now }) - }) + .map(|(h, p)| domain_json(h, p, new_id("dom"), now)) .collect(); let source = if s.source.kind == "git" { json!({ @@ -1587,9 +1949,15 @@ pub fn service_spec( "resources": { "cpuRequest": s.resources.cpu_request, "cpuLimit": s.resources.cpu_limit, "memoryRequest": s.resources.memory_request, "memoryLimit": s.resources.memory_limit, "gpu": s.resources.gpu }, "replicas": s.replicas, "healthCheck": s.health_check, }); + if let Some(f) = file { + spec["compose"] = record(f, &s.compose_name); + } if !s.container.is_empty() { spec["container"] = serde_json::to_value(&s.container).unwrap_or(Value::Null); } + if let Some(p) = &s.placement { + spec["placement"] = p.clone(); + } spec } @@ -1622,9 +1990,13 @@ pub struct PreviewBody { /// The project's name, when the file has none. #[serde(default)] pub name: Option, + /// The file's name, e.g. "compose.yaml". Its services remember it, so a + /// later sync finds them. A repository's file is named by its path. + #[serde(default)] + pub file_name: Option, } -#[derive(Debug, Deserialize, utoipa::ToSchema)] +#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] pub struct RepoInput { /// "owner/repo". @@ -1655,10 +2027,21 @@ pub async fn preview( crate::auth::SessionUser(user): crate::auth::SessionUser, crate::error::Json(b): crate::error::Json, ) -> crate::error::ApiResult> { + Ok(crate::error::Json(read_plan(&s, &user, &b).await?)) +} + +/// The plan of the file a preview or a sync names, for a team its user can +/// see. +pub(crate) async fn read_plan( + s: &crate::AppState, + user: &crate::auth::User, + b: &PreviewBody, +) -> crate::error::ApiResult { use crate::error::ApiError; let mut tx = s.db.begin().await?; - crate::ops::require_role(&mut tx, &user, &b.team_id, crate::ops::Role::Viewer).await?; - // Free domains go on the cluster's public address (none without one). + crate::ops::require_role(&mut tx, user, &b.team_id, crate::ops::Role::Viewer).await?; + // Free domains go on the cluster's free-domain address, or in tunnel + // mode under its default domain (none without either). let domain_base = match &b.cluster_id { Some(id) => { sqlx::query_scalar::<_, String>( @@ -1669,9 +2052,7 @@ pub async fn preview( .fetch_optional(&mut *tx) .await? .ok_or_else(|| ApiError::not_found("Cluster"))?; - crate::freedomain::for_cluster(&mut tx, id) - .await? - .map(|ip| format!("{ip}.nip.io")) + crate::freedomain::suffix_for(&mut tx, id).await? } None => None, }; @@ -1693,7 +2074,7 @@ pub async fn preview( .trim_end_matches(".git") .to_owned(); let (text, installation) = - crate::github::read_file(&s, &b.team_id, &repo, &r.branch, &r.path) + crate::github::read_file(s, &b.team_id, &repo, &r.branch, &r.path) .await? .ok_or_else(|| ApiError::not_found(&format!("{} on {}", r.path, r.branch)))?; let dir = r @@ -1730,7 +2111,7 @@ pub async fn preview( wanted.dedup(); for f in wanted.into_iter().take(20) { if let Some((t, _)) = - crate::github::read_file(&s, &b.team_id, &repo, &r.branch, &near(&f)).await? + crate::github::read_file(s, &b.team_id, &repo, &r.branch, &near(&f)).await? { files.insert(f, t); } @@ -1761,7 +2142,7 @@ pub async fn preview( .clone() .filter(|n| !n.trim().is_empty()) .unwrap_or(hint); - let plan = plan(&Input { + let mut plan = plan(&Input { file: &text, files, repo, @@ -1769,7 +2150,16 @@ pub async fn preview( domain_base, }) .map_err(ApiError::bad_request)?; - Ok(crate::error::Json(plan)) + if let Some(f) = b + .file_name + .as_deref() + .map(str::trim) + .filter(|f| !f.is_empty()) + && plan.project.file.is_empty() + { + plan.project.file = f.chars().take(200).collect(); + } + Ok(plan) } #[cfg(test)] @@ -2183,4 +2573,131 @@ mod tests { .any(|e| e.key == "API_URL" && e.value == "http://api:8000") ); } + + #[test] + fn x_pyo_settings_and_their_mistakes() { + let file = r#" +services: + web: + image: nginx:1.27 + expose: ["80"] + x-pyo: + domains: [Shop.Example.com, "not a domain", shop.example.com] + behindCdn: fastly + health: healthz + replicas: -1 + placement: { tags: [Bad_Tag] } + secrets: [API_KEY, "1BAD"] + domain: oops + workload: StatefulSet + worker: + image: busybox + x-pyo: + domains: [w.example.com] + health: tcp + placement: { servers: [fal1], tags: [eu] } + behindCdn: none +"#; + let p = plan(&Input { + file, + name_hint: "shop", + ..Default::default() + }) + .unwrap(); + let web = svc(&p, "web"); + assert_eq!(web.domains, vec!["shop.example.com"]); + assert!(web.ports[0].public, "a domain makes its web port public"); + assert_eq!(web.secrets, vec!["API_KEY"]); + assert!(web.behind_cdn.is_none() && !web.manages("behindCdn")); + assert!(web.placement.is_none() && !web.manages("replicas")); + assert_eq!(web.health_check["type"], "tcp", "the default stays"); + for field in [ + "x-pyo.domains", + "x-pyo.behindCdn", + "x-pyo.health", + "x-pyo.replicas", + "x-pyo.placement", + "x-pyo.secrets", + "x-pyo.domain", + ] { + assert!(warned(&p, Some("web"), field), "{field}"); + } + assert!(!warned(&p, Some("web"), "x-pyo.workload"), "a template's key"); + let worker = svc(&p, "worker"); + assert!(worker.domains.is_empty(), "no web port to serve it on"); + assert!(warned(&p, Some("worker"), "x-pyo.domains")); + assert!(warned(&p, Some("worker"), "x-pyo.health"), "no port to check"); + assert_eq!( + worker.placement, + Some(json!({ "servers": ["fal1"], "tags": ["eu"] })) + ); + assert!(worker.manages("behindCdn") && worker.behind_cdn.is_none()); + } + + fn without_x_pyo(v: &mut Value) { + if let Some(m) = v.as_object_mut() { + m.remove("x-pyo"); + m.values_mut().for_each(without_x_pyo); + } + if let Some(a) = v.as_array_mut() { + a.iter_mut().for_each(without_x_pyo); + } + } + + /// The templates of pyo-templates (next to this repository, or at + /// PYO_TEMPLATES_DIR) import as they did before: their `x-pyo` is for + /// the template catalog, so it changes nothing here and warns about + /// nothing. + #[test] + fn every_template_imports_as_before() { + let dir = std::env::var_os("PYO_TEMPLATES_DIR") + .map(std::path::PathBuf::from) + .or_else(|| { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .ancestors() + .map(|a| a.join("pyo-templates/templates")) + .find(|d| d.is_dir()) + }); + let Some(dir) = dir else { + eprintln!("pyo-templates isn't next to this repository, so no templates were read"); + return; + }; + let mut names: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.join("compose.yaml").is_file()) + .collect(); + names.sort(); + assert!(!names.is_empty(), "no templates in {}", dir.display()); + for t in &names { + let name = t.file_name().unwrap().to_string_lossy(); + let text = std::fs::read_to_string(t.join("compose.yaml")).unwrap(); + let read = |text: &str| { + plan(&Input { + file: text, + name_hint: &name, + domain_base: Some("1.2.3.4.nip.io".into()), + ..Default::default() + }) + .unwrap_or_else(|e| panic!("{name}: {e}")) + }; + let with = read(&text); + let mut doc = read_yaml(&text).unwrap(); + without_x_pyo(&mut doc); + // JSON is YAML too. + let without = read(&doc.to_string()); + assert_eq!( + serde_json::to_value(&with).unwrap(), + serde_json::to_value(&without).unwrap(), + "{name}" + ); + assert!( + with.warnings.iter().all(|w| !w.field.starts_with("x-pyo")), + "{name}: {:?}", + with.warnings + ); + } + eprintln!("{} templates imported as before", names.len()); + } } diff --git a/crates/pyo-api/src/compose_sync.rs b/crates/pyo-api/src/compose_sync.rs new file mode 100644 index 00000000..6809210e --- /dev/null +++ b/crates/pyo-api/src/compose_sync.rs @@ -0,0 +1,1280 @@ +//! Compose sync: a Compose file applied again to the project made from it +//! (or linked to it) changes only what the file says differently. The plan +//! lists each service as added, changed (and what), unchanged, or no longer +//! in the file. `syncCompose` works the plan out again in its own +//! transaction and applies it through the same operations the dashboard +//! uses, with their checks. +//! +//! - Only what the file sets is compared (`PlanService::managed`). A setting +//! changed in Pyo that the file doesn't mention stays as it is. +//! - Variables, ports, domains and volumes the file lists are added or +//! changed. Ones it doesn't list stay. +//! - A secret keeps its value in Pyo, whatever the file says. +//! - What can't change in place (a volume that would move, another kind of +//! source) is a manual step: listed, and left as it is. +//! - A service no longer in the file is only listed. With `prune` it's +//! deleted (its volumes are kept, detached), and only when it was made +//! from this file. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use crate::compose::{self, ComposePlan, PlanService, PlanVolume, PlanWarning}; +use crate::error::{ApiError, ApiResult}; + +/// What a sync would change. +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SyncPlan { + /// The project it syncs. None when there's none for this file yet: then + /// `importCompose` makes it from `file`. + pub project: Option, + /// The file's services in deploy order, then the project's services that + /// aren't in the file. + pub services: Vec, + /// What the file has that Pyo doesn't carry over. + pub warnings: Vec, + /// The file as Pyo reads it: pass it to `syncCompose` (or `importCompose`). + pub file: ComposePlan, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SyncProject { + pub id: String, + pub name: String, + pub namespace: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SyncService { + /// Its name in Pyo. + pub name: String, + /// Its name in the file. None when it isn't in the file. + #[serde(default)] + pub compose_name: Option, + /// None for a service the sync would add. + #[serde(default)] + pub service_id: Option, + /// "added", "changed", "unchanged" or "notInFile". + pub status: String, + pub changes: Vec, + /// What stays as it is in Pyo, and why. + pub notes: Vec, + /// What can't change in place. It's left as it is: change it by hand. + pub manual: Vec, + /// The sync deploys it. + pub deploy: bool, + /// For a service not in the file: it was made from this file, so + /// `prune` deletes it. + #[serde(default)] + pub from_file: bool, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SyncChange { + /// What changes, e.g. "image", "replicas", "env LOG_LEVEL", "domain app.example.com". + pub field: String, + /// As it is now. Variables' values are never shown. + #[serde(default)] + pub from: Option, + #[serde(default)] + pub to: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SyncNote { + pub field: String, + pub message: String, +} + +/// A service of the project, as the sync sees it. +#[derive(Debug, Clone, Default)] +pub struct Existing { + pub id: String, + pub name: String, + /// As stored: secrets sealed. + pub spec: Value, + pub behind_cdn: Option, + /// Its volumes' data: name, mountPath, sizeGi. + pub volumes: Vec, +} + +impl Existing { + /// The Compose service it was made from. + fn compose_name(&self) -> Option<&str> { + self.spec["compose"]["service"].as_str() + } +} + +/// One service brought in line with the file. +#[derive(Debug, Default)] +pub struct Merged { + /// Its new spec (secrets still sealed). + pub spec: Value, + pub changes: Vec, + pub notes: Vec, + pub manual: Vec, + pub deploy: bool, + /// A new CDN setting. + pub behind_cdn: Option>, + /// Volumes to add. + pub volumes: Vec, + /// Nothing changes but what it remembers of the file. + pub record_only: bool, +} + +impl Merged { + fn change(&mut self, field: impl Into, from: Option, to: Option) { + self.changes.push(SyncChange { + field: field.into(), + from, + to, + }); + } +} + +fn note(field: impl Into, message: impl Into) -> SyncNote { + SyncNote { + field: field.into(), + message: message.into(), + } +} + +fn image_words(image: &str, reference: &str) -> String { + if reference.starts_with("sha256:") { + format!("{image}@{reference}") + } else { + format!("{image}:{reference}") + } +} + +fn source_words(kind: &str) -> String { + match kind { + "image" => "deployed from an image".into(), + "git" => "built from Git".into(), + "upload" => "built from a folder".into(), + "template" => "deployed from a template".into(), + k => format!("from {k}"), + } +} + +fn health_words(h: &Value) -> String { + let port = h["port"].as_i64().unwrap_or(0); + match h["type"].as_str().unwrap_or("none") { + "http" => format!("{} on {port}", h["path"].as_str().unwrap_or("/")), + "tcp" => format!("tcp on {port}"), + "exec" => "a command".into(), + _ => "none".into(), + } +} + +fn placement_words(p: &crate::placement::Placement) -> String { + if p.any() { + return "any server".into(); + } + let mut parts = vec![]; + if !p.servers.is_empty() { + parts.push(p.servers.join(", ")); + } + if !p.tags.is_empty() { + parts.push(format!( + "{} {}", + if p.tags.len() == 1 { "tag" } else { "tags" }, + p.tags.join(", ") + )); + } + parts.join(" and ") +} + +fn port_words(exposure: &str, public_port: Option) -> String { + match (exposure, public_port) { + ("http", _) => "public".into(), + ("loadbalancer", Some(p)) => format!("public on {p}"), + ("loadbalancer" | "nodeport", None) => "public".into(), + _ => "inside the project".into(), + } +} + +fn sorted(mut p: crate::placement::Placement) -> crate::placement::Placement { + p.servers.sort(); + p.tags.sort(); + p +} + +/// A name for a new port that none of the service's ports has. +fn free_port_name(ports: &[Value], want: &str, protocol: &str, port: u16) -> String { + let taken = |n: &str| ports.iter().any(|p| p["name"] == json!(n)); + if !taken(want) { + return want.to_owned(); + } + let base = format!("{}-{port}", protocol.to_lowercase()); + let mut name = base.clone(); + let mut n = 2; + while taken(&name) { + name = format!("{base}-{n}"); + n += 1; + } + name +} + +/// A volume's name without its service's in front, as `addVolume` takes it. +pub fn volume_label(service: &str, volume: &str) -> String { + volume + .strip_prefix(&format!("{service}-")) + .filter(|l| !l.is_empty()) + .unwrap_or(volume) + .to_owned() +} + +/// `old` brought in line with what the file sets for it (`want`). +pub fn merge( + old: &Existing, + want: &PlanService, + file: &str, + now: i64, + new_id: &dyn Fn(&str) -> String, +) -> Merged { + let mut m = Merged::default(); + let mut spec = old.spec.clone(); + if !spec.is_object() { + spec = json!({}); + } + + // Its source. + let kind = spec["source"]["type"].as_str().unwrap_or("").to_owned(); + match (kind.as_str(), want.source.kind.as_str()) { + ("image", "image") => { + let src = &mut spec["source"]; + let from = image_words( + src["image"].as_str().unwrap_or(""), + src["reference"].as_str().unwrap_or(""), + ); + let to = image_words(&want.source.image, &want.source.reference); + if from != to { + src["image"] = json!(want.source.image); + src["reference"] = json!(want.source.reference); + m.change("image", Some(from), Some(to)); + m.deploy = true; + } + } + ("git" | "upload", "git") => { + let mut fields = vec![ + ("buildContext", "build context", &want.source.build_context), + ("dockerfilePath", "Dockerfile", &want.source.dockerfile_path), + ]; + if kind == "git" && !want.source.repo_url.is_empty() { + fields.push(("repoUrl", "repository", &want.source.repo_url)); + fields.push(("branch", "branch", &want.source.branch)); + } + for (key, label, to) in fields { + let src = &mut spec["source"]; + let from = src[key].as_str().unwrap_or("").to_owned(); + if &from != to { + src[key] = json!(to); + m.change(label, Some(from), Some(to.clone())); + m.deploy = true; + } + } + for a in &want.source.build_args { + let src = &mut spec["source"]; + if !src["buildArgs"].is_array() { + src["buildArgs"] = json!([]); + } + let Some(args) = src["buildArgs"].as_array_mut() else { + continue; + }; + match args.iter_mut().find(|x| x["key"] == json!(a.key)) { + Some(x) if x["value"] == json!(a.value) => {} + Some(x) => { + x["value"] = json!(a.value); + m.change(format!("build argument {}", a.key), None, None); + m.deploy = true; + } + None => { + args.push(json!({ "key": a.key, "value": a.value })); + m.change( + format!("build argument {}", a.key), + None, + Some("added".into()), + ); + m.deploy = true; + } + } + } + } + (from, to) => m.manual.push(note( + "source", + format!( + "It's {} in Pyo and {} in the file. Change its source in the dashboard.", + source_words(from), + source_words(to) + ), + )), + } + + // Variables: the file's are added or changed, a secret's value stays. + if !spec["env"].is_array() { + spec["env"] = json!([]); + } + for e in &want.env { + let field = format!("env {}", e.key); + let Some(env) = spec["env"].as_array_mut() else { + break; + }; + match env.iter_mut().find(|o| o["key"] == json!(e.key)) { + Some(o) if o["secret"] == json!(true) => { + if !e.value.is_empty() { + m.notes + .push(note(field, "It's a secret in Pyo, so its value stays.")); + } + } + Some(o) if o["value"].as_str() == Some(e.value.as_str()) => {} + Some(o) => { + o["value"] = json!(e.value); + o["updatedAt"] = json!(now); + m.change(field, None, None); + m.deploy = true; + } + None => { + env.push(json!({ "id": new_id("env"), "key": e.key, "value": e.value, "secret": e.secret, "updatedAt": now })); + m.change(field, None, Some("added".into())); + m.deploy = true; + } + } + } + for k in &want.secrets { + let field = format!("secret {k}"); + let Some(env) = spec["env"].as_array_mut() else { + break; + }; + match env.iter().find(|o| o["key"] == json!(k)) { + Some(o) if o["secret"] == json!(true) => {} + Some(_) => m.manual.push(note( + field, + "It's a plain variable in Pyo. Make it a secret in the dashboard.", + )), + None => { + env.push(json!({ "id": new_id("env"), "key": k, "value": "", "secret": true, "updatedAt": now })); + m.change(field.clone(), None, Some("added".into())); + m.notes.push(note(field, "Set its value in Pyo, then deploy.")); + } + } + } + + // Ports, matched by number (and UDP or not). + if want.manages("ports") { + if !spec["ports"].is_array() { + spec["ports"] = json!([]); + } + for p in &want.ports { + let field = format!("port {}", p.container_port); + let udp = p.protocol == "UDP"; + let want_exposure = compose::exposure(p); + let Some(ports) = spec["ports"].as_array_mut() else { + break; + }; + let found = ports.iter().position(|o| { + o["containerPort"].as_u64() == Some(u64::from(p.container_port)) + && (o["protocol"] == json!("UDP")) == udp + }); + let Some(i) = found else { + let name = free_port_name(ports, &p.name, &p.protocol, p.container_port); + let mut v = compose::port_json(p, new_id("port")); + v["name"] = json!(name); + ports.push(v); + m.change( + field, + None, + Some(port_words(want_exposure, p.public_port.map(u64::from))), + ); + m.deploy = true; + continue; + }; + let o = &mut ports[i]; + if !udp && o["protocol"] != json!(p.protocol) { + let from = o["protocol"].as_str().unwrap_or("").to_owned(); + o["protocol"] = json!(p.protocol); + m.change(field.clone(), Some(from), Some(p.protocol.clone())); + m.deploy = true; + } + let exposure = o["exposure"].as_str().unwrap_or("internal").to_owned(); + let from = port_words(&exposure, o["publicPort"].as_u64()); + let to = port_words(want_exposure, p.public_port.map(u64::from)); + match (exposure.as_str(), want_exposure) { + ("loadbalancer", "loadbalancer") => { + if let Some(pp) = p.public_port + && o["publicPort"].as_u64() != Some(u64::from(pp)) + { + o["publicPort"] = json!(pp); + m.change(field, Some(from), Some(to)); + m.deploy = true; + } + } + (a, b) if a == b => {} + ("http" | "loadbalancer" | "nodeport", "internal") => m + .notes + .push(note(field, "It's public in Pyo, so it stays public.")), + (_, "http") => { + // A website's port: its domains go live in place. + o["exposure"] = json!("http"); + if let Some(x) = o.as_object_mut() { + x.remove("publicPort"); + x.remove("proxy"); + } + m.change(field, Some(from), Some(to)); + if exposure != "internal" { + m.deploy = true; + } + } + _ => { + o["exposure"] = json!(want_exposure); + o["proxy"] = json!(true); + if let Some(pp) = p.public_port { + o["publicPort"] = json!(pp); + } + m.change(field, Some(from), Some(to)); + m.deploy = true; + } + } + } + } + + // Domains: the file's are added on its web port. + if want.manages("domains") { + if !spec["domains"].is_array() { + spec["domains"] = json!([]); + } + let ports = spec["ports"].as_array().cloned().unwrap_or_default(); + // The port the file serves them on, else its first website port. + let wanted_port = want + .ports + .iter() + .find(|p| p.public && p.protocol == "HTTP") + .map(|p| p.container_port); + let web = ports + .iter() + .find(|o| { + o["exposure"] == json!("http") + && wanted_port + .is_some_and(|w| o["containerPort"].as_u64() == Some(u64::from(w))) + }) + .or_else(|| ports.iter().find(|o| o["exposure"] == json!("http"))) + .and_then(|o| o["name"].as_str()) + .map(str::to_owned); + for d in &want.domains { + let Some(domains) = spec["domains"].as_array_mut() else { + break; + }; + if domains.iter().any(|o| { + o["hostname"] + .as_str() + .is_some_and(|h| h.eq_ignore_ascii_case(d)) + }) { + continue; + } + match &web { + Some(port) => { + domains.push(compose::domain_json(d, port, new_id("dom"), now)); + m.change(format!("domain {d}"), None, Some("added".into())); + } + None => m.manual.push(note( + format!("domain {d}"), + "It has no public web port in Pyo to serve it on. Make one public in the dashboard.", + )), + } + } + } + + // Health check. + if want.manages("health") { + let old_h = spec["healthCheck"].clone(); + let mut h = want.health_check.clone(); + if !want.manages("healthTiming") { + for k in ["initialDelaySeconds", "periodSeconds"] { + if let Some(v) = old_h.get(k) { + h[k] = v.clone(); + } + } + } + let same = old_h.get("auto").is_none_or(Value::is_null) + && [ + "type", + "path", + "port", + "command", + "initialDelaySeconds", + "periodSeconds", + ] + .iter() + .all(|k| old_h[*k] == h[*k]); + if !same { + m.change( + "health check", + Some(health_words(&old_h)), + Some(health_words(&h)), + ); + spec["healthCheck"] = h; + m.deploy = true; + } + } + + // Replicas, unless autoscaling sets them. + if want.manages("replicas") { + if spec.get("autoscale").is_some_and(|a| !a.is_null()) { + if spec["replicas"].as_i64() != Some(i64::from(want.replicas)) { + m.notes.push(note( + "replicas", + "Autoscaling sets them, so they stay as they are.", + )); + } + } else if spec["replicas"].as_i64() != Some(i64::from(want.replicas)) { + m.change( + "replicas", + spec["replicas"].as_i64().map(|n| n.to_string()), + Some(want.replicas.to_string()), + ); + spec["replicas"] = json!(want.replicas); + m.deploy = true; + } + } + + // Resources the file sets. + let r = &want.resources; + let mut set_resource = false; + for (field, key, value, label) in [ + ("resources.cpuLimit", "cpuLimit", r.cpu_limit, "cpu limit"), + ( + "resources.memoryLimit", + "memoryLimit", + r.memory_limit, + "memory limit", + ), + ("resources.cpuRequest", "cpuRequest", r.cpu_request, "cpu request"), + ( + "resources.memoryRequest", + "memoryRequest", + r.memory_request, + "memory request", + ), + ("resources.gpu", "gpu", r.gpu, "GPUs"), + ] { + if !want.manages(field) { + continue; + } + if !spec["resources"].is_object() { + spec["resources"] = json!({}); + } + let now_v = spec["resources"][key].as_i64(); + if now_v != Some(value) { + let unit = |n: i64| match key { + "cpuLimit" | "cpuRequest" => format!("{n}m"), + "gpu" => n.to_string(), + _ => format!("{n} MiB"), + }; + m.change(label, now_v.map(unit), Some(unit(value))); + spec["resources"][key] = json!(value); + set_resource = true; + } + } + if set_resource { + // A request is never above its limit. + for (req, lim) in [("cpuRequest", "cpuLimit"), ("memoryRequest", "memoryLimit")] { + let res = &mut spec["resources"]; + if let (Some(a), Some(b)) = (res[req].as_i64(), res[lim].as_i64()) + && a > b + { + res[req] = json!(b); + } + } + m.deploy = true; + } + + // How it starts. + let c = &want.container; + let mut container = spec + .get("container") + .cloned() + .filter(Value::is_object) + .unwrap_or_else(|| json!({})); + let mut set_container = false; + for (field, key, value, label) in [ + ( + "container.entrypoint", + "entrypoint", + json!(c.entrypoint), + "entrypoint", + ), + ("container.command", "command", json!(c.command), "command"), + ( + "container.workingDir", + "workingDir", + json!(c.working_dir), + "working directory", + ), + ] { + if !want.manages(field) { + continue; + } + let now_v = match container.get(key) { + None | Some(Value::Null) if value.is_array() => json!([]), + None | Some(Value::Null) => json!(""), + Some(v) => v.clone(), + }; + if now_v != value { + m.change(label, None, None); + container[key] = value; + set_container = true; + } + } + if want.manages("container.user") { + for (key, value) in [("runAsUser", c.run_as_user), ("runAsGroup", c.run_as_group)] { + if container.get(key).and_then(Value::as_i64) != value { + container[key] = json!(value); + set_container = true; + if !m.changes.iter().any(|x| x.field == "user") { + m.change("user", None, None); + } + } + } + } + if set_container { + // Empty ones keep the image's own. + if let Some(o) = container.as_object_mut() { + o.retain(|_, v| { + !(v.is_null() + || v.as_array().is_some_and(Vec::is_empty) + || v.as_str().is_some_and(str::is_empty)) + }); + } + if container.as_object().is_some_and(|o| o.is_empty()) { + if let Some(o) = spec.as_object_mut() { + o.remove("container"); + } + } else { + spec["container"] = container; + } + m.deploy = true; + } + + // Where it runs: changed in place. + if want.manages("placement") { + let wanted = json!({ "placement": want.placement.clone().unwrap_or(Value::Null) }); + let (from, to) = ( + sorted(crate::placement::Placement::of(&spec)), + sorted(crate::placement::Placement::of(&wanted)), + ); + if from != to { + m.change( + "placement", + Some(placement_words(&from)), + Some(placement_words(&to)), + ); + if let Some(o) = spec.as_object_mut() { + o.remove("servers"); + o.remove("serverTags"); + o.insert("placement".into(), to.to_value()); + } + } + } + + // Volumes, matched by where they're mounted. + if want.manages("volumes") { + for v in &want.volumes { + if old + .volumes + .iter() + .any(|o| o["mountPath"] == json!(v.mount_path)) + { + continue; + } + let label = volume_label(&old.name, &v.name); + let full = format!("{}-{label}", old.name); + let named = old.volumes.iter().find(|o| { + o["name"] == json!(v.name) || o["name"] == json!(full) + }); + match named { + Some(o) => m.manual.push(note( + format!("volume {}", o["name"].as_str().unwrap_or(&v.name)), + format!( + "It's mounted at {} in Pyo and {} in the file. Detach it and attach it at {} to move it.", + o["mountPath"].as_str().unwrap_or(""), + v.mount_path, + v.mount_path + ), + )), + None => { + m.change( + format!("volume {full}"), + None, + Some(format!("added at {}", v.mount_path)), + ); + m.volumes.push(v.clone()); + m.deploy = true; + } + } + } + } + + // Behind a CDN: changed in place. + if want.manages("behindCdn") && old.behind_cdn != want.behind_cdn { + m.change( + "behind CDN", + Some(old.behind_cdn.clone().unwrap_or_else(|| "none".into())), + Some(want.behind_cdn.clone().unwrap_or_else(|| "none".into())), + ); + m.behind_cdn = Some(want.behind_cdn.clone()); + } + + // What it remembers of the file. + let record = compose::record(file, &want.compose_name); + if spec.get("compose") != Some(&record) { + spec["compose"] = record; + m.record_only = m.changes.is_empty(); + } + m.spec = spec; + m +} + +/// The file's services and the project's, paired: a service made from a +/// Compose service matches it by that name, any other by its own name. +fn pair<'a>( + file: &'a ComposePlan, + existing: &'a [Existing], +) -> Vec<(Option<&'a PlanService>, Option<&'a Existing>)> { + let mut used = vec![false; existing.len()]; + let mut out = vec![]; + for want in &file.services { + let by_record = existing + .iter() + .enumerate() + .position(|(i, e)| !used[i] && e.compose_name() == Some(want.compose_name.as_str())); + let by_name = || { + existing.iter().enumerate().position(|(i, e)| { + !used[i] + && e.name == want.name + && e.compose_name().is_none_or(|c| { + !file.services.iter().any(|s| s.compose_name == c) + }) + }) + }; + match by_record.or_else(by_name) { + Some(i) => { + used[i] = true; + out.push((Some(want), Some(&existing[i]))); + } + None => out.push((Some(want), None)), + } + } + for (i, e) in existing.iter().enumerate() { + if !used[i] { + out.push((None, Some(e))); + } + } + out +} + +/// The file names a service's record and the file are compared by. +fn same_file(a: &str, b: &str) -> bool { + let base = |s: &str| s.trim().rsplit('/').next().unwrap_or("").to_owned(); + let (a, b) = ( + if a.trim().is_empty() { "compose.yaml" } else { a }, + if b.trim().is_empty() { "compose.yaml" } else { b }, + ); + base(a) == base(b) +} + +/// What syncing `file` into a project with `existing` services would do. +pub fn plan_of(project: Option, file: ComposePlan, existing: &[Existing]) -> SyncPlan { + let now = pyo_proto::now_ms(); + let new_id = |p: &str| crate::ids::new_id(p); + let mut services = vec![]; + for (want, old) in pair(&file, existing) { + match (want, old) { + (Some(w), None) => services.push(SyncService { + name: w.name.clone(), + compose_name: Some(w.compose_name.clone()), + status: "added".into(), + notes: w + .secrets + .iter() + .filter(|k| !w.env.iter().any(|e| &e.key == *k)) + .map(|k| note(format!("secret {k}"), "Set its value in Pyo, then deploy.")) + .collect(), + deploy: true, + ..Default::default() + }), + (Some(w), Some(o)) => { + let m = merge(o, w, &file.project.file, now, &new_id); + services.push(SyncService { + name: o.name.clone(), + compose_name: Some(w.compose_name.clone()), + service_id: Some(o.id.clone()), + status: if m.changes.is_empty() { + "unchanged" + } else { + "changed" + } + .into(), + deploy: m.deploy, + changes: m.changes, + notes: m.notes, + manual: m.manual, + from_file: true, + }); + } + (None, Some(o)) => { + let made_from = o.spec["compose"]["file"].as_str(); + let from_file = made_from.is_some_and(|f| same_file(f, &file.project.file)); + let notes = match made_from { + Some(f) if !from_file => { + vec![note("source", format!("It was made from {f}."))] + } + None => vec![note("source", "It wasn't made from a Compose file.")], + _ => vec![], + }; + services.push(SyncService { + name: o.name.clone(), + service_id: Some(o.id.clone()), + status: "notInFile".into(), + notes, + from_file, + ..Default::default() + }); + } + (None, None) => {} + } + } + SyncPlan { + project, + services, + warnings: file.warnings.clone(), + file, + } +} + +// ── Reading the project ────────────────────────────────────────────────────── + +/// The project's services a sync compares: not previews, not being deleted. +pub async fn existing( + tx: &mut Transaction<'_, Postgres>, + project_id: &str, +) -> ApiResult> { + let rows: Vec<(String, String, Value, Option)> = sqlx::query_as( + "SELECT id, name, spec, behind_cdn FROM pyo.services + WHERE project_id = $1 AND NOT deleting AND preview_of IS NULL + ORDER BY created_at, id", + ) + .bind(project_id) + .fetch_all(&mut **tx) + .await?; + let volumes: Vec<(String, Value)> = sqlx::query_as( + "SELECT service_id, data FROM pyo.volumes + WHERE project_id = $1 AND service_id IS NOT NULL AND NOT deleting", + ) + .bind(project_id) + .fetch_all(&mut **tx) + .await?; + let mut out = vec![]; + for (id, name, mut spec, behind_cdn) in rows { + // Variables are compared in the clear. Secrets never are: they're + // left blank, so a sync never opens them, and a save keeps them. + blank_secrets(&mut spec); + crate::vault::get().open_env(&mut spec).await?; + out.push(Existing { + volumes: volumes + .iter() + .filter(|(s, _)| *s == id) + .map(|(_, d)| d.clone()) + .collect(), + id, + name, + spec, + behind_cdn, + }); + } + Ok(out) +} + +/// The project a sync goes to: the one named, else the team's project made +/// from a Compose file of this name (its namespace). +async fn find_project( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + project_id: Option<&str>, + namespace: &str, +) -> ApiResult> { + let row: Option<(String, String, String)> = match project_id.filter(|p| !p.is_empty()) { + Some(id) => Some( + sqlx::query_as( + "SELECT id, name, namespace FROM pyo.projects WHERE id = $1 AND team_id = $2", + ) + .bind(id) + .bind(team_id) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(|| ApiError::not_found("Project"))?, + ), + None => { + sqlx::query_as( + "SELECT p.id, p.name, p.namespace FROM pyo.projects p + WHERE p.team_id = $1 AND p.namespace = $2 + AND EXISTS (SELECT 1 FROM pyo.services a + WHERE a.project_id = p.id AND NOT a.deleting AND a.spec ? 'compose')", + ) + .bind(team_id) + .bind(namespace) + .fetch_optional(&mut **tx) + .await? + } + }; + Ok(row.map(|(id, name, namespace)| SyncProject { + id, + name, + namespace, + })) +} + +// ── The plan endpoint ──────────────────────────────────────────────────────── + +/// A Compose file to sync: its text, or a file in one of the team's GitHub +/// repositories, and the project it goes to. +#[derive(Debug, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SyncBody { + /// The team it's for. + pub team_id: String, + /// The project to sync. Without it: the team's project made from a + /// Compose file of the same name, when there's one. + #[serde(default)] + pub project_id: Option, + /// The Compose file's text, when it isn't read from a repository. + #[serde(default)] + pub file: Option, + /// A .env file's text, for `${VAR}`s and `env_file: .env`. + #[serde(default)] + pub env: Option, + /// Or: a repository the team's GitHub App installations can see. + #[serde(default)] + pub repo: Option, + /// The cluster new services go to: their public web ports get a free + /// domain on it. + #[serde(default)] + pub cluster_id: Option, + /// The project's name, when the file has none. + #[serde(default)] + pub name: Option, + /// The file's name, e.g. "compose.yaml". Services remember it. + #[serde(default)] + pub file_name: Option, +} + +/// Plan a Docker Compose sync +/// +/// What applying a Compose file to the project made from it would change, +/// service by service: added, changed (and what), unchanged, or not in the +/// file. Only what the file sets is compared, so settings changed in Pyo +/// that the file doesn't mention stay. A secret's value is never changed. +/// What can't change in place is listed under `manual` and left as it is. +/// Nothing changes. Pass `file` to the `syncCompose` operation to apply it, +/// or to `importCompose` when there's no `project` yet. +/// +/// Besides Compose, each service's `x-pyo` can set `domains`, `behindCdn` +/// ("cloudflare" or "none"), `health` (a path like "/healthz", "tcp" or +/// "none"), `replicas`, `placement` (`{"servers": [...], "tags": [...]}`) +/// and `secrets` (variable names; their values are set in Pyo). +#[utoipa::path(post, path = "/compose/sync-plan", operation_id = "planComposeSync", tag = "Projects", + request_body = SyncBody, + responses( + (status = 200, description = "The plan.", body = SyncPlan), + (status = 400, description = "Not a Compose file Pyo can read, nothing importable, or no file given.", body = crate::error::ErrorBody), + (status = 404, description = "No such team, project, cluster or file.", body = crate::error::ErrorBody), + (status = 502, description = "GitHub couldn't be read.", body = crate::error::ErrorBody), + ), + extensions(("x-pyo-access" = json!("read"))))] +pub async fn plan( + axum::extract::State(s): axum::extract::State, + crate::auth::SessionUser(user): crate::auth::SessionUser, + crate::error::Json(b): crate::error::Json, +) -> ApiResult> { + let file = compose::read_plan( + &s, + &user, + &compose::PreviewBody { + team_id: b.team_id.clone(), + file: b.file, + env: b.env, + repo: b.repo, + cluster_id: b.cluster_id, + name: b.name, + file_name: b.file_name, + }, + ) + .await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; + let project = find_project( + &mut tx, + &b.team_id, + b.project_id.as_deref(), + &file.project.namespace, + ) + .await?; + let existing = match &project { + Some(p) => existing(&mut tx, &p.id).await?, + None => vec![], + }; + tx.commit().await?; + Ok(crate::error::Json(plan_of(project, file, &existing))) +} + +// ── Applying it ────────────────────────────────────────────────────────────── + +/// A secret goes back blank, so the save keeps its sealed value. +fn blank_secrets(spec: &mut Value) { + let blank = |env: &mut Value| { + for e in env.as_array_mut().into_iter().flatten() { + if e["secret"] == json!(true) { + e["value"] = json!(""); + } + } + }; + blank(&mut spec["env"]); + if let Some(env) = spec.get_mut("previews").and_then(|p| p.get_mut("env")) { + blank(env); + } +} + +/// `syncCompose`: the plan worked out again, then applied through the +/// operations it stands for. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn apply( + s: &crate::AppState, + tx: &mut Transaction<'_, Postgres>, + user: &crate::auth::User, + project_id: &str, + cluster_id: Option, + file: ComposePlan, + prune: bool, + confirm: bool, + wake: &mut Vec, +) -> ApiResult { + use crate::ops::{Op, Role, nested, require_role, team_of}; + let team_id = team_of(tx, "projects", project_id).await?; + require_role(tx, user, &team_id, Role::Developer).await?; + if file.services.is_empty() || file.services.len() > 40 { + return Err(ApiError::bad_request( + "A Compose file has 1 to 40 services.", + )); + } + for svc in &file.services { + crate::util::require_dns_label(&svc.name, "Service name")?; + } + let (name, namespace): (String, String) = + sqlx::query_as("SELECT name, namespace FROM pyo.projects WHERE id = $1") + .bind(project_id) + .fetch_one(&mut **tx) + .await?; + let existing = existing(tx, project_id).await?; + let plan = plan_of( + Some(SyncProject { + id: project_id.to_owned(), + name: name.clone(), + namespace, + }), + file.clone(), + &existing, + ); + let now = pyo_proto::now_ms(); + let new_id = |p: &str| crate::ids::new_id(p); + let mut cluster: Option = None; + let mut done = vec![]; + for ss in &plan.services { + let want = ss + .compose_name + .as_ref() + .and_then(|c| file.services.iter().find(|w| &w.compose_name == c)); + let old = ss + .service_id + .as_ref() + .and_then(|id| existing.iter().find(|e| &e.id == id)); + match (ss.status.as_str(), want, old) { + ("added", Some(w), _) => { + if w.source.kind == "git" && w.source.repo_url.trim().is_empty() { + return Err(ApiError::bad_request(format!( + "{} is built from source: sync from its repository, or give it an image.", + w.name + ))); + } + // Where new services run: the cluster given, else where the + // project's services run, else the team's default. + if cluster.is_none() { + let c = match cluster_id.clone().filter(|c| !c.is_empty()) { + Some(c) => c, + None => sqlx::query_scalar::<_, Option>( + "SELECT COALESCE( + (SELECT cluster_id FROM pyo.services WHERE project_id = $1 AND NOT deleting + GROUP BY cluster_id ORDER BY count(*) DESC, cluster_id LIMIT 1), + (SELECT default_cluster_id FROM pyo.teams WHERE id = $2))", + ) + .bind(project_id) + .bind(&team_id) + .fetch_one(&mut **tx) + .await? + .ok_or_else(|| { + ApiError::bad_request( + "This team has no cluster to deploy to. Add a server first.", + ) + })?, + }; + if team_of(tx, "clusters", &c).await? != team_id { + return Err(ApiError::not_found("Cluster")); + } + cluster = Some(c); + } + let cluster_id = cluster.clone().unwrap_or_default(); + let id = new_id("svc"); + let deployment_id = new_id("dpl"); + let service = compose::service_spec( + w, + Some(&file.project.file), + &id, + &team_id, + project_id, + &cluster_id, + now, + &new_id, + ); + let volumes = compose::volume_specs(w, &new_id); + let r = nested( + s, + tx, + user, + Op::CreateService { + service, + deployment_id: deployment_id.clone(), + volumes, + databases: vec![], + confirm, + upload_id: None, + }, + wake, + ) + .await?; + if let Some(cdn) = &w.behind_cdn { + nested( + s, + tx, + user, + Op::SetServiceBehindCdn { + service_id: id.clone(), + cdn: Some(cdn.clone()), + }, + wake, + ) + .await?; + } + done.push(json!({ "name": w.name, "id": id, "status": "added", "deploymentId": deployment_id, "warning": r.get("warning") })); + } + ("changed" | "unchanged", Some(w), Some(o)) => { + let m = merge(o, w, &file.project.file, now, &new_id); + if m.changes.is_empty() && !m.record_only { + continue; + } + for v in &m.volumes { + nested( + s, + tx, + user, + Op::AddVolume { + id: new_id("vol"), + service_id: o.id.clone(), + name: volume_label(&o.name, &v.name), + mount_path: v.mount_path.clone(), + size_gi: v.size_gi, + }, + wake, + ) + .await?; + } + let mut spec = m.spec; + blank_secrets(&mut spec); + spec["id"] = json!(o.id); + let deployment_id = m.deploy.then(|| new_id("dpl")); + let r = nested( + s, + tx, + user, + Op::SaveService { + service: spec, + deployment_id: deployment_id.clone(), + trigger: None, + confirm, + }, + wake, + ) + .await?; + if let Some(cdn) = m.behind_cdn { + nested( + s, + tx, + user, + Op::SetServiceBehindCdn { + service_id: o.id.clone(), + cdn, + }, + wake, + ) + .await?; + } + if !m.changes.is_empty() { + done.push(json!({ "name": o.name, "id": o.id, "status": "changed", "deploymentId": deployment_id, "warning": r.get("warning") })); + } + } + ("notInFile", _, Some(o)) if prune && ss.from_file => { + nested( + s, + tx, + user, + Op::DeleteService { + id: o.id.clone(), + delete_volumes: false, + }, + wake, + ) + .await?; + done.push(json!({ "name": o.name, "id": o.id, "status": "deleted" })); + } + _ => {} + } + } + if !done.is_empty() { + let file_name = compose::record(&file.project.file, "")["file"] + .as_str() + .unwrap_or("compose.yaml") + .to_owned(); + crate::ops::log_activity( + tx, + &team_id, + &user.name, + "project.updated", + "info", + &format!("Synced {name} with {file_name}"), + json!({ "kind": "project", "id": project_id, "label": name }), + json!({ "projectId": project_id }), + ) + .await?; + } + Ok(json!({ "ok": true, "projectId": project_id, "services": done, "plan": plan })) +} + +#[cfg(test)] +#[path = "compose_sync_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "compose_sync_db_tests.rs"] +mod db_tests; diff --git a/crates/pyo-api/src/compose_sync_db_tests.rs b/crates/pyo-api/src/compose_sync_db_tests.rs new file mode 100644 index 00000000..cd4a1023 --- /dev/null +++ b/crates/pyo-api/src/compose_sync_db_tests.rs @@ -0,0 +1,1199 @@ +//! Compose sync in the database, against a throwaway Postgres +//! (DATABASE_URL): what `syncCompose` writes, as `pyo deploy -f` runs it. +//! The plan comes from the `planComposeSync` route's handler and the apply +//! goes through `run_json`, so row security and the role and key checks +//! are the real ones. +//! +//! DATABASE_URL=… cargo test -p pyo-api --lib -- --ignored compose_sync::db_tests +//! +//! Run them on their own, as above: the process has one vault, and other +//! modules' tests set a secret key for the whole process. + +use axum::http::StatusCode; +use serde_json::{Value, json}; +use sqlx::PgPool; + +use super::*; +use crate::auth::{KeyAccess, KeyScope, User}; +use crate::ids::random_string; +use crate::teams_rls_tests::{cloud_db, drop_db, installation_db}; +use crate::teamsec_tests::run_big; + +/// A team with a connected cluster of one server (tagged `edge`), and its +/// owner. +struct Team { + id: String, + cluster: String, + owner: User, +} + +struct World { + s: crate::AppState, + db: PgPool, + run: String, +} + +/// The file every test starts from. Its domain is the run's own: a +/// hostname is one service's across the whole installation. +fn file(tag: &str) -> String { + format!( + r#"name: cloud +services: + api: + image: ghcr.io/acme/api:1.2 + environment: + LOG_LEVEL: info + ports: ["8080:8080"] + x-pyo: + domains: [api-{tag}.example.com] + behindCdn: cloudflare + health: /readyz + replicas: 2 + secrets: [API_TOKEN] + worker: + image: ghcr.io/acme/worker:1.2 + volumes: ["work:/data"] +volumes: + work: {{}} +"# + ) +} + +/// The file with one more service (`yaml`, indented as a service is). +fn with_service(text: &str, yaml: &str) -> String { + text.replace("volumes:\n work:", &format!("{yaml}volumes:\n work:")) +} + +/// The file without its worker. +fn without_worker(text: &str) -> String { + text.split(" worker:").next().unwrap().to_owned() +} + +fn status(e: &ApiError) -> StatusCode { + e.status +} + +impl World { + async fn new(db: PgPool) -> Self { + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + Self { + s: crate::sandbox::e2e::test_state(db.clone()), + db, + run: random_string(8).to_lowercase(), + } + } + + /// An account. Not in any team yet. + async fn account(&self, name: &str) -> User { + let id = format!("usr_{}{name}", self.run); + let user = User { + id: id.clone(), + name: name.to_owned(), + email: format!("{name}{}@sync.test", self.run), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + sqlx::query( + "INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $2, $3, '')", + ) + .bind(&user.id) + .bind(&user.email) + .bind(name) + .execute(&self.db) + .await + .unwrap(); + user + } + + /// An account in `team` with `role`. + async fn member(&self, team: &str, name: &str, role: &str) -> User { + let user = self.account(name).await; + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $4, $5, 'active')") + .bind(format!("mem_{}{name}", self.run)) + .bind(team) + .bind(&user.id) + .bind(&user.email) + .bind(role) + .execute(&self.db) + .await + .unwrap(); + user + } + + async fn team(&self, tag: &str) -> Team { + let id = format!("team_{}{tag}", self.run); + let cluster = format!("cl_{}{tag}", self.run); + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&id) + .execute(&self.db) + .await + .unwrap(); + let owner = self.member(&id, &format!("owner{tag}"), "owner").await; + sqlx::query("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash, status, last_seen_at) VALUES ($1, $2, $1, $1, 'connected', now())") + .bind(&cluster) + .bind(&id) + .execute(&self.db) + .await + .unwrap(); + sqlx::query("UPDATE pyo.teams SET default_cluster_id = $2 WHERE id = $1") + .bind(&id) + .bind(&cluster) + .execute(&self.db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO pyo.servers (id, cluster_id, name, report) VALUES ($1, $2, 'one', '{}')", + ) + .bind(format!("srv_{}{tag}", self.run)) + .bind(&cluster) + .execute(&self.db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO pyo.server_tags (cluster_id, name, tags) VALUES ($1, 'one', '{edge}')", + ) + .bind(&cluster) + .execute(&self.db) + .await + .unwrap(); + Team { id, cluster, owner } + } + + /// `planComposeSync`, as `pyo deploy -f compose.yaml` (and its + /// `--dry-run`) asks for it. `project` is `--project`. + async fn plan( + &self, + user: &User, + team: &str, + project: Option<&str>, + text: &str, + ) -> ApiResult { + super::plan( + axum::extract::State(self.s.clone()), + crate::auth::SessionUser(user.clone()), + crate::error::Json(SyncBody { + team_id: team.to_owned(), + project_id: project.map(str::to_owned), + file: Some(text.to_owned()), + env: None, + repo: None, + cluster_id: None, + name: Some("cloud".into()), + file_name: Some("compose.yaml".into()), + }), + ) + .await + .map(|j| j.0) + } + + /// `syncCompose` with a plan's file. + async fn sync( + &self, + user: &User, + project: &str, + file: &ComposePlan, + prune: bool, + ) -> ApiResult { + crate::ops::run_json( + &self.s, + user, + json!({ "op": "syncCompose", "projectId": project, "plan": file, "prune": prune }), + ) + .await + } + + /// Plans `text` and applies it, as the command does without `--dry-run`. + async fn deploy( + &self, + user: &User, + team: &str, + project: Option<&str>, + text: &str, + prune: bool, + ) -> ApiResult { + let plan = self.plan(user, team, project, text).await?; + let project = plan.project.expect("a project to sync").id; + self.sync(user, &project, &plan.file, prune).await + } + + /// The first `pyo deploy -f`: there's no project for the file yet, so + /// it's imported. Returns the project. + async fn import(&self, team: &Team, text: &str) -> String { + let plan = self.plan(&team.owner, &team.id, None, text).await.unwrap(); + assert!(plan.project.is_none(), "no project for this file yet"); + assert!(plan.services.iter().all(|s| s.status == "added")); + let out = crate::ops::run_json( + &self.s, + &team.owner, + json!({ "op": "importCompose", "teamId": team.id, "plan": plan.file }), + ) + .await + .unwrap(); + self.settle(&team.id).await; + out["projectId"].as_str().unwrap().to_owned() + } + + /// The agent finished every deploy of the team (there's none here). + async fn settle(&self, team: &str) { + sqlx::query("UPDATE pyo.deployments SET status = 'succeeded' WHERE team_id = $1 AND status NOT IN ('succeeded', 'failed', 'cancelled')") + .bind(team) + .execute(&self.db) + .await + .unwrap(); + } + + async fn project(&self, team: &Team, namespace: &str) -> String { + let id = format!("prj_{}{namespace}", self.run); + crate::ops::run_json( + &self.s, + &team.owner, + json!({ "op": "createProject", "id": id, "teamId": team.id, "name": namespace, "namespace": namespace, "description": "" }), + ) + .await + .unwrap(); + id + } + + /// A service made in the dashboard (`file` None), or one that + /// remembers another Compose file. + async fn service(&self, team: &Team, project: &str, name: &str, file: Option<&str>) -> String { + let text = format!("services:\n {name}:\n image: ghcr.io/acme/{name}:1\n"); + let plan = compose::plan(&compose::Input { + file: &text, + name_hint: "x", + ..Default::default() + }) + .unwrap(); + let id = crate::ids::new_id("svc"); + let new_id = |p: &str| crate::ids::new_id(p); + let spec = compose::service_spec( + &plan.services[0], + file, + &id, + &team.id, + project, + &team.cluster, + pyo_proto::now_ms(), + &new_id, + ); + crate::ops::run_json( + &self.s, + &team.owner, + json!({ "op": "createService", "service": spec, "deploymentId": crate::ids::new_id("dpl") }), + ) + .await + .unwrap(); + self.settle(&team.id).await; + id + } + + /// Everything of a team a sync could write: its projects, services, + /// deployments, volumes and activity, whole rows. + async fn snapshot(&self, team: &str) -> Value { + let mut out = json!({}); + for table in ["projects", "services", "deployments", "volumes", "activity"] { + let rows: Value = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT coalesce(jsonb_agg(to_jsonb(a) ORDER BY a.id), '[]'::jsonb) FROM pyo.{table} a WHERE a.team_id = $1" + ))) + .bind(team) + .fetch_one(&self.db) + .await + .unwrap(); + out[table] = rows; + } + out + } + + /// A project's service by name: id, spec as stored, behind_cdn, deleting. + async fn find(&self, project: &str, name: &str) -> Option<(String, Value, Option, bool)> { + sqlx::query_as( + "SELECT id, spec, behind_cdn, deleting FROM pyo.services WHERE project_id = $1 AND name = $2", + ) + .bind(project) + .bind(name) + .fetch_optional(&self.db) + .await + .unwrap() + } + + async fn get(&self, project: &str, name: &str) -> (String, Value, Option, bool) { + self.find(project, name).await.expect("the service") + } + + async fn names(&self, project: &str) -> Vec { + sqlx::query_scalar( + "SELECT name FROM pyo.services WHERE project_id = $1 AND NOT deleting ORDER BY name", + ) + .bind(project) + .fetch_all(&self.db) + .await + .unwrap() + } + + async fn deployments(&self, service: &str) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM pyo.deployments WHERE service_id = $1") + .bind(service) + .fetch_one(&self.db) + .await + .unwrap() + } +} + +/// A variable of a spec as stored: (its stored value, the value opened, secret). +async fn env(spec: &Value, key: &str) -> Option<(String, String, bool)> { + let e = spec["env"] + .as_array()? + .iter() + .find(|e| e["key"] == json!(key))?; + let stored = e["value"].as_str().unwrap_or("").to_owned(); + let opened = crate::vault::get().open(&stored).await.unwrap(); + Some((stored, opened, e["secret"] == json!(true))) +} + +fn hostnames(spec: &Value) -> Vec<&str> { + spec["domains"] + .as_array() + .into_iter() + .flatten() + .filter_map(|d| d["hostname"].as_str()) + .collect() +} + +fn statuses(plan: &SyncPlan) -> Vec<(&str, &str)> { + plan.services + .iter() + .map(|s| (s.name.as_str(), s.status.as_str())) + .collect() +} + +/// What a sync says it did: (name, status) in its order. +fn done(out: &Value) -> Vec<(String, String)> { + out["services"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v["name"].as_str().unwrap().to_owned(), + v["status"].as_str().unwrap().to_owned(), + ) + }) + .collect() +} + +fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> { + v.iter().map(|(a, b)| ((*a).to_owned(), (*b).to_owned())).collect() +} + +/// The first apply makes the project and its services as the file and its +/// `x-pyo` say. The same file again changes nothing: no row is written, +/// nothing is deployed, nothing is logged. Into an empty project named +/// with `--project`, the sync itself makes them, once. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn the_first_apply_makes_the_services_and_the_second_changes_nothing() { + run_big(async { + let w = World::new(installation_db().await).await; + let t = w.team("a").await; + let text = file(&w.run); + let project = w.import(&t, &text).await; + assert_eq!(w.names(&project).await, ["api", "worker"]); + + let (api, spec, cdn, _) = w.get(&project, "api").await; + assert_eq!(spec["compose"], json!({ "file": "compose.yaml", "service": "api" })); + assert_eq!(spec["replicas"], 2); + assert_eq!(spec["healthCheck"]["path"], "/readyz"); + assert_eq!(hostnames(&spec), [format!("api-{}.example.com", w.run)]); + assert_eq!(cdn.as_deref(), Some("cloudflare")); + let (_, token, secret) = env(&spec, "API_TOKEN").await.unwrap(); + assert!(secret && token.is_empty(), "a secret comes without a value"); + assert_eq!(w.deployments(&api).await, 1); + + // Again: found by the file's name, nothing to do, nothing written. + let before = w.snapshot(&t.id).await; + for prune in [false, true] { + let plan = w.plan(&t.owner, &t.id, None, &text).await.unwrap(); + assert_eq!(plan.project.as_ref().map(|p| p.id.as_str()), Some(project.as_str())); + assert_eq!(statuses(&plan), [("api", "unchanged"), ("worker", "unchanged")]); + assert!(plan.services.iter().all(|s| s.changes.is_empty() && !s.deploy)); + let out = w.sync(&t.owner, &project, &plan.file, prune).await.unwrap(); + assert_eq!(out["services"], json!([])); + assert_eq!(w.snapshot(&t.id).await, before, "prune: {prune}"); + } + + // Into an empty project: the sync adds them, and only once. + let empty = w.project(&t, "empty").await; + let other = file(&format!("{}b", w.run)); + let plan = w.plan(&t.owner, &t.id, Some(&empty), &other).await.unwrap(); + assert_eq!(statuses(&plan), [("api", "added"), ("worker", "added")]); + let out = w.sync(&t.owner, &empty, &plan.file, false).await.unwrap(); + assert_eq!(done(&out), pairs(&[("api", "added"), ("worker", "added")])); + assert_eq!(w.names(&empty).await, ["api", "worker"]); + let (id, spec, cdn, _) = w.get(&empty, "api").await; + assert_eq!(cdn.as_deref(), Some("cloudflare")); + assert_eq!(spec["compose"]["service"], "api"); + assert_eq!(w.deployments(&id).await, 1); + w.settle(&t.id).await; + let before = w.snapshot(&t.id).await; + let out = w.deploy(&t.owner, &t.id, Some(&empty), &other, false).await.unwrap(); + assert_eq!(out["services"], json!([])); + assert_eq!(w.snapshot(&t.id).await, before); + }); +} + +/// A new image, variables, replicas, health check, placement, domain and +/// CDN setting in the file change the service it was made from, in place: +/// the same row, one new deployment, and no second service. The service +/// the file didn't change isn't written. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn a_changed_file_updates_the_service_it_made() { + run_big(async { + let w = World::new(installation_db().await).await; + let t = w.team("a").await; + let text = file(&w.run); + let project = w.import(&t, &text).await; + let (api, _, _, _) = w.get(&project, "api").await; + let (worker, ..) = w.get(&project, "worker").await; + let worker_row = |snap: &Value| { + snap["services"] + .as_array() + .unwrap() + .iter() + .find(|s| s["id"] == json!(worker)) + .cloned() + }; + let before = w.snapshot(&t.id).await; + + let next = text + .replace("api:1.2", "api:1.3") + .replace("LOG_LEVEL: info", "LOG_LEVEL: debug\n REGION: sin") + .replace( + &format!("domains: [api-{}.example.com]", w.run), + &format!("domains: [api-{0}.example.com, www-{0}.example.com]", w.run), + ) + .replace("behindCdn: cloudflare", "behindCdn: none") + .replace("health: /readyz", "health: /healthz") + .replace("replicas: 2", "replicas: 3\n placement: { tags: [edge] }"); + let plan = w.plan(&t.owner, &t.id, None, &next).await.unwrap(); + assert_eq!(statuses(&plan), [("api", "changed"), ("worker", "unchanged")]); + let mut fields: Vec<&str> = plan.services[0].changes.iter().map(|c| c.field.as_str()).collect(); + fields.sort(); + let www = format!("domain www-{}.example.com", w.run); + assert_eq!( + fields, + ["behind CDN", www.as_str(), "env LOG_LEVEL", "env REGION", "health check", "image", "placement", "replicas"] + ); + + let out = w.sync(&t.owner, &project, &plan.file, false).await.unwrap(); + assert_eq!(done(&out), pairs(&[("api", "changed")])); + assert_eq!(out["services"][0]["id"], json!(api)); + assert_eq!(w.names(&project).await, ["api", "worker"], "no second service"); + let (id, spec, cdn, _) = w.get(&project, "api").await; + assert_eq!(id, api); + assert_eq!(spec["source"]["image"], "ghcr.io/acme/api"); + assert_eq!(spec["source"]["reference"], "1.3"); + assert_eq!(env(&spec, "LOG_LEVEL").await.unwrap().1, "debug"); + assert_eq!(env(&spec, "REGION").await.unwrap().1, "sin"); + assert_eq!(spec["replicas"], 3); + assert_eq!(spec["healthCheck"]["type"], "http"); + assert_eq!(spec["healthCheck"]["path"], "/healthz"); + assert_eq!(spec["placement"], json!({ "servers": [], "tags": ["edge"] })); + assert_eq!( + hostnames(&spec), + [format!("api-{}.example.com", w.run), format!("www-{}.example.com", w.run)] + ); + assert_eq!(cdn, None); + // Deployed once more, with what the file says now. + assert_eq!(w.deployments(&api).await, 2); + let dpl = out["services"][0]["deploymentId"].as_str().unwrap(); + let (service, deployed): (String, Value) = + sqlx::query_as("SELECT service_id, spec FROM pyo.deployments WHERE id = $1") + .bind(dpl) + .fetch_one(&w.db) + .await + .unwrap(); + assert_eq!(service, api); + assert_eq!(deployed["image"], "ghcr.io/acme/api:1.3"); + assert_eq!(deployed["replicas"], 3); + // The worker: not written, not deployed. + let after = w.snapshot(&t.id).await; + assert_eq!(worker_row(&after), worker_row(&before)); + assert_eq!(w.deployments(&worker).await, 1); + assert_eq!(after["volumes"], before["volumes"]); + + // The new file again: nothing. + w.settle(&t.id).await; + let before = w.snapshot(&t.id).await; + let out = w.deploy(&t.owner, &t.id, None, &next, false).await.unwrap(); + assert_eq!(out["services"], json!([])); + assert_eq!(w.snapshot(&t.id).await, before); + }); +} + +/// A service no longer in the file stays, and is only listed. With +/// `prune` it's deleted (its volume kept), and only it: not a service made +/// in the dashboard, not one made from another file, not the same name in +/// another project, not another team's. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn prune_deletes_only_what_this_file_made_in_this_project() { + run_big(async { + let w = World::new(installation_db().await).await; + let (a, b) = (w.team("a").await, w.team("b").await); + let text = file(&w.run); + let project = w.import(&a, &text).await; + let manual = w.service(&a, &project, "manual", None).await; + let legacy = w.service(&a, &project, "legacy", Some("other.yaml")).await; + // The same worker in another project of the team, and in another team. + let side = w.project(&a, "side").await; + let side_text = file(&format!("{}s", w.run)); + w.deploy(&a.owner, &a.id, Some(&side), &side_text, false).await.unwrap(); + w.settle(&a.id).await; + let theirs = w.import(&b, &file(&format!("{}b", w.run))).await; + let (worker, ..) = w.get(&project, "worker").await; + let (side_worker, ..) = w.get(&side, "worker").await; + + let next = without_worker(&text); + let plan = w.plan(&a.owner, &a.id, None, &next).await.unwrap(); + assert_eq!(plan.project.as_ref().unwrap().id, project); + let by = |name: &str| plan.services.iter().find(|s| s.name == name).unwrap(); + assert_eq!(by("api").status, "unchanged"); + for name in ["worker", "manual", "legacy"] { + assert_eq!(by(name).status, "notInFile", "{name}"); + } + assert!(by("worker").from_file); + assert!(!by("manual").from_file && !by("legacy").from_file); + assert_eq!(by("manual").notes[0].message, "It wasn't made from a Compose file."); + assert_eq!(by("legacy").notes[0].message, "It was made from other.yaml."); + + // Without prune: listed, and nothing is written. + let (before_a, before_b) = (w.snapshot(&a.id).await, w.snapshot(&b.id).await); + let out = w.sync(&a.owner, &project, &plan.file, false).await.unwrap(); + assert_eq!(out["services"], json!([])); + assert_eq!(w.snapshot(&a.id).await, before_a); + + // With it: the worker of this project, and nothing else. + let out = w.sync(&a.owner, &project, &plan.file, true).await.unwrap(); + assert_eq!(done(&out), pairs(&[("worker", "deleted")])); + assert_eq!(out["services"][0]["id"], json!(worker)); + let deleting: Vec = + sqlx::query_scalar("SELECT id FROM pyo.services WHERE team_id = $1 AND deleting") + .bind(&a.id) + .fetch_all(&w.db) + .await + .unwrap(); + assert_eq!(deleting, std::slice::from_ref(&worker)); + assert_eq!(w.names(&project).await, ["api", "legacy", "manual"]); + assert_eq!(w.names(&side).await, ["api", "worker"]); + assert!(!w.get(&side, "worker").await.3); + assert_eq!(w.get(&project, "manual").await.0, manual); + assert_eq!(w.get(&project, "legacy").await.0, legacy); + // Its volume is kept, and the other project's worker keeps its own. + let volumes: Vec<(Option, bool, String)> = sqlx::query_as( + "SELECT service_id, deleting, data->>'name' FROM pyo.volumes WHERE team_id = $1 ORDER BY project_id = $2 DESC", + ) + .bind(&a.id) + .bind(&project) + .fetch_all(&w.db) + .await + .unwrap(); + assert_eq!(volumes.len(), 2); + assert!(volumes.iter().all(|v| !v.1), "no volume is deleted"); + assert_eq!(volumes[1].0.as_deref(), Some(side_worker.as_str())); + // It's still the worker's until the agent has removed the service. + assert_eq!(volumes[0].0.as_deref(), Some(worker.as_str())); + assert_eq!(volumes[0].2, "work"); + // The other team: not a row touched. + assert_eq!(w.snapshot(&b.id).await, before_b); + assert_eq!(w.names(&theirs).await, ["api", "worker"]); + + // Again with prune: it's gone from the plan, and nothing more goes. + let before = w.snapshot(&a.id).await; + let plan = w.plan(&a.owner, &a.id, None, &next).await.unwrap(); + assert!(!plan.services.iter().any(|s| s.name == "worker")); + let out = w.sync(&a.owner, &project, &plan.file, true).await.unwrap(); + assert_eq!(out["services"], json!([])); + assert_eq!(w.snapshot(&a.id).await, before); + }); +} + +/// A secret named in `x-pyo.secrets` gets its value in Pyo. A sync keeps +/// it, whatever else of the service changes and whatever the file says for +/// that variable: the stored value is the same, it's deployed with it, and +/// neither the plan nor the sync's answer shows it. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn a_sync_keeps_a_secrets_value() { + run_big(async { + let w = World::new(installation_db().await).await; + let t = w.team("a").await; + let text = file(&w.run); + let project = w.import(&t, &text).await; + let (api, mut spec, _, _) = w.get(&project, "api").await; + + // Its value, set in Pyo. + let value = format!("s3cret-{}", w.run); + crate::vault::get().open_env(&mut spec).await.unwrap(); + spec["id"] = json!(api); + for e in spec["env"].as_array_mut().unwrap() { + if e["key"] == json!("API_TOKEN") { + e["value"] = json!(value); + } + } + crate::ops::run_json(&w.s, &t.owner, json!({ "op": "saveService", "service": spec })) + .await + .unwrap(); + let (_, spec, _, _) = w.get(&project, "api").await; + let (stored, opened, secret) = env(&spec, "API_TOKEN").await.unwrap(); + assert!(secret); + assert_eq!(opened, value); + if std::env::var("PYO_SECRET_KEY").is_ok() { + assert_ne!(stored, value, "sealed with the team's key"); + } + + // The same file: the value set in Pyo is no change. + let before = w.snapshot(&t.id).await; + let out = w.deploy(&t.owner, &t.id, None, &text, false).await.unwrap(); + assert_eq!(out["services"], json!([])); + assert_eq!(w.snapshot(&t.id).await, before); + + // The file now gives it a value, a second secret, and a new image. + let next = text + .replace("api:1.2", "api:1.3") + .replace("LOG_LEVEL: info", "LOG_LEVEL: info\n API_TOKEN: from-the-file") + .replace("secrets: [API_TOKEN]", "secrets: [API_TOKEN, SIGNING_KEY]"); + let plan = w.plan(&t.owner, &t.id, None, &next).await.unwrap(); + let s = plan.services.iter().find(|s| s.name == "api").unwrap(); + assert!(plan.warnings.iter().any(|x| x.field == "x-pyo.secrets" + && x.message + == "Secrets take their values from Pyo, not the file, so the file's API_TOKEN isn't used.")); + let mut fields: Vec<&str> = s.changes.iter().map(|c| c.field.as_str()).collect(); + fields.sort(); + assert_eq!(fields, ["image", "secret SIGNING_KEY"]); + assert!(!serde_json::to_string(&plan.services).unwrap().contains(&value)); + + let out = w.sync(&t.owner, &project, &plan.file, false).await.unwrap(); + assert_eq!(done(&out), pairs(&[("api", "changed")])); + assert!(!out.to_string().contains(&value)); + let (id, spec, _, _) = w.get(&project, "api").await; + assert_eq!(id, api); + assert_eq!(spec["source"]["reference"], "1.3"); + let (after, opened, secret) = env(&spec, "API_TOKEN").await.unwrap(); + assert!(secret, "still a secret"); + assert_eq!(opened, value, "not blanked, not the file's"); + assert_eq!(after, stored, "the stored value isn't written again"); + let (_, new, secret) = env(&spec, "SIGNING_KEY").await.unwrap(); + assert!(secret && new.is_empty()); + // It's deployed with the value it has in Pyo. + let dpl = out["services"][0]["deploymentId"].as_str().unwrap(); + let deployed: Value = sqlx::query_scalar("SELECT spec FROM pyo.deployments WHERE id = $1") + .bind(dpl) + .fetch_one(&w.db) + .await + .unwrap(); + assert_eq!(env(&deployed, "API_TOKEN").await.unwrap().1, value); + + // The file stops naming it a secret and keeps its own value for + // it, with another variable changed: in Pyo it's still the secret. + w.settle(&t.id).await; + let again = next + .replace("LOG_LEVEL: info", "LOG_LEVEL: warn") + .replace("secrets: [API_TOKEN, SIGNING_KEY]", "secrets: [SIGNING_KEY]"); + let plan = w.plan(&t.owner, &t.id, None, &again).await.unwrap(); + let s = plan.services.iter().find(|s| s.name == "api").unwrap(); + assert!( + s.notes.iter().any(|n| n.field == "env API_TOKEN" + && n.message == "It's a secret in Pyo, so its value stays.") + ); + let fields: Vec<&str> = s.changes.iter().map(|c| c.field.as_str()).collect(); + assert_eq!(fields, ["env LOG_LEVEL"]); + let out = w.sync(&t.owner, &project, &plan.file, false).await.unwrap(); + assert!(!out.to_string().contains(&value)); + let (_, spec, _, _) = w.get(&project, "api").await; + assert_eq!(env(&spec, "LOG_LEVEL").await.unwrap().1, "warn"); + let (after, opened, secret) = env(&spec, "API_TOKEN").await.unwrap(); + assert!(secret); + assert_eq!(opened, value); + assert_eq!(after, stored); + }); +} + +/// Without `--project` the file goes to the project made from a file of +/// its name. With it, to the project named and no other, also when that +/// one has nothing of the file yet. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn a_sync_goes_to_the_project_named() { + run_big(async { + let w = World::new(installation_db().await).await; + let t = w.team("a").await; + let text = file(&w.run); + let cloud = w.import(&t, &text).await; + let other = w.project(&t, "other").await; + + let plan = w.plan(&t.owner, &t.id, None, &text).await.unwrap(); + assert_eq!(plan.project.unwrap().id, cloud); + let e = w + .plan(&t.owner, &t.id, Some("prj_nosuchproject"), &text) + .await + .unwrap_err(); + assert_eq!(status(&e), StatusCode::NOT_FOUND); + + // Named: the other project gets the services, the first isn't written. + let rows = |snap: &Value, project: &str| -> Vec { + snap["services"] + .as_array() + .unwrap() + .iter() + .filter(|s| s["project_id"] == json!(project)) + .cloned() + .collect() + }; + let before = w.snapshot(&t.id).await; + let text_b = file(&format!("{}b", w.run)).replace("api:1.2", "api:9.9"); + let plan = w.plan(&t.owner, &t.id, Some(&other), &text_b).await.unwrap(); + assert_eq!(plan.project.as_ref().unwrap().id, other); + assert_eq!(statuses(&plan), [("api", "added"), ("worker", "added")]); + let out = w.sync(&t.owner, &other, &plan.file, true).await.unwrap(); + assert_eq!(out["projectId"], json!(other)); + assert_eq!(w.names(&other).await, ["api", "worker"]); + assert_eq!(w.get(&other, "api").await.1["source"]["reference"], "9.9"); + let after = w.snapshot(&t.id).await; + assert_eq!(rows(&after, &cloud), rows(&before, &cloud)); + assert_eq!(w.get(&cloud, "api").await.1["source"]["reference"], "1.2"); + + // Both have services of a compose.yaml now: without a name, still + // the one in the file's own namespace. + let plan = w.plan(&t.owner, &t.id, None, &text).await.unwrap(); + assert_eq!(plan.project.unwrap().id, cloud); + }); +} + +/// A team's sync stays in the team: another team's project isn't found by +/// name or by id, its cluster isn't one to deploy to, a hostname it holds +/// isn't taken, and none of its rows is written. +async fn teams_are_apart(db: PgPool) { + let w = World::new(db).await; + let (a, b) = (w.team("a").await, w.team("b").await); + let text_a = file(&w.run); + let text_b = file(&format!("{}b", w.run)); + let theirs = w.import(&a, &text_a).await; + let ours = w.import(&b, &text_b).await; + let (before_a, before_b) = (w.snapshot(&a.id).await, w.snapshot(&b.id).await); + let bob = &b.owner; + + // Both teams have a project "cloud" made from compose.yaml: each finds its own. + let plan = w.plan(bob, &b.id, None, &text_b).await.unwrap(); + assert_eq!(plan.project.as_ref().unwrap().id, ours); + let file_b = plan.file; + let plan = w.plan(&a.owner, &a.id, None, &text_a).await.unwrap(); + assert_eq!(plan.project.unwrap().id, theirs); + + // Their team, or their project under our team: not there. + for (team, project) in [(&a.id, None), (&a.id, Some(theirs.as_str())), (&b.id, Some(theirs.as_str()))] { + let e = w.plan(bob, team, project, &text_b).await.unwrap_err(); + assert_eq!(status(&e), StatusCode::NOT_FOUND, "{}", e.message); + } + for prune in [false, true] { + let e = w.sync(bob, &theirs, &file_b, prune).await.unwrap_err(); + assert_eq!(status(&e), StatusCode::NOT_FOUND, "{}", e.message); + } + // A file of ours with one service more, sent to their cluster. + let more = with_service(&text_b, " cache:\n image: redis:7\n"); + let plan = w.plan(bob, &b.id, None, &more).await.unwrap(); + let e = crate::ops::run_json( + &w.s, + bob, + json!({ "op": "syncCompose", "projectId": ours, "clusterId": a.cluster, "plan": plan.file }), + ) + .await + .unwrap_err(); + assert_eq!(status(&e), StatusCode::NOT_FOUND, "{}", e.message); + // A hostname their service has: refused, and their service isn't named. + let taken = text_b.replace( + &format!("api-{}b.example.com", w.run), + &format!("api-{0}b.example.com, api-{0}.example.com", w.run), + ); + let e = w.deploy(bob, &b.id, None, &taken, false).await.unwrap_err(); + assert_eq!(status(&e), StatusCode::CONFLICT); + assert_eq!( + e.message, + format!("api-{}.example.com is already used by another service.", w.run) + ); + assert_eq!(w.snapshot(&a.id).await, before_a); + assert_eq!(w.snapshot(&b.id).await, before_b); + + // What our team does to its own project leaves theirs as it was. + let out = w + .deploy(bob, &b.id, None, &without_worker(&text_b).replace("api:1.2", "api:2.0"), true) + .await + .unwrap(); + assert_eq!(done(&out), pairs(&[("api", "changed"), ("worker", "deleted")])); + assert_eq!(w.names(&ours).await, ["api"]); + assert_eq!(w.snapshot(&a.id).await, before_a); + assert_eq!(w.names(&theirs).await, ["api", "worker"]); +} + +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn a_team_cant_sync_into_another_teams_project() { + run_big(async { + teams_are_apart(installation_db().await).await; + }); +} + +/// The same on Pyo Cloud's login: not a superuser, held by row security. +/// In a database of its own, so with PYO_SECRET_KEY set it runs alone: +/// the process has one vault, and it keeps its data keys in the database +/// of the first test that started. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn a_team_cant_sync_into_another_teams_project_on_a_login_without_superuser() { + run_big(async { + let (db, name) = cloud_db().await; + teams_are_apart(db.clone()).await; + drop_db(db, &name).await; + }); +} + +/// Who may sync: the team's developers, admins and owners. A viewer only +/// sees the plan. The installation's admin has no say in a team they're +/// not in. An API key needs full access, in a team it's for. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn roles_and_api_keys_decide_who_syncs() { + run_big(async { + let w = World::new(installation_db().await).await; + let (a, b) = (w.team("a").await, w.team("b").await); + let text = file(&w.run); + let project = w.import(&a, &text).await; + let before = w.snapshot(&a.id).await; + let next = text.replace("replicas: 2", "replicas: 3"); + let file_next = w.plan(&a.owner, &a.id, None, &next).await.unwrap().file; + + // A viewer: the plan, not the sync. + let viewer = w.member(&a.id, "viewer", "viewer").await; + let plan = w.plan(&viewer, &a.id, None, &next).await.unwrap(); + assert_eq!(statuses(&plan), [("api", "changed"), ("worker", "unchanged")]); + let e = w.sync(&viewer, &project, &file_next, false).await.unwrap_err(); + assert_eq!(status(&e), StatusCode::FORBIDDEN); + assert_eq!(e.message, "Viewers can't make changes."); + + // The installation's admin, and an account in no team. + let mut admin = w.account("admin").await; + admin.is_admin = true; + sqlx::query("UPDATE pyo.users SET is_admin = true WHERE id = $1") + .bind(&admin.id) + .execute(&w.db) + .await + .unwrap(); + let nobody = w.account("nobody").await; + for user in [&admin, &nobody, &b.owner] { + let e = w.plan(user, &a.id, None, &next).await.unwrap_err(); + assert_eq!(status(&e), StatusCode::NOT_FOUND, "{}", user.name); + let e = w.sync(user, &project, &file_next, true).await.unwrap_err(); + assert_eq!(status(&e), StatusCode::NOT_FOUND, "{}", user.name); + } + + // API keys of the owner. + let key = |access: KeyAccess, teams: Option>| { + let mut u = a.owner.clone(); + u.key = Some(KeyScope { access, teams }); + u + }; + let read = key(KeyAccess::Read, None); + w.plan(&read, &a.id, None, &next).await.unwrap(); + for (user, want) in [ + (read, StatusCode::FORBIDDEN), + (key(KeyAccess::Deploy, None), StatusCode::FORBIDDEN), + (key(KeyAccess::Sandboxes, None), StatusCode::FORBIDDEN), + (key(KeyAccess::Full, Some(vec![b.id.clone()])), StatusCode::NOT_FOUND), + ] { + let e = w.sync(&user, &project, &file_next, true).await.unwrap_err(); + assert_eq!(status(&e), want, "{}", e.message); + } + // A deploy key deploys what's there. A sync changes settings, and + // so does the first apply (an import): both need full access. + let deploy = key(KeyAccess::Deploy, None); + let e = w.sync(&deploy, &project, &file_next, false).await.unwrap_err(); + assert_eq!( + e.message, + "This API key can only deploy, roll back, restart, stop and scale services." + ); + let e = crate::ops::run_json( + &w.s, + &deploy, + json!({ "op": "importCompose", "teamId": a.id, "plan": file_next }), + ) + .await + .unwrap_err(); + assert_eq!(status(&e), StatusCode::FORBIDDEN); + w.plan(&deploy, &a.id, None, &next).await.unwrap(); + assert_eq!(w.snapshot(&a.id).await, before, "none of them changed a thing"); + + // A full key for this team, then a developer and an admin. + let full = key(KeyAccess::Full, Some(vec![a.id.clone()])); + let out = w.sync(&full, &project, &file_next, false).await.unwrap(); + assert_eq!(done(&out), pairs(&[("api", "changed")])); + assert_eq!(w.get(&project, "api").await.1["replicas"], 3); + for (name, role, replicas) in [("dev", "developer", 4), ("adm", "admin", 5)] { + w.settle(&a.id).await; + let user = w.member(&a.id, name, role).await; + let text = text.replace("replicas: 2", &format!("replicas: {replicas}")); + let out = w.deploy(&user, &a.id, None, &text, false).await.unwrap(); + assert_eq!(done(&out), pairs(&[("api", "changed")]), "{role}"); + assert_eq!(w.get(&project, "api").await.1["replicas"], replicas); + } + }); +} + +/// `--dry-run` writes nothing, and what it lists is what the sync then +/// does: the same plan comes back with the sync, each service it lists as +/// added, changed or deleted is, and the others aren't written. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn the_dry_run_plan_is_what_the_sync_does() { + run_big(async { + let w = World::new(installation_db().await).await; + let t = w.team("a").await; + let text = file(&w.run); + let project = w.import(&t, &text).await; + let manual = w.service(&t, &project, "manual", None).await; + let (api, ..) = w.get(&project, "api").await; + let (worker, ..) = w.get(&project, "worker").await; + + let next = format!( + "{} cache:\n image: redis:7\n", + without_worker(&text) + .replace("api:1.2", "api:1.3") + .replace("replicas: 2", "replicas: 4") + ); + let before = w.snapshot(&t.id).await; + let plan = w.plan(&t.owner, &t.id, None, &next).await.unwrap(); + assert_eq!(w.snapshot(&t.id).await, before, "a plan writes nothing"); + assert_eq!( + statuses(&plan), + [("api", "changed"), ("cache", "added"), ("worker", "notInFile"), ("manual", "notInFile")] + ); + let api_plan = &plan.services[0]; + assert_eq!( + api_plan.changes, + [ + SyncChange { + field: "image".into(), + from: Some("ghcr.io/acme/api:1.2".into()), + to: Some("ghcr.io/acme/api:1.3".into()), + }, + SyncChange { + field: "replicas".into(), + from: Some("2".into()), + to: Some("4".into()), + }, + ] + ); + + let out = w.sync(&t.owner, &project, &plan.file, true).await.unwrap(); + // The sync worked out the same plan. + assert_eq!(out["plan"]["services"], serde_json::to_value(&plan.services).unwrap()); + // And did what it lists, no more. + let expected: Vec<(String, String)> = plan + .services + .iter() + .filter_map(|s| { + let did = match s.status.as_str() { + "added" => "added", + "changed" => "changed", + "notInFile" if s.from_file => "deleted", + _ => return None, + }; + Some((s.name.clone(), did.to_owned())) + }) + .collect(); + assert_eq!(done(&out), expected); + assert_eq!( + expected, + pairs(&[("api", "changed"), ("cache", "added"), ("worker", "deleted")]) + ); + let (id, spec, _, _) = w.get(&project, "api").await; + assert_eq!(id, api); + assert_eq!(spec["source"]["reference"], "1.3"); + assert_eq!(spec["replicas"], 4); + // Each service the plan deploys got one deployment. + for s in plan.services.iter().filter(|s| s.deploy) { + let d = out["services"] + .as_array() + .unwrap() + .iter() + .find(|v| v["name"] == json!(s.name)) + .unwrap(); + let service: String = + sqlx::query_scalar("SELECT service_id FROM pyo.deployments WHERE id = $1") + .bind(d["deploymentId"].as_str().unwrap()) + .fetch_one(&w.db) + .await + .unwrap(); + assert_eq!(json!(service), d["id"], "{}", s.name); + } + assert_eq!(w.names(&project).await, ["api", "cache", "manual"]); + assert!(w.get(&project, "worker").await.3, "{worker} is being deleted"); + let after = w.snapshot(&t.id).await; + let row = |snap: &Value| { + snap["services"] + .as_array() + .unwrap() + .iter() + .find(|s| s["id"] == json!(manual)) + .cloned() + }; + assert_eq!(row(&after), row(&before)); + + // Planned again, there's nothing left to do. + w.settle(&t.id).await; + let plan = w.plan(&t.owner, &t.id, None, &next).await.unwrap(); + assert_eq!( + statuses(&plan), + [("api", "unchanged"), ("cache", "unchanged"), ("manual", "notInFile")] + ); + }); +} + +/// A sync is one transaction: when a service of the file is refused, the +/// services before it that were changed, added or deleted are as they +/// were, with no deployment and no activity. The plan doesn't run those +/// checks, so a dry run of the same file lists it as a change. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn a_refused_service_leaves_the_project_as_it_was() { + run_big(async { + let w = World::new(installation_db().await).await; + let t = w.team("a").await; + let text = file(&w.run); + let project = w.import(&t, &text).await; + let legacy = with_service(&text, " legacy:\n image: ghcr.io/acme/legacy:1\n"); + w.deploy(&t.owner, &t.id, None, &legacy, false) + .await + .unwrap(); + w.settle(&t.id).await; + assert_eq!(w.names(&project).await, ["api", "legacy", "worker"]); + let before = w.snapshot(&t.id).await; + + // api changes, cache is new, legacy goes, and the worker (last, as + // it depends on the others) asks for a server the cluster hasn't. + let good = with_service( + &text.replace("api:1.2", "api:1.3").replace( + " volumes: [\"work:/data\"]", + " volumes: [\"work:/data\"]\n depends_on: [api, cache]\n x-pyo:\n placement: { servers: [one] }", + ), + " cache:\n image: redis:7\n", + ); + let bad = good.replace("servers: [one]", "servers: [nowhere]"); + let plan = w.plan(&t.owner, &t.id, None, &bad).await.unwrap(); + let order: Vec<&str> = plan.file.services.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(order, ["api", "cache", "worker"]); + assert_eq!( + statuses(&plan), + [("api", "changed"), ("cache", "added"), ("worker", "changed"), ("legacy", "notInFile")] + ); + let e = w.sync(&t.owner, &project, &plan.file, true).await.unwrap_err(); + assert_eq!(status(&e), StatusCode::BAD_REQUEST); + assert_eq!(e.message, "nowhere isn't a server of this cluster."); + assert_eq!(w.snapshot(&t.id).await, before, "nothing of it stays"); + + // A hostname another service of the team has: refused as a whole too. + let taken = good.replace( + &format!("domains: [api-{}.example.com]", w.run), + &format!("domains: [api-{0}.example.com, taken-{0}.example.com]", w.run), + ); + let side = w.project(&t, "side").await; + let holder = format!( + "services:\n holder:\n image: nginx:1\n ports: [\"80:80\"]\n x-pyo:\n domains: [taken-{}.example.com]\n", + w.run + ); + w.deploy(&t.owner, &t.id, Some(&side), &holder, false).await.unwrap(); + w.settle(&t.id).await; + let before = w.snapshot(&t.id).await; + let e = w.deploy(&t.owner, &t.id, None, &taken, true).await.unwrap_err(); + assert_eq!(status(&e), StatusCode::CONFLICT); + assert_eq!( + e.message, + format!("taken-{}.example.com is already used by holder.", w.run) + ); + assert_eq!(w.snapshot(&t.id).await, before); + + // The file put right goes through whole. + let out = w.deploy(&t.owner, &t.id, None, &good, true).await.unwrap(); + assert_eq!( + done(&out), + pairs(&[("api", "changed"), ("cache", "added"), ("worker", "changed"), ("legacy", "deleted")]) + ); + assert_eq!(w.names(&project).await, ["api", "cache", "worker"]); + assert_eq!( + w.get(&project, "worker").await.1["placement"], + json!({ "servers": ["one"], "tags": [] }) + ); + }); +} + +/// As it is today: the plan compares the file with the project and runs +/// none of the checks the apply does. A server the cluster hasn't, a +/// hostname another team's service has, and a very large replica change +/// are each listed as a plain change, so `--dry-run` reads clean, and the +/// sync of that same plan is refused (and changes nothing). +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn a_dry_run_doesnt_run_the_applys_checks() { + run_big(async { + let w = World::new(installation_db().await).await; + let (a, b) = (w.team("a").await, w.team("b").await); + let text = file(&w.run); + let project = w.import(&a, &text).await; + w.import(&b, &file(&format!("{}b", w.run))).await; + let before = w.snapshot(&a.id).await; + + let nowhere = + text.replace("replicas: 2", "replicas: 2\n placement: { servers: [nowhere] }"); + let taken = text.replace( + &format!("domains: [api-{}.example.com]", w.run), + &format!("domains: [api-{0}.example.com, api-{0}b.example.com]", w.run), + ); + let huge = text.replace("replicas: 2", "replicas: 500"); + let theirs = format!("domain api-{}b.example.com", w.run); + for (next, field, want, message) in [ + ( + &nowhere, + "placement", + StatusCode::BAD_REQUEST, + "nowhere isn't a server of this cluster.".to_owned(), + ), + ( + &taken, + theirs.as_str(), + StatusCode::CONFLICT, + format!("api-{}b.example.com is already used by another service.", w.run), + ), + (&huge, "replicas", StatusCode::CONFLICT, String::new()), + ] { + let plan = w.plan(&a.owner, &a.id, None, next).await.unwrap(); + let api = plan.services.iter().find(|s| s.name == "api").unwrap(); + assert_eq!(api.status, "changed", "{field}"); + let fields: Vec<&str> = api.changes.iter().map(|c| c.field.as_str()).collect(); + assert_eq!(fields, [field]); + assert!(api.notes.is_empty() && api.manual.is_empty(), "{field}: no hint"); + + let e = w.sync(&a.owner, &project, &plan.file, false).await.unwrap_err(); + assert_eq!(status(&e), want, "{field}: {}", e.message); + if message.is_empty() { + assert!(e.needs_confirm, "{field}: {}", e.message); + } else { + assert_eq!(e.message, message); + } + assert_eq!(w.snapshot(&a.id).await, before, "{field}"); + } + }); +} diff --git a/crates/pyo-api/src/compose_sync_tests.rs b/crates/pyo-api/src/compose_sync_tests.rs new file mode 100644 index 00000000..b0b570b1 --- /dev/null +++ b/crates/pyo-api/src/compose_sync_tests.rs @@ -0,0 +1,460 @@ +use std::collections::BTreeMap; + +use serde_json::{Value, json}; + +use super::*; +use crate::compose::{Input, plan}; + +const FILE: &str = r#" +name: cloud +services: + cloud-api: + image: ghcr.io/acme/cloud-api:1.2 + environment: + LOG_LEVEL: info + DATABASE_URL: postgres://db:5432/cloud + ports: ["8080:8080"] + x-pyo: + domains: [cloud.example.com] + behindCdn: cloudflare + health: /readyz + replicas: 3 + secrets: [PYO_SECRET_KEY] + db: + image: postgres:17 + volumes: ["db-data:/var/lib/postgresql/data"] +volumes: + db-data: {} +"#; + +fn file_plan(text: &str) -> ComposePlan { + let mut p = plan(&Input { + file: text, + files: BTreeMap::new(), + name_hint: "cloud", + ..Default::default() + }) + .unwrap(); + p.project.file = "compose.yaml".into(); + p +} + +/// The project as an import of `text` leaves it. +fn imported(text: &str) -> Vec { + let p = file_plan(text); + let n = std::cell::Cell::new(0); + let new_id = |prefix: &str| { + n.set(n.get() + 1); + format!("{prefix}_{}", n.get()) + }; + p.services + .iter() + .map(|s| { + let id = format!("svc_{}", s.name); + let spec = compose::service_spec( + s, + Some(&p.project.file), + &id, + "team_a", + "prj_a", + "cl_a", + 1, + &new_id, + ); + Existing { + id, + name: s.name.clone(), + spec, + behind_cdn: s.behind_cdn.clone(), + volumes: compose::volume_specs(s, &new_id), + } + }) + .collect() +} + +fn project() -> Option { + Some(SyncProject { + id: "prj_a".into(), + name: "cloud".into(), + namespace: "cloud".into(), + }) +} + +fn sync(text: &str, existing: &[Existing]) -> SyncPlan { + plan_of(project(), file_plan(text), existing) +} + +fn service<'a>(p: &'a SyncPlan, name: &str) -> &'a SyncService { + p.services.iter().find(|s| s.name == name).unwrap() +} + +fn fields(s: &SyncService) -> Vec<&str> { + s.changes.iter().map(|c| c.field.as_str()).collect() +} + +#[test] +fn the_file_reads_its_x_pyo() { + let p = file_plan(FILE); + let api = p.services.iter().find(|s| s.name == "cloud-api").unwrap(); + assert_eq!(api.domains, vec!["cloud.example.com"]); + assert_eq!(api.behind_cdn.as_deref(), Some("cloudflare")); + assert_eq!(api.replicas, 3); + assert_eq!(api.health_check["type"], "http"); + assert_eq!(api.health_check["path"], "/readyz"); + assert_eq!(api.health_check["port"], 8080); + assert_eq!(api.secrets, vec!["PYO_SECRET_KEY"]); + for m in [ + "source", "env", "ports", "domains", "behindCdn", "health", "replicas", "secrets", + ] { + assert!(api.manages(m), "{m}"); + } + assert!(!api.manages("volumes") && !api.manages("resources.cpuLimit")); + // Its domain replaces the free one. + assert_eq!(api.ports[0].domain.as_deref(), Some("cloud.example.com")); + assert!(p.warnings.iter().all(|w| !w.field.starts_with("x-pyo"))); +} + +#[test] +fn an_import_records_the_file_and_makes_what_x_pyo_says() { + let ex = imported(FILE); + let api = &ex[0].spec; + assert_eq!( + api["compose"], + json!({ "file": "compose.yaml", "service": "cloud-api" }) + ); + assert_eq!(api["domains"][0]["hostname"], "cloud.example.com"); + assert_eq!(api["domains"].as_array().unwrap().len(), 1); + let secret = api["env"] + .as_array() + .unwrap() + .iter() + .find(|e| e["key"] == "PYO_SECRET_KEY") + .unwrap(); + assert_eq!((secret["secret"].clone(), secret["value"].clone()), (json!(true), json!(""))); +} + +#[test] +fn the_same_file_again_changes_nothing() { + let ex = imported(FILE); + let p = sync(FILE, &ex); + assert_eq!(p.services.len(), 2); + for s in &p.services { + assert_eq!(s.status, "unchanged", "{}: {:?}", s.name, s.changes); + assert!(s.manual.is_empty() && !s.deploy, "{}", s.name); + } +} + +#[test] +fn every_kind_of_compose_file_reads_back_unchanged() { + for f in [ + "plausible.yml", + "immich.yml", + "n8n.yml", + "uptime-kuma.yml", + "edge-cases.yml", + "ac-wordpress-mysql.yml", + "ac-prometheus-grafana.yml", + ] { + let text = std::fs::read_to_string(format!( + "{}/tests/fixtures/compose/{f}", + env!("CARGO_MANIFEST_DIR") + )) + .unwrap(); + let ex = imported(&text); + let p = sync(&text, &ex); + for s in &p.services { + assert_eq!(s.status, "unchanged", "{f} {}: {:?}", s.name, s.changes); + } + } +} + +#[test] +fn only_what_the_file_says_differently_changes() { + let ex = imported(FILE); + let next = FILE + .replace("cloud-api:1.2", "cloud-api:1.3") + .replace("replicas: 3", "replicas: 4") + .replace("LOG_LEVEL: info", "LOG_LEVEL: debug\n NEW_ONE: x") + .replace("[cloud.example.com]", "[cloud.example.com, api.example.com]") + .replace("health: /readyz", "health: /livez"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(api.status, "changed"); + assert_eq!( + fields(api), + vec![ + "image", + "env LOG_LEVEL", + "env NEW_ONE", + "domain api.example.com", + "health check", + "replicas" + ] + ); + assert_eq!( + api.changes[0], + SyncChange { + field: "image".into(), + from: Some("ghcr.io/acme/cloud-api:1.2".into()), + to: Some("ghcr.io/acme/cloud-api:1.3".into()), + } + ); + // Values are never shown. + assert!(api.changes[1].from.is_none() && api.changes[1].to.is_none()); + assert!(api.deploy); + assert_eq!(service(&p, "db").status, "unchanged"); + + // The new spec has them, and keeps the rest. + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| format!("{p}_new")); + assert_eq!(m.spec["source"]["reference"], "1.3"); + assert_eq!(m.spec["replicas"], 4); + assert_eq!(m.spec["domains"].as_array().unwrap().len(), 2); + assert_eq!(m.spec["domains"][1]["portName"], m.spec["ports"][0]["name"]); + assert_eq!(m.spec["healthCheck"]["path"], "/livez"); +} + +#[test] +fn a_domain_alone_goes_live_without_a_deploy() { + let ex = imported(FILE); + let next = FILE.replace("[cloud.example.com]", "[cloud.example.com, b.example.com]"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(fields(api), vec!["domain b.example.com"]); + assert!(!api.deploy); + let next = FILE.replace("behindCdn: cloudflare", "behindCdn: none"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(fields(api), vec!["behind CDN"]); + assert!(!api.deploy); + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| p.to_owned()); + assert_eq!(m.behind_cdn, Some(None)); +} + +#[test] +fn settings_changed_in_pyo_stay_when_the_file_leaves_them_out() { + let mut ex = imported(FILE); + let db = &mut ex[1].spec; + // By hand: more replicas, a bigger limit, a variable, a domain, a placement. + db["replicas"] = json!(2); + db["resources"]["memoryLimit"] = json!(4096); + db["env"] + .as_array_mut() + .unwrap() + .push(json!({ "id": "env_x", "key": "EXTRA", "value": "1", "secret": false })); + db["placement"] = json!({ "servers": [], "tags": ["db"] }); + db["healthCheck"] = json!({ "type": "exec", "command": "pg_isready", "path": "", "port": 5432, "initialDelaySeconds": 5, "periodSeconds": 10 }); + let api = &mut ex[0].spec; + api["env"] + .as_array_mut() + .unwrap() + .push(json!({ "id": "env_y", "key": "BY_HAND", "value": "1", "secret": false })); + api["domains"] + .as_array_mut() + .unwrap() + .push(json!({ "id": "dom_y", "hostname": "extra.example.com", "portName": "http" })); + let p = sync(FILE, &ex); + for s in &p.services { + assert_eq!(s.status, "unchanged", "{}: {:?}", s.name, s.changes); + } +} + +#[test] +fn a_secrets_value_is_never_touched() { + let mut ex = imported(FILE); + // The secret got a value in Pyo (sealed), and LOG_LEVEL became a secret. + for e in ex[0].spec["env"].as_array_mut().unwrap() { + if e["key"] == "PYO_SECRET_KEY" { + e["value"] = json!("sealed:abc"); + } + if e["key"] == "LOG_LEVEL" { + e["secret"] = json!(true); + e["value"] = json!("sealed:def"); + } + } + let next = FILE.replace("LOG_LEVEL: info", "LOG_LEVEL: debug"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(api.status, "unchanged", "{:?}", api.changes); + assert!(api.notes.iter().any(|n| n.field == "env LOG_LEVEL")); + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| p.to_owned()); + let value = |k: &str| { + m.spec["env"] + .as_array() + .unwrap() + .iter() + .find(|e| e["key"] == k) + .unwrap()["value"] + .clone() + }; + assert_eq!(value("PYO_SECRET_KEY"), "sealed:abc"); + assert_eq!(value("LOG_LEVEL"), "sealed:def"); + // And a value in the file for an x-pyo secret isn't used. + let given = FILE.replace("LOG_LEVEL: info", "LOG_LEVEL: info\n PYO_SECRET_KEY: oops"); + let fp = file_plan(&given); + assert!(fp.warnings.iter().any(|w| w.field == "x-pyo.secrets")); + assert!(!fp.services[0].env.iter().any(|e| e.key == "PYO_SECRET_KEY")); +} + +#[test] +fn a_new_secret_comes_without_a_value() { + let ex = imported(FILE); + let next = FILE.replace("[PYO_SECRET_KEY]", "[PYO_SECRET_KEY, STRIPE_KEY]"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(fields(api), vec!["secret STRIPE_KEY"]); + assert!(!api.deploy, "it waits for its value"); + assert!(api.notes.iter().any(|n| n.field == "secret STRIPE_KEY")); + // A plain variable of that name is a manual step. + let mut ex = imported(FILE); + ex[0].spec["env"] + .as_array_mut() + .unwrap() + .push(json!({ "id": "env_s", "key": "STRIPE_KEY", "value": "x", "secret": false })); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(api.status, "unchanged"); + assert_eq!(api.manual[0].field, "secret STRIPE_KEY"); +} + +#[test] +fn what_cant_change_in_place_is_a_manual_step() { + let ex = imported(FILE); + // The volume would have to move. + let moved = FILE.replace("db-data:/var/lib/postgresql/data", "db-data:/data"); + let p = sync(&moved, &ex); + let db = service(&p, "db"); + assert_eq!(db.status, "unchanged"); + assert_eq!(db.manual.len(), 1); + assert!(db.manual[0].message.contains("/var/lib/postgresql/data")); + let m = merge(&ex[1], &p.file.services[1], "compose.yaml", 2, &|p| p.to_owned()); + assert!(m.volumes.is_empty()); + // Another kind of source. + let built = FILE.replace("image: postgres:17", "build: ./db"); + let p = sync(&built, &ex); + let db = service(&p, "db"); + assert_eq!(db.manual[0].field, "source"); + assert_eq!(db.status, "unchanged"); + // A new volume is added. + let more = FILE.replace( + "\"db-data:/var/lib/postgresql/data\"", + "\"db-data:/var/lib/postgresql/data\", \"wal:/wal\"", + ); + let p = sync(&more, &ex); + let db = service(&p, "db"); + assert_eq!(fields(db), vec!["volume db-wal"]); + assert!(db.deploy); +} + +#[test] +fn services_no_longer_in_the_file_are_only_listed() { + let mut ex = imported(FILE); + ex.push(Existing { + id: "svc_hand".into(), + name: "hand".into(), + spec: json!({ "name": "hand" }), + ..Default::default() + }); + ex.push(Existing { + id: "svc_other".into(), + name: "other".into(), + spec: json!({ "name": "other", "compose": { "file": "compose.db.yaml", "service": "other" } }), + ..Default::default() + }); + let only_api = r#" +services: + cloud-api: + image: ghcr.io/acme/cloud-api:1.2 +"#; + let p = sync(only_api, &ex); + let names: Vec<(&str, &str, bool)> = p + .services + .iter() + .map(|s| (s.name.as_str(), s.status.as_str(), s.from_file)) + .collect(); + assert_eq!( + names, + vec![ + ("cloud-api", "unchanged", true), + ("db", "notInFile", true), + ("hand", "notInFile", false), + ("other", "notInFile", false), + ] + ); +} + +#[test] +fn a_new_service_in_the_file_is_added() { + let ex = imported(FILE); + let more = format!("{FILE}\n"); + let more = more.replace( + "volumes:\n db-data: {}", + " worker:\n image: ghcr.io/acme/worker:1\nvolumes:\n db-data: {}", + ); + let p = sync(&more, &ex); + let w = service(&p, "worker"); + assert_eq!((w.status.as_str(), w.service_id.is_none(), w.deploy), ("added", true, true)); +} + +#[test] +fn autoscaling_keeps_its_replicas() { + let mut ex = imported(FILE); + ex[0].spec["autoscale"] = json!({ "min": 2, "max": 6, "cpuPercent": 70 }); + let next = FILE.replace("replicas: 3", "replicas: 5"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(api.status, "unchanged"); + assert!(api.notes.iter().any(|n| n.field == "replicas")); +} + +#[test] +fn placement_and_resources_follow_the_file() { + let ex = imported(FILE); + let next = FILE.replace( + " replicas: 3", + " replicas: 3\n placement: { tags: [edge] }", + ); + let next = next.replace( + " ports: [\"8080:8080\"]", + " ports: [\"8080:8080\"]\n deploy: { resources: { limits: { memory: 2G } } }", + ); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(fields(api), vec!["memory limit", "placement"]); + assert_eq!(api.changes[1].to.as_deref(), Some("tag edge")); + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| p.to_owned()); + assert_eq!(m.spec["placement"], json!({ "servers": [], "tags": ["edge"] })); + assert_eq!(m.spec["resources"]["memoryLimit"], 2048); + // The cpu limit isn't in the file: it stays. + assert_eq!(m.spec["resources"]["cpuLimit"], ex[0].spec["resources"]["cpuLimit"]); +} + +#[test] +fn a_linked_project_matches_by_name_and_starts_remembering() { + // Made by hand, then synced: matched by name, nothing else changes. + let mut ex = imported(FILE); + for e in &mut ex { + e.spec.as_object_mut().unwrap().remove("compose"); + } + let p = sync(FILE, &ex); + for s in &p.services { + assert_eq!(s.status, "unchanged", "{}", s.name); + assert!(s.service_id.is_some()); + } + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| p.to_owned()); + assert!(m.record_only); + assert_eq!(m.spec["compose"]["service"], "cloud-api"); +} + +#[test] +fn secrets_go_back_blank() { + let mut spec = json!({ "env": [ + { "key": "A", "value": "sealed:x", "secret": true }, + { "key": "B", "value": "plain", "secret": false }, + ] }); + blank_secrets(&mut spec); + assert_eq!(spec["env"][0]["value"], ""); + assert_eq!(spec["env"][1]["value"], "plain"); + assert_eq!(volume_label("db", "db-data"), "data"); + assert_eq!(volume_label("db", "uploads"), "uploads"); + let _ = Value::Null; +} diff --git a/crates/pyo-api/src/database_logs.rs b/crates/pyo-api/src/database_logs.rs index 4f568eb7..1faf93eb 100644 --- a/crates/pyo-api/src/database_logs.rs +++ b/crates/pyo-api/src/database_logs.rs @@ -330,6 +330,7 @@ fn activity_reason(kind: &str) -> &'static str { "database.import_finished" => "Imported", "database.import_failed" => "Import failed", "database.deleted" => "Deleting", + "database.restarted" => "Update", "database.connected" => "Connected", "database.disconnected" => "Disconnected", "secret.revealed" => "Password shown", diff --git a/crates/pyo-api/src/deploy.rs b/crates/pyo-api/src/deploy.rs index 47143f15..ee1d7c6b 100644 --- a/crates/pyo-api/src/deploy.rs +++ b/crates/pyo-api/src/deploy.rs @@ -2551,6 +2551,9 @@ pub(crate) async fn check_pending_dns(state: &AppState) -> ApiResult<()> { FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d WHERE NOT a.deleting AND d->>'status' IN ('pending_dns', 'verifying') AND lower(d->>'hostname') NOT LIKE '%.ts.net' + -- Through the Cloudflare Tunnel: its address is Cloudflare's, + -- and the tunnel loop says when it's ready. + AND coalesce(d->>'tunnel', '') = '' AND pyo.ms(now()) - coalesce((d->>'dnsCheckedAt')::bigint, 0) >= CASE WHEN pyo.ms(now()) - coalesce((d->>'createdAt')::bigint, 0) < 3600000 THEN 30000 WHEN pyo.ms(now()) - coalesce((d->>'createdAt')::bigint, 0) < 86400000 THEN 300000 diff --git a/crates/pyo-api/src/domainproof.rs b/crates/pyo-api/src/domainproof.rs index 9e38879e..649787eb 100644 --- a/crates/pyo-api/src/domainproof.rs +++ b/crates/pyo-api/src/domainproof.rs @@ -252,6 +252,49 @@ async fn own_free_domain( Ok(Some(false)) } +/// Not proven yet: the team's Cloudflare writes the record when it can +/// (cloudflare.rs `write_proof`), and it's read again for a few seconds +/// while Cloudflare's name servers take it. +async fn prove_with_cloudflare( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + host: &str, +) -> bool { + match crate::cloudflare::write_proof(tx, team_id, host).await { + Ok(true) => {} + Ok(false) => return false, + Err(e) => { + tracing::info!(%host, error = ?e.message, "domain proof: Cloudflare didn't write it"); + return false; + } + } + for _ in 0..5 { + if proven(team_id, host).await { + return true; + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + false +} + +/// One label under the default domain of a Cloudflare Tunnel of the +/// team's (Pyo Cloud: the zone is the team's, its token edits it). +async fn own_tunnel_domain( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + host: &str, +) -> ApiResult { + let domains: Vec = sqlx::query_scalar( + "SELECT default_domain FROM pyo.cluster_tunnels WHERE team_id = $1 AND default_domain IS NOT NULL AND state <> 'removing'", + ) + .bind(team_id) + .fetch_all(&mut **tx) + .await?; + Ok(domains + .iter() + .any(|d| crate::cloudflare::tunnel_loop::under_default(host, d))) +} + /// Checks the hostnames a service is about to claim, and takes over any /// another team holds without proof. `new_hosts`: the ones it doesn't /// have yet (the ones it has stay, proven when they were claimed). @@ -267,6 +310,11 @@ pub async fn check_claims( if pyo_proto::system::is_tailnet_host(host) { continue; } + // A free name under one of the team's own tunnels' default + // domains: a zone its Cloudflare token was checked to control. + if own_tunnel_domain(tx, team_id, host).await? { + continue; + } match own_free_domain(tx, team_id, host).await? { Some(true) => continue, Some(false) => { @@ -276,7 +324,7 @@ pub async fn check_claims( } None => {} } - if !proven(team_id, host).await { + if !proven(team_id, host).await && !prove_with_cloudflare(tx, team_id, host).await { return Err(ApiError::forbidden(how_to(team_id, host))); } // Held by another team: theirs while they can still prove it. diff --git a/crates/pyo-api/src/freedomain.rs b/crates/pyo-api/src/freedomain.rs index 1accf9ac..adb9c7d2 100644 --- a/crates/pyo-api/src/freedomain.rs +++ b/crates/pyo-api/src/freedomain.rs @@ -69,6 +69,10 @@ pub fn tailnet_v4(ip: &str) -> Option { pub enum Mode { Public, Tailscale, + /// Through the cluster's Cloudflare Tunnel: names under its default + /// domain (`-.example.com`), none without one. + /// From the cluster's traffic, never chosen as an address. + Tunnel, } impl Mode { @@ -84,6 +88,7 @@ impl Mode { match self { Mode::Public => "public", Mode::Tailscale => "tailscale", + Mode::Tunnel => "tunnel", } } } @@ -104,6 +109,10 @@ pub struct Cluster { /// issued the dashboard's certificate there): on the cluster Pyo runs /// on (publicdash.rs `reached`). pub reached: Option, + /// In tunnel mode (its traffic is "tunnel"). + pub tunnel: bool, + /// Its tunnel's default domain, when it has one. + pub tunnel_domain: Option, } /// Servers that take public traffic, ready ones first. @@ -198,6 +207,7 @@ impl Cluster { return None; } match (self.mode(), self.set.as_deref()) { + (Mode::Tunnel, _) => None, (Mode::Public, _) => self.public_ip(), (Mode::Tailscale, None) => self.cloud_ip(), (Mode::Tailscale, Some(_)) => None, @@ -223,6 +233,9 @@ impl Cluster { /// traffic and the internet reaches its public IP directly, else /// Tailscale. pub fn mode(&self) -> Mode { + if self.tunnel { + return Mode::Tunnel; + } self.set .as_deref() .and_then(Mode::parse) @@ -238,9 +251,21 @@ impl Cluster { match self.mode() { Mode::Public => self.public_ip(), Mode::Tailscale => self.tailnet_ip(), + Mode::Tunnel => None, + } + } + + /// What free domains end in now: "203.0.113.7.nip.io", or in tunnel + /// mode the tunnel's default domain ("example.com"). None: no free + /// domain (no address, or tunnel mode without a default domain). + pub fn suffix(&self) -> Option { + match self.mode() { + Mode::Tunnel => self.tunnel_domain.clone(), + _ => self.address().map(|ip| format!("{ip}.nip.io")), } } + /// Where a free domain on `ip` belongs now. One on a public address /// stays on the public IP (chosen when it was added: the dashboard's /// "Free domain"), while the cluster has one. Any other (Tailscale, @@ -275,6 +300,9 @@ impl Cluster { "tailnetIp": s(self.tailnet_ip()), "freeDomainAddress": self.mode().as_str(), "freeDomainIp": s(self.address()), + // What free domains end in ("203.0.113.7.nip.io", or the + // tunnel's default domain): null for none. + "freeDomainSuffix": self.suffix(), "behindNat": self.behind_nat(), }) } @@ -283,8 +311,13 @@ impl Cluster { /// "nginx-web.203.0.113.7.nip.io": the label at most 63 characters, so the /// whole name stays well within 253. pub fn hostname(service: &str, namespace: &str, ip: Ipv4Addr) -> String { + format!("{}.{ip}.nip.io", label(service, namespace)) +} + +/// A free domain's label: "nginx-web", at most 63 characters. +fn label(service: &str, namespace: &str) -> String { let label: String = format!("{service}-{namespace}").chars().take(63).collect(); - format!("{}.{ip}.nip.io", label.trim_end_matches('-')) + label.trim_end_matches('-').to_owned() } /// A free domain's parts: its label(s), address, and whether it's in the @@ -363,18 +396,26 @@ pub fn ips(caps: &Value, key: &str) -> Vec { .collect() } +/// A cluster's row as [`load`] reads it: team, public traffic, the +/// free-domain address set, capabilities, same cluster, tunnel mode, and +/// the tunnel's default domain. +type Stored = (String, bool, Option, Value, bool, bool, Option); + /// A cluster as stored, and its team. pub async fn load( tx: &mut Transaction<'_, Postgres>, cluster_id: &str, ) -> ApiResult> { - let row: Option<(String, bool, Option, Value, bool)> = sqlx::query_as( - "SELECT team_id, public_traffic, free_domain_address, capabilities, same_cluster FROM pyo.clusters WHERE id = $1", + let row: Option = sqlx::query_as( + "SELECT c.team_id, c.public_traffic, c.free_domain_address, c.capabilities, c.same_cluster, + c.traffic = 'tunnel', t.default_domain + FROM pyo.clusters c LEFT JOIN pyo.cluster_tunnels t ON t.cluster_id = c.id AND t.state <> 'removing' + WHERE c.id = $1", ) .bind(cluster_id) .fetch_optional(&mut **tx) .await?; - let Some((team_id, public_traffic, set, caps, same_cluster)) = row else { + let Some((team_id, public_traffic, set, caps, same_cluster, tunnel, tunnel_domain)) = row else { return Ok(None); }; let servers: Vec = @@ -395,16 +436,18 @@ pub async fn load( } else { None }, + tunnel, + tunnel_domain, }, ))) } -/// A cluster's free-domain address now. -pub async fn for_cluster( +/// What a cluster's free domains end in now ([`Cluster::suffix`]). +pub async fn suffix_for( tx: &mut Transaction<'_, Postgres>, cluster_id: &str, -) -> ApiResult> { - Ok(load(tx, cluster_id).await?.and_then(|(_, c)| c.address())) +) -> ApiResult> { + Ok(load(tx, cluster_id).await?.and_then(|(_, c)| c.suffix())) } /// Moves the cluster's free domains made on another of its addresses, or @@ -577,6 +620,7 @@ mod tests { tailnet_web: vec![], servers, reached: None, + ..Default::default() } } @@ -586,6 +630,35 @@ mod tests { "publicIpv4": "203.0.113.7", "nicPublicIps": ["203.0.113.7"], "tailnetIp": "100.64.0.9" }) } + /// In tunnel mode, free domains go under the tunnel's default domain + /// (its wildcard), and there's none without one. nip.io names stay + /// where they are (they stop answering until public ports are back). + #[test] + fn tunnel_mode_names_free_domains_under_the_default_domain() { + let mut c = cluster(false, None, vec![direct_server()]); + c.tunnel = true; + c.tunnel_domain = Some("example.com".into()); + assert_eq!(c.mode(), Mode::Tunnel); + assert_eq!(c.address(), None); + assert_eq!(c.suffix().as_deref(), Some("example.com")); + assert_eq!( + format!("{}.{}", label("web", "shop"), c.suffix().unwrap()), + "web-shop.example.com" + ); + assert_eq!(c.shown()["freeDomainAddress"], "tunnel"); + assert_eq!(c.shown()["freeDomainSuffix"], "example.com"); + // A nip.io domain from before stays put. + assert_eq!(moved("web-shop.203.0.113.7.nip.io", &c.known(), |ip| c.home(ip)), None); + c.tunnel_domain = None; + assert_eq!(c.suffix(), None); + + // Public ports again: the nip.io names answer as they were. + let c = cluster(true, None, vec![direct_server()]); + assert_eq!(c.suffix().as_deref(), Some("203.0.113.7.nip.io")); + assert_eq!(hostname("web", "shop", v4("203.0.113.7")), "web-shop.203.0.113.7.nip.io"); + assert_eq!(Mode::parse("tunnel"), None, "never chosen as an address"); + } + #[test] fn public_mode_uses_the_public_address_never_a_private_one() { let c = cluster(true, Some("public"), vec![nat_server()]); @@ -675,7 +748,7 @@ mod tests { assert_eq!( c.shown(), json!({ "publicIp": "129.226.158.31", "tailnetIp": "100.101.67.2", "freeDomainAddress": "tailscale", - "freeDomainIp": "100.101.67.2", "behindNat": true }) + "freeDomainIp": "100.101.67.2", "freeDomainSuffix": "100.101.67.2.nip.io", "behindNat": true }) ); // Public can still be chosen there. let c = cluster(true, Some("public"), vec![nat_server()]); diff --git a/crates/pyo-api/src/gate.rs b/crates/pyo-api/src/gate.rs index 927125ed..aae7e1e2 100644 --- a/crates/pyo-api/src/gate.rs +++ b/crates/pyo-api/src/gate.rs @@ -42,6 +42,8 @@ const REMOVALS: &[&str] = &[ "remove_server", "forget_snapshot", "tailscale_remove", + // A team can always take its Cloudflare Tunnel (and its records) back. + "tunnel_remove", ]; /// Commands that follow a change made elsewhere, a removal's too (the diff --git a/crates/pyo-api/src/install.rs b/crates/pyo-api/src/install.rs index e305947c..1e2745ce 100644 --- a/crates/pyo-api/src/install.rs +++ b/crates/pyo-api/src/install.rs @@ -129,8 +129,8 @@ async fn token_for_manifest(db: &sqlx::PgPool, token: &str) -> ApiResult<(String /// gateway is set up). A cluster that's running keeps its setting. async fn web_ports_busy(db: &sqlx::PgPool, cluster: &str) -> ApiResult<()> { let off = sqlx::query( - "UPDATE pyo.clusters SET public_traffic = false - WHERE id = $1 AND last_seen_at IS NULL AND public_traffic", + "UPDATE pyo.clusters SET traffic = 'tailscale' + WHERE id = $1 AND last_seen_at IS NULL AND traffic = 'public'", ) .bind(cluster) .execute(db) @@ -245,11 +245,12 @@ fn gateway_crds_yaml(with_api: bool) -> String { } /// Whether new installs bind the self-update role: their agent then -/// brings its admission policy up to date with Pyo by itself. On unless -/// `PYO_AGENT_SELF_UPDATE` is false: with it, whoever controls this Pyo can -/// loosen what the agent may do on those clusters, so a Pyo serving other -/// people's clusters (Pyo Cloud) turns it off. A cluster's owner can also -/// delete its `pyo-agent-self-update` binding. +/// brings its roles and its admission policy up to date with Pyo by +/// itself. On unless `PYO_AGENT_SELF_UPDATE` is false: with it, whoever +/// controls this Pyo can give the agent any permission on those clusters +/// (pyo-proto's rbac.rs says why that was so before it wrote roles too), +/// so a Pyo serving other people's clusters (Pyo Cloud) turns it off. A +/// cluster's owner can also delete its `pyo-agent-self-update` binding. pub fn self_update() -> bool { self_update_from(std::env::var("PYO_AGENT_SELF_UPDATE").ok().as_deref()) } @@ -282,6 +283,50 @@ pub fn parts(upgrades: bool) -> &'static pyo_proto::rbac::InstallParts { })[usize::from(upgrades)] } +/// The hash of the install a cluster without the self-update role gets +/// from this Pyo (not the cluster Pyo runs on): [`parts`]`(false)`'s on a +/// Pyo that hands out no self-update role (Pyo Cloud). +pub fn verifier_install() -> &'static str { + use pyo_proto::system::{db_images_from_env, geoip_image_from_env, waf_image_from_env}; + static HASH: std::sync::OnceLock = std::sync::OnceLock::new(); + HASH.get_or_init(|| { + pyo_proto::rbac::InstallParts::new( + false, + false, + &waf_image_from_env(), + &geoip_image_from_env(), + &db_images_from_env(), + ) + .hash + }) +} + +/// How long an answer of [`version`] may be kept, in seconds. +const VERSION_MAX_AGE: &str = "public, max-age=60"; + +/// GET /install/version: the version this Pyo runs and the install a +/// cluster without the self-update role gets from it +/// ([`verifier_install`]), as `{"version":"X.Y.Z","install":""}`. +/// +/// For the verifier on a cluster's first server (`pyo-verify`): it applies +/// only what the signed release of this version defines, so this names a +/// version and nothing more. No key, as `/api/v1/meta` (which says the +/// version too) and the install scripts beside it: nothing here is secret, +/// nothing is read from the database, and the answer may be kept a minute. +pub async fn version() -> impl IntoResponse { + ( + [(header::CACHE_CONTROL, VERSION_MAX_AGE)], + crate::error::Json(version_answer( + env!("CARGO_PKG_VERSION"), + verifier_install(), + )), + ) +} + +fn version_answer(version: &str, install: &str) -> serde_json::Value { + serde_json::json!({ "version": version, "install": install }) +} + /// The agent's manifest. On the cluster Pyo itself runs on (an in-cluster /// API address), its agent also runs Pyo's upgrader. pub fn render(api_url: &str, image: &str, token: &str) -> String { @@ -325,7 +370,11 @@ pub fn render_with(api_url: &str, image: &str, token: &str, extra_env: &[(&str, # DNS's scale; # - the gateway's routes, certificates and settings in pyo-gateway, # with exactly the content this release writes (never its Secrets' content), -# and its failed pods, deleted; +# and its failed pods, deleted. Its role there names no Service, network +# policy or ConfigMap it writes: the admission policy at the end does, by +# name and content. On Kubernetes older than 1.30 there is no admission +# policy, so the agent could change or delete any of those three kinds in +# pyo-gateway (Envoy Gateway's own included); # - the databases system in pyo-databases (CloudNativePG, the MySQL # operator and pyo-db-controller), once a team makes its first database # here, with exactly the content this release defines; @@ -336,9 +385,20 @@ pub fn render_with(api_url: &str, image: &str, token: &str, extra_env: &[(&str, # - servers (pyo-agent-nodes) and their disk and network figures # (pyo-agent-stats): delete those two bindings to take that away; # - read your pyo-system/pyo-policy ConfigMap, never write it; +# - read pyo-system/pyo-verifier, where your server's verifier says how +# automatic updates stand (when you set them up), never write it; # - with pyo-agent-self-update bound (on unless this Pyo turns it off): -# rewrite its own admission policy when Pyo is updated, once its roles are -# already as Pyo's; delete that binding to take that away. +# when Pyo is updated, update its own roles and bindings (the ones below, +# by name, never a new one) and rewrite its own admission policy, so the +# cluster needs no command after a release. With it, whoever controls +# this Pyo can give the agent any permission here, up to cluster-admin. +# That was already so while this role only rewrote the admission policy: +# the policy is what keeps the agent's roles from privileged pods and +# from writing other roles. Delete the pyo-agent-self-update +# ClusterRoleBinding to take all of it away. The agent's roles then +# change only when you run the connect command. A role the agent can't +# update (a new one, say) waits for that command, and the rest of a +# refresh goes on without it. # The admission policy at the end holds it to this, and refuses privileged # containers and the host's network, processes and files, except for Pyo's # own build, metrics and GPU components. @@ -378,9 +438,12 @@ spec: pyo.dev/token: "{token_stamp}" spec: serviceAccountName: pyo-agent - # It may run on a GPU server kept for GPU work. - tolerations: - - {{ key: nvidia.com/gpu, operator: Exists, effect: NoSchedule }} + # It keeps running on a server short of disk or memory, and starts + # there after an update: it reports that state, and cleans up what + # the evictions leave. It may also run on a GPU server kept for GPU + # work. A refresh brings these two to an older install. + priorityClassName: {priority} + tolerations: {tolerations} containers: - name: agent image: {image} @@ -407,6 +470,8 @@ spec: {admission}"#, annotation = pyo_proto::rbac::INSTALL_ANNOTATION, token_stamp = token_stamp(token), + priority = pyo_proto::rbac::AGENT_PRIORITY, + tolerations = pyo_proto::rbac::agent_tolerations(), ) } @@ -422,6 +487,40 @@ fn token_stamp(token: &str) -> String { /// the command is): shown with its "Update needed", and by what waits for it. pub const OUTDATED: &str = "This cluster's agent needs an update. Run the command under Refresh this cluster in the cluster's settings."; +/// An outdated install that refused the client policies removing +/// client-sent visitor headers: its agent wrote them without that +/// (`AgentScope::headers_kept`). +pub const HEADERS_KEPT: &str = "This cluster's install is older than Pyo's. Run the command under Refresh this cluster in the cluster's settings so client-sent visitor headers are removed."; + +/// What an install that's current except for some of its roles needs (a +/// refresh brought the admission policy and the image pins, and couldn't +/// write those roles): shown with its "Update needed", and by the features +/// that wait for them. +pub const ROLES: &str = "This cluster's agent needs an update for some features. Run the command under Refresh this cluster in the cluster's settings."; + +/// Whether the system bundles (the databases system, the WAF, Pyo Static) +/// can be installed and updated on a cluster whose install is in `state`: +/// when it's current, or current except for roles they don't need +/// (`bundles`, from `agentInstall.bundles`). Never while it's outdated or +/// updating: its older admission policy refuses this Pyo's bundles. +pub fn bundles_ready(state: Option<&str>, bundles: Option) -> bool { + match state { + None | Some("current") => true, + Some("roles") => bundles == Some(true), + _ => false, + } +} + +/// Why an outdated install needs its connect command, when nothing more +/// particular is known. +fn outdated_message(scope: &pyo_proto::rbac::AgentScope) -> &'static str { + if scope.headers_kept { + HEADERS_KEPT + } else { + OUTDATED + } +} + /// A deploy that needs what an outdated install can't do. pub fn outdated_deploy() -> String { format!("{OUTDATED} Then deploy again.") @@ -436,16 +535,19 @@ pub fn refused_by_install(message: &str) -> bool { } /// A command's error as the team reads it: a refusal while the cluster's -/// install (`install`, its state) is outdated is [`OUTDATED`]'s to fix. +/// install (`install`, its state) is outdated, or current except for some +/// roles, is [`OUTDATED`]'s to fix. pub fn shown(message: Option<&str>, install: &str) -> Option { match message { - Some(m) if install == "outdated" && refused_by_install(m) => Some(OUTDATED.into()), + Some(m) if matches!(install, "outdated" | "roles") && refused_by_install(m) => { + Some(OUTDATED.into()) + } m => m.map(str::to_owned), } } /// The cluster's install as its last heartbeat found: "current", -/// "updating" or "outdated" (current when it never said). +/// "updating", "outdated" or "roles" (current when it never said). pub async fn state_of(db: impl sqlx::PgExecutor<'_>, cluster_id: &str) -> ApiResult { Ok(sqlx::query_scalar::<_, Option>( "SELECT capabilities->'agentInstall'->>'state' FROM pyo.clusters WHERE id = $1", @@ -482,7 +584,8 @@ const REFRESH_PATIENCE_MAX_SECS: i64 = 10 * 60; const REFRESH_RETRY_SECS: i64 = 30 * 60; /// Where a cluster's install stands, and whether to send it a refresh: -/// ("current" | "updating" | "outdated", why it's outdated, send). +/// ("current" | "updating" | "outdated" | "roles", why it isn't current, +/// send). "roles": current except for some of its roles. pub fn install_state( scope: &pyo_proto::rbac::AgentScope, expected: &str, @@ -491,6 +594,12 @@ pub fn install_state( if pyo_proto::rbac::install_current(scope, expected) { return ("current", String::new(), false); } + // A refresh brought this Pyo's admission policy and image pins, and + // left roles it couldn't write. Another refresh would leave the same + // ones, so none is sent: the connect command brings them. + if scope.admission == "enforced" && scope.install == expected && !scope.roles_older.is_empty() { + return ("roles", ROLES.into(), false); + } // The agent may only update its admission policy, never make it: the // cluster's connect command puts a missing one back. if scope.admission == "missing" { @@ -503,6 +612,11 @@ pub fn install_state( } match last { None => ("updating", String::new(), true), + // Its roles aren't this Pyo's: the same agent can't make this + // refresh however often it's sent, so the connect command it is. + Some(l) if l.status == "failed" && roles_older(&l.message) && !l.agent_changed => { + ("outdated", String::new(), false) + } Some(l) if l.status == "failed" => { if l.age_secs < REFRESH_RETRY_SECS && !l.agent_changed { ("outdated", l.message.clone(), false) @@ -520,6 +634,14 @@ pub fn install_state( } } +/// Whether a refresh failed because the agent's roles aren't this Pyo's +/// (pyo-agent's install.rs says so in these words): no agent can change +/// its own roles, so only the cluster's connect command gets it further. +/// A release that changes the roles leaves every cluster there. +pub fn roles_older(message: &str) -> bool { + message.contains(pyo_proto::rbac::ROLES_OLDER) +} + /// How long the `attempts`th refresh of an install has before another is sent. fn refresh_patience(attempts: i64) -> i64 { let doublings = attempts.clamp(1, 11) - 1; @@ -596,7 +718,9 @@ pub async fn refreshing( } /// From a heartbeat: where the cluster's install stands against this Pyo's, -/// as `capabilities.agentInstall` (`{state, message, command}`), sending +/// as `capabilities.agentInstall` (`{state, message, command}`, and in +/// state "roles" `bundles`: whether the roles left behind leave the system +/// bundles free, see [`bundles_ready`]), sending /// the agent (version `agent`) a refresh when it can make one. Returns it, and whether a /// command was queued. `command`, in every state, is the connect command /// run again on the cluster's first server: it also applies Pyo's latest @@ -628,13 +752,414 @@ pub async fn sync( .await?; tracing::info!(cluster = cluster_id, install = %parts.hash, "sent the agent its install's refresh"); } - let mut out = json!({ "state": state, "command": command(same_cluster) }); + // The cluster Pyo runs on: its server runs the command by itself. + let host = host_refreshes(same_cluster, self_update(), scope, state); + let stamp = host_stamp(&parts.hash); + let (state, message) = if host && host_at_work(tx, &stamp).await? { + ("updating", String::new()) + } else { + (state, message) + }; + let out = install_shown( + scope, + state, + &message, + command(same_cluster), + host.then_some(stamp.as_str()), + unix_now(), + ); + Ok((out, send)) +} + +/// `capabilities.agentInstall` for a cluster whose install is in `state` +/// (see [`sync`]): `host_stamp` when its own server refreshes it. +/// `autoUpdate` ([`auto_update`]) is added last and is only ever shown: +/// everything else here is the same whatever the verifier's status says. +fn install_shown( + scope: &pyo_proto::rbac::AgentScope, + state: &str, + message: &str, + command: String, + host_stamp: Option<&str>, + now: i64, +) -> serde_json::Value { + use serde_json::json; + let mut out = json!({ "state": state, "command": command }); + if let Some(stamp) = host_stamp { + out["hostRefresh"] = json!(stamp); + } + if state == "roles" { + out["bundles"] = json!(!pyo_proto::rbac::bundles_held_back(&scope.roles_older)); + } if !message.is_empty() { out["message"] = json!(message); } else if state == "outdated" { - out["message"] = json!(OUTDATED); + out["message"] = json!(outdated_message(scope)); } - Ok((out, send)) + if let Some(auto) = auto_update(scope, state, now) { + out["autoUpdate"] = auto; + } + out +} + +// ── Automatic updates, as the server's verifier reports them ─────────────── +// +// A cluster without the self-update role (Pyo Cloud's) gets a release's +// roles, admission policy and image pins only from its connect command. +// With `--auto-update` that command also sets up the verifier +// (`pyo-verify`) on the cluster's first server: a root program on a timer +// that asks GET /install/version which version this Pyo runs, checks that +// version's signed release, and applies only what that release defines. +// Pyo can name a version. It can't turn the verifier on or off, make it +// run, or hand it anything to apply: the customer's switches are theirs +// (`updates: "hold"` in pyo-system/pyo-policy, /etc/pyo/verify.conf). +// +// 0.51.0 ships the verifier's bootstrap only: it checks the signed +// release, never moves backwards, replaces itself with that release's +// verifier, and writes its status. It applies nothing to the cluster yet, +// so an outdated install still shows "Update needed" with its command. +// +// Its status reaches Pyo through the agent (`AgentScope::verifier`), so an +// agent that was broken into can say anything there. It only ever adds +// `autoUpdate` to what the cluster's settings show ([`auto_update`]). The +// install's state, the refresh Pyo sends, what waits for the connect +// command and what the host does all follow from the rest of the scope. + +/// A status the verifier last wrote longer ago than this counts as no +/// verifier: its timer stopped, or it was removed. +pub const VERIFIER_STALE_SECS: i64 = 48 * 60 * 60; + +pub const AUTO_UPDATE_ON: &str = "Automatic updates are set up on this cluster"; +pub const AUTO_UPDATE_NEEDS_COMMAND: &str = "This update still needs the command."; +pub const AUTO_UPDATE_HOLD_SERVER: &str = + "Automatic updates are on hold. They were turned off on the server."; +pub const AUTO_UPDATE_HOLD_POLICY: &str = + "Automatic updates are on hold. They were turned off in this cluster's policy."; +pub const AUTO_UPDATE_PROBLEM: &str = "Automatic updates reported a problem:"; +pub const AUTO_UPDATE_FALLBACK: &str = "Run the command to update this cluster."; + +/// Seconds since 1970 of an RFC 3339 time ("2026-11-23T10:00:00Z", with or +/// without a fraction, `Z` or an offset). None when it isn't one. +fn rfc3339_secs(s: &str) -> Option { + let s = s.trim(); + if !s.is_ascii() || s.len() < 20 { + return None; + } + let b = s.as_bytes(); + let num = |from: usize, to: usize| -> Option { + let part = s.get(from..to)?; + part.bytes() + .all(|c| c.is_ascii_digit()) + .then(|| part.parse::().ok()) + .flatten() + }; + if b[4] != b'-' || b[7] != b'-' || !matches!(b[10], b'T' | b't' | b' ') || b[13] != b':' || b[16] != b':' { + return None; + } + let (y, m, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?); + let (h, min, sec) = (num(11, 13)?, num(14, 16)?, num(17, 19)?); + if !(1..=12).contains(&m) || !(1..=31).contains(&d) || h > 23 || min > 59 || sec > 60 { + return None; + } + let mut rest = &s[19..]; + if let Some(fraction) = rest.strip_prefix('.') { + let digits = fraction.bytes().take_while(u8::is_ascii_digit).count(); + if digits == 0 { + return None; + } + rest = &fraction[digits..]; + } + let offset = match rest { + "Z" | "z" => 0, + o if o.len() == 6 && o.as_bytes()[3] == b':' => { + let sign = match o.as_bytes()[0] { + b'+' => 1, + b'-' => -1, + _ => return None, + }; + let part = |r: std::ops::Range| -> Option { + let p = o.get(r)?; + p.bytes().all(|c| c.is_ascii_digit()).then(|| p.parse::().ok()).flatten() + }; + let (oh, om) = (part(1..3)?, part(4..6)?); + if oh > 23 || om > 59 { + return None; + } + sign * (oh * 3600 + om * 60) + } + _ => return None, + }; + // Days since 1970-01-01 of a date in the Gregorian calendar. + let (y, m) = if m <= 2 { (y - 1, m + 9) } else { (y, m - 3) }; + let era = y.div_euclid(400); + let yoe = y.rem_euclid(400); + let doy = (153 * m + 2) / 5 + d - 1; + let days = era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468; + Some(days * 86_400 + h * 3600 + min * 60 + sec - offset) +} + +/// The verifier's status when it counts: the cluster has no self-update +/// role (its agent refreshes it otherwise), and the verifier checked +/// within [`VERIFIER_STALE_SECS`] of `now`. A time that can't be read is +/// as good as none. +fn verifier_of( + scope: &pyo_proto::rbac::AgentScope, + now: i64, +) -> Option<&pyo_proto::rbac::VerifierStatus> { + let v = scope.verifier.as_ref().filter(|_| !scope.self_update)?; + let checked = rfc3339_secs(&v.checked)?; + (now - checked <= VERIFIER_STALE_SECS).then_some(v) +} + +/// Text from the verifier, as shown: one line, no control characters, at +/// most `max` characters. +fn shown_text(s: &str, max: usize) -> String { + let line = s + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect::(); + let line = line.split_whitespace().collect::>().join(" "); + match line.char_indices().nth(max) { + Some((at, _)) => format!("{}…", line[..at].trim_end()), + None => line, + } +} + +/// A version as the verifier names it, when it looks like one. +fn shown_version(s: &str) -> Option<&str> { + let s = s.trim().trim_start_matches('v'); + (!s.is_empty() + && s.len() <= 32 + && s.starts_with(|c: char| c.is_ascii_digit()) + && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'+'))) + .then_some(s) +} + +/// How automatic updates stand on a cluster without the self-update role, +/// for its settings: `{state, message, version?}`, none without a +/// verifier that checked lately ([`verifier_of`]). `state`: +/// +/// - "on": the verifier runs. While the install waits for the connect +/// command (`install`: its state), the message says the command is +/// still needed: the bootstrap applies nothing to the cluster. +/// - "hold": turned off by the customer, on the server or in the policy. +/// - "error": the verifier's last check failed, with its own words. +/// +/// Only ever shown: see the section's note. +pub fn auto_update( + scope: &pyo_proto::rbac::AgentScope, + install: &str, + now: i64, +) -> Option { + let v = verifier_of(scope, now)?; + let waits = matches!(install, "outdated" | "roles"); + let version = shown_version(&v.version); + let error = shown_text(&v.error, 300); + let (state, message) = if scope.policy.updates_hold { + ("hold", AUTO_UPDATE_HOLD_POLICY.to_owned()) + } else if v.hold { + ("hold", AUTO_UPDATE_HOLD_SERVER.to_owned()) + } else if !error.is_empty() { + let end = if error.ends_with(['.', '!', '?', '…']) { "" } else { "." }; + let fallback = if waits { format!(" {AUTO_UPDATE_FALLBACK}") } else { String::new() }; + ("error", format!("{AUTO_UPDATE_PROBLEM} {error}{end}{fallback}")) + } else { + let on = match version { + Some(v) => format!("{AUTO_UPDATE_ON} (version {v})."), + None => format!("{AUTO_UPDATE_ON}."), + }; + ("on", if waits { format!("{on} {AUTO_UPDATE_NEEDS_COMMAND}") } else { on }) + }; + let mut out = serde_json::json!({ "state": state, "message": message }); + if let Some(version) = version { + out["version"] = serde_json::json!(version); + } + Some(out) +} + +// ── The cluster Pyo runs on, refreshed by its own server ─────────────────── +// +// What no agent can bring (a new role object, a chart installed with the +// agent, host settings) comes with the connect command. On the server Pyo +// runs on, the host's timer (install.sh `host_units`) runs that command by +// itself: it asks GET /install/this-machine every minute, which says +// `"refresh": true` while this is so, and reports each step to POST +// /install/this-machine/refresh. Meanwhile the cluster shows "updating", +// not "Update needed". The host runs it once per install ([`host_stamp`]), +// again about hourly after a failure, and a few times a day at most. + +/// Whether the server Pyo runs on refreshes its cluster's install by +/// itself: the install waits for the connect command (`state`), and both +/// this installation (`self_update`, off on Pyo Cloud) and the cluster's +/// owner (the self-update role is bound, the cluster isn't read only) let +/// Pyo keep it current. +pub fn host_refreshes( + same_cluster: bool, + self_update: bool, + scope: &pyo_proto::rbac::AgentScope, + state: &str, +) -> bool { + same_cluster && host_may_refresh(self_update, scope) && matches!(state, "outdated" | "roles") +} + +/// Whether the server Pyo runs on may run the connect command for its +/// cluster by itself at all (see [`host_refreshes`]). +fn host_may_refresh(self_update: bool, scope: &pyo_proto::rbac::AgentScope) -> bool { + self_update && scope.self_update && !scope.policy.read_only +} + +/// What the host counts its automatic runs by: this Pyo's version and the +/// install (`hash`) it brings. One run each, unless it failed. +pub fn host_stamp(hash: &str) -> String { + format!("{}-{hash}", env!("CARGO_PKG_VERSION")) +} + +/// What the host last said of its refresh (`pyo.settings` 'host_refresh'). +#[derive(Debug, Clone, PartialEq)] +pub struct HostRefresh { + /// The [`host_stamp`] it's about. + pub install: String, + /// "waiting" (Pyo's own, until the host says more), "running", "done", + /// "failed" or "held" (it ran for this install already, or too often + /// today). + pub status: String, + pub age_secs: i64, +} + +/// The host takes this long to start (its timer runs every minute; after +/// an update its scripts come first), and after it's done the agent this +/// long to say the install is current. +const HOST_WAIT_SECS: i64 = 10 * 60; +/// A run takes minutes, more when k3s restarts. +const HOST_RUN_SECS: i64 = 30 * 60; + +/// Whether the host is about to refresh the install `stamp`, or at it +/// (`last`: its last word). Not once it failed, gave up, or took too long: +/// the cluster then says "Update needed" with its command, as any other. +/// A server without the timer (set up before Pyo 0.4.2 and never since) +/// gets there after [`HOST_WAIT_SECS`]. +pub fn host_working(stamp: &str, last: Option<&HostRefresh>) -> bool { + match last { + Some(l) if l.install == stamp => match l.status.as_str() { + "waiting" | "done" => l.age_secs < HOST_WAIT_SECS, + "running" => l.age_secs < HOST_RUN_SECS, + _ => false, + }, + // Nothing said of this install yet: asked from now on. + _ => true, + } +} + +fn unix_now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) +} + +/// [`HostRefresh`] from its setting. +fn host_refresh_from(value: &serde_json::Value, now: i64) -> Option { + Some(HostRefresh { + install: value["install"].as_str()?.to_owned(), + status: value["status"].as_str()?.to_owned(), + age_secs: (now - value["at"].as_i64()?).max(0), + }) +} + +/// The setting's next value when the host (or Pyo, "waiting") says +/// `status` of `install`: none when it said the same before, so the time +/// stays the first one's. +fn host_refresh_next( + last: Option<&HostRefresh>, + install: &str, + status: &str, + now: i64, +) -> Option { + if last.is_some_and(|l| l.install == install && l.status == status) { + return None; + } + Some(serde_json::json!({ "install": install, "status": status, "at": now })) +} + +async fn host_refresh_get(db: impl sqlx::PgExecutor<'_>) -> ApiResult> { + let v: Option = + sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'host_refresh'") + .fetch_optional(db) + .await?; + Ok(v.and_then(|v| host_refresh_from(&v, unix_now()))) +} + +async fn host_refresh_set(db: impl sqlx::PgExecutor<'_>, value: serde_json::Value) -> ApiResult<()> { + sqlx::query("INSERT INTO pyo.settings (key, value) VALUES ('host_refresh', $1) ON CONFLICT (key) DO UPDATE SET value = excluded.value") + .bind(value) + .execute(db) + .await?; + Ok(()) +} + +/// [`host_working`] for the install `stamp`, noting when Pyo first waited +/// for the host to refresh it. +async fn host_at_work(db: &mut sqlx::PgConnection, stamp: &str) -> ApiResult { + let last = host_refresh_get(&mut *db).await?; + if last.as_ref().is_none_or(|l| l.install != stamp) { + if let Some(v) = host_refresh_next(last.as_ref(), stamp, "waiting", unix_now()) { + host_refresh_set(&mut *db, v).await?; + } + return Ok(true); + } + Ok(host_working(stamp, last.as_ref())) +} + +/// What GET /install/this-machine adds for a connected machine: `install`, +/// this Pyo's [`host_stamp`], and `refresh` when the host should run the +/// connect command now (`asked`: the `hostRefresh` its cluster's last +/// heartbeat left, for this Pyo's install or an earlier one). Nothing when +/// the host may not refresh its cluster (`may`, [`host_may_refresh`]): +/// install.sh then leaves the cluster's install alone after an update too. +fn host_answer(may: bool, stamp: &str, asked: Option<&str>) -> serde_json::Value { + let mut out = serde_json::json!({ "state": "connected" }); + if may { + out["install"] = serde_json::json!(stamp); + if asked == Some(stamp) { + out["refresh"] = serde_json::json!(true); + } + } + out +} + +/// A [`host_stamp`], as the host sends it back: a version and a hash. +fn stamp_like(s: &str) -> bool { + !s.is_empty() + && s.len() <= 100 + && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'+' | b'_')) +} + +#[derive(Deserialize)] +pub struct ThisMachineRefresh { + key: String, + #[serde(default)] + install: String, + #[serde(default)] + status: String, +} + +/// POST /install/this-machine/refresh (form: key, install, status): how +/// the host's refresh of the install `install` goes ("running", "done", +/// "failed" or "held"), from its timer, with the bootstrap key as for +/// [`this_machine`]. Only what the cluster's settings show follows from it. +pub async fn this_machine_refresh( + State(s): State, + axum::Form(f): axum::Form, +) -> ApiResult> { + bootstrap_key(&f.key)?; + if !stamp_like(&f.install) || !matches!(f.status.as_str(), "running" | "done" | "failed" | "held") { + return Err(ApiError::bad_request("Not a refresh's status.")); + } + let last = host_refresh_get(&s.db).await?; + if let Some(v) = host_refresh_next(last.as_ref(), &f.install, &f.status, unix_now()) { + host_refresh_set(&s.db, v).await?; + tracing::info!(install = %f.install, status = %f.status, "this machine: its refresh"); + } + Ok(crate::error::Json(serde_json::json!({}))) } /// The connect command again, run on the cluster's first server: it reads @@ -688,6 +1213,30 @@ mod tests { assert_eq!(install_state(&loose, "h1", None).0, "current"); } + /// A cluster whose install refused the client policies that remove + /// visitor headers says so, and what to run. + #[test] + fn an_install_that_keeps_visitor_headers_says_so() { + let mut s = scope("old", false); + assert_eq!(install_state(&s, "h1", None).0, "outdated"); + assert_eq!(outdated_message(&s), OUTDATED); + s.headers_kept = true; + assert_eq!(outdated_message(&s), HEADERS_KEPT); + assert!(HEADERS_KEPT.contains("Refresh this cluster")); + assert!(!HEADERS_KEPT.contains(';')); + // As the agent sends it, and as older agents (without it) do. + let sent: AgentScope = serde_json::from_value(serde_json::json!({ + "access": "limited", "admission": "enforced", "headersKept": true, + })) + .unwrap(); + assert!(sent.headers_kept); + let older: AgentScope = + serde_json::from_value(serde_json::json!({ "access": "limited", "admission": "enforced" })) + .unwrap(); + assert!(!older.headers_kept); + assert!(serde_json::to_value(&older).unwrap().get("headersKept").is_none()); + } + #[test] fn a_missing_admission_policy_waits_for_the_connect_command() { let missing = AgentScope { @@ -784,6 +1333,237 @@ mod tests { assert!(!agent_changed(Some("0.3.1"), "")); } + /// A release that changes the agent's roles (0.51.0's Cloudflare + /// Tunnel Services): the refresh fails on them, on any cluster. It + /// isn't sent again every half hour, the install stays outdated (never + /// "updating" in between) and the cluster's settings say what to run, + /// in Pyo's words. + #[test] + fn a_refresh_that_failed_on_the_roles_waits_for_the_connect_command() { + let s = scope("h0", true); + let on_roles = |age_secs: i64| LastRefresh { + message: "this agent's roles are older than Pyo's (Role pyo-agent differs); run the cluster's connect command to bring them up to date".into(), + ..last("failed", age_secs) + }; + for age in [5, 60, REFRESH_RETRY_SECS, 30 * REFRESH_RETRY_SECS] { + assert_eq!( + install_state(&s, "h1", Some(&on_roles(age))), + ("outdated", String::new(), false), + "{age}" + ); + } + // With no message of its own, the cluster's settings say Pyo's. + assert_eq!(outdated_message(&s), OUTDATED); + assert!(OUTDATED.contains("Refresh this cluster") && !OUTDATED.contains(';')); + // Another version of the agent runs: it gets one try. + let other = LastRefresh { + agent_changed: true, + ..on_roles(60) + }; + assert_eq!( + install_state(&s, "h1", Some(&other)), + ("updating", String::new(), true) + ); + // Any other failure is still tried again later. + assert!(roles_older(&on_roles(0).message)); + assert!(!roles_older("couldn't read its Role pyo-agent (timed out); run the cluster's connect command to bring them up to date")); + assert!(install_state(&s, "h1", Some(&last("failed", REFRESH_RETRY_SECS))).2); + // The install the connect command brings is current again. + assert_eq!(install_state(&scope("h1", true), "h1", Some(&on_roles(60))).0, "current"); + } + + fn partial(install: &str, self_update: bool, older: &[&str]) -> AgentScope { + AgentScope { + roles_older: older.iter().map(|s| s.to_string()).collect(), + ..scope(install, self_update) + } + } + + /// A refresh that brought all but some roles: its own state, with its + /// own message, and no refresh sent again whatever came before. + #[test] + fn an_install_current_except_its_roles_says_so_and_gets_no_refresh() { + let s = partial("h1", true, &["Role/pyo-gateway/pyo-agent"]); + for l in [ + None, + Some(last("done", 5)), + Some(last("done", 30 * REFRESH_RETRY_SECS)), + Some(last("failed", 30 * REFRESH_RETRY_SECS)), + Some(LastRefresh { agent_changed: true, ..last("failed", 5) }), + Some(LastRefresh { attempts: 9, ..last("sent", REFRESH_PATIENCE_MAX_SECS) }), + ] { + assert_eq!(install_state(&s, "h1", l.as_ref()), ("roles", ROLES.to_owned(), false), "{l:?}"); + } + assert!(ROLES.contains("Refresh this cluster") && !ROLES.contains(';') && !ROLES.contains(" - ")); + // The same without the self-update role, or read only. + assert_eq!(install_state(&partial("h1", false, &["x"]), "h1", None).0, "roles"); + // Pyo moves on: the install is older again, and refreshed as any. + assert_eq!(install_state(&s, "h2", None), ("updating", String::new(), true)); + assert_eq!(install_state(&partial("h1", false, &["x"]), "h2", None), ("outdated", String::new(), false)); + // The connect command brings the roles: current. + assert_eq!(install_state(&scope("h1", true), "h1", None).0, "current"); + // What its roles refuse reads as the connect command's to fix. + let forbidden = "services \"pyo-tunnel-origin\" is forbidden: User \"system:serviceaccount:pyo-system:pyo-agent\" cannot patch resource"; + assert_eq!(shown(Some(forbidden), "roles").as_deref(), Some(OUTDATED)); + assert_eq!(shown(Some("image not found"), "roles").as_deref(), Some("image not found")); + // The bundles go on when the roles left behind aren't theirs. + assert!(bundles_ready(None, None)); + assert!(bundles_ready(Some("current"), None)); + assert!(bundles_ready(Some("roles"), Some(true))); + assert!(!bundles_ready(Some("roles"), Some(false))); + assert!(!bundles_ready(Some("roles"), None)); + assert!(!bundles_ready(Some("outdated"), Some(true))); + assert!(!bundles_ready(Some("updating"), None)); + } + + /// The whole way from 0.5.5, as each heartbeat sees it. Nothing loops, + /// one command brings it home, and the release after needs none. + #[test] + fn from_0_5_5_one_command_then_none() { + let was = "this agent's roles are older than Pyo's (Role pyo-agent differs); run the cluster's connect command to bring them up to date"; + // Pyo is now 0.51.0 (install h1). 0.5.5's agent gets one refresh. + let old = scope("h0", true); + assert_eq!(install_state(&old, "h1", None), ("updating", String::new(), true)); + // It never writes roles: it fails, and isn't sent another. + let failed = LastRefresh { message: was.into(), ..last("failed", 5) }; + assert_eq!(install_state(&old, "h1", Some(&failed)), ("outdated", String::new(), false)); + // So the agent's image moves on (updates.rs waits only while "updating"). + // 0.51.0's agent runs: one more try. + let moved = LastRefresh { agent_changed: true, ..failed.clone() }; + assert_eq!(install_state(&old, "h1", Some(&moved)), ("updating", String::new(), true)); + // 0.5.5's self-update role may not write roles, so that refresh + // brings the policy and the pins and leaves the roles: said once, + // with nothing more sent, however long it stays so. + let left = partial("h1", true, &["Role/pyo-gateway/pyo-agent", "ClusterRole/pyo-agent-self-update"]); + for age in [5, REFRESH_PATIENCE_MAX_SECS, 30 * REFRESH_RETRY_SECS] { + assert_eq!(install_state(&left, "h1", Some(&last("done", age))), ("roles", ROLES.to_owned(), false)); + } + // Its bundles' roles are as they were, so the databases system goes on. + assert!(!pyo_proto::rbac::bundles_held_back(&left.roles_older)); + // The owner runs the connect command, once. + let home = scope("h1", true); + assert_eq!(install_state(&home, "h1", Some(&last("done", 600))).0, "current"); + // A later release (h2) with other rules in the same roles: one + // refresh, which the agent makes whole. No command. + assert_eq!(install_state(&home, "h2", None), ("updating", String::new(), true)); + assert_eq!(install_state(&scope("h2", true), "h2", Some(&last("done", 5))).0, "current"); + // On Pyo Cloud (no self-update role) every step is the command's: + // no refresh is ever sent, so no partial one either. + let cloud = scope("h0", false); + for l in [None, Some(last("done", 5)), Some(moved.clone())] { + assert_eq!(install_state(&cloud, "h1", l.as_ref()), ("outdated", String::new(), false)); + } + } + + /// Pyo's own server runs the connect command for its cluster when the + /// install waits for it, and nowhere else. + #[test] + fn only_pyo_s_own_cluster_is_refreshed_by_its_server() { + let s = scope("h0", true); + for state in ["outdated", "roles"] { + assert!(host_refreshes(true, true, &s, state), "{state}"); + // Another cluster, or Pyo Cloud (self-update off). + assert!(!host_refreshes(false, true, &s, state), "{state}"); + assert!(!host_refreshes(true, false, &s, state), "{state}"); + // Its owner took the self-update role away, or made it read only. + assert!(!host_refreshes(true, true, &scope("h0", false), state), "{state}"); + let mut read_only = scope("h0", true); + read_only.policy.read_only = true; + assert!(!host_refreshes(true, true, &read_only, state), "{state}"); + } + // Current, or the agent is still at its own refresh. + for state in ["current", "updating"] { + assert!(!host_refreshes(true, true, &s, state), "{state}"); + } + // A missing admission policy is the command's too. + let mut missing = scope("h0", true); + missing.admission = "missing".into(); + let (state, _, send) = install_state(&missing, "h1", None); + assert!(!send && host_refreshes(true, true, &missing, state)); + } + + fn said(install: &str, status: &str, age_secs: i64) -> HostRefresh { + HostRefresh { install: install.into(), status: status.into(), age_secs } + } + + /// The cluster says "updating" while its server is about to run the + /// command or runs it, and "Update needed" once that failed, was given + /// up, or never came. + #[test] + fn the_cluster_waits_for_its_server_then_asks_for_the_command() { + // Nothing said yet, or only of an earlier install: it will. + assert!(host_working("1-h1", None)); + assert!(host_working("1-h1", Some(&said("1-h0", "failed", 5)))); + assert!(host_working("1-h1", Some(&said("1-h0", "held", 99_999)))); + // Asked, running, done: for a while each. + assert!(host_working("1-h1", Some(&said("1-h1", "waiting", HOST_WAIT_SECS - 1)))); + assert!(!host_working("1-h1", Some(&said("1-h1", "waiting", HOST_WAIT_SECS)))); + assert!(host_working("1-h1", Some(&said("1-h1", "running", HOST_RUN_SECS - 1)))); + assert!(!host_working("1-h1", Some(&said("1-h1", "running", HOST_RUN_SECS)))); + assert!(host_working("1-h1", Some(&said("1-h1", "done", HOST_WAIT_SECS - 1)))); + assert!(!host_working("1-h1", Some(&said("1-h1", "done", HOST_WAIT_SECS)))); + // Failed, or not run again: the command's pointer at once. + for status in ["failed", "held", "something else"] { + assert!(!host_working("1-h1", Some(&said("1-h1", status, 0))), "{status}"); + } + } + + /// The host's word is kept with the time it was first said, so a + /// status repeated every minute doesn't start its wait again. + #[test] + fn the_host_s_word_keeps_its_first_time() { + let v = host_refresh_next(None, "1-h1", "waiting", 100).unwrap(); + assert_eq!(v, serde_json::json!({ "install": "1-h1", "status": "waiting", "at": 100 })); + let last = host_refresh_from(&v, 160).unwrap(); + assert_eq!(last, said("1-h1", "waiting", 60)); + assert_eq!(host_refresh_next(Some(&last), "1-h1", "waiting", 160), None); + // Another status, or another install: from now. + assert_eq!( + host_refresh_next(Some(&last), "1-h1", "running", 160).unwrap()["at"], + serde_json::json!(160) + ); + assert!(host_refresh_next(Some(&last), "1-h2", "waiting", 160).is_some()); + // A clock set back never makes it negative, and other shapes are none. + assert_eq!(host_refresh_from(&v, 40).unwrap().age_secs, 0); + assert_eq!(host_refresh_from(&serde_json::json!({ "install": "x" }), 0), None); + } + + /// What the host's timer reads: `refresh` only for this Pyo's install, + /// and nothing at all on an installation that doesn't self-update. + #[test] + fn the_host_is_told_to_refresh_only_this_pyo_s_install() { + use serde_json::json; + let stamp = host_stamp("abc123"); + assert_eq!(stamp, concat!(env!("CARGO_PKG_VERSION"), "-abc123")); + assert!(stamp_like(&stamp)); + assert_eq!( + host_answer(true, &stamp, Some(&stamp)), + json!({ "state": "connected", "install": stamp, "refresh": true }) + ); + // Current, or asked by the Pyo before this one. + for asked in [None, Some("0.0.1-abc123")] { + assert_eq!( + host_answer(true, &stamp, asked), + json!({ "state": "connected", "install": stamp }) + ); + } + // Pyo Cloud, or a cluster its owner keeps Pyo from changing: as before. + assert_eq!(host_answer(false, &stamp, Some(&stamp)), json!({ "state": "connected" })); + assert!(host_may_refresh(true, &scope("h0", true))); + assert!(!host_may_refresh(false, &scope("h0", true))); + assert!(!host_may_refresh(true, &scope("h0", false))); + // The host's script reads these as plain text. + let text = host_answer(true, &stamp, Some(&stamp)).to_string(); + assert!(text.contains(r#""state":"connected""#), "{text}"); + assert!(text.contains(r#""refresh":true"#), "{text}"); + assert!(text.contains(&format!(r#""install":"{stamp}""#)), "{text}"); + // And only a stamp comes back from it. + assert!(stamp_like("0.51.0-rc.1+b_2-0a1b")); + for bad in ["", "a b", "a\"b", "a/b", "$(x)", &"a".repeat(101)] { + assert!(!stamp_like(bad), "{bad}"); + } + } + #[test] fn unanswered_refreshes_are_sent_again_sooner_then_less_often() { assert_eq!(REFRESH_PATIENCE_SECS, 60); @@ -808,6 +1588,273 @@ mod tests { ); } + // ── The verifier ─────────────────────────────────────────────────── + + /// 2026-11-23T10:00:00Z. + const NOW: i64 = 1_795_428_000; + + fn verifier(checked: &str) -> pyo_proto::rbac::VerifierStatus { + pyo_proto::rbac::VerifierStatus { + version: "0.51.0".into(), + live: "0.51.0".into(), + checked: checked.into(), + error: String::new(), + hold: false, + host: "server-1".into(), + } + } + + /// A cluster without the self-update role whose verifier checked an + /// hour ago. + fn verified(install: &str) -> AgentScope { + AgentScope { + verifier: Some(verifier("2026-11-23T09:00:00Z")), + ..scope(install, false) + } + } + + #[test] + fn rfc_3339_times_are_read() { + assert_eq!(rfc3339_secs("1970-01-01T00:00:00Z"), Some(0)); + assert_eq!(rfc3339_secs("2026-11-23T10:00:00Z"), Some(NOW)); + assert_eq!(rfc3339_secs(" 2026-11-23T10:00:00.123456789Z "), Some(NOW)); + assert_eq!(rfc3339_secs("2026-11-23T17:00:00+07:00"), Some(NOW)); + assert_eq!(rfc3339_secs("2026-11-23T05:30:00-04:30"), Some(NOW)); + assert_eq!(rfc3339_secs("2026-11-23t10:00:00z"), Some(NOW)); + assert_eq!(rfc3339_secs("2024-02-29T00:00:00Z"), Some(1_709_164_800)); + assert_eq!(rfc3339_secs("2000-03-01T00:00:00Z"), Some(951_868_800)); + for bad in [ + "", + "yesterday", + "2026-11-23", + "2026-11-23T10:00:00", + "2026-11-23T10:00:00.Z", + "2026-13-01T00:00:00Z", + "2026-11-23T24:00:00Z", + "2026-11-23T10:00:00+0700", + "2026-11-23T10:00:00*07:00", + "+026-11-23T10:00:00Z", + "2026-11-23T10:00:00Zjunk", + "2026-11-23T10:00:00Z", + "1795428000", + ] { + assert_eq!(rfc3339_secs(bad), None, "{bad}"); + } + } + + /// A status older than 48 hours counts as no verifier, and so does one + /// whose time can't be read. A cluster with the self-update role is + /// kept current by its agent, so its status isn't shown either. + #[test] + fn a_verifier_that_last_checked_two_days_ago_counts_as_none() { + let at = |checked: &str| { + let mut s = verified("h"); + s.verifier = Some(verifier(checked)); + auto_update(&s, "current", NOW) + }; + assert!(at("2026-11-23T09:59:59Z").is_some()); + // Exactly 48 hours: still counts. A second more: gone. + assert!(at("2026-11-21T10:00:00Z").is_some()); + assert!(at("2026-11-21T09:59:59Z").is_none()); + assert!(at("2026-01-01T00:00:00Z").is_none()); + // The server's clock ahead of Pyo's: fine. + assert!(at("2026-11-23T10:05:00Z").is_some()); + for unread in ["", "soon", "2026-11-23"] { + assert!(at(unread).is_none(), "{unread}"); + } + assert_eq!(VERIFIER_STALE_SECS, 48 * 3600); + // No verifier at all. + assert_eq!(auto_update(&scope("h", false), "current", NOW), None); + // With the self-update role: the agent's job. + let mut own = verified("h"); + own.self_update = true; + assert_eq!(auto_update(&own, "current", NOW), None); + } + + /// What the cluster's settings say of automatic updates. 0.51.0's + /// verifier applies nothing to the cluster, so an outdated install is + /// told it still needs the command, never that it updates by itself. + #[test] + fn automatic_updates_are_shown_as_the_verifier_says() { + use serde_json::json; + // Set up, the install current. + assert_eq!( + auto_update(&verified("h"), "current", NOW), + Some(json!({ "state": "on", "version": "0.51.0", "message": "Automatic updates are set up on this cluster (version 0.51.0)." })) + ); + // Set up, the install outdated or short of roles: the command. + for waits in ["outdated", "roles"] { + assert_eq!( + auto_update(&verified("old"), waits, NOW), + Some(json!({ "state": "on", "version": "0.51.0", "message": "Automatic updates are set up on this cluster (version 0.51.0). This update still needs the command." })) + ); + } + // A version that isn't one isn't shown. + let mut odd = verified("h"); + odd.verifier.as_mut().unwrap().version = "9".into(); + assert_eq!( + auto_update(&odd, "current", NOW), + Some(json!({ "state": "on", "message": "Automatic updates are set up on this cluster." })) + ); + // On hold on the server. + let mut held = verified("h"); + held.verifier.as_mut().unwrap().hold = true; + assert_eq!( + auto_update(&held, "current", NOW), + Some(json!({ "state": "hold", "version": "0.51.0", "message": "Automatic updates are on hold. They were turned off on the server." })) + ); + // On hold in the policy, whatever the verifier noticed of it yet. + let mut policy = verified("h"); + policy.policy.updates_hold = true; + assert_eq!( + auto_update(&policy, "outdated", NOW), + Some(json!({ "state": "hold", "version": "0.51.0", "message": "Automatic updates are on hold. They were turned off in this cluster's policy." })) + ); + // The policy alone, without a verifier: nothing to show. + let mut alone = scope("h", false); + alone.policy.updates_hold = true; + assert_eq!(auto_update(&alone, "current", NOW), None); + // An error, in the verifier's words, with the command when the + // install waits for it. Hold comes first: a held verifier's last + // error isn't news. + let mut failed = verified("h"); + failed.verifier.as_mut().unwrap().error = "The release's signature couldn't be checked".into(); + assert_eq!( + auto_update(&failed, "current", NOW), + Some(json!({ "state": "error", "version": "0.51.0", "message": "Automatic updates reported a problem: The release's signature couldn't be checked." })) + ); + assert_eq!( + auto_update(&failed, "outdated", NOW).unwrap()["message"], + "Automatic updates reported a problem: The release's signature couldn't be checked. Run the command to update this cluster." + ); + failed.verifier.as_mut().unwrap().hold = true; + assert_eq!(auto_update(&failed, "current", NOW).unwrap()["state"], "hold"); + // Its words are shown as one plain line, cut short. + let mut noisy = verified("h"); + noisy.verifier.as_mut().unwrap().error = format!("GitHub didn't answer.\n\t\u{1b}[31m{}", "x".repeat(1000)); + let message = auto_update(&noisy, "current", NOW).unwrap()["message"].as_str().unwrap().to_owned(); + assert!(message.starts_with("Automatic updates reported a problem: GitHub didn't answer. [31mxxx"), "{message}"); + assert!(message.ends_with("x…") && message.chars().count() < 350, "{message}"); + assert!(!message.contains(char::is_control)); + // No copy with a semicolon or a dash between clauses. + for text in [AUTO_UPDATE_ON, AUTO_UPDATE_NEEDS_COMMAND, AUTO_UPDATE_HOLD_SERVER, AUTO_UPDATE_HOLD_POLICY, AUTO_UPDATE_PROBLEM, AUTO_UPDATE_FALLBACK] { + assert!(!text.contains(';') && !text.contains(" - ") && !text.contains('—'), "{text}"); + } + } + + /// The verifier's status comes through the agent, so a broken-into + /// agent can make it say anything. Whatever it says, nothing but + /// `autoUpdate` changes: not the install's state, not whether a + /// refresh is sent, not what waits for the connect command, not what + /// the host does, not the command shown. + #[test] + fn a_lying_verifier_status_only_changes_what_is_shown() { + use pyo_proto::rbac::VerifierStatus; + let lies = [ + None, + Some(verifier("2026-11-23T09:00:00Z")), + Some(VerifierStatus { version: "99.0.0".into(), live: "99.0.0".into(), ..verifier("2026-11-23T09:59:00Z") }), + Some(VerifierStatus { hold: true, ..verifier("2026-11-23T09:00:00Z") }), + Some(VerifierStatus { error: "all is lost".into(), ..verifier("2026-11-23T09:00:00Z") }), + Some(VerifierStatus { checked: "9999-12-31T23:59:59Z".into(), ..verifier("") }), + Some(VerifierStatus { checked: "never".into(), ..verifier("") }), + Some(VerifierStatus::default()), + ]; + let failed = LastRefresh { message: "nope".into(), ..last("failed", 10) }; + let bases = [ + scope("h", true), + scope("old", true), + scope("h", false), + scope("old", false), + partial("h", true, &["ClusterRole/pyo-agent-bundles"]), + partial("h", false, &["ClusterRole/pyo-agent-read"]), + AgentScope { admission: "missing".into(), ..scope("old", false) }, + AgentScope { headers_kept: true, ..scope("old", false) }, + ]; + for base in &bases { + for last in [None, Some(&failed)] { + let honest = install_state(base, "h", last); + let honest_shown = install_shown(base, honest.0, &honest.1, "cmd".into(), Some("stamp"), NOW); + assert!(honest_shown.get("autoUpdate").is_none()); + for (lie, hold) in lies.iter().flat_map(|l| [(l, false), (l, true)]) { + let mut lying = base.clone(); + lying.verifier = lie.clone(); + lying.policy.updates_hold = hold; + let what = format!("{base:?} {lie:?} hold={hold}"); + assert_eq!(install_state(&lying, "h", last), honest, "{what}"); + assert_eq!( + pyo_proto::rbac::install_current(&lying, "h"), + pyo_proto::rbac::install_current(base, "h"), + "{what}" + ); + for (same, own) in [(true, true), (true, false), (false, true)] { + assert_eq!( + host_refreshes(same, own, &lying, honest.0), + host_refreshes(same, own, base, honest.0), + "{what}" + ); + assert_eq!(host_may_refresh(own, &lying), host_may_refresh(own, base), "{what}"); + } + let mut shown = install_shown(&lying, honest.0, &honest.1, "cmd".into(), Some("stamp"), NOW); + if let Some(o) = shown.as_object_mut() { + o.remove("autoUpdate"); + } + assert_eq!(shown, honest_shown, "{what}"); + // What the gates read of it: the state and `bundles`. + assert_eq!( + bundles_ready(shown["state"].as_str(), shown["bundles"].as_bool()), + bundles_ready(honest_shown["state"].as_str(), honest_shown["bundles"].as_bool()), + "{what}" + ); + } + } + } + // An outdated install stays "Update needed", with its command and + // its message, beside a verifier that says all is well. + let outdated = verified("old"); + let (state, message, send) = install_state(&outdated, "h", None); + assert_eq!((state, send), ("outdated", false)); + let shown = install_shown(&outdated, state, &message, "cmd".into(), None, NOW); + assert_eq!(shown["state"], "outdated"); + assert_eq!(shown["command"], "cmd"); + assert_eq!(shown["message"], OUTDATED); + assert_eq!(shown["autoUpdate"]["state"], "on"); + } + + /// GET /install/version: the version and the install a cluster + /// without the self-update role gets, and nothing else, kept a minute. + #[tokio::test] + async fn the_version_route_names_this_pyo_and_its_install() { + let res = version().await.into_response(); + assert_eq!(res.status(), axum::http::StatusCode::OK); + assert_eq!(res.headers()[header::CACHE_CONTROL], "public, max-age=60"); + assert!(res.headers()[header::CONTENT_TYPE].to_str().unwrap().starts_with("application/json")); + let body = axum::body::to_bytes(res.into_body(), 4096).await.unwrap(); + let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!( + v, + serde_json::json!({ "version": env!("CARGO_PKG_VERSION"), "install": verifier_install() }) + ); + assert_eq!(v.as_object().unwrap().len(), 2); + // The install: without the self-update role, on a cluster that + // isn't Pyo's own, with this installation's images. + use pyo_proto::system::{db_images_from_env, geoip_image_from_env, waf_image_from_env}; + let new = |self_update| { + pyo_proto::rbac::InstallParts::new(false, self_update, &waf_image_from_env(), &geoip_image_from_env(), &db_images_from_env()).hash + }; + assert_eq!(verifier_install(), new(false)); + assert_ne!(verifier_install(), new(true)); + assert_eq!(verifier_install().len(), 16); + // What a Pyo without self-update hands its clusters. + if !self_update() { + assert_eq!(verifier_install(), parts(false).hash); + } + assert_eq!( + version_answer("0.51.0", "abc").to_string(), + r#"{"install":"abc","version":"0.51.0"}"# + ); + } + #[test] fn self_update_is_on_unless_turned_off() { assert!(self_update_from(None)); @@ -874,6 +1921,36 @@ mod tests { assert!(!a.contains(&sha256_hex("abc")), "not the lookup hash"); } + /// A server short of disk neither evicts the agent nor keeps a new one + /// from starting, so it goes on reporting and cleaning up there. + #[test] + fn the_agent_stays_on_a_server_short_of_disk() { + let pod = render("https://pyo.example.com", "img@sha256:00", "abc") + .split("\n---") + .filter_map(|d| serde_norway::from_str::(d).ok()) + .find(|d| d["kind"] == "Deployment" && d["metadata"]["name"] == "pyo-agent") + .expect("the agent's Deployment")["spec"]["template"]["spec"] + .clone(); + assert_eq!(pod["priorityClassName"], "system-cluster-critical"); + // Exactly what a refresh brings, and the admission policy allows. + assert_eq!(pod["priorityClassName"], pyo_proto::rbac::AGENT_PRIORITY); + assert_eq!(pod["tolerations"], pyo_proto::rbac::agent_tolerations()); + let tolerated: Vec<&str> = pod["tolerations"] + .as_array() + .unwrap() + .iter() + .filter(|t| t["operator"] == "Exists" && t["effect"] == "NoSchedule") + .filter_map(|t| t["key"].as_str()) + .collect(); + for taint in [ + "node.kubernetes.io/disk-pressure", + "node.kubernetes.io/memory-pressure", + "nvidia.com/gpu", + ] { + assert!(tolerated.contains(&taint), "{taint}: {tolerated:?}"); + } + } + #[test] fn the_manifest_is_stamped_with_its_install() { let yaml = render("https://pyo.example.com", "img@sha256:00", "abc"); @@ -916,7 +1993,8 @@ pub struct ThisMachineQuery { /// install.sh, and their timer until it's done). `key` is the installation's /// bootstrap key (`PYO_BOOTSTRAP_KEY`, a Secret only the host reads). The /// cluster goes to the first team; before anyone has signed up there's none -/// yet, so the host asks again later. Answers `{"state": "connected"}`, +/// yet, so the host asks again later. Answers `{"state": "connected"}` +/// (with `install` and `refresh`, see [`host_answer`]), /// `{"state": "waiting"}` (no team yet) or `{"state": "connect", "command"}`. /// /// Until its agent reports in, every ask gets the same command, whichever @@ -931,7 +2009,20 @@ pub async fn this_machine( use serde_json::json; let key = bootstrap_key(&q.key)?; Ok(crate::error::Json(match hand_over(&s.db, &key).await? { - Handover::Connected => json!({ "state": "connected" }), + Handover::Connected => { + // What its cluster's last heartbeat asked of the host, and + // what its agent may do there. + let own: Option<(Option, Option)> = sqlx::query_as( + "SELECT capabilities->'agentInstall'->>'hostRefresh', capabilities->'agentScope' FROM pyo.clusters WHERE same_cluster LIMIT 1", + ) + .fetch_optional(&s.db) + .await?; + let (asked, scope) = own.unwrap_or_default(); + let may = scope + .and_then(|v| serde_json::from_value::(v).ok()) + .is_some_and(|scope| host_may_refresh(self_update(), &scope)); + host_answer(may, &host_stamp(&parts(true).hash), asked.as_deref()) + } Handover::Waiting => json!({ "state": "waiting" }), Handover::Connect { cluster_id, token } => { // The same command "Add cluster › This machine" gives. @@ -1023,7 +2114,8 @@ pub async fn reset_login( ))); } }; - // Made on the server: it also turns two-factor off (recovery.rs). + // Made on the server: it also turns two-factor off, and for an admin + // where admins may sign in from (recovery.rs). let token = crate::recovery::new_host_link(&mut conn, &id).await?; tracing::info!(user = %id, "sign-in link made on the host"); Ok(crate::error::Json(serde_json::json!({ diff --git a/crates/pyo-api/src/join.rs b/crates/pyo-api/src/join.rs index 7de781b0..f004c2f8 100644 --- a/crates/pyo-api/src/join.rs +++ b/crates/pyo-api/src/join.rs @@ -18,9 +18,44 @@ pub const SANDBOX_SCRIPT: &str = include_str!("../../../deploy/sandbox.sh"); /// `/v//`, only as its signed release.json lists them. pub const PUBLISHED_SCRIPTS_URL: &str = "https://pyo.dev"; -/// This release's scripts on pyo.dev: `https://pyo.dev/v/`. +/// Each release's assets on GitHub, its install scripts among them: +/// `/v/connect.sh`. pyo.dev doesn't serve a release +/// candidate's scripts, so a candidate's commands fetch them here. +pub const RELEASES_URL: &str = "https://github.com/upsetdev/pyo/releases/download"; + +/// This release's published scripts: `https://pyo.dev/v/`, or +/// for a release candidate its GitHub release. pub fn published_scripts_url() -> String { - format!("{PUBLISHED_SCRIPTS_URL}/v/{}", env!("CARGO_PKG_VERSION")) + published_scripts_url_for(env!("CARGO_PKG_VERSION")) +} + +/// A release's published scripts ([`published_scripts_url`]). +fn published_scripts_url_for(version: &str) -> String { + if is_release_candidate(version) { + format!("{RELEASES_URL}/v{version}") + } else { + format!("{PUBLISHED_SCRIPTS_URL}/v/{version}") + } +} + +/// A release candidate's version: `X.Y.Z-rc.N`. +pub const fn is_release_candidate(version: &str) -> bool { + let b = version.as_bytes(); + let mut i = 0; + while i < b.len() && b[i] != b'-' { + i += 1; + } + if b.len() < i + 5 || b[i + 1] != b'r' || b[i + 2] != b'c' || b[i + 3] != b'.' { + return false; + } + i += 4; + while i < b.len() { + if !b[i].is_ascii_digit() { + return false; + } + i += 1; + } + true } /// Where the commands for other machines fetch their scripts from, first @@ -31,8 +66,8 @@ pub fn published_scripts_url() -> String { /// which it has to reach anyway; /// 3. Pyo on the tailnet ([`crate::web::tailnet_api_url`]), then its HTTPS /// dashboard; -/// 4. pyo.dev ([`published_scripts_url`]), when Pyo is only on its own -/// machine or in its cluster. +/// 4. this release's published scripts ([`published_scripts_url`]), when +/// Pyo is only on its own machine or in its cluster. /// /// Only for machines already on the tailnet, or told Pyo's public URL. A /// command with a Tailscale key uses [`scripts_url_before_tailnet`]. @@ -70,7 +105,7 @@ fn pick_scripts_url(configured: Option<&str>, pyo: &[Option<&str>]) -> String { /// its public IP: that address may not be reachable from outside (a server /// behind NAT, like Starlink's). So: /// 1. `PYO_SCRIPTS_URL`, when set; -/// 2. else this release's scripts on pyo.dev ([`published_scripts_url`]), +/// 2. else this release's published scripts ([`published_scripts_url`]), /// and join.sh's `--k3s` keeps the server on the cluster's k3s. /// /// A dev build's version may not be a published release, so pyo.dev has no @@ -300,15 +335,19 @@ pub fn tailnet_only_command(base: &str, key: &str) -> String { } /// A script's arguments for where it's fetched from (`base`). A Pyo's own -/// scripts and pyo.dev's `/v//` are this release's. From anywhere -/// else (a mirror) they get `--version`: a release's join.sh and connect.sh -/// then run that release's script from pyo.dev when they're another's. +/// scripts and the published ones ([`published_scripts_url`]) are this +/// release's. From anywhere else (a mirror) they get `--version`: a +/// release's join.sh and connect.sh then run that release's published +/// script when they're another's. pub fn pinned( base: &str, mut args: Vec<(&'static str, Option)>, ) -> Vec<(&'static str, Option)> { let base = base.trim_end_matches('/'); - if !base.ends_with("/install") && !base.starts_with(&format!("{PUBLISHED_SCRIPTS_URL}/v/")) { + if !base.ends_with("/install") + && !base.starts_with(&format!("{PUBLISHED_SCRIPTS_URL}/v/")) + && base != published_scripts_url() + { args.push(("--version", Some(env!("CARGO_PKG_VERSION").to_owned()))); } args @@ -324,6 +363,60 @@ pub fn local_api_url() -> String { .unwrap_or_else(|| "http://127.0.0.1:8000".into()) } +/// connect.sh's flag that sets up the verifier on the cluster's first +/// server (`pyo-verify`, on a timer there): it keeps the cluster on what +/// this Pyo's signed release defines. +pub const AUTO_UPDATE: &str = "--auto-update"; +/// connect.sh's flag that leaves the verifier out, and removes one that's +/// there. +pub const NO_AUTO_UPDATE: &str = "--no-auto-update"; + +/// Which of the two a connect or refresh command carries: none on a Pyo +/// whose agents refresh their install themselves (`self_update`, +/// install.rs), where there's no verifier. On one that hands out no +/// self-update role (Pyo Cloud), [`AUTO_UPDATE`] unless the team unticked +/// it (`keep` off), then [`NO_AUTO_UPDATE`]. +/// +/// Pyo always renders the ticked one. The choice is never kept: the +/// dashboard's checkbox swaps the flag in the command it shows, so what +/// decides is the command the customer runs as root, never Pyo. +pub fn auto_update_flag(self_update: bool, keep: bool) -> Option<&'static str> { + match (self_update, keep) { + (true, _) => None, + (false, true) => Some(AUTO_UPDATE), + (false, false) => Some(NO_AUTO_UPDATE), + } +} + +/// connect.sh's flag for Pyo's public address, where a server gets its +/// install files (the agent's manifest, the gateway's CRDs) and its +/// verifier looks for releases. connect.sh keeps it for later runs. +pub const INSTALL_URL: &str = "--install-url"; + +/// What [`INSTALL_URL`] names on a Pyo whose agents reach it at another +/// address (`PYO_AGENT_ENDPOINT`, [`crate::agent_tls::endpoint`]): Pyo +/// Cloud's agent address takes only the agents' own requests, never +/// `/install/`. Pyo's public API address (`PYO_PUBLIC_API_URL`), else its +/// dashboard's. None on any other Pyo, where the agent's address serves +/// both (a refresh reads it from the agent's Secret). +pub fn install_url() -> Option { + let endpoint = crate::agent_tls::endpoint()?; + pick_install_url( + &endpoint, + std::env::var("PYO_PUBLIC_API_URL").ok().as_deref(), + crate::web::public_url().as_deref(), + ) +} + +fn pick_install_url(endpoint: &str, configured: Option<&str>, dashboard: Option<&str>) -> Option { + let url = [configured, dashboard] + .into_iter() + .flatten() + .map(|u| u.trim().trim_end_matches('/')) + .find(|u| !u.is_empty())?; + (url != endpoint.trim_end_matches('/') && outside(url) && secure_transport(url)).then(|| url.to_owned()) +} + /// The command that makes a machine a new cluster connected to Pyo. /// `registry`: Pyo's registry door on the tailnet and the cluster's pull /// token there. @@ -334,12 +427,38 @@ pub fn connect_command( tailscale_key: Option<&str>, registry: Option<(&str, &str)>, ) -> String { + connect_command_with( + base, + api, + token, + tailscale_key, + registry, + auto_update_flag(crate::install::self_update(), true), + // Not "This machine"'s, from Pyo on it. + install_url().is_some() && outside(api), + ) +} + +/// [`connect_command`] with this [`auto_update_flag`]. With `install`, +/// also [`INSTALL_URL`]: `api`, the public address it connects at, so +/// connect.sh keeps it for refreshes run without it. +fn connect_command_with( + base: &str, + api: &str, + token: &str, + tailscale_key: Option<&str>, + registry: Option<(&str, &str)>, + auto_update: Option<&'static str>, + install: bool, +) -> String { + let mut args = connect_args(api, token, tailscale_key, registry); + if install { + args.push((INSTALL_URL, Some(api.to_owned()))); + } + args.extend(auto_update.map(|flag| (flag, None))); format!( "curl -fsSL {base}/connect.sh | bash -s -- {}", - quoted(&pinned( - base, - connect_args(api, token, tailscale_key, registry) - )) + quoted(&pinned(base, args)) ) } @@ -368,9 +487,24 @@ pub fn connect_args( /// The command that brings a connected cluster's agent install up to date /// with Pyo's: connect.sh run on the cluster's first server, which reads -/// Pyo's address and the token from the agent already there. +/// Pyo's address and the token from the agent already there. Where the +/// agent's address isn't for installs, with [`INSTALL_URL`]. pub fn refresh_command(base: &str) -> String { - match quoted(&pinned(base, Vec::new())) { + refresh_command_with( + base, + auto_update_flag(crate::install::self_update(), true), + install_url().as_deref(), + ) +} + +/// [`refresh_command`] with this [`auto_update_flag`] and [`install_url`]. +fn refresh_command_with(base: &str, auto_update: Option<&'static str>, install: Option<&str>) -> String { + let mut args: Vec<(&'static str, Option)> = install + .map(|u| (INSTALL_URL, Some(u.to_owned()))) + .into_iter() + .collect(); + args.extend(auto_update.map(|flag| (flag, None))); + match quoted(&pinned(base, args)) { a if a.is_empty() => format!("curl -fsSL {base}/connect.sh | bash"), a => format!("curl -fsSL {base}/connect.sh | bash -s -- {a}"), } @@ -453,8 +587,16 @@ mod tests { } } - /// This release's scripts on pyo.dev. - const V: &str = concat!("https://pyo.dev/v/", env!("CARGO_PKG_VERSION")); + /// This release's published scripts: on pyo.dev, or a release + /// candidate's on GitHub. + const V: &str = if is_release_candidate(env!("CARGO_PKG_VERSION")) { + concat!( + "https://github.com/upsetdev/pyo/releases/download/v", + env!("CARGO_PKG_VERSION") + ) + } else { + concat!("https://pyo.dev/v/", env!("CARGO_PKG_VERSION")) + }; /// From a mirror, a release's scripts run this release's. const PIN: &str = concat!(" --version '", env!("CARGO_PKG_VERSION"), "'"); @@ -600,8 +742,13 @@ mod tests { "{mem}: {text}" ); } - // Memory it can't read: no drop-in (the one before is removed). - assert_eq!(config("nothing\n"), None); + // Memory it can't read: no reservations, the disk settings still. + let text = config("nothing\n").expect("a drop-in"); + assert!(!text.contains("reserved="), "{text}"); + assert!( + text.contains("\nkubelet-arg+:\n - \"eviction-hard="), + "{text}" + ); // The unit runs it at every start, at the path small_machine writes. let block = script_block("small-machine", CONNECT_SCRIPT); assert!( @@ -613,6 +760,78 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// The same drop-in: kubelet frees disk space only under 5% free (unused + /// images well before), and the server stops counting as short of disk + /// once 1 GiB more is free, not k3s's 10% more. Whatever the memory. + #[test] + fn kubelet_frees_disk_space_late_and_lets_go_soon() { + let helper = CONNECT_SCRIPT + .split("<<'MEMORY'\n") + .nth(1) + .and_then(|r| r.split("\nMEMORY\n").next()) + .expect("connect.sh has the memory helper"); + let dir = std::env::temp_dir().join(format!("pyo-disk-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let want = " - \"eviction-hard=imagefs.available<5%,nodefs.available<5%\"\n\ + \x20 - \"eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi\"\n\ + \x20 - \"image-gc-high-threshold=85\"\n\ + \x20 - \"image-gc-low-threshold=75\"\n"; + for meminfo in [ + "MemTotal: 983040 kB\n", + "MemTotal: 33554432 kB\n", + "nothing\n", + ] { + let info = dir.join("meminfo"); + std::fs::write(&info, meminfo).unwrap(); + let out = dir.join("50-pyo-memory.yaml"); + let status = std::process::Command::new("sh") + .args(["-c", helper, "pyo-memory.sh", "k3s-config"]) + .arg(&out) + .env("PYO_MEMINFO", &info) + .status() + .unwrap(); + assert!(status.success()); + let text = std::fs::read_to_string(&out).unwrap(); + assert!(text.ends_with(want), "{meminfo}: {text}"); + // One list, which k3s adds to its own arguments. + assert_eq!(text.matches("kubelet-arg").count(), 1, "{text}"); + } + let _ = std::fs::remove_dir_all(&dir); + // Image cleanup starts and ends before eviction does (95% used). + let pct = |key: &str| -> u32 { + want.split(&format!("{key}=")) + .nth(1) + .and_then(|r| r.split('"').next()) + .unwrap() + .parse() + .unwrap() + }; + assert!(pct("image-gc-low-threshold") < pct("image-gc-high-threshold")); + assert!(pct("image-gc-high-threshold") < 95); + } + + /// A server set up before the disk settings gets them, and k3s restarts + /// once for them, when its script runs again. + #[test] + fn existing_k3s_restarts_once_for_the_disk_settings() { + let dir = std::env::temp_dir().join(format!("pyo-disk-refresh-{}", std::process::id())); + let block = sandboxed_small_machine(&dir); + let d = dir.display(); + let (code, out, err) = bash(&format!( + "set -euo pipefail\nsystemctl() {{ [ \"$1\" != restart ] || echo RESTART; }}\n{block}\n\ + export PYO_MEMINFO={d}/meminfo; echo 'MemTotal: 16777216 kB' > $PYO_MEMINFO\n\ + mkdir -p {d}/config.yaml.d\n\ + printf '%s\\n' '# Managed by Pyo: what kubelet sets aside.' 'kubelet-arg+:' ' - \"kube-reserved=memory=768Mi\"' ' - \"system-reserved=memory=256Mi\"' > {d}/config.yaml.d/50-pyo-memory.yaml\n\ + : > {d}/run/pyo-k3s.env\n\ + k3s_memory_refresh\nk3s_memory_refresh" + )); + assert_eq!(code, 0, "{err}"); + assert_eq!(out.matches("RESTART").count(), 1, "{out}"); + let text = std::fs::read_to_string(dir.join("config.yaml.d/50-pyo-memory.yaml")).unwrap(); + assert!(text.contains("eviction-minimum-reclaim="), "{text}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// The scripts that install k3s, Tailscale and NVIDIA's toolkit share /// their installer code (`# >>> pyo:` … `# <<< pyo:`), and /// those that carry k3s's pin carry deploy/k3s.env's. @@ -810,6 +1029,53 @@ mod tests { } } + /// pyo.dev serves a release's scripts, but not a release candidate's: + /// a candidate's commands fetch them from its GitHub release, which + /// has them as assets (release.yml). + #[test] + fn a_release_candidates_scripts_come_from_its_github_release() { + assert_eq!( + published_scripts_url_for("0.51.0"), + "https://pyo.dev/v/0.51.0" + ); + assert_eq!( + published_scripts_url_for("0.51.0-rc.1"), + "https://github.com/upsetdev/pyo/releases/download/v0.51.0-rc.1" + ); + for v in ["0.51.0-rc.1", "0.51.0-rc.12", "1.0.0-rc.0"] { + assert!(is_release_candidate(v), "{v}"); + } + for v in [ + "0.51.0", + "", + "0.51.0-rc", + "0.51.0-rc.", + "0.51.0-rc.1x", + "0.51.0-beta.1", + "0.51.0-", + ] { + assert!(!is_release_candidate(v), "{v}"); + } + // This release's own published scripts need no --version, wherever + // they are. + let args = || vec![("--auto-update", None)]; + assert_eq!(pinned(&published_scripts_url(), args()), args()); + assert_eq!( + pinned(&format!("{}/", published_scripts_url()), args()), + args() + ); + assert_eq!( + refresh_command_with(&published_scripts_url(), None, None), + format!("curl -fsSL {}/connect.sh | bash", published_scripts_url()) + ); + // Another candidate's assets are a mirror's: pinned to this release. + let other = "https://github.com/upsetdev/pyo/releases/download/v0.0.1-rc.1"; + assert_eq!( + refresh_command_with(other, None, None), + format!("curl -fsSL {other}/connect.sh | bash -s --{PIN}") + ); + } + #[test] fn builds_command() { assert_eq!(published_scripts_url(), V); @@ -1004,6 +1270,131 @@ mod tests { } } + /// The verifier's flag: on a Pyo that hands out no self-update role + /// (Pyo Cloud) the commands carry `--auto-update`, or + /// `--no-auto-update` when the team unticked it. On any other, neither. + #[test] + fn commands_carry_the_auto_update_flag_only_without_self_update() { + assert_eq!(auto_update_flag(true, true), None); + assert_eq!(auto_update_flag(true, false), None); + assert_eq!(auto_update_flag(false, true), Some("--auto-update")); + assert_eq!(auto_update_flag(false, false), Some("--no-auto-update")); + let connect = |flag| { + connect_command_with( + "https://cloud.example/install", + "https://cloud.example", + "abc", + None, + None, + flag, + false, + ) + }; + let plain = "curl -fsSL https://cloud.example/install/connect.sh | bash -s -- --api 'https://cloud.example' --token 'abc'"; + // Self-hosted, with self-update: as before. + assert_eq!(connect(auto_update_flag(true, true)), plain); + assert_eq!(connect(auto_update_flag(true, false)), plain); + // Hosted: ticked, then unticked. + assert_eq!(connect(auto_update_flag(false, true)), format!("{plain} --auto-update")); + assert_eq!(connect(auto_update_flag(false, false)), format!("{plain} --no-auto-update")); + let refresh = |base, flag| refresh_command_with(base, flag, None); + let own = "https://cloud.example/install"; + assert_eq!( + refresh(own, auto_update_flag(true, true)), + "curl -fsSL https://cloud.example/install/connect.sh | bash" + ); + assert_eq!( + refresh(own, auto_update_flag(false, true)), + "curl -fsSL https://cloud.example/install/connect.sh | bash -s -- --auto-update" + ); + assert_eq!( + refresh(own, auto_update_flag(false, false)), + "curl -fsSL https://cloud.example/install/connect.sh | bash -s -- --no-auto-update" + ); + // Before a mirror's --version, as the other flags. + assert_eq!( + refresh("https://mirror.example.com", auto_update_flag(false, true)), + format!("curl -fsSL https://mirror.example.com/connect.sh | bash -s -- --auto-update{PIN}") + ); + // What Pyo hands out follows this installation, always ticked. + let handed = auto_update_flag(crate::install::self_update(), true); + assert_eq!(refresh_command(own), refresh(own, handed)); + assert_eq!( + connect_command(own, "https://cloud.example", "abc", None, None), + connect(handed) + ); + assert_eq!(handed.is_some(), !crate::install::self_update()); + // The servers Pyo makes at a cloud provider take connect.sh's + // arguments as they are: no verifier is set up without the + // customer's own command. + assert!( + !connect_args("https://cloud.example", "abc", None, None) + .iter() + .any(|(flag, _)| flag.contains("auto-update")) + ); + } + + /// A Pyo whose agents reach it at an address only they may use (Pyo + /// Cloud's agent address) names its public one for installs: the + /// refresh, which otherwise takes the agent's, and the connect, whose + /// --api it is, so the server keeps it. Any other Pyo: as before. + #[test] + fn hosted_commands_name_the_install_address() { + let agent = "https://agent.cloud.example"; + let public = Some("https://cloud.example"); + // Pyo Cloud: PYO_PUBLIC_API_URL, else the dashboard's address. + assert_eq!( + pick_install_url(agent, Some(" https://cloud.example/ "), Some("https://pyo.tail1.ts.net")).as_deref(), + public + ); + assert_eq!(pick_install_url(agent, None, public).as_deref(), public); + assert_eq!(pick_install_url(agent, Some(""), public).as_deref(), public); + // The same address for both, none, or one another machine can't + // use: nothing to name. + assert_eq!(pick_install_url(agent, Some("https://agent.cloud.example/"), None), None); + assert_eq!(pick_install_url(agent, None, None), None); + assert_eq!(pick_install_url(agent, Some("http://127.0.0.1:8000"), None), None); + assert_eq!(pick_install_url(agent, Some("http://pyo.example.com"), None), None); + // Agents with tokens (self-hosted): the address in their Secret serves both. + assert_eq!(crate::agent_tls::endpoint(), None); + assert_eq!(install_url(), None); + + let base = "https://cloud.example/install"; + assert_eq!( + refresh_command_with(base, Some(AUTO_UPDATE), public), + "curl -fsSL https://cloud.example/install/connect.sh | bash -s -- --install-url 'https://cloud.example' --auto-update" + ); + assert_eq!( + refresh_command_with(base, Some(NO_AUTO_UPDATE), public), + "curl -fsSL https://cloud.example/install/connect.sh | bash -s -- --install-url 'https://cloud.example' --no-auto-update" + ); + // Before a mirror's --version. + assert_eq!( + refresh_command_with("https://mirror.example.com", Some(AUTO_UPDATE), public), + format!("curl -fsSL https://mirror.example.com/connect.sh | bash -s -- --install-url 'https://cloud.example' --auto-update{PIN}") + ); + assert_eq!( + connect_command_with(base, "https://cloud.example", "abc", None, None, Some(AUTO_UPDATE), true), + "curl -fsSL https://cloud.example/install/connect.sh | bash -s -- --api 'https://cloud.example' --token 'abc' --install-url 'https://cloud.example' --auto-update" + ); + + // Self-hosted: the commands as before, with no install address. + let own = "https://pyo.example/install"; + assert_eq!(refresh_command(own), "curl -fsSL https://pyo.example/install/connect.sh | bash"); + assert_eq!( + connect_command(own, "https://pyo.example", "abc", None, None), + "curl -fsSL https://pyo.example/install/connect.sh | bash -s -- --api 'https://pyo.example' --token 'abc'" + ); + // "This machine": from Pyo on it. + assert_eq!( + connect_command(&local_scripts_url(), &local_api_url(), "abc", None, None), + "curl -fsSL http://127.0.0.1:8000/install/connect.sh | bash -s -- --api 'http://127.0.0.1:8000' --token 'abc'" + ); + // The dashboard swaps --auto-update (AgentInstall.tsx): the install + // address never looks like it. + assert!(!INSTALL_URL.contains("auto-update")); + } + #[test] fn commands_with_a_tailscale_key_fetch_their_script_off_the_tailnet() { let base = pick_scripts_url_before_tailnet(None); @@ -1288,7 +1679,7 @@ SS='LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pi // Nothing at all. assert_eq!(web_ports(""), "free"); // The manifest is asked for with it, and ufw left alone. - assert!(CONNECT_SCRIPT.contains(r#""$API/install/agent.yaml?token=$TOKEN$WEB_QUERY""#)); + assert!(CONNECT_SCRIPT.contains(r#""$INSTALL_URL/install/agent.yaml?token=$TOKEN$WEB_QUERY""#)); assert!(CONNECT_SCRIPT.contains("WEB_QUERY=\"&webPorts=busy\"")); } @@ -1701,4 +2092,1235 @@ if apply_agent; then echo "ok after $applies"; else echo "failed after $applies" assert_eq!(out.trim(), want.to_string(), "{mem}"); } } + + /// A script install.sh's host_units writes to /usr/local/lib/pyo. + fn host_script(name: &str) -> String { + let install = include_str!("../../../deploy/install.sh"); + let head = format!("tee /usr/local/lib/pyo/{name} >/dev/null <<'SH'\n"); + let start = install + .find(&head) + .unwrap_or_else(|| panic!("host_units writes no {name}")) + + head.len(); + let end = install[start..].find("\nSH\n").unwrap(); + install[start..start + end + 1].to_owned() + } + + /// Pyo's own server as connect-this-machine.sh sees it: its files in a + /// directory of the test's, Pyo's answers and connect.sh stubbed. + struct OwnServer { + dir: std::path::PathBuf, + } + + impl OwnServer { + fn new(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("pyo-own-server-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("bootstrap-key"), "k3y\n").unwrap(); + Self { dir } + } + + /// One run in `mode` ("auto", "refresh" or none) with Pyo + /// answering `answer` and connect.sh ending with `rc`: its exit + /// code and output. + fn run(&self, mode: &str, answer: &str, rc: i32) -> (i32, String) { + let d = self.dir.display().to_string(); + let script = host_script("connect-this-machine.sh") + .replace("/etc/pyo/", &format!("{d}/")) + .replace("/run/pyo-connect.lock", &format!("{d}/lock")); + assert!(!script.contains("/etc/pyo") && !script.contains("/run/"), "{script}"); + let (code, out, err) = bash(&format!( + r#"T='{d}' +ANSWER='{answer}' +curl() {{ + local a + case "$*" in + *"http://127.0.0.1:8000/install/this-machine?key=k3y") printf '%s' "$ANSWER" ;; + *"http://127.0.0.1:8000/install/this-machine/refresh"*) + for a in "$@"; do case "$a" in install=* | status=*) printf '%s ' "${{a#*=}}" >> "$T/told" ;; esac; done + echo >> "$T/told" ;; + *"http://127.0.0.1:8000/install/connect.sh") echo "echo connect.sh ran; echo x >> '$T/ran'; exit {rc}" ;; + *) echo "unexpected: curl $*" >&2; return 9 ;; + esac +}} +k3s() {{ [ ! -e "$T/no-policy" ]; }} +systemctl() {{ echo "$*" >> "$T/systemctl"; }} +flock() {{ echo "$*" >> "$T/flock"; }} +set -- {mode} +{script}"# + )); + assert_eq!(err, "", "{out}"); + (code, out) + } + + fn read(&self, file: &str) -> String { + std::fs::read_to_string(self.dir.join(file)).unwrap_or_default() + } + + /// How often connect.sh ran. + fn ran(&self) -> usize { + self.read("ran").lines().count() + } + + /// What the host told Pyo, one "install status" per line. + fn told(&self) -> Vec { + self.read("told").lines().map(|l| l.trim().to_owned()).collect() + } + + /// Makes `file` look written `minutes` ago. + fn age(&self, file: &str, minutes: u32) { + let ok = std::process::Command::new("touch") + .args(["-d", &format!("{minutes} minutes ago")]) + .arg(self.dir.join(file)) + .status() + .unwrap(); + assert!(ok.success()); + } + } + + impl Drop for OwnServer { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } + } + + const ASKED: &str = r#"{"install":"0.51.0-abc","refresh":true,"state":"connected"}"#; + const CURRENT: &str = r#"{"install":"0.51.0-abc","state":"connected"}"#; + + /// The timer's run every minute: nothing while Pyo doesn't ask, then + /// connect.sh once for the install, however long Pyo goes on asking. + #[test] + fn pyo_s_own_server_refreshes_once_when_pyo_asks() { + let s = OwnServer::new("once"); + for answer in [CURRENT, r#"{"state":"connected"}"#, r#"{"state":"waiting"}"#, ""] { + assert_eq!(s.run("auto", answer, 0), (0, String::new()), "{answer}"); + } + // Nor does it connect the machine: the connect timer does that. + let connect = r#"{"command":"echo connecting","state":"connect"}"#; + assert_eq!(s.run("auto", connect, 0), (0, String::new())); + assert_eq!((s.ran(), s.told().len()), (0, 0)); + + let (code, out) = s.run("auto", ASKED, 0); + assert_eq!(code, 0); + assert_eq!( + out, + "Refreshing this server for Pyo 0.51.0.\nconnect.sh ran\nThis server is up to date.\n" + ); + assert_eq!(s.ran(), 1); + assert_eq!(s.told(), ["0.51.0-abc running", "0.51.0-abc done"]); + assert_eq!(s.read("refresh-tried"), "0.51.0-abc\n"); + assert!(!s.dir.join("refresh-failed").exists()); + // It never waits for the lock, and never stops the connect timer. + assert_eq!(s.read("flock").lines().last(), Some("-n 9")); + assert_eq!(s.read("systemctl"), ""); + + // Pyo still asks (the agent hasn't said it's current, or it never + // will): not again, a day later either. + for _ in 0..5 { + assert_eq!(s.run("auto", ASKED, 0), (0, String::new())); + } + s.age("refresh-tried", 3 * 24 * 60); + assert_eq!(s.run("auto", ASKED, 0), (0, String::new())); + assert_eq!(s.ran(), 1); + assert_eq!(s.told().last().unwrap(), "0.51.0-abc done"); + + // Another release: once for it. And not again for the one before, + // should two Pyos answer in turn while one replaces the other. + let next = ASKED.replace("0.51.0-abc", "0.52.0-def"); + assert_eq!(s.run("auto", &next, 0).0, 0); + assert_eq!(s.ran(), 2); + for answer in [ASKED, next.as_str(), ASKED] { + assert_eq!(s.run("auto", answer, 0), (0, String::new())); + } + assert_eq!(s.ran(), 2); + assert_eq!(s.read("refresh-tried"), "0.51.0-abc\n0.52.0-def\n"); + } + + /// A refresh that failed comes again after an hour, not every minute, + /// at most 4 times a day, and at once for another Pyo version. + #[test] + fn a_failed_refresh_of_pyo_s_own_server_is_tried_again_hourly() { + let s = OwnServer::new("failed"); + let (code, out) = s.run("auto", ASKED, 1); + // The timer's unit doesn't fail with it. + assert_eq!(code, 0); + assert!( + out.ends_with("Couldn't refresh this server. Pyo tries again in an hour.\n"), + "{out}" + ); + assert_eq!(s.read("refresh-failed"), "0.51.0-abc\n"); + assert_eq!(s.told(), ["0.51.0-abc running", "0.51.0-abc failed"]); + // The next minutes: nothing but its word to Pyo. + for _ in 0..3 { + assert_eq!(s.run("auto", ASKED, 1), (0, String::new())); + } + s.age("refresh-failed", 59); + assert_eq!(s.run("auto", ASKED, 1), (0, String::new())); + assert_eq!(s.ran(), 1); + assert_eq!(s.told().last().unwrap(), "0.51.0-abc failed"); + // An hour later: again, and again failed. + s.age("refresh-failed", 61); + assert_eq!(s.run("auto", ASKED, 1).0, 0); + assert_eq!(s.ran(), 2); + // Four in a day, then no more however old the failure. + for _ in 0..4 { + s.age("refresh-failed", 61); + s.run("auto", ASKED, 1); + } + assert_eq!(s.ran(), 4); + assert_eq!(s.read("refresh-runs").lines().count(), 4); + assert_eq!(s.told().last().unwrap(), "0.51.0-abc held"); + // Another Pyo version would run at once, but for the day's four. + let next = ASKED.replace("0.51.0-abc", "0.51.1-abc"); + assert_eq!(s.run("auto", &next, 0), (0, String::new())); + assert_eq!(s.told().last().unwrap(), "0.51.1-abc held"); + // A day on (the runs are older): the new version at once, and a + // success clears the failure. + std::fs::write(s.dir.join("refresh-runs"), "1000\n1001\n1002\n1003\n").unwrap(); + let (code, out) = s.run("auto", &next, 0); + assert_eq!(code, 0); + assert!(out.ends_with("This server is up to date.\n"), "{out}"); + assert_eq!(s.ran(), 5); + assert!(!s.dir.join("refresh-failed").exists()); + assert_eq!(s.read("refresh-runs").lines().count(), 1); + // The one that failed, an hour on: once more, and it's done. + let two = OwnServer::new("failed-then-done"); + two.run("auto", ASKED, 1); + two.age("refresh-failed", 61); + two.run("auto", ASKED, 0); + assert_eq!((two.ran(), two.dir.join("refresh-failed").exists()), (2, false)); + assert_eq!(two.run("auto", ASKED, 0), (0, String::new())); + assert_eq!(two.ran(), 2); + } + + /// install.sh after an update: the refresh now, whether or not Pyo + /// asks yet, and the timer doesn't run it again for that install. + #[test] + fn the_installer_s_refresh_counts_for_the_timer() { + let s = OwnServer::new("installer"); + let (code, out) = s.run("refresh", CURRENT, 0); + assert_eq!(code, 0); + assert!(out.starts_with("Refreshing this server for Pyo 0.51.0.\n"), "{out}"); + assert_eq!(s.ran(), 1); + // It waits for the lock, and leaves the day's automatic runs alone. + assert_eq!(s.read("flock").lines().last(), Some("9")); + assert_eq!(s.read("refresh-runs"), ""); + assert_eq!(s.run("auto", ASKED, 0), (0, String::new())); + assert_eq!(s.ran(), 1); + // One that fails says so to install.sh, and the timer takes over + // an hour later. + let f = OwnServer::new("installer-failed"); + assert_eq!(f.run("refresh", ASKED, 1).0, 1); + assert_eq!(f.run("auto", ASKED, 0), (0, String::new())); + f.age("refresh-failed", 61); + f.run("auto", ASKED, 0); + assert_eq!(f.ran(), 2); + // A Pyo that doesn't keep its servers current (no install in its + // answer): as before, connect.sh only for a missing policy. + let c = OwnServer::new("installer-cloud"); + assert_eq!(c.run("refresh", r#"{"state":"connected"}"#, 0), (0, String::new())); + assert_eq!(c.run("", r#"{"state":"connected"}"#, 0), (0, String::new())); + assert_eq!(c.ran(), 0); + assert!(c.read("systemctl").contains("disable --now pyo-connect.timer")); + } + + /// Only a stamp is taken from Pyo's answer, and only with a quoted + /// "refresh":true. + #[test] + fn the_host_reads_only_a_stamp_from_pyo_s_answer() { + let s = OwnServer::new("stamp"); + for answer in [ + r#"{"install":"","refresh":true,"state":"connected"}"#, + r#"{"install":"a b; touch x","refresh":true,"state":"connected"}"#, + r#"{"install":"$(touch x)","refresh":true,"state":"connected"}"#, + r#"{"install":"0.51.0-abc","refresh":false,"state":"connected"}"#, + ] { + assert_eq!(s.run("auto", answer, 0), (0, String::new()), "{answer}"); + } + assert_eq!(s.ran(), 0); + } + + /// The tailnet timer's script (every minute, for good) brings this + /// Pyo's host scripts first, then asks for the refresh with them. + #[test] + fn the_minute_timer_updates_its_scripts_then_refreshes() { + let s = host_script("tailnet-this-machine.sh"); + let units = s.find("exec bash -c \"$units\"").unwrap(); + let auto = s.find("\nexec /usr/local/lib/pyo/connect-this-machine.sh auto\n").unwrap(); + assert!(units < auto); + assert!(s.ends_with("connect-this-machine.sh auto\n")); + // install.sh refreshes after an update, and connects a new install. + let install = include_str!("../../../deploy/install.sh"); + assert!(install.contains("quietly \"Refreshing this server…\" /usr/local/lib/pyo/connect-this-machine.sh refresh ||")); + assert!(install.contains("quietly \"Connecting this machine to Pyo…\" /usr/local/lib/pyo/connect-this-machine.sh ||")); + // What they say is plain. + for script in [host_script("connect-this-machine.sh"), s] { + for line in script.lines().filter(|l| l.trim_start().starts_with("echo \"")) { + assert!(!line.contains(';') && !line.contains(" - "), "{line}"); + } + } + } + + /// connect.sh's connect_lock with flock stubbed, as root unless `setup` + /// says otherwise: the flock calls it made, then whether it has the lock. + fn connect_lock(setup: &str) -> String { + let dir = std::env::temp_dir().join(format!( + "pyo-connect-lock-{}-{}", + std::process::id(), + setup.len() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let d = dir.display().to_string(); + let block = script_block("connect-lock", CONNECT_SCRIPT) + .replace("/run/pyo-connect.lock", &format!("{d}/lock")); + let (code, out, err) = bash(&format!( + r#"set -euo pipefail +T='{d}' +id() {{ echo "${{ID:-0}}"; }} +flock() {{ echo "flock $*"; [ "$*" != "-n 9" ] || [ -z "${{BUSY:-}}" ]; }} +{setup} +{block} +connect_lock +if connect_lock_held; then echo has-lock; else echo no-lock; fi +"# + )); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + out.trim().replace('\n', ", ") + } + + /// connect.sh takes one lock on every server, which the verifier's runs + /// and Pyo's own timers and installer take too, and doesn't wait for + /// itself under them. + #[test] + fn connect_takes_turns_with_other_pyo_setups_on_a_server() { + assert_eq!(connect_lock(""), "flock -n 9, has-lock"); + // Something else runs (the verifier, Pyo's timer): it waits, and + // says so. + assert_eq!( + connect_lock("BUSY=1"), + "flock -n 9, Waiting for another Pyo setup on this server to finish., flock 9, has-lock" + ); + // Run by Pyo's timer or installer, which hold it: theirs. + assert_eq!(connect_lock("exec 9>\"$T/lock\""), "has-lock"); + // Not root (--uninstall with KUBECONFIG): /run isn't its to write. + assert_eq!(connect_lock("ID=1000"), "no-lock"); + // Before --tailnet-only's exit and after --uninstall's. + let at = CONNECT_SCRIPT.find("\n[ -n \"$TAILNET_ONLY\" ] || connect_lock\n").unwrap(); + assert!(CONNECT_SCRIPT.find("\n uninstall\n exit 0\n").unwrap() < at); + assert!(at < CONNECT_SCRIPT.find("\nnvidia_gpu\n").unwrap()); + } + + /// The lines release-manifest.ts writes the verifier's release and + /// SHA-256 on, in the connect.sh a release publishes. + const VERIFY_PINS: [(&str, &str); 3] = [ + ("release", "PYO_VERIFY_RELEASE"), + ("x86_64", "PYO_VERIFY_SHA256_X86_64"), + ("aarch64", "PYO_VERIFY_SHA256_AARCH64"), + ]; + + fn verify_pin_line(name: &str, var: &str, value: &str) -> String { + format!("\n{var}=\"{value}\" # pyo:verify-pin {name}\n") + } + + /// `script` as a release publishes it: `pins` are the release, then the + /// x86_64 and aarch64 verifiers' SHA-256. + fn stamp_verifier(script: &str, pins: [&str; 3]) -> String { + let mut s = script.to_owned(); + for ((name, var), value) in VERIFY_PINS.iter().zip(pins) { + let empty = verify_pin_line(name, var, ""); + assert_eq!(s.matches(&empty).count(), 1, "{name}"); + s = s.replace(&empty, &verify_pin_line(name, var, value)); + } + s + } + + /// Pyo's own connect.sh has the pin lines empty, and the release's + /// script fills in exactly those. + #[test] + fn the_release_pins_its_verifier_in_connect_sh() { + let manifest = include_str!("../../../scripts/release-manifest.ts"); + for (name, var) in VERIFY_PINS { + assert_eq!(CONNECT_SCRIPT.matches(&verify_pin_line(name, var, "")).count(), 1, "{name}"); + assert_eq!(CONNECT_SCRIPT.matches(&format!("# pyo:verify-pin {name}\n")).count(), 1); + assert!(manifest.contains(&format!("[\"{name}\", \"{var}\"")), "{name}"); + } + assert!(manifest.contains("`\\n${variable}=\"${value}\" # pyo:verify-pin ${name}\\n`")); + // Only connect.sh is given them. + for other in [SCRIPT, SANDBOX_SCRIPT, include_str!("../../../deploy/install.sh")] { + assert!(!other.contains("pyo:verify-pin")); + } + // What the verifier's own release names: the same files, from the + // same place. + assert!(CONNECT_SCRIPT.contains( + "\nPYO_VERIFY_RELEASES=https://github.com/upsetdev/pyo/releases/download\n" + )); + assert!(CONNECT_SCRIPT.contains("\"$PYO_VERIFY_RELEASES/v$PYO_VERIFY_RELEASE/pyo-verify-linux-$arch\"")); + } + + /// connect.sh's options, read by its own loop: AUTO_UPDATE, or the + /// error. + fn auto_update_arg(args: &str) -> String { + let block = script_block("connect-args", CONNECT_SCRIPT); + let (code, out, err) = bash(&format!( + "set -euo pipefail\nset -- {args}\n{block}\necho \"[$AUTO_UPDATE] $API $TOKEN [$UNINSTALL]\"\n" + )); + if code == 0 { out.trim().to_owned() } else { format!("{code} {}", err.trim()) } + } + + #[test] + fn connect_reads_the_auto_update_flags() { + // As Pyo's commands give them: last, or before a mirror's --version. + assert_eq!(auto_update_arg("--auto-update"), "[on] []"); + assert_eq!(auto_update_arg("--no-auto-update"), "[off] []"); + assert_eq!(auto_update_arg("--api 'https://pyo.example/' --token 'ab12' --auto-update"), "[on] https://pyo.example ab12 []"); + assert_eq!( + auto_update_arg("--api 'https://pyo.example' --token 'ab12' --local-registry --no-auto-update --version '0.51.0'"), + "[off] https://pyo.example ab12 []" + ); + assert_eq!(auto_update_arg("--auto-update --version '0.51.0'"), "[on] []"); + // Neither: nothing chosen in this run. + assert_eq!(auto_update_arg(""), "[] []"); + assert_eq!(auto_update_arg("--api 'https://pyo.example' --token 'ab12'"), "[] https://pyo.example ab12 []"); + // Both: the last one. + assert_eq!(auto_update_arg("--auto-update --no-auto-update"), "[off] []"); + assert_eq!(auto_update_arg("--no-auto-update --auto-update"), "[on] []"); + assert_eq!(auto_update_arg("--uninstall --yes"), "[] [1]"); + assert_eq!(auto_update_arg("--auto-updates"), "2 Unknown option: --auto-updates"); + assert_eq!(auto_update_arg("--auto-update=off"), "2 Unknown option: --auto-update=off"); + } + + /// A server for connect.sh's auto-update steps: its files under a + /// directory, a release on "GitHub" with a stand-in verifier, and curl, + /// systemctl, uname and id answered here. flock and sha256sum are real. + struct VerifyHost { + dir: std::path::PathBuf, + } + + /// The x86_64 verifier's sum when a test wants one that matches nothing. + const OTHER_SUM: &str = "00000000000000000000000000000000000000000000000000000000000000ff"; + + impl VerifyHost { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("pyo-verify-host-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for sub in ["bin", "etc/pyo", "units", "release", "lib"] { + std::fs::create_dir_all(dir.join(sub)).unwrap(); + } + VerifyHost { dir } + } + + fn d(&self) -> String { + self.dir.display().to_string() + } + + /// A stand-in verifier that says it is `version`. It writes what it + /// is asked to `log`, and says so when it was started with the + /// lock's file. + fn verifier(&self, version: &str) -> String { + format!( + r#"#!/usr/bin/env bash +T='{d}' +[ ! -e "/proc/$$/fd/9" ] || echo "$1 was started with file 9" >>"$T/log" +case "$1" in + version) echo '{version}' ;; + install) + echo "{version} $*" >>"$T/log" + [ ! -e "$T/install-fails" ] || exit 1 + [ "$0" -ef "$T/bin/pyo-verify" ] || cp "$0" "$T/bin/pyo-verify" + ;; + uninstall) + echo "{version} uninstall" >>"$T/log" + rm -f "$T/bin/pyo-verify" + ;; + run) + exec 8>"$T/lock" + if flock -n 8; then echo "run: took the lock"; else echo "run: skipped"; fi >>"$T/log" + ;; +esac +"#, + d = self.d() + ) + } + + /// Puts `version`'s verifier in the release, as `file`. Its SHA-256. + fn release(&self, file: &str, version: &str) -> String { + use sha2::{Digest, Sha256}; + let text = self.verifier(version); + std::fs::write(self.dir.join("release").join(file), &text).unwrap(); + hex::encode(Sha256::digest(text.as_bytes())) + } + + /// The verifier this server already has. + fn installed(&self, version: &str) { + use std::os::unix::fs::PermissionsExt; + let path = self.dir.join("bin/pyo-verify"); + std::fs::write(&path, self.verifier(version)).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + + fn has(&self, file: &str) -> bool { + self.dir.join(file).exists() + } + + fn read(&self, file: &str) -> String { + std::fs::read_to_string(self.dir.join(file)).unwrap_or_default() + } + + /// What curl, systemctl and the verifier were asked, a line each. + fn log(&self) -> Vec { + let log = self.read("log").replace(&self.d(), ""); + let _ = std::fs::remove_file(self.dir.join("log")); + log.lines().map(str::to_owned).collect() + } + + /// The blocks as connect.sh has them, with `pins` written as a + /// release does (None: Pyo's own copy), then `steps`. + fn bash(&self, pins: Option<[&str; 3]>, steps: &str) -> (i32, String, String) { + let d = self.d(); + let script = match pins { + Some(p) => stamp_verifier(CONNECT_SCRIPT, p), + None => CONNECT_SCRIPT.to_owned(), + }; + let progress = script_block("progress", &script); + let lock = script_block("connect-lock", &script).replace("/run/pyo-connect.lock", &format!("{d}/lock")); + let block = script_block("auto-update", &script) + .replace("/etc/pyo/auto-update", &format!("{d}/etc/pyo/auto-update")) + .replace("/usr/local/bin/pyo-verify", &format!("{d}/bin/pyo-verify")) + .replace("/etc/systemd/system", &format!("{d}/units")) + .replace("/usr/local/lib/pyo/connect-this-machine.sh", &format!("{d}/lib/connect-this-machine.sh")); + let install = script_block("install-url", &script) + .replace("/etc/pyo/install-url", &format!("{d}/etc/pyo/install-url")); + bash(&format!( + r#"set -euo pipefail +T='{d}' +AUTO_UPDATE="" +id() {{ echo 0; }} +uname() {{ echo "${{ARCH:-x86_64}}"; }} +sleep() {{ :; }} +systemctl() {{ echo "systemctl $*" >>"$T/log"; }} +curl() {{ + local out="" url="" + while [ $# -gt 0 ]; do + case "$1" in -o) out=$2; shift 2 ;; --proto | --max-time | --max-filesize) shift 2 ;; -*) shift ;; *) url=$1; shift ;; esac + done + echo "curl $url" >>"$T/log" + [ -f "$T/release/${{url##*/}}" ] || return 22 + cp "$T/release/${{url##*/}}" "$out" +}} +{progress} +{lock} +{block} +{install} +{steps} +"# + )) + } + + /// A connect run with `flag` ("on", "off" or none), as connect.sh + /// orders the steps: what it printed, which has to end in + /// "connected". + fn connect(&self, pins: Option<[&str; 3]>, flag: &str) -> String { + let (code, out, err) = self.bash( + pins, + &format!( + r#"AUTO_UPDATE={flag} +{CONNECT_STEPS} +echo connected"# + ), + ); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + let out = out.trim_end(); + assert!(out.ends_with("connected"), "{out}"); + out.trim_end_matches("connected").trim_end().replace('\n', " | ") + } + } + + impl Drop for VerifyHost { + fn drop(&mut self) { + if !std::thread::panicking() { + let _ = std::fs::remove_dir_all(&self.dir); + } + } + } + + /// connect.sh's own lines for the lock and automatic updates, in the + /// order it runs them, for Pyo at https://pyo.example. + const CONNECT_STEPS: &str = r#"connect_lock +auto_update_choice +[ "$AUTO_UPDATE" != off ] || auto_update_off +[ "$AUTO_UPDATE" != on ] || auto_update_on https://pyo.example"#; + + /// CONNECT_STEPS are connect.sh's: the lock first, the choice once + /// --tailnet-only has left, the verifier once the agent runs. + #[test] + fn connect_sets_up_automatic_updates_after_the_agent() { + let at = |text: &str| CONNECT_SCRIPT.find(text).unwrap_or_else(|| panic!("no {text:?}")); + let lock = at("\n[ -n \"$TAILNET_ONLY\" ] || connect_lock\n"); + let choice = at("\nauto_update_choice\n[ \"$AUTO_UPDATE\" != off ] || auto_update_off\n"); + let agent = at("k3s kubectl -n pyo-system rollout status deployment/pyo-agent"); + let on = at("\n[ \"$AUTO_UPDATE\" != on ] || auto_update_on \"$INSTALL_URL\"\n"); + let done = at("\nok_line \"Connected "); + assert!(lock < choice && choice < agent && agent < on && on < done); + assert!(at(" echo \"$(hostname) is on your tailnet.\"\n") < choice); + for line in CONNECT_STEPS.lines() { + let line = line.replace("https://pyo.example", "\"$INSTALL_URL\"").replace("connect_lock", "[ -n \"$TAILNET_ONLY\" ] || connect_lock"); + assert_eq!(CONNECT_SCRIPT.matches(&format!("\n{line}\n")).count(), 1, "{line}"); + } + // Nothing about it shows sudo or a command to type. + let block = script_block("auto-update", CONNECT_SCRIPT); + let said: Vec<&str> = block + .lines() + .filter(|l| !l.starts_with('#') && l.to_lowercase().contains("automatic updates")) + .collect(); + assert_eq!(said.len(), 9, "{said:?}"); + for line in said { + assert!(!line.contains("sudo") && !line.contains(';') && !line.contains(" - "), "{line}"); + } + } + + const SET_UP: &str = "→ Setting up automatic updates… | ✓ Set up automatic updates"; + + #[test] + fn a_released_connect_installs_its_pinned_verifier() { + let h = VerifyHost::new("installs"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let pins = Some(["0.51.0", sum.as_str(), OTHER_SUM]); + assert_eq!(h.connect(pins, "on"), SET_UP); + assert_eq!( + h.log(), + [ + "curl https://github.com/upsetdev/pyo/releases/download/v0.51.0/pyo-verify-linux-x86_64", + "0.51.0 install --url https://pyo.example", + ] + ); + assert_eq!(h.read("bin/pyo-verify"), h.verifier("0.51.0")); + assert_eq!(h.read("etc/pyo/auto-update"), "on\n"); + // Nothing of the download stays. + assert!(!h.has("bin/.pyo-verify.new")); + // A release candidate's verifier takes release candidates. + let h = VerifyHost::new("installs-rc"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0-rc.1"); + assert_eq!(h.connect(Some(["0.51.0-rc.1", sum.as_str(), OTHER_SUM]), "on"), SET_UP); + assert_eq!( + h.log(), + [ + "curl https://github.com/upsetdev/pyo/releases/download/v0.51.0-rc.1/pyo-verify-linux-x86_64", + "0.51.0-rc.1 install --url https://pyo.example --channel rc", + ] + ); + } + + #[test] + fn connect_remembers_the_auto_update_choice() { + let h = VerifyHost::new("remembers"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let pins = Some(["0.51.0", sum.as_str(), OTHER_SUM]); + // Never asked for: nothing, and nothing kept. + assert_eq!(h.connect(pins, ""), ""); + assert!(h.log().is_empty()); + assert!(!h.has("etc/pyo/auto-update") && !h.has("bin/pyo-verify")); + // On, then the refresh command without arguments: still on. The + // verifier it has is this release's, so nothing is downloaded. + assert_eq!(h.connect(pins, "on"), SET_UP); + h.log(); + assert_eq!(h.connect(pins, ""), SET_UP); + assert_eq!(h.log(), ["0.51.0 install --url https://pyo.example"]); + // Off, and it stays off without arguments. + assert_eq!(h.connect(pins, "off"), "✓ Turned off automatic updates"); + assert_eq!(h.log(), ["0.51.0 uninstall"]); + assert_eq!(h.read("etc/pyo/auto-update"), "off\n"); + assert_eq!(h.connect(pins, ""), ""); + assert!(h.log().is_empty()); + assert!(!h.has("bin/pyo-verify")); + // And on again. + assert_eq!(h.connect(pins, "on"), SET_UP); + assert_eq!(h.read("etc/pyo/auto-update"), "on\n"); + // A file that says neither is no choice. + std::fs::write(h.dir.join("etc/pyo/auto-update"), "maybe\n").unwrap(); + h.installed("0.51.0"); + h.log(); + assert_eq!(h.connect(pins, ""), ""); + assert!(h.log().is_empty()); + } + + #[test] + fn connect_takes_the_verifier_for_the_server_s_processor() { + for (machine, file, arm) in [ + ("x86_64", "pyo-verify-linux-x86_64", false), + ("amd64", "pyo-verify-linux-x86_64", false), + ("aarch64", "pyo-verify-linux-aarch64", true), + ("arm64", "pyo-verify-linux-aarch64", true), + ] { + let h = VerifyHost::new(&format!("arch-{machine}")); + let sum = h.release(file, "0.51.0"); + // The other processor's sum matches nothing here. + let pins = if arm { ["0.51.0", OTHER_SUM, sum.as_str()] } else { ["0.51.0", sum.as_str(), OTHER_SUM] }; + let (code, out, err) = h.bash(Some(pins), &format!("ARCH={machine} AUTO_UPDATE=on\n{CONNECT_STEPS}\n")); + assert_eq!((code, err.as_str()), (0, ""), "{machine}: {out}"); + assert!(out.ends_with("✓ Set up automatic updates\n"), "{machine}: {out}"); + assert_eq!( + h.log(), + [ + format!("curl https://github.com/upsetdev/pyo/releases/download/v0.51.0/{file}"), + "0.51.0 install --url https://pyo.example".to_owned(), + ], + "{machine}" + ); + } + // A processor the release has no verifier for. + let h = VerifyHost::new("arch-other"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let (code, out, _) = h.bash(Some(["0.51.0", sum.as_str(), OTHER_SUM]), &format!("ARCH=riscv64 AUTO_UPDATE=on\n{CONNECT_STEPS}\necho connected")); + assert_eq!(code, 0); + assert_eq!(out, "● Automatic updates aren't available here. They stay off on this server.\nconnected\n"); + assert!(h.log().is_empty()); + } + + /// Pyo's own copy of connect.sh (a dev build, a self-hosted Pyo) has no + /// pins: the flag installs nothing, and the connect goes on. + #[test] + fn a_connect_script_without_pins_installs_no_verifier() { + const NEEDS: &str = "● Automatic updates aren't available here. They stay off on this server."; + let h = VerifyHost::new("unpinned"); + h.release("pyo-verify-linux-x86_64", "0.51.0"); + assert_eq!(h.connect(None, "on"), NEEDS); + assert!(h.log().is_empty(), "nothing is downloaded"); + assert!(!h.has("bin/pyo-verify")); + // Half a pin is none: a release without a sum, a sum that isn't one, + // a release that isn't one. + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + for pins in [ + ["0.51.0", "", ""], + ["", sum.as_str(), sum.as_str()], + ["0.51.0", "abc", "abc"], + ["0.51", sum.as_str(), sum.as_str()], + ["latest", sum.as_str(), sum.as_str()], + ["0.51.0/../x", sum.as_str(), sum.as_str()], + ] { + assert_eq!(h.connect(Some(pins), "on"), NEEDS, "{pins:?}"); + assert!(h.log().is_empty(), "{pins:?}"); + } + // Off works without pins, and a verifier a release set up stays + // as it is, quietly. + h.installed("0.51.0"); + assert_eq!(h.connect(None, "on"), ""); + assert!(h.log().is_empty()); + assert_eq!(h.connect(None, "off"), "✓ Turned off automatic updates"); + // The server Pyo itself runs on never gets one, whatever the flag, + // and remembers none. + let h = VerifyHost::new("own-server"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + std::fs::write(h.dir.join("lib/connect-this-machine.sh"), "").unwrap(); + for flag in ["on", "off", ""] { + assert_eq!(h.connect(Some(["0.51.0", sum.as_str(), OTHER_SUM]), flag), "", "{flag}"); + } + assert!(h.log().is_empty()); + assert!(!h.has("etc/pyo/auto-update") && !h.has("bin/pyo-verify")); + } + + #[test] + fn a_verifier_that_fails_its_checksum_is_not_installed() { + let h = VerifyHost::new("mismatch"); + h.release("pyo-verify-linux-x86_64", "0.51.0"); + // What the release pinned is another file. + assert_eq!( + h.connect(Some(["0.51.0", OTHER_SUM, OTHER_SUM]), "on"), + "→ Setting up automatic updates… | ● Automatic updates aren't set up. The download didn't match its checksum." + ); + // Downloaded once, never run, nothing left. + assert_eq!(h.log(), ["curl https://github.com/upsetdev/pyo/releases/download/v0.51.0/pyo-verify-linux-x86_64"]); + assert!(!h.has("bin/pyo-verify") && !h.has("bin/.pyo-verify.new")); + // The choice stays: the next run tries again. + assert_eq!(h.read("etc/pyo/auto-update"), "on\n"); + } + + #[test] + fn a_failed_verifier_download_or_setup_does_not_stop_the_connect() { + // The release has no such file (or GitHub doesn't answer). + let h = VerifyHost::new("download"); + assert_eq!( + h.connect(Some(["0.51.0", OTHER_SUM, OTHER_SUM]), "on"), + "→ Setting up automatic updates… | ● Automatic updates aren't set up. The download failed." + ); + assert_eq!(h.log().len(), 3, "three tries"); + assert!(!h.has("bin/pyo-verify") && !h.has("bin/.pyo-verify.new")); + // The verifier's own install fails. + let h = VerifyHost::new("install-fails"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + std::fs::write(h.dir.join("install-fails"), "").unwrap(); + assert_eq!( + h.connect(Some(["0.51.0", sum.as_str(), OTHER_SUM]), "on"), + "→ Setting up automatic updates… | ● Automatic updates couldn't be set up on this server." + ); + assert!(!h.has("bin/pyo-verify") && !h.has("bin/.pyo-verify.new")); + // Without the lock (no flock here), nothing is set up: the + // verifier's install counts on connect.sh holding it. + let h = VerifyHost::new("no-lock"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let (code, out, err) = h.bash( + Some(["0.51.0", sum.as_str(), OTHER_SUM]), + "AUTO_UPDATE=on\nauto_update_choice\nauto_update_on https://pyo.example\necho connected", + ); + assert_eq!((code, err.as_str()), (0, "")); + assert_eq!(out, "● Automatic updates couldn't be set up on this server.\nconnected\n"); + assert!(h.log().is_empty()); + } + + #[test] + fn no_auto_update_removes_the_verifier() { + let h = VerifyHost::new("off"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let pins = Some(["0.51.0", sum.as_str(), OTHER_SUM]); + // None here: nothing to say. + assert_eq!(h.connect(pins, "off"), ""); + assert!(h.log().is_empty()); + assert_eq!(h.read("etc/pyo/auto-update"), "off\n"); + h.installed("0.50.0"); + assert_eq!(h.connect(pins, "off"), "✓ Turned off automatic updates"); + assert_eq!(h.log(), ["0.50.0 uninstall"]); + assert!(!h.has("bin/pyo-verify")); + // A verifier that doesn't run here: its timer and files go anyway. + for file in ["bin/pyo-verify", "bin/pyo-verify.previous", "units/pyo-verify.timer", "units/pyo-verify.service"] { + std::fs::write(h.dir.join(file), "not a program").unwrap(); + } + assert_eq!(h.connect(pins, "off"), "✓ Turned off automatic updates"); + assert_eq!(h.log(), ["systemctl disable --now pyo-verify.timer", "systemctl daemon-reload"]); + for file in ["bin/pyo-verify", "bin/pyo-verify.previous", "units/pyo-verify.timer", "units/pyo-verify.service"] { + assert!(!h.has(file), "{file}"); + } + } + + #[test] + fn connect_never_moves_the_verifier_backwards() { + let h = VerifyHost::new("backwards"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let pins = Some(["0.51.0", sum.as_str(), OTHER_SUM]); + // The verifier moved on to a later release: kept, and set up again. + for later in ["0.51.1", "0.52.0", "1.0.0", "0.52.0-rc.1"] { + h.installed(later); + assert_eq!(h.connect(pins, "on"), SET_UP, "{later}"); + assert_eq!(h.log(), [format!("{later} install --url https://pyo.example")]); + assert_eq!(h.read("bin/pyo-verify"), h.verifier(later)); + } + // An earlier one, a release candidate of this release, or one that + // doesn't say: replaced by this release's. + for earlier in ["0.50.9", "0.5.5", "0.51.0-rc.9", "", "dev"] { + h.installed(earlier); + assert_eq!(h.connect(pins, "on"), SET_UP, "{earlier}"); + assert_eq!(h.log().last().unwrap(), "0.51.0 install --url https://pyo.example", "{earlier}"); + assert_eq!(h.read("bin/pyo-verify"), h.verifier("0.51.0")); + } + let (code, out, err) = h.bash( + None, + r#"for pair in "0.51.0 0.52.0" "0.51.9 0.52.0" "0.9.0 0.10.0" "0.51.0-rc.1 0.51.0" "0.51.0-rc.2 0.51.0-rc.10" "0.50.9 0.51.0-rc.1"; do + set -- $pair + verify_older "$1" "$2" || echo "$1 isn't older than $2" + ! verify_older "$2" "$1" || echo "$2 is older than $1" + ! verify_older "$1" "$1" || echo "$1 is older than itself" +done +! verify_older 0.51.0 "" && ! verify_older "" 0.51.0 && ! verify_older 0.51.0 v0.52.0 && ! verify_older 0.51.0 0.52 || echo "not versions" +"#, + ); + assert_eq!((code, out.as_str(), err.as_str()), (0, "", "")); + } + + /// With the real flock: a verifier run skips while connect.sh has the + /// lock, connect.sh waits for a run that has it, the verifier connect.sh + /// starts never gets the lock's file, and the lock goes with the script. + #[test] + fn connect_and_the_verifier_never_overlap_or_wait_for_each_other() { + if bash("command -v flock").0 != 0 { + return; + } + let h = VerifyHost::new("turns"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let pins = Some(["0.51.0", sum.as_str(), OTHER_SUM]); + // The timer fires in the middle of a connect: that run skips. The + // connect's own steps (install, then off's uninstall) don't take + // the lock, so they don't wait for the script that holds it. + let (code, out, err) = h.bash( + pins, + &format!( + r#"AUTO_UPDATE=on +{CONNECT_STEPS} +"$T/bin/pyo-verify" run 9>&- +AUTO_UPDATE=off +auto_update_choice +auto_update_off +connect_lock +echo connected +"# + ), + ); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert_eq!( + out, + "→ Setting up automatic updates…\n✓ Set up automatic updates\n✓ Turned off automatic updates\nconnected\n" + ); + assert_eq!( + h.log(), + [ + "curl https://github.com/upsetdev/pyo/releases/download/v0.51.0/pyo-verify-linux-x86_64", + "0.51.0 install --url https://pyo.example", + "run: skipped", + "0.51.0 uninstall", + ], + "no line says a verifier was started with file 9" + ); + // The script ended: the next run has the lock to itself. + h.installed("0.51.0"); + let (code, _, err) = bash(&format!("'{}/bin/pyo-verify' run", h.d())); + assert_eq!((code, err.as_str()), (0, "")); + assert_eq!(h.log(), ["run: took the lock"]); + // A run has the lock: the connect waits for it, then goes on. + let (code, out, err) = h.bash( + pins, + r#"( exec 8>"$T/lock"; flock 8; : >"$T/running"; command sleep 0.5; echo "run: done" >>"$T/log" ) & +until [ -e "$T/running" ]; do command sleep 0.05; done +connect_lock +echo "connect: has the lock" >>"$T/log" +wait +"#, + ); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert_eq!(out, "Waiting for another Pyo setup on this server to finish.\n"); + assert_eq!(h.log(), ["run: done", "connect: has the lock"]); + } + + /// connect.sh's uninstall() on a server whose cluster answers nothing + /// much: what it says and asks the verifier. + fn uninstall_with_verifier(h: &VerifyHost, vars: &str) -> (i32, String, String) { + let start = CONNECT_SCRIPT.find("\nuninstall() {\n").unwrap(); + let end = CONNECT_SCRIPT[start..].find("\n}\nif [ -n \"$UNINSTALL\" ]; then\n").unwrap(); + let uninstall = &CONNECT_SCRIPT[start..start + end + 3]; + h.bash( + None, + &format!( + r#"unset KUBECONFIG +KEEP_DATA="" YES=1 DRY_RUN="" WITH_PYO=1 +k3s() {{ return 0; }} +{vars} +{uninstall} +uninstall +"# + ), + ) + } + + #[test] + fn uninstall_removes_the_verifier_from_the_server() { + let h = VerifyHost::new("uninstall"); + h.installed("0.51.0"); + std::fs::write(h.dir.join("etc/pyo/auto-update"), "on\n").unwrap(); + std::fs::write(h.dir.join("etc/pyo/install-url"), "https://cloud.example\n").unwrap(); + // A dry run only says so. + let (code, out, err) = uninstall_with_verifier(&h, "DRY_RUN=1"); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert!(out.contains("\n - automatic updates on this server\n"), "{out}"); + assert!(out.contains("\n would remove automatic updates from this server\n"), "{out}"); + assert!(h.log().is_empty()); + assert!(h.has("bin/pyo-verify") && h.has("etc/pyo/auto-update")); + // For real: before the agent stops, under the lock. + let (code, out, err) = uninstall_with_verifier(&h, ""); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + let removing = out.find("\nRemoving automatic updates…\n").expect(&out); + assert!(removing < out.find("\nStopping the Pyo agent…\n").unwrap(), "{out}"); + assert_eq!(h.log(), ["0.51.0 uninstall"]); + assert!(!h.has("bin/pyo-verify") && !h.has("etc/pyo/auto-update")); + assert!(!h.has("etc/pyo/install-url")); + // No verifier here: not a word about it, and the choice goes. + std::fs::write(h.dir.join("etc/pyo/auto-update"), "off\n").unwrap(); + let (code, out, err) = uninstall_with_verifier(&h, ""); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert!(!out.contains("automatic updates"), "{out}"); + assert!(h.log().is_empty()); + assert!(!h.has("etc/pyo/auto-update")); + } + + /// connect.sh's own lines from its options to the verifier, in its + /// order: the lock, a refresh reads the agent's settings, the install + /// address is kept, then the manifest (the agent-manifest block) and + /// the verifier come from it. + const INSTALL_STEPS: [&str; 6] = [ + "[ -n \"$TAILNET_ONLY\" ] || connect_lock", + "if [ -z \"$TAILNET_ONLY\" ] && [ -z \"$API\" ] && [ -z \"$TOKEN\" ] && command -v k3s >/dev/null; then\n agent_settings\n [ -z \"$API\" ] || echo \"Updating this cluster's Pyo agent.\"\nfi", + "auto_update_choice\n[ \"$AUTO_UPDATE\" != off ] || auto_update_off\ninstall_url_keep", + "API=$(tailnet_url \"$API\")\nINSTALL_URL=$(tailnet_url \"${INSTALL_URL:-$API}\")", + "AGENT_MANIFEST", + "[ \"$AUTO_UPDATE\" != on ] || auto_update_on \"$INSTALL_URL\"", + ]; + + /// A connect.sh run on `h` with `args`, from its options to the + /// verifier ([`INSTALL_STEPS`]). The agent already here reaches Pyo at + /// `agent` (its Secret's PYO_API_URL), with the token ab12. Pyo answers + /// at every address but https://agent.cloud.example, which takes only + /// the agents' own requests (Pyo Cloud's Cloudflare rule) and answers + /// 403. What it printed. `h.log()` has what k3s and curl were asked. + fn connect_run(h: &VerifyHost, pins: Option<[&str; 3]>, args: &str, agent: &str) -> (i32, String, String) { + let script = match pins { + Some(p) => stamp_verifier(CONNECT_SCRIPT, p), + None => CONNECT_SCRIPT.to_owned(), + }; + let steps = INSTALL_STEPS + .join("\n") + .replace("AGENT_MANIFEST", &script_block("agent-manifest", &script)); + h.bash( + pins, + &format!( + r#"AGENT_API='{agent}' MANIFEST="$T/manifest" WEB_QUERY="" +k3s() {{ + echo "k3s $*" >>"$T/log" + case "$*" in + "kubectl -n pyo-system get secret pyo-agent -o jsonpath={{.data.PYO_API_URL}}") printf %s "$AGENT_API" | base64 ;; + "kubectl -n pyo-system get secret pyo-agent -o jsonpath={{.data.PYO_AGENT_TOKEN}}") printf %s ab12 | base64 ;; + *) return 1 ;; + esac +}} +curl() {{ + local out="" url="" + while [ $# -gt 0 ]; do + case "$1" in -o) out=$2; shift 2 ;; -w | --proto | --max-time | --max-filesize) shift 2 ;; -*) shift ;; *) url=$1; shift ;; esac + done + echo "curl $url" >>"$T/log" + case "$url" in + https://agent.cloud.example/*) echo 403; return 0 ;; + */install/agent.yaml\?token=ab12) echo manifest >"$out"; echo 200; return 0 ;; + */install/agent.yaml*) echo 404; return 0 ;; + esac + [ -f "$T/release/${{url##*/}}" ] || return 22 + cp "$T/release/${{url##*/}}" "$out" +}} +{tailnet} +set -- {args} +{connect_args} +{steps} +echo "agent at $API, installs from $INSTALL_URL" +"#, + tailnet = script_block("tailnet-host", &script), + connect_args = script_block("connect-args", &script), + ), + ) + } + + /// The steps [`connect_run`] runs are connect.sh's, in its order, and + /// every install file comes from the install address. + #[test] + fn connect_gets_its_install_files_from_the_install_address() { + let at = |text: &str| { + assert_eq!(CONNECT_SCRIPT.matches(text).count(), 1, "{text}"); + CONNECT_SCRIPT.find(text).unwrap() + }; + let mut last = 0; + for step in INSTALL_STEPS { + let here = match step { + "AGENT_MANIFEST" => at("\n# >>> pyo:agent-manifest "), + _ => at(&format!("{step}\n")), + }; + assert!(last < here, "{step}"); + last = here; + } + // Checked as --api is, before anything is set up. + let api = at("\n[ -n \"$TAILNET_ONLY\" ] || api_ok \"$API\" || "); + let install = at("\n[ -n \"$TAILNET_ONLY\" ] || [ -z \"$INSTALL_URL\" ] || api_ok \"$INSTALL_URL\" || { echo \"Pyo's address must be https:// ($INSTALL_URL isn't on a private network or the tailnet).\" >&2; exit 2; }\n"); + assert!(api < install && install < at("\n[ \"$(id -u)\" = 0 ] || ")); + // The gateway's CRDs too. Nothing else is fetched from Pyo. + assert!(CONNECT_SCRIPT.contains( + "curl -fsS --max-time 60 -o \"$CRDS\" \"$INSTALL_URL/install/gateway-crds.yaml$q\" && break\n" + )); + let fetches: Vec<&str> = CONNECT_SCRIPT + .lines() + .filter(|l| l.contains("/install/") && !l.trim_start().starts_with('#')) + .collect(); + assert_eq!(fetches.len(), 2, "{fetches:?}"); + assert!(fetches.iter().all(|l| l.contains("\"$INSTALL_URL/install/")), "{fetches:?}"); + assert!(!CONNECT_SCRIPT.contains("$API/")); + // --uninstall drops the kept address. + assert!(CONNECT_SCRIPT.contains("rm -f \"$AUTO_UPDATE_FILE\" \"$INSTALL_URL_FILE\"\n")); + } + + #[test] + fn connect_reads_the_install_address() { + let h = VerifyHost::new("install-flag"); + let (code, out, err) = connect_run(&h, None, "--api 'https://pyo.example' --token 'ab12' --install-url 'https://cloud.example/'", ""); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert_eq!(out, "agent at https://pyo.example, installs from https://cloud.example\n"); + let (code, _, err) = connect_run(&h, None, "--install-url", ""); + assert_ne!(code, 0, "{err}"); + } + + const AGENT: &str = "https://agent.cloud.example"; + + const SECRET_READS: [&str; 2] = [ + "k3s kubectl -n pyo-system get secret pyo-agent -o jsonpath={.data.PYO_API_URL}", + "k3s kubectl -n pyo-system get secret pyo-agent -o jsonpath={.data.PYO_AGENT_TOKEN}", + ]; + + /// Pyo Cloud's refresh command: the manifest and the verifier from Pyo's + /// public address, while the agent keeps its own (only read here, the + /// manifest Pyo hands out names it). Later runs without the flag (a + /// command copied before it) find the address kept. + #[test] + fn a_hosted_refresh_installs_from_the_public_address() { + let h = VerifyHost::new("hosted-refresh"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let pins = Some(["0.51.0", sum.as_str(), OTHER_SUM]); + let (code, out, err) = connect_run(&h, pins, "--install-url 'https://cloud.example' --auto-update", AGENT); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert!(out.starts_with("Updating this cluster's Pyo agent.\n"), "{out}"); + assert!(out.contains("Set up automatic updates"), "{out}"); + assert!( + out.ends_with("agent at https://agent.cloud.example, installs from https://cloud.example\n"), + "{out}" + ); + assert_eq!( + h.log(), + [ + SECRET_READS[0], + SECRET_READS[1], + "curl https://cloud.example/install/agent.yaml?token=ab12", + "curl https://github.com/upsetdev/pyo/releases/download/v0.51.0/pyo-verify-linux-x86_64", + "0.51.0 install --url https://cloud.example", + ] + ); + assert_eq!(h.read("manifest"), "manifest\n"); + assert_eq!(h.read("etc/pyo/install-url"), "https://cloud.example\n"); + + // A refresh command copied before --install-url: the kept address, + // and the verifier (already this release's) is given it again. + for args in ["--auto-update", ""] { + let (code, out, err) = connect_run(&h, pins, args, AGENT); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert!(out.ends_with("installs from https://cloud.example\n"), "{out}"); + assert_eq!( + h.log(), + [ + SECRET_READS[0], + SECRET_READS[1], + "curl https://cloud.example/install/agent.yaml?token=ab12", + "0.51.0 install --url https://cloud.example", + ] + ); + } + assert_eq!(h.read("etc/pyo/install-url"), "https://cloud.example\n"); + } + + /// A refresh command copied before --install-url, on a server that + /// never ran one with it: the agent's address turns the manifest away, + /// so it stops before anything is installed, and says to copy the + /// command again. + #[test] + fn an_old_hosted_refresh_asks_for_the_new_command() { + let h = VerifyHost::new("old-refresh"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + for args in ["", "--auto-update"] { + let (code, out, err) = connect_run(&h, Some(["0.51.0", sum.as_str(), OTHER_SUM]), args, AGENT); + assert_eq!(code, 1, "{out}"); + assert_eq!( + err, + "Pyo at https://agent.cloud.example answered 403 for the agent manifest.\nCopy the command from Pyo again and run that.\n" + ); + assert_eq!( + h.log(), + [SECRET_READS[0], SECRET_READS[1], "curl https://agent.cloud.example/install/agent.yaml?token=ab12"] + ); + assert!(!h.has("bin/pyo-verify") && !h.has("etc/pyo/install-url")); + } + // A first connect isn't told to copy it again. + let (code, _, err) = connect_run(&h, None, "--api 'https://agent.cloud.example' --token 'ab12'", ""); + assert_eq!(code, 1); + assert_eq!(err, "Pyo at https://agent.cloud.example answered 403 for the agent manifest.\n"); + } + + /// The first connect: everything from --api, as before. Pyo Cloud's + /// command also names it as the install address, which is kept. One + /// without it (self-hosted) drops a kept one: one address serves both. + #[test] + fn a_first_connect_installs_from_its_api() { + let h = VerifyHost::new("first-connect"); + let sum = h.release("pyo-verify-linux-x86_64", "0.51.0"); + let (code, out, err) = connect_run( + &h, + Some(["0.51.0", sum.as_str(), OTHER_SUM]), + "--api 'https://cloud.example' --token 'ab12' --install-url 'https://cloud.example' --auto-update", + "", + ); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert!(!out.contains("Updating"), "{out}"); + assert_eq!( + h.log(), + [ + "curl https://cloud.example/install/agent.yaml?token=ab12", + "curl https://github.com/upsetdev/pyo/releases/download/v0.51.0/pyo-verify-linux-x86_64", + "0.51.0 install --url https://cloud.example", + ] + ); + assert_eq!(h.read("etc/pyo/install-url"), "https://cloud.example\n"); + // Self-hosted, or a connect command from before: nothing kept. + let h = VerifyHost::new("first-connect-self-hosted"); + std::fs::write(h.dir.join("etc/pyo/install-url"), "https://cloud.example\n").unwrap(); + let (code, out, err) = connect_run(&h, None, "--api 'https://pyo.example/' --token 'ab12'", ""); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert_eq!(out, "agent at https://pyo.example, installs from https://pyo.example\n"); + assert_eq!(h.log(), ["curl https://pyo.example/install/agent.yaml?token=ab12"]); + assert!(!h.has("etc/pyo/install-url")); + } + + /// Self-hosted refreshes, as before: everything from the agent's + /// address. Pyo's own server too (connect-this-machine.sh), from Pyo + /// on it, whatever a file says. + #[test] + fn a_self_hosted_refresh_installs_from_the_agent_s_address() { + let h = VerifyHost::new("self-hosted-refresh"); + for (agent, from) in [ + ("https://pyo.example/", "https://pyo.example"), + ("http://100.64.0.1:8000", "http://100.64.0.1:8000"), + ] { + let (code, out, err) = connect_run(&h, None, "", agent); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert_eq!(out, format!("Updating this cluster's Pyo agent.\nagent at {from}, installs from {from}\n")); + assert_eq!( + h.log(), + [ + SECRET_READS[0].to_owned(), + SECRET_READS[1].to_owned(), + format!("curl {from}/install/agent.yaml?token=ab12"), + ] + ); + assert!(!h.has("etc/pyo/install-url")); + } + // Pyo's own server: its agent reaches Pyo in the cluster. + std::fs::write(h.dir.join("lib/connect-this-machine.sh"), "").unwrap(); + std::fs::write(h.dir.join("etc/pyo/install-url"), "https://cloud.example\n").unwrap(); + let (code, out, err) = connect_run(&h, None, "", "http://pyo.pyo-system.svc:8000"); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert_eq!( + out, + "Updating this cluster's Pyo agent.\nagent at http://127.0.0.1:8000, installs from http://127.0.0.1:8000\n" + ); + assert_eq!( + h.log().last().map(String::as_str), + Some("curl http://127.0.0.1:8000/install/agent.yaml?token=ab12") + ); + assert_eq!(h.read("etc/pyo/install-url"), "https://cloud.example\n"); + } + + /// A kept address that isn't one is left out. + #[test] + fn a_kept_install_address_has_to_be_one() { + let h = VerifyHost::new("kept-garbage"); + for kept in ["", "pyo.example\n", "ftp://pyo.example\n", "https://\n"] { + std::fs::write(h.dir.join("etc/pyo/install-url"), kept).unwrap(); + let (code, out, err) = connect_run(&h, None, "", "https://pyo.example"); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert!(out.ends_with("installs from https://pyo.example\n"), "{kept:?} {out}"); + h.log(); + } + std::fs::write(h.dir.join("etc/pyo/install-url"), "https://cloud.example/\nmore\n").unwrap(); + let (code, out, err) = connect_run(&h, None, "", AGENT); + assert_eq!((code, err.as_str()), (0, ""), "{out}"); + assert!(out.ends_with("installs from https://cloud.example\n"), "{out}"); + } } diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index d66cb511..318dc879 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -7,6 +7,9 @@ //! background tasks, migrations, dashboard features and entitlement checks //! (see [`Extensions`]); self-hosted Pyo has none of those. +mod admin_sign_in; +#[cfg(test)] +mod admin_sign_in_tests; mod agent; mod agent_auth; mod agent_tls; @@ -25,6 +28,7 @@ mod cli; mod cloud; mod cloudflare; pub mod compose; +pub mod compose_sync; mod cronruns; mod database_analytics; mod database_backups; @@ -79,7 +83,7 @@ mod routes; mod sandbox; mod secrets; mod secretstores; -mod sigstore; +use pyo_sigstore as sigstore; mod sites; mod snapshot; mod source_uploads; @@ -418,6 +422,11 @@ pub(crate) fn hosted() -> bool { /// Runs Pyo: migrates, starts the background work, and serves until a /// shutdown signal. The `pyo-api` binary is `run(Extensions::default())`. pub async fn run(ext: Extensions) -> anyhow::Result<()> { + // One TLS provider for every client and server that doesn't pick its + // own, before any of them starts. A build with ring next to aws-lc-rs + // (pyo-sandbox's, in a workspace build) can't guess one, and building a + // TLS config would panic. + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); let Extensions { routes: extra_routes, tasks, @@ -551,6 +560,7 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { // Each loop runs on one worker at a time (leader lock); jobs on any. tokio::spawn(deploy::sweeper(state.clone())); tokio::spawn(deploy::dns_watcher(state.clone())); + tokio::spawn(cloudflare::tunnel_loop::run(state.clone())); tokio::spawn(builders::watcher(state.clone())); tokio::spawn(github::poller(state.clone())); tokio::spawn(git::poller(state.clone())); @@ -668,6 +678,7 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { .route("/api/{*rest}", get(error::not_found).post(error::not_found)) .route("/install/agent.yaml", get(install::manifest)) .route("/install/gateway-crds.yaml", get(install::gateway_crds)) + .route("/install/version", get(install::version)) .route("/install/this-machine", get(install::this_machine)) .route("/install/first-sign-in", get(install::first_sign_in)) .route( @@ -678,6 +689,10 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { "/install/this-machine/tailnet", axum::routing::post(install::this_machine_tailnet), ) + .route( + "/install/this-machine/refresh", + axum::routing::post(install::this_machine_refresh), + ) .route("/install/join.sh", get(join::serve)) .route("/install/connect.sh", get(join::serve_connect)) .route("/install/sandbox.sh", get(join::serve_sandbox)) diff --git a/crates/pyo-api/src/mail.rs b/crates/pyo-api/src/mail.rs index 1f5ed861..ad2cbf88 100644 --- a/crates/pyo-api/src/mail.rs +++ b/crates/pyo-api/src/mail.rs @@ -464,6 +464,19 @@ pub fn two_factor_off(link: &str) -> Email { .reason("You get this email for every change to how you sign in.") } +/// An admin sign-in with the right credentials, refused because of where +/// it came from (admin_sign_in.rs). +pub fn sign_in_refused(address: &str, link: &str) -> Email { + Email::new("A Pyo sign-in was refused", "Sign-in refused") + .para(vec![ + t("Someone used your sign-in details for your Pyo admin account from "), + b(address), + t(". Pyo refused it because admins can't sign in from there. If that wasn't you, change your password."), + ]) + .button("Open security settings", link) + .reason("You get this email for every refused sign-in to an admin account.") +} + /// A new API key was made on the account. pub fn new_api_key(name: &str, link: &str) -> Email { Email::new("A new Pyo API key was made", "New API key") @@ -521,6 +534,7 @@ mod tests { ), ("two-factor-off", two_factor_off(&c.link("/profile"))), ("new-api-key", new_api_key(key, &c.link("/api-keys"))), + ("sign-in-refused", sign_in_refused(key, &c.link("/security"))), ] } diff --git a/crates/pyo-api/src/mcp.rs b/crates/pyo-api/src/mcp.rs index b2163bda..6d7826cc 100644 --- a/crates/pyo-api/src/mcp.rs +++ b/crates/pyo-api/src/mcp.rs @@ -148,14 +148,14 @@ fn curated() -> Vec { "replicas": { "type": "integer", "minimum": 1 }, "confirm": confirm, "env": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Environment variables" }, - "free_domain": { "type": "boolean", "description": "Give it a free nip.io domain (no DNS needed)" }, + "free_domain": { "type": "boolean", "description": "Give it a free nip.io domain, or a tunnel domain in tunnel mode (no DNS needed)" }, "domain": { "type": "string", "description": "A custom hostname to serve it on" }, "region": { "type": "string", "description": "Where to run it: a region of the team's servers (e.g. \"US East\" or \"Singapore, SG\"), a country code (DE, SG) or a city. The team's default cluster when omitted" }, "placement": placement_schema(), "server_tags": { "type": "array", "items": { "type": "string" }, "description": "Older form of placement.tags" }, }), &["name", "image"]), "annotations": write }), json!({ "name": "set_service_placement", "title": "Set service placement", "description": "Choose where a service runs: any server of its cluster (servers and tags both empty), or only the servers named and every server with one of the tags, including servers tagged later (see list_servers). A service with a volume has to keep its volume's server, and one with a GPU needs a GPU server. It changes in place, without a redeploy: its replicas move over with the same image. Refused with the reason when no server picked can run it.", "inputSchema": schema(json!({ "service_id": service, "servers": { "type": "array", "items": { "type": "string" }, "description": "Server names" }, "tags": { "type": "array", "items": { "type": "string" }, "description": "Server tags" } }), &["service_id"]), "annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": true } }), - json!({ "name": "add_domain", "title": "Add domain", "description": "Serve a service on a hostname, or on a free nip.io domain. It goes live in place, without a redeploy (a service never deployed gets it with its first deploy).", "inputSchema": schema(json!({ "service_id": service, "hostname": { "type": "string" }, "free_domain": { "type": "boolean" }, "cloudflare_dns": { "type": "boolean", "description": "Create its DNS record in the team's Cloudflare account when a connected zone covers the hostname (default true). Never overwrites a record." }, "proxied": { "type": "boolean", "description": "Proxied by Cloudflare, once its certificate is issued (default false)" } }), &["service_id"]), "annotations": write }), + json!({ "name": "add_domain", "title": "Add domain", "description": "Serve a service on a hostname, or on a free nip.io domain (a tunnel domain in tunnel mode). It goes live in place, without a redeploy (a service never deployed gets it with its first deploy).", "inputSchema": schema(json!({ "service_id": service, "hostname": { "type": "string" }, "free_domain": { "type": "boolean" }, "cloudflare_dns": { "type": "boolean", "description": "Create its DNS record in the team's Cloudflare account when a connected zone covers the hostname (default true). Never overwrites a record." }, "proxied": { "type": "boolean", "description": "Proxied by Cloudflare, once its certificate is issued (default false)" }, "tunnel": { "type": "boolean", "description": "Through the cluster's Cloudflare Tunnel when a tunnel-ready zone covers the hostname (default: on in tunnel mode)." } }), &["service_id"]), "annotations": write }), json!({ "name": "set_static_serving", "title": "Set static serving", "description": "For a service whose build is a static site: serve its build as static files from the cluster's shared static server (\"static\", the default), or run it as a service of its own (\"service\"). Takes effect with the next deploy.", "inputSchema": schema(json!({ "service_id": service, "serve_as": { "type": "string", "enum": ["static", "service"] } }), &["service_id", "serve_as"]), "annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": true } }), json!({ "name": "set_request_timeout", "title": "Set request timeout", "description": "How long the gateway waits for the service to answer a request on its domains before it returns 504, in seconds: 1 to 3600, or 0 for no limit. Without one it's 300. WebSockets aren't cut by it. It changes in place, without a redeploy.", "inputSchema": schema(json!({ "service_id": service, "seconds": { "type": ["integer", "null"], "minimum": 0, "maximum": 3600, "description": "null goes back to the default" } }), &["service_id", "seconds"]), "annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": true } }), json!({ "name": "stop_service", "title": "Stop service", "description": "Stop the service (scale to zero). Settings and data are kept.", "inputSchema": schema(json!({ "service_id": service }), &["service_id"]), "annotations": { "readOnlyHint": false, "destructiveHint": true, "idempotentHint": true } }), @@ -356,7 +356,7 @@ fn op_annotations(op: &str) -> Value { "readOnlyHint": read_only, // Undoing a server's removal takes nothing away. // A volume's restore replaces its data. - "destructiveHint": !read_only && op != "cancelServerRemoval" && (starts(&["delete", "remove", "stop", "discard", "rotate", "cancel", "revoke"]) || op == "restoreVolume"), + "destructiveHint": !read_only && op != "cancelServerRemoval" && (starts(&["delete", "remove", "stop", "discard", "rotate", "cancel", "revoke"]) || op == "restoreVolume" || op == "syncCompose"), "idempotentHint": read_only || starts(&["set", "update", "save", "scale", "remove", "delete", "stop", "verify", "replace", "detach", "attach", "resize"]), }) } @@ -650,6 +650,7 @@ async fn run_endpoint(s: &AppState, user: &User, id: &str, args: &Value) -> Resu "listImages" => json_of(crate::images::list(st(), me(), Query(args_as(args)?)).await), "getRegistry" => json_of(crate::images::registry(st(), me(), Query(args_as(args)?)).await), "getCloudflare" => json_of(crate::cloudflare::get(st(), me(), Query(args_as(args)?)).await), + "getClusterTunnel" => json_of(crate::cloudflare::tunnel_ops::get(st(), me(), path_id()?).await), "listDatabases" => json_of(crate::databases::list(st(), me(), Query(args_as(args)?)).await), "getDatabase" => { json_of(crate::databases::get(st(), me(), Path(arg(args, "id")?.to_owned())).await) @@ -688,6 +689,9 @@ async fn run_endpoint(s: &AppState, user: &User, id: &str, args: &Value) -> Resu "previewCompose" => { json_of(crate::compose::preview(st(), me(), Json(args_as(args)?)).await) } + "planComposeSync" => { + json_of(crate::compose_sync::plan(st(), me(), Json(args_as(args)?)).await) + } "getServiceConnections" => { json_of(ops::connections(st(), me(), path_id()?, Query(args_as(args)?)).await) } @@ -1304,7 +1308,31 @@ pub(crate) async fn run_tool( && !n.is_empty() && (host == n || host.ends_with(&format!(".{n}"))) }); - let dns_record = if covered && args["cloudflare_dns"].as_bool().unwrap_or(true) { + // Through the cluster's Cloudflare Tunnel, by default in tunnel mode. + let cluster = list("clusters") + .into_iter() + .find(|c| c["id"] == a["clusterId"]) + .unwrap_or_default(); + let tunnel_mode = cluster["traffic"] == json!("tunnel"); + let tunnel_ready = covered + && cluster["tunnel"].is_object() + && list("cloudflare") + .iter() + .filter(|c| c["teamId"] == team) + .flat_map(|c| c["zones"].as_array().cloned().unwrap_or_default()) + .any(|z| { + let n = z["name"].as_str().unwrap_or(""); + z["tunnel"]["ready"] == json!(true) + && z["accountId"] == cluster["tunnel"]["accountId"] + && !n.is_empty() + && (host == n || host.ends_with(&format!(".{n}"))) + }); + let tunnel = tunnel_ready && args["tunnel"].as_bool().unwrap_or(tunnel_mode); + let dns_record = if tunnel { + op(json!({ "op": "setDomainTunnel", "serviceId": id, "domainId": d["id"], "on": true })) + .await + .unwrap_or_else(|e| json!({ "status": "failed", "error": e })) + } else if covered && args["cloudflare_dns"].as_bool().unwrap_or(true) { op(json!({ "op": "createDnsRecord", "serviceId": id, "domainId": d["id"], "proxied": args["proxied"].as_bool().unwrap_or(false), @@ -1555,6 +1583,14 @@ fn cluster_at(snap: &Value, team: &str, place: &str) -> Result<(Value, String), /// "nginx-web.203.0.113.7.nip.io": resolves to the cluster's free-domain /// address (its public or Tailscale IP, as its settings say). fn free_hostname(cluster: &Value, service: &str, namespace: &str) -> Result { + // In tunnel mode, under its default domain (the tunnel's wildcard). + if cluster["traffic"] == json!("tunnel") { + let suffix = cluster["freeDomainSuffix"].as_str().ok_or( + "The cluster's Cloudflare Tunnel has no default domain, so there's no tunnel domain for it. Pick a default domain first, or use a custom hostname.", + )?; + let label: String = format!("{service}-{namespace}").chars().take(63).collect(); + return Ok(format!("{}.{suffix}", label.trim_end_matches('-'))); + } let ip = cluster["freeDomainIp"] .as_str() .and_then(|ip| ip.parse().ok()) diff --git a/crates/pyo-api/src/oauth.rs b/crates/pyo-api/src/oauth.rs index 80c0d99c..54510a98 100644 --- a/crates/pyo-api/src/oauth.rs +++ b/crates/pyo-api/src/oauth.rs @@ -644,7 +644,15 @@ impl FromRequestParts for OAuthUser { } // The same limits as an API key with the access the user chose, in // all their teams: what the account and the installation allow stays - // with the dashboard. + // with the dashboard. From where admins may not sign in, an admin's + // assistant acts as a member only (admin_sign_in.rs). + let is_admin = is_admin + && crate::admin_sign_in::admits( + &s.db, + &crate::admin_sign_in::Source::from_parts(parts), + ) + .await + .map_err(|_| challenge(None))?; let user = User { id, name, diff --git a/crates/pyo-api/src/openapi.rs b/crates/pyo-api/src/openapi.rs index 33852abb..d4d39cf4 100644 --- a/crates/pyo-api/src/openapi.rs +++ b/crates/pyo-api/src/openapi.rs @@ -51,6 +51,7 @@ use crate::{auth::KeyAccess, error::ErrorBody, ops::Op}; crate::images::list, crate::images::registry, crate::cloudflare::get, + crate::cloudflare::tunnel_ops::get, crate::databases::list, crate::databases::get, crate::databases::extensions, @@ -75,6 +76,7 @@ use crate::{auth::KeyAccess, error::ErrorBody, ops::Op}; crate::git::branches, crate::git::build_file, crate::compose::preview, + crate::compose_sync::plan, crate::cloud::options, crate::audit::list, crate::tailscale::lock, @@ -223,6 +225,7 @@ fn title(op: &str) -> String { match op { "setServerLocation" => return "Set server region".into(), "importCompose" => return "Import Docker Compose".into(), + "syncCompose" => return "Sync Docker Compose".into(), _ => {} } let mut words: Vec = vec![]; diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 930493e4..6204004d 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -94,6 +94,10 @@ pub fn routes() -> Router { .route("/images", get(crate::images::list)) .route("/registry", get(crate::images::registry)) .route("/cloudflare", get(crate::cloudflare::get)) + .route( + "/clusters/{id}/tunnel", + get(crate::cloudflare::tunnel_ops::get), + ) .route("/databases", get(crate::databases::list)) .route("/databases/{id}", get(crate::databases::get)) .route("/database-extensions", get(crate::databases::extensions)) @@ -104,6 +108,7 @@ pub fn routes() -> Router { ) .route("/database-backups", post(crate::database_backups::add)) .route("/compose/preview", post(crate::compose::preview)) + .route("/compose/sync-plan", post(crate::compose_sync::plan)) .route("/cloud/options", get(crate::cloud::options)) .route("/tailnet/lock", get(crate::tailscale::lock)) .route("/audit-log", get(crate::audit::list)) @@ -2225,6 +2230,13 @@ pub(crate) enum Op { require_two_factor: bool, audit_days: u16, }, + /// Where the installation's admins may sign in from: the tailnet, and addresses or ranges (IPv4 or IPv6, like 203.0.113.7 or 2001:db8::/48). Neither is anywhere. Only the installation's admin can do this, from the dashboard, and the address they save it from must stay allowed. + SaveAdminSignIn { + #[serde(default)] + tailnet: bool, + #[serde(default)] + addresses: Vec, + }, /// Turn observability (analytics, request logs, firewall and WAF history, usage history) on or off for the whole installation. Only the installation's admin can do this. Off stops storing and showing history and frees its memory. What was stored is kept for when it's back on. Live logs, current usage, deploys and the firewall keep working. SetObservability { enabled: bool }, /// How Pyo updates itself: "manual" or "auto" in a weekly window (UTC). @@ -2745,7 +2757,7 @@ pub(crate) enum Op { provider: Option, /// A location's `name` from getCloudOptions ("fsn1"). location: String, - /// A server type's `name` from getCloudOptions ("cx22"). + /// A server type's `name` from getCloudOptions ("cx23"). server_type: String, /// A build-only server: only Pyo's builder runs on it. #[serde(default)] @@ -2933,9 +2945,9 @@ pub(crate) enum Op { }, /// Revoke a Pyo registry token. Team owners and admins. RevokeRegistryToken { id: String }, - /// Connect the team's Cloudflare account, or replace its token. The token needs Zone:Read and DNS:Edit on the zones Pyo may use. Pyo lists its zones, checks it can edit DNS in each (it makes and deletes a TXT record `_pyo-check.`), then keeps it encrypted. It's never shown again. Team owners and admins. + /// Connect the team's Cloudflare account, or replace its token. The token needs Zone:Read and DNS:Edit on the zones Pyo may use, and for Cloudflare Tunnel also Cloudflare Tunnel:Edit and SSL and Certificates:Edit. Pyo lists its zones and their accounts, checks it can edit DNS in each (it makes and deletes a TXT record `_pyo-check.`), checks the tunnel permissions (it makes and deletes a tunnel `pyo-check--` once per account, and reads each zone's Origin CA certificates), then keeps it encrypted. It's never shown again. Each zone's `tunnel` says whether it can use Cloudflare Tunnel. Team owners and admins. ConnectCloudflare { team_id: String, token: String }, - /// Check the saved Cloudflare token again: the zones it covers now, and what it's missing (`problems`). Team owners and admins. + /// Check the saved Cloudflare token again: the zones it covers now, whether each can use Cloudflare Tunnel, and what it's missing (`problems`). Team owners and admins. TestCloudflare { team_id: String }, /// Forget the team's Cloudflare token. DNS records Pyo made stay in Cloudflare. Team owners and admins. RemoveCloudflare { team_id: String }, @@ -2955,6 +2967,40 @@ pub(crate) enum Op { service_id: String, domain_id: String, }, + /// How a cluster takes web traffic: "public" (ports 80 and 443 on every server but build-only ones), "tailscale" (only from the tailnet, or only inside the cluster without Tailscale) or "tunnel" (through Cloudflare Tunnel, with no ports 80 and 443 open). For "tunnel", the team's Cloudflare token needs Cloudflare Tunnel:Edit and SSL and Certificates:Edit, and the cluster's install must be Pyo's (run its connect command first when it's older). Domains in zones of the tunnel's account move to the tunnel. Those with a DNS record Pyo didn't make wait for `setDomainTunnel` with `replace`. Pyo does the Cloudflare work in the background: the cluster's `tunnel` shows how it's going. Team owners and admins. + SetClusterTraffic { + cluster_id: String, + mode: String, + /// A zone of the token (its apex, like "example.com"): services get names under it, and `*.example.com` goes through the tunnel. Optional. + #[serde(default)] + default_domain: Option, + /// The Cloudflare account for the tunnel, when the token's zones are in more than one. + #[serde(default)] + account_id: Option, + /// Public TCP and UDP ports stay on the servers in tunnel mode (they don't go through the tunnel). On by default. + #[serde(default)] + ports_public: Option, + }, + /// Serve a domain through the cluster's Cloudflare Tunnel (`on`), or move it back. Pyo adds the tunnel's route first, then points the name at the tunnel with a proxied CNAME, so both paths answer while it moves. When records Pyo didn't make have the name, the domain's `dnsRecord.status` turns "conflict" and `existing` lists them. Send it again with `replace` to replace them (team owners and admins): Pyo keeps a copy. Moving back with `restore` puts that copy back (team owners and admins), or without one, points the name at the cluster's public IP. A name one level under the tunnel's default domain always goes through the tunnel, so moving it back is refused unless a record it replaced comes back. A new name one level under the default domain gets no record of its own when nothing else at Cloudflare answers for it: the default domain's wildcard record has it, and the answer is `status: "active"`. A name that's already only through the tunnel stays that way while its own record is made. + SetDomainTunnel { + service_id: String, + domain_id: String, + on: bool, + /// Replace the records in the way. + #[serde(default)] + replace: bool, + /// Moving back: put back the records the tunnel replaced. On by default. + #[serde(default = "yes")] + restore: bool, + }, + /// Remove a cluster's Cloudflare Tunnel: its routes, the DNS records Pyo made (with `restoreRecords`, the ones they replaced come back), the connector in the cluster, its certificate and the tunnel itself. Pick Public ports or Tailscale only for the cluster first. Team owners and admins. + RemoveClusterTunnel { + cluster_id: String, + #[serde(default = "yes")] + restore_records: bool, + }, + /// Give the cluster's Cloudflare Tunnel a new token and a new certificate, and drop its old connections. Team owners and admins. + RotateTunnelToken { cluster_id: String }, /// Create a project and its services from a Docker Compose plan (from `POST /compose/preview`, edited if you like), and deploy them in order. ImportCompose { team_id: String, @@ -2965,6 +3011,21 @@ pub(crate) enum Op { project_id: Option, plan: crate::compose::ComposePlan, }, + /// Bring a project in line with a Docker Compose file: `file` from `POST /compose/sync-plan`, which shows what this does. Only what the file says differently changes, so settings changed in Pyo that the file doesn't mention stay, and a secret's value is never changed. Services whose settings change are deployed. What can't change in place (a volume that would move, another kind of source) is left as it is. + /// A service no longer in the file stays, unless `prune`. + SyncCompose { + project_id: String, + /// Where services new in the file run. Where the project's services run when omitted. + #[serde(default)] + cluster_id: Option, + plan: crate::compose::ComposePlan, + /// Delete the services made from this file that are no longer in it. Their volumes are kept, detached. + #[serde(default)] + prune: bool, + /// Go ahead with a very large replica change: without it, one that goes to 20 or more replicas and to more than 10 times what the service had, or more than twice what its servers have room for, is refused with 409 and `needsConfirm: true`. Ask the user before sending it. + #[serde(default)] + confirm: bool, + }, } /// Make a change @@ -3165,6 +3226,7 @@ fn installation_wide(op: &Op) -> bool { | Op::SaveObservabilitySettings { .. } | Op::SaveRetentionSettings { .. } | Op::SaveSecuritySettings { .. } + | Op::SaveAdminSignIn { .. } | Op::SaveUpdateSettings { .. } | Op::SetSandboxLimits { .. } | Op::CheckForUpdates {} @@ -3311,6 +3373,7 @@ pub(crate) fn key_access_for(op: &Op) -> Option { | Op::SaveObservabilitySettings { .. } | Op::SaveRetentionSettings { .. } | Op::SaveSecuritySettings { .. } + | Op::SaveAdminSignIn { .. } | Op::SetTeamSecurity { .. } | Op::SaveUpdateSettings { .. } | Op::SetSandboxLimits { .. } @@ -3376,7 +3439,8 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::UpdateProject { .. } | Op::DeleteProject { .. } | Op::SetProjectIsolation { .. } - | Op::ImportCompose { .. } => ("Projects", "prj"), + | Op::ImportCompose { .. } + | Op::SyncCompose { .. } => ("Projects", "prj"), Op::CreateService { .. } | Op::SaveService { .. } | Op::DeleteService { .. } @@ -3393,9 +3457,10 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { Op::SaveCronJob { .. } | Op::RemoveCronJob { .. } | Op::RunCronJob { .. } => { ("Cron jobs", "crn") } - Op::VerifyDomain { .. } | Op::CreateDnsRecord { .. } | Op::DeleteDnsRecord { .. } => { - ("Domains", "dom") - } + Op::VerifyDomain { .. } + | Op::CreateDnsRecord { .. } + | Op::DeleteDnsRecord { .. } + | Op::SetDomainTunnel { .. } => ("Domains", "dom"), Op::UploadCertificate { .. } | Op::ReplaceCertificate { .. } | Op::RemoveCertificate { .. } => ("Domains", "crt"), @@ -3435,6 +3500,9 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::SetClusterTrafficMode { .. } | Op::SetClusterWebProxyProtocol { .. } | Op::SetClusterPublicTraffic { .. } + | Op::SetClusterTraffic { .. } + | Op::RemoveClusterTunnel { .. } + | Op::RotateTunnelToken { .. } | Op::SetClusterFreeDomainAddress { .. } => ("Clusters", "cl"), Op::AddFirewallRule { .. } | Op::UpdateFirewallRule { .. } @@ -3498,6 +3566,7 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::SaveObservabilitySettings { .. } | Op::SaveRetentionSettings { .. } | Op::SaveSecuritySettings { .. } + | Op::SaveAdminSignIn { .. } | Op::SaveUpdateSettings { .. } | Op::SetSandboxLimits { .. } | Op::CheckForUpdates {} @@ -3534,6 +3603,21 @@ fn key_allows(user: &User, op: &Op) -> ApiResult<()> { } } +/// Another operation, run inside this one's transaction with its own +/// checks (a Compose sync saves, creates and deletes services this way). +pub(crate) fn nested<'a, 'c>( + s: &'a AppState, + tx: &'a mut Transaction<'c, Postgres>, + user: &'a User, + op: Op, + wake: &'a mut Vec, +) -> std::pin::Pin> + Send + 'a>> +where + 'c: 'a, +{ + Box::pin(apply(s, tx, user, op, wake)) +} + async fn apply( s: &AppState, tx: &mut Transaction<'_, Postgres>, @@ -4277,6 +4361,25 @@ async fn apply( } Ok(ok) } + Op::SaveAdminSignIn { tailnet, addresses } => { + require_admin(user)?; + let after = crate::admin_sign_in::checked(tailnet, &addresses)?; + // Never one that shuts out the request saving it. + crate::admin_sign_in::keeps(&after, &crate::audit::request_source())?; + let before = crate::admin_sign_in::save(tx, &after).await?; + if before != after { + // The admin's teams hear of it, as of a two-factor change + // (Pyo Cloud has no team of the installation's own). + crate::twofactor::notify_teams( + tx, + user, + "auth.admin_sign_in_changed", + &crate::admin_sign_in::change_title(&after), + ) + .await?; + } + Ok(json!({ "ok": true, "addresses": after.addresses })) + } Op::SetObservability { enabled } => { require_admin(user)?; sqlx::query("INSERT INTO pyo.settings (key, value) VALUES ('observability', jsonb_build_object('enabled', $1)) ON CONFLICT (key) DO UPDATE SET value = pyo.settings.value || excluded.value, updated_at = now()") @@ -4735,8 +4838,9 @@ async fn apply( Op::SetClusterPublicTraffic { cluster_id, on } => { let team_id = team_of(tx, "clusters", &cluster_id).await?; require_role(tx, user, &team_id, Role::Admin).await?; + // `public_traffic` follows `traffic` (a trigger keeps them in step). let name: String = sqlx::query_scalar( - "UPDATE pyo.clusters SET public_traffic = $2 WHERE id = $1 RETURNING name", + "UPDATE pyo.clusters SET traffic = CASE WHEN $2 THEN 'public' ELSE 'tailscale' END WHERE id = $1 RETURNING name", ) .bind(&cluster_id) .bind(on) @@ -4788,6 +4892,10 @@ async fn apply( crate::freedomain::Mode::Tailscale => { format!("Free domains on {name} use its Tailscale IP") } + // Never parsed from an address: it follows the cluster's traffic. + crate::freedomain::Mode::Tunnel => { + format!("Domains on {name} go through its Cloudflare Tunnel") + } }; log_activity( tx, @@ -5737,6 +5845,7 @@ async fn apply( let deployment_id = new_id("dpl"); let service = crate::compose::service_spec( svc, + Some(&plan.project.file), &id, &team_id, &project_id, @@ -5756,10 +5865,43 @@ async fn apply( None, ) .await?; + if let Some(cdn) = &svc.behind_cdn { + nested( + s, + tx, + user, + Op::SetServiceBehindCdn { + service_id: id.clone(), + cdn: Some(cdn.clone()), + }, + wake, + ) + .await?; + } made.push(json!({ "name": svc.name, "id": id, "deploymentId": deployment_id })); } Ok(json!({ "ok": true, "projectId": project_id, "services": made })) } + Op::SyncCompose { + project_id, + cluster_id, + plan, + prune, + confirm, + } => { + crate::compose_sync::apply( + s, + tx, + user, + &project_id, + cluster_id, + plan, + prune, + confirm, + wake, + ) + .await + } Op::CreateProject { id, team_id, @@ -6046,6 +6188,13 @@ async fn apply( // Where it came from stays, and a secret field's value never does. crate::template_source::keep_record(&mut spec, &old_spec); crate::template_source::scrub_fields(&mut spec); + // What it remembers of the Compose file it was made from stays + // when a client leaves it out. + if spec.get("compose").is_none_or(Value::is_null) + && let Some(c) = old_spec.get("compose").filter(|c| c.is_object()) + { + spec["compose"] = c.clone(); + } // Autoscaling has its own op: a save from a tab that hasn't seen // the latest setting can't change it, or the size it manages. match old_spec.get("autoscale") { @@ -6124,6 +6273,7 @@ async fn apply( if let Some(o) = v.as_object_mut() { o.remove("description"); o.remove("autoRollback"); + o.remove("compose"); o.remove("domains"); // Goes live with the domains (routes.rs). o.remove("requestTimeout"); @@ -8222,6 +8372,53 @@ async fn apply( service_id, domain_id, } => crate::cloudflare::delete_record(s, tx, user, &service_id, &domain_id).await, + Op::SetClusterTraffic { + cluster_id, + mode, + default_domain, + account_id, + ports_public, + } => { + crate::cloudflare::tunnel_ops::set_traffic( + s, + tx, + user, + &cluster_id, + &mode, + default_domain.as_deref(), + account_id.as_deref(), + ports_public, + wake, + ) + .await + } + Op::SetDomainTunnel { + service_id, + domain_id, + on, + replace, + restore, + } => { + crate::cloudflare::tunnel_ops::set_domain( + s, + tx, + user, + &service_id, + &domain_id, + on, + replace, + restore, + wake, + ) + .await + } + Op::RemoveClusterTunnel { + cluster_id, + restore_records, + } => crate::cloudflare::tunnel_ops::remove(tx, user, &cluster_id, restore_records, wake).await, + Op::RotateTunnelToken { cluster_id } => { + crate::cloudflare::tunnel_ops::rotate(tx, user, &cluster_id).await + } Op::UpdateProfile { name, timezone } => { let name = require_text(&name, "Name", 80)?; let tz = require_text(&timezone, "Time zone", 64)?; diff --git a/crates/pyo-api/src/passkeys.rs b/crates/pyo-api/src/passkeys.rs index 3b4ee3e9..47d1230d 100644 --- a/crates/pyo-api/src/passkeys.rs +++ b/crates/pyo-api/src/passkeys.rs @@ -230,6 +230,7 @@ struct LoginFinish { async fn login_finish( State(state): State, ClientIp(ip): ClientIp, + from: crate::admin_sign_in::Source, headers: HeaderMap, jar: CookieJar, Json(body): Json, @@ -238,6 +239,11 @@ async fn login_finish( // Only failures keep their slot. ratelimit::take(&state.db, &[(ratelimit::PASSKEY_FINISH_IP, &ip)]).await?; let user = verify_passkey(&state, body).await?; + // An admin from where admins may not sign in: as a passkey that didn't + // work. + if !crate::admin_sign_in::sign_in_allowed(&state, &user, &from, "with a passkey").await? { + return Err(failed("admin sign-in limit")); + } ratelimit::forgive(&state.db, &ratelimit::PASSKEY_FINISH_IP, &ip).await?; // A passkey is two factors on its own: no code after it (twofactor.rs). crate::audit::account_event( diff --git a/crates/pyo-api/src/platform_import/mod.rs b/crates/pyo-api/src/platform_import/mod.rs index 641d35ab..206e9369 100644 --- a/crates/pyo-api/src/platform_import/mod.rs +++ b/crates/pyo-api/src/platform_import/mod.rs @@ -429,7 +429,7 @@ impl Web { self.port(port, false); } self.warnings.push(format!( - "{host} is a free domain {} made. Add a free Pyo domain instead.", + "{host} is a free domain {} made. Add a domain in Pyo instead.", platform.label() )); return; @@ -1738,6 +1738,7 @@ async fn create( let id = new_id("svc"); let mut spec = crate::compose::service_spec( &service, + None, &id, team_id, &pid, @@ -1821,6 +1822,7 @@ async fn create( let id = new_id("svc"); let mut spec = crate::compose::service_spec( cs, + None, &id, team_id, &pid, diff --git a/crates/pyo-api/src/previews/domain.rs b/crates/pyo-api/src/previews/domain.rs index cb8fa9b3..14a2431e 100644 --- a/crates/pyo-api/src/previews/domain.rs +++ b/crates/pyo-api/src/previews/domain.rs @@ -11,6 +11,10 @@ //! certificate, and the record is made by hand. //! - Else nip.io on the cluster's free-domain address //! (`web-pr-42.203.0.113.7.nip.io`). +//! - In Cloudflare Tunnel mode, public previews go under the tunnel's +//! default domain (`web-pr-42.example.com`), covered by its wildcard +//! record and route, like free domains. The preview domain isn't used +//! then. Without a default domain there's no preview URL. //! //! A domain is per cluster: its wildcard record can point at one cluster. @@ -58,6 +62,10 @@ pub async fn with_certificate( cluster_id: &str, mut d: Value, ) -> ApiResult { + // Through the cluster's tunnel: the tunnel loop keeps its certificate. + if d["tunnel"].is_string() { + return Ok(d); + } let pd = stored(tx, cluster_id).await?; let host = d["hostname"].as_str().unwrap_or("").to_owned(); let under = pd["domain"] @@ -93,15 +101,31 @@ async fn suffix( None => Err("Private previews need Tailscale on the cluster.".into()), }); } - if let Some(d) = stored(tx, cluster_id).await?["domain"].as_str() { - return Ok(Ok(d.to_owned())); + let preview_domain = stored(tx, cluster_id).await?["domain"] + .as_str() + .map(str::to_owned); + let cluster = crate::freedomain::load(tx, cluster_id) + .await? + .map(|(_, c)| c) + .unwrap_or_default(); + Ok(public_suffix(&cluster, preview_domain.as_deref())) +} + +/// Said when a cluster in tunnel mode has no default domain for previews. +pub const PICK_DEFAULT_DOMAIN: &str = "Pick a default domain for the cluster's Cloudflare Tunnel first. Previews get names under it."; + +/// Where a public preview's URL goes: under the tunnel's default domain in +/// tunnel mode (none without one), else the preview domain, else the +/// cluster's free-domain address on nip.io. +pub fn public_suffix(c: &crate::freedomain::Cluster, preview_domain: Option<&str>) -> Result { + if c.tunnel { + return c.tunnel_domain.clone().ok_or_else(|| PICK_DEFAULT_DOMAIN.to_owned()); } - Ok( - match crate::freedomain::for_cluster(tx, cluster_id).await? { - Some(ip) => Ok(format!("{ip}.nip.io")), - None => Err("The cluster has no address for preview URLs yet.".into()), - }, - ) + if let Some(d) = preview_domain { + return Ok(d.to_owned()); + } + c.suffix() + .ok_or_else(|| "The cluster has no address for preview URLs yet.".into()) } /// Whether a host is taken: by a service's domain (not `copy`), or by @@ -620,6 +644,38 @@ mod tests { assert_eq!(v["record"]["content"], Value::Null); } + #[test] + fn previews_in_tunnel_mode_go_under_the_default_domain() { + use crate::freedomain::Cluster; + let server = json!({ "name": "vps", "status": "ready", "internalIP": "10.0.0.5", "addresses": ["10.0.0.5"], + "publicIpv4": "203.0.113.7", "nicPublicIps": ["203.0.113.7"] }); + let public = Cluster { + public_traffic: true, + servers: vec![server], + ..Default::default() + }; + assert_eq!(public_suffix(&public, None).unwrap(), "203.0.113.7.nip.io"); + assert_eq!(public_suffix(&public, Some("preview.example.com")).unwrap(), "preview.example.com"); + // Tunnel mode: under the default domain, whatever the preview domain. + let tunnel = Cluster { + tunnel: true, + tunnel_domain: Some("example.com".into()), + ..Default::default() + }; + assert_eq!(public_suffix(&tunnel, Some("preview.example.com")).unwrap(), "example.com"); + assert!(crate::cloudflare::tunnel_loop::under_default( + &naming::host(&naming::label("web", 42, naming::LABEL_MAX), "example.com"), + "example.com" + )); + // Without one: no preview URL, and why. + let bare = Cluster { + tunnel: true, + ..Default::default() + }; + assert_eq!(public_suffix(&bare, None).unwrap_err(), PICK_DEFAULT_DOMAIN); + assert!(!PICK_DEFAULT_DOMAIN.contains(';')); + } + #[test] fn new_domains_redirect_only_where_the_internet_reaches() { let d = new_domain("web-pr-42.203.0.113.7.nip.io", "http"); diff --git a/crates/pyo-api/src/ratelimit.rs b/crates/pyo-api/src/ratelimit.rs index f595d5da..d1efc9ee 100644 --- a/crates/pyo-api/src/ratelimit.rs +++ b/crates/pyo-api/src/ratelimit.rs @@ -264,6 +264,28 @@ impl Cidr { } } +/// Its network address, then the prefix length unless it's one address: +/// "198.51.100.0/24", "2001:db8::1". +impl std::fmt::Display for Cidr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let (net, max) = match self.net { + IpAddr::V4(n) => { + let mask = u32::MAX.checked_shl(32 - self.len).unwrap_or(0); + (IpAddr::V4((u32::from(n) & mask).into()), 32) + } + IpAddr::V6(n) => { + let mask = u128::MAX.checked_shl(128 - self.len).unwrap_or(0); + (IpAddr::V6((u128::from(n) & mask).into()), 128) + } + }; + if self.len == max { + write!(f, "{net}") + } else { + write!(f, "{net}/{}", self.len) + } + } +} + /// k3s's pod network, where the gateway's proxies run. const DEFAULT_TRUSTED_PROXIES: &str = "10.42.0.0/16,2001:cafe:42::/56"; diff --git a/crates/pyo-api/src/recovery.rs b/crates/pyo-api/src/recovery.rs index 99163fcd..96f6d061 100644 --- a/crates/pyo-api/src/recovery.rs +++ b/crates/pyo-api/src/recovery.rs @@ -19,7 +19,9 @@ //! password: a link alone is one factor. Except a link made on the server //! itself, which turns two-factor off (whoever has the server has //! everything anyway, and it's how someone who lost their app and their -//! recovery codes gets back in). +//! recovery codes gets back in). For an admin it also turns off where +//! admins may sign in from (admin_sign_in.rs): elsewhere an admin's link +//! answers as a used one. use crate::error::Json; use crate::error::Query; @@ -174,6 +176,7 @@ struct ResetBody { async fn reset( State(state): State, ClientIp(ip): ClientIp, + from: crate::admin_sign_in::Source, headers: HeaderMap, jar: CookieJar, Json(body): Json, @@ -209,6 +212,27 @@ async fn reset( must_set_up, key: None, }; + if user.is_admin { + if clears_two_factor { + // Made on the server: the admin sign-in limit goes too, so the + // admin who locked themselves out gets back in. + if crate::admin_sign_in::turn_off(&mut tx).await? { + crate::twofactor::notify_teams( + &mut tx, + &user, + "auth.admin_sign_in_off", + "Let admins sign in from anywhere with a sign-in link from the server", + ) + .await?; + } + } else if !crate::admin_sign_in::admits(&mut *tx, &from).await? { + // From where admins may not sign in: as a used link, and + // nothing changes (the link still works where they may). + tx.rollback().await?; + crate::admin_sign_in::refused(&state, &user, &from, "with a sign-in link").await; + return Err(used_or_expired()); + } + } let had_two_factor = crate::twofactor::enabled(&mut *tx, &user.id).await?; if clears_two_factor && had_two_factor { crate::twofactor::turn_off(&mut tx, &user.id).await?; diff --git a/crates/pyo-api/src/routes.rs b/crates/pyo-api/src/routes.rs index a29e4654..75a07f3e 100644 --- a/crates/pyo-api/src/routes.rs +++ b/crates/pyo-api/src/routes.rs @@ -36,6 +36,11 @@ pub fn domain_specs(domains: &Value) -> Vec { redirect_https: d["redirectHttps"].as_bool().unwrap_or(true), port_name: s(d, "portName"), hostname, + // Through the cluster's Cloudflare Tunnel (cloudflare/tunnel.rs). + tunnel: match d["tunnel"].as_str() { + Some(t @ (pyo_proto::TUNNEL_SWITCHING | pyo_proto::TUNNEL_ON)) => t.to_owned(), + _ => String::new(), + }, } }) .collect() @@ -114,6 +119,24 @@ pub async fn changed( Ok(Some(cluster_id)) } +/// [`changed`], with the routes sync's command (to wait for the agent to +/// have it): (cluster, command id). None when nothing was queued (the +/// service never ran, or is being deleted). +pub async fn changed_waiting( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, +) -> ApiResult> { + sqlx::query("UPDATE pyo.services SET routes_revision = routes_revision + 1 WHERE id = $1") + .bind(service_id) + .execute(&mut **tx) + .await?; + let Some((cluster_id, target)) = target(tx, service_id).await? else { + return Ok(None); + }; + let id = crate::deploy::enqueue(tx, &cluster_id, Command::SyncRoutes(Box::new(target))).await?; + Ok(Some((cluster_id, id))) +} + /// What a routes sync applies: the live deployment's service and ports (or, /// before its first rollout is done, that rollout's), its domains, firewall /// and WAF as they are now. None for a service never deployed (its first diff --git a/crates/pyo-api/src/sandbox/edgecert/tests.rs b/crates/pyo-api/src/sandbox/edgecert/tests.rs index c1900924..1c135370 100644 --- a/crates/pyo-api/src/sandbox/edgecert/tests.rs +++ b/crates/pyo-api/src/sandbox/edgecert/tests.rs @@ -67,9 +67,6 @@ impl Cf { } impl Cloudflare for Arc { - async fn zones(&self) -> Result, CfError> { - Ok(vec![(ZONE.into(), "example.com".into())]) - } async fn records(&self, zone_id: &str, name: &str) -> Result, CfError> { assert_eq!(zone_id, ZONE); Ok(self.named(name)) @@ -434,9 +431,6 @@ async fn a_wildcard_certificate_through_dns01() { struct Dropping(Arc); impl Cloudflare for Dropping { - async fn zones(&self) -> Result, CfError> { - self.0.zones().await - } async fn records(&self, z: &str, n: &str) -> Result, CfError> { self.0.records(z, n).await } @@ -481,9 +475,6 @@ async fn a_failed_challenge_still_cleans_up() { struct Refusing; impl Cloudflare for Refusing { - async fn zones(&self) -> Result, CfError> { - Ok(vec![]) - } async fn records(&self, _: &str, _: &str) -> Result, CfError> { Ok(vec![]) } diff --git a/crates/pyo-api/src/sandbox/join.rs b/crates/pyo-api/src/sandbox/join.rs index 00116ba7..2f136647 100644 --- a/crates/pyo-api/src/sandbox/join.rs +++ b/crates/pyo-api/src/sandbox/join.rs @@ -536,13 +536,14 @@ mod tests { render(&pick(Some("https://mirror.example.com/"))) .starts_with("curl -fsSL https://mirror.example.com/sandbox.sh | bash -s -- ") ); - // Else this release's sandbox.sh on pyo.dev. + // Else this release's published sandbox.sh: on pyo.dev, or a + // release candidate's on GitHub. for unset in [None, Some(" ")] { let c = render(&pick(unset)); assert!( c.starts_with(&format!( - "curl -fsSL https://pyo.dev/v/{}/sandbox.sh | bash -s -- ", - env!("CARGO_PKG_VERSION") + "curl -fsSL {}/sandbox.sh | bash -s -- ", + crate::join::published_scripts_url() )) && c.contains(" --version '0.4.0'"), "{c}" ); diff --git a/crates/pyo-api/src/sandbox/mod.rs b/crates/pyo-api/src/sandbox/mod.rs index f03e1474..fb4e38e4 100644 --- a/crates/pyo-api/src/sandbox/mod.rs +++ b/crates/pyo-api/src/sandbox/mod.rs @@ -1558,7 +1558,7 @@ pub struct AddCloudServer { pub provider: Option, /// A location's `name` from getCloudOptions ("fsn1"). pub location: String, - /// A server type's `name` from getCloudOptions ("cx22"). + /// A server type's `name` from getCloudOptions ("cx23"). pub server_type: String, /// A domain whose wildcard points at the server, as for /// `addSandboxServer`. diff --git a/crates/pyo-api/src/snapshot.rs b/crates/pyo-api/src/snapshot.rs index 4325215d..b2deafff 100644 --- a/crates/pyo-api/src/snapshot.rs +++ b/crates/pyo-api/src/snapshot.rs @@ -80,6 +80,12 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult = std::collections::HashSet::new(); let mut waf_active: std::collections::HashSet = std::collections::HashSet::new(); let syncing = crate::bundles::syncing_firewall(&mut *db, &ids).await?; + // Clusters whose databases restart once their install is this Pyo's + // (the cluster settings say so by the refresh command). + let databases_restart = crate::bundles::databases_restart(&mut *db, &ids).await?; for c in &mut clusters { + if c["id"].as_str().is_some_and(|id| databases_restart.contains(id)) { + c["databasesRestart"] = json!(true); + } waf_rejected.extend( c["capabilities"]["wafRejected"] .as_array() @@ -215,6 +229,8 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult ApiResult Value { // Whether its install is this Pyo's (install.rs): the cluster // settings' "Updating" and "Update needed". "agentInstall": or("agentInstall", Value::Null), + // Its agent runs Cloudflare Tunnel connectors. + "tunnel": or("tunnel", json!(false)), }) } diff --git a/crates/pyo-api/src/teambackup.rs b/crates/pyo-api/src/teambackup.rs index ed76ecbc..eb4b30e5 100644 --- a/crates/pyo-api/src/teambackup.rs +++ b/crates/pyo-api/src/teambackup.rs @@ -479,7 +479,8 @@ fn secret_fields(cmd: &mut Value) -> Vec<&mut Value> { } ("tailscale_setup", "token") | ("tailscale_client", "secret") - | ("sandbox_call", "token") => out.push(v), + | ("sandbox_call", "token") + | ("tunnel_set", "token") => out.push(v), ("backup", "connection") | ("db_setup", "admin") => { if let Some(p) = v.get_mut("password") { out.push(p); @@ -505,11 +506,14 @@ pub async fn seal_command(team_id: &str, cmd: &mut Value) -> anyhow::Result<()> } /// A command whose secret fields are of no more use once it's answered -/// (Tailscale's token and client secret): blanked, so Pyo's database keeps -/// no Tailscale credential, not even sealed. +/// (Tailscale's token and client secret, a Cloudflare Tunnel's token): +/// blanked, so Pyo's database keeps no such credential, not even sealed. pub fn wipe_command(cmd: &mut Value) -> bool { let kind = cmd["kind"].as_str().unwrap_or("").to_owned(); - if !matches!(kind.as_str(), "tailscale_setup" | "tailscale_client" | "sandbox_call") { + if !matches!( + kind.as_str(), + "tailscale_setup" | "tailscale_client" | "sandbox_call" | "tunnel_set" + ) { return false; } for v in secret_fields(cmd) { @@ -1097,6 +1101,29 @@ mod tests { } } + /// The tunnel's token: sealed while queued, wiped once answered, as the + /// command reaches the database. + #[test] + fn the_tunnel_token_is_sealed_then_wiped() { + let c = Command::TunnelSet { + tunnel_id: "c1744f8b-faa1-48a4-9e5c-02ac921467fa".into(), + token: "eyJhIjoiYiJ9".into(), + }; + let mut v = serde_json::to_value(&c).unwrap(); + assert_eq!(v["kind"], "tunnel_set"); + let found: Vec = secret_fields(&mut v) + .into_iter() + .map(|v| v.as_str().unwrap().to_owned()) + .collect(); + assert_eq!(found, ["eyJhIjoiYiJ9"]); + assert!(wipe_command(&mut v)); + assert_eq!(v["token"], ""); + assert_eq!(v["tunnel_id"], "c1744f8b-faa1-48a4-9e5c-02ac921467fa"); + let mut remove = serde_json::to_value(Command::TunnelRemove {}).unwrap(); + assert!(secret_fields(&mut remove).is_empty()); + assert!(!wipe_command(&mut remove)); + } + #[test] fn repository_paths() { let cfg = backup::Settings { diff --git a/crates/pyo-api/src/teams_rls_tests.rs b/crates/pyo-api/src/teams_rls_tests.rs index ad9d782e..e861d5ab 100644 --- a/crates/pyo-api/src/teams_rls_tests.rs +++ b/crates/pyo-api/src/teams_rls_tests.rs @@ -23,7 +23,7 @@ use crate::teamsec_tests::{Client, run_big}; /// Pyo's tables owned by a login that's neither a superuser nor bypasses /// row security, in a database of its own, as on Pyo Cloud. Dropped by /// [`drop_db`]. -async fn cloud_db() -> (PgPool, String) { +pub(crate) async fn cloud_db() -> (PgPool, String) { let opts: PgConnectOptions = std::env::var("DATABASE_URL") .expect("DATABASE_URL") .parse() @@ -70,7 +70,7 @@ async fn cloud_db() -> (PgPool, String) { (db, name) } -async fn drop_db(db: PgPool, name: &str) { +pub(crate) async fn drop_db(db: PgPool, name: &str) { db.close().await; let admin = PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) .await @@ -83,7 +83,7 @@ async fn drop_db(db: PgPool, name: &str) { .unwrap(); } -async fn installation_db() -> PgPool { +pub(crate) async fn installation_db() -> PgPool { let db = PgPool::connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL")) .await .unwrap(); diff --git a/crates/pyo-api/src/twofactor.rs b/crates/pyo-api/src/twofactor.rs index 8212abb0..78b43a87 100644 --- a/crates/pyo-api/src/twofactor.rs +++ b/crates/pyo-api/src/twofactor.rs @@ -322,9 +322,17 @@ struct CodeBody { code: String, } +fn wrong_code() -> ApiError { + ApiError::new( + axum::http::StatusCode::UNAUTHORIZED, + "That code didn't work. Try the newest one.", + ) +} + async fn login_code( State(state): State, ClientIp(ip): ClientIp, + from: crate::admin_sign_in::Source, headers: HeaderMap, jar: CookieJar, Json(body): Json, @@ -357,6 +365,11 @@ async fn login_code( .bind(&user_id) .fetch_one(&state.db) .await?; + // An admin from where admins may not sign in: as a wrong code, before + // the code (a recovery code stays unused). + if !crate::admin_sign_in::sign_in_allowed(&state, &user, &from, "with a code").await? { + return Err(wrong_code()); + } let Some(used) = verify(&state, &user_id, &ip, &body.code).await? else { audit::account_event( &state.db, @@ -370,10 +383,7 @@ async fn login_code( }, ) .await; - return Err(ApiError::new( - axum::http::StatusCode::UNAUTHORIZED, - "That code didn't work. Try the newest one.", - )); + return Err(wrong_code()); }; sqlx::query("DELETE FROM pyo.sign_in_challenges WHERE token_hash = $1") .bind(&hash) diff --git a/crates/pyo-api/src/updates.rs b/crates/pyo-api/src/updates.rs index d70fb669..e17cb4a7 100644 --- a/crates/pyo-api/src/updates.rs +++ b/crates/pyo-api/src/updates.rs @@ -72,20 +72,52 @@ fn newer(a: &str, b: &str) -> bool { matches!((parse_version(a), parse_version(b)), (Some(a), Some(b)) if a > b) } -/// Said before an update whose agent has other roles than this Pyo's: no -/// agent can change its own roles, so each cluster's connect command does. +/// Said before an update whose agent has other roles than this Pyo's, on +/// an installation whose clusters don't have the self-update role: their +/// agents can't change their own roles, so each cluster's connect command +/// does. pub const RECONNECT_NOTICE: &str = "After updating, run the connect command shown in each cluster's settings."; /// What to know before updating to `r`: its notices, and [`RECONNECT_NOTICE`] /// when its agent's roles aren't this Pyo's (a release that doesn't say -/// isn't assumed to change them). -pub fn before_you_update(r: &Release) -> Vec { +/// isn't assumed to change them) and this installation's clusters can't +/// bring them by themselves. `own_server_only`: its only cluster is the +/// one Pyo runs on ([`own_server_only`]). +pub fn before_you_update(r: &Release, own_server_only: bool) -> Vec { + notices(r, crate::install::self_update(), own_server_only) +} + +/// Whether every cluster of the installation is the one Pyo runs on, kept +/// current by its own server (install.rs `host_refreshes`): nobody has a +/// connect command to run after an update. +fn own_server_only(clusters: &[ClusterRow], self_update: bool) -> bool { + clusters.iter().all(|c| { + c.scope + .clone() + .and_then(|v| serde_json::from_value::(v).ok()) + .is_some_and(|scope| { + crate::install::host_refreshes(c.same_cluster, self_update, &scope, "outdated") + }) + }) +} + +/// [`before_you_update`], for an installation whose clusters have the +/// self-update role (`self_update`) or not. With it their agents write the +/// new roles themselves, so nothing is added: a release that needs the +/// command anyway (a new role object, a chart installed with the agent) +/// says so in its own notices, with [`RECONNECT_NOTICE`]. That line is +/// left out where Pyo's own server is the only cluster +/// (`own_server_only`): it runs the command by itself. +fn notices(r: &Release, self_update: bool, own_server_only: bool) -> Vec { let mut out = r.before_you_update.clone(); - let reconnect = r - .agent_access - .as_deref() - .is_some_and(|h| h != pyo_proto::rbac::access_hash()); + if self_update && own_server_only { + out.retain(|n| n != RECONNECT_NOTICE); + } + let reconnect = !self_update + && r.agent_access + .as_deref() + .is_some_and(|h| h != pyo_proto::rbac::access_hash()); if reconnect && !out.iter().any(|n| n == RECONNECT_NOTICE) { out.push(RECONNECT_NOTICE.into()); } @@ -586,20 +618,31 @@ async fn new_migrations(db: &PgPool, release: &Release) -> ApiResult /// Why `release` can't be started now, if it can't. fn blockers(release: &Release, clusters: &[ClusterRow], active: bool) -> Vec { + blockers_from(current(), release, clusters, active) +} + +/// [`blockers`] for a Pyo on `pyo`. A release candidate's version isn't +/// one updates compare, so tests name a release. +fn blockers_from( + pyo: &str, + release: &Release, + clusters: &[ClusterRow], + active: bool, +) -> Vec { let mut out = vec![]; if active { out.push("An update is already running.".into()); } - if !release.allows_from(current()) { + if !release.allows_from(pyo) { out.push(format!( "Pyo {} can't update straight to {}: update to {} first. On the server, run: curl -fsSL https://pyo.dev/install.sh | bash -s -- --version {}", - current(), + pyo, release.version, release.min_from.as_deref().unwrap_or("?"), release.min_from.as_deref().unwrap_or("?"), )); } - if newer(&release.version, current()) { + if newer(&release.version, pyo) { match clusters.iter().find(|c| c.same_cluster) { None => out.push("Pyo updates itself through an agent on the cluster it runs on, and there's none. Connect this machine as a cluster, or on the server run: curl -fsSL https://pyo.dev/install.sh | bash".into()), Some(c) if c.updates < 1 => out.push(format!("The agent on {} is too old to update Pyo. Update once on the server with: curl -fsSL https://pyo.dev/install.sh | bash (later releases can be applied here)", c.name)), @@ -687,6 +730,12 @@ pub async fn snapshot(db: &PgPool) -> ApiResult { platform_images.sort(); platform_images.dedup(); let migrations = new_migrations(db, r).await?; + // Databases that run another image on the release restart once. + let databases_restart = if pyo_needed { + crate::bundles::restart_count(db, &r.database_images()).await? + } else { + 0 + }; let agents_needed = agents.iter().any(|a| { a["needed"] == json!(true) && a["canUpdate"] == json!(true) && a["online"] == json!(true) }); @@ -717,7 +766,7 @@ pub async fn snapshot(db: &PgPool) -> ApiResult { "url": found.url, "publishedAt": found.published_at, "notes": found.notes, - "beforeYouUpdate": if pyo_needed { before_you_update(r) } else { r.before_you_update.clone() }, + "beforeYouUpdate": if pyo_needed { before_you_update(r, own_server_only(&all, crate::install::self_update())) } else { r.before_you_update.clone() }, "manualOnly": r.manual_only, "minFrom": r.min_from, }); @@ -730,6 +779,7 @@ pub async fn snapshot(db: &PgPool) -> ApiResult { "builders": builders, "migrations": migrations, "platformImages": platform_images, + "databasesRestart": databases_restart, "images": r.images, }); Ok(out) @@ -1775,11 +1825,34 @@ mod tests { } } + /// Nobody has a connect command to run where the only cluster is the + /// one Pyo runs on and its server keeps it current. + #[test] + fn an_installation_of_pyo_s_own_server_only() { + let with = |same: bool, scope: Value| ClusterRow { scope: Some(scope), ..cluster(same, 1, true) }; + let kept = json!({ "access": "limited", "admission": "enforced", "selfUpdate": true }); + let own = with(true, kept.clone()); + assert!(own_server_only(&[], true)); + assert!(own_server_only(&[with(true, kept.clone())], true)); + // Another cluster beside it, or Pyo Cloud. + assert!(!own_server_only(&[own, with(false, kept.clone())], true)); + assert!(!own_server_only(&[with(true, kept.clone())], false)); + // Its owner took the self-update role away or made it read only, + // or its agent doesn't say. + let plain = json!({ "access": "limited", "admission": "enforced" }); + let read_only = json!({ "access": "limited", "admission": "enforced", "selfUpdate": true, "policy": { "readOnly": true } }); + assert!(!own_server_only(&[with(true, plain)], true)); + assert!(!own_server_only(&[with(true, read_only)], true)); + assert!(!own_server_only(&[cluster(true, 1, true)], true)); + } + /// An update whose agent has other roles says, before it starts, that /// each cluster needs its connect command; one with the same roles, or - /// a release that doesn't say, doesn't. + /// a release that doesn't say, doesn't. Nor does an installation whose + /// agents bring their roles themselves. #[test] fn other_agent_roles_ask_for_the_connect_command() { + let before_you_update = |r: &Release| notices(r, false, false); let with = |access: Option, notices: &[&str]| Release { version: "99.0.0".into(), agent_access: access, @@ -1801,10 +1874,33 @@ mod tests { before_you_update(&with(Some("0000000000000000".into()), &[RECONNECT_NOTICE])), [RECONNECT_NOTICE] ); + // With the self-update role the agents write the new roles: only + // the release's own notices. + assert_eq!( + notices(&with(Some("0000000000000000".into()), &["Postgres restarts."]), true, false), + ["Postgres restarts."] + ); + assert_eq!( + notices(&with(Some("0000000000000000".into()), &[RECONNECT_NOTICE]), true, false), + [RECONNECT_NOTICE] + ); + // Pyo's own server is the only cluster: it runs the command by + // itself, so the release's line isn't shown. Its other notices are. + let both = with(Some("0000000000000000".into()), &["Postgres restarts.", RECONNECT_NOTICE]); + assert_eq!(notices(&both, true, true), ["Postgres restarts."]); + assert_eq!(notices(&both, true, false), ["Postgres restarts.", RECONNECT_NOTICE]); + // Without the self-update role nothing runs it there (Pyo Cloud). + assert_eq!(notices(&both, false, true), ["Postgres restarts.", RECONNECT_NOTICE]); + assert_eq!( + notices(&with(Some("0000000000000000".into()), &[]), false, true), + [RECONNECT_NOTICE] + ); } #[test] fn what_stops_an_update() { + let blockers = + |r: &Release, c: &[ClusterRow], active: bool| blockers_from("0.51.0", r, c, active); let r = Release { version: "99.0.0".into(), ..Default::default() @@ -1833,7 +1929,9 @@ mod hosted_tests { fn only_older_agents_are_behind() { let v = current(); assert!(!agent_behind(v)); - assert!(agent_behind("0.0.1")); + // A release candidate isn't a version updates compare, so it moves + // no agent. + assert_eq!(agent_behind("0.0.1"), parse_version(v).is_some()); assert!(!agent_behind("99.0.0")); // A build with no version is left alone. assert!(!agent_behind("")); diff --git a/crates/pyo-cli/Cargo.toml b/crates/pyo-cli/Cargo.toml index 82354f8c..26685c56 100644 --- a/crates/pyo-cli/Cargo.toml +++ b/crates/pyo-cli/Cargo.toml @@ -22,6 +22,7 @@ ignore = "0.4" jsonc-parser = { version = "0.34.0", features = ["cst", "serde"] } rand = "0.10.3" reqwest = { version = "0.13.5", default-features = false, features = ["json", "query", "rustls", "stream"] } +rustls = { version = "0.23.46", default-features = false, features = ["aws_lc_rs", "std"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" serde_path_to_error = "0.1.20" diff --git a/crates/pyo-cli/src/cloudflare.rs b/crates/pyo-cli/src/cloudflare.rs index 57cd139b..0ae3232b 100644 --- a/crates/pyo-cli/src/cloudflare.rs +++ b/crates/pyo-cli/src/cloudflare.rs @@ -36,7 +36,7 @@ fn read_token(file: Option<&str>, env: Option) -> Result { let t = t.trim().to_owned(); if t.is_empty() { bail!( - "Give the token in a file (--token-file, - for stdin) or in CLOUDFLARE_API_TOKEN. It needs Zone:Read and DNS:Edit." + "Give the token in a file (--token-file, - for stdin) or in CLOUDFLARE_API_TOKEN. It needs Zone:Read and DNS:Edit, and for Cloudflare Tunnel also Cloudflare Tunnel:Edit and SSL and Certificates:Edit." ); } Ok(t) @@ -54,18 +54,41 @@ fn print_zones(zones: &Value) { .chain([4]) .max() .unwrap_or(4); - println!("{}", ui::dim(&format!("{: String { + let missing: Vec<&str> = t["missing"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + if t["ready"] == json!(true) { + ui::green("ready") + } else if missing.len() == 1 { + ui::yellow(&format!("needs {}", missing[0])) + } else { + ui::dim("DNS only") } } @@ -235,6 +258,213 @@ pub async fn domain_dns( .await } +// ── Cloudflare Tunnel ────────────────────────────────────────────────────── + +/// The cluster (name or id, else the team's default) a tunnel command is about. +async fn cluster_of(api: &Api, team: Option<&str>, cluster: Option<&str>) -> Result<(String, String)> { + let (_, id) = crate::compose::team_and_cluster(api, team, cluster).await?; + let state = api.state().await?; + let name = state + .cluster(&id) + .and_then(|c| c["name"].as_str()) + .unwrap_or(&id) + .to_owned(); + Ok((id, name)) +} + +/// A tunnel's state in one line, as the dashboard says it. +pub fn tunnel_line(t: &Value) -> String { + let n = t["connectors"].as_array().map_or(0, Vec::len); + let ready = t["connectors"] + .as_array() + .into_iter() + .flatten() + .filter(|c| c["ready"] == json!(true)) + .count(); + let colos: Vec<&str> = t["colos"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + match t["health"].as_str().unwrap_or("unknown") { + "connected" if colos.is_empty() => format!("Tunnel connected · {ready} connectors"), + "connected" => format!("Tunnel connected · {ready} connectors · {}", colos.join(", ")), + "degraded" => format!("Tunnel degraded · {ready} of {n} connectors"), + "down" => "Tunnel down. Its websites don't answer.".into(), + "starting" => "Starting the tunnel…".into(), + "removing" => "Removing the tunnel…".into(), + _ => "Pyo can't reach Cloudflare. Websites keep working.".into(), + } +} + +pub async fn tunnel_status(api: &Api, team: Option<&str>, cluster: Option<&str>) -> Result<()> { + let (id, name) = cluster_of(api, team, cluster).await?; + let v = api.get(&format!("/clusters/{id}/tunnel")).await?; + println!("{name}: traffic {}", v["traffic"].as_str().unwrap_or("public")); + let t = &v["tunnel"]; + if t.is_null() { + println!("No Cloudflare Tunnel. Turn it on: pyo cloudflare tunnel on --cluster {name}"); + return Ok(()); + } + println!("{}", tunnel_line(t)); + if let Some(e) = t["error"].as_str() { + println!("{}", ui::yellow(e)); + } + if t["refused"] == json!(true) { + println!( + "{}", + ui::yellow("Run the command under Refresh this cluster in the cluster's settings.") + ); + } + for c in t["connectors"].as_array().into_iter().flatten() { + let server = c["server"].as_str().unwrap_or("?"); + match c["reason"].as_str() { + Some(r) if c["ready"] != json!(true) => println!(" {server} {}", ui::red(r)), + _ if c["ready"] == json!(true) => println!(" {server} {}", ui::green("ready")), + _ => println!(" {server} {}", ui::dim("starting")), + } + } + if let Some(d) = t["defaultDomain"].as_str() { + println!("Default domain: *.{d}"); + } + // Each domain through it, from the snapshot. + let state = api.state().await?; + for s in state.services().iter().filter(|s| s["clusterId"] == json!(id)) { + for d in s["domains"].as_array().into_iter().flatten() { + let Some(state) = d["tunnel"].as_str() else { + continue; + }; + let host = d["hostname"].as_str().unwrap_or(""); + let rec = &d["dnsRecord"]; + let what = match (state, rec["status"].as_str()) { + (_, Some("conflict")) => ui::yellow("waiting for --replace"), + (_, Some("reverting")) => ui::dim("switching back"), + ("on", _) => ui::green("via Tunnel"), + _ => ui::dim("switching"), + }; + println!(" {host} {what}"); + } + } + Ok(()) +} + +pub async fn tunnel_on( + api: &Api, + team: Option<&str>, + cluster: Option<&str>, + default_domain: Option<&str>, + account: Option<&str>, + ports_public: bool, +) -> Result<()> { + let (id, name) = cluster_of(api, team, cluster).await?; + let v = api + .op( + "setClusterTraffic", + json!({ "clusterId": id, "mode": "tunnel", "defaultDomain": default_domain, "accountId": account, "portsPublic": ports_public }), + ) + .await?; + ui::ok(&format!("{name} takes websites through Cloudflare Tunnel")); + let moving = v["moving"].as_u64().unwrap_or(0); + if moving > 0 { + println!("{moving} domains are moving. See them: pyo cloudflare tunnel status --cluster {name}"); + } + Ok(()) +} + +pub async fn tunnel_off(api: &Api, team: Option<&str>, cluster: Option<&str>, to: &str) -> Result<()> { + if !matches!(to, "public" | "tailscale") { + bail!("--to is public or tailscale."); + } + let (id, name) = cluster_of(api, team, cluster).await?; + api.op("setClusterTraffic", json!({ "clusterId": id, "mode": to })) + .await?; + ui::ok(&format!( + "{name} takes traffic {}", + if to == "public" { "on public ports" } else { "from Tailscale only" } + )); + println!("Domains keep using the tunnel until you move them back: pyo domain tunnel --back"); + Ok(()) +} + +pub async fn tunnel_remove( + api: &Api, + team: Option<&str>, + cluster: Option<&str>, + restore: bool, + yes: bool, +) -> Result<()> { + let (id, name) = cluster_of(api, team, cluster).await?; + if !yes { + let a = ui::ask(&format!("Remove the Cloudflare Tunnel of {name}? [y/N] "))?; + if !a.eq_ignore_ascii_case("y") { + bail!("Not removed."); + } + } + api.op( + "removeClusterTunnel", + json!({ "clusterId": id, "restoreRecords": restore }), + ) + .await?; + ui::ok("Removing the tunnel. Pyo deletes only the records it made."); + Ok(()) +} + +pub async fn tunnel_rotate(api: &Api, team: Option<&str>, cluster: Option<&str>) -> Result<()> { + let (id, name) = cluster_of(api, team, cluster).await?; + api.op("rotateTunnelToken", json!({ "clusterId": id })) + .await?; + ui::ok(&format!("{name}'s tunnel gets a new token and certificate")); + Ok(()) +} + +/// `pyo domain tunnel`: a domain through the tunnel, or back. +pub async fn domain_tunnel( + api: &Api, + service: Option<&str>, + hostname: &str, + on: bool, + replace: bool, + restore: bool, +) -> Result<()> { + let t = crate::service::target(api, service).await?; + let host = hostname.trim().trim_end_matches('.').to_lowercase(); + let d = t.service()["domains"] + .as_array() + .into_iter() + .flatten() + .find(|d| d["hostname"] == json!(host)) + .with_context(|| format!("{host} isn't one of {}'s domains.", t.state.path_of(t.service())))?; + // A record already in the way, from an earlier try. + let rec = &d["dnsRecord"]; + if on && !replace && rec["status"] == json!("conflict") { + println!("{}", ui::yellow(&format!("Cloudflare has a record for {host}:"))); + for r in rec["existing"].as_array().into_iter().flatten() { + println!( + " {} {} {}", + r["type"].as_str().unwrap_or(""), + r["name"].as_str().unwrap_or(""), + r["content"].as_str().unwrap_or("") + ); + } + bail!("Run again with --replace to replace it. Pyo keeps a copy."); + } + let v = api + .op( + "setDomainTunnel", + json!({ "serviceId": t.id, "domainId": d["id"], "on": on, "replace": replace, "restore": restore }), + ) + .await?; + match v["status"].as_str().unwrap_or("") { + "active" if !on => ui::ok(&format!("{host} stays on the tunnel, under its default domain")), + "active" => ui::ok(&format!("{host} goes through the tunnel")), + "switching" => ui::ok(&format!("Switching {host} to the tunnel. If Cloudflare has a record Pyo didn't make, pyo cloudflare tunnel status shows it.")), + "reverting" => ui::ok(&format!("Switching {host} back")), + _ => ui::ok(&format!("{host} doesn't go through the tunnel")), + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -253,6 +483,31 @@ mod tests { assert_eq!(zone_for(&s, "t2", "a.example.com"), None); } + #[test] + fn the_tunnel_column_says_what_a_zone_can_do() { + let plain = |t: Value| { + tunnel_column(&t) + .chars() + .filter(|c| !c.is_control()) + .collect::() + }; + assert!(plain(json!({ "ready": true })).contains("ready")); + assert!(plain(json!({ "ready": false, "missing": ["SSL and Certificates:Edit"] })).contains("needs SSL and Certificates:Edit")); + assert!(plain(json!({ "ready": false, "missing": ["a", "b"] })).contains("DNS only")); + // Stored before the tunnel: DNS only. + assert!(plain(Value::Null).contains("DNS only")); + } + + #[test] + fn tunnel_lines() { + let t = json!({ "health": "connected", "colos": ["AMS", "FRA"], "connectors": [{ "ready": true }, { "ready": true }] }); + assert_eq!(tunnel_line(&t), "Tunnel connected · 2 connectors · AMS, FRA"); + let t = json!({ "health": "degraded", "connectors": [{ "ready": true }, { "ready": false }] }); + assert_eq!(tunnel_line(&t), "Tunnel degraded · 1 of 2 connectors"); + assert_eq!(tunnel_line(&json!({ "health": "down" })), "Tunnel down. Its websites don't answer."); + assert_eq!(tunnel_line(&json!({})), "Pyo can't reach Cloudflare. Websites keep working."); + } + #[test] fn tokens_come_from_a_file_or_the_environment() { assert_eq!(read_token(None, Some(" abc \n".into())).unwrap(), "abc"); diff --git a/crates/pyo-cli/src/compose.rs b/crates/pyo-cli/src/compose.rs index a94d0689..a0f96808 100644 --- a/crates/pyo-cli/src/compose.rs +++ b/crates/pyo-cli/src/compose.rs @@ -1,6 +1,9 @@ -//! `pyo deploy -f compose.yml`: import a Docker Compose file as a project. -//! Pyo shows what it makes of the file (and what it leaves out), then -//! creates and deploys it once you say yes. +//! `pyo deploy -f compose.yml`: a Docker Compose file as a project. The +//! first time, Pyo shows what it makes of the file (and what it leaves out), +//! then creates and deploys it once you say yes. After that, the same +//! command syncs the project with the file: Pyo shows what changes and +//! applies only that. `--dry-run` only shows it, and `--prune` also deletes +//! the services no longer in the file. use std::path::Path; @@ -9,13 +12,17 @@ use serde_json::{Value, json}; use crate::{api::Api, ui}; -pub async fn deploy( - api: &Api, - file: &Path, - team: Option<&str>, - cluster: Option<&str>, - yes: bool, -) -> Result<()> { +pub struct Opts<'a> { + pub team: Option<&'a str>, + pub cluster: Option<&'a str>, + /// The project to sync into (name, namespace or id). + pub project: Option<&'a str>, + pub dry_run: bool, + pub prune: bool, + pub yes: bool, +} + +pub async fn deploy(api: &Api, file: &Path, o: Opts<'_>) -> Result<()> { let text = std::fs::read_to_string(file) .with_context(|| format!("Couldn't read {}", file.display()))?; let dir = file @@ -27,16 +34,107 @@ pub async fn deploy( .ok() .and_then(|d| d.file_name().map(|n| n.to_string_lossy().into_owned())) .unwrap_or_default(); + let file_name = file + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); - let (team_id, cluster_id) = team_and_cluster(api, team, cluster).await?; + let (team_id, cluster_id) = team_and_cluster(api, o.team, o.cluster).await?; + let project_id = match o.project { + Some(p) => Some(project_in(api, &team_id, p).await?), + None => None, + }; let plan = api - .post("/api/v1/compose/preview", &json!({ "teamId": team_id, "file": text, "env": env, "clusterId": cluster_id, "name": name })) + .post( + "/api/v1/compose/sync-plan", + &json!({ "teamId": team_id, "projectId": project_id, "file": text, "env": env, "clusterId": cluster_id, "name": name, "fileName": file_name }), + ) .await?; - print_plan(&plan); + if plan["project"].is_null() { + return import(api, &plan["file"], &team_id, &cluster_id, &o).await; + } + print_sync(&plan, o.prune); + let services = plan["services"].as_array().cloned().unwrap_or_default(); + let changing = services + .iter() + .filter(|s| matches!(s["status"].as_str(), Some("added" | "changed"))) + .count(); + let deleting = services + .iter() + .filter(|s| s["status"] == "notInFile" && s["fromFile"] == true && o.prune) + .count(); + if changing == 0 && deleting == 0 { + println!("Nothing to change."); + return Ok(()); + } + if o.dry_run { + println!("Dry run: nothing was changed."); + return Ok(()); + } + let project = plan["project"]["name"].as_str().unwrap_or("the project"); + if !o.yes { + let mut q = format!("Apply this to {project}?"); + if deleting > 0 { + q = format!( + "Apply this to {project} and delete {deleting} service{}?", + if deleting == 1 { "" } else { "s" } + ); + } + let a = ui::ask(&format!("{q} [y/N] "))?; + if !matches!(a.to_lowercase().as_str(), "y" | "yes") { + println!("Nothing was changed."); + return Ok(()); + } + } + let mut body = json!({ "projectId": plan["project"]["id"], "plan": plan["file"], "prune": o.prune, "confirm": o.yes }); + // New services run where the project's do, unless --cluster says. + if o.cluster.is_some() { + body["clusterId"] = json!(cluster_id); + } + let r = api.op("syncCompose", body).await?; + let mut deploying = false; + for s in r["services"].as_array().into_iter().flatten() { + let status = s["status"].as_str().unwrap_or(""); + let dep = s["deploymentId"].as_str().unwrap_or(""); + deploying |= !dep.is_empty(); + println!( + "{} {} {}", + ui::green("✓"), + s["name"].as_str().unwrap_or(""), + ui::dim(if dep.is_empty() { status } else { dep }) + ); + if let Some(w) = s["warning"].as_str() { + println!(" {} {w}", ui::yellow("!")); + } + } + if deploying { + ui::ok(&format!( + "Deploying. Follow it in the dashboard: {}", + api.base + )); + } else { + ui::ok("Done."); + } + Ok(()) +} + +/// The first time: a new project from the file. +async fn import( + api: &Api, + plan: &Value, + team_id: &str, + cluster_id: &str, + o: &Opts<'_>, +) -> Result<()> { + print_plan(plan); + if o.dry_run { + println!("Dry run: nothing was created."); + return Ok(()); + } let services = plan["services"].as_array().map(Vec::len).unwrap_or(0); - if !yes { + if !o.yes { if !std::io::IsTerminal::is_terminal(&std::io::stdin()) { bail!("No terminal to ask on: pass -y to confirm."); } @@ -71,6 +169,20 @@ pub async fn deploy( Ok(()) } +/// A project of the team by id, namespace or name. +async fn project_in(api: &Api, team_id: &str, p: &str) -> Result { + let state = api.state().await?; + state.0["projects"] + .as_array() + .into_iter() + .flatten() + .filter(|x| x["teamId"] == json!(team_id)) + .find(|x| x["id"] == json!(p) || x["namespace"] == json!(p) || x["name"] == json!(p)) + .and_then(|x| x["id"].as_str()) + .map(str::to_owned) + .with_context(|| format!("No project {p} in this team")) +} + /// The team (slug or id, else the first) and its cluster (name or id, else /// the team's default) an import goes to. pub async fn team_and_cluster( @@ -110,6 +222,98 @@ pub async fn team_and_cluster( Ok((team_id, cluster_id)) } +/// A sync plan, service by service. +pub fn sync_lines(plan: &Value, prune: bool) -> Vec { + let mut out = vec![]; + let file = plan["file"]["project"]["file"].as_str().unwrap_or(""); + out.push(format!( + "{} {}", + ui::bold(plan["project"]["name"].as_str().unwrap_or("")), + ui::dim(&format!( + "(synced with {})", + if file.is_empty() { "its Compose file" } else { file } + )) + )); + let mut manual = vec![]; + for s in plan["services"].as_array().into_iter().flatten() { + let name = s["name"].as_str().unwrap_or(""); + let from_file = s["fromFile"] == true; + let (mark, words) = match s["status"].as_str().unwrap_or("") { + "added" => (ui::green("+"), "added".to_owned()), + "changed" => (ui::yellow("~"), "changed".to_owned()), + "notInFile" if from_file && prune => { + (ui::red("-"), "not in the file, so it's deleted".to_owned()) + } + "notInFile" if from_file => ( + ui::red("-"), + "not in the file. --prune deletes it.".to_owned(), + ), + "notInFile" => (ui::dim("-"), "not in the file, kept".to_owned()), + _ => (ui::dim("="), "unchanged".to_owned()), + }; + out.push(format!(" {mark} {} {}", ui::bold(name), ui::dim(&words))); + for c in s["changes"].as_array().into_iter().flatten() { + let field = c["field"].as_str().unwrap_or(""); + let line = match (c["from"].as_str(), c["to"].as_str()) { + (Some(a), Some(b)) => format!("{field}: {a} → {b}"), + (None, Some(b)) => format!("{field}: {b}"), + _ => field.to_owned(), + }; + out.push(format!(" {line}")); + } + for n in s["notes"].as_array().into_iter().flatten() { + out.push(format!( + " {}", + ui::dim(&format!( + "{}: {}", + n["field"].as_str().unwrap_or(""), + n["message"].as_str().unwrap_or("") + )) + )); + } + for m in s["manual"].as_array().into_iter().flatten() { + manual.push(format!( + " {} {name}, {}: {}", + ui::yellow("!"), + m["field"].as_str().unwrap_or(""), + m["message"].as_str().unwrap_or("") + )); + } + } + if !manual.is_empty() { + out.push(ui::yellow("Pyo leaves these as they are. Change them by hand:")); + out.extend(manual); + } + out.extend(warning_lines(&plan["warnings"])); + out +} + +fn print_sync(plan: &Value, prune: bool) { + for l in sync_lines(plan, prune) { + println!("{l}"); + } +} + +fn warning_lines(warnings: &Value) -> Vec { + let warnings = warnings.as_array().cloned().unwrap_or_default(); + if warnings.is_empty() { + return vec![]; + } + let mut out = vec![ui::yellow("Not carried over, or changed:")]; + for w in warnings { + let who = w["service"] + .as_str() + .map(|s| format!("{s}: ")) + .unwrap_or_default(); + out.push(format!( + " {} {who}{}", + ui::yellow("!"), + w["message"].as_str().unwrap_or("") + )); + } + out +} + fn print_plan(plan: &Value) { println!( "{} {}", @@ -158,6 +362,16 @@ fn print_plan(plan: &Value) { }; println!(" {} {line}", ui::dim("port")); } + let domains: Vec<&str> = s["domains"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .skip(1) + .collect(); + if !domains.is_empty() { + println!(" {} {}", ui::dim("domains"), domains.join(", ")); + } for v in s["volumes"].as_array().into_iter().flatten() { println!( " {} {} at {} ({} GiB{})", @@ -176,20 +390,83 @@ fn print_plan(plan: &Value) { if env > 0 { println!(" {} {env}", ui::dim("variables")); } - } - let warnings = plan["warnings"].as_array().cloned().unwrap_or_default(); - if !warnings.is_empty() { - println!("{}", ui::yellow("Not carried over, or changed:")); - for w in warnings { - let who = w["service"] - .as_str() - .map(|s| format!("{s}: ")) - .unwrap_or_default(); + let secrets: Vec<&str> = s["secrets"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + if !secrets.is_empty() { println!( - " {} {who}{}", - ui::yellow("!"), - w["message"].as_str().unwrap_or("") + " {} {} {}", + ui::dim("secrets"), + secrets.join(", "), + ui::dim("(set their values in Pyo)") ); } } + for l in warning_lines(&plan["warnings"]) { + println!("{l}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plain(lines: Vec) -> String { + let text = lines.join("\n"); + // No colors in the comparison. + let mut out = String::new(); + let mut skip = false; + for c in text.chars() { + match (skip, c) { + (_, '\x1b') => skip = true, + (true, 'm') => skip = false, + (true, _) => {} + (false, c) => out.push(c), + } + } + out + } + + #[test] + fn a_sync_plan_reads_service_by_service() { + let plan = json!({ + "project": { "id": "prj_a", "name": "cloud", "namespace": "cloud" }, + "file": { "project": { "file": "compose.yaml" } }, + "services": [ + { "name": "cloud-api", "status": "changed", "fromFile": true, "deploy": true, + "changes": [ + { "field": "image", "from": "ghcr.io/acme/cloud-api:1.2", "to": "ghcr.io/acme/cloud-api:1.3" }, + { "field": "env LOG_LEVEL" }, + { "field": "domain api.example.com", "to": "added" }], + "notes": [{ "field": "env DATABASE_URL", "message": "It's a secret in Pyo, so its value stays." }], + "manual": [] }, + { "name": "worker", "status": "added", "changes": [], "notes": [], "manual": [] }, + { "name": "db", "status": "unchanged", "fromFile": true, "changes": [], "notes": [], + "manual": [{ "field": "volume db-data", "message": "It's mounted at /var/lib/postgresql/data in Pyo and /data in the file. Detach it and attach it at /data to move it." }] }, + { "name": "old", "status": "notInFile", "fromFile": true, "changes": [], "notes": [], "manual": [] }, + { "name": "hand", "status": "notInFile", "fromFile": false, "changes": [], "notes": [], "manual": [] } + ], + "warnings": [] + }); + let text = plain(sync_lines(&plan, false)); + assert_eq!( + text, + "cloud (synced with compose.yaml) + ~ cloud-api changed + image: ghcr.io/acme/cloud-api:1.2 → ghcr.io/acme/cloud-api:1.3 + env LOG_LEVEL + domain api.example.com: added + env DATABASE_URL: It's a secret in Pyo, so its value stays. + + worker added + = db unchanged + - old not in the file. --prune deletes it. + - hand not in the file, kept +Pyo leaves these as they are. Change them by hand: + ! db, volume db-data: It's mounted at /var/lib/postgresql/data in Pyo and /data in the file. Detach it and attach it at /data to move it." + ); + assert!(plain(sync_lines(&plan, true)).contains("- old not in the file, so it's deleted")); + } } diff --git a/crates/pyo-cli/src/domain.rs b/crates/pyo-cli/src/domain.rs index 071bb7af..0c91b202 100644 --- a/crates/pyo-cli/src/domain.rs +++ b/crates/pyo-cli/src/domain.rs @@ -265,7 +265,17 @@ pub async fn add( h } None if free => { - let ip = cluster_ip(&t, "freeDomainIp").context("The cluster has no address for free domains (its public or Tailscale IP, as its settings say), so there's no free domain for it. Use your own hostname.")?; + let tunnel = cluster_ip(&t, "traffic").as_deref() == Some("tunnel"); + // Its public or Tailscale IP's nip.io name, or in tunnel mode a + // name under the tunnel's default domain. + let suffix = match cluster_ip(&t, "freeDomainSuffix") { + Some(s) => s, + None if tunnel => bail!("The cluster's Cloudflare Tunnel has no default domain, so there's no tunnel domain for it. Pick a default domain first, or use your own hostname."), + None => { + let ip = cluster_ip(&t, "freeDomainIp").context("The cluster has no address for free domains (its public or Tailscale IP, as its settings say), so there's no free domain for it. Use your own hostname.")?; + format!("{ip}.nip.io") + } + }; let ns = t .state .project(s["projectId"].as_str().unwrap_or("")) @@ -276,9 +286,9 @@ pub async fn add( .chars() .take(63) .collect(); - format!("{}.{ip}.nip.io", label.trim_end_matches('-')) + format!("{}.{suffix}", label.trim_end_matches('-')) } - None => bail!("Give a hostname, or --free for a free domain."), + None => bail!("Give a hostname, or --free for a free or tunnel domain."), }; if let Some(other) = t.state.services().iter().find(|a| { a["domains"] @@ -344,7 +354,21 @@ pub async fn add( let in_cloudflare = !is_free(&host) && crate::cloudflare::zone_for(&t.state.0, team_id, &host) .is_some_and(|z| z["canEdit"] == json!(true)); - let made = if in_cloudflare && dns.cloudflare { + // Through the cluster's Cloudflare Tunnel: Pyo makes the switch. A name + // under the tunnel's default domain gets no record of its own (its + // wildcard has it), unless a record on that name is in the way. + let tunnel = cluster_ip(&t, "traffic").as_deref() == Some("tunnel"); + let free_tunnel = tunnel + && cluster_ip(&t, "freeDomainSuffix") + .is_some_and(|s| host.strip_suffix(&format!(".{s}")).is_some_and(|l| !l.contains('.'))); + let made = if tunnel && in_cloudflare && dns.cloudflare { + crate::cloudflare::domain_tunnel(api, Some(&t.id), &host, true, false, true) + .await + .map_err(|e| eprintln!("{}", ui::red(&e.to_string()))) + .is_ok() + } else if free_tunnel { + true + } else if in_cloudflare && dns.cloudflare { crate::cloudflare::create_record(api, &t.id, &id, &host, dns.proxied, false) .await .map_err(|e| eprintln!("{}", ui::red(&e.to_string()))) diff --git a/crates/pyo-cli/src/main.rs b/crates/pyo-cli/src/main.rs index 06c0cd59..a0d2f0ed 100644 --- a/crates/pyo-cli/src/main.rs +++ b/crates/pyo-cli/src/main.rs @@ -17,7 +17,6 @@ mod login; mod pack; mod registry; mod sandbox; -mod server; mod service; mod ui; mod upgrade; @@ -96,8 +95,9 @@ enum Command { /// /// A service built from a folder gets this folder, packed and uploaded /// (.gitignore and .pyoignore apply). In a folder no service is linked - /// to, it makes one and links it. With -f, import a Docker Compose file - /// instead: see what it makes, then deploy it. + /// to, it makes one and links it. With -f, deploy a Docker Compose file + /// instead: the first time it makes a project of it, and after that it + /// changes only what the file says differently. Deploy { #[command(flatten)] which: Which, @@ -113,21 +113,29 @@ enum Command { /// A new service's name. Defaults to the folder's. #[arg(long, conflicts_with = "file")] name: Option, - /// A new service's project (name or id), made when there's none by that name. - #[arg(long, conflicts_with = "file")] + /// A new service's project (name or id), made when there's none by + /// that name. With -f, the project the file goes to. + #[arg(long)] project: Option, - /// A Docker Compose file to import as a new project (a .env next to - /// it is read too). + /// A Docker Compose file to deploy as a project (a .env next to it + /// is read too). #[arg(long, short = 'f')] file: Option, + /// With -f: show what would change, and change nothing. + #[arg(long, requires = "file")] + dry_run: bool, + /// With -f: also delete the services made from the file that are no + /// longer in it. Their volumes are kept. + #[arg(long, requires = "file")] + prune: bool, /// The team of a new service or Compose import (slug or id). Defaults to your first team. #[arg(long)] team: Option, /// The cluster to run it on (name or id). Defaults to the team's default cluster. #[arg(long)] cluster: Option, - /// Don't ask: import the Compose file, or go ahead with a very - /// large replica change from pyo.jsonc. + /// Don't ask: deploy the Compose file (and delete with --prune), or + /// go ahead with a very large replica change. #[arg(long, short = 'y')] yes: bool, }, @@ -321,19 +329,6 @@ enum Command { #[command(flatten)] which: Which, }, - /// Hetzner Cloud: the team's API token, for making servers there. - Hetzner { - #[command(subcommand)] - command: HetznerCommand, - /// The team (slug or id). Defaults to your first team. - #[arg(long, global = true)] - team: Option, - }, - /// Servers Pyo makes at Hetzner and joins to a cluster over your tailnet. - Server { - #[command(subcommand)] - command: ServerCommand, - }, /// The CLI's version, like --version. #[command(disable_version_flag = true)] Version, @@ -349,86 +344,6 @@ enum Command { }, } -#[derive(Subcommand)] -enum HetznerCommand { - /// Save a project API token with Read & Write. Owners and admins. - Connect { - /// The token. Without it, it's read from PYO_HETZNER_TOKEN, a pipe, or asked for. - #[arg(long, env = "PYO_HETZNER_TOKEN", hide_env_values = true)] - hetzner_token: Option, - }, - /// List the locations the saved token sees. - Test, - /// Forget the token. Servers Pyo made there keep running. - Disconnect { - /// Don't ask to confirm. - #[arg(long, short = 'y')] - yes: bool, - }, -} - -#[derive(Subcommand)] -enum ServerCommand { - /// Server types and their monthly prices at Hetzner. - Types { - /// One location, e.g. fsn1. - #[arg(long)] - location: Option, - /// The team (slug or id). Defaults to your first team. - #[arg(long)] - team: Option, - }, - /// Make a server at Hetzner and join it to a cluster. Shows the price and asks first. - Create { - /// The cluster it joins (name or id). Defaults to the team's default cluster. - #[arg(long, conflicts_with = "new_cluster")] - cluster: Option, - /// Make a new cluster with this name instead. The server is its first. - #[arg(long)] - new_cluster: Option, - /// Its name. Defaults to -. - #[arg(long, conflicts_with = "new_cluster")] - name: Option, - /// A Hetzner location, e.g. fsn1 (see pyo server types). - #[arg(long)] - location: String, - /// A server type, e.g. cx22 (see pyo server types). - #[arg(long = "type")] - server_type: String, - /// A build-only server. - #[arg(long, conflicts_with = "new_cluster")] - builder: bool, - /// Your SSH public key file, to sign in over your tailnet. - #[arg(long, value_name = "FILE")] - ssh_key: Option, - /// A tag for placing services (repeatable). - #[arg(long = "tag")] - tags: Vec, - /// The team (slug or id). Defaults to your first team. - #[arg(long)] - team: Option, - /// Don't ask to confirm the price. - #[arg(long, short = 'y')] - yes: bool, - /// Start it and exit, without following it. - #[arg(long)] - detach: bool, - }, - /// The servers Pyo made at Hetzner, and how they're doing. - List, - /// Move a server's services off it, take it out of its cluster and your tailnet, and delete it at Hetzner. - Delete { - /// Its name or id. - name: String, - /// Its cluster, when names repeat. - #[arg(long)] - cluster: Option, - /// Don't ask to confirm. - #[arg(long, short = 'y')] - yes: bool, - }, -} - #[derive(Subcommand)] enum DomainCommand { /// The service's domains and their status. @@ -438,7 +353,7 @@ enum DomainCommand { /// e.g. app.example.com. #[arg(required_unless_present = "free", conflicts_with = "free")] hostname: Option, - /// A free nip.io domain instead (no DNS record needed). + /// A free nip.io domain instead, or a tunnel domain in tunnel mode (no DNS record needed). #[arg(long)] free: bool, /// The HTTP port to route to, by name or number (default: the first). @@ -465,6 +380,20 @@ enum DomainCommand { #[arg(long)] keep_dns_record: bool, }, + /// Serve a domain through the cluster's Cloudflare Tunnel, or move it back. + Tunnel { + /// e.g. app.example.com. + hostname: String, + /// Replace the records in the way. Owners and admins. + #[arg(long)] + replace: bool, + /// Move it back from the tunnel. Not for a name under the tunnel's default domain. + #[arg(long, conflicts_with = "replace")] + back: bool, + /// Moving back: don't put back the records the tunnel replaced. + #[arg(long, requires = "back")] + no_restore: bool, + }, /// Create a domain's DNS record in Cloudflare, or try again. Never overwrites a record. Dns { /// e.g. app.example.com. @@ -504,6 +433,59 @@ enum CloudflareCommand { #[arg(long, short = 'y')] yes: bool, }, + /// A cluster's Cloudflare Tunnel: websites through Cloudflare, no open ports. + Tunnel { + #[command(subcommand)] + command: TunnelCommand, + }, +} + +#[derive(Subcommand)] +enum TunnelCommand { + /// The tunnel, its connectors and its domains. + Status { + /// The cluster, by name or id (default: the team's). + #[arg(long)] + cluster: Option, + }, + /// Take the cluster's websites through Cloudflare Tunnel. Owners and admins. + On { + #[arg(long)] + cluster: Option, + /// A zone (like example.com): services get names under it. + #[arg(long)] + default_domain: Option, + /// The Cloudflare account, when the token's zones are in more than one. + #[arg(long)] + account: Option, + /// Don't keep public TCP and UDP ports on the servers. + #[arg(long)] + no_public_ports: bool, + }, + /// Take websites on public ports or Tailscale only again. The tunnel stays until removed. + Off { + #[arg(long)] + cluster: Option, + /// "public" or "tailscale". + #[arg(long, default_value = "public")] + to: String, + }, + /// Remove the tunnel, its records and its connector. Owners and admins. + Remove { + #[arg(long)] + cluster: Option, + /// Leave the records the tunnel replaced out (they're put back by default). + #[arg(long)] + keep_records: bool, + /// Don't ask to confirm. + #[arg(long, short = 'y')] + yes: bool, + }, + /// A new token and certificate for the tunnel. Owners and admins. + Rotate { + #[arg(long)] + cluster: Option, + }, } #[derive(Subcommand)] @@ -737,6 +719,9 @@ enum EnvCommand { #[tokio::main] async fn main() { + // One TLS provider for the websockets and anything else that doesn't + // pick its own: a build with ring next to aws-lc-rs can't guess one. + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); let cli = Cli::parse(); upgrade::remove_old(); let check = match cli.command { @@ -818,15 +803,23 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { file: Some(f), team, cluster, + project, + dry_run, + prune, yes, .. } => { compose::deploy( &config::client(url, token)?, &f, - team.as_deref(), - cluster.as_deref(), - yes, + compose::Opts { + team: team.as_deref(), + cluster: cluster.as_deref(), + project: project.as_deref(), + dry_run, + prune, + yes, + }, ) .await } @@ -1147,6 +1140,12 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { proxied, replace, } => cloudflare::domain_dns(&api, s, &hostname, proxied, replace).await, + DomainCommand::Tunnel { + hostname, + replace, + back, + no_restore, + } => cloudflare::domain_tunnel(&api, s, &hostname, !back, replace, !no_restore).await, } } Command::Cloudflare { command, team } => { @@ -1160,6 +1159,41 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { CloudflareCommand::Test => cloudflare::test(&api, team).await, CloudflareCommand::Zones => cloudflare::zones(&api, team).await, CloudflareCommand::Remove { yes } => cloudflare::remove(&api, team, yes).await, + CloudflareCommand::Tunnel { command } => match command { + TunnelCommand::Status { cluster } => { + cloudflare::tunnel_status(&api, team, cluster.as_deref()).await + } + TunnelCommand::On { + cluster, + default_domain, + account, + no_public_ports, + } => { + cloudflare::tunnel_on( + &api, + team, + cluster.as_deref(), + default_domain.as_deref(), + account.as_deref(), + !no_public_ports, + ) + .await + } + TunnelCommand::Off { cluster, to } => { + cloudflare::tunnel_off(&api, team, cluster.as_deref(), &to).await + } + TunnelCommand::Remove { + cluster, + keep_records, + yes, + } => { + cloudflare::tunnel_remove(&api, team, cluster.as_deref(), !keep_records, yes) + .await + } + TunnelCommand::Rotate { cluster } => { + cloudflare::tunnel_rotate(&api, team, cluster.as_deref()).await + } + }, } } Command::Sandbox { command, team } => { @@ -1170,60 +1204,6 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { Ok(()) } Command::Upgrade { version } => upgrade::run(version).await, - Command::Hetzner { command, team } => { - let api = config::client(url, token)?; - let team = team.as_deref(); - match command { - HetznerCommand::Connect { hetzner_token } => { - server::connect(&api, team, hetzner_token).await - } - HetznerCommand::Test => server::test(&api, team).await, - HetznerCommand::Disconnect { yes } => server::disconnect(&api, team, yes).await, - } - } - Command::Server { command } => { - let api = config::client(url, token)?; - match command { - ServerCommand::Types { location, team } => { - server::types(&api, team.as_deref(), location.as_deref()).await - } - ServerCommand::Create { - cluster, - new_cluster, - name, - location, - server_type, - builder, - ssh_key, - tags, - team, - yes, - detach, - } => { - server::create( - &api, - server::New { - team: team.as_deref(), - cluster: cluster.as_deref(), - new_cluster: new_cluster.as_deref(), - name: name.as_deref(), - location: &location, - server_type: &server_type, - builder, - ssh_key: ssh_key.as_deref(), - tags, - yes, - detach, - }, - ) - .await - } - ServerCommand::List => server::list_servers(&api).await, - ServerCommand::Delete { name, cluster, yes } => { - server::delete(&api, &name, cluster.as_deref(), yes).await - } - } - } Command::Backup { command: BackupCommand::Now { volume, db, wait }, which, @@ -1327,6 +1307,30 @@ mod tests { }) )); assert!(parse(&["pyo", "deploy", "--local", "-f", "compose.yml"]).is_err()); + assert!(matches!( + parse(&[ + "pyo", + "deploy", + "-f", + "compose.yml", + "--project", + "cloud", + "--dry-run", + "--prune", + "-y" + ]), + Ok(Command::Deploy { + file: Some(_), + project: Some(_), + dry_run: true, + prune: true, + yes: true, + .. + }) + )); + // Planning and pruning are for a Compose file. + assert!(parse(&["pyo", "deploy", "--dry-run"]).is_err()); + assert!(parse(&["pyo", "deploy", "--prune"]).is_err()); let Ok(Command::Env { command: Some(EnvCommand::Pull { file, out, secrets, .. diff --git a/crates/pyo-cli/src/sandbox.rs b/crates/pyo-cli/src/sandbox.rs index 94a99866..384b4861 100644 --- a/crates/pyo-cli/src/sandbox.rs +++ b/crates/pyo-cli/src/sandbox.rs @@ -206,30 +206,6 @@ pub enum ServersCommand { #[arg(long, value_name = "DOMAIN")] edge_domain: Option, }, - /// Buy a sandbox server at Hetzner. Pyo sets it up over your tailnet, - /// and it runs sandboxes on gVisor. Owners and admins. - Create { - /// Its name, lowercase letters, digits and dashes. - name: String, - /// A location, e.g. fsn1 (see pyo server types). - #[arg(long)] - location: String, - /// A server type, e.g. cx22 (see pyo server types). - #[arg(long = "type")] - server_type: String, - /// Serve sandbox ports at -.DOMAIN. Point *.DOMAIN at the server. - #[arg(long, value_name = "DOMAIN")] - edge_domain: Option, - /// Your SSH public key file, to sign in over your tailnet. - #[arg(long, value_name = "FILE")] - ssh_key: Option, - /// Don't ask to confirm the price. - #[arg(long, short = 'y')] - yes: bool, - /// Start it and exit, without following it. - #[arg(long)] - detach: bool, - }, /// The sandbox servers the team can use. Ls { /// Print it as JSON. @@ -697,52 +673,6 @@ async fn servers(api: &Api, team: Option<&str>, cmd: ServersCommand) -> Result<( println!("{}", r["command"].as_str().unwrap_or("")); Ok(()) } - ServersCommand::Create { - name, - location, - server_type, - edge_domain, - ssh_key, - yes, - detach, - } => { - let ssh_key = match ssh_key { - Some(p) => Some( - std::fs::read_to_string(&p) - .with_context(|| format!("Can't read {}", p.display()))? - .trim() - .to_owned(), - ), - None => None, - }; - let mut body = json!({ - "teamId": team, "name": name, "location": location, - "serverType": server_type, "sshKey": ssh_key, - }); - if let Some(d) = edge_domain { - body["edgeDomain"] = json!(d); - } - let path = "/api/v1/sandbox-servers/cloud"; - let r = match api.post(path, &body).await { - Err(e) if e.downcast_ref::().is_some() => { - println!("{e}"); - if !yes && !crate::server::yes_to("Go ahead? [y/N] ")? { - bail!("Nothing was changed."); - } - body["confirm"] = json!(true); - api.post(path, &body).await? - } - r => r?, - }; - ui::ok(&format!( - "Creating {name} at Hetzner. It runs sandboxes on gVisor." - )); - if detach { - return Ok(()); - } - let id = r["cloudServer"]["id"].as_str().unwrap_or("").to_owned(); - crate::server::follow(api, &id).await - } ServersCommand::Ls { json } => { let r = api .get(&format!("/api/v1/sandbox-servers?team={team}")) @@ -808,7 +738,7 @@ async fn servers(api: &Api, team: Option<&str>, cmd: ServersCommand) -> Result<( match api.delete(&path).await { Err(e) if e.downcast_ref::().is_some() => { println!("{e}"); - if !yes && !crate::server::yes_to("Go ahead? [y/N] ")? { + if !yes && !matches!(ui::ask("Go ahead? [y/N] ")?.trim(), "y" | "Y" | "yes") { bail!("Nothing was changed."); } api.delete(&format!("{path}?confirm=true")).await?; diff --git a/crates/pyo-cli/src/server.rs b/crates/pyo-cli/src/server.rs deleted file mode 100644 index a8772c53..00000000 --- a/crates/pyo-cli/src/server.rs +++ /dev/null @@ -1,389 +0,0 @@ -//! `pyo hetzner` and `pyo server`: connect a team to Hetzner Cloud, then -//! make servers there that join a cluster over the tailnet, follow them to -//! ready and delete them. Every create and delete shows its monthly price -//! and asks first (or -y). - -use std::io::{IsTerminal, Read, Write}; -use std::time::Duration; - -use anyhow::{Context, Result, bail}; -use serde_json::{Value, json}; - -use crate::{ - api::{Api, NeedsConfirm, State, new_id}, - ui, -}; - -/// A team by slug or id, else the first. -fn team<'a>(state: &'a State, team: Option<&str>) -> Result<&'a Value> { - let teams = state.teams(); - match team { - Some(t) => teams - .iter() - .find(|x| x["slug"] == json!(t) || x["id"] == json!(t)) - .with_context(|| format!("No team {t} among yours")), - None => teams.first().context("You aren't in any team"), - } -} - -fn id_of(v: &Value) -> String { - v["id"].as_str().unwrap_or("").to_owned() -} - -fn list<'a>(state: &'a State, key: &str) -> &'a [Value] { - state.0[key].as_array().map(Vec::as_slice).unwrap_or(&[]) -} - -/// The token: PYO_HETZNER_TOKEN, piped in, or typed without echo. -fn read_token(given: Option) -> Result { - if let Some(t) = given.filter(|t| !t.trim().is_empty()) { - return Ok(t.trim().to_owned()); - } - let mut s = String::new(); - if !std::io::stdin().is_terminal() { - std::io::stdin().read_to_string(&mut s)?; - return Ok(s.trim().to_owned()); - } - print!("Hetzner API token (Read & Write): "); - std::io::stdout().flush()?; - crossterm::terminal::enable_raw_mode()?; - let mut byte = [0u8; 1]; - let read = loop { - match std::io::stdin().read(&mut byte) { - Ok(1) if byte[0] == b'\r' || byte[0] == b'\n' => break Ok(()), - Ok(1) if byte[0] == 3 => break Err(anyhow::anyhow!("Cancelled.")), - Ok(1) if byte[0] == 127 || byte[0] == 8 => { - s.pop(); - } - Ok(1) => s.push(byte[0] as char), - Ok(_) => break Ok(()), - Err(e) => break Err(e.into()), - } - }; - crossterm::terminal::disable_raw_mode()?; - println!(); - read?; - Ok(s.trim().to_owned()) -} - -pub async fn connect(api: &Api, team_ref: Option<&str>, token: Option) -> Result<()> { - let state = api.state().await?; - let t = team(&state, team_ref)?; - let token = read_token(token)?; - let r = api - .op("saveHetzner", json!({ "teamId": id_of(t), "token": token })) - .await?; - let n = r["locations"].as_array().map_or(0, Vec::len); - ui::ok(&format!( - "Connected Hetzner to {}. The token sees {n} locations.", - t["name"].as_str().unwrap_or("") - )); - Ok(()) -} - -pub async fn test(api: &Api, team_ref: Option<&str>) -> Result<()> { - let state = api.state().await?; - let t = team(&state, team_ref)?; - let r = api.op("testHetzner", json!({ "teamId": id_of(t) })).await?; - for l in r["locations"].as_array().into_iter().flatten() { - println!( - "{} {}", - ui::bold(l["name"].as_str().unwrap_or("")), - ui::dim(&format!( - "{}, {}", - l["city"].as_str().unwrap_or(""), - l["country"].as_str().unwrap_or("") - )) - ); - } - ui::ok("Hetzner answers."); - Ok(()) -} - -pub async fn disconnect(api: &Api, team_ref: Option<&str>, yes: bool) -> Result<()> { - let state = api.state().await?; - let t = team(&state, team_ref)?; - if !yes && !yes_to("Forget the Hetzner token? Servers Pyo made there keep running. [y/N] ")? { - bail!("Kept."); - } - api.op("removeHetzner", json!({ "teamId": id_of(t) })) - .await?; - ui::ok("Hetzner disconnected."); - Ok(()) -} - -pub(crate) fn yes_to(q: &str) -> Result { - Ok(matches!( - ui::ask(q)?.trim().to_lowercase().as_str(), - "y" | "yes" - )) -} - -fn money(currency: &str, n: f64) -> String { - match currency { - "EUR" => format!("€{n:.2}"), - "USD" => format!("${n:.2}"), - c => format!("{n:.2} {c}"), - } -} - -pub async fn types(api: &Api, team_ref: Option<&str>, location: Option<&str>) -> Result<()> { - let state = api.state().await?; - let t = team(&state, team_ref)?; - let o = api - .get(&format!("/api/v1/cloud/options?team={}", id_of(t))) - .await?; - let currency = o["currency"].as_str().unwrap_or("EUR"); - let locations: Vec<&Value> = o["locations"] - .as_array() - .into_iter() - .flatten() - .filter(|l| location.is_none_or(|w| l["name"] == json!(w))) - .collect(); - if locations.is_empty() { - bail!("Hetzner has no location {}.", location.unwrap_or("")); - } - for l in locations { - let loc = l["name"].as_str().unwrap_or(""); - println!( - "{} {}", - ui::bold(loc), - ui::dim(&format!( - "{}, {}", - l["city"].as_str().unwrap_or(""), - l["country"].as_str().unwrap_or("") - )) - ); - for st in o["serverTypes"].as_array().into_iter().flatten() { - let Some(p) = st["prices"][loc].as_f64() else { - continue; - }; - let available = st["available"] - .as_array() - .is_some_and(|a| a.contains(&json!(loc))); - let note = if st["supported"] != true { - " (Arm, not for Pyo)" - } else if !available { - " (unavailable)" - } else { - "" - }; - let line = format!( - " {:<8} {:>2} vCPU {:>4} GB {:>5} GB disk {:<4} {:>8}/mo{note}", - st["name"].as_str().unwrap_or(""), - st["cores"], - st["memoryGb"], - st["diskGb"], - st["architecture"].as_str().unwrap_or(""), - money(currency, p), - ); - println!( - "{}", - if note.is_empty() { - line - } else { - ui::dim(&line) - } - ); - } - } - println!("{}", ui::dim("Monthly, before VAT, with the IPv4 address.")); - Ok(()) -} - -pub struct New<'a> { - pub team: Option<&'a str>, - pub cluster: Option<&'a str>, - pub new_cluster: Option<&'a str>, - pub name: Option<&'a str>, - pub location: &'a str, - pub server_type: &'a str, - pub builder: bool, - pub ssh_key: Option<&'a std::path::Path>, - pub tags: Vec, - pub yes: bool, - pub detach: bool, -} - -/// Sends an operation, showing its price and asking first. -async fn priced(api: &Api, op: &str, args: Value, yes: bool) -> Result { - match api.op(op, args.clone()).await { - Err(e) if e.downcast_ref::().is_some() => { - println!("{e}"); - if !yes && !yes_to("Go ahead? [y/N] ")? { - bail!("Nothing was changed."); - } - let mut args = args; - args["confirm"] = json!(true); - api.op(op, args).await - } - r => r, - } -} - -pub async fn create(api: &Api, n: New<'_>) -> Result<()> { - let state = api.state().await?; - let ssh_key = match n.ssh_key { - Some(p) => Some( - std::fs::read_to_string(p) - .with_context(|| format!("Can't read {}", p.display()))? - .trim() - .to_owned(), - ), - None => None, - }; - let id = new_id("cs"); - let (op, args) = if let Some(cluster_name) = n.new_cluster { - let t = team(&state, n.team)?; - ( - "createCloudCluster", - json!({ "id": new_id("cl"), "teamId": id_of(t), "name": cluster_name, "serverId": id, - "location": n.location, "serverType": n.server_type, "sshKey": ssh_key, "tags": n.tags }), - ) - } else { - let (_, cluster_id) = crate::compose::team_and_cluster(api, n.team, n.cluster).await?; - let taken: Vec<&str> = list(&state, "servers") - .iter() - .filter(|s| s["clusterId"] == json!(cluster_id)) - .filter_map(|s| s["name"].as_str()) - .chain( - list(&state, "cloudServers") - .iter() - .filter(|s| s["clusterId"] == json!(cluster_id)) - .filter_map(|s| s["name"].as_str()), - ) - .collect(); - let cluster_name = state - .cluster(&cluster_id) - .and_then(|c| c["name"].as_str()) - .unwrap_or("server") - .to_owned(); - let name = match n.name { - Some(x) => x.to_owned(), - None => (1..) - .map(|i| format!("{cluster_name}-{i}")) - .find(|x| !taken.contains(&x.as_str())) - .unwrap_or_default(), - }; - ( - "createCloudServer", - json!({ "id": id, "clusterId": cluster_id, "name": name, "location": n.location, - "serverType": n.server_type, "builder": n.builder, "sshKey": ssh_key, "tags": n.tags }), - ) - }; - let r = priced(api, op, args, n.yes).await?; - let name = r["name"].as_str().unwrap_or("").to_owned(); - ui::ok(&format!("Creating {name} at Hetzner.")); - if n.detach { - return Ok(()); - } - follow(api, &id).await -} - -/// Follows a new server to ready, saying each step. -pub(crate) async fn follow(api: &Api, id: &str) -> Result<()> { - let mut last = String::new(); - let mut sign_shown = false; - loop { - let state = api.state().await?; - let Some(s) = list(&state, "cloudServers") - .iter() - .find(|s| s["id"] == json!(id)) - else { - bail!("The server is gone."); - }; - let st = s["state"].as_str().unwrap_or("").to_owned(); - if st != last { - let label = match st.as_str() { - "creating" => "Creating", - "booting" => "Booting", - "joining" => "Joining", - "ready" => "Ready", - "failed" => "Failed", - other => other, - }; - println!("{} {label}", ui::dim("·")); - last = st.clone(); - } - if let Some(cmd) = s["signCommand"].as_str() - && !sign_shown - { - println!("Your tailnet has Tailnet Lock on. On a signing device, run:\n {cmd}"); - sign_shown = true; - } - match st.as_str() { - "ready" => { - ui::ok(&format!("{} is ready.", s["name"].as_str().unwrap_or(""))); - return Ok(()); - } - "failed" => bail!( - "{} Delete it with: pyo server delete {}", - s["error"].as_str().unwrap_or("It didn't join."), - s["name"].as_str().unwrap_or("") - ), - _ => tokio::time::sleep(Duration::from_secs(5)).await, - } - } -} - -pub async fn list_servers(api: &Api) -> Result<()> { - let state = api.state().await?; - let all = list(&state, "cloudServers"); - if all.is_empty() { - println!("No servers made at Hetzner."); - return Ok(()); - } - for s in all { - let cluster = s["clusterId"] - .as_str() - .and_then(|c| state.cluster(c)) - .and_then(|c| c["name"].as_str()) - .unwrap_or("(removed)"); - println!( - "{} {} {} in {} {}/mo {}", - ui::bold(s["name"].as_str().unwrap_or("")), - cluster, - s["serverType"].as_str().unwrap_or(""), - s["location"].as_str().unwrap_or(""), - money( - s["currency"].as_str().unwrap_or("EUR"), - s["monthly"].as_f64().unwrap_or(0.0) - ), - s["state"].as_str().unwrap_or("") - ); - if let Some(e) = s["error"].as_str() { - println!(" {} {e}", ui::red("error:")); - } - if let Some(c) = s["signCommand"].as_str() { - println!(" {} {c}", ui::yellow("sign:")); - } - } - Ok(()) -} - -pub async fn delete(api: &Api, name: &str, cluster: Option<&str>, yes: bool) -> Result<()> { - let state = api.state().await?; - let hits: Vec<&Value> = list(&state, "cloudServers") - .iter() - .filter(|s| s["id"] == json!(name) || s["name"] == json!(name)) - .filter(|s| { - cluster.is_none_or(|c| { - s["clusterId"] == json!(c) - || s["clusterId"] - .as_str() - .and_then(|id| state.cluster(id)) - .is_some_and(|x| x["name"] == json!(c)) - }) - }) - .collect(); - let s = match hits.len() { - 0 => bail!("No server {name} made at Hetzner. See them: pyo server list"), - 1 => hits[0], - _ => bail!("More than one server is called {name}. Pass --cluster."), - }; - priced(api, "deleteCloudServer", json!({ "id": s["id"] }), yes).await?; - ui::ok(&format!( - "Deleting {name}. Its services move off it first, then it's deleted at Hetzner." - )); - Ok(()) -} diff --git a/crates/pyo-db-controller/README.md b/crates/pyo-db-controller/README.md index 3005640c..9867a9e9 100644 --- a/crates/pyo-db-controller/README.md +++ b/crates/pyo-db-controller/README.md @@ -29,7 +29,7 @@ Valkey: the Redis protocol and the REST API. | Engine | Image | |---|---| | Postgres | Pyo's own per major version, `PYO_DB_POSTGRES_IMAGE_16`, `_17`, `_18` (`deploy/images/postgres.Dockerfile`). A version without one gets `PYO_DB_POSTGRES_IMAGE:` (CloudNativePG's). | -| Valkey | `PYO_DB_VALKEY_IMAGE:`; while it loads modules, `PYO_DB_VALKEY_BUNDLE_IMAGE` (valkey-bundle 8.1.11, pinned; Valkey 8.1 only) | +| Valkey | `PYO_DB_VALKEY_IMAGE:`; while it loads modules, `PYO_DB_VALKEY_BUNDLE_IMAGE` (valkey-bundle 8.1.12, pinned; Valkey 8.1 only) | | MySQL | `PYO_DB_MYSQL_IMAGE`, pinned | | KV address | `PYO_DB_PYO_KV_IMAGE` | @@ -66,7 +66,7 @@ doesn't handle them. `spec.valkey.modules` lists the Valkey modules a KV database loads, the catalog's `kv` entries in `extensions.json` (`src/modules.rs`): `valkey-json`, -`valkey-bloom` and `valkey-search` (BSD-3-Clause), from valkey-bundle 8.1.11 +`valkey-bloom` and `valkey-search` (BSD-3-Clause), from valkey-bundle 8.1.12 (`json` 1.0.3, `bf` 1.0.1, `search` 1.0.3 by `MODULE LIST`). The bundle also has valkey-ldap, which isn't offered. diff --git a/crates/pyo-db-controller/src/history.rs b/crates/pyo-db-controller/src/history.rs new file mode 100644 index 00000000..297b7d15 --- /dev/null +++ b/crates/pyo-db-controller/src/history.rs @@ -0,0 +1,413 @@ +//! Timeline history files in a Postgres database's backups. +//! +//! Every failover or switchover starts a new timeline, and Postgres writes +//! `.history` for it. A restore needs that file from the backups: +//! without it the first WAL file of the timeline is refused ("unexpected +//! timeline ID") and the restore fails. +//! +//! Postgres hands the file to the archiver once, when the timeline starts. +//! While backups are off, CloudNativePG's archiver takes it and stores +//! nothing, so backups turned on later never get it, and a base backup +//! that starts in that WAL file can't be restored. +//! +//! So when backups are on and the database is past its first timeline, a +//! Job puts the missing history files in the backups: it asks the primary +//! for each (`TIMELINE_HISTORY`, over a replication connection with the +//! cluster's own replication certificate) and archives it with +//! barman-cloud, as the archiver would have. Files already there are left +//! alone. It runs once per timeline and destination: the Cluster's +//! `pyo.dev/timeline-history` annotation records what's done. Backups +//! taken before the Job ran are restorable once it's done. + +use k8s_openapi::api::{batch::v1::Job, core::v1::Pod}; +use kube::{ + Api, Resource, ResourceExt, + api::{DynamicObject, ListParams, Patch, PatchParams, PostParams}, +}; +use serde_json::{Value, json}; + +use crate::{ + controller::{Kube, labels}, + crd::Destination, + postgres::destination_path, +}; + +/// On the Cluster: the timeline and destination whose history files are in +/// the backups ([`fingerprint`]). +pub const ANNOTATION: &str = "pyo.dev/timeline-history"; +/// The Job's pods (`pyo.dev/component`), as the backups' other objects. +const COMPONENT: &str = "backup"; + +/// What the Job did, for a timeline and a destination: another timeline +/// (a failover) or another destination, and it runs again. +pub fn fingerprint(timeline: i64, d: &Destination, namespace: &str, server: &str) -> String { + format!( + "{timeline} {}/{server} {}", + destination_path(d, namespace), + d.endpoint_url + ) +} + +/// The Job for one fingerprint: `-history-`. +pub fn job_name(db: &str, fingerprint: &str) -> String { + let hash = fingerprint + .bytes() + .fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); + format!("{db}-history-{:08x}", hash >> 32) +} + +/// Whether the history files of this timeline may be missing from the +/// backups: past the first timeline, and not recorded as done. +pub fn needed(timeline: i64, recorded: Option<&str>, fingerprint: &str) -> bool { + timeline > 1 && recorded != Some(fingerprint) +} + +/// For each timeline from 2 to the current one: leave the history file +/// when the backups have it, else read it from the primary and archive it. +/// barman-cloud-wal-restore exits 1 when the file isn't there, and with +/// something else when the storage can't be reached or refuses. +/// +/// An older timeline's file the primary no longer has is skipped: the +/// current one's lists every timeline before it. The current one's must +/// get there. +pub const SCRIPT: &str = r#"set -uo pipefail +fail() { echo "$1" | tee /dev/termination-log >&2; exit 1; } +# The last thing a tool said, without barman's time and level. +why() { grep -v '^$' /work/err | tail -n 1 | sed 's/^.* ERROR: //'; } +conn="host=$PGHOST_RW port=5432 dbname=postgres user=streaming_replica replication=true sslmode=verify-ca sslcert=/certs/tls.crt sslkey=/certs/tls.key sslrootcert=/ca/ca.crt connect_timeout=10" +cd /work || fail "no work directory" +added="" +for ((t = 2; t <= TIMELINE; t++)); do + f=$(printf '%08X.history' "$t") + barman-cloud-wal-restore --endpoint-url "$ENDPOINT" "$DESTINATION" "$SERVER" "$f" "/work/have-$f" 2>/work/err + rc=$? + if [ "$rc" = 0 ]; then echo "pyo-history: $f is in the backups"; continue; fi + if [ "$rc" != 1 ]; then fail "can't read the backups: $(why)"; fi + if ! psql "$conn" -XAtc "TIMELINE_HISTORY $t" >/work/raw 2>/work/err; then + if [ "$t" -lt "$TIMELINE" ]; then echo "pyo-history: the primary has no $f, skipped"; continue; fi + fail "can't read $f from the primary: $(why)" + fi + # psql prints "|" and one newline of its own. + sed '1s/^[^|]*|//' /work/raw | head -c -1 >"/work/$f" + [ -s "/work/$f" ] || fail "the primary sent an empty $f" + barman-cloud-wal-archive --gzip --endpoint-url "$ENDPOINT" "$DESTINATION" "$SERVER" "/work/$f" 2>/work/err \ + || fail "can't write $f to the backups: $(why)" + echo "pyo-history: archived $f" + added="$added $f" +done +# What was added, for the event. +if [ -n "$added" ]; then echo "added$added" >/dev/termination-log; fi +"#; + +/// The annotation's value on a Cluster. +fn recorded(cluster: &DynamicObject) -> Option<&str> { + cluster.annotations().get(ANNOTATION).map(String::as_str) +} + +impl Kube<'_> { + /// The Job that puts the history files up to `timeline` in the backups + /// at `d`. + pub fn history_job(&self, d: &Destination, timeline: i64, name: &str) -> Value { + let db = self.name(); + let key = |k: &str| json!({ "secretKeyRef": { "name": d.credentials_secret, "key": k } }); + let plain = |k: &str, v: String| json!({ "name": k, "value": v }); + let mut env = vec![ + plain("PGHOST_RW", self.svc_host(&format!("{db}-rw"))), + plain("TIMELINE", timeline.to_string()), + plain("ENDPOINT", d.endpoint_url.clone()), + plain("DESTINATION", destination_path(d, &self.ns())), + plain("SERVER", db.clone()), + json!({ "name": "AWS_ACCESS_KEY_ID", "valueFrom": key("accessKeyId") }), + json!({ "name": "AWS_SECRET_ACCESS_KEY", "valueFrom": key("secretAccessKey") }), + ]; + if !d.region.is_empty() { + env.push(plain("AWS_DEFAULT_REGION", d.region.clone())); + } + let lbl = labels(self.db, COMPONENT); + // The key is root's with the group's read bit: what libpq accepts. + let secret = |n: String| json!({ "secretName": n, "defaultMode": 0o640 }); + json!({ + "apiVersion": "batch/v1", "kind": "Job", + "metadata": { "name": name, "namespace": self.ns(), "labels": lbl, "ownerReferences": [self.db.controller_owner_ref(&())] }, + "spec": { + "backoffLimit": 2, + "activeDeadlineSeconds": 600, + // A failed one is made again once it's gone. + "ttlSecondsAfterFinished": 600, + "template": { "metadata": { "labels": lbl }, "spec": { + "restartPolicy": "Never", + "automountServiceAccountToken": false, + // CloudNativePG's images run Postgres as uid 26. + "securityContext": { "runAsNonRoot": true, "runAsUser": 26, "runAsGroup": 26, "fsGroup": 26, "seccompProfile": { "type": "RuntimeDefault" } }, + "containers": [{ + "name": "history", + "image": self.pg_image(), + "command": ["bash", "-c", SCRIPT], + "env": env, + "volumeMounts": [ + { "name": "certs", "mountPath": "/certs", "readOnly": true }, + { "name": "ca", "mountPath": "/ca", "readOnly": true }, + { "name": "work", "mountPath": "/work" }, + ], + "terminationMessagePolicy": "FallbackToLogsOnError", + "resources": { "requests": { "cpu": "20m", "memory": "64Mi" }, "limits": { "memory": "256Mi" } }, + "securityContext": { "allowPrivilegeEscalation": false, "capabilities": { "drop": ["ALL"] } }, + }], + "volumes": [ + { "name": "certs", "secret": secret(format!("{db}-replication")) }, + { "name": "ca", "secret": secret(format!("{db}-ca")) }, + { "name": "work", "emptyDir": {} }, + ], + } }, + }, + }) + } + + /// Sees to the history files of a database with backups on. `cluster` + /// is its CloudNativePG Cluster, `serving` whether its primary takes + /// connections. Returns what's wrong, for the backup status: empty + /// when the files are there or on their way. + pub async fn timeline_history( + &self, + d: &Destination, + cluster: &DynamicObject, + serving: bool, + ) -> anyhow::Result { + let timeline = cluster.data["status"]["timelineID"].as_i64().unwrap_or(0); + let want = fingerprint(timeline, d, &self.ns(), &self.name()); + if !needed(timeline, recorded(cluster), &want) || !serving { + return Ok(String::new()); + } + let name = job_name(&self.name(), &want); + let api: Api = Api::namespaced(self.ctx.client.clone(), &self.ns()); + let Some(job) = api.get_opt(&name).await? else { + let job: Job = serde_json::from_value(self.history_job(d, timeline, &name))?; + match api.create(&PostParams::default(), &job).await { + Err(kube::Error::Api(e)) if e.code == 409 => {} + r => { + r?; + } + } + return Ok(String::new()); + }; + let done = |t: &str| { + job.status + .as_ref() + .and_then(|s| s.conditions.as_ref()) + .is_some_and(|c| c.iter().any(|c| c.type_ == t && c.status == "True")) + }; + if done("Complete") { + let patch = json!({ "metadata": { "annotations": { ANNOTATION: want } } }); + let ar = kube::api::ApiResource::from_gvk(&kube::api::GroupVersionKind::gvk( + "postgresql.cnpg.io", + "v1", + "Cluster", + )); + Api::::namespaced_with(self.ctx.client.clone(), &self.ns(), &ar) + .patch(&self.name(), &PatchParams::default(), &Patch::Merge(&patch)) + .await?; + // Only when it had something to add. + if self.job_said(&name).await.starts_with("added") { + self.event( + false, + "BackupHistoryAdded", + "Added the failover history to the backups".into(), + ) + .await; + } + return Ok(String::new()); + } + if !done("Failed") { + return Ok(String::new()); + } + // The Job goes after 10 minutes, and the next pass makes it again. + Ok(failure_message(&self.job_said(&name).await)) + } + + /// What a Job's last pod left as its termination message. + async fn job_said(&self, job: &str) -> String { + let pods: Api = Api::namespaced(self.ctx.client.clone(), &self.ns()); + let Ok(list) = pods + .list(&ListParams::default().labels(&format!("job-name={job}"))) + .await + else { + return String::new(); + }; + let mut pods = list.items; + pods.sort_by_key(|p| p.metadata.creation_timestamp.clone()); + pods.iter() + .rev() + .find_map(|p| { + p.status + .as_ref()? + .container_statuses + .iter() + .flatten() + .find_map(|c| c.state.as_ref()?.terminated.as_ref()?.message.clone()) + }) + .unwrap_or_default() + .trim() + .to_owned() + } +} + +/// The backup status message while the history files can't be added. +pub fn failure_message(why: &str) -> String { + let last = why.lines().last().unwrap_or("").trim(); + if last.is_empty() { + "Backups can't be restored yet. Pyo is trying again".to_owned() + } else { + format!("Backups can't be restored yet: {last}") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dest() -> Destination { + serde_json::from_value(json!({ + "endpointURL": "http://s3:3900", "bucket": "b", "path": "team", "region": "garage", "credentialsSecret": "s3", + })) + .unwrap() + } + + #[test] + fn only_past_the_first_timeline_and_once() { + let fp = fingerprint(2, &dest(), "ns", "shop"); + assert_eq!(fp, "2 s3://b/team/ns/shop http://s3:3900"); + // A database that never failed over has no history file. + assert!(!needed(1, None, &fingerprint(1, &dest(), "ns", "shop"))); + assert!(!needed(0, None, &fingerprint(0, &dest(), "ns", "shop"))); + // After a failover, until it's recorded. + assert!(needed(2, None, &fp)); + assert!(!needed(2, Some(&fp), &fp)); + // Another failover, or another destination: again. + assert!(needed(3, Some(&fp), &fingerprint(3, &dest(), "ns", "shop"))); + let mut other = dest(); + other.bucket = "c".into(); + assert!(needed(2, Some(&fp), &fingerprint(2, &other, "ns", "shop"))); + } + + #[test] + fn job_names_follow_the_fingerprint() { + let a = job_name("shop", &fingerprint(2, &dest(), "ns", "shop")); + let b = job_name("shop", &fingerprint(3, &dest(), "ns", "shop")); + assert!(a.starts_with("shop-history-") && a.len() == "shop-history-".len() + 8); + assert_ne!(a, b); + assert_eq!(a, job_name("shop", &fingerprint(2, &dest(), "ns", "shop"))); + } + + #[test] + fn the_script_archives_only_what_is_missing() { + // Syntax, with bash when it's there. + if let Ok(out) = std::process::Command::new("bash").args(["-n", "-c", SCRIPT]).output() { + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + } + // Not found (1) is the only answer that leads to an upload. + assert!(SCRIPT.contains(r#"if [ "$rc" != 1 ]; then fail"#)); + assert!(SCRIPT.contains("TIMELINE_HISTORY $t")); + assert!(SCRIPT.contains("replication=true")); + assert!(SCRIPT.contains("sslmode=verify-ca")); + } + + /// The script against stand-ins for psql and barman-cloud: what's in + /// the backups stays, what's missing is written byte for byte, and a + /// storage error stops it. + #[test] + fn the_script_run_with_stand_ins() { + let Ok(bash) = std::process::Command::new("bash").arg("--version").output() else { + return; + }; + if !bash.status.success() { + return; + } + let dir = std::env::temp_dir().join(format!("pyo-history-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for d in ["bin", "work", "store"] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + let write = |name: &str, body: &str| { + use std::os::unix::fs::PermissionsExt; + let p = dir.join("bin").join(name); + std::fs::write(&p, body).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + }; + // The store is a directory; STORE_RC makes reads fail another way. + write( + "barman-cloud-wal-restore", + "#!/bin/bash\n[ -n \"${STORE_RC:-}\" ] && { echo '2026-01-01 00:00:00,000 [8] ERROR: boom' >&2; echo >&2; exit \"$STORE_RC\"; }\nf=\"${@: -2:1}\"; [ -f \"$STORE/$f\" ] || exit 1; cp \"$STORE/$f\" \"${@: -1}\"\n", + ); + write( + "barman-cloud-wal-archive", + "#!/bin/bash\nf=\"${@: -1}\"; cp \"$f\" \"$STORE/$(basename \"$f\")\"\n", + ); + // psql -At: the file's name, a bar, its content, and a newline. + write( + "psql", + "#!/bin/bash\nt=\"${@: -1}\"; t=${t##* }\n[ \"$t\" = 3 ] && { echo 'ERROR: could not open file' >&2; exit 1; }\nprintf '%08X.history|1\\t0/6000128\\tno recovery target specified\\n\\n' \"$t\"\n", + ); + let script = SCRIPT.replace("cd /work", &format!("cd {}", dir.join("work").display())) + .replace("/work/", &format!("{}/", dir.join("work").display())) + .replace("| tee /dev/termination-log", "") + .replace(">/dev/termination-log", &format!(">{}/said", dir.join("work").display())); + let run = |timeline: &str, store_rc: &str| { + std::process::Command::new("bash") + .args(["-c", &script]) + .env("PATH", format!("{}:{}", dir.join("bin").display(), std::env::var("PATH").unwrap())) + .env("STORE", dir.join("store")) + .env("STORE_RC", store_rc) + .env("TIMELINE", timeline) + .envs([("PGHOST_RW", "pg"), ("ENDPOINT", "e"), ("DESTINATION", "d"), ("SERVER", "s")]) + .output() + .unwrap() + }; + let store = |f: &str| std::fs::read_to_string(dir.join("store").join(f)).ok(); + + // Timeline 2's file is missing: written exactly as the primary has it. + let out = run("2", ""); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!( + store("00000002.history").as_deref(), + Some("1\t0/6000128\tno recovery target specified\n") + ); + // There already: left alone. + std::fs::write(dir.join("store/00000002.history"), "kept\n").unwrap(); + let out = run("2", ""); + assert!(out.status.success()); + assert!(String::from_utf8_lossy(&out.stdout).contains("is in the backups")); + assert_eq!(store("00000002.history").as_deref(), Some("kept\n")); + // An older timeline the primary no longer has (3) is skipped, the + // current one (4) is written. + let out = run("4", ""); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(store("00000003.history"), None); + assert!(store("00000004.history").is_some()); + // The current one the primary can't give: a failure. + std::fs::remove_file(dir.join("store/00000004.history")).unwrap(); + let out = run("3", ""); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("can't read 00000003.history from the primary")); + // The storage can't be read: nothing is written. + std::fs::remove_file(dir.join("store/00000002.history")).unwrap(); + let out = run("2", "2"); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("can't read the backups: boom")); + assert_eq!(store("00000002.history"), None); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn failures_in_plain_words() { + assert_eq!( + failure_message("x\ncan't read the backups: denied"), + "Backups can't be restored yet: can't read the backups: denied" + ); + assert_eq!( + failure_message(""), + "Backups can't be restored yet. Pyo is trying again" + ); + } +} diff --git a/crates/pyo-db-controller/src/main.rs b/crates/pyo-db-controller/src/main.rs index ea25cc24..7cf7464b 100644 --- a/crates/pyo-db-controller/src/main.rs +++ b/crates/pyo-db-controller/src/main.rs @@ -6,7 +6,7 @@ //! PYO_DB_POSTGRES_IMAGE Postgres image repository; the version is the tag (ghcr.io/cloudnative-pg/postgresql) //! PYO_DB_POSTGRES_IMAGE_ Pyo's Postgres image for that version (16, 17, 18), used instead //! PYO_DB_VALKEY_IMAGE Valkey image repository (docker.io/valkey/valkey) -//! PYO_DB_VALKEY_BUNDLE_IMAGE Valkey 8.1 with its modules, run while a Database loads any (docker.io/valkey/valkey-bundle:8.1.11@sha256:...) +//! PYO_DB_VALKEY_BUNDLE_IMAGE Valkey 8.1 with its modules, run while a Database loads any (docker.io/valkey/valkey-bundle:8.1.12@sha256:...) //! PYO_DB_PYO_KV_IMAGE pyo-kv image (ghcr.io/upsetdev/pyo-kv:latest) //! PYO_DB_MYSQL_IMAGE MySQL 8.4's mysqld image (ghcr.io/cybozu-go/moco/mysql:8.4.10.1) //! PYO_DB_DEFAULT_POSTGRES version when a Database doesn't say (18) @@ -19,6 +19,7 @@ mod controller; mod crd; mod extensions; +mod history; mod import; mod leader; mod modules; @@ -40,9 +41,9 @@ use kube::{ }; use tokio::io::AsyncWriteExt; -/// valkey-bundle 8.1.11 (Valkey 8.1.11 with valkey-json 1.0.3, valkey-bloom +/// valkey-bundle 8.1.12 (Valkey 8.1.12 with valkey-json 1.0.3, valkey-bloom /// 1.0.1 and valkey-search 1.0.3), the multi-platform index. -const VALKEY_BUNDLE: &str = "docker.io/valkey/valkey-bundle:8.1.11@sha256:3f57cc71a102e0e66991ae203b069038d8c3f6214ca887ff32f9a381091af8de"; +const VALKEY_BUNDLE: &str = "docker.io/valkey/valkey-bundle:8.1.12@sha256:ca9d1c30a6b3c30de34691ff5ddff6fb77f5c8c727a63723c62d8ebd280e7921"; fn env(k: &str, def: &str) -> String { std::env::var(k) diff --git a/crates/pyo-db-controller/src/postgres.rs b/crates/pyo-db-controller/src/postgres.rs index 34d5438c..0642a3a5 100644 --- a/crates/pyo-db-controller/src/postgres.rs +++ b/crates/pyo-db-controller/src/postgres.rs @@ -903,7 +903,22 @@ impl Kube<'_> { .map(|b| b.last_archived_wal.clone()) .filter(|s| !s.is_empty()) }); - Some(backup_status(&status, at)) + let mut b = backup_status(&status, at); + // The failover history a restore needs, when backups came + // on after a failover (history.rs). + if let (Some(on), Some(c)) = (backup_on(self.db), c.as_ref()) { + match self + .timeline_history(&on.destination, c, !primary.is_empty() && ready > 0) + .await + { + Ok(m) if b.message.is_empty() => b.message = m, + Ok(_) => {} + Err(e) => { + tracing::warn!(db = %self.name(), error = format!("{e:#}"), "timeline history") + } + } + } + Some(b) } None => None, }; diff --git a/crates/pyo-proto/src/bundles.rs b/crates/pyo-proto/src/bundles.rs index a2268dd8..2e550d9b 100644 --- a/crates/pyo-proto/src/bundles.rs +++ b/crates/pyo-proto/src/bundles.rs @@ -27,6 +27,7 @@ //! to one of its service accounts in each project namespace while it's //! installed (and in new ones as they're made), exactly that. +use std::collections::BTreeMap; use std::sync::OnceLock; use serde::{Deserialize, Serialize}; @@ -443,10 +444,25 @@ pub fn bindings_in( /// its images, Pyo Static and the databases system with the installation's /// (`PYO_STATIC_IMAGE`, `PYO_DB_CONTROLLER_IMAGE`, `PYO_KV_IMAGE`). pub fn policy_bundles(waf_image: &str, geoip_image: &str) -> Vec { + policy_bundles_with( + waf_image, + geoip_image, + &crate::system::static_image_from_env(), + &crate::system::db_images_from_env(), + ) +} + +/// [`policy_bundles`] with these images for Pyo Static and the databases. +pub fn policy_bundles_with( + waf_image: &str, + geoip_image: &str, + static_image: &str, + db: &crate::system::DbImages, +) -> Vec { vec![ waf_bundle(waf_image, geoip_image), - static_bundle(&crate::system::static_image_from_env()), - databases_bundle(&crate::system::db_images_from_env()), + static_bundle(static_image), + databases_bundle(db), ] } @@ -539,14 +555,14 @@ pub fn databases_bundle(img: &crate::system::DbImages) -> SystemBundle { "__POSTGRES_IMAGE_16__", "__POSTGRES_IMAGE_17__", "__POSTGRES_IMAGE_18__", - "ghcr.io/cloudnative-pg/cloudnative-pg:1.30.1@sha256:923c267ec29636db3bee20f993d0ec4973fa22998e1adad37da79e4d32b5bc07", + "ghcr.io/cloudnative-pg/cloudnative-pg:1.30.2@sha256:f96f6be3d81ec93819b443c665c575c609342fca840df90d4d87dae314a5b913", MYSQL_OPERATOR_PLACEHOLDER, MYSQL_BACKUP_PLACEHOLDER, "ghcr.io/cybozu-go/moco-agent:0.17.0@sha256:a6d9cc387a08a5d108ee89fb40e6274c47a435d3bb6fa71d4b822873e26b966b", "ghcr.io/cybozu-go/moco/fluent-bit:5.1.4.1@sha256:33895ebd0f7ba3d53d146b42a461ca6c05e51a78bed22cf158151bba059a5881", "ghcr.io/cybozu-go/moco/mysqld_exporter:0.20.0.1@sha256:793f8c94a43d03a2d1a176e80bfa99fa1ba0e4c4a83161f24a511e38da0e57e6", - "ghcr.io/cybozu-go/moco/mysql:8.4.10.1@sha256:51dffb347697795e1680b9930fea1e1055a71387a0e769cc61ab4efc539c149b", - "docker.io/valkey/valkey-bundle:8.1.11@sha256:3f57cc71a102e0e66991ae203b069038d8c3f6214ca887ff32f9a381091af8de", + "ghcr.io/cybozu-go/moco/mysql:8.4.10.1@sha256:bdb88ae2023dcba0218bf900c7f39117c7a6e4101de6b5c8f62774c1d897b68a", + "docker.io/valkey/valkey-bundle:8.1.12@sha256:ca9d1c30a6b3c30de34691ff5ddff6fb77f5c8c727a63723c62d8ebd280e7921", ] .map(str::to_owned) .to_vec(), @@ -605,6 +621,76 @@ pub fn databases_bundle(img: &crate::system::DbImages) -> SystemBundle { b } +/// The images databases themselves run, as a databases bundle gives them to +/// pyo-db-controller (its env): Pyo's Postgres per version ("postgres16", +/// "postgres17", "postgres18"), pyo-kv beside each KV database ("kv"), +/// MySQL's ("mysql") and Valkey with its modules ("valkeyBundle"). A database +/// restarts once when the image it runs changes. +pub fn database_images(b: &SystemBundle) -> BTreeMap { + const ENV: [(&str, &str); 6] = [ + ("PYO_DB_POSTGRES_IMAGE_16", "postgres16"), + ("PYO_DB_POSTGRES_IMAGE_17", "postgres17"), + ("PYO_DB_POSTGRES_IMAGE_18", "postgres18"), + ("PYO_DB_PYO_KV_IMAGE", "kv"), + ("PYO_DB_MYSQL_IMAGE", "mysql"), + ("PYO_DB_VALKEY_BUNDLE_IMAGE", "valkeyBundle"), + ]; + let mut out = BTreeMap::new(); + for c in b.containers() { + for e in c["env"].as_array().into_iter().flatten() { + let found = ENV.iter().find(|(name, _)| e["name"] == *name); + if let (Some((_, key)), Some(image)) = (found, e["value"].as_str()) + && !image.is_empty() + { + out.insert((*key).to_owned(), image.to_owned()); + } + } + } + out +} + +/// The database images a release's code pins itself (not built with the +/// release): MySQL's and Valkey's with its modules. release.json carries +/// them as `databasePins` (`pyo-agent database-pins`), so an installation +/// knows before it updates whether its databases restart. +pub fn database_pins() -> BTreeMap { + let mut all = database_images(&databases_bundle(&crate::system::DbImages { + controller: String::new(), + kv: String::new(), + postgres: Default::default(), + mysql_operator: String::new(), + mysql_backup: String::new(), + })); + all.retain(|k, _| DATABASE_PINS.contains(&k.as_str())); + all +} + +/// The keys of [`database_pins`]. +pub const DATABASE_PINS: [&str; 2] = ["mysql", "valkeyBundle"]; + +/// Whether a database restarts when the images go from `old` to `new` +/// ([`database_images`]): the one it runs is in both and differs. An image +/// one side doesn't name isn't known to change. `modules`: a KV database +/// that loads modules (it runs Valkey's image with them). +pub fn database_restarts( + engine: &str, + version: &str, + modules: bool, + old: &BTreeMap, + new: &BTreeMap, +) -> bool { + let major = version.split('.').next().unwrap_or(""); + let keys: Vec = match engine { + "postgres" => vec![format!("postgres{major}")], + "mysql" => vec!["mysql".into()], + "valkey" if modules => vec!["kv".into(), "valkeyBundle".into()], + "valkey" => vec!["kv".into()], + _ => vec![], + }; + keys.iter() + .any(|k| matches!((old.get(k), new.get(k)), (Some(a), Some(b)) if a != b)) +} + /// One of the databases system's Deployments that the agent stops on a /// small cluster while nothing needs it (pyo-agent's operators.rs). #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -687,20 +773,32 @@ pub fn never_pruned(r: &ObjectRef) -> bool { /// The web application firewall, with the installation's images (so it's /// built here, not loaded). Installed with the first service on the cluster /// that turns its WAF on, removed after the last one turns it off; its -/// version follows its images. +/// version follows its images and its objects, so a release that changes +/// its DaemonSet (its priority, say) updates it on every cluster. pub fn waf_bundle(waf_image: &str, geoip_image: &str) -> SystemBundle { use crate::system; - // FNV-1a: the same images, the same version. - let hash = format!("{waf_image}\n{geoip_image}") - .bytes() - .fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { - (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) - }); // Its settings are the agent's (waf.rs writes `config.json`), not the bundle's. let config = json!({ "apiVersion": "v1", "kind": "ConfigMap", "metadata": { "name": system::WAF_NAME, "namespace": system::WAF_NS, "labels": system::waf_labels() }, }); + let objects: Vec = [config] + .into_iter() + .chain(system::waf_access()) + .chain([ + system::waf_daemonset(waf_image, geoip_image), + system::waf_service(), + ]) + .collect(); + // FNV-1a: the same images and objects, the same version. + let hash = format!( + "{waf_image}\n{geoip_image}\n{}", + Value::Array(objects.clone()) + ) + .bytes() + .fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); SystemBundle { id: WAF_ID.into(), version: format!("{:08x}", hash >> 32), @@ -715,14 +813,7 @@ pub fn waf_bundle(waf_image: &str, geoip_image: &str) -> SystemBundle { }], in_use: vec![], managed_namespace_bindings: vec![], - objects: [config] - .into_iter() - .chain(system::waf_access()) - .chain([ - system::waf_daemonset(waf_image, geoip_image), - system::waf_service(), - ]) - .collect(), + objects, } } @@ -1078,6 +1169,26 @@ mod tests { ) } + /// The WAF's version follows what it writes, not only its images: a + /// release that makes its DaemonSet critical updates it on every + /// cluster, as the API resends a bundle whose version changed. + #[test] + fn the_wafs_version_follows_its_objects() { + let b = waf_bundle("w:1", "g:1"); + assert_eq!(b.version, waf_bundle("w:1", "g:1").version); + assert_ne!(b.version, waf_bundle("w:2", "g:1").version); + assert_eq!(b.version.len(), 8); + let images_only = "w:1\ng:1".bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); + assert_ne!(b.version, format!("{:08x}", images_only >> 32)); + let ds = b.objects.iter().find(|o| o["kind"] == "DaemonSet").unwrap(); + assert_eq!( + ds["spec"]["template"]["spec"]["priorityClassName"], + crate::system::SERVER_CRITICAL + ); + } + #[test] fn plurals() { assert_eq!(plural("Deployment"), "deployments"); @@ -1422,6 +1533,58 @@ mod tests { ); } + /// What a database runs comes from the bundle's own controller, so a + /// release that changes an image says which databases restart. + #[test] + fn databases_restart_when_their_image_changes() { + let old = database_images(&db()); + for k in ["postgres16", "postgres17", "postgres18", "kv", "mysql", "valkeyBundle"] { + assert!(old.contains_key(k), "{k}"); + } + assert_eq!(old["postgres18"], "registry.example.com/pyo/postgres:18-1"); + assert_eq!(old["kv"], "registry.example.com/pyo/kv:1"); + assert!(old["mysql"].starts_with("ghcr.io/cybozu-go/moco/mysql:")); + // The same images: nothing restarts. + for (engine, version) in [("postgres", "18"), ("mysql", "8.4"), ("valkey", "8.1")] { + assert!(!database_restarts(engine, version, true, &old, &old), "{engine}"); + } + // A new Postgres 18 image: only Postgres 18 databases. + let mut new = old.clone(); + new.insert("postgres18".into(), "registry.example.com/pyo/postgres:18-2".into()); + assert!(database_restarts("postgres", "18", false, &old, &new)); + assert!(database_restarts("postgres", "18.1", false, &old, &new)); + assert!(!database_restarts("postgres", "17", false, &old, &new)); + assert!(!database_restarts("mysql", "8.4", false, &old, &new)); + assert!(!database_restarts("valkey", "8.1", true, &old, &new)); + // MySQL's, and Valkey's with modules only where a database loads any. + let mut new = old.clone(); + new.insert("mysql".into(), "mysql:2".into()); + new.insert("valkeyBundle".into(), "bundle:2".into()); + assert!(database_restarts("mysql", "8.4", false, &old, &new)); + assert!(database_restarts("valkey", "8.1", true, &old, &new)); + assert!(!database_restarts("valkey", "8.1", false, &old, &new)); + assert!(!database_restarts("postgres", "16", false, &old, &new)); + // pyo-kv: every KV database. + let mut new = old.clone(); + new.insert("kv".into(), "kv:2".into()); + assert!(database_restarts("valkey", "9.0", false, &old, &new)); + // An image one side doesn't name isn't known to change. + let mut unknown = old.clone(); + unknown.remove("mysql"); + assert!(!database_restarts("mysql", "8.4", false, &unknown, &old)); + assert!(!database_restarts("mysql", "8.4", false, &old, &unknown)); + assert!(!database_restarts("sqlite", "3", false, &old, &new)); + } + + /// What release.json carries of them: the two the code pins, by digest. + #[test] + fn database_pins_are_the_images_the_code_pins() { + let pins = database_pins(); + assert_eq!(pins.keys().map(String::as_str).collect::>(), DATABASE_PINS); + assert!(pins.values().all(|i| crate::pinned_image(i)), "{pins:?}"); + assert_eq!(pins["mysql"], database_images(&db())["mysql"]); + } + /// The agent starts and stops the operators: their replica count is /// left out of what's applied, so an update keeps a stopped one stopped. #[test] diff --git a/crates/pyo-proto/src/firewall.rs b/crates/pyo-proto/src/firewall.rs index 4122883d..e95af907 100644 --- a/crates/pyo-proto/src/firewall.rs +++ b/crates/pyo-proto/src/firewall.rs @@ -591,6 +591,38 @@ pub fn web_authorization(fw: &Firewall, entry: Entry) -> Option { Some(json!({ "defaultAction": default, "rules": rules })) } +/// A website's authorization on its tunnel routes once its record points +/// at the tunnel (`DomainSpec::tunnel_only`): the behind gate first, so only +/// the tunnel's connectors (whose visitor was read from X-Forwarded-For) +/// get through and a direct connection gets 403, then the service's own +/// rules. The service's own "behind" CDN doesn't apply there. +pub fn tunnel_authorization(fw: &Firewall) -> Value { + let own = Firewall { + behind: None, + ..fw.clone() + }; + let (default, rules) = match authorization(&[&own], true) { + Some(a) => ( + a["defaultAction"].clone(), + a["rules"].as_array().cloned().unwrap_or_default(), + ), + None => (json!("Allow"), vec![]), + }; + let rules: Vec = [behind_gate_rule()].into_iter().chain(rules).collect(); + json!({ "defaultAction": default, "rules": rules }) +} + +/// What a tunnel client policy trusts: these addresses, or (with none +/// yet) one no connection ever comes from, never "anyone". +pub fn trusted_or_nothing(mut cidrs: Vec) -> Vec { + cidrs.sort(); + cidrs.dedup(); + if cidrs.is_empty() { + cidrs.push(NOTHING.into()); + } + cidrs +} + /// Whether a website's plain HTTP routes take its rate limits: not behind /// a CDN, where every request there comes from the CDN's few addresses. pub fn http_rate_limits(fw: &Firewall) -> bool { diff --git a/crates/pyo-proto/src/lib.rs b/crates/pyo-proto/src/lib.rs index a37bd39c..a15985d7 100644 --- a/crates/pyo-proto/src/lib.rs +++ b/crates/pyo-proto/src/lib.rs @@ -146,6 +146,58 @@ pub struct Heartbeat { /// services get what a newer agent writes. Empty from older agents. #[serde(default, skip_serializing_if = "String::is_empty")] pub routes_version: String, + /// The Cloudflare Tunnel connector, when the cluster has one (or the + /// agent knows tunnels: then it says it has none). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tunnel: Option, +} + +/// The cluster's Cloudflare Tunnel connector, as the agent sees it. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TunnelReport { + /// The tunnel its token is for (the Secret's label). None: no token here. + #[serde(default)] + pub tunnel_id: Option, + #[serde(default)] + pub replicas: i32, + #[serde(default)] + pub ready_replicas: i32, + #[serde(default)] + pub pods: Vec, + /// The origin Service is in place. + #[serde(default)] + pub origin_ready: bool, + /// The cluster's install refused a tunnel object: its admission policy + /// is older than the agent's. What runs is kept as it is. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub refused: bool, +} + +/// One connector pod. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TunnelPod { + pub server: String, + pub ready: bool, + #[serde(default)] + pub restarts: i32, + /// Why it isn't ready ("ImagePullBackOff"), at most 200 characters. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +/// The Cloudflare Tunnel connector Pyo wants ([`HeartbeatReply::tunnel`]). +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TunnelWanted { + /// The tunnel to run (with the token the agent has for it). None: + /// remove the connector and its token. + #[serde(default)] + pub tunnel_id: Option, + /// In tunnel mode, TCP and UDP ports stay published on the servers. + #[serde(default)] + pub ports_public: bool, } /// A server's Tailscale, as tailscaled says (the agent's tailnet pod on it). @@ -531,6 +583,10 @@ pub struct Capabilities { /// firewall sync is on its way, is still starting. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub waf_active: Vec, + /// The agent runs a Cloudflare Tunnel connector (`TunnelSet`) and + /// writes tunnel domains' routes. + #[serde(default)] + pub tunnel: bool, } /// A server where the gateway can't get some of its ports. @@ -1307,6 +1363,12 @@ pub enum Command { /// The team's registry tokens (their hashes) for the door of the /// cluster's own registry: these, and no others, from now on. SyncRegistryTokens(Box), + /// Run the cluster's Cloudflare Tunnel connector with this token: kept + /// as the Secret pyo-system/pyo-tunnel, labelled with the tunnel's id, + /// and the connector (re)applied. `data` is a [`TunnelReport`]. + TunnelSet { tunnel_id: String, token: String }, + /// Stop the connector and delete its token. + TunnelRemove {}, } // ── Releases and updates ─────────────────────────────────────────────────── @@ -1334,12 +1396,19 @@ pub struct Release { /// What to know or do before updating (breaking changes, manual steps). #[serde(default)] pub before_you_update: Vec, - /// The release's [`rbac::access_hash`]: its agent's roles. When it isn't - /// the running Pyo's, every cluster needs its connect command after - /// the update (updates.rs says so first). The release's own agent - /// checks it (`pyo-agent check-release`). + /// The release's [`rbac::access_hash`]: its agent's roles and admission + /// policy. When it isn't the running Pyo's, every cluster without the + /// self-update role needs its connect command after the update + /// (updates.rs says so first, on an installation without it). The + /// release's own agent checks it (`pyo-agent check-release`). #[serde(default, skip_serializing_if = "Option::is_none")] pub agent_access: Option, + /// The database images the release's code pins itself + /// ([`bundles::database_pins`]: MySQL's, Valkey's with its modules). + /// With `images`, what its databases run ([`Release::database_images`]). + /// The release's own agent checks it (`pyo-agent check-release`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub database_pins: Option>, } #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] @@ -1469,6 +1538,25 @@ pub fn parse_version(v: &str) -> Option<(u64, u64, u64)> { } impl Release { + /// The images its databases run, by [`bundles::database_images`]' keys: + /// Pyo's Postgres and pyo-kv from `images`, the rest from + /// `databasePins`. One it doesn't name is left out. + pub fn database_images(&self) -> std::collections::BTreeMap { + let mut out = self.database_pins.clone().unwrap_or_default(); + out.retain(|k, _| bundles::DATABASE_PINS.contains(&k.as_str())); + for (key, image) in [ + ("postgres16", &self.images.postgres16), + ("postgres17", &self.images.postgres17), + ("postgres18", &self.images.postgres18), + ("kv", &self.images.kv), + ] { + if !image.is_empty() { + out.insert(key.to_owned(), image.clone()); + } + } + out + } + /// What's wrong with it, if anything: a release Pyo would apply must /// name its version and pin every one of Pyo's images by digest, and /// its manifests may only use those (or images that aren't Pyo's). @@ -2295,8 +2383,30 @@ pub struct DomainSpec { /// Send plain HTTP requests to HTTPS (when `tls` is set). #[serde(default)] pub redirect_https: bool, + /// Through the cluster's Cloudflare Tunnel: "switching" (the tunnel and + /// direct visitors both get through, while its record moves) or "on" + /// (only the tunnel: direct connections get 403, no plain HTTP route). + /// "": direct only. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub tunnel: String, +} + +impl DomainSpec { + /// Served through the tunnel ("switching" or "on"). + pub fn via_tunnel(&self) -> bool { + matches!(self.tunnel.as_str(), TUNNEL_SWITCHING | TUNNEL_ON) + } + /// Only through the tunnel. + pub fn tunnel_only(&self) -> bool { + self.tunnel == TUNNEL_ON + } } +/// A domain's `tunnel` while its record moves: both paths answer. +pub const TUNNEL_SWITCHING: &str = "switching"; +/// A domain's `tunnel` once its record points at the tunnel. +pub const TUNNEL_ON: &str = "on"; + /// An uploaded certificate, as the agent gets it: the chain and its key, PEM. #[derive(Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -2680,6 +2790,15 @@ pub struct HeartbeatReply { /// without it): left as it is. #[serde(default, skip_serializing_if = "Option::is_none")] pub public_dashboard: Option, + /// The Cloudflare Tunnel connector. None (a reply without it): left as + /// it is. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tunnel: Option, + /// Public TCP and UDP ports are published on the servers: with public + /// traffic, or in tunnel mode when the cluster keeps them. None (a + /// reply without it): as `public_traffic` says. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub public_ports: Option, } /// Pyo's dashboard on the public IP ([`system::public_dashboard_objects`]). @@ -3029,6 +3148,31 @@ mod release_tests { } } + /// What a release's databases run: Pyo's own images and the pins its + /// code carries, under the keys a bundle's are compared by. + #[test] + fn a_release_names_its_database_images() { + let mut r = release(); + let images = r.database_images(); + assert_eq!( + images.keys().map(String::as_str).collect::>(), + ["kv", "postgres16", "postgres17", "postgres18"] + ); + assert_eq!(images["postgres18"], r.images.postgres18); + r.database_pins = Some( + [("mysql", "m@sha256:1"), ("other", "x")] + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .into(), + ); + let images = r.database_images(); + assert_eq!(images["mysql"], "m@sha256:1"); + assert!(!images.contains_key("other")); + // As release.json spells it, and left out when a release has none. + let json = serde_json::to_value(&r).unwrap(); + assert_eq!(json["databasePins"]["mysql"], "m@sha256:1"); + assert!(serde_json::to_value(release()).unwrap().get("databasePins").is_none()); + } + #[test] fn versions() { assert_eq!(parse_version("0.2.0"), Some((0, 2, 0))); diff --git a/crates/pyo-proto/src/rbac.rs b/crates/pyo-proto/src/rbac.rs index 2e4b8e1c..44ced18c 100644 --- a/crates/pyo-proto/src/rbac.rs +++ b/crates/pyo-proto/src/rbac.rs @@ -7,12 +7,17 @@ //! (pyo-system) and the projects' it creates. Each gets a RoleBinding to //! `pyo-agent-write`, the only role the agent may bind. //! - A few named objects elsewhere: the gateway's objects in -//! `pyo-gateway`, the GPU device plugin, join tokens, CoreDNS's replica +//! `pyo-gateway` (its Services, network policies and ConfigMaps named by +//! the admission policy, not the role), the GPU device plugin, join tokens, CoreDNS's replica //! count and disruption budget, two certificate issuers, the proxy's //! GatewayClass and a RuntimeClass. //! - Servers (labels, taints, cordon, drain, removal) in a role of their own //! that can be left out. //! - The customer's `pyo-system/pyo-policy` ConfigMap: read, never written. +//! - `pyo-system/pyo-verifier`, where the server's verifier says how its +//! automatic updates stand: read, never written. +//! - Its own Deployment: only its image, image pins, install stamp, and its +//! pods' priority and tolerations as this release sets them. //! //! RBAC can't say "only these names" for creating, or "only namespaces with //! this label"; the ValidatingAdmissionPolicy does, for requests made by the @@ -40,6 +45,10 @@ pub const WRITE_ROLE: &str = "pyo-agent-write"; pub const WRITE_BINDING: &str = "pyo-agent"; /// The customer's switches (see `Policy`), only ever read. pub const POLICY_CONFIGMAP: &str = "pyo-policy"; +/// Where the verifier on the cluster's first server (`pyo-verify`, run as +/// root by a timer there) writes how its automatic updates stand (see +/// [`VerifierStatus`]), only ever read. +pub const VERIFIER_CONFIGMAP: &str = "pyo-verifier"; /// The admission policy and its binding. pub const ADMISSION_POLICY: &str = "pyo-agent"; /// Server operations: optional. @@ -53,6 +62,156 @@ pub const UPGRADER: &str = "pyo-upgrade"; const RBAC: &str = "rbac.authorization.k8s.io/v1"; +/// The agent's own Deployment, in [`NS`]. +pub const AGENT_DEPLOYMENT: &str = "pyo-agent"; +/// Its pods' priority: a server short of disk or memory neither evicts the +/// agent nor refuses a new one, so it goes on reporting and cleaning up +/// there. The connect command sets it, and a refresh brings it. +pub const AGENT_PRIORITY: &str = "system-cluster-critical"; + +/// Its pods' tolerations, in this order: a GPU server kept for GPU work, +/// and a server short of disk or memory (so a new agent starts there after +/// an update). The connect command sets them, and a refresh brings them. +pub fn agent_tolerations() -> Value { + json!([ + { "key": crate::GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }, + { "key": "node.kubernetes.io/disk-pressure", "operator": "Exists", "effect": "NoSchedule" }, + { "key": "node.kubernetes.io/memory-pressure", "operator": "Exists", "effect": "NoSchedule" }, + ]) +} + +/// Its pod spec's fields that the agent never changes (all but its +/// containers, priority and tolerations), as of Kubernetes 1.30: a field +/// the API server doesn't know would break the whole policy. +const AGENT_POD_KEPT: [&str; 34] = [ + "activeDeadlineSeconds", + "affinity", + "automountServiceAccountToken", + "dnsConfig", + "dnsPolicy", + "enableServiceLinks", + "ephemeralContainers", + "hostAliases", + "hostIPC", + "hostNetwork", + "hostPID", + "hostUsers", + "hostname", + "imagePullSecrets", + "initContainers", + "nodeName", + "nodeSelector", + "os", + "overhead", + "preemptionPolicy", + "priority", + "readinessGates", + "resourceClaims", + "restartPolicy", + "runtimeClassName", + "schedulerName", + "schedulingGates", + "securityContext", + "serviceAccountName", + "setHostnameAsFQDN", + "shareProcessNamespace", + "subdomain", + "terminationGracePeriodSeconds", + "volumes", +]; +/// Its containers' fields that the agent never changes (all but the agent +/// container's image and the pinned env values), as of Kubernetes 1.30. +const AGENT_CONTAINER_KEPT: [&str; 20] = [ + "args", + "command", + "envFrom", + "imagePullPolicy", + "lifecycle", + "livenessProbe", + "ports", + "readinessProbe", + "resizePolicy", + "resources", + "restartPolicy", + "securityContext", + "startupProbe", + "stdin", + "stdinOnce", + "terminationMessagePath", + "terminationMessagePolicy", + "tty", + "volumeDevices", + "volumeMounts", +]; +/// The Deployment spec's fields kept as they are (all but its template). +const AGENT_SPEC_KEPT: [&str; 7] = [ + "minReadySeconds", + "paused", + "progressDeadlineSeconds", + "replicas", + "revisionHistoryLimit", + "selector", + "strategy", +]; + +/// CEL: `new.f` and `old.f` both missing, or equal. +fn kept_field(new: &str, old: &str, f: &str) -> String { + format!("(has({new}.{f}) == has({old}.{f}) && (!has({new}.{f}) || {new}.{f} == {old}.{f}))") +} + +/// CEL, for an update of the agent's own Deployment: all as it was but the +/// install stamp, the agent container's image (an update of the agent) and +/// pinned env values (a refresh), and its pods' priority and tolerations, +/// which may only become [`AGENT_PRIORITY`] and [`agent_tolerations`]. So +/// its token, Pyo's address, its other env, volumes and service account +/// stay as the connect command set them. +pub fn agent_deployment_kept() -> String { + let (n, o) = ("object", "oldObject"); + let (t, ot) = ("object.spec.template.spec", "oldObject.spec.template.spec"); + let ann = + |x: &str| format!("(has({x}.metadata.annotations) ? {x}.metadata.annotations : {{}})"); + let labels = |x: &str| format!("(has({x}.metadata.labels) ? {x}.metadata.labels : {{}})"); + let spec: Vec = AGENT_SPEC_KEPT + .iter() + .map(|f| kept_field(&format!("{n}.spec"), &format!("{o}.spec"), f)) + .collect(); + let pod: Vec = AGENT_POD_KEPT + .iter() + .map(|f| kept_field(t, ot, f)) + .collect(); + let container: Vec = AGENT_CONTAINER_KEPT + .iter() + .map(|f| kept_field("c", "p", f)) + .collect(); + let pinned = cel_literal(&json!(PINNED_ENV)); + format!( + "{labels_n} == {labels_o} && \ + {ann_n}.all(k, k == '{stamp}' || (k in {ann_o} && {ann_o}[k] == {ann_n}[k])) && {ann_o}.all(k, k == '{stamp}' || k in {ann_n}) && \ + {spec} && {template_meta} && {pod} && \ + (!has({t}.priorityClassName) ? !has({ot}.priorityClassName) : ({t}.priorityClassName == '{priority}' || (has({ot}.priorityClassName) && {ot}.priorityClassName == {t}.priorityClassName))) && \ + ((has({t}.tolerations) ? {t}.tolerations : []) == (has({ot}.tolerations) ? {ot}.tolerations : []) || (has({t}.tolerations) && {t}.tolerations == {tolerations})) && \ + size({t}.containers) == size({ot}.containers) && \ + {t}.containers.all(c, {ot}.containers.exists(p, p.name == c.name && (c.name == 'agent' || c.image == p.image) && {container} && \ + (has(c.env) ? c.env : []).all(e, e.name in {pinned} ? !has(e.valueFrom) : (has(p.env) && p.env.exists(x, x == e))) && \ + (has(p.env) ? p.env : []).all(x, x.name in {pinned} || (has(c.env) && c.env.exists(e, e == x)))))", + labels_n = labels(n), + labels_o = labels(o), + ann_n = ann(n), + ann_o = ann(o), + stamp = INSTALL_ANNOTATION, + spec = spec.join(" && "), + template_meta = kept_field( + &format!("{n}.spec.template"), + &format!("{o}.spec.template"), + "metadata" + ), + pod = pod.join(" && "), + priority = AGENT_PRIORITY, + tolerations = cel_literal(&agent_tolerations()), + container = container.join(" && "), + ) +} + fn labels() -> Value { json!({ "app.kubernetes.io/managed-by": "pyo", "app.kubernetes.io/part-of": "pyo-agent" }) } @@ -219,12 +378,12 @@ pub fn objects(upgrades: bool) -> Vec { ]), ), write_binding(NS), - // The customer's switches: read only. + // The customer's switches, and their verifier's status: read only. role( NS, "pyo-agent-policy", json!([ - { "apiGroups": [""], "resources": ["configmaps"], "verbs": ["get"], "resourceNames": [POLICY_CONFIGMAP] }, + { "apiGroups": [""], "resources": ["configmaps"], "verbs": ["get"], "resourceNames": [POLICY_CONFIGMAP, VERIFIER_CONFIGMAP] }, ]), ), role_binding(NS, "pyo-agent-policy", "Role", "pyo-agent-policy"), @@ -258,16 +417,15 @@ pub fn objects(upgrades: bool) -> Vec { { "apiGroups": ["gateway.envoyproxy.io"], "resources": ["backends", "clienttrafficpolicies", "securitypolicies", "backendtrafficpolicies", "envoyextensionpolicies", "envoyproxies"], "verbs": ALL }, { "apiGroups": ["cert-manager.io"], "resources": ["certificates"], "verbs": ALL }, { "apiGroups": [""], "resources": ["secrets"], "verbs": ["create", "patch", "delete"] }, - { "apiGroups": [""], "resources": ["configmaps"], "verbs": ["create"] }, - { "apiGroups": [""], "resources": ["configmaps"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::ORIGIN_PULL_SECRET] }, - // The firewall for UDP ports: a network policy on the proxy's pods. - { "apiGroups": ["networking.k8s.io"], "resources": ["networkpolicies"], "verbs": ["create"] }, - { "apiGroups": ["networking.k8s.io"], "resources": ["networkpolicies"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::FIREWALL_POLICY] }, - // Websites on the servers' Tailscale addresses: its own Service. - { "apiGroups": [""], "resources": ["services"], "verbs": ["create"] }, - { "apiGroups": [""], "resources": ["services"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::TAILNET_WEB_SERVICE, system::TAILNET_VIP_SERVICE, system::PUBLIC_NAT_SERVICE] }, - // The Tailscale Services' wanted list, for the servers' tailnet pods. - { "apiGroups": [""], "resources": ["configmaps"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::TAILNET_WANTED] }, + // Services, network policies and ConfigMaps: written without + // names here, so a release that adds one changes no role. + // The admission policy (`gatewayAllowed`) holds each to + // Pyo's own, by name and content. ConfigMaps are read by + // name only. + { "apiGroups": [""], "resources": ["services"], "verbs": ["get", "create", "patch", "delete"] }, + { "apiGroups": ["networking.k8s.io"], "resources": ["networkpolicies"], "verbs": ["get", "create", "patch", "delete"] }, + { "apiGroups": [""], "resources": ["configmaps"], "verbs": ["create", "patch", "delete"] }, + { "apiGroups": [""], "resources": ["configmaps"], "verbs": ["get"], "resourceNames": [system::ORIGIN_PULL_SECRET, system::TAILNET_WANTED] }, // The proxy's failed pods, cleaned up (an eviction on a full // disk leaves one each try). { "apiGroups": [""], "resources": ["pods"], "verbs": ["delete"] }, @@ -382,7 +540,95 @@ fn waf_pinned_for(block: bool) -> serde_json::Map { /// `waf_image` and `geoip_image`: the installation's images for the WAF's /// processor and the proxies' GeoIP database, the only ones they may use. pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { - let bundles = bundles::policy_bundles(waf_image, geoip_image); + admission_for(false, waf_image, geoip_image) +} + +/// [`admission`] for an install with (`self_update`) or without the +/// [`SELF_UPDATE_ROLE`]: with it, the policy lets the agent update its own +/// roles and bindings ([`own_roles_cel`]). Without it that stays refused, +/// whatever the roles say. +pub fn admission_for(self_update: bool, waf_image: &str, geoip_image: &str) -> Vec { + admission_with( + self_update, + waf_image, + geoip_image, + &system::static_image_from_env(), + &system::db_images_from_env(), + ) +} + +/// The agent's own roles and bindings, as every install can have them +/// (the upgrader's and the self-update role's too): (resource, namespace or +/// "", name). +pub fn own_role_objects() -> Vec<(String, String, String)> { + let mut out: Vec<(String, String, String)> = objects(true) + .iter() + .chain(self_update_objects().iter()) + .filter_map(|o| { + let resource = match o["kind"].as_str()? { + "ClusterRole" => "clusterroles", + "ClusterRoleBinding" => "clusterrolebindings", + "Role" => "roles", + "RoleBinding" => "rolebindings", + _ => return None, + }; + Some(( + resource.to_owned(), + o["metadata"]["namespace"].as_str().unwrap_or("").to_owned(), + o["metadata"]["name"].as_str()?.to_owned(), + )) + }) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// The `ownRoles` variable, with the self-update role: an update (never a +/// create or a delete) of one of the agent's own roles or bindings, by +/// namespace and name. A binding's subjects stay Pyo's own accounts in +/// pyo-system (Kubernetes never lets a binding's role change). What a role +/// holds isn't pinned: a later release's rules are what a refresh brings. +fn own_roles_cel() -> String { + let own = own_role_objects(); + let of = |resource: &str| -> Value { + json!( + own.iter() + .filter(|(r, _, _)| r == resource) + .map(|(_, ns, name)| if ns.is_empty() { + name.clone() + } else { + format!("{ns}/{name}") + }) + .collect::>() + ) + }; + let subjects = format!( + "has(object.subjects) && object.subjects.all(s, s.kind == 'ServiceAccount' && has(s.namespace) && s.namespace == '{NS}' && s.name in ['{SA}', '{TAILNET_SA}'])" + ); + format!( + "request.resource.group == 'rbac.authorization.k8s.io' && request.operation == 'UPDATE' && variables.sub == '' && (\ + (request.resource.resource == 'clusterroles' && variables.reqName in {cluster_roles}) || \ + (request.resource.resource == 'clusterrolebindings' && variables.reqName in {cluster_bindings} && {subjects}) || \ + (request.resource.resource == 'roles' && (variables.ns + '/' + variables.reqName) in {roles}) || \ + (request.resource.resource == 'rolebindings' && (variables.ns + '/' + variables.reqName) in {bindings} && {subjects}))", + cluster_roles = cel_literal(&of("clusterroles")), + cluster_bindings = cel_literal(&of("clusterrolebindings")), + roles = cel_literal(&of("roles")), + bindings = cel_literal(&of("rolebindings")), + ) +} + +/// [`admission_for`] with these images for Pyo Static and the databases +/// too, rather than the installation's. +pub fn admission_with( + self_update: bool, + waf_image: &str, + geoip_image: &str, + static_image: &str, + db: &system::DbImages, +) -> Vec { + let bundles = bundles::policy_bundles_with(waf_image, geoip_image, static_image, db); // The pod spec of whatever the request makes pods from. let pod_spec = "object.kind == 'Pod' ? object.spec : object.kind == 'CronJob' ? object.spec.jobTemplate.spec.template.spec : object.spec.template.spec"; let validations = json!([ @@ -395,12 +641,12 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { }, // Only namespaces it manages, and the named objects of kube-system. { - "expression": "variables.ns == '' || request.resource.resource == 'namespaces' || variables.managed || variables.kubeSystemAllowed || variables.gatewayAllowed || variables.drain || variables.bundleAllowed", + "expression": "variables.ns == '' || request.resource.resource == 'namespaces' || variables.managed || variables.kubeSystemAllowed || variables.gatewayAllowed || variables.drain || variables.bundleAllowed || variables.ownRoles", "messageExpression": "variables.ns in ['kube-system', 'pyo-gateway'] ? 'In ' + variables.ns + ', Pyo\\'s agent only writes its own objects, with exactly the content this release defines.' : 'Pyo\\'s agent only changes namespaces labelled pyo.dev/managed=true; ' + variables.ns + ' isn\\'t one.'", }, // Bundles' cluster-wide objects and charts: only as a bundle has them. { - "expression": format!("!(request.resource.resource in {}) || variables.bundleAllowed", cel_literal(&json!(bundles::guarded_resources()))), + "expression": format!("!(request.resource.resource in {}) || variables.bundleAllowed || variables.ownRoles", cel_literal(&json!(bundles::guarded_resources()))), "message": "Pyo's agent only writes its components' own objects, as this release defines them.", }, // In a bundle's namespace, only the bundle's own containers. @@ -461,11 +707,11 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { }, // RoleBindings: the write role, to the agent; the upgrader's, to the upgrader. { - "expression": "request.resource.resource != 'rolebindings' || request.operation == 'DELETE' || (object.roleRef.kind == 'ClusterRole' && object.roleRef.name == 'pyo-agent-write' && object.subjects.all(s, s.kind == 'ServiceAccount' && s.name == 'pyo-agent' && s.namespace == 'pyo-system')) || (variables.ns == 'pyo-system' && object.metadata.name == 'pyo-upgrade' && object.roleRef.kind == 'Role' && object.roleRef.name == 'pyo-upgrade' && object.subjects.all(s, s.kind == 'ServiceAccount' && s.name == 'pyo-upgrade' && s.namespace == 'pyo-system')) || variables.bundleAllowed", + "expression": "request.resource.resource != 'rolebindings' || request.operation == 'DELETE' || (object.roleRef.kind == 'ClusterRole' && object.roleRef.name == 'pyo-agent-write' && object.subjects.all(s, s.kind == 'ServiceAccount' && s.name == 'pyo-agent' && s.namespace == 'pyo-system')) || (variables.ns == 'pyo-system' && object.metadata.name == 'pyo-upgrade' && object.roleRef.kind == 'Role' && object.roleRef.name == 'pyo-upgrade' && object.subjects.all(s, s.kind == 'ServiceAccount' && s.name == 'pyo-upgrade' && s.namespace == 'pyo-system')) || variables.bundleAllowed || variables.ownRoles", "message": "Pyo's agent may only bind its own write role to itself.", }, { - "expression": "request.resource.resource != 'roles' || (variables.ns == 'pyo-system' && variables.reqName == 'pyo-upgrade') || variables.bundleAllowed", + "expression": "request.resource.resource != 'roles' || (variables.ns == 'pyo-system' && variables.reqName == 'pyo-upgrade') || variables.bundleAllowed || variables.ownRoles", "message": "Pyo's agent may only write the upgrader's role, and its components' own.", }, // The customer's policy is theirs. @@ -473,6 +719,18 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { "expression": "!(request.resource.resource == 'configmaps' && variables.ns == 'pyo-system' && variables.reqName == 'pyo-policy')", "message": "pyo-system/pyo-policy belongs to you: Pyo's agent only reads it.", }, + // So is what their server's verifier says of its automatic updates. + { + "expression": format!("!(request.resource.resource == 'configmaps' && variables.ns == '{NS}' && variables.reqName == '{VERIFIER_CONFIGMAP}')"), + "message": "pyo-system/pyo-verifier belongs to your server: Pyo's agent only reads it.", + }, + // Its own Deployment: only updated, and then only its image, image + // pins, install stamp, priority and tolerations, the last two to + // exactly this release's. + { + "expression": format!("!(request.resource.resource == 'deployments' && variables.ns == '{NS}' && variables.objName == '{AGENT_DEPLOYMENT}') || (request.operation == 'UPDATE' && variables.sub == '' && {})", agent_deployment_kept()), + "message": "Pyo's agent only changes its own Deployment's image, image pins, install stamp, priority and tolerations, as this release sets them.", + }, // No privileged containers, host namespaces or host paths, except // Pyo's own components that need them. { @@ -545,7 +803,7 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { (!has(object.spec.connection) || (object.spec.connection.all(k, k in ['connectionLimit', 'maxAcceptPerSocketEvent']) && (!has(object.spec.connection.maxAcceptPerSocketEvent) || object.spec.connection.maxAcceptPerSocketEvent == 1) && (!has(object.spec.connection.connectionLimit) || (object.spec.connection.connectionLimit.all(k, k == 'value') && object.spec.connection.connectionLimit.value >= 1)))) && \ (!has(object.spec.proxyProtocol) || object.spec.proxyProtocol == {pp_optional})) || \ (object.metadata.labels[?'{cdn_label}'].orValue('') in {behind} && object.spec.all(k, k in ['targetRefs', 'clientIPDetection', 'connection', 'headers', 'tls', 'proxyProtocol', 'timeout']) && ({cdn_headers}) && \ - size(object.spec.targetRefs) >= 1 && object.spec.targetRefs.all(t, t.group == 'gateway.networking.k8s.io' && t.kind == 'Gateway' && t.name + '-cdn' == variables.objName && has(t.sectionName) && t.sectionName.startsWith('h-')) && \ + size(object.spec.targetRefs) >= 1 && object.spec.targetRefs.all(t, t.group == 'gateway.networking.k8s.io' && t.kind == 'Gateway' && t.name + (object.metadata.labels[?'{cdn_label}'].orValue('') == '{tunnel_cdn}' ? '-{tunnel_cdn}' : '-cdn') == variables.objName && has(t.sectionName) && t.sectionName.startsWith('h-')) && \ {ctp_https}.exists(v, ['connection', 'tls', 'proxyProtocol', 'timeout'].all(k, (k in v) == (k in object.spec) && (!(k in v) || v[k] == object.spec[k]))) && \ object.spec.clientIPDetection.all(k, k == 'xForwardedFor') && object.spec.clientIPDetection.xForwardedFor.all(k, k == 'trustedCIDRs') && \ size(object.spec.clientIPDetection.xForwardedFor.trustedCIDRs) >= 1 && size(object.spec.clientIPDetection.xForwardedFor.trustedCIDRs) <= {max_trusted} && \ @@ -586,6 +844,13 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { (request.resource.resource == 'services' && variables.objName == '{vip_svc}' && variables.sub == '' && (request.operation == 'DELETE' || (object.spec.all(k, k in {tw_keys}) && \ object.spec.type == 'ClusterIP' && object.spec.externalTrafficPolicy == 'Local' && object.spec.selector == {tw_selector} && object.spec.ports == {vip_ports} && \ size(object.spec.externalIPs) >= 1 && size(object.spec.externalIPs) <= 1024 && object.spec.externalIPs.all(ip, ip.matches({tw_v4}) || ip.matches({tw_v6}))))) || \ + (request.resource.resource == 'services' && variables.objName == '{origin_svc}' && variables.sub == '' && (request.operation == 'DELETE' || (object.spec.all(k, k in {origin_keys}) && \ + object.spec.type == 'ClusterIP' && object.spec.selector == {tw_selector} && object.spec.ports == {origin_ports}))) || \ + (request.resource.resource == 'services' && variables.objName == '{pp_svc}' && variables.sub == '' && (request.operation == 'DELETE' || (object.spec.all(k, k in {pp_keys}) && \ + object.spec.type == 'LoadBalancer' && object.spec.externalTrafficPolicy == 'Local' && object.spec.selector == {tw_selector} && size(object.spec.ports) >= 1 && size(object.spec.ports) <= 256 && \ + object.spec.ports.all(p, p.all(k, k in ['name', 'port', 'targetPort', 'protocol', 'nodePort']) && \ + ((p.protocol == 'UDP' && !(p.port in {udp_reserved})) || (p.protocol == 'TCP' && !(p.port in {tcp_reserved}) && !(p.port >= 19000 && p.port <= 19003))) && \ + p.targetPort == (p.port < 1024 ? p.port + 10000 : p.port))))) || \ (request.resource.resource == 'services' && variables.objName == '{nat_svc}' && variables.sub == '' && (request.operation == 'DELETE' || (object.spec.all(k, k in {tw_keys}) && \ object.spec.type == 'ClusterIP' && object.spec.externalTrafficPolicy == 'Local' && object.spec.selector == {tw_selector} && object.spec.ports == {tw_ports} && \ size(object.spec.externalIPs) >= 1 && size(object.spec.externalIPs) <= 64 && object.spec.externalIPs.all(ip, ip.matches({nat_v4}) && !ip.matches({nat_private}))))) || \ @@ -596,7 +861,7 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { ((l.protocol == 'UDP' && !(l.port in {udp_reserved})) || (l.protocol == 'TCP' && !(l.port in {tcp_reserved}) && !(l.port >= 19000 && l.port <= 19003))) && l.allowedRoutes == {same_ns}))))) || \ (request.resource.resource == 'httproutes' && !(variables.objName in {tailnet_names}) && (request.operation == 'DELETE' || (object.spec.parentRefs.all(p, (!has(p.namespace) || p.namespace == '{gw}') && \ (p.name == '{tailnet_gw}' ? (variables.objName.startsWith('{tn_route}') && has(p.sectionName) && p.sectionName == '{tn_https}' && has(object.spec.hostnames) && size(object.spec.hostnames) >= 1 && object.spec.hostnames.all(h, h.lowerAscii().endsWith('{tn_suffix}'))) : \ - (!variables.objName.startsWith('{tn_route}') && (!has(object.spec.hostnames) || object.spec.hostnames.all(h, !h.lowerAscii().endsWith('{tn_suffix}')))))) && object.spec.rules.all(r, (!has(r.backendRefs) || r.backendRefs.all(b, b.kind == 'Backend' && b.group == 'gateway.envoyproxy.io' && (!has(b.namespace) || b.namespace == '{gw}'))) && (!has(r.filters) || r.filters.all(f, (f.type == 'RequestRedirect' && f.requestRedirect.scheme == 'https') || (f.type == 'RequestHeaderModifier' && f.requestHeaderModifier.all(k, k == 'set') && size(f.requestHeaderModifier.set) == 1 && f.requestHeaderModifier.set[0].name == '{static_header}'))))))) || \ + (!variables.objName.startsWith('{tn_route}') && (!has(object.spec.hostnames) || object.spec.hostnames.all(h, !h.lowerAscii().endsWith('{tn_suffix}')))))) && object.spec.rules.all(r, (!has(r.backendRefs) || r.backendRefs.all(b, b.kind == 'Backend' && b.group == 'gateway.envoyproxy.io' && (!has(b.namespace) || b.namespace == '{gw}'))) && (!has(r.filters) || r.filters.all(f, (f.type == 'RequestRedirect' && f.requestRedirect.scheme == 'https') || (f.type == 'RequestHeaderModifier' && f.requestHeaderModifier.all(k, k == 'set') && size(f.requestHeaderModifier.set) >= 1 && size(f.requestHeaderModifier.set) <= 2 && f.requestHeaderModifier.set.all(h, h.name == '{static_header}' || (h.name == '{forwarded_for}' && h.value == '{forwarded_for_visitor}'))))))))) || \ (request.resource.resource in ['tcproutes', 'udproutes'] && (request.operation == 'DELETE' || (object.spec.all(k, k in ['parentRefs', 'rules']) && object.spec.parentRefs.all(p, (!has(p.namespace) || p.namespace == '{gw}') && p.name.endsWith('-ports')) && size(object.spec.rules) == 1 && \ object.spec.rules.all(r, r.all(k, k == 'backendRefs') && r.backendRefs.all(b, b.kind == 'Backend' && b.group == 'gateway.envoyproxy.io' && (!has(b.namespace) || b.namespace == '{gw}')))))) || \ (request.resource.resource == 'backends' && variables.objName == '{waf}' && (request.operation == 'DELETE' || object.spec == {waf_backend})) || \ @@ -656,6 +921,16 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { // NAT (system.rs): this Service only, onto the proxies, the // websites' ports, and public IPv4 addresses alone. nat_svc = system::PUBLIC_NAT_SERVICE, + // Cloudflare Tunnel (system.rs): the connector's way in, onto the + // proxies' HTTPS only, and public TCP and UDP ports in tunnel + // mode, onto the proxies, never the websites' or the servers' + // own ports. + origin_svc = system::TUNNEL_ORIGIN_SERVICE, + origin_keys = cel_literal(&json!(["type", "selector", "ports"].iter().chain(system::TAILNET_WEB_DEFAULTED.iter()).collect::>())), + origin_ports = cel_literal(&system::tunnel_origin_ports()), + pp_svc = system::PUBLIC_PORTS_SERVICE, + pp_keys = cel_literal(&json!(["type", "externalTrafficPolicy", "selector", "ports"].iter().chain(system::TAILNET_WEB_DEFAULTED.iter()).chain(system::LOAD_BALANCER_DEFAULTED.iter()).collect::>())), + tunnel_cdn = system::TUNNEL_CDN, nat_v4 = cel_literal(&json!(system::IPV4_RE)), nat_private = cel_literal(&json!(system::NOT_PUBLIC_IPV4_RE)), label = system::GATEWAY_LABEL, @@ -677,7 +952,7 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { cdn_label = system::CDN_LABEL, // The headers it removes: all that name a visitor but the CDN's // own (system.rs `visitor_headers`), pinned per CDN. - cdn_headers = crate::firewall::BEHIND.iter().map(|cdn| format!( + cdn_headers = crate::firewall::BEHIND.iter().chain([&system::TUNNEL_CDN]).map(|cdn| format!( "(object.metadata.labels[?'{label}'].orValue('') == '{cdn}' && has(object.spec.headers) && object.spec.headers == {headers})", label = system::CDN_LABEL, headers = cel_literal(&system::visitor_headers(system::cdn_own_headers(cdn))))).collect::>().join(" || "), @@ -685,7 +960,8 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { // behind a CDN its connections only (firewall.rs). acme_rule = cel_literal(&crate::firewall::acme_rule()), gate_rule = cel_literal(&crate::firewall::behind_gate_rule()), - behind = cel_literal(&json!(crate::firewall::BEHIND)), + // The CDNs a website can be behind, and the tunnel's connectors. + behind = cel_literal(&json!(crate::firewall::BEHIND.iter().chain([&system::TUNNEL_CDN]).collect::>())), max_trusted = system::MAX_TRUSTED_CIDRS, trusted_v4 = cel_literal(&json!(system::TRUSTED_V4_RE)), trusted_v6 = cel_literal(&json!(system::TRUSTED_V6_RE)), @@ -710,6 +986,10 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { same_ns = cel_literal(&json!({ "namespaces": { "from": "Same" } })), // A static site's routes: the site and folder for pyo-static. static_header = system::STATIC_HEADER, + // A tunnel route's X-Forwarded-For: only ever the proxy's own + // address for the visitor (system.rs `forwarded_for_visitor`). + forwarded_for = system::FORWARDED_FOR_HEADER, + forwarded_for_visitor = system::FORWARDED_FOR_VISITOR, system_ns = cel_literal(&json!(["kube-system", "kube-public", "kube-node-lease", "default", "pyo-system", system::GATEWAY_NS, "cert-manager"])), http_spec = cel_literal(&system::http_gateway_spec())) }, // Cluster-wide objects it writes, with exactly Pyo's content. @@ -720,6 +1000,9 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { issuers = system::cluster_issuers().iter().map(|(n, spec)| format!("(variables.objName == '{n}' && object.spec == {})", cel_literal(spec))).collect::>().join(" || "), class = cel_literal(&system::gateway_class()["spec"]), scheduling = cel_literal(&system::gpu_runtime_scheduling())) }, + // Its own roles and bindings, updated by a refresh: only with the + // self-update role (never on an install without it). + { "name": "ownRoles", "expression": if self_update { own_roles_cel() } else { "false".to_owned() } }, // Draining a server: evicting or deleting its pods, wherever they are. { "name": "drain", "expression": "(request.resource.resource == 'pods' && variables.sub == 'eviction') || (request.resource.resource == 'pods' && variables.sub == '' && request.operation == 'DELETE')" }, { "name": "hasPods", "expression": "request.operation != 'DELETE' && variables.sub == '' && object.kind in ['Pod', 'Deployment', 'StatefulSet', 'DaemonSet', 'ReplicaSet', 'Job', 'CronJob']" }, @@ -774,19 +1057,43 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { // the agent reports it, so Pyo knows when a cluster's install is older than // its own. // -// With the optional [`SELF_UPDATE_ROLE`] bound, the agent brings the -// admission policy and its image pins up to date itself (`RefreshInstall`): -// only when its roles are already as Pyo's are (it may read them, never -// write them). Without it, the cluster's connect command does. +// With the optional [`SELF_UPDATE_ROLE`] bound, the agent brings its roles, +// the admission policy, its image pins and its pods' priority and +// tolerations up to date itself (`RefreshInstall`). It updates the roles +// and bindings an install already has, by name. It never makes one: a +// release that adds a role object, or changes a chart installed with the +// agent, still needs the cluster's connect command. Without the role, the +// connect command does all of it. +// +// A refresh that can't bring every role still brings the rest: the policy +// (which only narrows what the roles allow) and the image pins. Its stamp +// then names what was left ([`stamp`]), the agent reports those +// (`AgentScope::roles_older`), and Pyo holds back only what needs them +// until the connect command runs. +// +// What that role means: its holder can write any rule into the agent's own +// roles, so whoever controls Pyo can reach cluster-admin on the cluster. +// That was already so with this role before it could write roles: the +// agent takes any admission policy that fails closed (pyo-agent's +// install.rs `check` can't pin a later release's rules), and without the +// policy's limits its roles make privileged pods in pyo-system and write +// any rule into the bundles' ClusterRoles (bundles.rs `cluster_rules`). +// Pyo Cloud installs without this role, and a cluster's owner takes it away +// by deleting the `pyo-agent-self-update` ClusterRoleBinding. /// On the admission policy and the agent's Deployment: the hash of the /// install they're from. pub const INSTALL_ANNOTATION: &str = "pyo.dev/install"; -/// Optional: the agent may rewrite its own admission policy (and read its -/// roles, to know they're current). Deleting its binding takes that away. +/// Optional: the agent may rewrite its own admission policy and update its +/// own roles and bindings. Deleting its binding takes that away. pub const SELF_UPDATE_ROLE: &str = "pyo-agent-self-update"; -/// The agent Deployment's env that pins system images: the only part of -/// the Deployment a refresh changes. +/// How a refresh's failure starts when the agent's roles aren't Pyo's, as +/// 0.5.5's agent says it (it never writes them, and stops there): only +/// the cluster's connect command changes them, so Pyo doesn't send that +/// agent the refresh again. +pub const ROLES_OLDER: &str = "this agent's roles are older than Pyo's"; +/// The agent Deployment's env that pins system images: what a refresh +/// changes of it, with its pods' priority and tolerations. pub const PINNED_ENV: [&str; 10] = [ "PYO_WAF_IMAGE", "PYO_GEOIP_IMAGE", @@ -801,8 +1108,11 @@ pub const PINNED_ENV: [&str; 10] = [ ]; /// The optional role (and its binding) that lets the agent refresh its -/// admission policy: update only that policy and its binding, by name; read -/// only its own roles and the charts installed with it, by name. +/// install. All by name: update the admission policy and its binding; read +/// and update its own roles and bindings (this role too), writing rules it +/// doesn't hold itself (`escalate`) and keeping them bound (`bind`); read +/// the charts installed with it. Never create, patch or delete: a role +/// object an install doesn't have yet comes with the connect command. pub fn self_update_objects() -> Vec { let own = objects(true); let names = |kinds: &[&str], namespaced: bool| -> Vec { @@ -826,8 +1136,10 @@ pub fn self_update_objects() -> Vec { SELF_UPDATE_ROLE, json!([ { "apiGroups": ["admissionregistration.k8s.io"], "resources": ["validatingadmissionpolicies", "validatingadmissionpolicybindings"], "verbs": ["get", "update"], "resourceNames": [ADMISSION_POLICY] }, - { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["clusterroles", "clusterrolebindings"], "verbs": ["get"], "resourceNames": names(&["ClusterRole", "ClusterRoleBinding"], false) }, - { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["roles", "rolebindings"], "verbs": ["get"], "resourceNames": names(&["Role", "RoleBinding"], true) }, + { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["clusterroles", "clusterrolebindings"], "verbs": ["get", "update"], "resourceNames": names(&["ClusterRole", "ClusterRoleBinding"], false) }, + { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["clusterroles"], "verbs": ["escalate", "bind"], "resourceNames": names(&["ClusterRole"], false) }, + { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["roles", "rolebindings"], "verbs": ["get", "update"], "resourceNames": names(&["Role", "RoleBinding"], true) }, + { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["roles"], "verbs": ["escalate", "bind"], "resourceNames": names(&["Role"], true) }, { "apiGroups": ["helm.cattle.io"], "resources": ["helmcharts"], "verbs": ["get"], "resourceNames": names(&["HelmChart"], true) }, ]), ), @@ -841,8 +1153,9 @@ pub fn self_update_objects() -> Vec { pub struct InstallParts { /// Hex, stamped as [`INSTALL_ANNOTATION`]. pub hash: String, - /// Its roles and bindings (and the charts installed with it): only - /// read by a refresh, never written. + /// Its roles and bindings (and the charts installed with it). A + /// refresh updates the roles and bindings the cluster already has, and + /// only reads the rest. pub access: Vec, /// The admission policy (stamped) and its binding. pub admission: Vec, @@ -864,7 +1177,7 @@ impl InstallParts { if self_update { access.extend(self_update_objects()); } - let mut admission = admission(waf_image, geoip_image); + let mut admission = admission_for(self_update, waf_image, geoip_image); let [pg16, pg17, pg18] = db.postgres.clone(); let pins: std::collections::BTreeMap = PINNED_ENV .iter() @@ -905,15 +1218,39 @@ pub fn install_hash( /// A short hash (16 hex digits) of the roles and charts every install sets /// up, on any cluster and on the one Pyo runs on, with the optional -/// self-update role: what only a cluster's connect command can change (a -/// refresh never writes them). A release carries its own (release.json's -/// `agentAccess`), so an update that changes it says, before it starts, -/// that every cluster needs its connect command afterwards. +/// self-update role, and of the admission policy's rules (with and without +/// that role): what a cluster without the self-update role, or read only, +/// only gets from its connect command. A release carries its own +/// (release.json's `agentAccess`), so an update that changes it says, +/// before it starts and on an installation without the self-update role, +/// that every cluster needs its connect command afterwards. Images don't count: each release +/// has its own, and a refresh or the connect command brings them. pub fn access_hash() -> String { + access_hash_of(&access_admission()) +} + +/// The admission policies [`access_hash`] covers (without the self-update +/// role, then with it): their rules, with the same stand-in images +/// whatever the installation runs. +fn access_admission() -> Vec { + let db = system::DbImages { + controller: "db-controller".into(), + kv: "kv".into(), + postgres: system::POSTGRES_MAJORS.map(|m| format!("postgres:{m}")), + mysql_operator: "mysql-operator".into(), + mysql_backup: "mysql-backup".into(), + }; + let mut out = admission_with(false, "waf", "geoip", "static", &db); + out.extend(admission_with(true, "waf", "geoip", "static", &db)); + out +} + +fn access_hash_of(admission: &[Value]) -> String { short_hash(&json!([ objects(false), objects(true), - self_update_objects() + self_update_objects(), + admission ])) } @@ -926,10 +1263,53 @@ fn short_hash(doc: &Value) -> String { .collect() } +/// Between an install's hash and the roles a refresh left as they were, in +/// its stamp. +const STAMP_EXCEPT: &str = " except "; + +/// An install's stamp ([`INSTALL_ANNOTATION`]): its hash, and after a +/// refresh that couldn't bring every role, the ones left as they were +/// ("Kind/name" or "Kind/namespace/name"). +pub fn stamp(hash: &str, older: &[String]) -> String { + if older.is_empty() { + hash.to_owned() + } else { + format!("{hash}{STAMP_EXCEPT}{}", older.join(",")) + } +} + +/// A [`stamp`]'s hash and the roles left as they were. +pub fn parse_stamp(stamp: &str) -> (String, Vec) { + match stamp.split_once(STAMP_EXCEPT) { + Some((hash, older)) => ( + hash.to_owned(), + older + .split(',') + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect(), + ), + None => (stamp.to_owned(), vec![]), + } +} + +/// Whether roles a refresh left as they were (`older`) hold back the system +/// bundles (the databases system, the WAF, Pyo Static): the bundles' own +/// two roles (their cluster-wide names are in them), or a chart installed +/// with the agent. Any other role leaves them free to install and update. +pub fn bundles_held_back(older: &[String]) -> bool { + older.iter().any(|k| { + k.starts_with("HelmChart/") + || [bundles::CLUSTER_ROLE, bundles::WRITE_ROLE] + .iter() + .any(|r| k.rsplit('/').next() == Some(r) && k.contains("Role")) + }) +} + /// Whether a cluster's install, as its agent reports it, is Pyo's. pub fn install_current(scope: &AgentScope, expected: &str) -> bool { match scope.admission.as_str() { - "enforced" => scope.install == expected, + "enforced" => scope.install == expected && scope.roles_older.is_empty(), // The cluster has admission policies but not the agent's: only its // connect command puts it back. "missing" => false, @@ -953,6 +1333,10 @@ pub struct Policy { /// `readOnly: "true"`: the agent reports, and changes nothing. #[serde(default)] pub read_only: bool, + /// `updates: "hold"`: the server's verifier applies no update. Only + /// the verifier acts on it: Pyo shows it, and nothing else. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub updates_hold: bool, } impl Policy { @@ -966,6 +1350,63 @@ impl Policy { no_terminal: is("terminal", &["off", "false", "no", "disabled"]), no_force_remove: is("forceRemoveServers", &["off", "false", "no", "disabled"]), read_only: is("readOnly", &["true", "on", "yes"]), + updates_hold: is("updates", &["hold"]), + } + } +} + +/// How automatic updates stand on a cluster, as the verifier on its first +/// server wrote it to `pyo-system/pyo-verifier` and the agent read it. +/// +/// Only ever shown. The agent passes it on, so an agent that was broken +/// into can say anything here: no decision of Pyo's may follow from it. +/// The verifier takes nothing from Pyo but the version to be on, and Pyo +/// has no switch that turns it on or off or makes it run: those are the +/// customer's, in `pyo-system/pyo-policy` (`updates: "hold"`) and in +/// `/etc/pyo/verify.conf` on the server. +#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VerifierStatus { + /// The verifier's own version. + #[serde(default)] + pub version: String, + /// The version Pyo named when it last asked. + #[serde(default)] + pub live: String, + /// When it last checked (RFC 3339). + #[serde(default)] + pub checked: String, + /// What went wrong, in plain words. Empty when nothing did. + #[serde(default)] + pub error: String, + /// It's on hold: turned off on the server, or by the policy. + #[serde(default)] + pub hold: bool, + /// The server it runs on. + #[serde(default)] + pub host: String, +} + +impl VerifierStatus { + /// The longest a field is kept: an error is a sentence or two. + pub const FIELD_MAX: usize = 400; + + /// From the ConfigMap's data. A missing field is empty, `hold` is on + /// only when it says "true", and each field is cut to + /// [`Self::FIELD_MAX`] characters. + pub fn from_data(data: &std::collections::BTreeMap) -> Self { + let text = |k: &str| -> String { + data.get(k) + .map(|v| v.trim().chars().take(Self::FIELD_MAX).collect()) + .unwrap_or_default() + }; + VerifierStatus { + version: text("version"), + live: text("live"), + checked: text("checked"), + error: text("error"), + hold: text("hold").eq_ignore_ascii_case("true"), + host: text("host"), } } } @@ -996,6 +1437,23 @@ pub struct AgentScope { /// It may refresh its admission policy ([`SELF_UPDATE_ROLE`] is bound). #[serde(default)] pub self_update: bool, + /// The roles of [`AgentScope::install`] that a refresh left as they + /// were, from its stamp ([`parse_stamp`]): the install is current + /// except for these, until the connect command runs. The agent doesn't + /// compare its roles itself at each heartbeat: it only knows its own + /// release's, which aren't Pyo's while it's being updated. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub roles_older: Vec, + /// The cluster's admission policy is older than the agent's and refused + /// the client policies that remove client-sent visitor headers, so the + /// agent wrote them without that (`gateway.rs` `write_client_policy`). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub headers_kept: bool, + /// What the verifier on the cluster's first server last said (the + /// `pyo-system/pyo-verifier` ConfigMap): none when there's none, or + /// the install doesn't let the agent read it yet. Only ever shown. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub verifier: Option, } /// What the gateway could get at if it were broken into. @@ -1127,7 +1585,15 @@ mod tests { #[test] fn a_static_sites_routes_may_only_name_its_folder() { let policy = admission("w", "g")[0].to_string(); - assert!(policy.contains("(f.type == 'RequestHeaderModifier' && f.requestHeaderModifier.all(k, k == 'set') && size(f.requestHeaderModifier.set) == 1 && f.requestHeaderModifier.set[0].name == 'x-pyo-site')")); + assert!(policy.contains("(f.type == 'RequestHeaderModifier' && f.requestHeaderModifier.all(k, k == 'set') && size(f.requestHeaderModifier.set) >= 1 && size(f.requestHeaderModifier.set) <= 2 && f.requestHeaderModifier.set.all(h, h.name == 'x-pyo-site' || (h.name == 'X-Forwarded-For' && h.value == '%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%')))"), "{policy}"); + // A tunnel route's rule passes them too, alone or with a site's. + let rule = system::tunnel_rule(json!({ "filters": [system::static_filter("svc_1", "dep_1")] })); + let set = rule["filters"][0]["requestHeaderModifier"]["set"].as_array().unwrap().clone(); + assert_eq!(rule["filters"].as_array().unwrap().len(), 1); + assert_eq!(set.len(), 2); + assert_eq!(set[1], json!({ "name": "X-Forwarded-For", "value": "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%" })); + let alone = system::tunnel_rule(json!({ "backendRefs": [] })); + assert_eq!(alone["filters"], json!([{ "type": "RequestHeaderModifier", "requestHeaderModifier": { "set": [set[1]] } }])); // The filter the agent writes passes those checks. let f = system::static_filter("svc_1", "dep_1"); assert_eq!( @@ -1376,8 +1842,9 @@ mod tests { assert_eq!( svc, [ - &json!({ "apiGroups": [""], "resources": ["services"], "verbs": ["create"] }), - &json!({ "apiGroups": [""], "resources": ["services"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::TAILNET_WEB_SERVICE, system::TAILNET_VIP_SERVICE, system::PUBLIC_NAT_SERVICE] }), + // No names: the admission policy has them (below, and + // `the_gateway_namespace_is_held_by_the_policy`). + &json!({ "apiGroups": [""], "resources": ["services"], "verbs": ["get", "create", "patch", "delete"] }), ] ); let policy = admission("w", "g"); @@ -1437,6 +1904,256 @@ mod tests { /// The Service for the public IPs behind the cloud's NAT: pinned like /// the tailnet websites' one, on public IPv4 addresses only. + #[test] + fn the_tunnel_services_are_pinned() { + let policy = admission("w", "g"); + let all = policy[0]["spec"]["variables"] + .as_array() + .unwrap() + .iter() + .find(|v| v["name"] == "gatewayAllowed") + .unwrap()["expression"] + .as_str() + .unwrap(); + let clause = |name: &str| { + let start = all + .find(&format!("variables.objName == '{name}'")) + .unwrap_or_else(|| panic!("{name}'s clause")); + all[start..start + all[start..].find("))) || ").unwrap()].to_owned() + }; + let selector = format!( + "object.spec.selector == {}", + cel_literal(&system::proxy_pods()["matchLabels"]) + ); + let origin = clause(system::TUNNEL_ORIGIN_SERVICE); + for part in [ + "object.spec.type == 'ClusterIP'".to_owned(), + selector.clone(), + format!( + "object.spec.ports == {}", + cel_literal(&system::tunnel_origin_ports()) + ), + ] { + assert!(origin.contains(&part), "{part}\n{origin}"); + } + // No external addresses on the origin. + assert!(!origin.contains("externalIPs")); + let ports = clause(system::PUBLIC_PORTS_SERVICE); + for part in [ + "object.spec.type == 'LoadBalancer' && object.spec.externalTrafficPolicy == 'Local'" + .to_owned(), + selector, + "!(p.port in [80, 443, 10080, 10443, 22, 53, 2379, 2380, 6443, 10250".to_owned(), + "p.targetPort == (p.port < 1024 ? p.port + 10000 : p.port)".to_owned(), + ] { + assert!(ports.contains(&part), "{part}\n{ports}"); + } + assert!(!ports.contains("externalIPs")); + // What the agent writes is what's pinned. + assert_eq!(system::tunnel_origin_service()["spec"]["ports"], system::tunnel_origin_ports()); + let s = system::public_ports_service(&[("TCP".into(), 5432), ("UDP".into(), 53), ("TCP".into(), 25)]).unwrap(); + assert_eq!(s["spec"]["ports"][0], json!({ "name": "tcp-25", "port": 25, "targetPort": 10025, "protocol": "TCP" })); + assert_eq!(s["spec"]["ports"][1]["targetPort"], 5432); + assert!(system::public_ports_service(&[]).is_none()); + } + + /// The gateway role names no Service, network policy or ConfigMap it + /// writes, so the admission policy is what holds them. For each of + /// those three, every allowance in `gatewayAllowed` names one of Pyo's + /// own objects, and nothing else lets a write into pyo-gateway through. + #[test] + fn the_gateway_namespace_is_held_by_the_policy() { + let objects = objects(true); + let gw = objects + .iter() + .find(|o| { + o["kind"] == "Role" + && o["metadata"]["namespace"] == system::GATEWAY_NS + && o["metadata"]["name"] == "pyo-agent" + }) + .unwrap(); + let rules = gw["rules"].as_array().unwrap(); + let of = |resource: &str| -> Vec<&Value> { + rules + .iter() + .filter(|r| r["resources"] == json!([resource])) + .collect() + }; + assert_eq!(of("services"), [&json!({ "apiGroups": [""], "resources": ["services"], "verbs": ["get", "create", "patch", "delete"] })]); + assert_eq!(of("networkpolicies"), [&json!({ "apiGroups": ["networking.k8s.io"], "resources": ["networkpolicies"], "verbs": ["get", "create", "patch", "delete"] })]); + // ConfigMaps: read by name only (the policy doesn't see reads). + assert_eq!( + of("configmaps"), + [ + &json!({ "apiGroups": [""], "resources": ["configmaps"], "verbs": ["create", "patch", "delete"] }), + &json!({ "apiGroups": [""], "resources": ["configmaps"], "verbs": ["get"], "resourceNames": [system::ORIGIN_PULL_SECRET, system::TAILNET_WANTED] }), + ] + ); + // Secrets as they were, and no rule here reaches subresources, + // every object of a kind at once, or every kind. + assert_eq!(of("secrets"), [&json!({ "apiGroups": [""], "resources": ["secrets"], "verbs": ["create", "patch", "delete"] })]); + for r in rules { + let text = r.to_string(); + assert!( + !text.contains('*') && !text.contains("deletecollection") && !text.contains('/'), + "{r}" + ); + } + let policy = admission("w", "g"); + let spec = &policy[0]["spec"]; + // The policy sees every write the agent makes, and fails closed. + assert_eq!(spec["failurePolicy"], "Fail"); + assert_eq!( + spec["matchConstraints"]["resourceRules"], + json!([{ "apiGroups": ["*"], "apiVersions": ["*"], "operations": ["CREATE", "UPDATE", "DELETE"], "resources": ["*/*"] }]) + ); + // A write in a namespace passes only as one of these. + assert_eq!(spec["validations"][1]["expression"], NAMESPACE_WRITES); + let var = |name: &str| -> String { + spec["variables"] + .as_array() + .unwrap() + .iter() + .find(|v| v["name"] == name) + .unwrap()["expression"] + .as_str() + .unwrap() + .to_owned() + }; + // pyo-gateway isn't a managed namespace, and the agent can't make + // it one: it only changes a namespace already labelled as Pyo's. + let ns = objects + .iter() + .find(|o| o["kind"] == "Namespace" && o["metadata"]["name"] == system::GATEWAY_NS) + .unwrap(); + assert!(ns["metadata"]["labels"].is_null(), "{ns}"); + assert!(spec["validations"].to_string().contains( + "request.operation == 'CREATE' || (has(oldObject.metadata.labels) && (oldObject.metadata.labels[?'pyo.dev/managed'].orValue('') == 'true'" + )); + // The other ways through are for other things: kube-system, pods + // (a drain), a component's own pinned objects (none in + // pyo-gateway) and the agent's own roles (never without the + // self-update role). + assert_eq!(var("ownRoles"), "false"); + assert!(own_roles_cel().starts_with("request.resource.group == 'rbac.authorization.k8s.io' && ")); + assert!(var("kubeSystemAllowed").starts_with("variables.ns == 'kube-system' && (")); + assert_eq!( + var("drain"), + "(request.resource.resource == 'pods' && variables.sub == 'eviction') || (request.resource.resource == 'pods' && variables.sub == '' && request.operation == 'DELETE')" + ); + for b in bundles::policy_bundles("w", "g") { + assert_ne!(b.namespace, system::GATEWAY_NS); + for r in b.refs() { + assert_ne!(r.namespace.as_deref(), Some(system::GATEWAY_NS), "{r:?}"); + } + } + // In `gatewayAllowed`, each of the three kinds is only ever let + // through by name: creates and updates with content the policy + // checks (the clauses' own tests), deletes of those names alone. + let all = var("gatewayAllowed"); + assert!(all.starts_with(&format!("variables.ns == '{}' && (", system::GATEWAY_NS))); + for (resource, names) in [ + ( + "services", + &[ + system::TAILNET_WEB_SERVICE, + system::TAILNET_VIP_SERVICE, + system::PUBLIC_NAT_SERVICE, + system::TUNNEL_ORIGIN_SERVICE, + system::PUBLIC_PORTS_SERVICE, + ][..], + ), + ("networkpolicies", &[system::FIREWALL_POLICY][..]), + ( + "configmaps", + &[system::TAILNET_WANTED, system::ORIGIN_PULL_SECRET][..], + ), + ] { + let test = format!("request.resource.resource == '{resource}'"); + let mut seen = vec![]; + for (at, _) in all.match_indices(&test) { + let rest = &all[at + test.len()..]; + let name = names + .iter() + .find(|n| rest.starts_with(&format!(" && variables.objName == '{n}' && "))) + .unwrap_or_else(|| { + panic!( + "{resource} let through without a name: {}", + &rest[..rest.len().min(80)] + ) + }); + // Its clause: a delete, or content the policy checks. + let clause = &rest[..rest.find(" || (request.resource.resource").unwrap_or(rest.len())]; + assert!(clause.contains("(request.operation == 'DELETE' || "), "{clause}"); + assert!( + clause.contains("object.spec.") || clause.contains("object.data.all("), + "{clause}" + ); + seen.push(*name); + } + seen.sort_unstable(); + let mut want = names.to_vec(); + want.sort_unstable(); + assert_eq!(seen, want, "{resource}"); + // And by no list of kinds or negated test. + assert!( + !all.contains(&format!("'{resource}',")) && !all.contains(&format!(", '{resource}'")), + "{resource}" + ); + assert!(!all.contains(&format!("request.resource.resource != '{resource}'")), "{resource}"); + } + } + + #[test] + fn tunnel_client_policies_trust_only_their_listeners() { + let all = admission(system::WAF_IMAGE_DEFAULT, system::GEOIP_IMAGE_DEFAULT)[0].to_string(); + let start = all + .find("request.resource.resource == 'clienttrafficpolicies'") + .unwrap(); + let end = all[start..] + .find("request.resource.resource == 'securitypolicies'") + .unwrap(); + let ctp = &all[start..start + end]; + // The label, and Cloudflare's own headers kept (they come from it). + assert!(ctp.contains("dyn('cloudflare'), dyn('tunnel')"), "{ctp}"); + let kept = system::cel_literal(&system::visitor_headers(system::cdn_own_headers(system::TUNNEL_CDN))); + assert!(ctp.contains(&format!( + "(object.metadata.labels[?'{}'].orValue('') == 'tunnel' && has(object.spec.headers) && object.spec.headers == {kept})", + system::CDN_LABEL + ))); + // Named after its own Gateway. + assert!(ctp.contains("== 'tunnel' ? '-tunnel' : '-cdn') == variables.objName")); + // Not a CDN a user can pick. + assert!(!crate::firewall::BEHIND.contains(&system::TUNNEL_CDN)); + // Pod addresses as the policy holds them. + assert_eq!( + system::host_cidrs(&["10.42.1.7".into(), "fd00::5".into(), "10.42.1.7".into(), "bad".into()]), + ["10.42.1.7/32", "fd00::5/128"] + ); + let v4 = regex::Regex::new(system::TRUSTED_V4_RE).unwrap(); + let v6 = regex::Regex::new(system::TRUSTED_V6_RE).unwrap(); + assert!(v4.is_match("10.42.1.7/32") && v6.is_match("fd00::5/128")); + } + + #[test] + fn the_tunnel_connector_passes_the_pod_rules() { + let d = system::tunnel_deployment(system::CLOUDFLARED_IMAGE); + let pod = &d["spec"]["template"]["spec"]; + assert_eq!(pod["automountServiceAccountToken"], false); + assert!(pod.get("hostNetwork").is_none() && pod.get("volumes").is_none()); + let c = &pod["containers"][0]; + assert_eq!(c["securityContext"]["capabilities"]["drop"], json!(["ALL"])); + assert!(c.get("ports").is_none(), "nothing connects to it"); + assert!(c["args"].as_array().unwrap().contains(&json!("http2"))); + assert_eq!(d["metadata"]["namespace"], NS); + assert_eq!(system::tunnel_budget()["spec"]["minAvailable"], 1); + let s = system::tunnel_secret("c1744f8b-faa1-48a4-9e5c-02ac921467fa", "tok"); + assert_eq!(s["metadata"]["labels"][system::TUNNEL_ID_LABEL], "c1744f8b-faa1-48a4-9e5c-02ac921467fa"); + // The write role covers Deployments, Secrets and budgets in pyo-system. + let roles = json!(objects(false)).to_string(); + assert!(roles.contains("poddisruptionbudgets")); + } + #[test] fn the_public_nat_service_is_pinned() { let policy = admission("w", "g"); @@ -1502,6 +2219,91 @@ mod tests { } } + /// The agent's own Deployment: only updated, its priority and + /// tolerations only to exactly this release's, and its token, Pyo's + /// address, other env, volumes and account kept. + #[test] + fn the_agents_deployment_changes_only_as_a_refresh_does() { + let policy = admission("w", "g")[0].to_string(); + let rule = agent_deployment_kept(); + let escaped = serde_json::to_string(&rule).unwrap(); + assert!(policy.contains(&escaped[1..escaped.len() - 1])); + assert!(policy.contains(&format!( + "variables.objName == '{AGENT_DEPLOYMENT}') || (request.operation == 'UPDATE' && variables.sub == '' && " + ))); + assert!(rule.contains(&format!( + "object.spec.template.spec.priorityClassName == '{AGENT_PRIORITY}'" + ))); + assert!(rule.contains(&format!( + "object.spec.template.spec.tolerations == {}", + cel_literal(&agent_tolerations()) + ))); + // The two new tolerations, besides the GPU one it always had. + let tolerations = agent_tolerations(); + let keys: Vec<&str> = tolerations + .as_array() + .unwrap() + .iter() + .map(|t| t["key"].as_str().unwrap()) + .collect(); + assert_eq!( + keys, + [ + crate::GPU_RESOURCE, + "node.kubernetes.io/disk-pressure", + "node.kubernetes.io/memory-pressure" + ] + ); + // What must stay: by field, and env other than the pins. + for f in [ + "serviceAccountName", + "volumes", + "automountServiceAccountToken", + "initContainers", + ] { + assert!( + rule.contains(&format!( + "has(object.spec.template.spec.{f}) == has(oldObject.spec.template.spec.{f})" + )), + "{f}" + ); + } + for f in [ + "envFrom", + "command", + "args", + "volumeMounts", + "securityContext", + ] { + assert!(rule.contains(&format!("has(c.{f}) == has(p.{f})")), "{f}"); + } + assert!(rule.contains("(c.name == 'agent' || c.image == p.image)")); + assert!(rule.contains("e.name in [dyn('PYO_WAF_IMAGE')")); + assert!(rule.contains("object.spec.template.metadata == oldObject.spec.template.metadata")); + assert!(rule.contains(&format!("k == '{INSTALL_ANNOTATION}'"))); + // No field twice, and none it may change. + for list in [ + &AGENT_POD_KEPT[..], + &AGENT_CONTAINER_KEPT[..], + &AGENT_SPEC_KEPT[..], + ] { + let mut sorted = list.to_vec(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), list.len()); + for f in [ + "containers", + "priorityClassName", + "tolerations", + "image", + "env", + "template", + ] { + assert!(!list.contains(&f), "{f}"); + } + } + } + #[test] fn the_geoip_image_is_the_installations() { let img = "registry.example.com/pyo/geoip:7@sha256:bb"; @@ -1531,6 +2333,9 @@ mod tests { ); } + /// The validation every write in a namespace goes through. + const NAMESPACE_WRITES: &str = "variables.ns == '' || request.resource.resource == 'namespaces' || variables.managed || variables.kubeSystemAllowed || variables.gatewayAllowed || variables.drain || variables.bundleAllowed || variables.ownRoles"; + fn db(controller: &str) -> system::DbImages { system::DbImages { controller: controller.into(), @@ -1541,10 +2346,39 @@ mod tests { } } - /// The roles' hash: stable for the same roles, 16 hex digits, and - /// not moved by what a refresh can change (pins, the policy). + /// The roles alone: stable for the same roles. 0.5.5's roles with the + /// gateway's Services, network policies and ConfigMaps no longer named + /// in the role (the admission policy names them, so the Cloudflare + /// Tunnel's two Services and any later one change no role), which the + /// agent gets with the connect command, and the self-update role's + /// update, escalate and bind on the agent's own roles, so later + /// releases' roles come with a refresh. The disk pressure fix + /// (critical per-server pods, the agent's own priority and + /// tolerations) changes no role. Its stricter admission policy does + /// move [`access_hash`], so clusters that can't refresh are told to run + /// the connect command. And the role that reads the customer's policy + /// also reads their verifier's status (`pyo-system/pyo-verifier`). + /// Change this only with a release that means to + /// change the roles: from 0.51.0 on a cluster with the self-update role + /// gets them with a refresh, any other with its connect command. + #[test] + fn the_roles_are_as_0_51_0s() { + assert_eq!( + short_hash(&json!([ + objects(false), + objects(true), + self_update_objects() + ])), + "0dcaac0328ee92f9" + ); + } + + /// The access hash: stable, 16 hex digits, not moved by the images (a + /// refresh or the connect command brings those), but moved by any change + /// to the roles or to the admission policy's rules, which a cluster + /// that can't refresh only gets from its connect command. #[test] - fn access_hash_covers_only_the_roles() { + fn access_hash_covers_the_roles_and_the_admission_policy() { let h = access_hash(); assert_eq!(h.len(), 16); assert!(h.chars().all(|c| c.is_ascii_hexdigit())); @@ -1553,16 +2387,48 @@ mod tests { let a = InstallParts::new(false, true, "w:1", "g:1", &db); let b = InstallParts::new(false, true, "w:2", "g:2", &db); assert_ne!(a.hash, b.hash, "pins change the install"); - assert_eq!(access_hash(), h, "but not the roles"); - // Its content: every role set an install can have. + assert_eq!(access_hash(), h, "but not the access"); + // Its content: every role set an install can have, and the policy + // with stand-in images. + let policy = access_admission(); + // With and without the self-update role. + assert_eq!(policy.len(), 4); + assert_ne!(policy[0], policy[2]); assert_eq!( short_hash(&json!([ objects(false), objects(true), - self_update_objects() + self_update_objects(), + policy ])), h ); + assert_eq!(access_hash_of(&policy), h); + // Whatever images the installation runs (third-party images the + // code pins are part of the rules). + let text = json!(policy).to_string(); + assert!( + !text.contains("ghcr.io/upsetdev/") && !text.contains("127.0.0.1:5005"), + "{text}" + ); + // A change to the policy's rules: another hash. This one is what + // set apart a 0.5.4 install, whose client policies took no headers. + let mut older = policy.clone(); + let rules = older[0]["spec"]["variables"].to_string().replace( + "'clientIPDetection', 'connection', 'headers', 'tls'", + "'clientIPDetection', 'connection', 'tls'", + ); + assert_ne!(rules, older[0]["spec"]["variables"].to_string(), "the rule is there"); + older[0]["spec"]["variables"] = serde_json::from_str(&rules).unwrap(); + assert_ne!(access_hash_of(&older), h); + let mut message = policy.clone(); + message[0]["spec"]["validations"][0]["message"] = json!("another message"); + assert_ne!(access_hash_of(&message), h); + // And a change to the roles. + assert_ne!( + short_hash(&json!([objects(false), objects(true), json!([]), policy])), + h + ); } #[test] @@ -1596,6 +2462,45 @@ mod tests { assert_eq!(others[2].pins["PYO_DB_CONTROLLER_IMAGE"], "c2"); } + /// A refresh that left roles behind stamps them, and that install + /// isn't current. + #[test] + fn a_stamp_names_the_roles_left_behind() { + assert_eq!(stamp("abc", &[]), "abc"); + assert_eq!(parse_stamp("abc"), ("abc".to_owned(), vec![])); + let older = vec!["Role/pyo-gateway/pyo-agent".to_owned(), "ClusterRole/pyo-agent-self-update".to_owned()]; + let s = stamp("abc", &older); + assert_eq!(s, "abc except Role/pyo-gateway/pyo-agent,ClusterRole/pyo-agent-self-update"); + assert_eq!(parse_stamp(&s), ("abc".to_owned(), older.clone())); + assert_eq!(parse_stamp(""), (String::new(), vec![])); + let scope = AgentScope { + admission: "enforced".into(), + install: "abc".into(), + roles_older: older.clone(), + ..Default::default() + }; + assert!(!install_current(&scope, "abc")); + // Agents that don't say (0.5.5's) read as before, and a full + // install's scope carries no such field. + let wire = serde_json::to_value(AgentScope { roles_older: vec![], ..scope.clone() }).unwrap(); + assert!(wire.get("rolesOlder").is_none()); + let read: AgentScope = serde_json::from_value(wire).unwrap(); + assert!(install_current(&read, "abc")); + assert_eq!(serde_json::to_value(&scope).unwrap()["rolesOlder"], json!(older)); + // What holds the bundles back: their own roles, or a chart. + assert!(!bundles_held_back(&older)); + assert!(!bundles_held_back(&[])); + for k in [ + format!("ClusterRole/{}", bundles::CLUSTER_ROLE), + format!("ClusterRoleBinding/{}", bundles::CLUSTER_ROLE), + format!("ClusterRole/{}", bundles::WRITE_ROLE), + "HelmChart/kube-system/cert-manager".to_owned(), + ] { + assert!(bundles_held_back(&[older[0].clone(), k.clone()]), "{k}"); + } + assert!(!bundles_held_back(&["ClusterRole/pyo-agent-write".to_owned()])); + } + #[test] fn install_current_only_counts_an_enforced_policy() { let scope = |admission: &str, install: &str| AgentScope { @@ -1613,66 +2518,125 @@ mod tests { assert!(install_current(&scope("unsupported", ""), "abc")); } + /// The self-update role, exactly: everything by name, no create, patch + /// or delete, and `escalate` and `bind` only on the agent's own roles. #[test] fn self_update_is_narrow() { let objs = self_update_objects(); assert_eq!(objs.len(), 2); - let rules = objs[0]["rules"].as_array().unwrap(); - for r in rules { - // Everything by name; writes only to the admission policy, never create/patch/escalate/bind. - assert!( - r["resourceNames"].as_array().is_some_and(|n| !n.is_empty()), - "{r}" - ); - let verbs: Vec<&str> = r["verbs"] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_str().unwrap()) - .collect(); - if r["apiGroups"] == json!(["admissionregistration.k8s.io"]) { - assert_eq!(verbs, ["get", "update"]); - assert_eq!(r["resourceNames"], json!([ADMISSION_POLICY])); - } else { - assert_eq!(verbs, ["get"], "{r}"); + let cluster_roles = json!([ + "pyo-agent-bundle-write", + "pyo-agent-bundles", + "pyo-agent-cluster", + "pyo-agent-namespaces", + "pyo-agent-nodes", + "pyo-agent-read", + "pyo-agent-self-update", + "pyo-agent-stats", + "pyo-agent-write", + ]); + // Bindings share their roles' names (the bundles' write role is + // bound per namespace, by the agent). + let roles = json!(["pyo-agent", "pyo-agent-policy", "pyo-agent-upgrade", "pyo-tailnet"]); + assert_eq!( + objs[0]["rules"], + json!([ + { "apiGroups": ["admissionregistration.k8s.io"], "resources": ["validatingadmissionpolicies", "validatingadmissionpolicybindings"], "verbs": ["get", "update"], "resourceNames": [ADMISSION_POLICY] }, + { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["clusterroles", "clusterrolebindings"], "verbs": ["get", "update"], "resourceNames": cluster_roles }, + { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["clusterroles"], "verbs": ["escalate", "bind"], "resourceNames": cluster_roles }, + { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["roles", "rolebindings"], "verbs": ["get", "update"], "resourceNames": roles }, + { "apiGroups": ["rbac.authorization.k8s.io"], "resources": ["roles"], "verbs": ["escalate", "bind"], "resourceNames": roles }, + { "apiGroups": ["helm.cattle.io"], "resources": ["helmcharts"], "verbs": ["get"], "resourceNames": ["cert-manager", "envoy-gateway"] }, + ]) + ); + // Every name is one of an install's own objects, and every role and + // binding of an install is named. + let own = own_role_objects(); + for o in objects(true).iter().chain(objs.iter()) { + let kind = o["kind"].as_str().unwrap(); + if !kind.contains("Role") { + continue; } + let name = o["metadata"]["name"].as_str().unwrap(); + let list = if kind.starts_with("Cluster") { &cluster_roles } else { &roles }; + assert!(list.as_array().unwrap().contains(&json!(name)), "{kind} {name}"); + assert!(own.iter().any(|(_, _, n)| n == name), "{name}"); } - // It may read its own roles, the self-update one included. - let cluster = rules - .iter() - .find(|r| r["resources"] == json!(["clusterroles", "clusterrolebindings"])) - .unwrap(); - for n in [ - "pyo-agent-read", - WRITE_ROLE, - NODES_ROLE, - SELF_UPDATE_ROLE, - bundles::CLUSTER_ROLE, - ] { - assert!( - cluster["resourceNames"] - .as_array() - .unwrap() - .contains(&json!(n)), - "{n}" - ); + // No verb that makes or removes an object, and none unnamed. + for r in objs[0]["rules"].as_array().unwrap() { + assert!(r["resourceNames"].as_array().is_some_and(|n| !n.is_empty()), "{r}"); + for v in r["verbs"].as_array().unwrap() { + assert!(["get", "update", "escalate", "bind"].contains(&v.as_str().unwrap()), "{r}"); + } } - let ns = rules - .iter() - .find(|r| r["resources"] == json!(["roles", "rolebindings"])) - .unwrap(); - assert!( - ns["resourceNames"] + // Its binding is the owner's switch: to the agent's account only. + assert_eq!(objs[1]["kind"], "ClusterRoleBinding"); + assert_eq!(objs[1]["metadata"]["name"], SELF_UPDATE_ROLE); + assert_eq!(objs[1]["subjects"], json!([{ "kind": "ServiceAccount", "name": SA, "namespace": NS }])); + // Not part of the default roles, nor of an install without it + // (Pyo Cloud's), whose policy refuses a write to the roles too. + assert!(!objects(true).iter().any(|o| o["metadata"]["name"] == SELF_UPDATE_ROLE)); + let without = InstallParts::new(false, false, "w", "g", &db("c")); + assert!(!json!(without.access).to_string().contains(SELF_UPDATE_ROLE)); + assert!(!json!(without.access).to_string().contains("escalate\",\"bind\"],\"resourceNames\":[\"pyo-agent\"")); + let own_roles = |p: &InstallParts| { + p.admission[0]["spec"]["variables"] .as_array() .unwrap() - .contains(&json!("pyo-agent-upgrade")) - ); - // Not part of the default roles. - assert!( - !objects(true) .iter() - .any(|o| o["metadata"]["name"] == SELF_UPDATE_ROLE) - ); + .find(|v| v["name"] == "ownRoles") + .unwrap()["expression"] + .clone() + }; + assert_eq!(own_roles(&without), "false"); + let with = InstallParts::new(false, true, "w", "g", &db("c")); + assert_eq!(own_roles(&with), json!(own_roles_cel())); + assert_ne!(with.hash, without.hash); + } + + /// With the self-update role, the policy lets the agent update its own + /// roles and bindings: those objects only, never made or deleted, and + /// a binding's subjects stay Pyo's accounts. + #[test] + fn the_policy_lets_a_refresh_update_the_agents_own_roles() { + let cel = own_roles_cel(); + assert!(cel.starts_with("request.resource.group == 'rbac.authorization.k8s.io' && request.operation == 'UPDATE' && variables.sub == '' && ("), "{cel}"); + assert!(!cel.contains("CREATE") && !cel.contains("DELETE")); + for part in [ + "(request.resource.resource == 'clusterroles' && variables.reqName in ", + "'pyo-agent-read'", + "'pyo-agent-self-update'", + "(request.resource.resource == 'roles' && (variables.ns + '/' + variables.reqName) in ", + "'kube-system/pyo-agent'", + "'pyo-gateway/pyo-agent'", + "'pyo-gateway/pyo-tailnet'", + "'pyo-system/pyo-agent-policy'", + "'pyo-system/pyo-agent-upgrade'", + ] { + assert!(cel.contains(part), "{part}\n{cel}"); + } + // Both kinds of binding carry the subjects' rule. + let subjects = "has(object.subjects) && object.subjects.all(s, s.kind == 'ServiceAccount' && has(s.namespace) && s.namespace == 'pyo-system' && s.name in ['pyo-agent', 'pyo-tailnet'])"; + assert_eq!(cel.matches(subjects).count(), 2); + for resource in ["clusterrolebindings", "rolebindings"] { + let at = cel.find(&format!("request.resource.resource == '{resource}'")).unwrap(); + let clause = &cel[at..at + cel[at..].find(") || ").unwrap_or(cel.len() - at)]; + assert!(clause.contains(subjects), "{clause}"); + } + // Only roles of an install: nothing of a bundle, the upgrader or + // the cluster. + for other in ["cluster-admin", "'pyo-upgrade'", "system:", "cnpg"] { + assert!(!cel.contains(other), "{other}"); + } + // The four rules a role write would otherwise fail let it through, + // and only with the self-update role. + let with = admission_for(true, "w", "g")[0].to_string(); + let without = admission("w", "g")[0].to_string(); + assert_eq!(with.matches("|| variables.ownRoles\"").count(), 4); + assert_eq!(without.matches("|| variables.ownRoles\"").count(), 4); + assert!(without.contains(r#"{"expression":"false","name":"ownRoles"}"#), "{without}"); + assert!(!without.contains("'pyo-agent-self-update'")); + assert!(with.contains("'pyo-agent-self-update'")); } #[test] @@ -1691,5 +2655,122 @@ mod tests { ])); assert!(p.no_terminal && p.no_force_remove && p.read_only); assert!(!Policy::from_data(&d(&[("terminal", "on"), ("readOnly", "false")])).read_only); + // Automatic updates on hold: only the word "hold". + assert!(!p.updates_hold); + assert!(Policy::from_data(&d(&[("updates", " Hold ")])).updates_hold); + for other in ["", "on", "true", "off", "holding"] { + assert!(!Policy::from_data(&d(&[("updates", other)])).updates_hold, "{other}"); + } + // On the wire only when it's on, and a policy that never says is off. + let held = Policy { updates_hold: true, ..Default::default() }; + assert_eq!(json!(held)["updatesHold"], true); + assert!(json!(Policy::default()).get("updatesHold").is_none()); + assert_eq!(serde_json::from_value::(json!({})).unwrap(), Policy::default()); + } + + /// The verifier's status: the agent may read it by name, with the + /// role that reads the customer's policy (no new role object, so a + /// refresh brings it), and the admission policy refuses the agent any + /// write to it, whatever its roles say. + #[test] + fn the_agent_reads_the_verifiers_status_and_never_writes_it() { + let objs = objects(false); + let role = objs + .iter() + .find(|o| o["kind"] == "Role" && o["metadata"]["name"] == "pyo-agent-policy") + .unwrap(); + assert_eq!(role["metadata"]["namespace"], NS); + assert_eq!( + role["rules"], + json!([{ "apiGroups": [""], "resources": ["configmaps"], "verbs": ["get"], "resourceNames": ["pyo-policy", "pyo-verifier"] }]) + ); + // No other rule of an install names it, and the role bound in + // pyo-system reaches no ConfigMap. + for o in objects(true).iter().chain(self_update_objects().iter()) { + if o["kind"] == "Role" && o["metadata"]["name"] == "pyo-agent-policy" { + continue; + } + assert!(!o["rules"].to_string().contains(VERIFIER_CONFIGMAP), "{o}"); + } + let write = objs + .iter() + .find(|o| o["kind"] == "ClusterRole" && o["metadata"]["name"] == WRITE_ROLE) + .unwrap(); + assert!(!write["rules"].to_string().contains("configmaps")); + // The policy: every operation on it is refused, as for pyo-policy, + // with or without the self-update role. + for self_update in [false, true] { + let policy = &admission_for(self_update, "w", "g")[0]; + let rules = policy["spec"]["validations"].as_array().unwrap(); + for name in [POLICY_CONFIGMAP, VERIFIER_CONFIGMAP] { + let want = format!("!(request.resource.resource == 'configmaps' && variables.ns == 'pyo-system' && variables.reqName == '{name}')"); + let found: Vec<_> = rules.iter().filter(|r| r["expression"] == json!(want)).collect(); + assert_eq!(found.len(), 1, "{name}"); + // No way round it: the rule stands alone, with no "or". + assert!(!found[0]["expression"].as_str().unwrap().contains("||")); + } + } + assert_eq!( + admission("w", "g")[0]["spec"]["validations"] + .as_array() + .unwrap() + .iter() + .find(|r| r["expression"].as_str().is_some_and(|e| e.contains("'pyo-verifier'"))) + .unwrap()["message"], + "pyo-system/pyo-verifier belongs to your server: Pyo's agent only reads it." + ); + } + + #[test] + fn the_verifiers_status_is_read_leniently() { + let d = |pairs: &[(&str, &str)]| -> std::collections::BTreeMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + }; + let full = VerifierStatus::from_data(&d(&[ + ("version", "0.51.0"), + ("live", "0.51.0"), + ("checked", "2026-11-23T10:00:00Z"), + ("error", ""), + ("hold", "false"), + ("host", "server-1"), + ("more", "ignored"), + ])); + assert_eq!( + full, + VerifierStatus { + version: "0.51.0".into(), + live: "0.51.0".into(), + checked: "2026-11-23T10:00:00Z".into(), + error: String::new(), + hold: false, + host: "server-1".into(), + } + ); + // Missing fields are empty, and off. + assert_eq!(VerifierStatus::from_data(&d(&[])), VerifierStatus::default()); + // Hold only when it says so. + assert!(VerifierStatus::from_data(&d(&[("hold", " True ")])).hold); + for other in ["", "yes", "1", "on", "false"] { + assert!(!VerifierStatus::from_data(&d(&[("hold", other)])).hold, "{other}"); + } + // Whatever is there is kept as text, cut short. + let long = "é".repeat(5000); + let odd = VerifierStatus::from_data(&d(&[("checked", "yesterday"), ("error", &long)])); + assert_eq!(odd.checked, "yesterday"); + assert_eq!(odd.error.chars().count(), VerifierStatus::FIELD_MAX); + // On the wire: camelCase, absent when there's none, and a scope + // from an agent that never says is read as none. + let scope = AgentScope { verifier: Some(full.clone()), ..Default::default() }; + let wire = json!(scope); + assert_eq!(wire["verifier"]["checked"], "2026-11-23T10:00:00Z"); + assert_eq!(serde_json::from_value::(wire).unwrap(), scope); + assert!(json!(AgentScope::default()).get("verifier").is_none()); + let old: AgentScope = serde_json::from_value(json!({ "access": "limited", "admission": "enforced" })).unwrap(); + assert_eq!(old.verifier, None); + let partial: AgentScope = serde_json::from_value(json!({ "access": "limited", "admission": "enforced", "verifier": { "hold": true } })).unwrap(); + assert_eq!(partial.verifier, Some(VerifierStatus { hold: true, ..Default::default() })); } } diff --git a/crates/pyo-proto/src/system.rs b/crates/pyo-proto/src/system.rs index f91de332..8c4db022 100644 --- a/crates/pyo-proto/src/system.rs +++ b/crates/pyo-proto/src/system.rs @@ -414,6 +414,14 @@ pub fn waf_labels() -> Value { json!({ "app.kubernetes.io/name": WAF_NAME, "app.kubernetes.io/managed-by": "pyo" }) } +/// The priority of Pyo's pods that run on every server (the proxies, the +/// WAF, the tailnet pods, Vector): Kubernetes' own for such pods. A server +/// short of disk or memory never evicts them, and starts them all the same. +/// Without it, a DaemonSet's pod evicted there is replaced at once, the +/// replacement is refused, and so on: thousands of Failed pods an hour, +/// which can stall the cluster's datastore. +pub const SERVER_CRITICAL: &str = "system-node-critical"; + /// Which servers run a proxy: every one but build-only servers (labelled /// [`crate::BUILDER_NODE_LABEL`]; GPU servers too). The WAF's processor /// runs on exactly the same ones. @@ -445,6 +453,7 @@ pub fn waf_daemonset(image: &str, geoip_image: &str) -> Value { "serviceAccountName": WAF_NAME, "automountServiceAccountToken": true, "securityContext": { "runAsNonRoot": true, "runAsUser": 65532, "runAsGroup": 65532, "seccompProfile": { "type": "RuntimeDefault" } }, + "priorityClassName": SERVER_CRITICAL, "affinity": gateway_affinity(), "tolerations": [{ "key": crate::GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }], "containers": [{ @@ -664,6 +673,7 @@ pub fn envoy_proxy(geoip_image: &str, public: bool) -> Value { // host ports, so two fit on one server. "strategy": { "type": "RollingUpdate", "rollingUpdate": { "maxSurge": 1, "maxUnavailable": 0 } }, "pod": { + "priorityClassName": SERVER_CRITICAL, "affinity": gateway_affinity(), "tolerations": [{ "key": crate::GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }], "volumes": [{ "name": "geoip", "image": { "reference": geoip_image, "pullPolicy": "IfNotPresent" } }], @@ -725,6 +735,18 @@ pub fn envoy_proxy_public(spec: &Value) -> bool { spec["provider"]["kubernetes"]["envoyService"]["type"] != "ClusterIP" } +/// [`envoy_proxy`] without its pods' priority: the proxies as an install +/// whose admission policy is older than this agent's lists them (it +/// compares their whole settings, and 0.5.5's had no priority). None when +/// there's no priority to leave out. +pub fn envoy_proxy_without_priority(proxy: &Value) -> Option { + let mut older = proxy.clone(); + older["spec"]["provider"]["kubernetes"]["envoyDaemonSet"]["pod"] + .as_object_mut()? + .remove("priorityClassName")?; + Some(older) +} + pub fn gateway_class() -> Value { json!({ "apiVersion": "gateway.networking.k8s.io/v1", "kind": "GatewayClass", @@ -1093,6 +1115,7 @@ pub fn tailnet_daemonset(image: &str) -> Value { "metadata": { "labels": labels }, "spec": { "serviceAccountName": TAILNET_DAEMONSET, + "priorityClassName": SERVER_CRITICAL, "affinity": gateway_affinity(), "tolerations": [{ "key": crate::GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }], "containers": [{ @@ -1290,7 +1313,8 @@ pub const OTHER_VISITOR_HEADERS: [&str; 3] = ["x-real-ip", "x-client-ip", "forwa /// itself on every request it passes on. pub fn cdn_own_headers(cdn: &str) -> &'static [&'static str] { match cdn { - "cloudflare" => &["cf-connecting-ip", "cf-connecting-ipv6"], + // The tunnel's connectors pass on what Cloudflare set. + "cloudflare" | TUNNEL_CDN => &["cf-connecting-ip", "cf-connecting-ipv6"], _ => &[], } } @@ -1544,6 +1568,198 @@ pub fn cel_literal(v: &Value) -> String { } } +// ── Cloudflare Tunnel ────────────────────────────────────────────────────── +// +// A cluster's websites through Cloudflare with no open ports +// (docs/cloudflare-tunnel.md). The agent runs the connector (cloudflared) +// in pyo-system with the tunnel's token, and points it at +// `TUNNEL_ORIGIN_SERVICE`, its own Service in front of the proxies' +// HTTPS listener. Tunnel domains' listeners trust X-Forwarded-For only from +// the connector's pods (a client policy labelled [`TUNNEL_CDN`]). + +/// cloudflared, by digest (2026.10.7), as Pyo Cloud runs it. Renovate keeps +/// it current. +pub const CLOUDFLARED_IMAGE: &str = "cloudflare/cloudflared@sha256:4955524aeaa379e154023d5a027c250f7b35041a2e7e950cf13f144bc9b9c5ba"; +/// The connector's Deployment, Secret and disruption budget in pyo-system. +pub const TUNNEL_NAME: &str = "pyo-tunnel"; +/// The label on its pods (and the selector). +pub const TUNNEL_APP: &str = "pyo-tunnel"; +/// The Secret's label with the tunnel id its token is for. +pub const TUNNEL_ID_LABEL: &str = "pyo.dev/tunnel-id"; +/// The Secret's key with the token. +pub const TUNNEL_TOKEN_KEY: &str = "token"; +/// Connectors: two, spread across servers where it can. +pub const TUNNEL_REPLICAS: i32 = 2; +/// Where cloudflared serves `/ready` (nothing reaches it: pyo-system +/// denies ingress). +pub const TUNNEL_METRICS_PORT: i32 = 2000; +/// The Service cloudflared sends requests to: the proxies' HTTPS. +pub const TUNNEL_ORIGIN_SERVICE: &str = "pyo-tunnel-origin"; +/// The label on a service's client policy for its tunnel listeners +/// ([`CDN_LABEL`]): not a CDN users pick (`firewall::BEHIND`). +pub const TUNNEL_CDN: &str = "tunnel"; +/// The Service that keeps public TCP and UDP ports on the servers in +/// tunnel mode, when the proxies' own Service isn't published. +pub const PUBLIC_PORTS_SERVICE: &str = "pyo-public-ports"; + +/// The connector's token, labelled with its tunnel. +pub fn tunnel_secret(tunnel_id: &str, token: &str) -> Value { + json!({ + "apiVersion": "v1", "kind": "Secret", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/managed-by": "pyo", TUNNEL_ID_LABEL: tunnel_id } }, + "type": "Opaque", + "stringData": { TUNNEL_TOKEN_KEY: token }, + }) +} + +/// The connector: cloudflared over HTTP/2 (QUIC is often blocked, and its +/// fallback is slow enough that the probe restarts it first), with no +/// service account token, non-root, read only, no capabilities. Never on +/// build-only servers, spread across servers where it can be. +pub fn tunnel_deployment(image: &str) -> Value { + let app = json!({ "app.kubernetes.io/name": TUNNEL_APP }); + let probe = json!({ "httpGet": { "path": "/ready", "port": TUNNEL_METRICS_PORT } }); + json!({ + "apiVersion": "apps/v1", "kind": "Deployment", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/name": TUNNEL_APP, "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { + "replicas": TUNNEL_REPLICAS, + "selector": { "matchLabels": app }, + "strategy": { "type": "RollingUpdate", "rollingUpdate": { "maxSurge": 1, "maxUnavailable": 0 } }, + "template": { + "metadata": { "labels": app }, + "spec": { + "automountServiceAccountToken": false, + "affinity": gateway_affinity(), + "topologySpreadConstraints": [{ "maxSkew": 1, "topologyKey": "kubernetes.io/hostname", "whenUnsatisfiable": "ScheduleAnyway", "labelSelector": { "matchLabels": app } }], + "securityContext": { "runAsNonRoot": true, "runAsUser": 65532, "seccompProfile": { "type": "RuntimeDefault" } }, + "containers": [{ + "name": "cloudflared", + "image": image, + "args": ["tunnel", "--no-autoupdate", "--protocol", "http2", "--metrics", format!("0.0.0.0:{TUNNEL_METRICS_PORT}"), "--loglevel", "info", "run"], + "env": [{ "name": "TUNNEL_TOKEN", "valueFrom": { "secretKeyRef": { "name": TUNNEL_NAME, "key": TUNNEL_TOKEN_KEY } } }], + "readinessProbe": { "httpGet": probe["httpGet"], "periodSeconds": 10 }, + "livenessProbe": { "httpGet": probe["httpGet"], "initialDelaySeconds": 60, "periodSeconds": 30, "failureThreshold": 6 }, + "resources": { "requests": { "cpu": "10m", "memory": "32Mi" }, "limits": { "memory": "128Mi" } }, + "securityContext": { "allowPrivilegeEscalation": false, "readOnlyRootFilesystem": true, "capabilities": { "drop": ["ALL"] } }, + }], + }, + }, + }, + }) +} + +/// One connector stays up through a server's drain or a rollout. +pub fn tunnel_budget() -> Value { + json!({ + "apiVersion": "policy/v1", "kind": "PodDisruptionBudget", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "minAvailable": 1, "selector": { "matchLabels": { "app.kubernetes.io/name": TUNNEL_APP } } }, + }) +} + +/// The origin Service's one port: HTTPS onto the proxies' 443 listener. +pub fn tunnel_origin_ports() -> Value { + json!([{ "name": "https", "port": 443, "targetPort": 10443, "protocol": "TCP" }]) +} + +/// The Service cloudflared sends requests to, inside the cluster only. +pub fn tunnel_origin_service() -> Value { + json!({ + "apiVersion": "v1", "kind": "Service", + "metadata": { "name": TUNNEL_ORIGIN_SERVICE, "namespace": GATEWAY_NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "type": "ClusterIP", "selector": proxy_pods()["matchLabels"], "ports": tunnel_origin_ports() }, + }) +} + +/// Fields the API server fills in on a LoadBalancer Service with +/// externalTrafficPolicy Local, besides [`TAILNET_WEB_DEFAULTED`]. +pub const LOAD_BALANCER_DEFAULTED: [&str; 2] = ["allocateLoadBalancerNodePorts", "healthCheckNodePort"]; + +/// Public TCP and UDP ports in tunnel mode: a LoadBalancer Service onto +/// the proxies for these (protocol, public port), and nothing else. The +/// visitor's own address reaches the proxy (externalTrafficPolicy Local). +/// None without ports. +pub fn public_ports_service(ports: &[(String, i32)]) -> Option { + if ports.is_empty() { + return None; + } + let mut ports: Vec<(String, i32)> = ports.to_vec(); + ports.sort(); + ports.dedup(); + let list: Vec = ports + .iter() + .map(|(proto, port)| { + json!({ "name": format!("{}-{port}", proto.to_lowercase()), "port": port, "targetPort": crate::proxy_listen_port(*port), "protocol": proto }) + }) + .collect(); + Some(json!({ + "apiVersion": "v1", "kind": "Service", + "metadata": { "name": PUBLIC_PORTS_SERVICE, "namespace": GATEWAY_NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "type": "LoadBalancer", "externalTrafficPolicy": "Local", "selector": proxy_pods()["matchLabels"], "ports": list }, + })) +} + +/// X-Forwarded-For as a service gets it on its tunnel routes: the visitor +/// the proxy worked out, alone. The proxy reads the visitor from the +/// header only on the connectors' connections, then appends the address +/// it's connected to, so the service would see `, ` and an app reading the last entry would take a pod for its +/// visitor. This route filter replaces the header once the proxy is done +/// with it: the visitor through the tunnel, and a direct client's own +/// address while a domain is switching, whatever either sent. +pub const FORWARDED_FOR_HEADER: &str = "X-Forwarded-For"; +/// Envoy's own address for the request's client (never a header's text). +pub const FORWARDED_FOR_VISITOR: &str = "%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%"; + +/// The header a tunnel route's rules set ([`FORWARDED_FOR_HEADER`]). +pub fn forwarded_for_visitor() -> Value { + json!({ "name": FORWARDED_FOR_HEADER, "value": FORWARDED_FOR_VISITOR }) +} + +/// A route rule to a service, as its tunnel routes have it: with +/// X-Forwarded-For set to the visitor ([`forwarded_for_visitor`]). A rule +/// takes one header filter, so a static site's gets it in the one it has. +pub fn tunnel_rule(mut rule: Value) -> Value { + let header = forwarded_for_visitor(); + if let Some(set) = rule["filters"] + .as_array_mut() + .and_then(|fs| fs.iter_mut().find(|f| f["type"] == "RequestHeaderModifier")) + .and_then(|f| f["requestHeaderModifier"]["set"].as_array_mut()) + { + set.push(header); + return rule; + } + let filter = json!({ "type": "RequestHeaderModifier", "requestHeaderModifier": { "set": [header] } }); + match rule["filters"].as_array_mut() { + Some(fs) => fs.push(filter), + None => rule["filters"] = json!([filter]), + } + rule +} + +/// A service's client policy for its tunnel listeners. +pub fn tunnel_policy_name(base: &str) -> String { + format!("{base}-{TUNNEL_CDN}") +} + +/// Addresses as a client policy trusts them: each one alone (/32, /128), +/// sorted, deduped. +pub fn host_cidrs(ips: &[String]) -> Vec { + let mut out: Vec = ips + .iter() + .filter_map(|ip| ip.parse::().ok()) + .map(|ip| match ip { + std::net::IpAddr::V4(v4) => format!("{v4}/32"), + std::net::IpAddr::V6(v6) => format!("{v6}/128"), + }) + .collect(); + out.sort(); + out.dedup(); + out.truncate(MAX_TRUSTED_CIDRS); + out +} + #[cfg(test)] mod tests { #[test] @@ -1638,6 +1854,51 @@ mod tests { } } + /// A server short of disk keeps its proxy, WAF and tailnet pod: the + /// kubelet neither evicts nor refuses them, so their DaemonSets never + /// replace them over and over. + #[test] + fn per_server_pods_are_critical() { + for public in [true, false] { + let p = envoy_proxy("g", public); + assert_eq!( + p["spec"]["provider"]["kubernetes"]["envoyDaemonSet"]["pod"]["priorityClassName"], + SERVER_CRITICAL + ); + } + for ds in [waf_daemonset("w", "g"), tailnet_daemonset("a")] { + assert_eq!(ds["kind"], "DaemonSet"); + assert_eq!( + ds["spec"]["template"]["spec"]["priorityClassName"], SERVER_CRITICAL, + "{}", + ds["metadata"]["name"] + ); + } + // Kubernetes' built-in class for pods every server needs. + assert_eq!(SERVER_CRITICAL, "system-node-critical"); + } + + /// An install older than this agent lists the proxies without their + /// priority: that shape differs from this release's by the priority + /// alone, published or not, and there's none to leave out twice. + #[test] + fn the_proxies_older_shape_drops_only_their_priority() { + for public in [true, false] { + let now = envoy_proxy("g", public); + let mut older = envoy_proxy_without_priority(&now).expect("a priority to leave out"); + assert!( + older["spec"]["provider"]["kubernetes"]["envoyDaemonSet"]["pod"] + .get("priorityClassName") + .is_none() + ); + assert_eq!(envoy_proxy_public(&older["spec"]), public); + assert_eq!(envoy_proxy_without_priority(&older), None); + older["spec"]["provider"]["kubernetes"]["envoyDaemonSet"]["pod"]["priorityClassName"] = + json!(SERVER_CRITICAL); + assert_eq!(older, now); + } + } + /// An update never leaves a server without a proxy: the new one starts /// first, and the old one drains within the shutdown manager's 10 s. #[test] diff --git a/crates/pyo-proto/system/databases/cnpg.yaml b/crates/pyo-proto/system/databases/cnpg.yaml index 880ace53..69202994 100644 --- a/crates/pyo-proto/system/databases/cnpg.yaml +++ b/crates/pyo-proto/system/databases/cnpg.yaml @@ -1,12 +1,12 @@ -# CloudNativePG 1.30.1, the Postgres operator pyo-db-controller drives. +# CloudNativePG 1.30.2, the Postgres operator pyo-db-controller drives. # Vendored from its release manifest: -# https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.1/cnpg-1.30.1.yaml +# https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.2/cnpg-1.30.2.yaml # Changes from it (and nothing else): # - No cnpg-system Namespace: everything is in the databases namespace, # pyo-databases, so "namespace: cnpg-system" reads # "namespace: pyo-databases" throughout. # - The operator's image is pinned by digest (its container and -# OPERATOR_IMAGE_NAME): ghcr.io/cloudnative-pg/cloudnative-pg:1.30.1@sha256:923c267ec29636db3bee20f993d0ec4973fa22998e1adad37da79e4d32b5bc07 +# OPERATOR_IMAGE_NAME): ghcr.io/cloudnative-pg/cloudnative-pg:1.30.2@sha256:f96f6be3d81ec93819b443c665c575c609342fca840df90d4d87dae314a5b913 # - The operator runs 2 replicas (it elects a leader), preferably on # different servers, and leaves a lost server after 10s: with one, losing # its server blocks Postgres failover and every CloudNativePG webhook. @@ -17,8 +17,6 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: backups.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -428,6 +426,26 @@ spec: - key - name type: object + sseCustomerKey: + description: |- + Reference to the secret holding the key for Server-Side Encryption with + Customer-provided keys (SSE-C): a base64-encoded 256-bit AES key. + barman-cloud uses it to encrypt the objects it uploads and to read them + back. Meant for S3-compatible providers that only support SSE-C + (e.g. Hetzner Object Storage). Cannot be combined with `encryption`. + Works with any authentication method. Changing the key makes the + existing objects unreadable: use a new `destinationPath` or `serverName`. + properties: + key: + description: The key to select + type: string + name: + description: Name of the referent. + type: string + required: + - key + - name + type: object type: object serverName: description: |- @@ -489,8 +507,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: clusterimagecatalogs.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -709,8 +725,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: clusters.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -1859,12 +1873,13 @@ spec: description: |- Compress a backup file (a tar file per tablespace) while streaming it to the object store. Available options are empty string (no - compression, default), `gzip`, `bzip2`, `lz4`, and `snappy`. + compression, default), `gzip`, `bzip2`, `lz4`, `snappy`, and `zstd`. enum: - bzip2 - gzip - lz4 - snappy + - zstd type: string encryption: description: |- @@ -1970,6 +1985,16 @@ spec: HistoryTags is a list of key value pairs that will be passed to the Barman --history-tags option. type: object + s3AddressingStyle: + description: |- + How bucket names appear in S3 requests: `virtual` (bucket.endpoint/key), + `path` (endpoint/bucket/key) or `auto` (boto3 decides, same as unset). + Requires s3Credentials and Barman 3.18 or later. + enum: + - auto + - virtual + - path + type: string s3Credentials: description: The credentials to use to upload data to S3 properties: @@ -2030,6 +2055,26 @@ spec: - key - name type: object + sseCustomerKey: + description: |- + Reference to the secret holding the key for Server-Side Encryption with + Customer-provided keys (SSE-C): a base64-encoded 256-bit AES key. + barman-cloud uses it to encrypt the objects it uploads and to read them + back. Meant for S3-compatible providers that only support SSE-C + (e.g. Hetzner Object Storage). Cannot be combined with `encryption`. + Works with any authentication method. Changing the key makes the + existing objects unreadable: use a new `destinationPath` or `serverName`. + properties: + key: + description: The key to select + type: string + name: + description: Name of the referent. + type: string + required: + - key + - name + type: object type: object serverName: description: |- @@ -2122,6 +2167,11 @@ spec: required: - destinationPath type: object + x-kubernetes-validations: + - fieldPath: .s3AddressingStyle + message: s3AddressingStyle requires s3Credentials + reason: FieldValueForbidden + rule: '!has(self.s3AddressingStyle) || has(self.s3Credentials)' retentionPolicy: description: |- RetentionPolicy is the retention policy to be used for backups @@ -3474,12 +3524,13 @@ spec: description: |- Compress a backup file (a tar file per tablespace) while streaming it to the object store. Available options are empty string (no - compression, default), `gzip`, `bzip2`, `lz4`, and `snappy`. + compression, default), `gzip`, `bzip2`, `lz4`, `snappy`, and `zstd`. enum: - bzip2 - gzip - lz4 - snappy + - zstd type: string encryption: description: |- @@ -3585,6 +3636,16 @@ spec: HistoryTags is a list of key value pairs that will be passed to the Barman --history-tags option. type: object + s3AddressingStyle: + description: |- + How bucket names appear in S3 requests: `virtual` (bucket.endpoint/key), + `path` (endpoint/bucket/key) or `auto` (boto3 decides, same as unset). + Requires s3Credentials and Barman 3.18 or later. + enum: + - auto + - virtual + - path + type: string s3Credentials: description: The credentials to use to upload data to S3 properties: @@ -3645,6 +3706,26 @@ spec: - key - name type: object + sseCustomerKey: + description: |- + Reference to the secret holding the key for Server-Side Encryption with + Customer-provided keys (SSE-C): a base64-encoded 256-bit AES key. + barman-cloud uses it to encrypt the objects it uploads and to read them + back. Meant for S3-compatible providers that only support SSE-C + (e.g. Hetzner Object Storage). Cannot be combined with `encryption`. + Works with any authentication method. Changing the key makes the + existing objects unreadable: use a new `destinationPath` or `serverName`. + properties: + key: + description: The key to select + type: string + name: + description: Name of the referent. + type: string + required: + - key + - name + type: object type: object serverName: description: |- @@ -3737,6 +3818,11 @@ spec: required: - destinationPath type: object + x-kubernetes-validations: + - fieldPath: .s3AddressingStyle + message: s3AddressingStyle requires s3Credentials + reason: FieldValueForbidden + rule: '!has(self.s3AddressingStyle) || has(self.s3Credentials)' connectionParameters: additionalProperties: type: string @@ -8510,8 +8596,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: databaseroles.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -8837,8 +8921,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: databases.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -9434,8 +9516,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: failoverquorums.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -9511,8 +9591,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: imagecatalogs.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -9730,8 +9808,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: poolers.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -14826,6 +14902,7 @@ spec: Domain names *.k8s.io and *.kubernetes.io are reserved. This field must be unique for each responder. This field is required. + minLength: 1 type: string priority: description: |- @@ -14842,12 +14919,15 @@ spec: The interval 0-999 is reserved for responders with *.k8s.io suffix. This field is required. format: int32 + maximum: 100000 + minimum: 0 type: integer required: - name - priority type: object x-kubernetes-map-type: atomic + maxItems: 10 type: array x-kubernetes-list-map-keys: - name @@ -19538,8 +19618,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: publications.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -19736,8 +19814,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: scheduledbackups.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -19933,8 +20009,6 @@ spec: apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.22.0 name: subscriptions.postgresql.cnpg.io spec: group: postgresql.cnpg.io @@ -20248,6 +20322,7 @@ rules: - leases verbs: - create + - delete - get - list - update @@ -21034,14 +21109,14 @@ spec: - /manager env: - name: OPERATOR_IMAGE_NAME - value: ghcr.io/cloudnative-pg/cloudnative-pg:1.30.1@sha256:923c267ec29636db3bee20f993d0ec4973fa22998e1adad37da79e4d32b5bc07 + value: ghcr.io/cloudnative-pg/cloudnative-pg:1.30.2@sha256:f96f6be3d81ec93819b443c665c575c609342fca840df90d4d87dae314a5b913 - name: OPERATOR_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: MONITORING_QUERIES_CONFIGMAP value: cnpg-default-monitoring - image: ghcr.io/cloudnative-pg/cloudnative-pg:1.30.1@sha256:923c267ec29636db3bee20f993d0ec4973fa22998e1adad37da79e4d32b5bc07 + image: ghcr.io/cloudnative-pg/cloudnative-pg:1.30.2@sha256:f96f6be3d81ec93819b443c665c575c609342fca840df90d4d87dae314a5b913 imagePullPolicy: Always livenessProbe: httpGet: diff --git a/crates/pyo-proto/system/databases/controller.yaml b/crates/pyo-proto/system/databases/controller.yaml index 500a67b7..2e3b7385 100644 --- a/crates/pyo-proto/system/databases/controller.yaml +++ b/crates/pyo-proto/system/databases/controller.yaml @@ -148,8 +148,8 @@ spec: - {name: PYO_DB_POSTGRES_IMAGE_18, value: __POSTGRES_IMAGE_18__} - {name: PYO_DB_VALKEY_IMAGE, value: docker.io/valkey/valkey} # Valkey 8.1 with its modules (valkey-json, valkey-bloom, valkey-search), run while a KV database loads any. - - {name: PYO_DB_VALKEY_BUNDLE_IMAGE, value: "docker.io/valkey/valkey-bundle:8.1.11@sha256:3f57cc71a102e0e66991ae203b069038d8c3f6214ca887ff32f9a381091af8de"} - - {name: PYO_DB_MYSQL_IMAGE, value: "ghcr.io/cybozu-go/moco/mysql:8.4.10.1@sha256:51dffb347697795e1680b9930fea1e1055a71387a0e769cc61ab4efc539c149b"} + - {name: PYO_DB_VALKEY_BUNDLE_IMAGE, value: "docker.io/valkey/valkey-bundle:8.1.12@sha256:ca9d1c30a6b3c30de34691ff5ddff6fb77f5c8c727a63723c62d8ebd280e7921"} + - {name: PYO_DB_MYSQL_IMAGE, value: "ghcr.io/cybozu-go/moco/mysql:8.4.10.1@sha256:bdb88ae2023dcba0218bf900c7f39117c7a6e4101de6b5c8f62774c1d897b68a"} - {name: POD_NAME, valueFrom: {fieldRef: {fieldPath: metadata.name}}} - {name: POD_NAMESPACE, valueFrom: {fieldRef: {fieldPath: metadata.namespace}}} ports: [{name: probes, containerPort: 8081}] diff --git a/crates/pyo-sigstore/Cargo.toml b/crates/pyo-sigstore/Cargo.toml new file mode 100644 index 00000000..7cf4e856 --- /dev/null +++ b/crates/pyo-sigstore/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "pyo-sigstore" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +# Offline Sigstore checks, for pyo-api and the small static pyo-verify: +# keep this list short. +[dependencies] +anyhow = "1.0.104" +# The same aws-lc the rest of Pyo uses through rustls. +aws-lc-rs = { version = "1.18", default-features = false, features = ["aws-lc-sys", "prebuilt-nasm"] } +base64 = "0.23.1" +hex = "0.4.3" +serde_json = "1.0.154" +sha2 = "0.11.1" +x509-parser = "0.18" diff --git a/crates/pyo-api/assets/sigstore/fulcio-intermediate.der b/crates/pyo-sigstore/assets/fulcio-intermediate.der similarity index 100% rename from crates/pyo-api/assets/sigstore/fulcio-intermediate.der rename to crates/pyo-sigstore/assets/fulcio-intermediate.der diff --git a/crates/pyo-api/assets/sigstore/fulcio-root.der b/crates/pyo-sigstore/assets/fulcio-root.der similarity index 100% rename from crates/pyo-api/assets/sigstore/fulcio-root.der rename to crates/pyo-sigstore/assets/fulcio-root.der diff --git a/crates/pyo-api/assets/sigstore/rekor.der b/crates/pyo-sigstore/assets/rekor.der similarity index 100% rename from crates/pyo-api/assets/sigstore/rekor.der rename to crates/pyo-sigstore/assets/rekor.der diff --git a/crates/pyo-api/assets/sigstore/testdata/cosign_checksums.txt b/crates/pyo-sigstore/assets/testdata/cosign_checksums.txt similarity index 100% rename from crates/pyo-api/assets/sigstore/testdata/cosign_checksums.txt rename to crates/pyo-sigstore/assets/testdata/cosign_checksums.txt diff --git a/crates/pyo-api/assets/sigstore/testdata/cosign_checksums.txt.sigstore.json b/crates/pyo-sigstore/assets/testdata/cosign_checksums.txt.sigstore.json similarity index 100% rename from crates/pyo-api/assets/sigstore/testdata/cosign_checksums.txt.sigstore.json rename to crates/pyo-sigstore/assets/testdata/cosign_checksums.txt.sigstore.json diff --git a/crates/pyo-sigstore/assets/testdata/release-0.5.4/release.json b/crates/pyo-sigstore/assets/testdata/release-0.5.4/release.json new file mode 100644 index 00000000..4b085cbf --- /dev/null +++ b/crates/pyo-sigstore/assets/testdata/release-0.5.4/release.json @@ -0,0 +1,3308 @@ +{ + "version": "0.5.4", + "images": { + "pyo": "ghcr.io/upsetdev/pyo/pyo:0.5.4@sha256:b8778bdec53339b0f23d94520e2fe743728a519806d0f50e24cbc0c3afb60f8a", + "agent": "ghcr.io/upsetdev/pyo/agent:0.5.4@sha256:75947f00afdb21e3526cffa0c70f727b1d7b30bcc19a2fcd7b666d14ae4e48ba", + "builder": "ghcr.io/upsetdev/pyo/builder:0.5.4@sha256:774500c22a953db40c670822691e6209095531a70d2330c33a8313e4000deec0", + "flows": "ghcr.io/upsetdev/pyo/flows:0.5.4@sha256:aa9293228599aa952bb4ab315865787f8071f8f2c23c39fa3cb1bcc0edfd04dc", + "waf": "ghcr.io/upsetdev/pyo/waf:0.5.4@sha256:5a00c51d2de1bdb321703d9227ebd244606f24d07a6a373b2b52e3f06c625f5d", + "geoip": "ghcr.io/upsetdev/pyo/geoip:0.5.4@sha256:6d5b45b2b6bd0d2da9676e7ad8ea3cd66d330275cdb329c153a8c13bb88abb40", + "dbController": "ghcr.io/upsetdev/pyo/db-controller:0.5.4@sha256:3903974417d92f47fb0841d510e6f8d05343733327bd16fc826dcbbff95c750f", + "kv": "ghcr.io/upsetdev/pyo/kv:0.5.4@sha256:af56ee5e3f6e5f55fe642267c596381816de7e60455dc1adbf74262b386d4009", + "static": "ghcr.io/upsetdev/pyo/static:0.5.4@sha256:407bf277d59a158e1e4c7e8e31bcfbe4aef28b3ef1f79c6963117d3850511d4a", + "mysqlOperator": "ghcr.io/upsetdev/pyo/mysql-operator:0.5.4@sha256:84361c6e7990055481cd6032ec4b377eded64f82fc58d31043159364793a99ad", + "mysqlBackup": "ghcr.io/upsetdev/pyo/mysql-backup:0.5.4@sha256:70d2d853d357bd8d94ccec7fa8834cfb539c9b1fa5a56594e9de3017b27c23e5", + "sandboxBase": "ghcr.io/upsetdev/pyo-sandbox-images/base@sha256:c3735cc2430df05457817f1d8fa111bbb06bd3b70cfa61e197339b5506e79c2a", + "sandboxDesktop": "ghcr.io/upsetdev/pyo-sandbox-images/desktop@sha256:c47057d8a037403344172f3a73d3370bf9bd253b6c83addc9801878c76cad5f5", + "postgres16": "ghcr.io/upsetdev/pyo/postgres:16-0.5.4@sha256:54cd52417c189df7b035754d75a749c3cf05ba903b7c8ff957980d22079606dc", + "postgres17": "ghcr.io/upsetdev/pyo/postgres:17-0.5.4@sha256:e55fb95cf080da188e821d5eacfcdf626f9a7e88c38fdc3b26b5e9dc4f0bfd76", + "postgres18": "ghcr.io/upsetdev/pyo/postgres:18-0.5.4@sha256:7fff3b644b3c496ae3d467791166efe3000da1f8dae8d2aa3d523736db43612c" + }, + "k3s": { + "version": "v1.37.2+k3s1", + "installerSha256": "ed01f89fd977bf20ac1516bbebf8370bf3ddbaa55dac8aba610956a4c78cc00b", + "amd64Sha256": "265b3ee6a3198ef14033c63ef46cbb32370d83795199fb6d1b01f21575eddbda", + "arm64Sha256": "a779ccf1e5e2e33a62f5a29c2f1c0bbf99431e100579d4c10f0aa0742a6aa84b" + }, + "manifests": { + "platform": [ + { + "apiVersion": "v1", + "kind": "Namespace", + "metadata": { + "name": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + } + }, + { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": { + "name": "default-deny", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "podSelector": {}, + "policyTypes": [ + "Ingress" + ] + } + }, + { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": { + "name": "pyo", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "podSelector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo" + } + }, + "policyTypes": [ + "Ingress" + ], + "ingress": [ + { + "from": [ + { + "namespaceSelector": { + "matchLabels": { + "kubernetes.io/metadata.name": "pyo-system" + } + } + }, + { + "namespaceSelector": { + "matchLabels": { + "kubernetes.io/metadata.name": "pyo-gateway" + } + } + }, + { + "namespaceSelector": { + "matchLabels": { + "kubernetes.io/metadata.name": "pyo-static" + } + } + }, + { + "namespaceSelector": { + "matchExpressions": [ + { + "key": "pyo/project-id", + "operator": "DoesNotExist" + } + ] + }, + "podSelector": { + "matchLabels": { + "pyo.dev/component": "import" + } + } + } + ], + "ports": [ + { + "port": 8000 + }, + { + "port": 5006 + } + ] + }, + { + "from": [ + { + "ipBlock": { + "cidr": "10.42.0.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.1.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.2.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.3.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.4.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.5.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.6.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.7.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.8.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.9.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.10.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.11.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.12.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.13.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.14.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.15.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.16.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.17.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.18.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.19.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.20.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.21.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.22.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.23.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.24.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.25.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.26.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.27.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.28.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.29.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.30.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.31.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.32.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.33.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.34.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.35.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.36.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.37.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.38.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.39.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.40.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.41.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.42.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.43.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.44.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.45.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.46.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.47.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.48.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.49.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.50.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.51.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.52.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.53.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.54.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.55.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.56.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.57.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.58.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.59.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.60.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.61.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.62.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.63.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.64.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.65.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.66.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.67.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.68.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.69.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.70.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.71.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.72.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.73.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.74.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.75.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.76.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.77.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.78.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.79.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.80.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.81.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.82.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.83.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.84.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.85.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.86.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.87.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.88.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.89.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.90.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.91.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.92.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.93.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.94.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.95.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.96.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.97.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.98.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.99.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.100.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.101.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.102.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.103.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.104.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.105.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.106.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.107.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.108.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.109.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.110.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.111.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.112.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.113.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.114.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.115.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.116.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.117.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.118.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.119.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.120.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.121.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.122.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.123.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.124.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.125.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.126.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.127.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.128.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.129.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.130.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.131.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.132.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.133.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.134.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.135.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.136.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.137.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.138.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.139.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.140.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.141.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.142.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.143.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.144.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.145.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.146.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.147.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.148.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.149.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.150.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.151.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.152.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.153.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.154.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.155.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.156.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.157.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.158.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.159.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.160.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.161.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.162.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.163.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.164.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.165.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.166.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.167.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.168.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.169.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.170.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.171.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.172.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.173.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.174.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.175.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.176.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.177.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.178.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.179.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.180.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.181.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.182.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.183.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.184.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.185.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.186.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.187.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.188.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.189.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.190.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.191.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.192.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.193.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.194.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.195.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.196.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.197.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.198.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.199.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.200.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.201.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.202.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.203.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.204.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.205.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.206.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.207.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.208.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.209.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.210.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.211.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.212.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.213.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.214.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.215.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.216.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.217.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.218.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.219.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.220.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.221.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.222.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.223.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.224.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.225.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.226.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.227.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.228.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.229.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.230.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.231.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.232.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.233.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.234.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.235.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.236.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.237.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.238.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.239.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.240.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.241.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.242.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.243.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.244.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.245.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.246.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.247.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.248.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.249.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.250.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.251.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.252.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.253.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.254.0/31" + } + }, + { + "ipBlock": { + "cidr": "10.42.255.0/31" + } + } + ], + "ports": [ + { + "port": 8000 + }, + { + "port": 5006 + } + ] + } + ] + } + }, + { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": { + "name": "pyo-databases", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "podSelector": { + "matchExpressions": [ + { + "key": "app.kubernetes.io/name", + "operator": "In", + "values": [ + "pyo-postgres", + "pyo-clickhouse" + ] + } + ] + }, + "policyTypes": [ + "Ingress" + ], + "ingress": [ + { + "from": [ + { + "podSelector": { + "matchExpressions": [ + { + "key": "app.kubernetes.io/name", + "operator": "In", + "values": [ + "pyo", + "pyo-worker" + ] + } + ] + } + } + ], + "ports": [ + { + "port": 5432 + }, + { + "port": 8123 + } + ] + } + ] + } + }, + { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": { + "name": "pyo-backup-store", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "podSelector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-backup-store" + } + }, + "policyTypes": [ + "Ingress" + ], + "ingress": [ + { + "ports": [ + { + "port": 3900 + } + ] + }, + { + "from": [ + { + "podSelector": { + "matchExpressions": [ + { + "key": "app.kubernetes.io/name", + "operator": "In", + "values": [ + "pyo", + "pyo-worker" + ] + } + ] + } + } + ], + "ports": [ + { + "port": 3903 + } + ] + } + ] + } + }, + { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": { + "name": "registry", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "podSelector": { + "matchLabels": { + "app.kubernetes.io/name": "registry" + } + }, + "policyTypes": [ + "Ingress" + ], + "ingress": [ + { + "from": [ + { + "podSelector": { + "matchExpressions": [ + { + "key": "app.kubernetes.io/name", + "operator": "In", + "values": [ + "pyo", + "pyo-worker" + ] + } + ] + } + } + ], + "ports": [ + { + "port": 5000 + } + ] + } + ] + } + }, + { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": { + "name": "pyo-traffic", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "podSelector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-traffic" + } + }, + "policyTypes": [ + "Ingress" + ], + "ingress": [ + { + "from": [ + { + "podSelector": { + "matchExpressions": [ + { + "key": "app.kubernetes.io/name", + "operator": "In", + "values": [ + "pyo-agent", + "pyo-vector" + ] + } + ] + } + } + ], + "ports": [ + { + "port": 8090 + } + ] + } + ] + } + }, + { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": { + "name": "pyo-agent", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "podSelector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-agent" + } + }, + "policyTypes": [ + "Ingress" + ], + "ingress": [ + { + "from": [ + { + "podSelector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-vector" + } + } + } + ], + "ports": [ + { + "port": 8089 + } + ] + } + ] + } + }, + { + "apiVersion": "v1", + "kind": "PersistentVolumeClaim", + "metadata": { + "name": "registry-data", + "namespace": "pyo-system" + }, + "spec": { + "accessModes": [ + "ReadWriteOnce" + ], + "resources": { + "requests": { + "storage": "20Gi" + } + } + } + }, + { + "apiVersion": "v1", + "kind": "Service", + "metadata": { + "name": "pyo-registry", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "registry", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "selector": { + "app.kubernetes.io/name": "registry" + }, + "ports": [ + { + "name": "registry", + "port": 5000, + "targetPort": "registry" + } + ] + } + }, + { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": { + "name": "registry", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "registry", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "replicas": 1, + "strategy": { + "type": "Recreate" + }, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "registry" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "registry", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "containers": [ + { + "name": "registry", + "image": "registry:3.1.2", + "env": [ + { + "name": "REGISTRY_HTTP_ADDR", + "value": "0.0.0.0:5000" + }, + { + "name": "REGISTRY_STORAGE_DELETE_ENABLED", + "value": "true" + }, + { + "name": "OTEL_TRACES_EXPORTER", + "value": "none" + }, + { + "name": "REGISTRY_LOG_LEVEL", + "value": "warn" + }, + { + "name": "REGISTRY_LOG_ACCESSLOG_DISABLED", + "value": "true" + } + ], + "ports": [ + { + "name": "registry", + "containerPort": 5000 + } + ], + "readinessProbe": { + "httpGet": { + "path": "/v2/", + "port": "registry" + }, + "periodSeconds": 30, + "failureThreshold": 3 + }, + "volumeMounts": [ + { + "name": "data", + "mountPath": "/var/lib/registry" + } + ], + "resources": { + "requests": { + "cpu": "10m", + "memory": "24Mi" + }, + "limits": { + "memory": "512Mi" + } + } + }, + { + "name": "gc", + "image": "registry:3.1.2", + "command": [ + "sh", + "-c", + "while sleep 86400; do registry garbage-collect /etc/distribution/config.yml; done" + ], + "volumeMounts": [ + { + "name": "data", + "mountPath": "/var/lib/registry" + } + ], + "resources": { + "requests": { + "cpu": "5m", + "memory": "8Mi" + }, + "limits": { + "memory": "256Mi" + } + } + } + ], + "volumes": [ + { + "name": "data", + "persistentVolumeClaim": { + "claimName": "registry-data" + } + } + ] + } + } + } + }, + { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": { + "name": "pyo-host", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-host", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "replicas": 1, + "strategy": { + "type": "Recreate" + }, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-host" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "pyo-host", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "hostNetwork": true, + "dnsPolicy": "ClusterFirstWithHostNet", + "affinity": { + "podAffinity": { + "requiredDuringSchedulingIgnoredDuringExecution": [ + { + "labelSelector": { + "matchLabels": { + "app.kubernetes.io/name": "registry" + } + }, + "topologyKey": "kubernetes.io/hostname" + } + ] + } + }, + "containers": [ + { + "name": "forward", + "image": "alpine/socat:1.8.1.3", + "args": [ + "TCP-LISTEN:5005,bind=127.0.0.1,fork,reuseaddr", + "TCP:pyo-registry.pyo-system.svc.cluster.local:5000" + ], + "resources": { + "requests": { + "cpu": "5m", + "memory": "8Mi" + }, + "limits": { + "memory": "64Mi" + } + } + } + ] + } + } + } + }, + { + "apiVersion": "v1", + "kind": "ConfigMap", + "metadata": { + "name": "buildkitd", + "namespace": "pyo-system" + }, + "data": { + "buildkitd.toml": "[registry.\"127.0.0.1:5005\"]\n http = true\n insecure = true\n[worker.oci]\n gc = true\n gckeepstorage = \"20GB\"\n" + } + }, + { + "apiVersion": "v1", + "kind": "PersistentVolumeClaim", + "metadata": { + "name": "buildkit-cache", + "namespace": "pyo-system" + }, + "spec": { + "accessModes": [ + "ReadWriteOnce" + ], + "resources": { + "requests": { + "storage": "30Gi" + } + } + } + }, + { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": { + "name": "buildkitd", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "buildkitd", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "replicas": 0, + "strategy": { + "type": "Recreate" + }, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "buildkitd" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "buildkitd", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "hostNetwork": true, + "containers": [ + { + "name": "buildkitd", + "image": "moby/buildkit:v0.34.1", + "args": [ + "--addr=tcp://127.0.0.1:1234", + "--addr=unix:///run/buildkit/buildkitd.sock", + "--config=/etc/buildkit/buildkitd.toml" + ], + "securityContext": { + "privileged": true + }, + "readinessProbe": { + "exec": { + "command": [ + "buildctl", + "debug", + "workers" + ] + }, + "initialDelaySeconds": 3, + "periodSeconds": 10 + }, + "volumeMounts": [ + { + "name": "config", + "mountPath": "/etc/buildkit" + }, + { + "name": "cache", + "mountPath": "/var/lib/buildkit" + } + ], + "resources": { + "requests": { + "cpu": "100m", + "memory": "256Mi" + } + } + } + ], + "volumes": [ + { + "name": "config", + "configMap": { + "name": "buildkitd" + } + }, + { + "name": "cache", + "persistentVolumeClaim": { + "claimName": "buildkit-cache" + } + } + ] + } + } + } + }, + { + "apiVersion": "v1", + "kind": "Service", + "metadata": { + "name": "pyo-postgres", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-postgres", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "selector": { + "app.kubernetes.io/name": "pyo-postgres" + }, + "ports": [ + { + "name": "postgres", + "port": 5432, + "targetPort": "postgres" + } + ] + } + }, + { + "apiVersion": "apps/v1", + "kind": "StatefulSet", + "metadata": { + "name": "pyo-postgres", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-postgres", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "serviceName": "pyo-postgres", + "replicas": 1, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-postgres" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "pyo-postgres", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "securityContext": { + "runAsUser": 70, + "runAsGroup": 70, + "runAsNonRoot": true + }, + "containers": [ + { + "name": "postgres", + "image": "postgres:18.6-alpine", + "command": [ + "sh", + "-c" + ], + "args": [ + "mem=$$(awk '/^MemTotal:/ { print int($2 / 1024) }' \"${PYO_MEMINFO:-/proc/meminfo}\")\nif [ \"${mem:-4096}\" -lt 3584 ]; then\n set -- -c shared_buffers=16MB -c effective_cache_size=128MB -c maintenance_work_mem=16MB \\\n -c wal_buffers=512kB -c max_connections=40 -c autovacuum_max_workers=1 \\\n -c max_parallel_workers_per_gather=0\nelif [ \"$mem\" -lt 8192 ]; then\n set -- -c shared_buffers=32MB -c effective_cache_size=256MB -c maintenance_work_mem=32MB \\\n -c wal_buffers=1MB -c max_connections=80 -c autovacuum_max_workers=2\nelse\n set -- -c shared_buffers=64MB -c effective_cache_size=1GB -c maintenance_work_mem=64MB \\\n -c wal_buffers=2MB -c max_connections=120 -c autovacuum_max_workers=2\nfi\nexec docker-entrypoint.sh postgres \"$@\" -c work_mem=2MB -c jit=off -c huge_pages=off\n" + ], + "env": [ + { + "name": "POSTGRES_DB", + "value": "pyo" + }, + { + "name": "POSTGRES_USER", + "value": "pyo" + }, + { + "name": "POSTGRES_PASSWORD", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-postgres", + "key": "password" + } + } + }, + { + "name": "PGDATA", + "value": "/var/lib/postgresql/data/pgdata" + } + ], + "ports": [ + { + "name": "postgres", + "containerPort": 5432 + } + ], + "readinessProbe": { + "exec": { + "command": [ + "pg_isready", + "-U", + "pyo", + "-d", + "pyo" + ] + }, + "periodSeconds": 5 + }, + "volumeMounts": [ + { + "name": "data", + "mountPath": "/var/lib/postgresql/data" + } + ], + "resources": { + "requests": { + "cpu": "50m", + "memory": "112Mi" + }, + "limits": { + "memory": "512Mi" + } + } + } + ] + } + }, + "volumeClaimTemplates": [ + { + "metadata": { + "name": "data" + }, + "spec": { + "accessModes": [ + "ReadWriteOnce" + ], + "resources": { + "requests": { + "storage": "10Gi" + } + } + } + } + ] + } + }, + { + "apiVersion": "v1", + "kind": "Service", + "metadata": { + "name": "pyo-clickhouse", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-clickhouse", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "selector": { + "app.kubernetes.io/name": "pyo-clickhouse" + }, + "ports": [ + { + "name": "http", + "port": 8123, + "targetPort": "http" + } + ] + } + }, + { + "apiVersion": "v1", + "kind": "ConfigMap", + "metadata": { + "name": "pyo-clickhouse", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-clickhouse", + "app.kubernetes.io/part-of": "pyo" + } + }, + "data": { + "config.xml": "\n \n \n warning\n 50M\n 2\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n 0\n 0.7\n \n 6\n 134217728\n 16777216\n 0\n 0\n 0\n 16777216\n 64\n 8388608\n 1000\n 8388608\n \n 0\n 0\n \n\n \n 500\n 10\n 500\n 16\n 2\n 2\n 2\n 2\n 2\n 2\n 2\n 1\n 1\n 1\n 2\n 2\n 2\n 2\n 16\n 2\n 1\n 1\n 1\n 1\n 1\n 1\n 1\n 2\n 2\n 2\n 2\n\n \n \n 0\n 0\n 0\n \n\n", + "users.xml": "\n \n \n 2\n 209715200\n 33554432\n 0.2\n 33554432\n 0.2\n 30\n 20000\n 0\n \n \n\n" + } + }, + { + "apiVersion": "apps/v1", + "kind": "StatefulSet", + "metadata": { + "name": "pyo-clickhouse", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-clickhouse", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "serviceName": "pyo-clickhouse", + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-clickhouse" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "pyo-clickhouse", + "app.kubernetes.io/part-of": "pyo" + }, + "annotations": { + "pyo.dev/config": "1" + } + }, + "spec": { + "containers": [ + { + "name": "clickhouse", + "image": "clickhouse/clickhouse-server:26.8.36.3", + "env": [ + { + "name": "CLICKHOUSE_DB", + "value": "pyo_observability" + }, + { + "name": "CLICKHOUSE_USER", + "value": "pyo" + }, + { + "name": "CLICKHOUSE_PASSWORD", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-clickhouse", + "key": "password" + } + } + } + ], + "ports": [ + { + "name": "http", + "containerPort": 8123 + } + ], + "readinessProbe": { + "httpGet": { + "path": "/ping", + "port": "http" + }, + "periodSeconds": 5 + }, + "volumeMounts": [ + { + "name": "data", + "mountPath": "/var/lib/clickhouse" + }, + { + "name": "config", + "mountPath": "/etc/clickhouse-server/config.d/pyo.xml", + "subPath": "config.xml", + "readOnly": true + }, + { + "name": "config", + "mountPath": "/etc/clickhouse-server/users.d/pyo.xml", + "subPath": "users.xml", + "readOnly": true + } + ], + "resources": { + "requests": { + "cpu": "50m", + "memory": "144Mi" + }, + "limits": { + "memory": "512Mi" + } + } + } + ], + "volumes": [ + { + "name": "config", + "configMap": { + "name": "pyo-clickhouse" + } + } + ] + } + }, + "volumeClaimTemplates": [ + { + "metadata": { + "name": "data" + }, + "spec": { + "accessModes": [ + "ReadWriteOnce" + ], + "resources": { + "requests": { + "storage": "10Gi" + } + } + } + } + ] + } + }, + { + "apiVersion": "v1", + "kind": "ConfigMap", + "metadata": { + "name": "pyo-backup-store", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-backup-store", + "app.kubernetes.io/part-of": "pyo" + } + }, + "data": { + "garage.toml": "metadata_dir = \"/var/lib/garage/meta\"\ndata_dir = \"/var/lib/garage/data\"\ndb_engine = \"lmdb\"\nreplication_factor = 1\ncompression_level = \"none\"\nblock_ram_buffer_max = \"64MiB\"\nrpc_bind_addr = \"127.0.0.1:3901\"\nrpc_public_addr = \"127.0.0.1:3901\"\n\n[s3_api]\ns3_region = \"garage\"\napi_bind_addr = \"0.0.0.0:3900\"\n\n[admin]\napi_bind_addr = \"0.0.0.0:3903\"\nmetrics_require_token = true\n" + } + }, + { + "apiVersion": "v1", + "kind": "Service", + "metadata": { + "name": "pyo-backup-store", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-backup-store", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "selector": { + "app.kubernetes.io/name": "pyo-backup-store" + }, + "ports": [ + { + "name": "s3", + "port": 3900, + "targetPort": "s3" + }, + { + "name": "admin", + "port": 3903, + "targetPort": "admin" + } + ] + } + }, + { + "apiVersion": "apps/v1", + "kind": "StatefulSet", + "metadata": { + "name": "pyo-backup-store", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-backup-store", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "serviceName": "pyo-backup-store", + "replicas": 1, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-backup-store" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "pyo-backup-store", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "automountServiceAccountToken": false, + "securityContext": { + "runAsNonRoot": true, + "runAsUser": 1000, + "runAsGroup": 1000, + "fsGroup": 1000, + "seccompProfile": { + "type": "RuntimeDefault" + } + }, + "containers": [ + { + "name": "garage", + "image": "dxflrs/garage@sha256:677e5b758e4425a325b811c425c026bf35a4bf42f7ddbaa773de3f4fd779a5a5", + "command": [ + "/garage", + "-c", + "/etc/garage/garage.toml", + "server" + ], + "env": [ + { + "name": "GARAGE_RPC_SECRET", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-backup-store", + "key": "rpc-secret" + } + } + }, + { + "name": "GARAGE_ADMIN_TOKEN", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-backup-store", + "key": "admin-token" + } + } + } + ], + "ports": [ + { + "name": "s3", + "containerPort": 3900 + }, + { + "name": "admin", + "containerPort": 3903 + } + ], + "readinessProbe": { + "tcpSocket": { + "port": "s3" + }, + "periodSeconds": 5 + }, + "securityContext": { + "allowPrivilegeEscalation": false, + "readOnlyRootFilesystem": true, + "capabilities": { + "drop": [ + "ALL" + ] + } + }, + "volumeMounts": [ + { + "name": "config", + "mountPath": "/etc/garage", + "readOnly": true + }, + { + "name": "data", + "mountPath": "/var/lib/garage" + } + ], + "resources": { + "requests": { + "cpu": "20m", + "memory": "16Mi" + }, + "limits": { + "memory": "512Mi" + } + } + } + ], + "volumes": [ + { + "name": "config", + "configMap": { + "name": "pyo-backup-store" + } + } + ] + } + }, + "volumeClaimTemplates": [ + { + "metadata": { + "name": "data" + }, + "spec": { + "accessModes": [ + "ReadWriteOnce" + ], + "resources": { + "requests": { + "storage": "50Gi" + } + } + } + } + ] + } + } + ], + "pyo": [ + { + "apiVersion": "v1", + "kind": "Service", + "metadata": { + "name": "pyo", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "type": "ClusterIP", + "selector": { + "app.kubernetes.io/name": "pyo" + }, + "ports": [ + { + "name": "http", + "port": 8000, + "targetPort": "http" + } + ] + } + }, + { + "apiVersion": "v1", + "kind": "Service", + "metadata": { + "name": "pyo-registry-door", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "type": "ClusterIP", + "selector": { + "app.kubernetes.io/name": "pyo" + }, + "ports": [ + { + "name": "registry-door", + "port": 5006, + "targetPort": "registry-door" + } + ] + } + }, + { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": { + "name": "pyo", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "replicas": 1, + "strategy": { + "type": "RollingUpdate", + "rollingUpdate": { + "maxUnavailable": 0, + "maxSurge": 1 + } + }, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "pyo", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "terminationGracePeriodSeconds": 45, + "affinity": { + "podAntiAffinity": { + "preferredDuringSchedulingIgnoredDuringExecution": [ + { + "weight": 100, + "podAffinityTerm": { + "labelSelector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo" + } + }, + "topologyKey": "kubernetes.io/hostname" + } + } + ] + } + }, + "containers": [ + { + "name": "pyo", + "image": "ghcr.io/upsetdev/pyo/pyo:0.5.4@sha256:b8778bdec53339b0f23d94520e2fe743728a519806d0f50e24cbc0c3afb60f8a", + "ports": [ + { + "name": "http", + "containerPort": 8000 + }, + { + "name": "registry-door", + "containerPort": 5006 + } + ], + "env": [ + { + "name": "DATABASE_URL", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-postgres", + "key": "url" + } + } + }, + { + "name": "PYO_AGENT_API_URL", + "value": "http://pyo.pyo-system.svc:8000" + }, + { + "name": "PYO_AGENT_IMAGE", + "value": "ghcr.io/upsetdev/pyo/agent:0.5.4@sha256:75947f00afdb21e3526cffa0c70f727b1d7b30bcc19a2fcd7b666d14ae4e48ba" + }, + { + "name": "PYO_AGENT_SELF_UPDATE", + "value": "true" + }, + { + "name": "PYO_ALLOW_PRIVATE_NETWORKS", + "value": "true" + }, + { + "name": "PYO_FLOWS_IMAGE", + "value": "ghcr.io/upsetdev/pyo/flows:0.5.4@sha256:aa9293228599aa952bb4ab315865787f8071f8f2c23c39fa3cb1bcc0edfd04dc" + }, + { + "name": "PYO_WAF_IMAGE", + "value": "ghcr.io/upsetdev/pyo/waf:0.5.4@sha256:5a00c51d2de1bdb321703d9227ebd244606f24d07a6a373b2b52e3f06c625f5d" + }, + { + "name": "PYO_GEOIP_IMAGE", + "value": "ghcr.io/upsetdev/pyo/geoip:0.5.4@sha256:6d5b45b2b6bd0d2da9676e7ad8ea3cd66d330275cdb329c153a8c13bb88abb40" + }, + { + "name": "PYO_DB_CONTROLLER_IMAGE", + "value": "ghcr.io/upsetdev/pyo/db-controller:0.5.4@sha256:3903974417d92f47fb0841d510e6f8d05343733327bd16fc826dcbbff95c750f" + }, + { + "name": "PYO_KV_IMAGE", + "value": "ghcr.io/upsetdev/pyo/kv:0.5.4@sha256:af56ee5e3f6e5f55fe642267c596381816de7e60455dc1adbf74262b386d4009" + }, + { + "name": "PYO_STATIC_IMAGE", + "value": "ghcr.io/upsetdev/pyo/static:0.5.4@sha256:407bf277d59a158e1e4c7e8e31bcfbe4aef28b3ef1f79c6963117d3850511d4a" + }, + { + "name": "PYO_POSTGRES_IMAGE_16", + "value": "ghcr.io/upsetdev/pyo/postgres:16-0.5.4@sha256:54cd52417c189df7b035754d75a749c3cf05ba903b7c8ff957980d22079606dc" + }, + { + "name": "PYO_POSTGRES_IMAGE_17", + "value": "ghcr.io/upsetdev/pyo/postgres:17-0.5.4@sha256:e55fb95cf080da188e821d5eacfcdf626f9a7e88c38fdc3b26b5e9dc4f0bfd76" + }, + { + "name": "PYO_POSTGRES_IMAGE_18", + "value": "ghcr.io/upsetdev/pyo/postgres:18-0.5.4@sha256:7fff3b644b3c496ae3d467791166efe3000da1f8dae8d2aa3d523736db43612c" + }, + { + "name": "PYO_MYSQL_OPERATOR_IMAGE", + "value": "ghcr.io/upsetdev/pyo/mysql-operator:0.5.4@sha256:84361c6e7990055481cd6032ec4b377eded64f82fc58d31043159364793a99ad" + }, + { + "name": "PYO_MYSQL_BACKUP_IMAGE", + "value": "ghcr.io/upsetdev/pyo/mysql-backup:0.5.4@sha256:70d2d853d357bd8d94ccec7fa8834cfb539c9b1fa5a56594e9de3017b27c23e5" + }, + { + "name": "RUST_LOG", + "value": "pyo_api=info,tower_http=warn" + }, + { + "name": "PYO_ROLE", + "value": "web" + }, + { + "name": "POD_IP", + "valueFrom": { + "fieldRef": { + "fieldPath": "status.podIP" + } + } + }, + { + "name": "CLICKHOUSE_URL", + "value": "http://pyo-clickhouse.pyo-system.svc:8123" + }, + { + "name": "CLICKHOUSE_USER", + "value": "pyo" + }, + { + "name": "CLICKHOUSE_PASSWORD", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-clickhouse", + "key": "password" + } + } + }, + { + "name": "PYO_GEOIP_DB", + "value": "/geoip/GeoLite2-City.mmdb" + }, + { + "name": "MAXMIND_LICENSE_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-geoip", + "key": "maxmind-license-key", + "optional": true + } + } + }, + { + "name": "PYO_BUILDER_IMAGE", + "value": "ghcr.io/upsetdev/pyo/builder:0.5.4@sha256:774500c22a953db40c670822691e6209095531a70d2330c33a8313e4000deec0" + }, + { + "name": "PYO_REGISTRY_PULL", + "value": "127.0.0.1:5005" + }, + { + "name": "PYO_REGISTRY", + "value": "pyo-registry.pyo-system.svc.cluster.local:5000" + }, + { + "name": "PYO_BOOTSTRAP_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-bootstrap", + "key": "key", + "optional": true + } + } + }, + { + "name": "PYO_SECRET_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-secrets", + "key": "secret-key" + } + } + }, + { + "name": "PYO_ADMIN_PASSWORD", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-admin", + "key": "password", + "optional": true + } + } + }, + { + "name": "PYO_TELEMETRY", + "valueFrom": { + "configMapKeyRef": { + "name": "pyo-install", + "key": "telemetry", + "optional": true + } + } + }, + { + "name": "PYO_BACKUP_STORE_URL", + "value": "http://pyo-backup-store.pyo-system.svc.cluster.local:3900" + }, + { + "name": "PYO_BACKUP_STORE_ADMIN_URL", + "value": "http://pyo-backup-store.pyo-system.svc.cluster.local:3903" + }, + { + "name": "PYO_BACKUP_STORE_ADMIN_TOKEN", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-backup-store", + "key": "admin-token", + "optional": true + } + } + }, + { + "name": "PYO_BACKUP_STORE_ACCESS_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-backup-store", + "key": "access-key", + "optional": true + } + } + }, + { + "name": "PYO_BACKUP_STORE_SECRET_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-backup-store", + "key": "secret-key", + "optional": true + } + } + } + ], + "readinessProbe": { + "httpGet": { + "path": "/readyz", + "port": "http" + }, + "periodSeconds": 3, + "failureThreshold": 1 + }, + "lifecycle": { + "preStop": { + "sleep": { + "seconds": 5 + } + } + }, + "livenessProbe": { + "httpGet": { + "path": "/healthz", + "port": "http" + }, + "initialDelaySeconds": 20, + "periodSeconds": 20 + }, + "securityContext": { + "runAsNonRoot": true, + "allowPrivilegeEscalation": false, + "readOnlyRootFilesystem": true, + "capabilities": { + "drop": [ + "ALL" + ] + } + }, + "volumeMounts": [ + { + "name": "geoip", + "mountPath": "/geoip" + } + ], + "resources": { + "requests": { + "cpu": "20m", + "memory": "64Mi" + }, + "limits": { + "memory": "256Mi" + } + } + } + ], + "volumes": [ + { + "name": "geoip", + "emptyDir": { + "sizeLimit": "256Mi" + } + } + ] + } + } + } + }, + { + "apiVersion": "policy/v1", + "kind": "PodDisruptionBudget", + "metadata": { + "name": "pyo", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "maxUnavailable": 1, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo" + } + } + } + }, + { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": { + "name": "pyo-worker", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-worker", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "replicas": 1, + "strategy": { + "type": "RollingUpdate", + "rollingUpdate": { + "maxUnavailable": 0, + "maxSurge": 1 + } + }, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-worker" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "pyo-worker", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "terminationGracePeriodSeconds": 45, + "containers": [ + { + "name": "worker", + "image": "ghcr.io/upsetdev/pyo/pyo:0.5.4@sha256:b8778bdec53339b0f23d94520e2fe743728a519806d0f50e24cbc0c3afb60f8a", + "ports": [ + { + "name": "http", + "containerPort": 8000 + } + ], + "env": [ + { + "name": "PYO_ROLE", + "value": "worker" + }, + { + "name": "DATABASE_URL", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-postgres", + "key": "url" + } + } + }, + { + "name": "PYO_AGENT_API_URL", + "value": "http://pyo.pyo-system.svc:8000" + }, + { + "name": "PYO_AGENT_IMAGE", + "value": "ghcr.io/upsetdev/pyo/agent:0.5.4@sha256:75947f00afdb21e3526cffa0c70f727b1d7b30bcc19a2fcd7b666d14ae4e48ba" + }, + { + "name": "PYO_AGENT_SELF_UPDATE", + "value": "true" + }, + { + "name": "PYO_ALLOW_PRIVATE_NETWORKS", + "value": "true" + }, + { + "name": "PYO_FLOWS_IMAGE", + "value": "ghcr.io/upsetdev/pyo/flows:0.5.4@sha256:aa9293228599aa952bb4ab315865787f8071f8f2c23c39fa3cb1bcc0edfd04dc" + }, + { + "name": "PYO_WAF_IMAGE", + "value": "ghcr.io/upsetdev/pyo/waf:0.5.4@sha256:5a00c51d2de1bdb321703d9227ebd244606f24d07a6a373b2b52e3f06c625f5d" + }, + { + "name": "PYO_GEOIP_IMAGE", + "value": "ghcr.io/upsetdev/pyo/geoip:0.5.4@sha256:6d5b45b2b6bd0d2da9676e7ad8ea3cd66d330275cdb329c153a8c13bb88abb40" + }, + { + "name": "PYO_DB_CONTROLLER_IMAGE", + "value": "ghcr.io/upsetdev/pyo/db-controller:0.5.4@sha256:3903974417d92f47fb0841d510e6f8d05343733327bd16fc826dcbbff95c750f" + }, + { + "name": "PYO_KV_IMAGE", + "value": "ghcr.io/upsetdev/pyo/kv:0.5.4@sha256:af56ee5e3f6e5f55fe642267c596381816de7e60455dc1adbf74262b386d4009" + }, + { + "name": "PYO_STATIC_IMAGE", + "value": "ghcr.io/upsetdev/pyo/static:0.5.4@sha256:407bf277d59a158e1e4c7e8e31bcfbe4aef28b3ef1f79c6963117d3850511d4a" + }, + { + "name": "PYO_POSTGRES_IMAGE_16", + "value": "ghcr.io/upsetdev/pyo/postgres:16-0.5.4@sha256:54cd52417c189df7b035754d75a749c3cf05ba903b7c8ff957980d22079606dc" + }, + { + "name": "PYO_POSTGRES_IMAGE_17", + "value": "ghcr.io/upsetdev/pyo/postgres:17-0.5.4@sha256:e55fb95cf080da188e821d5eacfcdf626f9a7e88c38fdc3b26b5e9dc4f0bfd76" + }, + { + "name": "PYO_POSTGRES_IMAGE_18", + "value": "ghcr.io/upsetdev/pyo/postgres:18-0.5.4@sha256:7fff3b644b3c496ae3d467791166efe3000da1f8dae8d2aa3d523736db43612c" + }, + { + "name": "PYO_MYSQL_OPERATOR_IMAGE", + "value": "ghcr.io/upsetdev/pyo/mysql-operator:0.5.4@sha256:84361c6e7990055481cd6032ec4b377eded64f82fc58d31043159364793a99ad" + }, + { + "name": "PYO_MYSQL_BACKUP_IMAGE", + "value": "ghcr.io/upsetdev/pyo/mysql-backup:0.5.4@sha256:70d2d853d357bd8d94ccec7fa8834cfb539c9b1fa5a56594e9de3017b27c23e5" + }, + { + "name": "PYO_SANDBOX_BASE_REF", + "value": "" + }, + { + "name": "PYO_SANDBOX_DESKTOP_REF", + "value": "" + }, + { + "name": "RUST_LOG", + "value": "pyo_api=info" + }, + { + "name": "CLICKHOUSE_URL", + "value": "http://pyo-clickhouse.pyo-system.svc:8123" + }, + { + "name": "CLICKHOUSE_USER", + "value": "pyo" + }, + { + "name": "CLICKHOUSE_PASSWORD", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-clickhouse", + "key": "password" + } + } + }, + { + "name": "PYO_BUILDER_IMAGE", + "value": "ghcr.io/upsetdev/pyo/builder:0.5.4@sha256:774500c22a953db40c670822691e6209095531a70d2330c33a8313e4000deec0" + }, + { + "name": "PYO_REGISTRY_PULL", + "value": "127.0.0.1:5005" + }, + { + "name": "PYO_REGISTRY", + "value": "pyo-registry.pyo-system.svc.cluster.local:5000" + }, + { + "name": "PYO_BOOTSTRAP_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-bootstrap", + "key": "key", + "optional": true + } + } + }, + { + "name": "PYO_SECRET_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-secrets", + "key": "secret-key" + } + } + }, + { + "name": "PYO_BACKUP_STORE_URL", + "value": "http://pyo-backup-store.pyo-system.svc.cluster.local:3900" + }, + { + "name": "PYO_BACKUP_STORE_ADMIN_URL", + "value": "http://pyo-backup-store.pyo-system.svc.cluster.local:3903" + }, + { + "name": "PYO_BACKUP_STORE_ADMIN_TOKEN", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-backup-store", + "key": "admin-token", + "optional": true + } + } + }, + { + "name": "PYO_BACKUP_STORE_ACCESS_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-backup-store", + "key": "access-key", + "optional": true + } + } + }, + { + "name": "PYO_BACKUP_STORE_SECRET_KEY", + "valueFrom": { + "secretKeyRef": { + "name": "pyo-backup-store", + "key": "secret-key", + "optional": true + } + } + } + ], + "readinessProbe": { + "httpGet": { + "path": "/readyz", + "port": "http" + }, + "periodSeconds": 5 + }, + "livenessProbe": { + "httpGet": { + "path": "/healthz", + "port": "http" + }, + "initialDelaySeconds": 20, + "periodSeconds": 20 + }, + "securityContext": { + "runAsNonRoot": true, + "allowPrivilegeEscalation": false, + "readOnlyRootFilesystem": true, + "capabilities": { + "drop": [ + "ALL" + ] + } + }, + "resources": { + "requests": { + "cpu": "10m", + "memory": "32Mi" + }, + "limits": { + "memory": "512Mi" + } + } + } + ] + } + } + } + }, + { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": { + "name": "pyo-forward", + "namespace": "pyo-system", + "labels": { + "app.kubernetes.io/name": "pyo-forward", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "replicas": 1, + "strategy": { + "type": "Recreate" + }, + "selector": { + "matchLabels": { + "app.kubernetes.io/name": "pyo-forward" + } + }, + "template": { + "metadata": { + "labels": { + "app.kubernetes.io/name": "pyo-forward", + "app.kubernetes.io/part-of": "pyo" + } + }, + "spec": { + "hostNetwork": true, + "dnsPolicy": "ClusterFirstWithHostNet", + "affinity": { + "podAffinity": { + "requiredDuringSchedulingIgnoredDuringExecution": [ + { + "labelSelector": { + "matchLabels": { + "app.kubernetes.io/name": "registry" + } + }, + "topologyKey": "kubernetes.io/hostname" + } + ] + } + }, + "containers": [ + { + "name": "forward", + "image": "ghcr.io/upsetdev/pyo/agent:0.5.4@sha256:75947f00afdb21e3526cffa0c70f727b1d7b30bcc19a2fcd7b666d14ae4e48ba", + "args": [ + "forward", + "8000/local,private,tailnet=pyo.pyo-system.svc.cluster.local:8000", + "5006/tailnet=pyo-registry-door.pyo-system.svc.cluster.local:5006" + ], + "securityContext": { + "runAsNonRoot": true, + "runAsUser": 65532, + "allowPrivilegeEscalation": false, + "readOnlyRootFilesystem": true, + "capabilities": { + "drop": [ + "ALL" + ] + } + }, + "resources": { + "requests": { + "cpu": "5m", + "memory": "8Mi" + }, + "limits": { + "memory": "64Mi" + } + } + } + ] + } + } + } + } + ] + }, + "migrations": [ + "0001_init.sql", + "0002_free_domain_address.sql", + "0003_database_imported_from.sql", + "0004_platform_imports.sql", + "0005_tailnet.sql", + "0006_behind_cdn.sql", + "0007_cloudflare_dns.sql", + "0008_git_connections.sql", + "0009_cloud_servers.sql", + "0010_static_sites.sql", + "0011_sandboxes.sql", + "0012_sandbox_edges.sql", + "0013_sign_in_links.sql", + "0014_cloud_sandbox_servers.sql", + "0015_sandbox_base_template.sql", + "0016_sandbox_lifetimes.sql", + "0017_sandbox_names.sql", + "0018_tailnet_sandboxes.sql", + "0019_alerts.sql", + "0020_agent_certificates.sql", + "0021_agent_keys.sql", + "0022_row_security.sql", + "0023_component_keys.sql", + "0024_connect_tokens.sql", + "0025_agent_updates.sql", + "0026_build_log_cleanup.sql", + "0027_tailscale_in_clusters.sql", + "0028_previews.sql", + "0029_cli_login_requests.sql", + "0030_source_uploads.sql", + "0031_team_analytics_months.sql", + "0032_row_security_rest.sql", + "0033_rate_limit_lockout.sql", + "0034_team_security.sql", + "0035_log_follows.sql", + "0036_relay_tickets.sql", + "0037_commands_held.sql", + "0038_database_log_follows.sql" + ], + "minFrom": null, + "manualOnly": false, + "beforeYouUpdate": [], + "agentAccess": "5db0cd47517256de", + "sandbox": { + "x86_64": "784b397993a0113e8877cf93fd7a1b71540ad8e1b6a05bbfddbf9ea6b089f312", + "aarch64": "4fc6124dcb9e5134ec5627fb10b4888ecce2210a69a148b75cdaebdfd9bd5123" + }, + "sandboxGvisor": { + "x86_64": "1f1e66eec9b9c54a8e34dbcdd3ffa8c3e5007893266fa823e11c45bd7c0c3b73", + "aarch64": "e5d6a239b6f0c3f708647c07459ddde22a97c14c2fe77358abee0f55c27aa548" + }, + "scripts": { + "install.sh": "e3139e037f3e903db91c15e8695ad1cf72a9228d0751dd81ea7446ae3adecb55", + "cli.sh": "481ef4bcedcbc637b567dd8634b70de72ddafe87e1bb6e82f017477bcb0e9fc0", + "connect.sh": "1ea825f2981ed32c39f578faebc0957ab1a780ceb4131b5517ec8d24b6a8068b", + "join.sh": "83d94e47cdba43bd7aed1d755c5a6c3cb6506376d4773eb847d9578327b55ff4", + "sandbox.sh": "0d947ac6d481e022d7120de60dba5419ec8c2552b1802fb1846bc040e29bdc37" + } +} diff --git a/crates/pyo-sigstore/assets/testdata/release-0.5.4/release.json.sigstore.json b/crates/pyo-sigstore/assets/testdata/release-0.5.4/release.json.sigstore.json new file mode 100644 index 00000000..9a3b3a19 --- /dev/null +++ b/crates/pyo-sigstore/assets/testdata/release-0.5.4/release.json.sigstore.json @@ -0,0 +1 @@ +{"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json", "verificationMaterial":{"certificate":{"rawBytes":"MIIGuDCCBj+gAwIBAgIUYrEaNkHf2kojAa9COdbl+L07tH4wCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYxMTIxMjA1MDIwWhcNMjYxMTIxMjEwMDIwWjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEA94jW08M9NmV5AW+GuqRnH7lYcjI88ml/Y2SxTwFjZ9+NbrNe3p/4XjiARX8Qxg4SRJMNY4mtzuA63jeuNgQO6OCBV4wggVaMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAfBgNVHSMEGDAWgBTf0+nPViQRlvmo2OkoVaLGLhhkPzBcBgNVHREBAf8EUjBQhk5odHRwczovL2dpdGh1Yi5jb20vdXBzZXRkZXYvcHlvLy5naXRodWIvd29ya2Zsb3dzL3JlbGVhc2UueW1sQHJlZnMvdGFncy92MC41LjQwOQYKKwYBBAGDvzABAQQraHR0cHM6Ly90b2tlbi5hY3Rpb25zLmdpdGh1YnVzZXJjb250ZW50LmNvbTASBgorBgEEAYO/MAECBARwdXNoMDYGCisGAQQBg78wAQMEKDIwODNiNjAyMGVmYzY5YzEzOTI0YTk4Y2RjYWI1MDBjZDQ3Mzc2OGUwFQYKKwYBBAGDvzABBAQHUmVsZWFzZTAaBgorBgEEAYO/MAEFBAx1cHNldGRldi9weW8wHgYKKwYBBAGDvzABBgQQcmVmcy90YWdzL3YwLjUuNDA7BgorBgEEAYO/MAEIBC0MK2h0dHBzOi8vdG9rZW4uYWN0aW9ucy5naXRodWJ1c2VyY29udGVudC5jb20wXgYKKwYBBAGDvzABCQRQDE5odHRwczovL2dpdGh1Yi5jb20vdXBzZXRkZXYvcHlvLy5naXRodWIvd29ya2Zsb3dzL3JlbGVhc2UueW1sQHJlZnMvdGFncy92MC41LjQwOAYKKwYBBAGDvzABCgQqDCgyMDgzYjYwMjBlZmM2OWMxMzkyNGE5OGNkY2FiNTAwY2Q0NzM3NjhlMB0GCisGAQQBg78wAQsEDwwNZ2l0aHViLWhvc3RlZDAvBgorBgEEAYO/MAEMBCEMH2h0dHBzOi8vZ2l0aHViLmNvbS91cHNldGRldi9weW8wOAYKKwYBBAGDvzABDQQqDCgyMDgzYjYwMjBlZmM2OWMxMzkyNGE5OGNkY2FiNTAwY2Q0NzM3NjhlMCAGCisGAQQBg78wAQ4EEgwQcmVmcy90YWdzL3YwLjUuNDAaBgorBgEEAYO/MAEPBAwMCjE0NTU4MjQ4NjMwKwYKKwYBBAGDvzABEAQdDBtodHRwczovL2dpdGh1Yi5jb20vdXBzZXRkZXYwGAYKKwYBBAGDvzABEQQKDAg1OTc0NjY4NjBeBgorBgEEAYO/MAESBFAMTmh0dHBzOi8vZ2l0aHViLmNvbS91cHNldGRldi9weW8vLmdpdGh1Yi93b3JrZmxvd3MvcmVsZWFzZS55bWxAcmVmcy90YWdzL3YwLjUuNDA4BgorBgEEAYO/MAETBCoMKDIwODNiNjAyMGVmYzY5YzEzOTI0YTk4Y2RjYWI1MDBjZDQ3Mzc2OGUwFAYKKwYBBAGDvzABFAQGDARwdXNoMFMGCisGAQQBg78wARUERQxDaHR0cHM6Ly9naXRodWIuY29tL3Vwc2V0ZGV2L3B5by9hY3Rpb25zL3J1bnMvNDQ5NDU3ODM3NzAvYXR0ZW1wdHMvMTAWBgorBgEEAYO/MAEWBAgMBnB1YmxpYzBKBgorBgEEAYO/MAEYBDwMOnJlcG86dXBzZXRkZXZANTk3NDY2ODYvcHlvQDE0NTU4MjQ4NjM6cmVmOnJlZnMvdGFncy92MC41LjQwgYoGCisGAQQB1nkCBAIEfAR6AHgAdgDdPTBqxscRMmMZHhyZZzcCokpeuN48rf+HinKALynujgAAAaH/388EAAAEAwBHMEUCIBGOa3CavKV8Jzoq5BBkbJgDqXGSqDL+et+DKYnZ2Ak6AiEA9OpwWYzoKFIhXPlAEZC/0aenJCpiGYDAEiUIFJWr+7UwCgYIKoZIzj0EAwMDZwAwZAIwFQXbkAy178D/+anlZJDw0St59BYjsKTYbSI0XV4tv3dxCSGep9b25VeS4tFwb3FNAjAt+ibfsQYOTqbk55mrF9ZkNKgvcBOqqUwdAhnUlkUvO6fNi52PZCBcry5oQLRxT4w="}, "tlogEntries":[{"logIndex":"4034077355", "logId":{"keyId":"wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="}, "kindVersion":{"kind":"hashedrekord", "version":"0.0.1"}, "integratedTime":"1795294220", "inclusionPromise":{"signedEntryTimestamp":"MEUCIQChTxhfQAStKMSGn3LX7DquP6wzcxhlJfnf1R1EgvBZhgIgVuo3Gkoa0BmH5i89FC/t6cRC+NQivj+8FgbtvEdqokA="}, "inclusionProof":{"logIndex":"3912173093", "rootHash":"E40tOUeR+CVCM6K/bI2BGpCZs30hFeCQMg5JUr/pfBk=", "treeSize":"3912173095", "hashes":["4q9XjzBehs8m76qkxDydGGYAe/IzYAbRi9Jfb84ShIs=", "wWGcA0wUM00o29TnUg+vP/lMGT3Jc7erhLBC+fCeCto=", "0gHK32NPytxz3kl480voUS/KcUMj/d1bvhph/2uolN4=", "4H/0tT1aiM2uhmeUfVSr4d+N+CxPJVEkEpN4L4MCbgA=", "k5IqD/t0BJhzSW5kQQRNzMtbH87tDeKvg06GCD1l4IU=", "QgMlTZfftcdj3z9YRnJYEBD1oGBgEj86OEROsVCzJGs=", "PKi4fGF2ffLdRwhHfdf5a8Islc+0GAov4XbE2KFKCQQ=", "bu2S8zJLo7BGneWsH2h0s5MwabAMHH888ILnTqIFMWY=", "pUg20PA5wfzCU073zDIhSpn6pRC8VJ13Hw2Igk0vTGw=", "S+2VN5pncnfZvLoNKxKxSvQm/kCyEI/HLwm+qZhBY6o=", "A4XZMEOQoxhP6Rhr7z0Glq48q0wDILbA07yFV0q1Bh8=", "U/lsPUDNZFm/rZys64nJMBrkghJQ1CSVJUoUy3qgGGE=", "XYkf+Vk9hVBebwq5KRpgAFIE2Jk4aAgO1jFr22tSd4k=", "k0+Z1T6dI0Tgluh54oO/hnxtuoW22MqFIjVTPYeUJGU=", "1DaDKzrCNNBhmSdY5vFjz+NpAmxmYfYEgBCdPLrMP1A=", "xH/DCseLHr9eKoYT8qsORZK7zVdEGYWHuVtsVrD95wY="], "checkpoint":{"envelope":"rekor.sigstore.dev - 1193050959916656506\n3912173095\nE40tOUeR+CVCM6K/bI2BGpCZs30hFeCQMg5JUr/pfBk=\n\n— rekor.sigstore.dev wNI9ajBGAiEAwQmXnWBZRH1YJSvEvbI/rENi4XghDpFiY0DfZ0TW3d0CIQCUvFRD/Jp18LfEgdvOm+8+9EvH7Z22/RtUbPyGIvY+Ag==\n"}}, "canonicalizedBody":"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiI5MmZjNGIyYjliYWI3MzM4YmE3NTk0YzJhMmEyZTc4MWUzZjY2OTVjNjA5ZGZiMmQ5YTA0NzgzMjUwYTExNjVkIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FVUNJUUNUWFhXNFgzSkx2ZTJoeDV3RXhDNldrcUEzaVAxYnpDNUVqLzhBcW5UVHVRSWdYOE9sODNBYUxUTHl3dDBYY3lMbWtuQ1Z6ZlY1Q2pWKzdXVFVXUzhTemhRPSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVZDFSRU5EUW1vclowRjNTVUpCWjBsVldYSkZZVTVyU0dZeWEyOXFRV0U1UTA5a1ltd3JUREEzZEVnMGQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVWpSM1NFRlpSRlpSVVVSRmVGWjZZVmRrZW1SSE9YbGFVekZ3WW01U2JBcGpiVEZzV2tkc2FHUkhWWGRJYUdOT1RXcFplRTFVU1hoTmFrRXhUVVJKZDFkb1kwNU5hbGw0VFZSSmVFMXFSWGROUkVsM1YycEJRVTFHYTNkRmQxbElDa3R2V2tsNmFqQkRRVkZaU1V0dldrbDZhakJFUVZGalJGRm5RVVZCT1RScVZ6QTRUVGxPYlZZMVFWY3JSM1Z4VW01SU4yeFpZMnBKT0RodGJDOVpNbE1LZUZSM1JtcGFPU3RPWW5KT1pUTndMelJZYW1sQlVsZzRVWGhuTkZOU1NrMU9XVFJ0ZEhwMVFUWXphbVYxVG1kUlR6WlBRMEpXTkhkbloxWmhUVUUwUndwQk1WVmtSSGRGUWk5M1VVVkJkMGxJWjBSQlZFSm5UbFpJVTFWRlJFUkJTMEpuWjNKQ1owVkdRbEZqUkVGNlFXWkNaMDVXU0ZOTlJVZEVRVmRuUWxSbUNqQXJibEJXYVZGU2JIWnRiekpQYTI5V1lVeEhUR2hvYTFCNlFtTkNaMDVXU0ZKRlFrRm1PRVZWYWtKUmFHczFiMlJJVW5kamVtOTJUREprY0dSSGFERUtXV2sxYW1JeU1IWmtXRUo2V2xoU2ExcFlXWFpqU0d4MlRIazFibUZZVW05a1YwbDJaREk1ZVdFeVduTmlNMlI2VEROS2JHSkhWbWhqTWxWMVpWY3hjd3BSU0Vwc1dtNU5kbVJIUm01amVUa3lUVU0wTVV4cVVYZFBVVmxMUzNkWlFrSkJSMFIyZWtGQ1FWRlJjbUZJVWpCalNFMDJUSGs1TUdJeWRHeGlhVFZvQ2xrelVuQmlNalY2VEcxa2NHUkhhREZaYmxaNldsaEthbUl5TlRCYVZ6VXdURzFPZG1KVVFWTkNaMjl5UW1kRlJVRlpUeTlOUVVWRFFrRlNkMlJZVG04S1RVUlpSME5wYzBkQlVWRkNaemM0ZDBGUlRVVkxSRWwzVDBST2FVNXFRWGxOUjFadFdYcFpOVmw2UlhwUFZFa3dXVlJyTkZreVVtcFpWMGt4VFVSQ2FncGFSRkV6VFhwak1rOUhWWGRHVVZsTFMzZFpRa0pCUjBSMmVrRkNRa0ZSU0ZWdFZuTmFWMFo2V2xSQllVSm5iM0pDWjBWRlFWbFBMMDFCUlVaQ1FYZ3hDbU5JVG14a1IxSnNaR2s1ZDJWWE9IZElaMWxMUzNkWlFrSkJSMFIyZWtGQ1FtZFJVV050Vm0xamVUa3dXVmRrZWt3eldYZE1hbFYxVGtSQk4wSm5iM0lLUW1kRlJVRlpUeTlOUVVWSlFrTXdUVXN5YURCa1NFSjZUMms0ZG1SSE9YSmFWelIxV1ZkT01HRlhPWFZqZVRWdVlWaFNiMlJYU2pGak1sWjVXVEk1ZFFwa1IxWjFaRU0xYW1JeU1IZFlaMWxMUzNkWlFrSkJSMFIyZWtGQ1ExRlNVVVJGTlc5a1NGSjNZM3B2ZGt3eVpIQmtSMmd4V1drMWFtSXlNSFprV0VKNkNscFlVbXRhV0ZsMlkwaHNka3g1Tlc1aFdGSnZaRmRKZG1ReU9YbGhNbHB6WWpOa2Vrd3pTbXhpUjFab1l6SlZkV1ZYTVhOUlNFcHNXbTVOZG1SSFJtNEtZM2s1TWsxRE5ERk1hbEYzVDBGWlMwdDNXVUpDUVVkRWRucEJRa05uVVhGRVEyZDVUVVJuZWxscVdYZE5ha0pzV20xTk1rOVhUWGhOZW10NVRrZEZOUXBQUjA1cldUSkdhVTVVUVhkWk1sRXdUbnBOTTA1cWFHeE5RakJIUTJselIwRlJVVUpuTnpoM1FWRnpSVVIzZDA1YU1td3dZVWhXYVV4WGFIWmpNMUpzQ2xwRVFYWkNaMjl5UW1kRlJVRlpUeTlOUVVWTlFrTkZUVWd5YURCa1NFSjZUMms0ZGxveWJEQmhTRlpwVEcxT2RtSlRPVEZqU0U1c1pFZFNiR1JwT1hjS1pWYzRkMDlCV1V0TGQxbENRa0ZIUkhaNlFVSkVVVkZ4UkVObmVVMUVaM3BaYWxsM1RXcENiRnB0VFRKUFYwMTRUWHByZVU1SFJUVlBSMDVyV1RKR2FRcE9WRUYzV1RKUk1FNTZUVE5PYW1oc1RVTkJSME5wYzBkQlVWRkNaemM0ZDBGUk5FVkZaM2RSWTIxV2JXTjVPVEJaVjJSNlRETlpkMHhxVlhWT1JFRmhDa0puYjNKQ1owVkZRVmxQTDAxQlJWQkNRWGROUTJwRk1FNVVWVFJOYWxFMFRtcE5kMHQzV1V0TGQxbENRa0ZIUkhaNlFVSkZRVkZrUkVKMGIyUklVbmNLWTNwdmRrd3laSEJrUjJneFdXazFhbUl5TUhaa1dFSjZXbGhTYTFwWVdYZEhRVmxMUzNkWlFrSkJSMFIyZWtGQ1JWRlJTMFJCWnpGUFZHTXdUbXBaTkFwT2FrSmxRbWR2Y2tKblJVVkJXVTh2VFVGRlUwSkdRVTFVYldnd1pFaENlazlwT0haYU1td3dZVWhXYVV4dFRuWmlVemt4WTBoT2JHUkhVbXhrYVRsM0NtVlhPSFpNYldSd1pFZG9NVmxwT1ROaU0wcHlXbTE0ZG1RelRYWmpiVlp6V2xkR2VscFROVFZpVjNoQlkyMVdiV041T1RCWlYyUjZURE5aZDB4cVZYVUtUa1JCTkVKbmIzSkNaMFZGUVZsUEwwMUJSVlJDUTI5TlMwUkpkMDlFVG1sT2FrRjVUVWRXYlZsNldUVlpla1Y2VDFSSk1GbFVhelJaTWxKcVdWZEpNUXBOUkVKcVdrUlJNMDE2WXpKUFIxVjNSa0ZaUzB0M1dVSkNRVWRFZG5wQlFrWkJVVWRFUVZKM1pGaE9iMDFHVFVkRGFYTkhRVkZSUW1jM09IZEJVbFZGQ2xKUmVFUmhTRkl3WTBoTk5reDVPVzVoV0ZKdlpGZEpkVmt5T1hSTU0xWjNZekpXTUZwSFZqSk1NMEkxWW5rNWFGa3pVbkJpTWpWNlRETktNV0p1VFhZS1RrUlJOVTVFVlROUFJFMHpUbnBCZGxsWVVqQmFWekYzWkVoTmRrMVVRVmRDWjI5eVFtZEZSVUZaVHk5TlFVVlhRa0ZuVFVKdVFqRlpiWGh3V1hwQ1N3cENaMjl5UW1kRlJVRlpUeTlOUVVWWlFrUjNUVTl1U214alJ6ZzJaRmhDZWxwWVVtdGFXRnBCVGxSck0wNUVXVEpQUkZsMlkwaHNkbEZFUlRCT1ZGVTBDazFxVVRST2FrMDJZMjFXYlU5dVNteGFiazEyWkVkR2JtTjVPVEpOUXpReFRHcFJkMmRaYjBkRGFYTkhRVkZSUWpGdWEwTkNRVWxGWmtGU05rRklaMEVLWkdkRVpGQlVRbkY0YzJOU1RXMU5Xa2hvZVZwYWVtTkRiMnR3WlhWT05EaHlaaXRJYVc1TFFVeDViblZxWjBGQlFXRklMek00T0VWQlFVRkZRWGRDU0FwTlJWVkRTVUpIVDJFelEyRjJTMVk0U25wdmNUVkNRbXRpU21kRWNWaEhVM0ZFVEN0bGRDdEVTMWx1V2pKQmF6WkJhVVZCT1U5d2QxZFplbTlMUmtsb0NsaFFiRUZGV2tNdk1HRmxia3BEY0dsSFdVUkJSV2xWU1VaS1YzSXJOMVYzUTJkWlNVdHZXa2w2YWpCRlFYZE5SRnAzUVhkYVFVbDNSbEZZWW10QmVURUtOemhFTHl0aGJteGFTa1IzTUZOME5UbENXV3B6UzFSWllsTkpNRmhXTkhSMk0yUjRRMU5IWlhBNVlqSTFWbVZUTkhSR2QySXpSazVCYWtGMEsybGlaZ3B6VVZsUFZIRmlhelUxYlhKR09WcHJUa3RuZG1OQ1QzRnhWWGRrUVdodVZXeHJWWFpQTm1aT2FUVXlVRnBEUW1OeWVUVnZVVXhTZUZRMGR6MEtMUzB0TFMxRlRrUWdRMFZTVkVsR1NVTkJWRVV0TFMwdExRbz0ifX19fQ=="}], "timestampVerificationData":{"rfc3161Timestamps":[{"signedTimestamp":"MIICyjADAgEAMIICwQYJKoZIhvcNAQcCoIICsjCCAq4CAQMxDTALBglghkgBZQMEAgEwgbcGCyqGSIb3DQEJEAEEoIGnBIGkMIGhAgEBBgkrBgEEAYO/MAIwMTANBglghkgBZQMEAgEFAAQgwyVucsh32Ge7l5zAqi2x4VSIlPGYBC5iH/my9ydnkngCFHi0AWsE2Jlf/AhezhpHMGLglEueGA8yMDI2MTEyMTIwNTAyMFowAwIBAaAypDAwLjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MRUwEwYDVQQDEwxzaWdzdG9yZS10c2GgADGCAdwwggHYAgEBMFEwOTEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MSAwHgYDVQQDExdzaWdzdG9yZS10c2Etc2VsZnNpZ25lZAIUOhNULwyQYe68wUMvy4qOiyojiwwwCwYJYIZIAWUDBAIBoIH8MBoGCSqGSIb3DQEJAzENBgsqhkiG9w0BCRABBDAcBgkqhkiG9w0BCQUxDxcNMjYxMTIxMjA1MDIwWjAvBgkqhkiG9w0BCQQxIgQgexYTD9fb3cSliOKO9dDt4d/8wDP7+JomxVV002g9ZM4wgY4GCyqGSIb3DQEJEAIvMX8wfTB7MHkEIIX5J7wHq2LKw7RDVsEO/IGyxog/2nq55thw2dE6zQW3MFUwPaQ7MDkxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEgMB4GA1UEAxMXc2lnc3RvcmUtdHNhLXNlbGZzaWduZWQCFDoTVC8MkGHuvMFDL8uKjosqI4sMMAoGCCqGSM49BAMCBGgwZgIxAKLrcHwUf6bF77TUAHo085KNcnzxZfrNjO1kb2cVwnLsy+fy3jpgSFinPyHfshdDDAIxAPsVT9rrVneIR0CrgdMk9lTPUNGhlJHfJ66QPuvrZU7+OSqrOcE9VfEqDu89y/ji9Q=="}]}}, "messageSignature":{"messageDigest":{"algorithm":"SHA2_256", "digest":"kvxLK5urczi6dZTCoqLngeP2aVxgnfstmgR4MlChFl0="}, "signature":"MEUCIQCTXXW4X3JLve2hx5wExC6WkqA3iP1bzC5Ej/8AqnTTuQIgX8Ol83AaLTLywt0XcyLmknCVzfV5CjV+7WTUWS8SzhQ="}} \ No newline at end of file diff --git a/crates/pyo-api/src/sigstore.rs b/crates/pyo-sigstore/src/lib.rs similarity index 73% rename from crates/pyo-api/src/sigstore.rs rename to crates/pyo-sigstore/src/lib.rs index 9179d545..b9a8b3c5 100644 --- a/crates/pyo-api/src/sigstore.rs +++ b/crates/pyo-sigstore/src/lib.rs @@ -1,9 +1,12 @@ //! Checks a Sigstore bundle (`cosign sign-blob --bundle`, keyless) for a //! file: what the release workflow makes for release.json, so the -//! dashboard's updates use only a release Pyo's own workflow signed. +//! dashboard's updates (pyo-api) and the verifier on a customer's server +//! (pyo-verify) use only a release Pyo's own workflow signed. +//! +//! The trust root is compiled in. Nothing here takes another one. //! //! The trust is Sigstore's public instance, as of its trusted root -//! (assets/sigstore/): Fulcio's root and intermediate (valid to 2031) and +//! (assets/): Fulcio's root and intermediate (valid to 2031) and //! Rekor v1's key. The release workflow signs with Rekor v1 //! (.github/release-signing-config.json), whose signed entry timestamp //! (SET) this reads; checking is offline. @@ -20,16 +23,19 @@ //! - the signature is the certificate key's, over the file. use anyhow::{Context, anyhow, bail, ensure}; +use aws_lc_rs::signature::{ + ECDSA_P256_SHA256_ASN1, ECDSA_P256_SHA384_ASN1, ECDSA_P384_SHA256_ASN1, ECDSA_P384_SHA384_ASN1, + UnparsedPublicKey, +}; use base64::Engine; -use rustls::pki_types::{AlgorithmIdentifier, alg_id}; use serde_json::Value; use sha2::{Digest, Sha256}; use x509_parser::{certificate::X509Certificate, prelude::FromDer}; -const FULCIO_INTERMEDIATE: &[u8] = include_bytes!("../assets/sigstore/fulcio-intermediate.der"); -const FULCIO_ROOT: &[u8] = include_bytes!("../assets/sigstore/fulcio-root.der"); +const FULCIO_INTERMEDIATE: &[u8] = include_bytes!("../assets/fulcio-intermediate.der"); +const FULCIO_ROOT: &[u8] = include_bytes!("../assets/fulcio-root.der"); /// Rekor v1's public key (SPKI, ECDSA P-256). -const REKOR_KEY: &[u8] = include_bytes!("../assets/sigstore/rekor.der"); +const REKOR_KEY: &[u8] = include_bytes!("../assets/rekor.der"); /// Who must have signed: the certificate's SAN (a URI or email) starting /// with `identity_prefix` (or equal to it when `exact`), issued for a @@ -47,6 +53,31 @@ pub const RELEASE_SIGNER: Signer<'static> = Signer { issuer: "https://token.actions.githubusercontent.com", }; +/// Pyo's release workflow at the tag of one version, and no other: see +/// `release_signer_for`. +pub struct ReleaseSigner { + identity: String, +} + +impl ReleaseSigner { + pub fn signer(&self) -> Signer<'_> { + Signer { + identity_prefix: &self.identity, + exact: true, + issuer: RELEASE_SIGNER.issuer, + } + } +} + +/// Pyo's release workflow at exactly the tag `v`. Unlike +/// `RELEASE_SIGNER` (any version tag), a release signed at one tag doesn't +/// pass as another version's. `version` is the caller's to validate. +pub fn release_signer_for(version: &str) -> ReleaseSigner { + ReleaseSigner { + identity: format!("{}{version}", RELEASE_SIGNER.identity_prefix), + } +} + /// upsetdev/pyo-sandbox-images' release workflow, on main: what signs its /// images.json (sandbox/images.rs). pub const SANDBOX_IMAGES_SIGNER: Signer<'static> = Signer { @@ -67,22 +98,19 @@ fn b64(s: &str) -> anyhow::Result> { Ok(base64::engine::general_purpose::STANDARD.decode(s.trim())?) } -/// An ECDSA signature check by aws-lc (rustls's provider): `key` is the -/// SPKI's point, `curve` its curve's OID, `hash` the signature's. +/// An ECDSA signature check by aws-lc: `key` is the SPKI's point, `curve` +/// its curve's OID, `hash` the signature's. fn ecdsa_ok(curve: &str, hash: &str, key: &[u8], message: &[u8], signature: &[u8]) -> bool { - let want: (AlgorithmIdentifier, AlgorithmIdentifier) = match (curve, hash) { - (OID_EC_P256, "sha256") => (alg_id::ECDSA_P256, alg_id::ECDSA_SHA256), - (OID_EC_P256, "sha384") => (alg_id::ECDSA_P256, alg_id::ECDSA_SHA384), - (OID_EC_P384, "sha256") => (alg_id::ECDSA_P384, alg_id::ECDSA_SHA256), - (OID_EC_P384, "sha384") => (alg_id::ECDSA_P384, alg_id::ECDSA_SHA384), + let alg = match (curve, hash) { + (OID_EC_P256, "sha256") => &ECDSA_P256_SHA256_ASN1, + (OID_EC_P256, "sha384") => &ECDSA_P256_SHA384_ASN1, + (OID_EC_P384, "sha256") => &ECDSA_P384_SHA256_ASN1, + (OID_EC_P384, "sha384") => &ECDSA_P384_SHA384_ASN1, _ => return false, }; - rustls::crypto::aws_lc_rs::default_provider() - .signature_verification_algorithms - .all - .iter() - .find(|a| a.public_key_alg_id() == want.0 && a.signature_alg_id() == want.1) - .is_some_and(|a| a.verify_signature(key, message, signature).is_ok()) + UnparsedPublicKey::new(alg, key) + .verify(message, signature) + .is_ok() } /// A certificate's public key: (curve OID, point). @@ -120,6 +148,20 @@ fn signed_by(cert: &X509Certificate, issuer: &X509Certificate) -> bool { /// Checks `bundle` (a Sigstore bundle, JSON) for `blob`, signed by `signer`. pub fn verify(blob: &[u8], bundle: &str, signer: &Signer) -> anyhow::Result<()> { + verify_logged(blob, bundle, signer).map(|_| ()) +} + +/// What a bundle that checks out also says. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Verified { + /// When Rekor took the signature into its log (seconds since 1970): + /// Rekor's `integratedTime`, which its signed entry timestamp covers. + /// It is the log's word, not the signer's and not a local clock's. + pub integrated_time: i64, +} + +/// `verify`, and when Rekor logged the signature. +pub fn verify_logged(blob: &[u8], bundle: &str, signer: &Signer) -> anyhow::Result { let b: Value = serde_json::from_str(bundle).context("the signature isn't a Sigstore bundle")?; let vm = &b["verificationMaterial"]; let leaf_der = match vm["certificate"]["rawBytes"].as_str() { @@ -297,16 +339,17 @@ pub fn verify(blob: &[u8], bundle: &str, signer: &Signer) -> anyhow::Result<()> if !ecdsa_ok(&curve, "sha256", key, blob, &signature) { bail!("the signature doesn't match the file"); } - Ok(()) + Ok(Verified { + integrated_time: integrated, + }) } #[cfg(test)] mod tests { use super::*; - const BLOB: &[u8] = include_bytes!("../assets/sigstore/testdata/cosign_checksums.txt"); - const BUNDLE: &str = - include_str!("../assets/sigstore/testdata/cosign_checksums.txt.sigstore.json"); + const BLOB: &[u8] = include_bytes!("../assets/testdata/cosign_checksums.txt"); + const BUNDLE: &str = include_str!("../assets/testdata/cosign_checksums.txt.sigstore.json"); /// cosign's own release (v3.1.4), signed keyless by its release account. const COSIGN: Signer<'static> = Signer { identity_prefix: "keyless@projectsigstore.iam.gserviceaccount.com", @@ -319,6 +362,73 @@ mod tests { verify(BLOB, BUNDLE, &COSIGN).unwrap(); } + /// Pyo's release 0.5.4: its release.json and the bundle the release + /// workflow made for it. + const RELEASE: &[u8] = include_bytes!("../assets/testdata/release-0.5.4/release.json"); + const RELEASE_BUNDLE: &str = + include_str!("../assets/testdata/release-0.5.4/release.json.sigstore.json"); + + #[test] + fn a_release_is_signed_at_its_own_tag_only() { + let at = |v: &str| verify_logged(RELEASE, RELEASE_BUNDLE, &release_signer_for(v).signer()); + // Rekor's time comes back with it. + assert_eq!(at("0.5.4").unwrap().integrated_time, 1_795_294_220); + verify(RELEASE, RELEASE_BUNDLE, &RELEASE_SIGNER).unwrap(); + // Exact: not a version this one's tag starts with or continues, and + // not another one. + for other in [ + "0.5", + "0.5.40", + "0.5.4-rc.1", + "0.5.5", + "0.5.3", + "", + "0.5.4 ", + ] { + let e = format!("{:#}", at(other).unwrap_err()); + assert!( + e.contains("signed by https://github.com/upsetdev/pyo/.github/workflows/release.yml@refs/tags/v0.5.4, not"), + "{other:?}: {e}" + ); + } + let s = release_signer_for("0.51.0"); + assert_eq!( + s.signer().identity_prefix, + "https://github.com/upsetdev/pyo/.github/workflows/release.yml@refs/tags/v0.51.0" + ); + assert!(s.signer().exact); + assert_eq!( + s.signer().issuer, + "https://token.actions.githubusercontent.com" + ); + // Another file under that signature. + let mut other = RELEASE.to_vec(); + other[20] ^= 1; + assert!( + verify_logged( + &other, + RELEASE_BUNDLE, + &release_signer_for("0.5.4").signer() + ) + .is_err() + ); + } + + #[test] + fn the_logged_time_is_rekors() { + assert_eq!( + verify_logged(BLOB, BUNDLE, &COSIGN) + .unwrap() + .integrated_time, + serde_json::from_str::(BUNDLE).unwrap()["verificationMaterial"]["tlogEntries"] + [0]["integratedTime"] + .as_str() + .unwrap() + .parse::() + .unwrap() + ); + } + #[test] fn anything_else_doesnt() { let mut other = BLOB.to_vec(); diff --git a/crates/pyo-verify/Cargo.toml b/crates/pyo-verify/Cargo.toml new file mode 100644 index 00000000..b4aaa9c0 --- /dev/null +++ b/crates/pyo-verify/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "pyo-verify" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[[bin]] +name = "pyo-verify" +path = "src/main.rs" + +# A small static binary that runs as root on a customer's server: no async +# runtime, no HTTP or Kubernetes client (it runs curl and k3s kubectl). +# Think twice before adding to this list. +[dependencies] +hex = "0.4.3" +pyo-sigstore = { path = "../pyo-sigstore" } +serde_json = "1.0.154" +sha2 = "0.11.1" diff --git a/crates/pyo-verify/src/config.rs b/crates/pyo-verify/src/config.rs new file mode 100644 index 00000000..b594bdd8 --- /dev/null +++ b/crates/pyo-verify/src/config.rs @@ -0,0 +1,214 @@ +//! `/etc/pyo/verify.conf`: `key=value` lines, written by `install` and +//! edited by the server's owner. +//! +//! ```text +//! url=https://pyo.example.com +//! hold=false +//! channel=stable +//! # source=/srv/pyo-releases +//! ``` +//! +//! A key the verifier does not know, or a value it cannot read, stops it: +//! a typo in `hold` must not read as "go on". There is no key for what the +//! verifier trusts. + +use crate::{ + fetch::{Source, origin}, + sys::{Env, Problem, read_limited}, + version::Channel, +}; + +pub const PATH: &str = "/etc/pyo/verify.conf"; +const DAY: i64 = 24 * 3600; + +#[derive(Debug, Clone, PartialEq)] +pub struct Config { + /// The control plane's public URL, without a trailing slash. + pub url: String, + pub hold: bool, + pub channel: Channel, + pub source: Source, + /// How old a release's signature has to be before it is used. + pub soak_secs: i64, +} + +fn bad(what: &str) -> Problem { + Problem::new(format!( + "{PATH} has a line the verifier cannot use ({what}). Nothing was changed." + )) +} + +pub fn parse(text: &str) -> Result { + let (mut url, mut hold, mut channel, mut source, mut soak_hours) = + (None, false, Channel::Stable, Source::GitHub, None); + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let (key, value) = line.split_once('=').ok_or_else(|| bad("no ="))?; + let key = key.trim().to_ascii_lowercase(); + let value = value.trim(); + let value = value + .strip_prefix('"') + .and_then(|v| v.strip_suffix('"')) + .unwrap_or(value); + match key.as_str() { + "url" => { + let value = value.trim_end_matches('/'); + origin(value).ok_or_else(|| bad("url"))?; + url = Some(value.to_owned()); + } + "hold" => { + hold = match value.to_ascii_lowercase().as_str() { + "true" | "yes" | "on" | "1" => true, + "false" | "no" | "off" | "0" => false, + _ => return Err(bad("hold")), + } + } + "channel" => { + channel = match value { + "stable" => Channel::Stable, + "rc" => Channel::Rc, + _ => return Err(bad("channel")), + } + } + "source" => { + let value = value.trim_end_matches('/'); + source = if value.starts_with('/') { + Source::Dir(value.into()) + } else if origin(value).is_some() { + Source::Mirror(value.to_owned()) + } else { + return Err(bad("source")); + } + } + "soak_hours" => { + let hours: i64 = value.parse().map_err(|_| bad("soak_hours"))?; + if !(0..=24).contains(&hours) { + return Err(bad("soak_hours")); + } + soak_hours = Some(hours); + } + _ => return Err(bad(&key.chars().take(20).collect::())), + } + } + let url = url.ok_or_else(|| bad("no url"))?; + // Only test servers shorten the wait or talk to Pyo without TLS. + if channel != Channel::Rc { + if soak_hours.is_some() { + return Err(bad("soak_hours needs channel=rc")); + } + if !url.starts_with("https://") { + return Err(bad("url must be https")); + } + } + Ok(Config { + url, + hold, + channel, + source, + soak_secs: soak_hours.map_or(DAY, |h| h * 3600), + }) +} + +pub fn load(env: &Env) -> Result { + let text = read_limited(&env.path(PATH), 64 * 1024) + .ok() + .and_then(|b| String::from_utf8(b).ok()) + .ok_or_else(|| { + Problem::new( + "The verifier is not set up on this server. Run the connect command from Pyo again.", + ) + })?; + parse(&text) +} + +/// What `install` writes when there is no file yet. +pub fn fresh(url: &str, channel: Channel) -> String { + format!( + "# Pyo's verifier on this server. hold=true stops updates.\nurl={url}\nhold=false\nchannel={}\n", + match channel { + Channel::Stable => "stable", + Channel::Rc => "rc", + } + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_config_file_reads() { + let c = parse("# comment\n\nurl = https://pyo.example.com/\nHOLD=\"true\"\n").unwrap(); + assert_eq!(c.url, "https://pyo.example.com"); + assert!(c.hold); + assert_eq!(c.channel, Channel::Stable); + assert_eq!(c.source, Source::GitHub); + assert_eq!(c.soak_secs, DAY); + + let c = parse("url=http://10.0.0.2:8000\nchannel=rc\nsoak_hours=0\nsource=/srv/rel/\n") + .unwrap(); + assert_eq!(c.channel, Channel::Rc); + assert_eq!(c.soak_secs, 0); + assert_eq!(c.source, Source::Dir("/srv/rel".into())); + assert_eq!( + parse("url=https://a.example\nsource=https://mirror.example/pyo\n") + .unwrap() + .source, + Source::Mirror("https://mirror.example/pyo".into()) + ); + assert_eq!( + parse(&fresh("https://a.example", Channel::Rc)) + .unwrap() + .channel, + Channel::Rc + ); + } + + #[test] + fn a_config_it_cannot_read_stops_it() { + for bad in [ + "", + "hold=false", + "url=pyo.example.com", + "url=https://a.example\nhold=maybe", + "url=https://a.example\nhodl=true", + "url=https://a.example\nchannel=beta", + "url=https://a.example\nsource=relative/dir", + "url=https://a.example\njust words", + // The wait only shortens on the rc channel, and never grows. + "url=https://a.example\nsoak_hours=1", + "url=https://a.example\nchannel=rc\nsoak_hours=25", + "url=https://a.example\nchannel=rc\nsoak_hours=-1", + // Plain HTTP to Pyo is for test servers. + "url=http://a.example", + ] { + assert!(parse(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn nothing_in_the_config_names_what_to_trust() { + for key in [ + "trust_root", + "root", + "fulcio", + "rekor", + "signer", + "identity", + "issuer", + "key", + "insecure", + "verify", + "skip_verify", + "floor", + ] { + assert!( + parse(&format!("url=https://a.example\n{key}=x")).is_err(), + "{key}" + ); + } + } +} diff --git a/crates/pyo-verify/src/fetch.rs b/crates/pyo-verify/src/fetch.rs new file mode 100644 index 00000000..188f3f83 --- /dev/null +++ b/crates/pyo-verify/src/fetch.rs @@ -0,0 +1,167 @@ +//! Downloads. Every answer is untrusted: a size limit on each, and a +//! redirect is only followed to a host on a short list. + +use std::path::PathBuf; + +use crate::{ + sys::{Env, HttpError, Problem, read_limited}, + version::Version, +}; + +/// Where GitHub serves a release's files from, after its own redirect. +pub const GITHUB_HOSTS: &[&str] = &[ + "github.com", + "objects.githubusercontent.com", + "release-assets.githubusercontent.com", +]; +const GITHUB_RELEASES: &str = "https://github.com/upsetdev/pyo/releases/download"; +const MAX_REDIRECTS: usize = 5; + +pub const MAX_ANSWER: usize = 4 * 1024; +pub const MAX_MANIFEST: usize = 4 * 1024 * 1024; +pub const MAX_BUNDLE: usize = 256 * 1024; +pub const MAX_BINARY: usize = 64 * 1024 * 1024; + +/// The scheme and host (with its port, when it has one) of a URL the +/// verifier is willing to ask. None for anything else. +pub fn origin(url: &str) -> Option<(bool, String)> { + if !url.is_ascii() || url.bytes().any(|b| b <= b' ' || b == 0x7f) { + return None; + } + let (https, rest) = match (url.strip_prefix("https://"), url.strip_prefix("http://")) { + (Some(r), _) => (true, r), + (_, Some(r)) => (false, r), + _ => return None, + }; + let host = rest.split(['/', '?', '#']).next().unwrap_or(""); + let ok = !host.is_empty() + && host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':' | b'[' | b']')); + ok.then(|| (https, host.to_ascii_lowercase())) +} + +/// A GET that follows redirects only to `hosts`, and only over HTTPS when +/// it started there. +pub fn get(env: &Env, url: &str, max: usize, hosts: &[&str]) -> Result, Problem> { + let (https, first) = origin(url).ok_or_else(|| Problem::new("The address is not a URL."))?; + let mut at = url.to_owned(); + for _ in 0..=MAX_REDIRECTS { + let r = env.http.get(&at, max).map_err(|e| match e { + HttpError::TooLarge => Problem::new(format!( + "The answer from {first} is larger than expected. Nothing was changed." + )), + HttpError::Failed(why) => { + Problem::with(format!("{first} did not answer. Nothing was changed."), why) + } + })?; + if r.body.len() > max { + return Err(Problem::new(format!( + "The answer from {first} is larger than expected. Nothing was changed." + ))); + } + match (r.status, r.redirect) { + (200, _) => return Ok(r.body), + (300..=399, Some(to)) => { + let allowed = origin(&to) + .is_some_and(|(s, host)| (s || !https) && hosts.contains(&host.as_str())); + if !allowed { + return Err(Problem::with( + format!( + "{first} sent the download to an address the verifier does not use. Nothing was changed." + ), + to, + )); + } + at = to; + } + (status, _) => { + return Err(Problem::with( + format!( + "{first} did not have what the verifier asked for. Nothing was changed." + ), + format!("HTTP {status} for {at}"), + )); + } + } + } + Err(Problem::new(format!( + "{first} redirected too many times. Nothing was changed." + ))) +} + +/// Where a release's files come from. All of them are untrusted: what +/// counts is the signature on release.json and the checksums in it. +#[derive(Debug, Clone, PartialEq)] +pub enum Source { + GitHub, + /// A base URL laid out like GitHub's: `/v/`. + Mirror(String), + /// A directory laid out the same way. + Dir(PathBuf), +} + +impl Source { + pub fn fetch( + &self, + env: &Env, + version: &Version, + file: &str, + max: usize, + ) -> Result, Problem> { + match self { + Source::GitHub => get( + env, + &format!("{GITHUB_RELEASES}/v{version}/{file}"), + max, + GITHUB_HOSTS, + ), + Source::Mirror(base) => { + let host = origin(base).map(|(_, h)| h).unwrap_or_default(); + get(env, &format!("{base}/v{version}/{file}"), max, &[&host]) + } + Source::Dir(dir) => { + let path = dir.join(format!("v{version}")).join(file); + read_limited(&path, max).map_err(|e| { + Problem::with( + format!("{file} of release {version} could not be read from the release folder. Nothing was changed."), + format!("{}: {e}", path.display()), + ) + }) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_plain_urls_have_an_origin() { + assert_eq!( + origin("https://GitHub.com/a/b?c#d"), + Some((true, "github.com".into())) + ); + assert_eq!( + origin("http://10.0.0.5:8080"), + Some((false, "10.0.0.5:8080".into())) + ); + for bad in [ + "", + "github.com/x", + "ftp://github.com/x", + "file:///etc/passwd", + "https://", + "https:///x", + "https://user@github.com/x", + "https://github.com@evil.example/x", + "https://github.com /x", + "https://github.com/x\n--output=/etc/passwd", + "https://gíthub.com/x", + "-o/etc/passwd", + ] { + assert_eq!(origin(bad), None, "{bad:?}"); + } + } +} diff --git a/crates/pyo-verify/src/install.rs b/crates/pyo-verify/src/install.rs new file mode 100644 index 00000000..7aeb483a --- /dev/null +++ b/crates/pyo-verify/src/install.rs @@ -0,0 +1,299 @@ +//! `pyo-verify install` and `uninstall`: the config, the binary in its +//! place and the systemd timer. Pyo's connect command calls these while it +//! holds the lock, so they do not take it. + +use crate::{ + config, state, + status::{self, KUBECTL_TIMEOUT}, + sys::{Env, Problem, read_limited, write_atomic}, + update, + version::Channel, +}; + +pub const BINARY: &str = "/usr/local/bin/pyo-verify"; +pub const SERVICE: &str = "/etc/systemd/system/pyo-verify.service"; +pub const TIMER: &str = "/etc/systemd/system/pyo-verify.timer"; + +const SERVICE_UNIT: &str = "\ +[Unit] +Description=Pyo verifier (takes signed Pyo releases for this server) +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/bin/pyo-verify run +TimeoutStartSec=15min +NoNewPrivileges=yes +PrivateTmp=yes +"; + +/// About every 15 minutes, spread out so servers do not ask at once. A run +/// missed while the server was off happens after it starts. +const TIMER_UNIT: &str = "\ +[Unit] +Description=Runs the Pyo verifier + +[Timer] +OnCalendar=*:0/15 +RandomizedDelaySec=5min +Persistent=true + +[Install] +WantedBy=timers.target +"; + +fn cannot(what: &str, e: impl std::fmt::Display) -> Problem { + Problem::with( + format!( + "The verifier could not be set up on this server ({what}). It needs to run as root." + ), + e.to_string(), + ) +} + +fn systemctl(env: &Env, args: &[&str]) -> bool { + let mut argv = vec!["systemctl"]; + argv.extend(args); + env.runner.run(&argv, None).is_ok_and(|o| o.ok) +} + +/// Sets the verifier up. An existing config is kept as it is. Without one, +/// `url` (the control plane's public URL) is needed. +pub fn install(env: &Env, url: Option<&str>, channel: Option) -> Result { + let conf = env.path(config::PATH); + if conf.exists() { + // Kept, and it has to be one the verifier can use. + config::load(env)?; + } else { + let url = url.ok_or_else(|| { + Problem::new( + "The verifier needs the address of Pyo. Run pyo-verify install --url
.", + ) + })?; + let unusable = + || Problem::new("The address of Pyo has to be an https address. Nothing was changed."); + // One line of the config, and nothing more. + crate::fetch::origin(url).ok_or_else(unusable)?; + let text = config::fresh( + url.trim_end_matches('/'), + channel.unwrap_or(Channel::Stable), + ); + config::parse(&text).map_err(|_| unusable())?; + write_atomic(&conf, text.as_bytes(), 0o644).map_err(|e| cannot("config", e))?; + } + + let binary = env.path(BINARY); + if env.exe != binary { + let bytes = + read_limited(&env.exe, crate::fetch::MAX_BINARY).map_err(|e| cannot("binary", e))?; + write_atomic(&binary, &bytes, 0o755).map_err(|e| cannot("binary", e))?; + } + std::fs::create_dir_all(env.path(state::DIR)).map_err(|e| cannot("state", e))?; + write_atomic(&env.path(SERVICE), SERVICE_UNIT.as_bytes(), 0o644) + .map_err(|e| cannot("service", e))?; + write_atomic(&env.path(TIMER), TIMER_UNIT.as_bytes(), 0o644).map_err(|e| cannot("timer", e))?; + if !(systemctl(env, &["daemon-reload"]) + && systemctl(env, &["enable", "--now", "pyo-verify.timer"])) + { + return Err(cannot("timer", "systemctl failed")); + } + Ok("The verifier is set up on this server.".into()) +} + +/// Removes everything `install` and the verifier's runs left: the timer and +/// service, the config, the state, the status ConfigMap and the binary with +/// the one it kept. +pub fn uninstall(env: &Env) -> Result { + // Missing pieces are fine: it may be half there. + systemctl(env, &["disable", "--now", "pyo-verify.timer"]); + let binary = env.path(BINARY); + let previous = update::previous(&binary); + let mut left = Vec::new(); + for path in [ + env.path(TIMER), + env.path(SERVICE), + env.path(config::PATH), + previous, + binary, + ] { + match std::fs::remove_file(&path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => left.push(format!("{}: {e}", path.display())), + } + } + match std::fs::remove_dir_all(env.path(state::DIR)) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => left.push(format!("{}: {e}", state::DIR)), + } + systemctl(env, &["daemon-reload"]); + // A cluster that does not answer keeps the ConfigMap, which nothing + // reads once the verifier is gone. + let _ = env.runner.run( + &[ + "k3s", + "kubectl", + KUBECTL_TIMEOUT, + "-n", + status::NAMESPACE, + "delete", + "configmap", + status::CONFIGMAP, + "--ignore-not-found", + ], + None, + ); + if !left.is_empty() { + return Err(cannot("removing it", left.join(", "))); + } + Ok("The verifier is removed from this server.".into()) +} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + + use super::*; + use crate::{ + release::Sigstore, + sys::{CmdOut, Curl, Exec, Runner, SystemClock}, + testdir::TestDir, + version::Version, + }; + + #[derive(Default)] + struct Recorder(RefCell>); + + impl Runner for Recorder { + fn run(&self, argv: &[&str], _: Option<&[u8]>) -> std::io::Result { + self.0.borrow_mut().push(argv.join(" ")); + Ok(CmdOut { + ok: true, + stdout: Vec::new(), + }) + } + } + + /// A server's files in `dir`, with this binary somewhere else on it. + fn env<'a>(dir: &TestDir, runner: &'a Recorder) -> Env<'a> { + let exe = dir.path().join("root/pyo-verify-download"); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"this binary").unwrap(); + Env { + root: dir.path().to_owned(), + runner, + // Never reached: install and uninstall make no requests. + http: &Curl, + clock: &SystemClock, + handover: &Exec, + verifier: &Sigstore, + own: Version::own(), + arch: "x86_64", + exe, + } + } + + #[test] + fn install_sets_up_the_config_the_binary_and_the_timer() { + let (dir, runner) = (TestDir::new(), Recorder::default()); + let e = env(&dir, &runner); + install(&e, Some("https://pyo.example/"), None).unwrap(); + let read = |p: &str| std::fs::read_to_string(e.path(p)).unwrap(); + let conf = config::load(&e).unwrap(); + assert_eq!(conf.url, "https://pyo.example"); + assert!(!conf.hold); + assert_eq!(conf.channel, Channel::Stable); + assert_eq!(read(BINARY), "this binary"); + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(e.path(BINARY)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o755); + assert!(read(SERVICE).contains("ExecStart=/usr/local/bin/pyo-verify run\n")); + let timer = read(TIMER); + assert!(timer.contains("OnCalendar=*:0/15\n"), "{timer}"); + assert!(timer.contains("RandomizedDelaySec=5min\n")); + assert!(timer.contains("Persistent=true\n")); + assert!(e.path(state::DIR).is_dir()); + assert_eq!( + *runner.0.borrow(), + [ + "systemctl daemon-reload", + "systemctl enable --now pyo-verify.timer" + ] + ); + } + + #[test] + fn install_keeps_an_existing_config() { + let (dir, runner) = (TestDir::new(), Recorder::default()); + let e = env(&dir, &runner); + let mine = "url=https://pyo.example\nhold=true\nchannel=rc\n"; + std::fs::create_dir_all(e.path("/etc/pyo")).unwrap(); + std::fs::write(e.path(config::PATH), mine).unwrap(); + install(&e, Some("https://other.example"), Some(Channel::Stable)).unwrap(); + assert_eq!(std::fs::read_to_string(e.path(config::PATH)).unwrap(), mine); + // Again, also without an address: the same. + install(&e, None, None).unwrap(); + assert_eq!(std::fs::read_to_string(e.path(config::PATH)).unwrap(), mine); + } + + #[test] + fn install_needs_a_usable_address() { + for url in [ + None, + Some("pyo.example"), + Some("http://pyo.example"), + Some("https://pyo.example\nhold=true"), + ] { + let (dir, runner) = (TestDir::new(), Recorder::default()); + let e = env(&dir, &runner); + assert!(install(&e, url, None).is_err(), "{url:?}"); + assert!(!e.path(config::PATH).exists()); + assert!(!e.path(TIMER).exists()); + assert!(runner.0.borrow().is_empty()); + } + // Test servers may use plain HTTP. + let (dir, runner) = (TestDir::new(), Recorder::default()); + let e = env(&dir, &runner); + install(&e, Some("http://10.0.0.2:8000"), Some(Channel::Rc)).unwrap(); + assert_eq!(config::load(&e).unwrap().channel, Channel::Rc); + } + + #[test] + fn uninstall_removes_what_install_and_the_runs_left() { + let (dir, runner) = (TestDir::new(), Recorder::default()); + let e = env(&dir, &runner); + install(&e, Some("https://pyo.example"), None).unwrap(); + std::fs::write(e.path(state::PATH), "floor=0.51.0\n").unwrap(); + std::fs::write(e.path(status::PATH), "{}").unwrap(); + std::fs::write(update::previous(&e.path(BINARY)), "older").unwrap(); + runner.0.borrow_mut().clear(); + uninstall(&e).unwrap(); + for gone in [ + config::PATH, + BINARY, + SERVICE, + TIMER, + state::DIR, + "/usr/local/bin/pyo-verify.previous", + ] { + assert!(!e.path(gone).exists(), "{gone}"); + } + // Pyo's other files in /etc/pyo are not its to remove. + assert!(e.path("/etc/pyo").is_dir()); + assert_eq!( + *runner.0.borrow(), + [ + "systemctl disable --now pyo-verify.timer", + "systemctl daemon-reload", + "k3s kubectl --request-timeout=15s -n pyo-system delete configmap pyo-verifier --ignore-not-found", + ] + ); + // Twice is fine. + uninstall(&e).unwrap(); + } +} diff --git a/crates/pyo-verify/src/lib.rs b/crates/pyo-verify/src/lib.rs new file mode 100644 index 00000000..9b23eebd --- /dev/null +++ b/crates/pyo-verify/src/lib.rs @@ -0,0 +1,294 @@ +//! Pyo's verifier: a small root program on the first server of a cluster +//! that is connected to a Pyo it does not run itself (Pyo Cloud). A systemd +//! timer runs it. +//! +//! It takes only what a signed Pyo release defines, and only for the +//! version Pyo's control plane names as live. Two parties have to agree: +//! the release workflow signed the release (checked offline against +//! Sigstore's public trust root, compiled in), and the control plane says +//! that version is live. The control plane alone can only pick among +//! releases the workflow signed, never below what the server already has, +//! and never one younger than a day. +//! +//! This release is the bootstrap only: the verifier checks a release, +//! replaces itself with that release's verifier and hands over to it. It +//! applies nothing to the cluster. See run.rs. +//! +//! What it never does: write Secrets, write any cluster object besides its +//! own status ConfigMap, read or send a token, or take its trust root from +//! anywhere but its own binary. + +pub mod config; +pub mod fetch; +pub mod install; +pub mod release; +pub mod run; +pub mod state; +pub mod status; +pub mod sys; +pub mod update; +pub mod version; + +use version::Channel; + +pub const USAGE: &str = "\ +Usage: pyo-verify + + run check for a signed release now (the timer runs this) + status show what the last run found + install [--url
] [--channel stable|rc] + set up the config and the timer + uninstall remove the verifier from this server + version print this verifier's version"; + +#[derive(Debug, PartialEq)] +pub enum Command { + Run { + handed_over_from: Option, + }, + Status, + Install { + url: Option, + channel: Option, + }, + Uninstall, + Version, +} + +/// The command line, without the program's name. Anything it does not know +/// is refused: there are no hidden flags. +pub fn parse_args(args: &[String]) -> Option { + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + match args.as_slice() { + ["run"] => Some(Command::Run { + handed_over_from: None, + }), + ["run", "--handed-over-from", from] => Some(Command::Run { + handed_over_from: Some((*from).to_owned()), + }), + ["status"] => Some(Command::Status), + ["uninstall"] => Some(Command::Uninstall), + ["version"] => Some(Command::Version), + ["install", rest @ ..] => { + let (mut url, mut channel) = (None, None); + let mut rest = rest.iter(); + while let Some(flag) = rest.next() { + match (*flag, rest.next()) { + ("--url", Some(v)) if url.is_none() => url = Some((*v).to_owned()), + ("--channel", Some(&"stable")) if channel.is_none() => { + channel = Some(Channel::Stable) + } + ("--channel", Some(&"rc")) if channel.is_none() => channel = Some(Channel::Rc), + _ => return None, + } + } + Some(Command::Install { url, channel }) + } + _ => None, + } +} + +#[cfg(test)] +pub(crate) mod testdir { + use std::{ + cell::RefCell, + path::{Path, PathBuf}, + sync::{ + RwLock, RwLockReadGuard, RwLockWriteGuard, + atomic::{AtomicU32, Ordering}, + }, + }; + + /// A directory of its own for one test, removed with it. + pub struct TestDir(PathBuf); + + static NEXT: AtomicU32 = AtomicU32::new(0); + + /// Tests that start real programs hold this for writing, tests that + /// take the verifier's lock for reading. A program started by another + /// thread shares this process's open files until it execs, the lock + /// file with its lock among them, which would make a run see the lock + /// as held for a moment. + static SPAWNING: RwLock<()> = RwLock::new(()); + + thread_local! { + /// This thread's hold on `SPAWNING`, and how many share it. + static QUIET: RefCell<(u32, Option>)> = + const { RefCell::new((0, None)) }; + } + + pub fn spawning() -> RwLockWriteGuard<'static, ()> { + SPAWNING.write().unwrap_or_else(|e| e.into_inner()) + } + + /// While one of these lives, no test starts a program. + pub struct Quiet; + + impl Quiet { + pub fn new() -> Quiet { + QUIET.with_borrow_mut(|(count, guard)| { + if *count == 0 { + *guard = Some(SPAWNING.read().unwrap_or_else(|e| e.into_inner())); + } + *count += 1; + }); + Quiet + } + } + + impl Drop for Quiet { + fn drop(&mut self) { + QUIET.with_borrow_mut(|(count, guard)| { + *count -= 1; + if *count == 0 { + *guard = None; + } + }); + } + } + + impl TestDir { + pub fn new() -> TestDir { + let dir = std::env::temp_dir().join(format!( + "pyo-verify-test-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TestDir(dir) + } + + pub fn path(&self) -> &Path { + &self.0 + } + } + + impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(line: &str) -> Vec { + line.split_whitespace().map(str::to_owned).collect() + } + + #[test] + fn the_commands_parse() { + assert_eq!( + parse_args(&args("run")), + Some(Command::Run { + handed_over_from: None + }) + ); + assert_eq!( + parse_args(&args("run --handed-over-from 0.51.0")), + Some(Command::Run { + handed_over_from: Some("0.51.0".into()) + }) + ); + assert_eq!(parse_args(&args("status")), Some(Command::Status)); + assert_eq!(parse_args(&args("uninstall")), Some(Command::Uninstall)); + assert_eq!(parse_args(&args("version")), Some(Command::Version)); + assert_eq!( + parse_args(&args("install --channel rc --url https://pyo.example")), + Some(Command::Install { + url: Some("https://pyo.example".into()), + channel: Some(Channel::Rc) + }) + ); + assert_eq!( + parse_args(&args("install")), + Some(Command::Install { + url: None, + channel: None + }) + ); + } + + #[test] + fn anything_else_is_refused() { + for line in [ + "", + "apply", + "run now", + "run --handed-over-from", + "run --force", + "run --trust-root /tmp/root.pem", + "run --insecure", + "run --signer someone", + "run --source /tmp", + "run --url https://evil.example", + "run --floor 0.1.0", + "install --channel beta", + "install --url", + "install --url a --url b", + "install --trust-root x", + "status --json", + "version --all", + "--help", + ] { + assert_eq!(parse_args(&args(line)), None, "{line:?}"); + } + } + + /// The trust root is the one compiled into pyo-sigstore, and what a run + /// does comes from /etc/pyo/verify.conf alone. This holds the code to + /// it: outside of tests, no source file reads an environment variable, + /// and only main.rs builds the verifier, as `Sigstore`, a type without + /// fields (release.rs asserts that when compiling). The config has no + /// key for it (config.rs) and the command line no flag (above). + #[test] + fn nothing_can_swap_the_trust_root() { + let sources = [ + ("lib.rs", include_str!("lib.rs")), + ("main.rs", include_str!("main.rs")), + ("config.rs", include_str!("config.rs")), + ("fetch.rs", include_str!("fetch.rs")), + ("install.rs", include_str!("install.rs")), + ("release.rs", include_str!("release.rs")), + ("run.rs", include_str!("run.rs")), + ("state.rs", include_str!("state.rs")), + ("status.rs", include_str!("status.rs")), + ("sys.rs", include_str!("sys.rs")), + ("update.rs", include_str!("update.rs")), + ("version.rs", include_str!("version.rs")), + ]; + // Every module is in the list. + let mods = sources[0] + .1 + .lines() + .filter(|l| l.starts_with("pub mod ")) + .count(); + assert_eq!(mods + 2, sources.len()); + let var = ["env::", "var"].concat(); + let cfg_test = ["#[cfg(", "test)]"].concat(); + for (name, text) in sources { + // What ships: the file up to its tests. + let shipped = text.split(&cfg_test).next().unwrap(); + assert!(!shipped.contains(&var), "{name} reads the environment"); + assert!(!shipped.contains("option_env!"), "{name}"); + let builds_verifier = shipped.contains("= Env {"); + assert_eq!(builds_verifier, name == "main.rs", "{name}"); + } + assert!(sources[1].1.contains("verifier: &Sigstore,")); + // And the checker crate has one trust root, its own files. + let sigstore = include_str!("../../pyo-sigstore/src/lib.rs"); + let shipped = sigstore.split(&cfg_test).next().unwrap(); + assert_eq!(shipped.matches("include_bytes!(\"../assets/").count(), 3); + assert!(!shipped.contains(&var)); + for root in ["FULCIO_ROOT", "FULCIO_INTERMEDIATE", "REKOR_KEY"] { + assert!( + shipped.contains(&format!("const {root}: &[u8] = include_bytes!")), + "{root}" + ); + assert!(!shipped.contains(&format!("pub const {root}")), "{root}"); + } + } +} diff --git a/crates/pyo-verify/src/main.rs b/crates/pyo-verify/src/main.rs new file mode 100644 index 00000000..c4df1dc4 --- /dev/null +++ b/crates/pyo-verify/src/main.rs @@ -0,0 +1,76 @@ +//! The `pyo-verify` binary: the real server around lib.rs. + +use std::process::ExitCode; + +use pyo_verify::{ + Command, USAGE, install, parse_args, + release::Sigstore, + run, status, + sys::{Curl, Env, Exec, Problem, RealRunner, SystemClock}, + version::Version, +}; + +fn finish(result: Result) -> ExitCode { + match result { + Ok(line) => { + println!("{line}"); + ExitCode::SUCCESS + } + Err(p) => { + println!("{}", p.plain); + if let Some(detail) = p.detail { + eprintln!("{detail}"); + } + ExitCode::FAILURE + } + } +} + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let Some(command) = parse_args(&args) else { + eprintln!("{USAGE}"); + return ExitCode::from(2); + }; + if command == Command::Version { + println!("{}", Version::own()); + return ExitCode::SUCCESS; + } + let Ok(exe) = std::env::current_exe() else { + println!("The verifier could not find its own file."); + return ExitCode::FAILURE; + }; + // The one place the pieces are chosen. The verifier is Sigstore's, with + // the trust root compiled into pyo-sigstore. Nothing here is read from + // a flag, a file or the environment. + let env = Env { + root: "/".into(), + runner: &RealRunner, + http: &Curl, + clock: &SystemClock, + handover: &Exec, + verifier: &Sigstore, + own: Version::own(), + arch: std::env::consts::ARCH, + exe, + }; + match command { + Command::Version => ExitCode::SUCCESS, + Command::Run { handed_over_from } => { + let report = run::run(&env, handed_over_from.as_deref()); + println!("{}", report.message); + if let Some(detail) = report.detail { + eprintln!("{detail}"); + } + ExitCode::from(report.outcome.exit_code()) + } + Command::Status => { + println!("{}", status::show(&env)); + ExitCode::SUCCESS + } + Command::Install { url, channel } => { + finish(install::install(&env, url.as_deref(), channel)) + } + Command::Uninstall => finish(install::uninstall(&env)), + } +} diff --git a/crates/pyo-verify/src/release.rs b/crates/pyo-verify/src/release.rs new file mode 100644 index 00000000..69cc3675 --- /dev/null +++ b/crates/pyo-verify/src/release.rs @@ -0,0 +1,145 @@ +//! A release's signed release.json: who checks its signature, and the part +//! of it the verifier reads. + +use crate::{sys::Problem, version::Version}; + +/// What a good signature says besides "yes". +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Signed { + /// When Sigstore's transparency log took the signature (seconds since + /// 1970), signed by the log itself. + pub logged_at: i64, +} + +/// Checks that `manifest` is the release.json Pyo's release workflow signed +/// at the tag of exactly `version`. +pub trait ReleaseVerifier { + fn verify(&self, manifest: &[u8], bundle: &[u8], version: &Version) -> Result; +} + +/// The only verifier the binary has: Sigstore's public instance, as built +/// into pyo-sigstore. It has no fields, and nothing (no flag, no setting, no +/// environment variable) can give the binary another trust root. Tests that +/// need releases nobody signed use a verifier that exists only in test +/// builds (run.rs). +pub struct Sigstore; + +const _: () = assert!(std::mem::size_of::() == 0); + +impl ReleaseVerifier for Sigstore { + fn verify(&self, manifest: &[u8], bundle: &[u8], version: &Version) -> Result { + let refused = |why: String| { + Problem::with( + format!( + "Release {version} is not signed by Pyo's release workflow. Nothing was changed." + ), + why, + ) + }; + let bundle = std::str::from_utf8(bundle).map_err(|e| refused(e.to_string()))?; + let signer = pyo_sigstore::release_signer_for(&version.to_string()); + pyo_sigstore::verify_logged(manifest, bundle, &signer.signer()) + .map(|v| Signed { + logged_at: v.integrated_time, + }) + .map_err(|e| refused(format!("{e:#}"))) + } +} + +/// What the verifier reads from a release.json. Everything else in it is +/// for other readers. +#[derive(Debug, PartialEq)] +pub struct Manifest { + pub version: String, + /// The SHA-256 of this release's verifier, for this server's processor. + /// None: the release has no verifier. + pub verifier_sha256: Option, +} + +/// The name of the verifier for a processor, in `verifier` and as the +/// release's file `pyo-verify-`. +pub fn platform(arch: &str) -> String { + format!("linux-{arch}") +} + +pub fn parse_manifest(bytes: &[u8], arch: &str) -> Result { + let unreadable = || Problem::new("The signed release could not be read. Nothing was changed."); + let v: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| unreadable())?; + let o = v.as_object().ok_or_else(unreadable)?; + let version = o + .get("version") + .and_then(|v| v.as_str()) + .ok_or_else(unreadable)? + .to_owned(); + let verifier_sha256 = match o.get("verifier") { + None | Some(serde_json::Value::Null) => None, + Some(v) => { + let map = v.as_object().ok_or_else(unreadable)?; + match map.get(&platform(arch)) { + None => { + return Err(Problem::new(format!( + "Release {version} has no verifier for this server's processor. Run the connect command from Pyo to update this server." + ))); + } + Some(sum) => { + let sum = sum.as_str().ok_or_else(unreadable)?; + let hex = sum.len() == 64 + && sum + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + if !hex { + return Err(unreadable()); + } + Some(sum.to_owned()) + } + } + } + }; + Ok(Manifest { + version, + verifier_sha256, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_manifest_is_read_strictly() { + let sum = "ab".repeat(32); + let m = parse_manifest( + format!(r#"{{"version":"0.52.0","verifier":{{"linux-x86_64":"{sum}","linux-aarch64":"{sum}"}},"more":1}}"#).as_bytes(), + "x86_64", + ) + .unwrap(); + assert_eq!(m.version, "0.52.0"); + assert_eq!(m.verifier_sha256.as_deref(), Some(sum.as_str())); + // No verifier in the release. + let m = parse_manifest(br#"{"version":"0.5.4"}"#, "x86_64").unwrap(); + assert_eq!(m.verifier_sha256, None); + // Not for this processor. + let e = parse_manifest( + format!(r#"{{"version":"0.52.0","verifier":{{"linux-x86_64":"{sum}"}}}}"#).as_bytes(), + "aarch64", + ) + .unwrap_err(); + assert!(e.plain.contains("this server's processor"), "{}", e.plain); + for bad in [ + "".to_owned(), + "[]".to_owned(), + r#"{"version":51}"#.to_owned(), + r#"{"verifier":{}}"#.to_owned(), + r#"{"version":"0.52.0","verifier":"x"}"#.to_owned(), + r#"{"version":"0.52.0","verifier":{"linux-x86_64":"abc"}}"#.to_owned(), + r#"{"version":"0.52.0","verifier":{"linux-x86_64":7}}"#.to_owned(), + format!( + r#"{{"version":"0.52.0","verifier":{{"linux-x86_64":"{}"}}}}"#, + "AB".repeat(32) + ), + format!(r#"{{"version":"0.52.0","verifier":{{"linux-x86_64":"{sum}"}}}} trailing"#), + ] { + assert!(parse_manifest(bad.as_bytes(), "x86_64").is_err(), "{bad}"); + } + } +} diff --git a/crates/pyo-verify/src/run.rs b/crates/pyo-verify/src/run.rs new file mode 100644 index 00000000..52153c11 --- /dev/null +++ b/crates/pyo-verify/src/run.rs @@ -0,0 +1,1633 @@ +//! `pyo-verify run`: what the timer calls. +//! +//! In order, and on any failure nothing is changed: +//! 1. take the lock the connect command also takes; +//! 2. read the config, and stop on a hold (the config's or the cluster's); +//! 3. ask Pyo's control plane which version is live; +//! 4. go forward only: that version against the floor; +//! 5. fetch that release's release.json and check its signature for +//! exactly that version; +//! 6. wait until the signature is old enough; +//! 7. replace this binary with that release's verifier and start it; +//! 8. write the status, whatever happened. +//! +//! Two parties have to agree before step 7: the release workflow signed the +//! release, and the control plane names it. Either alone changes nothing. +//! +//! This release stops there: it applies nothing to the cluster. The next +//! one adds an `apply` module, called from `steps` where a run finds the +//! live version to be its own, with the release.json it verified the same +//! way. Because step 7 comes first, the code that applies a release is +//! always that release's own. + +use std::fs::File; + +use crate::{ + config::{self, Config}, + fetch::{self, MAX_ANSWER, MAX_BUNDLE, MAX_MANIFEST}, + release::parse_manifest, + state, + status::{self, KUBECTL_TIMEOUT, Status}, + sys::{Env, Problem}, + update, + version::{Channel, Version}, +}; + +/// Shared with Pyo's connect command (deploy/install.sh takes it with +/// `flock` on fd 9): a run and a connect never overlap. +pub const LOCK: &str = "/run/pyo-connect.lock"; +/// The customer's switches (pyo-proto's rbac.rs): read, never written. +const POLICY_CONFIGMAP: &str = "pyo-policy"; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Outcome { + /// Something else holds the lock: nothing read, nothing written. + Skipped, + /// The live version is this server's. + Current, + Hold, + /// A good release that is not used yet. + Waiting, + /// The live release has no verifier: the connect command is needed. + NoVerifier, + /// The new verifier was started in this one's place. + HandedOver, + Failed, +} + +impl Outcome { + /// For the process: a failure shows as a failed unit. + pub fn exit_code(self) -> u8 { + match self { + Outcome::Failed | Outcome::NoVerifier => 1, + _ => 0, + } + } +} + +pub struct Report { + pub outcome: Outcome, + /// One plain line. + pub message: String, + /// For the journal. + pub detail: Option, +} + +/// What a run learned on its way, for the status. +#[derive(Default)] +struct Seen { + live: Option, + hold: bool, + /// The version whose verifier now is this binary's file. + next: Option, +} + +enum Lock { + Taken(#[allow(dead_code)] File), + Held, + Failed(std::io::Error), +} + +/// Not waited for. Closed (and so released) when this process ends or +/// hands over. +fn lock(env: &Env) -> Lock { + let path = env.path(LOCK); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path); + match file { + Err(e) => Lock::Failed(e), + Ok(f) => match f.try_lock() { + Ok(()) => Lock::Taken(f), + Err(std::fs::TryLockError::WouldBlock) => Lock::Held, + Err(std::fs::TryLockError::Error(e)) => Lock::Failed(e), + }, + } +} + +/// The cluster's `updates` switch says hold: `hold`, as Pyo reads it +/// (trimmed, any case). Empty or `auto` go on, anything else stops. +fn policy_hold(env: &Env) -> Result { + let unreadable = || { + Problem::new( + "The verifier could not read this cluster's pyo-policy settings. Nothing was changed.", + ) + }; + let out = env + .runner + .run( + &[ + "k3s", + "kubectl", + KUBECTL_TIMEOUT, + "-n", + status::NAMESPACE, + "get", + "configmap", + POLICY_CONFIGMAP, + "--ignore-not-found", + "-o", + "jsonpath={.data.updates}", + ], + None, + ) + .ok() + .filter(|o| o.ok) + .ok_or_else(unreadable)?; + match String::from_utf8_lossy(&out.stdout) + .trim() + .to_ascii_lowercase() + .as_str() + { + // What Pyo shows as on hold (pyo-proto's `Policy::updates_hold`). + "hold" => Ok(true), + "" | "auto" => Ok(false), + // A value it does not know is not read as "go on". + _ => Err(Problem::new( + "The updates setting in this cluster's pyo-policy is not one the verifier knows. Nothing was changed.", + )), + } +} + +/// The live version, from the control plane's answer: an untrusted string +/// until it parses as a version. +fn parse_answer(body: &[u8], channel: Channel) -> Result { + let unusable = || { + Problem::new("Pyo's answer about its live version could not be used. Nothing was changed.") + }; + let v: serde_json::Value = serde_json::from_slice(body).map_err(|_| unusable())?; + let version = v + .as_object() + .and_then(|o| o.get("version")) + .and_then(|v| v.as_str()) + .and_then(Version::parse) + .ok_or_else(unusable)?; + if version.is_rc() && channel != Channel::Rc { + return Err(Problem::new( + "Pyo names a test version and this server only takes stable versions. Nothing was changed.", + )); + } + Ok(version) +} + +fn ask(env: &Env, cfg: &Config) -> Result { + // No redirects: the answer comes from the address in the config. + let body = fetch::get( + env, + &format!("{}/install/version", cfg.url), + MAX_ANSWER, + &[], + )?; + parse_answer(&body, cfg.channel) +} + +fn steps( + env: &Env, + handed_over_from: Option<&str>, + seen: &mut Seen, +) -> Result<(Outcome, String), Problem> { + let cfg = config::load(env)?; + if let Some(from) = handed_over_from { + // Started by the verifier this one replaced. Never by itself or a + // newer one: that would be a loop. + Version::parse(from).filter(|f| *f < env.own).ok_or_else(|| { + Problem::new( + "The verifier was started by one that is not older than itself. Nothing was changed.", + ) + })?; + state::raise(env, env.own)?; + } + if cfg.hold { + seen.hold = true; + return Ok(( + Outcome::Hold, + format!("Updates are on hold in {}.", config::PATH), + )); + } + if policy_hold(env)? { + seen.hold = true; + return Ok(( + Outcome::Hold, + "Updates are on hold in this cluster's pyo-policy settings.".into(), + )); + } + + let live = ask(env, &cfg)?; + seen.live = Some(live); + let floor = state::floor(env)?.map_or(env.own, |f| f.max(env.own)); + if live == floor { + return Ok(( + Outcome::Current, + format!("This server is on version {live}."), + )); + } + if live < floor { + return Err(Problem::new(format!( + "Pyo names version {live} and this server is already on {floor}. Nothing was changed." + ))); + } + + let manifest = cfg.source.fetch(env, &live, "release.json", MAX_MANIFEST)?; + let bundle = cfg + .source + .fetch(env, &live, "release.json.sigstore.json", MAX_BUNDLE)?; + // Nothing of the release is read before its signature checks out. + let signed = env.verifier.verify(&manifest, &bundle, &live)?; + let release = parse_manifest(&manifest, env.arch)?; + if release.version != live.to_string() { + return Err(Problem::new(format!( + "The signed release names another version than {live}. Nothing was changed." + ))); + } + + // The age is the log's time against this server's clock. A clock that + // runs behind makes the wait longer, one that runs ahead shorter. + let age = env.clock.now() - signed.logged_at; + if age < 0 { + return Ok(( + Outcome::Waiting, + format!( + "Release {live} is dated after this server's clock. Check the clock of this server." + ), + )); + } + if age < cfg.soak_secs { + return Ok(( + Outcome::Waiting, + format!( + "Release {live} was signed {} hours ago. This server takes it once it is {} hours old.", + age / 3600, + cfg.soak_secs / 3600 + ), + )); + } + + let Some(sha256) = release.verifier_sha256 else { + return Ok(( + Outcome::NoVerifier, + format!( + "Release {live} has no verifier. Run the connect command from Pyo to update this server." + ), + )); + }; + if handed_over_from.is_some() { + // One hand-over per run. + return Ok(( + Outcome::Waiting, + format!("Release {live} is newer than this verifier. It is taken on the next run."), + )); + } + update::replace(env, &cfg.source, &live, &sha256)?; + seen.next = Some(live); + Ok(( + Outcome::HandedOver, + format!("The verifier is updating itself to {live}."), + )) +} + +fn status_of(env: &Env, seen: &Seen, outcome: Outcome, message: &str) -> Status { + let failed = outcome.exit_code() != 0; + Status { + verifier_version: env.own.to_string(), + live_version: seen.live.map(|v| v.to_string()).unwrap_or_default(), + last_check: status::rfc3339(env.clock.now()), + state: match outcome { + Outcome::Current => "current", + Outcome::Hold => "hold", + Outcome::Waiting => "waiting", + Outcome::HandedOver => "updating", + Outcome::Failed | Outcome::NoVerifier | Outcome::Skipped => "error", + } + .into(), + message: message.to_owned(), + last_error: if failed { + message.to_owned() + } else { + String::new() + }, + hold: seen.hold, + host: status::host(env), + } +} + +/// One run. `handed_over_from`: the version of the verifier that started +/// this one in its place (`run --handed-over-from `). +pub fn run(env: &Env, handed_over_from: Option<&str>) -> Report { + let _lock = match lock(env) { + Lock::Taken(f) => f, + Lock::Held => { + return Report { + outcome: Outcome::Skipped, + message: "Another Pyo setup step is running on this server. The verifier tries again later.".into(), + detail: None, + }; + } + Lock::Failed(e) => { + return Report { + outcome: Outcome::Failed, + message: "The verifier needs to run as root.".into(), + detail: Some(e.to_string()), + }; + } + }; + + let mut seen = Seen::default(); + let (mut outcome, mut message, mut detail) = match steps(env, handed_over_from, &mut seen) { + Ok((outcome, message)) => (outcome, message, None), + Err(p) => (Outcome::Failed, p.plain, p.detail), + }; + status::write(env, &status_of(env, &seen, outcome, &message)); + + if let Some(next) = seen.next { + let own = env.own.to_string(); + // Said here: after a hand-over this process is gone. The lock is + // released by the exec, and the new verifier takes it again. + println!("{message}"); + let started = if next > env.own { + env.handover + .exec(&env.exe, &["run", "--handed-over-from", &own]) + } else { + Err(std::io::Error::other("not a newer version")) + }; + if let Err(e) = started { + let back = update::roll_back(env); + outcome = Outcome::Failed; + message = format!( + "The verifier of release {next} could not be started. This server keeps verifier {own}." + ); + detail = Some(format!("{e} (previous binary back: {})", back.is_ok())); + status::write(env, &status_of(env, &seen, outcome, &message)); + } + } + Report { + outcome, + message, + detail, + } +} + +#[cfg(test)] +mod tests { + use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + path::{Path, PathBuf}, + }; + + use sha2::{Digest, Sha256}; + + use super::*; + use crate::{ + release::{ReleaseVerifier, Signed, Sigstore}, + sys::{Clock, CmdOut, Handover, HttpError, Response, Runner, Transport}, + testdir::TestDir, + }; + + const GITHUB: &str = "https://github.com/upsetdev/pyo/releases/download"; + const PYO: &str = "https://pyo.example/install/version"; + const NOW: i64 = 2_000_000_000; + const DAY: i64 = 86_400; + /// A real release: its release.json and the bundle the release workflow + /// made for it. + const REAL_MANIFEST: &[u8] = + include_bytes!("../../pyo-sigstore/assets/testdata/release-0.5.4/release.json"); + const REAL_BUNDLE: &[u8] = include_bytes!( + "../../pyo-sigstore/assets/testdata/release-0.5.4/release.json.sigstore.json" + ); + /// When Rekor logged it. + const REAL_LOGGED: i64 = 1_795_294_220; + + /// Stands in for Sigstore where a test needs a release nobody signed. + /// It only exists in tests: the binary's verifier is `Sigstore`, built + /// in main.rs, and cannot be exchanged. + struct TestSigner; + + fn test_bundle(tag: &str, manifest: &[u8], logged_at: i64) -> Vec { + serde_json::json!({ + "tag": tag, + "sha256": hex::encode(Sha256::digest(manifest)), + "loggedAt": logged_at, + }) + .to_string() + .into_bytes() + } + + impl ReleaseVerifier for TestSigner { + fn verify( + &self, + manifest: &[u8], + bundle: &[u8], + version: &Version, + ) -> Result { + let refused = || { + Problem::new(format!( + "Release {version} is not signed by Pyo's release workflow. Nothing was changed." + )) + }; + let b: serde_json::Value = serde_json::from_slice(bundle).map_err(|_| refused())?; + if b["tag"] != format!("v{version}") + || b["sha256"] != hex::encode(Sha256::digest(manifest)) + { + return Err(refused()); + } + Ok(Signed { + logged_at: b["loggedAt"].as_i64().ok_or_else(refused)?, + }) + } + } + + /// A status, where it redirects to, and a body. + type Answer = (u16, Option, Vec); + + #[derive(Default)] + struct FakeHttp { + routes: RefCell>, + calls: RefCell>, + } + + impl Transport for FakeHttp { + fn get(&self, url: &str, max: usize) -> Result { + self.calls.borrow_mut().push(url.to_owned()); + match self.routes.borrow().get(url) { + Some((_, _, body)) if body.len() > max => Err(HttpError::TooLarge), + Some((status, redirect, body)) => Ok(Response { + status: *status, + redirect: redirect.clone(), + body: body.clone(), + }), + None => Ok(Response { + status: 404, + redirect: None, + body: b"Not Found".to_vec(), + }), + } + } + } + + struct FakeRunner { + k3s_up: Cell, + /// `updates` in pyo-policy. + policy: RefCell, + /// What a downloaded verifier answers to `version`. + new_says: RefCell, + applied: RefCell>, + calls: RefCell>>, + } + + impl Runner for FakeRunner { + fn run(&self, argv: &[&str], stdin: Option<&[u8]>) -> std::io::Result { + self.calls + .borrow_mut() + .push(argv.iter().map(|a| a.to_string()).collect()); + let out = |ok: bool, s: &str| { + Ok(CmdOut { + ok, + stdout: s.as_bytes().to_vec(), + }) + }; + if argv[0] == "k3s" { + if !self.k3s_up.get() { + return out(false, ""); + } + if argv.contains(&"get") { + return out(true, &self.policy.borrow()); + } + if argv.contains(&"apply") { + self.applied + .borrow_mut() + .push(String::from_utf8(stdin.unwrap().to_vec()).unwrap()); + } + return out(true, ""); + } + if argv.len() == 2 && argv[1] == "version" { + assert!(Path::new(argv[0]).exists(), "the staged binary is there"); + return out(true, &format!("{}\n", self.new_says.borrow())); + } + out(true, "") + } + } + + struct FakeClock(Cell); + + impl Clock for FakeClock { + fn now(&self) -> i64 { + self.0.get() + } + } + + #[derive(Default)] + struct FakeExec { + fails: Cell, + calls: RefCell)>>, + } + + impl Handover for FakeExec { + fn exec(&self, program: &Path, args: &[&str]) -> std::io::Result<()> { + self.calls.borrow_mut().push(( + program.to_owned(), + args.iter().map(|a| a.to_string()).collect(), + )); + if self.fails.get() { + return Err(std::io::Error::other("exec format error")); + } + Ok(()) + } + } + + /// A server: its files in a temporary directory, and fakes for the rest. + struct World { + dir: TestDir, + http: FakeHttp, + runner: FakeRunner, + clock: FakeClock, + exec: FakeExec, + own: Version, + /// Check signatures for real (Sigstore) instead of `TestSigner`. + real: bool, + _quiet: crate::testdir::Quiet, + } + + fn v(s: &str) -> Version { + Version::parse(s).unwrap() + } + + impl World { + /// A server whose verifier is version `own`, set up for + /// https://pyo.example. + fn new(own: &str) -> World { + let w = World { + dir: TestDir::new(), + http: FakeHttp::default(), + runner: FakeRunner { + k3s_up: Cell::new(true), + policy: RefCell::new(String::new()), + new_says: RefCell::new(String::new()), + applied: RefCell::default(), + calls: RefCell::default(), + }, + clock: FakeClock(Cell::new(NOW)), + exec: FakeExec::default(), + own: v(own), + real: false, + _quiet: crate::testdir::Quiet::new(), + }; + w.config("url=https://pyo.example\n"); + w.write("usr/local/bin/pyo-verify", b"old binary"); + w.write("proc/sys/kernel/hostname", b"web-1\n"); + w + } + + fn write(&self, rel: &str, bytes: &[u8]) { + let p = self.dir.path().join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, bytes).unwrap(); + } + + fn read(&self, rel: &str) -> Option> { + std::fs::read(self.dir.path().join(rel)).ok() + } + + fn config(&self, text: &str) { + self.write("etc/pyo/verify.conf", text.as_bytes()); + } + + fn exe(&self) -> PathBuf { + self.dir.path().join("usr/local/bin/pyo-verify") + } + + fn env(&self) -> Env<'_> { + Env { + root: self.dir.path().to_owned(), + runner: &self.runner, + http: &self.http, + clock: &self.clock, + handover: &self.exec, + verifier: if self.real { &Sigstore } else { &TestSigner }, + own: self.own, + arch: "x86_64", + exe: self.exe(), + } + } + + fn route(&self, url: &str, body: &[u8]) { + self.http + .routes + .borrow_mut() + .insert(url.to_owned(), (200, None, body.to_vec())); + } + + fn redirect(&self, url: &str, to: &str) { + self.http + .routes + .borrow_mut() + .insert(url.to_owned(), (302, Some(to.to_owned()), Vec::new())); + } + + /// The control plane names this version. + fn live(&self, version: &str) { + self.route( + PYO, + format!(r#"{{"version":"{version}","install":"abc123"}}"#).as_bytes(), + ); + } + + /// A release on GitHub, signed (by `TestSigner`) a week ago, with a + /// verifier binary of these bytes. + fn release(&self, version: &str, binary: Option<&[u8]>) { + self.release_logged(version, binary, NOW - 7 * DAY); + } + + fn release_logged(&self, version: &str, binary: Option<&[u8]>, logged_at: i64) { + let manifest = match binary { + Some(b) => { + self.route(&format!("{GITHUB}/v{version}/pyo-verify-linux-x86_64"), b); + *self.runner.new_says.borrow_mut() = version.to_owned(); + serde_json::json!({ "version": version, "verifier": { + "linux-x86_64": hex::encode(Sha256::digest(b)), + "linux-aarch64": "0".repeat(64), + }}) + } + None => serde_json::json!({ "version": version }), + } + .to_string(); + self.signed_manifest(version, manifest.as_bytes(), logged_at); + } + + fn signed_manifest(&self, version: &str, manifest: &[u8], logged_at: i64) { + self.route(&format!("{GITHUB}/v{version}/release.json"), manifest); + self.route( + &format!("{GITHUB}/v{version}/release.json.sigstore.json"), + &test_bundle(&format!("v{version}"), manifest, logged_at), + ); + } + + /// The real release 0.5.4, served as release `at`. + fn real_release(&self, at: &str, manifest: &[u8]) { + self.route(&format!("{GITHUB}/v{at}/release.json"), manifest); + self.route( + &format!("{GITHUB}/v{at}/release.json.sigstore.json"), + REAL_BUNDLE, + ); + } + + fn run(&self) -> Report { + run(&self.env(), None) + } + + fn status(&self) -> serde_json::Value { + serde_json::from_slice( + &self + .read("var/lib/pyo-verify/status.json") + .expect("a status file"), + ) + .unwrap() + } + + fn asked_github(&self) -> bool { + self.http + .calls + .borrow() + .iter() + .any(|u| u.contains("github")) + } + + /// Nothing on the server moved: the binary, no hand-over. + fn assert_unchanged(&self) { + assert_eq!( + self.read("usr/local/bin/pyo-verify").unwrap(), + b"old binary" + ); + assert!(self.read("usr/local/bin/pyo-verify.new").is_none()); + assert!(self.exec.calls.borrow().is_empty()); + } + } + + #[test] + fn the_live_version_being_this_one_changes_nothing() { + let w = World::new("0.51.0"); + w.live("0.51.0"); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Current, "{}", r.message); + assert_eq!(r.message, "This server is on version 0.51.0."); + assert!(!w.asked_github()); + w.assert_unchanged(); + let s = w.status(); + assert_eq!(s["state"], "current"); + assert_eq!(s["verifierVersion"], "0.51.0"); + assert_eq!(s["liveVersion"], "0.51.0"); + assert_eq!(s["lastError"], ""); + assert_eq!(s["host"], "web-1"); + assert_eq!(s["hold"], false); + } + + #[test] + fn a_lower_version_is_refused_and_reported() { + let w = World::new("0.51.0"); + w.live("0.50.9"); + w.release("0.50.9", Some(b"older")); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert_eq!( + r.message, + "Pyo names version 0.50.9 and this server is already on 0.51.0. Nothing was changed." + ); + assert!(!w.asked_github()); + w.assert_unchanged(); + assert_eq!(w.status()["state"], "error"); + assert_eq!(w.status()["lastError"], r.message); + } + + #[test] + fn the_recorded_floor_holds_under_an_older_binary() { + // An older verifier was put back on a server that had moved on. + let w = World::new("0.51.0"); + w.write("var/lib/pyo-verify/state", b"floor=0.53.0\n"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert!(r.message.contains("already on 0.53.0"), "{}", r.message); + w.assert_unchanged(); + w.live("0.53.0"); + assert_eq!(w.run().outcome, Outcome::Current); + // Above the floor it goes on. + w.live("0.54.0"); + w.release("0.54.0", Some(b"newer")); + assert_eq!(w.run().outcome, Outcome::HandedOver); + } + + #[test] + fn a_state_file_it_cannot_read_stops_it() { + let w = World::new("0.51.0"); + w.write("var/lib/pyo-verify/state", b"floor=lots\n"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + assert_eq!(w.run().outcome, Outcome::Failed); + w.assert_unchanged(); + } + + #[test] + fn an_answer_that_is_not_a_version_is_refused() { + for answer in [ + r#"{"version":"v0.52.0"}"#, + r#"{"version":"0.52"}"#, + r#"{"version":"latest"}"#, + r#"{"version":"0.52.0\n"}"#, + r#"{"version":"0.52.0 --insecure"}"#, + r#"{"version":"../../0.52.0"}"#, + r#"{"version":52}"#, + r#"{"version":null}"#, + r#"{"install":"abc"}"#, + r#"["0.52.0"]"#, + r#""0.52.0""#, + "0.52.0", + "", + "502 Bad Gateway", + r#"{"version":"0.52.0"} {"version":"0.53.0"}"#, + ] { + let w = World::new("0.51.0"); + w.route(PYO, answer.as_bytes()); + w.release("0.52.0", Some(b"new")); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed, "{answer}"); + assert_eq!( + r.message, + "Pyo's answer about its live version could not be used. Nothing was changed.", + "{answer}" + ); + assert!(!w.asked_github(), "{answer}"); + w.assert_unchanged(); + assert_eq!(w.status()["liveVersion"], "", "{answer}"); + } + // More fields than it knows are fine: the route may grow. + let w = World::new("0.51.0"); + w.route( + PYO, + br#"{"version":"0.51.0","install":"abc","more":{"x":1}}"#, + ); + assert_eq!(w.run().outcome, Outcome::Current); + } + + #[test] + fn rc_versions_need_the_rc_channel() { + let w = World::new("0.51.0"); + w.live("0.52.0-rc.1"); + w.release("0.52.0-rc.1", Some(b"rc binary")); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert!( + r.message.contains("only takes stable versions"), + "{}", + r.message + ); + assert!(!w.asked_github()); + w.assert_unchanged(); + + w.config("url=https://pyo.example\nchannel=rc\n"); + let r = w.run(); + assert_eq!(r.outcome, Outcome::HandedOver, "{}", r.message); + assert_eq!(w.read("usr/local/bin/pyo-verify").unwrap(), b"rc binary"); + + // An rc is older than its release, and newer than the one before. + let w = World::new("0.52.0"); + w.config("url=https://pyo.example\nchannel=rc\n"); + w.live("0.52.0-rc.2"); + assert!(w.run().message.contains("already on 0.52.0")); + } + + #[test] + fn hold_in_the_config_stops_everything_but_the_status() { + let w = World::new("0.51.0"); + w.config("url=https://pyo.example\nhold=true\n"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Hold); + assert_eq!(r.message, "Updates are on hold in /etc/pyo/verify.conf."); + assert!(w.http.calls.borrow().is_empty(), "nobody was asked"); + w.assert_unchanged(); + let s = w.status(); + assert_eq!(s["state"], "hold"); + assert_eq!(s["hold"], true); + assert_eq!(s["lastError"], ""); + // The status also went to the cluster. + let applied = w.runner.applied.borrow(); + let cm: serde_json::Value = serde_json::from_str(&applied[0]).unwrap(); + assert_eq!(cm["data"]["hold"], "true"); + // And `status` still answers. + assert!(status::show(&w.env()).contains("State hold")); + } + + #[test] + fn hold_in_the_cluster_stops_it() { + for value in ["hold", "Hold\n", " HOLD "] { + let w = World::new("0.51.0"); + *w.runner.policy.borrow_mut() = value.into(); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Hold, "{value}"); + assert_eq!( + r.message, + "Updates are on hold in this cluster's pyo-policy settings." + ); + assert!(w.http.calls.borrow().is_empty(), "{value}"); + w.assert_unchanged(); + assert_eq!(w.status()["hold"], true); + } + // Empty or `auto`: it goes on. + for value in ["", "auto", " Auto\n"] { + let w = World::new("0.51.0"); + *w.runner.policy.borrow_mut() = value.into(); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + assert_eq!(w.run().outcome, Outcome::HandedOver, "{value:?}"); + assert_eq!(w.status()["hold"], false, "{value:?}"); + } + // The switch is read, never written. + let w = World::new("0.51.0"); + w.live("0.51.0"); + w.run(); + let calls = w.runner.calls.borrow(); + let get = calls + .iter() + .find(|c| c.contains(&"pyo-policy".to_owned())) + .unwrap(); + assert_eq!( + get.join(" "), + "k3s kubectl --request-timeout=15s -n pyo-system get configmap pyo-policy --ignore-not-found -o jsonpath={.data.updates}" + ); + } + + #[test] + fn a_hold_switch_it_cannot_read_stops_it() { + // A value it does not know, a word Pyo doesn't show as on hold + // among them: neither hold nor go. + for value in ["sometimes", "paused", "off", "false", "on", "true", "holding"] { + let w = World::new("0.51.0"); + *w.runner.policy.borrow_mut() = value.into(); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed, "{value}"); + assert_eq!( + r.message, + "The updates setting in this cluster's pyo-policy is not one the verifier knows. Nothing was changed.", + "{value}" + ); + assert!(w.http.calls.borrow().is_empty(), "{value}"); + w.assert_unchanged(); + } + + // k3s is not answering: nothing happens, and the status is the file. + let w = World::new("0.51.0"); + w.runner.k3s_up.set(false); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert_eq!( + r.message, + "The verifier could not read this cluster's pyo-policy settings. Nothing was changed." + ); + assert!(w.http.calls.borrow().is_empty()); + w.assert_unchanged(); + assert_eq!(w.status()["lastError"], r.message); + assert!(w.runner.applied.borrow().is_empty()); + } + + #[test] + fn a_newer_signed_release_replaces_the_verifier_and_hands_over() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"the 0.52.0 verifier")); + let r = w.run(); + assert_eq!( + r.outcome, + Outcome::HandedOver, + "{} {:?}", + r.message, + r.detail + ); + assert_eq!(r.message, "The verifier is updating itself to 0.52.0."); + // The new binary is in place, the one it replaced is kept. + assert_eq!( + w.read("usr/local/bin/pyo-verify").unwrap(), + b"the 0.52.0 verifier" + ); + assert_eq!( + w.read("usr/local/bin/pyo-verify.previous").unwrap(), + b"old binary" + ); + assert!(w.read("usr/local/bin/pyo-verify.new").is_none()); + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(w.exe()).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o755); + // Started once, in this one's place, told where it came from. + let calls = w.exec.calls.borrow(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].0, w.exe()); + assert_eq!(calls[0].1, ["run", "--handed-over-from", "0.51.0"]); + let s = w.status(); + assert_eq!(s["state"], "updating"); + assert_eq!(s["liveVersion"], "0.52.0"); + // The floor is the new verifier's to record. + assert!(w.read("var/lib/pyo-verify/state").is_none()); + } + + #[test] + fn a_handed_over_run_records_the_floor() { + let w = World::new("0.52.0"); + w.live("0.52.0"); + let r = run(&w.env(), Some("0.51.0")); + assert_eq!(r.outcome, Outcome::Current, "{}", r.message); + assert_eq!( + w.read("var/lib/pyo-verify/state").unwrap(), + b"floor=0.52.0\n" + ); + assert_eq!(w.status()["verifierVersion"], "0.52.0"); + assert_eq!(w.status()["state"], "current"); + w.assert_unchanged(); + // Also when Pyo cannot be asked right then. + let w = World::new("0.52.0"); + let r = run(&w.env(), Some("0.51.0")); + assert_eq!(r.outcome, Outcome::Failed); + assert_eq!( + w.read("var/lib/pyo-verify/state").unwrap(), + b"floor=0.52.0\n" + ); + } + + #[test] + fn there_is_no_exec_loop() { + // A verifier never takes a hand-over from its own version, a newer + // one, or something that is not a version. + for from in ["0.52.0", "0.53.0", "", "0.52", "--help"] { + let w = World::new("0.52.0"); + w.live("0.53.0"); + w.release("0.53.0", Some(b"new")); + let r = run(&w.env(), Some(from)); + assert_eq!(r.outcome, Outcome::Failed, "{from:?}"); + assert!(w.http.calls.borrow().is_empty(), "{from:?}"); + assert!(w.read("var/lib/pyo-verify/state").is_none()); + w.assert_unchanged(); + } + // One hand-over per run: a handed-over verifier that finds an even + // newer release leaves it to the next run. + let w = World::new("0.52.0"); + w.live("0.53.0"); + w.release("0.53.0", Some(b"new")); + let r = run(&w.env(), Some("0.51.0")); + assert_eq!(r.outcome, Outcome::Waiting); + assert_eq!( + r.message, + "Release 0.53.0 is newer than this verifier. It is taken on the next run." + ); + w.assert_unchanged(); + assert!( + !w.http + .calls + .borrow() + .iter() + .any(|u| u.contains("pyo-verify-linux")) + ); + // The next run, started by the timer, takes it. + assert_eq!(w.run().outcome, Outcome::HandedOver); + assert_eq!(w.exec.calls.borrow().len(), 1); + } + + #[test] + fn a_real_signed_release_is_accepted() { + // Sigstore for real: release 0.5.4 as the release workflow signed + // it. It has no verifier yet, which is as far as a run can get with + // it, past the signature, the version and the wait. + let mut w = World::new("0.5.3"); + w.real = true; + w.clock.0.set(REAL_LOGGED + 2 * DAY); + w.live("0.5.4"); + w.real_release("0.5.4", REAL_MANIFEST); + let r = w.run(); + assert_eq!( + r.outcome, + Outcome::NoVerifier, + "{} {:?}", + r.message, + r.detail + ); + assert_eq!( + r.message, + "Release 0.5.4 has no verifier. Run the connect command from Pyo to update this server." + ); + assert_eq!(w.status()["state"], "error"); + assert_eq!(w.status()["lastError"], r.message); + w.assert_unchanged(); + // Its wait counts from the time Rekor signed. + w.clock.0.set(REAL_LOGGED + DAY - 1); + assert_eq!(w.run().outcome, Outcome::Waiting); + } + + #[test] + fn a_release_signed_at_another_tag_is_refused() { + // The real 0.5.4, offered as other versions: its signature names + // the tag v0.5.4 and no other. + for (own, live, channel) in [ + ("0.5.3", "0.5.5", "stable"), + ("0.5.3", "0.5.40", "stable"), + ("0.5.3", "0.5.4-rc.1", "rc"), + ("0.4.0", "0.5.0", "stable"), + ] { + let mut w = World::new(own); + w.real = true; + w.config(&format!("url=https://pyo.example\nchannel={channel}\n")); + w.clock.0.set(REAL_LOGGED + 2 * DAY); + w.live(live); + w.real_release(live, REAL_MANIFEST); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed, "{live}"); + assert_eq!( + r.message, + format!( + "Release {live} is not signed by Pyo's release workflow. Nothing was changed." + ) + ); + assert!(r.detail.unwrap().contains("refs/tags/v0.5.4"), "{live}"); + w.assert_unchanged(); + } + } + + #[test] + fn a_tampered_release_is_refused() { + // Against Sigstore: one changed byte in the real release.json. + let mut w = World::new("0.5.3"); + w.real = true; + w.clock.0.set(REAL_LOGGED + 2 * DAY); + w.live("0.5.4"); + let mut manifest = REAL_MANIFEST.to_vec(); + let at = manifest.windows(6).position(|w| w == b"sha256").unwrap(); + manifest[at + 10] ^= 1; + w.real_release("0.5.4", &manifest); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert!( + r.message + .contains("is not signed by Pyo's release workflow"), + "{}", + r.message + ); + w.assert_unchanged(); + + // A signature that is no bundle, or missing. + for bundle in [&b"{}"[..], b"", b"not json"] { + let mut w = World::new("0.5.3"); + w.real = true; + w.live("0.5.4"); + w.route(&format!("{GITHUB}/v0.5.4/release.json"), REAL_MANIFEST); + w.route( + &format!("{GITHUB}/v0.5.4/release.json.sigstore.json"), + bundle, + ); + assert_eq!(w.run().outcome, Outcome::Failed); + w.assert_unchanged(); + } + let mut w = World::new("0.5.3"); + w.real = true; + w.live("0.5.4"); + w.route(&format!("{GITHUB}/v0.5.4/release.json"), REAL_MANIFEST); + assert_eq!(w.run().outcome, Outcome::Failed); + + // And a release whose verifier checksum was swapped after signing. + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + let evil = serde_json::json!({ "version": "0.52.0", "verifier": { + "linux-x86_64": hex::encode(Sha256::digest(b"evil")) } }) + .to_string(); + w.route(&format!("{GITHUB}/v0.52.0/release.json"), evil.as_bytes()); + w.route( + &format!("{GITHUB}/v0.52.0/pyo-verify-linux-x86_64"), + b"evil", + ); + assert_eq!(w.run().outcome, Outcome::Failed); + w.assert_unchanged(); + } + + #[test] + fn a_release_that_names_another_version_is_refused() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.route(&format!("{GITHUB}/v0.52.0/pyo-verify-linux-x86_64"), b"new"); + let manifest = serde_json::json!({ "version": "0.53.0", "verifier": { + "linux-x86_64": hex::encode(Sha256::digest(b"new")) } }) + .to_string(); + w.signed_manifest("0.52.0", manifest.as_bytes(), NOW - 7 * DAY); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert_eq!( + r.message, + "The signed release names another version than 0.52.0. Nothing was changed." + ); + w.assert_unchanged(); + } + + #[test] + fn a_young_release_waits() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release_logged("0.52.0", Some(b"new"), NOW - 23 * 3600); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Waiting); + assert_eq!( + r.message, + "Release 0.52.0 was signed 23 hours ago. This server takes it once it is 24 hours old." + ); + w.assert_unchanged(); + assert_eq!(w.status()["state"], "waiting"); + assert_eq!(w.status()["lastError"], ""); + assert!( + !w.http + .calls + .borrow() + .iter() + .any(|u| u.contains("pyo-verify-linux")) + ); + // An hour later it is old enough. + w.clock.0.set(NOW + 3600); + assert_eq!(w.run().outcome, Outcome::HandedOver); + + // Signed after this server's clock: the clock is off. + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release_logged("0.52.0", Some(b"new"), NOW + 600); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Waiting); + assert!( + r.message.contains("Check the clock of this server"), + "{}", + r.message + ); + w.assert_unchanged(); + + // Test servers may shorten the wait. + let w = World::new("0.51.0"); + w.config("url=https://pyo.example\nchannel=rc\nsoak_hours=1\n"); + w.live("0.52.0-rc.1"); + w.release_logged("0.52.0-rc.1", Some(b"new"), NOW - 1800); + assert_eq!(w.run().outcome, Outcome::Waiting); + w.release_logged("0.52.0-rc.1", Some(b"new"), NOW - 3600); + assert_eq!(w.run().outcome, Outcome::HandedOver); + } + + #[test] + fn a_release_without_a_verifier_stops_cleanly() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", None); + let r = w.run(); + assert_eq!(r.outcome, Outcome::NoVerifier); + assert_eq!(r.outcome.exit_code(), 1); + w.assert_unchanged(); + assert!( + !w.http + .calls + .borrow() + .iter() + .any(|u| u.contains("pyo-verify-linux")) + ); + assert!(w.read("var/lib/pyo-verify/state").is_none()); + assert_eq!(w.status()["lastError"], r.message); + } + + #[test] + fn a_bad_checksum_is_refused_and_the_binary_kept() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"the signed verifier")); + w.route( + &format!("{GITHUB}/v0.52.0/pyo-verify-linux-x86_64"), + b"another binary", + ); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert_eq!( + r.message, + "The verifier of release 0.52.0 does not match its signed checksum. Nothing was changed." + ); + w.assert_unchanged(); + assert!(w.read("usr/local/bin/pyo-verify.previous").is_none()); + // It was never run. + assert!( + !w.runner + .calls + .borrow() + .iter() + .any(|c| c.get(1).is_some_and(|a| a == "version")) + ); + assert_eq!(w.status()["lastError"], r.message); + } + + #[test] + fn a_verifier_that_does_not_run_is_not_put_in_place() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + *w.runner.new_says.borrow_mut() = "0.51.0".into(); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert!( + r.message.contains("does not run on this server"), + "{}", + r.message + ); + w.assert_unchanged(); + } + + #[test] + fn a_verifier_that_does_not_start_is_rolled_back() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + w.exec.fails.set(true); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert_eq!( + r.message, + "The verifier of release 0.52.0 could not be started. This server keeps verifier 0.51.0." + ); + assert_eq!(w.read("usr/local/bin/pyo-verify").unwrap(), b"old binary"); + assert_eq!(w.status()["state"], "error"); + assert_eq!(w.status()["lastError"], r.message); + } + + #[test] + fn the_previous_binary_survives_each_replace() { + let w = World::new("0.51.0"); + w.write("usr/local/bin/pyo-verify.previous", b"an even older one"); + w.write("usr/local/bin/pyo-verify.new", b"left over from a crash"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + assert_eq!(w.run().outcome, Outcome::HandedOver); + assert_eq!(w.read("usr/local/bin/pyo-verify").unwrap(), b"new"); + assert_eq!( + w.read("usr/local/bin/pyo-verify.previous").unwrap(), + b"old binary" + ); + // Replaced by a rename: the old binary's file was never written to. + let w = World::new("0.51.0"); + use std::os::unix::fs::MetadataExt; + let before = std::fs::metadata(w.exe()).unwrap().ino(); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + w.run(); + assert_ne!(std::fs::metadata(w.exe()).unwrap().ino(), before); + let kept = w.dir.path().join("usr/local/bin/pyo-verify.previous"); + assert_eq!(std::fs::metadata(kept).unwrap().ino(), before); + } + + #[test] + fn the_status_is_written_on_every_outcome() { + type Setup = fn(&World); + let cases: [(&str, Setup, Outcome, &str); 7] = [ + ("current", |w| w.live("0.51.0"), Outcome::Current, "current"), + ( + "hold", + |w| w.config("url=https://pyo.example\nhold=yes\n"), + Outcome::Hold, + "hold", + ), + ("pyo is down", |_| {}, Outcome::Failed, "error"), + ( + "no config", + |w| std::fs::remove_file(w.dir.path().join("etc/pyo/verify.conf")).unwrap(), + Outcome::Failed, + "error", + ), + ( + "waiting", + |w| { + w.live("0.52.0"); + w.release_logged("0.52.0", Some(b"new"), NOW - 60); + }, + Outcome::Waiting, + "waiting", + ), + ( + "updating", + |w| { + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + }, + Outcome::HandedOver, + "updating", + ), + ("no release", |w| w.live("0.52.0"), Outcome::Failed, "error"), + ]; + for (name, setup, outcome, state) in cases { + let w = World::new("0.51.0"); + setup(&w); + let r = w.run(); + assert_eq!(r.outcome, outcome, "{name}: {}", r.message); + let s = w.status(); + assert_eq!(s["state"], state, "{name}"); + assert_eq!(s["message"], r.message, "{name}"); + assert_eq!(s["lastCheck"], "2033-05-18T03:33:20Z", "{name}"); + assert_eq!(s["verifierVersion"], "0.51.0", "{name}"); + assert_eq!(s["host"], "web-1", "{name}"); + // One line, in plain words. + assert!( + !r.message.contains(['\n', ';', '—', '–']), + "{name}: {}", + r.message + ); + assert!(!r.message.contains(" - "), "{name}: {}", r.message); + assert!(!r.message.to_lowercase().contains("node"), "{name}"); + // The same in the cluster. + let applied = w.runner.applied.borrow(); + let cm: serde_json::Value = serde_json::from_str(applied.last().unwrap()).unwrap(); + assert_eq!(cm["metadata"]["name"], "pyo-verifier", "{name}"); + assert_eq!(cm["data"]["state"], state, "{name}"); + assert_eq!(cm["data"]["message"], r.message, "{name}"); + } + } + + #[test] + fn downloads_have_a_size_limit() { + let large = |n: usize| vec![b' '; n]; + // The control plane's answer. + let w = World::new("0.51.0"); + let mut answer = br#"{"version":"0.52.0"}"#.to_vec(); + answer.extend(large(MAX_ANSWER)); + w.route(PYO, &answer); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed); + assert_eq!( + r.message, + "The answer from pyo.example is larger than expected. Nothing was changed." + ); + // release.json, its signature and the binary. + for file in [ + "release.json", + "release.json.sigstore.json", + "pyo-verify-linux-x86_64", + ] { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + let max = match file { + "release.json" => MAX_MANIFEST, + "release.json.sigstore.json" => MAX_BUNDLE, + _ => fetch::MAX_BINARY, + }; + w.route(&format!("{GITHUB}/v0.52.0/{file}"), &large(max + 1)); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed, "{file}"); + assert_eq!( + r.message, + "The answer from github.com is larger than expected. Nothing was changed.", + "{file}" + ); + w.assert_unchanged(); + } + // A transport that hands back more than it was asked for is not + // believed either. + struct Sloppy; + impl Transport for Sloppy { + fn get(&self, _: &str, max: usize) -> Result { + Ok(Response { + status: 200, + redirect: None, + body: vec![b'x'; max + 1], + }) + } + } + let w = World::new("0.51.0"); + let env = Env { + http: &Sloppy, + ..w.env() + }; + assert!(fetch::get(&env, "https://a.example/x", 10, &[]).is_err()); + // A release folder has the same limits. + let w = World::new("0.51.0"); + let folder = w.dir.path().join("releases"); + w.config(&format!( + "url=https://pyo.example\nsource={}\n", + folder.display() + )); + w.live("0.52.0"); + w.write("releases/v0.52.0/release.json", &large(MAX_MANIFEST + 1)); + assert_eq!(w.run().outcome, Outcome::Failed); + w.assert_unchanged(); + } + + #[test] + fn a_held_lock_means_skip() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + // A connect command is running. + w.write("run/pyo-connect.lock", b""); + let held = std::fs::File::open(w.dir.path().join("run/pyo-connect.lock")).unwrap(); + held.lock().unwrap(); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Skipped); + assert_eq!(r.outcome.exit_code(), 0); + assert!(w.http.calls.borrow().is_empty()); + assert!(w.runner.calls.borrow().is_empty()); + assert!(w.read("var/lib/pyo-verify/status.json").is_none()); + w.assert_unchanged(); + // Once it is done, the next run goes on. + drop(held); + assert_eq!(w.run().outcome, Outcome::HandedOver); + } + + #[test] + fn redirects_only_go_to_githubs_own_hosts() { + let asset = format!("{GITHUB}/v0.52.0/pyo-verify-linux-x86_64"); + // GitHub sends release files to its asset host. + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + let cdn = "https://release-assets.githubusercontent.com/github-production-release-asset/1/2?sig=3"; + w.redirect(&asset, cdn); + w.route(cdn, b"new"); + assert_eq!(w.run().outcome, Outcome::HandedOver); + + // Anywhere else, plain HTTP, or in circles: refused. + for to in [ + "https://evil.example/pyo-verify-linux-x86_64", + "https://github.com.evil.example/x", + "https://github.com@evil.example/x", + "http://release-assets.githubusercontent.com/x", + "https://release-assets.githubusercontent.com:8443/x", + "file:///usr/bin/true", + asset.as_str(), + ] { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + w.redirect(&asset, to); + w.route("https://evil.example/pyo-verify-linux-x86_64", b"new"); + let r = w.run(); + assert_eq!(r.outcome, Outcome::Failed, "{to}"); + w.assert_unchanged(); + assert!( + !w.http.calls.borrow().iter().any(|u| u.contains("evil")), + "{to}" + ); + } + + // The control plane's answer comes from its own address only. + let w = World::new("0.51.0"); + w.redirect(PYO, "https://github.com/x"); + w.route("https://github.com/x", br#"{"version":"0.52.0"}"#); + w.release("0.52.0", Some(b"new")); + assert_eq!(w.run().outcome, Outcome::Failed); + w.assert_unchanged(); + } + + #[test] + fn a_mirror_or_a_folder_can_stand_in_for_github() { + // A folder (air gaps, tests). It is as untrusted as the network. + let w = World::new("0.51.0"); + let folder = w.dir.path().join("releases"); + w.config(&format!( + "url=https://pyo.example\nsource={}\n", + folder.display() + )); + w.live("0.52.0"); + let manifest = serde_json::json!({ "version": "0.52.0", "verifier": { + "linux-x86_64": hex::encode(Sha256::digest(b"from the folder")) } }) + .to_string(); + w.write("releases/v0.52.0/release.json", manifest.as_bytes()); + w.write( + "releases/v0.52.0/release.json.sigstore.json", + &test_bundle("v0.52.0", manifest.as_bytes(), NOW - 2 * DAY), + ); + w.write( + "releases/v0.52.0/pyo-verify-linux-x86_64", + b"from the folder", + ); + *w.runner.new_says.borrow_mut() = "0.52.0".into(); + let r = w.run(); + assert_eq!( + r.outcome, + Outcome::HandedOver, + "{} {:?}", + r.message, + r.detail + ); + assert_eq!( + w.read("usr/local/bin/pyo-verify").unwrap(), + b"from the folder" + ); + assert!(!w.asked_github()); + // A release.json changed in the folder is refused like any other. + let w2 = World::new("0.51.0"); + w2.config(&format!( + "url=https://pyo.example\nsource={}\n", + folder.display() + )); + w2.live("0.52.0"); + w.write( + "releases/v0.52.0/release.json", + manifest.replace("0.52.0", "0.52.1").as_bytes(), + ); + assert_eq!(w2.run().outcome, Outcome::Failed); + w2.assert_unchanged(); + + // A mirror by URL. + let w = World::new("0.51.0"); + w.config("url=https://pyo.example\nsource=https://mirror.example/pyo\n"); + w.live("0.52.0"); + w.route( + "https://mirror.example/pyo/v0.52.0/release.json", + manifest.as_bytes(), + ); + w.route( + "https://mirror.example/pyo/v0.52.0/release.json.sigstore.json", + &test_bundle("v0.52.0", manifest.as_bytes(), NOW - 2 * DAY), + ); + w.route( + "https://mirror.example/pyo/v0.52.0/pyo-verify-linux-x86_64", + b"from the folder", + ); + *w.runner.new_says.borrow_mut() = "0.52.0".into(); + assert_eq!(w.run().outcome, Outcome::HandedOver); + assert!(!w.asked_github()); + } + + #[test] + fn it_touches_nothing_in_the_cluster_but_its_own_status() { + let w = World::new("0.51.0"); + w.live("0.52.0"); + w.release("0.52.0", Some(b"new")); + assert_eq!(w.run().outcome, Outcome::HandedOver); + let new = format!("{}.new", w.exe().display()); + for call in w.runner.calls.borrow().iter() { + let line = call.join(" "); + let known = line.starts_with( + "k3s kubectl --request-timeout=15s -n pyo-system get configmap pyo-policy ", + ) || line == "k3s kubectl --request-timeout=15s apply -f -" + || line == format!("{new} version"); + assert!(known, "{line}"); + } + for manifest in w.runner.applied.borrow().iter() { + let cm: serde_json::Value = serde_json::from_str(manifest).unwrap(); + assert_eq!(cm["kind"], "ConfigMap"); + assert_eq!(cm["metadata"]["namespace"], "pyo-system"); + assert_eq!(cm["metadata"]["name"], "pyo-verifier"); + } + // Only the control plane and the release were asked, with no + // credentials in the address. + for url in w.http.calls.borrow().iter() { + assert!( + url == PYO || url.starts_with(&format!("{GITHUB}/v0.52.0/")), + "{url}" + ); + } + } +} diff --git a/crates/pyo-verify/src/state.rs b/crates/pyo-verify/src/state.rs new file mode 100644 index 00000000..91a8a112 --- /dev/null +++ b/crates/pyo-verify/src/state.rs @@ -0,0 +1,52 @@ +//! `/var/lib/pyo-verify/state`: the highest version this server has moved +//! to (`floor=X.Y.Z`). The verifier never goes below it, also when an older +//! verifier binary is put back. + +use crate::{ + sys::{Env, Problem, read_limited, write_atomic}, + version::Version, +}; + +pub const DIR: &str = "/var/lib/pyo-verify"; +pub const PATH: &str = "/var/lib/pyo-verify/state"; + +/// The recorded floor. None when nothing was recorded yet. A file that is +/// there and does not read stops the verifier: it does not guess. +pub fn floor(env: &Env) -> Result, Problem> { + let path = env.path(PATH); + if !path.exists() { + return Ok(None); + } + let unreadable = || { + Problem::new(format!( + "{PATH} could not be read. Run the connect command from Pyo again." + )) + }; + let text = read_limited(&path, 4096) + .ok() + .and_then(|b| String::from_utf8(b).ok()) + .ok_or_else(unreadable)?; + text.lines() + .find_map(|l| l.trim().strip_prefix("floor=")) + .and_then(Version::parse) + .map(Some) + .ok_or_else(unreadable) +} + +/// Records `version` as the floor, unless the floor is already higher. +pub fn raise(env: &Env, version: Version) -> Result<(), Problem> { + if floor(env)?.is_some_and(|f| f >= version) { + return Ok(()); + } + write_atomic( + &env.path(PATH), + format!("floor={version}\n").as_bytes(), + 0o644, + ) + .map_err(|e| { + Problem::with( + format!("{PATH} could not be written. Nothing was changed."), + e.to_string(), + ) + }) +} diff --git a/crates/pyo-verify/src/status.rs b/crates/pyo-verify/src/status.rs new file mode 100644 index 00000000..4cef1502 --- /dev/null +++ b/crates/pyo-verify/src/status.rs @@ -0,0 +1,218 @@ +//! What the verifier last did, for the server's owner and for Pyo's agent: +//! `/var/lib/pyo-verify/status.json`, and the same as the ConfigMap +//! `pyo-system/pyo-verifier`. The ConfigMap is the only cluster object the +//! verifier writes in this release. + +use serde_json::json; + +use crate::sys::{Env, read_limited, write_atomic}; + +pub const PATH: &str = "/var/lib/pyo-verify/status.json"; +pub const NAMESPACE: &str = "pyo-system"; +pub const CONFIGMAP: &str = "pyo-verifier"; +/// Every kubectl call gives up after this. +pub const KUBECTL_TIMEOUT: &str = "--request-timeout=15s"; + +#[derive(Debug, Clone, PartialEq)] +pub struct Status { + pub verifier_version: String, + /// The version Pyo's control plane named. Empty when it was not asked + /// or its answer was not usable. + pub live_version: String, + /// RFC 3339, UTC. + pub last_check: String, + /// `current`, `hold`, `waiting`, `updating` or `error`. + pub state: String, + /// One plain line about this run. + pub message: String, + /// The same line when the run failed, else empty. + pub last_error: String, + pub hold: bool, + pub host: String, +} + +impl Status { + fn fields(&self) -> [(&'static str, String); 8] { + [ + ("verifierVersion", self.verifier_version.clone()), + ("liveVersion", self.live_version.clone()), + ("lastCheck", self.last_check.clone()), + ("state", self.state.clone()), + ("message", self.message.clone()), + ("lastError", self.last_error.clone()), + ("hold", self.hold.to_string()), + ("host", self.host.clone()), + ] + } + + fn file(&self) -> String { + let mut v = serde_json::Map::new(); + for (k, s) in self.fields() { + v.insert(k.into(), json!(s)); + } + v.insert("hold".into(), json!(self.hold)); + format!("{:#}\n", serde_json::Value::Object(v)) + } + + /// The ConfigMap, as JSON (which kubectl takes like YAML). Its values + /// are all strings, under the keys Pyo's agent reads ([`configmap_key`]). + fn configmap(&self) -> String { + let data: serde_json::Map = self + .fields() + .into_iter() + .map(|(k, s)| (configmap_key(k).to_owned(), json!(s))) + .collect(); + json!({ + "apiVersion": "v1", + "kind": "ConfigMap", + "metadata": { + "name": CONFIGMAP, + "namespace": NAMESPACE, + "labels": { "app.kubernetes.io/managed-by": "pyo-verify" }, + }, + "data": data, + }) + .to_string() + } +} + +/// A status field's key in the ConfigMap: what Pyo's agent reads there +/// (pyo-proto's `VerifierStatus::from_data`: version, live, checked, +/// error, hold, host). The file keeps its own names. +fn configmap_key(field: &str) -> &str { + match field { + "verifierVersion" => "version", + "liveVersion" => "live", + "lastCheck" => "checked", + "lastError" => "error", + other => other, + } +} + +/// This server's name. +pub fn host(env: &Env) -> String { + read_limited(&env.path("/proc/sys/kernel/hostname"), 256) + .ok() + .and_then(|b| String::from_utf8(b).ok()) + .map(|s| s.trim().to_owned()) + .unwrap_or_default() +} + +/// Seconds since 1970 as `2026-11-23T13:42:00Z`. +pub fn rfc3339(secs: i64) -> String { + let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400)); + // Days to a date (Howard Hinnant's civil_from_days). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} + +/// Writes the file, then the ConfigMap. A cluster that does not answer is +/// fine: the file is there. Returns whether each was written. +pub fn write(env: &Env, status: &Status) -> (bool, bool) { + let file = write_atomic(&env.path(PATH), status.file().as_bytes(), 0o644).is_ok(); + let cm = env + .runner + .run( + &["k3s", "kubectl", KUBECTL_TIMEOUT, "apply", "-f", "-"], + Some(status.configmap().as_bytes()), + ) + .is_ok_and(|o| o.ok); + (file, cm) +} + +/// The status file as a few plain lines, for `pyo-verify status`. +pub fn show(env: &Env) -> String { + let v: Option = read_limited(&env.path(PATH), 64 * 1024) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()); + let Some(v) = v else { + return "The verifier has not run on this server yet.".into(); + }; + let s = |k: &str| v[k].as_str().unwrap_or("").to_owned(); + let mut lines = vec![format!( + "Verifier {} on {}", + s("verifierVersion"), + s("host") + )]; + if !s("liveVersion").is_empty() { + lines.push(format!("Pyo names version {}", s("liveVersion"))); + } + lines.push(format!("Last check {}", s("lastCheck"))); + lines.push(format!("State {}", s("state"))); + lines.push(s("message")); + lines.join("\n") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn times_are_written_as_utc_dates() { + assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z"); + assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z"); + assert_eq!(rfc3339(1_795_294_220), "2026-11-21T20:50:20Z"); + assert_eq!(rfc3339(4_102_444_799), "2099-12-31T23:59:59Z"); + } + + #[test] + fn the_configmap_is_only_the_status() { + let s = Status { + verifier_version: "0.51.0".into(), + live_version: "0.52.0".into(), + last_check: rfc3339(0), + state: "error".into(), + message: "A \"quoted\"\nline".into(), + last_error: "A \"quoted\"\nline".into(), + hold: false, + host: "web-1".into(), + }; + let cm: serde_json::Value = serde_json::from_str(&s.configmap()).unwrap(); + assert_eq!(cm["kind"], "ConfigMap"); + assert_eq!(cm["metadata"]["namespace"], "pyo-system"); + assert_eq!(cm["metadata"]["name"], "pyo-verifier"); + assert_eq!(cm["data"]["hold"], "false"); + // The keys Pyo's agent reads (pyo-proto's VerifierStatus::from_data). + assert_eq!(cm["data"]["version"], "0.51.0"); + assert_eq!(cm["data"]["live"], "0.52.0"); + assert_eq!(cm["data"]["checked"], "1970-01-01T00:00:00Z"); + assert_eq!(cm["data"]["error"], "A \"quoted\"\nline"); + assert_eq!(cm["data"]["host"], "web-1"); + let mut keys: Vec<&str> = cm["data"] + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + keys.sort_unstable(); + assert_eq!( + keys, + [ + "checked", "error", "hold", "host", "live", "message", "state", "version" + ] + ); + assert!( + cm["data"] + .as_object() + .unwrap() + .values() + .all(|v| v.is_string()) + ); + let file: serde_json::Value = serde_json::from_str(&s.file()).unwrap(); + assert_eq!(file["hold"], false); + assert_eq!(file["liveVersion"], "0.52.0"); + } +} diff --git a/crates/pyo-verify/src/sys.rs b/crates/pyo-verify/src/sys.rs new file mode 100644 index 00000000..ce428ea2 --- /dev/null +++ b/crates/pyo-verify/src/sys.rs @@ -0,0 +1,388 @@ +//! Everything the verifier touches outside itself, behind small traits: the +//! files (under a root directory), the commands it runs, HTTP, the clock and +//! the hand-over to a new binary. The real ones are below. Tests bring their +//! own, so they need no root, network or k3s. + +use std::{ + io::{self, Read, Write}, + path::{Path, PathBuf}, + process::{Command, Stdio}, +}; + +use crate::{release::ReleaseVerifier, version::Version}; + +/// What went wrong, for the server's owner: one plain line. `detail` is for +/// the journal only and never goes into the status. +#[derive(Debug, Clone, PartialEq)] +pub struct Problem { + pub plain: String, + pub detail: Option, +} + +impl Problem { + pub fn new(plain: impl Into) -> Self { + Problem { + plain: plain.into(), + detail: None, + } + } + + /// With a technical note. It may quote what a server answered, so + /// anything but plain printable text is dropped. + pub fn with(plain: impl Into, detail: impl AsRef) -> Self { + let detail: String = detail + .as_ref() + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .take(400) + .collect(); + Problem { + plain: plain.into(), + detail: Some(detail), + } + } +} + +pub struct CmdOut { + pub ok: bool, + pub stdout: Vec, +} + +/// Runs a program with these arguments, never through a shell. +pub trait Runner { + fn run(&self, argv: &[&str], stdin: Option<&[u8]>) -> io::Result; +} + +pub struct Response { + pub status: u16, + /// Where a 3xx answer points. Never followed by the transport itself. + pub redirect: Option, + pub body: Vec, +} + +#[derive(Debug)] +pub enum HttpError { + /// The answer is longer than `max`. + TooLarge, + Failed(String), +} + +/// One GET, no redirects followed, at most `max` bytes of answer. +pub trait Transport { + fn get(&self, url: &str, max: usize) -> Result; +} + +pub trait Clock { + /// Seconds since 1970. + fn now(&self) -> i64; +} + +/// Replaces this process with another program. The real one only returns +/// when that failed. +pub trait Handover { + fn exec(&self, program: &Path, args: &[&str]) -> io::Result<()>; +} + +pub struct Env<'a> { + /// `/` on a server. Tests use a temporary directory. + pub root: PathBuf, + pub runner: &'a dyn Runner, + pub http: &'a dyn Transport, + pub clock: &'a dyn Clock, + pub handover: &'a dyn Handover, + pub verifier: &'a dyn ReleaseVerifier, + /// This build's version. + pub own: Version, + /// `x86_64` or `aarch64`. + pub arch: &'a str, + /// Where this binary is. Its replacement is written next to it. + pub exe: PathBuf, +} + +impl Env<'_> { + /// An absolute path, under the root. + pub fn path(&self, absolute: &str) -> PathBuf { + self.root.join(absolute.trim_start_matches('/')) + } +} + +/// Writes a file so that it is either the old or the new one, never half. +pub fn write_atomic(path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> { + use std::os::unix::fs::OpenOptionsExt; + let dir = path + .parent() + .ok_or_else(|| io::Error::other("no directory"))?; + std::fs::create_dir_all(dir)?; + let name = path + .file_name() + .ok_or_else(|| io::Error::other("no file name"))? + .to_string_lossy(); + let tmp = dir.join(format!(".{name}.tmp")); + // A fresh file: never written through something left at this name. + let _ = std::fs::remove_file(&tmp); + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(mode) + .open(&tmp)?; + let written = f.write_all(bytes).and_then(|()| f.sync_all()); + if let Err(e) = written.and_then(|()| std::fs::rename(&tmp, path)) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + if let Ok(d) = std::fs::File::open(dir) { + let _ = d.sync_all(); + } + Ok(()) +} + +/// At most `max` bytes of a file. Longer is an error. +pub fn read_limited(path: &Path, max: usize) -> io::Result> { + let mut out = Vec::new(); + std::fs::File::open(path)? + .take(max as u64 + 1) + .read_to_end(&mut out)?; + if out.len() > max { + return Err(io::Error::other("too large")); + } + Ok(out) +} + +pub struct RealRunner; + +impl Runner for RealRunner { + fn run(&self, argv: &[&str], stdin: Option<&[u8]>) -> io::Result { + let (program, args) = argv + .split_first() + .ok_or_else(|| io::Error::other("no program"))?; + let mut child = Command::new(program) + .args(args) + .stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn()?; + if let (Some(bytes), Some(mut pipe)) = (stdin, child.stdin.take()) { + // A program that stops reading early has failed, which its exit + // status says. + let _ = pipe.write_all(bytes); + } + let out = child.wait_with_output()?; + Ok(CmdOut { + ok: out.status.success(), + stdout: out.stdout, + }) + } +} + +/// HTTP through the server's curl, like Pyo's host scripts. +pub struct Curl; + +/// The line curl ends its error output with: the status and the redirect. +const CURL_MARK: &str = "pyo-verify-http "; + +impl Transport for Curl { + fn get(&self, url: &str, max: usize) -> Result { + let proto = if url.starts_with("https://") { + "=https" + } else { + "=http" + }; + let max_arg = max.to_string(); + let agent = format!("pyo-verify/{}", env!("CARGO_PKG_VERSION")); + let write_out = format!("%{{stderr}}\n{CURL_MARK}%{{http_code}} %{{redirect_url}}\n"); + // -q first: no curlrc. No --location: redirects are checked by + // fetch.rs, one at a time. The URL comes after `--`. + let mut child = Command::new("curl") + .args(["-q", "--silent", "--show-error", "--proto", proto]) + .args(["--connect-timeout", "15", "--max-time", "300"]) + .args(["--max-filesize", &max_arg, "--user-agent", &agent]) + .args(["--output", "-", "--write-out", &write_out, "--", url]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| HttpError::Failed(format!("curl did not start: {e}")))?; + // The limit is kept here: curl's own only works when the server says + // the length up front. + let mut body = Vec::new(); + let read = child + .stdout + .take() + .map(|out| out.take(max as u64 + 1).read_to_end(&mut body)); + if body.len() > max { + let _ = child.kill(); + let _ = child.wait(); + return Err(HttpError::TooLarge); + } + let out = child + .wait_with_output() + .map_err(|e| HttpError::Failed(e.to_string()))?; + if !matches!(read, Some(Ok(_))) { + return Err(HttpError::Failed("the answer could not be read".into())); + } + let notes = String::from_utf8_lossy(&out.stderr); + if out.status.code() == Some(63) { + return Err(HttpError::TooLarge); + } + if !out.status.success() { + return Err(HttpError::Failed(format!("curl: {}", notes.trim()))); + } + let line = notes + .lines() + .rev() + .find_map(|l| l.strip_prefix(CURL_MARK)) + .ok_or_else(|| HttpError::Failed("curl gave no status".into()))?; + let (status, redirect) = line.split_once(' ').unwrap_or((line, "")); + Ok(Response { + status: status + .parse() + .map_err(|_| HttpError::Failed("curl gave no status".into()))?, + redirect: Some(redirect.trim().to_owned()).filter(|r| !r.is_empty()), + body, + }) + } +} + +pub struct SystemClock; + +impl Clock for SystemClock { + fn now(&self) -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) + } +} + +pub struct Exec; + +impl Handover for Exec { + fn exec(&self, program: &Path, args: &[&str]) -> io::Result<()> { + use std::os::unix::process::CommandExt; + Err(Command::new(program).args(args).exec()) + } +} + +#[cfg(test)] +mod tests { + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + + use super::*; + + /// A web server on this machine for a few requests: curl for real, but + /// no network. + fn serve(requests: usize) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let own = base.clone(); + std::thread::spawn(move || { + for stream in listener.incoming().take(requests) { + let mut stream = stream.unwrap(); + let mut lines = BufReader::new(stream.try_clone().unwrap()).lines(); + let request = lines.next().unwrap().unwrap(); + for line in lines { + if line.unwrap().is_empty() { + break; + } + } + let path = request.split(' ').nth(1).unwrap().to_owned(); + let answer = match path.as_str() { + "/ok" => { + "HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\nhello" + .to_owned() + } + "/moved" => format!( + "HTTP/1.1 302 Found\r\nLocation: {own}/ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ), + "/missing" => { + "HTTP/1.1 404 Not Found\r\nContent-Length: 2\r\nConnection: close\r\n\r\nno" + .to_owned() + } + // Long, and says so. + "/long" => format!( + "HTTP/1.1 200 OK\r\nContent-Length: 5000\r\nConnection: close\r\n\r\n{}", + "x".repeat(5000) + ), + // Long, without saying so. + _ => format!( + "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{}", + "x".repeat(200_000) + ), + }; + let _ = stream.write_all(answer.as_bytes()); + } + }); + base + } + + #[test] + fn curl_answers_are_read_with_their_status_redirect_and_limit() { + let _alone = crate::testdir::spawning(); + if Command::new("curl").arg("--version").output().is_err() { + eprintln!("no curl here: skipped"); + return; + } + let base = serve(5); + let r = Curl.get(&format!("{base}/ok"), 100).unwrap(); + assert_eq!( + (r.status, r.redirect, r.body.as_slice()), + (200, None, &b"hello"[..]) + ); + // A redirect is reported, not followed. + let r = Curl.get(&format!("{base}/moved"), 100).unwrap(); + assert_eq!(r.status, 302); + assert_eq!(r.redirect, Some(format!("{base}/ok"))); + assert!(r.body.is_empty()); + let r = Curl.get(&format!("{base}/missing"), 100).unwrap(); + assert_eq!(r.status, 404); + // Too long, whether the server says so up front or not. + assert!(matches!( + Curl.get(&format!("{base}/long"), 100), + Err(HttpError::TooLarge) + )); + assert!(matches!( + Curl.get(&format!("{base}/endless"), 100), + Err(HttpError::TooLarge) + )); + // Nobody there. + assert!(matches!( + Curl.get("http://127.0.0.1:1/x", 100), + Err(HttpError::Failed(_)) + )); + } + + #[test] + fn commands_run_without_a_shell() { + let _alone = crate::testdir::spawning(); + let out = RealRunner + .run(&["printf", "%s", "$(id); `id` && x"], None) + .unwrap(); + assert!(out.ok); + assert_eq!(out.stdout, b"$(id); `id` && x"); + let out = RealRunner.run(&["cat"], Some(b"from stdin")).unwrap(); + assert_eq!(out.stdout, b"from stdin"); + assert!(!RealRunner.run(&["false"], None).unwrap().ok); + assert!(RealRunner.run(&["/nonexistent/program"], None).is_err()); + } + + #[test] + fn files_are_replaced_whole() { + let dir = crate::testdir::TestDir::new(); + let path = dir.path().join("a/b/file"); + write_atomic(&path, b"one", 0o644).unwrap(); + write_atomic(&path, b"two", 0o644).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"two"); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + assert_eq!(read_limited(&path, 3).unwrap(), b"two"); + assert!(read_limited(&path, 2).is_err()); + } +} diff --git a/crates/pyo-verify/src/update.rs b/crates/pyo-verify/src/update.rs new file mode 100644 index 00000000..3e810723 --- /dev/null +++ b/crates/pyo-verify/src/update.rs @@ -0,0 +1,105 @@ +//! The verifier replacing itself with the one from a signed release. +//! +//! The new binary is downloaded, held against the SHA-256 in the signed +//! release.json, written next to the current one, asked for its version, +//! and only then renamed over it. The binary it replaces stays as +//! `.previous`. + +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +use crate::{ + fetch::{MAX_BINARY, Source}, + release::platform, + sys::{Env, Problem}, + version::Version, +}; + +fn beside(exe: &Path, suffix: &str) -> PathBuf { + let mut name = exe.file_name().unwrap_or_default().to_os_string(); + name.push(suffix); + exe.with_file_name(name) +} + +/// The binary this one replaced. +pub fn previous(exe: &Path) -> PathBuf { + beside(exe, ".previous") +} + +fn staged(exe: &Path) -> PathBuf { + beside(exe, ".new") +} + +/// Puts release `version`'s verifier in this binary's place. On any error +/// the current binary is untouched. +pub fn replace(env: &Env, source: &Source, version: &Version, sha256: &str) -> Result<(), Problem> { + let file = format!("pyo-verify-{}", platform(env.arch)); + let bytes = source.fetch(env, version, &file, MAX_BINARY)?; + let got = hex::encode(Sha256::digest(&bytes)); + if got != sha256 { + return Err(Problem::with( + format!( + "The verifier of release {version} does not match its signed checksum. Nothing was changed." + ), + format!("sha256 {got}, signed {sha256}"), + )); + } + let new = staged(&env.exe); + let cannot_write = |e: std::io::Error| { + Problem::with( + format!( + "The verifier of release {version} could not be written to this server. Nothing was changed." + ), + e.to_string(), + ) + }; + write_new(&new, &bytes).map_err(cannot_write)?; + // A binary that does not start here, or is another version than its + // release says, never becomes the verifier. + let new_str = new.to_string_lossy(); + let says = env + .runner + .run(&[&new_str, "version"], None) + .ok() + .filter(|o| o.ok) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()); + if says.as_deref() != Some(version.to_string().as_str()) { + let _ = std::fs::remove_file(&new); + return Err(Problem::with( + format!( + "The verifier of release {version} does not run on this server. Nothing was changed." + ), + format!("it answered {says:?}"), + )); + } + let keep = previous(&env.exe); + let _ = std::fs::remove_file(&keep); + let kept = + std::fs::hard_link(&env.exe, &keep).or_else(|_| std::fs::copy(&env.exe, &keep).map(|_| ())); + if let Err(e) = kept.and_then(|()| std::fs::rename(&new, &env.exe)) { + let _ = std::fs::remove_file(&new); + return Err(cannot_write(e)); + } + if let Some(Ok(dir)) = env.exe.parent().map(std::fs::File::open) { + let _ = dir.sync_all(); + } + Ok(()) +} + +fn write_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + use std::{io::Write, os::unix::fs::OpenOptionsExt}; + let _ = std::fs::remove_file(path); + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o755) + .open(path)?; + f.write_all(bytes)?; + f.sync_all() +} + +/// Puts the previous binary back, after a new one that would not start. +pub fn roll_back(env: &Env) -> std::io::Result<()> { + std::fs::rename(previous(&env.exe), &env.exe) +} diff --git a/crates/pyo-verify/src/version.rs b/crates/pyo-verify/src/version.rs new file mode 100644 index 00000000..a28e18f5 --- /dev/null +++ b/crates/pyo-verify/src/version.rs @@ -0,0 +1,149 @@ +//! Release versions as the verifier takes them: `X.Y.Z`, and `X.Y.Z-rc.N` +//! on the rc channel. One spelling per version (no leading zeros), since the +//! version becomes the release tag the signature has to name exactly. + +use std::{cmp::Ordering, fmt}; + +/// Which versions a server takes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Channel { + Stable, + /// Release candidates too: for testing. + Rc, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Version { + major: u32, + minor: u32, + patch: u32, + /// `-rc.N`: before the release of the same numbers. + rc: Option, +} + +/// A number without a sign, spaces or leading zeros. +fn number(s: &str) -> Option { + if s.is_empty() || s.len() > 9 || !s.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + if s.len() > 1 && s.starts_with('0') { + return None; + } + s.parse().ok() +} + +impl Version { + /// `X.Y.Z` or `X.Y.Z-rc.N`, and nothing else. + pub fn parse(s: &str) -> Option { + let (numbers, rc) = match s.split_once('-') { + Some((n, pre)) => (n, Some(number(pre.strip_prefix("rc.")?)?)), + None => (s, None), + }; + let mut parts = numbers.split('.'); + let v = Version { + major: number(parts.next()?)?, + minor: number(parts.next()?)?, + patch: number(parts.next()?)?, + rc, + }; + parts.next().is_none().then_some(v) + } + + pub fn is_rc(&self) -> bool { + self.rc.is_some() + } + + /// This build's own version. + pub fn own() -> Version { + Version::parse(env!("CARGO_PKG_VERSION")).expect("the crate's version is X.Y.Z") + } + + fn key(&self) -> (u32, u32, u32, u64) { + ( + self.major, + self.minor, + self.patch, + self.rc.map_or(u64::MAX, u64::from), + ) + } +} + +impl Ord for Version { + fn cmp(&self, other: &Self) -> Ordering { + self.key().cmp(&other.key()) + } +} + +impl PartialOrd for Version { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl fmt::Display for Version { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?; + match self.rc { + Some(n) => write!(f, "-rc.{n}"), + None => Ok(()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(s: &str) -> Version { + Version::parse(s).unwrap() + } + + #[test] + fn only_plain_versions_parse() { + for ok in ["0.51.0", "1.2.3", "10.20.30", "0.51.0-rc.1", "0.0.0"] { + assert_eq!(v(ok).to_string(), ok); + } + for bad in [ + "", + "0.51", + "0.51.0.1", + "v0.51.0", + "0.51.0 ", + " 0.51.0", + "0.51.0\n", + "00.51.0", + "0.051.0", + "0.51.0-rc1", + "0.51.0-rc.", + "0.51.0-rc.01", + "0.51.0-beta.1", + "0.51.0-rc.1-rc.2", + "0.51.0+build", + "0.51.x", + "-1.0.0", + "+1.0.0", + "0.51.0/../x", + "1.2.3; rm -rf /", + "99999999999.0.0", + "٠.٥١.٠", + ] { + assert!(Version::parse(bad).is_none(), "{bad:?}"); + } + } + + #[test] + fn versions_order_by_number_and_rc_comes_first() { + assert!(v("0.51.0") > v("0.5.5")); + assert!(v("0.52.0") > v("0.51.9")); + assert!(v("1.0.0") > v("0.99.99")); + assert!(v("0.51.0") > v("0.51.0-rc.9")); + assert!(v("0.51.0-rc.2") > v("0.51.0-rc.1")); + assert!(v("0.51.0-rc.1") > v("0.50.9")); + assert_eq!(v("0.51.0"), v("0.51.0")); + } + + #[test] + fn this_build_has_a_version() { + assert_eq!(Version::own().to_string(), env!("CARGO_PKG_VERSION")); + } +} diff --git a/dash/src/components/pyo/AddDomainDialog.tsx b/dash/src/components/pyo/AddDomainDialog.tsx index 0ee9ecf2..f0bf7c37 100644 --- a/dash/src/components/pyo/AddDomainDialog.tsx +++ b/dash/src/components/pyo/AddDomainDialog.tsx @@ -9,6 +9,7 @@ import { import { CloudflareFields, useCloudflareFor, + useTunnelChoice, type CloudflareChoice, } from "~/components/pyo/Cloudflare"; import { SetUpTailscaleLink } from "~/components/pyo/Tailscale"; @@ -26,6 +27,8 @@ import { import { HOSTNAME } from "~/lib/pyo/format"; import { clusterTailnet, + freeDomainNoun, + freeSuffix, hostnameUsed, unusedHostname, } from "~/lib/pyo/freeDomain"; @@ -43,7 +46,7 @@ type Kind = "own" | "public" | "tailnet"; const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/; /** - * Add a domain: your own, a free one or a Tailscale one, its hostname, the service it routes to (asked when it isn't + * Add a domain: your own, a free one (a tunnel one in tunnel mode) or a Tailscale one, its hostname, the service it routes to (asked when it isn't * given, e.g. from the team's Domains page), the port when there's a * choice, and how HTTPS works. */ @@ -90,19 +93,30 @@ export function AddDomainDialog({ const port = portName || httpPorts[0]?.name || ""; const cluster = s.clusters.find((c) => c.id === app?.clusterId); // Free domains go on the public IP, whatever the cluster's free domains - // use by default: traffic goes straight to its servers. + // use by default: traffic goes straight to its servers. In tunnel mode, + // under the tunnel's default domain. + const tunnelMode = cluster?.traffic === "tunnel"; + // Before a service is picked: by the clusters it could be on. + const freeNoun = freeDomainNoun( + cluster + ? [cluster] + : [...new Set(usable.map((x) => x.a.clusterId))].map((id) => + s.clusters.find((c) => c.id === id), + ), + ); const freeIp = cluster?.publicIp ?? undefined; + const freeEnd = app ? freeSuffix(s, app.clusterId) : undefined; const tailnet = app ? clusterTailnet(s, app.clusterId) : undefined; const namespace = s.projects.find((p) => p.id === app?.projectId)?.namespace ?? "app"; // Picked, but the service's cluster has none: a note says why. const missing = !!app && - ((kind === "public" && !freeIp) || (kind === "tailnet" && !tailnet)); + ((kind === "public" && !freeEnd) || (kind === "tailnet" && !tailnet)); // No service yet: only your own domain, the free ones are named after it. const k: Kind = app ? kind : "own"; const suffix = - k === "public" ? `${freeIp}.nip.io` : k === "tailnet" ? tailnet : ""; + k === "public" ? freeEnd : k === "tailnet" ? tailnet : ""; const suggested = !app || k === "own" || missing ? "" @@ -118,6 +132,12 @@ export function AddDomainDialog({ k === "own" ? hostname : "", app?.clusterId, ); + // Through the cluster's Cloudflare Tunnel instead of a direct record. + const viaTunnel = useTunnelChoice( + k === "own" && HOSTNAME.test(hostname) ? hostname : "", + app?.clusterId, + cf, + ).on; const matching = s.certificates.filter( (c) => c.teamId === (app?.teamId ?? s.currentTeamId) && @@ -170,9 +190,13 @@ export function AddDomainDialog({ ? { certificateId: cert.id } : {}), }, - k === "own" && inCloudflare && cf.create - ? { proxied: cf.proxied } - : undefined, + k !== "own" + ? undefined + : viaTunnel + ? { tunnel: true } + : inCloudflare && cf.create + ? { proxied: cf.proxied } + : undefined, ); toast({ title: fixed @@ -180,7 +204,7 @@ export function AddDomainDialog({ : `Added ${hostname} to ${app.name}`, description: !app.currentDeploymentId ? "Live after the first deploy." - : k !== "own" || (inCloudflare && cf.create) + : k !== "own" || viaTunnel || (inCloudflare && cf.create) ? undefined : "Create the DNS record, then check DNS.", }); @@ -236,8 +260,14 @@ export function AddDomainDialog({ onSelect={() => setKind("own")} /> { @@ -268,6 +298,16 @@ export function AddDomainDialog({ ) + ) : tunnelMode ? ( + <> + Pick a default domain first.{" "} + + Cluster settings + + ) : cluster.publicTraffic === false ? ( <> Public traffic is off on {cluster.name}.{" "} @@ -290,7 +330,9 @@ export function AddDomainDialog({ error={touched ? error || undefined : undefined} hint={ k === "public" - ? cluster?.behindNat + ? tunnelMode + ? "Through Cloudflare Tunnel. No DNS needed." + : cluster?.behindNat ? `Points at ${freeIp}. Forward ports 80 and 443 to the server.` : `Points at ${freeIp}. No DNS needed.` : k === "tailnet" @@ -334,6 +376,7 @@ export function AddDomainDialog({ clusterId={app?.clusterId} value={cf} onChange={setCf} + tunnel /> ) : null} {httpPorts.length > 1 ? ( diff --git a/dash/src/components/pyo/AgentInstall.tsx b/dash/src/components/pyo/AgentInstall.tsx index f8687de7..920677a6 100644 --- a/dash/src/components/pyo/AgentInstall.tsx +++ b/dash/src/components/pyo/AgentInstall.tsx @@ -1,7 +1,7 @@ import { useState } from "react"; import { Button } from "~/components/ui/Button"; import { Dialog } from "~/components/ui/Dialog"; -import { Segmented } from "~/components/ui/Field"; +import { Checkbox, Segmented } from "~/components/ui/Field"; import { useHosted } from "~/components/pyo/Managed"; import { api, usePyo } from "~/lib/pyo/store"; import type { Cluster } from "~/lib/pyo/types"; @@ -26,6 +26,36 @@ export function Command({ value }: { value: string }) { ); } +// The flag a hosted Pyo's commands carry, and the one that leaves +// automatic updates out. +const AUTO_UPDATE = /(^| )--auto-update(?= |$)/; + +/** `command` with automatic updates kept or left out. */ +export function withAutoUpdate(command: string, keep: boolean) { + return keep ? command : command.replace(AUTO_UPDATE, "$1--no-auto-update"); +} + +/** + * The choice to keep a cluster up to date automatically, on a hosted Pyo + * whose command offers it: the command as chosen, and its checkbox (null + * anywhere else). It only changes the command shown. Pyo keeps no setting. + */ +export function useAutoUpdate(command: string) { + const hosted = useHosted(); + const [keep, setKeep] = useState(true); + const offered = hosted === true && AUTO_UPDATE.test(command); + return { + command: offered ? withAutoUpdate(command, keep) : command, + checkbox: offered ? ( + + ) : null, + }; +} + /** * The one command that sets up a cluster: it installs k3s on the machine if * it isn't there, then the Pyo agent. The token in it works once, for an @@ -45,9 +75,11 @@ export function AgentInstall({ thisMachine?: boolean; }) { const [kubectl, setKubectl] = useState(false); + const auto = useAutoUpdate(command); return (
- + {auto.checkbox} +

Works once, for an hour {thisMachine ? null : " · "} diff --git a/dash/src/components/pyo/Certificates.tsx b/dash/src/components/pyo/Certificates.tsx index a7de8e1f..95995cc8 100644 --- a/dash/src/components/pyo/Certificates.tsx +++ b/dash/src/components/pyo/Certificates.tsx @@ -15,7 +15,7 @@ import { Button } from "~/components/ui/Button"; import { ConfirmDialog, Dialog } from "~/components/ui/Dialog"; import { Field, Input, Textarea } from "~/components/ui/Field"; import { Menu } from "~/components/ui/Menu"; -import { EmptyState, Panel } from "~/components/ui/Panel"; +import { EmptyState, PageHeader, Panel } from "~/components/ui/Panel"; import { api, usePyo } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; import { isPrivateHost, isTailnetDomain } from "~/lib/pyo/freeDomain"; @@ -250,20 +250,20 @@ export function CertificatesList() { .map((d) => d.hostname), ); - const upload = (variant: "primary" | "secondary" = "secondary") => ( - - ); + const upload = () => setUploading(true); return ( <> -

-

- Your own certificates. Let's Encrypt is automatic. -

- {certs.length ? upload() : null} -
+ + Upload certificate + + ) : undefined + } + /> {certs.length ? (
    @@ -319,11 +319,14 @@ export function CertificatesList() {
) : ( + Upload certificate + + } /> )} void }) {
{editable.map((z) => ( - + {z.name} + {zoneNote(z)} ))} {lacking.map((z) => ( @@ -141,7 +150,7 @@ export function CloudflareDialog({ onClose }: { onClose: () => void }) {
{(p) => ( @@ -232,31 +241,98 @@ export function CloudflareDialog({ onClose }: { onClose: () => void }) { }); } -/** What to do about a new domain's DNS record in Cloudflare. */ -export type CloudflareChoice = { create: boolean; proxied: boolean }; +/** A zone's tunnel state on its badge: ready, DNS only, or the one permission it lacks. */ +function zoneTone(z: CloudflareZone): "success" | "warning" | undefined { + if (z.tunnel?.ready) return "success"; + return z.tunnel?.missing?.length === 1 ? "warning" : undefined; +} + +function zoneNote(z: CloudflareZone): string { + if (z.tunnel?.ready) return ""; + const missing = z.tunnel?.missing ?? []; + return missing.length === 1 ? ` · needs ${missing[0]}` : " · DNS only"; +} + +/** + * What to do about a new domain's DNS record in Cloudflare. `tunnel`: + * through the cluster's tunnel (unset: on in tunnel mode). + */ +export type CloudflareChoice = { create: boolean; proxied: boolean; tunnel?: boolean }; + +/** The tunnel-ready zone a new domain can use, and whether it goes through the tunnel. */ +export function useTunnelChoice( + hostname: string, + clusterId: string | undefined, + value: CloudflareChoice, +) { + const s = usePyo(); + const cluster = s.clusters.find((c) => c.id === clusterId); + const zone = + hostname && !isFreeDomain(hostname) + ? tunnelZoneFor(s, hostname, cluster) + : undefined; + const on = + !!zone && + (value.tunnel ?? (!!cluster && clusterTraffic(cluster) === "tunnel")); + return { zone, on }; +} /** * "Create the DNS record in Cloudflare" and "Proxied by Cloudflare", when a - * connected zone covers the hostname. Nothing otherwise. + * connected zone covers the hostname. Nothing otherwise. With `tunnel`, a + * tunnel-ready zone offers "Through Cloudflare Tunnel" first. */ export function CloudflareFields({ hostname, clusterId, value, onChange, + tunnel, }: { hostname: string; clusterId?: string; value: CloudflareChoice; onChange: (v: CloudflareChoice) => void; + /** Offer the cluster's tunnel (the caller switches the domain to it). */ + tunnel?: boolean; }) { const s = usePyo(); const zone = cloudflareZoneFor(s, hostname); + const choice = useTunnelChoice(tunnel ? hostname : "", clusterId, value); if (!zone || !hostname || isFreeDomain(hostname)) return null; const ip = s.clusters.find((c) => c.id === clusterId)?.publicIp; - const usable = zone.canEdit && !!ip; return (
+ {choice.zone ? ( + onChange({ ...value, tunnel: on })} + label="Through Cloudflare Tunnel" + description={`CNAME to the tunnel in ${choice.zone.name}`} + /> + ) : null} + {choice.on ? null : ( + + )} +
+ ); +} + +/** A direct A record: create it, and proxied or not. */ +function DirectRecordFields({ + zone, + ip, + value, + onChange, +}: { + zone: CloudflareZone; + ip?: string | null; + value: CloudflareChoice; + onChange: (v: CloudflareChoice) => void; +}) { + const usable = zone.canEdit && !!ip; + return ( + <> ) : null} -
+ ); } @@ -294,8 +370,42 @@ export function useCloudflareFor(hostname: string, clusterId?: string) { return !!zone?.canEdit && !!ip && !isFreeDomain(hostname); } -/** A domain's record in Cloudflare on the service's Domains: how it stands, and what to do. */ +/** + * A domain's record in Cloudflare on the service's Domains: how it stands, + * and what to do. Through the cluster's tunnel or not. + */ export function DnsRecordLine({ app, d }: { app: Application; d: Domain }) { + const s = usePyo(); + const cluster = s.clusters.find((c) => c.id === app.clusterId); + if (onTunnel(d)) return ; + const tunnelMode = !!cluster && clusterTraffic(cluster) === "tunnel"; + const zone = isFreeDomain(d.hostname) + ? undefined + : tunnelZoneFor(s, d.hostname, cluster); + if (tunnelMode && !zone && !isTailnetDomain(d.hostname)) + return ; + const r = d.dnsRecord; + const direct = ; + if (!zone || (r && !["created", "exists"].includes(r.status))) return direct; + return ( +
+ {direct} + +
+ ); +} + +/** A direct record: created, already there, in the way, or failed. */ +function DirectRecordLine({ + app, + d, + noCreate, +}: { + app: Application; + d: Domain; + /** No "Create in Cloudflare": the cluster takes no direct web traffic. */ + noCreate: boolean; +}) { const s = usePyo(); const r = d.dnsRecord; const admin = isAdmin(roleIn(s)); @@ -311,7 +421,12 @@ export function DnsRecordLine({ app, d }: { app: Application; d: Domain }) { }; if (!r) { // None yet: offer it while the domain waits for DNS. - if (!zone?.canEdit || d.status === "active" || isFreeDomain(d.hostname)) + if ( + noCreate || + !zone?.canEdit || + d.status === "active" || + isFreeDomain(d.hostname) + ) return null; return ( - ); + const create = () => setCreating(true); return ( -
-
-

- Accept traffic only from your CDN. Set per cluster. -

- {certs.length ? add() : null} -
+ <> + + Create certificate + + ) : undefined + } + /> {certs.length ? (
    @@ -689,11 +689,14 @@ export function OriginPullCertificates() {
) : ( + Create certificate + + } /> )}
@@ -713,6 +716,6 @@ export function OriginPullCertificates() { if (removing) void api.removeOriginPullCertificate(removing.id); }} /> -
+ ); } diff --git a/dash/src/components/pyo/ProjectDialog.tsx b/dash/src/components/pyo/ProjectDialog.tsx index 81175a60..ea44eed2 100644 --- a/dash/src/components/pyo/ProjectDialog.tsx +++ b/dash/src/components/pyo/ProjectDialog.tsx @@ -7,6 +7,7 @@ import { Field, Input } from "~/components/ui/Field"; import { DNS_LABEL, slugify } from "~/lib/pyo/format"; import { api, projectsIn, usePyo, projectParams } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; +import { useHeld } from "~/lib/pyo/useHeld"; import type { Project } from "~/lib/pyo/types"; import { currentSlug } from "~/lib/pyo/paths"; @@ -25,10 +26,14 @@ export function useProjectForm(project?: Project) { const [nsEdited, setNsEdited] = useState(!!project); const [description, setDescription] = useState(project?.description ?? ""); const [touched, setTouched] = useState(false); + // Once it has made its project, which is in the store at once: the checks + // stay as they were, so it doesn't read as taking its own name while the + // page moves on. + const [made, setMade] = useState(false); const others = projectsIn(s).filter((p) => p.id !== project?.id); const ns = nsEdited ? namespace : slugify(name); - const errors = { + const live = { name: !name.trim() ? "Name is required." : name.trim().length > 48 @@ -48,7 +53,8 @@ export function useProjectForm(project?: Project) { ? "Another project already uses this name." : "", }; - const valid = !errors.name && !errors.namespace; + const errors = useHeld(live, made); + const valid = !made && !errors.name && !errors.namespace; return { name, setName, @@ -61,6 +67,8 @@ export function useProjectForm(project?: Project) { setDescription, touched, setTouched, + created: () => setMade(true), + reset: () => setMade(false), errors, valid, }; @@ -134,6 +142,7 @@ export function ProjectDialog({ f.setName(project?.name ?? ""); f.setDescription(project?.description ?? ""); f.setTouched(false); + f.reset(); // Reset when reopened. // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]); @@ -160,6 +169,7 @@ export function ProjectDialog({ description: f.description, namespace: f.namespace, }); + f.created(); toast({ title: `Project ${f.name.trim()} created` }); onClose(); void navigate({ diff --git a/dash/src/components/pyo/TrafficMode.tsx b/dash/src/components/pyo/TrafficMode.tsx index c138a9ac..3be60529 100644 --- a/dash/src/components/pyo/TrafficMode.tsx +++ b/dash/src/components/pyo/TrafficMode.tsx @@ -1,9 +1,11 @@ +import { useState, type ReactNode } from "react"; +import { TunnelSettings, tunnelUnavailable } from "~/components/pyo/Tunnel"; import { LearnMore } from "~/components/ui/LearnMore"; import { optionClass, Switch } from "~/components/ui/Field"; import { Panel } from "~/components/ui/Panel"; -import { api } from "~/lib/pyo/store"; +import { api, clusterTraffic, usePyo } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; -import type { Cluster, TrafficMode } from "~/lib/pyo/types"; +import type { Cluster, ClusterTraffic as Traffic, TrafficMode } from "~/lib/pyo/types"; // How a cluster routes requests. Replicas are placed the same way in every // mode (evenly across regions, then servers); this only changes where each @@ -15,6 +17,42 @@ const MODES: { value: TrafficMode; label: string; hint: string }[] = [ { value: "spread", label: "Global", hint: "Distribute traffic across all servers" }, ]; +/** One choice of a radio group panel: a label and a hint line. */ +function RadioOption({ + name, + checked, + disabled, + label, + hint, + onSelect, +}: { + name: string; + checked: boolean; + disabled: boolean; + label: string; + hint: ReactNode; + onSelect: () => void; +}) { + return ( + + ); +} + export function ClusterTrafficMode({ cluster: c }: { cluster: Cluster }) { const capable = !!c.capabilities.trafficModes; const current = c.trafficMode ?? "region"; @@ -28,28 +66,18 @@ export function ClusterTrafficMode({ cluster: c }: { cluster: Cluster }) { className="space-y-2 p-4" > {MODES.map((m) => ( - + name={`traffic-${c.id}`} + checked={current === m.value} + disabled={off(m.value)} + label={m.label} + hint={capable && off(m.value) ? "Not reported yet." : m.hint} + onSelect={async () => { + const res = await api.setClusterTrafficMode(c.id, m.value); + if (res?.ok) toast({ title: m.label, description: c.name }); + }} + /> ))}
@@ -73,36 +101,58 @@ export function ClusterTrafficMode({ cluster: c }: { cluster: Cluster }) { ); } -/** Whether the gateway answers public traffic on the cluster's servers. */ -export function ClusterPublicTraffic({ cluster: c }: { cluster: Cluster }) { - const on = c.publicTraffic !== false; - const mode = c.freeDomainAddress ?? "public"; +const TRAFFIC: { value: Traffic; label: string }[] = [ + { value: "public", label: "Public ports" }, + { value: "tailscale", label: "Tailscale only" }, + { value: "tunnel", label: "Cloudflare Tunnel" }, +]; + +/** How the cluster takes web traffic: public ports, only the tailnet, or Cloudflare Tunnel. */ +export function ClusterTraffic({ cluster: c }: { cluster: Cluster }) { + const s = usePyo(); + const current = clusterTraffic(c); + // Cloudflare Tunnel waits for its settings and a confirm before it applies. + const [picked, setPicked] = useState(null); + const shown = picked ?? current; + const unavailable = current === "tunnel" ? null : tunnelUnavailable(s, c); + const hint = (m: Traffic) => + m === "public" + ? "Ports 80 and 443 on every server except build-only servers." + : m === "tailscale" + ? c.tailnet || c.tailscale + ? "Only from your tailnet." + : "Only inside the cluster until you set up Tailscale." + : (unavailable ?? "No open ports. Websites come in through Cloudflare."); + const pick = async (m: Traffic) => { + if (m === "tunnel" && current !== "tunnel") return setPicked(m); + setPicked(null); + if (m === current) return; + const res = await api.setClusterTraffic(c.id, m); + if (res?.ok) + toast({ title: TRAFFIC.find((x) => x.value === m)!.label, description: c.name }); + }; return ( - -
- { - const res = await api.setClusterPublicTraffic(c.id, v); - if (res?.ok) - toast({ - title: v ? "Public traffic on" : "Public traffic off", - description: c.name, - }); - }} - label="Accept public traffic" - description={ - <> - {on - ? "On every server except build-only servers." - : mode === "tailscale" - ? "Services are reachable only from your tailnet." - : "Services are reachable only inside the cluster."}{" "} - - - } - /> + }> +
+ {TRAFFIC.map((m) => ( + void pick(m.value)} + /> + ))}
+ {shown === "tunnel" || c.tunnel ? ( + setPicked(null)} + /> + ) : null}
); } diff --git a/dash/src/components/pyo/Tunnel.tsx b/dash/src/components/pyo/Tunnel.tsx new file mode 100644 index 00000000..49a548da --- /dev/null +++ b/dash/src/components/pyo/Tunnel.tsx @@ -0,0 +1,368 @@ +import { useState } from "react"; +import { Badge, Dot, type Tone } from "~/components/ui/Badge"; +import { Button } from "~/components/ui/Button"; +import { ConfirmDialog } from "~/components/ui/Dialog"; +import { Field, Select, Switch } from "~/components/ui/Field"; +import { plural } from "~/lib/pyo/format"; +import { isTailnetDomain } from "~/lib/pyo/freeDomain"; +import { + api, + cloudflareIn, + cloudflareZoneFor, + clusterTraffic, + listedServices, + usePyo, + type PyoState, +} from "~/lib/pyo/store"; +import { toast } from "~/lib/pyo/toast"; +import type { Cluster, ClusterTunnel } from "~/lib/pyo/types"; + +// A cluster's Cloudflare Tunnel: its settings in the Traffic panel, its +// health, its badge in the cluster list and its removal. + +/** Why the cluster can't use a tunnel yet, or null when it can. */ +export function tunnelUnavailable(s: PyoState, c: Cluster): string | null { + const account = cloudflareIn(s, c.teamId); + if (!account) return "Connect Cloudflare first."; + if (!account.zones.some((z) => z.tunnel?.ready)) + return "Give the token Cloudflare Tunnel:Edit."; + if (c.capabilities.tunnel !== true) return "Not reported yet."; + return null; +} + +/** "a", "a and b", "a, b and c". */ +const list = (xs: string[]) => + xs.length < 2 ? xs.join("") : `${xs.slice(0, -1).join(", ")} and ${xs.at(-1)}`; + +/** The tunnel's health as one line. */ +function healthLine(t: ClusterTunnel): { tone: Tone; text: string } { + const ready = t.connectors.filter((x) => x.ready).length; + if (t.state === "failed") + return { tone: "danger", text: `Cloudflare: ${t.error ?? "the tunnel wasn't made."}` }; + switch (t.health) { + case "connected": + return { + tone: "success", + text: ["Tunnel connected", plural(ready, "connector"), t.colos.join(", ")] + .filter(Boolean) + .join(" · "), + }; + case "degraded": + return { + tone: "warning", + text: `Tunnel degraded · ${ready} of ${plural(t.connectors.length, "connector")}`, + }; + case "down": + return { tone: "danger", text: "Tunnel down. Its websites don't answer." }; + case "starting": + return { tone: "progress", text: "Starting the tunnel…" }; + case "removing": + return { tone: "progress", text: "Removing the tunnel…" }; + default: + return { tone: "neutral", text: "Pyo can't reach Cloudflare. Websites keep working." }; + } +} + +/** The tunnel's status line, and the lines that say what's wrong. */ +export function TunnelStatus({ c }: { c: Cluster }) { + const s = usePyo(); + const t = c.tunnel; + if (!t) return null; + const line = healthLine(t); + const notes = [ + ...t.connectors + .filter((x) => !x.ready && x.reason) + .map((x) => `pyo-tunnel can't start on ${x.server}: ${x.reason}`), + t.state !== "failed" && t.error + ? t.error + : !cloudflareIn(s, c.teamId) + ? "Connect Cloudflare again to change the tunnel." + : null, + t.refused + ? "Run the command under Refresh this cluster in the cluster's settings." + : null, + ].filter((x): x is string => !!x); + return ( +
+

+ + {line.text} +

+ {notes.map((n) => ( +

+ {n} +

+ ))} +
+ ); +} + +/** "Tunnel" beside a cluster in tunnel mode, warning tone while it's degraded or down. */ +export function TunnelBadge({ c, className }: { c: Cluster; className?: string }) { + if (clusterTraffic(c) !== "tunnel") return null; + const bad = c.tunnel?.health === "degraded" || c.tunnel?.health === "down"; + return ( + + Tunnel + + ); +} + +/** + * The Traffic panel's tunnel part: its settings while Cloudflare Tunnel is + * picked, its status and Rotate while it has one. + */ +export function TunnelSettings({ + c, + editing, + onCancel, +}: { + c: Cluster; + /** Cloudflare Tunnel is picked. */ + editing: boolean; + onCancel: () => void; +}) { + const s = usePyo(); + const t = c.tunnel && c.tunnel.state !== "removing" ? c.tunnel : null; + const zones = (cloudflareIn(s, c.teamId)?.zones ?? []).filter( + (z) => z.tunnel?.ready && z.accountId, + ); + const accounts = [...new Map(zones.map((z) => [z.accountId!, z.accountName ?? z.accountId!]))]; + const [picked, setAccount] = useState(""); + // The tunnel's own account, as picked, or the first one. + const account = t?.accountId ?? (picked || zones[0]?.accountId || ""); + const [domain, setDomain] = useState(t?.defaultDomain ?? ""); + const [ports, setPorts] = useState(t?.portsPublic ?? true); + const [confirm, setConfirm] = useState<"switch" | "rotate" | null>(null); + const inTunnel = clusterTraffic(c) === "tunnel"; + const install = c.capabilities.agentInstall; + const outdated = !!install && install.state !== "current"; + const services = listedServices(s).filter((a) => a.clusterId === c.id); + const hasPorts = services.some((a) => + a.ports.some( + (p) => p.protocol !== "HTTP" && (p.exposure === "loadbalancer" || p.exposure === "nodeport"), + ), + ); + const dirty = + !inTunnel || + domain !== (t?.defaultDomain ?? "") || + ports !== (t?.portsPublic ?? true) || + (!!account && account !== t?.accountId); + + // What the switch does, for its confirm dialog. + const domains = services + .flatMap((a) => a.domains) + .filter((d) => !isTailnetDomain(d.hostname)); + const zoneOf = (host: string) => { + const z = cloudflareZoneFor(s, host, c.teamId); + return z?.tunnel?.ready && z.accountId === account ? z.name : undefined; + }; + const moving = [...new Set(domains.map((d) => zoneOf(d.hostname)).filter((z): z is string => !!z))]; + // Free nip.io domains: no public ports, so they stop answering too. + const nip = domains.filter((d) => /\.nip\.io$/i.test(d.hostname)).length; + const outside = domains.filter((d) => !zoneOf(d.hostname) && !/\.nip\.io$/i.test(d.hostname)).length; + const lines = [ + moving.length + ? `Websites on ${list(moving)} move to the tunnel. Records Pyo didn't make wait for your OK.` + : null, + outside === 1 + ? "1 domain isn't in your Cloudflare account. It stops answering from the internet." + : outside + ? `${outside} domains aren't in your Cloudflare account. They stop answering from the internet.` + : null, + nip === 1 + ? "1 free domain stops answering from the internet." + : nip + ? `${nip} free domains stop answering from the internet.` + : null, + c.sameCluster + ? "The public dashboard closes. Open Pyo through Tailscale or your local network." + : null, + ].filter((x): x is string => !!x); + + const save = async () => { + const res = await api.setClusterTraffic(c.id, "tunnel", { + defaultDomain: domain || null, + accountId: account || undefined, + portsPublic: ports, + }); + if (res?.ok) + toast({ + title: inTunnel ? "Tunnel saved" : "Cloudflare Tunnel", + description: res.moving ? `${plural(res.moving, "domain")} moving` : c.name, + }); + }; + + return ( + <> + {editing ? ( +
+ {accounts.length > 1 && !t ? ( + + {(p) => ( + + )} + + ) : null} + + {(p) => ( + + )} + + {hasPorts ? ( + + ) : null} + {outdated ? ( +

+ {install?.state === "updating" + ? "This cluster is updating. Try again in a few minutes." + : "Run the command under Refresh this cluster in the cluster's settings first."} +

+ ) : null} +
+ ) : null} + {c.tunnel ? ( +
+ +
+ ) : null} + {t || (editing && dirty) ? ( +
+ {t ? ( + + ) : null} + {editing && !inTunnel ? ( + + ) : null} + {editing && dirty ? ( + + ) : null} +
+ ) : null} + setConfirm(null)} + tone="primary" + title={`Switch ${c.name} to Cloudflare Tunnel?`} + description={ + lines.length ? ( +
+ {lines.map((l) => ( +

{l}

+ ))} +
+ ) : null + } + confirmLabel="Switch" + onConfirm={() => void save()} + /> + setConfirm(null)} + tone="primary" + title={`Rotate the tunnel token of ${c.name}?`} + description="The tunnel gets a new token and certificate, and reconnects." + confirmLabel="Rotate" + onConfirm={() => + void api.rotateTunnelToken(c.id).then((r) => { + if (r?.ok) toast({ title: "Tunnel token rotated", description: c.name }); + }) + } + /> + + ); +} + +/** Danger zone: remove the tunnel of a cluster that's no longer in tunnel mode. */ +export function RemoveTunnelRow({ c }: { c: Cluster }) { + const [open, setOpen] = useState(false); + const [restore, setRestore] = useState(true); + if (!c.tunnel || clusterTraffic(c) === "tunnel") return null; + const removing = c.tunnel.state === "removing"; + return ( +
  • +
    +

    Remove tunnel

    +

    + {removing ? "Removing…" : c.tunnel.tunnelName} +

    +
    + + setOpen(false)} + title={`Remove the tunnel of ${c.name}?`} + description="Pyo deletes the DNS records it made for it." + confirmLabel="Remove tunnel" + onConfirm={() => + void api.removeClusterTunnel(c.id, restore).then((r) => { + if (r?.ok) toast({ title: "Removing the tunnel", description: c.name }); + }) + } + > + + +
  • + ); +} diff --git a/dash/src/components/pyo/TunnelRecord.tsx b/dash/src/components/pyo/TunnelRecord.tsx new file mode 100644 index 00000000..302250d6 --- /dev/null +++ b/dash/src/components/pyo/TunnelRecord.tsx @@ -0,0 +1,247 @@ +import { useState } from "react"; +import { BrandMark, CLOUDFLARE_LOGO } from "~/components/pyo/common"; +import { Button } from "~/components/ui/Button"; +import { ConfirmDialog } from "~/components/ui/Dialog"; +import { Switch } from "~/components/ui/Field"; +import { api, cloudflareZoneFor, clusterTraffic, roleIn, usePyo } from "~/lib/pyo/store"; +import type { Application, Cluster, Domain, PreviousRecord } from "~/lib/pyo/types"; + +// A domain's side of the cluster's Cloudflare Tunnel on the service's +// Domains: switching to it and back, and what's in the way. + +const isAdmin = (role?: string) => role === "owner" || role === "admin"; + +/** The domain is through the tunnel, or on its way there or back. */ +export const onTunnel = (d: Domain) => + !!d.tunnel || + d.dnsRecord?.via === "tunnel" || + d.dnsRecord?.status === "switching" || + d.dnsRecord?.status === "reverting"; + +/** + * The tunnel's default domain when it covers the name (one label under + * it). Such a name always goes through the tunnel, so there's no Switch back. + */ +export const defaultDomainOver = (c: Cluster | undefined, hostname: string) => { + const dd = c?.tunnel?.defaultDomain?.toLowerCase(); + const host = hostname.toLowerCase(); + if (!dd || !host.endsWith(`.${dd}`)) return undefined; + return host.slice(0, -dd.length - 1).includes(".") ? undefined : dd; +}; + +/** "1f2e….cfargotunnel.com" for the tunnel's long id. */ +const shortTarget = (content: string) => { + const m = /^([^.]+)\.cfargotunnel\.com\.?$/.exec(content); + return m ? `${m[1].slice(0, 4)}….cfargotunnel.com` : content; +}; + +const recordText = (p: PreviousRecord) => `${p.type} ${p.name} ${p.content}`; + +/** Through the tunnel or on its way there or back: a record in the way or a failed switch alone isn't. */ +export const throughTunnel = (d: Domain) => + !!d.tunnel || + d.dnsRecord?.status === "switching" || + d.dnsRecord?.status === "reverting" || + (d.dnsRecord?.via === "tunnel" && + (d.dnsRecord.status === "created" || d.dnsRecord.status === "exists")); + +/** + * What a settled tunnel domain says when there's nothing to do, for the + * logo's tooltip: the wildcard or record it goes through. None while + * TunnelRecordLine has something to show. + */ +export function tunnelNote( + d: Domain, + cluster: Cluster | undefined, + admin: boolean, +): { name: string; more?: string } | undefined { + const r = d.dnsRecord; + const wildcard = defaultDomainOver(cluster, d.hostname); + if (!r) return d.tunnel === "on" && wildcard ? { name: `*.${wildcard}` } : undefined; + if (r.error || (r.status !== "created" && r.status !== "exists")) return undefined; + const name = `${r.type} ${shortTarget(r.content)}`; + const kept = r.previous?.length ?? 0; + if (wildcard && !kept) return { name }; + // Switch back is a button: the line stays. + return kept && !admin ? { name, more: "An owner or admin can switch it back." } : undefined; +} + +const lineClass = + "mt-1.5 inline-flex flex-wrap items-center gap-1.5 text-[12px] text-muted-foreground"; + +/** Switching, in the way, failed, or with a Switch back. Nothing for a settled one with nothing to do. */ +export function TunnelRecordLine({ app, d }: { app: Application; d: Domain }) { + const s = usePyo(); + const r = d.dnsRecord; + const admin = isAdmin(roleIn(s)); + const cluster = s.clusters.find((c) => c.id === app.clusterId); + const [busy, setBusy] = useState(false); + const [confirming, setConfirming] = useState(false); + const run = async (opts: { on: boolean; replace?: boolean; restore?: boolean }) => { + setBusy(true); + await api.setDomainTunnel(app.id, d.id, opts); + setBusy(false); + }; + const back = r?.status === "reverting"; + const wildcard = defaultDomainOver(cluster, d.hostname); + + if (r?.status === "conflict") + return ( +
    +

    Cloudflare has a record for {d.hostname}:

    + {r.existing.map((x) => ( +
    + {x.type} + {x.name} + {x.content} + {x.proxied ? proxied : null} +
    + ))} +

    Pyo keeps a copy. Switch back puts it back.

    +
    + {admin ? ( + + ) : ( + An owner or admin can replace it. + )} + +
    +
    + ); + + if (r?.status === "failed" || (r?.error && (r.status === "switching" || back))) + return ( +

    + Cloudflare: {r.error ?? "the record wasn't changed."} + +

    + ); + + // Nothing to do: the row's Cloudflare logo says it. + if (tunnelNote(d, cluster, admin)) return null; + + if (!r || r.status === "switching" || back) + return ( +

    + + {back ? "Switching back…" : "Switching to the tunnel…"} +

    + ); + + const kept = r.previous ?? []; + const ip = cluster && clusterTraffic(cluster) === "public" ? cluster.publicIp : null; + return ( + <> +

    + + Via Tunnel · + + {r.type} {shortTarget(r.content)} + + {r.error ? · {r.error} : null} + {wildcard && !kept.length ? null : kept.length && !admin ? ( + · An owner or admin can switch it back. + ) : ( + + )} +

    + setConfirming(false)} + tone="primary" + title={ + kept.length + ? `Put back ${kept[0].type} ${kept[0].content} for ${d.hostname}?` + : ip + ? `Point ${d.hostname} at ${ip}?` + : `Remove Pyo's record for ${d.hostname}?` + } + description={null} + confirmLabel="Switch back" + onConfirm={() => void run({ on: false, restore: kept.length > 0 })} + /> + + ); +} + +/** "Switch to Tunnel" for a direct domain in a tunnel-ready zone. */ +export function SwitchToTunnel({ app, d }: { app: Application; d: Domain }) { + const s = usePyo(); + const [busy, setBusy] = useState(false); + if (roleIn(s) === "viewer") return null; + return ( + + ); +} + +/** In tunnel mode, a domain no tunnel zone covers doesn't answer from the internet. */ +export function OutsideTunnel({ c, d }: { c: Cluster; d: Domain }) { + const s = usePyo(); + const zone = cloudflareZoneFor(s, d.hostname, c.teamId); + return ( +

    + {zone && c.tunnel && zone.accountId !== c.tunnel.accountId + ? "Another Cloudflare account. It doesn't answer from the internet." + : "Not in your Cloudflare account. It doesn't answer from the internet."} +

    + ); +} + +/** The remove dialog's choice to put back the record a tunnel domain replaced. */ +export function RestoreRecordSwitch({ + d, + checked, + onChange, +}: { + d: Domain | null; + checked: boolean; + onChange: (v: boolean) => void; +}) { + const kept = d?.dnsRecord?.previous ?? []; + if (!kept.length) return null; + return ( + + ); +} diff --git a/dash/src/components/pyo/UpdateNotice.tsx b/dash/src/components/pyo/UpdateNotice.tsx index e156c9ca..358ae141 100644 --- a/dash/src/components/pyo/UpdateNotice.tsx +++ b/dash/src/components/pyo/UpdateNotice.tsx @@ -1,16 +1,11 @@ import { ArrowSquareOutIcon, CloudArrowUpIcon, XIcon } from "@phosphor-icons/react"; import { Link } from "@tanstack/react-router"; import { useState } from "react"; -import { CopyButton } from "~/components/ui/Table"; import { usePyo } from "~/lib/pyo/store"; // A quiet note at the foot of the sidebar when a newer Pyo is out: the -// version, its release notes, the Updates page and the install command -// (running it again updates Pyo). For the installation's admin, until they -// dismiss that version. - -/** Running the installer again updates Pyo to the latest release (README, Updating). */ -export const UPDATE_COMMAND = "curl -fsSL https://pyo.dev/install.sh | bash"; +// version, its release notes and the Updates page. For the installation's +// admin, until they dismiss that version. const DISMISSED_KEY = "pyo:update-dismissed"; @@ -48,51 +43,40 @@ export function UpdateNotice({ managed }: { managed: boolean }) { return ( ); } diff --git a/dash/src/components/pyo/UpdateSettings.tsx b/dash/src/components/pyo/UpdateSettings.tsx index e381e7dc..b1cdbbf2 100644 --- a/dash/src/components/pyo/UpdateSettings.tsx +++ b/dash/src/components/pyo/UpdateSettings.tsx @@ -29,6 +29,9 @@ import { Arrow } from "~/components/ui/Arrow"; import { useHosted } from "~/components/pyo/Managed"; import { MenuPath } from "~/components/ui/MenuPath"; +/** Said wherever an update moves databases to new images. */ +export const DATABASES_RESTART = "Restarts your databases once"; + // Updates of Pyo itself: the version it runs, the latest release, how it // updates (an admin, or automatically in a weekly window) and the update // dialog listing everything that changes. Installation-wide, for its admin. @@ -233,6 +236,7 @@ function Status({ u, onOpen }: { u: Updates; onOpen: () => void }) { : u.settings.mode === "auto" ? `It's applied automatically in the next window (${windowText(u.settings)}), or now.` : "See what changes before you update."} + {u.plan?.databasesRestart ? ` ${DATABASES_RESTART}.` : ""} ); if (lastFailed) @@ -563,6 +567,17 @@ export function UpdateDialog({ } /> ))} + {plan.databasesRestart ? ( +
  • + +

    + {DATABASES_RESTART} +

    +
  • + ) : null}
  • c.status === "connected" || c.status === "degraded"); // Prefilled, so Create works as it opens. An untouched suggestion isn't @@ -93,7 +97,10 @@ export function useDatabaseDraft(engine: Engine, init?: { name: string; clusterI const [pooler, setPooler] = useState(true); const [rest, setRest] = useState(false); const cluster = clusterId || ready[0]?.id || ""; - const nameError = name ? databaseNameError(engine, name, s.databases.filter((d) => d.teamId === s.currentTeamId)) : "Enter a name."; + const nameError = useHeld( + name ? databaseNameError(engine, name, s.databases.filter((d) => d.teamId === s.currentTeamId)) : "Enter a name.", + held, + ); const custom = size === "custom"; const spec = custom ? { cpu, mem, storage } : SIZE_SPECS[size]; const sizeError = custom ? customError(engine, cpu, mem) || (storage >= 1 && storage <= 1000 ? "" : "Storage is 1 to 1000 GiB.") : ""; @@ -219,20 +226,23 @@ export function SizeAndAvailability({ engine, draft: f }: { engine: Engine; draf function NewDatabase({ engine }: { engine: Engine }) { const navigate = useNavigate(); const admin = useTeamAdmin(); - const f = useDatabaseDraft(engine, carried); + // On from Create until the page moves on. Off again when it's refused. + const [saving, setSaving] = useState(false); + const f = useDatabaseDraft(engine, carried, saving); useEffect(() => { carried = null; }, []); const [error, setError] = useState(""); - const [saving, setSaving] = useState(false); const canCreate = f.valid && !saving; const create = async () => { setSaving(true); setError(""); const r = await api.createDatabase(f.fields()); - setSaving(false); - if ("error" in r) return setError(r.error); + if ("error" in r) { + setSaving(false); + return setError(r.error); + } toast({ title: `Creating ${f.name}`, description: "It's ready in a minute or two." }); void navigate({ href: teamPath(currentSlug(), databaseHref(engine, r.data.id)) }); }; diff --git a/dash/src/components/pyo/sandbox/AddServerFlow.tsx b/dash/src/components/pyo/sandbox/AddServerFlow.tsx index aa7395d1..9cef3be9 100644 --- a/dash/src/components/pyo/sandbox/AddServerFlow.tsx +++ b/dash/src/components/pyo/sandbox/AddServerFlow.tsx @@ -21,6 +21,7 @@ import { Callout, Panel } from "~/components/ui/Panel"; import { DNS_LABEL } from "~/lib/pyo/format"; import { sandboxApi } from "~/lib/pyo/sandbox"; import { refresh, roleIn, sandboxServersIn, usePyo } from "~/lib/pyo/store"; +import { useHeld } from "~/lib/pyo/useHeld"; import { AddSandboxServer, RuntimeBadge } from "./common"; // Add a sandbox server: two square tiles first. "Hetzner" has Pyo buy the @@ -101,11 +102,15 @@ function CloudServer({ onMade }: { onMade: (m: { id: string; name: string }) => const { options } = useCloudOptions(connected && !!s.tailscale); const value = name || suggested; const edgeDomain = edge.trim().replace(/\.$/, ""); - const nameError = !DNS_LABEL.test(value) - ? "Lowercase letters, digits and dashes." - : servers.some((x) => x.name === value && x.teamId === s.currentTeamId) - ? "A sandbox server has this name." - : ""; + // Held from Create on: the server it makes doesn't take its own name. + const nameError = useHeld( + !DNS_LABEL.test(value) + ? "Lowercase letters, digits and dashes." + : servers.some((x) => x.name === value && x.teamId === s.currentTeamId) + ? "A sandbox server has this name." + : "", + creating, + ); const edgeError = !edgeDomain || EDGE_DOMAIN.test(edgeDomain) ? "" : "A domain, like sbx.example.com."; const price = priceOf(options, choice); diff --git a/dash/src/components/pyo/sandbox/common.tsx b/dash/src/components/pyo/sandbox/common.tsx index 10f2013b..0211abbe 100644 --- a/dash/src/components/pyo/sandbox/common.tsx +++ b/dash/src/components/pyo/sandbox/common.tsx @@ -1,5 +1,6 @@ import { CheckCircleIcon, CircleNotchIcon } from "@phosphor-icons/react"; import { useEffect, useState } from "react"; +import { useHosted } from "~/components/pyo/Managed"; import { NeedsTailscale } from "~/components/pyo/Tailscale"; import { TailnetLockWait } from "~/components/pyo/TailnetLock"; import { AppLink } from "~/components/ui/AppLink"; @@ -100,6 +101,7 @@ export function AddSandboxServer({ onDone }: { onDone?: () => void }) { const s = usePyo(); const role = roleIn(s); const canManage = role === "owner" || role === "admin"; + const hosted = useHosted(); const [name, setName] = useState(`sandbox-${sandboxServersIn(s).length + 1}`); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); @@ -233,6 +235,22 @@ export function AddSandboxServer({ onDone }: { onDone?: () => void }) { )} ) : null} + {/* A hosted Pyo shows no NeedsTailscale above, so the reason the button is off goes here. */} + {hosted && !s.tailscale ? ( + + {s.user.isAdmin ? ( + <> + Set up{" "} + + Tailscale + {" "} + first. + + ) : ( + "Tailscale isn't set up yet. Ask an installation admin." + )} + + ) : null} diff --git a/dash/src/components/pyo/wizard/ComposeImport.tsx b/dash/src/components/pyo/wizard/ComposeImport.tsx index d002df96..2f5a8f90 100644 --- a/dash/src/components/pyo/wizard/ComposeImport.tsx +++ b/dash/src/components/pyo/wizard/ComposeImport.tsx @@ -255,7 +255,7 @@ export function ComposeImport({ onBack }: { onBack: () => void }) {
    - + {(f) => (