diff --git a/.github/actions/trivy/action.yml b/.github/actions/trivy/action.yml new file mode 100644 index 00000000..50aaddef --- /dev/null +++ b/.github/actions/trivy/action.yml @@ -0,0 +1,24 @@ +name: Trivy +description: > + Installs Trivy at the pinned version and restores today's vulnerability + database from the Actions cache (saved by the first job of the day to + download it). + +runs: + using: composite + steps: + - uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # v0.3.1 + with: + version: v0.76.2 # aquasecurity/trivy + cache: true + - name: Today + id: today + shell: bash + run: echo "date=$(date -u +%F)" >> "$GITHUB_OUTPUT" + # Yesterday's database when today's isn't cached yet: Trivy sees it's + # old and downloads a new one, which this saves under today's key. + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.cache/trivy/db + key: trivy-db-${{ steps.today.outputs.date }} + restore-keys: trivy-db- diff --git a/.github/scripts/cve-issue.sh b/.github/scripts/cve-issue.sh new file mode 100755 index 00000000..65925a5b --- /dev/null +++ b/.github/scripts/cve-issue.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Keeps one GitHub issue per scanned image, labelled `security`, listing +# its HIGH and CRITICAL CVEs that have a fix (from trivy-scan.sh). Opens +# it, updates it (with a comment when new CVEs show up) or closes it once +# the image has none. The issue is found by the marker in its body, so +# its title can follow the image's version. Needs GH_TOKEN and GH_REPO. +# +# cve-issue.sh # .json and .md +set -euo pipefail +export LC_ALL=C + +key=$1 ref=$2 out=$3 +marker="" +title="CVEs with a fix in ${ref%@*}" +run="${GITHUB_SERVER_URL:-https://github.com}/${GH_REPO}/actions/runs/${GITHUB_RUN_ID:-0}" + +issue=$(gh issue list --state open --label security --limit 500 --json number,body \ + | jq -r --arg m "$marker" 'map(select(.body | contains($m))) | .[0].number // empty') + +ids=$(jq -r '[.Results[]?.Vulnerabilities[]?.VulnerabilityID] | unique | .[]' "$out.json") + +if [ -z "$ids" ]; then + if [ -n "$issue" ]; then + gh issue close "$issue" --comment "The scan of $(date -u +%F) finds no HIGH or CRITICAL CVEs with a fix in \`$ref\` ([run]($run))." + echo "Closed #$issue: nothing left." + else + echo "Nothing to report for $ref." + fi + exit 0 +fi + +rows=$(wc -l < "$out.md") +{ + echo "$marker" + echo "Trivy finds $(wc -l <<<"$ids") HIGH or CRITICAL CVEs with a fixed version in \`$ref\`." + echo + # An issue's body holds 65536 characters. + head -n 252 "$out.md" + if [ "$rows" -gt 252 ]; then + echo + echo "And $((rows - 252)) more. The run has them all." + fi + echo + echo "Scanned $(date -u +%F) ([run]($run)). This issue is updated by each daily scan and closed when nothing is left." + echo + echo "**To fix:** take the fixed versions. For one of Pyo's images, bump its base image or the dependency. For a third-party image, take the fixed image (Renovate opens a pull request when it's published). Then cut a patch release (RELEASING.md, Security patch release). A CVE that doesn't apply goes in \`.trivyignore\` with the reason." +} > "$out.issue.md" + +if [ -z "$issue" ]; then + gh issue create --title "$title" --label security --body-file "$out.issue.md" + exit 0 +fi + +before=$(gh issue view "$issue" --json body --jq .body | grep -oE '\[[A-Z]+-[A-Za-z0-9-]+\]' | tr -d '[]' | sort -u || true) +new=$(comm -13 <(echo "$before") <(echo "$ids" | sort -u) | paste -sd ' ' -) +gh issue edit "$issue" --title "$title" --body-file "$out.issue.md" +if [ -n "$new" ]; then + gh issue comment "$issue" --body "New since the last scan: $new" +fi +echo "Updated #$issue." diff --git a/.github/scripts/rebuild-issue.sh b/.github/scripts/rebuild-issue.sh new file mode 100755 index 00000000..9658399c --- /dev/null +++ b/.github/scripts/rebuild-issue.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# For the weekly Postgres rebuild check (postgres-rebuild.yml): compares +# the published image's HIGH and CRITICAL CVEs that have a fix with a +# fresh build's (trivy-scan.sh's published.json and fresh.json). While the +# fresh build has fewer, one issue per major version, labelled security, +# says a patch release would pick up the fixes. Closed once it doesn't. +# Needs GH_TOKEN and GH_REPO. +# +# rebuild-issue.sh +set -euo pipefail +export LC_ALL=C + +major=$1 published=$2 pinned=$3 today=$4 +marker="" +run="${GITHUB_SERVER_URL:-https://github.com}/${GH_REPO}/actions/runs/${GITHUB_RUN_ID:-0}" + +ids() { jq -r '[.Results[]?.Vulnerabilities[]?.VulnerabilityID] | unique | .[]' "$1"; } +before=$(ids published.json) +after=$(ids fresh.json) +nb=$(grep -c . <<<"$before" || true) +na=$(grep -c . <<<"$after" || true) +fixed=$(comm -23 <(echo "$before") <(echo "$after") | sed '/^$/d') + +echo "Postgres $major: the published image has $nb HIGH or CRITICAL CVEs with a fix, a fresh build has $na." \ + | tee -a "${GITHUB_STEP_SUMMARY:-/dev/null}" + +issue=$(gh issue list --state open --label security --limit 500 --json number,body \ + | jq -r --arg m "$marker" 'map(select(.body | contains($m))) | .[0].number // empty') + +if [ "$na" -ge "$nb" ]; then + if [ -n "$issue" ]; then + gh issue close "$issue" --comment "A rebuild on $(date -u +%F) no longer has fewer CVEs than \`$published\` ([run]($run))." + fi + exit 0 +fi + +{ + echo "$marker" + echo "A fresh build of Pyo's Postgres $major image has $na HIGH or CRITICAL CVEs with a fix. The published \`$published\` has $nb. A patch release would pick up these fixes:" + echo + jq -r --argjson fixed "$(jq -Rnc '[inputs | select(length > 0)]' <<<"$fixed")" ' + [.Results[]?.Vulnerabilities[]? | select(.VulnerabilityID as $id | $fixed | index($id))] + | unique_by([.VulnerabilityID, .PkgName]) + | sort_by([(if .Severity == "CRITICAL" then 0 else 1 end), .VulnerabilityID]) + | "| CVE | Severity | Package | Published has | Fixed in |", + "|---|---|---|---|---|", + (.[:250][] | "| [\(.VulnerabilityID)](\(.PrimaryURL // "https://osv.dev/vulnerability/\(.VulnerabilityID)")) | \(.Severity) | \(.PkgName) | \(.InstalledVersion) | \(.FixedVersion) |") + ' published.json + echo + echo "The fresh build is the release's \`deploy/images/postgres.Dockerfile\` with this week's extension packages, on the base image of the same tag as it is today." + echo + if [ "$pinned" = "$today" ]; then + echo "The base is the one the release pins, so the fixes are in the packages the build installs. Cutting a patch release rebuilds the image with them." + else + echo "- The release pins \`$pinned\`" + echo "- Today it's \`$today\`" + echo + echo "Bump \`BASE_$major\` in \`deploy/images/postgres.Dockerfile\` to today's digest (Renovate's pull request does it), then cut a patch release." + fi + echo + echo "See RELEASING.md, Security patch release. Checked $(date -u +%F) ([run]($run)). This issue is updated each week and closed when a rebuild no longer fixes more." +} > rebuild.issue.md + +title="Postgres $major: a rebuild has $((nb - na)) fewer CVEs" +if [ -n "$issue" ]; then + gh issue edit "$issue" --title "$title" --body-file rebuild.issue.md +else + gh issue create --title "$title" --label security --body-file rebuild.issue.md +fi diff --git a/.github/scripts/trivy-scan.sh b/.github/scripts/trivy-scan.sh new file mode 100755 index 00000000..ef10d258 --- /dev/null +++ b/.github/scripts/trivy-scan.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Scans an image, or this checkout's lockfiles, with Trivy for HIGH and +# CRITICAL CVEs that have a fixed version. Writes .json (Trivy's +# report), .sarif (for code scanning) and .md (a table, empty +# when there's nothing), adds the table to the job's summary and sets the +# step outputs `critical` and `high`: how many CVEs of each. +# +# It never fails because of what it finds. The workflow decides. +# .trivyignore lists CVEs checked and found not to apply. +# +# trivy-scan.sh image +# trivy-scan.sh fs +set -euo pipefail + +kind=$1 target=$2 out=$3 +case "$kind" in + image) args=() ;; + # bun.lock's dev dependencies too: they run in CI and on our machines. + fs) args=(--include-dev-deps) ;; + *) echo "trivy-scan.sh: image or fs, not $kind" >&2; exit 2 ;; +esac + +trivy "$kind" --scanners vuln --ignore-unfixed --severity HIGH,CRITICAL \ + "${args[@]}" --format json --output "$out.json" "$target" +trivy convert --format sarif --output "$out.sarif" "$out.json" + +# One row per CVE and package, CRITICAL first. +jq -r ' + [.Results[]? | .Vulnerabilities[]?] + | unique_by([.VulnerabilityID, .PkgName, .InstalledVersion]) + | sort_by([(if .Severity == "CRITICAL" then 0 else 1 end), .VulnerabilityID]) + | if length == 0 then empty else + "| CVE | Severity | Package | Installed | Fixed in |", + "|---|---|---|---|---|", + (.[] | "| [\(.VulnerabilityID)](\(.PrimaryURL // "https://osv.dev/vulnerability/\(.VulnerabilityID)")) | \(.Severity) | \(.PkgName) | \(.InstalledVersion) | \(.FixedVersion) |") + end +' "$out.json" > "$out.md" + +count() { + jq --arg s "$1" '[.Results[]?.Vulnerabilities[]? | select(.Severity == $s) | .VulnerabilityID] | unique | length' "$out.json" +} +critical=$(count CRITICAL) +high=$(count HIGH) + +{ + echo "### Trivy: \`$target\`" + echo + if [ -s "$out.md" ]; then + echo "$critical CRITICAL and $high HIGH with a fix." + echo + head -n 302 "$out.md" + else + echo "No HIGH or CRITICAL CVEs with a fix." + fi + echo +} >> "${GITHUB_STEP_SUMMARY:-/dev/stdout}" + +if [ -n "${GITHUB_OUTPUT:-}" ]; then + echo "critical=$critical" >> "$GITHUB_OUTPUT" + echo "high=$high" >> "$GITHUB_OUTPUT" +fi +echo "$target: $critical CRITICAL, $high HIGH with a fix." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5848868d..6c21c993 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,6 +90,55 @@ jobs: - run: scripts/install-railpack.sh - run: cargo test --locked --workspace + # 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 + # with a fix fails the check. HIGH ones are reported in the job's + # summary and in code scanning. + lockfiles: + name: Lockfile CVEs + runs-on: ubuntu-24.04 + permissions: + contents: read + security-events: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: ./.github/actions/trivy + - name: Scan for CVEs + id: scan + run: .github/scripts/trivy-scan.sh fs . trivy + # A fork's pull request can't write to code scanning. + - uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository + with: + sarif_file: trivy.sarif + category: lockfiles + - name: No CRITICAL CVE with a fix + if: steps.scan.outputs.critical != '0' + env: + CRITICAL: ${{ steps.scan.outputs.critical }} + run: | + echo "::error::The lockfiles have $CRITICAL CRITICAL CVEs with a fix (see the job's summary). Update those dependencies, or add a CVE that doesn't apply to .trivyignore with the reason." + exit 1 + + # cargo-deny, configured in deny.toml. RustSec advisories and crates + # from anywhere but crates.io fail the check. Licenses and banned or + # duplicate crates only warn for now (continue-on-error), until they're + # clean enough to enforce. + cargo-deny: + name: cargo-deny ${{ matrix.checks }} + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + checks: [advisories sources, bans licenses] + continue-on-error: ${{ matrix.checks == 'bans licenses' }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 + with: + rust-version: 1.99.1 + command: check ${{ matrix.checks }} + # Pyo Sandbox end to end: real Firecracker microVMs on the runner's KVM. # x64 only, as GitHub's arm runners have no KVM. The networking e2e # changes the host's network as root, so it runs last. diff --git a/.github/workflows/postgres-rebuild.yml b/.github/workflows/postgres-rebuild.yml new file mode 100644 index 00000000..08870799 --- /dev/null +++ b/.github/workflows/postgres-rebuild.yml @@ -0,0 +1,109 @@ +name: Postgres rebuild check + +# Every week: builds Pyo's Postgres images (16, 17 and 18) from the latest +# release's deploy/images/postgres.Dockerfile, with this week's extension +# packages and on the CloudNativePG base of the same tag as it is today, +# then scans each next to the published one. When the fresh build has +# fewer HIGH or CRITICAL CVEs with a fix, an issue (labelled security) +# says a patch release would pick up the fixes. +# +# Nothing is pushed anywhere. Pyo's images are published only by a tagged +# release, signed and versioned (release.yml). + +on: + schedule: + - cron: "41 3 * * 1" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: postgres-rebuild + +jobs: + release: + name: Latest release + runs-on: ubuntu-24.04 + outputs: + tag: ${{ steps.release.outputs.tag }} + images: ${{ steps.release.outputs.images }} + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + steps: + - name: Its tag and Postgres images + id: release + run: | + set -euo pipefail + tag=$(gh release view --json tagName --jq .tagName) + gh release download "$tag" --pattern release.json --dir release + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "images=$(jq -c '.images | {"16": .postgres16, "17": .postgres17, "18": .postgres18}' release/release.json)" >> "$GITHUB_OUTPUT" + + check: + name: Postgres ${{ matrix.major }} + needs: release + runs-on: ubuntu-24.04 + permissions: + contents: read + issues: write + strategy: + fail-fast: false + matrix: + major: ["16", "17", "18"] + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + MAJOR: ${{ matrix.major }} + PUBLISHED: ${{ fromJSON(needs.release.outputs.images)[matrix.major] }} + steps: + # This branch's scripts, and the release's Dockerfile beside them. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.release.outputs.tag }} + path: release + persist-credentials: false + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + - name: The base, pinned and today + id: base + run: | + set -euo pipefail + pinned=$(sed -n "s/^ARG BASE_${MAJOR}=//p" release/deploy/images/postgres.Dockerfile) + if [ -z "$pinned" ]; then + echo "::error::The release's postgres.Dockerfile has no BASE_${MAJOR}." + exit 1 + fi + tag=${pinned%@*} + digest=$(docker buildx imagetools inspect "$tag" --format '{{json .Manifest}}' | jq -r .digest) + echo "pinned=$pinned" >> "$GITHUB_OUTPUT" + echo "today=$tag@$digest" >> "$GITHUB_OUTPUT" + - name: Build, without pushing + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: release/deploy/images + file: release/deploy/images/postgres.Dockerfile + build-args: | + PG_MAJOR=${{ matrix.major }} + BASE_${{ matrix.major }}=${{ steps.base.outputs.today }} + platforms: linux/amd64 + no-cache: true + pull: true + push: false + load: true + tags: pyo-rebuild/postgres:${{ matrix.major }} + provenance: false + sbom: false + - uses: ./.github/actions/trivy + - name: Scan the published image + run: .github/scripts/trivy-scan.sh image "$PUBLISHED" published + - name: Scan the fresh build + run: .github/scripts/trivy-scan.sh image "pyo-rebuild/postgres:$MAJOR" fresh + - name: Open, update or close the issue + env: + PINNED: ${{ steps.base.outputs.pinned }} + TODAY: ${{ steps.base.outputs.today }} + run: .github/scripts/rebuild-issue.sh "$MAJOR" "$PUBLISHED" "$PINNED" "$TODAY" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2315dd21..48c6ce27 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -106,6 +106,7 @@ jobs: contents: read packages: write id-token: write # Signing: proves the image came from this workflow. + security-events: write # The image's CVEs, in code scanning. strategy: fail-fast: true matrix: @@ -140,6 +141,43 @@ jobs: username: ${{ github.actor }} password: ${{ github.token }} - uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 + # Scanned before anything is pushed or signed. The image is built + # into the runner's Docker first (amd64), and the push below takes + # its layers from the same builder's cache. A CRITICAL CVE that has + # a fix stops the release. HIGH ones are reported in the job's + # summary and in code scanning. .trivyignore lists the CVEs checked + # and found not to apply. + - name: Build for the scan + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ${{ matrix.context || '.' }} + file: deploy/images/${{ matrix.file || matrix.image }}.Dockerfile + build-args: ${{ matrix.args }} + target: ${{ matrix.target }} + platforms: linux/amd64 + cache-from: ${{ matrix.rust && format('type=gha,scope=rust-{0}', github.run_id) || '' }} + load: true + tags: pyo-scan/${{ matrix.image }}:${{ needs.verify.outputs.version }} + provenance: false + sbom: false + - uses: ./.github/actions/trivy + - name: Scan for CVEs + id: scan + env: + IMAGE: pyo-scan/${{ matrix.image }}:${{ needs.verify.outputs.version }} + run: .github/scripts/trivy-scan.sh image "$IMAGE" trivy + - uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + sarif_file: trivy.sarif + category: release-image-${{ matrix.image }} + - name: No CRITICAL CVE with a fix + if: steps.scan.outputs.critical != '0' + env: + IMAGE: ${{ matrix.image }} + CRITICAL: ${{ steps.scan.outputs.critical }} + run: | + echo "::error::$IMAGE has $CRITICAL CRITICAL CVEs with a fix (see the job's summary). Take the fixed versions and tag a new release, or add a CVE that doesn't apply to .trivyignore with the reason." + exit 1 - name: Build and push id: build uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml new file mode 100644 index 00000000..5fd072e0 --- /dev/null +++ b/.github/workflows/security-scan.yml @@ -0,0 +1,111 @@ +name: Security scan + +# Every day, Trivy scans: +# - the images of the latest release (ghcr.io/upsetdev/pyo/*, as its +# release.json pins them) +# - the third-party database images Pyo pins, as this branch has them: +# the databases system's images (crates/pyo-proto/system/databases: +# CloudNativePG, MOCO and its sidecars, MySQL, valkey-bundle) and the +# CloudNativePG bases of deploy/images/postgres.Dockerfile, plus plain +# Valkey 8.1, which isn't pinned (it follows a database's version) +# +# An image with HIGH or CRITICAL CVEs that have a fix gets one issue, +# labelled security, listing them with their fixed versions. Each scan +# updates it, and closes it when nothing is left. It uses the built-in +# GITHUB_TOKEN only. + +on: + schedule: + - cron: "23 2 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: security-scan + +jobs: + images: + name: Images to scan + runs-on: ubuntu-24.04 + permissions: + contents: read + issues: write + outputs: + images: ${{ steps.list.outputs.images }} + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: The security label + run: gh label create security --color B60205 --description "A vulnerability to fix" 2>/dev/null || true + - name: List them + id: list + run: | + set -euo pipefail + tag=$(gh release view --json tagName --jq .tagName) + gh release download "$tag" --pattern release.json --dir release + jq -c '[.images | to_entries[] | select(.value | startswith("ghcr.io/upsetdev/pyo/")) | {key: ("pyo/" + .key), ref: .value}]' \ + release/release.json > pyo.json + { + git grep -hoE '(docker\.io|ghcr\.io)/[a-z0-9._/-]+:[A-Za-z0-9._-]+@sha256:[0-9a-f]{64}' -- \ + crates/pyo-proto/system deploy/images/postgres.Dockerfile | sort -u + echo docker.io/valkey/valkey:8.1 + } | jq -Rnc '[inputs | select(length > 0) | {key: sub("@.*$"; ""), ref: .}]' > third-party.json + echo "images=$(jq -sc 'add' pyo.json third-party.json)" >> "$GITHUB_OUTPUT" + echo "$tag: $(jq length pyo.json) of Pyo's images and $(jq length third-party.json) third-party images." + + scan: + name: ${{ matrix.image.key }} + needs: images + runs-on: ubuntu-24.04 + permissions: + contents: read + issues: write + strategy: + fail-fast: false + max-parallel: 8 + matrix: + image: ${{ fromJSON(needs.images.outputs.images) }} + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + KEY: ${{ matrix.image.key }} + REF: ${{ matrix.image.ref }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ./.github/actions/trivy + - name: Scan for CVEs + run: .github/scripts/trivy-scan.sh image "$REF" trivy + - name: Open, update or close its issue + run: .github/scripts/cve-issue.sh "$KEY" "$REF" trivy + + # An image that isn't scanned anymore (a third-party image moved to a + # new version, say) has its issue closed. + tidy: + name: Close the issues of images not scanned + needs: [images, scan] + if: always() && needs.images.result == 'success' + runs-on: ubuntu-24.04 + permissions: + issues: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + IMAGES: ${{ needs.images.outputs.images }} + steps: + - name: Close them + run: | + set -euo pipefail + gh issue list --state open --label security --limit 500 --json number,body \ + | jq -r --argjson keep "$(jq -c 'map(.key)' <<<"$IMAGES")" \ + '.[] | (.body | capture("").k) as $k | select($keep | index($k) | not) | .number' \ + | while read -r n; do + gh issue close "$n" --comment "This image isn't scanned anymore: the latest release or the pinned images moved on." + done diff --git a/.trivyignore b/.trivyignore new file mode 100644 index 00000000..bf71f807 --- /dev/null +++ b/.trivyignore @@ -0,0 +1,4 @@ +# CVEs that Trivy reports and that were checked and found not to apply to +# Pyo. One ID per line, each with a comment saying why, and an expiry +# when it's waiting for an upstream fix (exp:2027-01-31 after the ID). +# The release, CI and the daily scan all read this file. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6c9c6971..e93b4a76 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -194,6 +194,8 @@ release has to keep working on the new schema. with a default. - Removing or renaming something takes several releases. - Never edit a migration that has been merged. +- A new table with a `team_id` gets a row security policy like the ones in + `0022_row_security.sql`, or a place in `NOT_COVERED` in `rls.rs`. `scripts/check-migrations.ts` enforces these rules in CI. The full rules are in [RELEASING.md](RELEASING.md#change-the-database). diff --git a/Cargo.lock b/Cargo.lock index a2059baf..925641c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -463,6 +463,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" +[[package]] +name = "base32" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "022dfe9eb35f19ebbcb51e0b40a5ab759f46ad60cadf7297e0bd085afb50e076" + [[package]] name = "base64" version = "0.21.7" @@ -612,6 +618,16 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "bstr" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "btoi" version = "0.5.0" @@ -812,6 +828,12 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "convert_case" version = "0.10.0" @@ -832,6 +854,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -902,6 +934,40 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-queue" version = "0.3.14" @@ -1383,9 +1449,9 @@ dependencies = [ [[package]] name = "email-encoding" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd" +checksum = "9f690ae2169f2ceb3f45b28b6fcd8fa16839f2f5c8818546774b9425f5f71004" dependencies = [ "base64 0.23.1", "memchr", @@ -1749,6 +1815,19 @@ dependencies = [ "polyval", ] +[[package]] +name = "globset" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f98b0d85522dc0a824cfebbc9594ff4a9b289c568bea0370319dfbdf20ccdd2d" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + [[package]] name = "gloo-timers" version = "0.3.0" @@ -1883,6 +1962,76 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hickory-net" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d" +dependencies = [ + "async-trait", + "cfg-if", + "data-encoding", + "futures-channel", + "futures-io", + "futures-util", + "hickory-proto", + "idna", + "ipnet", + "jni", + "rand 0.10.3", + "thiserror 2.0.21", + "tinyvec", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "hickory-proto" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" +dependencies = [ + "data-encoding", + "idna", + "ipnet", + "jni", + "once_cell", + "prefix-trie", + "rand 0.10.3", + "ring", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "url", +] + +[[package]] +name = "hickory-resolver" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981" +dependencies = [ + "cfg-if", + "futures-util", + "hickory-net", + "hickory-proto", + "ipconfig", + "ipnet", + "jni", + "moka", + "ndk-context", + "once_cell", + "parking_lot", + "rand 0.10.3", + "resolv-conf", + "smallvec", + "system-configuration", + "thiserror 2.0.21", + "tokio", + "tracing", +] + [[package]] name = "hkdf" version = "0.13.0" @@ -2186,6 +2335,22 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "ignore" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "484be5657551d7868d67587df967fb4fcbe9d266a761cc855aaa148fda0b3cc7" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -2251,11 +2416,27 @@ dependencies = [ "tokio", ] +[[package]] +name = "ipconfig" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222" +dependencies = [ + "socket2", + "widestring", + "windows-registry", + "windows-result", + "windows-sys 0.61.2", +] + [[package]] name = "ipnet" version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +dependencies = [ + "serde", +] [[package]] name = "ipnetwork" @@ -2609,9 +2790,9 @@ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "lettre" -version = "0.11.23" +version = "0.11.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae" +checksum = "f294f3d7cdb313e578acef7d7727d4e8d897e0fcd0d6d58c19959cec95073f19" dependencies = [ "async-trait", "base64 0.23.1", @@ -2802,6 +2983,23 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moka" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" +dependencies = [ + "crossbeam-channel", + "crossbeam-epoch", + "crossbeam-utils", + "equivalent", + "parking_lot", + "portable-atomic", + "smallvec", + "tagptr", + "uuid", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -2865,6 +3063,12 @@ dependencies = [ "uuid", ] +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2947,6 +3151,10 @@ name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] [[package]] name = "once_cell_polyfill" @@ -3307,6 +3515,17 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prefix-trie" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7" +dependencies = [ + "either", + "ipnet", + "num-traits", +] + [[package]] name = "primefield" version = "0.14.0" @@ -3354,28 +3573,38 @@ dependencies = [ [[package]] name = "pyo-agent" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", + "axum", "base64 0.23.1", + "flate2", "futures", + "hex", "http", + "jiff", + "jsonc-parser", "k8s-openapi", "kube", + "maxminddb", "pyo-proto", + "rcgen", "reqwest", "rustls", "serde", "serde_json", + "sha2 0.11.1", "tokio", "tokio-tungstenite", "tracing", "tracing-subscriber", + "woothee", + "zeroize", ] [[package]] name = "pyo-api" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", "argon2 0.6.0", @@ -3388,6 +3617,7 @@ dependencies = [ "flate2", "futures", "hex", + "hickory-resolver", "hmac", "hyper", "hyper-util", @@ -3399,6 +3629,7 @@ dependencies = [ "libc", "maxminddb", "pyo-proto", + "qrcode", "rand 0.10.3", "rcgen", "regex", @@ -3411,8 +3642,12 @@ dependencies = [ "sha2 0.11.1", "sqlx", "thiserror 2.0.21", + "time", "tokio", + "tokio-rustls", "tokio-tungstenite", + "totp-rs", + "tower", "tower-http 0.7.1", "tracing", "tracing-subscriber", @@ -3425,10 +3660,11 @@ dependencies = [ [[package]] name = "pyo-builder" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", "base64 0.23.1", + "flate2", "futures", "hex", "pyo-proto", @@ -3436,6 +3672,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "tar", "tokio", "tokio-util", "tracing", @@ -3444,13 +3681,16 @@ dependencies = [ [[package]] name = "pyo-cli" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", "clap", "crossterm", + "flate2", "futures", "hex", + "hostname", + "ignore", "jsonc-parser", "pyo-proto", "rand 0.10.3", @@ -3460,6 +3700,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "sha2 0.11.1", + "tar", "tokio", "tokio-tungstenite", "toml", @@ -3467,7 +3708,7 @@ dependencies = [ [[package]] name = "pyo-db-controller" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", "base64 0.23.1", @@ -3489,7 +3730,7 @@ dependencies = [ [[package]] name = "pyo-envd" -version = "0.4.5" +version = "0.5.0" dependencies = [ "libc", "pyo-proto", @@ -3498,7 +3739,7 @@ dependencies = [ [[package]] name = "pyo-flows" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", "libc", @@ -3512,7 +3753,7 @@ dependencies = [ [[package]] name = "pyo-kv" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", "axum", @@ -3529,21 +3770,25 @@ dependencies = [ [[package]] name = "pyo-proto" -version = "0.4.5" +version = "0.5.0" dependencies = [ "base64 0.23.1", + "jiff", + "rcgen", "regex", "ring", "serde", "serde_json", "serde_norway", "sha2 0.11.1", + "time", "utoipa", + "x509-parser", ] [[package]] name = "pyo-resp" -version = "0.4.5" +version = "0.5.0" dependencies = [ "futures", "socket2", @@ -3552,7 +3797,7 @@ dependencies = [ [[package]] name = "pyo-sandbox" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", "axum", @@ -3582,10 +3827,11 @@ dependencies = [ [[package]] name = "pyo-static" -version = "0.4.5" +version = "0.5.0" dependencies = [ "anyhow", "axum", + "base64 0.23.1", "futures", "hex", "pyo-proto", @@ -3600,6 +3846,12 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + [[package]] name = "quinn" version = "0.11.12" @@ -3766,6 +4018,7 @@ checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" dependencies = [ "aws-lc-rs", "pem 4.0.0", + "ring", "rustls-pki-types", "time", "x509-parser", @@ -3871,6 +4124,12 @@ dependencies = [ "web-sys", ] +[[package]] +name = "resolv-conf" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" + [[package]] name = "rfc6979" version = "0.6.0" @@ -3995,7 +4254,7 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ - "core-foundation", + "core-foundation 0.10.1", "core-foundation-sys", "jni", "log", @@ -4174,7 +4433,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "core-foundation-sys", "libc", "security-framework-sys", @@ -4834,6 +5093,33 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tagptr" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" + [[package]] name = "tar" version = "0.4.46" @@ -5079,6 +5365,22 @@ version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +[[package]] +name = "totp-rs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49d0f9b7aa5def86d3a8d8ba926fe8c1990924dd715d2b5fc54a4aa3788c11c1" +dependencies = [ + "base32", + "constant_time_eq", + "hmac", + "rand 0.10.3", + "serde", + "sha1 0.11.0", + "sha2 0.11.1", + "zeroize", +] + [[package]] name = "tower" version = "0.5.3" @@ -5646,6 +5948,12 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi" version = "0.3.9" @@ -5718,6 +6026,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -5891,6 +6210,7 @@ dependencies = [ "lazy_static", "nom 7.1.3", "oid-registry", + "ring", "rusticata-macros", "thiserror 2.0.21", "time", diff --git a/Cargo.toml b/Cargo.toml index 063d6198..d8e716ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ 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"] [workspace.package] -version = "0.4.5" +version = "0.5.0" edition = "2024" license = "Apache-2.0" publish = false diff --git a/RELEASING.md b/RELEASING.md index 7c3dbcb5..86512c21 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -83,6 +83,11 @@ instance with Rekor v1). The release's text lists the changes since the previous release (see [Release notes](#release-notes)). +Each image is scanned with Trivy before it's pushed or signed. A CRITICAL +CVE that has a fix stops the release. HIGH ones are listed in the job's +summary and in code scanning. A CVE checked and found not to apply goes in +`.trivyignore`, with the reason. + Don't move or reuse a tag. If a release is bad, publish the next version. The repo has GitHub's immutable releases on: once a release is published, @@ -97,6 +102,69 @@ Then the `site` job rebuilds pyo.dev (see [Install scripts on pyo.dev](#install-scripts-on-pyodev)). If it fails, run that job again. +## Security patch release + +When a fix can't wait for the next release, cut a patch release of the +latest one. Only the latest release gets fixes (see `SECURITY.md`). + +What asks for one: + +- the daily **Security scan** (`security-scan.yml`): an issue labelled + `security` for each image, Pyo's or a third-party database image, with + HIGH or CRITICAL CVEs that have a fix +- the weekly **Postgres rebuild check** (`postgres-rebuild.yml`): an issue + when a fresh build of Pyo's Postgres images would have fewer of them +- Renovate's security pull requests, which it opens right away +- CI's **Lockfile CVEs** and **cargo-deny** checks + +1. Fix it on `dev`: merge Renovate's pull request, or bump the dependency + or the image's digest. Name the commit `fix(security): ...` or give it + a `Security: GHSA-...` footer, so the release notes list it under + Security Fixes. A CVE that doesn't apply goes in `.trivyignore` + (images and lockfiles) or in `deny.toml` and `.cargo/audit.toml` (Rust + advisories), with the reason. +2. Make the branch from the last release tag: + + ```bash + scripts/patch-release.sh ... # a dry run: says what it would do + scripts/patch-release.sh --apply ... # does it, locally + ``` + + It branches `release/vX.Y.Z` from the tag, cherry-picks the commits + and bumps the version as a release commit does (`Cargo.toml`, each + crate's `pyo-proto` dependency, `Cargo.lock` and + `deploy/release-notices.json`). Keep the notices' `minFrom`, and clear + `beforeYouUpdate` and `manualOnly` unless the patch needs them. Without + commits it's a rebuild of the tag's code, which picks up what the + Dockerfiles install as it is today. That's enough when the weekly check + says so and the base image's digest didn't change. +3. Push the branch, open a pull request into `main` and wait for CI. The + release checks the template catalog against pyo-templates' main, so if + that check fails, cherry-pick the catalog's update too. +4. Merge it, then tag the merge `vX.Y.Z` (`v0.5.1` after `v0.5.0`) and push + the tag. The release workflow scans, signs and publishes it like any + release. + +How it reaches installations: + +- **Self-hosted:** an installation looks for a new release every 6 hours. + Its admins see it in the update notice in the sidebar and under + **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. +- **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. + +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 +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. + ## Release notes `scripts/release-notes.ts` writes each release's text from the Conventional diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..165ed02d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,29 @@ +# Security + +## Report a vulnerability + +Please don't report it in a public issue. Tell us privately instead: + +- on GitHub: [report a vulnerability](https://github.com/upsetdev/pyo/security/advisories/new) +- or by email to support@pyo.dev, with "Security" in the subject + +Say what's affected, how to reproduce it and which version you run (it's +under **Settings › Updates**). We'll confirm we got it, keep you posted on +the fix and credit you in the advisory if you'd like. + +This covers Pyo, its CLI, its install scripts and its images at +`ghcr.io/upsetdev/pyo`. Pyo Sandbox's templates live in +[upsetdev/pyo-sandbox-images](https://github.com/upsetdev/pyo-sandbox-images), +and you can report those here too. + +## Supported versions + +| Version | Security fixes | +|---|---| +| The latest release | Yes | +| Older releases | No. Update to the latest | + +A fix comes as a patch release, like 0.5.1 after 0.5.0. A self-hosted Pyo +shows it in the update notice and under **Settings › Updates**, and applies +it from there or by itself when automatic updates are on. Pyo Cloud is +updated for you. diff --git a/crates/pyo-agent/Cargo.toml b/crates/pyo-agent/Cargo.toml index 8033f06c..542309a6 100644 --- a/crates/pyo-agent/Cargo.toml +++ b/crates/pyo-agent/Cargo.toml @@ -7,12 +7,13 @@ publish.workspace = true [dependencies] anyhow = "1.0.104" -pyo-proto = { version = "0.4.5", path = "../pyo-proto" } +pyo-proto = { version = "0.5.0", path = "../pyo-proto", features = ["command-signing"] } futures = "0.3.34" +axum = { version = "0.8.9", default-features = false, features = ["http1", "tokio"] } http = "1.5.0" k8s-openapi = { version = "0.28.0", features = ["latest"] } kube = { version = "4.2.0", default-features = false, features = ["runtime", "client", "rustls-tls", "ws"] } -reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls"] } +reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls", "stream"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" tokio = { version = "1.54.1", features = ["full"] } @@ -21,3 +22,19 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } tokio-tungstenite = { version = "0.29", features = ["rustls-tls-native-roots"] } base64 = "0.23.1" rustls = { version = "0.23.46", default-features = false, features = ["aws_lc_rs", "std"] } +rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem"] } +# The traffic store (traffic/): countries, user agents, kept files. +maxminddb = { version = "0.32", features = ["mmap"] } +woothee = "0.13" +flate2 = "1" +sha2 = "0.11.1" +jiff = "0.2.38" +# The one-token Tailscale setup (tailscale/setup.rs): the policy is HuJSON, +# and the pasted token is wiped once used. +jsonc-parser = { version = "0.34.0", features = ["cst", "serde"] } +zeroize = "1" +hex = "0.4.3" + +[dev-dependencies] +# A mock Tailscale API in tests. +axum = { version = "0.8.9", default-features = false, features = ["http1", "tokio", "json"] } diff --git a/crates/pyo-agent/src/actions.rs b/crates/pyo-agent/src/actions.rs index 94979060..e6ebe393 100644 --- a/crates/pyo-agent/src/actions.rs +++ b/crates/pyo-agent/src/actions.rs @@ -1,5 +1,5 @@ //! Commands that aren't rollouts: restart, stop, delete, cordon, maintenance -//! and on-demand logs. +//! and on-demand logs (followed in logfollow.rs). use k8s_openapi::api::batch::v1::{CronJob, Job}; use k8s_openapi::api::{ @@ -24,6 +24,12 @@ pub async fn run(agent: &Agent, command: Command) -> CommandResult { Command::Restart(service) => restart(agent, &service).await, Command::Stop(service) => stop(agent, &service).await, Command::Scale { service, replicas } => scale(agent, &service, replicas).await, + Command::Place { + service, + server_names, + server_tags, + cron_jobs, + } => place(agent, &service, &server_names, &server_tags, &cron_jobs).await, Command::SyncCronJobs { service, jobs } => crate::cron::sync(&agent.kube, &service, &jobs) .await .map(|n| format!("{n} cron job(s) in place")), @@ -44,7 +50,9 @@ pub async fn run(agent: &Agent, command: Command) -> CommandResult { Command::FetchLogs { service, tail_lines, - } => return logs(agent, &service, tail_lines).await, + since_seconds, + replica, + } => return logs(agent, &service, tail_lines, since_seconds, &replica).await, Command::EnsureBuilder(spec) => crate::builder::ensure(agent, &spec).await, Command::RemoveBuilder { builder_id } => crate::builder::remove(agent, &builder_id).await, Command::RemoveServer { server, force } => { @@ -89,6 +97,17 @@ pub async fn run(agent: &Agent, command: Command) -> CommandResult { Command::CheckDatabaseImport(spec) => { return crate::dbimport::check(&agent.kube, *spec).await; } + Command::QueryTraffic(q) => { + return match crate::traffic::link::query(&q).await { + Ok(a) => CommandResult { + ok: true, + message: None, + logs: vec![], + data: serde_json::to_value(a).ok(), + }, + Err(e) => failed(format!("{e:#}")), + }; + } Command::SetTrafficMode { mode } => { crate::rollout::set_traffic_mode(&agent.kube, &mode).await } @@ -128,6 +147,8 @@ pub async fn run(agent: &Agent, command: Command) -> CommandResult { Command::Deploy(_) | Command::Cancel { .. } | Command::OpenTerminal { .. } + | Command::FollowLogs { .. } + | Command::FollowDatabaseLogs { .. } | Command::Backup(_) | Command::ListSnapshots(_) | Command::ForgetSnapshot(_) @@ -135,7 +156,16 @@ pub async fn run(agent: &Agent, command: Command) -> CommandResult { | Command::DbSetup { .. } | Command::UpgradePyo(_) | Command::UpdateAgent { .. } - | Command::RefreshInstall(_) => { + | Command::RefreshInstall(_) + | Command::TailscaleSetup { .. } + | Command::TailscaleClient { .. } + | Command::TailscaleTest {} + | Command::TailscaleSync(_) + | Command::TailscaleKey { .. } + | Command::TailscaleCheckName { .. } + | Command::TailscaleRemove { .. } + | Command::SandboxCall(_) + | Command::SyncRegistryTokens(_) => { unreachable!("handled by the command loop") } }; @@ -252,6 +282,104 @@ async fn scale(agent: &Agent, service: &ServiceRef, replicas: i32) -> anyhow::Re Ok(format!("Scaled {} to {replicas}", service.name)) } +/// The merge patch that moves a pod template (`spec.template` of a +/// Deployment or StatefulSet, or of a CronJob's job) to the servers and tags +/// picked: its affinity, and no longer the tag labels its node selector may +/// still ask for from a rollout that placed by tag that way. +pub fn place_patch( + server_names: &[String], + server_tags: &[String], + selector: Option<&std::collections::BTreeMap>, +) -> serde_json::Value { + let mut spec = json!({ "affinity": pyo_proto::placement_affinity(server_names, server_tags) }); + let stale: serde_json::Map = selector + .into_iter() + .flat_map(|m| m.keys()) + .filter(|k| k.starts_with(pyo_proto::TAG_LABEL_PREFIX)) + .map(|k| (k.clone(), serde_json::Value::Null)) + .collect(); + if !stale.is_empty() { + spec["nodeSelector"] = serde_json::Value::Object(stale); + } + json!({ "template": { "spec": spec } }) +} + +/// Where a service runs, changed in place: Kubernetes replaces its pods +/// with the same image, on the servers picked. Its cron jobs, made from +/// its pod template, follow. +async fn place( + agent: &Agent, + service: &ServiceRef, + server_names: &[String], + server_tags: &[String], + cron_jobs: &[pyo_proto::CronTask], +) -> anyhow::Result { + let c = agent.kube.clone(); + let ns = service.namespace.as_str(); + let pp = PatchParams::default(); + let found = match service.workload_kind.as_str() { + "CronJob" => { + let api = Api::::namespaced(c.clone(), ns); + match api.get_opt(&service.name).await? { + Some(cron) => { + let selector = cron + .spec + .job_template + .spec + .as_ref() + .and_then(|s| s.template.spec.as_ref()) + .and_then(|s| s.node_selector.clone()); + let body = json!({ "spec": { "jobTemplate": { "spec": place_patch(server_names, server_tags, selector.as_ref()) } } }); + api.patch(&service.name, &pp, &merge(body)).await?; + true + } + None => false, + } + } + "StatefulSet" => { + let api = Api::::namespaced(c.clone(), ns); + match api.get_opt(&service.name).await? { + Some(set) => { + let selector = set + .spec + .as_ref() + .and_then(|s| s.template.spec.as_ref()) + .and_then(|s| s.node_selector.clone()); + let body = json!({ "spec": place_patch(server_names, server_tags, selector.as_ref()) }); + api.patch(&service.name, &pp, &merge(body)).await?; + true + } + None => false, + } + } + _ => { + let api = Api::::namespaced(c.clone(), ns); + match api.get_opt(&service.name).await? { + Some(d) => { + let selector = d + .spec + .as_ref() + .and_then(|s| s.template.spec.as_ref()) + .and_then(|s| s.node_selector.clone()); + let body = json!({ "spec": place_patch(server_names, server_tags, selector.as_ref()) }); + api.patch(&service.name, &pp, &merge(body)).await?; + true + } + None => false, + } + } + }; + // Not running anything of its own (a static site, or not out yet): the + // next rollout places it. + if !found { + return Ok(format!("{} has no workload to move", service.name)); + } + if !cron_jobs.is_empty() { + crate::cron::sync(&c, service, cron_jobs).await?; + } + Ok(format!("Moving {} to the servers picked", service.name)) +} + async fn set_autoscale( agent: &Agent, service: &ServiceRef, @@ -449,7 +577,8 @@ pub async fn wait_let_go( let pods = Api::::namespaced(client.clone(), ns); let deadline = tokio::time::Instant::now() + wait; loop { - let users = claim_users(&pods.list(&ListParams::default()).await?.items, claim); + let live = ListParams::default().fields(crate::pods::LIVE); + let users = claim_users(&crate::pods::list_pods(&pods, &live).await?, claim); if users.is_empty() { return Ok(None); } @@ -558,14 +687,65 @@ async fn cordon( )) } -async fn logs(agent: &Agent, service: &ServiceRef, tail_lines: i64) -> CommandResult { +async fn logs( + agent: &Agent, + service: &ServiceRef, + tail_lines: i64, + since_seconds: Option, + replica: &str, +) -> CommandResult { + match read_logs(agent, service, tail_lines, since_seconds, replica).await { + Ok(r) => CommandResult { + ok: true, + message: Some(if r.static_site { + "Served as static files".into() + } else { + format!("{} pod(s)", r.pods.len()) + }), + logs: r.lines, + data: None, + }, + Err(e) => failed(e), + } +} + +/// A service's recent output, as [`read_logs`] found it. +pub struct RecentLogs { + /// Oldest first, the last `tail_lines` of all. + pub lines: Vec, + /// The replicas read. + pub pods: Vec, + /// The newest line's time of each replica that had output. + pub newest: std::collections::HashMap, + /// A static site: its requests, from pyo-static's output. + pub static_site: bool, +} + +/// The last `tail_lines` lines of each of the service's replicas (or only +/// `replica`), and of all of them together. +pub async fn read_logs( + agent: &Agent, + service: &ServiceRef, + tail_lines: i64, + since_seconds: Option, + replica: &str, +) -> Result { let pods = Api::::namespaced(agent.kube.clone(), &service.namespace); - let list = match pods - .list(&ListParams::default().labels(&format!("{SERVICE_LABEL}={}", service.service_id))) - .await - { - Ok(l) => l.items, - Err(e) => return failed(format!("Couldn't list pods: {e}")), + let mut list = + crate::pods::service_pods(&pods, &format!("{SERVICE_LABEL}={}", service.service_id)) + .await + .map_err(|e| format!("Couldn't list pods: {e}"))?; + if !replica.is_empty() { + list.retain(|p| p.name_any() == replica); + if list.is_empty() { + return Err(format!("{} has no replica {replica}.", service.name)); + } + } + let mut out = RecentLogs { + lines: vec![], + pods: list.iter().map(|p| p.name_any()).collect(), + newest: Default::default(), + static_site: false, }; // A static site: its requests, from pyo-static's output. if list.is_empty() @@ -573,48 +753,29 @@ async fn logs(agent: &Agent, service: &ServiceRef, tail_lines: i64) -> CommandRe .await .unwrap_or(false) { - return match crate::sites::logs(&agent.kube, &service.service_id, tail_lines).await { - Ok(logs) => CommandResult { - ok: true, - message: Some("Served as static files".into()), - logs, - data: None, - }, - Err(e) => failed(format!( - "Couldn't read the static file server's output: {e}" - )), - }; + out.lines = crate::sites::logs(&agent.kube, &service.service_id, tail_lines) + .await + .map_err(|e| format!("Couldn't read the static file server's output: {e}"))?; + out.static_site = true; + return Ok(out); } - let mut lines: Vec = vec![]; - for p in &list { - let name = p.name_any(); + for name in &out.pods { let lp = LogParams { tail_lines: Some(tail_lines.clamp(1, 2000)), + since_seconds: since_seconds.filter(|s| *s > 0), timestamps: true, ..Default::default() }; - match pods.logs(&name, &lp).await { - Ok(out) => { - for l in out.lines() { - // "2026-10-28T10:00:00.123456789Z message" - let (at, msg) = match l.split_once(' ') { - Some((ts, rest)) => match ts.parse::() { - Ok(t) => (t.as_millisecond(), rest), - Err(_) => (now_ms(), l), - }, - None => (now_ms(), l), - }; - // Its words, colors aside; the colors stay for the dashboard. - let level = pyo_proto::ansi::level_of(msg); - lines.push(LogLine { - at, - level: level.into(), - source: name.clone(), - message: msg.chars().take(4000).collect(), - }); + match pods.logs(name, &lp).await { + Ok(text) => { + for l in text.lines() { + let line = log_line(name, l); + let newest = out.newest.entry(name.clone()).or_insert(line.at); + *newest = (*newest).max(line.at); + out.lines.push(line); } } - Err(e) => lines.push(LogLine { + Err(e) => out.lines.push(LogLine { at: now_ms(), level: "warn".into(), source: name.clone(), @@ -622,13 +783,29 @@ async fn logs(agent: &Agent, service: &ServiceRef, tail_lines: i64) -> CommandRe }), } } - lines.sort_by_key(|l| l.at); - let skip = lines.len().saturating_sub(tail_lines as usize); - CommandResult { - ok: true, - message: Some(format!("{} pod(s)", list.len())), - logs: lines.into_iter().skip(skip).collect(), - data: None, + out.lines.sort_by_key(|l| l.at); + let skip = out.lines.len().saturating_sub(tail_lines as usize); + out.lines.drain(..skip); + Ok(out) +} + +/// One line of a pod's output read with timestamps +/// ("2026-10-28T10:00:00.123456789Z message"), as `pod` printed it. +pub fn log_line(pod: &str, l: &str) -> LogLine { + let (at, msg) = match l.split_once(' ') { + Some((ts, rest)) => match ts.parse::() { + Ok(t) => (t.as_millisecond(), rest), + Err(_) => (now_ms(), l), + }, + None => (now_ms(), l), + }; + // Its words, colors aside; the colors stay for the dashboard. + let level = pyo_proto::ansi::level_of(msg); + LogLine { + at, + level: level.into(), + source: pod.to_owned(), + message: msg.chars().take(4000).collect(), } } @@ -715,6 +892,40 @@ mod tests { .collect() } + #[test] + fn a_placement_change_patches_the_affinity_and_drops_old_tag_selectors() { + let names = vec!["server-1".to_owned()]; + let tags = vec!["gpu".to_owned()]; + // A rollout that placed by tag in its node selector: those labels go, + // the rest (location, GPU) stay as they are. + let selector = labels(&[ + ("pyo/tag-fast", "true"), + ("pyo/gpu", "nvidia"), + ("topology.kubernetes.io/region", "sg"), + ]); + let p = place_patch(&names, &tags, Some(&selector)); + assert_eq!( + p["template"]["spec"]["affinity"], + pyo_proto::placement_affinity(&names, &tags) + ); + assert_eq!( + p["template"]["spec"]["nodeSelector"], + json!({ "pyo/tag-fast": null }) + ); + // Back to any server: the affinity every server matches, and no + // node selector change when there's nothing stale. + let p = place_patch(&[], &[], Some(&labels(&[("pyo/gpu", "nvidia")]))); + assert_eq!( + p["template"]["spec"]["affinity"]["nodeAffinity"]["requiredDuringSchedulingIgnoredDuringExecution"] + ["nodeSelectorTerms"][0]["matchExpressions"][0]["operator"], + "Exists" + ); + assert!(p["template"]["spec"].get("nodeSelector").is_none()); + // It's a valid pod template for Kubernetes. + let _: k8s_openapi::api::core::v1::PodTemplateSpec = + serde_json::from_value(p["template"].clone()).unwrap(); + } + #[test] fn only_a_volumes_own_claim_is_deleted() { let ours = labels(&[ diff --git a/crates/pyo-agent/src/api.rs b/crates/pyo-agent/src/api.rs index ee909c5b..038e16cb 100644 --- a/crates/pyo-agent/src/api.rs +++ b/crates/pyo-agent/src/api.rs @@ -14,6 +14,12 @@ pub struct PyoApi { base: String, http: reqwest::Client, token: String, + /// With a client certificate (trust.rs): the same TLS for terminals. + tls: Option>, + /// Signed commands only (trust.rs). + verifier: Option>, + /// Every request signed with the agent's key (trust.rs `KeyIdentity`). + signer: Option>, } impl PyoApi { @@ -42,6 +48,18 @@ impl PyoApi { } pub fn new(url: &str, token: &str) -> anyhow::Result { + Self::with_trust(url, token, None, None, None) + } + + /// With Pyo Cloud's TLS (a pinned CA and a client certificate) and its + /// command signatures, when the install sets them (trust.rs). + pub fn with_trust( + url: &str, + token: &str, + tls: Option, + verifier: Option>, + signer: Option>, + ) -> anyhow::Result { let mut headers = HeaderMap::new(); let mut auth = HeaderValue::from_str(&format!("Bearer {token}")) .context("token has invalid characters")?; @@ -53,17 +71,69 @@ impl PyoApi { ); let instance = format!("{:x}{:x}", std::process::id(), pyo_proto::now_ms()); headers.insert(AGENT_INSTANCE_HEADER, HeaderValue::from_str(&instance)?); - let http = reqwest::Client::builder() + let mut http = reqwest::Client::builder() .default_headers(headers) - .connect_timeout(Duration::from_secs(10)) - .build()?; + .connect_timeout(Duration::from_secs(10)); + if let Some(tls) = &tls { + http = http.use_preconfigured_tls(tls.clone()); + } Ok(Self { base: format!("{}/api/agent/v1", url.trim_end_matches('/')), - http, + http: http.build()?, token: token.to_owned(), + tls: tls.map(std::sync::Arc::new), + verifier, + signer, }) } + /// A request to `path` (with its query) under the agent routes, signed + /// when the agent signs its requests. + async fn send( + &self, + method: reqwest::Method, + path: &str, + body: Option>, + timeout: Duration, + ) -> reqwest::Result { + self.send_with(method, path, body, timeout, &[]).await + } + + async fn send_with( + &self, + method: reqwest::Method, + path: &str, + body: Option>, + timeout: Duration, + extra: &[(&str, &str)], + ) -> reqwest::Result { + let url = format!("{}{path}", self.base); + let mut req = self.http.request(method.clone(), &url).timeout(timeout); + for (k, v) in extra { + req = req.header(*k, *v); + } + let bytes = body.unwrap_or_default(); + if let Some(signer) = &self.signer { + let signed_path = reqwest::Url::parse(&url) + .map(|u| match u.query() { + Some(q) => format!("{}?{q}", u.path()), + None => u.path().to_owned(), + }) + .unwrap_or_default(); + for (k, v) in signer.headers(method.as_str(), &signed_path, &bytes) { + req = req.header(k, v); + } + } + if !bytes.is_empty() { + req = req.header(reqwest::header::CONTENT_TYPE, "application/json").body(bytes); + } + req.send().await + } + + fn json(v: &T) -> Option> { + Some(serde_json::to_vec(v).unwrap_or_default()) + } + async fn check(res: reqwest::Response) -> anyhow::Result { let status = res.status(); if status.is_success() { @@ -73,26 +143,57 @@ impl PyoApi { anyhow::bail!("{status}: {body}") } - /// Report the cluster; the reply carries what the API wants applied (node location labels). - pub async fn heartbeat(&self, hb: &Heartbeat) -> anyhow::Result { + /// A request whose answer the agent acts on. With signed commands only + /// (trust.rs), the answer must be signed for this cluster and this + /// request (a fresh nonce): anything else is refused, and none of it used. + async fn reply( + &self, + method: reqwest::Method, + path: &str, + body: Option>, + ) -> anyhow::Result { + let nonce = pyo_proto::signing::new_nonce(); let res = self - .http - .post(format!("{}/heartbeat", self.base)) - .timeout(Duration::from_secs(20)) - .json(hb) - .send() + .send_with(method, path, body, Duration::from_secs(20), &[(pyo_proto::REPLY_NONCE_HEADER, &nonce)]) .await?; - Ok(Self::check(res).await?.json().await.unwrap_or_default()) + let v: serde_json::Value = Self::check(res).await?.json().await?; + match &self.verifier { + Some(verifier) => verifier.check_reply(&v, &nonce).map_err(|why| { + anyhow::anyhow!("refused Pyo's answer to {path}: {why}. This cluster acts only on answers Pyo's signer signed for it.") + }), + None => Ok(v), + } + } + + /// Report the cluster; the reply carries what the API wants applied (node location labels). + pub async fn heartbeat(&self, hb: &Heartbeat) -> anyhow::Result { + let v = self.reply(reqwest::Method::POST, "/heartbeat", Self::json(hb)).await?; + Ok(serde_json::from_value(v).unwrap_or_default()) } pub async fn poll(&self, wait_secs: u64) -> anyhow::Result> { let res = self - .http - .get(format!("{}/commands?wait={wait_secs}", self.base)) - .timeout(Duration::from_secs(wait_secs + 15)) - .send() + .send( + reqwest::Method::GET, + &format!("/commands?wait={wait_secs}"), + None, + Duration::from_secs(wait_secs + 15), + ) .await?; - let items: Vec = Self::check(res).await?.json().await?; + let mut items: Vec = Self::check(res).await?.json().await?; + if let Some(v) = &self.verifier { + let (ok, refused) = v.check(items).await; + items = ok; + for (id, why) in refused { + tracing::warn!(%id, %why, "refused a command"); + let result = crate::failed(format!( + "Refused: {why}. This cluster runs only commands Pyo's signer signed for it." + )); + if let Err(e) = self.command_result(&id, &result).await { + tracing::warn!(%id, error = %e, "couldn't report a refused command"); + } + } + } let (commands, unreadable) = read_commands(items); for (id, why) in unreadable { tracing::warn!(%id, error = %why, "got a command this agent can't read; is it out of date?"); @@ -108,11 +209,7 @@ impl PyoApi { pub async fn command_result(&self, id: &str, r: &CommandResult) -> anyhow::Result<()> { let res = self - .http - .post(format!("{}/commands/{id}", self.base)) - .timeout(Duration::from_secs(20)) - .json(r) - .send() + .send(reqwest::Method::POST, &format!("/commands/{id}"), Self::json(r), Duration::from_secs(20)) .await?; Self::check(res).await?; Ok(()) @@ -126,17 +223,40 @@ impl PyoApi { tokio_tungstenite::WebSocketStream< tokio_tungstenite::MaybeTlsStream, >, + > { + self.socket(&format!("/terminals/{session_id}")).await + } + + /// A WebSocket to `path` under the agent's endpoints, signed like its + /// other requests: a terminal's, or a log follow's. + pub async fn socket( + &self, + path: &str, + ) -> anyhow::Result< + tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >, > { use tokio_tungstenite::tungstenite::client::IntoClientRequest; - let url = format!("{}/terminals/{session_id}", self.base).replacen("http", "ws", 1); + let url = format!("{}{path}", self.base).replacen("http", "ws", 1); let mut req = url.into_client_request()?; req.headers_mut().insert( AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", self.token))?, ); + if let Some(signer) = &self.signer { + let path = req.uri().path().to_owned(); + for (k, v) in signer.headers("GET", &path, b"") { + req.headers_mut().insert(k, HeaderValue::from_str(&v)?); + } + } + let connector = self + .tls + .clone() + .map(tokio_tungstenite::Connector::Rustls); let (ws, _) = tokio::time::timeout( Duration::from_secs(15), - tokio_tungstenite::connect_async(req), + tokio_tungstenite::connect_async_tls_with_config(req, None, false, connector), ) .await .context("timed out")??; @@ -145,40 +265,85 @@ impl PyoApi { /// A private registry's login, for a service's pull secret. pub async fn registry_login(&self, id: &str) -> anyhow::Result { - let res = self - .http - .get(format!("{}/registry-logins/{id}", self.base)) - .timeout(Duration::from_secs(20)) - .send() - .await?; - Ok(Self::check(res).await?.json().await?) + let v = self.reply(reqwest::Method::GET, &format!("/registry-logins/{id}"), None).await?; + Ok(serde_json::from_value(v)?) } /// Pyo's address (what this agent reaches it at) and a token for this /// cluster's pyo-static, which reads static sites' folders with it. pub async fn static_login(&self) -> anyhow::Result<(String, String)> { let res = self - .http - .get(format!("{}/static-login", self.base)) - .timeout(Duration::from_secs(20)) - .send() + .send(reqwest::Method::GET, "/static-login", None, Duration::from_secs(20)) .await?; let v: serde_json::Value = Self::check(res).await?.json().await?; let token = v["token"].as_str().unwrap_or("").to_owned(); anyhow::ensure!(!token.is_empty(), "Pyo sent no token"); - let url = self.base.trim_end_matches("/api/agent/v1").to_owned(); - Ok((url, token)) + Ok((self.base_url(), token)) } - /// An uploaded certificate and its key, for a domain using it. - pub async fn certificate(&self, id: &str) -> anyhow::Result { + /// Vector's batch, sent on as this agent's own request (relay.rs): Pyo's + /// status and answer. + pub async fn relay(&self, path: &str, body: Vec) -> anyhow::Result<(u16, String)> { + let res = self.send(reqwest::Method::POST, path, Some(body), Duration::from_secs(30)).await?; + let status = res.status().as_u16(); + Ok((status, res.text().await.unwrap_or_default())) + } + + /// Pyo's view of this cluster's traffic for its traffic store: which + /// hosts and ports are services', firewalls, the IP setting and the + /// team's limits. Signed like any answer the agent acts on. + pub async fn traffic_context(&self) -> anyhow::Result { + let v = self.reply(reqwest::Method::GET, "/traffic-context", None).await?; + Ok(serde_json::from_value(v)?) + } + + /// Finished minutes of traffic totals, sent on from the traffic store. + pub async fn traffic_totals(&self, batch: &pyo_proto::traffic::TotalsBatch) -> anyhow::Result<()> { let res = self - .http - .get(format!("{}/certificates/{id}", self.base)) - .timeout(Duration::from_secs(20)) - .send() + .send(reqwest::Method::POST, "/traffic-totals", Self::json(batch), Duration::from_secs(30)) .await?; - Ok(Self::check(res).await?.json().await?) + Self::check(res).await?; + Ok(()) + } + + /// Pyo's address, as this agent reaches it (for its components). + pub fn base_url(&self) -> String { + self.base.trim_end_matches("/api/agent/v1").to_owned() + } + + /// Whether a component's key is still one Pyo knows for this cluster. + pub async fn component_key_live(&self, key_id: &str) -> anyhow::Result { + let res = self + .send(reqwest::Method::GET, &format!("/component-keys/{key_id}"), None, Duration::from_secs(20)) + .await?; + match res.status() { + s if s.is_success() => Ok(true), + reqwest::StatusCode::NOT_FOUND => Ok(false), + _ => Err(Self::check(res).await.err().unwrap_or_else(|| anyhow::anyhow!("unexpected answer"))), + } + } + + /// Registers a component's public key (trust.rs `component_key`): its key id. + pub async fn register_component_key( + &self, + component: &str, + builder_id: Option<&str>, + public_key: &str, + ) -> anyhow::Result { + let body = serde_json::json!({ "component": component, "builderId": builder_id, "publicKey": public_key }); + let res = self + .send(reqwest::Method::POST, "/component-keys", Self::json(&body), Duration::from_secs(20)) + .await?; + let v: serde_json::Value = Self::check(res).await?.json().await?; + let id = v["keyId"].as_str().unwrap_or("").to_owned(); + anyhow::ensure!(!id.is_empty(), "Pyo sent no key id"); + Ok(id) + } + + /// An uploaded certificate and its key, for a domain using it. + pub async fn certificate(&self, id: &str) -> anyhow::Result { + let v = self.reply(reqwest::Method::GET, &format!("/certificates/{id}"), None).await?; + Ok(serde_json::from_value(v)?) } /// Retries briefly: a lost stage report leaves the dashboard stale. @@ -190,14 +355,12 @@ impl PyoApi { let mut last = None; for attempt in 0..4 { let sent = self - .http - .post(format!( - "{}/deployments/{deployment_id}/progress", - self.base - )) - .timeout(Duration::from_secs(20)) - .json(p) - .send() + .send( + reqwest::Method::POST, + &format!("/deployments/{deployment_id}/progress"), + Self::json(p), + Duration::from_secs(20), + ) .await; match sent { Ok(res) => match Self::check(res).await { diff --git a/crates/pyo-agent/src/builder.rs b/crates/pyo-agent/src/builder.rs index b0f1dd7e..16a8807b 100644 --- a/crates/pyo-agent/src/builder.rs +++ b/crates/pyo-agent/src/builder.rs @@ -72,13 +72,34 @@ pub async fn ensure(agent: &Agent, spec: &BuilderSpec) -> anyhow::Result let pp = PatchParams::apply(MANAGER).force(); let labels = json!({ "app.kubernetes.io/name": "pyo-builder", "app.kubernetes.io/managed-by": MANAGER, "pyo/builder-id": spec.builder_id }); + // Its own key, made here and registered with Pyo: it signs its + // requests with it. The token is only its registry door login. + let mut env = serde_json::Map::new(); + env.insert("PYO_API_URL".into(), json!(spec.api_url)); + if !spec.token.is_empty() { + env.insert("PYO_BUILDER_TOKEN".into(), json!(spec.token)); + } + match crate::trust::component_key(&agent.api, "builder", Some(&spec.builder_id)).await { + Ok((key_id, pkcs8)) => { + env.insert("PYO_BUILDER_KEY_ID".into(), json!(key_id)); + env.insert("PYO_BUILDER_KEY".into(), json!(pkcs8)); + } + Err(e) => tracing::warn!(builder = %spec.builder_id, error = %format!("{e:#}"), "couldn't register the builder's key"), + } + // Restarted on a new login: it reads them at start. + let login_stamp = pyo_proto::token_hash(&format!( + "{}\n{}", + env.get("PYO_BUILDER_KEY_ID").and_then(|v| v.as_str()).unwrap_or(""), + pyo_proto::token_hash(&spec.token) + ))[..16] + .to_owned(); Api::::namespaced(c.clone(), NS) .patch( &name, &pp, &Patch::Apply(json!({ "apiVersion": "v1", "kind": "Secret", "metadata": { "name": name, "labels": labels }, "type": "Opaque", - "stringData": { "PYO_API_URL": spec.api_url, "PYO_BUILDER_TOKEN": spec.token }, + "stringData": env, })), ) .await?; @@ -106,7 +127,7 @@ pub async fn ensure(agent: &Agent, spec: &BuilderSpec) -> anyhow::Result "strategy": { "type": "Recreate" }, "selector": { "matchLabels": { "pyo/builder-id": spec.builder_id } }, "template": { - "metadata": { "labels": labels }, + "metadata": { "labels": labels, "annotations": { "pyo.dev/login": login_stamp } }, "spec": { "nodeSelector": { "kubernetes.io/hostname": spec.server }, // Build-only servers (join.sh --builder) are tainted for everything else. diff --git a/crates/pyo-agent/src/databases.rs b/crates/pyo-agent/src/databases.rs index be9a46e9..25feb645 100644 --- a/crates/pyo-agent/src/databases.rs +++ b/crates/pyo-agent/src/databases.rs @@ -460,70 +460,23 @@ pub async fn logs( since_seconds: Option, ) -> CommandResult { let pods_api = Api::::namespaced(client.clone(), ns); - let pods: Vec = match pods_api.list(&ListParams::default()).await { - Ok(l) => l - .items - .into_iter() - .filter(|p| is_member(p.labels(), name)) - .collect(), + let pods = match member_pods(&pods_api, name).await { + Ok(p) => p, Err(e) => return crate::failed(format!("Couldn't list pods: {e}")), }; let tail = tail_lines.clamp(1, 5000); let mut lines: Vec = vec![]; - let mut info = serde_json::Map::new(); for p in &pods { let pod = p.name_any(); - let keep = [ - "pyo.dev/component", - "pyo.dev/role", - "cnpg.io/instanceRole", - "cnpg.io/cluster", - "cnpg.io/poolerName", - "moco.cybozu.com/role", - ]; - let labels: serde_json::Map = p - .labels() - .iter() - .filter(|(k, _)| keep.contains(&k.as_str())) - .map(|(k, v)| (k.clone(), json!(v))) - .collect(); - info.insert(pod.clone(), json!({ "labels": labels, "server": p.spec.as_ref().and_then(|s| s.node_name.clone()) })); - // The main container: CloudNativePG's "postgres", MOCO's "mysqld", else the first. - let container = p - .spec - .as_ref() - .and_then(|s| { - s.containers - .iter() - .find(|c| c.name == "postgres" || c.name == "mysqld") - .or(s.containers.first()) - }) - .map(|c| c.name.clone()); let lp = LogParams { tail_lines: Some(tail), since_seconds, timestamps: true, - container, + container: main_container(p), ..Default::default() }; match pods_api.logs(&pod, &lp).await { - Ok(out) => { - for l in out.lines() { - let (at, msg) = match l.split_once(' ') { - Some((ts, rest)) => match ts.parse::() { - Ok(t) => (t.as_millisecond(), rest), - Err(_) => (pyo_proto::now_ms(), l), - }, - None => (pyo_proto::now_ms(), l), - }; - lines.push(LogLine { - at, - level: String::new(), - source: pod.clone(), - message: msg.chars().take(8000).collect(), - }); - } - } + Ok(out) => lines.extend(out.lines().map(|l| log_line(&pod, l))), Err(e) => lines.push(LogLine { at: pyo_proto::now_ms(), level: "warn".into(), @@ -535,10 +488,93 @@ pub async fn logs( lines.sort_by_key(|l| l.at); let skip = lines.len().saturating_sub(tail as usize); let lines: Vec = lines.into_iter().skip(skip).collect(); + let names: std::collections::HashSet = pods.iter().map(|p| p.name_any()).collect(); + let events = events(client, ns, name, &names).await; + CommandResult { + ok: true, + message: Some(format!("{} pod(s)", pods.len())), + logs: lines, + data: Some(json!({ "pods": pods_info(&pods), "events": events })), + } +} - // Events about the Database, its CloudNativePG objects (cluster, - // poolers, backups), its MOCO objects (MySQL) and its pods. - let pod_names: std::collections::HashSet = pods.iter().map(|p| p.name_any()).collect(); +/// The database's pods: its instances, poolers, sentinels, jobs. +/// A page at a time, keeping only its members: the namespace may hold +/// thousands of other pods that ended. +pub async fn member_pods(pods: &Api, name: &str) -> kube::Result> { + crate::pods::list(pods, &ListParams::default(), |p| { + is_member(p.labels(), name).then(|| crate::pods::slim_pod(p)) + }) + .await +} + +/// Each pod's labels that tell its part, and its server, by name. +pub fn pods_info(pods: &[Pod]) -> Value { + let keep = [ + "pyo.dev/component", + "pyo.dev/role", + "cnpg.io/instanceRole", + "cnpg.io/cluster", + "cnpg.io/poolerName", + "moco.cybozu.com/role", + ]; + let mut info = serde_json::Map::new(); + for p in pods { + let labels: serde_json::Map = p + .labels() + .iter() + .filter(|(k, _)| keep.contains(&k.as_str())) + .map(|(k, v)| (k.clone(), json!(v))) + .collect(); + info.insert( + p.name_any(), + json!({ "labels": labels, "server": p.spec.as_ref().and_then(|s| s.node_name.clone()) }), + ); + } + Value::Object(info) +} + +/// A pod's main container: CloudNativePG's "postgres", MOCO's "mysqld", +/// else the first. +pub fn main_container(p: &Pod) -> Option { + p.spec + .as_ref() + .and_then(|s| { + s.containers + .iter() + .find(|c| c.name == "postgres" || c.name == "mysqld") + .or(s.containers.first()) + }) + .map(|c| c.name.clone()) +} + +/// One line of a database pod's output read with timestamps, as printed +/// (the API reads its level and message). +pub fn log_line(pod: &str, l: &str) -> LogLine { + let (at, msg) = match l.split_once(' ') { + Some((ts, rest)) => match ts.parse::() { + Ok(t) => (t.as_millisecond(), rest), + Err(_) => (pyo_proto::now_ms(), l), + }, + None => (pyo_proto::now_ms(), l), + }; + LogLine { + at, + level: String::new(), + source: pod.to_owned(), + message: msg.chars().take(8000).collect(), + } +} + +/// Events about the Database, its CloudNativePG objects (cluster, +/// poolers, backups), its MOCO objects (MySQL) and its pods (`pod_names`), +/// oldest first. +pub async fn events( + client: &Client, + ns: &str, + name: &str, + pod_names: &std::collections::HashSet, +) -> Vec { let prefix = format!("{name}-"); let events = crate::pods::list( &Api::::namespaced(client.clone(), ns), @@ -568,7 +604,7 @@ pub async fn logs( }, ) .await; - let events: Vec = match events { + let mut events: Vec = match events { Ok(l) => l .into_iter() .map(|e| { @@ -597,12 +633,15 @@ pub async fn logs( .collect(), Err(_) => vec![], }; - CommandResult { - ok: true, - message: Some(format!("{} pod(s)", pods.len())), - logs: lines, - data: Some(json!({ "pods": info, "events": events })), - } + // The same order each time, so a follow sends them only when they change. + events.sort_by_key(|e| { + ( + e["at"].as_i64().unwrap_or(0), + e["object"].to_string(), + e["reason"].to_string(), + ) + }); + events } #[cfg(test)] diff --git a/crates/pyo-agent/src/logfollow.rs b/crates/pyo-agent/src/logfollow.rs new file mode 100644 index 00000000..f7871068 --- /dev/null +++ b/crates/pyo-agent/src/logfollow.rs @@ -0,0 +1,572 @@ +//! Following a service's logs (`pyo logs -f`, the dashboard's live logs) +//! or a database's: one signed command, then new lines pushed over a +//! WebSocket this agent dials to Pyo, instead of a command every few +//! seconds. +//! +//! First the recent lines, as `fetch_logs` (or `fetch_database_logs`) +//! reads them. Then each replica's output as Kubernetes streams it, from +//! just after its newest line sent. Replicas that start later (a rollout, +//! a failover) are followed from their start. A database's follow also +//! sends its pods' parts and its events when they change. It ends when Pyo +//! closes the socket, or after [`LOG_FOLLOW_SECS`]. + +use std::collections::{HashMap, HashSet}; +use std::time::Duration; + +use futures::{AsyncBufReadExt, SinkExt, StreamExt}; +use k8s_openapi::api::core::v1::Pod; +use kube::{Api, ResourceExt, api::LogParams}; +use pyo_proto::{LOG_FOLLOW_SECS, LogFrame, LogLine, ServiceRef}; +use tokio::{sync::mpsc, task::JoinSet}; +use tokio_tungstenite::tungstenite::Message; + +use crate::{Agent, actions::RecentLogs, observe::SERVICE_LABEL}; + +/// How often the replicas are listed again, for new ones. +const RELIST: Duration = Duration::from_secs(5); +/// How often a database's events are read again (in listings). +const EVENTS_EVERY: u32 = 3; +/// How often a static site's requests are read again. +const STATIC_POLL: Duration = Duration::from_secs(2); +/// An empty frame this long after the last one, so proxies keep the +/// connection open while nothing is printed. +const KEEPALIVE: Duration = Duration::from_secs(25); +/// The most lines in one frame. +const FRAME_LINES: usize = 500; +/// The most lines of a new replica's output from before it was followed. +const NEW_REPLICA_LINES: i64 = 2000; + +/// What to send first. +pub struct Start { + pub tail_lines: i64, + pub since_seconds: Option, + pub replica: String, +} + +type Socket = + tokio_tungstenite::WebSocketStream>; + +/// What a follower hands the socket: a line, or another frame (a +/// database's pods or events), in order. +enum Out { + Line(LogLine), + Frame(LogFrame), +} + +/// How a pod's output lines are read: a service's or a database's. +type Reader = fn(&str, &str) -> LogLine; + +fn frame(f: &LogFrame) -> Message { + Message::text(serde_json::to_string(f).unwrap_or_default()) +} + +/// The follow's socket to Pyo, or none (and why, logged). +async fn dial(agent: &Agent, session_id: &str) -> Option { + match agent + .api + .socket(&format!("/log-follows/{session_id}")) + .await + { + Ok(ws) => Some(ws), + Err(e) => { + tracing::warn!(%session_id, error = %e, "log follow: couldn't reach the API"); + None + } + } +} + +/// It can't follow: says why and closes. +async fn refuse(mut ws: Socket, message: String) { + let _ = ws.send(frame(&LogFrame::Error { message })).await; + let _ = ws.close(None).await; +} + +pub async fn run(agent: Agent, session_id: String, service: ServiceRef, start: Start) { + let Some(ws) = dial(&agent, &session_id).await else { + return; + }; + let started = pyo_proto::now_ms(); + let mut recent = match crate::actions::read_logs( + &agent, + &service, + start.tail_lines, + start.since_seconds, + &start.replica, + ) + .await + { + Ok(r) => r, + Err(message) => return refuse(ws, message).await, + }; + let lines = std::mem::take(&mut recent.lines); + let (out, rx) = mpsc::channel::(4096); + let follower = if recent.static_site { + let newest = lines.iter().map(|l| l.at).max().unwrap_or(started); + let seen = lines + .iter() + .filter(|l| l.at == newest) + .map(line_key) + .collect(); + tokio::spawn(static_site( + agent.clone(), + service.service_id.clone(), + newest, + seen, + out, + )) + } else { + tokio::spawn(replicas( + agent.clone(), + service.clone(), + start.replica, + recent, + floor(started, start.since_seconds), + out, + )) + }; + pump(ws, vec![LogFrame::Lines { lines }], rx).await; + follower.abort(); + tracing::debug!(%session_id, service = %service.name, "log follow ended"); +} + +/// Follows database `name` in namespace `ns`: its pods' parts, recent +/// lines and events first, then as they change. +pub async fn run_database( + agent: Agent, + session_id: String, + ns: String, + name: String, + start: Start, +) { + let Some(ws) = dial(&agent, &session_id).await else { + return; + }; + let started = pyo_proto::now_ms(); + let r = crate::databases::logs( + &agent.kube, + &ns, + &name, + start.tail_lines, + start.since_seconds, + ) + .await; + if !r.ok { + let message = r + .message + .unwrap_or_else(|| "Couldn't read the database's logs.".into()); + return refuse(ws, message).await; + } + let data = r.data.unwrap_or_default(); + let pods = data["pods"].clone(); + let events: Vec = + serde_json::from_value(data["events"].clone()).unwrap_or_default(); + let mut newest: HashMap = HashMap::new(); + for l in &r.logs { + let n = newest.entry(l.source.clone()).or_insert(l.at); + *n = (*n).max(l.at); + } + // Pods whose lines were all older than the ones sent: from now. + for pod in pods.as_object().into_iter().flatten().map(|(k, _)| k) { + newest.entry(pod.clone()).or_insert(started); + } + let (out, rx) = mpsc::channel::(4096); + let follower = tokio::spawn(database( + agent.clone(), + ns, + name.clone(), + Seen { + pods: pods.clone(), + events: events.clone(), + newest, + floor: floor(started, start.since_seconds), + }, + out, + )); + let first = vec![ + LogFrame::Pods { pods }, + LogFrame::Lines { lines: r.logs }, + LogFrame::Events { events }, + ]; + pump(ws, first, rx).await; + follower.abort(); + tracing::debug!(%session_id, database = %name, "log follow ended"); +} + +/// Where replicas read without output start: the start of `since`, or of +/// their output. +fn floor(started: i64, since_seconds: Option) -> i64 { + since_seconds + .filter(|s| *s > 0) + .map_or(0, |s| started - s * 1000) +} + +/// Sends `first`, then what the follower hands over, until Pyo closes the +/// socket, the follower stops, or [`LOG_FOLLOW_SECS`] pass. +async fn pump(ws: Socket, first: Vec, mut rx: mpsc::Receiver) { + let (mut tx, mut inbound) = ws.split(); + let mut open = true; + for f in &first { + if tx.send(frame(f)).await.is_err() { + open = false; + break; + } + } + if open { + let deadline = tokio::time::sleep(Duration::from_secs(LOG_FOLLOW_SECS)); + tokio::pin!(deadline); + let mut buf = Vec::with_capacity(FRAME_LINES); + 'follow: loop { + tokio::select! { + _ = &mut deadline => break, + m = inbound.next() => match m { + Some(Ok(Message::Close(_)) | Err(_)) | None => break, + Some(Ok(_)) => {} + }, + n = rx.recv_many(&mut buf, FRAME_LINES) => { + if n == 0 { + break; + } + for f in batch(std::mem::take(&mut buf)) { + if tx.send(frame(&f)).await.is_err() { + break 'follow; + } + } + } + _ = tokio::time::sleep(KEEPALIVE) => { + if tx.send(frame(&LogFrame::Lines { lines: vec![] })).await.is_err() { + break; + } + } + } + } + } + let _ = tx.close().await; +} + +/// Lines next to each other go in one frame. Other frames keep their place. +fn batch(items: Vec) -> Vec { + let mut frames = vec![]; + let mut lines = vec![]; + for item in items { + match item { + Out::Line(l) => lines.push(l), + Out::Frame(f) => { + if !lines.is_empty() { + frames.push(LogFrame::Lines { + lines: std::mem::take(&mut lines), + }); + } + frames.push(f); + } + } + } + if !lines.is_empty() { + frames.push(LogFrame::Lines { lines }); + } + frames +} + +/// Follows each replica's output, and new replicas as they come, until +/// `out` closes. +async fn replicas( + agent: Agent, + service: ServiceRef, + replica: String, + recent: RecentLogs, + floor: i64, + out: mpsc::Sender, +) { + let pods = Api::::namespaced(agent.kube.clone(), &service.namespace); + let labels = format!("{SERVICE_LABEL}={}", service.service_id); + // Each replica's newest line sent: its stream goes on after it. + let mut newest: HashMap = recent + .pods + .iter() + .map(|p| (p.clone(), recent.newest.get(p).copied().unwrap_or(floor))) + .collect(); + let mut streams = Streams::default(); + loop { + streams.ended(&mut newest); + match crate::pods::service_pods(&pods, &labels).await { + Ok(list) => { + let names: HashSet = list + .iter() + .map(|p| p.name_any()) + .filter(|n| replica.is_empty() || *n == replica) + .collect(); + newest.retain(|n, _| names.contains(n)); + for name in names { + streams.follow(&pods, name, None, &newest, &out, crate::actions::log_line); + } + } + Err(e) => tracing::debug!(error = %e, "log follow: couldn't list replicas"), + } + tokio::select! { + _ = out.closed() => return, + _ = tokio::time::sleep(RELIST) => {} + } + } +} + +/// What a database's follow sent last. +struct Seen { + pods: serde_json::Value, + events: Vec, + /// Each pod's newest line sent. + newest: HashMap, + /// Where pods read without output start. + floor: i64, +} + +/// Follows a database's pods (new ones too: a failover, a new replica), +/// and sends its pods' parts and its events again when they change. +async fn database(agent: Agent, ns: String, name: String, mut seen: Seen, out: mpsc::Sender) { + let pods = Api::::namespaced(agent.kube.clone(), &ns); + let floor = seen.floor; + let mut newest: HashMap = std::mem::take(&mut seen.newest); + let mut streams = Streams::default(); + let mut round = 0u32; + loop { + streams.ended(&mut newest); + match crate::databases::member_pods(&pods, &name).await { + Ok(list) => { + let info = crate::databases::pods_info(&list); + if info != seen.pods { + seen.pods = info.clone(); + if out + .send(Out::Frame(LogFrame::Pods { pods: info })) + .await + .is_err() + { + return; + } + } + let names: HashSet = list.iter().map(|p| p.name_any()).collect(); + newest.retain(|n, _| names.contains(n)); + for p in &list { + let pod = p.name_any(); + // A new pod: from `floor`. + newest.entry(pod.clone()).or_insert(floor); + streams.follow( + &pods, + pod, + crate::databases::main_container(p), + &newest, + &out, + crate::databases::log_line, + ); + } + round += 1; + if round.is_multiple_of(EVENTS_EVERY) { + let events = crate::databases::events(&agent.kube, &ns, &name, &names).await; + if events != seen.events { + seen.events = events.clone(); + if out + .send(Out::Frame(LogFrame::Events { events })) + .await + .is_err() + { + return; + } + } + } + } + Err(e) => tracing::debug!(error = %e, "log follow: couldn't list the database's pods"), + } + tokio::select! { + _ = out.closed() => return, + _ = tokio::time::sleep(RELIST) => {} + } + } +} + +/// The pods followed now, each by its own stream. +#[derive(Default)] +struct Streams { + following: HashSet, + tasks: JoinSet<(String, i64)>, +} + +impl Streams { + /// Ended (the container restarted, or the pod went): its newest line, + /// so a restart goes on from there. + fn ended(&mut self, newest: &mut HashMap) { + while let Some(r) = self.tasks.try_join_next() { + if let Ok((name, at)) = r { + self.following.remove(&name); + newest.insert(name, at); + } + } + } + + /// Follows pod `name` unless it already is: after its newest line + /// sent, or from its start. + fn follow( + &mut self, + pods: &Api, + name: String, + container: Option, + newest: &HashMap, + out: &mpsc::Sender, + read: Reader, + ) { + if self.following.insert(name.clone()) { + let after = newest.get(&name).copied().unwrap_or(0); + self.tasks.spawn(stream( + pods.clone(), + name, + container, + after, + out.clone(), + read, + )); + } + } +} + +/// Which lines a stream starting after `after` (milliseconds) asks for: +/// from that second on (the lines in it up to `after` are dropped), or a +/// new replica's output from its start. +fn stream_params(after: i64, container: Option) -> LogParams { + let since = (after > 0) + .then(|| k8s_openapi::jiff::Timestamp::from_second(after.div_euclid(1000)).ok()) + .flatten(); + LogParams { + follow: true, + timestamps: true, + tail_lines: since.is_none().then_some(NEW_REPLICA_LINES), + since_time: since, + container, + ..Default::default() + } +} + +/// One pod's output after `after`, until it ends. Gives back the pod's +/// name and its newest line's time. +async fn stream( + pods: Api, + name: String, + container: Option, + after: i64, + out: mpsc::Sender, + read: Reader, +) -> (String, i64) { + let mut newest = after; + match pods + .log_stream(&name, &stream_params(after, container)) + .await + { + Ok(reader) => { + let mut lines = reader.lines(); + while let Some(Ok(l)) = lines.next().await { + let line = read(&name, &l); + if line.at <= after { + continue; + } + newest = newest.max(line.at); + if out.send(Out::Line(line)).await.is_err() { + break; + } + } + } + // Not started yet, or gone: tried again on the next listing. + Err(e) => tracing::debug!(pod = %name, error = %e, "log follow: no stream"), + } + (name, newest) +} + +fn line_key(l: &LogLine) -> String { + format!("{}\u{0}{}\u{0}{}", l.at, l.source, l.message) +} + +/// A static site's requests, read again every few seconds from pyo-static's +/// output (inside the cluster: no command each time). +async fn static_site( + agent: Agent, + service_id: String, + mut newest: i64, + mut seen: HashSet, + out: mpsc::Sender, +) { + loop { + tokio::select! { + _ = out.closed() => return, + _ = tokio::time::sleep(STATIC_POLL) => {} + } + let Ok(mut lines) = crate::sites::logs(&agent.kube, &service_id, 500).await else { + continue; + }; + lines.sort_by_key(|l| l.at); + for l in fresh(&mut newest, &mut seen, lines) { + if out.send(Out::Line(l)).await.is_err() { + return; + } + } + } +} + +/// The lines not sent yet: after `newest`, or at it and not in `seen` +/// (the keys of the lines sent at `newest`). Moves both along. +fn fresh(newest: &mut i64, seen: &mut HashSet, lines: Vec) -> Vec { + let mut out = vec![]; + for l in lines { + if l.at < *newest { + continue; + } + if l.at > *newest { + *newest = l.at; + seen.clear(); + } + if seen.insert(line_key(&l)) { + out.push(l); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn line(at: i64, message: &str) -> LogLine { + LogLine { + at, + level: "info".into(), + source: "pyo-static-1".into(), + message: message.into(), + } + } + + #[test] + fn a_replica_goes_on_from_the_second_of_its_newest_line() { + let p = stream_params(1_700_000_000_750, None); + assert!(p.follow && p.timestamps); + assert_eq!( + p.since_time.map(|t| t.as_second()), + Some(1_700_000_000), + "the whole second, so no line after it is missed" + ); + assert_eq!(p.tail_lines, None); + let new = stream_params(0, Some("postgres".into())); + assert_eq!(new.container.as_deref(), Some("postgres")); + assert_eq!(new.since_time, None); + assert_eq!(new.tail_lines, Some(NEW_REPLICA_LINES)); + } + + #[test] + fn static_lines_are_sent_once() { + let mut newest = 10; + let mut seen: HashSet = [line_key(&line(10, "a"))].into(); + let got = fresh( + &mut newest, + &mut seen, + vec![line(9, "old"), line(10, "a"), line(10, "b"), line(12, "c")], + ); + let words: Vec<&str> = got.iter().map(|l| l.message.as_str()).collect(); + assert_eq!(words, ["b", "c"]); + assert_eq!(newest, 12); + let again = fresh(&mut newest, &mut seen, vec![line(12, "c"), line(13, "d")]); + assert_eq!(again.len(), 1); + assert_eq!(again[0].message, "d"); + } +} diff --git a/crates/pyo-agent/src/main.rs b/crates/pyo-agent/src/main.rs index 12b6e2fb..05e6bd05 100644 --- a/crates/pyo-agent/src/main.rs +++ b/crates/pyo-agent/src/main.rs @@ -25,20 +25,26 @@ mod gpu; mod install; mod kubelet; mod locate; +mod logfollow; mod observability; mod observe; mod operators; mod pods; mod publicdash; mod refused; +mod registrydoor; +mod relay; mod rollout; mod room; mod runs; mod scope; mod sites; mod tailnet; +mod tailscale; mod terminal; mod tls; +mod traffic; +mod trust; mod upgrade; mod volumes; mod waf; @@ -148,10 +154,18 @@ async fn main() -> anyhow::Result<()> { EnvFilter::try_from_default_env().unwrap_or_else(|_| "pyo_agent=info".into()), ) .init(); + // `pyo-agent sign-request …`: signed request headers, for tests (trust.rs). + if args.get(1).map(String::as_str) == Some("sign-request") { + return trust::sign_request_cli(&args[2..]).await; + } // A server's tailnet pod (tailnet.rs). if args.get(1).map(String::as_str) == Some("tailnet") { return tailnet::run_pod().await; } + // The cluster's traffic store, the pyo-traffic pod (traffic/). + if args.get(1).map(String::as_str) == Some("traffic") { + return traffic::run().await; + } // pyo-host's port forwards on Pyo's machine (forward.rs). if args.get(1).map(String::as_str) == Some("forward") { return forward::run(&args[2..]).await; @@ -170,9 +184,31 @@ async fn main() -> anyhow::Result<()> { .map_err(|_| anyhow::anyhow!("PYO_AGENT_TOKEN is required"))?; let kube = kube::Client::try_default().await?; let policy = scope::read_policy(&kube).await; + // Pyo Cloud: requests signed with the agent's key, or a client + // certificate, and signed commands only (trust.rs). + let key = trust::KeyIdentity::from_env(&url, &token, &kube)?.map(Arc::new); + let identity = match &key { + Some(_) => None, + None => trust::Identity::from_env(&url, &token, &kube)?.map(Arc::new), + }; + if let Some(k) = &key { + k.ensure().await; + tokio::spawn(k.clone().renew_loop()); + } + if let Some(id) = &identity { + id.ensure().await; + tokio::spawn(id.clone().renew_loop()); + } + let verifier = trust::Verifier::from_env(&kube).await?.map(Arc::new); + let tls = match (&key, &identity) { + (Some(k), _) => k.tls.clone(), + (None, Some(i)) => Some(i.tls.clone()), + _ => None, + }; + let api = api::PyoApi::with_trust(&url, &token, tls, verifier, key)?; let agent = Agent { kube, - api: api::PyoApi::new(&url, &token)?, + api, cancels: Default::default(), deploying: Default::default(), routes: Default::default(), @@ -188,6 +224,17 @@ async fn main() -> anyhow::Result<()> { tokio::spawn(gpu::run(agent.kube.clone())); tokio::spawn(gateway::collect_loop(agent.clone())); tokio::spawn(operators::run(agent.kube.clone())); + // pyo-static's key, when the one it has was revoked (trust.rs). + tokio::spawn(sites::renew_login(agent.clone())); + // Vector's data goes to Pyo through this agent (relay.rs). + tokio::spawn(relay::serve(agent.clone())); + // The door of the cluster's own registry (registrydoor.rs): not on + // the cluster Pyo runs on, which has Pyo's own. + if !agent.api.same_cluster() { + tokio::spawn(registrydoor::serve(agent.kube.clone())); + } + // The traffic store's totals to Pyo, Pyo's context to it. + tokio::spawn(traffic::link::run(agent.clone())); } // Checks the policy each run: a cluster made read only later is left be. tokio::spawn(cleanup::run(agent.clone())); @@ -343,6 +390,9 @@ fn ordered_keys(c: &Command) -> Vec { format!("service/{}", t.service.service_id), format!("bundle/{}", pyo_proto::bundles::WAF_ID), ], + // Two changes of where a service runs land in the order made, and + // never put back the objects of a service being deleted. + Command::Place { service, .. } => vec![format!("service/{}", service.service_id)], // A bundle turned off and on again: its install waits for the // removal (which ends once its namespace is gone). Command::ApplyBundle { bundle, .. } => vec![format!("bundle/{}", bundle.id)], @@ -354,6 +404,13 @@ fn ordered_keys(c: &Command) -> Vec { Command::RefreshInstall(_) | Command::UpdateAgent { .. } => { vec!["agent/deployment".to_owned()] } + // The cluster's Tailscale client and names: one change at a time, + // in order (a setup, then the names it makes possible). + Command::TailscaleSetup { .. } + | Command::TailscaleClient { .. } + | Command::TailscaleSync(_) + | Command::TailscaleRemove { .. } => vec!["tailscale".to_owned()], + Command::SyncRegistryTokens(_) => vec!["registry-tokens".to_owned()], _ => vec![], }; keys.sort(); @@ -404,7 +461,7 @@ impl Ordered { } async fn run_command(agent: Agent, envelope: CommandEnvelope) { - let CommandEnvelope { id, command } = envelope; + let CommandEnvelope { id, command, .. } = envelope; tracing::info!(%id, kind = command_kind(&command), "command"); // The customer's policy first: refused commands do nothing. let refused = scope::refusal( @@ -457,16 +514,62 @@ async fn run_command(agent: Agent, envelope: CommandEnvelope) { service, pod, shell, + command, + tty, } => { tokio::spawn(terminal::run( agent.clone(), session_id, service, - pod, - shell, + terminal::Run { + pod, + shell, + command, + tty, + }, )); ok("Opening a terminal.") } + // Followed in its own task until Pyo closes the socket. + Command::FollowLogs { + session_id, + service, + tail_lines, + since_seconds, + replica, + } => { + tokio::spawn(logfollow::run( + agent.clone(), + session_id, + service, + logfollow::Start { + tail_lines, + since_seconds, + replica, + }, + )); + ok("Following logs.") + } + Command::FollowDatabaseLogs { + session_id, + namespace, + name, + tail_lines, + since_seconds, + } => { + tokio::spawn(logfollow::run_database( + agent.clone(), + session_id, + namespace, + name, + logfollow::Start { + tail_lines, + since_seconds, + replica: String::new(), + }, + )); + ok("Following logs.") + } Command::Backup(spec) => backup::run(&agent, *spec).await, Command::ListSnapshots(spec) => backup::snapshots(&agent.kube, *spec).await, Command::ForgetSnapshot(spec) => backup::forget(&agent.kube, *spec).await, @@ -477,6 +580,28 @@ async fn run_command(agent: Agent, envelope: CommandEnvelope) { password, } => backup::setup(&agent, &namespace, &admin, &password).await, Command::UpgradePyo(spec) => upgrade::start(&agent, *spec).await, + Command::TailscaleSetup { token, version } => { + tailscale::run_setup(&agent.kube, token, version).await + } + Command::TailscaleClient { client_id, secret } => { + tailscale::run_client(&agent.kube, &client_id, &secret).await + } + Command::TailscaleTest {} => tailscale::run_test(&agent.kube).await, + Command::TailscaleSync(w) => tailscale::run_sync(&agent.kube, &w).await, + Command::SyncRegistryTokens(t) => match registrydoor::sync(&agent.kube, &t).await { + Ok(m) => ok(&m), + Err(e) => failed(e), + }, + Command::TailscaleKey { description } => { + tailscale::run_key(&agent.kube, &description).await + } + Command::TailscaleCheckName { name, marks } => { + tailscale::run_check_name(&agent.kube, &name, &marks).await + } + Command::TailscaleRemove { names, marks } => { + tailscale::run_remove(&agent.kube, &names, &marks).await + } + Command::SandboxCall(c) => tailscale::sandbox::run(&c).await, // Answered before switching: the switch stops this process. Command::UpdateAgent { image } => { let result = match upgrade::check_agent_image(&agent.kube, &image).await { @@ -555,12 +680,15 @@ fn command_kind(c: &Command) -> &'static str { Command::Stop(_) => "stop", Command::Scale { .. } => "scale", Command::Autoscale { .. } => "autoscale", + Command::Place { .. } => "place", Command::SyncCronJobs { .. } => "sync_cron_jobs", Command::RunCronJob { .. } => "run_cron_job", Command::DeleteService(_) => "delete_service", Command::SetSchedulable { .. } => "set_schedulable", Command::SetMaintenance { .. } => "set_maintenance", Command::FetchLogs { .. } => "fetch_logs", + Command::FollowLogs { .. } => "follow_logs", + Command::FollowDatabaseLogs { .. } => "follow_database_logs", Command::Cancel { .. } => "cancel", Command::EnsureBuilder(_) => "ensure_builder", Command::RemoveBuilder { .. } => "remove_builder", @@ -585,6 +713,16 @@ fn command_kind(c: &Command) -> &'static str { Command::DeleteDatabase { .. } => "delete_database", Command::DeleteVolume { .. } => "delete_volume", Command::FetchDatabaseLogs { .. } => "fetch_database_logs", + Command::QueryTraffic(_) => "query_traffic", + Command::TailscaleSetup { .. } => "tailscale_setup", + Command::TailscaleClient { .. } => "tailscale_client", + Command::TailscaleTest {} => "tailscale_test", + Command::TailscaleSync(_) => "tailscale_sync", + Command::TailscaleKey { .. } => "tailscale_key", + Command::TailscaleCheckName { .. } => "tailscale_check_name", + Command::TailscaleRemove { .. } => "tailscale_remove", + Command::SandboxCall(_) => "sandbox_call", + Command::SyncRegistryTokens(_) => "sync_registry_tokens", 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 cd608a62..0751cc39 100644 --- a/crates/pyo-agent/src/observability.rs +++ b/crates/pyo-agent/src/observability.rs @@ -1,17 +1,21 @@ //! Website analytics and server metrics on this cluster: the gateway -//! (Envoy) writes a JSON access log, and a Vector DaemonSet forwards those lines, plus each -//! server's own load, disk I/O and network (Vector's host_metrics), to the -//! Pyo API with this agent's token. +//! (Envoy) writes a JSON access log, and a Vector DaemonSet sends those +//! lines to the cluster's traffic store (traffic/, the pyo-traffic pod), +//! which keeps them here and adds them up into totals the agent sends to +//! Pyo. Each server's own load, disk I/O and network (Vector's +//! host_metrics) go to Pyo through this agent (relay.rs): Vector holds no +//! credential to Pyo. //! //! Observability is an installation-wide setting, sent with each heartbeat -//! reply. On: the agent (re)applies Vector at its first reply, so upgrading -//! the agent upgrades the pipeline, and on the cluster Pyo runs on it starts -//! ClickHouse. Off: Vector is removed and ClickHouse stopped, its volume -//! (and so the history) kept for when it's back on. +//! reply. On: the agent (re)applies Vector and the traffic store at its +//! first reply, so upgrading the agent upgrades the pipeline, and on the +//! cluster Pyo runs on it starts ClickHouse. Off: Vector and the store are +//! removed and ClickHouse stopped, their volumes (and so the history) kept +//! for when it's back on. use k8s_openapi::api::{ - apps::v1::{DaemonSet, StatefulSet}, - core::v1::{Secret, ServiceAccount}, + apps::v1::{DaemonSet, Deployment, StatefulSet}, + core::v1::{PersistentVolumeClaim, Secret, Service, ServiceAccount}, }; use kube::{ Api, Client, @@ -92,7 +96,7 @@ sinks: pyo_metrics: type: http inputs: [host_kept] - uri: "__API_URL__/api/agent/v1/host-metrics" + uri: "__RELAY__/host-metrics" method: post encoding: codec: json @@ -106,10 +110,12 @@ sinks: timeout_secs: 30 request: retry_attempts: 3 + # The gateway's lines stay in the cluster: the traffic store keeps + # them and sends Pyo only totals (traffic/). pyo: type: http inputs: [access] - uri: "__API_URL__/api/agent/v1/access-logs" + uri: "__STORE__/ingest" method: post encoding: codec: json @@ -117,7 +123,7 @@ sinks: method: newline_delimited auth: strategy: bearer - token: "__TOKEN__" + token: "__STORE_TOKEN__" batch: max_events: 1000 timeout_secs: 5 @@ -141,9 +147,15 @@ pub async fn set(client: &Client, on: bool, pyo_cluster: bool) -> anyhow::Result clickhouse(client, on).await?; } if on { - vector(client).await + // Vector either way: a store that can't be applied yet (its image + // unknown, the install refusing it) is tried again with the next + // heartbeat, and Vector holds its lines meanwhile. + let store = traffic_store(client).await; + vector(client).await?; + store } else { - remove_vector(client).await + remove_vector(client).await?; + remove_traffic_store(client).await } } @@ -195,14 +207,14 @@ async fn vector(client: &Client) -> anyhow::Result<()> { .patch("pyo-vector", &pp(), &Patch::Apply(json!({ "apiVersion": "v1", "kind": "ServiceAccount", "metadata": { "name": "pyo-vector", "labels": labels } }))) .await?; // Vector won't expand env vars in the sink URI, so the config carries the - // URL and token itself, and lives in a Secret. - let url = std::env::var("PYO_API_URL")? - .trim_end_matches('/') - .to_owned(); - let token = std::env::var("PYO_AGENT_TOKEN")?; + // relay's address and token itself, and lives in a Secret. Both are this + // agent process's: a new agent writes them anew. + let relay = crate::relay::endpoint(client).await?; let config = VECTOR_CONFIG - .replace("__API_URL__", &url) - .replace("__TOKEN__", &token); + .replace("__RELAY__", &relay) + .replace("__TOKEN__", crate::relay::token()) + .replace("__STORE__", &crate::traffic::url()) + .replace("__STORE_TOKEN__", crate::traffic::link::token()); Api::::namespaced(client.clone(), NS) .patch( "pyo-vector", @@ -272,6 +284,122 @@ async fn vector(client: &Client) -> anyhow::Result<()> { Ok(()) } +/// 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. +const TRAFFIC_VOLUME: &str = "2Gi"; + +/// The cluster's traffic store (traffic/): one pod on the agent's own image, +/// its volume, and its Service for Vector and the agent. +async fn traffic_store(client: &Client) -> anyhow::Result<()> { + let name = crate::traffic::NAME; + let Some(image) = crate::tailnet::own_image(client).await else { + anyhow::bail!("can't tell the agent's own image for the traffic store"); + }; + let labels = json!({ "app.kubernetes.io/name": name, "app.kubernetes.io/managed-by": MANAGER }); + let claims = Api::::namespaced(client.clone(), NS); + if claims.get_opt(name).await?.is_none() { + claims + .create( + &Default::default(), + &serde_json::from_value(json!({ + "apiVersion": "v1", "kind": "PersistentVolumeClaim", + "metadata": { "name": name, "labels": labels }, + "spec": { "accessModes": ["ReadWriteOnce"], "resources": { "requests": { "storage": TRAFFIC_VOLUME } } }, + }))?, + ) + .await?; + } + let token = crate::traffic::link::token(); + Api::::namespaced(client.clone(), NS) + .patch( + name, + &pp(), + &Patch::Apply(json!({ "apiVersion": "v1", "kind": "Secret", "metadata": { "name": name, "labels": labels }, "type": "Opaque", "stringData": { "PYO_TRAFFIC_TOKEN": token } })), + ) + .await?; + Api::::namespaced(client.clone(), NS) + .patch( + name, + &pp(), + &Patch::Apply(json!({ + "apiVersion": "v1", "kind": "Service", + "metadata": { "name": name, "labels": labels }, + "spec": { "selector": { "app.kubernetes.io/name": name }, "ports": [{ "name": "http", "port": crate::traffic::PORT, "targetPort": crate::traffic::PORT }] }, + })), + ) + .await?; + Api::::namespaced(client.clone(), NS) + .patch( + name, + &pp(), + &Patch::Apply(json!({ + "apiVersion": "apps/v1", "kind": "Deployment", + "metadata": { "name": name, "labels": labels }, + "spec": { + "replicas": 1, + // One pod on the volume at a time. + "strategy": { "type": "Recreate" }, + "selector": { "matchLabels": { "app.kubernetes.io/name": name } }, + "template": { + "metadata": { + "labels": labels, + // A new token (the cluster connected again) restarts it. + "annotations": { "pyo/config-hash": format!("{:x}", fxhash(token)) }, + }, + "spec": { + "automountServiceAccountToken": false, + "tolerations": [{ "key": "nvidia.com/gpu", "operator": "Exists", "effect": "NoSchedule" }], + "securityContext": { "runAsNonRoot": true, "runAsUser": 65532, "runAsGroup": 65532, "fsGroup": 65532, "seccompProfile": { "type": "RuntimeDefault" } }, + "containers": [{ + "name": "traffic", + "image": image, + "imagePullPolicy": "IfNotPresent", + "args": ["traffic"], + "envFrom": [{ "secretRef": { "name": name } }], + "env": [{ "name": "RUST_LOG", "value": "pyo_agent=info" }], + "ports": [{ "name": "http", "containerPort": crate::traffic::PORT }], + "readinessProbe": { "httpGet": { "path": "/healthz", "port": crate::traffic::PORT }, "periodSeconds": 10 }, + // Measured: 5 MiB at rest, 35 to 45 MiB at 1000 + // requests a second over 20 sites (and a query), + // 60 MiB at 2000 a second over 300 sites. + "resources": { "requests": { "cpu": "10m", "memory": "32Mi" }, "limits": { "memory": "128Mi" } }, + "securityContext": { + "runAsNonRoot": true, "runAsUser": 65532, "allowPrivilegeEscalation": false, + "readOnlyRootFilesystem": true, "capabilities": { "drop": ["ALL"] }, + }, + "volumeMounts": [ + { "name": "data", "mountPath": "/data" }, + { "name": "geoip", "mountPath": "/geoip", "readOnly": true }, + ], + }], + "volumes": [ + { "name": "data", "persistentVolumeClaim": { "claimName": name } }, + // The same GeoLite2 Country image the proxies and the + // WAF mount (pyo-proto's system.rs), as the install pins it. + { "name": "geoip", "image": { "reference": pyo_proto::system::geoip_image_from_env(), "pullPolicy": "IfNotPresent" } }, + ], + }, + }, + }, + })), + ) + .await?; + Ok(()) +} + +/// The store's pod and Service go; its volume (the kept requests) stays. +async fn remove_traffic_store(client: &Client) -> anyhow::Result<()> { + let name = crate::traffic::NAME; + let gone = |r: kube::Result<()>| match r { + Err(kube::Error::Api(e)) if e.code == 404 => Ok(()), + r => r, + }; + gone(Api::::namespaced(client.clone(), NS).delete(name, &DeleteParams::default()).await.map(|_| ()))?; + gone(Api::::namespaced(client.clone(), NS).delete(name, &DeleteParams::default()).await.map(|_| ()))?; + Ok(()) +} + /// Small stable hash for the config annotation. fn fxhash(s: &str) -> u64 { s.bytes().fold(0xcbf29ce484222325u64, |h, b| { diff --git a/crates/pyo-agent/src/observe.rs b/crates/pyo-agent/src/observe.rs index 547710de..261dba81 100644 --- a/crates/pyo-agent/src/observe.rs +++ b/crates/pyo-agent/src/observe.rs @@ -871,6 +871,7 @@ pub async fn heartbeat(client: &Client) -> anyhow::Result { public_dashboard: crate::publicdash::report(client).await, host_proof: None, updates: pyo_proto::UPDATES_VERSION, + component_keys: true, scope: None, bundles: crate::bundles::report(client, &bundle_namespaces).await, databases, diff --git a/crates/pyo-agent/src/pods.rs b/crates/pyo-agent/src/pods.rs index 7cedfaec..16db91a2 100644 --- a/crates/pyo-agent/src/pods.rs +++ b/crates/pyo-agent/src/pods.rs @@ -61,6 +61,28 @@ pub async fn list_pods(api: &Api, lp: &ListParams) -> kube::Result list(api, lp, |p| Some(slim_pod(p))).await } +/// The two lists of a service's pods (`selector`): those that haven't +/// ended, and the ended ones of its Jobs (a cron task's output stays +/// readable). Never its other ended pods: an evicted replica has no output +/// left, and a full disk leaves thousands of them. +pub fn service_lists(selector: &str) -> [ListParams; 2] { + [ + ListParams::default().labels(selector).fields(LIVE), + ListParams::default() + .labels(&format!("{selector},{}", crate::runs::JOB_LABEL)) + .fields(ENDED), + ] +} + +/// A service's pods as [`service_lists`] picks them, slim, a page at a time. +pub async fn service_pods(api: &Api, selector: &str) -> kube::Result> { + let mut pods = vec![]; + for lp in service_lists(selector) { + pods.extend(list_pods(api, &lp).await?); + } + Ok(pods) +} + /// A pod with what the agent reads of it: its name, labels, owners and /// times; where it runs; what its containers ask for, their ports and /// security settings; the claims it mounts; and its status. Not its @@ -108,6 +130,19 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn a_services_pods_leave_out_ended_replicas() { + let [live, ended] = service_lists("pyo/service-id=svc_1"); + assert_eq!(live.label_selector.as_deref(), Some("pyo/service-id=svc_1")); + assert_eq!(live.field_selector.as_deref(), Some(LIVE)); + // Ended ones only of its Jobs. + assert_eq!( + ended.label_selector.as_deref(), + Some("pyo/service-id=svc_1,batch.kubernetes.io/job-name") + ); + assert_eq!(ended.field_selector.as_deref(), Some(ENDED)); + } + #[test] fn a_slim_pod_keeps_what_is_read() { let p: Pod = serde_json::from_value(json!({ diff --git a/crates/pyo-agent/src/registrydoor.rs b/crates/pyo-agent/src/registrydoor.rs new file mode 100644 index 00000000..2221e9d0 --- /dev/null +++ b/crates/pyo-agent/src/registrydoor.rs @@ -0,0 +1,388 @@ +//! The door of the cluster's own registry (Pyo Cloud's clusters keep the +//! images they build: connect.sh `--local-registry`). The team pushes and +//! pulls its own images here with its registry tokens, by the same rules +//! as Pyo's own door (pyo-proto registry_door.rs): `//` +//! of its team only, and a pull token only pulls. +//! +//! Pyo never sends a token: only their SHA-256 and what each may do +//! ([`pyo_proto::Command::SyncRegistryTokens`], a signed command), kept in +//! a Secret in pyo-system so a restarted agent still has them. Until the +//! first sync every login is refused. +//! +//! It listens on [`PORT`], behind the Service `pyo-registry-door` that +//! connect.sh makes with the registry. People reach it at the cluster's +//! registry name on its tailnet, the same tailnet route Pyo's own registry +//! has. The registry itself answers only in the cluster. + +use std::sync::RwLock; + +use axum::{ + Router, + body::Body, + extract::Request, + http::{HeaderMap, HeaderValue, StatusCode, header}, + response::{IntoResponse, Response}, + routing::any, +}; +use base64::Engine; +use futures::TryStreamExt; +use k8s_openapi::api::core::v1::Secret; +use kube::api::{Patch, PatchParams}; +use pyo_proto::registry_door::{self, RegistryTokens, Wants}; +use serde_json::json; + +/// Where the door listens (the Service's target port). +pub const PORT: u16 = 5006; +/// The cluster's registry, in the cluster. +const REGISTRY: &str = "pyo-registry.pyo-system.svc.cluster.local:5000"; +/// The Secret the tokens' hashes are kept in. +const SECRET: &str = "pyo-registry-tokens"; +const NS: &str = "pyo-system"; +const KEY: &str = "tokens.json"; + +static TOKENS: RwLock> = RwLock::new(None); + +fn tokens() -> Option { + TOKENS.read().unwrap_or_else(|e| e.into_inner()).clone() +} + +fn set_tokens(t: RegistryTokens) { + *TOKENS.write().unwrap_or_else(|e| e.into_inner()) = Some(t); +} + +/// The tokens Pyo sent: used from now on, and kept. +pub async fn sync(kube: &kube::Client, t: &RegistryTokens) -> Result { + let api = kube::Api::::namespaced(kube.clone(), NS); + let s = json!({ + "apiVersion": "v1", + "kind": "Secret", + "metadata": { "name": SECRET, "namespace": NS, "labels": { "app.kubernetes.io/managed-by": crate::MANAGER } }, + "type": "Opaque", + "stringData": { KEY: serde_json::to_string(t).map_err(|e| e.to_string())? }, + }); + api.patch( + SECRET, + &PatchParams::apply(crate::MANAGER).force(), + &Patch::Apply(&s), + ) + .await + .map_err(|e| format!("couldn't keep the registry tokens: {e}"))?; + let n = t.tokens.len(); + set_tokens(t.clone()); + Ok(format!("{n} registry token(s)")) +} + +/// The kept tokens, at start. +async fn load(kube: &kube::Client) { + let api = kube::Api::::namespaced(kube.clone(), NS); + let kept = match api.get_opt(SECRET).await { + Ok(Some(s)) => s + .data + .unwrap_or_default() + .get(KEY) + .and_then(|b| serde_json::from_slice::(&b.0).ok()), + Ok(None) => None, + Err(e) => { + tracing::warn!(error = %e, "registry door: couldn't read the kept tokens"); + None + } + }; + if let Some(t) = kept { + set_tokens(t); + } +} + +/// Serves the door for as long as the agent runs. +pub async fn serve(kube: kube::Client) { + load(&kube).await; + let app = Router::new() + .route("/v2/", any(door)) + .route("/v2/{*rest}", any(door)); + let addr = std::net::SocketAddr::from(([0, 0, 0, 0], PORT)); + loop { + match tokio::net::TcpListener::bind(addr).await { + Ok(l) => { + if let Err(e) = axum::serve(l, app.clone()).await { + tracing::warn!(error = %e, "the registry door stopped"); + } + } + Err(e) => tracing::warn!(%addr, error = %e, "the registry door can't listen"), + } + tokio::time::sleep(std::time::Duration::from_secs(10)).await; + } +} + +fn errors(status: StatusCode, code: &str, message: &str) -> Response { + let mut r = ( + status, + [(header::CONTENT_TYPE, "application/json")], + json!({ "errors": [{ "code": code, "message": message }] }).to_string(), + ) + .into_response(); + r.headers_mut().insert( + "docker-distribution-api-version", + HeaderValue::from_static("registry/2.0"), + ); + if status == StatusCode::UNAUTHORIZED { + r.headers_mut().insert( + header::WWW_AUTHENTICATE, + HeaderValue::from_static("Basic realm=\"Pyo registry\""), + ); + } + r +} + +/// The password of a Basic login (any username). +fn password(headers: &HeaderMap) -> Option { + let v = headers + .get(header::AUTHORIZATION)? + .to_str() + .ok()? + .strip_prefix("Basic ")?; + let decoded = String::from_utf8( + base64::engine::general_purpose::STANDARD + .decode(v.trim()) + .ok()?, + ) + .ok()?; + decoded + .split_once(':') + .map(|(_, p)| p.to_owned()) + .filter(|p| !p.is_empty()) +} + +/// What the door lets through, by the login and the path: the slug to +/// keep mounts within, or the answer instead. +#[allow(clippy::result_large_err)] +fn decide( + tokens: Option<&RegistryTokens>, + headers: &HeaderMap, + method: &str, + path: &str, + now: i64, +) -> Result, Response> { + let unauthorized = |m: &str| errors(StatusCode::UNAUTHORIZED, "UNAUTHORIZED", m); + let Some(password) = password(headers) else { + return Err(unauthorized("Log in with a registry token from Pyo.")); + }; + let Some(tokens) = tokens else { + return Err(unauthorized( + "This cluster has no registry tokens from Pyo yet.", + )); + }; + let Some(token) = tokens.find(&password, now) else { + return Err(unauthorized( + "That token isn't valid (revoked or expired?).", + )); + }; + let slug = &tokens.team_slug; + match registry_door::wants(method, path) { + Wants::Root => Ok(None), + Wants::Repo { name, .. } if registry_door::allowed(slug, token.push, method, &name) => { + Ok(Some(slug.clone())) + } + Wants::Repo { .. } => Err(errors( + StatusCode::FORBIDDEN, + "DENIED", + &format!( + "This token can only {} images named {slug}//.", + if token.push { "push and pull" } else { "pull" } + ), + )), + Wants::Other => Err(errors( + StatusCode::FORBIDDEN, + "DENIED", + "Not available here.", + )), + } +} + +fn http() -> &'static reqwest::Client { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + C.get_or_init(|| { + reqwest::Client::builder() + .connect_timeout(std::time::Duration::from_secs(10)) + .redirect(reqwest::redirect::Policy::none()) + .build() + .expect("an HTTP client") + }) +} + +async fn door(req: Request) -> Response { + let (parts, body) = req.into_parts(); + let path = parts.uri.path().to_owned(); + let now = pyo_proto::now_ms() / 1000; + let slug = match decide( + tokens().as_ref(), + &parts.headers, + parts.method.as_str(), + &path, + now, + ) { + Ok(Some(slug)) => slug, + Ok(None) => { + return ( + [("docker-distribution-api-version", "registry/2.0")], + [(header::CONTENT_TYPE, "application/json")], + "{}", + ) + .into_response(); + } + Err(r) => return r, + }; + let query = parts + .uri + .query() + .map(|q| registry_door::scoped_query(q, &slug)) + .filter(|q| !q.is_empty()) + .map(|q| format!("?{q}")) + .unwrap_or_default(); + let mut out = http().request( + parts.method.clone(), + format!("http://{REGISTRY}{path}{query}"), + ); + for (k, v) in &parts.headers { + if !matches!( + *k, + header::HOST | header::AUTHORIZATION | header::CONNECTION | header::TRANSFER_ENCODING + ) { + out = out.header(k, v); + } + } + // Streamed through: a layer is never held whole. + out = out.body(reqwest::Body::wrap_stream( + body.into_data_stream().map_err(std::io::Error::other), + )); + let res = match out.send().await { + Ok(r) => r, + Err(e) => { + tracing::warn!(error = %e, "registry door: the registry didn't answer"); + return errors( + StatusCode::BAD_GATEWAY, + "UNAVAILABLE", + "The cluster's registry didn't answer.", + ); + } + }; + let mut back = Response::builder().status(res.status().as_u16()); + for (k, v) in res.headers() { + if matches!(*k, header::CONNECTION | header::TRANSFER_ENCODING) { + continue; + } + // Uploads continue through the door, not at the registry's address. + if *k == header::LOCATION + && let Some(rest) = v + .to_str() + .ok() + .and_then(|l| l.strip_prefix(&format!("http://{REGISTRY}"))) + && let Ok(v) = HeaderValue::from_str(rest) + { + back = back.header(k, v); + continue; + } + back = back.header(k, v); + } + back.body(Body::from_stream(res.bytes_stream())) + .unwrap_or_else(|_| { + errors( + StatusCode::BAD_GATEWAY, + "UNAVAILABLE", + "The cluster's registry didn't answer.", + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use pyo_proto::registry_door::RegistryToken; + use sha2::{Digest, Sha256}; + + fn login(token: &str) -> HeaderMap { + let mut h = HeaderMap::new(); + let b = base64::engine::general_purpose::STANDARD.encode(format!("me:{token}")); + h.insert(header::AUTHORIZATION, format!("Basic {b}").parse().unwrap()); + h + } + + #[test] + fn only_the_teams_tokens_and_images() { + let hash = |t: &str| hex::encode(Sha256::digest(t.as_bytes())); + let t = RegistryTokens { + team_slug: "acme".into(), + tokens: vec![ + RegistryToken { + sha256: hash("push-me"), + push: true, + expires_at: None, + }, + RegistryToken { + sha256: hash("pull-me"), + push: false, + expires_at: Some(50), + }, + ], + }; + let status = |r: Result, Response>| match r { + Ok(_) => StatusCode::OK, + Err(r) => r.status(), + }; + let path = "/v2/acme/shop/api/manifests/1"; + // Nothing synced yet, or no login: refused. + assert_eq!( + status(decide(None, &login("push-me"), "GET", path, 0)), + StatusCode::UNAUTHORIZED + ); + assert_eq!( + status(decide(Some(&t), &HeaderMap::new(), "GET", path, 0)), + StatusCode::UNAUTHORIZED + ); + assert_eq!( + status(decide(Some(&t), &login("nope"), "GET", path, 0)), + StatusCode::UNAUTHORIZED + ); + // A push token pushes the team's own. + assert_eq!( + decide(Some(&t), &login("push-me"), "PUT", path, 0).ok(), + Some(Some("acme".into())) + ); + assert_eq!( + decide(Some(&t), &login("push-me"), "GET", "/v2/", 0).ok(), + Some(None) + ); + // Another team's, or the catalog: no. + assert_eq!( + status(decide( + Some(&t), + &login("push-me"), + "GET", + "/v2/other/shop/api/manifests/1", + 0 + )), + StatusCode::FORBIDDEN + ); + assert_eq!( + status(decide( + Some(&t), + &login("push-me"), + "GET", + "/v2/_catalog", + 0 + )), + StatusCode::FORBIDDEN + ); + // A pull token pulls, until it expires. + assert_eq!( + status(decide(Some(&t), &login("pull-me"), "GET", path, 49)), + StatusCode::OK + ); + assert_eq!( + status(decide(Some(&t), &login("pull-me"), "PUT", path, 49)), + StatusCode::FORBIDDEN + ); + assert_eq!( + status(decide(Some(&t), &login("pull-me"), "GET", path, 50)), + StatusCode::UNAUTHORIZED + ); + } +} diff --git a/crates/pyo-agent/src/relay.rs b/crates/pyo-agent/src/relay.rs new file mode 100644 index 00000000..0d20eb42 --- /dev/null +++ b/crates/pyo-agent/src/relay.rs @@ -0,0 +1,123 @@ +//! Vector's servers' figures reach Pyo through this agent +//! (observability.rs); the gateway's access logs stay in the cluster, in +//! the traffic store (traffic/). Vector can't sign its +//! requests, and it gets no credential to Pyo: it posts here, inside the +//! cluster, with a token only this agent knows (made at its start), and the +//! agent sends each batch on as its own signed request. +//! +//! The listener is on the agent's pod address only, port 8089 +//! (`PYO_AGENT_RELAY_PORT`): nothing on the servers' addresses. + +use std::sync::OnceLock; + +use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, StatusCode}, + response::IntoResponse, + routing::post, +}; + +use crate::Agent; + +/// The largest batch passed on. +const MAX_BODY: usize = 8 << 20; + +fn port() -> u16 { + std::env::var("PYO_AGENT_RELAY_PORT") + .ok() + .and_then(|p| p.parse().ok()) + .unwrap_or(8089) +} + +/// The token Vector sends: this process's own. +pub fn token() -> &'static str { + static T: OnceLock = OnceLock::new(); + T.get_or_init(|| format!("{}{}", pyo_proto::signing::new_nonce(), pyo_proto::signing::new_nonce())) +} + +/// Where Vector posts: `http://:`. The pod's +/// address from Kubernetes (its name is the hostname). +pub async fn endpoint(client: &kube::Client) -> anyhow::Result { + static E: tokio::sync::OnceCell = tokio::sync::OnceCell::const_new(); + E.get_or_try_init(|| async { + let name = std::env::var("HOSTNAME").unwrap_or_default(); + anyhow::ensure!(!name.is_empty(), "no HOSTNAME: can't tell this pod"); + let pod = kube::Api::::namespaced(client.clone(), pyo_proto::rbac::NS) + .get(&name) + .await?; + let ip = pod + .status + .and_then(|s| s.pod_ip) + .filter(|ip| !ip.is_empty()) + .ok_or_else(|| anyhow::anyhow!("this pod has no address yet"))?; + let host = if ip.contains(':') { format!("[{ip}]") } else { ip }; + Ok(format!("http://{host}:{}", port())) + }) + .await + .cloned() +} + +/// Whether a request carries this agent's relay token (constant time). +fn allowed(headers: &HeaderMap) -> bool { + let got = headers + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .unwrap_or(""); + let want = token(); + got.len() == want.len() && got.bytes().zip(want.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0 +} + +async fn forward(agent: &Agent, headers: &HeaderMap, path: &str, body: Bytes) -> impl IntoResponse + use<> { + if !allowed(headers) { + return (StatusCode::UNAUTHORIZED, String::new()); + } + match agent.api.relay(path, body.to_vec()).await { + Ok((status, text)) => (StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY), text), + Err(e) => { + tracing::debug!(error = %format!("{e:#}"), path, "couldn't pass Vector's batch on"); + (StatusCode::BAD_GATEWAY, String::new()) + } + } +} + +/// Serves the relay for as long as the agent runs. +pub async fn serve(agent: Agent) { + let app = Router::new() + .route( + "/host-metrics", + post(|State(a): State, h: HeaderMap, b: Bytes| async move { forward(&a, &h, "/host-metrics", b).await }), + ) + .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY)) + .with_state(agent); + let addr = std::net::SocketAddr::from(([0, 0, 0, 0], port())); + loop { + match tokio::net::TcpListener::bind(addr).await { + Ok(l) => { + tracing::info!(%addr, "relaying Vector's data to Pyo"); + if let Err(e) = axum::serve(l, app.clone()).await { + tracing::warn!(error = %e, "the relay stopped"); + } + } + Err(e) => tracing::warn!(%addr, error = %e, "the relay can't listen"), + } + tokio::time::sleep(std::time::Duration::from_secs(10)).await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_this_agents_token_passes() { + let mut h = HeaderMap::new(); + assert!(!allowed(&h)); + h.insert("authorization", format!("Bearer {}", token()).parse().unwrap()); + assert!(allowed(&h)); + h.insert("authorization", "Bearer nope".parse().unwrap()); + assert!(!allowed(&h)); + } +} diff --git a/crates/pyo-agent/src/rollout.rs b/crates/pyo-agent/src/rollout.rs index d3e1fba9..4764b327 100644 --- a/crates/pyo-agent/src/rollout.rs +++ b/crates/pyo-agent/src/rollout.rs @@ -878,12 +878,10 @@ fn pod_template(spec: &DeploySpec, secret_name: &str) -> Value { if !spec.node_selector.is_empty() { pod["nodeSelector"] = json!(spec.node_selector); } - // Picked servers: a selector can't say "one of these", affinity can. - if !spec.server_names.is_empty() { - pod["affinity"] = json!({ "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ - { "matchExpressions": [{ "key": "kubernetes.io/hostname", "operator": "In", "values": spec.server_names }] } - ] } } }); - } + // Picked servers and tags: a selector can't say "one of these", + // affinity can. Always set, "any server" too, so this rollout takes + // back what a placement change patched in place (actions.rs). + pod["affinity"] = pyo_proto::placement_affinity(&spec.server_names, &spec.server_tags); if !spec.pull_login_id.is_empty() { pod["imagePullSecrets"] = json!([{ "name": pull_secret(&spec.service.name) }]); } @@ -2598,7 +2596,7 @@ mod gpu_tests { serde_json::from_value(json!({ "deploymentId": "dpl_1", "image": "ollama/ollama:0.12.0", "replicas": 1, "env": [], "ports": [], "domains": [], "volumes": [], "service": { "serviceId": "svc_llm", "name": "ollama", "namespace": "ai", "workloadKind": "Deployment" }, - "projectId": "prj_1", "timeoutSeconds": 600, "nodeSelector": { "pyo/tag-fast": "true" }, + "projectId": "prj_1", "timeoutSeconds": 600, "serverTags": ["fast"], "resources": { "cpuRequest": 1000, "cpuLimit": 4000, "memoryRequest": 4096, "memoryLimit": 16384, "gpu": gpu }, "healthCheck": { "type": "none", "path": "/", "port": 11434, "command": "", "initialDelaySeconds": 1, "periodSeconds": 1 }, })) @@ -2618,10 +2616,11 @@ mod gpu_tests { pod["tolerations"], json!([{ "key": "nvidia.com/gpu", "operator": "Exists", "effect": "NoSchedule" }]) ); - // The service's own server choice stays. + // Only GPU servers, among the ones it picked. + assert_eq!(pod["nodeSelector"], json!({ "pyo/gpu": "nvidia" })); assert_eq!( - pod["nodeSelector"], - json!({ "pyo/tag-fast": "true", "pyo/gpu": "nvidia" }) + pod["affinity"]["nodeAffinity"]["requiredDuringSchedulingIgnoredDuringExecution"]["nodeSelectorTerms"], + json!([{ "matchExpressions": [{ "key": "pyo/tag-fast", "operator": "In", "values": ["true"] }] }]) ); // And it's a valid Deployment. let d: Deployment = serde_json::from_value(json!({ "metadata": { "name": "x" }, "spec": { "selector": {}, "template": t, "strategy": deployment_strategy(false, 2, 0) } })).unwrap(); @@ -2717,7 +2716,7 @@ mod gpu_tests { .get("nvidia.com/gpu") .is_none() ); - assert_eq!(pod["nodeSelector"], json!({ "pyo/tag-fast": "true" })); + assert!(pod.get("nodeSelector").is_none()); assert_eq!( deployment_strategy(false, 0, 0)["rollingUpdate"]["maxSurge"], 1 diff --git a/crates/pyo-agent/src/scope.rs b/crates/pyo-agent/src/scope.rs index 9cec23c4..50e4fb73 100644 --- a/crates/pyo-agent/src/scope.rs +++ b/crates/pyo-agent/src/scope.rs @@ -176,15 +176,23 @@ async fn proxy_scope(client: &Client) -> Option { core::v1::Pod, }; let ns = pyo_proto::system::GATEWAY_NS; - let pods = - Api::::namespaced(client.clone(), ns) - .list(&ListParams::default().labels( - "app.kubernetes.io/component=proxy,app.kubernetes.io/managed-by=envoy-gateway", - )) - .await - .ok()? - .items; - if pods.is_empty() { + // Running proxies only, a page at a time, and of each only whether it + // carries a token: a server short of disk evicts the proxy over and + // over, and thousands of its Failed pods, whole, are more than the + // agent's memory. + let lp = ListParams::default() + .labels("app.kubernetes.io/component=proxy,app.kubernetes.io/managed-by=envoy-gateway") + .fields(crate::pods::LIVE); + let tokens: Vec = + crate::pods::list(&Api::::namespaced(client.clone(), ns), &lp, |p| { + Some( + p.spec + .is_none_or(|s| s.automount_service_account_token != Some(false)), + ) + }) + .await + .ok()?; + if tokens.is_empty() { return None; } let user = format!("system:serviceaccount:{ns}:envoy-gateway"); @@ -210,14 +218,9 @@ async fn proxy_scope(client: &Client) -> Option { .ok()? .status .is_some_and(|s| s.allowed); - let tokens = pods.iter().any(|p| { - p.spec - .as_ref() - .is_none_or(|s| s.automount_service_account_token != Some(false)) - }); Some(pyo_proto::rbac::ProxyScope { controller_reads_other_secrets: wide, - proxies_have_credentials: tokens, + proxies_have_credentials: tokens.contains(&true), }) } @@ -331,7 +334,12 @@ pub fn refusal(policy: &Policy, command: &Command) -> Option<&'static str> { if policy.read_only && !matches!( command, - Command::FetchLogs { .. } | Command::FetchDatabaseLogs { .. } | Command::Cancel { .. } + Command::FetchLogs { .. } + | Command::FollowLogs { .. } + | Command::FollowDatabaseLogs { .. } + | Command::FetchDatabaseLogs { .. } + | Command::QueryTraffic(_) + | Command::Cancel { .. } ) { return Some( @@ -421,6 +429,30 @@ mod tests { ..Default::default() }; assert!(refusal(&ro, &logs).is_none() && refusal(&ro, &gentle).is_some()); + let follow = Command::FollowLogs { + session_id: "lgf_x".into(), + service: pyo_proto::ServiceRef { + service_id: "svc_x".into(), + name: "web".into(), + namespace: "pyo-p".into(), + workload_kind: "Deployment".into(), + }, + tail_lines: 100, + since_seconds: None, + replica: String::new(), + }; + assert!(refusal(&ro, &follow).is_none(), "following logs only reads"); + let db_follow = Command::FollowDatabaseLogs { + session_id: "lgf_y".into(), + namespace: "pyo-db-team".into(), + name: "main".into(), + tail_lines: 500, + since_seconds: None, + }; + assert!( + refusal(&ro, &db_follow).is_none(), + "following a database's logs only reads" + ); } #[test] diff --git a/crates/pyo-agent/src/sites.rs b/crates/pyo-agent/src/sites.rs index cbd78641..bd6b4478 100644 --- a/crates/pyo-agent/src/sites.rs +++ b/crates/pyo-agent/src/sites.rs @@ -1,8 +1,10 @@ //! Pyo Static on this cluster: the static sites `pyo-static` serves //! (pyo-proto's site.rs). //! -//! - Its bundle's login Secret gets Pyo's address and the cluster's token -//! when the bundle is applied ([`fill_login`]). +//! - Its bundle's login Secret gets Pyo's address and a key of its own, +//! made here and registered with Pyo, when the bundle is applied +//! ([`fill_login`]), and a new key when the one there was revoked (a new +//! connect command), at the agent's start ([`renew_login`]). //! - A static deploy has `pyo-static` fetch its folder first ([`warm`]), //! then moves the site's routes there (gateway.rs sends them to //! `pyo-static` with the folder in a header), and only then removes the @@ -37,11 +39,25 @@ pub fn marker_name(service: &str) -> String { format!("{service}-site") } -/// Puts Pyo's address and the cluster's token into the bundle's login -/// Secret (only its name is pinned). Without them `pyo-static` serves -/// only what it has cached, so a failure is logged, not fatal. +/// pyo-static's login: Pyo's address and a new key of its own (registered +/// with Pyo), or, from a Pyo that gives none (older), the cluster's token. +async fn login(agent: &Agent) -> anyhow::Result { + let url = agent.api.base_url(); + match crate::trust::component_key(&agent.api, "static", None).await { + Ok((key_id, key)) => Ok(json!({ "url": url, "key-id": key_id, "key": key })), + Err(e) => { + tracing::warn!(error = %format!("{e:#}"), "couldn't register pyo-static's key; asking for a token"); + let (url, token) = agent.api.static_login().await?; + Ok(json!({ "url": url, "token": token })) + } + } +} + +/// Puts Pyo's address and pyo-static's key into the bundle's login Secret +/// (only its name is pinned). Without them `pyo-static` serves only what it +/// has cached, so a failure is logged, not fatal. pub async fn fill_login(agent: &Agent, bundle: &mut SystemBundle) { - let login = match agent.api.static_login().await { + let login = match login(agent).await { Ok(l) => l, Err(e) => { tracing::warn!(error = %format!("{e:#}"), "couldn't get pyo-static's login"); @@ -50,11 +66,50 @@ pub async fn fill_login(agent: &Agent, bundle: &mut SystemBundle) { }; for o in &mut bundle.objects { if o["kind"] == "Secret" && o["metadata"]["name"] == STATIC_LOGIN { - o["stringData"] = json!({ "url": login.0, "token": login.1 }); + o["stringData"] = login.clone(); } } } +/// At the agent's start: a new login for pyo-static, when it's installed +/// and its key is no longer one Pyo knows (revoked with the cluster's +/// earlier keys), or it still reads with a token. +pub async fn renew_login(agent: Agent) { + let api = Api::::namespaced(agent.kube.clone(), STATIC_NS); + let Ok(Some(secret)) = api.get_opt(STATIC_LOGIN).await else { + return; + }; + let get = |k: &str| { + secret + .data + .as_ref() + .and_then(|d| d.get(k)) + .and_then(|v| String::from_utf8(v.0.clone()).ok()) + .unwrap_or_default() + }; + let key_id = get("key-id"); + if !key_id.is_empty() && agent.api.component_key_live(&key_id).await.unwrap_or(true) { + return; + } + let login = match login(&agent).await { + Ok(l) => l, + Err(e) => { + tracing::warn!(error = %format!("{e:#}"), "couldn't renew pyo-static's login"); + return; + } + }; + // A login with a key takes the old token away. + let patch = if login.get("token").is_none() { + json!({ "stringData": login, "data": { "token": null } }) + } else { + json!({ "stringData": login }) + }; + match api.patch(STATIC_LOGIN, &PatchParams::default(), &Patch::Merge(&patch)).await { + Ok(_) => tracing::info!("renewed pyo-static's login"), + Err(e) => tracing::warn!(error = %format!("{e:#}"), "couldn't save pyo-static's login"), + } +} + /// Whether `pyo-static` is up (its Deployment has a ready copy), waiting up /// to `wait`. pub async fn wait_ready(client: &Client, wait: Duration) -> bool { diff --git a/crates/pyo-agent/src/tailnet.rs b/crates/pyo-agent/src/tailnet.rs index a731ede5..ffce60c5 100644 --- a/crates/pyo-agent/src/tailnet.rs +++ b/crates/pyo-agent/src/tailnet.rs @@ -699,8 +699,9 @@ pub async fn apply(kube: &Client, wanted: &TailnetWanted, same_cluster: bool) { /// What the cluster's install refused last, and that install's stamp. static TAILNET_REFUSED: std::sync::Mutex> = std::sync::Mutex::new(None); -/// The agent's own image (its Deployment's), for its tailnet pods. -async fn own_image(kube: &Client) -> Option { +/// The agent's own image (its Deployment's), for its tailnet pods and +/// the traffic store. +pub(crate) async fn own_image(kube: &Client) -> Option { Api::::namespaced(kube.clone(), NS) .get_opt("pyo-agent") .await diff --git a/crates/pyo-agent/src/tailscale/mod.rs b/crates/pyo-agent/src/tailscale/mod.rs new file mode 100644 index 00000000..e5df2425 --- /dev/null +++ b/crates/pyo-agent/src/tailscale/mod.rs @@ -0,0 +1,1004 @@ +//! Tailscale through the agent (pyo-proto's tailscale.rs). +//! +//! - **The client**: this cluster's own OAuth client, kept as a Secret in +//! pyo-system ([`SECRET`]). Only this agent uses it. Scopes: +//! `devices:core` and `auth_keys` (both with `tag:pyo`), and `services`. +//! It comes from the one-token setup ([`setup`]), a client pasted by +//! hand, or the one Pyo kept before clusters kept their own. +//! - **Joining**: each join command carries a fresh auth key from it: +//! single-use, preauthorized, `tag:pyo`, for an hour ([`Client::auth_key`]). +//! - **Names on the tailnet** are Tailscale Services ("svc:blog" is +//! "blog..ts.net"). [`sync`] keeps the cluster's as Pyo wants +//! them: makes each (marked as this cluster's), approves the cluster's +//! servers as its hosts, deletes the ones no longer used, and never +//! touches one it didn't make. The servers do the rest (tailnet.rs). + +pub mod sandbox; +pub mod setup; + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use k8s_openapi::api::core::v1::Secret; +use kube::api::{DeleteParams, Patch, PatchParams}; +use pyo_proto::CommandResult; +use pyo_proto::tailscale::{ + self as ts, Check, ClientState, LockWaiting, NameCheck, NameState, SECRET, SECRET_ID, + SECRET_KEY, TAG, TailnetSync, TailnetSynced, +}; +use serde_json::{Value, json}; + +use crate::{failed, ok}; + +/// Tailscale's API. `PYO_TAILSCALE_API_URL` points the agent at another +/// (a fake one, in Pyo's own end-to-end tests). +pub(crate) fn api_url() -> String { + std::env::var("PYO_TAILSCALE_API_URL") + .ok() + .map(|u| u.trim().trim_end_matches('/').to_owned()) + .filter(|u| !u.is_empty()) + .unwrap_or_else(|| "https://api.tailscale.com/api/v2".to_owned()) +} + +const NS: &str = "pyo-system"; + +pub(crate) fn http() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| { + reqwest::Client::builder() + .user_agent("pyo") + .timeout(Duration::from_secs(30)) + .build() + .expect("http client") + }) +} + +// ── The cluster's client ──────────────────────────────────────────────────── + +/// The OAuth client, with its access token while it lasts. +pub struct Client { + /// The API ("https://api.tailscale.com/api/v2"; a mock in tests). + base: String, + id: String, + secret: String, + token: Mutex>, +} + +/// One per client ID and secret, so tokens are reused. +pub fn client(id: &str, secret: &str) -> Arc { + static C: Mutex>> = Mutex::new(None); + let base = api_url(); + let mut g = C.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(c) = g + .as_ref() + .filter(|c| c.id == id && c.secret == secret && c.base == base) + { + return c.clone(); + } + let c = Arc::new(Client::at(&base, id, secret)); + *g = Some(c.clone()); + c +} + +impl Client { + pub fn at(base: &str, id: &str, secret: &str) -> Self { + Client { + base: base.trim_end_matches('/').to_owned(), + id: id.to_owned(), + secret: secret.to_owned(), + token: Mutex::new(None), + } + } +} + +/// The client kept in pyo-system: its ID and secret, when there's one. +pub async fn stored(kube: &kube::Client) -> anyhow::Result> { + let api = kube::Api::::namespaced(kube.clone(), NS); + let Some(s) = api.get_opt(SECRET).await? else { + return Ok(None); + }; + let data = s.data.unwrap_or_default(); + let read = |k: &str| { + data.get(k) + .map(|b| String::from_utf8_lossy(&b.0).trim().to_owned()) + .filter(|v| !v.is_empty()) + }; + Ok(read(SECRET_ID).zip(read(SECRET_KEY))) +} + +/// The kept client, ready to use. +pub async fn saved(kube: &kube::Client) -> anyhow::Result>> { + Ok(stored(kube).await?.map(|(id, secret)| client(&id, &secret))) +} + +/// Keeps the client in pyo-system, replacing any other. +async fn keep(kube: &kube::Client, id: &str, secret: &str) -> anyhow::Result<()> { + let api = kube::Api::::namespaced(kube.clone(), NS); + let s = json!({ + "apiVersion": "v1", + "kind": "Secret", + "metadata": { "name": SECRET, "namespace": NS, "labels": { "app.kubernetes.io/managed-by": crate::MANAGER } }, + "type": "Opaque", + "stringData": { SECRET_ID: id, SECRET_KEY: secret }, + }); + api.patch( + SECRET, + &PatchParams::apply(crate::MANAGER).force(), + &Patch::Apply(&s), + ) + .await?; + Ok(()) +} + +async fn forget(kube: &kube::Client) -> anyhow::Result<()> { + let api = kube::Api::::namespaced(kube.clone(), NS); + match api.delete(SECRET, &DeleteParams::default()).await { + Ok(_) => Ok(()), + Err(kube::Error::Api(e)) if e.code == 404 => Ok(()), + Err(e) => Err(e.into()), + } +} + +// ── Tailscale's API ───────────────────────────────────────────────────────── + +/// What Tailscale said, as people read it. +#[derive(Debug)] +pub struct TsError { + pub status: u16, + pub message: String, +} + +impl std::fmt::Display for TsError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Tailscale answered {}: {}", self.status, self.message) + } +} + +impl std::error::Error for TsError {} + +/// What Tailscale answered: its body, and the ETag when there's one. +pub(crate) struct Reply { + pub text: String, + pub etag: Option, +} + +/// Sends a request to Tailscale's API. Anything but a 2xx is a [`TsError`] +/// with Tailscale's own message, and status 0 when it couldn't be reached. +pub(crate) async fn send(req: reqwest::RequestBuilder) -> Result { + let r = req.send().await.map_err(|e| TsError { + status: 0, + message: format!("Couldn't reach Tailscale: {}", e.without_url()), + })?; + let status = r.status().as_u16(); + let etag = r + .headers() + .get(reqwest::header::ETAG) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + let text = r.text().await.unwrap_or_default(); + if !(200..300).contains(&status) { + let message = serde_json::from_str::(&text) + .ok() + .and_then(|v| v["message"].as_str().map(str::to_owned)) + .unwrap_or_else(|| text.trim().chars().take(300).collect()); + return Err(TsError { status, message }); + } + Ok(Reply { text, etag }) +} + +fn strings(v: &Value) -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() +} + +/// A machine on the tailnet ([`Client::device_details`]). +#[derive(Debug, Clone, PartialEq)] +pub struct Device { + pub node_id: String, + pub hostname: String, + pub tags: Vec, + /// "nodekey:…" + pub node_key: String, + /// Set while Tailnet Lock waits for this machine's key to be signed. + pub lock_error: String, +} + +impl Client { + pub(crate) async fn access_token(&self) -> anyhow::Result { + if let Some((t, at)) = self.token.lock().unwrap_or_else(|e| e.into_inner()).clone() + && at.elapsed() < Duration::from_secs(45 * 60) + { + return Ok(t); + } + let r = http() + .post(format!("{}/oauth/token", self.base)) + .header( + reqwest::header::CONTENT_TYPE, + "application/x-www-form-urlencoded", + ) + .body( + reqwest::Url::parse_with_params( + "http://form/", + &[ + ("client_id", self.id.as_str()), + ("client_secret", self.secret.as_str()), + ], + )? + .query() + .unwrap_or("") + .to_owned(), + ) + .send() + .await + .map_err(|e| TsError { + status: 0, + message: format!("Couldn't reach Tailscale: {}", e.without_url()), + })?; + let status = r.status().as_u16(); + let body: Value = r.json().await.unwrap_or(Value::Null); + let Some(t) = body["access_token"].as_str().filter(|_| status == 200) else { + return Err(TsError { + status, + message: body["message"] + .as_str() + .or(body["error_description"].as_str()) + .or(body["error"].as_str()) + .unwrap_or("the client ID or secret isn't right") + .to_owned(), + } + .into()); + }; + *self.token.lock().unwrap_or_else(|e| e.into_inner()) = + Some((t.to_owned(), Instant::now())); + Ok(t.to_owned()) + } + + async fn call( + &self, + method: reqwest::Method, + path: &str, + body: Option<&Value>, + ) -> anyhow::Result { + let token = self.access_token().await?; + let mut req = http() + .request(method, format!("{}{path}", self.base)) + .bearer_auth(token); + if let Some(b) = body { + req = req.json(b); + } + let text = send(req).await?.text; + Ok(if text.trim().is_empty() { + Value::Null + } else { + serde_json::from_str(&text)? + }) + } + + /// The tailnet's Services: name ("blog") → (comment, addresses). + pub async fn services(&self) -> anyhow::Result)>> { + let v = self + .call(reqwest::Method::GET, "/tailnet/-/services", None) + .await?; + Ok(v["vipServices"] + .as_array() + .into_iter() + .flatten() + .filter_map(|s| { + let name = s["name"].as_str()?.strip_prefix("svc:")?.to_owned(); + Some(( + name, + ( + s["comment"].as_str().unwrap_or("").to_owned(), + strings(&s["addrs"]), + ), + )) + }) + .collect()) + } + + /// Make a Service: ports 80 and 443, tagged, marked as Pyo's. Its + /// addresses come back. + pub async fn create_service(&self, name: &str, comment: &str) -> anyhow::Result> { + let body = json!({ "name": format!("svc:{name}"), "comment": comment, "ports": ["tcp:80", "tcp:443"], "tags": [TAG] }); + let v = self + .call( + reqwest::Method::PUT, + &format!("/tailnet/-/services/svc:{name}"), + Some(&body), + ) + .await?; + Ok(strings(&v["addrs"])) + } + + /// One Service, read directly: its comment and addresses, or None when + /// there's no such Service (404). The list leaves some out (Tailscale's + /// API reference: it has the Services of the admin console's + /// "Advertised" tab, so not one defined and hosted nowhere). Any other + /// answer is an error, 403 included ("access to the Service is + /// forbidden"), so a name Pyo can't read is never taken. + /// + /// There's no create-only write: PUT creates or updates, with no + /// If-Match or If-None-Match for Services (only the policy file has + /// ETags). So this read is what keeps Pyo off Services it didn't make. + pub async fn service(&self, name: &str) -> anyhow::Result)>> { + match self + .call( + reqwest::Method::GET, + &format!("/tailnet/-/services/svc:{name}"), + None, + ) + .await + { + Ok(v) => Ok(Some(( + v["comment"].as_str().unwrap_or("").to_owned(), + strings(&v["addrs"]), + ))), + Err(e) if e.downcast_ref::().is_some_and(|t| t.status == 404) => Ok(None), + Err(e) => Err(e), + } + } + + pub async fn delete_service(&self, name: &str) -> anyhow::Result<()> { + self.call( + reqwest::Method::DELETE, + &format!("/tailnet/-/services/svc:{name}"), + None, + ) + .await + .map(|_| ()) + } + + /// A Service's hosts: node ID → approved. + pub async fn hosts(&self, name: &str) -> anyhow::Result> { + let v = self + .call( + reqwest::Method::GET, + &format!("/tailnet/-/services/svc:{name}/devices"), + None, + ) + .await?; + Ok(v["hosts"] + .as_array() + .into_iter() + .flatten() + .filter_map(|h| { + Some(( + h["stableNodeID"].as_str()?.to_owned(), + h["approvalLevel"] + .as_str() + .is_some_and(|l| l.starts_with("approved")), + )) + }) + .collect()) + } + + pub async fn approve(&self, name: &str, node: &str) -> anyhow::Result<()> { + self.call( + reqwest::Method::POST, + &format!("/tailnet/-/services/svc:{name}/device/{node}/approved"), + Some(&json!({ "approved": true })), + ) + .await + .map(|_| ()) + } + + /// The tailnet's machines: (node ID, full name, tags). + pub async fn devices(&self) -> anyhow::Result)>> { + let v = self + .call(reqwest::Method::GET, "/tailnet/-/devices", None) + .await?; + Ok(v["devices"] + .as_array() + .into_iter() + .flatten() + .filter_map(|d| { + Some(( + d["nodeId"].as_str()?.to_owned(), + d["name"] + .as_str() + .unwrap_or("") + .trim_end_matches('.') + .to_owned(), + strings(&d["tags"]), + )) + }) + .collect()) + } + + /// The tailnet's machines with their hostname, and their key while + /// Tailnet Lock waits for its signature. + pub async fn device_details(&self) -> anyhow::Result> { + let v = self + .call( + reqwest::Method::GET, + "/tailnet/-/devices?fields=default", + None, + ) + .await?; + Ok(v["devices"] + .as_array() + .into_iter() + .flatten() + .filter_map(|d| { + Some(Device { + node_id: d["nodeId"].as_str()?.to_owned(), + hostname: d["hostname"].as_str().unwrap_or("").to_owned(), + tags: strings(&d["tags"]), + node_key: d["nodeKey"].as_str().unwrap_or("").to_owned(), + lock_error: d["tailnetLockError"].as_str().unwrap_or("").to_owned(), + }) + }) + .collect()) + } + + /// Takes a machine off the tailnet (only tag:pyo ones: the client's + /// Devices › Core scope is for that tag). + pub async fn delete_device(&self, node: &str) -> anyhow::Result<()> { + if node.is_empty() || !node.bytes().all(|b| b.is_ascii_alphanumeric()) { + anyhow::bail!("not a node ID"); + } + match self + .call(reqwest::Method::DELETE, &format!("/device/{node}"), None) + .await + { + Err(e) if e.downcast_ref::().is_some_and(|t| t.status == 404) => Ok(()), + r => r.map(|_| ()), + } + } + + pub async fn tag(&self, node: &str) -> anyhow::Result<()> { + self.call( + reqwest::Method::POST, + &format!("/device/{node}/tags"), + Some(&json!({ "tags": [TAG] })), + ) + .await + .map(|_| ()) + } + + /// A single-use, preauthorized auth key with `tag:pyo`, for an hour: + /// (its ID, the key). + pub async fn auth_key(&self, description: &str) -> anyhow::Result<(String, String)> { + let body = json!({ + "capabilities": { "devices": { "create": { "reusable": false, "ephemeral": false, "preauthorized": true, "tags": [TAG] } } }, + "expirySeconds": 3600, + "description": ts::key_description(description), + }); + let v = self + .call(reqwest::Method::POST, "/tailnet/-/keys", Some(&body)) + .await?; + match (v["id"].as_str(), v["key"].as_str()) { + (Some(id), Some(k)) => Ok((id.to_owned(), k.to_owned())), + _ => anyhow::bail!("Tailscale made no key"), + } + } + + pub async fn delete_key(&self, id: &str) -> anyhow::Result<()> { + self.call( + reqwest::Method::DELETE, + &format!("/tailnet/-/keys/{id}"), + None, + ) + .await + .map(|_| ()) + } +} + +/// Pyo's machines (tag:pyo) that Tailnet Lock keeps out until a signing +/// device signs their key: their hostname, and the command that signs it. +pub fn lock_waiting(devices: &[Device]) -> Vec { + devices + .iter() + .filter(|d| { + !d.lock_error.is_empty() + && d.node_key.starts_with("nodekey:") + && d.tags.iter().any(|t| t == TAG) + }) + .map(|d| LockWaiting { + name: d.hostname.clone(), + sign_command: format!("tailscale lock sign {}", d.node_key), + }) + .collect() +} + +/// Pyo's machines (tag:pyo), with what Tailnet Lock waits for. +pub fn machines(devices: &[Device]) -> Vec { + devices + .iter() + .filter(|d| d.tags.iter().any(|t| t == TAG)) + .map(|d| ts::Machine { + node_id: d.node_id.clone(), + hostname: d.hostname.clone(), + sign_command: (!d.lock_error.is_empty() && d.node_key.starts_with("nodekey:")) + .then(|| format!("tailscale lock sign {}", d.node_key)), + }) + .collect() +} + +/// What a wanted name is on the tailnet. +#[derive(Debug, PartialEq)] +pub enum Claim { + /// Pyo's (made by this cluster): its addresses. + Ours(Vec), + /// Someone else's, or one Pyo can't read. + Taken, +} + +/// A wanted name: Pyo's own Service, made now (marked `mark`) if there's +/// none by that name at all. Read directly first, whatever the list said: a +/// name that exists and isn't marked with one of `marks` is never written. +pub async fn claim(c: &Client, name: &str, mark: &str, marks: &[&str]) -> anyhow::Result { + match c.service(name).await? { + Some((comment, addrs)) if marks.contains(&comment.as_str()) => Ok(Claim::Ours(addrs)), + Some(_) => Ok(Claim::Taken), + None => { + let addrs = c.create_service(name, mark).await?; + tracing::info!(name, "tailnet name made"); + Ok(Claim::Ours(addrs)) + } + } +} + +/// Deletes a Service only if its own record has one of `marks`. +pub async fn delete_if_ours(c: &Client, name: &str, marks: &[&str]) -> anyhow::Result { + match c.service(name).await? { + Some((comment, _)) if marks.contains(&comment.as_str()) => { + c.delete_service(name).await?; + Ok(true) + } + _ => Ok(false), + } +} + +// ── Checking the client ───────────────────────────────────────────────────── + +fn check(name: &str, ok: bool, message: impl Into) -> Check { + Check { + name: name.to_owned(), + ok, + message: message.into(), + } +} + +/// What the client can do, check by check, saying what's missing. +pub async fn test(c: &Client) -> (Vec, Option) { + let mut out = Vec::new(); + let mut suffix = None; + if let Err(e) = c.access_token().await { + out.push(check( + "client", + false, + format!("Couldn't sign in with it. {e}"), + )); + return (out, None); + } + out.push(check("client", true, "Signed in.")); + match c.devices().await { + Ok(d) => { + suffix = d.iter().find_map(|(_, n, _)| ts::suffix_of(n)); + out.push(check("devices", true, "Can read the tailnet's machines.")); + } + Err(e) => out.push(check( + "devices", + false, + format!("Needs the Devices › Core scope with tag:pyo. {e}"), + )), + } + match c.services().await { + Ok(_) => out.push(check("services", true, "Can manage Services.")), + Err(e) => out.push(check( + "services", + false, + format!("Needs the Services scope. {e}"), + )), + } + match c.auth_key("Pyo test").await { + Ok((id, _)) => { + let _ = c.delete_key(&id).await; + out.push(check("authKeys", true, "Can make auth keys with tag:pyo.")); + } + Err(e) => out.push(check( + "authKeys", + false, + format!("Needs the Auth Keys scope with tag:pyo, and tag:pyo in the tailnet policy's tagOwners. {e}"), + )), + } + (out, suffix) +} + +/// The secret's last characters, to tell it apart. +fn hint(secret: &str) -> String { + let tail: String = secret + .chars() + .rev() + .take(4) + .collect::>() + .into_iter() + .rev() + .collect(); + format!("…{tail}") +} + +/// Takes an OAuth client once it signs in: checks it and keeps it. A +/// client that doesn't sign in is refused, and the kept one stays. +pub async fn use_client( + kube: &kube::Client, + base: &str, + id: &str, + secret: &str, +) -> Result { + let id = id.trim(); + let secret = secret.trim(); + if id.is_empty() || id.len() > 100 || !id.bytes().all(|b| b.is_ascii_alphanumeric()) { + return Err("Paste the client ID from Tailscale's Trust credentials page.".into()); + } + if !(secret.starts_with("tskey-client-") + && secret.len() > 20 + && !secret.contains(char::is_whitespace)) + { + return Err("A client secret starts with tskey-client-.".into()); + } + let (checks, suffix) = test(&Client::at(base, id, secret)).await; + if let Some(c) = checks.iter().find(|c| c.name == "client" && !c.ok) { + return Err(c.message.clone()); + } + keep(kube, id, secret) + .await + .map_err(|e| format!("Couldn't keep the client in the cluster: {e:#}"))?; + tracing::info!(client = %id, "tailscale client kept"); + Ok(ClientState { + ok: checks.iter().all(|c| c.ok), + checks, + client_id: id.to_owned(), + hint: hint(secret), + suffix, + }) +} + +// ── Keeping the names ─────────────────────────────────────────────────────── + +/// Approvals asked for already: (Service, node). +static APPROVED: Mutex> = Mutex::new(BTreeSet::new()); + +const TAKEN: &str = "Taken on your tailnet"; + +/// The cluster's names on the tailnet as Pyo wants them ([`TailnetSync`]). +pub async fn sync(c: &Client, w: &TailnetSync) -> anyhow::Result { + let marks: Vec<&str> = std::iter::once(w.mark.as_str()) + .chain(w.adopt.iter().map(String::as_str)) + .filter(|m| !m.is_empty()) + .collect(); + if marks.is_empty() { + anyhow::bail!("no mark for the cluster's names"); + } + let devices = c.devices().await?; + let suffix = devices.iter().find_map(|(_, n, _)| ts::suffix_of(n)); + let remote = c.services().await?; + let ours = |n: &str| { + remote + .get(n) + .is_some_and(|(cm, _)| marks.contains(&cm.as_str())) + }; + let machine = |n: &str| { + w.peers.iter().any(|p| p == n) + || devices + .iter() + .any(|(_, full, _)| full.split('.').next() == Some(n)) + }; + let taken = |n: &str| (remote.contains_key(n) && !ours(n)) || machine(n); + + // Pyo's own names: picked here when they have none, and sandboxes' + // picked again when someone else has it. + let mut wanted: Vec<(String, String)> = Vec::new(); + for o in &w.own { + let others = + |n: &str| wanted.iter().any(|(x, _)| x == n) || w.domains.iter().any(|d| d == n); + let name = if o.keep { + match o.current.as_deref().filter(|n| !n.is_empty()) { + Some(n) => n.to_owned(), + None => ts::pick_name(&o.base, &o.more, |n| taken(n) || others(n)), + } + } else { + ts::own_name(o.current.as_deref(), &o.base, &o.more, |n| { + taken(n) || others(n) + }) + }; + if !ts::valid_name(&name) { + continue; + } + if o.current.as_deref().is_some_and(|c| c != name) { + tracing::info!(old = ?o.current, new = name, kind = o.kind, "tailnet name taken; picked another"); + } + wanted.push((name, o.kind.clone())); + } + for d in &w.domains { + if ts::valid_name(d) && !wanted.iter().any(|(n, _)| n == d) { + wanted.push((d.clone(), "domain".into())); + } + } + + let mut names = Vec::new(); + for (name, kind) in &wanted { + let (addrs, error) = match remote.get(name.as_str()) { + Some((_, addrs)) if ours(name) => (addrs.clone(), None), + Some(_) => (Vec::new(), Some(TAKEN.to_owned())), + None if machine(name) => (Vec::new(), Some(TAKEN.to_owned())), + None => match claim(c, name, &w.mark, &marks).await { + Ok(Claim::Ours(a)) => (a, None), + Ok(Claim::Taken) => (Vec::new(), Some(TAKEN.to_owned())), + Err(e) => { + tracing::warn!(name, error = %e, "couldn't make the tailnet name"); + ( + Vec::new(), + Some("Couldn't make it on your tailnet".to_owned()), + ) + } + }, + }; + names.push(NameState { + name: name.clone(), + kind: kind.clone(), + addrs, + error, + }); + } + + // Ours, no longer used: deleted on the tailnet, and the servers take it + // off. Only names Pyo made for this cluster, each read again first. + let mut deleted = Vec::new(); + for name in w + .made + .iter() + .filter(|n| ours(n) && !wanted.iter().any(|(x, _)| x == *n)) + { + match delete_if_ours(c, name, &marks).await { + Ok(true) => { + tracing::info!(name, "tailnet name deleted"); + deleted.push(name.clone()); + } + Ok(false) => tracing::warn!(name, "not deleted: not Pyo's on the tailnet"), + Err(e) => tracing::warn!(name, error = %e, "couldn't delete the tailnet name"), + } + } + + // The servers: tagged, and approved as hosts of the names they advertise. + let tagged: BTreeMap<&str, bool> = devices + .iter() + .map(|(id, _, tags)| (id.as_str(), tags.iter().any(|t| t == TAG))) + .collect(); + for sv in &w.servers { + let id = sv.node_id.as_str(); + if !id.is_empty() && tagged.get(id) == Some(&false) { + match c.tag(id).await { + Ok(()) => tracing::info!(server = %sv.server, "tagged tag:pyo"), + Err(e) => { + tracing::warn!(server = %sv.server, error = %e, "couldn't tag the server") + } + } + } + } + for n in names.iter().filter(|n| n.error.is_none()) { + let name = &n.name; + let nodes: Vec<&str> = w + .servers + .iter() + .filter(|sv| sv.advertised.iter().any(|a| a == name)) + .map(|sv| sv.node_id.as_str()) + .filter(|n| !n.is_empty()) + .collect(); + let asked = |n: &str| { + APPROVED + .lock() + .map(|a| a.contains(&(name.clone(), n.to_owned()))) + .unwrap_or(false) + }; + if nodes.iter().all(|n| asked(n)) { + continue; + } + let Ok(hosts) = c.hosts(name).await else { + continue; + }; + for node in nodes { + let ok = hosts.get(node) == Some(&true) || c.approve(name, node).await.is_ok(); + if ok && let Ok(mut a) = APPROVED.lock() { + a.insert((name.clone(), node.to_owned())); + } + } + } + + // Machines whose server was deleted: off the tailnet. + let mut forgotten = Vec::new(); + for node in &w.forget { + match c.delete_device(node).await { + Ok(()) => forgotten.push(node.clone()), + Err(e) => tracing::warn!(node, error = %e, "couldn't take the machine off the tailnet"), + } + } + let (lock_waiting, machines) = match c.device_details().await { + Ok(d) => (lock_waiting(&d), machines(&d)), + Err(e) => { + tracing::warn!(error = %e, "tailnet lock: couldn't read the tailnet"); + (Vec::new(), Vec::new()) + } + }; + Ok(TailnetSynced { + suffix, + names, + deleted, + lock_waiting, + machines, + forgotten, + }) +} + +/// Whether a name typed for a tailnet domain can be had. +pub async fn check_name(c: &Client, name: &str, marks: &[&str]) -> anyhow::Result { + let devices = c.devices().await?; + let suffix = devices.iter().find_map(|(_, n, _)| ts::suffix_of(n)); + let remote = c.services().await?; + let mine = remote + .get(name) + .is_some_and(|(cm, _)| marks.contains(&cm.as_str())); + let machine = devices + .iter() + .any(|(_, full, _)| full.split('.').next() == Some(name)); + let state = if (remote.contains_key(name) && !mine) || machine { + "taken" + } else { + // The list can leave some out: the Service itself, read directly. + match c.service(name).await? { + None => "free", + Some((comment, _)) if marks.contains(&comment.as_str()) => "ours", + Some(_) => "taken", + } + }; + Ok(NameCheck { + state: state.into(), + suffix, + }) +} + +// ── The commands ──────────────────────────────────────────────────────────── + +fn with_data(mut r: CommandResult, data: impl serde::Serialize) -> CommandResult { + r.data = serde_json::to_value(data).ok(); + r +} + +const NO_CLIENT: &str = "Tailscale isn't set up on this cluster."; + +async fn need_client(kube: &kube::Client) -> Result, CommandResult> { + match saved(kube).await { + Ok(Some(c)) => Ok(c), + Ok(None) => Err(failed(NO_CLIENT)), + Err(e) => Err(failed(format!( + "Couldn't read the cluster's Tailscale client: {e:#}" + ))), + } +} + +/// [`pyo_proto::Command::TailscaleSetup`]. +pub async fn run_setup( + kube: &kube::Client, + token: String, + version: Option, +) -> CommandResult { + let host = setup::Cluster { + kube: kube.clone(), + base: api_url(), + }; + let api = setup::Api::at(&api_url(), setup::Token::from(token)); + match version { + None => match setup::plan(&api, &host).await { + Ok(p) => with_data(ok("Read the tailnet."), p), + Err(e) => failed(e), + }, + Some(v) => { + let out = setup::apply(&api, &host, &v).await; + let mut data = serde_json::to_value(&out).unwrap_or(Value::Null); + // The client the cluster keeps now, as Pyo shows it (never + // its secret). + if let Ok(Some((id, secret))) = stored(kube).await { + data["client"] = json!({ "clientId": id, "hint": hint(&secret) }); + } + CommandResult { + data: Some(data), + ..ok("Set up.") + } + } + } +} + +/// [`pyo_proto::Command::TailscaleClient`]. +pub async fn run_client(kube: &kube::Client, id: &str, secret: &str) -> CommandResult { + match use_client(kube, &api_url(), id, secret).await { + Ok(state) => with_data(ok("Kept the Tailscale client."), state), + Err(e) => failed(e), + } +} + +/// [`pyo_proto::Command::TailscaleTest`]. +pub async fn run_test(kube: &kube::Client) -> CommandResult { + let Ok(Some((id, secret))) = stored(kube).await else { + return failed(NO_CLIENT); + }; + let (checks, suffix) = test(&client(&id, &secret)).await; + with_data( + ok("Checked."), + ClientState { + ok: checks.iter().all(|c| c.ok), + checks, + client_id: id, + hint: hint(&secret), + suffix, + }, + ) +} + +/// [`pyo_proto::Command::TailscaleSync`]. +pub async fn run_sync(kube: &kube::Client, w: &TailnetSync) -> CommandResult { + let c = match need_client(kube).await { + Ok(c) => c, + Err(r) => return r, + }; + match sync(&c, w).await { + Ok(s) => with_data(ok("Synced."), s), + Err(e) => failed(format!("{e:#}")), + } +} + +/// [`pyo_proto::Command::TailscaleKey`]. +pub async fn run_key(kube: &kube::Client, description: &str) -> CommandResult { + let c = match need_client(kube).await { + Ok(c) => c, + Err(r) => return r, + }; + match c.auth_key(description).await { + Ok((_, key)) => with_data(ok("Made a key."), json!({ ts::KEY_FIELD: key })), + Err(e) => { + tracing::warn!(error = %format!("{e:#}"), "Tailscale made no auth key"); + failed("Tailscale made no auth key. Check Tailscale on this cluster.") + } + } +} + +/// [`pyo_proto::Command::TailscaleCheckName`]. +pub async fn run_check_name(kube: &kube::Client, name: &str, marks: &[String]) -> CommandResult { + let c = match need_client(kube).await { + Ok(c) => c, + Err(r) => return r, + }; + let marks: Vec<&str> = marks.iter().map(String::as_str).collect(); + match check_name(&c, name, &marks).await { + Ok(n) => with_data(ok("Checked."), n), + Err(e) => failed(format!("{e:#}")), + } +} + +/// [`pyo_proto::Command::TailscaleRemove`]: Pyo's names deleted while the +/// client still can, then the client forgotten. +pub async fn run_remove(kube: &kube::Client, names: &[String], marks: &[String]) -> CommandResult { + let marks: Vec<&str> = marks.iter().map(String::as_str).collect(); + if let Ok(Some(c)) = saved(kube).await { + for name in names { + if let Err(e) = delete_if_ours(&c, name, &marks).await { + tracing::warn!(name, error = %e, "couldn't delete the tailnet name"); + } + } + } + match forget(kube).await { + Ok(()) => ok("Removed Tailscale."), + Err(e) => failed(format!( + "Couldn't remove the cluster's Tailscale client: {e:#}" + )), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/pyo-agent/src/tailscale/sandbox.rs b/crates/pyo-agent/src/tailscale/sandbox.rs new file mode 100644 index 00000000..e08d6772 --- /dev/null +++ b/crates/pyo-agent/src/tailscale/sandbox.rs @@ -0,0 +1,162 @@ +//! Pyo's calls to a sandbox server's daemon, made from the cluster +//! (pyo-proto's tailscale.rs [`SandboxCall`]): the daemon answers plain +//! HTTP on the server's tailnet address, which the cluster's servers reach +//! and Pyo may not (Pyo Cloud runs outside every customer's tailnet). +//! +//! Only the daemon's own API: a tailnet address, its port, a path under +//! `/v1/`, and the token Pyo signed for the call. The daemon checks that +//! token itself, so this agent adds no access of its own. + +use std::time::Duration; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as B64; +use pyo_proto::CommandResult; +use pyo_proto::tailscale::{SandboxAnswer, SandboxCall, tailnet_ip}; + +use crate::{failed, ok}; + +/// The longest a call may take (an exec's own timeout, and some). +const MAX: Duration = Duration::from_secs(15 * 60); + +fn client() -> &'static reqwest::Client { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + C.get_or_init(|| { + reqwest::Client::builder() + .connect_timeout(Duration::from_secs(5)) + // The tailnet, never a proxy. + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .build() + .expect("an HTTP client") + }) +} + +/// The daemon's URL for a call, or why it isn't one Pyo makes. +pub fn url(c: &SandboxCall) -> Result { + if !tailnet_ip(&c.address) { + return Err("A sandbox server is called on its tailnet address only."); + } + if !c.path.starts_with("/v1/") || c.path.contains("..") || c.path.contains('#') { + return Err("Only the sandbox server's own API is called."); + } + let port = pyo_proto::sandbox::DAEMON_PORT; + Ok(match c.address.parse::() { + Ok(std::net::IpAddr::V6(v)) => format!("http://[{v}]:{port}{}", c.path), + _ => format!("http://{}:{port}{}", c.address, c.path), + }) +} + +pub async fn run(c: &SandboxCall) -> CommandResult { + let url = match url(c) { + Ok(u) => u, + Err(e) => return failed(e), + }; + let method = match c.method.as_str() { + "GET" => reqwest::Method::GET, + "POST" => reqwest::Method::POST, + "PUT" => reqwest::Method::PUT, + "DELETE" => reqwest::Method::DELETE, + _ => return failed("Not a method Pyo calls a sandbox server with."), + }; + let mut req = client() + .request(method, &url) + .bearer_auth(&c.token) + .timeout(Duration::from_secs(c.timeout_secs.max(1)).min(MAX)); + if let Some(ct) = &c.content_type { + req = req.header(reqwest::header::CONTENT_TYPE, ct); + } + if let Some(b) = &c.body { + req = if c.raw { + match B64.decode(b) { + Ok(bytes) => req.body(bytes), + Err(_) => return failed("The body isn't base64."), + } + } else { + req.header(reqwest::header::CONTENT_TYPE, "application/json") + .body(b.clone()) + }; + } + let answer = match req.send().await { + Ok(r) => { + let status = r.status().as_u16(); + let content_type = r + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + match r.bytes().await { + Ok(b) => SandboxAnswer { + status, + body: if c.raw && (200..300).contains(&status) { + B64.encode(&b) + } else { + String::from_utf8_lossy(&b).into_owned() + }, + content_type, + }, + Err(e) => unreachable(e), + } + } + Err(e) => unreachable(e), + }; + CommandResult { + data: serde_json::to_value(answer).ok(), + ..ok("Called the sandbox server.") + } +} + +/// Couldn't reach it: status 0, and why. +fn unreachable(e: reqwest::Error) -> SandboxAnswer { + SandboxAnswer { + status: 0, + body: if e.is_timeout() { + "The sandbox server didn't answer in time.".to_owned() + } else { + format!("Couldn't reach the sandbox server: {}", e.without_url()) + }, + content_type: None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn call(address: &str, path: &str) -> SandboxCall { + SandboxCall { + address: address.into(), + method: "GET".into(), + path: path.into(), + token: "t".into(), + body: None, + raw: false, + content_type: None, + timeout_secs: 5, + } + } + + #[test] + fn only_the_daemon_on_the_tailnet() { + assert_eq!( + url(&call("100.64.0.7", "/v1/report")).unwrap(), + "http://100.64.0.7:7070/v1/report" + ); + assert_eq!( + url(&call( + "fd7a:115c:a1e0::1", + "/v1/sandboxes/s1/files?path=%2Fa" + )) + .unwrap(), + "http://[fd7a:115c:a1e0::1]:7070/v1/sandboxes/s1/files?path=%2Fa" + ); + // Not the tailnet: the cluster's own network, the cloud's metadata. + assert!(url(&call("10.43.0.1", "/v1/report")).is_err()); + assert!(url(&call("169.254.169.254", "/v1/report")).is_err()); + assert!(url(&call("example.com", "/v1/report")).is_err()); + // Not the daemon's API. + assert!(url(&call("100.64.0.7", "/metrics")).is_err()); + assert!(url(&call("100.64.0.7", "/v1/../admin")).is_err()); + assert!(url(&call("100.64.0.7", "@evil/v1/")).is_err()); + } +} diff --git a/crates/pyo-api/src/tailscale_setup.rs b/crates/pyo-agent/src/tailscale/setup.rs similarity index 92% rename from crates/pyo-api/src/tailscale_setup.rs rename to crates/pyo-agent/src/tailscale/setup.rs index 24d2bef1..cc6c31ce 100644 --- a/crates/pyo-api/src/tailscale_setup.rs +++ b/crates/pyo-agent/src/tailscale/setup.rs @@ -1,8 +1,10 @@ -//! Setting up Tailscale from one API access token (Integrations › Tailscale). +//! Setting up Tailscale from one API access token, in the cluster's agent. //! //! An admin pastes a short-lived API access token (Settings › Keys in the -//! Tailscale console). [`plan`] reads the tailnet and says what's missing, -//! changing nothing. [`apply`] then makes those changes: +//! Tailscale console) in the dashboard. Pyo passes it to the cluster's +//! agent in a signed command, and never keeps it. [`plan`] reads the +//! tailnet and says what's missing, changing nothing. [`apply`] then makes +//! those changes: //! //! - **MagicDNS** and **HTTPS certificates** on. //! - **The policy**: `tag:pyo` in `tagOwners`, a grant to reach it on ports @@ -12,13 +14,15 @@ //! place, so its comments and formatting stay. It's validated first and //! written with `If-Match`, and only as the admin reviewed it: if it //! changed since, nothing is written and the admin reviews it again. -//! - **Pyo's own OAuth client**, with the scopes the manual path asks for, -//! saved and checked like one pasted by hand ([`crate::tailscale::save_client`]). +//! - **The cluster's own OAuth client**, with the scopes the manual path +//! asks for, checked and kept like one pasted by hand +//! ([`super::use_client`]): a Secret in pyo-system. //! - **The pasted token is deleted** last, however the setup ends, or left //! to the admin as a todo. It's kept only for a new review. //! -//! The token lives in memory for one request only: it's never stored, -//! logged or put in an error ([`Token`], [`Api::scrub`]). A tailnet that's +//! The token lives in memory for one command only: it's never stored, +//! logged or put in an error ([`Token`], [`Api::scrub`]). Only non-secret +//! results go back to Pyo. A tailnet that's //! already set up gets no changes. A policy managed in Git isn't written: //! the lines to add come back instead. @@ -26,9 +30,9 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use zeroize::Zeroize; -use crate::AppState; -use crate::error::{ApiError, ApiResult}; -use crate::tailscale::{Reply, TAG, TsError}; +use pyo_proto::tailscale::TAG; + +use super::{Reply, TsError}; /// The scopes Pyo's own client gets: what the manual path asks for. const SCOPES: [&str; 3] = ["devices:core", "auth_keys", "services"]; @@ -48,6 +52,12 @@ const DELETE_TOKEN: &str = "Delete the token under Settings › Keys in the Tail #[serde(transparent)] pub struct Token(String); +impl From for Token { + fn from(s: String) -> Self { + Self(s) + } +} + impl Token { #[cfg(test)] pub fn new(s: &str) -> Self { @@ -74,7 +84,7 @@ impl Drop for Token { } /// The token's first check: the shape of an API access token. -fn check_shape(t: &Token) -> Result<(), String> { +pub fn check_shape(t: &Token) -> Result<(), String> { let s = t.0.trim(); if s.starts_with("tskey-client-") { return Err("That's an OAuth client secret. Paste an API access token, or set up with an OAuth client instead.".into()); @@ -111,11 +121,7 @@ pub struct Api { } impl Api { - pub fn new(token: Token) -> Self { - Self::at(crate::tailscale::API, token) - } - - fn at(base: &str, mut token: Token) -> Self { + pub fn at(base: &str, mut token: Token) -> Self { let t = token.0.trim().to_owned(); token.0.zeroize(); token.0 = t; @@ -135,8 +141,8 @@ impl Api { out } - /// A request with the token, through the same path as Pyo's own client - /// ([`crate::tailscale::send`]), with the token scrubbed from any error. + /// A request with the token, through the same path as the cluster's + /// client ([`super::send`]), with the token scrubbed from any error. async fn send( &self, method: reqwest::Method, @@ -144,7 +150,7 @@ impl Api { body: Body, headers: &[(&str, &str)], ) -> Result { - let mut req = crate::tailscale::http() + let mut req = super::http() .request(method, format!("{}{path}", self.base)) .bearer_auth(&self.token.0); for (k, v) in headers { @@ -157,7 +163,7 @@ impl Api { .header(reqwest::header::CONTENT_TYPE, "application/hujson") .body(t), }; - crate::tailscale::send(req).await.map_err(|e| TsError { + super::send(req).await.map_err(|e| TsError { status: e.status, message: self.scrub(&e.message), }) @@ -512,32 +518,40 @@ pub fn diff(old: &str, new: &str) -> Vec { // ── Reading the tailnet ───────────────────────────────────────────────────── -/// What the installation does for the setup: the AppState, or a stand-in -/// in tests. +/// What the cluster does for the setup: its agent, or a stand-in in tests. pub(crate) trait Host { - /// It can seal a client secret (PYO_SECRET_KEY is set). + /// It can keep a client secret. fn can_store(&self) -> bool; - /// The saved OAuth client's ID, when it signs in. + /// The kept OAuth client's ID, when it signs in. async fn working_client(&self) -> Option; - /// Saves a new client like one pasted by hand: `{ ok, checks }`. + /// Keeps a new client like one pasted by hand: `{ ok, checks }`. async fn save_client(&self, id: &str, secret: &str) -> Result; } -impl Host for AppState { +/// The cluster: its client is a Secret in pyo-system. +pub struct Cluster { + pub kube: kube::Client, + /// Tailscale's API. + pub base: String, +} + +impl Host for Cluster { fn can_store(&self) -> bool { - self.sealer.enabled() + true } async fn working_client(&self) -> Option { - let (cfg, c) = crate::tailscale::saved_client(self).await.ok()??; - c.access_token().await.ok()?; - Some(cfg.client_id) + let (id, secret) = super::stored(&self.kube).await.ok()??; + super::Client::at(&self.base, &id, &secret) + .access_token() + .await + .ok()?; + Some(id) } async fn save_client(&self, id: &str, secret: &str) -> Result { - crate::tailscale::save_client(self, id, Some(secret)) - .await - .map_err(|e| e.message) + let state = super::use_client(&self.kube, &self.base, id, secret).await?; + Ok(json!({ "ok": state.ok, "checks": state.checks })) } } @@ -570,7 +584,7 @@ struct Survey { magic_dns: bool, /// None when Tailscale doesn't say. https: Option, - /// Pyo's saved client is on this tailnet and signs in. + /// The cluster's kept client is on this tailnet and signs in. client: bool, } @@ -672,7 +686,7 @@ pub struct Plan { pub diff: Vec, /// Why Pyo can't go on by itself, with `diff` as the lines to add. pub blocked: Option, - /// The policy as Pyo read it, to hand back to setUpTailscale: if it + /// The policy as Pyo read it, to hand back for the setup: if it /// changed since, Pyo changes nothing and asks for a new review. pub version: String, } @@ -733,8 +747,7 @@ pub(crate) async fn plan_with(api: &Api, host: &impl Host) -> Result Result, Stop> { async fn make_client(api: &Api, host: &impl Host) -> Result, String> { let body = json!({ "keyType": "client", - "description": crate::tailscale::key_description("Pyo"), + "description": pyo_proto::tailscale::key_description("Pyo"), "scopes": SCOPES, "tags": [TAG], }); @@ -1068,19 +1081,21 @@ pub(crate) async fn apply_with(api: &Api, host: &impl Host, reviewed: &str) -> O out } -/// planTailscaleSetup. -pub async fn plan(s: &AppState, token: Token) -> ApiResult { - check_shape(&token).map_err(ApiError::bad_request)?; - let p = plan_with(&Api::new(token), s) - .await - .map_err(ApiError::bad_request)?; - Ok(json!({ "ok": true, "plan": p })) +/// The plan, for the token `api` carries. +pub async fn plan(api: &Api, host: &impl Host) -> Result { + check_shape(&api.token)?; + plan_with(api, host).await } -/// setUpTailscale: `version` is the reviewed plan's. -pub async fn apply(s: &AppState, token: Token, version: &str) -> ApiResult { - check_shape(&token).map_err(ApiError::bad_request)?; - Ok(apply_with(&Api::new(token), s, version).await) +/// The setup, as reviewed (`version` is the reviewed plan's). +pub async fn apply(api: &Api, host: &impl Host, version: &str) -> Outcome { + if let Err(e) = check_shape(&api.token) { + return Outcome { + error: Some(e), + ..Default::default() + }; + } + apply_with(api, host, version).await } #[cfg(test)] diff --git a/crates/pyo-api/src/tailscale_setup/tests.rs b/crates/pyo-agent/src/tailscale/setup/tests.rs similarity index 99% rename from crates/pyo-api/src/tailscale_setup/tests.rs rename to crates/pyo-agent/src/tailscale/setup/tests.rs index 83af82a9..58dfc392 100644 --- a/crates/pyo-api/src/tailscale_setup/tests.rs +++ b/crates/pyo-agent/src/tailscale/setup/tests.rs @@ -264,7 +264,7 @@ async fn serve(m: Mock) -> (String, Shared) { (format!("http://{addr}"), st) } -/// The installation, as the setup sees it. +/// The cluster, as the setup sees it. #[derive(Default)] struct FakeHost { no_key: bool, diff --git a/crates/pyo-agent/src/tailscale/tests.rs b/crates/pyo-agent/src/tailscale/tests.rs new file mode 100644 index 00000000..de299d15 --- /dev/null +++ b/crates/pyo-agent/src/tailscale/tests.rs @@ -0,0 +1,363 @@ +//! The cluster's client against a mock Tailscale API. + +use super::*; +use std::sync::{Arc, Mutex}; + +use axum::{ + Json, Router, + body::Bytes, + extract::State, + http::{Method, StatusCode, Uri}, + response::{IntoResponse, Response}, +}; +use pyo_proto::tailscale::{OwnName, SyncServer}; + +/// A tailnet: Services by name (comment, addresses), machines (node ID, +/// full name, tags), each Service's approved hosts, and every write. +#[derive(Default)] +struct Net { + services: BTreeMap)>, + /// Services the list leaves out (defined, hosted nowhere). + hidden: BTreeSet, + devices: Vec<(String, String, Vec)>, + approved: BTreeSet<(String, String)>, + writes: Vec, +} + +type Shared = Arc>; + +async fn handle(State(st): State, method: Method, uri: Uri, _body: Bytes) -> Response { + let mut n = st.lock().unwrap(); + let path = uri.path().to_owned(); + let svc = |p: &str| { + p.strip_prefix("/tailnet/-/services/svc:") + .map(str::to_owned) + }; + match (method.as_str(), path.as_str()) { + ("POST", "/oauth/token") => Json(json!({ "access_token": "t" })).into_response(), + ("GET", "/tailnet/-/services") => { + let list: Vec = n + .services + .iter() + .filter(|(k, _)| !n.hidden.contains(*k)) + .map(|(k, (c, a))| json!({ "name": format!("svc:{k}"), "comment": c, "addrs": a })) + .collect(); + Json(json!({ "vipServices": list })).into_response() + } + ("GET", "/tailnet/-/devices") => { + let list: Vec = n + .devices + .iter() + .map(|(id, name, tags)| json!({ "nodeId": id, "name": name, "hostname": name.split('.').next(), "tags": tags })) + .collect(); + Json(json!({ "devices": list })).into_response() + } + ("POST", "/tailnet/-/keys") => { + n.writes.push("key".into()); + Json(json!({ "id": "k1", "key": "tskey-auth-k1-secret" })).into_response() + } + ("POST", p) if p.starts_with("/device/") && p.ends_with("/tags") => { + let id = p + .trim_start_matches("/device/") + .trim_end_matches("/tags") + .to_owned(); + n.writes.push(format!("tag {id}")); + Json(json!({})).into_response() + } + (m, p) if svc(p).is_some() => { + let rest = svc(p).unwrap(); + if let Some((name, tail)) = rest.split_once('/') { + if tail == "devices" { + let hosts: Vec = n + .approved + .iter() + .filter(|(s, _)| s == name) + .map(|(_, node)| json!({ "stableNodeID": node, "approvalLevel": "approved" })) + .collect(); + return Json(json!({ "hosts": hosts })).into_response(); + } + if let Some(node) = tail + .strip_prefix("device/") + .and_then(|t| t.strip_suffix("/approved")) + { + n.writes.push(format!("approve {name} {node}")); + n.approved.insert((name.to_owned(), node.to_owned())); + return Json(json!({})).into_response(); + } + } + let name = rest; + match m { + "GET" => match n.services.get(&name) { + Some((c, a)) => Json(json!({ "comment": c, "addrs": a })).into_response(), + None => ( + StatusCode::NOT_FOUND, + Json(json!({ "message": "not found" })), + ) + .into_response(), + }, + "PUT" => { + n.writes.push(format!("PUT {name}")); + let addrs = vec![format!("100.100.1.{}", n.services.len() + 10)]; + n.services + .insert(name, ("Made by Pyo (i cl_a)".into(), addrs.clone())); + Json(json!({ "addrs": addrs })).into_response() + } + "DELETE" => { + n.writes.push(format!("DELETE {name}")); + n.services.remove(&name); + Json(json!({})).into_response() + } + _ => StatusCode::METHOD_NOT_ALLOWED.into_response(), + } + } + _ => ( + StatusCode::NOT_FOUND, + Json(json!({ "message": "no such path" })), + ) + .into_response(), + } +} + +async fn serve(net: Net) -> (Client, Shared) { + let st: Shared = Arc::new(Mutex::new(net)); + 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() }); + ( + Client::at(&format!("http://{addr}"), "id", "tskey-client-id-secret"), + st, + ) +} + +const MARK: &str = "Made by Pyo (i cl_a)"; + +fn svc(comment: &str, addr: &str) -> (String, Vec) { + (comment.to_owned(), vec![addr.to_owned()]) +} + +/// A Service ("docker", someone else's) that the list leaves out but a +/// direct read finds. Pyo must refuse the name and never write to it. +#[tokio::test] +async fn a_service_the_list_leaves_out_is_never_written() { + let mut net = Net::default(); + net.services + .insert("docker".into(), svc("the user's", "100.100.1.1")); + net.services.insert("mine".into(), svc(MARK, "100.100.1.2")); + net.hidden = ["docker".to_owned(), "mine".to_owned()].into(); + let (c, st) = serve(net).await; + assert!( + c.services().await.unwrap().is_empty(), + "the list leaves them out" + ); + assert_eq!( + claim(&c, "docker", MARK, &[MARK]).await.unwrap(), + Claim::Taken + ); + assert!(!delete_if_ours(&c, "docker", &[MARK]).await.unwrap()); + assert_eq!( + claim(&c, "mine", MARK, &[MARK]).await.unwrap(), + Claim::Ours(vec!["100.100.1.2".into()]) + ); + assert!(matches!( + claim(&c, "blog", MARK, &[MARK]).await.unwrap(), + Claim::Ours(_) + )); + assert!(delete_if_ours(&c, "mine", &[MARK]).await.unwrap()); + assert_eq!(st.lock().unwrap().writes, ["PUT blog", "DELETE mine"]); +} + +#[test] +fn machines_waiting_for_a_signature() { + let d = |host: &str, tag: &str, key: &str, err: &str| Device { + node_id: "n".into(), + hostname: host.into(), + tags: vec![tag.into()], + node_key: key.into(), + lock_error: err.into(), + }; + let waiting = lock_waiting(&[ + d( + "sbx-1", + TAG, + "nodekey:ab12", + "tailnet lock: node key not signed", + ), + d("laptop", "tag:other", "nodekey:cd34", "not signed"), + d("web-1", TAG, "nodekey:ef56", ""), + ]); + assert_eq!( + waiting, + [LockWaiting { + name: "sbx-1".into(), + sign_command: "tailscale lock sign nodekey:ab12".into() + }] + ); +} + +fn own(kind: &str, current: Option<&str>, base: &str, keep: bool) -> OwnName { + OwnName { + kind: kind.into(), + current: current.map(str::to_owned), + base: base.into(), + more: "home".into(), + keep, + } +} + +fn names(s: &TailnetSynced) -> Vec<(String, String, bool)> { + s.names + .iter() + .map(|n| (n.name.clone(), n.kind.clone(), n.error.is_none())) + .collect() +} + +/// Pyo's own names on the cluster Pyo runs on: picked around what's taken +/// (someone's Service, a machine, a domain), the dashboard's kept even +/// when someone else has it, the sandboxes' picked again. +#[tokio::test] +async fn own_names_are_picked_around_what_is_taken() { + let mut net = Net::default(); + net.services + .insert("pyo".into(), svc("someone's", "100.100.1.1")); + net.services + .insert("sandboxes".into(), svc("another Pyo's", "100.100.1.3")); + net.devices + .push(("n1".into(), "registry.tail1.ts.net".into(), vec![])); + net.devices + .push(("n2".into(), "web-1.tail1.ts.net".into(), vec![TAG.into()])); + let (c, st) = serve(net).await; + let w = TailnetSync { + mark: MARK.into(), + own: vec![ + own("dashboard", None, "pyo", true), + own("registry", None, "registry", true), + own("sandboxes", Some("sandboxes"), "sandboxes", false), + ], + domains: vec!["blog".into()], + ..Default::default() + }; + let s = sync(&c, &w).await.unwrap(); + assert_eq!(s.suffix.as_deref(), Some("tail1.ts.net")); + assert_eq!( + names(&s), + [ + ("pyo-home".into(), "dashboard".into(), true), + ("registry-home".into(), "registry".into(), true), + ("sandboxes-home".into(), "sandboxes".into(), true), + ("blog".into(), "domain".into(), true), + ] + ); + // A kept name someone else took meanwhile: kept, and said so. + let w = TailnetSync { + own: vec![own("dashboard", Some("pyo"), "pyo", true)], + ..w + }; + let s = sync(&c, &w).await.unwrap(); + assert_eq!(s.names[0].name, "pyo"); + assert_eq!(s.names[0].error.as_deref(), Some(TAKEN)); + let writes = st.lock().unwrap().writes.clone(); + assert!( + !writes + .iter() + .any(|w| w == "PUT pyo" || w == "PUT sandboxes"), + "{writes:?}" + ); +} + +/// Only names this cluster made, no longer wanted, and still marked as its +/// own on the tailnet are deleted. Another cluster's (another mark) and +/// someone's own stay. +#[tokio::test] +async fn only_this_clusters_unused_names_are_deleted() { + let mut net = Net::default(); + net.services.insert("old".into(), svc(MARK, "100.100.1.1")); + net.services + .insert("adopted".into(), svc("Made by Pyo (i)", "100.100.1.2")); + net.services + .insert("other".into(), svc("Made by Pyo (i cl_b)", "100.100.1.3")); + net.services + .insert("theirs".into(), svc("the user's", "100.100.1.4")); + net.services.insert("kept".into(), svc(MARK, "100.100.1.5")); + let (c, st) = serve(net).await; + let w = TailnetSync { + mark: MARK.into(), + adopt: vec!["Made by Pyo (i)".into()], + domains: vec!["kept".into()], + made: ["old", "adopted", "other", "theirs", "kept"] + .map(str::to_owned) + .to_vec(), + ..Default::default() + }; + let s = sync(&c, &w).await.unwrap(); + assert_eq!(s.deleted, ["old", "adopted"]); + let net = st.lock().unwrap(); + assert_eq!(net.writes, ["DELETE old", "DELETE adopted"]); + assert!(net.services.contains_key("other") && net.services.contains_key("theirs")); +} + +/// The cluster's servers: tagged when they aren't, and approved as hosts +/// of the names they advertise, once. +#[tokio::test] +async fn servers_are_tagged_and_approved_once() { + let mut net = Net::default(); + net.devices + .push(("n1".into(), "web-1.tail1.ts.net".into(), vec![])); + net.devices + .push(("n2".into(), "web-2.tail1.ts.net".into(), vec![TAG.into()])); + let (c, st) = serve(net).await; + let server = |name: &str, node: &str| SyncServer { + server: name.into(), + node_id: node.into(), + advertised: vec!["shop".into()], + }; + let w = TailnetSync { + mark: MARK.into(), + domains: vec!["shop".into()], + servers: vec![server("web-1", "n1"), server("web-2", "n2")], + ..Default::default() + }; + sync(&c, &w).await.unwrap(); + sync(&c, &w).await.unwrap(); + let writes = st.lock().unwrap().writes.clone(); + assert_eq!( + writes, + [ + "PUT shop", + "tag n1", + "approve shop n1", + "approve shop n2", + "tag n1" + ] + ); +} + +#[tokio::test] +async fn a_name_check_reads_the_service_itself() { + let mut net = Net::default(); + net.services + .insert("docker".into(), svc("the user's", "100.100.1.1")); + net.services.insert("blog".into(), svc(MARK, "100.100.1.2")); + net.hidden = ["docker".to_owned()].into(); + net.devices + .push(("n1".into(), "laptop.tail1.ts.net".into(), vec![])); + let (c, _) = serve(net).await; + let state = async |n: &str| check_name(&c, n, &[MARK]).await.unwrap().state; + assert_eq!(state("docker").await, "taken"); + assert_eq!(state("laptop").await, "taken"); + assert_eq!(state("blog").await, "ours"); + assert_eq!(state("shop").await, "free"); +} + +#[tokio::test] +async fn a_join_key_is_single_use_tagged_and_short_lived() { + let (c, st) = serve(Net::default()).await; + let (_, key) = c.auth_key("Pyo: join web-2").await.unwrap(); + assert_eq!(key, "tskey-auth-k1-secret"); + assert_eq!(st.lock().unwrap().writes, ["key"]); +} + +#[test] +fn hints_show_the_last_characters_only() { + assert_eq!(hint("tskey-client-abc-0123456789WXYZ"), "…WXYZ"); +} diff --git a/crates/pyo-agent/src/terminal.rs b/crates/pyo-agent/src/terminal.rs index 69157ebf..fb651ba7 100644 --- a/crates/pyo-agent/src/terminal.rs +++ b/crates/pyo-agent/src/terminal.rs @@ -1,5 +1,7 @@ //! A shell in one of a service's replicas, for the dashboard's terminal: exec -//! with a TTY, relayed over a WebSocket the agent dials to the API. +//! with a TTY, relayed over a WebSocket the agent dials to the API. Also one +//! command (`pyo exec -- cmd`), with or without a TTY: without one, each +//! output frame starts with its stream, and the exit code comes back. use futures::{SinkExt, StreamExt}; use k8s_openapi::api::core::v1::Pod; @@ -7,7 +9,7 @@ use kube::{ Api, ResourceExt, api::{AttachParams, ListParams, TerminalSize}, }; -use pyo_proto::{ServiceRef, TerminalFrame}; +use pyo_proto::{STREAM_STDERR, STREAM_STDOUT, ServiceRef, TerminalFrame}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio_tungstenite::tungstenite::Message; @@ -26,20 +28,22 @@ fn frame(f: &TerminalFrame) -> Message { Message::text(serde_json::to_string(f).unwrap_or_default()) } -pub async fn run( - agent: Agent, - session_id: String, - service: ServiceRef, - pod: String, - shell: String, -) { +/// What to run: a shell, or one command, with or without a TTY. +pub struct Run { + pub pod: String, + pub shell: String, + pub command: Vec, + pub tty: bool, +} + +pub async fn run(agent: Agent, session_id: String, service: ServiceRef, what: Run) { let mut ws = match agent.api.terminal_socket(&session_id).await { Ok(ws) => ws, Err(e) => { return tracing::warn!(%session_id, error = %e, "terminal: couldn't reach the API"); } }; - let result = open(&agent, &service, &pod, &shell, &mut ws).await; + let result = open(&agent, &service, &what, &mut ws).await; if let Err(e) = result { let _ = ws .send(frame(&TerminalFrame::Error { @@ -51,22 +55,42 @@ pub async fn run( tracing::info!(%session_id, service = %service.name, "terminal closed"); } -async fn open( - agent: &Agent, - service: &ServiceRef, - want_pod: &str, - shell: &str, - ws: &mut S, -) -> anyhow::Result<()> +/// The exit code an exec's status gives: 0 for success, the code of a +/// command that failed, none when it didn't run (and why). +fn exit_code( + status: Option<&k8s_openapi::apimachinery::pkg::apis::meta::v1::Status>, +) -> Result { + let Some(st) = status else { + return Err("The command's status is unknown.".into()); + }; + if st.status.as_deref() == Some("Success") { + return Ok(0); + } + st.details + .as_ref() + .and_then(|d| d.causes.as_ref()) + .and_then(|cs| cs.iter().find(|c| c.reason.as_deref() == Some("ExitCode"))) + .and_then(|c| c.message.as_deref()?.trim().parse().ok()) + .ok_or_else(|| { + st.message + .clone() + .filter(|m| !m.is_empty()) + .unwrap_or_else(|| "The command didn't run.".into()) + }) +} + +async fn open(agent: &Agent, service: &ServiceRef, what: &Run, ws: &mut S) -> anyhow::Result<()> where S: futures::Stream> + futures::Sink + Unpin, { + let (want_pod, shell) = (what.pod.as_str(), what.shell.as_str()); let pods: Api = Api::namespaced(agent.kube.clone(), &service.namespace); - let list = pods - .list(&ListParams::default().labels(&format!("{SERVICE_LABEL}={}", service.service_id))) - .await?; + let lp = ListParams::default() + .labels(&format!("{SERVICE_LABEL}={}", service.service_id)) + .fields(crate::pods::LIVE); + let list = crate::pods::list_pods(&pods, &lp).await?; let ready = |p: &Pod| { p.metadata.deletion_timestamp.is_none() && p.status @@ -75,14 +99,14 @@ where .is_some_and(|cs| cs.iter().any(|c| c.type_ == "Ready" && c.status == "True")) }; let pod = if want_pod.is_empty() { - list.items.iter().find(|p| ready(p)).ok_or_else(|| { + list.iter().find(|p| ready(p)).ok_or_else(|| { anyhow::anyhow!( "{} has no running replica to open a terminal in. Start or deploy it first.", service.name ) })? } else { - let p = list.items.iter().find(|p| p.name_any() == want_pod).ok_or_else(|| anyhow::anyhow!("Replica {want_pod} is gone (replaced by a deploy or restart). Pick another one."))?; + let p = list.iter().find(|p| p.name_any() == want_pod).ok_or_else(|| anyhow::anyhow!("Replica {want_pod} is gone (replaced by a deploy or restart). Pick another one."))?; if !ready(p) { anyhow::bail!("Replica {want_pod} isn't running right now. Pick another one."); } @@ -90,6 +114,10 @@ where }; let name = pod.name_any(); + if !what.command.is_empty() { + return command(&pods, &name, what, ws).await; + } + // A named shell must exist in the image: say so rather than a bare exit. if shell != "auto" && !shell.is_empty() { let mut probe = pods @@ -134,8 +162,13 @@ where s.await; } }); + // A ping every 30 seconds keeps a quiet session open through proxies + // that close idle connections (Cloudflare: after 100 seconds). + let mut keepalive = tokio::time::interval(std::time::Duration::from_secs(30)); + keepalive.tick().await; loop { tokio::select! { + _ = keepalive.tick() => ws.send(Message::Ping(Default::default())).await?, n = stdout.read(&mut buf) => match n { Ok(0) | Err(_) => break, Ok(n) => ws.send(Message::binary(buf[..n].to_vec())).await?, @@ -162,7 +195,99 @@ where } ws.send(Message::binary(buf[..n].to_vec())).await?; } - ws.send(frame(&TerminalFrame::Exit)).await?; + ws.send(frame(&TerminalFrame::Exit { code: None })).await?; + Ok(()) +} + +/// One command, as it is (no shell), until it exits: stdin from the +/// socket until `StdinEnd`, its output back, then its exit code. +async fn command(pods: &Api, name: &str, what: &Run, ws: &mut S) -> anyhow::Result<()> +where + S: futures::Stream> + + futures::Sink + + Unpin, +{ + let params = if what.tty { + AttachParams::interactive_tty() + } else { + AttachParams::default() + .stdin(true) + .stdout(true) + .stderr(true) + }; + let mut proc = pods + .exec(name, what.command.clone(), ¶ms) + .await + .map_err(|e| anyhow::anyhow!("Couldn't run the command in {name}: {e}"))?; + let mut stdin = proc.stdin(); + let mut stdout = proc.stdout().ok_or_else(|| anyhow::anyhow!("no stdout"))?; + let mut stderr = proc.stderr(); + let mut size = proc.terminal_size(); + let status = proc.take_status(); + ws.send(frame(&TerminalFrame::Ready { + pod: name.to_owned(), + })) + .await?; + // Output frames carry their stream without a TTY. + let tag = |stream: u8, b: &[u8]| { + if what.tty { + b.to_vec() + } else { + let mut v = Vec::with_capacity(b.len() + 1); + v.push(stream); + v.extend_from_slice(b); + v + } + }; + let mut out = vec![0u8; 16 * 1024]; + let mut err = vec![0u8; 16 * 1024]; + let (mut out_open, mut err_open) = (true, stderr.is_some()); + let mut keepalive = tokio::time::interval(std::time::Duration::from_secs(30)); + keepalive.tick().await; + while out_open || err_open { + tokio::select! { + _ = keepalive.tick() => ws.send(Message::Ping(Default::default())).await?, + n = stdout.read(&mut out), if out_open => match n { + Ok(0) | Err(_) => out_open = false, + Ok(n) => ws.send(Message::binary(tag(STREAM_STDOUT, &out[..n]))).await?, + }, + n = async { stderr.as_mut().expect("open").read(&mut err).await }, if err_open => match n { + Ok(0) | Err(_) => err_open = false, + Ok(n) => ws.send(Message::binary(tag(STREAM_STDERR, &err[..n]))).await?, + }, + msg = ws.next() => match msg { + Some(Ok(Message::Binary(b))) => { + if let Some(w) = stdin.as_mut() { + w.write_all(&b).await?; + } + } + Some(Ok(Message::Text(t))) => match serde_json::from_str(t.as_str()) { + // Dropping the writer closes the command's stdin. + Ok(TerminalFrame::StdinEnd) => drop(stdin.take()), + Ok(TerminalFrame::Resize { cols, rows }) => { + if let Some(s) = size.as_mut() { + let _ = s.send(TerminalSize { width: cols, height: rows }).await; + } + } + _ => {} + }, + Some(Ok(Message::Close(_))) | None | Some(Err(_)) => return Ok(()), + _ => {} + }, + } + } + drop(stdin); + let st = match status { + Some(s) => s.await, + None => None, + }; + match exit_code(st.as_ref()) { + Ok(code) => { + ws.send(frame(&TerminalFrame::Exit { code: Some(code) })) + .await? + } + Err(why) => anyhow::bail!(why), + } Ok(()) } @@ -171,3 +296,39 @@ fn no_sh(pod: &str, e: kube::Error) -> anyhow::Error { "Couldn't start a shell in {pod}: {e}. Images without sh (distroless, scratch) have no shell to open." ) } + +#[cfg(test)] +mod tests { + use super::*; + use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Status, StatusCause, StatusDetails}; + + #[test] + fn exit_codes_from_the_status() { + let ok = Status { + status: Some("Success".into()), + ..Default::default() + }; + assert_eq!(exit_code(Some(&ok)), Ok(0)); + let failed = Status { + status: Some("Failure".into()), + reason: Some("NonZeroExitCode".into()), + details: Some(StatusDetails { + causes: Some(vec![StatusCause { + reason: Some("ExitCode".into()), + message: Some("3".into()), + ..Default::default() + }]), + ..Default::default() + }), + ..Default::default() + }; + assert_eq!(exit_code(Some(&failed)), Ok(3)); + let missing = Status { + status: Some("Failure".into()), + message: Some("exec: \"nope\": executable file not found in $PATH".into()), + ..Default::default() + }; + assert!(exit_code(Some(&missing)).unwrap_err().contains("not found")); + assert!(exit_code(None).is_err()); + } +} diff --git a/crates/pyo-agent/src/traffic/agg.rs b/crates/pyo-agent/src/traffic/agg.rs new file mode 100644 index 00000000..3cf321cc --- /dev/null +++ b/crates/pyo-agent/src/traffic/agg.rs @@ -0,0 +1,268 @@ +//! Per-minute totals of the cleaned rows: per host for websites, per +//! proxied port for connections. Fixed-size sketches (a HyperLogLog for +//! visitors, a histogram for response times) and bounded top lists, so a +//! busy minute costs about as much memory as a quiet one. + +use std::collections::{BTreeMap, HashMap}; + +use pyo_proto::traffic::{ + self as t, HostTotals, PortTotals, TopK, TotalsBatch, hll_insert, latency_bucket, +}; + +use super::clean::Cleaned; + +/// Lines this late after their minute ended still go into it; later ones +/// go into a second row for the same minute, which Pyo adds up. +pub const LATE_SECS: i64 = 30; +/// Top lists track this many times the keys they report, so the counts +/// that are reported are near exact. +const TRACK: usize = 4; +/// Hosts and ports per minute, at most (Pyo said which are services'; +/// until it has, a gateway that answers many names can't grow this). +const MAX_KEYS: usize = 2000; +/// Long paths and URLs are cut in the top lists. +const KEY_CHARS: usize = 300; + +struct HostAgg { + t: HostTotals, + paths: TopK, + pages: TopK, + referrers: TopK, + params: TopK, + blocked_paths: TopK, + waf_paths: TopK, +} + +impl HostAgg { + fn new(minute: i64, host: &str) -> Self { + HostAgg { + t: HostTotals { minute, host: host.to_owned(), ..Default::default() }, + paths: TopK::new(t::TOP_PATHS * TRACK), + pages: TopK::new(t::TOP_PAGES * TRACK), + referrers: TopK::new(t::TOP_REFERRERS * TRACK), + params: TopK::new(t::TOP_PARAMS * TRACK), + blocked_paths: TopK::new(t::TOP_BLOCKED_PATHS * TRACK), + waf_paths: TopK::new(t::TOP_BLOCKED_PATHS * TRACK), + } + } + + fn finish(mut self) -> HostTotals { + self.t.paths = self.paths.top(t::TOP_PATHS); + self.t.pages = self.pages.top(t::TOP_PAGES); + self.t.referrers = self.referrers.top(t::TOP_REFERRERS); + self.t.params = self.params.top(t::TOP_PARAMS); + self.t.blocked_paths = self.blocked_paths.top(t::TOP_BLOCKED_PATHS); + self.t.waf_paths = self.waf_paths.top(t::TOP_BLOCKED_PATHS * 2); + self.t + } +} + +fn bump(m: &mut BTreeMap, k: &str) { + *m.entry(k.to_owned()).or_insert(0) += 1; +} + +fn cut(s: &str) -> String { + s.chars().take(KEY_CHARS).collect() +} + +#[derive(Default)] +pub struct Aggregator { + hosts: HashMap<(i64, String), HostAgg>, + ports: HashMap<(i64, String), PortTotals>, + waf_messages: BTreeMap, +} + +impl Aggregator { + pub fn add(&mut self, c: &Cleaned) { + match c { + Cleaned::Request { row, visitor, pageview, params } => { + let Some(a) = self.host(row.at, &row.host) else { return }; + let h = &mut a.t; + h.requests += 1; + h.bytes += row.bytes; + h.duration_ms += row.duration_ms.max(0.0); + if row.status >= 500 { + h.errors += 1; + } + bump(&mut h.statuses, &format!("{}xx", row.status / 100)); + bump(&mut h.methods, &row.method); + let b = latency_bucket(row.duration_ms); + *h.latency.entry(b).or_insert(0) += 1; + hll_insert(&mut h.visitors, *visitor); + bump(&mut h.countries, &row.country); + if !row.server.is_empty() { + bump(&mut h.servers, &row.server); + *h.server_latency.entry(format!("{}|{b}", row.server)).or_insert(0) += 1; + if row.status >= 500 { + bump(&mut h.server_errors, &row.server); + } + } + if !row.blocked_by.is_empty() { + bump(&mut h.blocked, &row.blocked_by); + bump(&mut h.blocked_countries, &row.country); + a.blocked_paths.add(&cut(&row.path), 1); + } + a.paths.add(&cut(&row.path), 1); + for p in params.iter().take(20) { + a.params.add(&cut(p), 1); + } + if *pageview { + h.pageviews += 1; + a.pages.add(&cut(&row.url), 1); + if !row.referrer.is_empty() { + a.referrers.add(&row.referrer, 1); + } + bump(&mut h.devices, &row.device); + bump(&mut h.browsers, &row.browser); + } + } + Cleaned::Waf { row, visitor } => { + for (rule, msg) in row.rules.iter().zip(row.messages.iter()) { + if self.waf_messages.len() < 500 && !self.waf_messages.contains_key(&rule.to_string()) { + self.waf_messages.insert(rule.to_string(), msg.clone()); + } + } + let Some(a) = self.host(row.at, &row.host) else { return }; + let h = &mut a.t; + let (map, mark) = if row.blocked { (&mut h.waf_blocked, "b") } else { (&mut h.waf_logged, "l") }; + for rule in &row.rules { + bump(map, &rule.to_string()); + } + bump(&mut h.waf_countries, &format!("{mark}:{}", row.country)); + hll_insert(&mut h.waf_visitors, *visitor); + a.waf_paths.add(&format!("{mark}:{}", cut(&row.path)), 1); + } + Cleaned::Connection { row, visitor } => { + let minute = row.at.div_euclid(60_000) * 60; + if !self.ports.contains_key(&(minute, row.key.clone())) && self.ports.len() >= MAX_KEYS { + return; + } + let p = self.ports.entry((minute, row.key.clone())).or_insert_with(|| PortTotals { + minute, + key: row.key.clone(), + protocol: row.protocol.clone(), + ..Default::default() + }); + p.connections += 1; + p.bytes_in += row.bytes_in; + p.bytes_out += row.bytes_out; + *p.duration.entry(latency_bucket(row.duration_ms)).or_insert(0) += 1; + bump(&mut p.outcomes, &row.outcome); + bump(&mut p.countries, &row.country); + hll_insert(&mut p.visitors, *visitor); + if row.outcome == "blocked" { + bump(&mut p.blocked, if row.rule.is_empty() { "blocked" } else { &row.rule }); + bump(&mut p.blocked_countries, &row.country); + } + } + } + } + + fn host(&mut self, at: i64, host: &str) -> Option<&mut HostAgg> { + let minute = at.div_euclid(60_000) * 60; + let key = (minute, host.to_owned()); + if !self.hosts.contains_key(&key) && self.hosts.len() >= MAX_KEYS { + return None; + } + Some(self.hosts.entry(key).or_insert_with(|| HostAgg::new(minute, host))) + } + + /// The minutes that ended at least `LATE_SECS` before `now` (seconds), + /// taken out. None when there's nothing. + pub fn take_finished(&mut self, now: i64) -> Option { + let done = |m: i64| m + 60 + LATE_SECS <= now; + let hosts: Vec<(i64, String)> = self.hosts.keys().filter(|k| done(k.0)).cloned().collect(); + let ports: Vec<(i64, String)> = self.ports.keys().filter(|k| done(k.0)).cloned().collect(); + if hosts.is_empty() && ports.is_empty() { + return None; + } + let mut b = TotalsBatch { + hosts: hosts.iter().filter_map(|k| self.hosts.remove(k)).map(HostAgg::finish).collect(), + ports: ports.iter().filter_map(|k| self.ports.remove(k)).collect(), + waf_messages: std::mem::take(&mut self.waf_messages), + ..Default::default() + }; + b.hosts.sort_by(|a, b| (a.minute, &a.host).cmp(&(b.minute, &b.host))); + b.ports.sort_by(|a, b| (a.minute, &a.key).cmp(&(b.minute, &b.key))); + Some(b) + } + + pub fn len(&self) -> usize { + self.hosts.len() + self.ports.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pyo_proto::traffic::{ConnectionRow, RequestRow, WafRow, hll_estimate}; + + fn req(at: i64, path: &str, status: u16, visitor: u64, pageview: bool) -> Cleaned { + Cleaned::Request { + row: RequestRow { + at, + host: "a.example".into(), + method: "GET".into(), + path: path.into(), + url: path.into(), + status, + duration_ms: 20.0, + bytes: 100, + country: "ID".into(), + referrer: "Direct".into(), + device: "Desktop".into(), + browser: "Chrome".into(), + server: "sg-1".into(), + ..Default::default() + }, + visitor, + pageview, + params: vec![], + } + } + + #[test] + fn a_minute_adds_up() { + let mut a = Aggregator::default(); + // 12:00:10 and 12:00:50 in one minute, 12:01:05 in the next. + let m = 1_794_000_000_000 / 60_000 * 60_000; + // Visitor hashes spread over the registers, as real ones are. + let (v1, v2, v3) = (0x1111_0000_0000_0001, 0x9999_0000_0000_0002, 0x5555_0000_0000_0003); + a.add(&req(m + 10_000, "/", 200, v1, true)); + a.add(&req(m + 50_000, "/x", 503, v2, false)); + a.add(&req(m + 50_000, "/", 200, v1, true)); + a.add(&req(m + 65_000, "/", 200, v3, true)); + a.add(&Cleaned::Waf { + row: WafRow { at: m + 1000, host: "a.example".into(), path: "/login".into(), country: "DE".into(), blocked: true, rules: vec![942100], messages: vec!["SQLi".into()], ..Default::default() }, + visitor: 9, + }); + a.add(&Cleaned::Connection { + row: ConnectionRow { at: m + 2000, key: "db-tcp-5432".into(), protocol: "TCP".into(), outcome: "blocked".into(), rule: "office".into(), bytes_in: 5, ..Default::default() }, + visitor: 4, + }); + // The first minute isn't done until 30s after it ends. + let s = m / 1000; + assert!(a.take_finished(s + 60 + 29).is_none()); + let b = a.take_finished(s + 60 + 30).unwrap(); + assert_eq!(b.hosts.len(), 1); + let h = &b.hosts[0]; + assert_eq!((h.minute, h.requests, h.pageviews, h.errors, h.bytes), (s, 3, 2, 1, 300)); + assert_eq!(h.statuses["2xx"], 2); + assert_eq!(h.statuses["5xx"], 1); + assert_eq!(hll_estimate(&h.visitors).round(), 2.0); + assert_eq!(h.paths["/"], 2); + assert_eq!(h.pages["/"], 2); + assert_eq!(h.servers["sg-1"], 3); + assert_eq!(h.server_errors["sg-1"], 1); + assert_eq!(h.waf_blocked["942100"], 1); + assert_eq!(h.waf_countries["b:DE"], 1); + assert_eq!(h.waf_paths["b:/login"], 1); + assert_eq!(b.waf_messages["942100"], "SQLi"); + assert_eq!(b.ports[0].blocked["office"], 1); + assert_eq!(b.ports[0].bytes_in, 5); + // The next minute is still open, then done. + assert_eq!(a.len(), 1); + assert_eq!(a.take_finished(s + 200).unwrap().hosts[0].requests, 1); + assert!(a.take_finished(s + 300).is_none()); + } +} diff --git a/crates/pyo-agent/src/traffic/clean.rs b/crates/pyo-agent/src/traffic/clean.rs new file mode 100644 index 00000000..3bd1e458 --- /dev/null +++ b/crates/pyo-agent/src/traffic/clean.rs @@ -0,0 +1,311 @@ +//! One gateway line in, one kept row out: the query's sensitive values +//! redacted, the visitor's country looked up and their address hashed with +//! the day's salt, then kept only as the IP setting says. Nothing here +//! leaves the cluster but what the totals add up. + +use std::net::IpAddr; + +use pyo_proto::traffic::{ + AccessLine, ConnectionRow, RequestRow, TrafficContext, WafRow, mask_ip, port_key_string, + refusal, split_url, +}; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +/// What a line became, with what the totals need and the row doesn't keep. +#[derive(Debug, PartialEq)] +pub enum Cleaned { + Request { + row: RequestRow, + visitor: u64, + pageview: bool, + /// The query's parameter names. + params: Vec, + }, + Connection { + row: ConnectionRow, + visitor: u64, + }, + Waf { + row: WafRow, + visitor: u64, + }, +} + +/// Looks up an address's country code ("" when unknown). +pub trait Locate { + fn country(&self, ip: &str) -> String; +} + +impl String> Locate for F { + fn country(&self, ip: &str) -> String { + self(ip) + } +} + +pub struct Cleaner<'a> { + pub ctx: &'a TrafficContext, + /// Whether Pyo has said which hosts and ports are services' yet (until + /// then everything is kept). + pub known: bool, + pub salt: &'a str, + pub locate: &'a dyn Locate, + pub ua: &'a woothee::parser::Parser, +} + +fn hash(parts: &[&str]) -> u64 { + let d = Sha256::digest(parts.join("|").as_bytes()); + u64::from_be_bytes(d[..8].try_into().unwrap_or([0; 8])) +} + +fn capped(s: &str, n: usize) -> String { + s.chars().take(n).collect() +} + +/// The UTC day of a time, for the salt. +pub fn day_of(ms: i64) -> String { + jiff::Timestamp::from_millisecond(ms) + .map(|t| t.strftime("%Y-%m-%d").to_string()) + .unwrap_or_default() +} + +impl Cleaner<'_> { + /// The rule behind a refusal: behind a CDN, a connection that didn't + /// come from it (`peer`) is the CDN check's ("cdn"); else the rule that + /// matches the address (or its country), else what the proxy said. + fn rule(&self, service_id: &str, why: String, ip: &str, peer: &str, country: &str) -> String { + if why != "blocked" && why != "rate-limit" { + return why; + } + let (Some(f), Ok(addr)) = (self.ctx.firewalls.get(service_id), ip.parse::()) else { + return why; + }; + if why == "blocked" + && let Ok(peer) = peer.parse::() + && !pyo_proto::firewall::via_cdn(f, peer) + { + return pyo_proto::firewall::BEHIND_RULE.to_owned(); + } + let rule = if why == "blocked" { + pyo_proto::firewall::blocking_rule(&[f], addr, Some(country).filter(|c| !c.is_empty())) + } else { + pyo_proto::firewall::rate_limiting_rule(&[f], addr) + }; + rule.map(str::to_owned).unwrap_or(why) + } + + pub fn clean(&self, l: &Value, now_ms: i64) -> Option { + // The WAF's finding for one request (pyo-waf's line). + if l.get("waf").is_some() { + let host = l["host"].as_str().unwrap_or("").to_lowercase(); + if self.known && !self.ctx.hosts.contains_key(&host) { + return None; + } + let at = l["time"] + .as_str() + .and_then(pyo_proto::traffic::parse_time_ms) + .unwrap_or(now_ms); + let ip = l["client"].as_str().unwrap_or(""); + let country = self.locate.country(ip); + let (path, url, _, _) = split_url(l["uri"].as_str().unwrap_or("/")); + let row = WafRow { + at, + host: host.clone(), + method: capped(l["method"].as_str().unwrap_or(""), 16), + path, + url, + ip: mask_ip(&self.ctx.ip_mode, ip), + country, + blocked: l["blocked"].as_bool().unwrap_or(false), + rules: l["rules"].as_array().into_iter().flatten().filter_map(Value::as_u64).take(50).collect(), + messages: l["messages"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .take(50) + .map(|m| capped(m, 300)) + .collect(), + severity: capped(l["severity"].as_str().unwrap_or(""), 16), + server: capped(l["PyoNode"].as_str().unwrap_or(""), 253), + }; + let visitor = hash(&[self.salt, ip, "waf", &host]); + return Some(Cleaned::Waf { row, visitor }); + } + let l = AccessLine::read(l); + let at = l.ts_ms.unwrap_or(now_ms); + let ip = l.visitor_ip().to_owned(); + // A connection to a public TCP or UDP port. + if let Some((proto, key)) = l.port_key() { + let key = port_key_string(proto, &key); + let owner = self.ctx.ports.get(&key); + if self.known && owner.is_none() { + return None; + } + let (service_id, port) = owner.cloned().unwrap_or_default(); + let country = self.locate.country(&ip); + let why = refusal("", &l.termination, 0); + let row = ConnectionRow { + at, + key: key.clone(), + service_id: service_id.clone(), + port, + protocol: proto.to_owned(), + ip: mask_ip(&self.ctx.ip_mode, &ip), + duration_ms: l.duration_ms, + bytes_in: l.bytes_in, + bytes_out: l.bytes, + outcome: l.outcome().to_owned(), + rule: self.rule(&service_id, why, &ip, "", &country), + country, + server: capped(&l.node, 253), + }; + let visitor = hash(&[self.salt, &ip, &key]); + return Some(Cleaned::Connection { row, visitor }); + } + let host = l.host.split(':').next().unwrap_or("").to_lowercase(); + let service_id = match self.ctx.hosts.get(&host) { + Some(s) => s.clone(), + None if self.known => return None, + None => String::new(), + }; + if host.is_empty() { + return None; + } + let ua = l.user_agent.as_str(); + let status = l.status; + let method = if l.method.is_empty() { "GET".to_owned() } else { capped(&l.method, 16) }; + let (path, url, keys, _) = split_url(if l.path.is_empty() { "/" } else { l.path.as_str() }); + let parsed = self.ua.parse(ua); + let crawler = parsed.as_ref().is_some_and(|r| r.category == "crawler"); + let device = match parsed.as_ref().map(|r| r.category) { + Some("pc") => "Desktop", + Some("smartphone") | Some("mobilephone") => "Mobile", + Some("crawler") => "Bot", + Some("appliance") => "Other", + _ if ua.is_empty() => "Unknown", + _ => "Other", + }; + let browser = parsed + .as_ref() + .map(|r| r.name) + .filter(|n| !n.is_empty() && *n != "UNKNOWN") + .unwrap_or(if ua.starts_with("curl/") { "curl" } else { "Other" }); + // A page view: a GET answered with HTML (a 304 has no body, so a path without an extension). + let ctype = l.content_type.as_str(); + let html = ctype.starts_with("text/html") + || (status == 304 && ctype.is_empty() && !path.rsplit('/').next().unwrap_or("").contains('.')); + let pageview = method == "GET" && (200..400).contains(&status) && html && !crawler; + let referrer = Some(l.referer.as_str()) + .filter(|r| !r.is_empty()) + .and_then(|r| r.split("://").nth(1)) + .map(|r| r.split(['/', '?', ':']).next().unwrap_or("").to_lowercase()); + let referrer = match referrer.as_deref() { + None | Some("") => "Direct".to_owned(), + Some(r) if r == host => String::new(), + Some(r) => capped(r.trim_start_matches("www."), 253), + }; + let country = self.locate.country(&ip); + let why = refusal(&l.details, "", status); + let row = RequestRow { + at, + host: host.clone(), + method, + path, + url, + status: status.min(999) as u16, + duration_ms: l.duration_ms, + bytes: l.bytes, + referrer, + device: device.to_owned(), + browser: capped(browser, 64), + ip: mask_ip(&self.ctx.ip_mode, &ip), + // As sent; capped like a header line. + user_agent: capped(ua, 512), + server: capped(&l.node, 253), + blocked_by: self.rule(&service_id, why, &ip, &l.peer, &country), + waf: false, + country, + }; + let visitor = hash(&[self.salt, &ip, ua, &host]); + Some(Cleaned::Request { row, visitor, pageview, params: keys }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn ctx() -> TrafficContext { + serde_json::from_value(json!({ + "hosts": { "shop.example.com": "svc_1" }, + "ports": { "shop-cache-tcp-6379": ["svc_2", 6379] }, + "firewalls": { "svc_1": { "rules": [{ "id": "no-de", "action": "block", "sources": ["DE"] }] } }, + "ipMode": "anonymized", + })) + .unwrap() + } + + fn cleaner<'a>(ctx: &'a TrafficContext, ua: &'a woothee::parser::Parser, locate: &'a dyn Locate) -> Cleaner<'a> { + Cleaner { ctx, known: true, salt: "s", locate, ua } + } + + #[test] + fn a_request_is_cleaned_before_it_is_kept() { + let ctx = ctx(); + let ua = woothee::parser::Parser::new(); + let locate = |ip: &str| if ip == "203.0.113.9" { "ID".to_owned() } else { String::new() }; + let c = cleaner(&ctx, &ua, &locate); + let line = json!({ "start_time": "2026-11-06T12:28:32.253Z", "host": "Shop.example.com:443", "method": "GET", "path": "/reset?token=abc&page=2", + "status": 200, "content_type": "text/html", "peer": "10.0.2.2", "remote": "203.0.113.9", "duration_ms": 12, "bytes": 900, + "referer": "https://www.news.example/a", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36", "PyoNode": "sg-1" }); + let Some(Cleaned::Request { row, visitor, pageview, params }) = c.clean(&line, 0) else { + panic!("a request") + }; + assert_eq!(row.host, "shop.example.com"); + assert_eq!(row.url, "/reset?token=[redacted]&page=2"); + assert_eq!(row.ip, "203.0.113.0", "as the IP setting keeps it"); + assert_eq!(row.country, "ID", "looked up from the whole address"); + assert_eq!(row.referrer, "news.example"); + assert_eq!((row.device.as_str(), row.browser.as_str()), ("Desktop", "Chrome")); + assert!(pageview); + assert_eq!(params, ["token", "page"]); + assert_eq!(visitor, hash(&["s", "203.0.113.9", row.user_agent.as_str(), "shop.example.com"])); + // Another host on the gateway (a scanner, another cluster's name): not kept. + let mut other = line.clone(); + other["host"] = json!("203.0.113.1"); + assert_eq!(c.clean(&other, 0), None); + } + + #[test] + fn refusals_name_their_rule() { + let ctx = ctx(); + let ua = woothee::parser::Parser::new(); + let locate = |_: &str| "DE".to_owned(); + let c = cleaner(&ctx, &ua, &locate); + let line = json!({ "host": "shop.example.com", "method": "GET", "path": "/", "status": 403, "remote": "198.51.100.4", + "details": "rbac_access_denied_matched_policy[DENY]" }); + let Some(Cleaned::Request { row, pageview, .. }) = c.clean(&line, 5) else { panic!() }; + assert_eq!((row.blocked_by.as_str(), row.at, pageview), ("no-de", 5, false)); + } + + #[test] + fn connections_and_waf_findings() { + let ctx = ctx(); + let ua = woothee::parser::Parser::new(); + let locate = |_: &str| String::new(); + let c = cleaner(&ctx, &ua, &locate); + let tcp = json!({ "peer": "10.0.2.2", "remote": "203.0.113.9", "local_port": "16379", "bytes": "120", "bytes_in": 64, + "duration_ms": 5012, "upstream": "tcproute/pyo-gateway/shop-cache-tcp-6379/rule/0", "flags": "-" }); + let Some(Cleaned::Connection { row, .. }) = c.clean(&tcp, 0) else { panic!() }; + assert_eq!((row.service_id.as_str(), row.port, row.outcome.as_str(), row.ip.as_str()), ("svc_2", 6379, "ok", "203.0.113.0")); + let waf = json!({ "waf": true, "host": "shop.example.com", "time": "2026-11-06T12:28:32Z", "client": "203.0.113.9", "uri": "/login?password=x", + "method": "POST", "blocked": true, "rules": [942100], "messages": ["SQL Injection"], "severity": "critical" }); + let Some(Cleaned::Waf { row, .. }) = c.clean(&waf, 0) else { panic!() }; + assert_eq!((row.url.as_str(), row.blocked, row.rules.as_slice()), ("/login?password=[redacted]", true, &[942100][..])); + // Before Pyo said which hosts are services': kept. + let unknown = Cleaner { known: false, ..c }; + assert!(unknown.clean(&json!({ "host": "new.example.com", "status": 200 }), 0).is_some()); + } +} diff --git a/crates/pyo-agent/src/traffic/files.rs b/crates/pyo-agent/src/traffic/files.rs new file mode 100644 index 00000000..bd7fb0dc --- /dev/null +++ b/crates/pyo-agent/src/traffic/files.rs @@ -0,0 +1,288 @@ +//! The kept rows: one file per kind and hour (UTC), `/.ndjson.gz`, +//! one JSON row per line. Each batch is added as its own gzip member, so a +//! file is readable while it's written and a cut-off last batch loses only +//! itself. The oldest hours go first once the team's size or age limit is +//! reached. + +use std::{ + collections::BinaryHeap, + fs, + io::{BufRead, BufReader, Write}, + path::{Path, PathBuf}, +}; + +use flate2::{Compression, read::MultiGzDecoder, write::GzEncoder}; +use pyo_proto::traffic::{ConnectionRow, RequestRow, TrafficAnswer, TrafficQuery, WafRow}; +use serde_json::Value; + +pub const KINDS: [&str; 3] = ["requests", "connections", "waf"]; +/// The most a query reads (uncompressed), so a query over a very busy week +/// can't hold the store up: it answers with what it found (`partial`). +const READ_BUDGET: u64 = 2 << 30; + +/// An hour's number: hours since 1970. +pub fn hour_of(ms: i64) -> i64 { + ms.div_euclid(3_600_000) +} + +fn file_name(hour: i64) -> String { + jiff::Timestamp::from_second(hour * 3600) + .map(|t| t.strftime("%Y%m%d%H").to_string()) + .unwrap_or_else(|_| hour.to_string()) +} + +fn hour_of_name(name: &str) -> Option { + let stem = name.strip_suffix(".ndjson.gz")?; + let t = jiff::civil::DateTime::strptime("%Y%m%d%H", stem).ok()?; + let ts = t.to_zoned(jiff::tz::TimeZone::UTC).ok()?.timestamp(); + Some(ts.as_second() / 3600) +} + +pub struct Files { + dir: PathBuf, +} + +impl Files { + pub fn new(dir: &Path) -> anyhow::Result { + for k in KINDS { + fs::create_dir_all(dir.join(k))?; + } + Ok(Files { dir: dir.to_owned() }) + } + + /// Adds rows (JSON lines) to their hour's file, as one gzip member. + pub fn append(&self, kind: &str, hour: i64, lines: &str) -> anyhow::Result<()> { + if lines.is_empty() { + return Ok(()); + } + let mut gz = GzEncoder::new(Vec::with_capacity(lines.len() / 4), Compression::new(6)); + gz.write_all(lines.as_bytes())?; + let bytes = gz.finish()?; + let mut f = fs::OpenOptions::new() + .create(true) + .append(true) + .open(self.dir.join(kind).join(format!("{}.ndjson.gz", file_name(hour))))?; + f.write_all(&bytes)?; + Ok(()) + } + + /// Every kept file: (hour, size, path), oldest first. + pub fn list(&self) -> Vec<(i64, u64, PathBuf)> { + let mut out = vec![]; + for k in KINDS { + let Ok(rd) = fs::read_dir(self.dir.join(k)) else { continue }; + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().to_string(); + let (Some(h), Ok(m)) = (hour_of_name(&name), e.metadata()) else { continue }; + out.push((h, m.len(), e.path())); + } + } + out.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2))); + out + } + + /// Bytes on disk. + pub fn size(&self) -> u64 { + self.list().iter().map(|f| f.1).sum() + } + + /// The oldest kept time (ms), if anything is kept. + pub fn kept_since(&self) -> Option { + self.list().first().map(|f| f.0 * 3_600_000) + } + + /// Deletes hours older than `max_days`, then the oldest until the rest + /// fits in `max_bytes`. Returns how many files went. + pub fn enforce(&self, now_ms: i64, max_bytes: u64, max_days: u32) -> usize { + let oldest = hour_of(now_ms - max_days as i64 * 86_400_000); + let mut files = self.list(); + let mut gone = 0; + files.retain(|(h, _, p)| { + if *h < oldest { + gone += fs::remove_file(p).is_ok() as usize; + false + } else { + true + } + }); + let mut total: u64 = files.iter().map(|f| f.1).sum(); + for (_, size, p) in files { + if total <= max_bytes { + break; + } + if fs::remove_file(&p).is_ok() { + gone += 1; + total -= size; + } + } + gone + } + + /// The newest rows that match, newest first. + pub fn query(&self, q: &TrafficQuery) -> TrafficAnswer { + let limit = q.limit(); + let kind = if KINDS.contains(&q.rows.as_str()) { q.rows.as_str() } else { "requests" }; + let before = if q.before_ms > 0 { q.before_ms } else { i64::MAX }; + let (from, to) = (hour_of(q.since_ms.max(0)), hour_of(before.min(i64::MAX - 1))); + let mut files: Vec<(i64, u64, PathBuf)> = self + .list() + .into_iter() + .filter(|(h, _, p)| *h >= from && *h <= to && p.parent().is_some_and(|d| d.ends_with(kind))) + .collect(); + files.sort_by_key(|f| std::cmp::Reverse(f.0)); + // The newest `limit + 1` (one more says there are older ones): + // a min-heap on time, so the oldest kept is dropped first. + let mut heap: BinaryHeap> = BinaryHeap::new(); + let mut vals: std::collections::HashMap = Default::default(); + let mut seq = 0usize; + let mut read = 0u64; + let mut partial = false; + 'files: for (_, _, path) in files { + let Ok(f) = fs::File::open(&path) else { continue }; + let mut r = BufReader::new(MultiGzDecoder::new(BufReader::new(f))); + let mut line = String::new(); + loop { + line.clear(); + // A cut-off last batch ends the file early. + match r.read_line(&mut line) { + Ok(0) | Err(_) => break, + Ok(n) => read += n as u64, + } + let Some((at, v)) = matching(kind, q, line.trim_end()) else { continue }; + if at < q.since_ms || at >= before { + continue; + } + if heap.len() > limit && heap.peek().is_some_and(|m| m.0.0 >= at) { + continue; + } + seq += 1; + heap.push(std::cmp::Reverse((at, seq))); + vals.insert(seq, v); + if heap.len() > limit + 1 + && let Some(std::cmp::Reverse((_, gone))) = heap.pop() + { + vals.remove(&gone); + } + if read > READ_BUDGET { + partial = true; + break 'files; + } + } + // Files are hours, newest first: once there are enough, an + // older hour has nothing newer. + if heap.len() > limit { + break; + } + } + let mut rows: Vec<(i64, usize)> = heap.into_iter().map(|r| r.0).collect(); + rows.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1))); + let more = rows.len() > limit; + rows.truncate(limit); + TrafficAnswer { + rows: rows.into_iter().filter_map(|r| vals.remove(&r.1)).collect(), + more, + kept_since: self.kept_since(), + partial, + } + } +} + +/// A line's time and row, when it's the query's. +fn matching(kind: &str, q: &TrafficQuery, line: &str) -> Option<(i64, Value)> { + if line.is_empty() { + return None; + } + match kind { + "connections" => { + let r: ConnectionRow = serde_json::from_str(line).ok()?; + q.matches_connection(&r).then(|| (r.at, serde_json::to_value(&r).unwrap_or_default())) + } + "waf" => { + let r: WafRow = serde_json::from_str(line).ok()?; + q.matches_waf(&r).then(|| (r.at, serde_json::to_value(&r).unwrap_or_default())) + } + _ => { + let r: RequestRow = serde_json::from_str(line).ok()?; + q.matches_request(&r).then(|| (r.at, serde_json::to_value(&r).unwrap_or_default())) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("pyo-traffic-test-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + d + } + + fn rows(from_ms: i64, n: i64, step_ms: i64, status: u16) -> String { + (0..n) + .map(|i| { + let r = RequestRow { at: from_ms + i * step_ms, host: "a.example".into(), path: format!("/{i}"), url: format!("/{i}"), status, ..Default::default() }; + format!("{}\n", serde_json::to_string(&r).unwrap()) + }) + .collect() + } + + #[test] + fn newest_first_across_hours_and_pages() { + let d = dir("query"); + let f = Files::new(&d).unwrap(); + let h0 = 1_794_000_000_000 / 3_600_000 * 3_600_000; + // Two batches in the first hour (one 5xx), one in the next. + f.append("requests", hour_of(h0), &rows(h0, 10, 1000, 200)).unwrap(); + f.append("requests", hour_of(h0), &rows(h0 + 20_000, 1, 1000, 503)).unwrap(); + f.append("requests", hour_of(h0 + 3_600_000), &rows(h0 + 3_600_000, 5, 1000, 200)).unwrap(); + let q = |limit: u32, before: i64, status: Option<&str>| TrafficQuery { + rows: "requests".into(), + limit, + before_ms: before, + status: status.map(str::to_owned), + hosts: vec!["a.example".into()], + ..Default::default() + }; + let a = f.query(&q(3, 0, None)); + let ats: Vec = a.rows.iter().map(|r| r["at"].as_i64().unwrap()).collect(); + assert_eq!(ats, [h0 + 3_604_000, h0 + 3_603_000, h0 + 3_602_000]); + assert!(a.more); + // The next page from the last one's time, across the hour. + let b = f.query(&q(4, *ats.last().unwrap(), None)); + let ats: Vec = b.rows.iter().map(|r| r["at"].as_i64().unwrap()).collect(); + assert_eq!(ats, [h0 + 3_601_000, h0 + 3_600_000, h0 + 20_000, h0 + 9_000]); + let e = f.query(&q(50, 0, Some("5xx"))); + assert_eq!((e.rows.len(), e.more), (1, false)); + assert_eq!(e.kept_since, Some(h0)); + // A cut-off batch (a crash mid-write) costs only itself. + let p = d.join("requests").join(format!("{}.ndjson.gz", file_name(hour_of(h0)))); + let mut bytes = fs::read(&p).unwrap(); + bytes.extend_from_slice(&[0x1f, 0x8b, 8, 0, 0]); + fs::write(&p, bytes).unwrap(); + assert_eq!(f.query(&q(50, 0, Some("5xx"))).rows.len(), 1); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn oldest_hours_go_first() { + let d = dir("enforce"); + let f = Files::new(&d).unwrap(); + let now = 1_794_000_000_000i64; + for h in 0..10 { + f.append("requests", hour_of(now) - h * 24, &rows(now - h * 86_400_000, 200, 10, 200)).unwrap(); + } + assert_eq!(f.list().len(), 10); + // Older than 7 days: three files. + assert_eq!(f.enforce(now, u64::MAX, 7), 2); + let size = f.size(); + let each = size / 8; + // Room for about five: the oldest go. + f.enforce(now, each * 5 + each / 2, 7); + let left = f.list(); + assert_eq!(left.len(), 5); + assert_eq!(left.last().unwrap().0, hour_of(now), "the newest stays"); + assert_eq!(hour_of_name(&format!("{}.ndjson.gz", file_name(477_000))), Some(477_000)); + let _ = fs::remove_dir_all(&d); + } +} diff --git a/crates/pyo-agent/src/traffic/link.rs b/crates/pyo-agent/src/traffic/link.rs new file mode 100644 index 00000000..c845bbeb --- /dev/null +++ b/crates/pyo-agent/src/traffic/link.rs @@ -0,0 +1,102 @@ +//! The agent's side of the traffic store: it brings the store Pyo's context, +//! sends the store's finished totals on to Pyo as its own signed requests, +//! and answers Pyo's queries for kept rows (QueryTraffic) from the store. + +use std::{sync::OnceLock, time::Duration}; + +use pyo_proto::traffic::{TotalsBatch, TrafficAnswer, TrafficQuery}; +use serde_json::{Value, json}; + +use crate::Agent; + +/// The store's token, from this agent's own (`token_for`). +pub fn token() -> &'static str { + static T: OnceLock = OnceLock::new(); + T.get_or_init(|| super::token_for(&std::env::var("PYO_AGENT_TOKEN").unwrap_or_default())) +} + +fn http() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(reqwest::Client::new) +} + +async fn call(method: reqwest::Method, path: &str, body: Option>, timeout: Duration) -> anyhow::Result { + let mut req = http() + .request(method, format!("{}{path}", super::url())) + .bearer_auth(token()) + .timeout(timeout); + if let Some(b) = body { + req = req.header("content-type", "application/json").body(b); + } + let res = req.send().await?; + let status = res.status(); + let text = res.text().await.unwrap_or_default(); + anyhow::ensure!(status.is_success(), "the traffic store answered {status}"); + Ok(serde_json::from_str(&text).unwrap_or(Value::Null)) +} + +/// Pyo's query for kept rows, answered by the store. +pub async fn query(q: &TrafficQuery) -> anyhow::Result { + let v = call(reqwest::Method::POST, "/query", Some(serde_json::to_vec(q)?), Duration::from_secs(20)) + .await + .map_err(|e| anyhow::anyhow!("couldn't read the kept requests: {e:#}"))?; + Ok(serde_json::from_value(v)?) +} + +/// Every 15 seconds: the store's finished minutes to Pyo; every minute (and +/// at the start), Pyo's context to the store. Quiet while there's no store +/// (observability off, or it's starting). +pub async fn run(agent: Agent) { + let mut tick = tokio::time::interval(Duration::from_secs(15)); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut n: u64 = 0; + let mut warned = false; + loop { + tick.tick().await; + // No store (observability is off, or it's starting): nothing to do. + if call(reqwest::Method::GET, "/status", None, Duration::from_secs(5)).await.is_err() { + continue; + } + if n.is_multiple_of(4) + && let Err(e) = push_context(&agent).await + { + tracing::debug!(error = %format!("{e:#}"), "traffic store's context not updated"); + } + n += 1; + match send_totals(&agent).await { + Ok(_) => warned = false, + Err(e) if !warned => { + tracing::warn!(error = %format!("{e:#}"), "couldn't send traffic totals; retrying"); + warned = true; + } + Err(_) => {} + } + } +} + +async fn push_context(agent: &Agent) -> anyhow::Result<()> { + let ctx = agent.api.traffic_context().await?; + call(reqwest::Method::PUT, "/context", Some(serde_json::to_vec(&ctx)?), Duration::from_secs(10)).await?; + Ok(()) +} + +/// Sends what the store has finished, oldest first, acknowledging each +/// batch Pyo took. Returns how many went. +async fn send_totals(agent: &Agent) -> anyhow::Result { + let v = call(reqwest::Method::GET, "/totals", None, Duration::from_secs(10)).await?; + let mut sent = 0; + for b in v["batches"].as_array().into_iter().flatten() { + let seq = b["seq"].as_u64().unwrap_or(0); + let batch: TotalsBatch = serde_json::from_value(b["batch"].clone())?; + agent.api.traffic_totals(&batch).await?; + call( + reqwest::Method::POST, + "/totals/ack", + Some(json!({ "upto": seq }).to_string().into_bytes()), + Duration::from_secs(10), + ) + .await?; + sent += 1; + } + Ok(sent) +} diff --git a/crates/pyo-agent/src/traffic/mod.rs b/crates/pyo-agent/src/traffic/mod.rs new file mode 100644 index 00000000..ae1dd314 --- /dev/null +++ b/crates/pyo-agent/src/traffic/mod.rs @@ -0,0 +1,430 @@ +//! The traffic store (`pyo-agent traffic`, the pyo-traffic pod): where a +//! cluster's website and port traffic stays. +//! +//! Vector posts the gateway's access log lines here, inside the cluster. +//! Each line is cleaned (clean.rs: redaction, country, salted visitor +//! hash, the IP setting), kept in hourly files on this pod's small volume +//! (files.rs, capped by the team's size and age limits), and added to +//! per-minute totals (agg.rs). The agent takes the finished totals and sends +//! them to Pyo as its own signed requests; it brings Pyo's context (which +//! hosts and ports are services', firewalls, limits) and Pyo's queries for +//! kept rows (the request explorer). Raw lines and addresses never leave +//! the cluster. +//! +//! Why here and not in Vector: Vector's transforms add up counters and +//! histograms, but have no mergeable distinct count (a `set` keeps every +//! value), no top lists (a tag per path is a series per path), can't take a +//! salt that changes daily without reloading, and can't answer queries for +//! the files it writes. Vector stays a reader of the log files. + +pub mod agg; +pub mod clean; +pub mod files; +pub mod link; + +use std::{ + collections::VecDeque, + path::PathBuf, + sync::{Arc, Mutex, RwLock}, + time::Duration, +}; + +use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, StatusCode}, + routing::{get, post, put}, +}; +use pyo_proto::traffic::{TotalsBatch, TrafficContext, TrafficQuery}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +use clean::{Cleaned, Cleaner}; + +/// The store's name (Deployment, Service, volume claim) and port. +pub const NAME: &str = "pyo-traffic"; +pub const PORT: u16 = 8090; +/// Where the store is, from inside the cluster. +pub fn url() -> String { + format!("http://{NAME}.{}.svc:{PORT}", pyo_proto::rbac::NS) +} + +/// Finished minutes kept for the agent while Pyo can't be reached: six +/// hours' worth, then the oldest go. +const PENDING_MAX: usize = 360; +/// The largest batch Vector sends. +const MAX_BODY: usize = 16 << 20; + +/// The store's token: Vector and the agent send it. Made from the agent's +/// own token, so the agent knows it after a restart without reading a +/// Secret, and a new agent token (the cluster connected again) changes it. +pub fn token_for(agent_token: &str) -> String { + let d = Sha256::digest(format!("pyo-traffic\n{agent_token}").as_bytes()); + d.iter().map(|b| format!("{b:02x}")).collect() +} + +/// The cluster's one GeoLite2 Country database: the image the gateway's +/// proxies and the WAF place visitors with (`PYO_GEOIP_IMAGE`, pinned by the +/// agent's install), mounted read-only into the store as an image volume +/// (observability.rs). Nothing is downloaded for it in the cluster. +const GEOIP: &str = pyo_proto::system::GEOIP_PATH; + +pub struct Store { + files: files::Files, + dir: PathBuf, + token: String, + /// This process's id, so a batch sent twice is stored once. + instance: String, + geo: Option>, + ctx: RwLock>, + agg: Mutex, + pending: Mutex<(u64, VecDeque<(u64, TotalsBatch)>)>, + salt: Mutex<(String, String)>, + /// One writer at a time on the files. + writing: Mutex<()>, +} + +impl Store { + pub fn open(dir: PathBuf, token: String, geoip: Option) -> anyhow::Result { + let geo = geoip.and_then(|p| { + // SAFETY: the file is a read-only image volume's, never written. + match unsafe { maxminddb::Reader::open_mmap(&p) } { + Ok(r) => Some(r), + Err(e) => { + tracing::warn!(error = %e, path = %p.display(), "no country database; countries are unknown"); + None + } + } + }); + Ok(Store { + files: files::Files::new(&dir)?, + dir, + token, + instance: pyo_proto::signing::new_nonce().replace(['+', '/', '='], ""), + geo, + ctx: RwLock::new(None), + agg: Mutex::new(agg::Aggregator::default()), + pending: Mutex::new((0, VecDeque::new())), + salt: Mutex::new((String::new(), String::new())), + writing: Mutex::new(()), + }) + } + + fn country(&self, ip: &str) -> String { + let (Some(geo), Ok(addr)) = (&self.geo, ip.parse::()) else { + return String::new(); + }; + geo.lookup(addr) + .ok() + .and_then(|r| r.decode::().ok().flatten()) + .and_then(|c| c.country.iso_code.map(str::to_owned)) + .unwrap_or_default() + } + + /// The day's salt, kept on the volume (a restart keeps the day's + /// visitors the same), the day before's deleted. + fn salt(&self, day: &str) -> String { + let mut g = self.salt.lock().unwrap_or_else(|e| e.into_inner()); + if g.0 == day { + return g.1.clone(); + } + let dir = self.dir.join("salt"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join(day); + let salt = match std::fs::read_to_string(&path) { + Ok(s) if !s.trim().is_empty() => s.trim().to_owned(), + _ => { + let s = format!("{}{}", pyo_proto::signing::new_nonce(), pyo_proto::signing::new_nonce()); + let _ = std::fs::write(&path, &s); + s + } + }; + if let Ok(rd) = std::fs::read_dir(&dir) { + for e in rd.flatten() { + if e.file_name().to_string_lossy().as_ref() < day { + let _ = std::fs::remove_file(e.path()); + } + } + } + *g = (day.to_owned(), salt.clone()); + salt + } + + /// Vector's lines: cleaned, kept and added up. Returns how many were kept. + pub fn ingest(&self, body: &[u8], now_ms: i64) -> usize { + let text = String::from_utf8_lossy(body); + let lines: Vec = if text.trim_start().starts_with('[') { + serde_json::from_str(&text).unwrap_or_default() + } else { + text.lines().filter(|l| !l.trim().is_empty()).filter_map(|l| serde_json::from_str(l).ok()).collect() + }; + let ctx = self.ctx.read().unwrap_or_else(|e| e.into_inner()).clone(); + let known = ctx.is_some(); + let ctx = ctx.unwrap_or_default(); + let ua = woothee::parser::Parser::new(); + let locate = |ip: &str| self.country(ip); + let mut cleaned = Vec::with_capacity(lines.len()); + // The salt is the day's of each line (a batch can cross midnight). + let mut salts: Vec<(String, String)> = vec![]; + for l in &lines { + let at = l["start_time"] + .as_str() + .or_else(|| l["time"].as_str()) + .and_then(pyo_proto::traffic::parse_time_ms) + .unwrap_or(now_ms); + let day = clean::day_of(at); + let salt = match salts.iter().find(|s| s.0 == day) { + Some(s) => s.1.clone(), + None => { + let s = self.salt(&day); + salts.push((day, s.clone())); + s + } + }; + let c = Cleaner { ctx: &ctx, known, salt: &salt, locate: &locate, ua: &ua }; + if let Some(x) = c.clean(l, now_ms) { + cleaned.push(x); + } + } + { + let mut agg = self.agg.lock().unwrap_or_else(|e| e.into_inner()); + for c in &cleaned { + agg.add(c); + } + } + // Rows by kind and hour, one gzip member each. + let mut groups: std::collections::BTreeMap<(&str, i64), String> = Default::default(); + for c in &cleaned { + let (kind, at, json) = match c { + Cleaned::Request { row, .. } => ("requests", row.at, serde_json::to_string(row)), + Cleaned::Connection { row, .. } => ("connections", row.at, serde_json::to_string(row)), + Cleaned::Waf { row, .. } => ("waf", row.at, serde_json::to_string(row)), + }; + let Ok(json) = json else { continue }; + let s = groups.entry((kind, files::hour_of(at))).or_default(); + s.push_str(&json); + s.push('\n'); + } + let _w = self.writing.lock().unwrap_or_else(|e| e.into_inner()); + for ((kind, hour), lines) in groups { + if let Err(e) = self.files.append(kind, hour, &lines) { + tracing::warn!(error = %e, kind, "couldn't keep rows"); + } + } + cleaned.len() + } + + /// Moves finished minutes to the pending batches. + pub fn tick(&self, now_ms: i64) { + let done = self.agg.lock().unwrap_or_else(|e| e.into_inner()).take_finished(now_ms / 1000); + if let Some(mut b) = done { + let mut p = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + p.0 += 1; + b.id = format!("{}-{}", self.instance, p.0); + let seq = p.0; + p.1.push_back((seq, b)); + while p.1.len() > PENDING_MAX { + p.1.pop_front(); + } + } + } + + /// Applies the limits: the context's, or the defaults. + pub fn enforce(&self, now_ms: i64) { + let (mb, days) = self + .ctx + .read() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map(|c| (c.max_mb, c.max_days)) + .filter(|(mb, d)| *mb > 0 && *d > 0) + .unwrap_or((pyo_proto::traffic::DEFAULT_MAX_MB, pyo_proto::traffic::DEFAULT_MAX_DAYS)); + let _w = self.writing.lock().unwrap_or_else(|e| e.into_inner()); + let gone = self.files.enforce(now_ms, mb << 20, days); + if gone > 0 { + tracing::info!(files = gone, "removed the oldest kept requests"); + } + } + + fn pending(&self, max: usize) -> Vec { + let p = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + p.1.iter().take(max).map(|(seq, b)| json!({ "seq": seq, "batch": b })).collect() + } + + fn ack(&self, upto: u64) { + let mut p = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + p.1.retain(|(s, _)| *s > upto); + } + + fn status(&self) -> Value { + json!({ + "bytes": self.files.size(), + "keptSince": self.files.kept_since(), + "pending": self.pending.lock().map(|p| p.1.len()).unwrap_or(0), + "open": self.agg.lock().map(|a| a.len()).unwrap_or(0), + "context": self.ctx.read().map(|c| c.is_some()).unwrap_or(false), + }) + } +} + +fn allowed(token: &str, headers: &HeaderMap) -> bool { + let got = headers + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .unwrap_or(""); + got.len() == token.len() && got.bytes().zip(token.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0 +} + +type Shared = Arc; + +fn guard(s: &Store, h: &HeaderMap) -> Result<(), (StatusCode, String)> { + if allowed(&s.token, h) { Ok(()) } else { Err((StatusCode::UNAUTHORIZED, String::new())) } +} + +fn ok(v: Value) -> (StatusCode, String) { + (StatusCode::OK, v.to_string()) +} + +pub fn router(store: Shared) -> Router { + Router::new() + .route( + "/ingest", + post(|State(s): State, h: HeaderMap, b: Bytes| async move { + guard(&s, &h)?; + let s2 = s.clone(); + let kept = tokio::task::spawn_blocking(move || s2.ingest(&b, pyo_proto::now_ms())).await.unwrap_or(0); + Ok::<_, (StatusCode, String)>(ok(json!({ "kept": kept }))) + }), + ) + .route( + "/context", + put(|State(s): State, h: HeaderMap, b: Bytes| async move { + guard(&s, &h)?; + let ctx: TrafficContext = + serde_json::from_slice(&b).map_err(|_| (StatusCode::BAD_REQUEST, String::new()))?; + *s.ctx.write().unwrap_or_else(|e| e.into_inner()) = Some(ctx); + Ok::<_, (StatusCode, String)>(ok(json!({ "ok": true }))) + }), + ) + .route( + "/totals", + get(|State(s): State, h: HeaderMap| async move { + guard(&s, &h)?; + Ok::<_, (StatusCode, String)>(ok(json!({ "batches": s.pending(30) }))) + }), + ) + .route( + "/totals/ack", + post(|State(s): State, h: HeaderMap, b: Bytes| async move { + guard(&s, &h)?; + let v: Value = serde_json::from_slice(&b).unwrap_or_default(); + s.ack(v["upto"].as_u64().unwrap_or(0)); + Ok::<_, (StatusCode, String)>(ok(json!({ "ok": true }))) + }), + ) + .route( + "/query", + post(|State(s): State, h: HeaderMap, b: Bytes| async move { + guard(&s, &h)?; + let q: TrafficQuery = + serde_json::from_slice(&b).map_err(|_| (StatusCode::BAD_REQUEST, String::new()))?; + let s2 = s.clone(); + let a = tokio::task::spawn_blocking(move || s2.files.query(&q)) + .await + .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, String::new()))?; + Ok::<_, (StatusCode, String)>(ok(serde_json::to_value(a).unwrap_or_default())) + }), + ) + .route( + "/status", + get(|State(s): State, h: HeaderMap| async move { + guard(&s, &h)?; + Ok::<_, (StatusCode, String)>(ok(s.status())) + }), + ) + .route("/healthz", get(|| async { "ok" })) + .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY)) + .with_state(store) +} + +/// `pyo-agent traffic`: serves the store until the pod stops. +pub async fn run() -> anyhow::Result<()> { + let token = std::env::var("PYO_TRAFFIC_TOKEN").map_err(|_| anyhow::anyhow!("PYO_TRAFFIC_TOKEN is required"))?; + let dir = PathBuf::from(std::env::var("PYO_TRAFFIC_DIR").unwrap_or_else(|_| "/data".into())); + let geoip = std::env::var("PYO_TRAFFIC_GEOIP").unwrap_or_else(|_| GEOIP.into()); + let store = Arc::new(Store::open(dir, token, Some(PathBuf::from(geoip)))?); + let s = store.clone(); + tokio::spawn(async move { + let mut tick = tokio::time::interval(Duration::from_secs(10)); + let mut n = 0u64; + loop { + tick.tick().await; + let now = pyo_proto::now_ms(); + s.tick(now); + // The limits once a minute (and at the start). + if n.is_multiple_of(6) { + let s = s.clone(); + let _ = tokio::task::spawn_blocking(move || s.enforce(now)).await; + } + n += 1; + } + }); + let addr = std::net::SocketAddr::from(([0, 0, 0, 0], PORT)); + let l = tokio::net::TcpListener::bind(addr).await?; + tracing::info!(%addr, "keeping the cluster's traffic"); + axum::serve(l, router(store)).await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lines_in_totals_and_rows_out() { + let d = std::env::temp_dir().join(format!("pyo-traffic-store-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + let s = Store::open(d.clone(), "t".into(), None).unwrap(); + let now = 1_794_000_000_000i64; + let line = |path: &str, status: u16| { + json!({ "start_time": jiff::Timestamp::from_millisecond(now).unwrap().to_string(), "host": "a.example", "method": "GET", "path": path, + "status": status, "remote": "203.0.113.9", "duration_ms": 12, "bytes": 10, "content_type": "text/html" }) + .to_string() + }; + let body = format!("{}\n{}\n{}\n", line("/", 200), line("/x?token=1", 404), line("/", 500)); + assert_eq!(s.ingest(body.as_bytes(), now), 3); + // Kept, newest first, with values redacted and no address (IP + // setting "none" until Pyo says otherwise). + let a = s.files.query(&TrafficQuery { rows: "requests".into(), limit: 10, status: Some("4xx".into()), ..Default::default() }); + assert_eq!(a.rows.len(), 1); + assert_eq!(a.rows[0]["url"], "/x?token=[redacted]"); + assert_eq!(a.rows[0]["ip"], ""); + // Totals once the minute is done, acknowledged once sent. + s.tick(now + 120_000); + let p = s.pending(10); + assert_eq!(p.len(), 1); + assert_eq!(p[0]["batch"]["hosts"][0]["requests"], 3); + assert_eq!(p[0]["batch"]["hosts"][0]["errors"], 1); + s.ack(p[0]["seq"].as_u64().unwrap()); + assert!(s.pending(10).is_empty()); + // The day's salt is kept. + let day = clean::day_of(now); + assert_eq!(s.salt(&day), std::fs::read_to_string(d.join("salt").join(&day)).unwrap()); + // With Pyo's context: other hosts aren't kept. + *s.ctx.write().unwrap() = Some(TrafficContext { ip_mode: "full".into(), ..Default::default() }); + assert_eq!(s.ingest(line("/", 200).as_bytes(), now), 0); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn tokens() { + assert_eq!(token_for("a").len(), 64); + assert_ne!(token_for("a"), token_for("b")); + let mut h = HeaderMap::new(); + h.insert("authorization", format!("Bearer {}", token_for("a")).parse().unwrap()); + assert!(allowed(&token_for("a"), &h)); + assert!(!allowed(&token_for("b"), &h)); + } +} diff --git a/crates/pyo-agent/src/trust.rs b/crates/pyo-agent/src/trust.rs new file mode 100644 index 00000000..b651e103 --- /dev/null +++ b/crates/pyo-agent/src/trust.rs @@ -0,0 +1,574 @@ +//! What the agent trusts, when its install says so (Pyo Cloud): +//! +//! - `PYO_AGENT_CA`: the only CA the API's agent endpoint may present (no +//! public CAs). The agent proves who it is with a client certificate from +//! that CA, for its cluster only, valid a day. Its key is made here and +//! never leaves the cluster (Secret `pyo-agent-identity`). The first one +//! comes with the connect command's token, which works once; later ones +//! with the certificate it replaces, at half its lifetime. +//! - `PYO_COMMAND_KEY` and `PYO_CLUSTER_ID`: commands run only when the +//! signer signed them for this cluster, newer than the last one run, and +//! not expired (pyo-proto `signing`). The last number run is kept in the +//! same Secret, so a restart doesn't open the door to replays. +//! +//! Without them (self-hosted), nothing here runs: the token alone works. + +use std::sync::{Arc, RwLock}; +use std::time::Duration; + +use anyhow::Context; +use k8s_openapi::api::core::v1::Secret; +use kube::api::{Patch, PatchParams}; +use pyo_proto::signing::{Refused, TrustedKeys}; +use rustls::pki_types::pem::PemObject; +use rustls::pki_types::{CertificateDer, PrivateKeyDer}; +use rustls::sign::CertifiedKey; +use serde_json::{Value, json}; + +pub const IDENTITY_SECRET: &str = "pyo-agent-identity"; + +// ── Client certificate ────────────────────────────────────────────────────── + +/// The client certificate new connections present; swapped on renewal. +#[derive(Debug, Default)] +pub struct CertSlot(RwLock>>); + +impl rustls::client::ResolvesClientCert for CertSlot { + fn resolve(&self, _: &[&[u8]], _: &[rustls::SignatureScheme]) -> Option> { + self.0.read().ok()?.clone() + } + fn has_certs(&self) -> bool { + self.0.read().map(|c| c.is_some()).unwrap_or(false) + } +} + +impl CertSlot { + fn set(&self, cert_pem: &str, key_pem: &str) -> anyhow::Result<()> { + let certs = CertificateDer::pem_slice_iter(cert_pem.as_bytes()) + .collect::, _>>() + .context("the certificate isn't PEM")?; + anyhow::ensure!(!certs.is_empty(), "no certificate"); + let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes()).context("the key isn't PEM")?; + let provider = rustls::crypto::aws_lc_rs::default_provider(); + let ck = CertifiedKey::from_der(certs, key, &provider)?; + *self.0.write().map_err(|_| anyhow::anyhow!("lock"))? = Some(Arc::new(ck)); + Ok(()) + } +} + +/// The agent's TLS to the API: Pyo's agent CA only, TLS 1.3, and the +/// client certificate in `slot`. +pub fn client_config(ca_pem: &str, slot: Arc) -> anyhow::Result { + let mut roots = rustls::RootCertStore::empty(); + for c in CertificateDer::pem_slice_iter(ca_pem.as_bytes()) { + roots.add(c.context("PYO_AGENT_CA isn't PEM")?)?; + } + anyhow::ensure!(!roots.is_empty(), "PYO_AGENT_CA holds no certificate"); + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let mut cfg = rustls::ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13])? + .with_root_certificates(roots) + .with_client_cert_resolver(slot); + cfg.alpn_protocols = vec![b"http/1.1".to_vec()]; + // Every connection proves who it is anew: a resumed session would carry + // the identity it started with (none, for the one that enrolled). + cfg.resumption = rustls::client::Resumption::disabled(); + Ok(cfg) +} + +/// What's kept in the identity Secret. +#[derive(Default, Clone)] +struct Stored { + key: String, + cert: String, + not_after: u64, + last_seq: u64, +} + +async fn load(kube: &kube::Client) -> Stored { + let api = kube::Api::::namespaced(kube.clone(), pyo_proto::rbac::NS); + let Ok(Some(s)) = api.get_opt(IDENTITY_SECRET).await else { + return Stored::default(); + }; + let get = |k: &str| { + s.data + .as_ref() + .and_then(|d| d.get(k)) + .and_then(|v| String::from_utf8(v.0.clone()).ok()) + .unwrap_or_default() + }; + Stored { + key: get("key.pem"), + cert: get("cert.pem"), + not_after: get("not-after").trim().parse().unwrap_or(0), + last_seq: get("last-seq").trim().parse().unwrap_or(0), + } +} + +/// Writes some of the Secret's keys. Each `manager` owns its own keys +/// (server-side apply drops a manager's keys it leaves out). +async fn save(kube: &kube::Client, manager: &str, fields: Value) -> anyhow::Result<()> { + use base64::Engine as _; + let api = kube::Api::::namespaced(kube.clone(), pyo_proto::rbac::NS); + let data: serde_json::Map = fields + .as_object() + .into_iter() + .flatten() + .map(|(k, v)| { + let raw = v.as_str().unwrap_or_default(); + (k.clone(), json!(base64::engine::general_purpose::STANDARD.encode(raw))) + }) + .collect(); + let doc = json!({ + "apiVersion": "v1", + "kind": "Secret", + "metadata": { "name": IDENTITY_SECRET, "namespace": pyo_proto::rbac::NS, "labels": { "app.kubernetes.io/part-of": "pyo" } }, + "type": "Opaque", + "data": data, + }); + api.patch(IDENTITY_SECRET, &PatchParams::apply(manager).force(), &Patch::Apply(doc)) + .await + .with_context(|| format!("couldn't save {IDENTITY_SECRET}"))?; + Ok(()) +} + +/// The agent's identity at the API's agent endpoint. +pub struct Identity { + pub slot: Arc, + pub tls: rustls::ClientConfig, + base: String, + token: String, + kube: kube::Client, +} + +impl Identity { + /// From `PYO_AGENT_CA`; None when the install doesn't set it. + pub fn from_env(base: &str, token: &str, kube: &kube::Client) -> anyhow::Result> { + let Some(ca) = std::env::var("PYO_AGENT_CA").ok().filter(|v| !v.trim().is_empty()) else { + return Ok(None); + }; + let slot = Arc::new(CertSlot::default()); + let tls = client_config(&ca, slot.clone())?; + Ok(Some(Self { + slot, + tls, + base: base.trim_end_matches('/').to_owned(), + token: token.to_owned(), + kube: kube.clone(), + })) + } + + fn http(&self) -> anyhow::Result { + Ok(reqwest::Client::builder() + .use_preconfigured_tls(self.tls.clone()) + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(30)) + .build()?) + } + + /// A certificate to start with: the stored one while it has more than + /// an hour left, else a new one for the connect command's token. + /// Retries until it has one. + pub async fn ensure(&self) { + let mut wait = Duration::from_secs(2); + loop { + match self.try_ensure().await { + Ok(()) => return, + Err(e) => { + tracing::warn!(error = %format!("{e:#}"), retry_in = ?wait, "no client certificate yet"); + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(60)); + } + } + } + } + + async fn try_ensure(&self) -> anyhow::Result<()> { + let s = load(&self.kube).await; + if !s.cert.is_empty() && s.not_after > pyo_proto::now_ms() as u64 + 3_600_000 { + self.slot.set(&s.cert, &s.key)?; + tracing::info!(not_after = s.not_after, "using the stored client certificate"); + return Ok(()); + } + self.request("enroll", Some(&self.token)).await + } + + /// A new key and certificate, through `/enroll` (with the token) or + /// `/renew` (with the current certificate). + async fn request(&self, how: &str, token: Option<&str>) -> anyhow::Result<()> { + let key = rcgen::KeyPair::generate()?; + let csr = rcgen::CertificateParams::new(Vec::::new())?.serialize_request(&key)?.pem()?; + let mut body = json!({ "csr": csr }); + if let Some(t) = token { + body["token"] = json!(t); + } + let res = self + .http()? + .post(format!("{}/api/agent/v1/{how}", self.base)) + .json(&body) + .send() + .await?; + let status = res.status(); + let v: Value = res.json().await.unwrap_or_default(); + anyhow::ensure!(status.is_success(), "{status}: {}", v["error"].as_str().or(v["message"].as_str()).unwrap_or("")); + let cert = v["certificate"].as_str().unwrap_or("").to_owned(); + let not_after = v["notAfter"].as_u64().unwrap_or(0); + anyhow::ensure!(!cert.is_empty() && not_after > 0, "the API sent no certificate"); + let key_pem = key.serialize_pem(); + self.slot.set(&cert, &key_pem)?; + save( + &self.kube, + "pyo-agent-identity", + json!({ "key.pem": key_pem, "cert.pem": cert, "not-after": not_after.to_string() }), + ) + .await?; + tracing::info!(how, not_after, "got a client certificate"); + Ok(()) + } + + /// Renews the certificate at half its lifetime, for as long as the agent runs. + pub async fn renew_loop(self: Arc) { + loop { + tokio::time::sleep(Duration::from_secs(600)).await; + let s = load(&self.kube).await; + let left = s.not_after.saturating_sub(pyo_proto::now_ms() as u64); + // Certificates last a day: renew once less than half is left. + if left > 12 * 3_600_000 { + continue; + } + if let Err(e) = self.request("renew", None).await { + tracing::warn!(error = %format!("{e:#}"), left_ms = left, "couldn't renew the client certificate"); + } + } + } +} + +// ── Signed commands ───────────────────────────────────────────────────────── + +/// Checks commands against the signer's keys, for this cluster. +pub struct Verifier { + keys: TrustedKeys, + cluster: String, + last: tokio::sync::Mutex, + kube: kube::Client, +} + +impl Verifier { + /// From `PYO_COMMAND_KEY` and `PYO_CLUSTER_ID`; None when the install + /// doesn't set a key. A key without the cluster's id is an error: the + /// agent would otherwise run commands signed for any cluster. + pub async fn from_env(kube: &kube::Client) -> anyhow::Result> { + let Some(k) = std::env::var("PYO_COMMAND_KEY").ok().filter(|v| !v.trim().is_empty()) else { + return Ok(None); + }; + let keys = TrustedKeys::parse(&k).map_err(|e| anyhow::anyhow!("PYO_COMMAND_KEY: {e}"))?; + let cluster = std::env::var("PYO_CLUSTER_ID") + .ok() + .filter(|v| !v.trim().is_empty()) + .context("PYO_COMMAND_KEY needs PYO_CLUSTER_ID")?; + let last = load(kube).await.last_seq; + tracing::info!(cluster = %cluster, last_seq = last, "running signed commands only"); + Ok(Some(Self { + keys, + cluster, + last: tokio::sync::Mutex::new(last), + kube: kube.clone(), + })) + } + + /// Keeps the commands that check out, each with its signed JSON in + /// place of what came beside it. The rest, by id, with why. + pub async fn check(&self, items: Vec) -> (Vec, Vec<(String, Refused)>) { + let mut last = self.last.lock().await; + let before = *last; + let mut ok = Vec::with_capacity(items.len()); + let mut refused = vec![]; + for mut item in items { + let id = item["id"].as_str().unwrap_or("").to_owned(); + let signed: Option = + serde_json::from_value(item["signed"].clone()).ok(); + match self.keys.verify(signed.as_ref(), &id, &self.cluster, *last, pyo_proto::now_ms() as u64) { + Ok(claims) => match serde_json::from_str::(&signed.map(|s| s.command).unwrap_or_default()) { + Ok(command) => { + *last = claims.seq; + item["command"] = command; + ok.push(item); + } + Err(_) => refused.push((id, Refused::BadClaims)), + }, + Err(why) => refused.push((id, why)), + } + } + if *last != before + && let Err(e) = save(&self.kube, "pyo-agent-commands", json!({ "last-seq": last.to_string() })).await + { + tracing::warn!(error = %format!("{e:#}"), "couldn't keep the last command number"); + } + (ok, refused) + } + + /// Checks a reply to the request sent with `nonce`: the signed JSON + /// in place of the plain fields beside it, or why it's refused. + pub fn check_reply(&self, body: &Value, nonce: &str) -> Result { + check_reply(&self.keys, &self.cluster, body, nonce, pyo_proto::now_ms() as u64) + } +} + +/// A reply's signed JSON, when it checks out for `cluster` and the request +/// sent with `nonce` (the plain fields beside it are never used). +fn check_reply(keys: &TrustedKeys, cluster: &str, body: &Value, nonce: &str, now_ms: u64) -> Result { + let signed: Option = serde_json::from_value(body["signed"].clone()).ok(); + let json = keys.verify_reply(signed.as_ref(), cluster, nonce, now_ms)?; + serde_json::from_str(json).map_err(|_| Refused::BadClaims) +} + +// ── Signed requests ───────────────────────────────────────────────────────── + +/// The agent's request key (`PYO_AGENT_AUTH=signed`): made here, its public +/// half enrolled with the connect command's token, renewed at half its day. +/// Every request to Pyo is signed with it (pyo-proto `agentauth`), so who +/// the agent is survives a proxy that ends TLS. Kept in pyo-agent-identity. +pub struct KeyIdentity { + key: RwLock)>>, + /// Pyo's endpoint certificate's CA, when it isn't a public one. + pub tls: Option, + base: String, + token: String, + kube: kube::Client, +} + +fn b64(b: &[u8]) -> String { + use base64::Engine as _; + base64::engine::general_purpose::STANDARD.encode(b) +} + +fn unb64(s: &str) -> Option> { + use base64::Engine as _; + base64::engine::general_purpose::STANDARD.decode(s.trim()).ok() +} + +struct StoredKey { + pkcs8: Vec, + key_id: String, + not_after: u64, + token_sha: String, +} + +async fn load_key(kube: &kube::Client) -> Option { + let api = kube::Api::::namespaced(kube.clone(), pyo_proto::rbac::NS); + let s = api.get_opt(IDENTITY_SECRET).await.ok()??; + let d = s.data?; + let get = |k: &str| d.get(k).and_then(|v| String::from_utf8(v.0.clone()).ok()).unwrap_or_default(); + let pkcs8 = unb64(&get("request-key"))?; + let key_id = get("key-id"); + (!key_id.is_empty()).then(|| StoredKey { + pkcs8, + key_id, + not_after: get("key-not-after").trim().parse().unwrap_or(0), + token_sha: get("key-token"), + }) +} + +impl KeyIdentity { + /// From `PYO_AGENT_AUTH=signed`; None otherwise. + pub fn from_env(base: &str, token: &str, kube: &kube::Client) -> anyhow::Result> { + if std::env::var("PYO_AGENT_AUTH").ok().as_deref().map(str::trim) != Some("signed") { + return Ok(None); + } + let tls = match std::env::var("PYO_AGENT_CA").ok().filter(|v| !v.trim().is_empty()) { + Some(ca) => Some(client_config(&ca, Arc::new(CertSlot::default()))?), + None => None, + }; + Ok(Some(Self { + key: RwLock::new(None), + tls, + base: base.trim_end_matches('/').to_owned(), + token: token.to_owned(), + kube: kube.clone(), + })) + } + + /// The headers that sign a request (`path` with its query). + pub fn headers(&self, method: &str, path: &str, body: &[u8]) -> Vec<(&'static str, String)> { + let Some((id, key)) = self.key.read().ok().and_then(|k| k.clone()) else { + return vec![]; + }; + key.sign(&id, method, path, body, pyo_proto::now_ms() / 1000).to_vec() + } + + fn http(&self) -> anyhow::Result { + let mut b = reqwest::Client::builder() + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(30)); + if let Some(tls) = &self.tls { + b = b.use_preconfigured_tls(tls.clone()); + } + Ok(b.build()?) + } + + /// A key to start with: the stored one while it has more than an hour + /// left and came from this token, else a new one. Retries until it has one. + pub async fn ensure(&self) { + let mut wait = Duration::from_secs(2); + loop { + match self.try_ensure().await { + Ok(()) => return, + Err(e) => { + tracing::warn!(error = %format!("{e:#}"), retry_in = ?wait, "no request key yet"); + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(60)); + } + } + } + } + + async fn try_ensure(&self) -> anyhow::Result<()> { + if let Some(s) = load_key(&self.kube).await + && s.token_sha == pyo_proto::token_hash(&self.token) + && s.not_after > pyo_proto::now_ms() as u64 + 3_600_000 + { + let key = pyo_proto::agentauth::RequestKey::from_pkcs8(&s.pkcs8).map_err(anyhow::Error::msg)?; + *self.key.write().map_err(|_| anyhow::anyhow!("lock"))? = Some((s.key_id.clone(), Arc::new(key))); + tracing::info!(key = %s.key_id, "using the stored request key"); + return Ok(()); + } + self.request(true).await + } + + /// A new key, enrolled with the token (`first`) or swapped in with the current one. + async fn request(&self, first: bool) -> anyhow::Result<()> { + let pkcs8 = pyo_proto::agentauth::RequestKey::generate_pkcs8().map_err(anyhow::Error::msg)?; + let key = pyo_proto::agentauth::RequestKey::from_pkcs8(&pkcs8).map_err(anyhow::Error::msg)?; + let (path, body) = if first { + ("/api/agent/v1/enroll-key", json!({ "token": self.token, "publicKey": key.public_key() })) + } else { + ("/api/agent/v1/renew-key", json!({ "publicKey": key.public_key() })) + }; + let body = serde_json::to_vec(&body)?; + let url = format!("{}{path}", self.base); + let mut req = self.http()?.post(&url).header("content-type", "application/json"); + if !first { + let signed_path = reqwest::Url::parse(&url)?.path().to_owned(); + for (k, v) in self.headers("POST", &signed_path, &body) { + req = req.header(k, v); + } + } + let res = req.body(body).send().await?; + let status = res.status(); + let v: Value = res.json().await.unwrap_or_default(); + anyhow::ensure!(status.is_success(), "{status}: {}", v["error"].as_str().unwrap_or("")); + let key_id = v["keyId"].as_str().unwrap_or("").to_owned(); + let not_after = v["notAfter"].as_u64().unwrap_or(0); + anyhow::ensure!(!key_id.is_empty(), "Pyo sent no key id"); + save( + &self.kube, + "pyo-agent-key", + json!({ + "request-key": b64(&pkcs8), + "key-id": key_id, + "key-not-after": not_after.to_string(), + "key-token": pyo_proto::token_hash(&self.token), + }), + ) + .await?; + *self.key.write().map_err(|_| anyhow::anyhow!("lock"))? = Some((key_id.clone(), Arc::new(key))); + tracing::info!(key = %key_id, first, not_after, "got a request key"); + Ok(()) + } + + /// Swaps in a new key at half the current one's day, while the agent runs. + pub async fn renew_loop(self: Arc) { + loop { + tokio::time::sleep(Duration::from_secs(600)).await; + let left = load_key(&self.kube) + .await + .map(|s| s.not_after.saturating_sub(pyo_proto::now_ms() as u64)) + .unwrap_or(0); + if left > 12 * 3_600_000 { + continue; + } + if let Err(e) = self.request(false).await { + tracing::warn!(error = %format!("{e:#}"), left_ms = left, "couldn't renew the request key"); + } + } + } +} + +// ── Components' keys ──────────────────────────────────────────────────────── + +/// A new key for one of the cluster's components (a builder, pyo-static), +/// made here and registered with Pyo by this agent: its key id and its +/// PKCS#8 document (standard base64), for the component's Secret. The +/// private half never leaves the cluster. +pub async fn component_key( + api: &crate::api::PyoApi, + component: &str, + builder_id: Option<&str>, +) -> anyhow::Result<(String, String)> { + let pkcs8 = pyo_proto::agentauth::RequestKey::generate_pkcs8().map_err(anyhow::Error::msg)?; + let key = pyo_proto::agentauth::RequestKey::from_pkcs8(&pkcs8).map_err(anyhow::Error::msg)?; + let key_id = api.register_component_key(component, builder_id, &key.public_key()).await?; + Ok((key_id, b64(&pkcs8))) +} + +/// `pyo-agent sign-request METHOD PATH [--at UNIX_SECONDS] [--key-id ID]`: +/// the two headers that sign a request with this agent's stored key, empty +/// body. For tests of the API's checks (a replay, a stale time, a key id +/// that isn't this key's). +pub async fn sign_request_cli(args: &[String]) -> anyhow::Result<()> { + let (Some(method), Some(path)) = (args.first(), args.get(1)) else { + anyhow::bail!("usage: pyo-agent sign-request METHOD PATH [--at UNIX_SECONDS] [--key-id ID]"); + }; + let mut at = pyo_proto::now_ms() / 1000; + let mut key_id = None; + let mut i = 2; + while i < args.len() { + match (args[i].as_str(), args.get(i + 1)) { + ("--at", Some(v)) => at = v.parse()?, + ("--key-id", Some(v)) => key_id = Some(v.clone()), + _ => anyhow::bail!("unknown option {}", args[i]), + } + i += 2; + } + let kube = kube::Client::try_default().await?; + let s = load_key(&kube).await.context("no request key here")?; + let key = pyo_proto::agentauth::RequestKey::from_pkcs8(&s.pkcs8).map_err(anyhow::Error::msg)?; + for (k, v) in key.sign(key_id.as_deref().unwrap_or(&s.key_id), method, path, b"", at) { + println!("{k}: {v}"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use pyo_proto::signing::{REPLY_TTL_MS, ReplyClaims, Signer, sha256_hex}; + + fn signed(s: &Signer, cluster: &str, nonce: &str, reply: &Value, now: u64) -> Value { + let json = reply.to_string(); + let claims = ReplyClaims { v: 1, cluster: cluster.into(), nonce: nonce.into(), iat: now, exp: now + REPLY_TTL_MS, sha256: sha256_hex(json.as_bytes()) }; + let (c, sig) = s.sign_reply(&claims); + let mut out = reply.clone(); + out["signed"] = json!({ "claims": c, "sig": sig, "kid": s.kid(), "reply": json }); + out + } + + #[test] + fn only_the_signed_reply_is_used() { + let s = Signer::from_pkcs8(&Signer::generate_pkcs8().unwrap()).unwrap(); + let keys = TrustedKeys::parse(&s.public_key()).unwrap(); + let now = 1_000_000; + let reply = json!({ "publicTraffic": true, "serverTags": [] }); + let mut body = signed(&s, "cl_a", "nonce-1234", &reply, now); + // The plain fields beside it are changed on the way: they don't count. + body["publicTraffic"] = json!(false); + assert_eq!(check_reply(&keys, "cl_a", &body, "nonce-1234", now), Ok(reply.clone())); + // A reply without a signature, or for another request or cluster. + assert_eq!(check_reply(&keys, "cl_a", &reply, "nonce-1234", now), Err(Refused::Unsigned)); + assert_eq!(check_reply(&keys, "cl_a", &body, "nonce-0000", now), Err(Refused::OtherRequest)); + assert_eq!(check_reply(&keys, "cl_b", &body, "nonce-1234", now), Err(Refused::OtherCluster)); + // Its signed JSON changed. + body["signed"]["reply"] = json!(json!({ "publicTraffic": false }).to_string()); + assert_eq!(check_reply(&keys, "cl_a", &body, "nonce-1234", now), Err(Refused::Tampered)); + } +} diff --git a/crates/pyo-agent/src/volumes.rs b/crates/pyo-agent/src/volumes.rs index 76fdd0cb..59de3eca 100644 --- a/crates/pyo-agent/src/volumes.rs +++ b/crates/pyo-agent/src/volumes.rs @@ -74,7 +74,8 @@ async fn wait_unmounted( let pods = Api::::namespaced(client.clone(), ns); let deadline = tokio::time::Instant::now() + wait; loop { - let users = claim_users(&pods.list(&ListParams::default()).await?.items, claim); + let live = ListParams::default().fields(crate::pods::LIVE); + let users = claim_users(&crate::pods::list_pods(&pods, &live).await?, claim); if users.is_empty() { return Ok(()); } diff --git a/crates/pyo-api/Cargo.toml b/crates/pyo-api/Cargo.toml index d9160360..85eb9200 100644 --- a/crates/pyo-api/Cargo.toml +++ b/crates/pyo-api/Cargo.toml @@ -12,7 +12,7 @@ axum = { version = "0.8.9", features = ["ws"] } axum-extra = { version = "0.12.6", features = ["cookie", "typed-header"] } base64 = "0.23.1" cookie = "0.18" -pyo-proto = { version = "0.4.5", path = "../pyo-proto", features = ["openapi", "sandbox-token"] } +pyo-proto = { version = "0.5.0", path = "../pyo-proto", features = ["openapi", "sandbox-token", "command-signing", "agent-ca"] } hex = "0.4.3" hmac = "0.13.0" hyper = { version = "1.12.0", features = ["client", "http1"] } @@ -40,6 +40,9 @@ tower-http = { version = "0.7.1", features = ["fs", "trace", "compression-gzip", tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } woothee = "0.13" +# Two-factor with an authenticator app (twofactor.rs), and its QR code. +totp-rs = { version = "6.0.0", default-features = false, features = ["std"] } +qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } webauthn-rs = { version = "=0.6.2", features = ["danger-allow-state-serialisation", "conditional-ui"] } x509-parser = "0.18" tokio-tungstenite = "0.29" @@ -47,12 +50,17 @@ futures = "0.3.34" crypto_secretbox = "0.1.1" zeroize = "1" flate2 = "1" -rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem"] } +rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem", "x509-parser"] } +time = "0.3" +tokio-rustls = { version = "0.26", default-features = false, features = ["aws_lc_rs"] } +# Domain proofs: TXT records read from the domain's own name servers. +hickory-resolver = { version = "0.26.3", default-features = false, features = ["tokio", "system-config"] } # ACME for sandbox edge certificates. Its HTTP goes through reqwest. instant-acme = { version = "0.8.5", default-features = false, features = ["aws-lc-rs", "rcgen"] } serde_norway = "0.9.42" [dev-dependencies] boon = "0.6.1" +tower = { version = "0.5", features = ["util"] } # The mock ACME server signs the CSRs it gets. rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem", "x509-parser"] } diff --git a/crates/pyo-api/assets/connect.sh b/crates/pyo-api/assets/connect.sh index 781d50ee..3b23145c 100644 --- a/crates/pyo-api/assets/connect.sh +++ b/crates/pyo-api/assets/connect.sh @@ -7,10 +7,12 @@ # [--registry server-1.tail1234.ts.net:5006 --registry-token 9b1c...] # # --api where the agent reaches Pyo -# --token the cluster's agent token (shown once in Pyo) +# --token the connect token (works once, within an hour) # --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 # # Or only joins this machine to the tailnet (Pyo's own machine does this @@ -234,7 +236,7 @@ quietly() { set -euo pipefail export DEBIAN_FRONTEND=noninteractive -API="" TOKEN="" TS_AUTHKEY="${TS_AUTHKEY:-}" REGISTRY="" REGISTRY_TOKEN="" +API="" TOKEN="" TS_AUTHKEY="${TS_AUTHKEY:-}" REGISTRY="" REGISTRY_TOKEN="" LOCAL_REGISTRY="" UNINSTALL="" KEEP_DATA="" YES="" DRY_RUN="" WITH_PYO="" TAILNET_ONLY="" while [ $# -gt 0 ]; do case "$1" in @@ -243,6 +245,7 @@ while [ $# -gt 0 ]; do --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 ;; --uninstall) UNINSTALL=1; shift ;; --keep-data) KEEP_DATA=1; shift ;; @@ -553,7 +556,7 @@ if [ -z "$TAILNET_ONLY" ] && [ -z "$API" ] && [ -z "$TOKEN" ] && command -v k3s case "$API" in http://*.svc:* | http://*.svc.cluster.local:*) API=http://127.0.0.1:8000 ;; esac [ -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]" >&2; exit 2; } +[ -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; } [ -z "$REGISTRY" ] || [ -n "$REGISTRY_TOKEN" ] || { echo "--registry needs --registry-token: copy the full command from Pyo." >&2; exit 2; } case "$REGISTRY_TOKEN" in *[!0-9a-fA-F]*) echo "That registry token doesn't look like one from Pyo." >&2; exit 2 ;; esac # The agent's token and its commands' secrets travel to --api: plain http @@ -1009,6 +1012,8 @@ code=$(curl -sS -o "$MANIFEST" -w '%{http_code}' --max-time 30 "$API/install/age 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 ;; + 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 ;; esac @@ -1191,6 +1196,23 @@ REG ) chmod 600 /etc/rancher/k3s/registries.yaml fi +# Its own registry (--local-registry): this machine pulls the images built +# here from 127.0.0.1:5005, which pyo-registry-host forwards to the registry. +LOCAL_REGISTRY_NEW="" +if [ -n "$LOCAL_REGISTRY" ] && ! grep -qs '"127.0.0.1:5005"' /etc/rancher/k3s/registries.yaml; then + if [ -s /etc/rancher/k3s/registries.yaml ]; then + echo "/etc/rancher/k3s/registries.yaml has other settings. Add a mirror for 127.0.0.1:5005 (http://127.0.0.1:5005) to it, then run this again." >&2 + exit 1 + fi + (umask 077 && cat > /etc/rancher/k3s/registries.yaml <<'REG' +mirrors: + "127.0.0.1:5005": + endpoint: + - "http://127.0.0.1:5005" +REG + ) + LOCAL_REGISTRY_NEW=1 +fi if ! command -v k3s >/dev/null; then # Pyo's k3s (deploy/k3s.env), downloaded and checked before it's set up. quietly "Downloading k3s…" k3s_fetch "$K3S_DIR" "$PYO_K3S_VERSION" || @@ -1217,7 +1239,7 @@ else # Its memory reserve brought up to date; k3s restarts below if it changed. k3s_memory_refresh later # k3s finds a newly installed NVIDIA toolkit only when it starts. - if [ -n "$REGISTRY" ] || [ -n "$GPU_TOOLKIT_NEW" ] || [ -n "$K3S_MEMORY_CHANGED" ]; then systemctl restart k3s 2>/dev/null || true; fi + if [ -n "$REGISTRY" ] || [ -n "$LOCAL_REGISTRY_NEW" ] || [ -n "$GPU_TOOLKIT_NEW" ] || [ -n "$K3S_MEMORY_CHANGED" ]; then systemctl restart k3s 2>/dev/null || true; fi fi k3s_up() { k3s kubectl get nodes >/dev/null 2>&1; } @@ -1263,6 +1285,120 @@ gateway_crds() { } gateway_crds +# The cluster's own registry (--local-registry): builders here push to it, +# and every server pulls from it through 127.0.0.1:5005 (loopback only). +local_registry() { + k3s kubectl apply --server-side --force-conflicts --field-manager=pyo -f - >/dev/null <<'YAML' +apiVersion: v1 +kind: Namespace +metadata: + name: pyo-system + labels: { pyo.dev/managed: "true" } +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: registry-data + namespace: pyo-system + labels: { app.kubernetes.io/part-of: pyo } +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 + volumeMounts: + - { name: data, mountPath: /var/lib/registry } + resources: + requests: { cpu: 10m, memory: 24Mi } + limits: { memory: 512Mi } + volumes: + - name: data + persistentVolumeClaim: { claimName: registry-data } +--- +# Its door (the agent's, registrydoor.rs): the team's registry tokens push +# and pull its own images. The tailnet's registry name routes here. +apiVersion: v1 +kind: Service +metadata: + name: pyo-registry-door + namespace: pyo-system + labels: { app.kubernetes.io/name: pyo-registry-door, app.kubernetes.io/part-of: pyo } +spec: + selector: { app.kubernetes.io/name: pyo-agent } + ports: + - { name: door, port: 5006, targetPort: 5006 } +--- +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: pyo-registry-host + namespace: pyo-system + labels: { app.kubernetes.io/name: pyo-registry-host, app.kubernetes.io/part-of: pyo } +spec: + selector: + matchLabels: { app.kubernetes.io/name: pyo-registry-host } + template: + metadata: + labels: { app.kubernetes.io/name: pyo-registry-host, app.kubernetes.io/part-of: pyo } + spec: + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet + tolerations: + - { operator: Exists } + 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 } +YAML +} +if [ -n "$LOCAL_REGISTRY" ]; then + quietly "Setting up this cluster's registry…" local_registry || { echo "Couldn't set up this cluster's registry (see above)." >&2; exit 1; } +fi + # >>> pyo:agent-apply (connect.sh only; join.rs tests it) # The Kubernetes minor version the API server reports; empty when it doesn't # answer. diff --git a/crates/pyo-api/assets/sandbox-images/images.json b/crates/pyo-api/assets/sandbox-images/images.json index 208247ec..ccc54a8b 100644 --- a/crates/pyo-api/assets/sandbox-images/images.json +++ b/crates/pyo-api/assets/sandbox-images/images.json @@ -1,27 +1,27 @@ { "contract": 1, "ubuntu": "24.04", - "date": "20261118", - "commit": "99c10c2d273e2f6cf083ec3168ac688caaf71b6b", + "date": "20261120", + "commit": "8d8daef52b455416e7adcb27127e42e6a4cc74d4", "images": { "base": { "repository": "ghcr.io/upsetdev/pyo-sandbox-images/base", - "digest": "sha256:daa2f35bfaedfe0407c306812f5cfdcc4dfd41d250c553eddb1ec1c96f8a387f", - "ref": "ghcr.io/upsetdev/pyo-sandbox-images/base@sha256:daa2f35bfaedfe0407c306812f5cfdcc4dfd41d250c553eddb1ec1c96f8a387f", + "digest": "sha256:c3735cc2430df05457817f1d8fa111bbb06bd3b70cfa61e197339b5506e79c2a", + "ref": "ghcr.io/upsetdev/pyo-sandbox-images/base@sha256:c3735cc2430df05457817f1d8fa111bbb06bd3b70cfa61e197339b5506e79c2a", "tags": { - "24.04": "sha256:daa2f35bfaedfe0407c306812f5cfdcc4dfd41d250c553eddb1ec1c96f8a387f", - "24.04-20261118": "sha256:daa2f35bfaedfe0407c306812f5cfdcc4dfd41d250c553eddb1ec1c96f8a387f", - "99c10c2d273e2f6cf083ec3168ac688caaf71b6b": "sha256:daa2f35bfaedfe0407c306812f5cfdcc4dfd41d250c553eddb1ec1c96f8a387f" + "24.04": "sha256:c3735cc2430df05457817f1d8fa111bbb06bd3b70cfa61e197339b5506e79c2a", + "24.04-20261120": "sha256:c3735cc2430df05457817f1d8fa111bbb06bd3b70cfa61e197339b5506e79c2a", + "8d8daef52b455416e7adcb27127e42e6a4cc74d4": "sha256:c3735cc2430df05457817f1d8fa111bbb06bd3b70cfa61e197339b5506e79c2a" } }, "desktop": { "repository": "ghcr.io/upsetdev/pyo-sandbox-images/desktop", - "digest": "sha256:2d6cd2b055fd052ce806bdc0266f12f504cfa0ca6c4440915498b78a75ed36df", - "ref": "ghcr.io/upsetdev/pyo-sandbox-images/desktop@sha256:2d6cd2b055fd052ce806bdc0266f12f504cfa0ca6c4440915498b78a75ed36df", + "digest": "sha256:c47057d8a037403344172f3a73d3370bf9bd253b6c83addc9801878c76cad5f5", + "ref": "ghcr.io/upsetdev/pyo-sandbox-images/desktop@sha256:c47057d8a037403344172f3a73d3370bf9bd253b6c83addc9801878c76cad5f5", "tags": { - "24.04": "sha256:2d6cd2b055fd052ce806bdc0266f12f504cfa0ca6c4440915498b78a75ed36df", - "24.04-20261118": "sha256:2d6cd2b055fd052ce806bdc0266f12f504cfa0ca6c4440915498b78a75ed36df", - "99c10c2d273e2f6cf083ec3168ac688caaf71b6b": "sha256:2d6cd2b055fd052ce806bdc0266f12f504cfa0ca6c4440915498b78a75ed36df" + "24.04": "sha256:c47057d8a037403344172f3a73d3370bf9bd253b6c83addc9801878c76cad5f5", + "24.04-20261120": "sha256:c47057d8a037403344172f3a73d3370bf9bd253b6c83addc9801878c76cad5f5", + "8d8daef52b455416e7adcb27127e42e6a4cc74d4": "sha256:c47057d8a037403344172f3a73d3370bf9bd253b6c83addc9801878c76cad5f5" } } } diff --git a/crates/pyo-api/assets/sandbox-images/images.json.sigstore.json b/crates/pyo-api/assets/sandbox-images/images.json.sigstore.json index d33f7038..f4cd1b0b 100644 --- a/crates/pyo-api/assets/sandbox-images/images.json.sigstore.json +++ b/crates/pyo-api/assets/sandbox-images/images.json.sigstore.json @@ -1 +1 @@ -{"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json", "verificationMaterial":{"certificate":{"rawBytes":"MIIHGjCCBqGgAwIBAgIUcDupbHsfHHkFmp5tCBFTu/KyKc8wCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYxMTE4MDIyMjU0WhcNMjYxMTE4MDIzMjU0WjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAED3IqpmqawdubqOlL+CEW+RvODuRhHeWblb/RNCbOX6Pm81DiXH7dI7NgFZCQjucufCYoAqA1moYukv8PK0lWlKOCBcAwggW8MA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAfBgNVHSMEGDAWgBTf0+nPViQRlvmo2OkoVaLGLhhkPzBqBgNVHREBAf8EYDBehlxodHRwczovL2dpdGh1Yi5jb20vdXBzZXRkZXYvcHlvLXNhbmRib3gtaW1hZ2VzLy5naXRodWIvd29ya2Zsb3dzL3JlbGVhc2UueW1sQHJlZnMvaGVhZHMvbWFpbjA5BgorBgEEAYO/MAEBBCtodHRwczovL3Rva2VuLmFjdGlvbnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tMBIGCisGAQQBg78wAQIEBHB1c2gwNgYKKwYBBAGDvzABAwQoOTljMTBjMmQyNzNlMmY2Y2YwODNlYzMxNjhhYzY4OGNhYWY3MWI2YjAVBgorBgEEAYO/MAEEBAdSZWxlYXNlMCkGCisGAQQBg78wAQUEG3Vwc2V0ZGV2L3B5by1zYW5kYm94LWltYWdlczAdBgorBgEEAYO/MAEGBA9yZWZzL2hlYWRzL21haW4wOwYKKwYBBAGDvzABCAQtDCtodHRwczovL3Rva2VuLmFjdGlvbnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tMGwGCisGAQQBg78wAQkEXgxcaHR0cHM6Ly9naXRodWIuY29tL3Vwc2V0ZGV2L3B5by1zYW5kYm94LWltYWdlcy8uZ2l0aHViL3dvcmtmbG93cy9yZWxlYXNlLnltbEByZWZzL2hlYWRzL21haW4wOAYKKwYBBAGDvzABCgQqDCg5OWMxMGMyZDI3M2UyZjZjZjA4M2VjMzE2OGFjNjg4Y2FhZjcxYjZiMB0GCisGAQQBg78wAQsEDwwNZ2l0aHViLWhvc3RlZDA+BgorBgEEAYO/MAEMBDAMLmh0dHBzOi8vZ2l0aHViLmNvbS91cHNldGRldi9weW8tc2FuZGJveC1pbWFnZXMwOAYKKwYBBAGDvzABDQQqDCg5OWMxMGMyZDI3M2UyZjZjZjA4M2VjMzE2OGFjNjg4Y2FhZjcxYjZiMB8GCisGAQQBg78wAQ4EEQwPcmVmcy9oZWFkcy9tYWluMBoGCisGAQQBg78wAQ8EDAwKMTQ2MDM3Mjg3NDArBgorBgEEAYO/MAEQBB0MG2h0dHBzOi8vZ2l0aHViLmNvbS91cHNldGRldjAYBgorBgEEAYO/MAERBAoMCDU5NzQ2Njg2MGwGCisGAQQBg78wARIEXgxcaHR0cHM6Ly9naXRodWIuY29tL3Vwc2V0ZGV2L3B5by1zYW5kYm94LWltYWdlcy8uZ2l0aHViL3dvcmtmbG93cy9yZWxlYXNlLnltbEByZWZzL2hlYWRzL21haW4wOAYKKwYBBAGDvzABEwQqDCg5OWMxMGMyZDI3M2UyZjZjZjA4M2VjMzE2OGFjNjg4Y2FhZjcxYjZiMBQGCisGAQQBg78wARQEBgwEcHVzaDBiBgorBgEEAYO/MAEVBFQMUmh0dHBzOi8vZ2l0aHViLmNvbS91cHNldGRldi9weW8tc2FuZGJveC1pbWFnZXMvYWN0aW9ucy9ydW5zLzQ0MjIxNjUwOTA5L2F0dGVtcHRzLzEwFgYKKwYBBAGDvzABFgQIDAZwdWJsaWMwWAYKKwYBBAGDvzABGARKDEhyZXBvOnVwc2V0ZGV2QDU5NzQ2Njg2L3B5by1zYW5kYm94LWltYWdlc0AxNDYwMzcyODc0OnJlZjpyZWZzL2hlYWRzL21haW4wgYkGCisGAQQB1nkCBAIEewR5AHcAdQDdPTBqxscRMmMZHhyZZzcCokpeuN48rf+HinKALynujgAAAaHsdthTAAAEAwBGMEQCICVvDpBuyjxQZDwFpIEZsu8BoilcGtDtlHaHKXWMo+6XAiAUbnw8cpuMXEwj/J9/LWHm8aMSkdFflIh62z5SIp1y0DAKBggqhkjOPQQDAwNnADBkAjB2cyzlgRDd9SLV9l3b5Ekkf6p9wcf3abpsaAtjs1uQ32Da4YRIirBkdtasFtfRpLsCMGyYgLnnZeJ5s8p/T0/9ngqWE8lxYw3aUzJezXcEy78D9Pb5qVfrq3vRyJ0qCxCyUw=="}, "tlogEntries":[{"logIndex":"3958815131", "logId":{"keyId":"wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="}, "kindVersion":{"kind":"hashedrekord", "version":"0.0.1"}, "integratedTime":"1794968574", "inclusionPromise":{"signedEntryTimestamp":"MEYCIQC7mkEeJlBNbUg1VDjh8Ps9+qhreOmL0WXZ4WpdjDmeeQIhAPSQXeTMNQ9nxa5F9PB8VV5u7JyNTYoaVA4j+tpxyNif"}, "inclusionProof":{"logIndex":"3836910869", "rootHash":"0D0aKnjH5fHknpodJcGK9+9XFAOHApcoozbMs+mx1qI=", "treeSize":"3836911028", "hashes":["1QMpeHnSoNPTA5a2N/IT/6/1iRlW8vIzHjtHOJKWCCA=", "CPOuatXLcrZtd8mW8GA33FooEIUKLnl6HZiu1jjKbyc=", "Gb88GaQoNKfB5pSVPX8UH/KyIQULRPomPDwFPA0xSmM=", "Z5STddlHQAgD3HHYPafVVr9DlzexAQfSib44GF3k1z8=", "N5vH3M8yMlzPTDO/CTtfD7SHyS1hCpLUjs1o+o20qI0=", "6aqDlvL/YevdHcgxcsZPltMlbqpvOQ2gN4jHzcDBdug=", "ry/sBkdILvGopDWgfvLjJyeR6jnMJRAcQ4iG0FmhyVg=", "Et7dlnOagf8dpAmMCtZagFWlPYE7LIP4QdgaqVyeYLg=", "wgm+myBwwcPIH69YVe2cqdstKXVsTaZJ/yvi7kFlfN8=", "vG0jSfxLklcjAtAAfr4JVafuZjxXaP1Fm+WUIM6z7EY=", "nX3GJP8Aa+jNE6VMu8qKnniJMnpu4mMF10QZAcOLM3Q=", "R0iG0gq+uBy1ttx++rzOvC0L/wRZAPPqtJulJleyVQ0=", "cSZvVVBGie0bD+f0ImODai6tBxCpRnBWCrkRM6VDkKo=", "1r/JqgYoKOXwDtCN8OCPfmZb5c5skEbHp8fF+bFqROU=", "weqBwZbwT8oUWLTr49mTfZXwg2fBFJOo1CeINc7b80E=", "9XweFtMybPSXATq/c56uIBbTsQhc3eLZqmxrLlhWX+c=", "HLmxxFvTcpxFxREJRKQ7t4vmiLAFt+axwTiLM71BE0s=", "pGLNL38fZHRQRuTPkhqzP2fMx5gxRPH/gPikPPETFpY=", "k0+Z1T6dI0Tgluh54oO/hnxtuoW22MqFIjVTPYeUJGU=", "1DaDKzrCNNBhmSdY5vFjz+NpAmxmYfYEgBCdPLrMP1A=", "xH/DCseLHr9eKoYT8qsORZK7zVdEGYWHuVtsVrD95wY="], "checkpoint":{"envelope":"rekor.sigstore.dev - 1193050959916656506\n3836911028\n0D0aKnjH5fHknpodJcGK9+9XFAOHApcoozbMs+mx1qI=\n\n— rekor.sigstore.dev wNI9ajBFAiAQDhDZVNZpTtolSj93xkbH+LSqp4VESNI1aTp7ApHU1gIhAJlm8jJQnFyMgDA6SbOksRl8YkFKLdzCmfT3KuWNlgcf\n"}}, "canonicalizedBody":"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiI0NmQzMjIxOGFiMzM2YTQzY2FiMzViYWE5OTdkZmE0ZTE0ODVkZjBkMWY1ZjdlZjAwNTgwMjg5NTI4OGJmYmEyIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FVUNJUUNMK3VwZ1duV0NoR1hKM1BJTlg0OHlSRGdRdlN4Y0J3b1dTdFdPaWF4MEFBSWdhSWRwcFNWME9iVXV3RXEvWG5laDdieTdDM0lTQ1dxLytzemVvWjI1VEFnPSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaEhha05EUW5GSFowRjNTVUpCWjBsVlkwUjFjR0pJYzJaSVNHdEdiWEExZEVOQ1JsUjFMMHQ1UzJNNGQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVWpSM1NFRlpSRlpSVVVSRmVGWjZZVmRrZW1SSE9YbGFVekZ3WW01U2JBcGpiVEZzV2tkc2FHUkhWWGRJYUdOT1RXcFplRTFVUlRSTlJFbDVUV3BWTUZkb1kwNU5hbGw0VFZSRk5FMUVTWHBOYWxVd1YycEJRVTFHYTNkRmQxbElDa3R2V2tsNmFqQkRRVkZaU1V0dldrbDZhakJFUVZGalJGRm5RVVZFTTBseGNHMXhZWGRrZFdKeFQyeE1LME5GVnl0U2RrOUVkVkpvU0dWWFlteGlMMUlLVGtOaVQxZzJVRzA0TVVScFdFZzNaRWszVG1kR1drTlJhblZqZFdaRFdXOUJjVUV4Ylc5WmRXdDJPRkJMTUd4WGJFdFBRMEpqUVhkbloxYzRUVUUwUndwQk1WVmtSSGRGUWk5M1VVVkJkMGxJWjBSQlZFSm5UbFpJVTFWRlJFUkJTMEpuWjNKQ1owVkdRbEZqUkVGNlFXWkNaMDVXU0ZOTlJVZEVRVmRuUWxSbUNqQXJibEJXYVZGU2JIWnRiekpQYTI5V1lVeEhUR2hvYTFCNlFuRkNaMDVXU0ZKRlFrRm1PRVZaUkVKbGFHeDRiMlJJVW5kamVtOTJUREprY0dSSGFERUtXV2sxYW1JeU1IWmtXRUo2V2xoU2ExcFlXWFpqU0d4MlRGaE9hR0p0VW1saU0yZDBZVmN4YUZveVZucE1lVFZ1WVZoU2IyUlhTWFprTWpsNVlUSmFjd3BpTTJSNlRETktiR0pIVm1oak1sVjFaVmN4YzFGSVNteGFiazEyWVVkV2FGcElUWFppVjBad1ltcEJOVUpuYjNKQ1owVkZRVmxQTDAxQlJVSkNRM1J2Q21SSVVuZGplbTkyVEROU2RtRXlWblZNYlVacVpFZHNkbUp1VFhWYU1td3dZVWhXYVdSWVRteGpiVTUyWW01U2JHSnVVWFZaTWpsMFRVSkpSME5wYzBjS1FWRlJRbWMzT0hkQlVVbEZRa2hDTVdNeVozZE9aMWxMUzNkWlFrSkJSMFIyZWtGQ1FYZFJiMDlVYkdwTlZFSnFUVzFSZVU1NlRteE5iVmt5V1RKWmR3cFBSRTVzV1hwTmVFNXFhR2haZWxrMFQwZE9hRmxYV1ROTlYwa3lXV3BCVmtKbmIzSkNaMFZGUVZsUEwwMUJSVVZDUVdSVFdsZDRiRmxZVG14TlEydEhDa05wYzBkQlVWRkNaemM0ZDBGUlZVVkhNMVozWXpKV01GcEhWakpNTTBJMVlua3hlbGxYTld0WmJUazBURmRzZEZsWFpHeGpla0ZrUW1kdmNrSm5SVVVLUVZsUEwwMUJSVWRDUVRsNVdsZGFla3d5YUd4WlYxSjZUREl4YUdGWE5IZFBkMWxMUzNkWlFrSkJSMFIyZWtGQ1EwRlJkRVJEZEc5a1NGSjNZM3B2ZGdwTU0xSjJZVEpXZFV4dFJtcGtSMngyWW01TmRWb3liREJoU0ZacFpGaE9iR050VG5aaWJsSnNZbTVSZFZreU9YUk5SM2RIUTJselIwRlJVVUpuTnpoM0NrRlJhMFZZWjNoallVaFNNR05JVFRaTWVUbHVZVmhTYjJSWFNYVlpNamwwVEROV2QyTXlWakJhUjFZeVRETkNOV0o1TVhwWlZ6VnJXVzA1TkV4WGJIUUtXVmRrYkdONU9IVmFNbXd3WVVoV2FVd3paSFpqYlhSdFlrYzVNMk41T1hsYVYzaHNXVmhPYkV4dWJIUmlSVUo1V2xkYWVrd3lhR3haVjFKNlRESXhhQXBoVnpSM1QwRlpTMHQzV1VKQ1FVZEVkbnBCUWtOblVYRkVRMmMxVDFkTmVFMUhUWGxhUkVrelRUSlZlVnBxV21wYWFrRTBUVEpXYWsxNlJUSlBSMFpxQ2s1cVp6UlpNa1pvV21wamVGbHFXbWxOUWpCSFEybHpSMEZSVVVKbk56aDNRVkZ6UlVSM2QwNWFNbXd3WVVoV2FVeFhhSFpqTTFKc1drUkJLMEpuYjNJS1FtZEZSVUZaVHk5TlFVVk5Ra1JCVFV4dGFEQmtTRUo2VDJrNGRsb3liREJoU0ZacFRHMU9kbUpUT1RGalNFNXNaRWRTYkdScE9YZGxWemgwWXpKR2RRcGFSMHAyWlVNeGNHSlhSbTVhV0UxM1QwRlpTMHQzV1VKQ1FVZEVkbnBCUWtSUlVYRkVRMmMxVDFkTmVFMUhUWGxhUkVrelRUSlZlVnBxV21wYWFrRTBDazB5Vm1wTmVrVXlUMGRHYWs1cVp6UlpNa1pvV21wamVGbHFXbWxOUWpoSFEybHpSMEZSVVVKbk56aDNRVkUwUlVWUmQxQmpiVlp0WTNrNWIxcFhSbXNLWTNrNWRGbFhiSFZOUW05SFEybHpSMEZSVVVKbk56aDNRVkU0UlVSQmQwdE5WRkV5VFVSTk0wMXFaek5PUkVGeVFtZHZja0puUlVWQldVOHZUVUZGVVFwQ1FqQk5SekpvTUdSSVFucFBhVGgyV2pKc01HRklWbWxNYlU1MllsTTVNV05JVG14a1IxSnNaR3BCV1VKbmIzSkNaMFZGUVZsUEwwMUJSVkpDUVc5TkNrTkVWVFZPZWxFeVRtcG5NazFIZDBkRGFYTkhRVkZSUW1jM09IZEJVa2xGV0dkNFkyRklVakJqU0UwMlRIazVibUZZVW05a1YwbDFXVEk1ZEV3elZuY0tZekpXTUZwSFZqSk1NMEkxWW5reGVsbFhOV3RaYlRrMFRGZHNkRmxYWkd4amVUaDFXakpzTUdGSVZtbE1NMlIyWTIxMGJXSkhPVE5qZVRsNVdsZDRiQXBaV0U1c1RHNXNkR0pGUW5sYVYxcDZUREpvYkZsWFVucE1NakZvWVZjMGQwOUJXVXRMZDFsQ1FrRkhSSFo2UVVKRmQxRnhSRU5uTlU5WFRYaE5SMDE1Q2xwRVNUTk5NbFY1V21wYWFscHFRVFJOTWxacVRYcEZNazlIUm1wT2FtYzBXVEpHYUZwcVkzaFphbHBwVFVKUlIwTnBjMGRCVVZGQ1p6YzRkMEZTVVVVS1FtZDNSV05JVm5waFJFSnBRbWR2Y2tKblJVVkJXVTh2VFVGRlZrSkdVVTFWYldnd1pFaENlazlwT0haYU1td3dZVWhXYVV4dFRuWmlVemt4WTBoT2JBcGtSMUpzWkdrNWQyVlhPSFJqTWtaMVdrZEtkbVZETVhCaVYwWnVXbGhOZGxsWFRqQmhWemwxWTNrNWVXUlhOWHBNZWxFd1RXcEplRTVxVlhkUFZFRTFDa3d5UmpCa1IxWjBZMGhTZWt4NlJYZEdaMWxMUzNkWlFrSkJSMFIyZWtGQ1JtZFJTVVJCV25ka1YwcHpZVmROZDFkQldVdExkMWxDUWtGSFJIWjZRVUlLUjBGU1MwUkZhSGxhV0VKMlQyNVdkMk15VmpCYVIxWXlVVVJWTlU1NlVUSk9hbWN5VEROQ05XSjVNWHBaVnpWcldXMDVORXhYYkhSWlYyUnNZekJCZUFwT1JGbDNUWHBqZVU5RVl6QlBia3BzV21wd2VWcFhXbnBNTW1oc1dWZFNla3d5TVdoaFZ6UjNaMWxyUjBOcGMwZEJVVkZDTVc1clEwSkJTVVZsZDFJMUNrRklZMEZrVVVSa1VGUkNjWGh6WTFKTmJVMWFTR2g1V2xwNlkwTnZhM0JsZFU0ME9ISm1LMGhwYmt0QlRIbHVkV3BuUVVGQllVaHpaSFJvVkVGQlFVVUtRWGRDUjAxRlVVTkpRMVoyUkhCQ2RYbHFlRkZhUkhkR2NFbEZXbk4xT0VKdmFXeGpSM1JFZEd4SVlVaExXRmROYnlzMldFRnBRVlZpYm5jNFkzQjFUUXBZUlhkcUwwbzVMMHhYU0cwNFlVMVRhMlJHWm14SmFEWXllalZUU1hBeGVUQkVRVXRDWjJkeGFHdHFUMUJSVVVSQmQwNXVRVVJDYTBGcVFqSmplWHBzQ21kU1JHUTVVMHhXT1d3ellqVkZhMnRtTm5BNWQyTm1NMkZpY0hOaFFYUnFjekYxVVRNeVJHRTBXVkpKYVhKQ2EyUjBZWE5HZEdaU2NFeHpRMDFIZVZrS1oweHVibHBsU2pWek9IQXZWREF2T1c1bmNWZEZPR3g0V1hjellWVjZTbVY2V0dORmVUYzRSRGxRWWpWeFZtWnljVE4yVW5sS01IRkRlRU41VlhjOVBRb3RMUzB0TFVWT1JDQkRSVkpVU1VaSlEwRlVSUzB0TFMwdENnPT0ifX19fQ=="}], "timestampVerificationData":{"rfc3161Timestamps":[{"signedTimestamp":"MIICyTADAgEAMIICwAYJKoZIhvcNAQcCoIICsTCCAq0CAQMxDTALBglghkgBZQMEAgEwgbcGCyqGSIb3DQEJEAEEoIGnBIGkMIGhAgEBBgkrBgEEAYO/MAIwMTANBglghkgBZQMEAgEFAAQgU8ThjHMm3xXz8za6L9RIPPxfCfHxIKHZUnhxh8Il+E4CFB9GbAf8ZFSN+SxuAJ9CNFp5siGZGA8yMDI2MTExODAyMjI1NFowAwIBAaAypDAwLjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MRUwEwYDVQQDEwxzaWdzdG9yZS10c2GgADGCAdswggHXAgEBMFEwOTEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MSAwHgYDVQQDExdzaWdzdG9yZS10c2Etc2VsZnNpZ25lZAIUOhNULwyQYe68wUMvy4qOiyojiwwwCwYJYIZIAWUDBAIBoIH8MBoGCSqGSIb3DQEJAzENBgsqhkiG9w0BCRABBDAcBgkqhkiG9w0BCQUxDxcNMjYxMTE4MDIyMjU0WjAvBgkqhkiG9w0BCQQxIgQgkQHJBDlsIvIjeSPW0Qq3YYO8pHUyn2CAEsKPzCQjvsswgY4GCyqGSIb3DQEJEAIvMX8wfTB7MHkEIIX5J7wHq2LKw7RDVsEO/IGyxog/2nq55thw2dE6zQW3MFUwPaQ7MDkxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEgMB4GA1UEAxMXc2lnc3RvcmUtdHNhLXNlbGZzaWduZWQCFDoTVC8MkGHuvMFDL8uKjosqI4sMMAoGCCqGSM49BAMCBGcwZQIwcd5giU8BvmzAHly+uyA7017M1LhG0Cuz1GTxVanmQyEIutBK1Ht3cfpdznTEAacgAjEA7oMbR3KsvhX2edgStqVyPyjAUYC2KFqhm9k8mxyOVMZ2Md8g2XFC9+3iE5lSsbEh"}]}}, "messageSignature":{"messageDigest":{"algorithm":"SHA2_256", "digest":"RtMiGKszakPKs1uqmX36ThSF3w0fX37wBYAolSiL+6I="}, "signature":"MEUCIQCL+upgWnWChGXJ3PINX48yRDgQvSxcBwoWStWOiax0AAIgaIdppSV0ObUuwEq/Xneh7by7C3ISCWq/+szeoZ25TAg="}} \ No newline at end of file +{"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json", "verificationMaterial":{"certificate":{"rawBytes":"MIIHHDCCBqKgAwIBAgIUHlqpVbD1enBLw/njzLzsH4XIOX0wCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYxMTIwMDAyNzA4WhcNMjYxMTIwMDAzNzA4WjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEb+DlDupGCXczEZo8s8gbKFFPaH2X87e8E2U+7aDqqfeH9/ugoL4c/ZoztRUgE2O+vTOHELU5AKKhY59kkft036OCBcEwggW9MA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAfBgNVHSMEGDAWgBTf0+nPViQRlvmo2OkoVaLGLhhkPzBqBgNVHREBAf8EYDBehlxodHRwczovL2dpdGh1Yi5jb20vdXBzZXRkZXYvcHlvLXNhbmRib3gtaW1hZ2VzLy5naXRodWIvd29ya2Zsb3dzL3JlbGVhc2UueW1sQHJlZnMvaGVhZHMvbWFpbjA5BgorBgEEAYO/MAEBBCtodHRwczovL3Rva2VuLmFjdGlvbnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tMBIGCisGAQQBg78wAQIEBHB1c2gwNgYKKwYBBAGDvzABAwQoOGQ4ZGFlZjUyYjQ1NTQxNmU3YWRjYjI3MTI3ZTQyZTZhNGNjNzRkNDAVBgorBgEEAYO/MAEEBAdSZWxlYXNlMCkGCisGAQQBg78wAQUEG3Vwc2V0ZGV2L3B5by1zYW5kYm94LWltYWdlczAdBgorBgEEAYO/MAEGBA9yZWZzL2hlYWRzL21haW4wOwYKKwYBBAGDvzABCAQtDCtodHRwczovL3Rva2VuLmFjdGlvbnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tMGwGCisGAQQBg78wAQkEXgxcaHR0cHM6Ly9naXRodWIuY29tL3Vwc2V0ZGV2L3B5by1zYW5kYm94LWltYWdlcy8uZ2l0aHViL3dvcmtmbG93cy9yZWxlYXNlLnltbEByZWZzL2hlYWRzL21haW4wOAYKKwYBBAGDvzABCgQqDCg4ZDhkYWVmNTJiNDU1NDE2ZTdhZGNiMjcxMjdlNDJlNmE0Y2M3NGQ0MB0GCisGAQQBg78wAQsEDwwNZ2l0aHViLWhvc3RlZDA+BgorBgEEAYO/MAEMBDAMLmh0dHBzOi8vZ2l0aHViLmNvbS91cHNldGRldi9weW8tc2FuZGJveC1pbWFnZXMwOAYKKwYBBAGDvzABDQQqDCg4ZDhkYWVmNTJiNDU1NDE2ZTdhZGNiMjcxMjdlNDJlNmE0Y2M3NGQ0MB8GCisGAQQBg78wAQ4EEQwPcmVmcy9oZWFkcy9tYWluMBoGCisGAQQBg78wAQ8EDAwKMTQ2MDM3Mjg3NDArBgorBgEEAYO/MAEQBB0MG2h0dHBzOi8vZ2l0aHViLmNvbS91cHNldGRldjAYBgorBgEEAYO/MAERBAoMCDU5NzQ2Njg2MGwGCisGAQQBg78wARIEXgxcaHR0cHM6Ly9naXRodWIuY29tL3Vwc2V0ZGV2L3B5by1zYW5kYm94LWltYWdlcy8uZ2l0aHViL3dvcmtmbG93cy9yZWxlYXNlLnltbEByZWZzL2hlYWRzL21haW4wOAYKKwYBBAGDvzABEwQqDCg4ZDhkYWVmNTJiNDU1NDE2ZTdhZGNiMjcxMjdlNDJlNmE0Y2M3NGQ0MBQGCisGAQQBg78wARQEBgwEcHVzaDBiBgorBgEEAYO/MAEVBFQMUmh0dHBzOi8vZ2l0aHViLmNvbS91cHNldGRldi9weW8tc2FuZGJveC1pbWFnZXMvYWN0aW9ucy9ydW5zLzQ0NjQ0NDMxODMyL2F0dGVtcHRzLzEwFgYKKwYBBAGDvzABFgQIDAZwdWJsaWMwWAYKKwYBBAGDvzABGARKDEhyZXBvOnVwc2V0ZGV2QDU5NzQ2Njg2L3B5by1zYW5kYm94LWltYWdlc0AxNDYwMzcyODc0OnJlZjpyZWZzL2hlYWRzL21haW4wgYoGCisGAQQB1nkCBAIEfAR6AHgAdgDdPTBqxscRMmMZHhyZZzcCokpeuN48rf+HinKALynujgAAAaH2WZYTAAAEAwBHMEUCIQCDa2qwtEeedimLnSmLVJ3Aq3mUMYYrEyChIJC2R1GHLwIgYXW5EAuIpWZw3w2RJF5A7C8apw79aUPjTJDz3cHEo9swCgYIKoZIzj0EAwMDaAAwZQIxAMA6b6WWkiRYw23Crbui+4+17hv9QkMFrAfKHP8HSxfzCbLmaehRnEvriLgK1G5o7gIwIxY7HrNt7TvlSiobGG7RV152m7KkdoSuxEiTlzz/OR+0VeX10ZuG2nb9bAu357dW"}, "tlogEntries":[{"logIndex":"4011247543", "logId":{"keyId":"wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="}, "kindVersion":{"kind":"hashedrekord", "version":"0.0.1"}, "integratedTime":"1795134431", "inclusionPromise":{"signedEntryTimestamp":"MEUCIQC7qpva4+RgZIAtWiaL3SYiogzoQ9/xUKTj5+MnodCtUAIgbo93r8e61QzqX3UJI6P0AaZZ9mV3pahn5u5ummAnuQk="}, "inclusionProof":{"logIndex":"3889343281", "rootHash":"WFf3ZY3SlOiGcY+pQXiYSdWkg1UbM55gAoAgeLQdR4c=", "treeSize":"3889345219", "hashes":["zozGx4Nj/NQE27AKA2tToMTjIA1USfmLbsBeB3sinxw=", "7a3+W0V9HoCZi9RRmx24YoYobpD6GfhAb4rrfMtXLxU=", "1b/BLtAV16f11yG4Ev4MSbJwuZF8FhOAAJqdsgz6HUg=", "gmtKcavcOApBdn4HXi0JkdXxQHGpK67nWU4IBnvjcNc=", "rkFm7NpXIeuVNdTy4EkjqbKQ2rFlj42pPXs6utXzCYM=", "Z/R6aGESuwgFOad5IsJsVwK3csGjU8sI+tG+SPvSAyI=", "jed1zDFw8L7vCFpMpABJOJ4UZ0BCrr5Sk5G8yJ4PlkE=", "pznZ60uxKKIrPkgZwnl04IOgGgfDXae/+Z08V/3qqmg=", "LUfwtTgTMMr0ikbUNvgfJEFhuI+nwWwpqhpaU1d8y0A=", "xbhrGqpyNdjXZBRbPyej6+mNnss3T6TNJsDe8NdJsmY=", "hdMce2pbDnfhoaCP0oqGmMa1bDhun8FNkjwhuO/xEIE=", "MnCpl0LvNW6DaS1uLX8LS5fex9kTI4WgUmirS1hMyDs=", "El3NstvZaRR/KQLLQ2sU1RTsH6DB/FnXABvB7C7hZ+I=", "By3jxU5t7GMBPpOA92L20KJBS+RRQSDX+fXCTu0Hp0o=", "dQamStdaFG8XXovFygk64qfG2Ag+67q3xyOaLSZ6np0=", "idEnq+jKak6kH8QTstX7G4Zn2bDM8ghXKowNxLvB3Pk=", "niMXH/4hR3MVPdm+CxNHsd9r8oczU/98PTJJth3JQhU=", "Duy4ZRTVboAR7WCFPIkOaBJ0ygOQC1dVaPRIwVGsX3I=", "Sk6oPrG3jANPhz5sn7nlY/PAHGXfWYffGH32lyhJIuk=", "RTepMdAfKu9KPurjUoAa9cZYUOabSA/sVgQFzx6Uk4k=", "svJO4LBKuKdchux4v5ePFDVO7eJ+EmJkrTkTnHs6a9o=", "pGLNL38fZHRQRuTPkhqzP2fMx5gxRPH/gPikPPETFpY=", "k0+Z1T6dI0Tgluh54oO/hnxtuoW22MqFIjVTPYeUJGU=", "1DaDKzrCNNBhmSdY5vFjz+NpAmxmYfYEgBCdPLrMP1A=", "xH/DCseLHr9eKoYT8qsORZK7zVdEGYWHuVtsVrD95wY="], "checkpoint":{"envelope":"rekor.sigstore.dev - 1193050959916656506\n3889345219\nWFf3ZY3SlOiGcY+pQXiYSdWkg1UbM55gAoAgeLQdR4c=\n\n— rekor.sigstore.dev wNI9ajBFAiB1ja2jSR+uYex3Tv/G4hJIw02Fbxt8PxpgPHqiodIH7QIhALUbEzVI1OVsiUhPRlNf4DdzR7WBe0/qL5f8a/E3PVfJ\n"}}, "canonicalizedBody":"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIyNzhiMjJjZjU1OGUyZTlmOWFhZmUyNjE1ZTU4NzdlODZkNTgwMDFiYTI2YTc2YzRjMWQyYzYyODFkY2RkZTdmIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FUUNJQ3kzVHRldlhNRXZRTFBXV2dFN3pjaENvaDA5em5NRUd1Znd2MXF6UlptWkFpQnowbXZBNFFJYmp6WEhtSDZ1eGVvZXgvSXRqUHNhRnlSVG5ISm5jTnlPUXc9PSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaElSRU5EUW5GTFowRjNTVUpCWjBsVlNHeHhjRlppUkRGbGJrSk1keTl1YW5wTWVuTklORmhKVDFnd2QwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVWpSM1NFRlpSRlpSVVVSRmVGWjZZVmRrZW1SSE9YbGFVekZ3WW01U2JBcGpiVEZzV2tkc2FHUkhWWGRJYUdOT1RXcFplRTFVU1hkTlJFRjVUbnBCTkZkb1kwNU5hbGw0VFZSSmQwMUVRWHBPZWtFMFYycEJRVTFHYTNkRmQxbElDa3R2V2tsNmFqQkRRVkZaU1V0dldrbDZhakJFUVZGalJGRm5RVVZpSzBSc1JIVndSME5ZWTNwRldtODRjemhuWWt0R1JsQmhTREpZT0RkbE9FVXlWU3NLTjJGRWNYRm1aVWc1TDNWbmIwdzBZeTlhYjNwMFVsVm5SVEpQSzNaVVQwaEZURlUxUVV0TGFGazFPV3RyWm5Rd016WlBRMEpqUlhkbloxYzVUVUUwUndwQk1WVmtSSGRGUWk5M1VVVkJkMGxJWjBSQlZFSm5UbFpJVTFWRlJFUkJTMEpuWjNKQ1owVkdRbEZqUkVGNlFXWkNaMDVXU0ZOTlJVZEVRVmRuUWxSbUNqQXJibEJXYVZGU2JIWnRiekpQYTI5V1lVeEhUR2hvYTFCNlFuRkNaMDVXU0ZKRlFrRm1PRVZaUkVKbGFHeDRiMlJJVW5kamVtOTJUREprY0dSSGFERUtXV2sxYW1JeU1IWmtXRUo2V2xoU2ExcFlXWFpqU0d4MlRGaE9hR0p0VW1saU0yZDBZVmN4YUZveVZucE1lVFZ1WVZoU2IyUlhTWFprTWpsNVlUSmFjd3BpTTJSNlRETktiR0pIVm1oak1sVjFaVmN4YzFGSVNteGFiazEyWVVkV2FGcElUWFppVjBad1ltcEJOVUpuYjNKQ1owVkZRVmxQTDAxQlJVSkNRM1J2Q21SSVVuZGplbTkyVEROU2RtRXlWblZNYlVacVpFZHNkbUp1VFhWYU1td3dZVWhXYVdSWVRteGpiVTUyWW01U2JHSnVVWFZaTWpsMFRVSkpSME5wYzBjS1FWRlJRbWMzT0hkQlVVbEZRa2hDTVdNeVozZE9aMWxMUzNkWlFrSkJSMFIyZWtGQ1FYZFJiMDlIVVRSYVIwWnNXbXBWZVZscVVURk9WRkY0VG0xVk13cFpWMUpxV1dwSk0wMVVTVE5hVkZGNVdsUmFhRTVIVG1wT2VsSnJUa1JCVmtKbmIzSkNaMFZGUVZsUEwwMUJSVVZDUVdSVFdsZDRiRmxZVG14TlEydEhDa05wYzBkQlVWRkNaemM0ZDBGUlZVVkhNMVozWXpKV01GcEhWakpNTTBJMVlua3hlbGxYTld0WmJUazBURmRzZEZsWFpHeGpla0ZrUW1kdmNrSm5SVVVLUVZsUEwwMUJSVWRDUVRsNVdsZGFla3d5YUd4WlYxSjZUREl4YUdGWE5IZFBkMWxMUzNkWlFrSkJSMFIyZWtGQ1EwRlJkRVJEZEc5a1NGSjNZM3B2ZGdwTU0xSjJZVEpXZFV4dFJtcGtSMngyWW01TmRWb3liREJoU0ZacFpGaE9iR050VG5aaWJsSnNZbTVSZFZreU9YUk5SM2RIUTJselIwRlJVVUpuTnpoM0NrRlJhMFZZWjNoallVaFNNR05JVFRaTWVUbHVZVmhTYjJSWFNYVlpNamwwVEROV2QyTXlWakJhUjFZeVRETkNOV0o1TVhwWlZ6VnJXVzA1TkV4WGJIUUtXVmRrYkdONU9IVmFNbXd3WVVoV2FVd3paSFpqYlhSdFlrYzVNMk41T1hsYVYzaHNXVmhPYkV4dWJIUmlSVUo1V2xkYWVrd3lhR3haVjFKNlRESXhhQXBoVnpSM1QwRlpTMHQzV1VKQ1FVZEVkbnBCUWtOblVYRkVRMmMwV2tSb2ExbFhWbTFPVkVwcFRrUlZNVTVFUlRKYVZHUm9Xa2RPYVUxcVkzaE5hbVJzQ2s1RVNteE9iVVV3V1RKTk0wNUhVVEJOUWpCSFEybHpSMEZSVVVKbk56aDNRVkZ6UlVSM2QwNWFNbXd3WVVoV2FVeFhhSFpqTTFKc1drUkJLMEpuYjNJS1FtZEZSVUZaVHk5TlFVVk5Ra1JCVFV4dGFEQmtTRUo2VDJrNGRsb3liREJoU0ZacFRHMU9kbUpUT1RGalNFNXNaRWRTYkdScE9YZGxWemgwWXpKR2RRcGFSMHAyWlVNeGNHSlhSbTVhV0UxM1QwRlpTMHQzV1VKQ1FVZEVkbnBCUWtSUlVYRkVRMmMwV2tSb2ExbFhWbTFPVkVwcFRrUlZNVTVFUlRKYVZHUm9DbHBIVG1sTmFtTjRUV3BrYkU1RVNteE9iVVV3V1RKTk0wNUhVVEJOUWpoSFEybHpSMEZSVVVKbk56aDNRVkUwUlVWUmQxQmpiVlp0WTNrNWIxcFhSbXNLWTNrNWRGbFhiSFZOUW05SFEybHpSMEZSVVVKbk56aDNRVkU0UlVSQmQwdE5WRkV5VFVSTk0wMXFaek5PUkVGeVFtZHZja0puUlVWQldVOHZUVUZGVVFwQ1FqQk5SekpvTUdSSVFucFBhVGgyV2pKc01HRklWbWxNYlU1MllsTTVNV05JVG14a1IxSnNaR3BCV1VKbmIzSkNaMFZGUVZsUEwwMUJSVkpDUVc5TkNrTkVWVFZPZWxFeVRtcG5NazFIZDBkRGFYTkhRVkZSUW1jM09IZEJVa2xGV0dkNFkyRklVakJqU0UwMlRIazVibUZZVW05a1YwbDFXVEk1ZEV3elZuY0tZekpXTUZwSFZqSk1NMEkxWW5reGVsbFhOV3RaYlRrMFRGZHNkRmxYWkd4amVUaDFXakpzTUdGSVZtbE1NMlIyWTIxMGJXSkhPVE5qZVRsNVdsZDRiQXBaV0U1c1RHNXNkR0pGUW5sYVYxcDZUREpvYkZsWFVucE1NakZvWVZjMGQwOUJXVXRMZDFsQ1FrRkhSSFo2UVVKRmQxRnhSRU5uTkZwRWFHdFpWMVp0Q2s1VVNtbE9SRlV4VGtSRk1scFVaR2hhUjA1cFRXcGplRTFxWkd4T1JFcHNUbTFGTUZreVRUTk9SMUV3VFVKUlIwTnBjMGRCVVZGQ1p6YzRkMEZTVVVVS1FtZDNSV05JVm5waFJFSnBRbWR2Y2tKblJVVkJXVTh2VFVGRlZrSkdVVTFWYldnd1pFaENlazlwT0haYU1td3dZVWhXYVV4dFRuWmlVemt4WTBoT2JBcGtSMUpzWkdrNWQyVlhPSFJqTWtaMVdrZEtkbVZETVhCaVYwWnVXbGhOZGxsWFRqQmhWemwxWTNrNWVXUlhOWHBNZWxFd1RtcFJNRTVFVFhoUFJFMTVDa3d5UmpCa1IxWjBZMGhTZWt4NlJYZEdaMWxMUzNkWlFrSkJSMFIyZWtGQ1JtZFJTVVJCV25ka1YwcHpZVmROZDFkQldVdExkMWxDUWtGSFJIWjZRVUlLUjBGU1MwUkZhSGxhV0VKMlQyNVdkMk15VmpCYVIxWXlVVVJWTlU1NlVUSk9hbWN5VEROQ05XSjVNWHBaVnpWcldXMDVORXhYYkhSWlYyUnNZekJCZUFwT1JGbDNUWHBqZVU5RVl6QlBia3BzV21wd2VWcFhXbnBNTW1oc1dWZFNla3d5TVdoaFZ6UjNaMWx2UjBOcGMwZEJVVkZDTVc1clEwSkJTVVZtUVZJMkNrRklaMEZrWjBSa1VGUkNjWGh6WTFKTmJVMWFTR2g1V2xwNlkwTnZhM0JsZFU0ME9ISm1LMGhwYmt0QlRIbHVkV3BuUVVGQllVZ3lWMXBaVkVGQlFVVUtRWGRDU0UxRlZVTkpVVU5FWVRKeGQzUkZaV1ZrYVcxTWJsTnRURlpLTTBGeE0yMVZUVmxaY2tWNVEyaEpTa015VWpGSFNFeDNTV2RaV0ZjMVJVRjFTUXB3VjFwM00zY3lVa3BHTlVFM1F6aGhjSGMzT1dGVlVHcFVTa1I2TTJOSVJXODVjM2REWjFsSlMyOWFTWHBxTUVWQmQwMUVZVUZCZDFwUlNYaEJUVUUyQ21JMlYxZHJhVkpaZHpJelEzSmlkV2tyTkNzeE4yaDJPVkZyVFVaeVFXWkxTRkE0U0ZONFpucERZa3h0WVdWb1VtNUZkbkpwVEdkTE1VYzFiemRuU1hjS1NYaFpOMGh5VG5RM1ZIWnNVMmx2WWtkSE4xSldNVFV5YlRkTGEyUnZVM1Y0UldsVWJIcDZMMDlTS3pCV1pWZ3hNRnAxUnpKdVlqbGlRWFV6TlRka1Z3b3RMUzB0TFVWT1JDQkRSVkpVU1VaSlEwRlVSUzB0TFMwdENnPT0ifX19fQ=="}], "timestampVerificationData":{"rfc3161Timestamps":[{"signedTimestamp":"MIICyTADAgEAMIICwAYJKoZIhvcNAQcCoIICsTCCAq0CAQMxDTALBglghkgBZQMEAgEwgbcGCyqGSIb3DQEJEAEEoIGnBIGkMIGhAgEBBgkrBgEEAYO/MAIwMTANBglghkgBZQMEAgEFAAQguTIPr8g9F8f0eXVkNRZo1x7Li1vH2YbqWqHzuF+kbdUCFDcd8ZG6Fc0ty7Hcm/nBl1xnpriKGA8yMDI2MTEyMDAwMjcwOFowAwIBAaAypDAwLjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MRUwEwYDVQQDEwxzaWdzdG9yZS10c2GgADGCAdswggHXAgEBMFEwOTEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MSAwHgYDVQQDExdzaWdzdG9yZS10c2Etc2VsZnNpZ25lZAIUOhNULwyQYe68wUMvy4qOiyojiwwwCwYJYIZIAWUDBAIBoIH8MBoGCSqGSIb3DQEJAzENBgsqhkiG9w0BCRABBDAcBgkqhkiG9w0BCQUxDxcNMjYxMTIwMDAyNzA4WjAvBgkqhkiG9w0BCQQxIgQgV9lmWbQtNBH3TSty6IgRJ0Pg41YdSliJHVF4jEhdoSEwgY4GCyqGSIb3DQEJEAIvMX8wfTB7MHkEIIX5J7wHq2LKw7RDVsEO/IGyxog/2nq55thw2dE6zQW3MFUwPaQ7MDkxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEgMB4GA1UEAxMXc2lnc3RvcmUtdHNhLXNlbGZzaWduZWQCFDoTVC8MkGHuvMFDL8uKjosqI4sMMAoGCCqGSM49BAMCBGcwZQIxAMhHxbCmNDTKX8zRb0E8i/WWydoS+a2mMae6rZMRrleXmcd444lbStjw6gbwuwclsgIwDNGQ5ems1+T7mHj1+xW3V4Ok8gMaoqNrHvt5ST/Y7o9yGRsQIiOJy9KGpGwCyUB7"}]}}, "messageSignature":{"messageDigest":{"algorithm":"SHA2_256", "digest":"J4siz1WOLp+ar+JhXlh36G1YABuianbEwdLGKB3N3n8="}, "signature":"MEQCICy3TtevXMEvQLPWWgE7zchCoh09znMEGufwv1qzRZmZAiBz0mvA4QIbjzXHmH6uxeoex/ItjPsaFyRTnHJncNyOQw=="}} \ No newline at end of file diff --git a/crates/pyo-api/migrations/0020_agent_certificates.sql b/crates/pyo-api/migrations/0020_agent_certificates.sql new file mode 100644 index 00000000..5ec682d2 --- /dev/null +++ b/crates/pyo-api/migrations/0020_agent_certificates.sql @@ -0,0 +1,6 @@ +-- Agents with a client certificate (agent_tls.rs): the serial of the +-- cluster's current certificate and the one before it (through a renewal), +-- and the connect token already used to enroll (a token enrolls once). +ALTER TABLE pyo.clusters ADD COLUMN agent_cert_serial text; +ALTER TABLE pyo.clusters ADD COLUMN agent_cert_prev_serial text; +ALTER TABLE pyo.clusters ADD COLUMN agent_token_used_hash text; diff --git a/crates/pyo-api/migrations/0021_agent_keys.sql b/crates/pyo-api/migrations/0021_agent_keys.sql new file mode 100644 index 00000000..9cff92a0 --- /dev/null +++ b/crates/pyo-api/migrations/0021_agent_keys.sql @@ -0,0 +1,19 @@ +-- Signed agent requests (agent_auth.rs): each agent's public keys (a day +-- each, the newest and the one it replaced), and the nonces of requests +-- seen in the last minutes, so none is accepted twice. +CREATE TABLE pyo.agent_keys ( + id text PRIMARY KEY, + cluster_id text NOT NULL REFERENCES pyo.clusters (id) ON DELETE CASCADE, + -- Ed25519, base64url. + public_key text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz NOT NULL, + revoked_at timestamptz +); +CREATE INDEX agent_keys_cluster_idx ON pyo.agent_keys (cluster_id); + +CREATE TABLE pyo.agent_nonces ( + nonce text PRIMARY KEY, + seen_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX agent_nonces_seen_idx ON pyo.agent_nonces (seen_at); diff --git a/crates/pyo-api/migrations/0022_row_security.sql b/crates/pyo-api/migrations/0022_row_security.sql new file mode 100644 index 00000000..ce7f0b75 --- /dev/null +++ b/crates/pyo-api/migrations/0022_row_security.sql @@ -0,0 +1,78 @@ +-- Row security on team_id (rls.rs), behind the API's own team checks. +-- +-- Pyo connects as the owner of these tables, which row security doesn't +-- hold back: migrations, agents, builders, webhooks and background jobs +-- see every row as before, and so does the release before this one. A +-- request made for a person or an API key lowers its transaction to the +-- pyo_team role, with the teams it may see in pyo.team_ids. There the +-- policies below show and accept only those teams' rows. + +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'pyo_team') THEN + CREATE ROLE pyo_team NOLOGIN; + END IF; + -- Pyo's own login switches to it (SET ROLE) in a request's transaction. + -- A superuser already may. + IF NOT pg_has_role(current_user, 'pyo_team', + CASE WHEN current_setting('server_version_num')::int >= 160000 THEN 'SET' ELSE 'MEMBER' END) THEN + EXECUTE format('GRANT pyo_team TO %I', current_user); + END IF; +END +$$; + +GRANT USAGE ON SCHEMA pyo TO pyo_team; +GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA pyo TO pyo_team; +GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA pyo TO pyo_team; +-- Tables later migrations add, as these are. +ALTER DEFAULT PRIVILEGES IN SCHEMA pyo GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO pyo_team; +ALTER DEFAULT PRIVILEGES IN SCHEMA pyo GRANT USAGE, SELECT, UPDATE ON SEQUENCES TO pyo_team; + +-- The teams the transaction may see. NULL (none) when it set none. +CREATE FUNCTION pyo.team_scope() RETURNS text[] + LANGUAGE sql STABLE AS $$ SELECT string_to_array(nullif(current_setting('pyo.team_ids', true), ''), ',') $$; + +-- Tables with a team_id: secrets, credentials and what services run with. +DO $$ +DECLARE + t text; +BEGIN + FOREACH t IN ARRAY ARRAY[ + 'alert_channels', 'backup_databases', 'backup_store_logins', 'build_jobs', + 'certificates', 'cloudflare_accounts', 'data_keys', 'databases', + 'deploy_hooks', 'deployments', 'dns_records', 'git_connections', + 'github_installations', 'integrations', 'origin_pull_certificates', + 'registry_logins', 'registry_tokens', 'secret_stores', 'services', + 'team_backup_settings' + ] LOOP + EXECUTE format('ALTER TABLE pyo.%I ENABLE ROW LEVEL SECURITY', t); + EXECUTE format( + 'CREATE POLICY team_rows ON pyo.%I TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope()))', t); + END LOOP; +END +$$; + +-- Tables without one go by what they belong to. +ALTER TABLE pyo.deployment_logs ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.deployment_logs TO pyo_team + USING (deployment_id IN (SELECT id FROM pyo.deployments WHERE team_id = ANY (pyo.team_scope()))) + WITH CHECK (deployment_id IN (SELECT id FROM pyo.deployments WHERE team_id = ANY (pyo.team_scope()))); + +ALTER TABLE pyo.git_webhooks ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.git_webhooks TO pyo_team + USING (connection_id IN (SELECT id FROM pyo.git_connections WHERE team_id = ANY (pyo.team_scope()))) + WITH CHECK (connection_id IN (SELECT id FROM pyo.git_connections WHERE team_id = ANY (pyo.team_scope()))); + +-- An agent's keys, and the commands it gets (with what services run +-- with): its cluster's team. +ALTER TABLE pyo.agent_keys ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.agent_keys TO pyo_team + USING (cluster_id IN (SELECT id FROM pyo.clusters WHERE team_id = ANY (pyo.team_scope()))) + WITH CHECK (cluster_id IN (SELECT id FROM pyo.clusters WHERE team_id = ANY (pyo.team_scope()))); + +ALTER TABLE pyo.commands ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.commands TO pyo_team + USING (cluster_id IN (SELECT id FROM pyo.clusters WHERE team_id = ANY (pyo.team_scope()))) + WITH CHECK (cluster_id IN (SELECT id FROM pyo.clusters WHERE team_id = ANY (pyo.team_scope()))); diff --git a/crates/pyo-api/migrations/0023_component_keys.sql b/crates/pyo-api/migrations/0023_component_keys.sql new file mode 100644 index 00000000..e48a2ba3 --- /dev/null +++ b/crates/pyo-api/migrations/0023_component_keys.sql @@ -0,0 +1,7 @@ +-- Keys of a cluster's other components (agent_auth.rs): its builders and +-- its pyo-static sign their requests too, with keys the agent makes in the +-- cluster and registers. 'agent' is the agent's own. A builder's key goes +-- with the builder. +ALTER TABLE pyo.agent_keys ADD COLUMN component text NOT NULL DEFAULT 'agent'; +ALTER TABLE pyo.agent_keys ADD COLUMN builder_id text REFERENCES pyo.builders (id) ON DELETE CASCADE; +CREATE INDEX agent_keys_builder_idx ON pyo.agent_keys (builder_id) WHERE builder_id IS NOT NULL; diff --git a/crates/pyo-api/migrations/0024_connect_tokens.sql b/crates/pyo-api/migrations/0024_connect_tokens.sql new file mode 100644 index 00000000..787a50a0 --- /dev/null +++ b/crates/pyo-api/migrations/0024_connect_tokens.sql @@ -0,0 +1,10 @@ +-- Connect commands carry a connect token of their own (install.rs), not +-- the agent's credential: it installs the agent once, within an hour, for +-- the team and cluster it was made for. Fetching the agent's manifest with +-- it makes the agent's own token there, which no command shows. It's used +-- once that agent reports in. +ALTER TABLE pyo.clusters ADD COLUMN connect_token_hash text; +ALTER TABLE pyo.clusters ADD COLUMN connect_token_team text; +ALTER TABLE pyo.clusters ADD COLUMN connect_token_expires_at timestamptz; +ALTER TABLE pyo.clusters ADD COLUMN connect_token_used_at timestamptz; +CREATE INDEX clusters_connect_token_idx ON pyo.clusters (connect_token_hash) WHERE connect_token_hash IS NOT NULL; diff --git a/crates/pyo-api/migrations/0025_agent_updates.sql b/crates/pyo-api/migrations/0025_agent_updates.sql new file mode 100644 index 00000000..eac2624f --- /dev/null +++ b/crates/pyo-api/migrations/0025_agent_updates.sql @@ -0,0 +1,7 @@ +-- A team's agent updates on a hosted Pyo (updates.rs `hosted_agents`): +-- 'auto' moves its clusters' agents to Pyo's version on their own, +-- 'manual' leaves it to the team, from each cluster's page. +ALTER TABLE pyo.teams ADD COLUMN agent_updates text NOT NULL DEFAULT 'auto' CHECK (agent_updates IN ('auto', 'manual')); +-- Each cluster's agent updates, newest first (the cluster's page, and +-- which clusters are due). +CREATE INDEX commands_update_agent_idx ON pyo.commands (cluster_id, created_at DESC) WHERE command->>'kind' = 'update_agent'; diff --git a/crates/pyo-api/migrations/0026_build_log_cleanup.sql b/crates/pyo-api/migrations/0026_build_log_cleanup.sql new file mode 100644 index 00000000..2fc30918 --- /dev/null +++ b/crates/pyo-api/migrations/0026_build_log_cleanup.sql @@ -0,0 +1,3 @@ +-- Build and deploy logs are kept 90 days (jobs.rs `prune`): the oldest +-- lines, found by their time. +CREATE INDEX deployment_logs_at_idx ON pyo.deployment_logs (at); diff --git a/crates/pyo-api/migrations/0027_tailscale_in_clusters.sql b/crates/pyo-api/migrations/0027_tailscale_in_clusters.sql new file mode 100644 index 00000000..e4f59517 --- /dev/null +++ b/crates/pyo-api/migrations/0027_tailscale_in_clusters.sql @@ -0,0 +1,37 @@ +-- Tailscale goes through each cluster's agent (tailscale.rs). The cluster +-- keeps its own OAuth client, as a Secret in its pyo-system. Pyo keeps +-- only what isn't secret: the client's ID and hint, the tailnet's suffix, +-- Pyo's own names there and what the last sync said. +ALTER TABLE pyo.clusters ADD COLUMN tailscale jsonb; + +-- The cluster's names on its tailnet (Tailscale Services). Per cluster: +-- each cluster's tailnet is its own, so two clusters can both have a +-- "blog". Replaces pyo.tailnet_services, whose name was unique across the +-- installation. That table stays until the release before this one stops +-- reading it. +CREATE TABLE pyo.cluster_tailnet_names ( + cluster_id text NOT NULL REFERENCES pyo.clusters (id) ON DELETE CASCADE, + name text NOT NULL, + kind text NOT NULL CHECK (kind IN ('dashboard', 'registry', 'sandboxes', 'domain')), + -- Its VIPs, IPv4 then IPv6. + addrs text[] NOT NULL DEFAULT '{}', + -- Why it isn't working, as people read it ("Taken on your tailnet"). + error text, + -- Deleted on the tailnet: its servers take it off. + retired_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (cluster_id, name) +); + +INSERT INTO pyo.cluster_tailnet_names (cluster_id, name, kind, addrs, error, retired_at, created_at, updated_at) +SELECT cluster_id, name, kind, addrs, error, retired_at, created_at, updated_at + FROM pyo.tailnet_services WHERE cluster_id IS NOT NULL; + +-- A sandbox server is reached through the agent of the cluster whose +-- tailnet it joined: Pyo itself may be on no tailnet (Pyo Cloud). +ALTER TABLE pyo.sandbox_servers ADD COLUMN via_cluster text REFERENCES pyo.clusters (id) ON DELETE SET NULL; +-- The installation's servers so far joined Pyo's own tailnet, the one its +-- own cluster is on. +UPDATE pyo.sandbox_servers SET via_cluster = (SELECT id FROM pyo.clusters WHERE same_cluster ORDER BY created_at LIMIT 1) + WHERE via_cluster IS NULL; diff --git a/crates/pyo-api/migrations/0028_previews.sql b/crates/pyo-api/migrations/0028_previews.sql new file mode 100644 index 00000000..8fd9e412 --- /dev/null +++ b/crates/pyo-api/migrations/0028_previews.sql @@ -0,0 +1,108 @@ +-- Preview environments (previews/): each open pull request (GitHub) or +-- merge request (GitLab) gets a copy of the services that turned previews +-- on, built from its head and removed when it closes. + +-- A preview's copy is a service of its own, next to the one it previews +-- (same project and cluster, its own name): deploys, logs and routes work +-- as for any service. Gone with it. +ALTER TABLE pyo.services ADD COLUMN preview_of text REFERENCES pyo.services (id) ON DELETE CASCADE; +CREATE INDEX services_preview_of_idx ON pyo.services (preview_of) WHERE preview_of IS NOT NULL; + +-- A cluster's preview domain: {"domain", "certificateId", "certificate": +-- {"state", "error", "at"}, "record": {"id", "content", "state"}}. +-- Previews there get "." (a wildcard record points at it). +ALTER TABLE pyo.clusters ADD COLUMN preview_domain jsonb; + +-- What an installation of the GitHub App may do, as GitHub last said: +-- previews need pull requests, deployments and checks. +ALTER TABLE pyo.github_installations ADD COLUMN permissions jsonb; +ALTER TABLE pyo.github_installations ADD COLUMN events text[]; +ALTER TABLE pyo.github_installations ADD COLUMN checked_at timestamptz; + +-- A GitLab webhook that sends merge request events too (made before +-- previews, it only sent pushes, and is made again). +ALTER TABLE pyo.git_webhooks ADD COLUMN merge_requests boolean NOT NULL DEFAULT false; + +-- Pull requests and merge requests of repositories whose services have +-- previews on, as Pyo last saw them, with what the bot left on them. +CREATE TABLE pyo.pull_requests ( + id text PRIMARY KEY, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + provider text NOT NULL CHECK (provider IN ('github', 'gitlab')), + -- Whose: the GitHub installation, or the team's GitLab connection. + installation_id bigint, + connection_id text REFERENCES pyo.git_connections (id) ON DELETE CASCADE, + -- The installation's id or the connection's: one row per PR of each. + source text NOT NULL, + -- "owner/repo" or "group/sub/project", lowercased. + repo text NOT NULL, + number bigint NOT NULL, + title text NOT NULL DEFAULT '', + url text NOT NULL DEFAULT '', + author text NOT NULL DEFAULT '', + head_ref text NOT NULL DEFAULT '', + head_sha text NOT NULL DEFAULT '', + base_ref text NOT NULL DEFAULT '', + -- From another repository (a fork). + fork boolean NOT NULL DEFAULT false, + labels text[] NOT NULL DEFAULT '{}', + state text NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'closed', 'merged')), + -- The last push (a new head): previews idle since are removed. + pushed_at timestamptz NOT NULL DEFAULT now(), + -- The bot's comment (GitHub) or note (GitLab), and a hash of its text. + comment_id bigint, + comment_hash text, + -- The check run (GitHub) or commit status (GitLab) on the head. + check_id bigint, + check_sha text, + check_hash text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + closed_at timestamptz, + UNIQUE (team_id, provider, source, repo, number) +); +CREATE INDEX pull_requests_open_idx ON pyo.pull_requests (state) WHERE state = 'open'; + +-- A service's preview for a pull request. +CREATE TABLE pyo.previews ( + id text PRIMARY KEY, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + pull_id text NOT NULL REFERENCES pyo.pull_requests (id) ON DELETE CASCADE, + -- The service previewed, and its copy while there is one. + service_id text NOT NULL REFERENCES pyo.services (id) ON DELETE CASCADE, + preview_service_id text REFERENCES pyo.services (id) ON DELETE SET NULL, + -- The copy's name ("web-pr-42") and URL host: kept for the PR's life. + name text NOT NULL, + hostname text, + -- waiting (over the limit) | active (has a copy) | failed (couldn't + -- start one) | removed + state text NOT NULL CHECK (state IN ('waiting', 'active', 'failed', 'removed')), + -- Why it waits, failed or was removed, as people read it. + message text, + -- closed | merged | idle | label | settings | user | fork | limit + removed_reason text, + -- The commit last deployed (or tried), and its deployment. + sha text NOT NULL DEFAULT '', + deployment_id text, + -- GitHub's deployment for `sha` ("View deployment"), and what was last + -- reported on it; GitLab's environment and deployment. + remote_deployment_id bigint, + remote_deployment_sha text, + remote_environment_id bigint, + reported text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (pull_id, service_id) +); +CREATE INDEX previews_service_idx ON pyo.previews (service_id); +CREATE INDEX previews_copy_idx ON pyo.previews (preview_service_id) WHERE preview_service_id IS NOT NULL; + +-- Row security (rls.rs), as for the other team tables. +ALTER TABLE pyo.pull_requests ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.pull_requests TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope())); +ALTER TABLE pyo.previews ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.previews TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope())); diff --git a/crates/pyo-api/migrations/0029_cli_login_requests.sql b/crates/pyo-api/migrations/0029_cli_login_requests.sql new file mode 100644 index 00000000..3b344060 --- /dev/null +++ b/crates/pyo-api/migrations/0029_cli_login_requests.sql @@ -0,0 +1,26 @@ +-- `pyo login` (cli.rs): the CLI asks Pyo for a sign-in and polls for the +-- answer, so the browser never has to reach the CLI on localhost. The +-- terminal shows a short code that the person types on the dashboard to +-- approve it, then the CLI trades its verifier for an API key. Requests +-- last 10 minutes and work once. Only hashes of the code and verifier +-- are stored. Replaces pyo.cli_logins, which the release before this one +-- still uses: it goes in a later release. +CREATE TABLE pyo.cli_login_requests ( + -- In the approval page's link. Not a secret: the code and the verifier are. + id text PRIMARY KEY, + -- sha256 of the verifier only the CLI knows. + challenge text NOT NULL, + -- sha256 of the code the terminal shows. + code_hash text NOT NULL, + -- The computer's name and the CLI's version and OS, as the CLI sent them. + name text NOT NULL, + client text NOT NULL, + -- Days the key lasts (NULL: it never expires). + key_days integer, + status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'denied')), + -- Who approved it. + user_id text REFERENCES pyo.users (id) ON DELETE CASCADE, + -- Wrong codes typed. Five end the request. + tries integer NOT NULL DEFAULT 0, + expires_at timestamptz NOT NULL +); diff --git a/crates/pyo-api/migrations/0030_source_uploads.sql b/crates/pyo-api/migrations/0030_source_uploads.sql new file mode 100644 index 00000000..4ba2216d --- /dev/null +++ b/crates/pyo-api/migrations/0030_source_uploads.sql @@ -0,0 +1,41 @@ +-- Folders sent with `pyo deploy` (source_uploads.rs): the CLI sends a +-- gzipped tar in parts, Pyo keeps them here until a builder in the +-- service's cluster has fetched the archive, then deletes them. In Pyo's +-- own database so every web replica (and Pyo Cloud) sees them. Never kept +-- longer than a few hours. +CREATE TABLE pyo.source_uploads ( + id text PRIMARY KEY, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + -- The archive's size in bytes and hex SHA-256, as the CLI said. + size bigint NOT NULL CHECK (size > 0), + sha256 text NOT NULL, + -- What it holds and where it came from, for the deployment's page. + files integer NOT NULL DEFAULT 0, + folder text NOT NULL DEFAULT '', + machine text NOT NULL DEFAULT '', + created_by text NOT NULL, + -- uploading: parts arriving. ready: every part here and checked. + -- used: a deployment builds it (deployment_id). + state text NOT NULL DEFAULT 'uploading' CHECK (state IN ('uploading', 'ready', 'used')), + deployment_id text, + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz NOT NULL +); +CREATE INDEX source_uploads_team_idx ON pyo.source_uploads (team_id); +CREATE INDEX source_uploads_deployment_idx ON pyo.source_uploads (deployment_id) WHERE deployment_id IS NOT NULL; + +-- The archive, in order (n from 0), each part the same size but the last. +CREATE TABLE pyo.source_upload_parts ( + upload_id text NOT NULL REFERENCES pyo.source_uploads (id) ON DELETE CASCADE, + n integer NOT NULL CHECK (n >= 0), + data bytea NOT NULL, + PRIMARY KEY (upload_id, n) +); +-- Large and short-lived: no compression attempt on the gzip inside. +ALTER TABLE pyo.source_upload_parts ALTER COLUMN data SET STORAGE EXTERNAL; + +-- Row security (rls.rs), as for the other team tables. +ALTER TABLE pyo.source_uploads ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.source_uploads TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope())); diff --git a/crates/pyo-api/migrations/0031_team_analytics_months.sql b/crates/pyo-api/migrations/0031_team_analytics_months.sql new file mode 100644 index 00000000..3f97ee12 --- /dev/null +++ b/crates/pyo-api/migrations/0031_team_analytics_months.sql @@ -0,0 +1,5 @@ +-- A team may keep its analytics shorter than the installation does +-- (retention.rs): 3, 6 or 12 months. Null keeps them as long as the +-- installation (Settings › Observability). Once a day the rows older than +-- a team's months are removed from the analytics tables. +ALTER TABLE pyo.teams ADD COLUMN analytics_months smallint CHECK (analytics_months IN (3, 6, 12)); diff --git a/crates/pyo-api/migrations/0032_row_security_rest.sql b/crates/pyo-api/migrations/0032_row_security_rest.sql new file mode 100644 index 00000000..a41e9974 --- /dev/null +++ b/crates/pyo-api/migrations/0032_row_security_rest.sql @@ -0,0 +1,106 @@ +-- Row security (rls.rs) on the team tables 0022 left out, and on the +-- tables that belong to a cluster, service, database or upload. As in +-- 0022, Pyo's own login (the owner) sees every row: only a request's +-- transaction lowered to pyo_team is held to its teams. + +-- The teams a person (or an API key limited to some teams) may see, read +-- as the owner: members has row security now, and a transaction already +-- lowered would see only the teams it had. +CREATE FUNCTION pyo.member_team_ids(p_user text, p_key_teams text[]) RETURNS text + LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pyo AS $$ + SELECT coalesce(string_agg(team_id, ','), '') FROM pyo.members + WHERE user_id = p_user AND status = 'active' AND (p_key_teams IS NULL OR team_id = ANY (p_key_teams)) +$$; +REVOKE ALL ON FUNCTION pyo.member_team_ids(text, text[]) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION pyo.member_team_ids(text, text[]) TO pyo_team; + +-- Tables with a team_id. +DO $$ +DECLARE + t text; +BEGIN + FOREACH t IN ARRAY ARRAY[ + 'activity', 'alert_state', 'backups', 'builders', 'cloud_servers', + 'clusters', 'database_import_uploads', 'database_imports', + 'firewall_rules', 'members', 'platform_imports', 'projects', + 'registry_repos', 'sandbox_limits', 'sandbox_usage', 'sandboxes', + 'static_sites', 'terminal_sessions', 'volumes', 'waf_rules' + ] LOOP + EXECUTE format('ALTER TABLE pyo.%I ENABLE ROW LEVEL SECURITY', t); + EXECUTE format( + 'CREATE POLICY team_rows ON pyo.%I TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope()))', t); + END LOOP; +END +$$; + +-- Sandbox servers and templates of the installation (team_id NULL) are +-- every team's to use, and only its admin's to change (outside a team's +-- scope). +DO $$ +DECLARE + t text; +BEGIN + FOREACH t IN ARRAY ARRAY['sandbox_servers', 'sandbox_templates'] LOOP + EXECUTE format('ALTER TABLE pyo.%I ENABLE ROW LEVEL SECURITY', t); + EXECUTE format( + 'CREATE POLICY team_rows ON pyo.%I TO pyo_team + USING (team_id IS NULL OR team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope()))', t); + END LOOP; +END +$$; + +-- What a cluster's agent reports and keeps: its cluster's team. +DO $$ +DECLARE + t text; +BEGIN + FOREACH t IN ARRAY ARRAY[ + 'servers', 'server_tags', 'cluster_bundles', 'cluster_tailnet_names', + 'tailnet_services', 'deleted_databases', 'deleted_volumes' + ] LOOP + EXECUTE format('ALTER TABLE pyo.%I ENABLE ROW LEVEL SECURITY', t); + EXECUTE format( + 'CREATE POLICY team_rows ON pyo.%I TO pyo_team + USING (cluster_id IN (SELECT id FROM pyo.clusters WHERE team_id = ANY (pyo.team_scope()))) + WITH CHECK (cluster_id IN (SELECT id FROM pyo.clusters WHERE team_id = ANY (pyo.team_scope())))', t); + END LOOP; +END +$$; + +-- A service's cron runs, with their output. +ALTER TABLE pyo.cron_runs ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.cron_runs TO pyo_team + USING (service_id IN (SELECT id FROM pyo.services WHERE team_id = ANY (pyo.team_scope()))) + WITH CHECK (service_id IN (SELECT id FROM pyo.services WHERE team_id = ANY (pyo.team_scope()))); + +-- A database's events and the services it's linked to. +DO $$ +DECLARE + t text; +BEGIN + FOREACH t IN ARRAY ARRAY['database_events', 'database_links'] LOOP + EXECUTE format('ALTER TABLE pyo.%I ENABLE ROW LEVEL SECURITY', t); + EXECUTE format( + 'CREATE POLICY team_rows ON pyo.%I TO pyo_team + USING (database_id IN (SELECT id FROM pyo.databases WHERE team_id = ANY (pyo.team_scope()))) + WITH CHECK (database_id IN (SELECT id FROM pyo.databases WHERE team_id = ANY (pyo.team_scope())))', t); + END LOOP; +END +$$; + +-- A folder sent with `pyo deploy`. +ALTER TABLE pyo.source_upload_parts ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.source_upload_parts TO pyo_team + USING (upload_id IN (SELECT id FROM pyo.source_uploads WHERE team_id = ANY (pyo.team_scope()))) + WITH CHECK (upload_id IN (SELECT id FROM pyo.source_uploads WHERE team_id = ANY (pyo.team_scope()))); + +-- A sandbox server's edge certificate: its key is changed only for the +-- team's own servers. The installation's servers' (shared by every team) +-- can be read, like the servers. +ALTER TABLE pyo.sandbox_edges ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.sandbox_edges TO pyo_team + USING (server_id IN (SELECT id FROM pyo.sandbox_servers)) + WITH CHECK (server_id IN (SELECT id FROM pyo.sandbox_servers WHERE team_id = ANY (pyo.team_scope()))); diff --git a/crates/pyo-api/migrations/0033_rate_limit_lockout.sql b/crates/pyo-api/migrations/0033_rate_limit_lockout.sql new file mode 100644 index 00000000..c65b9e00 --- /dev/null +++ b/crates/pyo-api/migrations/0033_rate_limit_lockout.sql @@ -0,0 +1,5 @@ +-- Rate limits that lock out for longer each time (ratelimit.rs): a key +-- that used up its window again within a day waits twice as long as the +-- last time, up to its limit's cap. A successful sign-in starts over. +ALTER TABLE pyo.rate_limits ADD COLUMN strikes integer NOT NULL DEFAULT 0; +ALTER TABLE pyo.rate_limits ADD COLUMN blocked_until timestamptz; diff --git a/crates/pyo-api/migrations/0034_team_security.sql b/crates/pyo-api/migrations/0034_team_security.sql new file mode 100644 index 00000000..fc40c4b0 --- /dev/null +++ b/crates/pyo-api/migrations/0034_team_security.sql @@ -0,0 +1,120 @@ +-- Team security (twofactor.rs, audit.rs): two-factor authentication with +-- an authenticator app, teams that require it, and the audit log. + +-- An account's authenticator app. The secret is sealed with the +-- installation's key: it belongs to the account, not to a team. While +-- `enabled_at` is NULL it's being set up and isn't asked for yet. +CREATE TABLE pyo.user_totp ( + user_id text PRIMARY KEY REFERENCES pyo.users (id) ON DELETE CASCADE, + secret_sealed text NOT NULL, + enabled_at timestamptz, + -- The last time step a code was accepted for: each code works once. + last_step bigint NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- One-time recovery codes, for when the app is lost. Only their sha256 is +-- kept, and a used one stays marked so it can't work again. +CREATE TABLE pyo.recovery_codes ( + user_id text NOT NULL REFERENCES pyo.users (id) ON DELETE CASCADE, + code_hash text NOT NULL, + used_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, code_hash) +); + +-- A sign-in that got the password (or a sign-in link) right and waits for +-- the code. Single use, a few minutes long, a few tries. +CREATE TABLE pyo.sign_in_challenges ( + token_hash text PRIMARY KEY, + user_id text NOT NULL REFERENCES pyo.users (id) ON DELETE CASCADE, + -- 'password' or 'link': how the first step was made. + method text NOT NULL, + attempts integer NOT NULL DEFAULT 0, + expires_at timestamptz NOT NULL +); +CREATE INDEX sign_in_challenges_user_idx ON pyo.sign_in_challenges (user_id); + +-- A sign-in link made on the server Pyo runs on (pyo-reset-login) also +-- turns off two-factor: whoever has the server has everything anyway. +ALTER TABLE pyo.sign_in_links ADD COLUMN clears_two_factor boolean NOT NULL DEFAULT false; + +-- A team can require two-factor for its members, and chooses what its +-- audit log keeps of addresses: 'full', 'anonymized' or 'none'. +ALTER TABLE pyo.teams ADD COLUMN require_two_factor boolean NOT NULL DEFAULT false; +ALTER TABLE pyo.teams ADD COLUMN audit_ips text NOT NULL DEFAULT 'full' + CHECK (audit_ips IN ('full', 'anonymized', 'none')); + +-- Who did what in a team, when and from where. Written with the team's +-- activity and for security events (sign-ins, two-factor, API keys). +-- Kept a year on Pyo Cloud, as the installation's setting says when +-- self-hosted (pyo.settings 'security'). +CREATE TABLE pyo.audit_events ( + id text PRIMARY KEY, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + at timestamptz NOT NULL DEFAULT now(), + -- 'auth.sign_in', 'api_key.created', 'service.deployed', ... + action text NOT NULL, + title text NOT NULL, + -- The account, kept as it was when the account is gone. + actor_id text, + actor_name text NOT NULL, + actor_email text NOT NULL DEFAULT '', + -- How: 'dashboard', 'api' (an API key), 'mcp' (an assistant) or 'system'. + via text NOT NULL CHECK (via IN ('dashboard', 'api', 'mcp', 'system')), + -- The API key's or assistant's name. + key_name text, + -- As the team's audit_ips allowed when it was written. + ip text, + user_agent text NOT NULL DEFAULT '', + target jsonb NOT NULL DEFAULT '{}', + -- 'ok', or 'failed' (a wrong password or code). + outcome text NOT NULL DEFAULT 'ok' CHECK (outcome IN ('ok', 'failed')) +); +CREATE INDEX audit_events_team_idx ON pyo.audit_events (team_id, at DESC); +CREATE INDEX audit_events_actor_idx ON pyo.audit_events (team_id, actor_id, at DESC); +CREATE INDEX audit_events_at_idx ON pyo.audit_events (at); + +-- Row security (rls.rs): a team's request sees and adds its own team's +-- entries, and never changes or removes one. Pruning runs as the owner. +ALTER TABLE pyo.audit_events ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_read ON pyo.audit_events FOR SELECT TO pyo_team + USING (team_id = ANY (pyo.team_scope())); +CREATE POLICY team_write ON pyo.audit_events FOR INSERT TO pyo_team + WITH CHECK (team_id = ANY (pyo.team_scope())); + +-- Whether an account still has to set up two-factor before it may use +-- anything but its own profile: the installation requires it of everyone +-- (pyo.settings 'security'), or of Pyo Cloud's staff (its admins, when +-- `p_hosted`). +CREATE FUNCTION pyo.needs_two_factor(p_user text, p_hosted boolean) RETURNS boolean + LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pyo AS $$ + SELECT NOT EXISTS (SELECT 1 FROM pyo.user_totp t WHERE t.user_id = p_user AND t.enabled_at IS NOT NULL) + AND ((p_hosted AND coalesce((SELECT u.is_admin FROM pyo.users u WHERE u.id = p_user), false)) + OR coalesce((SELECT (s.value->>'requireTwoFactor')::boolean FROM pyo.settings s WHERE s.key = 'security'), false)) +$$; +REVOKE ALL ON FUNCTION pyo.needs_two_factor(text, boolean) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION pyo.needs_two_factor(text, boolean) TO pyo_team; + +-- The teams a person (or an API key limited to some teams) may see: as +-- before, without the teams that require two-factor while the account +-- has none, and without any while the account must set it up first. +CREATE FUNCTION pyo.member_team_ids(p_user text, p_key_teams text[], p_hosted boolean) RETURNS text + LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pyo AS $$ + SELECT coalesce(string_agg(m.team_id, ','), '') + FROM pyo.members m JOIN pyo.teams t ON t.id = m.team_id + WHERE m.user_id = p_user AND m.status = 'active' + AND (p_key_teams IS NULL OR m.team_id = ANY (p_key_teams)) + AND NOT pyo.needs_two_factor(p_user, p_hosted) + AND (NOT t.require_two_factor + OR EXISTS (SELECT 1 FROM pyo.user_totp u WHERE u.user_id = p_user AND u.enabled_at IS NOT NULL)) +$$; +REVOKE ALL ON FUNCTION pyo.member_team_ids(text, text[], boolean) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION pyo.member_team_ids(text, text[], boolean) TO pyo_team; + +-- The release before this one asks with two arguments while it still +-- serves: it gets the same answer (staff are a Pyo Cloud matter). +CREATE OR REPLACE FUNCTION pyo.member_team_ids(p_user text, p_key_teams text[]) RETURNS text + LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pyo AS $$ + SELECT pyo.member_team_ids(p_user, p_key_teams, false) +$$; diff --git a/crates/pyo-api/migrations/0035_log_follows.sql b/crates/pyo-api/migrations/0035_log_follows.sql new file mode 100644 index 00000000..d456d315 --- /dev/null +++ b/crates/pyo-api/migrations/0035_log_follows.sql @@ -0,0 +1,19 @@ +-- Following a service's logs (logfollow.rs): one signed command opens a +-- follow, and the cluster's agent dials back to send new lines. A row +-- says which API replica holds the reader's socket. Rows go after a day. +CREATE TABLE pyo.log_follows ( + id text PRIMARY KEY, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + service_id text NOT NULL REFERENCES pyo.services (id) ON DELETE CASCADE, + -- host:port of the API replica the reader is connected to. + relay text, + created_at timestamptz NOT NULL DEFAULT now(), + ended_at timestamptz +); +CREATE INDEX log_follows_created_idx ON pyo.log_follows (created_at); + +-- Row security (rls.rs): a team's request sees and adds its own rows. +ALTER TABLE pyo.log_follows ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.log_follows TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope())); diff --git a/crates/pyo-api/migrations/0036_relay_tickets.sql b/crates/pyo-api/migrations/0036_relay_tickets.sql new file mode 100644 index 00000000..197d6fb8 --- /dev/null +++ b/crates/pyo-api/migrations/0036_relay_tickets.sql @@ -0,0 +1,13 @@ +-- An agent's socket (a terminal's or a log follow's) that lands on another +-- web replica than the one holding the other end is forwarded there +-- (terminal.rs `hand_over`). The replica that checked the agent leaves a +-- ticket here, good once for a minute, and the other one takes it. Only +-- Pyo itself reads them: no team policy. +CREATE TABLE pyo.relay_tickets ( + -- SHA-256 of the ticket, never the ticket. + hash text PRIMARY KEY, + session_id text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX relay_tickets_created_idx ON pyo.relay_tickets (created_at); +ALTER TABLE pyo.relay_tickets ENABLE ROW LEVEL SECURITY; diff --git a/crates/pyo-api/migrations/0037_commands_held.sql b/crates/pyo-api/migrations/0037_commands_held.sql new file mode 100644 index 00000000..4b32910f --- /dev/null +++ b/crates/pyo-api/migrations/0037_commands_held.sql @@ -0,0 +1,5 @@ +-- A hosted team whose plan paused or ended has commands held back +-- (gate.rs). When it was first held back since its last sync: once its +-- plan allows commands again, its clusters get their syncs sent once +-- more, and this goes back to NULL. +ALTER TABLE pyo.teams ADD COLUMN commands_held_at timestamptz; diff --git a/crates/pyo-api/migrations/0038_database_log_follows.sql b/crates/pyo-api/migrations/0038_database_log_follows.sql new file mode 100644 index 00000000..3157c9cf --- /dev/null +++ b/crates/pyo-api/migrations/0038_database_log_follows.sql @@ -0,0 +1,4 @@ +-- A database's live logs are followed too (logfollow.rs): a follow is a +-- service's or a database's. +ALTER TABLE pyo.log_follows ALTER COLUMN service_id DROP NOT NULL; +ALTER TABLE pyo.log_follows ADD COLUMN database_id text REFERENCES pyo.databases (id) ON DELETE CASCADE; diff --git a/crates/pyo-api/src/agent.rs b/crates/pyo-api/src/agent.rs index 28c1c873..d87c86ae 100644 --- a/crates/pyo-api/src/agent.rs +++ b/crates/pyo-api/src/agent.rs @@ -28,7 +28,8 @@ pub fn routes() -> Router { .route("/commands", get(poll)) .route("/commands/{id}", post(command_result)) .route("/deployments/{id}/progress", post(progress)) - .route("/access-logs", post(access_logs)) + .route("/traffic-totals", post(traffic_totals)) + .route("/traffic-context", get(traffic_context)) .route("/host-metrics", post(host_metrics)) .route("/certificates/{id}", get(certificate)) .route("/registry-logins/{id}", get(registry_login)) @@ -47,6 +48,47 @@ impl FromRequestParts for AgentCluster { parts: &mut Parts, state: &AppState, ) -> Result { + // A signed request (agent_auth.rs): the cluster its key belongs to, + // when it's the agent's own key (a builder's or pyo-static's isn't). + if let Some(v) = parts.extensions.get::() { + if !v.is_agent() { + return Err(ApiError::new(StatusCode::FORBIDDEN, "This key isn't the agent's.")); + } + return Ok(AgentCluster { id: v.cluster_id.clone(), team_id: v.team_id.clone() }); + } + // Over the mTLS endpoint: the cluster its certificate names, while + // that certificate is the cluster's current (or the one before it, + // through a renewal). Never from the request. + if let Some(peer) = parts.extensions.get::() + && let Some(cert) = &peer.cert + { + let id = crate::agent_tls::identity(cert) + .ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "This certificate names no cluster."))?; + let ok: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.clusters WHERE id = $1 AND team_id = $2 AND $3 IN (agent_cert_serial, agent_cert_prev_serial))", + ) + .bind(&id.cluster) + .bind(&id.team) + .bind(&id.serial) + .fetch_one(&state.db) + .await?; + if !ok { + return Err(ApiError::new( + StatusCode::UNAUTHORIZED, + "This certificate was replaced or revoked. Run the cluster's connect command again.", + )); + } + return Ok(AgentCluster { id: id.cluster, team_id: id.team }); + } + if crate::agent_auth::refuse_tokens() { + return Err(ApiError::new( + StatusCode::UNAUTHORIZED, + match crate::agent_auth::mode() { + crate::agent_auth::Mode::Signed => "Agents sign their requests here.", + _ => "Agents connect with a client certificate here.", + }, + )); + } let token = parts .headers .get("authorization") @@ -68,45 +110,124 @@ impl FromRequestParts for AgentCluster { } } -/// An uploaded certificate with its key, for a cluster of the team that owns it. +/// An uploaded certificate a domain of a service on this cluster uses, with +/// its key. Its team has to own the cluster too. +const CLUSTER_CERTIFICATE: &str = "SELECT c.chain_pem, c.key_sealed FROM pyo.certificates c + WHERE c.id = $1 AND c.team_id = $2 + AND EXISTS (SELECT 1 FROM pyo.clusters k WHERE k.id = $3 AND k.team_id = c.team_id) + AND EXISTS (SELECT 1 FROM pyo.services a, jsonb_array_elements(coalesce(a.spec->'domains', '[]')) d + WHERE a.cluster_id = $3 AND a.team_id = c.team_id AND d->>'certificateId' = c.id)"; + +/// A registry login a deployment on this cluster pulls with, with its +/// password. Its team has to own the cluster too. +const CLUSTER_REGISTRY_LOGIN: &str = "UPDATE pyo.registry_logins l SET last_used_at = now() + WHERE l.id = $1 AND l.team_id = $2 + AND EXISTS (SELECT 1 FROM pyo.clusters k WHERE k.id = $3 AND k.team_id = l.team_id) + AND EXISTS (SELECT 1 FROM pyo.deployments d + WHERE d.cluster_id = $3 AND d.team_id = l.team_id AND d.spec->>'pullLoginId' = l.id) + RETURNING l.host, l.username, l.secret_sealed"; + +/// An uploaded certificate with its key, for a cluster that uses it. async fn certificate( State(s): State, cluster: AgentCluster, + headers: axum::http::HeaderMap, Path(id): Path, -) -> ApiResult> { - let row: Option<(String, String)> = sqlx::query_as( - "SELECT chain_pem, key_sealed FROM pyo.certificates WHERE id = $1 AND team_id = $2", - ) - .bind(&id) - .bind(&cluster.team_id) - .fetch_optional(&s.db) - .await?; +) -> ApiResult> { + let row: Option<(String, String)> = sqlx::query_as(CLUSTER_CERTIFICATE) + .bind(&id) + .bind(&cluster.team_id) + .bind(&cluster.id) + .fetch_optional(&s.db) + .await?; let (certificate, sealed) = row.ok_or_else(|| ApiError::not_found("Certificate"))?; - let private_key = s.sealer.open(&sealed).map_err(ApiError::from)?; - Ok(Json(pyo_proto::TlsCertificate { + let private_key = crate::vault::get() + .open_credential(&s.sealer, &sealed) + .await?; + let reply = json!(pyo_proto::TlsCertificate { certificate, private_key, - })) + }); + Ok(Json(signed_reply(&cluster.id, &headers, reply).await)) } -/// A registry login with its password, for a cluster of the team that owns it. +/// A registry login with its password, for a cluster that pulls with it. async fn registry_login( State(s): State, cluster: AgentCluster, + headers: axum::http::HeaderMap, Path(id): Path, -) -> ApiResult> { - let row: Option<(String, String, String)> = sqlx::query_as("UPDATE pyo.registry_logins SET last_used_at = now() WHERE id = $1 AND team_id = $2 RETURNING host, username, secret_sealed") +) -> ApiResult> { + let row: Option<(String, String, String)> = sqlx::query_as(CLUSTER_REGISTRY_LOGIN) .bind(&id) .bind(&cluster.team_id) + .bind(&cluster.id) .fetch_optional(&s.db) .await?; let (host, username, sealed) = row.ok_or_else(|| ApiError::not_found("Registry login"))?; - let password = s.sealer.open(&sealed).map_err(ApiError::from)?; - Ok(Json(pyo_proto::RegistryLogin { + let password = crate::vault::get() + .open_credential(&s.sealer, &sealed) + .await?; + let reply = json!(pyo_proto::RegistryLogin { host, username, password, - })) + }); + Ok(Json(signed_reply(&cluster.id, &headers, reply).await)) +} + +/// A reply the agent acts on, with the signer's signature when this Pyo +/// has a signer (pyo-proto `signing`, `pyoreply1`): bound to the cluster +/// and to the nonce the agent sent with its request. The plain fields stay +/// beside it. When it can't be signed (no nonce, the signer down) it goes +/// out as it is, and an agent that requires signatures acts on nothing in it. +pub(crate) async fn signed_reply( + cluster_id: &str, + headers: &axum::http::HeaderMap, + reply: Value, +) -> Value { + match crate::command_signer() { + Some(signer) => sign_reply_with(signer.as_ref(), cluster_id, headers, reply).await, + None => reply, + } +} + +async fn sign_reply_with( + signer: &dyn crate::CommandSigner, + cluster_id: &str, + headers: &axum::http::HeaderMap, + mut reply: Value, +) -> Value { + let Some(nonce) = headers + .get(pyo_proto::REPLY_NONCE_HEADER) + .and_then(|v| v.to_str().ok()) + .filter(|n| pyo_proto::valid_reply_nonce(n)) + else { + return reply; + }; + let json = reply.to_string(); + let item = crate::ReplyToSign { + nonce: nonce.to_owned(), + sha256: sha256_hex(&json), + }; + match signer.sign_reply(cluster_id, &item).await { + Ok(sig) if sig.refused.is_none() => { + reply["signed"] = json!(pyo_proto::SignedReplyWire { + claims: sig.claims, + sig: sig.sig, + kid: sig.kid, + reply: json, + delegation: sig.delegation, + }); + } + Ok(sig) => { + tracing::warn!(cluster = %cluster_id, why = sig.refused.unwrap_or_default(), "the signer refused a reply") + } + Err(e) => { + tracing::warn!(cluster = %cluster_id, error = %format!("{e:#}"), "couldn't sign a reply") + } + } + reply } fn storage_class_json(sc: &pyo_proto::StorageClassReport) -> Value { @@ -154,6 +275,7 @@ const SERVICE_STATUS: &str = "UPDATE pyo.services SET runtime = $3, async fn heartbeat( State(s): State, cluster: AgentCluster, + headers: axum::http::HeaderMap, Json(hb): Json, ) -> ApiResult> { if hb.protocol != PROTOCOL_VERSION { @@ -227,6 +349,8 @@ async fn heartbeat( "wafActive": caps.waf_active, // Whether this agent can update Pyo and itself (updates.rs). "updates": hb.updates, + // Its builders and pyo-static sign their requests (agent_auth.rs). + "componentKeys": hb.component_keys, // What the agent may do there, and the cluster owner's switches. "agentScope": hb.scope, // Whether its install is this Pyo's (install.rs). @@ -240,6 +364,7 @@ async fn heartbeat( .bind(&cluster.id) .fetch_one(&mut *tx) .await?; + crate::install::agent_reported(&mut tx, &cluster.id).await?; sqlx::query( "UPDATE pyo.clusters SET status = $2, version = $3, agent_version = $4, capabilities = $5, workloads = $6, same_cluster = $7, last_seen_at = now() WHERE id = $1", ) @@ -254,9 +379,10 @@ async fn heartbeat( .await?; name_from_host(&mut tx, &cluster.id, &cluster.team_id, &hb.servers).await?; // The server Pyo runs on, connecting for the first time: the team's - // first builder goes there. + // first builder goes there. Where every cluster keeps its own images + // (Pyo Cloud), a team's first cluster to connect gets it. let builder_added = was == "pending" - && same_cluster + && (same_cluster || crate::deploy::in_cluster_registries()) && crate::builders::first_on_this_server( &mut tx, &s.config, @@ -587,9 +713,8 @@ 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?; - Ok(Json( - 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 }), - )) + 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 }); + Ok(Json(signed_reply(&cluster.id, &headers, reply).await)) } /// Which GPU servers are kept for GPU work. A server's own setting wins; @@ -695,8 +820,19 @@ async fn poll( // runs commands on the same object in the order it gets them. rows.sort_by_key(|r| r.2); if !rows.is_empty() { + // A hosted team's plan paused or ended: only reads and + // removals go out, the rest fail unsigned (gate.rs). + let held = crate::gate::held_back(&s.db, &cluster.team_id).await?; let mut out = Vec::with_capacity(rows.len()); for (id, mut command, _) in rows { + if let Some(why) = &held + && !crate::gate::allowed(command["kind"].as_str().unwrap_or("")) + { + undeliverable(&s, &id, &command, why).await; + // Sent again once the plan allows it (gate.rs `resume`). + crate::gate::mark_held(&s.db, &cluster.team_id).await; + continue; + } let opened = async { crate::vault::get().open_env(&mut command).await?; crate::teambackup::open_command(&mut command).await?; @@ -715,7 +851,7 @@ async fn poll( continue; } match serde_json::from_value(command.clone()) { - Ok(command) => out.push(CommandEnvelope { id, command }), + Ok(command) => out.push(CommandEnvelope { id, command, signed: None }), Err(e) => { tracing::error!(%id, error = %e, "unreadable command"); undeliverable(&s, &id, &command, &format!("Pyo couldn't read it: {e}")) @@ -723,6 +859,9 @@ async fn poll( } } } + if let Some(signer) = crate::command_signer() { + out = sign_all(&s, signer.as_ref(), &cluster.id, out).await?; + } return Ok(Json(out)); } let left = deadline.saturating_duration_since(tokio::time::Instant::now()); @@ -735,6 +874,76 @@ async fn poll( } } +/// Has the signer sign each command for this cluster, in order. When it +/// can't, the commands go back to the queue and the agent asks again. +/// A command the signer refuses fails, with its reason; the rest go out. +async fn sign_all( + s: &AppState, + signer: &dyn crate::CommandSigner, + cluster_id: &str, + out: Vec, +) -> ApiResult> { + if out.is_empty() { + return Ok(out); + } + let mut items = Vec::with_capacity(out.len()); + let mut jsons = Vec::with_capacity(out.len()); + for e in out.iter() { + let json = serde_json::to_string(&e.command).map_err(anyhow::Error::from)?; + let kind = serde_json::from_str::(&json) + .ok() + .and_then(|v| v["kind"].as_str().map(str::to_owned)) + .unwrap_or_default(); + let command = crate::SIGNER_CHECKS.contains(&kind.as_str()).then(|| json.clone()); + items.push(crate::ToSign { + id: e.id.clone(), + kind, + sha256: sha256_hex(&json), + command, + }); + jsons.push(json); + } + match signer.sign(cluster_id, &items).await { + Ok(sigs) if sigs.len() == out.len() => { + let mut signed = Vec::with_capacity(out.len()); + for ((mut e, sig), json) in out.into_iter().zip(sigs).zip(jsons) { + if let Some(why) = sig.refused { + tracing::warn!(cluster = %cluster_id, id = %e.id, %why, "the signer refused a command"); + let command: Value = serde_json::from_str(&json).unwrap_or(Value::Null); + undeliverable(s, &e.id, &command, &format!("Pyo's signer refused it: {why}")).await; + continue; + } + e.signed = Some(pyo_proto::SignedCommandWire { + claims: sig.claims, + sig: sig.sig, + kid: sig.kid, + command: json, + delegation: sig.delegation, + }); + signed.push(e); + } + Ok(signed) + } + other => { + let why = match other { + Ok(_) => "the signer signed a different number of commands".to_owned(), + Err(e) => format!("{e:#}"), + }; + tracing::error!(cluster = %cluster_id, error = %why, "couldn't sign commands; they go back to the queue"); + let ids: Vec<&str> = out.iter().map(|e| e.id.as_str()).collect(); + sqlx::query("UPDATE pyo.commands SET status = 'pending', sent_at = NULL, sent_to = NULL WHERE cluster_id = $1 AND id = ANY($2) AND status = 'sent'") + .bind(cluster_id) + .bind(&ids) + .execute(&s.db) + .await?; + Err(ApiError::new( + StatusCode::SERVICE_UNAVAILABLE, + "Commands can't be signed right now.", + )) + } + } +} + async fn command_result( State(s): State, cluster: AgentCluster, @@ -759,6 +968,20 @@ async fn command_result( if command["kind"] == json!("backup") { crate::teambackup::finished(&mut tx, &command, &r).await?; } + // A Tailscale token or client secret, or a sandbox call's token: no + // more use for it, so it isn't kept, even sealed. + let mut wiped = command.clone(); + if crate::teambackup::wipe_command(&mut wiped) { + sqlx::query("UPDATE pyo.commands SET command = $3 WHERE id = $1 AND cluster_id = $2") + .bind(&id) + .bind(&cluster.id) + .bind(&wiped) + .execute(&mut *tx) + .await?; + } + if command["kind"] == json!("tailscale_sync") { + crate::tailscale::synced(&mut tx, &cluster.id, &id, &r).await?; + } if command["kind"] == json!("refresh_install") { crate::install::answered(&mut tx, &id, &cluster.id).await?; } @@ -875,24 +1098,29 @@ async fn progress( Ok(Json(json!({ "ok": true }))) } -/// The gateway's access log lines from the cluster's Vector, one JSON object per -/// line (or a JSON array). See observability.rs for what's kept. -async fn access_logs( +/// A cluster's traffic totals, from its traffic store through its agent +/// (totals.rs): finished minutes per host and proxied port. Raw requests +/// stay in the cluster. +async fn traffic_totals( State(s): State, cluster: AgentCluster, - body: String, + Json(batch): Json, ) -> ApiResult> { - let lines: Vec = if body.trim_start().starts_with('[') { - serde_json::from_str(&body).map_err(|_| ApiError::bad_request("Expected JSON lines."))? - } else { - body.lines() - .filter(|l| !l.trim().is_empty()) - .filter_map(|l| serde_json::from_str(l).ok()) - .collect() - }; - let received = lines.len(); - let stored = s.observability.ingest(&cluster.id, lines).await?; - Ok(Json(json!({ "received": received, "stored": stored }))) + let stored = s.observability.ingest_totals(&cluster.id, &batch).await?; + Ok(Json(json!({ "stored": stored }))) +} + +/// What the cluster's traffic store needs from Pyo: its services' hosts +/// and ports, their firewalls, the IP setting and the team's limits. +/// Signed like every answer the agent acts on. +async fn traffic_context( + State(s): State, + cluster: AgentCluster, + headers: axum::http::HeaderMap, +) -> ApiResult> { + let ctx = crate::totals::context(&s.db, &cluster.id, &cluster.team_id).await?; + let reply = serde_json::to_value(ctx).map_err(anyhow::Error::from)?; + Ok(Json(signed_reply(&cluster.id, &headers, reply).await)) } /// Each server's load, disk I/O and network from the cluster's Vector @@ -974,6 +1202,43 @@ async fn undeliverable(s: &AppState, id: &str, command: &Value, why: &str) { { let _ = tx.commit().await; } + // A system bundle's install or removal: not under way any more, so + // the next sync of it sends it again. + if matches!( + command["kind"].as_str(), + Some("apply_bundle" | "remove_bundle") + ) && let Ok(cluster) = + sqlx::query_scalar::<_, String>("SELECT cluster_id FROM pyo.commands WHERE id = $1") + .bind(id) + .fetch_one(&s.db) + .await + && let Ok(mut tx) = s.db.begin().await + && crate::bundles::finished(&mut tx, &cluster, id, command, false, Some(why)) + .await + .is_ok() + { + let _ = tx.commit().await; + } + // A deployment shows why it didn't happen. + if command["kind"] == json!("deploy") + && let Some(deployment) = command["deploymentId"].as_str() + && let Ok(cluster) = + sqlx::query_scalar::<_, String>("SELECT cluster_id FROM pyo.commands WHERE id = $1") + .bind(id) + .fetch_one(&s.db) + .await + { + let p = DeploymentProgress { + status: "failed".into(), + failure: Some(pyo_proto::Failure { + stage: "applying".into(), + reason: "NotSent".into(), + message: why.to_owned(), + }), + ..Default::default() + }; + let _ = deploy::apply_progress(s, &cluster, deployment, p).await; + } // A volume's restore, move or growth shows why it didn't happen. if matches!( command["kind"].as_str(), @@ -1580,3 +1845,431 @@ mod name_tests { .unwrap(); } } + +#[cfg(test)] +mod lookup_tests { + use super::*; + + /// Against a throwaway Postgres: a cluster gets a certificate only when + /// a domain of a service on it uses it, and a registry login only when + /// a deployment on it pulls with it. Another cluster of the same team + /// gets neither, and another team's cluster even less. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn certificates_and_registry_logins_stay_with_their_cluster() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + let run = crate::ids::random_string(8); + let (team, other) = (format!("team_l{run}"), format!("team_o{run}")); + let (here, there, theirs) = ( + format!("cl_h{run}"), + format!("cl_t{run}"), + format!("cl_o{run}"), + ); + let (crt, rgl) = (format!("crt_{run}"), format!("rgl_{run}")); + let q = |sql: &'static str| sqlx::query(sql); + for t in [&team, &other] { + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(t) + .execute(&db) + .await + .unwrap(); + } + for (c, t) in [(&here, &team), (&there, &team), (&theirs, &other)] { + q("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash) VALUES ($1, $2, $1, $1)").bind(c).bind(t).execute(&db).await.unwrap(); + } + q("INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, 'p', $1)") + .bind(format!("prj_{run}")) + .bind(&team) + .execute(&db) + .await + .unwrap(); + let spec = json!({ "domains": [{ "id": "dom_1", "hostname": "shop.example.com", "tlsMode": "custom", "certificateId": crt }] }); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec) VALUES ($1, $2, $3, $4, 'web', $5)").bind(format!("svc_{run}")).bind(&team).bind(format!("prj_{run}")).bind(&here).bind(&spec).execute(&db).await.unwrap(); + q("INSERT INTO pyo.deployments (id, team_id, project_id, service_id, cluster_id, status, data, spec) VALUES ($1, $2, $3, $4, $5, 'succeeded', '{}', $6)").bind(format!("dpl_{run}")).bind(&team).bind(format!("prj_{run}")).bind(format!("svc_{run}")).bind(&here).bind(json!({ "pullLoginId": rgl })).execute(&db).await.unwrap(); + q("INSERT INTO pyo.certificates (id, team_id, name, hostnames, issuer, not_before, not_after, fingerprint, chain_pem, key_sealed) VALUES ($1, $2, $1, '{}', 'x', now(), now(), 'f', 'pem', 'key')").bind(&crt).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.registry_logins (id, team_id, host, username, secret_sealed) VALUES ($1, $2, 'ghcr.io', 'u', 'sealed')").bind(&rgl).bind(&team).execute(&db).await.unwrap(); + + let gets = |cluster: &str, cluster_team: &str| { + let (db, cluster, cluster_team, crt, rgl) = ( + db.clone(), + cluster.to_owned(), + cluster_team.to_owned(), + crt.clone(), + rgl.clone(), + ); + async move { + let cert: Option<(String, String)> = sqlx::query_as(CLUSTER_CERTIFICATE) + .bind(&crt) + .bind(&cluster_team) + .bind(&cluster) + .fetch_optional(&db) + .await + .unwrap(); + let login: Option<(String, String, String)> = + sqlx::query_as(CLUSTER_REGISTRY_LOGIN) + .bind(&rgl) + .bind(&cluster_team) + .bind(&cluster) + .fetch_optional(&db) + .await + .unwrap(); + (cert.is_some(), login.is_some()) + } + }; + assert_eq!(gets(&here, &team).await, (true, true)); + assert_eq!( + gets(&there, &team).await, + (false, false), + "another cluster of the team" + ); + assert_eq!( + gets(&theirs, &other).await, + (false, false), + "another team's cluster" + ); + assert_eq!( + gets(&theirs, &team).await, + (false, false), + "a cluster the team doesn't own" + ); + + for t in [&team, &other] { + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(t) + .execute(&db) + .await + .unwrap(); + } + } +} + +#[cfg(test)] +mod reply_tests { + use super::*; + use pyo_proto::signing::{REPLY_TTL_MS, ReplyClaims, Signer, TrustedKeys}; + + /// A signer here, as cloud-signer signs replies. + struct Local(Signer); + + impl crate::CommandSigner for Local { + fn sign<'a>(&'a self, _: &'a str, _: &'a [crate::ToSign]) -> futures::future::BoxFuture<'a, anyhow::Result>> { + Box::pin(async { Ok(vec![]) }) + } + fn sign_reply<'a>(&'a self, cluster_id: &'a str, r: &'a crate::ReplyToSign) -> futures::future::BoxFuture<'a, anyhow::Result> { + Box::pin(async move { + let now = pyo_proto::now_ms() as u64; + let claims = ReplyClaims { v: 1, cluster: cluster_id.into(), nonce: r.nonce.clone(), iat: now, exp: now + REPLY_TTL_MS, sha256: r.sha256.clone() }; + let (claims, sig) = self.0.sign_reply(&claims); + Ok(crate::Signature { claims, sig, kid: self.0.kid().into(), refused: None, delegation: None }) + }) + } + fn public_keys(&self) -> String { + self.0.public_key() + } + } + + fn headers(nonce: &str) -> axum::http::HeaderMap { + let mut h = axum::http::HeaderMap::new(); + h.insert(pyo_proto::REPLY_NONCE_HEADER, nonce.parse().unwrap()); + h + } + + #[tokio::test] + async fn replies_are_signed_for_the_cluster_and_the_request() { + let signer = Local(Signer::from_pkcs8(&Signer::generate_pkcs8().unwrap()).unwrap()); + let keys = TrustedKeys::parse(&crate::CommandSigner::public_keys(&signer)).unwrap(); + let reply = json!({ "ok": true, "publicTraffic": true, "serverTags": [{ "server": "s1", "tags": ["web"] }] }); + let out = sign_reply_with(&signer, "cl_a", &headers("nonce-1234"), reply.clone()).await; + // The plain fields stay, for agents that don't check. + assert_eq!(out["publicTraffic"], json!(true)); + let wire: pyo_proto::SignedReplyWire = serde_json::from_value(out["signed"].clone()).unwrap(); + let now = pyo_proto::now_ms() as u64; + let signed = keys.verify_reply(Some(&wire), "cl_a", "nonce-1234", now).unwrap(); + assert_eq!(serde_json::from_str::(signed).unwrap(), reply); + assert!(keys.verify_reply(Some(&wire), "cl_b", "nonce-1234", now).is_err()); + assert!(keys.verify_reply(Some(&wire), "cl_a", "nonce-9999", now).is_err()); + // No nonce, or not one an agent makes: nothing to bind it to, so unsigned. + let plain = sign_reply_with(&signer, "cl_a", &axum::http::HeaderMap::new(), reply.clone()).await; + assert!(plain.get("signed").is_none()); + let odd = sign_reply_with(&signer, "cl_a", &headers("short"), reply.clone()).await; + assert!(odd.get("signed").is_none()); + } +} + +#[cfg(test)] +mod gate_tests { + use super::*; + use pyo_proto::Command; + + /// Against a throwaway Postgres: a person's request for a change to an + /// ended team's cluster is refused with the plain message, a removal + /// isn't. The agent then gets only the removal: what Pyo queued itself + /// fails unsigned, with the same message. Other teams are untouched. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn an_ended_teams_clusters_get_only_reads_and_removals() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + crate::gate::test_plans::install(); + let run = crate::ids::random_string(8).to_lowercase(); + let s = crate::rls::tests::state(db.clone()); + let mut teams = vec![]; + for (t, ended) in [("a", true), ("b", false)] { + let team = if ended { + format!("team_ended_{run}") + } else { + format!("team_ok_{run}") + }; + let (user, cluster, project, svc) = ( + format!("usr_{t}{run}"), + format!("cl_{t}{run}"), + format!("prj_{t}{run}"), + format!("svc_{t}{run}"), + ); + let q = |sql: &'static str| sqlx::query(sql); + q("INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $1 || '@gate.test', $1, '')").bind(&user).execute(&db).await.unwrap(); + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&db) + .await + .unwrap(); + q("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $3 || '@gate.test', 'admin', 'active')").bind(format!("mem_{t}{run}")).bind(&team).bind(&user).execute(&db).await.unwrap(); + q("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(&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(); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web', '{}', 'running')").bind(&svc).bind(&team).bind(&project).bind(&cluster).execute(&db).await.unwrap(); + let person = crate::auth::User { + id: user, + name: t.into(), + email: format!("{t}@gate.test"), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + let service = pyo_proto::ServiceRef { + service_id: svc, + name: "web".into(), + namespace: project, + workload_kind: "Deployment".into(), + }; + teams.push((team, cluster, person, service, ended)); + } + for (team, cluster, person, service, ended) in &teams { + // A person's restart: refused for the ended team, with why. + let mut tx = crate::rls::begin(&db, person).await.unwrap(); + let restart = + deploy::enqueue(&mut tx, cluster, Command::Restart(service.clone())).await; + if *ended { + let e = restart.expect_err("refused"); + assert_eq!(e.status, StatusCode::PAYMENT_REQUIRED); + assert_eq!(e.message, crate::gate::STOPPED); + } else { + restart.unwrap(); + } + // Removals and their follow-ons are queued. + deploy::enqueue(&mut tx, cluster, Command::DeleteService(service.clone())) + .await + .unwrap(); + deploy::enqueue( + &mut tx, + cluster, + Command::SyncCronJobs { + service: service.clone(), + jobs: vec![], + }, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + // Pyo's own, queued outside a request. + let mut tx = db.begin().await.unwrap(); + deploy::enqueue(&mut tx, cluster, Command::Stop(service.clone())) + .await + .unwrap(); + tx.commit().await.unwrap(); + + let Json(got) = poll( + State(s.clone()), + AgentCluster { + id: cluster.clone(), + team_id: team.clone(), + }, + axum::http::HeaderMap::new(), + Query(PollQuery { wait: Some(0) }), + ) + .await + .unwrap(); + let kinds: Vec = got.iter().map(|e| command_kind(&e.command)).collect(); + let rows: Vec<(String, String, Option)> = sqlx::query_as( + "SELECT command->>'kind', status, result->>'message' FROM pyo.commands WHERE cluster_id = $1 ORDER BY created_at", + ) + .bind(cluster) + .fetch_all(&db) + .await + .unwrap(); + if *ended { + assert_eq!(kinds, ["delete_service"]); + for (kind, status, message) in &rows { + if kind != "delete_service" { + assert_eq!( + (status.as_str(), message.as_deref()), + ("failed", Some(crate::gate::STOPPED)), + "{kind}" + ); + } + } + } else { + assert_eq!( + kinds, + ["restart", "delete_service", "sync_cron_jobs", "stop"] + ); + assert!(rows.iter().all(|(_, status, _)| status == "sent")); + } + } + for (team, ..) in &teams { + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(team) + .execute(&db) + .await + .unwrap(); + } + } + + /// Against a throwaway Postgres: a sync Pyo queued while a team's plan + /// was paused is held back. Once the team may get commands again, its + /// clusters get their syncs sent once more, once. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn held_back_syncs_go_out_again_once_a_team_resumes() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + crate::gate::test_plans::install(); + let run = crate::ids::random_string(8).to_lowercase(); + let s = crate::rls::tests::state(db.clone()); + let (team, cluster, project, svc, dpl) = ( + format!("team_pause_{run}"), + format!("cl_p{run}"), + format!("prj_p{run}"), + format!("svc_p{run}"), + format!("dpl_p{run}"), + ); + crate::gate::test_plans::PAUSED + .lock() + .unwrap() + .insert(team.clone()); + 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) VALUES ($1, $2, $1, $1, 'connected', now())").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 cron = json!([{ "id": "crn_1", "name": "nightly", "schedule": "0 3 * * *", "command": "true" }]); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web', jsonb_build_object('cronJobs', $5::jsonb), 'running')").bind(&svc).bind(&team).bind(&project).bind(&cluster).bind(&cron).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": [] }); + 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(); + let agent = || AgentCluster { + id: cluster.clone(), + team_id: team.clone(), + }; + let polled = || async { + let Json(got) = poll( + State(s.clone()), + agent(), + axum::http::HeaderMap::new(), + Query(PollQuery { wait: Some(0) }), + ) + .await + .unwrap(); + got.iter() + .map(|e| command_kind(&e.command)) + .collect::>() + }; + let marked = || async { + sqlx::query_scalar::<_, bool>( + "SELECT commands_held_at IS NOT NULL FROM pyo.teams WHERE id = $1", + ) + .bind(&team) + .fetch_one(&db) + .await + .unwrap() + }; + + // Pyo syncs the firewall while the plan is paused: held back. + let mut tx = db.begin().await.unwrap(); + crate::firewall::sync(&mut tx, &cluster).await.unwrap(); + tx.commit().await.unwrap(); + assert!(polled().await.is_empty()); + assert!(marked().await); + // Still paused: nothing is sent again. + crate::gate::resume(&s).await.unwrap(); + assert!(polled().await.is_empty()); + assert!(marked().await); + + // Paid: the cluster's syncs go out again, once. + crate::gate::test_plans::PAUSED + .lock() + .unwrap() + .remove(&team); + crate::gate::resume(&s).await.unwrap(); + assert!(!marked().await); + let got = polled().await; + assert_eq!(got, ["sync_firewall", "sync_cron_jobs"]); + let jobs: Value = sqlx::query_scalar( + "SELECT command->'jobs' FROM pyo.commands WHERE cluster_id = $1 AND command->>'kind' = 'sync_cron_jobs'", + ) + .bind(&cluster) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(jobs[0]["name"], "nightly"); + crate::gate::resume(&s).await.unwrap(); + assert!(polled().await.is_empty()); + + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + } + + fn command_kind(c: &Command) -> String { + serde_json::to_value(c).unwrap()["kind"] + .as_str() + .unwrap() + .to_owned() + } +} diff --git a/crates/pyo-api/src/agent_auth.rs b/crates/pyo-api/src/agent_auth.rs new file mode 100644 index 00000000..88a208e7 --- /dev/null +++ b/crates/pyo-api/src/agent_auth.rs @@ -0,0 +1,590 @@ +//! How agents prove who they are (`PYO_AGENT_AUTH`): +//! +//! - `token` (self-hosted, the default): the cluster's bearer token. +//! - `mtls`: a client certificate on the mTLS listener (agent_tls.rs), for +//! a direct connection. +//! - `signed` (Pyo Cloud): every request signed with the agent's own key +//! (pyo-proto `agentauth`), over plain HTTPS. It works behind a proxy that +//! ends TLS, such as Cloudflare in front of agent.pyo.dev. +//! +//! In `mtls` and `signed` a bearer token alone gets nothing. +//! +//! Signed mode: the agent makes an Ed25519 key in its cluster and enrolls +//! its public half at `/enroll-key` with the connect command's token, which +//! works once. It gets a key id, good for a day, and swaps in a new key at +//! `/renew-key` at half that (the old one stays good for a few minutes). +//! Rotating the cluster's token revokes its keys. Each request's time must +//! be within a minute of Pyo's clock, and its nonce new. +//! +//! Components: the cluster's builders and its pyo-static sign their +//! requests the same way, in every mode, with keys the agent makes in the +//! cluster and registers at `/component-keys` (one live key per builder, +//! one for pyo-static). A component's key is only its own: never the +//! agent's routes. Rotating the token or enrolling again revokes them too, +//! and the agent registers new ones (builders get their spec again, +//! builders.rs). Their bearer tokens are refused when agents don't use +//! tokens, and otherwise only until that component has a key. + +use axum::{ + Router, + body::Body, + extract::{Request, State}, + http::StatusCode, + middleware::Next, + response::{IntoResponse, Response}, + routing::post, +}; +use pyo_proto::agentauth; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::{ + AppState, + agent::AgentCluster, + error::{ApiError, ApiResult, Json}, + ids::sha256_hex, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + Token, + Mtls, + Signed, +} + +pub fn mode() -> Mode { + static M: std::sync::OnceLock = std::sync::OnceLock::new(); + *M.get_or_init(|| { + match std::env::var("PYO_AGENT_AUTH").unwrap_or_default().trim() { + "signed" => Mode::Signed, + "mtls" => Mode::Mtls, + // Before PYO_AGENT_AUTH: certificates were asked for this way. + _ if std::env::var("PYO_AGENT_REQUIRE_CERT").is_ok_and(|v| matches!(v.trim(), "1" | "true")) => Mode::Mtls, + _ => Mode::Token, + } + }) +} + +/// Whether a bearer token alone is refused on agent routes. +pub fn refuse_tokens() -> bool { + mode() != Mode::Token +} + +/// A key's lifetime. +const KEY_HOURS: i64 = 24; + +/// The agent (or component) a signed request came from (set by [`signed`]). +#[derive(Clone, Debug)] +pub struct VerifiedAgent { + pub cluster_id: String, + pub team_id: String, + /// "agent", "builder" or "static". + pub component: String, + /// The builder, for a builder's key. + pub builder_id: Option, +} + +impl VerifiedAgent { + pub fn is_agent(&self) -> bool { + self.component == AGENT + } +} + +pub const AGENT: &str = "agent"; +pub const BUILDER: &str = "builder"; +pub const STATIC: &str = "static"; + +/// A body declared by its hash (agentauth `BODY_SHA256_HEADER`), checked as +/// it streams: a body that doesn't match ends in an error, so nothing +/// downstream takes it as complete (the store checks the same hash too). +fn checked_body(body: Body, want: String) -> Body { + use futures::StreamExt; + use sha2::Digest; + let state = (body.into_data_stream(), Some(sha2::Sha256::new()), want); + let stream = futures::stream::unfold(state, |(mut st, hasher, want)| async move { + let mut h = hasher?; + match st.next().await { + Some(Ok(chunk)) => { + h.update(&chunk); + Some((Ok(chunk), (st, Some(h), want))) + } + Some(Err(e)) => Some((Err(std::io::Error::other(e)), (st, None, want))), + None if hex::encode(h.finalize()) == want => None, + None => Some(( + Err(std::io::Error::other("the body doesn't match the hash it was signed with")), + (st, None, want), + )), + } + }); + Body::from_stream(stream) +} + +fn refused(why: &str) -> Response { + (StatusCode::UNAUTHORIZED, axum::Json(json!({ "error": why }))).into_response() +} + +/// A key's cluster, team, public key, component and builder. +type KeyRow = (String, String, String, String, Option); + +/// Checks a signed agent request: its key, its signature over the method, +/// path, time, nonce and body, the time, and that the nonce is new. A +/// request without a signature goes on (the routes refuse it unless +/// tokens are allowed). +pub async fn signed(State(s): State, req: Request, next: Next) -> Response { + // Owned before any await: the request (its body) isn't Sync. + let (key_id, sig) = { + let h = req.headers(); + let get = |k: &str| h.get(k).and_then(|v| v.to_str().ok()).map(str::to_owned); + (get(agentauth::KEY_HEADER), get(agentauth::SIGNATURE_HEADER)) + }; + let (Some(key_id), Some(sig)) = (key_id, sig) else { + return next.run(req).await; + }; + let (mut parts, body) = req.into_parts(); + let path = parts + .extensions + .get::() + .map(|u| u.0.clone()) + .unwrap_or_else(|| parts.uri.clone()); + let path = path.path_and_query().map(|p| p.as_str().to_owned()).unwrap_or_default(); + // A body signed by the hash it declares streams through, checked on the + // way. Any other is read whole and signed as it is. + let declared = parts + .headers + .get(agentauth::BODY_SHA256_HEADER) + .and_then(|v| v.to_str().ok()) + .filter(|v| v.len() == 64 && v.bytes().all(|b| b.is_ascii_hexdigit())) + .map(str::to_ascii_lowercase); + let (body, body_sha) = match declared { + Some(sha) => (checked_body(body, sha.clone()), sha), + None => { + let Ok(bytes) = axum::body::to_bytes(body, 16 * 1024 * 1024).await else { + return refused("The request's body is too large."); + }; + let sha = agentauth::body_sha256(&bytes); + (Body::from(bytes), sha) + } + }; + let row: sqlx::Result> = sqlx::query_as( + "SELECT k.cluster_id, c.team_id, k.public_key, k.component, k.builder_id FROM pyo.agent_keys k JOIN pyo.clusters c ON c.id = k.cluster_id + WHERE k.id = $1 AND k.revoked_at IS NULL AND k.expires_at > now()", + ) + .bind(&key_id) + .fetch_optional(&s.db) + .await; + let Ok(Some((cluster_id, team_id, public_key, component, builder_id))) = row else { + return refused("This key is unknown, expired or revoked. Run the cluster's connect command again."); + }; + let now = pyo_proto::now_ms() / 1000; + let nonce = match agentauth::verify_hashed(&public_key, &key_id, parts.method.as_str(), &path, &body_sha, &sig, now) { + Ok(n) => n, + Err(e) => return refused(&e.to_string()), + }; + let fresh = sqlx::query("INSERT INTO pyo.agent_nonces (nonce) VALUES ($1) ON CONFLICT DO NOTHING") + .bind(format!("{key_id}:{nonce}")) + .execute(&s.db) + .await; + match fresh { + Ok(r) if r.rows_affected() == 1 => {} + Ok(_) => return refused("This request was already used."), + Err(_) => return (StatusCode::SERVICE_UNAVAILABLE, "database unavailable").into_response(), + } + parts.extensions.insert(VerifiedAgent { cluster_id, team_id, component, builder_id }); + next.run(Request::from_parts(parts, body)).await +} + +/// Forgets nonces once their requests are too old to pass anyway. +pub async fn sweeper(db: sqlx::PgPool) { + loop { + tokio::time::sleep(std::time::Duration::from_secs(60)).await; + let _ = sqlx::query("DELETE FROM pyo.agent_nonces WHERE seen_at < now() - interval '5 minutes'") + .execute(&db) + .await; + } +} + +pub fn routes() -> Router { + Router::new() + .route("/enroll-key", post(enroll_key)) + .route("/renew-key", post(renew_key)) + .merge(component_routes()) +} + +/// Where the agent registers its components' keys (on the mTLS listener too). +pub fn component_routes() -> Router { + Router::new() + .route("/component-keys", post(component_key)) + .route("/component-keys/{id}", axum::routing::get(component_key_live)) +} + +/// 200 while one of this cluster's components' keys is live, else 404. +async fn component_key_live( + State(s): State, + cluster: AgentCluster, + axum::extract::Path(id): axum::extract::Path, +) -> ApiResult> { + let live: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.agent_keys WHERE id = $1 AND cluster_id = $2 AND component <> 'agent' + AND revoked_at IS NULL AND expires_at > now())", + ) + .bind(&id) + .bind(&cluster.id) + .fetch_one(&s.db) + .await?; + if !live { + return Err(ApiError::not_found("Key")); + } + Ok(Json(json!({ "ok": true }))) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct ComponentKey { + /// "builder" or "static". + component: String, + #[serde(default)] + builder_id: Option, + public_key: String, +} + +/// A key for one of the cluster's components, made by its agent in the +/// cluster: the builder's (one of this cluster's) or pyo-static's. It +/// replaces that component's key before it. +async fn component_key( + State(s): State, + cluster: AgentCluster, + Json(b): Json, +) -> ApiResult> { + if !agentauth::valid_public_key(&b.public_key) { + return Err(ApiError::bad_request("That isn't an Ed25519 public key.")); + } + let builder = match (b.component.as_str(), b.builder_id.as_deref()) { + (BUILDER, Some(id)) => Some(id.to_owned()), + (STATIC, None) => None, + _ => return Err(ApiError::bad_request("Keys are for a builder (with its id) or pyo-static.")), + }; + let mut tx = s.db.begin().await?; + if let Some(id) = &builder { + let ours: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.builders WHERE id = $1 AND cluster_id = $2 AND status <> 'removing')", + ) + .bind(id) + .bind(&cluster.id) + .fetch_one(&mut *tx) + .await?; + if !ours { + return Err(ApiError::not_found("Builder")); + } + } + sqlx::query( + "UPDATE pyo.agent_keys SET revoked_at = now() + WHERE cluster_id = $1 AND component = $2 AND builder_id IS NOT DISTINCT FROM $3 AND revoked_at IS NULL", + ) + .bind(&cluster.id) + .bind(&b.component) + .bind(&builder) + .execute(&mut *tx) + .await?; + let id = crate::ids::new_id("akey"); + sqlx::query( + "INSERT INTO pyo.agent_keys (id, cluster_id, public_key, expires_at, component, builder_id) VALUES ($1, $2, $3, 'infinity', $4, $5)", + ) + .bind(&id) + .bind(&cluster.id) + .bind(b.public_key.trim()) + .bind(&b.component) + .bind(&builder) + .execute(&mut *tx) + .await?; + tx.commit().await?; + tracing::info!(cluster = %cluster.id, component = %b.component, builder = ?builder, key = %id, "registered a component's key"); + Ok(Json(json!({ "keyId": id }))) +} + +/// Whether a component has a live key: its bearer token no longer counts. +pub async fn has_key( + db: &sqlx::PgPool, + cluster_id: &str, + component: &str, + builder_id: Option<&str>, +) -> sqlx::Result { + sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.agent_keys WHERE cluster_id = $1 AND component = $2 + AND builder_id IS NOT DISTINCT FROM $3 AND revoked_at IS NULL AND expires_at > now())", + ) + .bind(cluster_id) + .bind(component) + .bind(builder_id) + .fetch_one(db) + .await +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct EnrollKey { + token: String, + public_key: String, +} + +async fn add_key(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, cluster_id: &str, public_key: &str) -> ApiResult<(String, i64)> { + let id = crate::ids::new_id("akey"); + let not_after: i64 = sqlx::query_scalar( + "INSERT INTO pyo.agent_keys (id, cluster_id, public_key, expires_at) VALUES ($1, $2, $3, now() + make_interval(hours => $4)) + RETURNING (extract(epoch FROM expires_at) * 1000)::bigint", + ) + .bind(&id) + .bind(cluster_id) + .bind(public_key.trim()) + .bind(KEY_HOURS as i32) + .fetch_one(&mut **tx) + .await?; + Ok((id, not_after)) +} + +/// The agent's first key, for the connect command's token. Once. +async fn enroll_key(State(s): State, Json(b): Json) -> ApiResult> { + if mode() != Mode::Signed { + return Err(ApiError::not_found("Agent keys")); + } + if !agentauth::valid_public_key(&b.public_key) { + return Err(ApiError::bad_request("That isn't an Ed25519 public key.")); + } + let hash = sha256_hex(b.token.trim()); + let mut tx = s.db.begin().await?; + let row: Option<(String, Option)> = + sqlx::query_as("SELECT id, agent_token_used_hash FROM pyo.clusters WHERE agent_token_hash = $1 FOR UPDATE") + .bind(&hash) + .fetch_optional(&mut *tx) + .await?; + let (cluster, used) = row.ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "Unknown connect token."))?; + if used.as_deref() == Some(hash.as_str()) { + return Err(ApiError::conflict( + "This connect command was used already. Get a new one in the cluster's settings.", + )); + } + // A cluster has one agent: a new enrollment ends the keys before it, + // its components' too (the new agent registers theirs). + sqlx::query("UPDATE pyo.agent_keys SET revoked_at = now() WHERE cluster_id = $1 AND revoked_at IS NULL") + .bind(&cluster) + .execute(&mut *tx) + .await?; + builders_need_keys(&mut tx, &cluster).await?; + let (key_id, not_after) = add_key(&mut tx, &cluster, &b.public_key).await?; + sqlx::query("UPDATE pyo.clusters SET agent_token_used_hash = $2 WHERE id = $1") + .bind(&cluster) + .bind(&hash) + .execute(&mut *tx) + .await?; + tx.commit().await?; + tracing::info!(%cluster, %key_id, "agent enrolled its key"); + Ok(Json(json!({ "keyId": key_id, "notAfter": not_after }))) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RenewKey { + public_key: String, +} + +/// A new key for the agent, asked for with its current one. The current +/// one keeps working for 15 minutes, for requests already on their way. +async fn renew_key( + State(s): State, + cluster: AgentCluster, + verified: Option>, + Json(b): Json, +) -> ApiResult> { + if verified.is_none() { + return Err(ApiError::new(StatusCode::UNAUTHORIZED, "Renewing needs a signed request.")); + } + if !agentauth::valid_public_key(&b.public_key) { + return Err(ApiError::bad_request("That isn't an Ed25519 public key.")); + } + let mut tx = s.db.begin().await?; + sqlx::query( + "UPDATE pyo.agent_keys SET expires_at = least(expires_at, now() + interval '15 minutes') + WHERE cluster_id = $1 AND component = 'agent' AND revoked_at IS NULL", + ) + .bind(&cluster.id) + .execute(&mut *tx) + .await?; + let (key_id, not_after) = add_key(&mut tx, &cluster.id, &b.public_key).await?; + tx.commit().await?; + Ok(Json(json!({ "keyId": key_id, "notAfter": not_after }))) +} + +/// The cluster's keys stop working, its components' too (its token was +/// rotated, or it was removed). +pub async fn revoke(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, cluster_id: &str) -> ApiResult<()> { + sqlx::query("UPDATE pyo.agent_keys SET revoked_at = now() WHERE cluster_id = $1 AND revoked_at IS NULL") + .bind(cluster_id) + .execute(&mut **tx) + .await?; + builders_need_keys(tx, cluster_id).await +} + +/// The cluster's builders get their spec (and a new key) from the next +/// agent as soon as it reports in (builders.rs). +async fn builders_need_keys(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, cluster_id: &str) -> ApiResult<()> { + sqlx::query("UPDATE pyo.builders SET info = info - 'keyAskedAt' WHERE cluster_id = $1 AND info ? 'keyAskedAt'") + .bind(cluster_id) + .execute(&mut **tx) + .await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::http::{Method, Request as HttpRequest}; + use pyo_proto::agentauth::RequestKey; + use tower::ServiceExt as _; + + #[tokio::test] + async fn a_streamed_body_must_match_its_signed_hash() { + let collect = |b: Body| async move { axum::body::to_bytes(b, 1 << 20).await }; + let file = b"

hi

".to_vec(); + let good = checked_body(Body::from(file.clone()), agentauth::body_sha256(&file)); + assert_eq!(collect(good).await.unwrap().to_vec(), file); + let bad = checked_body(Body::from(b"

other

".to_vec()), agentauth::body_sha256(&file)); + assert!(collect(bad).await.is_err()); + } + + fn state(db: sqlx::PgPool) -> AppState { + let config = crate::Config { + agent_api_url: String::new(), + agent_image: String::new(), + waf_image: String::new(), + geoip_image: String::new(), + cookie_secure: false, + allow_signup: false, + builder_image: String::new(), + relay_addr: None, + }; + let (_stop, stopping) = tokio::sync::watch::channel(false); + AppState { + db: db.clone(), + config: std::sync::Arc::new(config), + observability: crate::observability::Observability::from_env(db), + sealer: std::sync::Arc::new(crate::secrets::Sealer::for_tests()), + wakers: Default::default(), + terminals: Default::default(), + stopping, + } + } + + struct Key(String, RequestKey); + + fn new_key() -> (RequestKey, String) { + let k = RequestKey::from_pkcs8(&RequestKey::generate_pkcs8().unwrap()).unwrap(); + let pk = k.public_key(); + (k, pk) + } + + async fn call(app: &Router, method: Method, path: &str, key: Option<&Key>, bearer: Option<&str>, body: &[u8]) -> (StatusCode, Value) { + let mut req = HttpRequest::builder().method(method.clone()).uri(path).header("content-type", "application/json"); + if let Some(Key(id, k)) = key { + for (h, v) in k.sign(id, method.as_str(), path, body, pyo_proto::now_ms() / 1000) { + req = req.header(h, v); + } + } + if let Some(t) = bearer { + req = req.header("authorization", format!("Bearer {t}")); + } + let res = app.clone().oneshot(req.body(Body::from(body.to_vec())).unwrap()).await.unwrap(); + let status = res.status(); + let bytes = axum::body::to_bytes(res.into_body(), 1 << 20).await.unwrap(); + (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + } + + /// Against a throwaway Postgres: the agent registers its builders' and + /// pyo-static's keys; each signs only as itself; a builder's token stops + /// counting once it has a key; a new key revokes the one before, and + /// revoking the cluster's keys takes the components' too. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn components_sign_with_keys_the_agent_registers() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()).await.unwrap(); + crate::migrate::run(&db).await.unwrap(); + let run = crate::ids::random_string(8); + let (team, cl, other) = (format!("team_k{run}"), format!("cl_k{run}"), format!("cl_o{run}")); + let (bld, theirs) = (format!("bld_k{run}"), format!("bld_o{run}")); + 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(); + for c in [&cl, &other] { + q("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash) VALUES ($1, $2, $1, $1)").bind(c).bind(&team).execute(&db).await.unwrap(); + } + let door = format!("door{run}"); + for (b, c) in [(&bld, &cl), (&theirs, &other)] { + q("INSERT INTO pyo.builders (id, team_id, name, kind, cluster_id, server, token_hash, status) VALUES ($1, $2, $1, 'cluster', $3, 's', $4, 'ready')") + .bind(b).bind(&team).bind(c).bind(sha256_hex(&format!("{door}{b}"))).execute(&db).await.unwrap(); + } + let (agent_key, agent_pk) = new_key(); + let agent_id = format!("akey_a{run}"); + q("INSERT INTO pyo.agent_keys (id, cluster_id, public_key, expires_at) VALUES ($1, $2, $3, now() + interval '1 hour')") + .bind(&agent_id).bind(&cl).bind(&agent_pk).execute(&db).await.unwrap(); + let agent = Key(agent_id, agent_key); + let s = state(db.clone()); + let layer = || axum::middleware::from_fn_with_state(s.clone(), signed); + let app = Router::new() + .nest("/api/agent/v1", routes().layer(layer())) + .nest("/api/builder/v1", crate::builders::routes().merge(crate::sites::builder_routes()).layer(layer())) + .nest("/api/static/v1", crate::sites::routes().layer(layer())) + .with_state(s.clone()); + + // Before it has a key, a builder's token still counts (agents use tokens here). + let hb = br#"{"version":"t","buildkit":true,"cpus":1,"memoryGi":1}"#; + let token = format!("{door}{bld}"); + assert_eq!(call(&app, Method::POST, "/api/builder/v1/heartbeat", None, Some(&token), hb).await.0, StatusCode::OK); + + // The agent registers its builder's key. + let (bkey, bpk) = new_key(); + let body = serde_json::to_vec(&json!({ "component": "builder", "builderId": bld, "publicKey": bpk })).unwrap(); + let (st, v) = call(&app, Method::POST, "/api/agent/v1/component-keys", Some(&agent), None, &body).await; + assert_eq!(st, StatusCode::OK, "{v}"); + let builder = Key(v["keyId"].as_str().unwrap().to_owned(), bkey); + assert_eq!(call(&app, Method::POST, "/api/builder/v1/heartbeat", Some(&builder), None, hb).await.0, StatusCode::OK); + // Its token no longer counts. + assert_eq!(call(&app, Method::POST, "/api/builder/v1/heartbeat", None, Some(&token), hb).await.0, StatusCode::UNAUTHORIZED); + // Each key only as itself. + let (_, x) = new_key(); + let body2 = serde_json::to_vec(&json!({ "component": "static", "publicKey": x })).unwrap(); + assert_eq!(call(&app, Method::POST, "/api/agent/v1/component-keys", Some(&builder), None, &body2).await.0, StatusCode::FORBIDDEN); + assert_eq!(call(&app, Method::POST, "/api/builder/v1/heartbeat", Some(&agent), None, hb).await.0, StatusCode::FORBIDDEN); + // Not for another cluster's builder. + let body3 = serde_json::to_vec(&json!({ "component": "builder", "builderId": theirs, "publicKey": x })).unwrap(); + assert_eq!(call(&app, Method::POST, "/api/agent/v1/component-keys", Some(&agent), None, &body3).await.0, StatusCode::NOT_FOUND); + + // pyo-static: its key reads (an unknown site, once let in, is a 404). + let (skey, spk) = new_key(); + let body4 = serde_json::to_vec(&json!({ "component": "static", "publicKey": spk })).unwrap(); + let (st, v) = call(&app, Method::POST, "/api/agent/v1/component-keys", Some(&agent), None, &body4).await; + assert_eq!(st, StatusCode::OK); + let reader = Key(v["keyId"].as_str().unwrap().to_owned(), skey); + let manifest = "/api/static/v1/sites/svc_x/deploys/dpl_x/manifest"; + assert_eq!(call(&app, Method::GET, manifest, Some(&reader), None, b"").await.0, StatusCode::NOT_FOUND); + assert_eq!(call(&app, Method::GET, manifest, Some(&builder), None, b"").await.0, StatusCode::FORBIDDEN); + assert_eq!(call(&app, Method::GET, manifest, None, None, b"").await.0, StatusCode::UNAUTHORIZED); + let live = format!("/api/agent/v1/component-keys/{}", reader.0); + assert_eq!(call(&app, Method::GET, &live, Some(&agent), None, b"").await.0, StatusCode::OK); + + // A new builder key revokes the one before. + let (bkey2, bpk2) = new_key(); + let body5 = serde_json::to_vec(&json!({ "component": "builder", "builderId": bld, "publicKey": bpk2 })).unwrap(); + let (_, v) = call(&app, Method::POST, "/api/agent/v1/component-keys", Some(&agent), None, &body5).await; + let builder2 = Key(v["keyId"].as_str().unwrap().to_owned(), bkey2); + assert_eq!(call(&app, Method::POST, "/api/builder/v1/heartbeat", Some(&builder), None, hb).await.0, StatusCode::UNAUTHORIZED); + assert_eq!(call(&app, Method::POST, "/api/builder/v1/heartbeat", Some(&builder2), None, hb).await.0, StatusCode::OK); + + // The cluster's keys revoked (a new connect command): the components' go too. + let mut tx = db.begin().await.unwrap(); + revoke(&mut tx, &cl).await.unwrap(); + tx.commit().await.unwrap(); + assert_eq!(call(&app, Method::POST, "/api/builder/v1/heartbeat", Some(&builder2), None, hb).await.0, StatusCode::UNAUTHORIZED); + assert_eq!(call(&app, Method::GET, manifest, Some(&reader), None, b"").await.0, StatusCode::UNAUTHORIZED); + let agent2 = Key(format!("akey_b{run}"), RequestKey::from_pkcs8(&RequestKey::generate_pkcs8().unwrap()).unwrap()); + q("INSERT INTO pyo.agent_keys (id, cluster_id, public_key, expires_at) VALUES ($1, $2, $3, now() + interval '1 hour')") + .bind(&agent2.0).bind(&cl).bind(agent2.1.public_key()).execute(&db).await.unwrap(); + assert_eq!(call(&app, Method::GET, &live, Some(&agent2), None, b"").await.0, StatusCode::NOT_FOUND); + } +} diff --git a/crates/pyo-api/src/agent_tls.rs b/crates/pyo-api/src/agent_tls.rs new file mode 100644 index 00000000..43022eea --- /dev/null +++ b/crates/pyo-api/src/agent_tls.rs @@ -0,0 +1,418 @@ +//! The agent endpoint over mutual TLS (Pyo Cloud's agent.pyo.dev). +//! +//! With `PYO_AGENT_MTLS_ADDR` set, Pyo also listens there for agents only: +//! TLS 1.3, its own CA (the agent pins it, no public CA counts), and a +//! client certificate from that CA naming the agent's cluster +//! (`pyo://team//cluster/` as a URI name, valid a day). An +//! agent gets its first certificate at `/enroll` with the connect command's +//! token, which works once, and renews at `/renew` with the certificate it +//! has. The cluster comes from the certificate, never the request. +//! +//! With `PYO_AGENT_AUTH=mtls` the agent routes refuse a bearer token +//! alone, on this listener and the main one (agent_auth.rs). +//! +//! The CA's key is a file here (`PYO_AGENT_CA_DIR`, made on first start); +//! a hosted build passes its own CA ([`crate::AgentCa`]): Pyo Cloud's +//! signer, with the key in a KMS. Certificates look the same either way +//! (pyo-proto `agent_ca`). + +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use axum::{ + Router, + extract::{ConnectInfo, State}, + http::StatusCode, + routing::{get, post}, +}; +use futures::future::BoxFuture; +use pyo_proto::agent_ca::{self, Issued}; +use rcgen::{Issuer, KeyPair}; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject}; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::{ + AppState, + agent::AgentCluster, + error::{ApiError, ApiResult, Json}, + ids::sha256_hex, +}; + +/// The agent CA, when this Pyo runs the mTLS endpoint. +pub fn ca() -> Option<&'static Arc> { + CA.get() +} +static CA: std::sync::OnceLock> = std::sync::OnceLock::new(); + +/// Where agents reach Pyo (`PYO_AGENT_ENDPOINT`), for the install manifest: +/// the mTLS listener, or (signed requests) Pyo's agent address behind its +/// proxy. None when agents use tokens. +pub fn endpoint() -> Option { + use crate::agent_auth::{Mode, mode}; + match mode() { + Mode::Token => return None, + Mode::Mtls => { + ca()?; + } + Mode::Signed => {} + } + std::env::var("PYO_AGENT_ENDPOINT") + .ok() + .map(|v| v.trim().trim_end_matches('/').to_owned()) + .filter(|v| !v.is_empty()) +} + +/// Pyo's own agent CA: its key in a file. +pub struct Ca { + pem: String, + key_pem: String, +} + +impl Ca { + /// The CA in `dir` (ca.pem, ca.key), made there on first start. + pub fn load_or_create(dir: &std::path::Path) -> anyhow::Result { + let (cert, key) = (dir.join("ca.pem"), dir.join("ca.key")); + if cert.exists() && key.exists() { + return Ok(Self { + pem: std::fs::read_to_string(&cert)?, + key_pem: std::fs::read_to_string(&key)?, + }); + } + std::fs::create_dir_all(dir)?; + let key_pair = KeyPair::generate()?; + let pem = agent_ca::ca_cert(&key_pair).map_err(anyhow::Error::msg)?; + let key_pem = key_pair.serialize_pem(); + { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&key)?; + f.write_all(key_pem.as_bytes())?; + } + std::fs::write(&cert, &pem)?; + tracing::info!(dir = %dir.display(), "made the agent CA"); + Ok(Self { pem, key_pem }) + } + + fn issuer(&self) -> anyhow::Result> { + let key = KeyPair::from_pem(&self.key_pem)?; + agent_ca::issuer(&self.pem, key).map_err(anyhow::Error::msg) + } +} + +impl crate::AgentCa for Ca { + fn pem(&self) -> &str { + &self.pem + } + + fn issue<'a>(&'a self, csr_pem: &'a str, team: &'a str, cluster: &'a str) -> BoxFuture<'a, anyhow::Result> { + Box::pin(async move { agent_ca::issue_client(&self.issuer()?, csr_pem, team, cluster).map_err(anyhow::Error::msg) }) + } + + fn issue_server<'a>(&'a self, csr_pem: &'a str, names: &'a [String]) -> BoxFuture<'a, anyhow::Result> { + Box::pin(async move { agent_ca::issue_server(&self.issuer()?, csr_pem, names).map_err(anyhow::Error::msg) }) + } +} + +/// The endpoint's own certificate and key (PEM), from the CA. +async fn server_cert(ca: &dyn crate::AgentCa, names: &[String]) -> anyhow::Result<(String, String)> { + let key = KeyPair::generate()?; + let csr = agent_ca::csr(&key).map_err(anyhow::Error::msg)?; + let cert = ca.issue_server(&csr, names).await?; + Ok((cert, key.serialize_pem())) +} + +/// The cluster a client certificate names, and its serial (hex). +pub struct CertIdentity { + pub team: String, + pub cluster: String, + pub serial: String, +} + +pub fn identity(der: &[u8]) -> Option { + let (_, cert) = x509_parser::parse_x509_certificate(der).ok()?; + let serial = hex::encode(cert.raw_serial()); + let san = cert.subject_alternative_name().ok()??; + for name in &san.value.general_names { + if let x509_parser::extensions::GeneralName::URI(uri) = name { + let rest = uri.strip_prefix("pyo://team/")?; + let (team, cluster) = rest.split_once("/cluster/")?; + if team.is_empty() || cluster.is_empty() || cluster.contains('/') { + return None; + } + return Some(CertIdentity { + team: team.to_owned(), + cluster: cluster.to_owned(), + // Stored without leading zero bytes' ambiguity: as issued. + serial: serial.trim_start_matches("00").to_owned(), + }); + } + } + None +} + +/// Who's on the other end of an agent-endpoint connection. +#[derive(Clone, Debug)] +pub struct AgentPeer { + pub addr: SocketAddr, + /// The verified client certificate (DER), when one was presented. + pub cert: Option>>, +} + +impl axum::extract::connect_info::Connected> for AgentPeer { + fn connect_info(s: axum::serve::IncomingStream<'_, TlsListener>) -> Self { + s.remote_addr().clone() + } +} + +/// Accepts TLS connections; handshakes run beside the accept loop, so a +/// slow client can't hold up others. +pub struct TlsListener { + rx: tokio::sync::mpsc::Receiver<(tokio_rustls::server::TlsStream, AgentPeer)>, + local: SocketAddr, +} + +impl axum::serve::Listener for TlsListener { + type Io = tokio_rustls::server::TlsStream; + type Addr = AgentPeer; + + async fn accept(&mut self) -> (Self::Io, Self::Addr) { + match self.rx.recv().await { + Some(x) => x, + // The accept loop ended: wait forever (the server stops on its own signal). + None => std::future::pending().await, + } + } + + fn local_addr(&self) -> std::io::Result { + Ok(AgentPeer { addr: self.local, cert: None }) + } +} + +async fn server_config(ca: &dyn crate::AgentCa, names: &[String]) -> anyhow::Result { + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let mut roots = rustls::RootCertStore::empty(); + for c in CertificateDer::pem_slice_iter(ca.pem().as_bytes()) { + roots.add(c?)?; + } + let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider.clone()) + // Enrolling agents have no certificate yet; every other route wants one. + .allow_unauthenticated() + .build()?; + let (cert_pem, key_pem) = server_cert(ca, names).await?; + let chain = CertificateDer::pem_slice_iter(cert_pem.as_bytes()).collect::, _>>()?; + let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes())?; + let mut cfg = rustls::ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13])? + .with_client_cert_verifier(verifier) + .with_single_cert(chain, key)?; + cfg.alpn_protocols = vec![b"http/1.1".to_vec()]; + // No resumption: a resumed session keeps the client certificate (or + // none) of the one it came from, past a renewal or a revocation. + cfg.session_storage = Arc::new(rustls::server::NoServerSessionStorage {}); + cfg.send_tls13_tickets = 0; + Ok(cfg) +} + +/// Starts the endpoint when `PYO_AGENT_MTLS_ADDR` is set, with the +/// hosted build's CA or Pyo's own. +pub async fn start( + state: AppState, + agent_routes: Router, + hosted_ca: Option>, +) -> anyhow::Result<()> { + let Some(addr) = std::env::var("PYO_AGENT_MTLS_ADDR").ok().filter(|v| !v.trim().is_empty()) else { + return Ok(()); + }; + let addr: SocketAddr = addr.trim().parse()?; + let ca: Arc = match hosted_ca { + Some(ca) => ca, + None => { + let dir = std::env::var("PYO_AGENT_CA_DIR").unwrap_or_else(|_| "/var/lib/pyo/agent-ca".into()); + Arc::new(Ca::load_or_create(std::path::Path::new(&dir))?) + } + }; + // The names the endpoint answers to: its URL's host, and any extra. + let mut names: Vec = std::env::var("PYO_AGENT_TLS_NAMES") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()) + .collect(); + if let Some(host) = std::env::var("PYO_AGENT_ENDPOINT").ok().and_then(|u| { + let rest = u.trim().split("://").nth(1)?.split('/').next()?.to_owned(); + let host = if rest.starts_with('[') { + rest.trim_start_matches('[').split(']').next()?.to_owned() + } else { + rest.split(':').next()?.to_owned() + }; + Some(host) + }) { + names.insert(0, host); + } + anyhow::ensure!(!names.is_empty(), "PYO_AGENT_MTLS_ADDR needs PYO_AGENT_ENDPOINT or PYO_AGENT_TLS_NAMES"); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config(ca.as_ref(), &names).await?)); + let _ = CA.set(ca); + let tcp = tokio::net::TcpListener::bind(addr).await?; + let local = tcp.local_addr()?; + let (tx, rx) = tokio::sync::mpsc::channel(256); + tokio::spawn(async move { + loop { + let Ok((sock, peer)) = tcp.accept().await else { + tokio::time::sleep(Duration::from_millis(50)).await; + continue; + }; + let acceptor = acceptor.clone(); + let tx = tx.clone(); + tokio::spawn(async move { + let Ok(Ok(tls)) = tokio::time::timeout(Duration::from_secs(10), acceptor.accept(sock)).await else { + return; + }; + let cert = tls + .get_ref() + .1 + .peer_certificates() + .and_then(|c| c.first()) + .map(|c| Arc::new(c.clone().into_owned())); + let _ = tx.send((tls, AgentPeer { addr: peer, cert })).await; + }); + } + }); + let app = Router::new() + .route("/healthz", get(|| async { "ok" })) + .nest("/api/agent/v1", agent_routes.merge(routes())) + .layer(axum::middleware::from_fn(peer_info)) + .layer(axum::extract::DefaultBodyLimit::max(4 * 1024 * 1024)) + .with_state(state); + tracing::info!(%addr, names = ?names, "agent endpoint (mTLS) listening"); + tokio::spawn(async move { + let listener = TlsListener { rx, local }; + if let Err(e) = axum::serve(listener, app.into_make_service_with_connect_info::()).await { + tracing::warn!(error = %e, "agent endpoint stopped"); + } + }); + Ok(()) +} + +/// Handlers read the peer's address as everywhere else, and the agent +/// extractor reads its certificate. +async fn peer_info( + ConnectInfo(peer): ConnectInfo, + mut req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + req.extensions_mut().insert(ConnectInfo(peer.addr)); + req.extensions_mut().insert(peer); + next.run(req).await +} + +fn routes() -> Router { + Router::new() + .route("/enroll", post(enroll)) + .route("/renew", post(renew)) +} + +#[derive(Deserialize)] +struct EnrollBody { + token: String, + csr: String, +} + +/// The first client certificate, for the connect command's token. Once. +async fn enroll( + State(s): State, + peer: Option>, + Json(b): Json, +) -> ApiResult> { + let ca = ca().ok_or_else(|| ApiError::not_found("Agent endpoint"))?; + if peer.is_none() { + return Err(ApiError::not_found("Agent endpoint")); + } + let hash = sha256_hex(b.token.trim()); + let mut tx = s.db.begin().await?; + let row: Option<(String, String, Option)> = sqlx::query_as( + "SELECT id, team_id, agent_token_used_hash FROM pyo.clusters WHERE agent_token_hash = $1 FOR UPDATE", + ) + .bind(&hash) + .fetch_optional(&mut *tx) + .await?; + let (cluster, team, used) = + row.ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "Unknown connect token."))?; + if used.as_deref() == Some(hash.as_str()) { + return Err(ApiError::conflict( + "This connect command was used already. Get a new one in the cluster's settings.", + )); + } + let Issued { serial, pem, not_after_ms: not_after } = ca + .issue(&b.csr, &team, &cluster) + .await + .map_err(|e| ApiError::bad_request(format!("Couldn't read the request: {e}")))?; + sqlx::query("UPDATE pyo.clusters SET agent_cert_prev_serial = NULL, agent_cert_serial = $2, agent_token_used_hash = $3 WHERE id = $1") + .bind(&cluster) + .bind(&serial) + .bind(&hash) + .execute(&mut *tx) + .await?; + tx.commit().await?; + tracing::info!(%cluster, "agent enrolled"); + Ok(Json(json!({ "certificate": pem, "notAfter": not_after, "ca": ca.pem() }))) +} + +#[derive(Deserialize)] +struct RenewBody { + csr: String, +} + +/// A new certificate for the one presented (its cluster, a fresh key). +async fn renew( + State(s): State, + cluster: AgentCluster, + peer: Option>, + Json(b): Json, +) -> ApiResult> { + let ca = ca().ok_or_else(|| ApiError::not_found("Agent endpoint"))?; + if !peer.is_some_and(|p| p.cert.is_some()) { + return Err(ApiError::new(StatusCode::UNAUTHORIZED, "Renewing needs the current certificate.")); + } + let Issued { serial, pem, not_after_ms: not_after } = ca + .issue(&b.csr, &cluster.team_id, &cluster.id) + .await + .map_err(|e| ApiError::bad_request(format!("Couldn't read the request: {e}")))?; + sqlx::query("UPDATE pyo.clusters SET agent_cert_prev_serial = agent_cert_serial, agent_cert_serial = $2 WHERE id = $1") + .bind(&cluster.id) + .bind(&serial) + .execute(&s.db) + .await?; + Ok(Json(json!({ "certificate": pem, "notAfter": not_after, "ca": ca.pem() }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::AgentCa; + + #[tokio::test] + async fn a_cluster_certificate_names_its_cluster() { + let dir = std::env::temp_dir().join(format!("pyo-ca-test-{}", rand::random::())); + let ca = Ca::load_or_create(&dir).unwrap(); + let key = KeyPair::generate().unwrap(); + let csr = agent_ca::csr(&key).unwrap(); + let Issued { serial, pem, .. } = ca.issue(&csr, "team_a", "cl_1").await.unwrap(); + let der = CertificateDer::from_pem_slice(pem.as_bytes()).unwrap(); + let id = identity(&der).unwrap(); + assert_eq!((id.team.as_str(), id.cluster.as_str()), ("team_a", "cl_1")); + assert_eq!(id.serial, serial); + // The endpoint's own certificate, and a TLS config from both. + assert!(server_config(&ca, &["agent.pyo.test".into()]).await.is_ok()); + // The same CA again from its files. + let again = Ca::load_or_create(&dir).unwrap(); + assert_eq!(again.pem(), ca.pem()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/pyo-api/src/alerts.rs b/crates/pyo-api/src/alerts.rs index 34b3ea0b..777160a9 100644 --- a/crates/pyo-api/src/alerts.rs +++ b/crates/pyo-api/src/alerts.rs @@ -468,7 +468,7 @@ async fn check_target(t: &Target, private_allowed: bool) -> Result<(), String> { /// Whether a webhook may go to a private network: where the installation /// allows it, and never on a hosted Pyo. fn private_ok() -> bool { - outbound::private_allowed() && crate::features().is_empty() + outbound::private_allowed() && !crate::hosted() } // ── Sending ──────────────────────────────────────────────────────────────── diff --git a/crates/pyo-api/src/audit.rs b/crates/pyo-api/src/audit.rs new file mode 100644 index 00000000..5b4fa066 --- /dev/null +++ b/crates/pyo-api/src/audit.rs @@ -0,0 +1,639 @@ +//! The audit log: who did what in a team, when, from where and how. +//! +//! Every entry of a team's activity that a person made goes here too +//! (ops.rs `log_activity`), with what the request says about them: their +//! account, the address and browser it came from, and whether it came from +//! the dashboard, an API key or an assistant (MCP). Security events that +//! aren't activity go here only: sign-ins and failed ones, two-factor +//! changes, recovery codes used. +//! +//! What a request knows about itself is kept for it by [`middleware`] (a +//! task-local), and filled in by the extractors that find out who it is +//! (auth.rs, oauth.rs), so `log_activity`'s many callers needn't pass it +//! along. Work a request hands to another task is recorded as Pyo's own. +//! +//! Addresses are kept as each team chose (`teams.audit_ips`: full, +//! anonymized or none) when the entry is written. Owners and admins read +//! the log on Team › Audit log and can download it as CSV. Entries are +//! kept a year on Pyo Cloud, and as the installation's admin chose when +//! self-hosted (Settings › Security). + +use std::{ + net::SocketAddr, + sync::{Arc, Mutex}, +}; + +use axum::{ + extract::{ConnectInfo, Request, State}, + http::{HeaderValue, header}, + middleware::Next, + response::{IntoResponse, Response}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sqlx::{PgConnection, PgPool}; + +use crate::{ + AppState, + auth::{SessionUser, User}, + error::{ApiError, ApiResult, Json, Query}, +}; + +/// How a request reached Pyo. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Via { + Dashboard, + /// An API key (scripts, the CLI). + Api, + /// An assistant connected over OAuth. + Mcp, + /// Pyo itself: background work, agents, webhooks. + System, +} + +impl Via { + pub fn as_str(self) -> &'static str { + match self { + Via::Dashboard => "dashboard", + Via::Api => "api", + Via::Mcp => "mcp", + Via::System => "system", + } + } +} + +/// Who did it, as an entry records them. +#[derive(Debug, Clone)] +pub struct Who { + pub id: Option, + pub name: String, + pub email: String, + pub via: Via, + /// The API key's or assistant's name. + pub key: Option, +} + +impl Who { + /// A person, signing in or using the dashboard. + pub fn person(user: &User) -> Self { + Who { + id: Some(user.id.clone()), + name: user.name.clone(), + email: user.email.clone(), + via: Via::Dashboard, + key: None, + } + } + + /// Someone who isn't signed in yet (a failed sign-in), by account. + pub fn account(id: &str, name: &str, email: &str) -> Self { + Who { + id: Some(id.to_owned()), + name: name.to_owned(), + email: email.to_owned(), + via: Via::Dashboard, + key: None, + } + } + + /// The request's own person when it has one, else `name` as Pyo's own + /// work ("pyo", a job acting for someone). + fn current(name: &str) -> Self { + if name != "pyo" + && let Some(who) = REQUEST + .try_with(|r| r.actor.lock().unwrap_or_else(|e| e.into_inner()).clone()) + .ok() + .flatten() + { + return who; + } + Who { + id: None, + name: name.to_owned(), + email: String::new(), + via: Via::System, + key: None, + } + } +} + +/// What a request says about itself, for its entries. +struct RequestInfo { + ip: String, + user_agent: String, + actor: Mutex>, +} + +tokio::task_local! { + static REQUEST: Arc; +} + +/// Keeps the request's address and browser for the entries it writes. +pub async fn middleware(req: Request, next: Next) -> Response { + let info = Arc::new(request_info(&req)); + REQUEST.scope(info, next.run(req)).await +} + +fn request_info(req: &Request) -> RequestInfo { + let peer = req + .extensions() + .get::>() + .map(|c| c.0.ip().to_string()) + .unwrap_or_default(); + let h = |k: &str| { + req.headers() + .get_all(k) + .iter() + .filter_map(|v| v.to_str().ok()) + .collect::>() + .join(",") + }; + let ip = crate::ratelimit::visitor_ip( + &peer, + &h("cf-connecting-ip"), + &h("x-forwarded-for"), + crate::ratelimit::trusted_proxies(), + ); + RequestInfo { + ip, + user_agent: user_agent(req.headers()), + actor: Mutex::new(None), + } +} + +/// A browser's User-Agent, cut to a sane length. +pub fn user_agent(headers: &axum::http::HeaderMap) -> String { + headers + .get(header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .chars() + .take(300) + .collect() +} + +/// The request is `user`'s, through `via` (and that key or assistant). +pub fn set_actor(user: &User, via: Via, key: Option<&str>) { + let _ = REQUEST.try_with(|r| { + *r.actor.lock().unwrap_or_else(|e| e.into_inner()) = Some(Who { + id: Some(user.id.clone()), + name: user.name.clone(), + email: user.email.clone(), + via, + key: key.map(str::to_owned), + }) + }); +} + +fn request_ip() -> String { + REQUEST.try_with(|r| r.ip.clone()).unwrap_or_default() +} + +fn request_agent() -> String { + REQUEST + .try_with(|r| r.user_agent.clone()) + .unwrap_or_default() +} + +/// One entry, before it's written. +pub struct Entry<'a> { + pub action: &'a str, + pub title: &'a str, + /// `{kind, id, label}`, as activity has it. + pub target: Value, + pub failed: bool, +} + +/// The teams an entry goes to. +enum Teams<'a> { + One(&'a str), + /// Every team the account is an active member of. + OfUser(&'a str), +} + +async fn insert( + conn: &mut PgConnection, + teams: Teams<'_>, + who: &Who, + e: Entry<'_>, +) -> sqlx::Result<()> { + let ip = request_ip(); + let anonymized = pyo_proto::traffic::mask_ip("anonymized", &ip); + let full = pyo_proto::traffic::mask_ip("full", &ip); + let (filter, team) = match teams { + Teams::One(t) => ("t.id = $1", t), + Teams::OfUser(u) => ( + "t.id IN (SELECT team_id FROM pyo.members WHERE user_id = $1 AND status = 'active')", + u, + ), + }; + let sql = format!( + "INSERT INTO pyo.audit_events (id, team_id, action, title, actor_id, actor_name, actor_email, via, key_name, ip, user_agent, target, outcome) + SELECT 'aud_' || substr(md5(random()::text || clock_timestamp()::text || t.id), 1, 24), t.id, $2, $3, $4, $5, $6, $7, $8, + nullif(CASE t.audit_ips WHEN 'full' THEN $9 WHEN 'anonymized' THEN $10 END, ''), $11, $12, $13 + FROM pyo.teams t WHERE {filter}" + ); + sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(team) + .bind(e.action) + .bind(e.title) + .bind(&who.id) + .bind(&who.name) + .bind(&who.email) + .bind(who.via.as_str()) + .bind(&who.key) + .bind(full) + .bind(anonymized) + .bind(if who.via == Via::System { + String::new() + } else { + request_agent() + }) + .bind(&e.target) + .bind(if e.failed { "failed" } else { "ok" }) + .execute(conn) + .await?; + Ok(()) +} + +/// An entry of a team's activity (ops.rs `log_activity`), by whoever the +/// request is for. Pyo's own events aren't audited. +pub async fn from_activity( + conn: &mut PgConnection, + team_id: &str, + actor: &str, + kind: &str, + title: &str, + target: &Value, +) -> sqlx::Result<()> { + let who = Who::current(actor); + if who.via == Via::System && actor == "pyo" { + return Ok(()); + } + insert( + conn, + Teams::One(team_id), + &who, + Entry { + action: kind, + title, + target: target.clone(), + failed: false, + }, + ) + .await +} + +/// A security event of an account (a sign-in, a two-factor change), in +/// every team it's a member of. Never fails what it records: a missing +/// entry is logged instead. +pub async fn account_event(db: &PgPool, user_id: &str, who: &Who, e: Entry<'_>) { + let action = e.action.to_owned(); + let out = async { + let mut conn = db.acquire().await?; + insert(&mut conn, Teams::OfUser(user_id), who, e).await + } + .await; + if let Err(err) = out { + tracing::warn!(error = %err, action, "audit entry not written"); + } +} + +/// [`account_event`] within a transaction already open. +pub async fn account_event_in( + conn: &mut PgConnection, + user_id: &str, + who: &Who, + e: Entry<'_>, +) -> sqlx::Result<()> { + insert(conn, Teams::OfUser(user_id), who, e).await +} + +// ── Settings ─────────────────────────────────────────────────────────────── + +/// What the audit log may be kept for when self-hosted, in days. +pub const AUDIT_DAYS: [u16; 4] = [90, 180, 365, 730]; +/// Pyo Cloud keeps it a year. +pub const HOSTED_AUDIT_DAYS: u16 = 365; + +/// The installation's security settings ('security' in pyo.settings). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SecuritySettings { + /// Everyone on this installation must use two-factor. + #[serde(default)] + pub require_two_factor: bool, + /// How long audit entries are kept. + #[serde(default = "default_days")] + pub audit_days: u16, +} + +fn default_days() -> u16 { + HOSTED_AUDIT_DAYS +} + +impl Default for SecuritySettings { + fn default() -> Self { + SecuritySettings { + require_two_factor: false, + audit_days: HOSTED_AUDIT_DAYS, + } + } +} + +pub async fn settings(db: impl sqlx::PgExecutor<'_>) -> sqlx::Result { + let v: Option = + sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'security'") + .fetch_optional(db) + .await?; + let mut s: SecuritySettings = v + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default(); + if !AUDIT_DAYS.contains(&s.audit_days) { + s.audit_days = HOSTED_AUDIT_DAYS; + } + if crate::hosted() { + s.audit_days = HOSTED_AUDIT_DAYS; + } + Ok(s) +} + +pub async fn save_settings(conn: &mut PgConnection, s: &SecuritySettings) -> ApiResult<()> { + if !AUDIT_DAYS.contains(&s.audit_days) { + return Err(ApiError::bad_request( + "Keep the audit log 90, 180, 365 or 730 days.", + )); + } + sqlx::query( + "INSERT INTO pyo.settings (key, value) VALUES ('security', $1) + ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()", + ) + .bind(json!(s)) + .execute(conn) + .await?; + Ok(()) +} + +/// Entries older than the installation keeps them go, a batch at a time. +/// Returns how many went. +pub async fn prune(db: &PgPool) -> sqlx::Result { + let days = settings(db).await?.audit_days; + Ok(sqlx::query( + "DELETE FROM pyo.audit_events WHERE id IN ( + SELECT id FROM pyo.audit_events WHERE at < now() - make_interval(days => $1) LIMIT 5000)", + ) + .bind(i32::from(days)) + .execute(db) + .await? + .rows_affected()) +} + +// ── Reading ──────────────────────────────────────────────────────────────── + +/// Entries per page. +const PAGE: i64 = 100; +/// Rows in one CSV download. +const CSV_ROWS: i64 = 50_000; + +#[derive(Deserialize, utoipa::IntoParams)] +#[into_params(parameter_in = Query)] +#[serde(rename_all = "camelCase")] +pub struct AuditQuery { + /// The team's id (`team_…`). + team: String, + /// Only what this account did (its user id), or `pyo` for Pyo's own. + #[serde(default)] + person: Option, + /// Only this action (`member.role_changed`) or kind of action (`member`). + #[serde(default)] + action: Option, + /// From this time on (milliseconds). + #[serde(default)] + from: Option, + /// Up to this time (milliseconds). + #[serde(default)] + to: Option, + /// The `next` of the page before. + #[serde(default)] + cursor: Option, + /// `csv` for a download of everything that matches (up to 50,000 rows). + #[serde(default)] + format: Option, +} + +/// Audit log +/// +/// Who did what in a team, newest first: when, the account, the action, +/// how (dashboard, API key or assistant) and the address and browser it +/// came from, as the team keeps them. Sign-ins, failed sign-ins and +/// two-factor changes are here too. For the team's owners and admins. +#[utoipa::path(get, path = "/audit-log", operation_id = "listAuditLog", tag = "Teams", + params(AuditQuery), + responses( + (status = 200, description = "`events` (each with `id`, `at`, `action`, `title`, `actor` {id, name, email}, `via`, `key`, `ip`, `userAgent`, `target` and `outcome`), `next` (the `cursor` for the next page, or null), `people` (who appears in the log), `ips` (what the team keeps of addresses) and `days` (how long entries are kept). With `format=csv`, a CSV file.", body = Object), + (status = 403, description = "Not an owner or admin of the team.", body = crate::error::ErrorBody), + (status = 404, description = "No such team, or it isn't yours to see.", body = crate::error::ErrorBody), + ), + extensions(("x-pyo-access" = json!("read"))))] +pub async fn list( + State(s): State, + SessionUser(user): SessionUser, + Query(q): Query, +) -> ApiResult { + Ok(match read(&s, &user, q).await? { + Read::Page(v) => Json(v).into_response(), + Read::Csv { slug, body } => { + let mut res = body.into_response(); + let h = res.headers_mut(); + h.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/csv; charset=utf-8"), + ); + if let Ok(v) = + HeaderValue::from_str(&format!("attachment; filename=\"{slug}-audit-log.csv\"")) + { + h.insert(header::CONTENT_DISPOSITION, v); + } + res + } + }) +} + +/// [`list`] as JSON only (assistants' tool). +pub async fn page( + State(s): State, + SessionUser(user): SessionUser, + Query(mut q): Query, +) -> ApiResult> { + q.format = None; + match read(&s, &user, q).await? { + Read::Page(v) => Ok(Json(v)), + Read::Csv { .. } => Err(ApiError::bad_request("Ask for JSON.")), + } +} + +enum Read { + Page(Value), + Csv { slug: String, body: String }, +} + +async fn read(s: &AppState, user: &User, q: AuditQuery) -> ApiResult { + let days = settings(&s.db).await?.audit_days; + let mut tx = crate::rls::begin(&s.db, user).await?; + // Owners and admins, from the dashboard or with a key that reads. + let role = crate::ops::require_role(&mut tx, user, &q.team, crate::ops::Role::Viewer).await?; + if role < crate::ops::Role::Admin { + return Err(ApiError::forbidden( + "Only team owners and admins can see the audit log.", + )); + } + let csv = q.format.as_deref() == Some("csv"); + let (cursor_at, cursor_id) = match q.cursor.as_deref().and_then(|c| c.split_once(':')) { + Some((at, id)) => (at.parse::().ok(), Some(id.to_owned())), + None => (None, None), + }; + let action = q.action.as_deref().map(str::trim).filter(|a| !a.is_empty()); + let person = q.person.as_deref().map(str::trim).filter(|p| !p.is_empty()); + let rows: Vec = sqlx::query_scalar( + "SELECT jsonb_build_object('id', id, 'at', pyo.ms(at), 'action', action, 'title', title, + 'actor', jsonb_build_object('id', actor_id, 'name', actor_name, 'email', actor_email), + 'via', via, 'key', key_name, 'ip', ip, 'userAgent', user_agent, 'target', target, 'outcome', outcome) + FROM pyo.audit_events + WHERE team_id = $1 + AND ($2::text IS NULL OR action = $2 OR action LIKE $2 || '.%') + AND ($3::text IS NULL OR ($3 = 'pyo' AND via = 'system') OR actor_id = $3) + AND ($4::bigint IS NULL OR at >= to_timestamp($4::float8 / 1000)) + AND ($5::bigint IS NULL OR at <= to_timestamp($5::float8 / 1000)) + AND ($6::bigint IS NULL OR (pyo.ms(at), id) < ($6, $7)) + ORDER BY at DESC, id DESC + LIMIT $8", + ) + .bind(&q.team) + .bind(action) + .bind(person) + .bind(q.from) + .bind(q.to) + .bind(cursor_at) + .bind(cursor_id.unwrap_or_default()) + .bind(if csv { CSV_ROWS } else { PAGE + 1 }) + .fetch_all(&mut *tx) + .await?; + if csv { + let (slug,): (String,) = sqlx::query_as("SELECT slug FROM pyo.teams WHERE id = $1") + .bind(&q.team) + .fetch_one(&mut *tx) + .await?; + tx.commit().await?; + return Ok(Read::Csv { + slug, + body: to_csv(&rows), + }); + } + let people: Vec = sqlx::query_scalar( + "SELECT jsonb_build_object('id', actor_id, 'name', max(actor_name), 'email', max(actor_email)) + FROM pyo.audit_events WHERE team_id = $1 AND actor_id IS NOT NULL + GROUP BY actor_id ORDER BY max(actor_name) LIMIT 500", + ) + .bind(&q.team) + .fetch_all(&mut *tx) + .await?; + let ips: String = sqlx::query_scalar("SELECT audit_ips FROM pyo.teams WHERE id = $1") + .bind(&q.team) + .fetch_one(&mut *tx) + .await?; + tx.commit().await?; + let mut events = rows; + let next = if events.len() as i64 > PAGE { + events.truncate(PAGE as usize); + events + .last() + .map(|e| format!("{}:{}", e["at"], e["id"].as_str().unwrap_or(""))) + } else { + None + }; + Ok(Read::Page(json!({ + "events": events, + "next": next, + "people": people, + "ips": ips, + "days": days, + }))) +} + +/// The CSV download: one row per entry, times in UTC. +fn to_csv(rows: &[Value]) -> String { + let mut out = + String::from("time,person,email,action,title,via,key,ip,user_agent,outcome,target\n"); + for r in rows { + let s = |v: &Value| v.as_str().unwrap_or("").to_owned(); + let at = r["at"] + .as_i64() + .and_then(|ms| jiff::Timestamp::from_millisecond(ms).ok()) + .map(|t| t.to_string()) + .unwrap_or_default(); + let fields = [ + at, + s(&r["actor"]["name"]), + s(&r["actor"]["email"]), + s(&r["action"]), + s(&r["title"]), + s(&r["via"]), + s(&r["key"]), + s(&r["ip"]), + s(&r["userAgent"]), + s(&r["outcome"]), + s(&r["target"]["label"]), + ]; + let line: Vec = fields.iter().map(|f| csv_field(f)).collect(); + out.push_str(&line.join(",")); + out.push('\n'); + } + out +} + +/// One CSV field, quoted when it needs to be. A field a spreadsheet would +/// run as a formula starts with a quote mark instead. +fn csv_field(f: &str) -> String { + let f = if f.starts_with(['=', '+', '-', '@', '\t', '\r']) { + format!("'{f}") + } else { + f.to_owned() + }; + if f.contains([',', '"', '\n', '\r']) { + format!("\"{}\"", f.replace('"', "\"\"")) + } else { + f + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn csv_fields_are_quoted_and_never_formulas() { + assert_eq!(csv_field("plain"), "plain"); + assert_eq!(csv_field("a,b"), "\"a,b\""); + assert_eq!(csv_field("say \"hi\""), "\"say \"\"hi\"\"\""); + assert_eq!(csv_field("=HYPERLINK(1)"), "'=HYPERLINK(1)"); + assert_eq!(csv_field("-1+1"), "'-1+1"); + let rows = vec![json!({ + "at": 1_794_000_000_000_i64, "action": "auth.sign_in", "title": "Signed in", + "actor": { "name": "Ada", "email": "ada@example.com" }, "via": "dashboard", + "ip": "203.0.113.7", "userAgent": "Firefox, on Linux", "outcome": "ok", "target": {} + })]; + let csv = to_csv(&rows); + let line = csv.lines().nth(1).unwrap(); + assert!(line.starts_with("2026-"), "{line}"); + assert!(line.contains(",Ada,ada@example.com,auth.sign_in,Signed in,dashboard,,203.0.113.7,\"Firefox, on Linux\",ok,")); + } + + #[test] + fn hosted_keeps_a_year_and_self_hosted_picks() { + assert!(AUDIT_DAYS.contains(&HOSTED_AUDIT_DAYS)); + assert_eq!(SecuritySettings::default().audit_days, 365); + let s: SecuritySettings = + serde_json::from_value(json!({ "requireTwoFactor": true })).unwrap(); + assert_eq!((s.require_two_factor, s.audit_days), (true, 365)); + } +} diff --git a/crates/pyo-api/src/auth.rs b/crates/pyo-api/src/auth.rs index 4894c54c..27a3c889 100644 --- a/crates/pyo-api/src/auth.rs +++ b/crates/pyo-api/src/auth.rs @@ -49,6 +49,7 @@ pub fn routes() -> Router { .route("/invite/accept", post(accept)) .merge(crate::passkeys::routes()) .merge(crate::recovery::routes()) + .merge(crate::twofactor::routes()) } /// A Pyo account. @@ -172,22 +173,25 @@ impl FromRequestParts for AnySession { { return Err(ApiError::forbidden("Missing request header.")); } + crate::audit::set_actor(&user, crate::audit::Via::Dashboard, None); Ok(AnySession(user)) } } /// 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). +/// 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> { let hash = sha256_hex(token); let user = sqlx::query_as::<_, User>( - "SELECT u.id, u.name, u.email, u.timezone, u.is_admin, u.must_set_up + "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 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)", ) .bind(&hash) .bind(SESSION_DAYS as i32) + .bind(crate::hosted()) .fetch_optional(db) .await?; if user.is_some() { @@ -205,7 +209,7 @@ async fn session_user(db: &sqlx::PgPool, token: &str) -> ApiResult> } /// An API key's user and scope: id, name, email, timezone, is_admin, -/// must_set_up, access, team_ids, expired. +/// must_set_up, access, team_ids, expired, the key's name. type KeyRow = ( String, String, @@ -216,6 +220,7 @@ type KeyRow = ( String, Option>, bool, + String, ); /// A user acting through an API key (`Authorization: Bearer pyo_…`, made on @@ -243,25 +248,42 @@ impl FromRequestParts for TokenUser { "Send a Pyo API key: Authorization: Bearer pyo_…", ) })?; - Ok(TokenUser(key_user(&state.db, token).await?)) + 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?)) } } +/// [`key_user`] for a request from `ip`: wrong keys count per address +/// (a used-up address can't try more), and each key's requests per key. +pub(crate) async fn key_user_from(db: &sqlx::PgPool, token: &str, ip: &str) -> ApiResult { + let user = match key_user(db, token).await { + Err(e) if e.status == StatusCode::UNAUTHORIZED => { + ratelimit::take(db, &[(ratelimit::API_KEY_WRONG_IP, ip)]).await?; + return Err(e); + } + other => other?, + }; + ratelimit::take(db, &[(ratelimit::API_KEY_REQUESTS, &sha256_hex(token))]).await?; + Ok(user) +} + /// The user behind an API key; expired keys are refused. Records when the /// key was last used, at most once a minute so busy clients don't write on /// every call. pub(crate) async fn key_user(db: &sqlx::PgPool, token: &str) -> ApiResult { let hash = sha256_hex(token); let row: Option = sqlx::query_as( - "SELECT u.id, u.name, u.email, u.timezone, u.is_admin, u.must_set_up, t.access, t.team_ids, - COALESCE(t.expires_at <= now(), false) + "SELECT u.id, u.name, u.email, u.timezone, u.is_admin AND NOT pyo.needs_two_factor(u.id, $2), u.must_set_up, t.access, t.team_ids, + COALESCE(t.expires_at <= now(), false), t.name FROM pyo.api_tokens t JOIN pyo.users u ON u.id = t.user_id WHERE t.token_hash = $1", ) .bind(&hash) + .bind(crate::hosted()) .fetch_optional(db) .await?; - let (id, name, email, timezone, is_admin, must_set_up, access, teams, expired) = row + let (id, name, email, timezone, is_admin, must_set_up, access, teams, expired, key_name) = row .ok_or_else(|| { ApiError::new( StatusCode::UNAUTHORIZED, @@ -279,7 +301,7 @@ pub(crate) async fn key_user(db: &sqlx::PgPool, token: &str) -> ApiResult .bind(&hash) .execute(db) .await; - Ok(User { + let user = User { id, name, email, @@ -287,7 +309,9 @@ pub(crate) async fn key_user(db: &sqlx::PgPool, token: &str) -> ApiResult is_admin, must_set_up, key: Some(key), - }) + }; + crate::audit::set_actor(&user, crate::audit::Via::Api, Some(&key_name)); + Ok(user) } /// Prefix of every API key (and CLI token) Pyo hands out. @@ -745,13 +769,15 @@ struct LoginBody { password: String, } +/// The password's right: signed in, or, with two-factor on, a code next +/// (twofactor.rs `/login/code`), with no session yet. async fn login( State(state): State, ClientIp(ip): ClientIp, headers: HeaderMap, jar: CookieJar, Json(body): Json, -) -> ApiResult<(CookieJar, Json)> { +) -> ApiResult<(CookieJar, Json)> { require_csrf(&headers)?; let email = body.email.trim().to_lowercase(); // Before the lookup, keyed by the email as typed: the same for accounts @@ -785,6 +811,21 @@ async fn login( .await .map_err(anyhow::Error::from)?; if !ok || id.is_empty() { + // An account's teams see wrong passwords for it. + if !id.is_empty() { + crate::audit::account_event( + &state.db, + &id, + &crate::audit::Who::account(&id, &name, &email), + crate::audit::Entry { + action: "auth.sign_in_failed", + title: "Wrong password", + target: json!({}), + failed: true, + }, + ) + .await; + } return Err(ApiError::new( StatusCode::UNAUTHORIZED, "Wrong email or password.", @@ -792,19 +833,33 @@ async fn login( } ratelimit::reset(&state.db, &ratelimit::LOGIN_ACCOUNT, &email).await?; ratelimit::forgive(&state.db, &ratelimit::LOGIN_IP, &ip).await?; - let jar = start_session(&state, jar, &id, &headers).await?; - Ok(( - jar, - Json(User { - id, - name, - email, - timezone, - is_admin, - must_set_up, - key: None, - }), - )) + 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)))); + } + let user = User { + id, + name, + email, + timezone, + is_admin, + must_set_up, + key: None, + }; + crate::audit::account_event( + &state.db, + &user.id, + &crate::audit::Who::person(&user), + crate::audit::Entry { + action: "auth.sign_in", + title: "Signed in with a password", + target: json!({}), + failed: false, + }, + ) + .await; + let jar = start_session(&state, jar, &user.id, &headers).await?; + Ok((jar, Json(json!(user)))) } /// Is this the account's password? The same check, and the same work, as @@ -852,8 +907,11 @@ async fn logout( )) } -async fn me(AnySession(user): AnySession) -> Json { - Json(user) +/// The signed-in account, with its two-factor (twofactor.rs `summary`). +async fn me(State(state): State, AnySession(user): AnySession) -> ApiResult> { + let mut me = json!(user); + me["twoFactor"] = crate::twofactor::summary(&state.db, &user.id).await?; + Ok(Json(me)) } #[derive(Deserialize)] diff --git a/crates/pyo-api/src/bg.rs b/crates/pyo-api/src/bg.rs index 9c484b6b..9aa466af 100644 --- a/crates/pyo-api/src/bg.rs +++ b/crates/pyo-api/src/bg.rs @@ -74,6 +74,8 @@ pub const LOCK_DNS: i64 = 7_004; pub const LOCK_BACKUP: i64 = 7_005; pub const LOCK_TEAM_BACKUP: i64 = 7_006; 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; /// 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; @@ -262,9 +264,12 @@ mod tests { LOCK_BACKUP, LOCK_TEAM_BACKUP, LOCK_UPDATES, + LOCK_AGENT_UPDATES, + LOCK_TAILSCALE, LOCK_BACKUP_STORE, LOCK_DATABASE_IMPORTS, crate::geoip::LOCK_GEOIP, + crate::previews::LOCK, // updates::start's one-start-at-a-time lock. LOCK_UPDATES + 1000, ]; diff --git a/crates/pyo-api/src/builders.rs b/crates/pyo-api/src/builders.rs index d11f2ff6..5b62d7b1 100644 --- a/crates/pyo-api/src/builders.rs +++ b/crates/pyo-api/src/builders.rs @@ -27,8 +27,22 @@ use crate::{ /// Bump when the cluster builder's pod spec changes (the agent builds it from /// EnsureBuilder); builders on an older one get it re-sent. 2: unprivileged, -/// read-only pyo-builder. 3: BuildKit started on demand. -pub const CLUSTER_BUILDER_SPEC: i32 = 3; +/// read-only pyo-builder. 3: BuildKit started on demand. 4: a key of its +/// own from the agent (agent_auth.rs), a token only to push to Pyo's door. +pub const CLUSTER_BUILDER_SPEC: i32 = 4; + +/// The builder's login at Pyo's registry door, when it pushes there (never +/// sent for a cluster's own registry, which needs none). Only its hash is +/// kept: a builder without one gets a hash of nothing anyone holds. +fn door_login(registry_host: &str) -> (String, String) { + let token = secret_token(); + let hash = sha256_hex(&token); + if registry_host.is_empty() || registry_host == deploy::INTERNAL_DEFAULT { + (String::new(), hash) + } else { + (token, hash) + } +} pub fn routes() -> Router { Router::new() @@ -38,7 +52,8 @@ pub fn routes() -> Router { .route("/jobs/{id}/result", post(result)) } -/// The builder a bearer token belongs to. +/// The builder a request came from: its key (agent_auth.rs), or its +/// bearer token while it has no key and agents may use tokens. pub struct BuilderAuth { pub id: String, pub team_id: String, @@ -51,24 +66,39 @@ impl FromRequestParts for BuilderAuth { parts: &mut Parts, state: &AppState, ) -> Result { + let gone = || ApiError::new(StatusCode::UNAUTHORIZED, "Unknown builder. Was it removed?"); + if let Some(v) = parts.extensions.get::() { + let Some(id) = v.builder_id.clone().filter(|_| v.component == crate::agent_auth::BUILDER) else { + return Err(ApiError::new(StatusCode::FORBIDDEN, "This key isn't a builder's.")); + }; + let team_id: Option = sqlx::query_scalar( + "SELECT team_id FROM pyo.builders WHERE id = $1 AND cluster_id = $2 AND status <> 'removing'", + ) + .bind(&id) + .bind(&v.cluster_id) + .fetch_optional(&state.db) + .await?; + return Ok(BuilderAuth { id, team_id: team_id.ok_or_else(gone)? }); + } + if crate::agent_auth::refuse_tokens() { + return Err(ApiError::new(StatusCode::UNAUTHORIZED, "Builders sign their requests here.")); + } let token = parts .headers .get("authorization") .and_then(|v| v.to_str().ok()) .and_then(|v| v.strip_prefix("Bearer ")) .ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "Missing builder token."))?; + // A builder with a key no longer counts with its token (which stays + // its registry door login). let row: Option<(String, String)> = sqlx::query_as( - "SELECT id, team_id FROM pyo.builders WHERE token_hash = $1 AND status <> 'removing'", + "SELECT b.id, b.team_id FROM pyo.builders b WHERE b.token_hash = $1 AND b.status <> 'removing' + AND NOT EXISTS (SELECT 1 FROM pyo.agent_keys k WHERE k.builder_id = b.id AND k.revoked_at IS NULL AND k.expires_at > now())", ) .bind(sha256_hex(token)) .fetch_optional(&state.db) .await?; - let (id, team_id) = row.ok_or_else(|| { - ApiError::new( - StatusCode::UNAUTHORIZED, - "Unknown builder token. Was the builder removed?", - ) - })?; + let (id, team_id) = row.ok_or_else(gone)?; Ok(BuilderAuth { id, team_id }) } } @@ -103,8 +133,34 @@ struct PollQuery { wait: Option, } -/// Hand the oldest queued build of the team to this builder, waiting up to -/// `wait` seconds for one. +/// Whether a builder may build for another of its team's clusters, one +/// without a ready builder of its own. Only while every cluster pulls from +/// Pyo's registry: with in-cluster registries (Pyo Cloud) an image stays in +/// the cluster that built it, so a build goes to the deploy's own cluster. +pub fn builds_for_other_clusters() -> bool { + !deploy::in_cluster_registries() +} + +/// The oldest queued build this builder may take: one for its own cluster, +/// or ([`builds_for_other_clusters`]) for a cluster of its team that has no +/// ready builder. Claims it, and notes on its deployment which builder +/// built it. ($1 team, $2 builder, $3 its cluster, $4 other clusters too.) +const CLAIM_BUILD: &str = "WITH j AS ( + UPDATE pyo.build_jobs SET status = 'running', builder_id = $2, started_at = now() + WHERE id = (SELECT q.id FROM pyo.build_jobs q JOIN pyo.deployments d ON d.id = q.deployment_id + WHERE q.team_id = $1 AND q.status = 'queued' + AND (d.cluster_id = $3 + OR ($4 AND NOT EXISTS (SELECT 1 FROM pyo.builders o + WHERE o.team_id = q.team_id AND o.cluster_id = d.cluster_id AND o.status = 'ready'))) + ORDER BY q.created_at LIMIT 1 FOR UPDATE OF q SKIP LOCKED) + RETURNING job, deployment_id + ), d AS ( + UPDATE pyo.deployments SET data = data || jsonb_build_object('builderId', $2::text) WHERE id = (SELECT deployment_id FROM j) + ) + SELECT job FROM j"; + +/// Hand the oldest queued build this builder may take to it, waiting up +/// to `wait` seconds for one. async fn poll( State(s): State, b: BuilderAuth, @@ -112,33 +168,25 @@ async fn poll( ) -> ApiResult>> { let deadline = tokio::time::Instant::now() + Duration::from_secs(q.wait.unwrap_or(25).min(55)); let waker = s.waker(&format!("builders:{}", b.team_id)).await; + let cluster: Option = + sqlx::query_scalar("SELECT cluster_id FROM pyo.builders WHERE id = $1") + .bind(&b.id) + .fetch_one(&s.db) + .await?; loop { let notified = waker.notified(); - // Claim the job, and note on its deployment which builder built it. - let row: Option<(Value,)> = sqlx::query_as( - "WITH j AS ( - UPDATE pyo.build_jobs SET status = 'running', builder_id = $2, started_at = now() - WHERE id = (SELECT id FROM pyo.build_jobs WHERE team_id = $1 AND status = 'queued' ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) - RETURNING job, deployment_id - ), d AS ( - UPDATE pyo.deployments SET data = data || jsonb_build_object('builderId', $2::text) WHERE id = (SELECT deployment_id FROM j) - ) - SELECT job FROM j", - ) - .bind(&b.team_id) - .bind(&b.id) - .fetch_optional(&s.db) - .await?; + let row: Option<(Value,)> = sqlx::query_as(CLAIM_BUILD) + .bind(&b.team_id) + .bind(&b.id) + .bind(&cluster) + .bind(builds_for_other_clusters()) + .fetch_optional(&s.db) + .await?; if let Some((job,)) = row { let mut job: BuildJob = serde_json::from_value(job).map_err(anyhow::Error::from)?; // Pushed through this builder's way to the registry (its door). - let cluster: Option = - sqlx::query_scalar("SELECT cluster_id FROM pyo.builders WHERE id = $1") - .bind(&b.id) - .fetch_one(&s.db) - .await?; - let host = match cluster { - Some(c) => registry_for(&s.db, &c).await?, + let host = match &cluster { + Some(c) => registry_for(&s.db, c).await?, None => String::new(), }; if let Some(rest) = job @@ -221,14 +269,15 @@ pub async fn add_on_server( cluster_id: &str, node: &str, ) -> ApiResult<()> { - let token = secret_token(); + let registry_host = registry_for(&mut **tx, cluster_id).await?; + let (token, hash) = door_login(®istry_host); sqlx::query("INSERT INTO pyo.builders (id, team_id, name, kind, cluster_id, server, token_hash, info) VALUES ($1, $2, $3, 'cluster', $4, $5, $6, jsonb_build_object('specVersion', $7::int, 'image', $8::text))") .bind(id) .bind(team_id) .bind(name) .bind(cluster_id) .bind(node) - .bind(sha256_hex(&token)) + .bind(hash) .bind(CLUSTER_BUILDER_SPEC) .bind(&config.builder_image) .execute(&mut **tx) @@ -239,7 +288,7 @@ pub async fn add_on_server( api_url: config.agent_api_url.clone(), token, image: config.builder_image.clone(), - registry_host: registry_for(&mut **tx, cluster_id).await?, + registry_host, }; deploy::enqueue( tx, @@ -276,9 +325,12 @@ fn first_builder_server(nodes: &[pyo_proto::ServerReport]) -> Option<&str> { .map(|n| n.name.as_str()) } -/// The first time the server Pyo runs on connects, a team without builders -/// gets one there, named after the server: Git deploys work from the start. -/// Only then, so a builder removed later stays removed. Returns its name. +/// The first time the server Pyo runs on connects (or, with in-cluster +/// registries, a team's cluster), a team without builders gets one there, +/// named after the server: Git deploys work from the start. With in-cluster +/// registries each cluster builds its own images, so each cluster without a +/// builder gets one. Only then, so a builder removed later stays removed. +/// Returns its name. pub async fn first_on_this_server( tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, config: &crate::Config, @@ -289,11 +341,14 @@ pub async fn first_on_this_server( let Some(node) = first_builder_server(nodes) else { return Ok(None); }; - let have: bool = - sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pyo.builders WHERE team_id = $1)") - .bind(team_id) - .fetch_one(&mut **tx) - .await?; + let have: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.builders WHERE team_id = $1 AND ($3 OR cluster_id = $2))", + ) + .bind(team_id) + .bind(cluster_id) + .bind(builds_for_other_clusters()) + .fetch_one(&mut **tx) + .await?; if have { return Ok(None); } @@ -328,34 +383,41 @@ pub async fn watcher(s: AppState) { } } -/// Re-send the pod spec to cluster builders made with an older one, or with -/// another builder image (Pyo was updated). Only the token's hash is stored, -/// so each gets a fresh token with it. +/// Builders whose pod spec is re-sent: made with an older one, or with +/// another builder image (Pyo was updated), or without a key of their own +/// where the agent gives them one (an agent updated since, or keys revoked +/// by a new connect command). Also builders on a new server, once it has +/// joined its cluster and is ready (they start at spec version 0). A +/// builder in the middle of a build moves after it. A keyless builder is +/// asked again at most every 10 minutes. +const OUTDATED_BUILDERS: &str = "SELECT b.id, b.cluster_id, b.server FROM pyo.builders b JOIN pyo.clusters c ON c.id = b.cluster_id + WHERE b.kind IN ('cluster', 'server') AND b.status <> 'removing' AND b.server IS NOT NULL + AND (coalesce((b.info->>'specVersion')::int, 1) < $1 + OR (b.info->>'image' IS DISTINCT FROM $2 AND b.info->>'busyWith' IS NULL AND b.status = 'ready') + OR (coalesce((c.capabilities->>'componentKeys')::bool, false) AND b.info->>'busyWith' IS NULL + AND coalesce((b.info->>'keyAskedAt')::bigint, 0) < pyo.ms(now() - interval '10 minutes') + AND NOT EXISTS (SELECT 1 FROM pyo.agent_keys k WHERE k.builder_id = b.id AND k.revoked_at IS NULL AND k.expires_at > now()))) + AND (b.kind = 'cluster' OR EXISTS ( + SELECT 1 FROM pyo.servers n WHERE n.cluster_id = b.cluster_id AND n.name = b.server AND n.report->>'status' = 'ready'))"; + +/// Re-send the pod spec to builders that need it ([`OUTDATED_BUILDERS`]). +/// Only the door login's hash is stored, so each gets a fresh one with it. async fn refresh_cluster_builders(s: &AppState) -> anyhow::Result<()> { - // Also builders on a new server, once it has joined its cluster and - // is ready (they start at spec version 0). A builder in the middle of a - // build moves to a new image after it. - let outdated: Vec<(String, String, String)> = sqlx::query_as( - "SELECT b.id, b.cluster_id, b.server FROM pyo.builders b - WHERE b.kind IN ('cluster', 'server') AND b.status <> 'removing' AND b.cluster_id IS NOT NULL AND b.server IS NOT NULL - AND (coalesce((b.info->>'specVersion')::int, 1) < $1 - OR (b.info->>'image' IS DISTINCT FROM $2 AND b.info->>'busyWith' IS NULL AND b.status = 'ready')) - AND (b.kind = 'cluster' OR EXISTS ( - SELECT 1 FROM pyo.servers n WHERE n.cluster_id = b.cluster_id AND n.name = b.server AND n.report->>'status' = 'ready'))", - ) - .bind(CLUSTER_BUILDER_SPEC) - .bind(&s.config.builder_image) - .fetch_all(&s.db) - .await?; + let outdated: Vec<(String, String, String)> = sqlx::query_as(OUTDATED_BUILDERS) + .bind(CLUSTER_BUILDER_SPEC) + .bind(&s.config.builder_image) + .fetch_all(&s.db) + .await?; for (id, cluster_id, node) in outdated { - let token = secret_token(); let mut tx = s.db.begin().await?; + let registry_host = registry_for(&mut *tx, &cluster_id).await?; + let (token, hash) = door_login(®istry_host); sqlx::query( - "UPDATE pyo.builders SET token_hash = $2, info = info || jsonb_build_object('specVersion', $3::int, 'image', $4::text), + "UPDATE pyo.builders SET token_hash = $2, info = info || jsonb_build_object('specVersion', $3::int, 'image', $4::text, 'keyAskedAt', pyo.ms(now())), status_message = CASE WHEN kind = 'server' THEN 'Starting the builder.' ELSE status_message END WHERE id = $1", ) .bind(&id) - .bind(sha256_hex(&token)) + .bind(hash) .bind(CLUSTER_BUILDER_SPEC) .bind(&s.config.builder_image) .execute(&mut *tx) @@ -366,7 +428,7 @@ async fn refresh_cluster_builders(s: &AppState) -> anyhow::Result<()> { api_url: s.config.agent_api_url.clone(), token, image: s.config.builder_image.clone(), - registry_host: registry_for(&mut *tx, &cluster_id).await?, + registry_host, }; deploy::enqueue( &mut tx, @@ -384,6 +446,8 @@ async fn refresh_cluster_builders(s: &AppState) -> anyhow::Result<()> { async fn watch_once(s: &AppState) -> anyhow::Result<()> { refresh_cluster_builders(s).await?; + // Folders sent with `pyo deploy` that were never built in time. + crate::source_uploads::sweep(&s.db).await?; sqlx::query("UPDATE pyo.builders SET status = 'offline' WHERE status = 'ready' AND last_seen_at < now() - interval '60 seconds'").execute(&s.db).await?; // Builds nobody finished (builder gone mid-build) fail after an hour. let stale: Vec<(String, String)> = sqlx::query_as( @@ -510,4 +574,162 @@ pub(crate) mod first_builder_tests { .await .unwrap(); } + + /// Against a real Postgres: a build goes to a builder of the deploy's + /// own cluster. Another cluster's builder takes it only when images go + /// to Pyo's registry and the deploy's cluster has no ready builder. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn builds_go_to_the_deploys_cluster() { + let pool = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&pool).await.unwrap(); + let run = crate::ids::random_string(8); + let team = format!("team_b{run}"); + let (one, two) = (format!("cl_1{run}"), format!("cl_2{run}")); + let (b1, b2) = (format!("bld_1{run}"), format!("bld_2{run}")); + let q = |sql: &'static str| sqlx::query(sql); + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&pool) + .await + .unwrap(); + for c in [&one, &two] { + q("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash) VALUES ($1, $2, $1, $1)").bind(c).bind(&team).execute(&pool).await.unwrap(); + } + q("INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, 'p', $1)") + .bind(format!("prj_{run}")) + .bind(&team) + .execute(&pool) + .await + .unwrap(); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec) VALUES ($1, $2, $3, $4, 'web', '{}')").bind(format!("svc_{run}")).bind(&team).bind(format!("prj_{run}")).bind(&two).execute(&pool).await.unwrap(); + q("INSERT INTO pyo.deployments (id, team_id, project_id, service_id, cluster_id, status, data, spec) VALUES ($1, $2, $3, $4, $5, 'building', '{}', '{}')").bind(format!("dpl_{run}")).bind(&team).bind(format!("prj_{run}")).bind(format!("svc_{run}")).bind(&two).execute(&pool).await.unwrap(); + for (b, c) in [(&b1, &one), (&b2, &two)] { + q("INSERT INTO pyo.builders (id, team_id, name, kind, cluster_id, server, token_hash, status) VALUES ($1, $2, $1, 'cluster', $3, 's', $1, 'ready')").bind(b).bind(&team).bind(c).execute(&pool).await.unwrap(); + } + let job = format!("bj_{run}"); + let queue = || async { + sqlx::query("DELETE FROM pyo.build_jobs WHERE id = $1") + .bind(&job) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.build_jobs (id, team_id, deployment_id, job) VALUES ($1, $2, $3, '{}')").bind(&job).bind(&team).bind(format!("dpl_{run}")).execute(&pool).await.unwrap(); + }; + let claim = |builder: &str, cluster: &str, others: bool| { + let (pool, team, builder, cluster) = ( + pool.clone(), + team.clone(), + builder.to_owned(), + cluster.to_owned(), + ); + async move { + sqlx::query_scalar::<_, serde_json::Value>(CLAIM_BUILD) + .bind(&team) + .bind(&builder) + .bind(&cluster) + .bind(others) + .fetch_optional(&pool) + .await + .unwrap() + .is_some() + } + }; + + // In-cluster registries: cluster one's builder never builds for two. + queue().await; + assert!(!claim(&b1, &one, false).await); + assert!(claim(&b2, &two, false).await); + // Pyo's registry: two's own builder first, while it's ready. + queue().await; + assert!(!claim(&b1, &one, true).await); + sqlx::query("UPDATE pyo.builders SET status = 'offline' WHERE id = $1") + .bind(&b2) + .execute(&pool) + .await + .unwrap(); + assert!( + claim(&b1, &one, true).await, + "two has none ready: one helps out" + ); + // In-cluster registries wait for two's own. + queue().await; + assert!(!claim(&b1, &one, false).await); + + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&pool) + .await + .unwrap(); + } +} + +#[cfg(test)] +mod key_tests { + use super::*; + + #[test] + fn only_a_builder_pushing_to_pyos_door_gets_a_login() { + let (t, h) = door_login(deploy::DOOR_IN_CLUSTER); + assert!(!t.is_empty() && h == sha256_hex(&t)); + let (t, h) = door_login("100.64.0.1:5006"); + assert!(!t.is_empty() && h == sha256_hex(&t)); + // Its cluster's own registry needs none: nothing to send, a hash of nothing anyone holds. + let (t, h) = door_login(deploy::INTERNAL_DEFAULT); + assert!(t.is_empty() && h.len() == 64); + assert!(door_login("").0.is_empty()); + } + + /// Against a throwaway Postgres: a builder without a key of its own gets + /// its spec again once its agent gives builders keys, at most every 10 + /// minutes, and not mid-build; one with a key, or on an older agent, doesn't. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn builders_without_a_key_get_their_spec_again() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()).await.unwrap(); + crate::migrate::run(&db).await.unwrap(); + let run = crate::ids::random_string(8); + let team = format!("team_b{run}"); + 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(); + let (new_agent, old_agent) = (format!("cl_n{run}"), format!("cl_o{run}")); + for (c, keys) in [(&new_agent, true), (&old_agent, false)] { + q("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash, capabilities) VALUES ($1, $2, $1, $1, $3)") + .bind(c).bind(&team).bind(json!({ "componentKeys": keys })).execute(&db).await.unwrap(); + } + let image = "builder@sha256:00"; + let add = |id: String, cluster: String, info: Value| { + let (db, team) = (db.clone(), team.clone()); + async move { + sqlx::query("INSERT INTO pyo.builders (id, team_id, name, kind, cluster_id, server, token_hash, status, info) VALUES ($1, $2, $1, 'cluster', $3, 's', $1, 'ready', $4)") + .bind(&id).bind(&team).bind(&cluster).bind(info).execute(&db).await.unwrap(); + id + } + }; + let current = json!({ "specVersion": CLUSTER_BUILDER_SPEC, "image": image }); + let keyless = add(format!("bld_a{run}"), new_agent.clone(), current.clone()).await; + let keyed = add(format!("bld_b{run}"), new_agent.clone(), current.clone()).await; + let busy = add(format!("bld_c{run}"), new_agent.clone(), json!({ "specVersion": CLUSTER_BUILDER_SPEC, "image": image, "busyWith": "job_1" })).await; + let asked = add(format!("bld_d{run}"), new_agent.clone(), json!({ "specVersion": CLUSTER_BUILDER_SPEC, "image": image, "keyAskedAt": pyo_proto::now_ms() })).await; + let older = add(format!("bld_e{run}"), old_agent.clone(), current.clone()).await; + let old_spec = add(format!("bld_f{run}"), old_agent.clone(), json!({ "specVersion": 3, "image": image })).await; + q("INSERT INTO pyo.agent_keys (id, cluster_id, public_key, expires_at, component, builder_id) VALUES ($1, $2, 'k', 'infinity', 'builder', $3)") + .bind(format!("akey_{run}")).bind(&new_agent).bind(&keyed).execute(&db).await.unwrap(); + let due: Vec = sqlx::query_as::<_, (String, String, String)>(OUTDATED_BUILDERS) + .bind(CLUSTER_BUILDER_SPEC) + .bind(image) + .fetch_all(&db) + .await + .unwrap() + .into_iter() + .map(|r| r.0) + .filter(|id| id.ends_with(&run)) + .collect(); + assert!(due.contains(&keyless) && due.contains(&old_spec), "{due:?}"); + for not in [&keyed, &busy, &asked, &older] { + assert!(!due.contains(not), "{not} isn't due: {due:?}"); + } + } } diff --git a/crates/pyo-api/src/bundles.rs b/crates/pyo-api/src/bundles.rs index c232ae40..6f1f0fd3 100644 --- a/crates/pyo-api/src/bundles.rs +++ b/crates/pyo-api/src/bundles.rs @@ -23,7 +23,7 @@ use pyo_proto::{ }, }; use serde_json::{Value, json}; -use sqlx::{PgPool, Postgres, Transaction}; +use sqlx::{Postgres, Transaction}; use crate::{deploy, error::ApiResult, ops::log_activity}; @@ -123,7 +123,7 @@ pub async fn ready_on( /// "ready", "failed" (with a message) or "removing". None where it isn't /// installed. pub async fn waf_state( - db: &PgPool, + db: &mut sqlx::PgConnection, cluster_ids: &[String], ) -> ApiResult> { let rows: Vec<(String, String, String, Value, Value)> = sqlx::query_as( @@ -132,7 +132,7 @@ pub async fn waf_state( ) .bind(WAF_ID) .bind(cluster_ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; Ok(rows .into_iter() @@ -178,12 +178,12 @@ pub fn waf_shown( /// Clusters with a firewall sync not done yet (sent or waiting): their /// services' routes and WAF policies are about to change. pub async fn syncing_firewall( - db: &PgPool, + db: &mut sqlx::PgConnection, cluster_ids: &[String], ) -> ApiResult> { let rows: Vec = sqlx::query_scalar("SELECT DISTINCT cluster_id FROM pyo.commands WHERE cluster_id = ANY($1) AND status IN ('pending', 'sent') AND command->>'kind' = 'sync_firewall'") .bind(cluster_ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; Ok(rows.into_iter().collect()) } @@ -390,7 +390,7 @@ pub async fn sync_databases( /// message). Ready once it runs a database there, so an update with Pyo /// doesn't count as setting up. None where it was never set up. pub async fn databases_state( - db: &PgPool, + db: &mut sqlx::PgConnection, cluster_ids: &[String], ) -> ApiResult> { let rows: Vec<(String, String, String, Value, Value, bool)> = sqlx::query_as( @@ -399,7 +399,7 @@ pub async fn databases_state( FROM pyo.cluster_bundles a JOIN pyo.clusters c ON c.id = a.cluster_id WHERE a.bundle = 'databases' AND a.cluster_id = ANY($1)", ) .bind(cluster_ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; Ok(rows .into_iter() @@ -439,11 +439,14 @@ pub fn operator_starting(engine: &str, workloads: &Value) -> Option { } /// Each cluster's workloads, as its last heartbeat reported them. -pub async fn workloads(db: &PgPool, cluster_ids: &[String]) -> ApiResult> { +pub async fn workloads( + db: &mut sqlx::PgConnection, + cluster_ids: &[String], +) -> ApiResult> { let rows: Vec<(String, Value)> = sqlx::query_as("SELECT id, workloads FROM pyo.clusters WHERE id = ANY($1)") .bind(cluster_ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; Ok(rows.into_iter().collect()) } diff --git a/crates/pyo-api/src/capacity.rs b/crates/pyo-api/src/capacity.rs index 02fd763f..60540f03 100644 --- a/crates/pyo-api/src/capacity.rs +++ b/crates/pyo-api/src/capacity.rs @@ -21,19 +21,7 @@ pub enum Ask { /// pods there ask for. None when no server has reported any. pub fn free_for(spec: &Value, servers: &[(String, Value, Vec)]) -> Option<(f64, f64)> { let gpu = spec["resources"]["gpu"].as_u64().is_some_and(|g| g > 0); - let named: Vec<&str> = spec["servers"] - .as_array() - .into_iter() - .flatten() - .filter_map(|n| n.as_str()) - .filter(|n| !n.is_empty()) - .collect(); - let tags: Vec<&str> = spec["serverTags"] - .as_array() - .into_iter() - .flatten() - .filter_map(|t| t.as_str()) - .collect(); + let placement = crate::placement::Placement::of(spec); let mut seen = false; let (mut cpu, mut mem) = (0.0, 0.0); for (name, r, have) in servers { @@ -42,8 +30,8 @@ pub fn free_for(spec: &Value, servers: &[(String, Value, Vec)]) -> Optio && r["maintenance"] != true && r["builder"] != true && (gpu || r["gpuDedicated"] != true) - && (named.is_empty() || named.contains(&name.as_str())) - && tags.iter().all(|t| have.iter().any(|h| h == t)); + && (!gpu || r["gpuDetected"] == true) + && placement.takes(name, have); let alloc = ( r["allocatable"]["cpu"].as_f64().unwrap_or(0.0), r["allocatable"]["memoryGi"].as_f64().unwrap_or(0.0), @@ -285,6 +273,14 @@ mod tests { free_for(&json!({ "servers": ["a"] }), &servers), Some((3.0, 6.0)) ); + // Servers and tags picked add up. + assert_eq!( + free_for( + &json!({ "placement": { "servers": ["a"], "tags": ["fast"] } }), + &servers + ), + Some((7.0, 14.0)) + ); assert_eq!(free_for(&json!({}), &[]), None, "nothing reported"); } diff --git a/crates/pyo-api/src/cli.rs b/crates/pyo-api/src/cli.rs index cccb8f2f..e2e50de7 100644 --- a/crates/pyo-api/src/cli.rs +++ b/crates/pyo-api/src/cli.rs @@ -1,118 +1,341 @@ //! `pyo login`, the CLI's sign-in. //! -//! The CLI listens on localhost and opens the dashboard's `/cli-login` page -//! with a challenge (sha256 of a verifier it keeps). The signed-in user -//! approves there: `POST /api/v1/cli/approve` makes a one-time code, which -//! the page hands to the CLI's localhost address. The CLI trades code and -//! verifier at `POST /api/cli/token` for an API key named after its machine, -//! good for a year unless `pyo login --expires` says otherwise (`pyo login` -//! again makes a new one). Only hashes are stored; codes last 5 minutes and work once. +//! The CLI asks for a sign-in at `POST /api/cli/start` with a challenge +//! (sha256 of a verifier it keeps) and gets back the request's id and a +//! short code. It shows the code and opens the dashboard's `/cli-login` +//! page for that id. A signed-in person types the code there to approve +//! it (or refuses it). Meanwhile the CLI polls `POST /api/cli/token` with +//! the id and its verifier, and gets an API key named after its computer +//! once approved, good for a year unless `pyo login --expires` says +//! otherwise (`pyo login` again makes a new one). +//! +//! Nothing goes from the browser to the CLI, so it works from any address +//! and any browser, also over SSH. The code stops a link someone else +//! sends from approving their CLI: it's only in the terminal that asked. +//! The key only goes to whoever holds the verifier. Only hashes are +//! stored. Requests last 10 minutes, work once, and end after five wrong +//! codes. use crate::error::Json; -use axum::{Router, extract::State, routing::post}; +use axum::{ + Router, + extract::{Path, State}, + http::StatusCode, + routing::{get, post}, +}; use serde::Deserialize; use serde_json::{Value, json}; +use sqlx::PgPool; use crate::{ AppState, auth::SessionUser, error::{ApiError, ApiResult}, ids::{new_id, secret_token, sha256_hex}, + ratelimit::{self, ClientIp}, }; -/// Approve, from the dashboard (a browser session, not an API key). +/// How long a request waits for its answer. +const MINUTES: i32 = 10; +/// Wrong codes a request takes before it ends. +const MAX_TRIES: i32 = 5; +/// The code's letters: consonants only, so no words and nothing that +/// reads like a digit. +const CODE_LETTERS: &[u8] = b"BCDFGHJKLMNPQRSTVWXZ"; + +/// Approve or refuse, from the dashboard (a browser session, not an API key). pub fn routes() -> Router { - Router::new().route("/cli/approve", post(approve)) + Router::new() + .route("/cli/logins/{id}", get(show)) + .route("/cli/logins/{id}/approve", post(approve)) + .route("/cli/logins/{id}/deny", post(deny)) } -/// The CLI's side: no session, the code and verifier are the proof. +/// The CLI's side: no session, the verifier is the proof. pub fn public_routes() -> Router { - Router::new().route("/token", post(token)) + Router::new() + .route("/start", post(start)) + .route("/token", post(token)) +} + +/// Gone, used or expired. (400 is a wrong code, so the page can tell.) +fn expired() -> ApiError { + ApiError::new( + StatusCode::GONE, + "This sign-in expired. Run pyo login again.", + ) +} + +fn refused() -> ApiError { + ApiError::forbidden("This sign-in was refused in the browser. Run pyo login again.") +} + +/// A new code: 8 letters, shown as ABCD-EFGH. +fn new_code() -> String { + let mut out = String::with_capacity(9); + while out.len() < 9 { + let mut b = [0u8; 16]; + rand::fill(&mut b[..]); + // 240 is 12 × 20: anything above would favor the first letters. + for x in b.into_iter().filter(|x| *x < 240) { + if out.len() == 4 { + out.push('-'); + } + if out.len() == 9 { + break; + } + out.push(CODE_LETTERS[(x % 20) as usize] as char); + } + } + out +} + +/// A typed code as stored: its letters only, in capitals. +fn code_key(code: &str) -> String { + let letters: String = code + .chars() + .filter(char::is_ascii_alphabetic) + .map(|c| c.to_ascii_uppercase()) + .collect(); + sha256_hex(&letters) +} + +/// Up to `max` printable characters. +fn clean(s: &str, max: usize) -> String { + s.trim() + .chars() + .filter(|c| !c.is_control()) + .take(max) + .collect() +} + +/// Days until a CLI key expires (None: never). +fn cli_key_days(expires: Option<&str>) -> ApiResult> { + match expires { + None | Some("1y") => Ok(Some(crate::auth::CLI_KEY_DAYS)), + Some("30d") => Ok(Some(30)), + Some("90d") => Ok(Some(90)), + Some("never") => Ok(None), + Some(_) => Err(ApiError::bad_request( + "The key expires in 30d, 90d, 1y or never.", + )), + } } #[derive(Deserialize)] -struct ApproveBody { +struct StartBody { challenge: String, + #[serde(default)] name: String, + /// The CLI's version and OS ("pyo 0.5.0 on linux"). + #[serde(default)] + client: String, + /// "30d", "90d", "1y" (the default) or "never". + #[serde(default)] + expires: Option, +} + +/// A new sign-in request: its id (for the page's link) and its code. +async fn start( + State(s): State, + ClientIp(ip): ClientIp, + Json(b): Json, +) -> ApiResult> { + ratelimit::take(&s.db, &[(ratelimit::CLI_LOGIN_IP, &ip)]).await?; + let (id, code) = start_login(&s.db, &b).await?; + Ok(Json(json!({ + "id": id, + "code": code, + "expiresIn": MINUTES * 60, + "interval": 2, + }))) +} + +async fn start_login(db: &PgPool, b: &StartBody) -> ApiResult<(String, String)> { + if b.challenge.len() != 64 || !b.challenge.bytes().all(|c| c.is_ascii_hexdigit()) { + return Err(ApiError::bad_request( + "Invalid login request. Run pyo login again.", + )); + } + let days = cli_key_days(b.expires.as_deref())?; + let (id, code) = (new_id("clg"), new_code()); + sqlx::query("DELETE FROM pyo.cli_login_requests WHERE expires_at < now()") + .execute(db) + .await?; + sqlx::query("INSERT INTO pyo.cli_login_requests (id, challenge, code_hash, name, client, key_days, expires_at) VALUES ($1, $2, $3, $4, $5, $6, now() + make_interval(mins => $7))") + .bind(&id) + .bind(b.challenge.to_ascii_lowercase()) + .bind(code_key(&code)) + .bind(clean(&b.name, 40)) + .bind(clean(&b.client, 60)) + .bind(days) + .bind(MINUTES) + .execute(db) + .await?; + Ok((id, code)) +} + +/// A request, for the approval page. +async fn show( + State(s): State, + SessionUser(_): SessionUser, + Path(id): Path, +) -> ApiResult> { + let row: Option<(String, String, String)> = sqlx::query_as( + "SELECT name, client, status FROM pyo.cli_login_requests WHERE id = $1 AND expires_at > now()", + ) + .bind(&id) + .fetch_optional(&s.db) + .await?; + let Some((name, client, status)) = row else { + return Err(expired()); + }; + Ok(Json( + json!({ "name": name, "client": client, "status": status }), + )) +} + +#[derive(Deserialize)] +struct ApproveBody { + code: String, } async fn approve( State(s): State, SessionUser(user): SessionUser, + Path(id): Path, Json(b): Json, ) -> ApiResult> { if user.key.is_some() { return Err(ApiError::forbidden("Approve the CLI from the dashboard.")); } - if b.challenge.len() != 64 || !b.challenge.bytes().all(|c| c.is_ascii_hexdigit()) { - return Err(ApiError::bad_request( - "Invalid login request. Run pyo login again.", - )); - } - let name: String = b - .name - .trim() - .chars() - .filter(|c| !c.is_control()) - .take(40) - .collect(); - let name = if name.is_empty() { - "CLI".to_owned() - } else { - format!("CLI · {name}") + approve_login(&s.db, &id, &user.id, &b.code).await?; + Ok(Json(json!({ "ok": true }))) +} + +async fn approve_login(db: &PgPool, id: &str, user_id: &str, code: &str) -> ApiResult<()> { + let mut tx = db.begin().await?; + let row: Option<(String, String, i32)> = sqlx::query_as( + "SELECT code_hash, status, tries FROM pyo.cli_login_requests WHERE id = $1 AND expires_at > now() FOR UPDATE", + ) + .bind(id) + .fetch_optional(&mut *tx) + .await?; + let Some((code_hash, status, tries)) = row else { + return Err(expired()); }; - let code = secret_token(); - sqlx::query("DELETE FROM pyo.cli_logins WHERE expires_at < now()") - .execute(&s.db) + match status.as_str() { + "pending" => {} + "approved" => return Err(ApiError::conflict("This sign-in is already approved.")), + _ => return Err(refused()), + } + if code_key(code) != code_hash { + let tries = tries + 1; + let end = tries >= MAX_TRIES; + sqlx::query("UPDATE pyo.cli_login_requests SET tries = $2, status = CASE WHEN $3 THEN 'denied' ELSE status END WHERE id = $1") + .bind(id) + .bind(tries) + .bind(end) + .execute(&mut *tx) + .await?; + tx.commit().await?; + return Err(if end { + ApiError::forbidden("Too many wrong codes. Run pyo login again.") + } else { + ApiError::bad_request("That's not the code in your terminal.") + }); + } + sqlx::query("UPDATE pyo.cli_login_requests SET status = 'approved', user_id = $2 WHERE id = $1") + .bind(id) + .bind(user_id) + .execute(&mut *tx) .await?; - sqlx::query("INSERT INTO pyo.cli_logins (code_hash, user_id, challenge, name, expires_at) VALUES ($1, $2, $3, $4, now() + interval '5 minutes')") - .bind(sha256_hex(&code)) - .bind(&user.id) - .bind(b.challenge.to_ascii_lowercase()) - .bind(&name) + tx.commit().await?; + Ok(()) +} + +async fn deny( + State(s): State, + SessionUser(_): SessionUser, + Path(id): Path, +) -> ApiResult> { + sqlx::query("UPDATE pyo.cli_login_requests SET status = 'denied' WHERE id = $1 AND status = 'pending'") + .bind(&id) .execute(&s.db) .await?; - Ok(Json(json!({ "ok": true, "code": code }))) + Ok(Json(json!({ "ok": true }))) } #[derive(Deserialize)] struct TokenBody { - code: String, + id: String, verifier: String, - /// "30d", "90d", "1y" (the default) or "never". - #[serde(default)] - expires: Option, } -/// Days until a CLI key expires (None: never). -fn cli_key_days(expires: Option<&str>) -> ApiResult> { - match expires { - None | Some("1y") => Ok(Some(crate::auth::CLI_KEY_DAYS)), - Some("30d") => Ok(Some(30)), - Some("90d") => Ok(Some(90)), - Some("never") => Ok(None), - Some(_) => Err(ApiError::bad_request( - "The key expires in 30d, 90d, 1y or never.", - )), - } +/// 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)) => { + let (s2, to) = (s.clone(), email.clone()); + tokio::spawn(async move { + crate::twofactor::mail_user(&s2, &to, "/api-keys", |link| { + crate::mail::new_api_key("CLI", link) + }) + .await; + }); + json!({ "token": key, "user": { "name": user_name, "email": email } }) + } + })) } -async fn token(State(s): State, Json(b): Json) -> ApiResult> { - let days = cli_key_days(b.expires.as_deref())?; - let row: Option<(String, String, String)> = sqlx::query_as("DELETE FROM pyo.cli_logins WHERE code_hash = $1 AND expires_at > now() RETURNING user_id, challenge, name") - .bind(sha256_hex(&b.code)) - .fetch_optional(&s.db) - .await?; - let Some((user_id, challenge, name)) = row else { - return Err(ApiError::bad_request( - "That login expired or was used. Run pyo login again.", - )); +/// 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); + +/// None while pending, else the new key and its user's name and email. +async fn poll_login( + db: &PgPool, + id: &str, + verifier: &str, +) -> ApiResult> { + let mut tx = db.begin().await?; + 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) + .fetch_optional(&mut *tx) + .await?; + let Some((challenge, status, user_id, name, days)) = row else { + return Err(expired()); }; - if sha256_hex(&b.verifier) != challenge { + if sha256_hex(verifier) != challenge { return Err(ApiError::bad_request( "That login doesn't match. Run pyo login again.", )); } + let user_id = match (status.as_str(), user_id) { + ("pending", _) => return Ok(None), + ("approved", Some(u)) => u, + _ => { + sqlx::query("DELETE FROM pyo.cli_login_requests WHERE id = $1") + .bind(id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + return Err(refused()); + } + }; + sqlx::query("DELETE FROM pyo.cli_login_requests WHERE id = $1") + .bind(id) + .execute(&mut *tx) + .await?; + let name = if name.is_empty() { + "CLI".to_owned() + } else { + format!("CLI · {name}") + }; let key = format!("{}{}", crate::auth::API_KEY_PREFIX, secret_token()); sqlx::query("INSERT INTO pyo.api_tokens (id, user_id, name, token_hash, prefix, access, expires_at) VALUES ($1, $2, $3, $4, $5, 'full', now() + make_interval(days => $6))") .bind(new_id("tok")) @@ -121,20 +344,32 @@ async fn token(State(s): State, Json(b): Json) -> ApiResult .bind(sha256_hex(&key)) .bind(key.chars().take(10).collect::()) .bind(days) - .execute(&s.db) + .execute(&mut *tx) .await?; - let (user_name, email): (String, String) = - sqlx::query_as("SELECT name, email FROM pyo.users WHERE id = $1") - .bind(&user_id) - .fetch_one(&s.db) - .await?; - Ok(Json( - json!({ "token": key, "user": { "name": user_name, "email": email } }), - )) + 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)); + crate::twofactor::notify_teams( + &mut tx, + &user, + "api_key.created", + &format!("Made API key {name} (full access) with pyo login"), + ) + .await?; + tx.commit().await?; + Ok(Some((key, user.name, user.email))) } #[cfg(test)] mod tests { + use super::*; + #[test] fn cli_key_lifetimes() { use super::cli_key_days as d; @@ -145,4 +380,139 @@ mod tests { assert_eq!(d(Some("never")).unwrap(), None); assert!(d(Some("7d")).is_err()); } + + #[test] + fn codes_read_easily() { + for _ in 0..200 { + let c = new_code(); + assert_eq!(c.len(), 9); + assert_eq!(&c[4..5], "-"); + assert!( + c.bytes() + .filter(|b| *b != b'-') + .all(|b| CODE_LETTERS.contains(&b)) + ); + } + // Typed in lower case, without the dash or with spaces: the same code. + assert_eq!(code_key("BCDF-GHJK"), code_key("bcdf ghjk")); + assert_ne!(code_key("BCDF-GHJK"), code_key("BCDF-GHJL")); + } + + /// A code that isn't `code`. + fn other(code: &str) -> &'static str { + if code.starts_with('B') { + "CCCC-CCCC" + } else { + "BBBB-BBBB" + } + } + + /// Against a real Postgres (DATABASE_URL, a throwaway one): a request + /// waits, takes only its own code, and gives its key once and only to + /// its verifier. Refused, mistyped and expired ones end. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn sign_in_requests() { + let pool = PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&pool).await.unwrap(); + let user = new_id("usr"); + sqlx::query( + "INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $2, 'C', '')", + ) + .bind(&user) + .bind(format!("{user}@cli.test")) + .execute(&pool) + .await + .unwrap(); + let verifier = secret_token(); + let body = |expires: Option<&str>| StartBody { + challenge: sha256_hex(&verifier), + name: "laptop\n".into(), + client: "pyo 0.5.0 on linux".into(), + expires: expires.map(str::to_owned), + }; + let msg = |e: ApiError| e.message; + + // 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")); + assert!( + msg(approve_login(&pool, &id, &user, other(&code)) + .await + .unwrap_err()) + .contains("not the code") + ); + approve_login(&pool, &id, &user, &code.to_lowercase()) + .await + .unwrap(); + assert!(approve_login(&pool, &id, &user, &code).await.is_err()); + let (key, _, email) = poll_login(&pool, &id, &verifier).await.unwrap().unwrap(); + 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", + ) + .bind(sha256_hex(&key)) + .fetch_one(&pool) + .await + .unwrap(); + 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"), + "used" + ); + + // Refused: the CLI hears so, then it's gone. + let (id, code) = start_login(&pool, &body(None)).await.unwrap(); + sqlx::query("UPDATE pyo.cli_login_requests SET status = 'denied' WHERE id = $1") + .bind(&id) + .execute(&pool) + .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")); + + // Five wrong codes end it, the right one after them too. + let (id, code) = start_login(&pool, &body(None)).await.unwrap(); + for _ in 0..MAX_TRIES { + assert!( + approve_login(&pool, &id, &user, other(&code)) + .await + .is_err() + ); + } + assert!(approve_login(&pool, &id, &user, &code).await.is_err()); + assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("refused")); + + // Expired: nothing to approve or poll. + let (id, code) = start_login(&pool, &body(None)).await.unwrap(); + sqlx::query( + "UPDATE pyo.cli_login_requests SET expires_at = now() - interval '1 second' WHERE id = $1", + ) + .bind(&id) + .execute(&pool) + .await + .unwrap(); + 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")); + + // A bad challenge or lifetime never starts. + let bad = StartBody { + challenge: "abc".into(), + ..body(None) + }; + assert!(start_login(&pool, &bad).await.is_err()); + assert!(start_login(&pool, &body(Some("7d"))).await.is_err()); + sqlx::query("DELETE FROM pyo.users WHERE id = $1") + .bind(&user) + .execute(&pool) + .await + .unwrap(); + } } diff --git a/crates/pyo-api/src/cloud/bootstrap.rs b/crates/pyo-api/src/cloud/bootstrap.rs index 2677233c..c19d2483 100644 --- a/crates/pyo-api/src/cloud/bootstrap.rs +++ b/crates/pyo-api/src/cloud/bootstrap.rs @@ -54,6 +54,7 @@ pub const WRONG_CODE_SERVER: Limit = Limit { scope: "cloud-bootstrap:server", max: 10, window_secs: 15 * 60, + backoff_cap_secs: 0, }; /// Wrong codes from anywhere: every ask comes through pyo-forward, so /// there's no address to tell askers apart. @@ -61,6 +62,7 @@ pub const WRONG_CODE_ALL: Limit = Limit { scope: "cloud-bootstrap:all", max: 60, window_secs: 15 * 60, + backoff_cap_secs: 0, }; /// What the server runs once it has its details. diff --git a/crates/pyo-api/src/cloud/mod.rs b/crates/pyo-api/src/cloud/mod.rs index a6be3841..d47300cf 100644 --- a/crates/pyo-api/src/cloud/mod.rs +++ b/crates/pyo-api/src/cloud/mod.rs @@ -436,12 +436,12 @@ pub async fn provider(db: &PgPool, team_id: &str) -> ApiResult Ok(hetzner::Hetzner::new(&t)?) } -/// Servers join over the tailnet: Tailscale comes first. -pub async fn needs_tailscale(db: &PgPool) -> ApiResult<()> { - if crate::tailscale::settings(db).await?.is_none() { - return Err(ApiError::bad_request(crate::tailscale::NEEDED)); - } - Ok(()) +/// Servers join over the tailnet: Tailscale comes first, on the cluster +/// they join (or, for a new cluster, the one Pyo runs on). +pub async fn needs_tailscale(db: &PgPool, cluster_id: Option<&str>) -> ApiResult<()> { + crate::tailscale::key_cluster(db, cluster_id) + .await + .map(|_| ()) } /// Saves a team's token once Hetzner accepts it (it lists the locations). @@ -452,7 +452,6 @@ pub async fn save(s: &AppState, team_id: &str, token: &str) -> ApiResult "Paste the API token from your Hetzner project's Security page. It's 64 letters and digits.", )); } - needs_tailscale(&s.db).await?; let locations = hetzner::Hetzner::new(token)?.locations().await?; let sealed = crate::vault::get().seal(team_id, token).await?; if !crate::vault::Vault::is_sealed(&sealed) { @@ -557,7 +556,7 @@ pub async fn options( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team, Role::Viewer).await?; drop(tx); let provider = q.provider.as_deref().unwrap_or("hetzner"); @@ -643,17 +642,31 @@ pub fn next_state(seen: &Seen, age: Duration) -> (&'static str, Option) ("failed", Some(why.into())) } -/// The tailnet's machines as the loop needs them, or None without -/// Tailscale. -async fn tailnet_devices(s: &AppState) -> Option> { - let (_, c) = crate::tailscale::saved_client(s).await.ok().flatten()?; - match c.device_details().await { - Ok(d) => Some(d), - Err(e) => { - tracing::warn!(error = %e, "cloud servers: couldn't read the tailnet"); - None - } - } +/// The cluster whose tailnet a server joins: its own cluster's, a sandbox +/// server's cluster, or the one Pyo runs on. +async fn tailnet_of(db: &PgPool, r: &Row) -> ApiResult> { + let via: Option = match (&r.cluster_id, &r.sandbox_server_id) { + (Some(c), _) => Some(c.clone()), + (None, Some(sbs)) => sqlx::query_scalar::<_, Option>( + "SELECT via_cluster FROM pyo.sandbox_servers WHERE id = $1", + ) + .bind(sbs) + .fetch_optional(db) + .await? + .flatten(), + (None, None) => None, + }; + Ok(crate::tailscale::key_cluster(db, via.as_deref()).await.ok()) +} + +/// Pyo's machines on a cluster's tailnet, as its last sync saw them, or +/// None without Tailscale there. +async fn tailnet_devices( + db: &PgPool, + cluster: Option<&str>, +) -> Option> { + let t = crate::tailscale::of(db, cluster?).await.ok().flatten()?; + Some(t.machines) } /// One pass: new servers move on, deleted ones go. Run by the Tailscale @@ -672,7 +685,6 @@ pub async fn tick(s: &AppState) -> ApiResult<()> { return Ok(()); } let install = crate::tailscale::install_id(&s.db).await?; - let devices = tailnet_devices(s).await; let mut providers: BTreeMap> = BTreeMap::new(); for r in rows { if !providers.contains_key(&r.team_id) { @@ -691,8 +703,10 @@ pub async fn tick(s: &AppState) -> ApiResult<()> { .await?; continue; }; + let tailnet = tailnet_of(&s.db, &r).await?; + let devices = tailnet_devices(&s.db, tailnet.as_deref()).await; let result = if r.state == "removing" { - finish_removal(s, p, &r, &install, devices.as_deref()).await + finish_removal(s, p, &r, &install, tailnet.as_deref(), devices.as_deref()).await } else { follow(s, p, &r, devices.as_deref()).await }; @@ -713,22 +727,22 @@ async fn set_error(db: &PgPool, id: &str, error: Option<&str>) -> ApiResult<()> Ok(()) } -/// The machine on the tailnet that is this server: tagged tag:pyo, by its -/// hostname. +/// The machine on the tailnet that is this server (Pyo's machines are +/// tagged tag:pyo), by its hostname. fn device_of<'a>( - devices: &'a [crate::tailscale::Device], + devices: &'a [pyo_proto::tailscale::Machine], name: &str, -) -> impl Iterator { - devices.iter().filter(move |d| { - d.hostname.eq_ignore_ascii_case(name) && d.tags.iter().any(|t| t == crate::tailscale::TAG) - }) +) -> impl Iterator { + devices + .iter() + .filter(move |d| d.hostname.eq_ignore_ascii_case(name)) } async fn follow( s: &AppState, p: &hetzner::Hetzner, r: &Row, - devices: Option<&[crate::tailscale::Device]>, + devices: Option<&[pyo_proto::tailscale::Machine]>, ) -> ApiResult<()> { let remote = p.server(&r.remote_id).await?; let mut refused = None; @@ -762,13 +776,10 @@ async fn follow( } (None, None) => None, }; - let mine: Vec<&crate::tailscale::Device> = devices + let mine: Vec<&pyo_proto::tailscale::Machine> = devices .map(|d| device_of(d, &r.name).collect()) .unwrap_or_default(); - let sign = mine - .iter() - .find(|d| !d.lock_error.is_empty() && !d.node_key.is_empty()) - .map(|d| format!("tailscale lock sign {}", d.node_key)); + let sign = mine.iter().find_map(|d| d.sign_command.clone()); let seen = Seen { remote: remote.as_ref().map(|x| x.status.clone()), on_tailnet: !mine.is_empty(), @@ -812,7 +823,8 @@ async fn finish_removal( p: &hetzner::Hetzner, r: &Row, install: &str, - devices: Option<&[crate::tailscale::Device]>, + tailnet: Option<&str>, + devices: Option<&[pyo_proto::tailscale::Machine]>, ) -> ApiResult<()> { let joined: Option<(Option, Option)> = match &r.cluster_id { Some(c) => sqlx::query_as( @@ -871,8 +883,9 @@ async fn finish_removal( } _ => {} } - // Off the tailnet: by the node ID its cluster reported, else by name. - if let Some((_, c)) = crate::tailscale::saved_client(s).await? { + // Off the tailnet (with the cluster's next sync): by the node ID its + // cluster reported, else by name. + if let Some(tailnet) = tailnet { let reported: Option = match &r.cluster_id { Some(cl) => sqlx::query_scalar( "SELECT t->>'nodeId' FROM pyo.clusters, jsonb_array_elements(coalesce(capabilities->'tailnet', '[]')) t @@ -893,9 +906,9 @@ async fn finish_removal( None }); if let Some(node) = node - && let Err(e) = c.delete_device(&node).await + && let Err(e) = crate::tailscale::forget_machine(&s.db, tailnet, &node).await { - tracing::warn!(server = %r.name, error = %e, "couldn't take the server off the tailnet"); + tracing::warn!(server = %r.name, error = %e.message, "couldn't take the server off the tailnet"); } } let owner = match (&r.cluster_id, &r.sandbox_server_id) { @@ -930,13 +943,16 @@ async fn finish_removal( /// For the dashboard: the team's connections (the token's end only), and /// the servers Pyo made. -pub async fn snapshot(db: &PgPool, team_ids: &[String]) -> ApiResult<(Value, Value)> { +pub async fn snapshot( + db: &mut sqlx::PgConnection, + team_ids: &[String], +) -> ApiResult<(Value, Value)> { let connections: Vec = sqlx::query_scalar( "SELECT jsonb_build_object('teamId', team_id, 'provider', kind, 'hint', hint, 'createdAt', pyo.ms(created_at)) FROM pyo.integrations WHERE team_id = ANY($1) AND kind = 'hetzner'", ) .bind(team_ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; let servers: Vec = sqlx::query_scalar( "SELECT jsonb_build_object('id', id, 'teamId', team_id, 'provider', provider, 'clusterId', cluster_id, @@ -948,7 +964,7 @@ pub async fn snapshot(db: &PgPool, team_ids: &[String]) -> ApiResult<(Value, Val FROM pyo.cloud_servers WHERE team_id = ANY($1) AND state <> 'deleted' ORDER BY created_at", ) .bind(team_ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; Ok((json!(connections), json!(servers))) } diff --git a/crates/pyo-api/src/cloudflare.rs b/crates/pyo-api/src/cloudflare.rs index de9e01ae..f845651a 100644 --- a/crates/pyo-api/src/cloudflare.rs +++ b/crates/pyo-api/src/cloudflare.rs @@ -28,7 +28,7 @@ use axum::{extract::State, http::StatusCode}; use reqwest::{Method, Url}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use sqlx::{PgPool, Postgres, Transaction}; +use sqlx::{Postgres, Transaction}; use crate::{ AppState, @@ -504,7 +504,7 @@ pub(crate) async fn account( let Some((sealed, zones)) = row else { return Ok(None); }; - let token = s.sealer.open(&sealed).map_err(|_| { + let token = crate::vault::get().open_credential(&s.sealer, &sealed).await.map_err(|_| { ApiError::new( StatusCode::SERVICE_UNAVAILABLE, "Pyo can't open the saved Cloudflare token. Connect Cloudflare again.", @@ -565,7 +565,11 @@ fn parse_role(r: &str) -> Role { } /// The teams' connections, for the snapshot. -pub async fn snapshot(db: &PgPool, user: &User, team_ids: &[String]) -> ApiResult> { +pub async fn snapshot( + db: &mut sqlx::PgConnection, + user: &User, + team_ids: &[String], +) -> ApiResult> { let rows: Vec<(Value, String)> = sqlx::query_as( "SELECT jsonb_build_object('teamId', c.team_id, 'zones', c.zones, 'hint', c.hint, 'createdBy', c.created_by, 'createdAt', pyo.ms(c.created_at), 'testedAt', pyo.ms(c.tested_at)), m.role @@ -575,7 +579,7 @@ pub async fn snapshot(db: &PgPool, user: &User, team_ids: &[String]) -> ApiResul ) .bind(team_ids) .bind(&user.id) - .fetch_all(db) + .fetch_all(&mut *db) .await?; Ok(rows .iter() @@ -584,7 +588,11 @@ pub async fn snapshot(db: &PgPool, user: &User, team_ids: &[String]) -> ApiResul } /// Each domain's record, as `dnsRecord` on the services' domains. -pub async fn attach(db: &PgPool, team_ids: &[String], services: &mut [Value]) -> ApiResult<()> { +pub async fn attach( + db: &mut sqlx::PgConnection, + team_ids: &[String], + services: &mut [Value], +) -> ApiResult<()> { let rows: Vec<(String, String, Value)> = sqlx::query_as( "SELECT service_id, domain_id, jsonb_build_object( 'zone', zone_name, 'type', type, 'content', content, 'proxied', proxied, 'proxy', proxy, @@ -593,7 +601,7 @@ pub async fn attach(db: &PgPool, team_ids: &[String], services: &mut [Value]) -> FROM pyo.dns_records WHERE team_id = ANY($1)", ) .bind(team_ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; if rows.is_empty() { return Ok(()); @@ -683,7 +691,7 @@ pub async fn connect( ON CONFLICT (team_id) DO UPDATE SET token_sealed = $2, hint = $3, zones = $4, created_by = $5, created_at = now(), tested_at = now()", ) .bind(team_id) - .bind(s.sealer.seal(token)?) + .bind(crate::vault::get().seal_credential(team_id, token).await?) .bind(hint(token)) .bind(json!(zones)) .bind(&user.name) @@ -792,7 +800,7 @@ pub async fn get( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let role = require_role(&mut tx, &user, &q.team, role_for(Action::ListZones)).await?; let row: Option = sqlx::query_scalar( "SELECT jsonb_build_object('teamId', team_id, 'zones', zones, 'hint', hint, 'createdBy', created_by, diff --git a/crates/pyo-api/src/cronruns.rs b/crates/pyo-api/src/cronruns.rs index dee20183..4a18fb70 100644 --- a/crates/pyo-api/src/cronruns.rs +++ b/crates/pyo-api/src/cronruns.rs @@ -153,7 +153,7 @@ pub async fn list( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = crate::ops::team_of(&mut tx, "services", &q.service).await?; crate::ops::require_role(&mut tx, &user, &team_id, crate::ops::Role::Viewer).await?; let runs: Vec = sqlx::query_scalar( diff --git a/crates/pyo-api/src/database_analytics.rs b/crates/pyo-api/src/database_analytics.rs index acb00c0e..85010cca 100644 --- a/crates/pyo-api/src/database_analytics.rs +++ b/crates/pyo-api/src/database_analytics.rs @@ -59,7 +59,7 @@ pub async fn analytics( Path(id): Path, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "databases", &id).await?; require_role(&mut tx, &user, &team_id, Role::Viewer).await?; let engine: String = sqlx::query_scalar("SELECT engine FROM pyo.databases WHERE id = $1") diff --git a/crates/pyo-api/src/database_backups.rs b/crates/pyo-api/src/database_backups.rs index 4dbc29e8..ddecea34 100644 --- a/crates/pyo-api/src/database_backups.rs +++ b/crates/pyo-api/src/database_backups.rs @@ -10,7 +10,7 @@ use axum::extract::State; use pyo_proto::{BackupSpec, Command, CommandResult, DbConnection}; use serde::Deserialize; use serde_json::{Value, json}; -use sqlx::{PgPool, Postgres, Transaction}; +use sqlx::{Postgres, Transaction}; use crate::{ AppState, @@ -362,7 +362,7 @@ pub async fn tick(s: &AppState) -> anyhow::Result<()> { } /// The dashboard's view of a team's databases, with a year of backups each. -pub async fn snapshot(db: &PgPool, team: &str) -> ApiResult> { +pub async fn snapshot(db: &mut sqlx::PgConnection, team: &str) -> ApiResult> { Ok(sqlx::query_scalar( "SELECT jsonb_build_object( 'id', d.id, 'clusterId', d.cluster_id, 'serviceId', d.service_id, 'name', d.name, 'engine', d.engine, @@ -377,6 +377,6 @@ pub async fn snapshot(db: &PgPool, team: &str) -> ApiResult> { FROM pyo.backup_databases d WHERE d.team_id = $1 ORDER BY d.name", ) .bind(team) - .fetch_all(db) + .fetch_all(&mut *db) .await?) } diff --git a/crates/pyo-api/src/database_imports.rs b/crates/pyo-api/src/database_imports.rs index 7938441a..0232ea94 100644 --- a/crates/pyo-api/src/database_imports.rs +++ b/crates/pyo-api/src/database_imports.rs @@ -1169,7 +1169,7 @@ pub(crate) async fn spec_part( /// The latest import of each of these databases, as listed. pub(crate) async fn listing( - db: &PgPool, + db: &mut sqlx::PgConnection, ids: &[String], ) -> ApiResult> { let rows: Vec<(String, Value)> = sqlx::query_as( @@ -1180,7 +1180,7 @@ pub(crate) async fn listing( FROM pyo.database_imports WHERE database_id = ANY($1) ORDER BY database_id, created_at DESC", ) .bind(ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; Ok(rows.into_iter().collect()) } diff --git a/crates/pyo-api/src/database_logs.rs b/crates/pyo-api/src/database_logs.rs index 8a6e1b75..4f568eb7 100644 --- a/crates/pyo-api/src/database_logs.rs +++ b/crates/pyo-api/src/database_logs.rs @@ -4,21 +4,26 @@ //! status the topology uses, so parts follow failovers. Events are the //! cluster's about the database, the status changes Pyo saw (recorded in //! `reported`) and the team's activity on it. Team members only, like -//! service logs; not an MCP tool for now. +//! service logs; not an MCP tool for now. Live, they're followed over one +//! WebSocket instead ([`follow`], logfollow.rs). use crate::error::Json; use crate::error::Query; use std::time::Duration; -use axum::extract::{Path, State}; -use pyo_proto::{Command, CommandResult, now_ms}; +use axum::extract::{ + Path, State, + ws::{Message, WebSocket}, +}; +use futures::{SinkExt, StreamExt}; +use pyo_proto::{Command, CommandResult, LogFrame, LogLine, now_ms}; use serde::Deserialize; use serde_json::{Value, json}; use sqlx::{Postgres, Transaction}; use crate::{ AppState, - auth::SessionUser, + auth::{SessionUser, User}, deploy, error::{ApiError, ApiResult, ErrorBody}, ops::{Role, require_role, team_of}, @@ -37,6 +42,12 @@ pub struct LogsQuery { /// `source` (the instance), `role` ("primary", "replica", "read", /// "pooler", "read-pooler", "sentinel", "proxy" (KV's endpoint) or "other"), `message`, and /// `raw` for structured lines. `events`: what happened to it, newest first. +/// To follow them live, open the WebSocket at `/databases/{id}/logs/follow`: +/// it sends the last lines, then new ones as they're printed, each text +/// frame `{"type":"lines","lines":[…]}`, and all events as +/// `{"type":"events","events":[…]}` when they change (or +/// `{"type":"error","message":…}`). It closes after an hour, so open it +/// again with `since` set to the newest line's time. #[utoipa::path(get, path = "/databases/{id}/logs", operation_id = "getDatabaseLogs", tag = "Databases", params(("id" = String, Path, description = "The database's id."), LogsQuery), responses( @@ -64,7 +75,7 @@ pub async fn logs( )); } }; - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "databases", &id).await?; require_role(&mut tx, &user, &team_id, Role::Viewer).await?; let (cluster_id, namespace, name, status): (String, String, String, Value) = sqlx::query_as( @@ -117,23 +128,37 @@ pub async fn logs( )); } let data = r.data.unwrap_or_default(); - let pods = &data["pods"]; let logs: Vec = r .logs .iter() - .map(|l| { - let (level, message, raw) = if l.level.is_empty() { parse_line(&l.message) } else { (l.level.clone(), l.message.clone(), None) }; - let mut v = json!({ "at": l.at, "level": level, "source": l.source, "role": role_of(&l.source, &name, &status, &pods[&l.source]["labels"]), "message": message }); - if let Some(raw) = raw { - v["raw"] = raw; - } - v - }) + .map(|l| shown_line(l, &name, &status, &data["pods"])) .collect(); + let mut events = cluster_events(&data["events"]); + events.extend(pyo_events(&s, &user, &team_id, &id).await?); + newest_first(&mut events); + Ok(Json( + json!({ "logs": logs, "events": events, "fetchedAt": now_ms() }), + )) +} + +/// A line as the logs show it: its level and message read, and its part +/// from the status and its pod's labels (`pods`, by pod name). +fn shown_line(l: &LogLine, name: &str, status: &Value, pods: &Value) -> Value { + let (level, message, raw) = if l.level.is_empty() { + parse_line(&l.message) + } else { + (l.level.clone(), l.message.clone(), None) + }; + let mut v = json!({ "at": l.at, "level": level, "source": l.source, "role": role_of(&l.source, name, status, &pods[&l.source]["labels"]), "message": message }); + if let Some(raw) = raw { + v["raw"] = raw; + } + v +} - // Events: the cluster's, the status changes Pyo recorded, and the - // team's changes to it, newest first. - let mut events: Vec = data["events"] +/// The cluster's events about it, as the logs show them. +fn cluster_events(events: &Value) -> Vec { + events .as_array() .into_iter() .flatten() @@ -141,21 +166,27 @@ pub async fn logs( let (kind, reason, message) = plain_event(e["type"].as_str().unwrap_or(""), e["reason"].as_str().unwrap_or(""), e["message"].as_str().unwrap_or("")); json!({ "at": e["at"], "type": kind, "reason": reason, "source": "cluster", "object": e["object"], "message": message, "count": e["count"] }) }) - .collect(); + .collect() +} + +/// The status changes Pyo recorded and the team's changes to database `id`. +async fn pyo_events(s: &AppState, user: &User, team_id: &str, id: &str) -> ApiResult> { + let mut tx = crate::rls::begin(&s.db, user).await?; let recorded: Vec<(i64, String, String, String)> = sqlx::query_as( "SELECT pyo.ms(at), type, reason, message FROM pyo.database_events WHERE database_id = $1 AND at > now() - interval '30 days' ORDER BY at DESC LIMIT 200", ) - .bind(&id) - .fetch_all(&s.db) + .bind(id) + .fetch_all(&mut *tx) .await?; - events.extend(recorded.into_iter().map(|(at, t, reason, message)| json!({ "at": at, "type": t, "reason": reason, "source": "pyo", "message": message }))); let changes: Vec<(i64, Value)> = sqlx::query_as( "SELECT pyo.ms(at), data FROM pyo.activity WHERE team_id = $1 AND data->'target'->>'id' = $2 AND at > now() - interval '30 days' ORDER BY at DESC LIMIT 100", ) - .bind(&team_id) - .bind(&id) - .fetch_all(&s.db) + .bind(team_id) + .bind(id) + .fetch_all(&mut *tx) .await?; + tx.commit().await?; + let mut events: Vec = recorded.into_iter().map(|(at, t, reason, message)| json!({ "at": at, "type": t, "reason": reason, "source": "pyo", "message": message })).collect(); events.extend(changes.into_iter().map(|(at, d)| { json!({ "at": at, @@ -165,10 +196,107 @@ pub async fn logs( "message": format!("{} ({})", d["title"].as_str().unwrap_or(""), d["actor"]["name"].as_str().unwrap_or("")), }) })); + Ok(events) +} + +fn newest_first(events: &mut [Value]) { events.sort_by_key(|e| std::cmp::Reverse(e["at"].as_i64().unwrap_or(0))); - Ok(Json( - json!({ "logs": logs, "events": events, "fetchedAt": now_ms() }), - )) +} + +/// How often a followed database's status and Pyo's events are read again. +const FOLLOW_REFRESH: Duration = Duration::from_secs(15); + +/// The database a reader follows (logfollow.rs). +pub(crate) struct Followed { + pub id: String, + pub team_id: String, + pub name: String, +} + +/// Relays a database's follow from its agent (`agent`) to the reader: +/// lines as [`logs`] shows them, each with its part, and all events again +/// whenever they change. Until either side closes. +pub(crate) async fn follow( + s: &AppState, + user: &User, + f: &Followed, + reader: WebSocket, + agent: WebSocket, +) { + let (mut r_tx, mut r_rx) = reader.split(); + let (mut a_tx, mut a_rx) = agent.split(); + let status_of = || async { + sqlx::query_scalar::<_, Value>("SELECT status FROM pyo.databases WHERE id = $1") + .bind(&f.id) + .fetch_optional(&s.db) + .await + .ok() + .flatten() + .unwrap_or_default() + }; + let mut status = status_of().await; + let mut pods = Value::Null; + let mut cluster: Vec = vec![]; + let mut sent: Option> = None; + // All events, when they differ from what the reader has. + let events = |cluster: &[Value], sent: &mut Option>, mine: Vec| { + let mut all = cluster.to_vec(); + all.extend(mine); + newest_first(&mut all); + if sent.as_ref() == Some(&all) { + return None; + } + *sent = Some(all.clone()); + Some(json!({ "type": "events", "events": all })) + }; + let mut refresh = + tokio::time::interval_at(tokio::time::Instant::now() + FOLLOW_REFRESH, FOLLOW_REFRESH); + loop { + let out = tokio::select! { + m = r_rx.next() => match m { + Some(Ok(Message::Close(_)) | Err(_)) | None => break, + Some(Ok(_)) => None, + }, + m = a_rx.next() => match m { + Some(Ok(Message::Text(t))) => match serde_json::from_str::(t.as_str()) { + Ok(LogFrame::Lines { lines }) => { + let lines: Vec = lines.iter().map(|l| shown_line(l, &f.name, &status, &pods)).collect(); + Some(json!({ "type": "lines", "lines": lines })) + } + // Its pods changed (a failover, a new replica): the + // status that names their parts too, likely. + Ok(LogFrame::Pods { pods: p }) => { + pods = p; + status = status_of().await; + None + } + Ok(LogFrame::Events { events: e }) => { + cluster = cluster_events(&Value::Array(e)); + let mine = pyo_events(s, user, &f.team_id, &f.id).await.unwrap_or_default(); + events(&cluster, &mut sent, mine) + } + Ok(LogFrame::Error { message }) => Some(json!({ "type": "error", "message": message })), + Err(_) => None, + }, + Some(Ok(Message::Close(_)) | Err(_)) | None => break, + Some(Ok(_)) => None, + }, + _ = refresh.tick() => { + status = status_of().await; + match pyo_events(s, user, &f.team_id, &f.id).await { + Ok(mine) => events(&cluster, &mut sent, mine), + Err(_) => None, + } + } + }; + if let Some(v) = out + && r_tx.send(Message::text(v.to_string())).await.is_err() + { + break; + } + } + let _ = a_tx.close().await; + let _ = r_tx.close().await; } /// The controller's event reasons that read better in words: (type, diff --git a/crates/pyo-api/src/databases.rs b/crates/pyo-api/src/databases.rs index 2e3051d8..099d5443 100644 --- a/crates/pyo-api/src/databases.rs +++ b/crates/pyo-api/src/databases.rs @@ -22,7 +22,7 @@ use axum::extract::{Path, State}; use pyo_proto::{Command, DatabaseReport, DatabaseSpec, EnvVar, NamedSecret}; use serde::Deserialize; use serde_json::{Value, json}; -use sqlx::{PgPool, Postgres, Transaction}; +use sqlx::{Postgres, Transaction}; use crate::{ AppState, @@ -397,7 +397,7 @@ async fn destination( team_id: &str, cluster_id: &str, ) -> ApiResult { - let Some(t) = crate::teambackup::settings(&s.db, team_id).await? else { + let Some(t) = crate::teambackup::settings(tx, team_id).await? else { return Err(ApiError::conflict( "Set where the team's backups go first (Backups).", )); @@ -1482,13 +1482,13 @@ async fn set_kv_backups( } /// A KV database's backups, as Backups has them; null until first turned on. -async fn kv_backup(pool: &PgPool, id: &str) -> ApiResult { +async fn kv_backup(db: &mut sqlx::PgConnection, id: &str) -> ApiResult { Ok(sqlx::query_scalar( "SELECT jsonb_build_object('enabled', enabled, 'schedule', schedule, 'hour', hour, 'keep', keep, 'backupDatabaseId', id) FROM pyo.backup_databases WHERE database_id = $1", ) .bind(id) - .fetch_optional(pool) + .fetch_optional(db) .await? .unwrap_or(Value::Null)) } @@ -2270,22 +2270,26 @@ pub async fn finished( } /// The databases of these teams, as listed (never logins). -pub async fn listing(db: &PgPool, team_ids: &[String], id: Option<&str>) -> ApiResult> { +pub async fn listing( + db: &mut sqlx::PgConnection, + team_ids: &[String], + id: Option<&str>, +) -> ApiResult> { let rows: Vec = sqlx::query_as::<_, Db>( "SELECT id, team_id, cluster_id, name, engine, version, size, storage_gi, instances, pooler, rest, deletion_protection, namespace, password, token, readonly_token, state, backup, restore, restored_from, read_replicas, cpu_millis, memory_mi, extensions FROM pyo.databases WHERE team_id = ANY($1) AND ($2::text IS NULL OR id = $2) ORDER BY created_at", ) .bind(team_ids) .bind(id) - .fetch_all(db) + .fetch_all(&mut *db) .await?; // Where the databases system is on their clusters: "setting up" while // it's being installed there (a first database waits for it). let clusters: Vec = rows.iter().map(|d| d.cluster_id.clone()).collect(); - let systems = crate::bundles::databases_state(db, &clusters).await?; - let workloads = crate::bundles::workloads(db, &clusters).await?; + let systems = crate::bundles::databases_state(&mut *db, &clusters).await?; + let workloads = crate::bundles::workloads(&mut *db, &clusters).await?; let imports = crate::database_imports::listing( - db, + &mut *db, &rows.iter().map(|d| d.id.clone()).collect::>(), ) .await?; @@ -2304,7 +2308,7 @@ pub async fn listing(db: &PgPool, team_ids: &[String], id: Option<&str>) -> ApiR FROM pyo.databases m WHERE m.id = $1", ) .bind(&d.id) - .fetch_one(db) + .fetch_one(&mut *db) .await?; // Being made while its operator starts (stopped while the cluster // had no databases of its engine). @@ -2337,7 +2341,7 @@ pub async fn listing(db: &PgPool, team_ids: &[String], id: Option<&str>) -> ApiR "size": d.size, "cpu": cpu, "memory": memory, "storageGi": d.storage_gi, "instances": d.instances, "pooler": d.pooler, "rest": d.rest, "deletionProtection": d.deletion_protection, "state": d.state, "status": status, "members": members, "createdAt": created_at, "connections": links, - "backup": if point_in_time(&d.engine) { json!({ "enabled": d.backup["enabled"].as_bool().unwrap_or(false), "retentionDays": d.backup["retentionDays"].as_i64().unwrap_or(7), "hour": d.backup["hour"].as_i64().unwrap_or(3) }) } else { kv_backup(db, &d.id).await? }, + "backup": if point_in_time(&d.engine) { json!({ "enabled": d.backup["enabled"].as_bool().unwrap_or(false), "retentionDays": d.backup["retentionDays"].as_i64().unwrap_or(7), "hour": d.backup["hour"].as_i64().unwrap_or(3) }) } else { kv_backup(&mut *db, &d.id).await? }, "restoredFrom": d.restored_from, "import": imports.get(&d.id).cloned().unwrap_or(Value::Null), "readReplicas": read_replicas_of(&d, &status), @@ -2378,12 +2382,11 @@ pub(crate) async fn list( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team, Role::Viewer).await?; + let databases = listing(&mut tx, &[q.team], None).await?; tx.commit().await?; - Ok(Json( - json!({ "databases": listing(&s.db, &[q.team], None).await? }), - )) + Ok(Json(json!({ "databases": databases }))) } /// A database @@ -2401,12 +2404,12 @@ pub(crate) async fn get( SessionUser(user): SessionUser, Path(id): Path, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "databases", &id).await?; require_role(&mut tx, &user, &team_id, Role::Viewer).await?; + let db = listing(&mut tx, &[team_id], Some(&id)).await?; tx.commit().await?; - let db = listing(&s.db, &[team_id], Some(&id)) - .await? + let db = db .into_iter() .next() .ok_or_else(|| ApiError::not_found("Database"))?; @@ -3051,7 +3054,7 @@ mod tests { #[tokio::test] #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] async fn deletions_are_retried_and_orphans_cleaned_up() { - let pool = PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + let pool = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) .await .unwrap(); crate::migrate::run(&pool).await.unwrap(); diff --git a/crates/pyo-api/src/deploy.rs b/crates/pyo-api/src/deploy.rs index 60a4cbf6..07e6b9ac 100644 --- a/crates/pyo-api/src/deploy.rs +++ b/crates/pyo-api/src/deploy.rs @@ -72,26 +72,40 @@ pub fn registry_push() -> String { .unwrap_or_default() } +/// Every other cluster keeps the images it builds in its own registry +/// (`PYO_CLUSTER_REGISTRY=in-cluster`, Pyo Cloud): connect.sh's +/// `--local-registry` sets it up, and its servers pull them from +/// 127.0.0.1:5005 as on Pyo's own. +pub fn in_cluster_registries() -> bool { + std::env::var("PYO_CLUSTER_REGISTRY").is_ok_and(|v| v.trim() == "in-cluster") +} + /// Where a builder on this cluster pushes: the door in the cluster on Pyo's -/// own, its tailnet address elsewhere (None without one). +/// own, its own registry with in-cluster registries, else Pyo's door at its +/// tailnet address (None without one). pub fn builder_registry(on_pyos_cluster: bool) -> Option { if on_pyos_cluster { return Some(DOOR_IN_CLUSTER.into()); } + if in_cluster_registries() { + return Some(INTERNAL_DEFAULT.into()); + } let push = registry_push(); (!push.is_empty()).then_some(push) } -/// A build job for a deployment's Git source. +/// A build job for a deployment's Git source, or for a folder uploaded +/// with `pyo deploy` (source_uploads.rs), built with the same settings. fn build_job( id: &str, deployment_id: &str, service_id: &str, source: &Value, upload_site: bool, + upload: Option, ) -> pyo_proto::BuildJob { let r = registry(); - pyo_proto::BuildJob { + let mut job = pyo_proto::BuildJob { id: id.to_owned(), deployment_id: deployment_id.to_owned(), repo_url: str_at(source, &["repoUrl"]).trim().to_owned(), @@ -133,7 +147,42 @@ fn build_job( clone_token: None, clone_username: None, upload_site, + source_upload: None, + }; + if let Some(u) = upload { + // Nothing to clone, and no repository to report a commit status to. + job.repo_url = String::new(); + job.branch = String::new(); + job.commit = String::new(); + job.github_installation_id = None; + job.git_connection_id = None; + job.source_upload = Some(u); + } + job +} + +/// A deployment's source for a folder uploaded with `pyo deploy`: where it +/// came from, for the dashboard ("Uploaded from …"), and the service's +/// build settings (a Git service's too, deployed with `--local`). +fn upload_source(service_source: &Value, u: &crate::source_uploads::Claimed) -> Value { + let mut src = json!({ + "type": "upload", + "uploadId": u.job.id, + "sha256": u.job.sha256, + "size": u.job.size, + "files": u.files, + "folder": u.folder, + "machine": u.machine, + }); + for k in ["dockerfilePath", "buildContext", "buildArgs"] { + if !service_source[k].is_null() { + src[k] = service_source[k].clone(); + } + } + if service_source["type"] == json!("git") { + src["fromGit"] = json!(true); } + src } const FINAL: [&str; 3] = ["succeeded", "failed", "cancelled"]; @@ -174,6 +223,22 @@ pub fn image_ref(source: &Value) -> ApiResult { r => format!("{image}:{r}"), }) } + // From a folder (`pyo deploy`): each deploy uploads it, or reuses + // the image built last. + "upload" => { + for (k, what) in [ + ("dockerfilePath", "Dockerfile path"), + ("buildContext", "Build context"), + ] { + let v = str_at(source, &[k]); + if v.contains("..") || v.contains(['#', ':', ' ']) { + return Err(ApiError::bad_request(format!( + "{what} can't contain '..', '#', ':' or spaces." + ))); + } + } + Ok(String::new()) + } // Built by a builder; the image is known once the build finishes. "git" => { let url = str_at(source, &["repoUrl"]).trim(); @@ -382,14 +447,9 @@ pub fn build_spec( firewall: None, waf: None, site: None, - server_names: spec["servers"] - .as_array() - .into_iter() - .flatten() - .filter_map(|n| n.as_str()) - .filter(|n| !n.is_empty()) - .map(str::to_owned) - .collect(), + // Servers and tags picked (placement.rs), set again by `create`. + server_names: crate::placement::Placement::of(spec).servers, + server_tags: crate::placement::Placement::of(spec).tags, node_selector: { let mut m: std::collections::BTreeMap = Default::default(); if let Some((region, zone)) = pyo_proto::location_labels(str_at(spec, &["location"])) { @@ -398,15 +458,6 @@ pub fn build_spec( m.insert(pyo_proto::ZONE_LABEL.to_owned(), z); } } - // Placed by tag: only on servers carrying every one of them. - for t in spec["serverTags"] - .as_array() - .into_iter() - .flatten() - .filter_map(|t| t.as_str().and_then(pyo_proto::valid_tag)) - { - m.insert(format!("{}{t}", pyo_proto::TAG_LABEL_PREFIX), "true".into()); - } m }, deployment_id: deployment_id.to_owned(), @@ -496,6 +547,9 @@ pub struct DeployRequest<'a> { pub retry_of: Option<&'a str>, /// Build this commit instead of the source's pin or branch head (a push). pub commit: Option<&'a str>, + /// Build this uploaded folder (source_uploads.rs) instead of the + /// service's source. + pub upload: Option<&'a str>, } /// What a deployment needs of its service: team, project, cluster, spec, @@ -540,6 +594,19 @@ pub async fn create( )); } + let service_kind = str_at(&spec, &["source", "type"]).to_owned(); + let upload = match req.upload { + Some(id) => { + if !matches!(service_kind.as_str(), "git" | "upload") { + return Err(ApiError::bad_request( + "This service runs an image, so it isn't built from a folder.", + )); + } + Some(crate::source_uploads::claim(tx, id, &team_id, req.deployment_id).await?) + } + None => None, + }; + // Rollbacks and retries reuse the exact spec of an earlier deployment. let earlier = req.rollback_of.or(req.retry_of); let (mut deploy_spec, source) = if let Some(prev_id) = earlier { @@ -580,7 +647,53 @@ pub async fn create( crate::secretstores::import_env(tx, &team_id, &spec, &mut built.env).await?; // `${{postgres.DATABASE_URL}}` and the like, from the project's services. crate::refs::resolve(tx, &project_id, &namespace, &mut built.env).await?; - (built, spec["source"].clone()) + match &upload { + Some(u) => (built, upload_source(&spec["source"], u)), + // A service from a folder deployed again without one: the image + // built last, with the settings it has now. + None if service_kind == "upload" => { + let live: Option<(Value, Value)> = match &live_id { + Some(l) => { + sqlx::query_as("SELECT spec, data FROM pyo.deployments WHERE id = $1") + .bind(l) + .fetch_optional(&mut **tx) + .await? + } + None => None, + }; + let image = live.as_ref().and_then(|(spec, data)| { + data["pinnedImage"] + .as_str() + .or(spec["image"].as_str()) + .filter(|i| !i.is_empty()) + .map(str::to_owned) + }); + let Some(image) = image else { + return Err(ApiError::conflict( + "This service is built from a folder. Deploy it from there: pyo deploy", + )); + }; + built.image = image; + ( + built, + live.map(|(_, d)| d["source"].clone()).unwrap_or_default(), + ) + } + None => (built, spec["source"].clone()), + } + }; + // A retried build of an upload builds the same folder, while Pyo has it. + let retried_upload = match (req.retry_of, &source["type"]) { + (Some(_), t) if t == "upload" && deploy_spec.image.is_empty() => Some( + crate::source_uploads::reclaim( + tx, + str_at(&source, &["uploadId"]), + &team_id, + req.deployment_id, + ) + .await?, + ), + _ => None, }; // A static deploy's folder, when it's still kept and the service still // serves static builds as files; else its image runs as a service. @@ -595,6 +708,16 @@ pub async fn create( // Its volumes as they are now, rollbacks included: a volume detached // (or attached) since isn't mounted (or is) by an older version. deploy_spec.volumes = volume_specs(&attached_volumes(tx, req.service_id).await?); + // Where it runs as set now, rollbacks included: a placement change + // went live without a deploy (placement.rs). + { + let p = crate::placement::Placement::of(&spec); + deploy_spec.server_names = p.servers; + deploy_spec.server_tags = p.tags; + deploy_spec + .node_selector + .retain(|k, _| !k.starts_with(pyo_proto::TAG_LABEL_PREFIX)); + } // The cluster's traffic mode now, rollbacks included. deploy_spec.traffic_mode = sqlx::query_scalar::<_, Option>( "SELECT traffic_mode FROM pyo.clusters WHERE id = $1", @@ -625,14 +748,26 @@ pub async fn create( // pushed first (names stay put when a team, project or service is // renamed). Nothing else of Pyo registry's, and nothing else on this // machine's own addresses. + // Pyo Cloud: an image the team pushed to this cluster's own registry, + // by its door's tailnet name. The servers pull it from the registry + // itself, and the door only took the team's own. + let mut in_this_cluster = false; + if let Some(door) = crate::registrydoor::cluster_address(tx, &cluster_id).await? + && let Some(rest) = deploy_spec.image.strip_prefix(&format!("{door}/")) + { + deploy_spec.image = format!("{}/{rest}", registry().pull); + in_this_cluster = true; + } match pyo_registry_image(&deploy_spec.image) { + _ if in_this_cluster => {} Some(Ok(pulled)) => deploy_spec.image = pulled, Some(Err(why)) => return Err(ApiError::forbidden(why)), None => {} } - if let Some(rest) = deploy_spec - .image - .strip_prefix(&format!("{}/", registry().pull)) + if !in_this_cluster + && let Some(rest) = deploy_spec + .image + .strip_prefix(&format!("{}/", registry().pull)) { let repo = rest.split('@').next().unwrap_or(rest); let repo = repo @@ -677,25 +812,45 @@ pub async fn create( // No image yet: a Git source that has to be built first. let needs_build = deploy_spec.image.is_empty(); if needs_build { + // A builder of the service's cluster builds it (builders.rs), or + // one of another cluster when images go to Pyo's registry. + let anywhere = crate::builders::builds_for_other_clusters(); let ready: bool = sqlx::query_scalar( - "SELECT EXISTS (SELECT 1 FROM pyo.builders WHERE team_id = $1 AND status = 'ready')", + "SELECT EXISTS (SELECT 1 FROM pyo.builders WHERE team_id = $1 AND status = 'ready' AND ($3 OR cluster_id = $2))", ) .bind(&team_id) + .bind(&cluster_id) + .bind(anywhere) .fetch_one(&mut **tx) .await?; if !ready { return Err(ApiError::conflict( - "Git deploys need a builder. Add one in Builders, then deploy again.", + match (anywhere, source["type"] == json!("upload")) { + (true, false) => { + "Git deploys need a builder. Add one in Builders, then deploy again." + } + (false, false) => { + "Git deploys need a builder in the service's cluster. Add one in Builders, then deploy again." + } + (true, true) => { + "Deploying a folder needs a builder. Add one in Builders, then deploy again." + } + (false, true) => { + "Deploying a folder needs a builder in the service's cluster. Add one in Builders, then deploy again." + } + }, )); } } let now = now_ms(); - let revision_label = if needs_build { + let revision_label = if needs_build && source["type"] == json!("upload") { + str_at(&source, &["sha256"]).chars().take(7).collect() + } else if needs_build { match str_at(&source, &["commit"]) { "" => str_at(&source, &["branch"]).to_owned(), c => c.chars().take(7).collect(), } - } else if source["type"] == json!("git") { + } else if matches!(source["type"].as_str(), Some("git" | "upload")) { // A rollback or retry of a build: same image, same commit. deploy_spec .image @@ -761,6 +916,7 @@ pub async fn create( req.service_id, &source, crate::sites::serves_static(&spec), + upload.map(|u| u.job).or(retried_upload), ); sqlx::query( "INSERT INTO pyo.build_jobs (id, team_id, deployment_id, job) VALUES ($1, $2, $3, $4)", @@ -788,6 +944,37 @@ pub async fn create( Ok(cluster_id) } +/// Cancels a deployment that hasn't finished: the agent stops watching it +/// (and settles it cancelled), a build that hasn't finished is dropped, and +/// a rollout it hasn't picked up yet is withdrawn. Its cluster, to wake. +pub async fn cancel(tx: &mut Transaction<'_, Postgres>, deployment_id: &str) -> ApiResult { + let cluster_id: String = + sqlx::query_scalar("SELECT cluster_id FROM pyo.deployments WHERE id = $1") + .bind(deployment_id) + .fetch_one(&mut **tx) + .await?; + enqueue( + tx, + &cluster_id, + Command::Cancel { + deployment_id: deployment_id.to_owned(), + }, + ) + .await?; + // A build that hasn't finished is dropped; its result is ignored. + sqlx::query("UPDATE pyo.build_jobs SET status = 'cancelled', finished_at = now() WHERE deployment_id = $1 AND status IN ('queued', 'running')") + .bind(deployment_id) + .execute(&mut **tx) + .await?; + crate::source_uploads::drop_for(&mut **tx, deployment_id).await?; + // Queued work the agent hasn't picked up yet is withdrawn here. + sqlx::query("UPDATE pyo.commands SET status = 'failed', done_at = now(), result = '{\"ok\":false,\"message\":\"Cancelled\",\"logs\":[]}' WHERE status = 'pending' AND command->>'kind' = 'deploy' AND command->>'deploymentId' = $1") + .bind(deployment_id) + .execute(&mut **tx) + .await?; + Ok(cluster_id) +} + /// How long a rollout waits for its service's databases before it fails. pub const DATABASE_WAIT_SECS: i64 = 15 * 60; @@ -1016,6 +1203,8 @@ pub async fn enqueue( .bind(cluster_id) .fetch_one(&mut **tx) .await?; + // A hosted team's plan paused or ended: no changes (gate.rs). + crate::gate::check_queue(tx, &team, stored["kind"].as_str().unwrap_or("")).await?; crate::vault::get().seal_env(&team, &mut stored).await?; crate::teambackup::seal_command(&team, &mut stored).await?; // clock_timestamp(), not now(): commands queued in one transaction keep @@ -1552,6 +1741,8 @@ pub async fn sweeper(state: AppState) { tick.tick().await; let Some(r) = crate::bg::as_leader(&state.db, crate::bg::LOCK_SWEEPER, || async { let _ = crate::jobs::prune(&state).await; + // Once a day: teams that keep analytics shorter. + crate::retention::nightly(&state).await; let _ = crate::certs::warn_expiring(&state).await; if let Err(e) = crate::alerts::flush(&state.db).await { tracing::warn!(error = ?e.message, "sending held alerts failed"); @@ -1559,6 +1750,9 @@ pub async fn sweeper(state: AppState) { if let Err(e) = release_waiting(&state).await { tracing::warn!(error = ?e.message, "releasing rollouts held for databases failed"); } + if let Err(e) = crate::gate::resume(&state).await { + tracing::warn!(error = ?e.message, "sending held back syncs again failed"); + } sweep(&state, started.elapsed() > AGENTS_BACK).await }) .await @@ -1685,6 +1879,8 @@ pub async fn finish_build( tx.commit().await?; return Ok(None); }; + // Built (or not): an uploaded folder isn't needed any more. + crate::source_uploads::drop_for(&mut *tx, &deployment_id).await?; // The service's id, not the label in the spec: the builder pushed to // pyo/services/ (build_job). let (cluster_id, service_id, status, mut spec, mut data): (String, String, String, Value, Value) = @@ -1771,9 +1967,12 @@ pub async fn finish_build( .execute(&mut *tx) .await?; } - data["revision"] = json!(r.commit); - data["revisionLabel"] = json!(r.commit.chars().take(7).collect::()); - data["source"]["commit"] = json!(r.commit); + // An uploaded folder has no commit: its label stays the archive's. + if !r.commit.is_empty() { + data["revision"] = json!(r.commit); + data["revisionLabel"] = json!(r.commit.chars().take(7).collect::()); + data["source"]["commit"] = json!(r.commit); + } // "Dockerfile" or "Containerfile", or the framework Railpack detected. if let Some(how) = &r.detected { data["source"]["builder"] = @@ -1982,7 +2181,7 @@ mod build_job_tests { "type": "git", "repoUrl": "https://github.com/acme/site", "branch": "main", "buildArgs": [{ "key": "RAILPACK_SPA_OUTPUT_DIR", "value": "build" }, { "key": "", "value": "dropped" }], }); - let job = super::build_job("bld_1", "dpl_1", "svc_1", &source, true); + let job = super::build_job("bld_1", "dpl_1", "svc_1", &source, true, None); assert_eq!(job.build_args.len(), 1); assert_eq!( ( @@ -1991,6 +2190,56 @@ mod build_job_tests { ), ("RAILPACK_SPA_OUTPUT_DIR", "build") ); + assert!(job.source_upload.is_none()); + } + + #[test] + fn an_upload_builds_with_the_services_settings_and_clones_nothing() { + let git = json!({ + "type": "git", "repoUrl": "https://github.com/acme/site", "branch": "main", "installationId": 7, + "dockerfilePath": "docker/Dockerfile", "buildContext": "web", + "buildArgs": [{ "key": "A", "value": "1" }], + }); + let claimed = crate::source_uploads::Claimed { + job: pyo_proto::SourceUpload { + id: "src_1".into(), + size: 10, + sha256: "ab".repeat(32), + }, + files: 3, + folder: "site".into(), + machine: "laptop".into(), + }; + let source = super::upload_source(&git, &claimed); + assert_eq!(source["type"], "upload"); + assert_eq!(source["machine"], "laptop"); + assert_eq!(source["fromGit"], true); + assert!(source["repoUrl"].is_null()); + let job = super::build_job( + "bld_1", + "dpl_1", + "svc_1", + &source, + false, + Some(claimed.job.clone()), + ); + assert_eq!(job.repo_url, ""); + assert_eq!(job.github_installation_id, None); + assert_eq!( + (job.dockerfile_path.as_str(), job.build_context.as_str()), + ("docker/Dockerfile", "web") + ); + assert_eq!(job.build_args.len(), 1); + assert_eq!( + job.source_upload.as_ref().map(|u| u.id.as_str()), + Some("src_1") + ); + assert!( + super::image_ref(&json!({ "type": "upload" })) + .unwrap() + .is_empty() + ); + assert!(super::image_ref(&json!({ "type": "upload", "buildContext": "../x" })).is_err()); } } @@ -2272,6 +2521,8 @@ pub async fn set_domain_dns( /// Checks the DNS of domains still waiting for it, so nobody has to press a /// button: every 30 seconds for an hour after a domain is added, then every /// 5 minutes for a day, then every 30 minutes. +/// Not tailnet domains: Pyo can't look those up (only devices on the +/// tailnet can), so they follow the cluster's tailnet (tailscale.rs). pub async fn dns_watcher(state: AppState) { let mut tick = tokio::time::interval(Duration::from_secs(15)); loop { @@ -2288,11 +2539,12 @@ pub async fn dns_watcher(state: AppState) { } } -async fn check_pending_dns(state: &AppState) -> ApiResult<()> { +pub(crate) async fn check_pending_dns(state: &AppState) -> ApiResult<()> { let due: Vec<(String, String, String, String)> = sqlx::query_as( "SELECT a.id, a.team_id, d->>'id', d->>'hostname' 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' 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 new file mode 100644 index 00000000..9e38879e --- /dev/null +++ b/crates/pyo-api/src/domainproof.rs @@ -0,0 +1,361 @@ +//! Proof of owning a domain, before a team may claim it (Pyo Cloud). +//! +//! Hostnames are first come over every team of an installation, so where +//! teams don't trust each other one could claim another's domain first. +//! There ([`crate::verify_domains`]), a team claims a hostname only with a +//! DNS TXT record `_pyo-verify.` holding the token Pyo gives that +//! team for that host. A team that proves it can take a hostname over from +//! a team that can't (anymore). Free domains (nip.io and sslip.io) need no +//! record: their address must be one of the team's own servers. +//! +//! TXT records are read from the domain's own name servers, asked +//! directly with nothing cached ([`authoritative_txt`]): what the team set +//! there just now counts, and no resolver in between can answer for them. +//! The name servers themselves are found through the system's resolver. +//! For tests only, `PYO_DEV_TXT_FILE` names a JSON file of records to use +//! instead (`{"_pyo-verify.example.com": ["pyo-verify-…"]}`), and +//! `PYO_DEV_TXT_DOH` a DNS over HTTPS endpoint to ask instead (one that +//! answers `application/dns-json`, such as Cloudflare's). + +use std::time::Duration; + +use hickory_resolver::{ + config::{NameServerConfig, ResolveHosts, ResolverConfig, ResolverOpts}, + proto::rr::{Name, RData, RecordType}, +}; +use serde_json::Value; +use sqlx::{Postgres, Transaction}; + +use crate::error::ApiResult; + +/// The record a team adds for `host`. +pub fn record(host: &str) -> String { + format!("_pyo-verify.{host}") +} + +/// The token a team puts in `host`'s record: the same every time, and +/// another team's never matches. +pub fn token(team_id: &str, host: &str) -> String { + let h = crate::ids::sha256_hex(&format!("pyo-verify\n{team_id}\n{}", host.to_lowercase())); + format!("pyo-verify-{}", &h[..32]) +} + +/// What to tell a team that hasn't proven `host` yet. +pub fn how_to(team_id: &str, host: &str) -> String { + format!( + "Prove you own {host} first: add a TXT record {} with the value {}, then try again.", + record(host), + token(team_id, host) + ) +} + +/// The TXT values at `name`. +async fn txt(name: &str) -> Vec { + if let Ok(path) = std::env::var("PYO_DEV_TXT_FILE") + && !path.trim().is_empty() + { + let v: Value = std::fs::read(path.trim()) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default(); + return v[name] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(); + } + if let Ok(url) = std::env::var("PYO_DEV_TXT_DOH") + && !url.trim().is_empty() + { + return doh_txt(url.trim(), name).await; + } + match authoritative_txt(name).await { + Ok(v) => v, + Err(e) => { + tracing::info!(%name, error = %e, "domain proof: no TXT record read"); + vec![] + } + } +} + +/// How long each step may take, and how many name servers are asked. +const DNS_TIMEOUT: Duration = Duration::from_secs(4); +const NAME_SERVERS: usize = 4; + +/// The TXT values at `name`, asked of its zone's own name servers: the +/// zone is the nearest name at or above it with NS records, found through +/// the system's resolver; then its name servers are asked directly, without +/// recursion or a cache. A CNAME there is followed (a few times at most). +pub async fn authoritative_txt(name: &str) -> anyhow::Result> { + let recursive = hickory_resolver::Resolver::builder_tokio()? + .with_options(dns_options(true)) + .build()?; + let mut name = Name::from_ascii(name.trim_end_matches('.'))?; + name.set_fqdn(true); + for _ in 0..4 { + let servers = zone_servers(&recursive, &name).await?; + let config = ResolverConfig::from_name_servers( + servers + .into_iter() + .map(NameServerConfig::udp_and_tcp) + .collect(), + ); + let authoritative = hickory_resolver::Resolver::builder_with_config( + config, + hickory_resolver::net::runtime::TokioRuntimeProvider::default(), + ) + .with_options(dns_options(false)) + .build()?; + let answers = match authoritative.lookup(name.clone(), RecordType::TXT).await { + Ok(l) => l.answers().to_vec(), + Err(e) if e.is_no_records_found() || e.is_nx_domain() => { + // Nothing, unless the name is a CNAME to follow. + match authoritative.lookup(name.clone(), RecordType::CNAME).await { + Ok(l) => l.answers().to_vec(), + Err(e) if e.is_no_records_found() || e.is_nx_domain() => return Ok(vec![]), + Err(e) => return Err(e.into()), + } + } + Err(e) => return Err(e.into()), + }; + let txt: Vec = answers + .iter() + .filter_map(|r| match &r.data { + RData::TXT(t) => Some( + t.txt_data + .iter() + .map(|c| String::from_utf8_lossy(c).into_owned()) + .collect::(), + ), + _ => None, + }) + .collect(); + if !txt.is_empty() { + return Ok(txt); + } + let Some(target) = answers.iter().find_map(|r| match &r.data { + RData::CNAME(c) => Some(c.0.clone()), + _ => None, + }) else { + return Ok(vec![]); + }; + name = target; + } + anyhow::bail!("too many CNAMEs") +} + +fn dns_options(recursive: bool) -> ResolverOpts { + let mut o = ResolverOpts::default(); + o.timeout = DNS_TIMEOUT; + o.attempts = 2; + o.use_hosts_file = ResolveHosts::Never; + if !recursive { + // Ask the name servers themselves, fresh each time. + o.recursion_desired = false; + o.cache_size = 0; + } + o +} + +/// The addresses of the name servers of the zone `name` is in. +async fn zone_servers( + recursive: &hickory_resolver::TokioResolver, + name: &Name, +) -> anyhow::Result> { + let mut zone = name.clone(); + loop { + anyhow::ensure!(zone.num_labels() >= 2, "no zone found for {name}"); + if let Ok(l) = recursive.lookup(zone.clone(), RecordType::NS).await { + let ns: Vec = l + .answers() + .iter() + .filter_map(|r| match &r.data { + RData::NS(n) if r.name == zone => Some(n.0.clone()), + _ => None, + }) + .collect(); + if !ns.is_empty() { + let mut ips = vec![]; + for n in ns.into_iter().take(NAME_SERVERS) { + if let Ok(found) = recursive.lookup_ip(n).await { + ips.extend(found.iter().take(2)); + } + } + anyhow::ensure!( + !ips.is_empty(), + "the name servers of {zone} have no address" + ); + return Ok(ips); + } + } + zone = zone.base_name(); + } +} + +/// The TXT values at `name` through DNS over HTTPS (`PYO_DEV_TXT_DOH`). +async fn doh_txt(url: &str, name: &str) -> Vec { + let Ok(client) = reqwest::Client::builder() + .timeout(Duration::from_secs(8)) + .build() + else { + return vec![]; + }; + let Ok(res) = client + .get(url) + .query(&[("name", name), ("type", "TXT")]) + .header("accept", "application/dns-json") + .send() + .await + else { + return vec![]; + }; + let v: Value = res.json().await.unwrap_or_default(); + v["Answer"] + .as_array() + .into_iter() + .flatten() + .filter(|a| a["type"] == 16) + .filter_map(|a| a["data"].as_str()) + .map(|d| d.trim().trim_matches('"').to_owned()) + .collect() +} + +/// Whether `host`'s record holds `team_id`'s token now. +pub async fn proven(team_id: &str, host: &str) -> bool { + let want = token(team_id, host); + txt(&record(host)).await.contains(&want) +} + +/// A free domain on one of the team's own servers' addresses (it can't +/// hold a TXT record, and points only at that server anyway). +async fn own_free_domain( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + host: &str, +) -> ApiResult> { + let Some(ip) = crate::freedomain::ip_in(host) else { + return Ok(None); + }; + let clusters: Vec = sqlx::query_scalar("SELECT id FROM pyo.clusters WHERE team_id = $1") + .bind(team_id) + .fetch_all(&mut **tx) + .await?; + for c in clusters { + if let Some((_, cluster)) = crate::freedomain::load(tx, &c).await? + && cluster.known().contains(&std::net::IpAddr::V4(ip)) + { + return Ok(Some(true)); + } + } + Ok(Some(false)) +} + +/// 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). +pub async fn check_claims( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + service_id: &str, + new_hosts: &[String], +) -> ApiResult> { + use crate::error::ApiError; + let mut wake = vec![]; + for host in new_hosts { + if pyo_proto::system::is_tailnet_host(host) { + continue; + } + match own_free_domain(tx, team_id, host).await? { + Some(true) => continue, + Some(false) => { + return Err(ApiError::forbidden(format!( + "{host} points at a server that isn't one of this team's." + ))); + } + None => {} + } + if !proven(team_id, host).await { + return Err(ApiError::forbidden(how_to(team_id, host))); + } + // Held by another team: theirs while they can still prove it. + let holders: Vec<(String, String, Value)> = sqlx::query_as( + "SELECT a.id, a.team_id, a.spec->'domains' FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d + WHERE a.id <> $1 AND a.team_id <> $2 AND NOT a.deleting AND lower(d->>'hostname') = $3", + ) + .bind(service_id) + .bind(team_id) + .bind(host) + .fetch_all(&mut **tx) + .await?; + for (other_service, other_team, domains) in holders { + if proven(&other_team, host).await { + return Err(ApiError::conflict(format!("{host} is already used by another service."))); + } + let kept: Vec = domains + .as_array() + .into_iter() + .flatten() + .filter(|d| d["hostname"].as_str().map(str::to_lowercase).as_deref() != Some(host.as_str())) + .cloned() + .collect(); + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(&other_service) + .bind(Value::Array(kept)) + .execute(&mut **tx) + .await?; + if let Some(c) = crate::routes::changed(tx, &other_service, true).await? { + wake.push(c); + } + crate::ops::log_activity( + tx, + &other_team, + "Pyo", + "domain.removed", + "warning", + &format!("{host} was removed: another team proved it owns it"), + serde_json::json!({ "kind": "service", "id": other_service, "label": host }), + serde_json::json!({}), + ) + .await?; + tracing::info!(%host, from = %other_team, to = %team_id, "domain taken over by its proven owner"); + } + } + Ok(wake) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tokens_differ_by_team_and_host() { + assert_eq!(token("t1", "Example.com"), token("t1", "example.com")); + assert_ne!(token("t1", "example.com"), token("t2", "example.com")); + assert_ne!(token("t1", "example.com"), token("t1", "www.example.com")); + assert!(how_to("t1", "a.com").contains("_pyo-verify.a.com")); + } + + /// Over the internet: a TXT record read from its zone's own name + /// servers (`cargo test -p pyo-api domainproof -- --ignored`). + #[tokio::test] + #[ignore = "needs the internet"] + async fn reads_txt_from_the_zones_own_name_servers() { + let spf = authoritative_txt("google.com").await.unwrap(); + assert!(spf.iter().any(|t| t.starts_with("v=spf1")), "{spf:?}"); + // A name with no TXT record, and one that doesn't exist. + assert!( + authoritative_txt("_pyo-verify.google.com") + .await + .unwrap() + .is_empty() + ); + assert!( + authoritative_txt("no-such-name-for-pyo.example.com") + .await + .unwrap() + .is_empty() + ); + } +} diff --git a/crates/pyo-api/src/firewall.rs b/crates/pyo-api/src/firewall.rs index 2f01e74b..d5bd46b3 100644 --- a/crates/pyo-api/src/firewall.rs +++ b/crates/pyo-api/src/firewall.rs @@ -391,25 +391,6 @@ pub async fn sync(tx: &mut Transaction<'_, Postgres>, cluster_id: &str) -> ApiRe Ok(()) } -/// Every service's firewall on every cluster, for naming the rule behind a -/// refusal: (cluster, service) -> its firewall. -pub async fn all_firewalls( - db: &sqlx::PgPool, -) -> ApiResult> { - let mut tx = db.begin().await?; - let services: Vec<(String, String)> = - sqlx::query_as("SELECT cluster_id, id FROM pyo.services WHERE NOT deleting") - .fetch_all(&mut *tx) - .await?; - let mut out = std::collections::HashMap::new(); - for (cluster, service) in services { - let f = for_service(&mut tx, &service).await?; - out.insert((cluster, service), f); - } - tx.commit().await?; - Ok(out) -} - /// Fill in a deploy's firewall (none without rules) and WAF /// (`waf_for`). pub async fn fill( @@ -425,22 +406,6 @@ pub async fn fill( Ok(()) } -/// Why the proxy refused a request or connection, from its log line: -/// "blocked" (an allow or block rule; the proxy doesn't say which) or -/// "rate-limit"; "" when it didn't. -pub fn refusal(details: &str, termination: &str, status: u64) -> String { - if [details, termination] - .iter() - .any(|d| d.starts_with("rbac_access_denied_matched_policy[")) - { - return "blocked".into(); - } - if status == 429 && details.contains("rate_limited") { - return "rate-limit".into(); - } - String::new() -} - #[cfg(test)] mod tests { use super::*; @@ -555,22 +520,4 @@ mod tests { "Allow if client IP is in 203.0.113.7, 2001:db8::/32" ); } - - #[test] - fn refusals() { - assert_eq!( - refusal("rbac_access_denied_matched_policy[DENY]", "", 403), - "blocked" - ); - assert_eq!( - refusal("rbac_access_denied_matched_policy[none]", "", 403), - "blocked" - ); - assert_eq!( - refusal("", "rbac_access_denied_matched_policy[DENY]", 0), - "blocked" - ); - assert_eq!(refusal("local_rate_limited", "", 429), "rate-limit"); - assert_eq!(refusal("via_upstream", "", 403), ""); - } } diff --git a/crates/pyo-api/src/freedomain.rs b/crates/pyo-api/src/freedomain.rs index 1c4e13bb..1accf9ac 100644 --- a/crates/pyo-api/src/freedomain.rs +++ b/crates/pyo-api/src/freedomain.rs @@ -31,7 +31,9 @@ //! Free domains Pyo made on another of the cluster's addresses (a private //! one, the other mode's, one a server no longer has) or in the older //! dashed form ("203-0-113-7.nip.io") follow it: [`rehome`] moves them in -//! place, with a routes sync (no redeploy). +//! place, with a routes sync (no redeploy). One on the public IP stays +//! there while the cluster has one, whatever the mode: the dashboard adds +//! free domains on the public IP ([`Cluster::home`]). use std::net::{IpAddr, Ipv4Addr}; @@ -239,8 +241,20 @@ impl Cluster { } } + /// 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, + /// private) follows the free-domain address. + pub fn home(&self, ip: Ipv4Addr) -> Option { + if public(&IpAddr::V4(ip)) { + self.public_ip().or_else(|| self.address()) + } else { + self.address() + } + } + /// Every address of its own: where a free domain Pyo made could point. - fn known(&self) -> Vec { + pub(crate) fn known(&self) -> Vec { let mut known: Vec = self.servers.iter().flat_map(addresses).collect(); known.extend( self.lb_ips @@ -302,10 +316,15 @@ fn parts(rest: &str) -> Option<(&str, Ipv4Addr, bool)> { } /// The hostname a free domain moves to: one on another of the cluster's -/// own addresses (`known`), or in the dashed form, goes to `to`. Any other -/// hostname stays. -pub fn moved(host: &str, known: &[IpAddr], to: Ipv4Addr) -> Option { +/// own addresses (`known`), or in the dashed form, goes to where `to` says +/// a domain on its address goes. Any other hostname stays. +pub fn moved( + host: &str, + known: &[IpAddr], + to: impl Fn(Ipv4Addr) -> Option, +) -> Option { let (label, ip, dashed) = split(host)?; + let to = to(ip)?; let ours = ip == to || known.contains(&IpAddr::V4(ip)); (ours && (ip != to || dashed)).then(|| format!("{label}.{to}.nip.io")) } @@ -395,9 +414,6 @@ pub async fn rehome(tx: &mut Transaction<'_, Postgres>, cluster_id: &str) -> Api let Some((team_id, c)) = load(tx, cluster_id).await? else { return Ok(false); }; - let Some(to) = c.address() else { - return Ok(false); - }; let known = c.known(); let services: Vec<(String, String, Value)> = sqlx::query_as( "SELECT id, name, spec->'domains' FROM pyo.services @@ -411,7 +427,7 @@ pub async fn rehome(tx: &mut Transaction<'_, Postgres>, cluster_id: &str) -> Api let mut changes = vec![]; for d in domains.as_array_mut().into_iter().flatten() { let host = d["hostname"].as_str().unwrap_or("").to_owned(); - let Some(new) = moved(&host, &known, to) else { + let Some(new) = moved(&host, &known, |ip| c.home(ip)) else { continue; }; if taken(tx, &new).await? { @@ -449,14 +465,18 @@ pub async fn rehome(tx: &mut Transaction<'_, Postgres>, cluster_id: &str) -> Api } /// Whether a service already has the hostname. +/// Any team's: row security is lifted for it (rls.rs). async fn taken(tx: &mut Transaction<'_, Postgres>, host: &str) -> ApiResult { - Ok(sqlx::query_scalar( + let lifted = crate::rls::lift(tx).await?; + let taken = sqlx::query_scalar( "SELECT EXISTS (SELECT 1 FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d WHERE NOT a.deleting AND d->>'hostname' = $1)", ) .bind(host) .fetch_one(&mut **tx) - .await?) + .await?; + lifted.lower(tx).await?; + Ok(taken) } /// A domain on its new hostname: its DNS and certificate start over, and @@ -773,7 +793,7 @@ mod tests { .map(|s| s.parse().unwrap()) .collect(); let public = v4("129.226.158.31"); - let m = |h: &str, to| moved(h, &known, to); + let m = |h: &str, to| moved(h, &known, |_| Some(to)); // The private address, in either form, and the older dashed form. assert_eq!( m("whoami-web.10-3-8-13.nip.io", public).as_deref(), @@ -811,6 +831,36 @@ mod tests { assert_eq!(m("10.3.8.13.nip.io", public), None); } + #[test] + fn a_free_domain_on_the_public_ip_stays_there() { + let public = v4("129.226.158.31"); + let tailnet = v4("100.101.67.2"); + let private = v4("10.3.8.13"); + // Behind NAT, so Tailscale: one added on the public IP stays, any + // other follows the Tailscale IP. + let c = cluster(true, None, vec![nat_server()]); + assert_eq!(c.mode(), Mode::Tailscale); + assert_eq!(c.home(public), Some(public)); + assert_eq!(c.home(v4("203.0.113.7")), Some(public)); + assert_eq!(c.home(private), Some(tailnet)); + // Public: the Tailscale IP's follow the public IP. + let c = cluster(true, Some("public"), vec![nat_server()]); + assert_eq!(c.home(tailnet), Some(public)); + assert_eq!(c.home(public), Some(public)); + // No public traffic: the public IP's go to the Tailscale IP. + let c = cluster(false, None, vec![nat_server()]); + assert_eq!(c.home(public), Some(tailnet)); + // In a rehome. + let c = cluster(true, None, vec![nat_server()]); + let known = c.known(); + let m = |h: &str| moved(h, &known, |ip| c.home(ip)); + assert_eq!(m("app.129.226.158.31.nip.io"), None); + assert_eq!( + m("app.10.3.8.13.nip.io").as_deref(), + Some("app.100.101.67.2.nip.io") + ); + } + #[test] fn a_moved_domain_starts_over_on_https() { let mut d = json!({ "id": "dom_1", "hostname": "a.10-3-8-13.nip.io", "status": "active", "tls": "issued", "tlsMode": "auto", diff --git a/crates/pyo-api/src/gate.rs b/crates/pyo-api/src/gate.rs new file mode 100644 index 00000000..927125ed --- /dev/null +++ b/crates/pyo-api/src/gate.rs @@ -0,0 +1,295 @@ +//! A hosted Pyo's teams whose plan is paused or has ended (Pyo Cloud +//! Terms, sections 9 and 11): their clusters get no new commands. One +//! check, [`Entitlements::can_command`](crate::Entitlements::can_command), +//! asked where commands are queued (a person's or API key's request is +//! refused with its message) and where agents take them (anything else +//! held back fails with it, unsigned). +//! +//! Still allowed: heartbeats and their replies (not commands), so servers +//! keep reporting. Commands that only read what the dashboard shows. And +//! removals, so a team can delete its things and leave. +//! +//! Self-hosted Pyo has no entitlements: nothing is held back. +//! +//! What was held back isn't lost: the team is marked, and once its plan +//! allows commands again its clusters get what Pyo wants there sent once +//! more ([`resume`]). + +use axum::http::StatusCode; +use sqlx::PgConnection; + +use crate::error::{ApiError, ApiResult}; + +/// Commands that only read. +const READS: &[&str] = &[ + "fetch_logs", + "follow_logs", + "follow_database_logs", + "fetch_database_logs", + "query_traffic", + "list_snapshots", + "cancel", +]; + +/// Commands that remove a team's things. +const REMOVALS: &[&str] = &[ + "delete_service", + "delete_database", + "delete_volume", + "delete_namespace", + "remove_bundle", + "remove_builder", + "remove_server", + "forget_snapshot", + "tailscale_remove", +]; + +/// Commands that follow a change made elsewhere, a removal's too (the +/// firewall without a deleted service's WAF, the static file server +/// without its last site). Queued without an error, then held back with +/// the rest. +const FOLLOW_ONS: &[&str] = &[ + "sync_routes", + "sync_firewall", + "sync_registry_tokens", + "sync_cron_jobs", + "apply_bundle", + "tailscale_sync", +]; + +/// Why a team's clusters get no new commands, when the entitlement doesn't say. +pub const STOPPED: &str = "This team's Pyo Cloud plan is paused or has ended, so its servers get no new commands. Your services keep running. Pay in Settings › Billing to resume."; + +/// Whether a command of this kind still goes out while a team's plan is +/// paused or has ended. +pub fn allowed(kind: &str) -> bool { + READS.contains(&kind) || REMOVALS.contains(&kind) +} + +/// Whether queueing a command of this kind asks the entitlement: for a +/// person's or API key's request (`request`), and a kind that's held back +/// and isn't a change's follow-on. +fn asks_at_queue(kind: &str, request: bool) -> bool { + request && !allowed(kind) && !FOLLOW_ONS.contains(&kind) +} + +/// Before a command of `kind` is queued for one of `team_id`'s clusters: +/// fails with 402 and the entitlement's message when a person's or API +/// key's request asks for one its team may not get now. Commands queued +/// by Pyo itself go in the queue, and [`held_back`] fails them. +pub(crate) async fn check_queue( + conn: &mut PgConnection, + team_id: &str, + kind: &str, +) -> ApiResult<()> { + let Some(e) = crate::ENTITLEMENTS.get() else { + return Ok(()); + }; + if allowed(kind) { + return Ok(()); + } + // A request's transaction is lowered to its teams (rls.rs). A hosted + // build's billing tables are outside row security. + let lifted = crate::rls::lift(conn).await?; + let out = if asks_at_queue(kind, lifted.was_scoped()) { + e.can_command(conn, team_id).await + } else { + Ok(()) + }; + lifted.lower(conn).await?; + out.map_err(|m| ApiError::new(StatusCode::PAYMENT_REQUIRED, m)) +} + +/// When an agent takes commands: why `team_id`'s clusters get none now +/// but reads and removals, if so. +pub(crate) async fn held_back(db: &sqlx::PgPool, team_id: &str) -> ApiResult> { + let Some(e) = crate::ENTITLEMENTS.get() else { + return Ok(None); + }; + let mut conn = db.acquire().await?; + Ok(e.can_command(&mut conn, team_id).await.err()) +} + +/// A command of `team_id`'s was held back: [`resume`] sends its clusters +/// their syncs again once its plan allows it. +pub(crate) async fn mark_held(db: &sqlx::PgPool, team_id: &str) { + let _ = sqlx::query( + "UPDATE pyo.teams SET commands_held_at = now() WHERE id = $1 AND commands_held_at IS NULL", + ) + .bind(team_id) + .execute(db) + .await; +} + +/// From the worker's sweep: each team that had commands held back and may +/// get commands again has its clusters' syncs queued once more (the +/// clusters to wake come back). Asks only for marked teams. +pub async fn resume(s: &crate::AppState) -> ApiResult<()> { + let Some(e) = crate::ENTITLEMENTS.get() else { + return Ok(()); + }; + let teams: Vec = + sqlx::query_scalar("SELECT id FROM pyo.teams WHERE commands_held_at IS NOT NULL") + .fetch_all(&s.db) + .await?; + for team in teams { + let mut tx = s.db.begin().await?; + // Once: whoever takes the mark sends them. + let marked: Option = sqlx::query_scalar( + "SELECT id FROM pyo.teams WHERE id = $1 AND commands_held_at IS NOT NULL FOR UPDATE SKIP LOCKED", + ) + .bind(&team) + .fetch_optional(&mut *tx) + .await?; + if marked.is_none() || e.can_command(&mut tx, &team).await.is_err() { + continue; + } + sqlx::query("UPDATE pyo.teams SET commands_held_at = NULL WHERE id = $1") + .bind(&team) + .execute(&mut *tx) + .await?; + let clusters = resend(&mut tx, &team).await?; + tx.commit().await?; + tracing::info!(%team, clusters = clusters.len(), "commands allowed again: syncs sent again"); + for c in clusters { + s.wake(&c).await; + } + } + Ok(()) +} + +/// What Pyo wants on each of a team's clusters, queued again: each running +/// service's routes, firewall and WAF (with the WAF's bundle), Pyo Static, +/// cron jobs, the registry's tokens and the tailnet's names. Deploys and +/// other changes a person asked for aren't: they were told why they +/// didn't happen. Gives back the clusters. +async fn resend( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + team_id: &str, +) -> ApiResult> { + let clusters: Vec = + sqlx::query_scalar("SELECT id FROM pyo.clusters WHERE team_id = $1 ORDER BY created_at") + .bind(team_id) + .fetch_all(&mut **tx) + .await?; + for c in &clusters { + crate::firewall::sync(tx, c).await?; + crate::sites::sync(tx, c).await?; + let crons: Vec<(String, serde_json::Value)> = sqlx::query_as( + "SELECT id, spec->'cronJobs' FROM pyo.services + WHERE cluster_id = $1 AND current_deployment_id IS NOT NULL AND NOT deleting AND spec ? 'cronJobs' + ORDER BY created_at", + ) + .bind(c) + .fetch_all(&mut **tx) + .await?; + for (service_id, jobs) in crons { + let service = crate::ops::service_ref(tx, &service_id).await?; + let jobs = serde_json::from_value(jobs).unwrap_or_default(); + crate::deploy::enqueue(tx, c, pyo_proto::Command::SyncCronJobs { service, jobs }) + .await?; + } + crate::tailscale::send_again(tx, c).await?; + } + crate::registrydoor::sync_clusters(tx, team_id, None).await?; + Ok(clusters) +} + +/// A hosted build's plans, for tests: teams named `team_ended_…` have an +/// ended plan, and those in [`test_plans::PAUSED`] a paused one. Deploys +/// are refused, so commands are too (the default). +#[cfg(test)] +pub(crate) mod test_plans { + use std::collections::BTreeSet; + use std::sync::Mutex; + + pub static PAUSED: Mutex> = Mutex::new(BTreeSet::new()); + + struct Plans; + + impl crate::Entitlements for Plans { + fn can_add_server<'a>( + &'a self, + _: &'a mut sqlx::PgConnection, + _: &'a str, + ) -> futures::future::BoxFuture<'a, Result<(), String>> { + Box::pin(async { Ok(()) }) + } + fn can_deploy<'a>( + &'a self, + _: &'a mut sqlx::PgConnection, + team_id: &'a str, + ) -> futures::future::BoxFuture<'a, Result<(), String>> { + let paused = PAUSED.lock().unwrap().contains(team_id); + Box::pin(async move { + if team_id.starts_with("team_ended_") || paused { + Err("This team's subscription ended.".into()) + } else { + Ok(()) + } + }) + } + } + + /// This test process is a hosted build with these plans. + pub fn install() { + let _ = crate::ENTITLEMENTS.set(std::sync::Arc::new(Plans)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_and_removals_go_out() { + for k in [ + "fetch_logs", + "follow_logs", + "follow_database_logs", + "query_traffic", + "delete_service", + "remove_server", + "cancel", + ] { + assert!(allowed(k), "{k}"); + } + for k in [ + "deploy", + "restart", + "scale", + "open_terminal", + "update_agent", + "backup", + "sync_routes", + "apply_bundle", + ] { + assert!(!allowed(k), "{k}"); + } + } + + #[test] + fn only_a_request_for_a_change_is_refused_when_queued() { + assert!(asks_at_queue("restart", true)); + assert!(asks_at_queue("open_terminal", true)); + // Pyo's own (a scheduled backup, an agent update): held back later. + assert!(!asks_at_queue("backup", false)); + assert!(!asks_at_queue("update_agent", false)); + // A deleted service's firewall sync doesn't stop the delete. + assert!(!asks_at_queue("sync_firewall", true)); + assert!(!asks_at_queue("delete_service", true)); + assert!(!asks_at_queue("fetch_logs", true)); + } + + #[test] + fn follow_ons_are_held_back() { + for k in FOLLOW_ONS { + assert!(!allowed(k), "{k}"); + } + } + + #[test] + fn the_message_is_plain() { + assert!(!STOPPED.contains(';') && !STOPPED.contains(" - ") && !STOPPED.contains('—')); + } +} diff --git a/crates/pyo-api/src/git/gitlab.rs b/crates/pyo-api/src/git/gitlab.rs index 252f590b..0643b055 100644 --- a/crates/pyo-api/src/git/gitlab.rs +++ b/crates/pyo-api/src/git/gitlab.rs @@ -398,10 +398,24 @@ impl Gitlab { state: &str, description: &str, target_url: &str, + ) -> Result<()> { + self.set_named_status(repo, sha, "Pyo", state, description, target_url) + .await + } + + /// A commit status of Pyo's under its own name ("Pyo · Preview"). + pub async fn set_named_status( + &self, + repo: &str, + sha: &str, + name: &str, + state: &str, + description: &str, + target_url: &str, ) -> Result<()> { let mut body = json!({ "state": state, - "name": "Pyo", + "name": name, "description": description.chars().take(140).collect::(), }); if !target_url.is_empty() { @@ -490,7 +504,8 @@ impl Gitlab { "token": secret, "push_events": true, "tag_push_events": false, - "merge_requests_events": false, + // Previews (previews/gitlab.rs). + "merge_requests_events": true, "enable_ssl_verification": url.starts_with("https://"), })), ) @@ -511,6 +526,181 @@ impl Gitlab { .await } + // ── Merge requests (previews) ── + + /// The project's open merge requests, the 100 updated last. + pub async fn merge_requests(&self, repo: &str) -> Result> { + self.list( + &["projects", repo, "merge_requests"], + &[("state", "opened"), ("order_by", "updated_at")], + 1, + &format!("list the merge requests of {repo}"), + ) + .await + } + + pub async fn merge_request(&self, repo: &str, iid: i64) -> Result { + self.get( + self.url(&["projects", repo, "merge_requests", &iid.to_string()]), + &format!("read merge request {iid}"), + ) + .await + } + + /// Posts a note on a merge request, or edits it in place (posting it + /// again when it was deleted). Its id. + pub async fn note(&self, repo: &str, iid: i64, id: Option, body: &str) -> Result { + let b = json!({ "body": body }); + let iid = iid.to_string(); + if let Some(id) = id { + let (status, v) = self + .send( + self.http + .put(self.url(&[ + "projects", + repo, + "merge_requests", + &iid, + "notes", + &id.to_string(), + ])) + .json(&b), + ) + .await?; + if status.is_success() { + return Ok(id); + } + if status != StatusCode::NOT_FOUND { + return Err(describe(status, "edit the merge request note", &v)); + } + } + let (status, v) = self + .send( + self.http + .post(self.url(&["projects", repo, "merge_requests", &iid, "notes"])) + .json(&b), + ) + .await?; + if !status.is_success() { + return Err(describe(status, "comment on the merge request", &v)); + } + v["id"] + .as_u64() + .ok_or_else(|| error(None, "GitLab gave the note no id.")) + } + + /// An environment named `name` with `external_url` ("View app"): the + /// one Pyo made (`id`), else one of that name, else a new one. + pub async fn environment( + &self, + repo: &str, + id: Option, + name: &str, + external_url: Option<&str>, + ) -> Result { + let mut b = json!({ "name": name }); + if let Some(u) = external_url { + b["external_url"] = json!(u); + } + if let Some(id) = id { + let (status, v) = self + .send( + self.http + .put(self.url(&["projects", repo, "environments", &id.to_string()])) + .json(&json!({ "external_url": external_url })), + ) + .await?; + if status.is_success() { + return Ok(id); + } + if status != StatusCode::NOT_FOUND { + return Err(describe(status, "update the environment", &v)); + } + } + let (status, v) = self + .send( + self.http + .post(self.url(&["projects", repo, "environments"])) + .json(&b), + ) + .await?; + if status.is_success() { + return v["id"] + .as_u64() + .ok_or_else(|| error(None, "GitLab gave the environment no id.")); + } + // There already: that one. + let mut url = self.url(&["projects", repo, "environments"]); + url.query_pairs_mut().append_pair("name", name); + let found = self.get(url, "find the environment").await?; + found + .as_array() + .and_then(|a| a.iter().find(|e| e["name"] == json!(name))) + .and_then(|e| e["id"].as_u64()) + .ok_or_else(|| describe(status, "add the environment", &v)) + } + + /// Stops an environment and deletes it. Gone already is done. + pub async fn remove_environment(&self, repo: &str, id: u64) -> Result<()> { + let id = id.to_string(); + let (status, v) = self + .send( + self.http + .post(self.url(&["projects", repo, "environments", &id, "stop"])), + ) + .await?; + if !status.is_success() && status != StatusCode::NOT_FOUND { + return Err(describe(status, "stop the environment", &v)); + } + self.delete( + self.url(&["projects", repo, "environments", &id]), + "delete the environment", + ) + .await + } + + /// A deployment of `sha` to the environment `name` in `status` + /// ("running", "success", "failed", "canceled"): a new one when `id` is + /// None, else that one moved on. Its id. + pub async fn deployment( + &self, + repo: &str, + id: Option, + name: &str, + sha: &str, + git_ref: &str, + status: &str, + ) -> Result { + if let Some(id) = id { + let (st, v) = self + .send( + self.http + .put(self.url(&["projects", repo, "deployments", &id.to_string()])) + .json(&json!({ "status": status })), + ) + .await?; + if st.is_success() || (st == StatusCode::BAD_REQUEST && same_state(&v)) { + return Ok(id); + } + if st != StatusCode::NOT_FOUND { + return Err(describe(st, "update the deployment", &v)); + } + } + let (st, v) = self + .send( + self.http + .post(self.url(&["projects", repo, "deployments"])) + .json(&json!({ "environment": name, "sha": sha, "ref": git_ref, "tag": false, "status": status })), + ) + .await?; + if !st.is_success() { + return Err(describe(st, "add a deployment", &v)); + } + v["id"] + .as_u64() + .ok_or_else(|| error(None, "GitLab gave the deployment no id.")) + } + /// Remove several webhooks, carrying on past failures: the ones that /// couldn't be removed, with why. pub async fn delete_hooks(&self, hooks: &[(String, i64)]) -> Vec<(String, Error)> { diff --git a/crates/pyo-api/src/git/mod.rs b/crates/pyo-api/src/git/mod.rs index 522d4399..30801374 100644 --- a/crates/pyo-api/src/git/mod.rs +++ b/crates/pyo-api/src/git/mod.rs @@ -137,9 +137,29 @@ impl Connection { } } +type Row = (String, String, String, String, String, String, String); + /// A connection by id, its secrets opened. `team`: only that team's. pub async fn load(db: &sqlx::PgPool, team: Option<&str>, id: &str) -> ApiResult { - type Row = (String, String, String, String, String, String, String); + opened(row(db, team, id).await?).await +} + +/// [`load`] for a person's request: read within their teams (rls.rs), by +/// a viewer of `team` or more, then its secrets opened. +pub async fn load_for( + db: &sqlx::PgPool, + user: &crate::auth::User, + team: &str, + id: &str, +) -> ApiResult { + let mut tx = crate::rls::begin(db, user).await?; + crate::ops::require_role(&mut tx, user, team, crate::ops::Role::Viewer).await?; + let row = row(&mut *tx, Some(team), id).await?; + tx.commit().await?; + opened(row).await +} + +async fn row<'e, E: sqlx::PgExecutor<'e>>(db: E, team: Option<&str>, id: &str) -> ApiResult { let row: Option = sqlx::query_as( "SELECT id, provider, base_url, account, public_url, token, webhook_secret FROM pyo.git_connections WHERE id = $1 AND ($2::text IS NULL OR team_id = $2)", @@ -148,9 +168,11 @@ pub async fn load(db: &sqlx::PgPool, team: Option<&str>, id: &str) -> ApiResult< .bind(team) .fetch_optional(db) .await?; - let Some((id, provider, base_url, account, public_url, token, secret)) = row else { - return Err(ApiError::not_found("Git connection")); - }; + row.ok_or_else(|| ApiError::not_found("Git connection")) +} + +async fn opened(row: Row) -> ApiResult { + let (id, provider, base_url, account, public_url, token, secret) = row; let v = crate::vault::get(); Ok(Connection { id, @@ -709,18 +731,18 @@ pub(crate) async fn repos( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team, Role::Viewer).await?; - tx.commit().await?; let ids: Vec = sqlx::query_scalar( "SELECT id FROM pyo.git_connections WHERE team_id = $1 ORDER BY created_at", ) .bind(&q.team) - .fetch_all(&s.db) + .fetch_all(&mut *tx) .await?; + tx.commit().await?; let (mut out, mut errors) = (vec![], vec![]); for id in ids { - let conn = load(&s.db, Some(&q.team), &id).await?; + let conn = load_for(&s.db, &user, &q.team, &id).await?; let listed = match conn.api().await { Ok(api) => api .projects(q.search.as_deref()) @@ -785,10 +807,7 @@ pub(crate) async fn branches( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; - require_role(&mut tx, &user, &q.team, Role::Viewer).await?; - tx.commit().await?; - let conn = load(&s.db, Some(&q.team), &q.connection).await?; + let conn = load_for(&s.db, &user, &q.team, &q.connection).await?; let repo = repo_arg(&conn, &q.repo)?; let list = conn .api() @@ -836,10 +855,7 @@ pub(crate) async fn build_file( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; - require_role(&mut tx, &user, &q.team, Role::Viewer).await?; - tx.commit().await?; - let conn = load(&s.db, Some(&q.team), &q.connection).await?; + let conn = load_for(&s.db, &user, &q.team, &q.connection).await?; let repo = repo_arg(&conn, &q.repo)?; let dir = crate::github::build_dir(&q.context) .ok_or_else(|| ApiError::bad_request("Build context can't contain '..'."))?; @@ -1012,6 +1028,10 @@ pub async fn report( let Some((data, slug)) = row else { return Ok(()); }; + // A preview's deployment: its pull request's bot says it instead. + if crate::previews::deployment_changed(s, deployment_id).await? { + return Ok(()); + } let src = &data["source"]; if src["installationId"].is_i64() { return crate::github::report(s, &data, &slug, deployment_id, state, description).await; @@ -1070,7 +1090,7 @@ pub async fn deploy_push( }; let services: Vec<(String, String, Value)> = sqlx::query_as( "SELECT a.id, a.team_id, a.spec->'source' FROM pyo.services a - WHERE NOT a.deleting AND a.spec->'source'->>'type' = 'git' + WHERE NOT a.deleting AND a.preview_of IS NULL AND a.spec->'source'->>'type' = 'git' AND CASE WHEN $2::text IS NULL THEN a.spec->'source'->>'installationId' IS NOT NULL ELSE a.spec->'source'->>'gitConnectionId' = $2 END AND coalesce(a.spec->'source'->>'branch', 'main') = $1 AND coalesce((a.spec->'source'->>'autoDeploy')::bool, true) @@ -1118,6 +1138,7 @@ pub async fn deploy_push( rollback_of: None, retry_of: None, commit: Some(sha), + upload: None, }, ) .await @@ -1158,24 +1179,49 @@ pub async fn deploy_push( /// A connection's webhook: a push deploys the services that follow it. async fn webhook( State(s): State, + crate::ratelimit::ClientIp(ip): crate::ratelimit::ClientIp, Path(id): Path, headers: HeaderMap, body: Bytes, ) -> ApiResult { + let wrong = || async { + crate::ratelimit::take(&s.db, &[(crate::ratelimit::GIT_WEBHOOK_WRONG_IP, &ip)]).await + }; let conn = match load(&s.db, None, &id).await { Ok(c) => c, Err(e) if e.status == StatusCode::NOT_FOUND => { + wrong().await?; return Ok((StatusCode::NOT_FOUND, "no such connection")); } Err(e) => return Err(e), }; let header = |k: &str| headers.get(k).and_then(|v| v.to_str().ok()); if !gitlab::token_ok(&conn.webhook_secret, header("x-gitlab-token")) { + wrong().await?; return Ok((StatusCode::UNAUTHORIZED, "bad token")); } + // Per connection: a push storm can't queue builds without end. + crate::ratelimit::take( + &s.db, + &[(crate::ratelimit::GIT_WEBHOOK_CALLS, &format!("gitlab:{}", conn.id))], + ) + .await?; let Ok(v) = serde_json::from_slice::(&body) else { return Ok((StatusCode::BAD_REQUEST, "not JSON")); }; + // A merge request: its previews (previews/gitlab.rs). + if let Some(mr) = crate::previews::gitlab::pull_of_hook(header("x-gitlab-event"), &v, &conn) { + let team: String = + sqlx::query_scalar("SELECT team_id FROM pyo.git_connections WHERE id = $1") + .bind(&conn.id) + .fetch_one(&s.db) + .await?; + let followed = crate::previews::pull_event(&s, &team, &mr).await?; + return Ok(( + StatusCode::OK, + if followed { "previews" } else { "no previews" }, + )); + } let Some(push) = gitlab::push_of(header("x-gitlab-event"), &v) else { return Ok((StatusCode::OK, "ignored")); }; @@ -1227,11 +1273,20 @@ pub async fn sync_hooks(s: &AppState, id: &str) -> anyhow::Result<()> { let mut wanted: Vec = urls.iter().filter_map(|u| conn.repo_of(u)).collect(); wanted.sort_by_key(|r| r.to_lowercase()); wanted.dedup_by_key(|r| r.to_lowercase()); + let rows: Vec<(String, Option, String, bool)> = sqlx::query_as( + "SELECT repo, hook_id, url, merge_requests FROM pyo.git_webhooks WHERE connection_id = $1", + ) + .bind(id) + .fetch_all(&mut *tx) + .await?; + // Hooks made before previews send pushes only: they're made again. + let old_hooks: Vec = rows + .iter() + .filter(|r| r.1.is_some() && !r.3) + .map(|r| r.0.clone()) + .collect(); let have: Vec<(String, Option, String)> = - sqlx::query_as("SELECT repo, hook_id, url FROM pyo.git_webhooks WHERE connection_id = $1") - .bind(id) - .fetch_all(&mut *tx) - .await?; + rows.into_iter().map(|(r, h, u, _)| (r, h, u)).collect(); let api = conn .api() .await @@ -1259,6 +1314,7 @@ pub async fn sync_hooks(s: &AppState, id: &str) -> anyhow::Result<()> { let saved = have.iter().find(|(r, _, _)| *r == key); if let Some((_, Some(_), url)) = saved && Some(url) == hook_url.as_ref() + && !old_hooks.contains(&key) { continue; } @@ -1279,8 +1335,8 @@ pub async fn sync_hooks(s: &AppState, id: &str) -> anyhow::Result<()> { }, }; sqlx::query( - "INSERT INTO pyo.git_webhooks (connection_id, repo, hook_id, url, error, updated_at) VALUES ($1, $2, $3, $4, $5, now()) - ON CONFLICT (connection_id, repo) DO UPDATE SET hook_id = $3, url = $4, error = $5, updated_at = now()", + "INSERT INTO pyo.git_webhooks (connection_id, repo, hook_id, url, error, merge_requests, updated_at) VALUES ($1, $2, $3, $4, $5, $3 IS NOT NULL, now()) + ON CONFLICT (connection_id, repo) DO UPDATE SET hook_id = $3, url = $4, error = $5, merge_requests = $3 IS NOT NULL, updated_at = now()", ) .bind(id) .bind(&key) diff --git a/crates/pyo-api/src/github.rs b/crates/pyo-api/src/github.rs index 1dea1d97..4174b207 100644 --- a/crates/pyo-api/src/github.rs +++ b/crates/pyo-api/src/github.rs @@ -42,7 +42,15 @@ use crate::{ ops::{Role, log_activity, require_role}, }; -const API: &str = "https://api.github.com"; +/// GitHub's REST API: `PYO_GITHUB_API` when set (tests and the e2e run a fake +/// GitHub there), else api.github.com. +pub fn api_base() -> String { + std::env::var("PYO_GITHUB_API") + .ok() + .map(|u| u.trim().trim_end_matches('/').to_owned()) + .filter(|u| !u.is_empty()) + .unwrap_or_else(|| "https://api.github.com".to_owned()) +} /// The app, as saved after the manifest flow. Secrets are sealed. #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -61,12 +69,20 @@ pub struct GithubApp { pub public_url: String, /// Whether GitHub sends webhooks (only with a public https URL). pub webhook_active: bool, + /// What the app may do and the events it gets, as GitHub last said + /// (previews/github.rs `check_all`). Null until checked. + pub permissions: Value, + pub events: Vec, + /// "User" or "Organization": where its settings are. + pub owner_type: String, } impl GithubApp { /// For the dashboard: no keys. pub fn public(&self) -> Value { - json!({ "slug": self.slug, "name": self.name, "htmlUrl": self.html_url, "owner": self.owner, "publicUrl": self.public_url, "webhookActive": self.webhook_active }) + json!({ "slug": self.slug, "name": self.name, "htmlUrl": self.html_url, "owner": self.owner, "publicUrl": self.public_url, "webhookActive": self.webhook_active, + "missingPermissions": crate::previews::github::missing(&self.permissions, &self.events), + "permissionsUrl": crate::previews::github::app_settings_url(self) }) } } @@ -79,7 +95,7 @@ pub async fn app(db: &sqlx::PgPool) -> ApiResult> { .filter(|a: &GithubApp| a.app_id > 0)) } -fn http() -> &'static reqwest::Client { +pub(crate) fn http() -> &'static reqwest::Client { static C: OnceLock = OnceLock::new(); C.get_or_init(|| { reqwest::Client::builder() @@ -176,8 +192,8 @@ pub async fn manifest(user_id: &str, public_url: &str, org: Option<&str>) -> Api "setup_on_update": true, "callback_urls": [format!("{base}/api/github/authorized")], "hook_attributes": { "url": format!("{base}/api/github/webhook"), "active": webhook }, - "default_events": ["push"], - "default_permissions": { "contents": "read", "metadata": "read", "statuses": "write" }, + "default_events": ["push", "pull_request"], + "default_permissions": crate::previews::github::manifest_permissions(), }); let state = remember(Pending::Manifest { user_id: user_id.to_owned(), @@ -220,7 +236,11 @@ async fn created( )); } let res = http() - .post(format!("{API}/app-manifests/{}/conversions", q.code)) + .post(format!( + "{}/app-manifests/{}/conversions", + api_base(), + q.code + )) .header("accept", "application/vnd.github+json") .send() .await @@ -243,6 +263,7 @@ async fn created( client_secret_sealed: seal("client_secret")?, public_url, webhook_active: webhook, + ..Default::default() }; sqlx::query("INSERT INTO pyo.settings (key, value) VALUES ('github', $1) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()") .bind(serde_json::to_value(&app).map_err(anyhow::Error::from)?) @@ -495,7 +516,10 @@ async fn user_installations(s: &AppState, app: &GithubApp, code: &str) -> anyhow let mut ids = vec![]; for page in 1..=10 { let res = http() - .get(format!("{API}/user/installations?per_page=100&page={page}")) + .get(format!( + "{}/user/installations?per_page=100&page={page}", + api_base() + )) .bearer_auth(token) .header("accept", "application/vnd.github+json") .send() @@ -524,7 +548,7 @@ fn installation_ids(v: &Value) -> Vec { // ── Tokens and API calls ───────────────────────────────────────────────────── /// A JWT signed with the app's key, for calls as the app itself. -fn app_jwt(s: &AppState, app: &GithubApp) -> anyhow::Result { +pub(crate) fn app_jwt(s: &AppState, app: &GithubApp) -> anyhow::Result { let pem = s.sealer.open(&app.pem_sealed)?; let now = pyo_proto::now_ms() / 1000; let claims = json!({ "iat": now - 60, "exp": now + 540, "iss": app.app_id.to_string() }); @@ -536,13 +560,13 @@ fn app_jwt(s: &AppState, app: &GithubApp) -> anyhow::Result { )?) } -async fn app_get(s: &AppState, path: &str) -> anyhow::Result { +pub(crate) async fn app_get(s: &AppState, path: &str) -> anyhow::Result { let app = app(&s.db) .await .map_err(|e| anyhow::anyhow!("{}", e.message))? .ok_or_else(|| anyhow::anyhow!("GitHub isn't set up"))?; let res = http() - .get(format!("{API}{path}")) + .get(format!("{}{path}", api_base())) .bearer_auth(app_jwt(s, &app)?) .header("accept", "application/vnd.github+json") .send() @@ -571,7 +595,8 @@ pub async fn installation_token(s: &AppState, installation_id: i64) -> anyhow::R .ok_or_else(|| anyhow::anyhow!("GitHub isn't set up"))?; let res = http() .post(format!( - "{API}/app/installations/{installation_id}/access_tokens" + "{}/app/installations/{installation_id}/access_tokens", + api_base() )) .bearer_auth(app_jwt(s, &app)?) .header("accept", "application/vnd.github+json") @@ -600,7 +625,7 @@ async fn get_as( ) -> anyhow::Result { let tok = installation_token(s, installation_id).await?; Ok(http() - .get(format!("{API}{path}")) + .get(format!("{}{path}", api_base())) .bearer_auth(tok) .header("accept", accept) .send() @@ -723,7 +748,7 @@ pub(crate) async fn repos( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team, Role::Viewer).await?; let installs: Vec<(i64, String)> = sqlx::query_as( "SELECT id, account FROM pyo.github_installations WHERE team_id = $1 ORDER BY account", @@ -777,7 +802,7 @@ pub(crate) async fn build_file( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team, Role::Viewer).await?; tx.commit().await?; let repo = @@ -864,7 +889,7 @@ pub async fn report( let state = if state == "running" { "pending" } else { state }; let tok = installation_token(s, inst).await?; let res = http() - .post(format!("{API}/repos/{repo}/statuses/{sha}")) + .post(format!("{}/repos/{repo}/statuses/{sha}", api_base())) .bearer_auth(tok) .header("accept", "application/vnd.github+json") .json(&json!({ "state": state, "description": description.chars().take(140).collect::(), "context": "Pyo", "target_url": format!("{}/{slug}/deployments/{deployment_id}", app.public_url) })) @@ -895,6 +920,7 @@ pub fn signature_ok(secret: &str, body: &[u8], header: &str) -> bool { async fn webhook( State(s): State, + crate::ratelimit::ClientIp(ip): crate::ratelimit::ClientIp, headers: HeaderMap, body: Bytes, ) -> ApiResult { @@ -910,12 +936,37 @@ async fn webhook( .and_then(|v| v.to_str().ok()) .unwrap_or(""); if !signature_ok(&secret, &body, sig) { + crate::ratelimit::take(&s.db, &[(crate::ratelimit::GIT_WEBHOOK_WRONG_IP, &ip)]).await?; return Ok((StatusCode::UNAUTHORIZED, "bad signature")); } - if headers.get("x-github-event").and_then(|v| v.to_str().ok()) != Some("push") { - return Ok((StatusCode::OK, "ignored")); + let event = headers + .get("x-github-event") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + let Ok(v) = serde_json::from_slice::(&body) else { + return Ok((StatusCode::BAD_REQUEST, "not JSON")); + }; + // Per installation: a push storm can't queue builds without end. + let source = format!("github:{}", v["installation"]["id"].as_i64().unwrap_or(0)); + crate::ratelimit::take(&s.db, &[(crate::ratelimit::GIT_WEBHOOK_CALLS, &source)]).await?; + match event { + "push" => {} + // Pull requests: their previews (previews/). + "pull_request" => { + return Ok(( + StatusCode::OK, + crate::previews::github::webhook(&s, &v).await?, + )); + } + // Permissions approved (or changed) on GitHub: previews may run now. + "installation" | "installation_repositories" => { + if let Some(id) = v["installation"]["id"].as_i64() { + crate::previews::github::check_installation(&s, id).await; + } + return Ok((StatusCode::OK, "noted")); + } + _ => return Ok((StatusCode::OK, "ignored")), } - let v: Value = serde_json::from_slice(&body).map_err(anyhow::Error::from)?; if v["deleted"] == json!(true) { return Ok((StatusCode::OK, "branch deleted")); } diff --git a/crates/pyo-api/src/hooks.rs b/crates/pyo-api/src/hooks.rs index 67a85361..1300f58f 100644 --- a/crates/pyo-api/src/hooks.rs +++ b/crates/pyo-api/src/hooks.rs @@ -21,6 +21,7 @@ use crate::{ error::{ApiError, ApiResult}, ids::{new_id, sha256_hex}, ops::log_activity, + ratelimit::{self, ClientIp}, }; pub fn routes() -> Router { @@ -29,13 +30,19 @@ pub fn routes() -> Router { async fn trigger( State(s): State, + ClientIp(ip): ClientIp, Path(token): Path, ) -> ApiResult<(StatusCode, Json)> { + // Guessing tokens: wrong ones count per address, a right one is given back. + ratelimit::take(&s.db, &[(ratelimit::DEPLOY_HOOK_WRONG_IP, &ip)]).await?; let hook: Option<(String, String, String, Option, String)> = sqlx::query_as("SELECT id, team_id, project_id, service_id, name FROM pyo.deploy_hooks WHERE token_hash = $1").bind(sha256_hex(&token)).fetch_optional(&s.db).await?; let Some((hook_id, team_id, project_id, service_id, name)) = hook else { return Err(ApiError::not_found("Deploy hook")); }; + ratelimit::forgive(&s.db, &ratelimit::DEPLOY_HOOK_WRONG_IP, &ip).await?; + // A runaway pipeline can't queue deploys without end. + ratelimit::take(&s.db, &[(ratelimit::DEPLOY_HOOK_CALLS, &hook_id)]).await?; let services: Vec<(String, String, String)> = match &service_id { Some(a) => sqlx::query_as("SELECT id, name, status FROM pyo.services WHERE id = $1 AND NOT deleting").bind(a).fetch_all(&s.db).await?, None => sqlx::query_as("SELECT id, name, status FROM pyo.services WHERE project_id = $1 AND NOT deleting ORDER BY created_at").bind(&project_id).fetch_all(&s.db).await?, @@ -63,6 +70,7 @@ async fn trigger( rollback_of: None, retry_of: None, commit: None, + upload: None, }, ) .await diff --git a/crates/pyo-api/src/images.rs b/crates/pyo-api/src/images.rs index d829d484..303dd3aa 100644 --- a/crates/pyo-api/src/images.rs +++ b/crates/pyo-api/src/images.rs @@ -84,7 +84,7 @@ pub async fn list( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team, Role::Viewer).await?; let rows: Vec = sqlx::query_as( "SELECT d.spec->>'image', nullif(coalesce(d.data->>'pinnedImage', d.data->>'imageId', ''), ''), coalesce(d.data->>'revisionLabel', ''), d.service_id, @@ -96,16 +96,16 @@ pub async fn list( .bind(&q.team) .fetch_all(&mut *tx) .await?; + let team_repos: Vec = + sqlx::query_scalar("SELECT repo FROM pyo.registry_repos WHERE team_id = $1 ORDER BY repo") + .bind(&q.team) + .fetch_all(&mut *tx) + .await?; tx.commit().await?; let ours = format!("{}/pyo/services/", deploy::registry().pull); let theirs = format!("{}/", deploy::registry().pull); let ours_root = format!("{}/pyo/", deploy::registry().pull); - let team_repos: Vec = - sqlx::query_scalar("SELECT repo FROM pyo.registry_repos WHERE team_id = $1 ORDER BY repo") - .bind(&q.team) - .fetch_all(&s.db) - .await?; let mut images: BTreeMap = BTreeMap::new(); for (image, pinned, label, service_id, at, live, expired) in rows { let digest = pinned @@ -349,7 +349,7 @@ pub struct RegistryQuery { #[utoipa::path(get, path = "/registry", operation_id = "getRegistry", tag = "Images", params(RegistryQuery), responses( - (status = 200, description = "`address` (in the cluster only, where servers pull from), `location` (`clusterId` and `server`, or null), `reachable`, `usedBytes`, `repositories`, `retainDeployments`, `lastCleanupAt`, `pushAddress`, `teamPath` and `tokens`. Each of `repositories` has `repository` (as servers pull it), `tailnetRepository`, `kind` (\"built\" or \"pushed\"), `serviceId`, `tags`, `bytes` and `lastPushAt`. `tailnetRepository` is a pushed repository's name on the team's tailnet, `///`. It's null for one Pyo built, or without a tailnet. `pushAddress` is the registry's address on the team's tailnet, where the team pushes and pulls its own images, or null without a tailnet. Each of `tokens` has `id`, `name`, `scope`, `createdBy`, `createdAt`, `expiresAt` and `lastUsedAt`, but never the token itself.", body = Object), + (status = 200, description = "`address` (in the cluster only, where servers pull from), `location` (`clusterId` and `server`, or null), `reachable`, `usedBytes`, `repositories`, `retainDeployments`, `lastCleanupAt`, `pushAddress`, `teamPath` and `tokens`. Each of `repositories` has `repository` (as servers pull it), `tailnetRepository`, `kind` (\"built\" or \"pushed\"), `serviceId`, `tags`, `bytes` and `lastPushAt`. `tailnetRepository` is a pushed repository's name on the team's tailnet, `///`. It's null for one Pyo built, or without a tailnet. `pushAddress` is the registry's address on the team's tailnet, where the team pushes and pulls its own images, or null without a tailnet. On Pyo Cloud each cluster keeps its own registry: `clusterRegistries` lists the team's clusters, each with `clusterId`, `name` and its registry's `pushAddress` on the cluster's tailnet (null until the cluster has Tailscale), and `pushAddress` is the first of them. Each of `tokens` has `id`, `name`, `scope`, `createdBy`, `createdAt`, `expiresAt` and `lastUsedAt`, but never the token itself.", body = Object), (status = 400, description = "No `team`.", body = crate::error::ErrorBody), (status = 404, description = "No such team, or you aren't in it.", body = crate::error::ErrorBody), ), @@ -359,7 +359,7 @@ pub async fn registry( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team, Role::Viewer).await?; let pull = deploy::registry().pull.clone(); // Pyo's own calls go to the registry itself, in the cluster. @@ -397,6 +397,22 @@ pub async fn registry( .bind(&repos) .fetch_one(&mut *tx) .await?; + // Pyo Cloud: each of the team's clusters keeps its own registry, with a + // door on the cluster's tailnet (registrydoor.rs). + let mut cluster_registries = vec![]; + if deploy::in_cluster_registries() { + let ids: Vec<(String, String)> = sqlx::query_as( + "SELECT id, name FROM pyo.clusters WHERE team_id = $1 AND NOT same_cluster ORDER BY created_at", + ) + .bind(&q.team) + .fetch_all(&mut *tx) + .await?; + for (id, name) in ids { + let address = crate::registrydoor::cluster_address(&mut tx, &id).await?; + cluster_registries + .push(json!({ "clusterId": id, "name": name, "pushAddress": address })); + } + } // Where it runs: Pyo's own cluster, when it's this team's. let location: Option<(String, Value)> = sqlx::query_as( "SELECT id, workloads FROM pyo.clusters WHERE team_id = $1 AND same_cluster LIMIT 1", @@ -499,7 +515,14 @@ pub async fn registry( "lastCleanupAt": last_cleanup, // Pushing the team's own: where (over the tailnet; null without one), // under which path, and its tokens (never the tokens themselves). - "pushAddress": crate::registrydoor::address(), + // On Pyo Cloud, the first of the team's clusters' (each has its + // own, `clusterRegistries`). + "pushAddress": if deploy::in_cluster_registries() { + cluster_registries.iter().find_map(|c| c["pushAddress"].as_str().map(str::to_owned)) + } else { + crate::registrydoor::address() + }, + "clusterRegistries": cluster_registries, "teamPath": crate::registrydoor::team_path(&slug), "tokens": tokens, }))) diff --git a/crates/pyo-api/src/install.rs b/crates/pyo-api/src/install.rs index ec64991d..effcfff4 100644 --- a/crates/pyo-api/src/install.rs +++ b/crates/pyo-api/src/install.rs @@ -1,7 +1,12 @@ //! The agent's install manifest: `kubectl apply -f /install/agent.yaml?token=…`. //! -//! The token is the cluster's agent credential; it's only valid for the -//! cluster it was issued to and can be rotated from the dashboard. +//! The token in a connect command is a connect token ([`new_connect_token`]): +//! one cluster's, made for its team, good for an hour and for one agent. +//! Fetching the manifest with it makes the agent's own token, which goes +//! only into the manifest (a command run again within the hour, after a +//! failed try, makes another). Once that agent reports in, the connect +//! token is used up. The agent's own token also fetches the manifest +//! again, unchanged: the refresh command reads it from the agent there. use crate::error::Query; use axum::{extract::State, http::header, response::IntoResponse}; @@ -18,19 +23,141 @@ pub struct InstallQuery { token: String, } +/// How long a connect command works. +pub const CONNECT_TOKEN_HOURS: i32 = 1; + +/// Said when a connect command ran after its hour. +pub const CONNECT_EXPIRED: &str = + "This connect command expired. Get a new one in Pyo: open the cluster and show its install command."; +/// Said when its agent already connected with it. +pub const CONNECT_USED: &str = + "This connect command was used already. Get a new one in Pyo: open the cluster and show its install command."; + +/// A new connect command's token for a cluster of `team_id`: good for +/// [`CONNECT_TOKEN_HOURS`], once. One before it stops working. +pub async fn new_connect_token( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + cluster_id: &str, + team_id: &str, +) -> ApiResult { + let token = crate::ids::secret_token(); + sqlx::query( + "UPDATE pyo.clusters SET connect_token_hash = $2, connect_token_team = $3, + connect_token_expires_at = now() + make_interval(hours => $4), connect_token_used_at = NULL + WHERE id = $1", + ) + .bind(cluster_id) + .bind(sha256_hex(&token)) + .bind(team_id) + .bind(CONNECT_TOKEN_HOURS) + .execute(&mut **tx) + .await?; + Ok(token) +} + +/// The cluster's agent reported in: its connect command is used up. (The +/// agent before it was cut off when that command was made.) +pub async fn agent_reported( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + cluster_id: &str, +) -> ApiResult<()> { + sqlx::query( + "UPDATE pyo.clusters SET connect_token_used_at = now() + WHERE id = $1 AND connect_token_hash IS NOT NULL AND connect_token_used_at IS NULL", + ) + .bind(cluster_id) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Which cluster a manifest fetch is for, and the agent token its manifest +/// carries: a new one for a connect token, the same one for the agent's own. +async fn token_for_manifest(db: &sqlx::PgPool, token: &str) -> ApiResult<(String, String)> { + if !token.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(ApiError::not_found("Install token")); + } + let hash = sha256_hex(token); + let mut tx = db.begin().await?; + let row: Option<(String, bool, bool, bool, bool)> = sqlx::query_as( + "SELECT id, agent_token_hash = $1, coalesce(connect_token_team = team_id, false), + coalesce(connect_token_expires_at > now(), false), connect_token_used_at IS NOT NULL + FROM pyo.clusters WHERE agent_token_hash = $1 OR connect_token_hash = $1 FOR UPDATE", + ) + .bind(&hash) + .fetch_optional(&mut *tx) + .await?; + let Some((cluster, agent_token, same_team, fresh, used)) = row else { + return Err(ApiError::not_found("Install token")); + }; + if agent_token { + return Ok((cluster, token.to_owned())); + } + // A connect token, bound to the team it was made for. + if !same_team { + return Err(ApiError::not_found("Install token")); + } + if used { + return Err(ApiError::conflict(CONNECT_USED)); + } + if !fresh { + return Err(ApiError::new(axum::http::StatusCode::GONE, CONNECT_EXPIRED)); + } + // The agent's own token, shown nowhere. Its keys and certificate come + // with it (enrolled once, with this token). + let agent = crate::ids::secret_token(); + sqlx::query( + "UPDATE pyo.clusters SET agent_token_hash = $2, agent_token_used_hash = NULL WHERE id = $1", + ) + .bind(&cluster) + .bind(sha256_hex(&agent)) + .execute(&mut *tx) + .await?; + tx.commit().await?; + tracing::info!(%cluster, "connect command fetched the agent's manifest"); + Ok((cluster, agent)) +} + pub async fn manifest( State(s): State, headers: axum::http::HeaderMap, Query(q): Query, ) -> ApiResult { - let known: bool = sqlx::query_scalar( - "SELECT EXISTS (SELECT 1 FROM pyo.clusters WHERE agent_token_hash = $1)", - ) - .bind(sha256_hex(&q.token)) - .fetch_one(&s.db) - .await?; - if !known || !q.token.bytes().all(|b| b.is_ascii_hexdigit()) { - return Err(ApiError::not_found("Install token")); + let (cluster, token) = token_for_manifest(&s.db, q.token.trim()).await?; + // Pyo Cloud: the agent dials the mTLS endpoint, trusts only its CA and + // runs only commands the signer signed for this cluster (agent_tls.rs, + // the agent's trust.rs). + if let Some(endpoint) = crate::agent_tls::endpoint() { + let signed = crate::agent_auth::mode() == crate::agent_auth::Mode::Signed; + // mTLS: Pyo's agent CA. Signed requests: the CA of the endpoint's + // certificate only when it isn't a public one (PYO_AGENT_ENDPOINT_CA_FILE). + let ca = if signed { + std::env::var("PYO_AGENT_ENDPOINT_CA_FILE") + .ok() + .filter(|f| !f.trim().is_empty()) + .and_then(|f| std::fs::read_to_string(f.trim()).ok()) + .unwrap_or_default() + } else { + crate::agent_tls::ca().map(|c| c.pem().to_owned()).unwrap_or_default() + }; + let mut env = vec![ + ("PYO_AGENT_AUTH", if signed { "signed" } else { "mtls" }.to_owned()), + ("PYO_CLUSTER_ID", cluster.clone()), + ]; + if !ca.is_empty() { + env.push(("PYO_AGENT_CA", ca)); + } + if let Some(signer) = crate::command_signer() { + env.push(("PYO_COMMAND_KEY", signer.public_keys())); + } + let yaml = render_with(&endpoint, &s.config.agent_image, &token, &env); + return Ok(( + [ + (header::CONTENT_TYPE, "application/yaml"), + (header::CACHE_CONTROL, "no-store"), + ], + yaml, + )); } // The agent reaches Pyo the way the installer just did, unless that was // localhost (meaningless inside a pod): then the in-cluster address. @@ -41,7 +168,7 @@ pub async fn manifest( } else { base }; - let yaml = render(&api, &s.config.agent_image, &q.token); + let yaml = render(&api, &s.config.agent_image, &token); Ok(( [ (header::CONTENT_TYPE, "application/yaml"), @@ -131,6 +258,11 @@ pub fn parts(upgrades: bool) -> &'static pyo_proto::rbac::InstallParts { /// 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 { + render_with(api_url, image, token, &[]) +} + +/// [`render`], with more of the agent's env (Pyo Cloud's trust settings). +pub fn render_with(api_url: &str, image: &str, token: &str, extra_env: &[(&str, String)]) -> String { let parts = parts(pyo_proto::in_cluster_url(api_url)); let docs = |objects: &[serde_json::Value]| { objects @@ -145,10 +277,12 @@ pub fn render(api_url: &str, image: &str, token: &str) -> String { let pins: String = parts .pins .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .chain(extra_env.iter().map(|(k, v)| (*k, v.as_str()))) .map(|(k, v)| { format!( " - name: {k}\n value: {}\n", - serde_json::Value::from(v.as_str()) + serde_json::Value::from(v) ) }) .collect(); @@ -862,7 +996,8 @@ pub async fn reset_login( ))); } }; - let token = crate::recovery::new_link(&mut conn, &id).await?; + // Made on the server: it also turns two-factor off (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!({ "email": email, @@ -1313,3 +1448,75 @@ mod gateway_crds_tests { assert_eq!(both.len(), envoy_only.len() + docs(GATEWAY_API_CRDS).len()); } } + +#[cfg(test)] +mod connect_token_tests { + use super::*; + + /// Against a throwaway Postgres: a connect command's token fetches the + /// manifest (with an agent token of its own) until its agent reports + /// in or its hour is over; another team's, or a used or expired one, + /// gets nothing. The agent's own token fetches the same manifest again. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn connect_tokens_work_once_within_the_hour() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()).await.unwrap(); + crate::migrate::run(&db).await.unwrap(); + let run = crate::ids::random_string(8); + let (team, other, cl) = (format!("team_c{run}"), format!("team_x{run}"), format!("cl_c{run}")); + for t in [&team, &other] { + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)").bind(t).execute(&db).await.unwrap(); + } + sqlx::query("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash) VALUES ($1, $2, $1, $3)") + .bind(&cl) + .bind(&team) + .bind(sha256_hex(&crate::ids::secret_token())) + .execute(&db) + .await + .unwrap(); + let mut tx = db.begin().await.unwrap(); + let connect = new_connect_token(&mut tx, &cl, &team).await.unwrap(); + tx.commit().await.unwrap(); + let agent_hash = || async { + sqlx::query_scalar::<_, String>("SELECT agent_token_hash FROM pyo.clusters WHERE id = $1").bind(&cl).fetch_one(&db).await.unwrap() + }; + + // Its manifest carries an agent token of its own, never the connect token. + let (c, first) = token_for_manifest(&db, &connect).await.unwrap(); + assert_eq!(c, cl); + assert_ne!(first, connect); + assert_eq!(agent_hash().await, sha256_hex(&first)); + // Run again before the agent reports in (a failed try): another one. + let (_, second) = token_for_manifest(&db, &connect).await.unwrap(); + assert_ne!(second, first); + assert_eq!(agent_hash().await, sha256_hex(&second)); + // The agent's own token: the same manifest again (the refresh command). + assert_eq!(token_for_manifest(&db, &second).await.unwrap().1, second); + assert!(token_for_manifest(&db, &first).await.is_err()); + + // Its agent reports in: the command is used up. + let mut tx = db.begin().await.unwrap(); + agent_reported(&mut tx, &cl).await.unwrap(); + tx.commit().await.unwrap(); + let used = token_for_manifest(&db, &connect).await.unwrap_err(); + assert_eq!((used.status, used.message.as_str()), (axum::http::StatusCode::CONFLICT, CONNECT_USED)); + assert_eq!(token_for_manifest(&db, &second).await.unwrap().1, second); + + // A new command, after its hour. + let mut tx = db.begin().await.unwrap(); + let late = new_connect_token(&mut tx, &cl, &team).await.unwrap(); + tx.commit().await.unwrap(); + assert!(token_for_manifest(&db, &connect).await.is_err(), "the command before it stops working"); + sqlx::query("UPDATE pyo.clusters SET connect_token_expires_at = now() - interval '1 minute' WHERE id = $1").bind(&cl).execute(&db).await.unwrap(); + let expired = token_for_manifest(&db, &late).await.unwrap_err(); + assert_eq!((expired.status, expired.message.as_str()), (axum::http::StatusCode::GONE, CONNECT_EXPIRED)); + + // Made for another team (the cluster isn't its): nothing. + let mut tx = db.begin().await.unwrap(); + let foreign = new_connect_token(&mut tx, &cl, &other).await.unwrap(); + tx.commit().await.unwrap(); + assert_eq!(token_for_manifest(&db, &foreign).await.unwrap_err().status, axum::http::StatusCode::NOT_FOUND); + assert_eq!(token_for_manifest(&db, "not-hex").await.unwrap_err().status, axum::http::StatusCode::NOT_FOUND); + assert_eq!(agent_hash().await, sha256_hex(&second), "nothing above changed the agent's token"); + } +} diff --git a/crates/pyo-api/src/jobs.rs b/crates/pyo-api/src/jobs.rs index 565bd9e8..ae03eb65 100644 --- a/crates/pyo-api/src/jobs.rs +++ b/crates/pyo-api/src/jobs.rs @@ -126,12 +126,19 @@ async fn run(s: &AppState, kind: &str, p: &Value) -> anyhow::Result<()> { .await } "alert.send" => crate::alerts::run_job(s, p).await, + // Previews (previews/): the bot, a service's settings, a redeploy. + "preview.report" => crate::previews::report(s, &str_of("pullId")).await, + "preview.sync" => crate::previews::sync_service(s, &str_of("serviceId")).await, + "preview.reconcile" => crate::previews::reconcile(s, &str_of("pullId")) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message)), other => anyhow::bail!("unknown job kind {other}"), } } /// Finished jobs older than a week are deleted; failed ones are kept a month. -/// Also prunes old MCP calls, logs, rate limits and long-expired API keys. +/// Also prunes old MCP calls, logs, audit entries, rate limits and +/// long-expired API keys. pub async fn prune(s: &AppState) -> sqlx::Result<()> { sqlx::query("DELETE FROM pyo.jobs WHERE (status = 'done' AND finished_at < now() - interval '7 days') OR (status = 'failed' AND finished_at < now() - interval '30 days')") .execute(&s.db) @@ -147,12 +154,84 @@ pub async fn prune(s: &AppState) -> sqlx::Result<()> { sqlx::query("DELETE FROM pyo.platform_imports WHERE created_at < now() - interval '30 days'") .execute(&s.db) .await?; + prune_deployment_logs(&s.db).await?; + // The audit log, as long as the installation keeps it (a year on Pyo Cloud). + crate::audit::prune(&s.db).await?; crate::database_logs::prune(&s.db).await?; crate::ratelimit::prune(&s.db).await?; Ok(()) } +/// Build and deploy logs are kept as long as the installation's retention +/// says (90 days by default, 30 to 365: Settings › Observability), on Pyo +/// Cloud and self-hosted: a batch at a time, so a large backlog doesn't +/// hold the table up (this runs every 15 seconds). Returns the lines +/// deleted. +pub async fn prune_deployment_logs(db: &sqlx::PgPool) -> sqlx::Result { + let days = match crate::retention::load(db).await { + Ok(r) => r.build_log_days, + Err(_) => crate::retention::Retention::default().build_log_days, + }; + Ok(sqlx::query( + "DELETE FROM pyo.deployment_logs WHERE id IN ( + SELECT id FROM pyo.deployment_logs WHERE at < now() - make_interval(days => $1) LIMIT 5000)", + ) + .bind(i32::from(days)) + .execute(db) + .await? + .rows_affected()) +} + /// Payload helpers, so enqueuers and the runner agree on field names. pub fn git_status(deployment_id: &str, state: &str, description: &str) -> Value { json!({ "deploymentId": deployment_id, "state": state, "description": description }) } + +#[cfg(test)] +mod log_tests { + /// Against a real Postgres (DATABASE_URL, a throwaway one): lines older + /// than 90 days go, newer ones stay; with the setting at 30 days, those + /// older than 30 go. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn build_logs_go_after_the_settings_days() { + let pool = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()).await.unwrap(); + crate::migrate::run(&pool).await.unwrap(); + let run = crate::ids::new_id("t"); + let (team, cluster, dpl) = (format!("team_{run}"), format!("cl_{run}"), format!("dpl_{run}")); + let q = |sql: &'static str| sqlx::query(sql); + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)").bind(&team).execute(&pool).await.unwrap(); + q("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash) VALUES ($1, $2, $1, $1)").bind(&cluster).bind(&team).execute(&pool).await.unwrap(); + q("INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, 'p', $1)").bind(format!("prj_{run}")).bind(&team).execute(&pool).await.unwrap(); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec) VALUES ($1, $2, $3, $4, 'web', '{}')").bind(format!("svc_{run}")).bind(&team).bind(format!("prj_{run}")).bind(&cluster).execute(&pool).await.unwrap(); + q("INSERT INTO pyo.deployments (id, team_id, project_id, service_id, cluster_id, status, data, spec) VALUES ($1, $2, $3, $4, $5, 'succeeded', '{}', '{}')").bind(&dpl).bind(&team).bind(format!("prj_{run}")).bind(format!("svc_{run}")).bind(&cluster).execute(&pool).await.unwrap(); + for days in [120, 91, 89, 1] { + q("INSERT INTO pyo.deployment_logs (deployment_id, at, level, source, message) VALUES ($1, now() - make_interval(days => $2), 'info', 'build', 'x')") + .bind(&dpl) + .bind(days) + .execute(&pool) + .await + .unwrap(); + } + // The default: 90 days. + q("DELETE FROM pyo.settings WHERE key = 'observability'").execute(&pool).await.unwrap(); + while super::prune_deployment_logs(&pool).await.unwrap() > 0 {} + let left = || async { + sqlx::query_scalar::<_, i32>("SELECT extract(day FROM now() - at)::int FROM pyo.deployment_logs WHERE deployment_id = $1 ORDER BY at") + .bind(&dpl) + .fetch_all(&pool) + .await + .unwrap() + }; + assert_eq!(left().await, [89, 1]); + // The installation keeps them 30 days. + q("INSERT INTO pyo.settings (key, value) VALUES ('observability', '{\"retention\": {\"analyticsMonths\": 12, \"metricsDays\": 30, \"buildLogDays\": 30}}')") + .execute(&pool) + .await + .unwrap(); + while super::prune_deployment_logs(&pool).await.unwrap() > 0 {} + assert_eq!(left().await, [1]); + q("DELETE FROM pyo.settings WHERE key = 'observability'").execute(&pool).await.unwrap(); + q("DELETE FROM pyo.teams WHERE id = $1").bind(&team).execute(&pool).await.unwrap(); + } +} diff --git a/crates/pyo-api/src/join.rs b/crates/pyo-api/src/join.rs index a217dc08..15d7dbb3 100644 --- a/crates/pyo-api/src/join.rs +++ b/crates/pyo-api/src/join.rs @@ -283,6 +283,22 @@ pub fn command(base: &str, j: &Join) -> String { ) } +/// Puts a cluster's server on the cluster's tailnet and moves its k3s there +/// (connect.sh --tailnet-only): a cluster connected without Tailscale does +/// this on its control-plane server before more servers join it. +pub fn tailnet_only_command(base: &str, key: &str) -> String { + format!( + "curl -fsSL {base}/connect.sh | bash -s -- {}", + quoted(&pinned( + base, + vec![ + ("--tailnet-only", None), + ("--tailscale-key", Some(key.to_owned())), + ] + )) + ) +} + /// 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 @@ -344,6 +360,8 @@ pub fn connect_args( if let Some((r, t)) = registry { a.push(("--registry", Some(r.to_owned()))); a.push(("--registry-token", Some(t.to_owned()))); + } else if crate::deploy::in_cluster_registries() { + a.push(("--local-registry", None)); } a } @@ -1347,7 +1365,7 @@ if apply_agent; then echo "ok after $applies"; else echo "failed after $applies" ); } assert!(CONNECT_SCRIPT.contains( - "if [ -n \"$REGISTRY\" ] || [ -n \"$GPU_TOOLKIT_NEW\" ] || [ -n \"$K3S_MEMORY_CHANGED\" ]; then systemctl restart k3s" + "if [ -n \"$REGISTRY\" ] || [ -n \"$LOCAL_REGISTRY_NEW\" ] || [ -n \"$GPU_TOOLKIT_NEW\" ] || [ -n \"$K3S_MEMORY_CHANGED\" ]; then systemctl restart k3s" )); } diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index bbb51aad..d6deb15b 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -8,7 +8,10 @@ //! (see [`Extensions`]); self-hosted Pyo has none of those. mod agent; +mod agent_auth; +mod agent_tls; mod alerts; +mod audit; pub mod auth; mod backup; mod backupstore; @@ -29,9 +32,11 @@ mod database_imports; mod database_logs; mod databases; mod deploy; +mod domainproof; pub mod error; mod firewall; mod freedomain; +mod gate; mod geoip; mod git; mod github; @@ -41,23 +46,33 @@ mod images; mod install; mod jobs; mod join; +mod logfollow; mod mail; mod mcp; mod migrate; mod oauth; pub mod observability; +pub mod requests; +pub mod totals; pub mod openapi; pub mod ops; mod outbound; mod passkeys; +mod twofactor; +#[cfg(test)] +mod teamsec_tests; +mod placement; mod platform_import; mod pressure; +mod previews; mod publicdash; mod ratelimit; mod recovery; mod refs; +mod retention; mod registry; mod registrydoor; +mod rls; mod routes; mod sandbox; mod secrets; @@ -65,8 +80,8 @@ mod secretstores; mod sigstore; mod sites; mod snapshot; +mod source_uploads; mod tailscale; -mod tailscale_setup; mod teambackup; mod template_source; mod terminal; @@ -171,6 +186,107 @@ pub struct Extensions { pub features: Vec, /// Checks before a team adds a server or deploys. pub entitlements: Option>, + /// Signs every command before an agent gets it, with a key this + /// process doesn't hold. Agents installed from here are given its + /// public keys and refuse anything unsigned. + pub command_signer: Option>, + /// Hostnames need proof of ownership (a DNS TXT record) before a team + /// can claim one. For an installation shared by teams that don't trust + /// each other. + pub verify_domains: bool, + /// The agent CA for the mTLS agent endpoint, kept outside this process + /// (Pyo Cloud: its signer). Without one, Pyo keeps its own in + /// `PYO_AGENT_CA_DIR`. + pub agent_ca: Option>, +} + +pub use pyo_proto::agent_ca::Issued as IssuedCert; + +/// The agent CA behind the mTLS agent endpoint (agent_tls.rs). What it +/// issues is pyo-proto's `agent_ca`; where its key lives is up to it. +pub trait AgentCa: Send + Sync { + /// The CA certificate agents trust (PEM). + fn pem(&self) -> &str; + /// A client certificate for a cluster's agent, from its CSR. + fn issue<'a>( + &'a self, + csr_pem: &'a str, + team: &'a str, + cluster: &'a str, + ) -> futures::future::BoxFuture<'a, anyhow::Result>; + /// The endpoint's own certificate for `names` (PEM), from its CSR. + fn issue_server<'a>( + &'a self, + csr_pem: &'a str, + names: &'a [String], + ) -> futures::future::BoxFuture<'a, anyhow::Result>; +} + +/// A command to sign: its id, its `kind`, and the hex SHA-256 of its JSON. +#[derive(Debug, Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ToSign { + pub id: String, + pub kind: String, + pub sha256: String, + /// The command's exact JSON, for kinds that carry no secrets and whose + /// content the signer checks itself ([`SIGNER_CHECKS`]). + #[serde(skip_serializing_if = "Option::is_none")] + pub command: Option, +} + +/// Kinds a signer sees in full, to hold them to its own policy: an agent +/// update names the image every customer's agent will run. +pub const SIGNER_CHECKS: &[&str] = &["update_agent"]; + +/// A reply to sign (pyo-proto `signing`, `pyoreply1`): for this cluster, +/// to the request that sent `nonce`, whose JSON hashes to `sha256`. +#[derive(Debug, Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReplyToSign { + pub nonce: String, + pub sha256: String, +} + +/// A signature over a command's claims (pyo-proto `signing`), or why the +/// signer won't sign that command (`refused`). +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Signature { + #[serde(default)] + pub claims: String, + #[serde(default)] + pub sig: String, + #[serde(default)] + pub kid: String, + #[serde(default)] + pub refused: Option, + /// When a session key signed it: the trusted key's delegation to it, + /// passed on to the agent with the signature. + #[serde(default)] + pub delegation: Option, +} + +/// Where commands get signed (pyo-proto `signing`). The signer picks each +/// command's sequence number and expiry. +pub trait CommandSigner: Send + Sync { + /// Signs commands for one cluster, in this order: one [`Signature`] + /// each, or its refusal. + fn sign<'a>( + &'a self, + cluster_id: &'a str, + items: &'a [ToSign], + ) -> futures::future::BoxFuture<'a, anyhow::Result>>; + /// Signs a reply the agent acts on (the heartbeat's, a certificate, a + /// registry login), bound to its request's nonce. The signer picks + /// the expiry. + fn sign_reply<'a>( + &'a self, + cluster_id: &'a str, + reply: &'a ReplyToSign, + ) -> futures::future::BoxFuture<'a, anyhow::Result>; + /// The public keys agents trust (`PYO_COMMAND_KEY`: base64url, comma separated). + fn public_keys(&self) -> String; } /// A background task: given the app state, runs until the process stops. @@ -194,9 +310,36 @@ pub trait Entitlements: Send + Sync { let _ = (conn, team_id); Box::pin(async { Ok(()) }) } + /// Whether a team's clusters may get commands now (gate.rs): refused, + /// they get only reads and removals. Asked before a request queues a + /// command, and when an agent takes its commands. By default refused + /// whenever deploys are, with [`gate::STOPPED`] as the message. + fn can_command<'a>( + &'a self, + conn: &'a mut sqlx::PgConnection, + team_id: &'a str, + ) -> futures::future::BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + self.can_deploy(conn, team_id) + .await + .map_err(|_| gate::STOPPED.to_owned()) + }) + } } static ENTITLEMENTS: std::sync::OnceLock> = std::sync::OnceLock::new(); +static SIGNER: std::sync::OnceLock> = std::sync::OnceLock::new(); +static VERIFY_DOMAINS: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// The command signer, when this build has one. +pub(crate) fn command_signer() -> Option<&'static Arc> { + SIGNER.get() +} + +/// Whether hostnames need proof of ownership (see [`Extensions::verify_domains`]). +pub(crate) fn verify_domains() -> bool { + VERIFY_DOMAINS.get().copied().unwrap_or(false) +} static FEATURES: std::sync::OnceLock> = std::sync::OnceLock::new(); /// Fails with 402 and the entitlement's message when a team may not add a server. @@ -204,13 +347,14 @@ pub(crate) async fn check_add_server( conn: &mut sqlx::PgConnection, team_id: &str, ) -> error::ApiResult<()> { - match ENTITLEMENTS.get() { - Some(e) => e - .can_add_server(conn, team_id) - .await - .map_err(|m| error::ApiError::new(axum::http::StatusCode::PAYMENT_REQUIRED, m)), - None => Ok(()), - } + let Some(e) = ENTITLEMENTS.get() else { + return Ok(()); + }; + // A hosted build's own tables, outside row security (rls.rs). + let lifted = rls::lift(conn).await?; + let out = e.can_add_server(conn, team_id).await; + lifted.lower(conn).await?; + out.map_err(|m| error::ApiError::new(axum::http::StatusCode::PAYMENT_REQUIRED, m)) } /// Fails with 402 and the entitlement's message when a team may not deploy. @@ -218,13 +362,13 @@ pub(crate) async fn check_deploy( conn: &mut sqlx::PgConnection, team_id: &str, ) -> error::ApiResult<()> { - match ENTITLEMENTS.get() { - Some(e) => e - .can_deploy(conn, team_id) - .await - .map_err(|m| error::ApiError::new(axum::http::StatusCode::PAYMENT_REQUIRED, m)), - None => Ok(()), - } + let Some(e) = ENTITLEMENTS.get() else { + return Ok(()); + }; + let lifted = rls::lift(conn).await?; + let out = e.can_deploy(conn, team_id).await; + lifted.lower(conn).await?; + out.map_err(|m| error::ApiError::new(axum::http::StatusCode::PAYMENT_REQUIRED, m)) } /// The dashboard features a hosted build turned on (none when self-hosted). @@ -232,6 +376,12 @@ pub(crate) fn features() -> &'static [String] { FEATURES.get().map(Vec::as_slice).unwrap_or(&[]) } +/// Whether this Pyo is hosted (Pyo Cloud): one Pyo for many teams, outside +/// their clusters. A hosted build turns dashboard features on. +pub(crate) fn hosted() -> bool { + !features().is_empty() +} + /// 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<()> { @@ -241,8 +391,16 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { migrator: extra_migrator, features, entitlements, + command_signer, + verify_domains, + agent_ca, } = ext; let _ = FEATURES.set(features); + let _ = VERIFY_DOMAINS.set(verify_domains); + let dev_txt = std::env::var("PYO_DEV_TXT_FILE").is_ok_and(|v| !v.trim().is_empty()); + if let Some(s) = command_signer { + let _ = SIGNER.set(s); + } if let Some(e) = entitlements { let _ = ENTITLEMENTS.set(e); } @@ -353,6 +511,7 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { } // Every process: the worker sends sandbox servers images through the // registry door's tailnet address (sandbox/templates.rs). + sandbox::daemon::init(state.clone()); tokio::spawn(tailscale::addresses_follower(state.db.clone())); if role.worker() { // Each loop runs on one worker at a time (leader lock); jobs on any. @@ -361,6 +520,7 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { tokio::spawn(builders::watcher(state.clone())); tokio::spawn(github::poller(state.clone())); tokio::spawn(git::poller(state.clone())); + tokio::spawn(previews::runner(state.clone())); tokio::spawn(jobs::runner(state.clone())); tokio::spawn(backupstore::keeper(state.db.clone())); tokio::spawn(sites::sweeper(state.db.clone())); @@ -368,11 +528,13 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { tokio::spawn(teambackup::runner(state.clone())); tokio::spawn(database_imports::runner(state.clone())); tokio::spawn(updates::runner(state.clone())); + tokio::spawn(updates::hosted_agents(state.clone())); tokio::spawn(tailscale::runner(state.clone())); tokio::spawn(cdn::keeper(state.clone())); tokio::spawn(sandbox::runner::runner(state.clone())); tokio::spawn(sandbox::base::seed(state.clone())); tokio::spawn(sandbox::images::runner(state.clone())); + tokio::spawn(agent_auth::sweeper(state.db.clone())); for task in tasks { tokio::spawn(task(state.clone())); } @@ -391,6 +553,9 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { }); } tracing::info!(role = ?role, version = env!("CARGO_PKG_VERSION"), "pyo starting"); + if dev_txt { + tracing::warn!("PYO_DEV_TXT_FILE is set: domain proofs come from that file, not DNS. For tests only"); + } let web_dir = PathBuf::from(env("PYO_WEB_DIR", "dash/dist/client")); // Unknown paths are dashboard routes: hand them the app shell. @@ -404,13 +569,14 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { .route("/readyz", get(readyz)); let extra_routes = extra_routes.unwrap_or_default(); let door_state = state.clone(); + let door_state_for_agents = state.clone(); let app = if !role.web() { // A worker answers only its probes. probes.with_state(state) } else { probes .nest("/api/auth", auth::routes()) - // JSON is compressed; the terminal's WebSocket isn't (it's not a body). + // JSON is compressed; the terminal's and log follow's WebSockets aren't (they're not bodies). .nest( "/api/v1", ops::routes() @@ -420,7 +586,9 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { .merge(sandbox::api::routes()) .layer(CompressionLayer::new()) .merge(terminal::routes()) + .merge(logfollow::routes()) .merge(database_imports::routes()) + .merge(source_uploads::routes()) .merge(platform_import::routes()), ) .nest("/api/cli", cli::public_routes()) @@ -435,13 +603,33 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { agent::routes() .merge(sites::agent_routes()) .merge(terminal::agent_routes()) - .merge(database_imports::agent_routes()), + .merge(logfollow::agent_routes()) + .merge(database_imports::agent_routes()) + .merge(agent_auth::routes()) + // Signed requests (agent_auth.rs): who sent it, from its key. + .layer(axum::middleware::from_fn_with_state( + state.clone(), + agent_auth::signed, + )), ) + // Builders and pyo-static sign with keys of their own. .nest( "/api/builder/v1", - builders::routes().merge(sites::builder_routes()), + builders::routes() + .merge(sites::builder_routes()) + .merge(source_uploads::builder_routes()) + .layer(axum::middleware::from_fn_with_state( + state.clone(), + agent_auth::signed, + )), + ) + .nest( + "/api/static/v1", + sites::routes().layer(axum::middleware::from_fn_with_state( + state.clone(), + agent_auth::signed, + )), ) - .nest("/api/static/v1", sites::routes()) .merge(extra_routes) .route("/api/{*rest}", get(error::not_found).post(error::not_found)) .route("/install/agent.yaml", get(install::manifest)) @@ -461,6 +649,8 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { .route("/install/sandbox.sh", get(join::serve_sandbox)) .route("/install/host-units.sh", get(join::serve_host_units)) .fallback_service(tower_http::compression::Compression::new(spa)) + // Who a request is for, and from where, for the audit log. + .layer(axum::middleware::from_fn(audit::middleware)) .layer(axum::middleware::from_fn_with_state( state.config.cookie_secure, web::headers, @@ -500,6 +690,20 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { Err(e) => tracing::warn!(%door, error = %e, "registry door not listening"), } } + // Agents over mTLS (agent_tls.rs), when this Pyo has that endpoint. + if role.web() { + agent_tls::start( + door_state_for_agents, + agent::routes() + .merge(sites::agent_routes()) + .merge(terminal::agent_routes()) + .merge(logfollow::agent_routes()) + .merge(database_imports::agent_routes()) + .merge(agent_auth::component_routes()), + agent_ca, + ) + .await?; + } let addr: SocketAddr = env("LISTEN_ADDR", "0.0.0.0:8000").parse()?; tracing::info!(%addr, web = %web_dir.display(), "pyo api listening"); let listener = tokio::net::TcpListener::bind(addr).await?; diff --git a/crates/pyo-api/src/logfollow.rs b/crates/pyo-api/src/logfollow.rs new file mode 100644 index 00000000..87785174 --- /dev/null +++ b/crates/pyo-api/src/logfollow.rs @@ -0,0 +1,261 @@ +//! Following a service's logs (`pyo logs -f`, the dashboard's live logs) +//! or a database's (its live logs). +//! +//! One signed command (`follow_logs`, `follow_database_logs`) per follow, +//! not one every few seconds: the reader opens a WebSocket here, the +//! cluster's agent is asked to follow the pods and dial back to +//! `/api/agent/v1/log-follows/`, and this process relays the agent's +//! frames ([`pyo_proto::LogFrame`]) to the reader (a database's as its logs +//! read them, database_logs.rs `follow`). The agent stops when the reader +//! goes, or after [`pyo_proto::LOG_FOLLOW_SECS`], when the reader opens +//! another. With several web replicas the agent's socket is forwarded to +//! the one holding the reader's, as a terminal's is (terminal.rs +//! `hand_over`). + +use std::time::Duration; + +use axum::{ + Router, + extract::{ + Path, State, + ws::{Message, WebSocket, WebSocketUpgrade}, + }, + http::HeaderMap, + response::Response, + routing::get, +}; +use futures::SinkExt; +use pyo_proto::{Command, LOG_FOLLOW_SECS, LogFrame}; +use serde::Deserialize; +use sqlx::{Postgres, Transaction}; +use tokio::sync::oneshot; + +use crate::{ + AppState, + agent::AgentCluster, + auth::SessionUser, + error::{ApiError, ApiResult, Query}, + ids::new_id, + ops::{self, LogsQuery, Role}, + terminal, +}; + +/// How long the reader waits for the agent to dial back. +const AGENT_WAIT: Duration = Duration::from_secs(20); +/// The lines of a database's live logs sent first, as `range=live` reads. +const DATABASE_TAIL: i64 = 500; + +pub fn routes() -> Router { + Router::new() + .route("/services/{id}/logs/follow", get(open)) + .route("/databases/{id}/logs/follow", get(open_database)) +} + +pub fn agent_routes() -> Router { + Router::new().route("/log-follows/{id}", get(agent_side)) +} + +/// GET /api/v1/services/{id}/logs/follow?since=&replica=&tail= (WebSocket). +async fn open( + State(s): State, + SessionUser(user): SessionUser, + headers: HeaderMap, + Path(service_id): Path, + Query(q): Query, + ws: WebSocketUpgrade, +) -> ApiResult { + if !terminal::same_origin(&headers) { + return Err(ApiError::forbidden("Follow logs from the Pyo dashboard.")); + } + let replica = ops::replica_name(q.replica)?; + let mut tx = crate::rls::begin(&s.db, &user).await?; + let team_id = ops::team_of(&mut tx, "services", &service_id).await?; + ops::require_role(&mut tx, &user, &team_id, Role::Viewer).await?; + let cluster_id: String = + sqlx::query_scalar("SELECT cluster_id FROM pyo.services WHERE id = $1") + .bind(&service_id) + .fetch_one(&mut *tx) + .await?; + let service = ops::service_ref(&mut tx, &service_id).await?; + let id = new_id("lgf"); + sqlx::query( + "INSERT INTO pyo.log_follows (id, team_id, service_id, relay) VALUES ($1, $2, $3, $4)", + ) + .bind(&id) + .bind(&team_id) + .bind(&service_id) + .bind(&s.config.relay_addr) + .execute(&mut *tx) + .await?; + crate::deploy::enqueue( + &mut tx, + &cluster_id, + Command::FollowLogs { + session_id: id.clone(), + service, + tail_lines: q.tail.unwrap_or(300).clamp(1, 2000), + since_seconds: ops::since_seconds(q.since, pyo_proto::now_ms()), + replica, + }, + ) + .await?; + let recv = start(&s, tx, &id, &cluster_id).await?; + Ok(ws.on_upgrade(move |reader| async move { + match arrived(&s, &id, recv).await { + Some(agent) => { + let cap = Duration::from_secs(LOG_FOLLOW_SECS + 30); + let _ = tokio::time::timeout(cap, terminal::relay(reader, agent)).await; + } + None => no_agent(reader).await, + } + ended(&s, &id).await; + })) +} + +#[derive(Deserialize)] +struct DatabaseFollowQuery { + /// Only lines since this time, in milliseconds since 1970 (a follow + /// opened again from its newest line). + since: Option, +} + +/// GET /api/v1/databases/{id}/logs/follow?since= (WebSocket): a database's +/// live logs. The last lines first, then new ones as they're printed, each +/// text frame `{"type":"lines","lines":[…]}` with lines as +/// `GET /databases/{id}/logs` has them, `{"type":"events","events":[…]}` +/// (all of them, newest first) when they change, or +/// `{"type":"error","message":…}`. It closes after an hour. +async fn open_database( + State(s): State, + SessionUser(user): SessionUser, + headers: HeaderMap, + Path(database_id): Path, + Query(q): Query, + ws: WebSocketUpgrade, +) -> ApiResult { + if !terminal::same_origin(&headers) { + return Err(ApiError::forbidden("Follow logs from the Pyo dashboard.")); + } + let mut tx = crate::rls::begin(&s.db, &user).await?; + let team_id = ops::team_of(&mut tx, "databases", &database_id).await?; + ops::require_role(&mut tx, &user, &team_id, Role::Viewer).await?; + let (cluster_id, namespace, name): (String, String, String) = + sqlx::query_as("SELECT cluster_id, namespace, name FROM pyo.databases WHERE id = $1") + .bind(&database_id) + .fetch_one(&mut *tx) + .await?; + let id = new_id("lgf"); + sqlx::query( + "INSERT INTO pyo.log_follows (id, team_id, database_id, relay) VALUES ($1, $2, $3, $4)", + ) + .bind(&id) + .bind(&team_id) + .bind(&database_id) + .bind(&s.config.relay_addr) + .execute(&mut *tx) + .await?; + crate::deploy::enqueue( + &mut tx, + &cluster_id, + Command::FollowDatabaseLogs { + session_id: id.clone(), + namespace, + name: name.clone(), + tail_lines: DATABASE_TAIL, + since_seconds: ops::since_seconds(q.since, pyo_proto::now_ms()), + }, + ) + .await?; + let recv = start(&s, tx, &id, &cluster_id).await?; + Ok(ws.on_upgrade(move |reader| async move { + match arrived(&s, &id, recv).await { + Some(agent) => { + let f = crate::database_logs::Followed { + id: database_id, + team_id, + name, + }; + let cap = Duration::from_secs(LOG_FOLLOW_SECS + 30); + let _ = tokio::time::timeout( + cap, + crate::database_logs::follow(&s, &user, &f, reader, agent), + ) + .await; + } + None => no_agent(reader).await, + } + ended(&s, &id).await; + })) +} + +/// Commits the transaction that queued follow `id`'s command, with this +/// replica waiting for the agent's socket. Gives back where it comes. +async fn start( + s: &AppState, + tx: Transaction<'_, Postgres>, + id: &str, + cluster_id: &str, +) -> ApiResult> { + let (send, recv) = oneshot::channel(); + s.terminals.lock().await.insert(id.to_owned(), send); + if let Err(e) = tx.commit().await { + s.terminals.lock().await.remove(id); + return Err(e.into()); + } + s.wake(cluster_id).await; + // Follows that ended a day ago are of no more use. + let _ = sqlx::query("DELETE FROM pyo.log_follows WHERE created_at < now() - interval '1 day'") + .execute(&s.db) + .await; + Ok(recv) +} + +/// The agent's socket, once it dials back in time. +async fn arrived(s: &AppState, id: &str, recv: oneshot::Receiver) -> Option { + let agent = tokio::time::timeout(AGENT_WAIT, recv).await; + s.terminals.lock().await.remove(id); + agent.ok()?.ok() +} + +/// The agent didn't dial back: the reader is told. +async fn no_agent(mut reader: WebSocket) { + let frame = LogFrame::Error { + message: "The cluster's agent didn't answer. Is the server online?".into(), + }; + let _ = reader + .send(Message::text( + serde_json::to_string(&frame).unwrap_or_default(), + )) + .await; + let _ = reader.close().await; +} + +async fn ended(s: &AppState, id: &str) { + let _ = sqlx::query("UPDATE pyo.log_follows SET ended_at = now() WHERE id = $1") + .bind(id) + .execute(&s.db) + .await; +} + +/// GET /api/agent/v1/log-follows/{id} (WebSocket): the agent's end. +async fn agent_side( + State(s): State, + cluster: AgentCluster, + Path(id): Path, + ws: WebSocketUpgrade, +) -> ApiResult { + let row: Option<(Option,)> = sqlx::query_as( + "SELECT f.relay FROM pyo.log_follows f + LEFT JOIN pyo.services a ON a.id = f.service_id + LEFT JOIN pyo.databases d ON d.id = f.database_id + WHERE f.id = $1 AND coalesce(a.cluster_id, d.cluster_id) = $2 AND f.ended_at IS NULL AND f.created_at > now() - interval '1 minute'", + ) + .bind(&id) + .bind(&cluster.id) + .fetch_optional(&s.db) + .await?; + let Some((relay_addr,)) = row else { + return Err(ApiError::not_found("Log follow")); + }; + terminal::hand_over(&s, &id, relay_addr, ws, "Log follow").await +} diff --git a/crates/pyo-api/src/mail.rs b/crates/pyo-api/src/mail.rs index 064522a1..4c236ad8 100644 --- a/crates/pyo-api/src/mail.rs +++ b/crates/pyo-api/src/mail.rs @@ -211,6 +211,32 @@ pub fn sign_in_link(link: &str, minutes: i32) -> (String, String, String) { ) } +/// Two-factor was turned off on the account. +pub fn two_factor_off(link: &str) -> (String, String, String) { + let body = "Two-factor authentication was turned off on your Pyo account. If that wasn't you, sign in, change your password and turn it on again."; + let button = "Open your profile"; + let footer = "You get this email for every change to how you sign in."; + ( + "Two-factor authentication was turned off".into(), + format!("{body}\n\n{button}: {link}\n\n{footer}\n"), + layout("Two-factor authentication is off", body, button, link, footer), + ) +} + +/// A new API key was made on the account. +pub fn new_api_key(name: &str, link: &str) -> (String, String, String) { + let body = format!( + "A new API key named {name} was made on your Pyo account. If that wasn't you, revoke it and change your password." + ); + let button = "See your API keys"; + let footer = "You get this email for every new API key."; + ( + "A new Pyo API key was made".into(), + format!("{body}\n\n{button}: {link}\n\n{footer}\n"), + layout("New API key", &body, button, link, footer), + ) +} + fn article(role: &str) -> String { match role { "admin" => "an admin".into(), diff --git a/crates/pyo-api/src/mcp.rs b/crates/pyo-api/src/mcp.rs index 74e53742..08ea73e1 100644 --- a/crates/pyo-api/src/mcp.rs +++ b/crates/pyo-api/src/mcp.rs @@ -151,8 +151,10 @@ fn curated() -> Vec { "free_domain": { "type": "boolean", "description": "Give it a free nip.io domain (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" }, - "server_tags": { "type": "array", "items": { "type": "string" }, "description": "Run only on servers that have all of these tags (see list_servers)" }, + "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": "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": "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 } }), @@ -197,6 +199,12 @@ const NOT_TOOLS: &[&str] = &[ "getDatabaseLogs", "createDatabaseDumpUpload", "uploadDatabaseDump", + // A folder for `pyo deploy` goes up in parts of a request body each, + // which a tool can't send: assistants deploy what's in Git or an image. + "createSourceUpload", + "uploadSourcePart", + "getSourceUpload", + "completeSourceUpload", // They take another platform's API token: kept out of assistants. "previewPlatformImport", "startPlatformImport", @@ -240,6 +248,7 @@ const CURATED_RUNS: &[(&str, &str)] = &[ ("create_service", "createService"), ("add_domain", "saveService"), ("set_static_serving", "saveService"), + ("set_service_placement", "saveService"), ("create_sandbox", "createSandbox"), ("run_code", "createSandboxToken"), ("exec", "createSandboxToken"), @@ -626,6 +635,9 @@ async fn run_endpoint(s: &AppState, user: &User, id: &str, args: &Value) -> Resu "listCronRuns" => { json_of(crate::cronruns::list(st(), me(), Query(args_as(args)?)).await).map(plain_text) } + "listAuditLog" => { + json_of(crate::audit::page(st(), me(), Query(args_as(args)?)).await).map(plain_text) + } "getMetrics" => json_of(ops::metrics(st(), me(), Query(args_as(args)?)).await), "getObservabilitySettings" => json_of(ops::observability_settings(st(), me()).await), "getObservability" => json_of(ops::observability(st(), me(), Query(args_as(args)?)).await), @@ -894,7 +906,12 @@ fn structured(tool: &str, v: Value) -> Value { json!({ key: v }) } -async fn run_tool(s: &AppState, user: &User, name: &str, args: &Value) -> Result { +pub(crate) async fn run_tool( + s: &AppState, + user: &User, + name: &str, + args: &Value, +) -> Result { if crate::sandbox::mcp::TOOLS.contains(&name) { return crate::sandbox::mcp::run(s, user, name, args).await; } @@ -1022,7 +1039,9 @@ async fn run_tool(s: &AppState, user: &User, name: &str, args: &Value) -> Result } "get_service_logs" => { let id = service_id(args)?; - let v = ops::fetch_service_logs(s, user, id).await.map_err(err)?; + let v = ops::fetch_service_logs(s, user, id, Default::default()) + .await + .map_err(err)?; let lines: Vec = v["logs"] .as_array() .cloned() @@ -1056,6 +1075,7 @@ async fn run_tool(s: &AppState, user: &User, name: &str, args: &Value) -> Result "name": n["name"], "status": n["status"], "ip": n["internalIP"], "cpu": { "cores": n["capacity"]["cpu"], "used": n["usage"]["cpu"] }, "memoryGb": { "total": n["capacity"]["memoryGi"], "used": n["usage"]["memoryGi"] }, + "tags": n["tags"], "gpu": n["gpuDetected"] == json!(true), })).collect::>(), })) .collect::>())) @@ -1189,7 +1209,7 @@ async fn run_tool(s: &AppState, user: &User, name: &str, args: &Value) -> Result "id": service_id, "teamId": team, "projectId": project["id"], "clusterId": cluster["id"], "name": name, "description": "", "kind": "application", "workloadKind": "Deployment", "location": if pin.is_empty() { Value::Null } else { json!(pin) }, - "serverTags": args["server_tags"].as_array().map(|ts| ts.iter().filter_map(|t| t.as_str().and_then(pyo_proto::valid_tag)).collect::>()).unwrap_or_default(), + "placement": placement_arg(args), "source": { "type": "image", "image": image, "reference": reference, "registryId": "reg_dockerhub", "private": false }, "env": env, "ports": [{ "id": new_id("port"), "name": "http", "protocol": "HTTP", "containerPort": port, "exposure": if domains.is_empty() { "internal" } else { "http" } }], @@ -1234,7 +1254,7 @@ async fn run_tool(s: &AppState, user: &User, name: &str, args: &Value) -> Result .as_array() .is_some_and(|ds| ds.iter().any(|d| d["hostname"] == json!(host))) { - return Err(format!("{host} is already on this service")); + return Err(format!("{host} is already used.")); } let ports = a["ports"] .as_array_mut() @@ -1301,6 +1321,23 @@ async fn run_tool(s: &AppState, user: &User, name: &str, args: &Value) -> Result } Ok(out) } + "set_service_placement" => { + let id = service_id(args)?; + let mut a = find_service(id)?; + let placement = placement_arg(args); + a["placement"] = placement.clone(); + if let Some(o) = a.as_object_mut() { + o.remove("servers"); + o.remove("serverTags"); + } + op(json!({ "op": "saveService", "service": a })).await?; + let any = placement["servers"].as_array().is_none_or(|v| v.is_empty()) + && placement["tags"].as_array().is_none_or(|v| v.is_empty()); + Ok(json!({ + "placement": if any { Value::Null } else { placement }, + "next": "Saved. Its replicas move over now, without a redeploy.", + })) + } "set_static_serving" => { let id = service_id(args)?; let mut a = find_service(id)?; @@ -1318,6 +1355,44 @@ async fn run_tool(s: &AppState, user: &User, name: &str, args: &Value) -> Result } } +/// The `placement` input: what a tool's arguments pick of servers and +/// tags. Read from `placement` (`{"servers": [...], "tags": [...]}`), else +/// `servers` and `tags`, else the older `server_tags`. Nothing picked is +/// any server. +fn placement_arg(args: &Value) -> Value { + let list = |v: &Value| -> Vec { + v.as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()) + .collect() + }; + let (servers, tags) = if args["placement"].is_object() { + ( + list(&args["placement"]["servers"]), + list(&args["placement"]["tags"]), + ) + } else if args.get("servers").is_some() || args.get("tags").is_some() { + (list(&args["servers"]), list(&args["tags"])) + } else { + (vec![], list(&args["server_tags"])) + }; + json!({ "servers": servers, "tags": tags }) +} + +fn placement_schema() -> Value { + json!({ + "type": "object", + "description": "Where it runs: only the servers named and every server with one of the tags (see list_servers). Any server when omitted", + "properties": { + "servers": { "type": "array", "items": { "type": "string" }, "description": "Server names" }, + "tags": { "type": "array", "items": { "type": "string" }, "description": "Server tags" }, + }, + }) +} + /// A project with a free namespace, named like the dashboard does. async fn new_project( s: &AppState, @@ -1508,6 +1583,30 @@ mod tests { ); } + #[test] + fn placement_input() { + let p = |args: Value| placement_arg(&args); + assert_eq!( + p(json!({ "placement": { "servers": ["server-1"], "tags": ["gpu"] } })), + json!({ "servers": ["server-1"], "tags": ["gpu"] }) + ); + assert_eq!( + p(json!({ "servers": [" gpu-box "], "tags": [] })), + json!({ "servers": ["gpu-box"], "tags": [] }) + ); + // The older server_tags: its tags, picked. + assert_eq!( + p(json!({ "server_tags": ["gpu", ""] })), + json!({ "servers": [], "tags": ["gpu"] }) + ); + // Nothing: any server. + assert_eq!(p(json!({})), json!({ "servers": [], "tags": [] })); + // The API keeps it as placement, the older form included. + let mut spec = json!({ "name": "web", "placement": p(json!({ "server_tags": ["gpu"] })) }); + crate::placement::normalize(&mut spec).unwrap(); + assert_eq!(spec["placement"], json!({ "servers": [], "tags": ["gpu"] })); + } + #[test] fn output_is_plain() { let v = plain_text( diff --git a/crates/pyo-api/src/oauth.rs b/crates/pyo-api/src/oauth.rs index 4e5a5496..80c0d99c 100644 --- a/crates/pyo-api/src/oauth.rs +++ b/crates/pyo-api/src/oauth.rs @@ -583,6 +583,8 @@ impl FromRequestParts for OAuthUser { type Rejection = Response; async fn from_request_parts(parts: &mut Parts, s: &AppState) -> Result { + let Ok(crate::ratelimit::ClientIp(ip)) = + crate::ratelimit::ClientIp::from_request_parts(parts, s).await; // 401 points the client at how to get a token (RFC 9728). let challenge = |error: Option<&str>| { let meta = format!( @@ -615,16 +617,27 @@ impl FromRequestParts for OAuthUser { return Err(challenge(None)); }; let hash = sha256_hex(token); - let (id, name, email, timezone, is_admin, must_set_up, client, scope): (String, String, String, String, bool, bool, String, String) = sqlx::query_as( - "SELECT u.id, u.name, u.email, u.timezone, u.is_admin, u.must_set_up, c.name, g.scope + type Grant = (String, String, String, String, bool, bool, String, String); + let row: Option = sqlx::query_as( + "SELECT u.id, u.name, u.email, u.timezone, u.is_admin AND NOT pyo.needs_two_factor(u.id, $2), u.must_set_up, c.name, g.scope FROM pyo.oauth_grants g JOIN pyo.users u ON u.id = g.user_id JOIN pyo.oauth_clients c ON c.id = g.client_id WHERE g.access_hash = $1 AND g.access_expires_at > now()", ) .bind(&hash) + .bind(crate::hosted()) .fetch_optional(&s.db) .await - .map_err(|_| challenge(None))? - .ok_or_else(|| challenge(Some("invalid_token")))?; + .map_err(|_| challenge(None))?; + // Wrong tokens count per address; a token's requests per token. + let Some((id, name, email, timezone, is_admin, must_set_up, client, scope)) = row else { + crate::ratelimit::take(&s.db, &[(crate::ratelimit::API_KEY_WRONG_IP, &ip)]) + .await + .map_err(IntoResponse::into_response)?; + return Err(challenge(Some("invalid_token"))); + }; + crate::ratelimit::take(&s.db, &[(crate::ratelimit::API_KEY_REQUESTS, &hash)]) + .await + .map_err(IntoResponse::into_response)?; // Still on the installer's printed sign-in: nothing works until it's replaced. if must_set_up { return Err(challenge(Some("invalid_token"))); @@ -644,6 +657,7 @@ impl FromRequestParts for OAuthUser { teams: None, }), }; + crate::audit::set_actor(&user, crate::audit::Via::Mcp, Some(&client)); let _ = sqlx::query("UPDATE pyo.oauth_grants SET last_used_at = now() WHERE access_hash = $1 AND (last_used_at IS NULL OR last_used_at < now() - interval '1 minute')") .bind(&hash) .execute(&s.db) diff --git a/crates/pyo-api/src/observability.rs b/crates/pyo-api/src/observability.rs index 29a72e10..8843a738 100644 --- a/crates/pyo-api/src/observability.rs +++ b/crates/pyo-api/src/observability.rs @@ -1,22 +1,16 @@ -//! Observability: website analytics and server metrics. The gateway's -//! access logs come in, per-team traffic goes out. +//! Observability: website analytics and server metrics. //! -//! Each cluster's Vector forwards Envoy's JSON access log lines here (with -//! the cluster's agent token). This module turns them into rows and stores -//! them in ClickHouse: -//! - the hostname decides the team, project and service; other traffic is dropped -//! - the client IP is looked up in DB-IP Lite (country, city) and then -//! discarded unless the IP setting keeps it (anonymized or whole); visitors -//! are a hash of IP + user agent + host with a salt that -//! changes daily, so they can't be tied back to anyone -//! - sensitive query parameter values are replaced with "[redacted]" -//! -//! The dashboard's analytics page reads aggregates through `query`. +//! Website and port traffic stays in each cluster: its traffic store +//! (pyo-agent's traffic/) cleans the gateway's lines there and sends Pyo +//! per-minute totals, stored and read in totals.rs. The request explorer +//! asks the cluster for kept requests (requests.rs). Requests Pyo stored +//! itself before 0.5 stay readable on a self-hosted Pyo until they expire +//! (`legacy_access_logs`); Pyo Cloud drops them. //! //! Server metrics live here too: each cluster's heartbeat carries current CPU //! and memory per server and per service; one sample a minute goes into -//! `pyo_observability.metrics` (kept 30 days) and `metrics` reads it back as -//! time series. +//! `pyo_observability.metrics` (kept 30 days by default, the installation's +//! retention: retention.rs) and `metrics` reads it back as time series. use std::{ collections::HashMap, @@ -27,95 +21,11 @@ use std::{ use maxminddb::{Reader, geoip2}; use serde_json::{Value, json}; -use sha2::{Digest, Sha256}; use sqlx::PgPool; use tokio::sync::{Mutex, RwLock}; use crate::error::{ApiError, ApiResult}; -const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS pyo_observability.requests ( - ts DateTime64(3, 'UTC'), - team_id LowCardinality(String), - project_id LowCardinality(String), - service_id LowCardinality(String), - host LowCardinality(String), - method LowCardinality(String), - path String, - url String, - query_keys Array(String), - redacted_keys Array(String), - status UInt16, - duration_ms Float32, - bytes UInt64, - pageview UInt8, - visitor UInt64, - country LowCardinality(String), - country_name LowCardinality(String), - city String, - referrer String, - device LowCardinality(String), - browser LowCardinality(String), - ip String DEFAULT '', - user_agent String DEFAULT '', - -- The server that answered (traffic per region). - node LowCardinality(String) DEFAULT '', - -- The firewall's refusals: the rule (or blocked, rate-limit when it - -- can't be told) behind a 403 or 429. - blocked_by String DEFAULT '' -) ENGINE = MergeTree -PARTITION BY toYYYYMM(ts) -ORDER BY (team_id, host, ts) -TTL toDateTime(ts) + INTERVAL 180 DAY"; - -/// Connections to public TCP and UDP ports through the gateway: one -/// row per connection (per UDP session), written when it ends. -const CONNECTIONS_SCHEMA: &str = "CREATE TABLE IF NOT EXISTS pyo_observability.connections ( - ts DateTime64(3, 'UTC'), - team_id LowCardinality(String), - project_id LowCardinality(String), - service_id LowCardinality(String), - port UInt16, - protocol LowCardinality(String), - visitor UInt64, - ip String DEFAULT '', - country LowCardinality(String), - country_name LowCardinality(String), - city String, - duration_ms Float64, - bytes_in UInt64, - bytes_out UInt64, - outcome LowCardinality(String), - node LowCardinality(String) DEFAULT '', - rule String DEFAULT '' -) ENGINE = MergeTree -PARTITION BY toYYYYMM(ts) -ORDER BY (team_id, service_id, ts) -TTL toDateTime(ts) + INTERVAL 180 DAY"; - -/// The WAF's findings: one row per request where rules matched, -/// blocked or only logged. -const WAF_SCHEMA: &str = "CREATE TABLE IF NOT EXISTS pyo_observability.waf_hits ( - ts DateTime64(3, 'UTC'), - team_id LowCardinality(String), - project_id LowCardinality(String), - service_id LowCardinality(String), - host LowCardinality(String), - method LowCardinality(String), - path String, - url String, - ip String DEFAULT '', - country LowCardinality(String), - visitor UInt64, - blocked UInt8, - rules Array(UInt32), - messages Array(String), - severity LowCardinality(String), - node LowCardinality(String) DEFAULT '' -) ENGINE = MergeTree -PARTITION BY toYYYYMM(ts) -ORDER BY (team_id, host, ts) -TTL toDateTime(ts) + INTERVAL 180 DAY"; - const METRICS_SCHEMA: &str = "CREATE TABLE IF NOT EXISTS pyo_observability.metrics ( ts DateTime('UTC'), team_id LowCardinality(String), @@ -176,6 +86,12 @@ PARTITION BY toYYYYMM(ts) ORDER BY (team_id, database_id, metric, member, ts) TTL ts + INTERVAL 30 DAY"; +/// The metrics tables' statements, for tests that make them. +#[cfg(test)] +pub(crate) fn schema_for_tests() -> [&'static str; 3] { + [METRICS_SCHEMA, NODE_METRICS_SCHEMA, DATABASE_METRICS_SCHEMA] +} + /// One database metrics sample per cluster this often (the agent reads /// every member's page every 30s; heartbeats come every 10s). const DATABASE_SAMPLE_EVERY: Duration = Duration::from_secs(30); @@ -279,7 +195,7 @@ pub fn bar_steps(range: &str) -> (i64, i64) { /// Rows with a bucket (`b`, seconds) as one point per bucket of the /// range's bar chart, ending with the current one (empty buckets are 0). -fn bar_series(rows: &[Value], range: &str, point: impl Fn(Option<&Value>) -> Value) -> Vec { +pub(crate) fn bar_series(rows: &[Value], range: &str, point: impl Fn(Option<&Value>) -> Value) -> Vec { let (points, step) = bar_steps(range); let end = (pyo_proto::now_ms() / 1000 / step + 1) * step; let start = end - points * step; @@ -405,24 +321,8 @@ fn ingress_sample(hb: &pyo_proto::Heartbeat) -> Option { /// One metrics sample per cluster this often; heartbeats come every 10s. const SAMPLE_EVERY: Duration = Duration::from_secs(60); -/// Query parameters whose values are never stored. -const SENSITIVE: [&str; 15] = [ - "token", - "password", - "passwd", - "secret", - "apikey", - "api_key", - "auth", - "session", - "signature", - "email", - "otp", - "jwt", - "credential", - "code", - "invite", -]; +/// Where Pyo kept raw traffic before 0.5. +const LEGACY_TABLES: [&str; 3] = ["requests", "connections", "waf_hits"]; pub struct ClickHouse { http: reqwest::Client, @@ -432,11 +332,26 @@ pub struct ClickHouse { } impl ClickHouse { - async fn exec( + pub fn new(url: String, user: String, password: String) -> Self { + ClickHouse { http: reqwest::Client::new(), url, user, password } + } + + pub(crate) async fn exec( &self, sql: &str, body: Option, params: &[(&str, String)], + ) -> anyhow::Result { + self.exec_with(sql, body, params, &[]).await + } + + /// `exec` with ClickHouse settings for this statement. + pub(crate) async fn exec_with( + &self, + sql: &str, + body: Option, + params: &[(&str, String)], + settings: &[(&str, String)], ) -> anyhow::Result { let mut q: Vec<(String, String)> = vec![ ("output_format_json_quote_64bit_integers".into(), "0".into()), @@ -445,6 +360,9 @@ impl ClickHouse { for (k, v) in params { q.push((format!("param_{k}"), v.clone())); } + for (k, v) in settings { + q.push(((*k).to_owned(), v.clone())); + } let req = self .http .post(&self.url) @@ -470,7 +388,7 @@ impl ClickHouse { Ok(text) } - async fn rows(&self, sql: String, params: Vec<(&str, String)>) -> anyhow::Result> { + pub(crate) async fn rows(&self, sql: String, params: Vec<(&str, String)>) -> anyhow::Result> { let text = self .exec(&format!("{sql} FORMAT JSONEachRow"), None, ¶ms) .await?; @@ -483,21 +401,20 @@ impl ClickHouse { } #[derive(Clone)] -struct Owner { - team_id: String, - project_id: String, - service_id: String, - cluster_id: String, +pub(crate) struct Owner { + pub team_id: String, + pub project_id: String, + pub service_id: String, + pub cluster_id: String, } /// (cluster, a proxied port's route or "/") -> its /// service and public port. -type PortOwners = HashMap<(String, String), (Owner, u16)>; +pub(crate) type PortOwners = HashMap<(String, String), (Owner, u16)>; -/// (cluster, service) -> its firewall. -type Firewalls = HashMap<(String, String), pyo_proto::firewall::Firewall>; -/// Filters for `Observability::access_logs`. +/// Filters for the request log. +#[derive(Clone)] pub struct LogFilter { pub range: String, pub before: i64, @@ -517,10 +434,10 @@ pub struct Observability { /// (cluster, proxied port's route, or "/") -> /// owning service and the public port, cached 30s. routes: RwLock<(Instant, PortOwners)>, - /// Every service's firewall, to name the rule behind a refusal (30s). - firewalls: RwLock<(Instant, Firewalls)>, - salt: Mutex<(String, String)>, ready: RwLock, + /// The requests table from before 0.5 is still there (self-hosted, + /// read only until it expires). + legacy: RwLock, /// When each cluster's last metrics sample was stored. sampled: Mutex>, /// And its last database metrics sample. @@ -558,181 +475,12 @@ pub enum IpMode { impl IpMode { pub fn apply(self, ip: &str) -> String { - match (self, ip.parse::()) { - (IpMode::None, _) | (_, Err(_)) => String::new(), - (IpMode::Full, Ok(a)) => a.to_string(), - (IpMode::Anonymized, Ok(IpAddr::V4(v))) => { - let [a, b, c, _] = v.octets(); - std::net::Ipv4Addr::new(a, b, c, 0).to_string() - } - (IpMode::Anonymized, Ok(IpAddr::V6(v))) => { - let s = v.segments(); - std::net::Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0).to_string() - } - } - } -} - -impl AccessLine { - /// The visitor: the address the proxy placed them at (a PROXY protocol - /// header's, else the connection's), as its firewall and rate limits - /// see them; the TCP peer for lines without it. Never X-Forwarded-For - /// or X-Real-Ip: whoever reaches the proxy could write any address there - /// (pyo-proto's `client_policy_spec`). - pub fn visitor_ip(&self) -> &str { - if self.remote.is_empty() { - &self.peer - } else { - &self.remote - } - } -} - -/// One access log line from the gateway (Envoy's JSON, fields in -/// pyo-proto's system.rs). -#[derive(Debug, Default, PartialEq)] -pub struct AccessLine { - pub host: String, - pub ts_ms: Option, - pub peer: String, - pub forwarded_for: String, - pub real_ip: String, - pub user_agent: String, - pub status: u64, - pub method: String, - pub path: String, - pub content_type: String, - pub referer: String, - pub duration_ms: f64, - pub bytes: u64, - pub node: String, - /// The visitor as the proxy saw them (a PROXY protocol header's address, - /// or the peer). - pub remote: String, - /// TCP and UDP ports: bytes from the visitor, the route - /// (`tcproute/pyo-gateway//rule/0`), Envoy's flags and how the - /// connection ended. - pub bytes_in: u64, - pub upstream: String, - pub upstream_host: String, - pub local_port: u64, - pub flags: String, - pub termination: String, - /// Why the proxy answered itself (a firewall rule, a rate limit). - pub details: String, -} - -/// Which proxied port a connection line is about. -#[derive(Debug, PartialEq)] -pub enum PortKey<'a> { - /// By its route (TCP connections that reached it). - Route(&'a str), - /// By where the proxy listens for it (UDP sessions, which don't name - /// their route, and TCP connections turned away before one). - Listen(u16), -} - -impl AccessLine { - pub fn read(l: &Value) -> Self { - // Envoy writes null for a header that wasn't there. - let s = |k: &str| l[k].as_str().unwrap_or("").to_owned(); - let n = |k: &str| { - l[k].as_u64() - .or_else(|| l[k].as_str().and_then(|v| v.parse().ok())) - .unwrap_or(0) + let mode = match self { + IpMode::None => "none", + IpMode::Anonymized => "anonymized", + IpMode::Full => "full", }; - let ts = |k: &str| { - l[k].as_str() - .and_then(|t| t.parse::().ok()) - .map(|t| t.as_millisecond()) - }; - AccessLine { - host: s("host"), - ts_ms: ts("start_time"), - peer: s("peer"), - forwarded_for: s("x_forwarded_for"), - real_ip: s("x_real_ip"), - user_agent: s("user_agent"), - status: n("status"), - method: s("method"), - path: s("path"), - content_type: s("content_type"), - referer: s("referer"), - duration_ms: l["duration_ms"] - .as_f64() - .or_else(|| l["duration_ms"].as_str().and_then(|v| v.parse().ok())) - .unwrap_or(0.0), - bytes: n("bytes"), - node: s("PyoNode"), - remote: s("remote"), - bytes_in: n("bytes_in"), - upstream: s("upstream"), - upstream_host: s("upstream_host"), - local_port: n("local_port"), - flags: s("flags"), - termination: s("termination"), - details: s("details"), - } - } - - /// A connection to a public TCP or UDP port (no HTTP request in it): its - /// protocol and which port. TCP connections name their route - /// (`tcproute/pyo-gateway//rule/`); UDP sessions don't, but go - /// somewhere (`upstream_host`); a TCP connection the limit turned away - /// has neither. - pub fn port_key(&self) -> Option<(&'static str, PortKey<'_>)> { - if !self.method.is_empty() || !self.host.is_empty() { - return None; - } - if let Some(rest) = self - .upstream - .strip_prefix("tcproute/") - .or_else(|| self.upstream.strip_prefix("udproute/")) - { - let proto = if self.upstream.starts_with("tcp") { - "TCP" - } else { - "UDP" - }; - // //rule/ - let route = rest.split('/').nth(1)?; - return Some((proto, PortKey::Route(route))); - } - let port = u16::try_from(self.local_port).ok().filter(|p| *p > 0)?; - if !self.upstream.is_empty() { - return None; - } - Some(( - if self.upstream_host.is_empty() { - "TCP" - } else { - "UDP" - }, - PortKey::Listen(port), - )) - } - - /// How a connection went: "ok", "blocked" (an IP rule), "limited" (the - /// connection limit) or "unreachable" (the service didn't answer). - pub fn outcome(&self) -> &'static str { - let t = self.termination.to_ascii_lowercase(); - let f = self.flags.as_str(); - if t.contains("rbac") { - "blocked" - } else if t.contains("limit") - || f.contains("UO") - || f.contains("OL") - || (self.upstream.is_empty() && self.upstream_host.is_empty()) - { - "limited" - } else if ["UF", "UH", "URX", "NR", "UMSDR"] - .iter() - .any(|x| f.split(',').any(|y| y == *x)) - { - "unreachable" - } else { - "ok" - } + pyo_proto::traffic::mask_ip(mode, ip) } } @@ -791,12 +539,18 @@ type Series<'a> = (String, String, Vec>); impl Observability { pub fn from_env(db: PgPool) -> Arc { - let ch = env("CLICKHOUSE_URL").map(|url| ClickHouse { - http: reqwest::Client::new(), - url, - user: env("CLICKHOUSE_USER").unwrap_or_else(|| "default".into()), - password: env("CLICKHOUSE_PASSWORD").unwrap_or_default(), + let ch = env("CLICKHOUSE_URL").map(|url| { + ClickHouse::new( + url, + env("CLICKHOUSE_USER").unwrap_or_else(|| "default".into()), + env("CLICKHOUSE_PASSWORD").unwrap_or_default(), + ) }); + Self::with(db, ch) + } + + /// With this ClickHouse (or none). + pub fn with(db: PgPool, ch: Option) -> Arc { // geoip.rs loads the database once it has one. let geo: Option> = None; if ch.is_none() { @@ -808,9 +562,8 @@ impl Observability { db, hosts: RwLock::new((Instant::now() - Duration::from_secs(3600), HashMap::new())), routes: RwLock::new((Instant::now() - Duration::from_secs(3600), HashMap::new())), - firewalls: RwLock::new((Instant::now() - Duration::from_secs(3600), HashMap::new())), - salt: Mutex::new((String::new(), String::new())), ready: RwLock::new(false), + legacy: RwLock::new(false), sampled: Mutex::new(HashMap::new()), db_sampled: Mutex::new(HashMap::new()), ip_mode: RwLock::new((Instant::now() - Duration::from_secs(60), IpMode::None)), @@ -843,7 +596,7 @@ impl Observability { } /// ClickHouse, while observability is on. - async fn store(&self) -> Option<&ClickHouse> { + pub(crate) async fn store(&self) -> Option<&ClickHouse> { if self.enabled().await { self.ch.as_ref() } else { @@ -852,7 +605,7 @@ impl Observability { } /// ClickHouse for a reader, or why there's nothing to read. - async fn reader(&self) -> ApiResult<&ClickHouse> { + pub(crate) async fn reader(&self) -> ApiResult<&ClickHouse> { let Some(ch) = &self.ch else { return Err(ApiError::new( axum::http::StatusCode::SERVICE_UNAVAILABLE, @@ -877,16 +630,35 @@ impl Observability { let r = async { ch.exec("CREATE DATABASE IF NOT EXISTS pyo_observability", None, &[]) .await?; - ch.exec(SCHEMA, None, &[]).await?; - ch.exec(CONNECTIONS_SCHEMA, None, &[]).await?; - ch.exec(WAF_SCHEMA, None, &[]).await?; ch.exec(METRICS_SCHEMA, None, &[]).await?; ch.exec(NODE_METRICS_SCHEMA, None, &[]).await?; - ch.exec(DATABASE_METRICS_SCHEMA, None, &[]).await + ch.exec(DATABASE_METRICS_SCHEMA, None, &[]).await?; + for sql in crate::totals::schema() { + ch.exec(&sql, None, &[]).await?; + } + // Tables made with another TTL follow the installation's + // retention (Settings › Observability). + let retention = crate::retention::load(&self.db) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + crate::retention::apply(ch, &retention).await?; + // Raw requests from before 0.5: Pyo Cloud drops them; a + // self-hosted Pyo keeps them read only until they expire + // (180 days after they came in). + if crate::hosted() { + for t in LEGACY_TABLES { + ch.exec(&format!("DROP TABLE IF EXISTS pyo_observability.{t}"), None, &[]).await?; + } + anyhow::Ok(false) + } else { + let exists = ch.exec("EXISTS TABLE pyo_observability.requests", None, &[]).await?; + anyhow::Ok(exists.trim() == "1") + } } .await; match r { - Ok(_) => { + Ok(legacy) => { + *self.legacy.write().await = legacy; *self.ready.write().await = true; tracing::info!("observability storage ready"); return; @@ -900,7 +672,7 @@ impl Observability { } /// hostname -> owning service, from the domains of every service (cached 30s). - async fn owners(&self) -> anyhow::Result> { + pub(crate) async fn owners(&self) -> anyhow::Result> { { let g = self.hosts.read().await; if g.0.elapsed() < Duration::from_secs(30) { @@ -934,7 +706,7 @@ impl Observability { /// Each proxied TCP and UDP port's route (as the agent names it, /// `--tcp-`) -> its service and port. - async fn port_routes(&self) -> anyhow::Result { + pub(crate) async fn port_routes(&self) -> anyhow::Result { { let g = self.routes.read().await; if g.0.elapsed() < Duration::from_secs(30) { @@ -984,48 +756,7 @@ impl Observability { Ok(map) } - /// The rule behind a refusal: behind a CDN, a connection that didn't - /// come from it (`peer`, the connection's own address) is the CDN - /// check's ("cdn"); else the rule that matches the address (or its - /// country), else what the proxy said. - async fn refusal_rule( - &self, - cluster_id: &str, - service_id: &str, - why: String, - ip: &str, - peer: &str, - country: &str, - ) -> String { - if why != "blocked" && why != "rate-limit" { - return why; - } - let stale = self.firewalls.read().await.0.elapsed() >= Duration::from_secs(30); - if stale && let Ok(all) = crate::firewall::all_firewalls(&self.db).await { - *self.firewalls.write().await = (Instant::now(), all); - } - let g = self.firewalls.read().await; - let (Some(f), Ok(addr)) = ( - g.1.get(&(cluster_id.to_owned(), service_id.to_owned())), - ip.parse::(), - ) else { - return why; - }; - if why == "blocked" - && let Ok(peer) = peer.parse::() - && !pyo_proto::firewall::via_cdn(f, peer) - { - return pyo_proto::firewall::BEHIND_RULE.to_owned(); - } - let rule = if why == "blocked" { - pyo_proto::firewall::blocking_rule(&[f], addr, Some(country).filter(|c| !c.is_empty())) - } else { - pyo_proto::firewall::rate_limiting_rule(&[f], addr) - }; - rule.map(str::to_owned).unwrap_or(why) - } - - async fn current_ip_mode(&self) -> IpMode { + pub(crate) async fn current_ip_mode(&self) -> IpMode { { let g = self.ip_mode.read().await; if g.0.elapsed() < Duration::from_secs(30) { @@ -1037,241 +768,31 @@ impl Observability { mode } - /// Today's salt for visitor hashes, shared through Postgres; older ones are deleted. - async fn daily_salt(&self, day: &str) -> anyhow::Result { - let mut g = self.salt.lock().await; - if g.0 == day { - return Ok(g.1.clone()); + /// After the retention setting changed: the tables' TTLs follow now + /// while storage is up, else when it's set up next. + pub(crate) async fn apply_retention(&self, r: crate::retention::Retention) { + let Some(ch) = self.store().await else { return }; + if !self.is_ready().await { + return; + } + if let Err(e) = crate::retention::apply(ch, &r).await { + tracing::warn!(error = %format!("{e:#}"), "couldn't apply the observability retention; it applies at the next start"); } - let fresh = crate::ids::secret_token(); - let salt: String = sqlx::query_scalar( - "INSERT INTO pyo.observability_salts (day, salt) VALUES ($1::date, $2) - ON CONFLICT (day) DO UPDATE SET day = excluded.day RETURNING salt", - ) - .bind(day) - .bind(&fresh) - .fetch_one(&self.db) - .await?; - sqlx::query("DELETE FROM pyo.observability_salts WHERE day < $1::date - 1") - .bind(day) - .execute(&self.db) - .await?; - *g = (day.to_owned(), salt.clone()); - Ok(salt) } - /// Store a batch of access log lines (the gateway's) from one cluster. - pub async fn ingest(&self, cluster_id: &str, lines: Vec) -> ApiResult { - let Some(ch) = self.store().await else { - return Ok(0); - }; - if !*self.ready.read().await { - return Err(ApiError::new( - axum::http::StatusCode::SERVICE_UNAVAILABLE, - "Observability storage is starting.", - )); - } - let owners = self.owners().await?; - let ua_parser = woothee::parser::Parser::new(); - let mut out = String::new(); - let mut conns = String::new(); - let mut waf = String::new(); - let mut n = 0; - for l in lines { - // The WAF's finding for one request (pyo-waf's line). - if l.get("waf").is_some() { - let host = l["host"].as_str().unwrap_or("").to_lowercase(); - let Some(owner) = owners.get(&host).filter(|o| o.cluster_id == cluster_id) else { - continue; - }; - let ts = l["time"] - .as_str() - .and_then(|t| t.parse::().ok()) - .map(|t| t.as_millisecond()) - .unwrap_or_else(pyo_proto::now_ms); - let day = jiff::Timestamp::from_millisecond(ts) - .map(|t| t.strftime("%Y-%m-%d").to_string()) - .unwrap_or_default(); - let salt = self.daily_salt(&day).await?; - let ip = l["client"].as_str().unwrap_or("").to_owned(); - let (country, _, _) = self.locate(&ip); - let (path, url, _, _) = split_url(l["uri"].as_str().unwrap_or("/")); - let visitor = { - let d = Sha256::digest(format!("{salt}|{ip}|waf|{host}").as_bytes()); - u64::from_be_bytes(d[..8].try_into().unwrap_or([0; 8])) - }; - let row = json!({ - "ts": ts as f64 / 1000.0, - "team_id": owner.team_id, "project_id": owner.project_id, "service_id": owner.service_id, - "host": host, "method": l["method"].as_str().unwrap_or("").chars().take(16).collect::(), - "path": path, "url": url, - "ip": self.current_ip_mode().await.apply(&ip), "country": country, "visitor": visitor, - "blocked": l["blocked"].as_bool().unwrap_or(false) as u8, - "rules": l["rules"].as_array().into_iter().flatten().filter_map(Value::as_u64).take(50).collect::>(), - "messages": l["messages"].as_array().into_iter().flatten().filter_map(Value::as_str).take(50).map(|m| m.chars().take(300).collect::()).collect::>(), - "severity": l["severity"].as_str().unwrap_or("").chars().take(16).collect::(), - "node": l["PyoNode"].as_str().unwrap_or("").chars().take(253).collect::(), - }); - waf.push_str(&row.to_string()); - waf.push('\n'); - n += 1; - continue; - } - let l = AccessLine::read(&l); - // A connection to a public TCP or UDP port. - if let Some((proto, key)) = l.port_key() { - let routes = self.port_routes().await?; - let key = match key { - PortKey::Route(r) => r.to_owned(), - PortKey::Listen(port) => format!("{proto}/{port}"), - }; - let Some((owner, port)) = routes.get(&(cluster_id.to_owned(), key)) else { - continue; - }; - let ts = l.ts_ms.unwrap_or_else(pyo_proto::now_ms); - let day = jiff::Timestamp::from_millisecond(ts) - .map(|t| t.strftime("%Y-%m-%d").to_string()) - .unwrap_or_default(); - let salt = self.daily_salt(&day).await?; - let ip = l.visitor_ip().to_owned(); - let (country, country_name, city) = self.locate(&ip); - let visitor = { - let d = Sha256::digest( - format!("{salt}|{ip}|{}|{port}", owner.service_id).as_bytes(), - ); - u64::from_be_bytes(d[..8].try_into().unwrap_or([0; 8])) - }; - let row = json!({ - "ts": ts as f64 / 1000.0, - "team_id": owner.team_id, "project_id": owner.project_id, "service_id": owner.service_id, - "port": port, "protocol": proto, "visitor": visitor, - "ip": self.current_ip_mode().await.apply(&ip), - "country": country, "country_name": country_name, "city": city, - "duration_ms": l.duration_ms, "bytes_in": l.bytes_in, "bytes_out": l.bytes, - "outcome": l.outcome(), - "node": l.node.chars().take(253).collect::(), - "rule": self.refusal_rule(cluster_id, &owner.service_id, crate::firewall::refusal("", &l.termination, 0), &ip, "", &country).await, - }); - conns.push_str(&row.to_string()); - conns.push('\n'); - n += 1; - continue; - } - let host = l.host.split(':').next().unwrap_or("").to_lowercase(); - // Only traffic for a domain of a service on this cluster. - let Some(owner) = owners.get(&host).filter(|o| o.cluster_id == cluster_id) else { - continue; - }; - let ts = l.ts_ms.unwrap_or_else(pyo_proto::now_ms); - let day = jiff::Timestamp::from_millisecond(ts) - .map(|t| t.strftime("%Y-%m-%d").to_string()) - .unwrap_or_default(); - let salt = self.daily_salt(&day).await?; - let ip = l.visitor_ip(); - let ua = l.user_agent.as_str(); - let status = l.status; - let method = if l.method.is_empty() { - "GET" - } else { - l.method.as_str() - }; - let (path, url, keys, redacted) = split_url(if l.path.is_empty() { - "/" - } else { - l.path.as_str() - }); - let ctype = l.content_type.as_str(); - - let parsed = ua_parser.parse(ua); - let crawler = parsed.as_ref().is_some_and(|r| r.category == "crawler"); - let device = match parsed.as_ref().map(|r| r.category) { - Some("pc") => "Desktop", - Some("smartphone") | Some("mobilephone") => "Mobile", - Some("crawler") => "Bot", - Some("appliance") => "Other", - _ if ua.is_empty() => "Unknown", - _ => "Other", - }; - let browser = parsed - .as_ref() - .map(|r| r.name) - .filter(|n| !n.is_empty() && *n != "UNKNOWN") - .unwrap_or(if ua.starts_with("curl/") { - "curl" - } else { - "Other" - }); - // A page view: a GET answered with HTML (a 304 has no body, so a path without an extension). - let html = ctype.starts_with("text/html") - || (status == 304 - && ctype.is_empty() - && !path.rsplit('/').next().unwrap_or("").contains('.')); - let pageview = method == "GET" && (200..400).contains(&status) && html && !crawler; - - let referrer = Some(l.referer.as_str()) - .filter(|r| !r.is_empty()) - .and_then(|r| r.split("://").nth(1)) - .map(|r| r.split(['/', '?', ':']).next().unwrap_or("").to_lowercase()); - let referrer = match referrer.as_deref() { - None | Some("") => "Direct".to_owned(), - Some(r) if r == host => String::new(), - Some(r) => r.trim_start_matches("www.").to_owned(), - }; + pub(crate) async fn is_ready(&self) -> bool { + *self.ready.read().await + } - let (country, country_name, city) = self.locate(ip); - let stored_ip = self.current_ip_mode().await.apply(ip); - let visitor = { - let d = Sha256::digest(format!("{salt}|{ip}|{ua}|{host}").as_bytes()); - u64::from_be_bytes(d[..8].try_into().unwrap_or([0; 8])) - }; + /// Tests: storage as if its tables were made. + #[cfg(test)] + pub async fn ensure_ready_for_tests(&self) { + *self.ready.write().await = true; + } - let row = json!({ - "ts": ts as f64 / 1000.0, - "team_id": owner.team_id, "project_id": owner.project_id, "service_id": owner.service_id, - "host": host, "method": method, "path": path, "url": url, - "query_keys": keys, "redacted_keys": redacted, - "status": status, - "duration_ms": l.duration_ms, - "bytes": l.bytes, - "pageview": pageview as u8, - "visitor": visitor, - "country": country, "country_name": country_name, "city": city, - "referrer": referrer, "device": device, "browser": browser, - "ip": stored_ip, - // As sent, for the request log; capped like a header line. - "user_agent": ua.chars().take(512).collect::(), - "node": l.node.chars().take(253).collect::(), - "blocked_by": self.refusal_rule(cluster_id, &owner.service_id, crate::firewall::refusal(&l.details, "", status), ip, &l.peer, &country).await, - }); - out.push_str(&row.to_string()); - out.push('\n'); - n += 1; - } - if !out.is_empty() { - ch.exec( - "INSERT INTO pyo_observability.requests FORMAT JSONEachRow", - Some(out), - &[], - ) - .await?; - } - if !conns.is_empty() { - ch.exec( - "INSERT INTO pyo_observability.connections FORMAT JSONEachRow", - Some(conns), - &[], - ) - .await?; - } - if !waf.is_empty() { - ch.exec( - "INSERT INTO pyo_observability.waf_hits FORMAT JSONEachRow", - Some(waf), - &[], - ) - .await?; - } - Ok(n) + /// The requests table from before 0.5 is there to read. + pub async fn has_legacy(&self) -> bool { + self.ch.is_some() && *self.legacy.read().await } /// Store a heartbeat's CPU and memory figures, at most once a minute per @@ -1710,81 +1231,11 @@ impl Observability { ) } - /// The web server's request log for a set of hostnames: newest first, - /// `limit` rows before `before` (ms; now when 0). Filters: a status class - /// ("2xx"…"5xx"), a method, and text in the host, path or URL. Client IPs - /// follow the analytics setting, like the analytics page's. - /// Requests, server errors and response times per answering server, for - /// some hostnames over the last `hours`. Empty without storage. - pub async fn per_server( - &self, - team_id: &str, - hosts: &[String], - hours: i64, - ) -> ApiResult> { - let Some(ch) = self.store().await else { - return Ok(vec![]); - }; - if hosts.is_empty() { - return Ok(vec![]); - } - let hosts_param = format!( - "[{}]", - hosts - .iter() - .map(|h| format!("'{}'", h.replace(['\\', '\''], ""))) - .collect::>() - .join(",") - ); - let since = pyo_proto::now_ms() - hours * 3_600_000; - Ok(ch - .rows( - "SELECT node, count() AS requests, countIf(status >= 500) AS errors, round(avg(duration_ms), 1) AS avgMs, round(quantile(0.95)(duration_ms), 1) AS p95Ms - FROM pyo_observability.requests - WHERE team_id = {team:String} AND has({hosts:Array(String)}, host) AND ts >= fromUnixTimestamp64Milli({since:Int64}) - GROUP BY node" - .into(), - vec![("team", team_id.to_owned()), ("hosts", hosts_param), ("since", since.to_string())], - ) - .await?) - } - - /// Requests per answering server per hour, for the last `hours` - /// (sparklines). Empty without storage. - pub async fn per_server_hourly( - &self, - team_id: &str, - hosts: &[String], - hours: i64, - ) -> ApiResult> { - let Some(ch) = self.store().await else { - return Ok(vec![]); - }; - if hosts.is_empty() { - return Ok(vec![]); - } - let hosts_param = format!( - "[{}]", - hosts - .iter() - .map(|h| format!("'{}'", h.replace(['\\', '\''], ""))) - .collect::>() - .join(",") - ); - let since = pyo_proto::now_ms() - hours * 3_600_000; - Ok(ch - .rows( - "SELECT node, toUnixTimestamp(toStartOfHour(ts)) AS hour, count() AS requests - FROM pyo_observability.requests - WHERE team_id = {team:String} AND has({hosts:Array(String)}, host) AND ts >= fromUnixTimestamp64Milli({since:Int64}) - GROUP BY node, hour" - .into(), - vec![("team", team_id.to_owned()), ("hosts", hosts_param), ("since", since.to_string())], - ) - .await?) - } - - pub async fn access_logs( + /// The web server's request log as Pyo kept it before 0.5 (self-hosted, + /// until it expires): newest first, `limit` rows before `before` (ms; + /// now when 0). Filters: a status class ("2xx"…"5xx"), a method, and + /// text in the host, path or URL. Client IPs follow the IP setting. + pub async fn legacy_access_logs( &self, team_id: &str, hosts: &[String], @@ -1895,444 +1346,15 @@ impl Observability { Ok(json!({ "logs": logs, "next": next, "ipMode": mode, "summary": summary })) } - /// The analytics page's data for a set of hostnames of one team. - pub async fn query(&self, team_id: &str, hosts: &[String], range: &str) -> ApiResult { - let ch = self.reader().await?; - let (points, step, start, end) = window(range, pyo_proto::now_ms() / 1000); - let prev_start = start - points * step; - - let hosts_param = format!( - "[{}]", - hosts - .iter() - .map(|h| format!("'{}'", h.replace(['\\', '\''], ""))) - .collect::>() - .join(",") - ); - let p = |s: i64, e: i64| -> Vec<(&'static str, String)> { - vec![ - ("team", team_id.to_owned()), - ("hosts", hosts_param.clone()), - ("start", s.to_string()), - ("end", e.to_string()), - ("step", step.to_string()), - ] - }; - const W: &str = "team_id = {team:String} AND has({hosts:Array(String)}, host) AND ts >= toDateTime64({start:Int64}, 3) AND ts < toDateTime64({end:Int64}, 3)"; - - let summary_sql = format!( - "SELECT count() AS requests, uniq(visitor) AS visitors, countIf(pageview = 1) AS pageviews, - sum(bytes) / 1e6 AS mb, countIf(status >= 500) AS errors, - quantiles(0.5, 0.95, 0.99)(duration_ms) AS q - FROM pyo_observability.requests WHERE {W}" - ); - let (cur, prev, series, statuses, pages, paths, refs, countries, cities, devices, browsers, params, recent, ips) = tokio::try_join!( - ch.rows(summary_sql.clone(), p(start, end)), - ch.rows(summary_sql.clone(), p(prev_start, start)), - ch.rows( - format!( - "SELECT toUnixTimestamp(toStartOfInterval(ts, toIntervalSecond({{step:Int64}}))) AS b, count() AS requests, uniq(visitor) AS visitors, - sum(bytes) / 1e6 AS mb, countIf(status >= 500) AS errors, quantiles(0.5, 0.95, 0.99)(duration_ms) AS q - FROM pyo_observability.requests WHERE {W} GROUP BY b ORDER BY b" - ), - p(start, end) - ), - ch.rows(format!("SELECT concat(toString(intDiv(status, 100)), 'xx') AS code, count() AS c FROM pyo_observability.requests WHERE {W} AND status >= 200 GROUP BY code"), p(start, end)), - ch.rows(format!("SELECT url, any(path) AS path, count() AS views, uniq(visitor) AS visitors, avg(duration_ms) AS ms FROM pyo_observability.requests WHERE {W} AND pageview = 1 GROUP BY url ORDER BY views DESC LIMIT 100"), p(start, end)), - ch.rows(format!("SELECT path, count() AS c, quantile(0.95)(duration_ms) AS p95 FROM pyo_observability.requests WHERE {W} GROUP BY path ORDER BY c DESC LIMIT 25"), p(start, end)), - ch.rows(format!("SELECT referrer AS k, uniq(visitor) AS v FROM pyo_observability.requests WHERE {W} AND pageview = 1 AND referrer != '' GROUP BY k ORDER BY v DESC LIMIT 25"), p(start, end)), - ch.rows(format!("SELECT if(country = '', '??', country) AS code, if(country_name = '', 'Unknown', country_name) AS name, uniq(visitor) AS v FROM pyo_observability.requests WHERE {W} GROUP BY code, name ORDER BY v DESC LIMIT 25"), p(start, end)), - ch.rows(format!("SELECT city, any(country) AS country, uniq(visitor) AS v FROM pyo_observability.requests WHERE {W} AND city != '' GROUP BY city ORDER BY v DESC LIMIT 25"), p(start, end)), - ch.rows(format!("SELECT device AS k, uniq(visitor) AS v FROM pyo_observability.requests WHERE {W} GROUP BY k ORDER BY v DESC"), p(start, end)), - ch.rows(format!("SELECT browser AS k, uniq(visitor) AS v FROM pyo_observability.requests WHERE {W} GROUP BY k ORDER BY v DESC LIMIT 15"), p(start, end)), - ch.rows( - format!( - "SELECT splitByChar('=', kv)[1] AS k, count() AS c, uniqExact(kv) AS d, max(position(kv, '[redacted]') > 0) AS r - FROM pyo_observability.requests ARRAY JOIN extractURLParameters(url) AS kv WHERE {W} GROUP BY k ORDER BY c DESC LIMIT 30" - ), - p(start, end) - ), - ch.rows(format!("SELECT toUnixTimestamp64Milli(ts) AS at, method, url, path, status, duration_ms, bytes, country, ip FROM pyo_observability.requests WHERE {W} ORDER BY ts DESC LIMIT 50"), p(start, end)), - ch.rows(format!("SELECT ip AS k, count() AS c, uniq(visitor) AS v FROM pyo_observability.requests WHERE {W} AND ip != '' GROUP BY k ORDER BY c DESC LIMIT 100"), p(start, end)), - )?; - // Client IPs as the analytics setting says now: hidden when it's - // "none", shortened when it's "anonymized" (for rows kept in full - // before the setting changed). - let mode = self.current_ip_mode().await; - let mut by_ip: Vec<(String, f64, f64)> = vec![]; - for r in &ips { - let ip = mode.apply(r["k"].as_str().unwrap_or("")); - if ip.is_empty() { - continue; - } - let (c, v) = ( - r["c"].as_f64().unwrap_or(0.0), - r["v"].as_f64().unwrap_or(0.0), - ); - match by_ip.iter_mut().find(|x| x.0 == ip) { - Some(x) => { - x.1 += c; - x.2 += v; - } - None => by_ip.push((ip, c, v)), - } - } - by_ip.sort_by(|a, b| b.1.total_cmp(&a.1)); - by_ip.truncate(25); - - let num = |v: &Value, k: &str| v[k].as_f64().unwrap_or(0.0); - let q = |v: &Value, i: usize| { - v["q"][i] - .as_f64() - .filter(|x| x.is_finite()) - .unwrap_or(0.0) - .round() - }; - let c = cur.first().cloned().unwrap_or_default(); - let pv = prev.first().cloned().unwrap_or_default(); - let requests = num(&c, "requests"); - - // Every bucket, including empty ones. - let by_bucket: HashMap = series - .iter() - .map(|r| (r["b"].as_i64().unwrap_or(0), r)) - .collect(); - let series: Vec = (0..points) - .map(|i| { - let b = start + i * step; - let r = by_bucket.get(&b); - let g = |k: &str| r.map(|r| num(r, k)).unwrap_or(0.0); - json!({ - "at": b * 1000, - "requests": g("requests"), "visitors": g("visitors"), "bandwidthMb": g("mb"), "errors": g("errors"), - "p50": r.map(|r| q(r, 0)).unwrap_or(0.0), "p95": r.map(|r| q(r, 1)).unwrap_or(0.0), "p99": r.map(|r| q(r, 2)).unwrap_or(0.0), - }) - }) - .collect(); - - let status_codes: Vec = ["2xx", "3xx", "4xx", "5xx"] - .iter() - .map(|code| json!({ "code": code, "count": statuses.iter().find(|s| s["code"] == json!(code)).map(|s| num(s, "c")).unwrap_or(0.0) })) - .collect(); - let kv = |rows: &[Value], key: &str, label: &str| -> Vec { - rows.iter() - .map(|r| json!({ key: r["k"], label: num(r, "v") })) - .collect() - }; - let summary = json!({ - "range": range, - "requests": requests, - "estimatedVisitors": num(&c, "visitors"), - "pageviews": num(&c, "pageviews"), - "bandwidthMb": num(&c, "mb"), - "errorRate": if requests > 0.0 { num(&c, "errors") / requests } else { 0.0 }, - "latency": { "p50": q(&c, 0), "p95": q(&c, 1), "p99": q(&c, 2) }, - "statusCodes": status_codes, - "topPaths": paths.iter().map(|r| json!({ "path": r["path"], "requests": num(r, "c"), "p95": num(r, "p95").round() })).collect::>(), - "referrers": kv(&refs, "source", "visitors"), - "countries": countries.iter().map(|r| json!({ "code": r["code"], "name": r["name"], "visitors": num(r, "v") })).collect::>(), - "cities": cities.iter().map(|r| json!({ "city": r["city"], "country": r["country"], "visitors": num(r, "v") })).collect::>(), - "pages": pages.iter().map(|r| json!({ "url": r["url"], "path": r["path"], "views": num(r, "views"), "visitors": num(r, "visitors"), "avgMs": num(r, "ms").round() })).collect::>(), - "devices": kv(&devices, "label", "visitors"), - "browsers": kv(&browsers, "label", "visitors"), - "queryParams": params.iter().map(|r| json!({ "key": r["k"], "requests": num(r, "c"), "distinct": num(r, "d"), "redacted": num(r, "r") > 0.0 })).collect::>(), - "recentRequests": recent.iter().enumerate().map(|(i, r)| json!({ "id": format!("req_{i}"), "at": r["at"], "method": r["method"], "url": r["url"], "path": r["path"], "status": r["status"], "durationMs": num(r, "duration_ms").round(), "bytes": r["bytes"], "country": r["country"], "ip": mode.apply(r["ip"].as_str().unwrap_or("")) })).collect::>(), - "ipMode": mode, - "clientIps": by_ip.iter().map(|(ip, c, v)| json!({ "ip": ip, "requests": c, "visitors": v })).collect::>(), - }); - let prev_requests = num(&pv, "requests"); - Ok(json!({ - "summary": summary, - "series": series, - "previous": { - "estimatedVisitors": num(&pv, "visitors"), - "pageviews": num(&pv, "pageviews"), - "errorRate": if prev_requests > 0.0 { num(&pv, "errors") / prev_requests } else { 0.0 }, - }, - })) - } } impl Observability { - /// A service's connections to its public TCP and UDP ports through the - /// gateway: per port, over time, by country and outcome, and the - /// latest ones. - pub async fn connections( - &self, - team_id: &str, - service_id: &str, - range: &str, - ) -> ApiResult { - let ch = self.reader().await?; - let (points, step) = match range { - "1h" => (60i64, 60i64), - "24h" => (48, 1800), - "30d" => (30, 86400), - _ => (42, 14400), - }; - let now = pyo_proto::now_ms() / 1000; - let end = (now / step + 1) * step; - let start = end - points * step; - let p = || -> Vec<(&'static str, String)> { - vec![ - ("team", team_id.to_owned()), - ("service", service_id.to_owned()), - ("start", start.to_string()), - ("end", end.to_string()), - ("step", step.to_string()), - ] - }; - const W: &str = "team_id = {team:String} AND service_id = {service:String} AND ts >= toDateTime64({start:Int64}, 3) AND ts < toDateTime64({end:Int64}, 3)"; - let (ports, series, countries, outcomes, recent) = tokio::try_join!( - ch.rows(format!("SELECT port, protocol, count() AS c, uniq(visitor) AS v, sum(bytes_in) AS bin, sum(bytes_out) AS bout, quantiles(0.5, 0.95)(duration_ms) AS q, countIf(outcome = 'blocked') AS blocked, countIf(outcome = 'limited') AS limited, countIf(outcome = 'unreachable') AS unreachable FROM pyo_observability.connections WHERE {W} GROUP BY port, protocol ORDER BY port"), p()), - ch.rows(format!("SELECT toUnixTimestamp(toStartOfInterval(ts, toIntervalSecond({{step:Int64}}))) AS b, count() AS c, uniq(visitor) AS v, sum(bytes_in + bytes_out) AS bytes FROM pyo_observability.connections WHERE {W} GROUP BY b ORDER BY b"), p()), - ch.rows(format!("SELECT if(country = '', '??', country) AS code, if(country_name = '', 'Unknown', country_name) AS name, uniq(visitor) AS v, count() AS c FROM pyo_observability.connections WHERE {W} GROUP BY code, name ORDER BY c DESC LIMIT 25"), p()), - ch.rows(format!("SELECT outcome AS k, count() AS c FROM pyo_observability.connections WHERE {W} GROUP BY k"), p()), - ch.rows(format!("SELECT toUnixTimestamp64Milli(ts) AS at, port, protocol, ip, country, duration_ms, bytes_in, bytes_out, outcome FROM pyo_observability.connections WHERE {W} ORDER BY ts DESC LIMIT 50"), p()), - )?; - let mode = self.current_ip_mode().await; - let num = |v: &Value, k: &str| v[k].as_f64().unwrap_or(0.0); - let q = |v: &Value, i: usize| { - v["q"][i] - .as_f64() - .filter(|x| x.is_finite()) - .unwrap_or(0.0) - .round() - }; - let by_bucket: HashMap = series - .iter() - .map(|r| (r["b"].as_i64().unwrap_or(0), r)) - .collect(); - let series: Vec = (0..points) - .map(|i| { - let b = start + i * step; - let r = by_bucket.get(&b); - let g = |k: &str| r.map(|r| num(r, k)).unwrap_or(0.0); - json!({ "at": b * 1000, "connections": g("c"), "clients": g("v"), "bytes": g("bytes") }) - }) - .collect(); - Ok(json!({ - "range": range, - "ports": ports.iter().map(|r| json!({ - "port": r["port"], "protocol": r["protocol"], "connections": num(r, "c"), "clients": num(r, "v"), - "bytesIn": num(r, "bin"), "bytesOut": num(r, "bout"), "durationP50Ms": q(r, 0), "durationP95Ms": q(r, 1), - "blocked": num(r, "blocked"), "limited": num(r, "limited"), "unreachable": num(r, "unreachable"), - })).collect::>(), - "series": series, - "countries": countries.iter().map(|r| json!({ "code": r["code"], "name": r["name"], "clients": num(r, "v"), "connections": num(r, "c") })).collect::>(), - "outcomes": outcomes.iter().map(|r| json!({ "outcome": r["k"], "count": num(r, "c") })).collect::>(), - "recent": recent.iter().map(|r| json!({ - "at": r["at"], "port": r["port"], "protocol": r["protocol"], "ip": mode.apply(r["ip"].as_str().unwrap_or("")), "country": r["country"], - "durationMs": num(r, "duration_ms").round(), "bytesIn": r["bytes_in"], "bytesOut": r["bytes_out"], "outcome": r["outcome"], - })).collect::>(), - "ipMode": mode, - })) - } -} - -impl Observability { - /// What the firewall turned away for these services: over time, per - /// rule, source, country and website path, and the latest, from - /// websites (403s and 429s the proxy answered itself) and TCP ports - /// through the proxy. - pub async fn blocked( - &self, - team_id: &str, - services: &[String], - range: &str, - ) -> ApiResult { - let ch = self.reader().await?; - let secs = match range { - "1h" => 3600, - "7d" => 7 * 86400, - "30d" => 30 * 86400, - _ => 86400, - }; - let start = pyo_proto::now_ms() / 1000 - secs; - let services_param = format!( - "[{}]", - services - .iter() - .map(|a| format!("'{}'", a.replace(['\\', '\''], ""))) - .collect::>() - .join(",") - ); - let step = bar_steps(range).1; - let p = || -> Vec<(&'static str, String)> { - vec![ - ("team", team_id.to_owned()), - ("services", services_param.clone()), - ("start", start.to_string()), - ("step", step.to_string()), - ] - }; - // Both tables, as one: a website request or a connection. - let both = "(SELECT ts, service_id, 'website' AS kind, host AS target, path, ip, country, country_name, blocked_by AS rule, visitor FROM pyo_observability.requests - WHERE team_id = {team:String} AND has({services:Array(String)}, service_id) AND ts >= toDateTime64({start:Int64}, 3) AND blocked_by != '' - UNION ALL - SELECT ts, service_id, lower(protocol) AS kind, toString(port) AS target, '' AS path, ip, country, country_name, rule, visitor FROM pyo_observability.connections - WHERE team_id = {team:String} AND has({services:Array(String)}, service_id) AND ts >= toDateTime64({start:Int64}, 3) AND outcome = 'blocked')"; - let (rules, sources, countries, paths, series, recent) = tokio::try_join!( - ch.rows(format!("SELECT rule, count() AS c FROM {both} GROUP BY rule ORDER BY c DESC LIMIT 50"), p()), - ch.rows(format!("SELECT ip, any(country) AS country, any(country_name) AS name, count() AS c, uniq(visitor) AS v FROM {both} GROUP BY ip ORDER BY c DESC LIMIT 50"), p()), - ch.rows(format!("SELECT country, count() AS c FROM {both} GROUP BY country ORDER BY c DESC LIMIT 25"), p()), - ch.rows(format!("SELECT path, count() AS c FROM {both} WHERE kind = 'website' GROUP BY path ORDER BY c DESC LIMIT 25"), p()), - ch.rows(format!("SELECT toUnixTimestamp(toStartOfInterval(ts, toIntervalSecond({{step:Int64}}))) AS b, count() AS c FROM {both} GROUP BY b"), p()), - ch.rows(format!("SELECT toUnixTimestamp64Milli(ts) AS at, service_id, kind, target, ip, country, rule FROM {both} ORDER BY ts DESC LIMIT 50"), p()), - )?; - let mode = self.current_ip_mode().await; - let num = |v: &Value, k: &str| v[k].as_f64().unwrap_or(0.0); - Ok(json!({ - "range": range, - "total": rules.iter().map(|r| num(r, "c")).sum::(), - "series": bar_series(&series, range, |r| json!({ "count": r.map(|r| num(r, "c")).unwrap_or(0.0) })), - "rules": rules.iter().map(|r| json!({ "rule": r["rule"], "count": num(r, "c") })).collect::>(), - "sources": sources.iter().map(|r| json!({ "ip": mode.apply(r["ip"].as_str().unwrap_or("")), "country": r["country"], "countryName": r["name"], "count": num(r, "c"), "clients": num(r, "v") })).collect::>(), - "countries": countries.iter().map(|r| json!({ "country": r["country"], "count": num(r, "c") })).collect::>(), - "paths": paths.iter().map(|r| json!({ "path": r["path"], "count": num(r, "c") })).collect::>(), - "recent": recent.iter().map(|r| json!({ "at": r["at"], "serviceId": r["service_id"], "kind": r["kind"], "target": r["target"], "ip": mode.apply(r["ip"].as_str().unwrap_or("")), "country": r["country"], "rule": r["rule"] })).collect::>(), - "ipMode": mode, - })) - } - - /// The WAF's findings for these services: blocked and logged - /// requests, over time, per rule, domain, source, country and path, the - /// latest 50, and the custom rules' match counts. - pub async fn waf_hits( - &self, - team_id: &str, - services: &[String], - range: &str, - ) -> ApiResult { - let ch = self.reader().await?; - let secs = match range { - "1h" => 3600, - "7d" => 7 * 86400, - "30d" => 30 * 86400, - _ => 86400, - }; - let start = pyo_proto::now_ms() / 1000 - secs; - let services_param = format!( - "[{}]", - services - .iter() - .map(|a| format!("'{}'", a.replace(['\\', '\''], ""))) - .collect::>() - .join(",") - ); - let step = bar_steps(range).1; - let p = || -> Vec<(&'static str, String)> { - vec![ - ("team", team_id.to_owned()), - ("services", services_param.clone()), - ("start", start.to_string()), - ("step", step.to_string()), - ] - }; - const W: &str = "team_id = {team:String} AND has({services:Array(String)}, service_id) AND ts >= toDateTime64({start:Int64}, 3)"; - // Custom rules are numbered from 1000000 (pyo_proto::WAF_RULE_IDS); - // the Core Rule Set's from 949000 are its scoring, not findings. - let (totals, rules, hosts, recent, custom, (series, sources, countries, paths)) = tokio::try_join!( - ch.rows(format!("SELECT countIf(blocked = 1) AS nb, countIf(blocked = 0) AS nl, uniq(visitor) AS v FROM pyo_observability.waf_hits WHERE {W}"), p()), - ch.rows(format!("SELECT rule, any(msg) AS message, count() AS c FROM pyo_observability.waf_hits ARRAY JOIN rules AS rule, messages AS msg WHERE {W} AND (rule < 949000 OR rule >= 1000000) GROUP BY rule ORDER BY c DESC LIMIT 25"), p()), - ch.rows(format!("SELECT host, countIf(blocked = 1) AS nb, countIf(blocked = 0) AS nl FROM pyo_observability.waf_hits WHERE {W} GROUP BY host ORDER BY nb + nl DESC LIMIT 25"), p()), - ch.rows(format!("SELECT toUnixTimestamp64Milli(ts) AS at, service_id, host, method, url, ip, country, blocked, rules, messages, severity FROM pyo_observability.waf_hits WHERE {W} ORDER BY ts DESC LIMIT 50"), p()), - ch.rows(format!("SELECT rule, count() AS c FROM pyo_observability.waf_hits ARRAY JOIN rules AS rule WHERE {W} AND rule >= 1000000 GROUP BY rule"), p()), - async { - tokio::try_join!( - ch.rows(format!("SELECT toUnixTimestamp(toStartOfInterval(ts, toIntervalSecond({{step:Int64}}))) AS b, countIf(blocked = 1) AS nb, countIf(blocked = 0) AS nl FROM pyo_observability.waf_hits WHERE {W} GROUP BY b"), p()), - ch.rows(format!("SELECT ip, any(country) AS country, countIf(blocked = 1) AS nb, countIf(blocked = 0) AS nl FROM pyo_observability.waf_hits WHERE {W} GROUP BY ip ORDER BY nb + nl DESC LIMIT 50"), p()), - ch.rows(format!("SELECT country, countIf(blocked = 1) AS nb, countIf(blocked = 0) AS nl FROM pyo_observability.waf_hits WHERE {W} GROUP BY country ORDER BY nb + nl DESC LIMIT 25"), p()), - ch.rows(format!("SELECT path, countIf(blocked = 1) AS nb, countIf(blocked = 0) AS nl FROM pyo_observability.waf_hits WHERE {W} GROUP BY path ORDER BY nb + nl DESC LIMIT 25"), p()), - ) - }, - )?; - let mode = self.current_ip_mode().await; - let num = |v: &Value, k: &str| v[k].as_f64().unwrap_or(0.0); - let t = totals.first().cloned().unwrap_or_default(); - Ok(json!({ - "range": range, - "blocked": num(&t, "nb"), "logged": num(&t, "nl"), "clients": num(&t, "v"), - "rules": rules.iter().map(|r| json!({ "rule": r["rule"], "message": r["message"], "count": num(r, "c") })).collect::>(), - "hosts": hosts.iter().map(|r| json!({ "host": r["host"], "blocked": num(r, "nb"), "logged": num(r, "nl") })).collect::>(), - "series": bar_series(&series, range, |r| json!({ "blocked": r.map(|r| num(r, "nb")).unwrap_or(0.0), "logged": r.map(|r| num(r, "nl")).unwrap_or(0.0) })), - "sources": sources.iter().map(|r| json!({ "ip": mode.apply(r["ip"].as_str().unwrap_or("")), "country": r["country"], "blocked": num(r, "nb"), "logged": num(r, "nl") })).collect::>(), - "countries": countries.iter().map(|r| json!({ "country": r["country"], "blocked": num(r, "nb"), "logged": num(r, "nl") })).collect::>(), - "paths": paths.iter().map(|r| json!({ "path": r["path"], "blocked": num(r, "nb"), "logged": num(r, "nl") })).collect::>(), - // Each custom rule's matches in the range, by its number. - "custom": custom.iter().map(|r| json!({ "rule": r["rule"], "count": num(r, "c") })).collect::>(), - "recent": recent.iter().map(|r| json!({ - "at": r["at"], "serviceId": r["service_id"], "host": r["host"], "method": r["method"], "url": r["url"], - "ip": mode.apply(r["ip"].as_str().unwrap_or("")), "country": r["country"], "blocked": num(r, "blocked") > 0.0, - "rules": r["rules"], "messages": r["messages"], "severity": r["severity"], - })).collect::>(), - "ipMode": mode, - })) - } - /// An address's country, for the dashboard's lockout check. pub fn country_of(&self, ip: &str) -> String { self.locate(ip).0 } } -/// "/a?token=x&page=2" -> ("/a", "/a?token=[redacted]&page=2", ["token","page"], ["token"]). -/// The analytics page's buckets for a range at `now` (Unix seconds): how -/// many, how long each, and the window's start and end. Buckets start at -/// whole multiples of the step since the epoch, as ClickHouse's -/// `toStartOfInterval(ts, toIntervalSecond(step))` puts them, and the last -/// one holds `now`. -fn window(range: &str, now: i64) -> (i64, i64, i64, i64) { - let (points, step) = match range { - "1h" => (60, 60), - "24h" => (48, 1800), - "30d" => (30, 86400), - _ => (42, 14400), - }; - let end = (now / step + 1) * step; - (points, step, end - points * step, end) -} - -fn split_url(raw: &str) -> (String, String, Vec, Vec) { - let raw: String = raw.chars().take(2000).collect(); - let (path, query) = match raw.split_once('?') { - Some((p, q)) => (p.to_owned(), q.to_owned()), - None => (raw.clone(), String::new()), - }; - if query.is_empty() { - return (path.clone(), path, vec![], vec![]); - } - let mut keys = vec![]; - let mut redacted = vec![]; - let parts: Vec = query - .split('&') - .filter(|kv| !kv.is_empty()) - .map(|kv| { - let (k, v) = kv.split_once('=').unwrap_or((kv, "")); - let lower = k.to_ascii_lowercase(); - if !keys.contains(&k.to_owned()) { - keys.push(k.to_owned()); - } - if SENSITIVE.iter().any(|s| lower.contains(s)) { - if !redacted.contains(&k.to_owned()) { - redacted.push(k.to_owned()); - } - format!("{k}=[redacted]") - } else if v.is_empty() { - k.to_owned() - } else { - format!("{k}={v}") - } - }) - .collect(); - ( - path.clone(), - format!("{path}?{}", parts.join("&")), - keys, - redacted, - ) -} - /// A failed request-log query: the details go to the log, the user gets one /// plain sentence. fn logs_unreadable(e: impl std::fmt::Display) -> ApiError { @@ -2345,156 +1367,7 @@ fn logs_unreadable(e: impl std::fmt::Display) -> ApiError { #[cfg(test)] mod tests { - use super::{IpMode, split_url, window}; - - /// A request lands in the bucket of its own minute (hour, day), the - /// one ClickHouse's toStartOfInterval gives it, and the last bucket - /// holds now. - #[test] - fn buckets_hold_their_own_time() { - // 2026-11-15T10:03:29Z, and now a few minutes later. - let at = 1_794_737_009; - let now = at + 200; - for range in ["1h", "24h", "7d", "30d"] { - let (points, step, start, end) = window(range, now); - assert_eq!(end - start, points * step, "{range}"); - assert_eq!(start % step, 0, "{range}"); - assert!(start <= now && now < end, "{range}: now in the last bucket"); - assert!(end - step <= now, "{range}: the last bucket is now's"); - let bucket = at / step * step; - let i = (bucket - start) / step; - assert!((0..points).contains(&i), "{range}"); - assert!(bucket <= at && at < bucket + step, "{range}"); - } - let (_, step, start, _) = window("1h", now); - // 10:03:00Z, three before the last bucket (10:06, now's). - assert_eq!(at / step * step, 1_794_736_980); - assert_eq!((1_794_736_980 - start) / step, 56); - } - - /// The proxy's access log, as Vector sends it: every field analytics uses - /// comes from a field the proxy writes. - #[test] - fn access_log_fields() { - use super::AccessLine; - use serde_json::json; - let envoy = json!({ "bytes": 354, "client_ip": "203.0.113.9", "content_type": "text/html; charset=utf-8", "duration_ms": 6, "host": "shop.example.com", - "method": "GET", "path": "/x?a=1", "peer": "10.42.0.1", "referer": "https://a.example/", "start_time": "2026-11-06T12:28:32.253Z", "status": 200, - "user_agent": "Mozilla/5", "x_forwarded_for": "203.0.113.9,10.0.2.2", "x_real_ip": null, "PyoNode": "sg-1" }); - let a = AccessLine::read(&envoy); - assert_eq!( - a, - AccessLine { - host: "shop.example.com".into(), - ts_ms: Some(1793968112253), - peer: "10.42.0.1".into(), - forwarded_for: "203.0.113.9,10.0.2.2".into(), - real_ip: String::new(), - user_agent: "Mozilla/5".into(), - status: 200, - method: "GET".into(), - path: "/x?a=1".into(), - content_type: "text/html; charset=utf-8".into(), - referer: "https://a.example/".into(), - duration_ms: 6.0, - bytes: 354, - node: "sg-1".into(), - ..Default::default() - } - ); - assert_eq!(a.port_key(), None, "a website request"); - // Whatever X-Forwarded-For says, the visitor is who the proxy saw. - assert_eq!(a.visitor_ip(), "10.42.0.1"); - // Every key the proxy writes is one this reads (and the reverse). - let mut written: Vec<&str> = pyo_proto::system::ACCESS_LOG_FIELDS - .iter() - .map(|(k, _)| *k) - .collect(); - written.push(pyo_proto::system::ACCESS_LOG_CONTENT_TYPE.0); - written.sort(); - let mut read = vec![ - "host", - "start_time", - "peer", - "x_forwarded_for", - "x_real_ip", - "user_agent", - "status", - "method", - "path", - "content_type", - "referer", - "duration_ms", - "bytes", - "remote", - "local_port", - "bytes_in", - "upstream", - "upstream_host", - "flags", - "termination", - "details", - ]; - read.sort(); - assert_eq!(written, read); - } - - #[test] - fn connection_lines() { - use super::AccessLine; - use serde_json::json; - // Envoy's line for a TCP connection: no HTTP fields. - let tcp = AccessLine::read( - &json!({ "start_time": "2026-11-06T12:28:32.253Z", "peer": "10.0.2.2", "remote": "203.0.113.9", "local_port": "16379", "bytes": "120", "bytes_in": 64, - "duration_ms": 5012, "upstream": "tcproute/pyo-gateway/shop-cache-tcp-6379/rule/0", "flags": "-", "termination": null, "host": null, "method": null }), - ); - assert_eq!( - tcp.port_key(), - Some(("TCP", super::PortKey::Route("shop-cache-tcp-6379"))) - ); - assert_eq!( - ( - tcp.bytes_in, - tcp.bytes, - tcp.duration_ms, - tcp.remote.as_str(), - tcp.outcome() - ), - (64, 120, 5012.0, "203.0.113.9", "ok") - ); - // As Envoy Gateway v1.9.3 logs them: a UDP session (no route named, - // after a minute without packets), and a TCP connection the limit - // turned away (nothing upstream). - let udp = AccessLine::read( - &json!({ "bytes": 123, "bytes_in": 55, "duration_ms": 60004, "flags": "-", "host": null, "local_port": 10053, "method": null, "peer": "10.0.2.2", "remote": "10.0.2.2", "status": 0, "upstream": null, "upstream_host": "10.43.152.148:53" }), - ); - assert_eq!( - (udp.port_key(), udp.outcome()), - (Some(("UDP", super::PortKey::Listen(10053))), "ok") - ); - let limited = AccessLine::read( - &json!({ "bytes": 0, "bytes_in": 0, "duration_ms": 0, "flags": "-", "local_port": 6379, "peer": "10.0.2.2", "upstream": null, "upstream_host": null }), - ); - assert_eq!( - (limited.port_key(), limited.outcome()), - (Some(("TCP", super::PortKey::Listen(6379))), "limited") - ); - let outcome = |flags: &str, termination: &str| { - AccessLine { - upstream: "tcproute/x/y/rule/0".into(), - flags: flags.into(), - termination: termination.into(), - ..Default::default() - } - .outcome() - }; - assert_eq!( - outcome("-", "rbac_access_denied_matched_policy[deny]"), - "blocked" - ); - assert_eq!(outcome("UF,URX", ""), "unreachable"); - assert_eq!(outcome("UO", ""), "limited"); - } + use super::IpMode; #[test] fn the_traffic_proxy_is_measured_against_the_whole_cluster() { @@ -2539,48 +1412,6 @@ mod tests { ); } - #[test] - fn visitors_are_who_the_proxy_saw() { - let line = |peer: &str, remote: &str, xff: &str, real: &str| super::AccessLine { - peer: peer.into(), - remote: remote.into(), - forwarded_for: xff.into(), - real_ip: real.into(), - ..Default::default() - }; - // Straight from the internet: the peer, whatever headers say. - assert_eq!( - line("203.0.113.7", "203.0.113.7", "1.2.3.4", "").visitor_ip(), - "203.0.113.7" - ); - // A tailnet device (or anything on a private network) naming someone - // else: still itself, as the firewall sees it. - assert_eq!( - line( - "100.101.102.103", - "100.101.102.103", - "198.51.100.9", - "198.51.100.10" - ) - .visitor_ip(), - "100.101.102.103" - ); - assert_eq!( - line("10.42.0.1", "10.42.0.1", "198.51.100.9", "").visitor_ip(), - "10.42.0.1" - ); - // A PROXY protocol header's address, when the proxy read one. - assert_eq!( - line("10.0.2.2", "198.51.100.9", "6.6.6.6", "").visitor_ip(), - "198.51.100.9" - ); - // Lines without the proxy's view: the peer. - assert_eq!( - line("203.0.113.7", "", "6.6.6.6", "").visitor_ip(), - "203.0.113.7" - ); - } - #[test] fn ip_modes() { assert_eq!(IpMode::None.apply("203.0.113.7"), ""); @@ -2593,25 +1424,6 @@ mod tests { assert_eq!(IpMode::Full.apply("not-an-ip"), ""); } - #[test] - fn redacts_sensitive_values() { - let (path, url, keys, redacted) = split_url("/reset?email=a@b.c&token=xyz&page=2"); - assert_eq!(path, "/reset"); - assert_eq!(url, "/reset?email=[redacted]&token=[redacted]&page=2"); - assert_eq!(keys, vec!["email", "token", "page"]); - assert_eq!(redacted, vec!["email", "token"]); - assert_eq!( - split_url("/signup?invite=abc").1, - "/signup?invite=[redacted]" - ); - } - - #[test] - fn plain_paths() { - assert_eq!(split_url("/").1, "/"); - assert_eq!(split_url("/a?x").1, "/a?x"); - } - #[test] fn host_metrics_kept_and_dropped() { use super::host_metric_row; @@ -2779,4 +1591,4 @@ mod tests { && r["team_id"] == "team_a" && r["member"] == "pg-1")); } -} +} \ No newline at end of file diff --git a/crates/pyo-api/src/openapi.rs b/crates/pyo-api/src/openapi.rs index f1978d0d..cc137826 100644 --- a/crates/pyo-api/src/openapi.rs +++ b/crates/pyo-api/src/openapi.rs @@ -62,6 +62,10 @@ use crate::{auth::KeyAccess, error::ErrorBody, ops::Op}; crate::database_imports::retry, crate::database_imports::create_upload, crate::database_imports::upload_content, + crate::source_uploads::create, + crate::source_uploads::part, + crate::source_uploads::status, + crate::source_uploads::complete, crate::github::repos, crate::github::build_file, crate::git::repos, @@ -69,6 +73,7 @@ use crate::{auth::KeyAccess, error::ErrorBody, ops::Op}; crate::git::build_file, crate::compose::preview, crate::cloud::options, + crate::audit::list, crate::tailscale::lock, crate::platform_import::preview, crate::platform_import::apply, @@ -107,7 +112,7 @@ use crate::{auth::KeyAccess, error::ErrorBody, ops::Op}; (name = "Teams", description = "Teams, their members and invites."), (name = "Projects", description = "Projects group a team's services."), (name = "Services", description = "Create, change, scale and stop services, and read their logs and traffic."), - (name = "Deployments", description = "Deploy, roll back and cancel, and manage deploy hooks."), + (name = "Deployments", description = "Deploy, roll back and cancel, deploy an uploaded folder, manage deploy hooks, and remove or redeploy previews."), (name = "Cron jobs", description = "Commands a service runs on a schedule, and their runs."), (name = "Domains", description = "Domains and their certificates."), (name = "Volumes", description = "Persistent storage for services."), diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 05805804..c09d338e 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -106,6 +106,7 @@ pub fn routes() -> Router { .route("/compose/preview", post(crate::compose::preview)) .route("/cloud/options", get(crate::cloud::options)) .route("/tailnet/lock", get(crate::tailscale::lock)) + .route("/audit-log", get(crate::audit::list)) } /// Everything you can see @@ -191,6 +192,8 @@ async fn mail_invite( role: &str, invite: Option<&str>, ) -> ApiResult { + // Each invite may be an email: a team sends so many an hour. + op_limit(tx, crate::ratelimit::INVITES_TEAM, team_id, true).await?; let (team, slug): (String, String) = sqlx::query_as("SELECT name, slug FROM pyo.teams WHERE id = $1") .bind(team_id) @@ -274,6 +277,8 @@ pub async fn require_role( .fetch_optional(&mut **tx) .await?; let role = parse_role(&role.ok_or_else(|| ApiError::not_found("Team"))?)?; + // A team's operations together, all its members and keys. + op_limit(tx, crate::ratelimit::OPS_TEAM, team_id, false).await?; if let Some(k) = &user.key { if k.teams .as_ref() @@ -335,13 +340,14 @@ pub async fn team_of( // "pyo": Pyo registry keeps Pyo's own builds under pyo/. // "backups" to "updates": the installation's settings pages // (SETTINGS_PAGES in dash/src/lib/pyo/paths.ts). -const RESERVED_SLUGS: [&str; 23] = [ +const RESERVED_SLUGS: [&str; 24] = [ "profile", "settings", "backups", "email", "github", "observability", + "security", "updates", "oauth", "api-keys", @@ -493,6 +499,8 @@ pub async fn log_activity( .bind(&data) .execute(&mut **tx) .await?; + // What a person did goes to the audit log too, with how and from where. + crate::audit::from_activity(tx, team_id, actor, kind, title, &data["target"]).await?; // The important ones go to the team's alert channels too. crate::alerts::on_activity(tx, team_id, kind, &data["target"], &data).await; Ok(()) @@ -565,6 +573,9 @@ fn service_spec_from(service: &Value) -> Value { "currentDeploymentId", "pendingChanges", "waf", + "wafState", + "behindCdn", + "previewOf", "createdAt", "updatedAt", ] { @@ -675,7 +686,7 @@ async fn waf_changed( /// New tailnet domains (`blog..ts.net`) need Tailscale and a name /// nothing else on the tailnet has (tailscale.rs `check_domain`). Ones Pyo /// already hosts are left to its loop. -async fn tailnet_domains_ok(s: &AppState, domains: &Value) -> ApiResult<()> { +async fn tailnet_domains_ok(s: &AppState, cluster_id: &str, domains: &Value) -> ApiResult<()> { let hosts: Vec = domains .as_array() .into_iter() @@ -687,13 +698,14 @@ async fn tailnet_domains_ok(s: &AppState, domains: &Value) -> ApiResult<()> { for host in hosts { let label = host.split('.').next().unwrap_or(""); let ours: bool = sqlx::query_scalar( - "SELECT EXISTS (SELECT 1 FROM pyo.tailnet_services WHERE name = $1 AND kind = 'domain' AND retired_at IS NULL AND error IS NULL)", + "SELECT EXISTS (SELECT 1 FROM pyo.cluster_tailnet_names WHERE cluster_id = $1 AND name = $2 AND kind = 'domain' AND retired_at IS NULL AND error IS NULL)", ) + .bind(cluster_id) .bind(label) .fetch_one(&s.db) .await?; if !ours { - crate::tailscale::check_domain(s, &host).await?; + crate::tailscale::check_domain(s, cluster_id, &host).await?; } } Ok(()) @@ -706,6 +718,19 @@ async fn domains_unique( team_id: &str, service_id: &str, spec: &Value, +) -> ApiResult<()> { + // Other teams' services, and a takeover of a claim they can't prove. + let lifted = crate::rls::lift(tx).await?; + let out = Box::pin(domains_unique_across_teams(tx, team_id, service_id, spec)).await; + lifted.lower(tx).await?; + out +} + +async fn domains_unique_across_teams( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + service_id: &str, + spec: &Value, ) -> ApiResult<()> { let hosts: Vec = spec["domains"] .as_array() @@ -717,6 +742,22 @@ async fn domains_unique( if hosts.is_empty() { return Ok(()); } + // Twice on the service itself. + if let Some(host) = hosts.iter().enumerate().find_map(|(i, h)| hosts[..i].contains(h).then_some(h)) { + return Err(ApiError::conflict(format!("{host} is already used."))); + } + // Teams that don't trust each other (Pyo Cloud): a new hostname needs + // proof of owning it, and one held without proof is taken over. + if crate::verify_domains() { + let current: Vec = sqlx::query_scalar( + "SELECT lower(d->>'hostname') FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d WHERE a.id = $1", + ) + .bind(service_id) + .fetch_all(&mut **tx) + .await?; + let new: Vec = hosts.iter().filter(|h| !current.contains(h)).cloned().collect(); + crate::domainproof::check_claims(tx, team_id, service_id, &new).await?; + } let taken: Option<(String, String, String)> = sqlx::query_as( "SELECT lower(d->>'hostname'), a.team_id, a.name FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d WHERE a.id <> $1 AND NOT a.deleting AND lower(d->>'hostname') = ANY($2) LIMIT 1", @@ -748,25 +789,32 @@ async fn reach( cluster_id: &str, what: &str, ) -> ApiResult<(String, String, Option<(String, String)>)> { - if crate::tailscale::settings(&s.db).await?.is_none() { - return Err(ApiError::bad_request(crate::tailscale::NEEDED)); - } + let keys = crate::tailscale::key_cluster(&s.db, None).await?; let api = crate::web::tailnet_api_url().ok_or_else(|| { ApiError::conflict("Pyo's server isn't on your tailnet yet. Try again in a minute.") })?; - let key = crate::tailscale::join_key(s, what, "this server").await?; - let door = crate::join::friendly(&deploy::registry_push()); - let registry = if door.is_empty() { - None - } else { - Some((door, registry_token(tx, s, cluster_id).await?)) - }; + let key = crate::tailscale::join_key(s, &keys, what, "this server").await?; + let registry = registry_door(tx, s, cluster_id).await?; Ok((crate::join::friendly(&api), key, registry)) } +/// Pyo's registry door for Pyo-built images, with the cluster's pull +/// token, when Pyo has one on the tailnet. +async fn registry_door( + tx: &mut Transaction<'_, Postgres>, + s: &AppState, + cluster_id: &str, +) -> ApiResult> { + let door = crate::join::friendly(&deploy::registry_push()); + if door.is_empty() || crate::web::tailnet_api_url().is_none() { + return Ok(None); + } + Ok(Some((door, registry_token(tx, s, cluster_id).await?))) +} + /// The cluster's pull token at Pyo's registry door (its servers' /// registries.yaml): made on first use, then the same for every server. -async fn registry_token( +pub(crate) async fn registry_token( tx: &mut Transaction<'_, Postgres>, s: &AppState, cluster_id: &str, @@ -777,14 +825,21 @@ async fn registry_token( .fetch_optional(&mut **tx) .await? .flatten(); - if let Some(t) = sealed.and_then(|x| s.sealer.open(&x).ok()) { + let v = crate::vault::get(); + if let Some(x) = sealed + && let Ok(t) = v.open_credential(&s.sealer, &x).await + { return Ok(t); } + let team_id: String = sqlx::query_scalar("SELECT team_id FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_one(&mut **tx) + .await?; let token = secret_token(); sqlx::query("UPDATE pyo.clusters SET registry_token_hash = $2, registry_token_sealed = $3 WHERE id = $1") .bind(cluster_id) .bind(sha256_hex(&token)) - .bind(s.sealer.seal(&token)?) + .bind(v.seal_credential(&team_id, &token).await?) .execute(&mut **tx) .await?; Ok(token) @@ -802,6 +857,19 @@ async fn connect_command( token: &str, public: Option<&str>, ) -> ApiResult<(String, bool)> { + // Agents over mTLS (Pyo Cloud): machines install from Pyo's public + // address (PYO_PUBLIC_API_URL, else the dashboard's), never a tailnet. + let configured = crate::agent_tls::endpoint().and_then(|_| { + std::env::var("PYO_PUBLIC_API_URL") + .ok() + .filter(|u| !u.trim().is_empty()) + }); + let public = configured.as_deref().or(public); + if crate::agent_tls::endpoint().is_some() && public.is_none() { + return Err(ApiError::bad_request( + "Connect from the dashboard's address: Pyo has no public address set.", + )); + } if let Some(url) = public { let url = url.trim().trim_end_matches('/'); if !(url.starts_with("https://") || url.starts_with("http://")) @@ -855,6 +923,9 @@ struct JoinParts { tailscale_key: String, registry: Option<(String, String)>, ttl: u64, + /// The control-plane server isn't on the tailnet yet: its name, and a + /// key to put it there first. + tailnet_first: Option<(String, String)>, } impl JoinParts { @@ -892,8 +963,11 @@ async fn join_command( // fetches the script off the tailnet. let base = crate::join::scripts_url_before_tailnet(); let command = crate::join::command(&base, &p.join(server_name, builder, true)); + let first = p.tailnet_first.as_ref().map(|(server, key)| { + json!({ "server": server, "command": crate::join::tailnet_only_command(&base, key) }) + }); Ok( - json!({ "ok": true, "command": command, "scriptUrl": format!("{base}/join.sh"), "expiresAt": now_ms() + p.ttl as i64 * 1000, "tailscale": true }), + json!({ "ok": true, "command": command, "scriptUrl": format!("{base}/join.sh"), "expiresAt": now_ms() + p.ttl as i64 * 1000, "tailscale": true, "tailnetFirst": first }), ) } @@ -927,18 +1001,43 @@ async fn join_parts( } // The control plane's address, which new servers join through: its // Tailscale address when it has one. - let server_ip: Option = sqlx::query_scalar( - "SELECT coalesce(nullif(report->>'tailnetIp', ''), report->>'internalIP') FROM pyo.servers WHERE cluster_id = $1 AND report->'roles' ? 'control-plane' + let control: Option<(String, Option, bool)> = sqlx::query_as( + "SELECT name, coalesce(nullif(report->>'tailnetIp', ''), report->>'internalIP'), coalesce(report->>'tailnetIp', '') <> '' + FROM pyo.servers WHERE cluster_id = $1 AND report->'roles' ? 'control-plane' ORDER BY (report->>'status' = 'ready') DESC LIMIT 1", ) .bind(cluster_id) .fetch_optional(&mut **tx) .await?; - let server_ip = server_ip.filter(|ip| !ip.is_empty()).ok_or_else(|| { - ApiError::conflict("The cluster has no control-plane server reported yet.") - })?; - let (_, ts_key, registry) = - reach(tx, s, cluster_id, &format!("Pyo: join {server_name}")).await?; + let (control, server_ip, on_tailnet) = control + .and_then(|(n, ip, t)| Some((n, ip.filter(|ip| !ip.is_empty())?, t))) + .ok_or_else(|| { + ApiError::conflict("The cluster has no control-plane server reported yet.") + })?; + // The cluster's own tailnet: its agent makes the key. + let keys = crate::tailscale::key_cluster(&s.db, Some(cluster_id)).await?; + let ts_key = crate::tailscale::join_key( + s, + &keys, + &format!("Pyo: join {server_name}"), + "this server", + ) + .await?; + let registry = registry_door(tx, s, cluster_id).await?; + // A cluster connected without Tailscale (Pyo Cloud): its control-plane + // server joins the tailnet first, so new servers can reach it there. + let tailnet_first = if on_tailnet { + None + } else { + let key = crate::tailscale::join_key( + s, + &keys, + &format!("Pyo: {control} onto the tailnet"), + "this server", + ) + .await?; + Some((control, key)) + }; let alnum = |n: usize| { crate::ids::secret_token() .chars() @@ -967,6 +1066,7 @@ async fn join_parts( tailscale_key: ts_key, registry, ttl, + tailnet_first, }) } @@ -1378,6 +1478,7 @@ pub(crate) const RESERVED_PROJECT_SLUGS: &[&str] = &[ "activity", "analytics", "api-keys", + "audit-log", "services", "backups", "builders", @@ -1836,9 +1937,23 @@ pub(crate) enum Op { /// The team's dashboard preferences, saved as given. #[schema(value_type = Option)] preferences: Option, + /// On a hosted Pyo: "auto" updates the team's agents when Pyo has a new version, "manual" leaves it to you. + #[serde(default)] + agent_updates: Option, + /// Keep the team's analytics 3, 6 or 12 months, at most as long as the installation. 0 keeps them as long as the installation does. + #[serde(default)] + analytics_months: Option, }, /// Delete a team and everything in it. Owners only. DeleteTeam { id: String }, + /// A team's security: whether its members must use two-factor authentication, and what its audit log keeps of addresses ("full", "anonymized" or "none"). Owners and admins, from the dashboard. + SetTeamSecurity { + team_id: String, + #[serde(default)] + require_two_factor: Option, + #[serde(default)] + audit_ips: Option, + }, /// Invite someone to a team by email, as owner, admin, developer or viewer. InviteMember { /// A new id you choose: `mem_` then 4 to 40 lowercase letters, digits, dashes or underscores. @@ -2054,6 +2169,17 @@ pub(crate) enum Op { SaveObservabilitySettings { ip_mode: crate::observability::IpMode, }, + /// How long this installation keeps observability data: analytics 3, 6, 12 or 24 months, server, service and database metrics 7 to 90 days, build and deploy logs 30 to 365 days. A team can keep its analytics shorter (`updateTeam`'s `analyticsMonths`). Raw request logs are each team's own setting. + SaveRetentionSettings { + analytics_months: u8, + metrics_days: u16, + build_log_days: u16, + }, + /// The installation's security: whether everyone must use two-factor authentication, and how long the audit log is kept (90, 180, 365 or 730 days). Only the installation's admin can do this. Pyo Cloud keeps the audit log a year. + SaveSecuritySettings { + require_two_factor: bool, + audit_days: u16, + }, /// 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). @@ -2134,7 +2260,7 @@ pub(crate) enum Op { /// server but build-only ones (ports 80 and 443, and public TCP and UDP /// ports through it). Off: services are only reachable inside the cluster. SetClusterPublicTraffic { cluster_id: String, on: bool }, - /// Where the cluster's free domains (`..nip.io`) point: "public" (its public IP, for everyone) or "tailscale" (its Tailscale IP, only from the tailnet). With "tailscale", services are reachable from your tailnet on ports 80 and 443 whether or not the cluster takes public traffic. Free domains on it move to the new address in place. By default it's public when the cluster takes public traffic and a server has its public IP itself (on a network card or as its ExternalIP), a load balancer gives it one, or its cloud maps one to it and Let's Encrypt reached it there. Behind NAT, it's Tailscale. + /// Where the cluster's free domains (`..nip.io`) point: "public" (its public IP, for everyone) or "tailscale" (its Tailscale IP, only from the tailnet). With "tailscale", services are reachable from your tailnet on ports 80 and 443 whether or not the cluster takes public traffic. Free domains on it move to the new address in place, except ones on the public IP, which stay there while the cluster has one. By default it's public when the cluster takes public traffic and a server has its public IP itself (on a network card or as its ExternalIP), a load balancer gives it one, or its cloud maps one to it and Let's Encrypt reached it there. Behind NAT, it's Tailscale. SetClusterFreeDomainAddress { cluster_id: String, address: String }, /// Add an access rule to the end of a service's firewall. Allow and block rules are checked in order, and the first match decides. With no match, the client gets in. Rate limit rules then apply to websites, and each matching one counts the request, per client address and per server. AddFirewallRule { @@ -2319,6 +2445,10 @@ pub(crate) enum Op { #[serde(default)] delete_volumes: bool, }, + /// Remove a pull request's preview of a service now. The next push to the pull request brings it back. + DeletePreview { id: String }, + /// Deploy a pull request's preview again from its head (a failed one tries again, a removed one comes back). + RedeployPreview { id: String }, /// Isolate a project's network: only its own services and the web server reach them. SetProjectIsolation { id: String, isolate: bool }, /// Give the team a new data key and seal its stored secrets again with it. @@ -2333,6 +2463,7 @@ pub(crate) enum Op { /// Its `healthCheck`, which says when a replica is ready: `type` ("http" for a request to `path` on `port` answered with 2xx or 3xx, "tcp" for `port` accepting connections, "exec" to run `command`, or "none" so deploys don't wait for it), `initialDelaySeconds` and `periodSeconds`. With `auto` ("default" or "static") Pyo picks it from what each build finds: a static site or single-page app gets an HTTP check of `/`. A check without `auto` is kept as it is. /// A Git `source` has `buildArgs` (`[{"key": …, "value": …}]`), used by its next build: Dockerfile build arguments, or Railpack settings such as `RAILPACK_BUILD_CMD`. They can end up in the image, so no secrets. /// Its `serveAs`, for a build Pyo detects as a static site: "static" (the default) serves the build's output as static files from the cluster's shared static server, "service" runs it as a service of its own. Takes effect with the next deploy. + /// Its `placement`, where it runs: `{"servers": [...], "tags": [...]}` runs it only on the servers named and on every server with one of the tags, tagged now or later. Absent or null: any server of its cluster. A service with a volume keeps its volume's server, and one with a GPU needs a GPU server. A change goes live without a deploy. The older `serverTags` is read as its tags. #[schema(value_type = Object)] service: Value, /// A new id you choose for its first deployment: `dpl_` then 4 to 40 lowercase letters, digits, dashes or underscores. @@ -2348,6 +2479,9 @@ pub(crate) enum Op { /// 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, + /// A folder uploaded with `createSourceUpload`, for a service whose `source` is `{"type": "upload"}` (built from a folder with `pyo deploy`): its first deployment builds it. + #[serde(default)] + upload_id: Option, }, /// Save a service's configuration. With `deploymentId`, roll it out too. Changes to its `domains` go live without a deploy once it has been deployed. #[serde(rename = "saveService")] @@ -2358,6 +2492,7 @@ pub(crate) enum Op { /// Its `healthCheck`, which says when a replica is ready: `type` ("http" for a request to `path` on `port` answered with 2xx or 3xx, "tcp" for `port` accepting connections, "exec" to run `command`, or "none" so deploys don't wait for it), `initialDelaySeconds` and `periodSeconds`. With `auto` ("default" or "static") Pyo picks it from what each build finds: a static site or single-page app gets an HTTP check of `/`. A check without `auto` is kept as it is. /// A Git `source` has `buildArgs` (`[{"key": …, "value": …}]`), used by its next build: Dockerfile build arguments, or Railpack settings such as `RAILPACK_BUILD_CMD`. They can end up in the image, so no secrets. /// Its `serveAs`, for a build Pyo detects as a static site: "static" (the default) serves the build's output as static files from the cluster's shared static server, "service" runs it as a service of its own. Takes effect with the next deploy. + /// Its `placement`, where it runs: `{"servers": [...], "tags": [...]}` runs it only on the servers named and on every server with one of the tags, tagged now or later. Absent or null: any server of its cluster. A service with a volume keeps its volume's server, and one with a GPU needs a GPU server. A change goes live without a deploy. The older `serverTags` is read as its tags. #[schema(value_type = Object)] service: Value, deployment_id: Option, @@ -2385,6 +2520,9 @@ pub(crate) enum Op { rollback_of: Option, /// The failed deployment to try again. retry_of: Option, + /// A folder uploaded with `createSourceUpload` to build and deploy, instead of the service's source. For services built from Git or from a folder. + #[serde(default)] + upload_id: Option, }, /// Cancel a deployment that hasn't finished. Cancel { deployment_id: String }, @@ -2489,6 +2627,8 @@ pub(crate) enum Op { #[serde(default)] public_api_url: Option, }, + /// Set the domain previews on a cluster use (`-pr-.`, a wildcard record pointing at the cluster), or null for nip.io. Admins only. + SetClusterPreviewDomain { id: String, domain: Option }, /// Rename a cluster or change its description, location or tags. UpdateCluster { id: String, @@ -2513,6 +2653,8 @@ pub(crate) enum Op { #[serde(default)] public_api_url: Option, }, + /// On a hosted Pyo: update a cluster's agent to Pyo's version now. + UpdateClusterAgent { id: String }, /// Discard a cluster that was added but never connected. DiscardClusterDraft { id: String }, /// Remove a cluster from Pyo. Its servers keep running. @@ -2616,29 +2758,41 @@ pub(crate) enum Op { RemoveBuilder { id: String }, /// A new token for a builder. The old one stops working. RotateBuilderToken { id: String }, - /// Set up Tailscale for this installation (admins only): an OAuth client with the scopes Devices › Core and Auth Keys (both with tag:pyo) and Services. Servers and clusters join your tailnet with it, and Pyo gets names on it. Pyo checks it first and says what it can do. A missing secret keeps the saved one. + /// Set up Tailscale on a cluster (the team's admins) with an OAuth client with the scopes Devices › Core and Auth Keys (both with tag:pyo) and Services. The cluster's agent checks it and keeps it. Pyo never stores it. Servers join the cluster's tailnet with it, and Pyo gets names on it. Without `clusterId`, the cluster Pyo runs on. SaveTailscale { + #[serde(default)] + cluster_id: Option, client_id: String, secret: Option, }, - /// See what setting up Tailscale with an API access token would change (admins only). Nothing changes yet. + /// See what setting up Tailscale on a cluster with an API access token would change (the team's admins). Nothing changes yet. Without `clusterId`, the cluster Pyo runs on. PlanTailscaleSetup { - /// An API access token from the Tailscale console's Keys page. Used for this request only and never stored. + #[serde(default)] + cluster_id: Option, + /// An API access token from the Tailscale console's Keys page. Passed to the cluster's agent and never stored. #[schema(value_type = String)] - token: crate::tailscale_setup::Token, + token: crate::tailscale::Token, }, - /// Set up Tailscale with an API access token (admins only): MagicDNS, HTTPS certificates, tag:pyo in the tailnet policy, and an OAuth client of Pyo's own. Pyo deletes the token when it's done. + /// Set up Tailscale on a cluster with an API access token (the team's admins): MagicDNS, HTTPS certificates, tag:pyo in the tailnet policy, and an OAuth client the cluster's agent keeps. The agent deletes the token when it's done. Without `clusterId`, the cluster Pyo runs on. SetUpTailscale { - /// An API access token from the Tailscale console's Keys page. Used for this request only and never stored. + #[serde(default)] + cluster_id: Option, + /// An API access token from the Tailscale console's Keys page. Passed to the cluster's agent and never stored. #[schema(value_type = String)] - token: crate::tailscale_setup::Token, + token: crate::tailscale::Token, /// The `version` planTailscaleSetup returned. If the tailnet policy changed since, nothing changes and `reviewAgain` comes back. version: String, }, - /// Check the saved Tailscale OAuth client again, scope by scope. - TestTailscale {}, - /// Forget the Tailscale OAuth client. Pyo's names on your tailnet are deleted. Servers stay on it. - RemoveTailscale {}, + /// Check a cluster's Tailscale OAuth client again, scope by scope. Without `clusterId`, the cluster Pyo runs on. + TestTailscale { + #[serde(default)] + cluster_id: Option, + }, + /// Forget a cluster's Tailscale OAuth client. Pyo's names on its tailnet are deleted. Servers stay on it. Without `clusterId`, the cluster Pyo runs on. + RemoveTailscale { + #[serde(default)] + cluster_id: Option, + }, /// Rename Pyo's own name on your tailnet: `kind` "dashboard" (pyo..ts.net), "registry" or "sandboxes" (sandboxes' web pages, like the desktop). RenameTailscaleName { kind: String, name: String }, /// Connect a team to Hetzner Cloud (team admins): a project API token with Read & Write, from the project's Security page. Pyo checks it by listing the locations, and keeps it encrypted. Servers join over your tailnet, so Tailscale comes first. @@ -2867,17 +3021,78 @@ fn bucket_refused(e: anyhow::Error) -> ApiError { )) } +tokio::task_local! { + /// What an operation counts against rate limits once its transaction + /// is over (ratelimit.rs), so the count takes no other connection + /// while it's open: (limit, key, counted only when it succeeded). + static COUNT_AFTER: std::sync::Mutex>; +} + +/// Refuses with 429 when `key` used up `limit`, and counts this operation +/// against it once it's done. Outside an operation it does nothing. +async fn op_limit( + tx: &mut sqlx::PgConnection, + limit: crate::ratelimit::Limit, + key: &str, + only_success: bool, +) -> ApiResult<()> { + let Ok(()) = COUNT_AFTER.try_with(|_| ()) else { + return Ok(()); + }; + if let Some(retry) = crate::ratelimit::used_up(tx, &limit, key).await? { + return Err(crate::ratelimit::too_many_for(&limit, retry)); + } + let _ = COUNT_AFTER.try_with(|c| { + let mut c = c.lock().unwrap_or_else(|e| e.into_inner()); + if !c.iter().any(|(l, k, _)| l.scope == limit.scope && k == key) { + c.push((limit, key.to_owned(), only_success)); + } + }); + Ok(()) +} + async fn run_op(s: &AppState, user: &User, op: Op) -> ApiResult { key_allows(user, &op)?; + crate::ratelimit::take(&s.db, &[(crate::ratelimit::OPS_USER, &user.id)]).await?; + let counts = std::sync::Mutex::new(vec![]); + let (out, counts) = COUNT_AFTER + .scope(counts, async { + let out = run_op_counted(s, user, op).await; + let counts = COUNT_AFTER + .try_with(|c| std::mem::take(&mut *c.lock().unwrap_or_else(|e| e.into_inner()))) + .unwrap_or_default(); + (out, counts) + }) + .await; + for (limit, key, only_success) in counts { + if out.is_ok() || !only_success { + crate::ratelimit::take_after(&s.db, &limit, &key).await; + } + } + out +} + +async fn run_op_counted(s: &AppState, user: &User, op: Op) -> ApiResult { let s = s.clone(); // Long calls to outside services hold no transaction open. if matches!( op, - Op::PlanTailscaleSetup { .. } | Op::SetUpTailscale { .. } | Op::TestAlertChannel { .. } + Op::PlanTailscaleSetup { .. } + | Op::SetUpTailscale { .. } + | Op::SaveTailscale { .. } + | Op::TestTailscale { .. } + | Op::RemoveTailscale { .. } + | Op::RenameTailscaleName { .. } + | Op::TestAlertChannel { .. } ) { return outside_tx(&s, user, op).await; } let mut tx = s.db.begin().await?; + // Row security: the user's teams only (rls.rs). The installation's own + // settings are its admin's, across every team. + if !(user.is_admin && installation_wide(&op)) { + crate::rls::scope(&mut tx, user).await?; + } // Clusters whose agent should look for new work after this commits. let mut wake: Vec = vec![]; let out = apply(&s, &mut tx, user, op, &mut wake).await?; @@ -2890,6 +3105,72 @@ async fn run_op(s: &AppState, user: &User, op: Op) -> ApiResult { Ok(out) } +/// Operations on the installation itself rather than on a team: they go +/// across every team (an update reaches every cluster), so they run outside +/// row security, for its admin only. +fn installation_wide(op: &Op) -> bool { + matches!( + op, + Op::SaveBackupSettings { .. } + | Op::RemoveBackupSettings {} + | Op::RunBackup {} + | Op::SaveEmailSettings { .. } + | Op::RemoveEmailSettings {} + | Op::SendTestEmail {} + | Op::SaveObservabilitySettings { .. } + | Op::SaveRetentionSettings { .. } + | Op::SaveSecuritySettings { .. } + | Op::SaveUpdateSettings { .. } + | Op::SetSandboxLimits { .. } + | Op::CheckForUpdates {} + | Op::StartUpdate { .. } + | Op::GithubManifest { .. } + | Op::RemoveGithubApp {} + | Op::SetPublicDashboard { .. } + ) +} + +/// The cluster a Tailscale op is for, and that the user may set it up +/// there: the team's admins. Without one, the cluster Pyo runs on, for the +/// installation's admins. +async fn tailscale_cluster(s: &AppState, user: &User, cluster_id: Option) -> ApiResult { + match cluster_id { + Some(c) => { + crate::tailscale::require_cluster_admin(s, user, &c).await?; + Ok(c) + } + None => { + require_admin(user)?; + crate::tailscale::host_cluster(&s.db) + .await? + .ok_or_else(|| ApiError::bad_request("Pick the cluster to set Tailscale up on.")) + } + } +} + +/// Logs a Tailscale change on the cluster's team. +async fn log_tailscale(s: &AppState, user: &User, cluster_id: &str, title: &str) -> ApiResult<()> { + let mut tx = s.db.begin().await?; + let (team, name): (String, String) = + sqlx::query_as("SELECT team_id, name FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_one(&mut *tx) + .await?; + log_activity( + &mut tx, + &team, + &user.name, + "settings.changed", + "info", + &format!("{title} on {name}"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({}), + ) + .await?; + tx.commit().await?; + Ok(()) +} + /// Operations made of many calls to an outside API run here, before any /// transaction: they read through the pool, make their calls, and write /// what happened in a short transaction of their own. Every other op goes @@ -2898,31 +3179,70 @@ async fn outside_tx(s: &AppState, user: &User, op: Op) -> ApiResult { match op { Op::TestAlertChannel { id } => { let mut tx = s.db.begin().await?; + crate::rls::scope(&mut tx, user).await?; let team_id = team_of(&mut tx, "alert_channels", &id).await?; require_role(&mut tx, user, &team_id, Role::Admin).await?; tx.commit().await?; crate::alerts::test(s, &id).await?; Ok(json!({ "ok": true })) } - Op::PlanTailscaleSetup { token } => { - require_admin(user)?; - crate::tailscale_setup::plan(s, token).await + Op::PlanTailscaleSetup { cluster_id, token } => { + let c = tailscale_cluster(s, user, cluster_id).await?; + crate::tailscale::plan(s, &c, token.into_inner()).await } - Op::SetUpTailscale { token, version } => { - require_admin(user)?; - let out = crate::tailscale_setup::apply(s, token, &version).await?; - if !out.changed.is_empty() { - let mut tx = s.db.begin().await?; - log_setting( - &mut tx, - user, - "tailscale", - "Set up Tailscale with an access token", - ) - .await?; - tx.commit().await?; + Op::SetUpTailscale { + cluster_id, + token, + version, + } => { + let c = tailscale_cluster(s, user, cluster_id).await?; + let out = crate::tailscale::set_up(s, &c, token.into_inner(), &version).await?; + if out["changed"].as_array().is_some_and(|a| !a.is_empty()) { + log_tailscale(s, user, &c, "Set up Tailscale with an access token").await?; } - Ok(serde_json::to_value(out).map_err(anyhow::Error::from)?) + Ok(out) + } + Op::SaveTailscale { + cluster_id, + client_id, + secret, + } => { + let c = tailscale_cluster(s, user, cluster_id).await?; + let out = crate::tailscale::save_client(s, &c, &client_id, secret.as_deref()).await?; + log_tailscale(s, user, &c, "Connected Tailscale").await?; + Ok(out) + } + Op::TestTailscale { cluster_id } => { + let c = tailscale_cluster(s, user, cluster_id).await?; + crate::tailscale::test_saved(s, &c).await + } + Op::RemoveTailscale { cluster_id } => { + let c = tailscale_cluster(s, user, cluster_id).await?; + crate::tailscale::remove(s, &c).await?; + log_tailscale(s, user, &c, "Removed Tailscale").await?; + Ok(json!({ "ok": true })) + } + Op::RenameTailscaleName { kind, name } => { + require_admin(user)?; + crate::tailscale::rename(s, &kind, &name).await?; + let mut tx = s.db.begin().await?; + let what = match kind.as_str() { + "registry" => "registry", + "sandboxes" => "sandboxes' pages", + _ => "dashboard", + }; + log_setting( + &mut tx, + user, + "tailscale", + &format!( + "Renamed the {what} on the tailnet to {}", + name.trim().to_ascii_lowercase() + ), + ) + .await?; + tx.commit().await?; + Ok(json!({ "ok": true })) } _ => Err(anyhow::anyhow!("this operation runs in a transaction").into()), } @@ -2944,6 +3264,9 @@ pub(crate) fn key_access_for(op: &Op) -> Option { | Op::RemoveBackupSettings {} | Op::RunBackup {} | Op::SaveObservabilitySettings { .. } + | Op::SaveRetentionSettings { .. } + | Op::SaveSecuritySettings { .. } + | Op::SetTeamSecurity { .. } | Op::SaveUpdateSettings { .. } | Op::SetSandboxLimits { .. } | Op::CheckForUpdates {} @@ -2955,8 +3278,8 @@ pub(crate) fn key_access_for(op: &Op) -> Option { | Op::SaveTailscale { .. } | Op::PlanTailscaleSetup { .. } | Op::SetUpTailscale { .. } - | Op::TestTailscale {} - | Op::RemoveTailscale {} + | Op::TestTailscale { .. } + | Op::RemoveTailscale { .. } | Op::RenameTailscaleName { .. } | Op::SetPublicDashboard { .. } | Op::CreateOriginPullCertificate { .. } @@ -2975,6 +3298,7 @@ pub(crate) fn key_access_for(op: &Op) -> Option { op, Op::Deploy { .. } | Op::Cancel { .. } + | Op::RedeployPreview { .. } | Op::RestartService { .. } | Op::StopService { .. } | Op::SetAutoscale { .. } @@ -2993,7 +3317,10 @@ pub(crate) fn key_access_for(op: &Op) -> Option { /// be placed here. pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { match op { - Op::CreateTeam { .. } | Op::UpdateTeam { .. } | Op::DeleteTeam { .. } => ("Teams", "team"), + Op::CreateTeam { .. } + | Op::UpdateTeam { .. } + | Op::DeleteTeam { .. } + | Op::SetTeamSecurity { .. } => ("Teams", "team"), Op::InviteMember { .. } | Op::ResendInvite { .. } | Op::UpdateMemberRole { .. } @@ -3014,6 +3341,7 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::SetAutoscale { .. } | Op::RevealSecret { .. } => ("Services", "svc"), Op::Deploy { .. } | Op::Cancel { .. } => ("Deployments", "dpl"), + Op::DeletePreview { .. } | Op::RedeployPreview { .. } => ("Deployments", "pvw"), Op::CreateDeployHook { .. } | Op::RevealDeployHook { .. } | Op::RemoveDeployHook { .. } => { ("Deployments", "hook") } @@ -3054,7 +3382,9 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::RevealBackupPassword { .. } => ("Backups", "team"), Op::CreateCluster { .. } | Op::UpdateCluster { .. } + | Op::SetClusterPreviewDomain { .. } | Op::RotateAgentToken { .. } + | Op::UpdateClusterAgent { .. } | Op::DiscardClusterDraft { .. } | Op::RemoveCluster { .. } | Op::SetClusterTrafficMode { .. } @@ -3099,8 +3429,8 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { Op::SaveTailscale { .. } | Op::PlanTailscaleSetup { .. } | Op::SetUpTailscale { .. } - | Op::TestTailscale {} - | Op::RemoveTailscale {} + | Op::TestTailscale { .. } + | Op::RemoveTailscale { .. } | Op::RenameTailscaleName { .. } => ("Integrations", ""), Op::SetPublicDashboard { .. } => ("Settings", ""), Op::ConnectCloudflare { .. } @@ -3121,6 +3451,8 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::RemoveEmailSettings {} | Op::SendTestEmail {} | Op::SaveObservabilitySettings { .. } + | Op::SaveRetentionSettings { .. } + | Op::SaveSecuritySettings { .. } | Op::SaveUpdateSettings { .. } | Op::SetSandboxLimits { .. } | Op::CheckForUpdates {} @@ -3191,6 +3523,8 @@ async fn apply( .bind(&user.email) .execute(&mut **tx) .await?; + // The new team is one of theirs now. + crate::rls::scope(tx, user).await?; log_activity( tx, &id, @@ -3210,8 +3544,29 @@ async fn apply( description, default_cluster_id, preferences, + agent_updates, + analytics_months, } => { require_role(tx, user, &id, Role::Admin).await?; + if let Some(m) = analytics_months { + let installation = crate::retention::load(&s.db).await?; + crate::retention::check_team_months(m, &installation).map_err(ApiError::bad_request)?; + sqlx::query("UPDATE pyo.teams SET analytics_months = $2 WHERE id = $1") + .bind(&id) + .bind((m != 0).then_some(i16::from(m))) + .execute(&mut **tx) + .await?; + } + if let Some(m) = agent_updates { + if !crate::updates::AGENT_UPDATE_MODES.contains(&m.as_str()) { + return Err(ApiError::bad_request("Agent updates are \"auto\" or \"manual\".")); + } + sqlx::query("UPDATE pyo.teams SET agent_updates = $2 WHERE id = $1") + .bind(&id) + .bind(&m) + .execute(&mut **tx) + .await?; + } let mut slug = None; if let Some(n) = name { let n = require_text(&n, "Team name", 60)?; @@ -3222,6 +3577,8 @@ async fn apply( .bind(&sl) .execute(&mut **tx) .await?; + // Its images' path changed: so did its clusters' doors'. + wake.extend(crate::registrydoor::sync_clusters(tx, &id, None).await?); slug = Some(sl); } if let Some(d) = description { @@ -3448,12 +3805,20 @@ async fn apply( "Set PYO_SECRET_KEY on the API first: backups are encrypted with it.", )); } - let saved = crate::teambackup::settings(&s.db, &team_id).await?; + let saved = crate::teambackup::settings(tx, &team_id).await?; let secret = secret_key .filter(|k| !k.trim().is_empty()) .map(|k| k.trim().to_owned()); + let destination = destination.unwrap_or_else(|| "local".into()); + if destination == "local" && !crate::teambackup::store_on_pyo() { + return Err(ApiError::bad_request(if crate::hosted() { + "Pyo Cloud doesn't keep teams' backups. Add an S3 bucket." + } else { + "This installation has no backup store. Add an S3 bucket." + })); + } let base = crate::backup::Settings { - destination: destination.unwrap_or_else(|| "local".into()), + destination, enabled, schedule, hour, @@ -3464,7 +3829,7 @@ async fn apply( prefix: prefix.trim().to_owned(), access_key: access_key.trim().to_owned(), secret_sealed: match &secret { - Some(k) => Some(s.sealer.seal(k)?), + Some(k) => Some(crate::vault::get().seal_credential(&team_id, k).await?), None => saved.as_ref().and_then(|x| x.base.secret_sealed.clone()), }, }; @@ -3481,6 +3846,14 @@ async fn apply( ) })?; } else { + // The key kept from before is the team's, sealed with its data key. + let secret = match (&secret, &base.secret_sealed) { + (Some(k), _) => Some(k.clone()), + (None, Some(x)) => { + Some(crate::vault::get().open_credential(&s.sealer, x).await?) + } + (None, None) => None, + }; crate::backup::probe(s, &base, secret.as_deref(), crate::outbound::Reach::team()) .await .map_err(bucket_refused)?; @@ -3609,7 +3982,7 @@ async fn apply( } Op::RevealBackupPassword { team_id } => { require_role(tx, user, &team_id, Role::Admin).await?; - let cfg = crate::teambackup::settings(&s.db, &team_id) + let cfg = crate::teambackup::settings(tx, &team_id) .await? .ok_or_else(|| ApiError::not_found("Backup settings"))?; let password = crate::vault::get().open(&cfg.repo_password_sealed).await?; @@ -3799,6 +4172,66 @@ async fn apply( } Ok(ok) } + Op::SaveRetentionSettings { + analytics_months, + metrics_days, + build_log_days, + } => { + require_admin(user)?; + let r = crate::retention::Retention { + analytics_months, + metrics_days, + build_log_days, + }; + if crate::retention::save(tx, &r).await? { + log_setting(tx, user, "observability", "Changed how long observability data is kept") + .await?; + } + // ClickHouse's tables follow (and again at every start). + let obs = s.observability.clone(); + tokio::spawn(async move { obs.apply_retention(r).await }); + Ok(ok) + } + Op::SaveSecuritySettings { + require_two_factor, + audit_days, + } => { + require_admin(user)?; + if crate::hosted() { + return Err(ApiError::bad_request( + "Pyo Cloud keeps the audit log a year, and its staff always use two-factor.", + )); + } + let before = crate::audit::settings(&mut **tx).await?; + let after = crate::audit::SecuritySettings { + require_two_factor, + audit_days, + }; + if require_two_factor && !before.require_two_factor && !crate::twofactor::enabled(&mut **tx, &user.id).await? { + return Err(ApiError::bad_request( + "Turn on two-factor for your own account first, in your profile.", + )); + } + crate::audit::save_settings(tx, &after).await?; + if before.require_two_factor != require_two_factor { + log_setting( + tx, + user, + "security", + if require_two_factor { + "Required two-factor authentication for everyone" + } else { + "Stopped requiring two-factor authentication for everyone" + }, + ) + .await?; + } + if before.audit_days != audit_days { + log_setting(tx, user, "security", &format!("Keeps the audit log {audit_days} days")) + .await?; + } + Ok(ok) + } 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()") @@ -3937,7 +4370,7 @@ async fn apply( .bind(&service_id) .bind(&name) .bind(sha256_hex(&token)) - .bind(s.sealer.seal(&token)?) + .bind(crate::vault::get().seal_credential(&team_id, &token).await?) .bind(&user.name) .execute(&mut **tx) .await?; @@ -3946,13 +4379,24 @@ async fn apply( Op::RevealDeployHook { id } => { let team_id = team_of(tx, "deploy_hooks", &id).await?; require_role(tx, user, &team_id, Role::Developer).await?; - let sealed: String = - sqlx::query_scalar("SELECT token_sealed FROM pyo.deploy_hooks WHERE id = $1") + let (sealed, name): (String, String) = + sqlx::query_as("SELECT token_sealed, name FROM pyo.deploy_hooks WHERE id = $1") .bind(&id) .fetch_one(&mut **tx) .await?; + log_activity( + tx, + &team_id, + &user.name, + "secret.revealed", + "info", + &format!("Revealed deploy hook {name}"), + json!({ "kind": "deployHook", "id": id, "label": name }), + json!({}), + ) + .await?; Ok( - json!({ "ok": true, "path": format!("/api/hooks/deploy/{}", s.sealer.open(&sealed)?) }), + json!({ "ok": true, "path": format!("/api/hooks/deploy/{}", crate::vault::get().open_credential(&s.sealer, &sealed).await?) }), ) } Op::RemoveDeployHook { id } => { @@ -3999,6 +4443,23 @@ async fn apply( .bind(days) .execute(&mut **tx) .await?; + // Each team the key reaches hears of it, and its owner by email. + crate::twofactor::notify_teams_in( + tx, + user, + team_ids.as_deref(), + "api_key.created", + &format!("Made API key {name} ({access} access)"), + ) + .await?; + let (to, key_name) = (user.email.clone(), name.clone()); + let s2 = s.clone(); + tokio::spawn(async move { + crate::twofactor::mail_user(&s2, &to, "/api-keys", |link| { + crate::mail::new_api_key(&key_name, link) + }) + .await; + }); Ok(json!({ "ok": true, "token": token })) } Op::UploadCertificate { @@ -4015,9 +4476,12 @@ async fn apply( "" => p.hostnames[0].clone(), n => require_text(n, "Certificate name", 60)?, }; - let sealed = s.sealer.seal(&p.key_pem).map_err(|_| { - ApiError::bad_request("Set PYO_SECRET_KEY on the API to store private keys.") - })?; + let sealed = crate::vault::get() + .seal_credential(&team_id, &p.key_pem) + .await + .map_err(|_| { + ApiError::bad_request("Set PYO_SECRET_KEY on the API to store private keys.") + })?; 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)", @@ -4846,9 +5310,12 @@ async fn apply( "The new certificate isn't valid for {host}, which uses this one." ))); } - let sealed = s.sealer.seal(&p.key_pem).map_err(|_| { - ApiError::bad_request("Set PYO_SECRET_KEY on the API to store private keys.") - })?; + let sealed = crate::vault::get() + .seal_credential(&team_id, &p.key_pem) + .await + .map_err(|_| { + ApiError::bad_request("Set PYO_SECRET_KEY on the API to store private keys.") + })?; let name: String = sqlx::query_scalar( "UPDATE pyo.certificates SET hostnames = $2, issuer = $3, not_before = to_timestamp($4), not_after = to_timestamp($5), fingerprint = $6, chain_pem = $7, key_sealed = $8, warned_days = NULL, updated_at = now() WHERE id = $1 RETURNING name", @@ -4916,11 +5383,23 @@ async fn apply( Ok(ok) } Op::RevokeApiToken { id } => { - sqlx::query("DELETE FROM pyo.api_tokens WHERE id = $1 AND user_id = $2") - .bind(&id) - .bind(&user.id) - .execute(&mut **tx) + let gone: Option<(String, Option>)> = sqlx::query_as( + "DELETE FROM pyo.api_tokens WHERE id = $1 AND user_id = $2 RETURNING name, team_ids", + ) + .bind(&id) + .bind(&user.id) + .fetch_optional(&mut **tx) + .await?; + if let Some((name, team_ids)) = gone { + crate::twofactor::notify_teams_in( + tx, + user, + team_ids.as_deref(), + "api_key.revoked", + &format!("Revoked API key {name}"), + ) .await?; + } Ok(ok) } Op::SendTestEmail {} => { @@ -4934,6 +5413,76 @@ async fn apply( .map_err(|e| ApiError::bad_request(format!("Couldn't send: {}", smtp_error(&e))))?; Ok(json!({ "ok": true, "to": user.email })) } + Op::SetTeamSecurity { + team_id, + require_two_factor, + audit_ips, + } => { + require_role(tx, user, &team_id, Role::Admin).await?; + let (was_required, was_ips): (bool, String) = sqlx::query_as( + "SELECT require_two_factor, audit_ips FROM pyo.teams WHERE id = $1", + ) + .bind(&team_id) + .fetch_one(&mut **tx) + .await?; + if let Some(req) = require_two_factor.filter(|r| *r != was_required) { + // Whoever turns it on keeps their way in. + if req && !crate::twofactor::enabled(&mut **tx, &user.id).await? { + return Err(ApiError::bad_request( + "Turn on two-factor for your own account first, in your profile.", + )); + } + sqlx::query("UPDATE pyo.teams SET require_two_factor = $2 WHERE id = $1") + .bind(&team_id) + .bind(req) + .execute(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "team.two_factor_required", + "info", + if req { + "Required two-factor authentication for members" + } else { + "Stopped requiring two-factor authentication" + }, + json!({ "kind": "team", "id": team_id, "label": "Security" }), + json!({}), + ) + .await?; + } + if let Some(ips) = audit_ips.filter(|i| *i != was_ips) { + let label = match ips.as_str() { + "full" => "full addresses", + "anonymized" => "anonymized addresses", + "none" => "no addresses", + _ => { + return Err(ApiError::bad_request( + "Keep full, anonymized or no addresses.", + )); + } + }; + sqlx::query("UPDATE pyo.teams SET audit_ips = $2 WHERE id = $1") + .bind(&team_id) + .bind(&ips) + .execute(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "team.updated", + "info", + &format!("The audit log keeps {label}"), + json!({ "kind": "team", "id": team_id, "label": "Security" }), + json!({}), + ) + .await?; + } + Ok(ok) + } Op::UpdateMemberRole { id, role } => { let team_id = team_of(tx, "members", &id).await?; require_role(tx, user, &team_id, Role::Admin).await?; @@ -4952,6 +5501,23 @@ async fn apply( .bind(&role) .execute(&mut **tx) .await?; + if current != role { + let email: String = sqlx::query_scalar("SELECT email FROM pyo.members WHERE id = $1") + .bind(&id) + .fetch_one(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "member.role_changed", + "info", + &format!("Changed the role of {email} from {current} to {role}"), + json!({ "kind": "member", "id": id, "label": email }), + json!({}), + ) + .await?; + } Ok(ok) } Op::ResetMemberSignIn { id } => { @@ -5013,10 +5579,26 @@ async fn apply( if role == "owner" { return Err(ApiError::bad_request("The owner can't be removed.")); } - sqlx::query("DELETE FROM pyo.members WHERE id = $1") - .bind(&id) - .execute(&mut **tx) - .await?; + let (email, status): (String, String) = + sqlx::query_as("DELETE FROM pyo.members WHERE id = $1 RETURNING email, status") + .bind(&id) + .fetch_one(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "member.removed", + "warning", + &if status == "invited" { + format!("Revoked the invite of {email}") + } else { + format!("Removed {email}") + }, + json!({ "kind": "member", "id": id, "label": email }), + json!({}), + ) + .await?; Ok(ok) } @@ -5120,6 +5702,7 @@ async fn apply( volumes, vec![], wake, + None, ) .await?; made.push(json!({ "name": svc.name, "id": id, "deploymentId": deployment_id })); @@ -5162,6 +5745,11 @@ async fn apply( } Ok(ok) } + Op::DeletePreview { id } => crate::previews::delete(tx, user, &id, wake).await, + Op::RedeployPreview { id } => crate::previews::redeploy(tx, user, &id).await, + Op::SetClusterPreviewDomain { id, domain } => { + crate::previews::domain::set(tx, user, &id, domain.as_deref()).await + } Op::SetProjectIsolation { id, isolate } => { let team_id = team_of(tx, "projects", &id).await?; require_role(tx, user, &team_id, Role::Admin).await?; @@ -5231,6 +5819,16 @@ async fn apply( .bind(&id) .fetch_one(&mut **tx) .await?; + // Their previews' pull requests say they're removed. + let pulls: Vec = sqlx::query_scalar( + "SELECT DISTINCT p.pull_id FROM pyo.previews p JOIN pyo.services a ON a.id = p.service_id WHERE a.project_id = $1", + ) + .bind(&id) + .fetch_all(&mut **tx) + .await?; + for p in pulls { + crate::jobs::enqueue(&mut **tx, "preview.report", json!({ "pullId": p })).await?; + } // Its services go first, each on its cluster (the agent runs a // namespace's deletions in order: services, volumes, namespace). let services: Vec<(String, String)> = sqlx::query_as( @@ -5311,9 +5909,15 @@ async fn apply( volumes, databases, confirm, + upload_id, } => { let id = service["id"].as_str().unwrap_or("").to_owned(); - tailnet_domains_ok(s, &service["domains"]).await?; + tailnet_domains_ok( + s, + service["clusterId"].as_str().unwrap_or(""), + &service["domains"], + ) + .await?; let mut service = service; fill_in_source(&mut service).await; create_service( @@ -5324,6 +5928,7 @@ async fn apply( volumes, databases, wake, + upload_id.as_deref(), ) .await?; Ok(with_warning( @@ -5342,10 +5947,23 @@ async fn apply( require_role(tx, user, &team_id, Role::Developer).await?; let (old_name, current, old_spec, pending): (String, Option, Value, bool) = sqlx::query_as("SELECT name, current_deployment_id, spec, pending_changes FROM pyo.services WHERE id = $1").bind(&id).fetch_one(&mut **tx).await?; + // A preview's copy follows the service it previews. + if crate::previews::is_copy(&mut **tx, &id).await? { + return Err(ApiError::conflict( + "This is a preview. Change the service it previews: the next push brings the change here.", + )); + } // The dashboard never gets secret values back, so a secret it // sends without one keeps the stored (sealed) value. let mut service = service; - let unhidden = keep_secret_values(&mut service, &old_spec); + let mut unhidden = keep_secret_values(&mut service, &old_spec); + // And the same for the previews' variables. + if service["previews"].is_object() { + unhidden.extend(keep_secret_values( + &mut service["previews"], + &old_spec["previews"], + )); + } if !unhidden.is_empty() { // Same as revealing it, for the whole team: admins, logged. if require_role(tx, user, &team_id, Role::Admin).await.is_err() { @@ -5399,23 +6017,40 @@ async fn apply( } } } + crate::placement::normalize(&mut spec)?; validate_service_spec(&spec)?; + crate::previews::check_settings(&mut spec)?; + let placed = crate::placement::Placement::of(&spec); + let placement_changed = placed != crate::placement::Placement::of(&old_spec); // Only a change of GPUs is checked against the cluster: a save // of anything else shouldn't fail because a server is down. - if spec["resources"]["gpu"] != old_spec["resources"]["gpu"] { + let gpu_changed = spec["resources"]["gpu"] != old_spec["resources"]["gpu"]; + if gpu_changed || placement_changed { let cluster_id: String = sqlx::query_scalar("SELECT cluster_id FROM pyo.services WHERE id = $1") .bind(&id) .fetch_one(&mut **tx) .await?; - gpu_ok(tx, &cluster_id, &spec).await?; + if gpu_changed { + gpu_ok(tx, &cluster_id, &spec).await?; + } + // Where it runs: a server picked has to be able to run it. + // Room counts only when that's what changed. + if placement_changed || !placed.any() { + crate::placement::check(tx, &cluster_id, Some(&id), &spec, placement_changed) + .await?; + } } github_source_ok(tx, &team_id, &spec).await?; crate::git::source_ok(tx, &team_id, &spec).await?; crate::git::queue_sync_for(tx, &[&old_spec["source"], &spec["source"]]).await?; crate::certs::domains_ok(tx, &team_id, &spec).await?; domains_unique(tx, &team_id, &id, &spec).await?; - tailnet_domains_ok(s, &spec["domains"]).await?; + let on: String = sqlx::query_scalar("SELECT cluster_id FROM pyo.services WHERE id = $1") + .bind(&id) + .fetch_one(&mut **tx) + .await?; + tailnet_domains_ok(s, &on, &spec["domains"]).await?; let cluster_id: String = sqlx::query_scalar("SELECT cluster_id FROM pyo.services WHERE id = $1") .bind(&id) @@ -5430,14 +6065,19 @@ async fn apply( )); } // Settings that don't change what runs need no redeploy, and nor - // do domains: they go live in place (routes.rs), and a port's - // exposure "http" only says a domain uses it. + // do domains and where it runs: they go live in place (routes.rs, + // placement.rs), and a port's exposure "http" only says a domain + // uses it. let rollout = |v: &Value| { let mut v = v.clone(); if let Some(o) = v.as_object_mut() { o.remove("description"); o.remove("autoRollback"); o.remove("domains"); + // Where it runs changes in place (placement.rs). + o.remove("placement"); + o.remove("servers"); + o.remove("serverTags"); if let Some(src) = o.get_mut("source").and_then(|x| x.as_object_mut()) { src.remove("autoDeploy"); } @@ -5456,7 +6096,8 @@ async fn apply( }; let domains_changed = crate::routes::differ(&spec["domains"], &old_spec["domains"]); // Compared in the clear: sealing the same value twice differs. - let (mut a, mut b) = (spec.clone(), old_spec.clone()); + // Only what the user sets counts, never what the API shows. + let (mut a, mut b) = (spec.clone(), service_spec_from(&old_spec)); crate::vault::get().open_env(&mut a).await?; crate::vault::get().open_env(&mut b).await?; let changed = rollout(&a) != rollout(&b); @@ -5469,6 +6110,36 @@ async fn apply( .execute(&mut **tx) .await?; crate::cloudflare::forget_removed(tx, &id, &spec).await?; + // A new placement goes live now; with a deploy, it goes out with it. + if placement_changed { + if deployment_id.is_none() + && let Some(c) = crate::placement::go_live(tx, &id, &spec).await? + { + wake.push(c); + } + let project_id: String = + sqlx::query_scalar("SELECT project_id FROM pyo.services WHERE id = $1") + .bind(&id) + .fetch_one(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "service.updated", + "info", + &format!("Changed where {name} runs"), + json!({ "kind": "service", "id": id, "label": name }), + json!({ "projectId": project_id, "serviceId": id }), + ) + .await?; + // Its previews run where it does. + if deployment_id.is_none() { + crate::previews::placement_changed(tx, &id, wake).await?; + } + } + // Its previews follow the settings (and the repository). + crate::previews::settings_saved(tx, &id, &old_spec, &spec).await?; // New domains go live now; with a deploy, they go out with it. if domains_changed && let Some(c) = crate::routes::changed(tx, &id, deployment_id.is_none()).await? @@ -5488,6 +6159,7 @@ async fn apply( rollback_of: None, retry_of: None, commit: None, + upload: None, }, ) .await?; @@ -5523,6 +6195,8 @@ async fn apply( .await?; // Its repository's webhook goes when no other service follows it. crate::git::queue_sync_for(tx, &[&source]).await?; + // Its previews go with it (or, for a preview's copy, its preview). + crate::previews::service_deleted(tx, &id, wake).await?; sqlx::query("UPDATE pyo.deployments SET status = 'cancelled', finished_at = now() WHERE service_id = $1 AND status NOT IN ('succeeded', 'failed', 'cancelled')") .bind(&id) .execute(&mut **tx) @@ -5563,8 +6237,14 @@ async fn apply( trigger, rollback_of, retry_of, + upload_id, } => { client_id(&deployment_id, "dpl")?; + if upload_id.is_some() && (rollback_of.is_some() || retry_of.is_some()) { + return Err(ApiError::bad_request( + "An upload deploys on its own, not with a rollback or retry.", + )); + } let team_id = team_of(tx, "services", &service_id).await?; require_role(tx, user, &team_id, Role::Developer).await?; let trigger = match trigger.as_str() { @@ -5581,6 +6261,7 @@ async fn apply( rollback_of: rollback_of.as_deref(), retry_of: retry_of.as_deref(), commit: None, + upload: upload_id.as_deref(), }, ) .await?; @@ -5601,24 +6282,7 @@ async fn apply( if deploy::is_final(&status) { return Err(ApiError::conflict("This deployment already finished.")); } - deploy::enqueue( - tx, - &cluster_id, - Command::Cancel { - deployment_id: deployment_id.clone(), - }, - ) - .await?; - // A build that hasn't finished is dropped; its result is ignored. - sqlx::query("UPDATE pyo.build_jobs SET status = 'cancelled', finished_at = now() WHERE deployment_id = $1 AND status IN ('queued', 'running')") - .bind(&deployment_id) - .execute(&mut **tx) - .await?; - // Queued work the agent hasn't picked up yet is withdrawn here. - sqlx::query("UPDATE pyo.commands SET status = 'failed', done_at = now(), result = '{\"ok\":false,\"message\":\"Cancelled\",\"logs\":[]}' WHERE status = 'pending' AND command->>'kind' = 'deploy' AND command->>'deploymentId' = $1") - .bind(&deployment_id) - .execute(&mut **tx) - .await?; + deploy::cancel(tx, &deployment_id).await?; wake.push(cluster_id); Ok(ok) } @@ -6218,12 +6882,22 @@ async fn apply( .bind(&service_id) .fetch_one(&mut **tx) .await?; - let host = spec["domains"] + let d = spec["domains"] .as_array() .and_then(|ds| ds.iter().find(|d| d["id"] == json!(domain_id))) - .and_then(|d| d["hostname"].as_str()) - .ok_or_else(|| ApiError::not_found("Domain"))? - .to_owned(); + .ok_or_else(|| ApiError::not_found("Domain"))?; + let host = d["hostname"].as_str().unwrap_or_default().to_owned(); + // A tailnet domain has no DNS to check: it goes live once the + // cluster serves it (tailscale.rs). + if pyo_proto::system::is_tailnet_host(&host) { + let live = d["status"] == json!("active"); + let message = (!live).then(|| { + d["error"].as_str().map(str::to_owned).unwrap_or_else(|| { + format!("{host} goes live once the cluster serves it on your tailnet.") + }) + }); + return Ok(json!({ "ok": live, "message": message, "addresses": [] })); + } // The DNS watcher does this on its own; this is the same check, now. let resolved = deploy::resolve(&host).await; deploy::set_domain_dns(&s.db, &service_id, &domain_id, !resolved.is_empty(), &host) @@ -6246,6 +6920,12 @@ async fn apply( public_api_url, } => { let tags = valid_tags(&tags)?; + // Agents over mTLS (Pyo Cloud): Pyo's own machine isn't a team's server. + if this_machine && crate::agent_tls::endpoint().is_some() { + return Err(ApiError::bad_request( + "Connect one of your own servers. Pyo doesn't run on them here.", + )); + } // One agent per machine: a second "This machine" would replace the first. if this_machine { let taken: Option = sqlx::query_scalar("SELECT team_id FROM pyo.clusters WHERE same_cluster OR from_host_setup LIMIT 1").fetch_optional(&mut **tx).await?; @@ -6282,25 +6962,29 @@ async fn apply( reserved_cluster_name(&name)?; name }; - let token = secret_token(); // Detected per server from its public address; a cluster-wide one is optional. let location = if location.trim().is_empty() { String::new() } else { require_location(&location)? }; + // The agent's token is made when the connect command first + // fetches its manifest (install.rs): none works before. sqlx::query("INSERT INTO pyo.clusters (id, team_id, name, description, location, agent_token_hash, tags, name_from_host) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)") .bind(&id) .bind(&team_id) .bind(&name) .bind(description.trim()) .bind(&location) - .bind(sha256_hex(&token)) + .bind(sha256_hex(&secret_token())) .bind(&tags) .bind(from_host) .execute(&mut **tx) .await?; + let token = crate::install::new_connect_token(tx, &id, &team_id).await?; sqlx::query("UPDATE pyo.teams SET default_cluster_id = coalesce(default_cluster_id, $2) WHERE id = $1").bind(&team_id).bind(&id).execute(&mut **tx).await?; + // Its registry's door gets the team's tokens once its agent is in. + crate::registrydoor::sync_clusters(tx, &team_id, Some(&id)).await?; // Run on this machine, the installer reaches Pyo at localhost, // so the agent is given the in-cluster address (install.rs). let (command, tailnet) = if this_machine { @@ -6328,12 +7012,20 @@ async fn apply( } => { let team_id = team_of(tx, "clusters", &id).await?; require_role(tx, user, &team_id, Role::Admin).await?; - let token = secret_token(); - sqlx::query("UPDATE pyo.clusters SET agent_token_hash = $2 WHERE id = $1") + if this_machine && crate::agent_tls::endpoint().is_some() { + return Err(ApiError::bad_request( + "Connect one of your own servers. Pyo doesn't run on them here.", + )); + } + // The agent's token, keys and certificates go: it connects again + // with the new command, whose connect token makes its new token. + crate::agent_auth::revoke(tx, &id).await?; + sqlx::query("UPDATE pyo.clusters SET agent_token_hash = $2, agent_cert_serial = NULL, agent_cert_prev_serial = NULL WHERE id = $1") .bind(&id) - .bind(sha256_hex(&token)) + .bind(sha256_hex(&secret_token())) .execute(&mut **tx) .await?; + let token = crate::install::new_connect_token(tx, &id, &team_id).await?; // As in CreateCluster: run where Pyo runs, the agent dials the in-cluster address. let (command, tailnet) = if this_machine { ( @@ -6353,6 +7045,27 @@ async fn apply( json!({ "ok": true, "token": token, "command": command, "tailscale": tailnet, "tailnet": tailnet }), ) } + Op::UpdateClusterAgent { id } => { + let team_id = team_of(tx, "clusters", &id).await?; + require_role(tx, user, &team_id, Role::Admin).await?; + let command = crate::updates::update_cluster_agent(s, &id).await?; + let name: String = sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(&id) + .fetch_one(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "cluster.updated", + "info", + &format!("Updating the agent of {name} to {}", crate::updates::current()), + json!({ "kind": "cluster", "id": id, "label": name }), + json!({ "clusterId": id }), + ) + .await?; + Ok(json!({ "ok": true, "commandId": command })) + } Op::UpdateCluster { id, name, @@ -6824,7 +7537,9 @@ async fn apply( let verified = crate::registry::verify(&host, &username, password.trim()) .await .map_err(ApiError::bad_request)?; - let sealed = s.sealer.seal(password.trim()).map_err(ApiError::from)?; + let sealed = crate::vault::get() + .seal_credential(&team_id, password.trim()) + .await?; sqlx::query( "INSERT INTO pyo.registry_logins (id, team_id, host, username, secret_sealed, verified) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (team_id, host) DO UPDATE SET username = $4, secret_sealed = $5, verified = $6, created_at = now()", @@ -6903,6 +7618,8 @@ async fn apply( .bind(&team_id) .fetch_one(&mut **tx) .await?; + // Each cluster's own registry's door (Pyo Cloud). + wake.extend(crate::registrydoor::sync_clusters(tx, &team_id, None).await?); log_activity( tx, &team_id, @@ -6931,6 +7648,7 @@ async fn apply( .bind(&id) .fetch_one(&mut **tx) .await?; + wake.extend(crate::registrydoor::sync_clusters(tx, &team_id, None).await?); log_activity( tx, &team_id, @@ -7224,7 +7942,7 @@ async fn apply( let tags = valid_tags(&tags)?; let ssh_key = cloud_ssh_key(ssh_key)?; cloud_name_free(tx, &cluster_id, &name).await?; - crate::cloud::needs_tailscale(&s.db).await?; + crate::cloud::needs_tailscale(&s.db, Some(&cluster_id)).await?; let p = crate::cloud::provider(&s.db, &team_id).await?; let catalog = crate::cloud::catalog(&s.db, &team_id).await?; let monthly = catalog.pick(&location, &server_type)?; @@ -7324,7 +8042,7 @@ async fn apply( require_dns_label(&server, "Cluster name")?; let tags = valid_tags(&tags)?; let ssh_key = cloud_ssh_key(ssh_key)?; - crate::cloud::needs_tailscale(&s.db).await?; + crate::cloud::needs_tailscale(&s.db, None).await?; let p = crate::cloud::provider(&s.db, &team_id).await?; let catalog = crate::cloud::catalog(&s.db, &team_id).await?; let monthly = catalog.pick(&location, &server_type)?; @@ -7402,44 +8120,19 @@ async fn apply( Op::DeleteCloudServer { id, confirm } => { delete_cloud_server(tx, user, &id, confirm, wake).await } - Op::SaveTailscale { client_id, secret } => { - require_admin(user)?; - let out = crate::tailscale::save_client(s, &client_id, secret.as_deref()).await?; - log_setting(tx, user, "tailscale", "Connected Tailscale").await?; - Ok(out) - } - // Run by outside_tx, with no transaction open. - Op::PlanTailscaleSetup { .. } | Op::SetUpTailscale { .. } => { - Err(anyhow::anyhow!("the tailscale setup runs outside the transaction").into()) + // Run by outside_tx, with no transaction open: each waits for the + // cluster's agent. + Op::PlanTailscaleSetup { .. } + | Op::SetUpTailscale { .. } + | Op::SaveTailscale { .. } + | Op::TestTailscale { .. } + | Op::RemoveTailscale { .. } + | Op::RenameTailscaleName { .. } => { + Err(anyhow::anyhow!("tailscale runs outside the transaction").into()) } Op::TestAlertChannel { .. } => { Err(anyhow::anyhow!("an alert test runs outside the transaction").into()) } - Op::TestTailscale {} => { - require_admin(user)?; - crate::tailscale::test_saved(s).await - } - Op::RemoveTailscale {} => { - require_admin(user)?; - crate::tailscale::remove(s).await?; - log_setting(tx, user, "tailscale", "Removed Tailscale").await?; - Ok(ok) - } - Op::RenameTailscaleName { kind, name } => { - require_admin(user)?; - crate::tailscale::rename(s, &kind, &name).await?; - let title = format!( - "Renamed the {} on the tailnet to {}", - if kind == "registry" { - "registry" - } else { - "dashboard" - }, - name.trim().to_ascii_lowercase() - ); - log_setting(tx, user, "tailscale", &title).await?; - Ok(ok) - } Op::SetPublicDashboard { open } => { require_admin(user)?; crate::publicdash::set_open(&s.db, open).await?; @@ -7912,7 +8605,7 @@ pub(crate) async fn service_preview( SessionUser(user): SessionUser, Path(id): Path, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "services", &id).await?; require_role(&mut tx, &user, &team_id, Role::Viewer).await?; let spec: Value = sqlx::query_scalar("SELECT spec FROM pyo.services WHERE id = $1") @@ -8008,37 +8701,80 @@ pub(crate) async fn service_preview( #[derive(serde::Serialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] pub(crate) struct ServiceLogs { - /// The last 300 lines of each replica, oldest first. + /// The last lines of each replica (300, or `tail`), oldest first. `source` is the replica. logs: Vec, /// When they were read, in milliseconds since 1970. fetched_at: i64, } +/// Which of a service's lines to read. +#[derive(Deserialize, Default, utoipa::IntoParams)] +#[into_params(parameter_in = Query)] +pub struct LogsQuery { + /// Only lines since this time, in milliseconds since 1970 (at most a week back). + pub(crate) since: Option, + /// Only this replica, by name (a log line's `source`). + pub(crate) replica: Option, + /// How many lines of each replica, 1 to 2000. 300 by default. + pub(crate) tail: Option, +} + /// Recent logs /// /// The last lines each of a service's replicas printed, read from its -/// cluster on request. Takes up to 15 seconds. +/// cluster on request. Takes up to 15 seconds. To follow them, open the +/// WebSocket at `/services/{id}/logs/follow` with the same query: it sends +/// these lines, then new ones as they're printed, each text frame +/// `{"type":"lines","lines":[…]}` (or `{"type":"error","message":…}`). It +/// closes after an hour, so open it again with `since` set to the newest +/// line's time. #[utoipa::path(get, path = "/services/{id}/logs", operation_id = "getServiceLogs", tag = "Services", - params(("id" = String, Path, description = "The service's id (`svc_…`).")), + params(("id" = String, Path, description = "The service's id (`svc_…`)."), LogsQuery), responses( (status = 200, description = "The lines.", body = ServiceLogs), + (status = 400, description = "Not a replica name.", body = ErrorBody), (status = 404, description = "No such service, or it isn't yours to see.", body = ErrorBody), (status = 502, description = "The cluster couldn't read them.", body = ErrorBody), (status = 504, description = "The cluster didn't answer within 15 seconds (is it connected?).", body = ErrorBody), ), extensions(("x-pyo-access" = json!("read"))))] -async fn service_logs( +pub(crate) async fn service_logs( State(s): State, SessionUser(user): SessionUser, Path(id): Path, + crate::error::Query(q): crate::error::Query, ) -> ApiResult> { - Ok(Json(fetch_service_logs(&s, &user, &id).await?)) + Ok(Json(fetch_service_logs(&s, &user, &id, q).await?)) +} + +/// Seconds back to read from `since` (ms), rounded up, a week at most. +pub(crate) fn since_seconds(since: Option, now: i64) -> Option { + since.map(|t| ((now - t).max(0) / 1000 + 1).min(7 * 86400)) +} + +/// A replica's name from a query, checked. Empty: all of them. +pub(crate) fn replica_name(replica: Option) -> ApiResult { + let replica = replica.unwrap_or_default(); + if replica.len() > 253 + || !replica + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'.') + { + return Err(ApiError::bad_request("That isn't a replica name.")); + } + Ok(replica) } /// Recent output of a service's replicas, read by its cluster's agent. -pub async fn fetch_service_logs(s: &AppState, user: &User, id: &str) -> ApiResult { +pub async fn fetch_service_logs( + s: &AppState, + user: &User, + id: &str, + q: LogsQuery, +) -> ApiResult { + let replica = replica_name(q.replica)?; let id = id.to_owned(); - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, user).await?; let team_id = team_of(&mut tx, "services", &id).await?; require_role(&mut tx, user, &team_id, Role::Viewer).await?; let cluster_id: String = @@ -8052,7 +8788,9 @@ pub async fn fetch_service_logs(s: &AppState, user: &User, id: &str) -> ApiResul &cluster_id, Command::FetchLogs { service, - tail_lines: 300, + tail_lines: q.tail.unwrap_or(300).clamp(1, 2000), + since_seconds: since_seconds(q.since, now_ms()), + replica, }, ) .await?; @@ -8109,13 +8847,14 @@ pub(crate) struct MetricsQuery { /// Observability settings /// /// Whether observability is on for this installation (it's off on a new -/// install on a server with under 3.5 GB of memory), and what it keeps of -/// visitors' IP addresses. `small`: the server Pyo runs on has under 3.5 GB -/// of memory now. The installation's admin turns it on or off with -/// `setObservability`. +/// install on a server with under 3.5 GB of memory), what it keeps of +/// visitors' IP addresses, and how long it keeps data (`retention`: +/// `analyticsMonths`, `metricsDays`, `buildLogDays`). `small`: the server +/// Pyo runs on has under 3.5 GB of memory now. The installation's admin +/// turns it on or off with `setObservability`. #[utoipa::path(get, path = "/observability/settings", operation_id = "getObservabilitySettings", tag = "Observability", responses( - (status = 200, description = "`enabled`, `ipMode` and `small`.", body = Object), + (status = 200, description = "`enabled`, `ipMode`, `retention` and `small`.", body = Object), ), extensions(("x-pyo-access" = json!("read"))))] pub(crate) async fn observability_settings( @@ -8125,6 +8864,7 @@ pub(crate) async fn observability_settings( Ok(Json(json!({ "enabled": crate::observability::setting(&s.db).await?, "ipMode": crate::observability::ip_mode(&s.db).await?, + "retention": crate::retention::load(&s.db).await?, "small": pyo_proto::memory::server_mib().map(|m| pyo_proto::memory::tier(m) == pyo_proto::memory::Tier::Small), }))) } @@ -8149,7 +8889,7 @@ pub(crate) async fn metrics( SessionUser(user): SessionUser, crate::error::Query(q): crate::error::Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team, Role::Viewer).await?; tx.commit().await?; let cluster = q.cluster.filter(|c| c != "all").unwrap_or_default(); @@ -8198,20 +8938,24 @@ pub(crate) struct AccessLogQuery { method: Option, /// Only requests whose URL or host contains this (any case). q: Option, + /// Only requests whose path starts with this, such as "/api". + path: Option, } /// Request log /// /// The web server's log of requests to a team's websites, newest first, -/// filtered like the traffic figures. +/// filtered like the traffic figures. Requests stay in each website's +/// cluster (1 GB or 7 days by default, the team's `requestLogs` +/// preference), which answers within seconds, up to 500 at a time. #[utoipa::path(get, path = "/access-logs", operation_id = "getAccessLogs", tag = "Observability", params(AccessLogQuery), responses( - (status = 200, description = "`logs` (newest first: time, method, host, path, status, duration, size, country, device and address as the IP setting allows), `next` (the `before` for the next page, or null), `ipMode`, and on the first page a `summary` of the filtered requests.", body = Object), + (status = 200, description = "`logs` (newest first: time, method, host, path, status, duration, size, country, device and address as the IP setting allows), `next` (the `before` for the next page, or null), `ipMode`, `unavailable` (clusters that didn't answer, with why), and on the first page without filters a `summary` of the range.", body = Object), (status = 400, description = "No `team`.", body = ErrorBody), (status = 404, description = "No such team, or you aren't in it.", body = ErrorBody), - (status = 502, description = "The log storage couldn't be read.", body = ErrorBody), - (status = 503, description = "This installation doesn't store request logs.", body = ErrorBody), + (status = 503, description = "Observability is off on this installation.", body = ErrorBody), + (status = 504, description = "No cluster answered in time.", body = ErrorBody), ), extensions(("x-pyo-access" = json!("read"))))] pub(crate) async fn access_logs( @@ -8232,12 +8976,12 @@ pub(crate) async fn access_logs( range: q.range.unwrap_or_else(|| "24h".into()), before: q.before, limit: q.limit.unwrap_or(100), - status: q.status, - method: q.method, + status: q.status.filter(|v| !v.is_empty()), + method: q.method.filter(|v| !v.is_empty()), q: q.q, }; Ok(Json( - s.observability.access_logs(&q.team, &hosts, &f).await?, + crate::requests::access_logs(&s, &q.team, &hosts, &f, q.path).await?, )) } @@ -8256,7 +9000,7 @@ async fn team_hosts( site: Option, service: Option, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, user).await?; require_role(&mut tx, user, team, Role::Viewer).await?; let project = filter_value(project); let site = filter_value(site); @@ -8278,13 +9022,16 @@ async fn team_hosts( /// Website traffic /// -/// Visits, requests, errors, response times, countries, pages and referrers -/// for a team's websites: all of them, one project's, one service's, or one -/// domain. +/// Visitors, requests, errors, response times, countries, pages and +/// referrers for a team's websites: all of them, one project's, one +/// service's, or one domain. Read from per-minute totals each cluster +/// sends (kept 12 months by default), so it works with a cluster offline. +/// Top lists count page views (referrers, pages, devices, browsers) or +/// requests (paths, countries, query parameters). #[utoipa::path(get, path = "/observability", operation_id = "getObservability", tag = "Observability", params(ObservabilityQuery), responses( - (status = 200, description = "Totals, series over time and top lists for the range.", body = Object), + (status = 200, description = "`summary` (totals and top lists for the range), `series` (over time) and `previous` (the period before).", body = Object), (status = 400, description = "No `team`.", body = ErrorBody), (status = 404, description = "No such team, or you aren't in it.", body = ErrorBody), (status = 503, description = "This installation doesn't store traffic.", body = ErrorBody), @@ -8321,7 +9068,7 @@ pub(crate) struct ConnectionsQuery { #[utoipa::path(get, path = "/services/{id}/connections", operation_id = "getServiceConnections", tag = "Observability", params(("id" = String, Path, description = "The service's id."), ConnectionsQuery), responses( - (status = 200, description = "`ports`, `series`, `countries`, `outcomes`, `recent` (address as the IP setting allows) and `ipMode`.", body = Object), + (status = 200, description = "`ports`, `series`, `countries`, `outcomes`, and from the cluster `recent` (address as the IP setting allows), `ipMode` and `recentError` when it couldn't answer.", body = Object), (status = 404, description = "No such service, or you can't see it.", body = ErrorBody), (status = 503, description = "This installation doesn't store traffic.", body = ErrorBody), ), @@ -8332,7 +9079,7 @@ pub(crate) async fn connections( axum::extract::Path(id): axum::extract::Path, crate::error::Query(q): crate::error::Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "services", &id).await?; require_role(&mut tx, &user, &team_id, Role::Viewer).await?; tx.commit().await?; @@ -8340,9 +9087,9 @@ pub(crate) async fn connections( Some(r @ ("1h" | "24h" | "7d" | "30d")) => r.to_owned(), _ => "7d".to_owned(), }; - Ok(Json( - s.observability.connections(&team_id, &id, &range).await?, - )) + let mut out = s.observability.connections(&team_id, &id, &range).await?; + crate::requests::connections_recent(&s, &id, &range, &mut out).await?; + Ok(Json(out)) } #[derive(Deserialize, utoipa::IntoParams)] @@ -8365,7 +9112,7 @@ pub(crate) struct BlockedQuery { #[utoipa::path(get, path = "/firewall/blocked", operation_id = "getFirewallBlocked", tag = "Firewall", params(BlockedQuery), responses( - (status = 200, description = "`total`, `series`, `rules`, `sources` (address as the IP setting allows), `countries`, `paths`, `recent` and `ipMode`.", body = Object), + (status = 200, description = "`total`, `series`, `rules`, `countries`, `paths`, and from the cluster `sources` (among the latest 500, address as the IP setting allows), `recent`, `ipMode` and `recentError` when it couldn't answer.", body = Object), (status = 404, description = "No such service, or you can't see it.", body = ErrorBody), (status = 503, description = "This installation doesn't store traffic.", body = ErrorBody), ), @@ -8375,7 +9122,7 @@ pub(crate) async fn firewall_blocked( SessionUser(user): SessionUser, crate::error::Query(q): crate::error::Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "services", &q.service).await?; require_role(&mut tx, &user, &team_id, Role::Viewer).await?; tx.commit().await?; @@ -8384,9 +9131,9 @@ pub(crate) async fn firewall_blocked( Some(r @ ("1h" | "24h" | "7d" | "30d")) => r.to_owned(), _ => "24h".to_owned(), }; - Ok(Json( - s.observability.blocked(&team_id, &services, &range).await?, - )) + let mut out = s.observability.blocked(&team_id, &services, &range).await?; + crate::requests::blocked_recent(&s, &services[0], &range, &mut out).await?; + Ok(Json(out)) } /// WAF findings @@ -8400,7 +9147,7 @@ pub(crate) async fn firewall_blocked( #[utoipa::path(get, path = "/waf/hits", operation_id = "getWafHits", tag = "Firewall", params(BlockedQuery), responses( - (status = 200, description = "`blocked`, `logged`, `clients`, `series`, `rules`, `hosts`, `sources`, `countries`, `paths`, `recent`, `custom` and `ipMode`.", body = Object), + (status = 200, description = "`blocked`, `logged`, `clients`, `series`, `rules`, `hosts`, `countries`, `paths`, `custom`, and from the cluster `sources` (among the latest 500), `recent`, `ipMode` and `recentError` when it couldn't answer.", body = Object), (status = 404, description = "No such service, or you can't see it.", body = ErrorBody), (status = 503, description = "This installation doesn't store traffic.", body = ErrorBody), ), @@ -8410,7 +9157,7 @@ pub(crate) async fn waf_hits( SessionUser(user): SessionUser, crate::error::Query(q): crate::error::Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "services", &q.service).await?; require_role(&mut tx, &user, &team_id, Role::Viewer).await?; tx.commit().await?; @@ -8419,11 +9166,9 @@ pub(crate) async fn waf_hits( Some(r @ ("1h" | "24h" | "7d" | "30d")) => r.to_owned(), _ => "24h".to_owned(), }; - Ok(Json( - s.observability - .waf_hits(&team_id, &services, &range) - .await?, - )) + let mut out = s.observability.waf_hits(&team_id, &services, &range).await?; + crate::requests::waf_recent(&s, &services[0], &range, &mut out).await?; + Ok(Json(out)) } /// Your address @@ -8579,6 +9324,7 @@ async fn fill_in_source(service: &mut Value) { /// A new service and its first deployment (createService, and each of a /// Compose import's services). Without a deployment id it's only saved, /// stopped, until it's deployed (a platform import that doesn't deploy). +#[allow(clippy::too_many_arguments)] pub(crate) async fn create_service( tx: &mut Transaction<'_, Postgres>, user: &User, @@ -8587,6 +9333,7 @@ pub(crate) async fn create_service( volumes: Vec, databases: Vec, wake: &mut Vec, + upload: Option<&str>, ) -> ApiResult<()> { let id = service["id"].as_str().unwrap_or("").to_owned(); if !crate::ids::valid_client_id(&id, "svc") { @@ -8609,8 +9356,11 @@ pub(crate) async fn create_service( } let mut spec = service_spec_from(&service); crate::template_source::scrub_fields(&mut spec); + crate::placement::normalize(&mut spec)?; validate_service_spec(&spec)?; + crate::previews::check_settings(&mut spec)?; gpu_ok(tx, &cluster_id, &spec).await?; + crate::placement::check(tx, &cluster_id, None, &spec, true).await?; github_source_ok(tx, &team_id, &spec).await?; crate::git::source_ok(tx, &team_id, &spec).await?; crate::git::queue_sync_for(tx, &[&spec["source"]]).await?; @@ -8705,6 +9455,7 @@ pub(crate) async fn create_service( rollback_of: None, retry_of: None, commit: None, + upload, }, ) .await?; @@ -8716,6 +9467,15 @@ pub(crate) async fn create_service( mod op_error_tests { use super::*; + #[test] + fn logs_since_a_time_read_back_far_enough() { + assert_eq!(since_seconds(None, 10_000), None); + // Rounded up: nothing in the last partial second is missed. + assert_eq!(since_seconds(Some(8_500), 10_000), Some(2)); + assert_eq!(since_seconds(Some(20_000), 10_000), Some(1)); + assert_eq!(since_seconds(Some(0), 30 * 86_400_000), Some(7 * 86400)); + } + fn err(v: serde_json::Value) -> String { op_error(&serde_json::from_value::(v).err().unwrap().to_string()) } @@ -9148,9 +9908,24 @@ mod removal_tests { #[cfg(test)] mod secret_tests { - use super::keep_secret_values; + use super::{keep_secret_values, service_spec_from}; use serde_json::json; + #[test] + fn what_the_api_shows_is_never_stored() { + let shown = json!({ + "id": "svc_1", "name": "web", "status": "running", "pendingChanges": false, + "waf": { "mode": "block" }, "wafState": { "state": "ready", "message": "" }, + "behindCdn": "cloudflare", "replicas": 1, + "domains": [{ "id": "dom_1", "hostname": "a.example.com", "dnsRecord": { "zone": "example.com" } }], + }); + let spec = service_spec_from(&shown); + assert_eq!( + spec, + json!({ "name": "web", "replicas": 1, "domains": [{ "id": "dom_1", "hostname": "a.example.com" }] }) + ); + } + #[test] fn a_blank_secret_keeps_its_value() { let old = json!({ "env": [{ "id": "e1", "key": "TOKEN", "value": "pyo1:sealed", "secret": true }] }); @@ -9754,6 +10529,7 @@ mod compose_import_tests { #[ignore] fn a_compose_import_in_the_database() { let rt = tokio::runtime::Builder::new_multi_thread() + .thread_stack_size(64 << 20) .enable_all() .build() .unwrap(); diff --git a/crates/pyo-api/src/passkeys.rs b/crates/pyo-api/src/passkeys.rs index 2d153aec..3b4ee3e9 100644 --- a/crates/pyo-api/src/passkeys.rs +++ b/crates/pyo-api/src/passkeys.rs @@ -239,6 +239,19 @@ async fn login_finish( ratelimit::take(&state.db, &[(ratelimit::PASSKEY_FINISH_IP, &ip)]).await?; let user = verify_passkey(&state, body).await?; 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( + &state.db, + &user.id, + &crate::audit::Who::person(&user), + crate::audit::Entry { + action: "auth.sign_in", + title: "Signed in with a passkey", + target: json!({}), + failed: false, + }, + ) + .await; let jar = start_session(&state, jar, &user.id, &headers).await?; Ok((jar, Json(user))) } @@ -426,6 +439,18 @@ async fn register_finish( if added == 0 { return Err(ApiError::conflict("This passkey is already added.")); } + crate::audit::account_event( + &state.db, + &user.id, + &crate::audit::Who::person(&user), + crate::audit::Entry { + action: "auth.passkey_added", + title: &format!("Added passkey {name}"), + target: json!({ "kind": "passkey", "id": id, "label": name }), + failed: false, + }, + ) + .await; Ok(( StatusCode::CREATED, Json(json!({ "id": id, "name": name, "rpId": rp.id })), @@ -483,17 +508,28 @@ async fn remove( ) -> ApiResult { browser_only(&user)?; // The password stays, so this can't lock anyone out. - let n = sqlx::query("DELETE FROM pyo.passkeys WHERE id = $1 AND user_id = $2") - .bind(&id) - .bind(&user.id) - .execute(&state.db) - .await? - .rows_affected(); - if n == 0 { - Err(ApiError::not_found("Passkey")) - } else { - Ok(StatusCode::NO_CONTENT) - } + let name: Option = + sqlx::query_scalar("DELETE FROM pyo.passkeys WHERE id = $1 AND user_id = $2 RETURNING name") + .bind(&id) + .bind(&user.id) + .fetch_optional(&state.db) + .await?; + let Some(name) = name else { + return Err(ApiError::not_found("Passkey")); + }; + crate::audit::account_event( + &state.db, + &user.id, + &crate::audit::Who::person(&user), + crate::audit::Entry { + action: "auth.passkey_removed", + title: &format!("Removed passkey {name}"), + target: json!({ "kind": "passkey", "id": id, "label": name }), + failed: false, + }, + ) + .await; + Ok(StatusCode::NO_CONTENT) } #[cfg(test)] diff --git a/crates/pyo-api/src/placement.rs b/crates/pyo-api/src/placement.rs new file mode 100644 index 00000000..303710d5 --- /dev/null +++ b/crates/pyo-api/src/placement.rs @@ -0,0 +1,691 @@ +//! Where a service runs: on any server of its cluster, or only on servers +//! picked by name and on servers with a tag picked (every server that has +//! it, tagged now or later). Kept in its spec as +//! `"placement": { "servers": [...], "tags": [...] }`, absent for any +//! server. Services saved before kept `servers` and `serverTags`, which +//! read as the same (their tags as tags picked). +//! +//! A change goes live in place, without a deploy: the agent patches the +//! workload's node affinity and Kubernetes replaces its pods with the same +//! image ([`go_live`], `Command::Place`). + +use std::collections::HashMap; + +use pyo_proto::{Command, CronTask}; +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use crate::error::{ApiError, ApiResult}; + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Placement { + pub servers: Vec, + pub tags: Vec, +} + +fn strings(v: &Value) -> Vec { + v.as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect() +} + +fn dedup(mut v: Vec) -> Vec { + let mut seen = std::collections::HashSet::new(); + v.retain(|x| seen.insert(x.clone())); + v +} + +impl Placement { + /// A spec's placement: `placement` when it has one (null is any + /// server), else the `servers` and `serverTags` it was saved with. + pub fn of(spec: &Value) -> Self { + let (servers, tags) = match spec.get("placement") { + Some(p) => (strings(&p["servers"]), strings(&p["tags"])), + None => (strings(&spec["servers"]), strings(&spec["serverTags"])), + }; + Placement { + servers: dedup(servers), + tags: dedup( + tags.iter() + .filter_map(|t| pyo_proto::valid_tag(t)) + .collect(), + ), + } + } + + /// Any server of its cluster. + pub fn any(&self) -> bool { + self.servers.is_empty() && self.tags.is_empty() + } + + /// It may run on this server (with these tags). + pub fn takes(&self, server: &str, tags: &[String]) -> bool { + self.any() + || self.servers.iter().any(|s| s == server) + || self.tags.iter().any(|t| tags.contains(t)) + } + + pub fn to_value(&self) -> Value { + json!({ "servers": self.servers, "tags": self.tags }) + } +} + +/// A spec's placement as it's kept: `placement`, absent for any server. +/// `servers` and `serverTags`, as clients may still send, go into it +/// unless `placement` is there too (it wins). A tag that can't be one is +/// refused. +pub fn normalize(spec: &mut Value) -> ApiResult<()> { + let raw_tags = match spec.get("placement") { + Some(p) => strings(&p["tags"]), + None => strings(&spec["serverTags"]), + }; + if let Some(bad) = raw_tags.iter().find(|t| pyo_proto::valid_tag(t).is_none()) { + return Err(ApiError::bad_request(format!( + "{bad} isn't a tag. Tags are lowercase letters, digits and dashes, up to 32." + ))); + } + let p = Placement::of(spec); + if let Some(o) = spec.as_object_mut() { + o.remove("servers"); + o.remove("serverTags"); + if p.any() { + o.remove("placement"); + } else { + o.insert("placement".into(), p.to_value()); + } + } + Ok(()) +} + +/// A server of the cluster, as the checks see it. +#[derive(Debug, Clone)] +pub struct Server { + pub name: String, + pub tags: Vec, + /// Its last report (allocatable, requested, gpuDetected, builder...). + pub report: Value, +} + +/// What one replica of the service needs. +#[derive(Debug, Clone, Copy, Default)] +pub struct Need { + pub gpu: bool, + /// Cores. + pub cpu: f64, + /// GiB. + pub memory_gi: f64, +} + +/// "2.5", "30": one decimal under 10, whole numbers above. +fn amount(x: f64) -> String { + if x < 10.0 { + let r = (x * 10.0).round() / 10.0; + if r.fract() == 0.0 { + format!("{}", r as i64) + } else { + format!("{r:.1}") + } + } else { + format!("{}", x.round() as i64) + } +} + +/// Why a service can't run where `p` puts it, or None when some server +/// picked can. Any server is never refused here: its volume, if any, keeps +/// it on its server, and Kubernetes picks a GPU server for a GPU service. +/// +/// `volume`: one of its volumes that keeps data on one server's disk +/// (its name, that server). `own`: what its replicas ask for now on each +/// server, which they give back when they move. +pub fn refusal( + p: &Placement, + servers: &[Server], + volume: Option<(&str, &str)>, + need: Need, + own: &HashMap, +) -> Option { + if p.any() { + return None; + } + if let Some(missing) = p + .servers + .iter() + .find(|n| !servers.iter().any(|s| &s.name == *n)) + { + return Some(format!("{missing} isn't a server of this cluster.")); + } + let picked: Vec<&Server> = servers + .iter() + .filter(|s| p.takes(&s.name, &s.tags)) + .collect(); + if picked.is_empty() { + return Some(match p.tags.as_slice() { + [t] => format!("No server has the tag {t} yet. Tag one first, or pick servers."), + _ => "No server has these tags yet. Tag one first, or pick servers.".to_owned(), + }); + } + if let Some((name, on)) = volume + && !picked.iter().any(|s| s.name == on) + { + return Some(format!( + "Its volume {name} lives on {on}, so it has to run there. Pick {on} too." + )); + } + let usable: Vec<&Server> = picked + .iter() + .copied() + .filter(|s| s.report["builder"] != json!(true)) + .collect(); + if usable.is_empty() { + return Some("These servers only run builds. Pick another server.".to_owned()); + } + let usable: Vec<&Server> = if need.gpu { + let gpu: Vec<&Server> = usable + .into_iter() + .filter(|s| s.report["gpuDetected"] == json!(true)) + .collect(); + if gpu.is_empty() { + return Some( + "It asks for a GPU, and none of these servers has one. Pick a GPU server." + .to_owned(), + ); + } + gpu + } else { + let regular: Vec<&Server> = usable + .into_iter() + .filter(|s| s.report["gpuDedicated"] != json!(true)) + .collect(); + if regular.is_empty() { + return Some( + "These servers only run services that use a GPU. Pick another server.".to_owned(), + ); + } + regular + }; + // Room: only when every one of them has said what it has. + let alloc = |s: &Server| { + ( + s.report["allocatable"]["cpu"].as_f64().unwrap_or(0.0), + s.report["allocatable"]["memoryGi"].as_f64().unwrap_or(0.0), + ) + }; + if usable.iter().any(|s| alloc(s).0 <= 0.0) { + return None; + } + let fits = usable.iter().any(|s| { + let (cpu, mem) = alloc(s); + let (own_cpu, own_mem) = own.get(&s.name).copied().unwrap_or_default(); + let free_cpu = cpu - s.report["requested"]["cpu"].as_f64().unwrap_or(0.0) + own_cpu; + let free_mem = mem - s.report["requested"]["memoryGi"].as_f64().unwrap_or(0.0) + own_mem; + need.cpu <= free_cpu + 0.01 && need.memory_gi <= free_mem + 0.01 + }); + if !fits { + return Some(format!( + "None of these servers has room for it. It needs about {} CPU and {} GB of memory.", + amount(need.cpu), + amount(need.memory_gi) + )); + } + None +} + +/// The cluster's servers (not being removed), with their tags and reports. +pub async fn servers( + tx: &mut Transaction<'_, Postgres>, + cluster_id: &str, +) -> ApiResult> { + let rows: Vec<(String, Vec, Value)> = sqlx::query_as( + "SELECT n.name, coalesce(t.tags, '{}'), coalesce(n.report, '{}') FROM pyo.servers n + LEFT JOIN pyo.server_tags t ON t.cluster_id = n.cluster_id AND t.name = n.name + WHERE n.cluster_id = $1 AND n.removal IS NULL", + ) + .bind(cluster_id) + .fetch_all(&mut **tx) + .await?; + Ok(rows + .into_iter() + .map(|(name, tags, report)| Server { name, tags, report }) + .collect()) +} + +/// Refuses a placement no server picked can run the service with `spec` +/// on: none left, its volume elsewhere, no GPU, no room (only with +/// `room`: a change of anything else isn't held back for room). `service_id` is +/// None for a service not made yet (no volumes or replicas of its own). +pub async fn check( + tx: &mut Transaction<'_, Postgres>, + cluster_id: &str, + service_id: Option<&str>, + spec: &Value, + room: bool, +) -> ApiResult<()> { + let p = Placement::of(spec); + if p.any() { + return Ok(()); + } + let servers = servers(tx, cluster_id).await?; + let mut volume = None; + let mut own: HashMap = HashMap::new(); + let r = &spec["resources"]; + let need = Need { + gpu: r["gpu"].as_u64().unwrap_or(0) > 0, + cpu: if room { + r["cpuRequest"].as_i64().unwrap_or(100).max(0) as f64 / 1000.0 + } else { + 0.0 + }, + memory_gi: if room { + r["memoryRequest"].as_i64().unwrap_or(128).max(0) as f64 / 1024.0 + } else { + 0.0 + }, + }; + if let Some(id) = service_id { + volume = pinned_volume(tx, cluster_id, id).await?; + let runtime: Value = + sqlx::query_scalar("SELECT coalesce(runtime, '{}') FROM pyo.services WHERE id = $1") + .bind(id) + .fetch_optional(&mut **tx) + .await? + .unwrap_or(Value::Null); + // What its replicas hold now, by what the live version asks for. + let old: Value = sqlx::query_scalar("SELECT spec FROM pyo.services WHERE id = $1") + .bind(id) + .fetch_optional(&mut **tx) + .await? + .unwrap_or(Value::Null); + let each = ( + old["resources"]["cpuRequest"] + .as_i64() + .unwrap_or(100) + .max(0) as f64 + / 1000.0, + old["resources"]["memoryRequest"] + .as_i64() + .unwrap_or(128) + .max(0) as f64 + / 1024.0, + ); + for rep in runtime["replicas"].as_array().into_iter().flatten() { + if let Some(s) = rep["server"].as_str().filter(|s| !s.is_empty()) { + let e = own.entry(s.to_owned()).or_default(); + e.0 += each.0; + e.1 += each.1; + } + } + } + let vol = volume.as_ref().map(|(n, s)| (n.as_str(), s.as_str())); + match refusal(&p, &servers, vol, need, &own) { + Some(why) => Err(ApiError::bad_request(why)), + None => Ok(()), + } +} + +/// One of the service's volumes whose data stays on one server's disk: +/// its name and that server. +async fn pinned_volume( + tx: &mut Transaction<'_, Postgres>, + cluster_id: &str, + service_id: &str, +) -> ApiResult> { + let rows: Vec<(String, Value)> = sqlx::query_as( + "SELECT data->>'name', data FROM pyo.volumes WHERE service_id = $1 AND NOT deleting ORDER BY created_at", + ) + .bind(service_id) + .fetch_all(&mut **tx) + .await?; + for (name, data) in rows { + if let Some(server) = crate::volumes::pinned_server(tx, cluster_id, &data).await? { + return Ok(Some((name, server))); + } + } + Ok(None) +} + +/// A placement change on a deployed service, live: its live deployment +/// takes the new placement (so a rollback to it or a failed rollout's +/// fallback keeps it) and the agent moves its workload in place. Returns +/// the cluster to wake, or None when nothing runs yet. +pub async fn go_live( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + spec: &Value, +) -> ApiResult> { + let (cluster_id, current): (String, Option) = + sqlx::query_as("SELECT cluster_id, current_deployment_id FROM pyo.services WHERE id = $1") + .bind(service_id) + .fetch_one(&mut **tx) + .await?; + let in_flight: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pyo.deployments WHERE service_id = $1 AND status NOT IN ('succeeded', 'failed', 'cancelled'))") + .bind(service_id) + .fetch_one(&mut **tx) + .await?; + if in_flight { + return Err(ApiError::conflict( + "A deploy is running. Change where it runs once it finishes.", + )); + } + let Some(current) = current else { + return Ok(None); + }; + let p = Placement::of(spec); + let live: Value = sqlx::query_scalar("SELECT spec FROM pyo.deployments WHERE id = $1") + .bind(¤t) + .fetch_one(&mut **tx) + .await?; + let mut live = live; + live_placement(&mut live, &p); + sqlx::query("UPDATE pyo.deployments SET spec = $2 WHERE id = $1") + .bind(¤t) + .bind(&live) + .execute(&mut **tx) + .await?; + // A static site runs on the cluster's static server, not on its own. + if !live["site"].is_null() { + return Ok(None); + } + let service = crate::ops::service_ref(tx, service_id).await?; + let cron_jobs: Vec = + serde_json::from_value(spec["cronJobs"].clone()).unwrap_or_default(); + crate::deploy::enqueue( + tx, + &cluster_id, + Command::Place { + service, + server_names: p.servers, + server_tags: p.tags, + cron_jobs, + }, + ) + .await?; + Ok(Some(cluster_id)) +} + +/// A stored rollout spec (a `DeploySpec`) with this placement: its servers +/// and tags, and no tag labels left in its node selector. +pub fn live_placement(deploy_spec: &mut Value, p: &Placement) { + deploy_spec["serverNames"] = json!(p.servers); + deploy_spec["serverTags"] = json!(p.tags); + if let Some(sel) = deploy_spec + .get_mut("nodeSelector") + .and_then(Value::as_object_mut) + { + sel.retain(|k, _| !k.starts_with(pyo_proto::TAG_LABEL_PREFIX)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn server(name: &str, tags: &[&str], report: Value) -> Server { + Server { + name: name.into(), + tags: tags.iter().map(|t| t.to_string()).collect(), + report, + } + } + + fn room(cpu: f64, mem: f64, used: (f64, f64)) -> Value { + json!({ "status": "ready", "allocatable": { "cpu": cpu, "memoryGi": mem }, "requested": { "cpu": used.0, "memoryGi": used.1 } }) + } + + fn cluster() -> Vec { + let mut gpu = room(16.0, 64.0, (1.0, 2.0)); + gpu["gpuDetected"] = json!(true); + vec![ + server("server-1", &["eu"], room(4.0, 4.0, (1.0, 1.0))), + server("gpu-box", &["gpu"], gpu), + server("small-1", &[], room(2.0, 2.0, (1.9, 1.9))), + ] + } + + fn pick(servers: &[&str], tags: &[&str]) -> Placement { + Placement { + servers: servers.iter().map(|s| s.to_string()).collect(), + tags: tags.iter().map(|s| s.to_string()).collect(), + } + } + + const SMALL: Need = Need { + gpu: false, + cpu: 0.1, + memory_gi: 0.125, + }; + + #[test] + fn old_server_tags_read_as_tags_picked() { + let p = Placement::of(&json!({ "serverTags": ["gpu", "GPU", "eu"], "servers": ["a"] })); + assert_eq!(p, pick(&["a"], &["gpu", "eu"])); + // A placement saved wins over what's left of the old fields. + let p = Placement::of(&json!({ "placement": null, "serverTags": ["gpu"] })); + assert!(p.any()); + let p = Placement::of(&json!({ "placement": { "tags": ["eu"] }, "serverTags": ["gpu"] })); + assert_eq!(p, pick(&[], &["eu"])); + assert!(Placement::of(&json!({})).any()); + } + + #[test] + fn saved_as_placement_only() { + let mut spec = json!({ "name": "web", "serverTags": ["gpu"], "servers": [] }); + normalize(&mut spec).unwrap(); + assert_eq!( + spec, + json!({ "name": "web", "placement": { "servers": [], "tags": ["gpu"] } }) + ); + // Any server: nothing kept. + let mut spec = json!({ "name": "web", "placement": { "servers": [], "tags": [] }, "serverTags": ["gpu"] }); + normalize(&mut spec).unwrap(); + assert_eq!(spec, json!({ "name": "web" })); + let mut spec = json!({ "placement": { "tags": ["no way"] } }); + assert!(normalize(&mut spec).is_err()); + } + + #[test] + fn servers_and_tags_add_up() { + let p = pick(&["small-1"], &["gpu"]); + assert!(p.takes("small-1", &[])); + assert!(p.takes("gpu-box", &["gpu".into()])); + assert!(p.takes("later", &["gpu".into()]), "tagged later"); + assert!(!p.takes("server-1", &["eu".into()])); + assert!(Placement::default().takes("anything", &[])); + } + + #[test] + fn any_server_is_never_refused() { + let need = Need { + gpu: true, + cpu: 99.0, + memory_gi: 99.0, + }; + assert_eq!( + refusal( + &Placement::default(), + &cluster(), + Some(("data", "x")), + need, + &HashMap::new() + ), + None + ); + } + + #[test] + fn an_empty_set_is_refused() { + let why = refusal( + &pick(&[], &["arm"]), + &cluster(), + None, + SMALL, + &HashMap::new(), + ); + assert_eq!( + why.as_deref(), + Some("No server has the tag arm yet. Tag one first, or pick servers.") + ); + let why = refusal( + &pick(&["gone"], &[]), + &cluster(), + None, + SMALL, + &HashMap::new(), + ); + assert_eq!(why.as_deref(), Some("gone isn't a server of this cluster.")); + assert_eq!( + refusal( + &pick(&["server-1"], &[]), + &cluster(), + None, + SMALL, + &HashMap::new() + ), + None + ); + } + + #[test] + fn a_volume_keeps_its_server() { + let why = refusal( + &pick(&["small-1"], &[]), + &cluster(), + Some(("data", "server-1")), + SMALL, + &HashMap::new(), + ); + assert_eq!( + why.as_deref(), + Some("Its volume data lives on server-1, so it has to run there. Pick server-1 too.") + ); + // Picked through a tag it has: fine. + assert_eq!( + refusal( + &pick(&["small-1"], &["eu"]), + &cluster(), + Some(("data", "server-1")), + SMALL, + &HashMap::new() + ), + None + ); + } + + #[test] + fn a_gpu_service_needs_a_gpu_server() { + let gpu = Need { gpu: true, ..SMALL }; + let why = refusal( + &pick(&["server-1", "small-1"], &[]), + &cluster(), + None, + gpu, + &HashMap::new(), + ); + assert_eq!( + why.as_deref(), + Some("It asks for a GPU, and none of these servers has one. Pick a GPU server.") + ); + assert_eq!( + refusal( + &pick(&["server-1"], &["gpu"]), + &cluster(), + None, + gpu, + &HashMap::new() + ), + None + ); + // A server kept for GPU work takes nothing else. + let mut servers = cluster(); + servers[1].report["gpuDedicated"] = json!(true); + let why = refusal( + &pick(&["gpu-box"], &[]), + &servers, + None, + SMALL, + &HashMap::new(), + ); + assert!(why.unwrap().contains("only run services that use a GPU")); + } + + #[test] + fn no_room_is_refused_counting_what_it_gives_back() { + let big = Need { + gpu: false, + cpu: 0.5, + memory_gi: 0.5, + }; + let why = refusal( + &pick(&["small-1"], &[]), + &cluster(), + None, + big, + &HashMap::new(), + ); + assert_eq!( + why.as_deref(), + Some( + "None of these servers has room for it. It needs about 0.5 CPU and 0.5 GB of memory." + ) + ); + // Its own replica there now frees its share when it moves. + let own = HashMap::from([("small-1".to_owned(), (0.5, 0.5))]); + assert_eq!( + refusal(&pick(&["small-1"], &[]), &cluster(), None, big, &own), + None + ); + // A server that hasn't said what it has: not refused. + let mut servers = cluster(); + servers[2].report = json!({}); + assert_eq!( + refusal( + &pick(&["small-1"], &[]), + &servers, + None, + big, + &HashMap::new() + ), + None + ); + // A build-only server isn't one to run on. + servers[2].report = json!({ "builder": true }); + assert!( + refusal( + &pick(&["small-1"], &[]), + &servers, + None, + big, + &HashMap::new() + ) + .unwrap() + .contains("only run builds") + ); + } + + #[test] + fn the_live_version_takes_the_placement() { + let mut live = json!({ "image": "web:1", "nodeSelector": { "pyo/tag-fast": "true", "topology.kubernetes.io/region": "sg" }, "serverNames": ["a"] }); + live_placement(&mut live, &pick(&[], &["gpu"])); + assert_eq!(live["serverNames"], json!([])); + assert_eq!(live["serverTags"], json!(["gpu"])); + assert_eq!( + live["nodeSelector"], + json!({ "topology.kubernetes.io/region": "sg" }) + ); + assert_eq!(live["image"], "web:1"); + let d: pyo_proto::DeploySpec = serde_json::from_value(json!({ + "deploymentId": "dpl_1", "image": "web:1", "replicas": 1, "env": [], "ports": [], "domains": [], "volumes": [], + "service": { "serviceId": "svc_1", "name": "web", "namespace": "shop", "workloadKind": "Deployment" }, + "projectId": "prj_1", "timeoutSeconds": 60, + "resources": { "cpuRequest": 100, "cpuLimit": 500, "memoryRequest": 64, "memoryLimit": 128 }, + "healthCheck": { "type": "none", "path": "", "port": 0, "command": "", "initialDelaySeconds": 1, "periodSeconds": 1 }, + "serverTags": live["serverTags"], + })) + .unwrap(); + assert_eq!(d.server_tags, vec!["gpu".to_owned()]); + } +} diff --git a/crates/pyo-api/src/platform_import/mod.rs b/crates/pyo-api/src/platform_import/mod.rs index 4e40b053..641d35ab 100644 --- a/crates/pyo-api/src/platform_import/mod.rs +++ b/crates/pyo-api/src/platform_import/mod.rs @@ -75,6 +75,7 @@ const LIMIT: ratelimit::Limit = ratelimit::Limit { scope: "platform-import:user", max: 30, window_secs: 15 * 60, + backoff_cap_secs: 0, }; /// One request to the platform. @@ -1368,7 +1369,7 @@ fn runs_query(filter: &str) -> String { ) } -async fn load_run(db: &sqlx::PgPool, id: &str) -> ApiResult> { +async fn load_run<'e, E: sqlx::PgExecutor<'e>>(db: E, id: &str) -> ApiResult> { let row: Option = sqlx::query_as(sqlx::AssertSqlSafe(runs_query("id = $1"))) .bind(id) .fetch_optional(db) @@ -1553,10 +1554,10 @@ async fn finish( /// The run's team, for its owners and admins. async fn run_team(s: &AppState, user: &User, id: &str) -> ApiResult { - let run = load_run(&s.db, id) + let mut tx = crate::rls::begin(&s.db, user).await?; + let run = load_run(&mut *tx, id) .await? .ok_or_else(|| ApiError::not_found("Import"))?; - let mut tx = s.db.begin().await?; require_role(&mut tx, user, &run.team_id, Role::Admin).await?; tx.commit().await?; Ok(run) @@ -1605,15 +1606,15 @@ pub async fn list_runs( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; require_role(&mut tx, &user, &q.team_id, Role::Admin).await?; - tx.commit().await?; let rows: Vec = sqlx::query_as(sqlx::AssertSqlSafe(runs_query( "team_id = $1 ORDER BY created_at DESC LIMIT 20", ))) .bind(&q.team_id) - .fetch_all(&s.db) + .fetch_all(&mut *tx) .await?; + tx.commit().await?; let runs: Vec = rows.into_iter().map(Into::into).collect(); Ok(Json(json!({ "imports": runs }))) } @@ -1762,6 +1763,7 @@ async fn create( volumes, vec![], &mut wake, + None, ) .await?; Ok::<_, ApiError>((pid, id)) @@ -1849,6 +1851,7 @@ async fn create( volumes, vec![], &mut wake, + None, ) .await?; } @@ -2182,6 +2185,7 @@ async fn first_deploy(s: &AppState, user: &User, service_id: &str) -> ApiResult< rollback_of: None, retry_of: None, commit: None, + upload: None, }, ) .await?; diff --git a/crates/pyo-api/src/previews/bot.rs b/crates/pyo-api/src/previews/bot.rs new file mode 100644 index 00000000..a81492bf --- /dev/null +++ b/crates/pyo-api/src/previews/bot.rs @@ -0,0 +1,383 @@ +//! What the bot says on a pull request, worked out from the previews alone +//! (no calls here): the comment, the check, each deployment's state. + +use serde_json::{Value, json}; + +/// A preview as people see it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shown { + /// Over the service's limit: starts when another preview goes. + Waiting, + Building, + Ready, + Failed, + /// Its copy is going. + Removing, + Removed, +} + +impl Shown { + /// From a preview's state and its latest deployment's status. + pub fn of(state: &str, deployment: Option<&str>, copy_left: bool) -> Shown { + match state { + "waiting" => Shown::Waiting, + "failed" => Shown::Failed, + "removed" if copy_left => Shown::Removing, + "removed" => Shown::Removed, + _ => match deployment { + Some("succeeded") => Shown::Ready, + Some("failed" | "cancelled") => Shown::Failed, + // Queued, building, rolling out, or not deployed yet. + _ => Shown::Building, + }, + } + } + + /// The dashboard's word (`Preview.status`). + pub fn key(self) -> &'static str { + match self { + Shown::Waiting => "waiting", + Shown::Building => "building", + Shown::Ready => "ready", + Shown::Failed => "failed", + Shown::Removing => "removing", + Shown::Removed => "removed", + } + } + + pub fn word(self) -> &'static str { + match self { + Shown::Waiting => "Waiting", + Shown::Building => "Building", + Shown::Ready => "Ready", + Shown::Failed => "Failed", + Shown::Removing | Shown::Removed => "Removed", + } + } + + fn gone(self) -> bool { + matches!(self, Shown::Removing | Shown::Removed) + } + + /// GitHub's deployment status for it. + pub fn github_deployment(self) -> &'static str { + match self { + Shown::Waiting => "queued", + Shown::Building => "in_progress", + Shown::Ready => "success", + Shown::Failed => "failure", + Shown::Removing | Shown::Removed => "inactive", + } + } + + /// GitLab's deployment status for it (none while it waits). + pub fn gitlab_deployment(self) -> Option<&'static str> { + match self { + Shown::Waiting => None, + Shown::Building => Some("running"), + Shown::Ready => Some("success"), + Shown::Failed => Some("failed"), + Shown::Removing | Shown::Removed => Some("canceled"), + } + } +} + +/// One line of the bot's table. +#[derive(Debug, Clone, PartialEq)] +pub struct Row { + pub service: String, + pub shown: Shown, + /// https://… when it has a URL. + pub url: Option, + /// Why it waits, failed or was removed. + pub message: Option, + /// When it last changed (ms). + pub updated_ms: i64, + /// Its deployment in the dashboard. + pub logs: Option, +} + +/// The hidden mark that finds the bot's comment again. +pub fn marker(team_id: &str) -> String { + format!("") +} + +/// "Nov 20, 14:05 UTC". +fn when(ms: i64) -> String { + match jiff::Timestamp::from_millisecond(ms) { + Ok(t) => t.strftime("%b %-d, %H:%M UTC").to_string(), + Err(_) => String::new(), + } +} + +/// Text that can't break the table: no pipes, no new lines, kept short. +fn cell(s: &str) -> String { + let one: String = s + .replace(['\r', '\n'], " ") + .replace('|', "\\|") + .chars() + .take(160) + .collect(); + one.trim().to_owned() +} + +/// The comment: a table of the previews, or "Preview removed" once the pull +/// request closed or none is left. +pub fn comment(team_id: &str, rows: &[Row], open: bool) -> String { + let mut out = format!("{}\n", marker(team_id)); + let live: Vec<&Row> = rows.iter().filter(|r| !r.shown.gone()).collect(); + if !open || live.is_empty() { + out.push_str("**Preview removed**\n"); + if !rows.is_empty() { + let names: Vec = rows + .iter() + .map(|r| format!("`{}`", cell(&r.service))) + .collect(); + out.push_str(&format!("\nServices: {}\n", names.join(", "))); + } + return out; + } + out.push_str( + "**Preview**\n\n| Service | Status | URL | Updated | |\n| :-- | :-- | :-- | :-- | :-- |\n", + ); + for r in live { + let status = match (&r.message, r.shown) { + (Some(m), Shown::Failed | Shown::Waiting) if !m.is_empty() => { + format!("{} ({})", r.shown.word(), cell(m)) + } + _ => r.shown.word().to_owned(), + }; + let url = match (&r.url, r.shown) { + (Some(u), Shown::Ready) => format!("[{}]({u})", u.trim_start_matches("https://")), + (Some(u), _) => u.trim_start_matches("https://").to_owned(), + (None, _) => String::new(), + }; + let logs = r + .logs + .as_ref() + .map(|l| format!("[Logs]({l})")) + .unwrap_or_default(); + out.push_str(&format!( + "| {} | {status} | {url} | {} | {logs} |\n", + cell(&r.service), + when(r.updated_ms) + )); + } + out +} + +/// The check run ("Pyo · Preview") for the head: GitHub's status and +/// conclusion, with a title and a summary. +#[derive(Debug, Clone, PartialEq)] +pub struct Check { + /// "in_progress" or "completed". + pub status: &'static str, + /// "success", "failure" or "neutral" once completed. + pub conclusion: Option<&'static str>, + pub title: String, + pub summary: String, +} + +pub const CHECK_NAME: &str = "Pyo · Preview"; + +pub fn check(rows: &[Row]) -> Check { + let live: Vec<&Row> = rows.iter().filter(|r| !r.shown.gone()).collect(); + let count = |s: Shown| live.iter().filter(|r| r.shown == s).count(); + let (building, failed, ready) = ( + count(Shown::Building), + count(Shown::Failed), + count(Shown::Ready), + ); + let (status, conclusion, title) = if building > 0 { + ("in_progress", None, "Building".to_owned()) + } else if failed > 0 { + let names: Vec<&str> = live + .iter() + .filter(|r| r.shown == Shown::Failed) + .map(|r| r.service.as_str()) + .collect(); + ( + "completed", + Some("failure"), + format!("Failed: {}", names.join(", ")), + ) + } else if ready > 0 { + ("completed", Some("success"), "Ready".to_owned()) + } else if live.is_empty() { + ("completed", Some("neutral"), "Removed".to_owned()) + } else { + ("completed", Some("neutral"), "Waiting".to_owned()) + }; + let summary = live + .iter() + .map(|r| { + let mut line = format!("- {}: {}", r.service, r.shown.word()); + if let Some(u) = &r.url { + line.push_str(&format!(" ({u})")); + } + if let Some(m) = r.message.as_ref().filter(|m| !m.is_empty()) + && matches!(r.shown, Shown::Failed | Shown::Waiting) + { + line.push_str(&format!(". {}", m.trim_end_matches('.'))); + } + line + }) + .collect::>() + .join("\n"); + Check { + status, + conclusion, + title, + summary, + } +} + +impl Check { + /// GitHub's check run body (`details_url`: the first logs link). + pub fn github(&self, sha: &str, details: Option<&str>) -> Value { + let mut v = json!({ + "name": CHECK_NAME, + "head_sha": sha, + "status": self.status, + "output": { "title": self.title, "summary": if self.summary.is_empty() { "No previews." } else { &self.summary } }, + }); + if let Some(c) = self.conclusion { + v["conclusion"] = json!(c); + } + if let Some(d) = details { + v["details_url"] = json!(d); + } + v + } + + /// GitLab's commit status state. + pub fn gitlab_state(&self) -> &'static str { + match (self.status, self.conclusion) { + ("in_progress", _) => "running", + (_, Some("success")) => "success", + (_, Some("failure")) => "failed", + _ => "skipped", + } + } +} + +/// A short hash of what's said, to say it only when it changed. +pub fn hash(v: &str) -> String { + crate::ids::sha256_hex(v)[..16].to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(service: &str, shown: Shown) -> Row { + Row { + service: service.into(), + shown, + url: Some(format!("https://{service}-pr-42.203.0.113.7.nip.io")), + message: None, + updated_ms: 1_795_000_000_000, + logs: Some(format!( + "https://pyo.example.com/acme/deployments/dpl_{service}" + )), + } + } + + #[test] + fn statuses_from_deployments() { + assert_eq!(Shown::of("active", None, true), Shown::Building); + assert_eq!(Shown::of("active", Some("queued"), true), Shown::Building); + assert_eq!(Shown::of("active", Some("building"), true), Shown::Building); + assert_eq!(Shown::of("active", Some("succeeded"), true), Shown::Ready); + assert_eq!(Shown::of("active", Some("failed"), true), Shown::Failed); + assert_eq!(Shown::of("active", Some("cancelled"), true), Shown::Failed); + assert_eq!(Shown::of("failed", None, false), Shown::Failed); + assert_eq!(Shown::of("waiting", None, false), Shown::Waiting); + assert_eq!( + Shown::of("removed", Some("succeeded"), true), + Shown::Removing + ); + assert_eq!( + Shown::of("removed", Some("succeeded"), false), + Shown::Removed + ); + } + + #[test] + fn deployment_states_on_each_provider() { + assert_eq!(Shown::Building.github_deployment(), "in_progress"); + assert_eq!(Shown::Ready.github_deployment(), "success"); + assert_eq!(Shown::Failed.github_deployment(), "failure"); + assert_eq!(Shown::Removed.github_deployment(), "inactive"); + assert_eq!(Shown::Waiting.github_deployment(), "queued"); + assert_eq!(Shown::Building.gitlab_deployment(), Some("running")); + assert_eq!(Shown::Ready.gitlab_deployment(), Some("success")); + assert_eq!(Shown::Failed.gitlab_deployment(), Some("failed")); + assert_eq!(Shown::Removing.gitlab_deployment(), Some("canceled")); + assert_eq!(Shown::Waiting.gitlab_deployment(), None); + } + + #[test] + fn the_comment_is_a_table() { + let mut failed = row("api", Shown::Failed); + failed.message = Some("The build failed | exit 1\nsee logs".into()); + let c = comment( + "team_1", + &[row("web", Shown::Ready), failed, row("old", Shown::Removed)], + true, + ); + assert!(c.starts_with("\n"), "{c}"); + assert!(c.contains("| web | Ready | [web-pr-42.203.0.113.7.nip.io](https://web-pr-42.203.0.113.7.nip.io) |"), "{c}"); + // A message can't break the table. + assert!( + c.contains("| api | Failed (The build failed \\| exit 1 see logs) |"), + "{c}" + ); + assert!( + c.contains("[Logs](https://pyo.example.com/acme/deployments/dpl_web)"), + "{c}" + ); + assert!(!c.contains("| old |"), "removed ones aren't listed: {c}"); + assert!(c.contains("Nov "), "{c}"); + assert_eq!( + c.lines().filter(|l| l.starts_with("| ")).count(), + 4, + "header, rule and two rows" + ); + } + + #[test] + fn closed_says_removed() { + let rows = [row("web", Shown::Ready), row("api", Shown::Building)]; + let c = comment("team_1", &rows, false); + assert!(c.contains("**Preview removed**"), "{c}"); + assert!(c.contains("`web`, `api`"), "{c}"); + assert!(!c.contains("| web |"), "{c}"); + // All removed while open: the same. + let gone = [row("web", Shown::Removed)]; + assert!(comment("team_1", &gone, true).contains("**Preview removed**")); + } + + #[test] + fn check_states() { + let c = check(&[row("web", Shown::Ready), row("api", Shown::Building)]); + assert_eq!((c.status, c.conclusion), ("in_progress", None)); + assert_eq!(c.gitlab_state(), "running"); + let c = check(&[row("web", Shown::Ready), row("api", Shown::Failed)]); + assert_eq!((c.status, c.conclusion), ("completed", Some("failure"))); + assert_eq!(c.title, "Failed: api"); + assert_eq!(c.gitlab_state(), "failed"); + let c = check(&[row("web", Shown::Ready)]); + assert_eq!(c.conclusion, Some("success")); + assert_eq!(c.gitlab_state(), "success"); + let c = check(&[row("web", Shown::Waiting)]); + assert_eq!(c.conclusion, Some("neutral")); + assert_eq!(c.gitlab_state(), "skipped"); + let body = check(&[row("web", Shown::Ready)]).github("abc", Some("https://x")); + assert_eq!(body["name"], "Pyo · Preview"); + assert_eq!(body["conclusion"], "success"); + assert_eq!(body["details_url"], "https://x"); + let building = check(&[row("web", Shown::Building)]).github("abc", None); + assert!(building.get("conclusion").is_none()); + } +} diff --git a/crates/pyo-api/src/previews/domain.rs b/crates/pyo-api/src/previews/domain.rs new file mode 100644 index 00000000..cb8fa9b3 --- /dev/null +++ b/crates/pyo-api/src/previews/domain.rs @@ -0,0 +1,635 @@ +//! Where previews are reached, and a cluster's preview domain. +//! +//! - Private previews: the cluster's tailnet (`web-pr-42..ts.net`), +//! a Tailscale Service its agent makes as for any tailnet domain. +//! - Else the cluster's preview domain when it has one +//! (`web-pr-42.preview.example.com`): a wildcard record points at the +//! cluster's public IP. With the team's Cloudflare covering the domain, +//! Pyo makes that record and gets a wildcard certificate (DNS-01, as for +//! sandbox edges), kept with the team's certificates and renewed 30 +//! days before it runs out. Without, each preview gets its own +//! 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`). +//! +//! A domain is per cluster: its wildcard record can point at one cluster. + +use std::{net::Ipv4Addr, time::Duration}; + +use instant_acme::RetryPolicy; +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use super::{Settings, naming}; +use crate::{ + AppState, + auth::User, + cloudflare::{self, Cloudflare}, + error::{ApiError, ApiResult}, + ops::{Role, log_activity, require_role}, +}; + +/// A preview's domain on its copy, as the dashboard makes domains. +pub fn new_domain(host: &str, port: &str) -> Value { + json!({ + "id": crate::ids::new_id("dom"), "hostname": host, "portName": port, + "status": "pending_dns", "tls": "pending", "tlsMode": "auto", + "redirectHttps": !crate::deploy::private_host(host), + "createdAt": pyo_proto::now_ms(), + }) +} + +/// The cluster's preview domain as stored. +async fn stored(tx: &mut Transaction<'_, Postgres>, cluster_id: &str) -> ApiResult { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT preview_domain FROM pyo.clusters WHERE id = $1", + ) + .bind(cluster_id) + .fetch_optional(&mut **tx) + .await? + .flatten() + .unwrap_or(Value::Null)) +} + +/// A domain under the cluster's preview domain uses its wildcard +/// certificate once there is one; else its own (Let's Encrypt). +pub async fn with_certificate( + tx: &mut Transaction<'_, Postgres>, + cluster_id: &str, + mut d: Value, +) -> ApiResult { + let pd = stored(tx, cluster_id).await?; + let host = d["hostname"].as_str().unwrap_or("").to_owned(); + let under = pd["domain"] + .as_str() + .is_some_and(|dom| host.ends_with(&format!(".{dom}"))); + match pd["certificateId"].as_str() { + Some(cert) if under && pd["certificate"]["state"] == json!("issued") => { + d["tlsMode"] = json!("custom"); + d["certificateId"] = json!(cert); + } + _ => { + if d["tlsMode"] == json!("custom") { + d["tlsMode"] = json!("auto"); + } + if let Some(o) = d.as_object_mut() { + o.remove("certificateId"); + } + } + } + Ok(d) +} + +/// The suffix of a preview's URL on the cluster, or why it has none. +async fn suffix( + tx: &mut Transaction<'_, Postgres>, + cluster_id: &str, + settings: &Settings, +) -> ApiResult> { + if settings.access == "private" { + let t = crate::tailscale::of(&mut **tx, cluster_id).await?; + return Ok(match t.and_then(|t| t.suffix) { + Some(s) => Ok(s), + 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())); + } + 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()), + }, + ) +} + +/// Whether a host is taken: by a service's domain (not `copy`), or by +/// another preview that isn't removed. Any team's. +async fn taken( + tx: &mut Transaction<'_, Postgres>, + host: &str, + preview_id: &str, + copy: Option<&str>, +) -> ApiResult { + let lifted = crate::rls::lift(tx).await?; + let taken: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.services a, jsonb_array_elements(coalesce(a.spec->'domains', '[]')) d + WHERE NOT a.deleting AND lower(d->>'hostname') = $1 AND a.id IS DISTINCT FROM $3) + OR EXISTS (SELECT 1 FROM pyo.previews WHERE hostname = $1 AND id <> $2 AND state <> 'removed')", + ) + .bind(host) + .bind(preview_id) + .bind(copy) + .fetch_one(&mut **tx) + .await?; + lifted.lower(tx).await?; + Ok(taken) +} + +/// A preview's URL host: the one it had while it still fits where its +/// previews go now, else `-pr-` there (told apart by a short +/// hash when another has it). The inner error says why there's none. +#[allow(clippy::too_many_arguments)] +pub async fn host_for( + tx: &mut Transaction<'_, Postgres>, + cluster_id: &str, + settings: &Settings, + service: &str, + number: i64, + service_id: &str, + current: Option<&str>, + preview_id: &str, + copy: Option<&str>, +) -> ApiResult, String>> { + let suffix = match suffix(tx, cluster_id, settings).await? { + Ok(s) => s.to_ascii_lowercase(), + Err(why) => return Ok(Err(why)), + }; + if let Some(h) = current + && h.ends_with(&format!(".{suffix}")) + && !taken(tx, h, preview_id, copy).await? + { + return Ok(Ok(Some(h.to_owned()))); + } + for label in [ + naming::label(service, number, naming::LABEL_MAX), + naming::label_salted(service, number, naming::LABEL_MAX, service_id), + ] { + let h = naming::host(&label, &suffix); + if h.len() <= 253 && !taken(tx, &h, preview_id, copy).await? { + return Ok(Ok(Some(h))); + } + } + Ok(Err("Another service has this preview's address.".into())) +} + +// ── The cluster's preview domain ─────────────────────────────────────────── + +/// For the dashboard: the domain, the wildcard record to make (at the +/// cluster's public IP), whether Pyo makes it in Cloudflare, and the +/// wildcard certificate. +pub fn show(stored: &Value, public_ip: Option) -> Value { + let Some(domain) = stored["domain"].as_str() else { + return Value::Null; + }; + let cf = stored["dns"] == json!("cloudflare"); + json!({ + "domain": domain, + "record": { "name": format!("*.{domain}"), "type": "A", "content": public_ip.map(|i| i.to_string()) }, + "dns": if cf { "cloudflare" } else { "manual" }, + "certificate": if cf && stored["certificate"].is_object() { + json!({ + "state": stored["certificate"]["state"], + "notAfter": stored["certificate"]["notAfter"], + "error": stored["certificate"]["error"], + }) + } else { Value::Null }, + "error": stored["record"]["error"], + }) +} + +/// A preview domain as typed: a hostname of two labels or more, not one of +/// the free or tailnet ones. +pub fn parse(domain: &str) -> ApiResult { + let d = domain + .trim() + .trim_end_matches('.') + .trim_start_matches("*.") + .to_ascii_lowercase(); + if !crate::util::hostname(&d) { + return Err(ApiError::bad_request( + "Give a domain like preview.example.com.", + )); + } + if [".nip.io", ".sslip.io", ".ts.net"] + .iter() + .any(|s| d.ends_with(s) || d == s[1..]) + { + return Err(ApiError::bad_request( + "Use a domain of your own. Previews get a nip.io address without one.", + )); + } + Ok(d) +} + +/// setClusterPreviewDomain: sets the cluster's preview domain (None +/// removes it). Running previews keep their address until the next push. +pub async fn set( + tx: &mut Transaction<'_, Postgres>, + user: &User, + cluster_id: &str, + domain: Option<&str>, +) -> ApiResult { + let team = crate::ops::team_of(tx, "clusters", cluster_id).await?; + require_role(tx, user, &team, Role::Admin).await?; + let domain = match domain.map(str::trim).filter(|d| !d.is_empty()) { + Some(d) => Some(parse(d)?), + None => None, + }; + let before = stored(tx, cluster_id).await?; + if let Some(d) = &domain { + let lifted = crate::rls::lift(tx).await?; + let other: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.clusters WHERE id <> $1 AND preview_domain->>'domain' = $2)", + ) + .bind(cluster_id) + .bind(d) + .fetch_one(&mut **tx) + .await?; + lifted.lower(tx).await?; + if other { + return Err(ApiError::conflict(format!( + "{d} is the preview domain of another cluster." + ))); + } + // Where teams don't trust each other (Pyo Cloud): theirs only. + if crate::verify_domains() && !crate::domainproof::proven(&team, d).await { + return Err(ApiError::forbidden(crate::domainproof::how_to(&team, d))); + } + } + let value = match &domain { + // The same domain keeps its certificate and record. + Some(d) if before["domain"].as_str() == Some(d) => before.clone(), + Some(d) => json!({ "domain": d }), + None => Value::Null, + }; + sqlx::query("UPDATE pyo.clusters SET preview_domain = $2 WHERE id = $1") + .bind(cluster_id) + .bind(if value.is_null() { None } else { Some(&value) }) + .execute(&mut **tx) + .await?; + 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, + &user.name, + "cluster.updated", + "info", + &match &domain { + Some(d) => format!("Previews on {name} use {d}"), + None => format!("Previews on {name} use nip.io"), + }, + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({}), + ) + .await?; + Ok(json!({ "ok": true })) +} + +/// A wildcard certificate that failed is tried again after this long. +const RETRY_MS: i64 = 6 * 3600 * 1000; +/// One still "issuing" after this long was cut off. +const STALE_MS: i64 = 15 * 60 * 1000; + +/// For each cluster's preview domain in a zone of the team's Cloudflare: +/// the wildcard record at its public IP, and the wildcard certificate (got, +/// renewed, retried after a failure). Without Cloudflare: nothing to do. +pub async fn tick(s: &AppState) -> ApiResult<()> { + let rows: Vec<(String, String, Value)> = sqlx::query_as( + "SELECT id, team_id, preview_domain FROM pyo.clusters WHERE preview_domain IS NOT NULL", + ) + .fetch_all(&s.db) + .await?; + for (cluster, team, pd) in rows { + if let Err(e) = one(s, &cluster, &team, pd).await { + tracing::info!(%cluster, error = %e.message, "previews: preview domain"); + } + } + Ok(()) +} + +async fn one(s: &AppState, cluster: &str, team: &str, mut pd: Value) -> ApiResult<()> { + let Some(domain) = pd["domain"].as_str().map(str::to_owned) else { + return Ok(()); + }; + let mut tx = s.db.begin().await?; + let account = cloudflare::account(s, &mut tx, team).await?; + let ip = crate::freedomain::load(&mut tx, cluster) + .await? + .and_then(|(_, c)| c.public_ip()); + let marker = cloudflare::marker(&cloudflare::install_id(&mut tx).await?); + tx.commit().await?; + let zone = account.as_ref().and_then(|a| { + cloudflare::zone_for(&format!("x.{domain}"), &a.zones) + .filter(|z| z.can_edit) + .cloned() + }); + let (Some(account), Some(zone)) = (account, zone) else { + if pd["dns"] == json!("cloudflare") { + pd["dns"] = json!("manual"); + save(s, cluster, &pd).await?; + } + return Ok(()); + }; + let before = pd.clone(); + pd["dns"] = json!("cloudflare"); + let cf = cloudflare::Http::new(&account.token)?; + let now = pyo_proto::now_ms(); + // The wildcard record, at the public IP (Pyo's old ones go first). + if let Some(ip) = ip.map(|i| i.to_string()) + && (pd["record"]["content"] != json!(ip) + || (pd["record"]["state"] != json!("ok") + && now - pd["record"]["at"].as_i64().unwrap_or(0) > 600_000)) + { + let name = format!("*.{domain}"); + if let Ok(found) = cf.records(&zone.id, &name).await { + for r in found + .iter() + .filter(|r| cloudflare::ours(r, &marker, &name) && r.kind == "A" && r.content != ip) + { + let _ = cf.delete(&zone.id, &r.id).await; + } + } + let out = crate::sandbox::edgecert::ensure_wildcard( + &cf, + &zone.id, + &name, + &[("A".to_owned(), ip.clone())], + &marker, + ) + .await; + pd["record"] = match out { + Ok(o) if o.status == "conflict" => json!({ + "content": ip, "state": "conflict", "at": now, + "error": format!("{name} has other records in Cloudflare. Remove them or point them at {ip}."), + }), + Ok(_) => json!({ "content": ip, "state": "ok", "at": now }), + Err(e) => { + json!({ "content": ip, "state": "failed", "at": now, "error": e.to_string() }) + } + }; + } + // The wildcard certificate. + let cert = &pd["certificate"]; + let state = cert["state"].as_str().unwrap_or(""); + let at = cert["at"].as_i64().unwrap_or(0); + let due = match state { + "issuing" => now - at > STALE_MS, + "failed" => now - at > RETRY_MS, + "issued" => crate::sandbox::edgecert::due( + cert["notBefore"].as_i64().unwrap_or(0) / 1000, + cert["notAfter"].as_i64().unwrap_or(0) / 1000, + now / 1000, + ), + _ => true, + }; + if due && s.sealer.enabled() { + pd["certificate"]["state"] = json!("issuing"); + pd["certificate"]["at"] = json!(now); + save(s, cluster, &pd).await?; + let (s2, c2, t2, d2, z2, tok) = ( + s.clone(), + cluster.to_owned(), + team.to_owned(), + domain.clone(), + zone.id.clone(), + account.token.clone(), + ); + tokio::spawn(async move { + let out = issue(&s2, &c2, &t2, &d2, &z2, &tok, &marker).await; + if let Err(e) = &out { + tracing::warn!(cluster = %c2, error = %e, "previews: wildcard certificate"); + } + if let Err(e) = issued(&s2, &c2, &t2, &d2, out).await { + tracing::warn!(cluster = %c2, error = %e.message, "previews: keeping the wildcard certificate"); + } + }); + return Ok(()); + } + if pd != before { + save(s, cluster, &pd).await?; + } + Ok(()) +} + +async fn save(s: &AppState, cluster: &str, pd: &Value) -> ApiResult<()> { + // Only while it's still the same domain (it may have been changed). + sqlx::query("UPDATE pyo.clusters SET preview_domain = $2 WHERE id = $1 AND preview_domain->>'domain' = $2->>'domain'") + .bind(cluster) + .bind(pd) + .execute(&s.db) + .await?; + Ok(()) +} + +/// Gets `*.` from Let's Encrypt with a DNS-01 challenge in the zone. +async fn issue( + s: &AppState, + _cluster: &str, + _team: &str, + domain: &str, + zone_id: &str, + token: &str, + marker: &str, +) -> Result { + use crate::sandbox::edgecert; + let client = crate::outbound::client( + crate::outbound::Reach::installation(), + Duration::from_secs(30), + ) + .map_err(|e| e.to_string())?; + let account = edgecert::account(s, client, &edgecert::directory_url()) + .await + .map_err(|e| e.message)?; + let cf = cloudflare::Http::new(token).map_err(|e| e.message)?; + let doh = crate::outbound::client( + crate::outbound::Reach { private: false }, + Duration::from_secs(10), + ) + .map_err(|e| e.to_string())?; + let retry = RetryPolicy::new() + .initial_delay(Duration::from_secs(2)) + .timeout(Duration::from_secs(180)); + let got = edgecert::obtain( + &account, + &cf, + zone_id, + marker, + domain, + &edgecert::DnsOverHttps(doh), + &retry, + ) + .await?; + edgecert::check(&got, domain, pyo_proto::now_ms() / 1000) +} + +/// Keeps a wildcard certificate with the team's certificates (the same one +/// renewed in place), and points the cluster's previews under the domain +/// at it, live. Or keeps why it failed. +async fn issued( + s: &AppState, + cluster: &str, + team: &str, + domain: &str, + out: Result, +) -> ApiResult<()> { + let mut tx = s.db.begin().await?; + let mut pd = stored(&mut tx, cluster).await?; + if pd["domain"].as_str() != Some(domain) { + return Ok(()); + } + let now = pyo_proto::now_ms(); + let p = match out { + Ok(p) => p, + Err(e) => { + pd["certificate"] = json!({ "state": "failed", "at": now, "error": e, "notAfter": pd["certificate"]["notAfter"], "notBefore": pd["certificate"]["notBefore"] }); + sqlx::query("UPDATE pyo.clusters SET preview_domain = $2 WHERE id = $1") + .bind(cluster) + .bind(&pd) + .execute(&mut *tx) + .await?; + tx.commit().await?; + return Ok(()); + } + }; + let sealed = crate::vault::get() + .seal_credential(team, &p.key_pem) + .await?; + let existing: Option = match pd["certificateId"].as_str() { + Some(id) => { + sqlx::query_scalar("SELECT id FROM pyo.certificates WHERE id = $1 AND team_id = $2") + .bind(id) + .bind(team) + .fetch_optional(&mut *tx) + .await? + } + None => None, + }; + let id = existing.unwrap_or_else(|| crate::ids::new_id("crt")); + 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(team) + .bind(format!("Previews (*.{domain})")) + .bind(&p.hostnames) + .bind(&p.issuer) + .bind(p.not_before as f64) + .bind(p.not_after as f64) + .bind(&p.fingerprint) + .bind(&p.chain_pem) + .bind(&sealed) + .execute(&mut *tx) + .await?; + pd["certificateId"] = json!(id); + pd["certificate"] = json!({ "state": "issued", "at": now, "notBefore": p.not_before * 1000, "notAfter": p.not_after * 1000, "error": null }); + sqlx::query("UPDATE pyo.clusters SET preview_domain = $2 WHERE id = $1") + .bind(cluster) + .bind(&pd) + .execute(&mut *tx) + .await?; + // The copies under the domain: on the wildcard certificate, live. + let copies: Vec<(String, Value)> = sqlx::query_as( + "SELECT id, coalesce(spec->'domains', '[]') FROM pyo.services WHERE cluster_id = $1 AND preview_of IS NOT NULL AND NOT deleting", + ) + .bind(cluster) + .fetch_all(&mut *tx) + .await?; + let mut wake = vec![]; + for (copy, domains) in copies { + let mut moved = Value::Array(vec![]); + let mut changed = false; + for d in domains.as_array().into_iter().flatten() { + let host = d["hostname"].as_str().unwrap_or(""); + let mut d = d.clone(); + // Under the domain: on the certificate (and a renewed one is + // fetched again with the sync). + if host.ends_with(&format!(".{domain}")) { + d["tlsMode"] = json!("custom"); + d["certificateId"] = json!(id); + changed = true; + } + if let Some(a) = moved.as_array_mut() { + a.push(d); + } + } + if !changed { + continue; + } + sqlx::query( + "UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1", + ) + .bind(©) + .bind(&moved) + .execute(&mut *tx) + .await?; + if let Some(c) = crate::routes::changed(&mut tx, ©, true).await? { + wake.push(c); + } + } + log_activity( + &mut tx, + team, + "Pyo", + "domain.certificate_replaced", + "success", + &format!("Got a certificate for *.{domain}"), + json!({ "kind": "certificate", "id": id, "label": format!("*.{domain}") }), + json!({}), + ) + .await?; + tx.commit().await?; + for c in wake { + s.wake(&c).await; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preview_domains_as_typed() { + assert_eq!( + parse(" Preview.Example.com. ").unwrap(), + "preview.example.com" + ); + assert_eq!( + parse("*.preview.example.com").unwrap(), + "preview.example.com" + ); + assert!(parse("localhost").is_err()); + assert!(parse("x.203.0.113.7.nip.io").is_err()); + assert!(parse("tail1234.ts.net").is_err()); + assert!(parse("bad_domain!.com").is_err()); + } + + #[test] + fn shown_with_the_record_to_make() { + let ip: Ipv4Addr = "203.0.113.7".parse().unwrap(); + assert_eq!(show(&Value::Null, Some(ip)), Value::Null); + let v = show(&json!({ "domain": "preview.example.com" }), Some(ip)); + assert_eq!(v["record"]["name"], "*.preview.example.com"); + assert_eq!(v["record"]["content"], "203.0.113.7"); + assert_eq!(v["dns"], "manual"); + assert_eq!(v["certificate"], Value::Null); + let v = show( + &json!({ "domain": "preview.example.com", "dns": "cloudflare", "certificate": { "state": "issued", "notAfter": 5, "at": 1 } }), + None, + ); + assert_eq!(v["dns"], "cloudflare"); + assert_eq!(v["certificate"]["state"], "issued"); + assert_eq!(v["record"]["content"], Value::Null); + } + + #[test] + fn new_domains_redirect_only_where_the_internet_reaches() { + let d = new_domain("web-pr-42.203.0.113.7.nip.io", "http"); + assert_eq!(d["redirectHttps"], true); + assert_eq!(d["tlsMode"], "auto"); + assert_eq!(d["status"], "pending_dns"); + assert!(d["id"].as_str().unwrap().starts_with("dom_")); + assert_eq!( + new_domain("web-pr-42.100.64.0.9.nip.io", "http")["redirectHttps"], + false + ); + } +} diff --git a/crates/pyo-api/src/previews/github.rs b/crates/pyo-api/src/previews/github.rs new file mode 100644 index 00000000..a3b4bb6e --- /dev/null +++ b/crates/pyo-api/src/previews/github.rs @@ -0,0 +1,908 @@ +//! Previews on GitHub, through Pyo's GitHub App (it shows as +//! `[bot]`): pull request events, the comment, the check run +//! "Pyo · Preview" and a deployment per preview ("View deployment"). +//! +//! The app needs Pull requests, Deployments and Checks (write) and the +//! Pull request event. An app made before previews doesn't have them: its +//! owner adds them in the app's settings, then each installation's owner +//! approves them once on GitHub. Pyo asks GitHub what each has +//! ([`check_all`]) and the dashboard links where to do it. + +use reqwest::{Method, StatusCode}; +use serde_json::{Value, json}; + +use super::{Pull, PullRow, Remote, bot}; +use crate::AppState; + +/// What previews need, as GitHub names the permissions, and as people +/// read them. +const NEEDED: [(&str, &str); 3] = [ + ("pull_requests", "Pull requests: write"), + ("deployments", "Deployments: write"), + ("checks", "Checks: write"), +]; + +/// The permissions a new app asks for (github.rs `manifest`). +pub fn manifest_permissions() -> Value { + json!({ + "contents": "read", "metadata": "read", "statuses": "write", + "pull_requests": "write", "deployments": "write", "checks": "write", + }) +} + +/// What's missing for previews, from what GitHub said the app (or an +/// installation) may do. Nothing while it hasn't been asked yet. +pub fn missing(permissions: &Value, events: &[String]) -> Vec { + if !permissions.is_object() { + return vec![]; + } + let mut out: Vec = NEEDED + .iter() + .filter(|(k, _)| permissions[*k] != json!("write")) + .map(|(_, shown)| (*shown).to_owned()) + .collect(); + if !events.iter().any(|e| e == "pull_request") { + out.push("Pull request events".into()); + } + out +} + +/// Where the app's owner changes its permissions and events. +pub fn app_settings_url(app: &crate::github::GithubApp) -> String { + if app.slug.is_empty() { + return String::new(); + } + match app.owner_type.as_str() { + "Organization" => format!( + "https://github.com/organizations/{}/settings/apps/{}/permissions", + app.owner, app.slug + ), + _ => format!("https://github.com/settings/apps/{}/permissions", app.slug), + } +} + +/// Where an installation's owner approves new permissions. +pub fn installation_url(account: &str, account_type: &str, id: i64) -> String { + match account_type { + "Organization" => { + format!("https://github.com/organizations/{account}/settings/installations/{id}") + } + _ => format!("https://github.com/settings/installations/{id}"), + } +} + +/// An installation in the snapshot: `missingPermissions` and `approveUrl` +/// instead of what GitHub said. +pub fn show_installation(i: &mut Value) { + let events: Vec = serde_json::from_value(i["events"].clone()).unwrap_or_default(); + let missing = missing(&i["permissions"], &events); + let url = installation_url( + i["account"].as_str().unwrap_or(""), + i["accountType"].as_str().unwrap_or(""), + i["id"].as_i64().unwrap_or(0), + ); + if let Some(o) = i.as_object_mut() { + o.remove("permissions"); + o.remove("events"); + o.insert("missingPermissions".into(), json!(missing)); + o.insert("approveUrl".into(), json!(url)); + } +} + +/// Asks GitHub what one installation may do now, and keeps it. +pub async fn check_installation(s: &AppState, id: i64) { + match crate::github::app_get(s, &format!("/app/installations/{id}")).await { + Ok(v) => { + let events: Vec = + serde_json::from_value(v["events"].clone()).unwrap_or_default(); + let r = sqlx::query("UPDATE pyo.github_installations SET permissions = $2, events = $3, checked_at = now() WHERE id = $1") + .bind(id) + .bind(&v["permissions"]) + .bind(&events) + .execute(&s.db) + .await; + if let Err(e) = r { + tracing::warn!(installation = id, error = %e, "previews: couldn't keep the installation's permissions"); + } + } + Err(e) => { + tracing::info!(installation = id, error = %format!("{e:#}"), "previews: couldn't ask GitHub about an installation") + } + } +} + +/// Asks GitHub what the app and each linked installation may do. +pub async fn check_all(s: &AppState) { + let Ok(Some(_)) = crate::github::app(&s.db).await else { + return; + }; + match crate::github::app_get(s, "/app").await { + Ok(v) => { + let fields = json!({ + "permissions": v["permissions"], + "events": v["events"], + "ownerType": v["owner"]["type"], + }); + let r = sqlx::query("UPDATE pyo.settings SET value = value || $1 WHERE key = 'github'") + .bind(fields) + .execute(&s.db) + .await; + if let Err(e) = r { + tracing::warn!(error = %e, "previews: couldn't keep the app's permissions"); + } + } + Err(e) => { + tracing::info!(error = %format!("{e:#}"), "previews: couldn't ask GitHub about the app") + } + } + let ids: Vec = sqlx::query_scalar("SELECT id FROM pyo.github_installations") + .fetch_all(&s.db) + .await + .unwrap_or_default(); + for id in ids { + check_installation(s, id).await; + } +} + +// ── Events ───────────────────────────────────────────────────────────────── + +/// A pull request from GitHub's API or a `pull_request` event (its +/// `pull_request` object). None when it's not one Pyo can use. +pub fn pull_of(pr: &Value, installation_id: i64) -> Option { + let base_repo = pr["base"]["repo"]["full_name"].as_str()?; + let head_repo = pr["head"]["repo"]["full_name"].as_str(); + let state = match ( + pr["state"].as_str(), + pr["merged"].as_bool(), + pr["merged_at"].is_string(), + ) { + (Some("open"), _, _) => "open", + (_, Some(true), _) | (_, _, true) => "merged", + _ => "closed", + }; + Some(Pull { + provider: "github", + installation_id: Some(installation_id), + connection_id: None, + repo: base_repo.to_owned(), + number: pr["number"].as_i64()?, + title: pr["title"].as_str().unwrap_or("").to_owned(), + url: pr["html_url"].as_str().unwrap_or("").to_owned(), + author: pr["user"]["login"].as_str().unwrap_or("").to_owned(), + head_ref: pr["head"]["ref"].as_str().unwrap_or("").to_owned(), + head_sha: pr["head"]["sha"] + .as_str() + .filter(|s| s.len() == 40)? + .to_owned(), + base_ref: pr["base"]["ref"].as_str().unwrap_or("").to_owned(), + // A deleted fork has no repository any more: still a fork. + fork: head_repo.is_none_or(|h| !h.eq_ignore_ascii_case(base_repo)), + labels: pr["labels"] + .as_array() + .into_iter() + .flatten() + .filter_map(|l| l["name"].as_str().map(str::to_owned)) + .collect(), + state, + }) +} + +/// The actions of a `pull_request` event that change a preview. +const ACTIONS: [&str; 8] = [ + "opened", + "reopened", + "synchronize", + "closed", + "labeled", + "unlabeled", + "edited", + "ready_for_review", +]; + +/// A `pull_request` event (signature already checked): its previews +/// follow. What to answer GitHub. +pub async fn webhook(s: &AppState, v: &Value) -> crate::error::ApiResult<&'static str> { + if !ACTIONS.contains(&v["action"].as_str().unwrap_or("")) { + return Ok("ignored"); + } + let Some(inst) = v["installation"]["id"].as_i64() else { + return Ok("no installation"); + }; + let Some(pull) = pull_of(&v["pull_request"], inst) else { + return Ok("ignored"); + }; + let team: Option = + sqlx::query_scalar("SELECT team_id FROM pyo.github_installations WHERE id = $1") + .bind(inst) + .fetch_optional(&s.db) + .await?; + let Some(team) = team else { + return Ok("no team"); + }; + Ok(if super::pull_event(s, &team, &pull).await? { + "previews" + } else { + "no previews" + }) +} + +// ── The API ──────────────────────────────────────────────────────────────── + +/// GitHub's REST API as an installation. +pub struct Client { + base: String, + token: String, +} + +impl Client { + pub fn new(base: &str, token: &str) -> Client { + Client { + base: base.trim_end_matches('/').to_owned(), + token: token.to_owned(), + } + } + + pub async fn for_installation(s: &AppState, installation_id: i64) -> anyhow::Result { + let token = crate::github::installation_token(s, installation_id).await?; + Ok(Client::new(&crate::github::api_base(), &token)) + } + + async fn call( + &self, + method: Method, + path: &str, + body: Option<&Value>, + ) -> anyhow::Result<(StatusCode, Value)> { + let mut req = crate::github::http() + .request(method, format!("{}{path}", self.base)) + .bearer_auth(&self.token) + .header("accept", "application/vnd.github+json") + .header("x-github-api-version", "2022-11-28"); + if let Some(b) = body { + req = req.json(b); + } + let res = req.send().await?; + let status = res.status(); + let v = res.json().await.unwrap_or(Value::Null); + Ok((status, v)) + } + + /// A call that has to work: GitHub's own words when it doesn't. + async fn ok( + &self, + method: Method, + path: &str, + body: Option<&Value>, + what: &str, + ) -> anyhow::Result { + let (status, v) = self.call(method, path, body).await?; + if !status.is_success() { + let msg = v["message"].as_str().unwrap_or(""); + if status == StatusCode::FORBIDDEN + || status == StatusCode::NOT_FOUND && msg.contains("Resource not accessible") + { + anyhow::bail!( + "GitHub refused to {what} ({status}): the app's new permissions may not be approved yet. {msg}" + ); + } + anyhow::bail!("GitHub refused to {what} ({status}). {msg}"); + } + Ok(v) + } + + /// The repository's open pull requests, the 100 updated last. + pub async fn open_pulls(&self, repo: &str, installation_id: i64) -> anyhow::Result> { + let v = self + .ok( + Method::GET, + &format!("/repos/{repo}/pulls?state=open&sort=updated&direction=desc&per_page=100"), + None, + "list pull requests", + ) + .await?; + Ok(v.as_array() + .into_iter() + .flatten() + .filter_map(|p| pull_of(p, installation_id)) + .collect()) + } + + pub async fn pull( + &self, + repo: &str, + number: i64, + installation_id: i64, + ) -> anyhow::Result> { + let (status, v) = self + .call(Method::GET, &format!("/repos/{repo}/pulls/{number}"), None) + .await?; + if status == StatusCode::NOT_FOUND { + return Ok(None); + } + if !status.is_success() { + anyhow::bail!("GitHub answered {status} for pull request {number}"); + } + Ok(pull_of(&v, installation_id)) + } + + /// Posts the comment, or edits it; one deleted since is posted again. + pub async fn comment( + &self, + repo: &str, + number: i64, + id: Option, + body: &str, + ) -> anyhow::Result { + let b = json!({ "body": body }); + if let Some(id) = id { + let (status, v) = self + .call( + Method::PATCH, + &format!("/repos/{repo}/issues/comments/{id}"), + Some(&b), + ) + .await?; + if status.is_success() { + return Ok(v["id"].as_i64().unwrap_or(id)); + } + if status != StatusCode::NOT_FOUND { + anyhow::bail!( + "GitHub refused to edit the comment ({status}). {}", + v["message"].as_str().unwrap_or("") + ); + } + } + let v = self + .ok( + Method::POST, + &format!("/repos/{repo}/issues/{number}/comments"), + Some(&b), + "comment on the pull request", + ) + .await?; + v["id"] + .as_i64() + .ok_or_else(|| anyhow::anyhow!("GitHub gave the comment no id")) + } + + pub async fn check(&self, repo: &str, id: Option, body: &Value) -> anyhow::Result { + if let Some(id) = id { + let mut b = body.clone(); + if let Some(o) = b.as_object_mut() { + o.remove("head_sha"); + } + let (status, v) = self + .call( + Method::PATCH, + &format!("/repos/{repo}/check-runs/{id}"), + Some(&b), + ) + .await?; + if status.is_success() { + return Ok(id); + } + if status != StatusCode::NOT_FOUND { + anyhow::bail!( + "GitHub refused to update the check ({status}). {}", + v["message"].as_str().unwrap_or("") + ); + } + } + let v = self + .ok( + Method::POST, + &format!("/repos/{repo}/check-runs"), + Some(body), + "add the check", + ) + .await?; + v["id"] + .as_i64() + .ok_or_else(|| anyhow::anyhow!("GitHub gave the check no id")) + } + + /// A deployment of `sha` to `environment`: transient (GitHub doesn't + /// mark other pull requests' previews inactive) and not production. + pub async fn create_deployment( + &self, + repo: &str, + sha: &str, + environment: &str, + description: &str, + ) -> anyhow::Result { + let v = self + .ok( + Method::POST, + &format!("/repos/{repo}/deployments"), + Some(&json!({ + "ref": sha, "environment": environment, "description": description, + "auto_merge": false, "required_contexts": [], + "transient_environment": true, "production_environment": false, + })), + "add a deployment", + ) + .await?; + v["id"].as_i64().ok_or_else(|| { + anyhow::anyhow!( + "GitHub gave the deployment no id ({})", + v["message"].as_str().unwrap_or("") + ) + }) + } + + pub async fn deployment_status( + &self, + repo: &str, + id: i64, + state: &str, + url: Option<&str>, + logs: Option<&str>, + ) -> anyhow::Result<()> { + let mut b = json!({ "state": state, "auto_inactive": false }); + if let Some(u) = url.filter(|_| state != "inactive") { + b["environment_url"] = json!(u); + } + if let Some(l) = logs { + b["log_url"] = json!(l); + } + let (status, v) = self + .call( + Method::POST, + &format!("/repos/{repo}/deployments/{id}/statuses"), + Some(&b), + ) + .await?; + // A deployment deleted on GitHub: nothing left to say. + if status.is_success() || status == StatusCode::NOT_FOUND { + return Ok(()); + } + anyhow::bail!( + "GitHub refused the deployment status ({status}). {}", + v["message"].as_str().unwrap_or("") + ) + } +} + +/// The environment of a service's previews: "Preview – web". +pub fn environment(service: &str) -> String { + format!("Preview – {service}") +} + +/// The bot on one pull request. +pub struct Forge { + client: Client, + repo: String, + number: i64, + dashboard: String, +} + +impl Forge { + /// None without the app or an installation (it was removed). + pub async fn for_pull(s: &AppState, pull: &PullRow) -> anyhow::Result> { + let Some(app) = crate::github::app(&s.db) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))? + else { + return Ok(None); + }; + let Some(inst) = pull.installation_id else { + return Ok(None); + }; + Ok(Some(Forge { + client: Client::for_installation(s, inst).await?, + repo: pull.repo.clone(), + number: pull.number, + dashboard: app.public_url.trim_end_matches('/').to_owned(), + })) + } + + #[cfg(test)] + pub fn new(client: Client, repo: &str, number: i64, dashboard: &str) -> Forge { + Forge { + client, + repo: repo.to_owned(), + number, + dashboard: dashboard.to_owned(), + } + } + + /// Where Pyo's dashboard is, for logs links. + pub fn dashboard(&self) -> &str { + &self.dashboard + } +} + +impl super::Forge for Forge { + async fn comment(&self, id: Option, body: &str) -> anyhow::Result { + self.client.comment(&self.repo, self.number, id, body).await + } + + async fn check( + &self, + id: Option, + sha: &str, + check: &bot::Check, + details: Option<&str>, + ) -> anyhow::Result> { + Ok(Some( + self.client + .check(&self.repo, id, &check.github(sha, details)) + .await?, + )) + } + + async fn deployment(&self, d: &mut Remote, shown: bot::Shown) -> anyhow::Result<()> { + let state = shown.github_deployment(); + if state == "inactive" { + if let Some(id) = d.deployment_id { + self.client + .deployment_status(&self.repo, id, "inactive", None, d.logs.as_deref()) + .await?; + } + return Ok(()); + } + // A new head: a new deployment, and the one before goes inactive. + if d.deployment_id.is_none() || d.deployment_sha.as_deref() != Some(d.sha.as_str()) { + if let Some(old) = d.deployment_id.take() { + self.client + .deployment_status(&self.repo, old, "inactive", None, None) + .await?; + } + let id = self + .client + .create_deployment( + &self.repo, + &d.sha, + &environment(&d.service), + &format!("Preview of {}", d.service), + ) + .await?; + d.deployment_id = Some(id); + d.deployment_sha = Some(d.sha.clone()); + } + if let Some(id) = d.deployment_id { + self.client + .deployment_status(&self.repo, id, state, d.url.as_deref(), d.logs.as_deref()) + .await?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::super::Forge as _; + use super::*; + use axum::{ + Json, Router, + extract::{Path, State}, + http::{HeaderMap, StatusCode as Code}, + routing::{patch, post}, + }; + use std::sync::{Arc, Mutex}; + + fn pr(state: &str, head_repo: Option<&str>) -> Value { + json!({ + "number": 42, "state": state, "merged": state == "merged", "title": "Add search", + "html_url": "https://github.com/acme/shop/pull/42", "user": { "login": "ana" }, + "head": { "ref": "search", "sha": "a".repeat(40), "repo": head_repo.map(|r| json!({ "full_name": r })) }, + "base": { "ref": "main", "repo": { "full_name": "acme/shop" } }, + "labels": [{ "name": "preview" }], + }) + } + + #[test] + fn pull_requests_from_events() { + let p = pull_of(&pr("open", Some("acme/shop")), 7).unwrap(); + assert_eq!( + (p.repo.as_str(), p.number, p.state, p.fork), + ("acme/shop", 42, "open", false) + ); + assert_eq!(p.labels, vec!["preview"]); + assert_eq!(p.installation_id, Some(7)); + assert_eq!(p.head_ref, "search"); + // From a fork, or a fork deleted since. + assert!(pull_of(&pr("open", Some("mallory/shop")), 7).unwrap().fork); + assert!(pull_of(&pr("open", None), 7).unwrap().fork); + // Closed, and merged (GitHub says "closed" with merged true). + let mut merged = pr("closed", Some("acme/shop")); + merged["merged"] = json!(true); + assert_eq!(pull_of(&merged, 7).unwrap().state, "merged"); + assert_eq!( + pull_of(&pr("closed", Some("acme/shop")), 7).unwrap().state, + "closed" + ); + // No head commit: not one to deploy. + let mut bad = pr("open", Some("acme/shop")); + bad["head"]["sha"] = json!("abc"); + assert!(pull_of(&bad, 7).is_none()); + } + + #[test] + fn what_previews_still_need() { + let all = json!({ "pull_requests": "write", "deployments": "write", "checks": "write", "contents": "read" }); + assert!(missing(&all, &["push".into(), "pull_request".into()]).is_empty()); + let old = json!({ "contents": "read", "metadata": "read", "statuses": "write" }); + assert_eq!( + missing(&old, &["push".into()]), + vec![ + "Pull requests: write", + "Deployments: write", + "Checks: write", + "Pull request events" + ] + ); + let read = json!({ "pull_requests": "read", "deployments": "write", "checks": "write" }); + assert_eq!( + missing(&read, &["pull_request".into()]), + vec!["Pull requests: write"] + ); + // Not asked yet: nothing to say. + assert!(missing(&Value::Null, &[]).is_empty()); + // New apps ask for all of it. + assert!(missing(&manifest_permissions(), &["pull_request".into()]).is_empty()); + } + + #[test] + fn where_to_approve() { + assert_eq!( + installation_url("acme", "Organization", 9), + "https://github.com/organizations/acme/settings/installations/9" + ); + assert_eq!( + installation_url("ana", "User", 9), + "https://github.com/settings/installations/9" + ); + let mut app = crate::github::GithubApp { + slug: "pyo-abc".into(), + owner: "acme".into(), + ..Default::default() + }; + assert_eq!( + app_settings_url(&app), + "https://github.com/settings/apps/pyo-abc/permissions" + ); + app.owner_type = "Organization".into(); + assert_eq!( + app_settings_url(&app), + "https://github.com/organizations/acme/settings/apps/pyo-abc/permissions" + ); + let mut i = json!({ "id": 9, "account": "acme", "accountType": "Organization", "permissions": { "contents": "read" }, "events": ["push"] }); + show_installation(&mut i); + assert_eq!( + i["approveUrl"], + "https://github.com/organizations/acme/settings/installations/9" + ); + assert_eq!(i["missingPermissions"].as_array().unwrap().len(), 4); + assert!(i.get("permissions").is_none()); + } + + /// Requests the fake GitHub saw: method and path, then the body. + type Seen = Arc>>; + + #[derive(Clone)] + struct Fake { + seen: Seen, + /// Comments that were deleted on GitHub. + gone: Arc>>, + } + + fn authed(h: &HeaderMap) -> bool { + h.get("authorization").and_then(|v| v.to_str().ok()) == Some("Bearer ghs_test") + } + + async fn fake() -> (Client, Fake) { + let f = Fake { + seen: Seen::default(), + gone: Arc::default(), + }; + let app = Router::new() + .route( + "/repos/{o}/{r}/issues/{n}/comments", + post( + |State(f): State, + Path((_o, _r, n)): Path<(String, String, i64)>, + h: HeaderMap, + Json(b): Json| async move { + assert!(authed(&h)); + f.seen + .lock() + .unwrap() + .push((format!("POST comment {n}"), b)); + (Code::CREATED, Json(json!({ "id": 1000 + n }))) + }, + ), + ) + .route( + "/repos/{o}/{r}/issues/comments/{id}", + patch( + |State(f): State, + Path((_o, _r, id)): Path<(String, String, i64)>, + Json(b): Json| async move { + f.seen + .lock() + .unwrap() + .push((format!("PATCH comment {id}"), b)); + if f.gone.lock().unwrap().contains(&id) { + return (Code::NOT_FOUND, Json(json!({ "message": "Not Found" }))); + } + (Code::OK, Json(json!({ "id": id }))) + }, + ), + ) + .route( + "/repos/{o}/{r}/check-runs", + post(|State(f): State, Json(b): Json| async move { + f.seen.lock().unwrap().push(("POST check".into(), b)); + (Code::CREATED, Json(json!({ "id": 77 }))) + }), + ) + .route( + "/repos/{o}/{r}/check-runs/{id}", + patch( + |State(f): State, + Path((_o, _r, id)): Path<(String, String, i64)>, + Json(b): Json| async move { + f.seen + .lock() + .unwrap() + .push((format!("PATCH check {id}"), b)); + (Code::OK, Json(json!({ "id": id }))) + }, + ), + ) + .route( + "/repos/{o}/{r}/deployments", + post(|State(f): State, Json(b): Json| async move { + let n = f + .seen + .lock() + .unwrap() + .iter() + .filter(|(k, _)| k == "POST deployment") + .count() as i64; + f.seen.lock().unwrap().push(("POST deployment".into(), b)); + (Code::CREATED, Json(json!({ "id": 500 + n }))) + }), + ) + .route( + "/repos/{o}/{r}/deployments/{id}/statuses", + post( + |State(f): State, + Path((_o, _r, id)): Path<(String, String, i64)>, + Json(b): Json| async move { + f.seen + .lock() + .unwrap() + .push((format!("POST status {id}"), b)); + (Code::CREATED, Json(json!({ "id": 1 }))) + }, + ), + ) + .with_state(f.clone()); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + (Client::new(&format!("http://{addr}"), "ghs_test"), f) + } + + fn seen(f: &Fake) -> Vec { + f.seen + .lock() + .unwrap() + .iter() + .map(|(k, _)| k.clone()) + .collect() + } + + #[tokio::test] + async fn the_comment_is_edited_in_place_and_posted_again_when_deleted() { + let (c, f) = fake().await; + let forge = Forge::new(c, "acme/shop", 42, "https://pyo.example.com"); + let id = forge.comment(None, "one").await.unwrap(); + assert_eq!(id, 1042); + assert_eq!(forge.comment(Some(id), "two").await.unwrap(), 1042); + f.gone.lock().unwrap().push(1042); + assert_eq!(forge.comment(Some(1042), "three").await.unwrap(), 1042); + assert_eq!( + seen(&f), + vec![ + "POST comment 42", + "PATCH comment 1042", + "PATCH comment 1042", + "POST comment 42" + ] + ); + assert_eq!(f.seen.lock().unwrap()[3].1["body"], "three"); + } + + #[tokio::test] + async fn the_check_is_made_once_per_head_then_updated() { + let (c, f) = fake().await; + let forge = Forge::new(c, "acme/shop", 42, ""); + let building = bot::Check { + status: "in_progress", + conclusion: None, + title: "Building".into(), + summary: String::new(), + }; + let id = forge + .check(None, &"a".repeat(40), &building, None) + .await + .unwrap(); + assert_eq!(id, Some(77)); + let done = bot::Check { + status: "completed", + conclusion: Some("failure"), + title: "Failed: web".into(), + summary: "- web: Failed".into(), + }; + forge + .check(id, &"a".repeat(40), &done, Some("https://pyo/x")) + .await + .unwrap(); + let s = f.seen.lock().unwrap().clone(); + assert_eq!(s[0].0, "POST check"); + assert_eq!(s[0].1["name"], "Pyo · Preview"); + assert_eq!(s[0].1["status"], "in_progress"); + assert_eq!(s[1].0, "PATCH check 77"); + assert_eq!(s[1].1["conclusion"], "failure"); + assert!( + s[1].1.get("head_sha").is_none(), + "an update can't move the check" + ); + } + + #[tokio::test] + async fn a_deployment_per_head_with_its_states() { + let (c, f) = fake().await; + let forge = Forge::new(c, "acme/shop", 42, ""); + let mut d = Remote { + name: "web-pr-42".into(), + service: "web".into(), + sha: "a".repeat(40), + url: Some("https://web-pr-42.203.0.113.7.nip.io".into()), + logs: Some("https://pyo/acme/deployments/dpl_1".into()), + ..Default::default() + }; + forge + .deployment(&mut d, bot::Shown::Building) + .await + .unwrap(); + forge.deployment(&mut d, bot::Shown::Ready).await.unwrap(); + // A push: a new deployment, the old one inactive. + d.sha = "b".repeat(40); + forge + .deployment(&mut d, bot::Shown::Building) + .await + .unwrap(); + forge.deployment(&mut d, bot::Shown::Removed).await.unwrap(); + assert_eq!( + seen(&f), + vec![ + "POST deployment", + "POST status 500", + "POST status 500", + "POST status 500", + "POST deployment", + "POST status 501", + "POST status 501" + ] + ); + let s = f.seen.lock().unwrap().clone(); + assert_eq!(s[0].1["environment"], "Preview – web"); + assert_eq!(s[0].1["transient_environment"], true); + assert_eq!(s[0].1["production_environment"], false); + assert_eq!(s[1].1["state"], "in_progress"); + assert_eq!(s[2].1["state"], "success"); + assert_eq!( + s[2].1["environment_url"], + "https://web-pr-42.203.0.113.7.nip.io" + ); + assert_eq!(s[3].1["state"], "inactive"); + assert_eq!(s[4].1["ref"], "b".repeat(40)); + assert_eq!(s[6].1["state"], "inactive"); + assert!(s[6].1.get("environment_url").is_none()); + assert_eq!(d.deployment_id, Some(501)); + } +} diff --git a/crates/pyo-api/src/previews/gitlab.rs b/crates/pyo-api/src/previews/gitlab.rs new file mode 100644 index 00000000..3b692368 --- /dev/null +++ b/crates/pyo-api/src/previews/gitlab.rs @@ -0,0 +1,446 @@ +//! Previews on GitLab, through the team's GitLab connection: merge request +//! events (the connection's webhook sends them), a note edited in place, +//! a commit status "Pyo · Preview", and an environment per preview +//! (`preview/web-pr-42`) with a deployment, which gives the merge request +//! its "View app" button. + +use serde_json::Value; + +use super::{Pull, PullRow, Remote, bot}; +use crate::{AppState, git::gitlab::Gitlab}; + +/// A merge request from GitLab's API (`GET .../merge_requests`). +pub fn pull_of_api(v: &Value, connection_id: &str, repo: &str) -> Option { + let state = match v["state"].as_str()? { + "opened" => "open", + "merged" => "merged", + _ => "closed", + }; + Some(Pull { + provider: "gitlab", + installation_id: None, + connection_id: Some(connection_id.to_owned()), + repo: repo.to_owned(), + number: v["iid"].as_i64()?, + title: v["title"].as_str().unwrap_or("").to_owned(), + url: v["web_url"].as_str().unwrap_or("").to_owned(), + author: v["author"]["username"].as_str().unwrap_or("").to_owned(), + head_ref: v["source_branch"].as_str().unwrap_or("").to_owned(), + head_sha: v["sha"].as_str().filter(|s| s.len() == 40)?.to_owned(), + base_ref: v["target_branch"].as_str().unwrap_or("").to_owned(), + fork: v["source_project_id"] != v["target_project_id"], + labels: v["labels"] + .as_array() + .into_iter() + .flatten() + .filter_map(|l| l.as_str().or_else(|| l["name"].as_str()).map(str::to_owned)) + .collect(), + state, + }) +} + +/// A merge request event (`X-Gitlab-Event: Merge Request Hook`), its token +/// already checked. None for anything else. +pub fn pull_of_hook(event: Option<&str>, v: &Value, conn: &crate::git::Connection) -> Option { + if event != Some("Merge Request Hook") || v["object_kind"].as_str() != Some("merge_request") { + return None; + } + let a = &v["object_attributes"]; + let repo = conn + .repo_of(v["project"]["web_url"].as_str().unwrap_or("")) + .or_else(|| { + v["project"]["path_with_namespace"] + .as_str() + .map(str::to_owned) + })?; + let state = match a["state"].as_str()? { + "opened" => "open", + "merged" => "merged", + _ => "closed", + }; + Some(Pull { + provider: "gitlab", + installation_id: None, + connection_id: Some(conn.id.clone()), + repo, + number: a["iid"].as_i64()?, + title: a["title"].as_str().unwrap_or("").to_owned(), + url: a["url"].as_str().unwrap_or("").to_owned(), + author: v["user"]["username"].as_str().unwrap_or("").to_owned(), + head_ref: a["source_branch"].as_str().unwrap_or("").to_owned(), + head_sha: a["last_commit"]["id"] + .as_str() + .filter(|s| s.len() == 40)? + .to_owned(), + base_ref: a["target_branch"].as_str().unwrap_or("").to_owned(), + fork: a["source_project_id"] != a["target_project_id"], + labels: v["labels"] + .as_array() + .into_iter() + .flatten() + .filter_map(|l| l["title"].as_str().map(str::to_owned)) + .collect(), + state, + }) +} + +/// Whether the connection's webhook on the source's repository sends merge +/// request events (else Pyo asks GitLab every minute). +pub async fn hooked(db: &sqlx::PgPool, src: &Value) -> anyhow::Result { + let Some(conn) = src["gitConnectionId"].as_str() else { + return Ok(false); + }; + let base: Option = + sqlx::query_scalar("SELECT base_url FROM pyo.git_connections WHERE id = $1") + .bind(conn) + .fetch_optional(db) + .await?; + let Some(repo) = + base.and_then(|b| crate::git::repo_path(&b, src["repoUrl"].as_str().unwrap_or(""))) + else { + return Ok(false); + }; + Ok(sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.git_webhooks WHERE connection_id = $1 AND repo = $2 AND hook_id IS NOT NULL AND merge_requests)", + ) + .bind(conn) + .bind(repo.to_lowercase()) + .fetch_one(db) + .await?) +} + +/// The environment of a preview: "preview/web-pr-42" (one per merge +/// request, so each gets its own "View app"). +pub fn environment(name: &str) -> String { + format!("preview/{name}") +} + +/// The bot on one merge request. +pub struct Forge { + api: Gitlab, + repo: String, + number: i64, + dashboard: String, +} + +impl Forge { + /// None when the connection is gone. + pub async fn for_pull(s: &AppState, pull: &PullRow) -> anyhow::Result> { + let Some(id) = &pull.connection_id else { + return Ok(None); + }; + let conn = match crate::git::load(&s.db, None, id).await { + Ok(c) => c, + Err(e) if e.status == axum::http::StatusCode::NOT_FOUND => return Ok(None), + Err(e) => anyhow::bail!("{}", e.message), + }; + let api = conn + .api() + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + Ok(Some(Forge { + api, + repo: pull.repo.clone(), + number: pull.number, + dashboard: crate::git::public_url(Some(&conn.public_url)), + })) + } + + #[cfg(test)] + pub fn new(api: Gitlab, repo: &str, number: i64, dashboard: &str) -> Forge { + Forge { + api, + repo: repo.to_owned(), + number, + dashboard: dashboard.to_owned(), + } + } + + pub fn dashboard(&self) -> &str { + &self.dashboard + } +} + +impl super::Forge for Forge { + async fn comment(&self, id: Option, body: &str) -> anyhow::Result { + Ok(self + .api + .note(&self.repo, self.number, id.map(|i| i as u64), body) + .await? as i64) + } + + async fn check( + &self, + _id: Option, + sha: &str, + check: &bot::Check, + details: Option<&str>, + ) -> anyhow::Result> { + self.api + .set_named_status( + &self.repo, + sha, + bot::CHECK_NAME, + check.gitlab_state(), + &check.title, + details.unwrap_or(""), + ) + .await?; + Ok(None) + } + + async fn deployment(&self, d: &mut Remote, shown: bot::Shown) -> anyhow::Result<()> { + let env = environment(&d.name); + if matches!(shown, bot::Shown::Removed | bot::Shown::Removing) { + if let Some(id) = d.environment_id.take() { + self.api.remove_environment(&self.repo, id as u64).await?; + } + d.deployment_id = None; + d.deployment_sha = None; + return Ok(()); + } + let Some(status) = shown.gitlab_deployment() else { + return Ok(()); + }; + let env_id = self + .api + .environment( + &self.repo, + d.environment_id.map(|i| i as u64), + &env, + d.url.as_deref(), + ) + .await?; + d.environment_id = Some(env_id as i64); + // A new head: a new deployment. + let id = if d.deployment_sha.as_deref() == Some(d.sha.as_str()) { + d.deployment_id.map(|i| i as u64) + } else { + None + }; + let id = self + .api + .deployment(&self.repo, id, &env, &d.sha, &d.head_ref, status) + .await?; + d.deployment_id = Some(id as i64); + d.deployment_sha = Some(d.sha.clone()); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::super::Forge as _; + use super::*; + use axum::{ + Json, Router, + extract::{Path, State}, + http::StatusCode as Code, + routing::{post, put}, + }; + use serde_json::json; + use std::sync::{Arc, Mutex}; + + fn mr(state: &str, fork: bool) -> Value { + json!({ + "iid": 7, "state": state, "title": "Add search", "web_url": "https://gitlab.com/acme/shop/-/merge_requests/7", + "author": { "username": "ana" }, "source_branch": "search", "target_branch": "main", + "sha": "c".repeat(40), "source_project_id": if fork { 99 } else { 1 }, "target_project_id": 1, + "labels": ["preview"], + }) + } + + #[test] + fn merge_requests_from_the_api() { + let p = pull_of_api(&mr("opened", false), "gitc_1", "acme/shop").unwrap(); + assert_eq!( + (p.number, p.state, p.fork, p.provider), + (7, "open", false, "gitlab") + ); + assert_eq!(p.connection_id.as_deref(), Some("gitc_1")); + assert_eq!(p.labels, vec!["preview"]); + assert!( + pull_of_api(&mr("opened", true), "gitc_1", "acme/shop") + .unwrap() + .fork + ); + assert_eq!( + pull_of_api(&mr("merged", false), "gitc_1", "acme/shop") + .unwrap() + .state, + "merged" + ); + assert_eq!( + pull_of_api(&mr("closed", false), "gitc_1", "acme/shop") + .unwrap() + .state, + "closed" + ); + } + + /// Requests the fake GitLab saw. + type Seen = Arc>>; + + async fn fake() -> (Gitlab, Seen) { + let seen: Seen = Seen::default(); + let app = Router::new() + .route( + "/api/v4/projects/{p}/merge_requests/{iid}/notes", + post( + |State(s): State, + Path((p, iid)): Path<(String, i64)>, + Json(b): Json| async move { + s.lock().unwrap().push((format!("POST note {p} {iid}"), b)); + (Code::CREATED, Json(json!({ "id": 31 }))) + }, + ), + ) + .route( + "/api/v4/projects/{p}/merge_requests/{iid}/notes/{id}", + put( + |State(s): State, + Path((_p, _iid, id)): Path<(String, i64, u64)>, + Json(b): Json| async move { + s.lock().unwrap().push((format!("PUT note {id}"), b)); + if id == 404 { + return (Code::NOT_FOUND, Json(json!({ "message": "404 Not found" }))); + } + (Code::OK, Json(json!({ "id": id }))) + }, + ), + ) + .route( + "/api/v4/projects/{p}/statuses/{sha}", + post(|State(s): State, Json(b): Json| async move { + s.lock().unwrap().push(("POST status".into(), b)); + (Code::CREATED, Json(json!({ "id": 1 }))) + }), + ) + .route( + "/api/v4/projects/{p}/environments", + post(|State(s): State, Json(b): Json| async move { + s.lock().unwrap().push(("POST environment".into(), b)); + (Code::CREATED, Json(json!({ "id": 12 }))) + }), + ) + .route( + "/api/v4/projects/{p}/environments/{id}", + put(|State(s): State, Json(b): Json| async move { + s.lock().unwrap().push(("PUT environment".into(), b)); + (Code::OK, Json(json!({ "id": 12 }))) + }) + .delete(|State(s): State| async move { + s.lock() + .unwrap() + .push(("DELETE environment".into(), Value::Null)); + Code::NO_CONTENT + }), + ) + .route( + "/api/v4/projects/{p}/environments/{id}/stop", + post(|State(s): State| async move { + s.lock().unwrap().push(("POST stop".into(), Value::Null)); + (Code::OK, Json(json!({}))) + }), + ) + .route( + "/api/v4/projects/{p}/deployments", + post(|State(s): State, Json(b): Json| async move { + s.lock().unwrap().push(("POST deployment".into(), b)); + (Code::CREATED, Json(json!({ "id": 40 }))) + }), + ) + .route( + "/api/v4/projects/{p}/deployments/{id}", + put(|State(s): State, Json(b): Json| async move { + s.lock().unwrap().push(("PUT deployment".into(), b)); + (Code::OK, Json(json!({ "id": 40 }))) + }), + ) + .with_state(seen.clone()); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + let base = reqwest::Url::parse(&format!("http://{addr}")).unwrap(); + ( + Gitlab::with_client(base, "glpat-x", reqwest::Client::new()), + seen, + ) + } + + fn kinds(s: &Seen) -> Vec { + s.lock().unwrap().iter().map(|(k, _)| k.clone()).collect() + } + + #[tokio::test] + async fn the_note_is_edited_in_place() { + let (api, seen) = fake().await; + let f = Forge::new(api, "acme/shop", 7, ""); + assert_eq!(f.comment(None, "one").await.unwrap(), 31); + assert_eq!(f.comment(Some(31), "two").await.unwrap(), 31); + // Deleted on GitLab: posted again. + assert_eq!(f.comment(Some(404), "three").await.unwrap(), 31); + assert_eq!( + kinds(&seen), + vec![ + "POST note acme/shop 7", + "PUT note 31", + "PUT note 404", + "POST note acme/shop 7" + ] + ); + } + + #[tokio::test] + async fn status_environment_and_deployment() { + let (api, seen) = fake().await; + let f = Forge::new(api, "acme/shop", 7, ""); + let failed = bot::Check { + status: "completed", + conclusion: Some("failure"), + title: "Failed: web".into(), + summary: String::new(), + }; + f.check(None, &"c".repeat(40), &failed, Some("https://pyo/x")) + .await + .unwrap(); + let mut d = Remote { + name: "web-pr-7".into(), + service: "web".into(), + sha: "c".repeat(40), + head_ref: "search".into(), + url: Some("https://web-pr-7.203.0.113.7.nip.io".into()), + ..Default::default() + }; + f.deployment(&mut d, bot::Shown::Waiting).await.unwrap(); + f.deployment(&mut d, bot::Shown::Building).await.unwrap(); + f.deployment(&mut d, bot::Shown::Ready).await.unwrap(); + f.deployment(&mut d, bot::Shown::Removed).await.unwrap(); + assert_eq!( + kinds(&seen), + vec![ + "POST status", + "POST environment", + "POST deployment", + "PUT environment", + "PUT deployment", + "POST stop", + "DELETE environment" + ] + ); + let s = seen.lock().unwrap().clone(); + assert_eq!(s[0].1["name"], "Pyo · Preview"); + assert_eq!(s[0].1["state"], "failed"); + assert_eq!(s[0].1["target_url"], "https://pyo/x"); + assert_eq!(s[1].1["name"], "preview/web-pr-7"); + assert_eq!( + s[1].1["external_url"], + "https://web-pr-7.203.0.113.7.nip.io" + ); + assert_eq!(s[2].1["status"], "running"); + assert_eq!(s[2].1["environment"], "preview/web-pr-7"); + assert_eq!(s[2].1["ref"], "search"); + assert_eq!(s[4].1["status"], "success"); + assert_eq!(d.environment_id, None); + } +} diff --git a/crates/pyo-api/src/previews/mod.rs b/crates/pyo-api/src/previews/mod.rs new file mode 100644 index 00000000..76242547 --- /dev/null +++ b/crates/pyo-api/src/previews/mod.rs @@ -0,0 +1,1804 @@ +//! Preview environments: each open pull request (GitHub) or merge request +//! (GitLab) gets a copy of the services that turned previews on, built +//! from its head, and loses it when it closes or merges. +//! +//! - **A copy is a service** (`pyo.services.preview_of`), next to the one +//! it previews: same project, namespace and cluster, its own name +//! (`web-pr-42`), env, routes and deployments. Builds, deploys (signed +//! agent commands on Pyo Cloud), logs and removal are the ones every +//! service has. The dashboard lists copies under their service only. +//! - **What runs** ([`reconcile`]): a pull request's previews are brought +//! in line with it and with each service's settings (`spec.previews`, +//! [`Settings`]) whenever something changes: a webhook, a poll of the +//! provider ([`runner`]), a deployment that settled, a setting saved. +//! It decides per service ([`decide`]): run (start, redeploy the new +//! head), wait (over the service's limit) or remove (closed, merged, +//! idle, label gone, fork, previews off). +//! - **URLs** ([`domain`], [`naming`]): `-pr-` on the +//! cluster's preview domain, else nip.io on its address, or its tailnet +//! for private previews. Kept for the pull request's life. +//! - **The bot** ([`report`], [`bot`], [`github`], [`gitlab`]): one comment +//! edited in place, a check (GitHub) or commit status (GitLab), and a +//! deployment per preview, through the GitHub App or the GitLab +//! connection. A job per change, idempotent: it says only what changed. +//! - **Forks** are not deployed unless the service allows it, and never +//! with secrets unless it allows that too. + +pub mod bot; +pub mod domain; +pub mod github; +pub mod gitlab; +pub mod naming; +#[cfg(test)] +mod tests; + +use std::time::Duration; + +use pyo_proto::{Command, now_ms}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use crate::{ + AppState, + auth::User, + deploy::{self, DeployRequest}, + error::{ApiError, ApiResult}, + ids::new_id, + ops::{Role, log_activity, require_role}, +}; + +use bot::Shown; + +/// Advisory lock of the previews loop ([`runner`]). +pub const LOCK: i64 = 7_071; + +// ── Settings ─────────────────────────────────────────────────────────────── + +/// A service's previews (`spec.previews`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Settings { + pub enabled: bool, + /// "all", or "label": only pull requests with `label`. + pub pulls: String, + pub label: String, + /// Previews of the service at once. + pub limit: i64, + /// Removed after this many days without a push (0: never). + pub idle_days: i64, + /// "public", or "private" (on the cluster's tailnet). + pub access: String, + /// Copy the service's secret variables. + pub copy_secrets: bool, + /// Pull requests from forks: "off", "no-secrets" or "secrets". + pub forks: String, + /// Variables for previews: they replace the service's by key, or add. + pub env: Vec, +} + +impl Default for Settings { + fn default() -> Self { + Settings { + enabled: false, + pulls: "all".into(), + label: "preview".into(), + limit: 5, + idle_days: 0, + access: "public".into(), + copy_secrets: false, + forks: "off".into(), + env: vec![], + } + } +} + +impl Settings { + pub fn of(spec: &Value) -> Settings { + serde_json::from_value(spec["previews"].clone()).unwrap_or_default() + } +} + +/// A variable's name: letters, digits, `_`, `.` and `-`, not starting with +/// a digit. +fn env_key(k: &str) -> bool { + let mut b = k.bytes(); + matches!(b.next(), Some(c) if c.is_ascii_alphabetic() || c == b'_') + && b.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'-')) + && k.len() <= 200 +} + +/// Checks a service's `previews` before it's saved, and stores them tidy +/// (defaults filled in). Previews need a repository Pyo can read pull +/// requests of: the GitHub App's, or a GitLab connection's. +pub fn check_settings(spec: &mut Value) -> ApiResult<()> { + let Some(v) = spec.get("previews").cloned() else { + return Ok(()); + }; + if v.is_null() { + if let Some(o) = spec.as_object_mut() { + o.remove("previews"); + } + return Ok(()); + } + let bad = |m: &str| Err(ApiError::bad_request(m.to_owned())); + let mut s: Settings = serde_json::from_value(v) + .map_err(|_| ApiError::bad_request("Pyo can't read these preview settings."))?; + s.label = s.label.trim().to_owned(); + if !matches!(s.pulls.as_str(), "all" | "label") { + return bad("Previews are for all pull requests or ones with a label."); + } + if s.pulls == "label" && (s.label.is_empty() || s.label.chars().count() > 50) { + return bad("Give the label pull requests need for a preview."); + } + if !(1..=50).contains(&s.limit) { + return bad("Previews at once: 1 to 50."); + } + if !(0..=90).contains(&s.idle_days) { + return bad("Remove previews after 1 to 90 days without a push, or never."); + } + if !matches!(s.access.as_str(), "public" | "private") { + return bad("Previews are public, or private on the tailnet."); + } + if !matches!(s.forks.as_str(), "off" | "no-secrets" | "secrets") { + return bad("Pick what happens to pull requests from forks."); + } + let mut keys = std::collections::HashSet::new(); + for e in &mut s.env { + let k = e["key"].as_str().unwrap_or("").trim().to_owned(); + if !env_key(&k) { + return Err(ApiError::bad_request(format!( + "{} isn't a valid variable name.", + if k.is_empty() { "An empty name" } else { &k } + ))); + } + if !keys.insert(k.clone()) { + return Err(ApiError::bad_request(format!("{k} is there twice."))); + } + e["key"] = json!(k); + if !e["id"].is_string() { + e["id"] = json!(new_id("env")); + } + } + if s.enabled { + let src = &spec["source"]; + let git = src["type"] == json!("git") + && (src["installationId"].is_i64() + || src["gitConnectionId"] + .as_str() + .is_some_and(|c| !c.is_empty())); + if !git { + return bad( + "Previews need a repository from GitHub (through Pyo's GitHub App) or a GitLab connection.", + ); + } + if spec["workloadKind"] == json!("CronJob") { + return bad("Cron jobs have no previews."); + } + } + spec["previews"] = serde_json::to_value(&s).map_err(anyhow::Error::from)?; + Ok(()) +} + +// ── Pull requests ────────────────────────────────────────────────────────── + +/// A pull request or merge request, as its provider tells it. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Pull { + /// "github" or "gitlab". + pub provider: &'static str, + pub installation_id: Option, + pub connection_id: Option, + /// "owner/repo" or "group/sub/project". + pub repo: String, + pub number: i64, + pub title: String, + pub url: String, + pub author: String, + pub head_ref: String, + pub head_sha: String, + pub base_ref: String, + pub fork: bool, + pub labels: Vec, + /// "open", "closed" or "merged". + pub state: &'static str, +} + +impl Pull { + /// Whose it is: the installation's id or the connection's. + fn source(&self) -> String { + match self.provider { + "github" => self.installation_id.unwrap_or(0).to_string(), + _ => self.connection_id.clone().unwrap_or_default(), + } + } +} + +/// A pull request as Pyo keeps it. +#[derive(sqlx::FromRow, Debug, Clone, Default)] +pub struct PullRow { + pub id: String, + pub team_id: String, + pub provider: String, + pub installation_id: Option, + pub connection_id: Option, + pub repo: String, + pub number: i64, + pub author: String, + pub head_ref: String, + pub head_sha: String, + pub fork: bool, + pub labels: Vec, + pub state: String, + pub pushed_ms: i64, + pub comment_id: Option, + pub comment_hash: Option, + pub check_id: Option, + pub check_sha: Option, + pub check_hash: Option, +} + +const PULL_COLS: &str = "id, team_id, provider, installation_id, connection_id, repo, number, author, head_ref, head_sha, fork, labels, state, pyo.ms(pushed_at) AS pushed_ms, comment_id, comment_hash, check_id, check_sha, check_hash"; + +impl PullRow { + /// The ref a build fetches: the branch, or for a fork the pull + /// request's own ref in the repository (its branch is in the fork). + pub fn build_ref(&self) -> String { + match (self.fork, self.provider.as_str()) { + (true, "github") => format!("refs/pull/{}/head", self.number), + (true, _) => format!("refs/merge-requests/{}/head", self.number), + _ => self.head_ref.clone(), + } + } +} + +pub async fn load_pull( + tx: &mut Transaction<'_, Postgres>, + id: &str, + lock: bool, +) -> sqlx::Result> { + sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT {PULL_COLS} FROM pyo.pull_requests WHERE id = $1{}", + if lock { " FOR UPDATE" } else { "" } + ))) + .bind(id) + .fetch_optional(&mut **tx) + .await +} + +/// A preview as stored. +#[derive(sqlx::FromRow, Debug, Clone, Default)] +pub struct PreviewRow { + pub id: String, + pub team_id: String, + pub pull_id: String, + pub service_id: String, + pub preview_service_id: Option, + pub name: String, + pub hostname: Option, + pub state: String, + pub message: Option, + pub removed_reason: Option, + pub sha: String, + pub deployment_id: Option, + pub remote_deployment_id: Option, + pub remote_deployment_sha: Option, + pub remote_environment_id: Option, + pub reported: Option, +} + +const PREVIEW_COLS: &str = "id, team_id, pull_id, service_id, preview_service_id, name, hostname, state, message, removed_reason, sha, deployment_id, remote_deployment_id, remote_deployment_sha, remote_environment_id, reported"; + +/// A service whose previews follow a repository. +#[derive(sqlx::FromRow, Debug, Clone)] +struct Source { + id: String, + team_id: String, + project_id: String, + cluster_id: String, + name: String, + spec: Value, +} + +/// The team's services with previews on that build `repo`, from the +/// installation's repositories (GitHub) or the connection's (GitLab). +async fn sources( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + provider: &str, + connection_id: Option<&str>, + repo: &str, +) -> ApiResult> { + let rows: Vec = sqlx::query_as( + "SELECT id, team_id, project_id, cluster_id, name, spec FROM pyo.services + WHERE team_id = $1 AND NOT deleting AND preview_of IS NULL AND spec->'source'->>'type' = 'git' + AND coalesce((spec->'previews'->>'enabled')::bool, false) + AND CASE WHEN $2 = 'github' THEN spec->'source'->>'installationId' IS NOT NULL + ELSE spec->'source'->>'gitConnectionId' = $3 END + ORDER BY created_at", + ) + .bind(team_id) + .bind(provider) + .bind(connection_id) + .fetch_all(&mut **tx) + .await?; + let base: Option = match connection_id { + Some(c) if provider == "gitlab" => { + sqlx::query_scalar("SELECT base_url FROM pyo.git_connections WHERE id = $1") + .bind(c) + .fetch_optional(&mut **tx) + .await? + } + _ => None, + }; + Ok(rows + .into_iter() + .filter(|r| { + let url = r.spec["source"]["repoUrl"].as_str().unwrap_or(""); + let theirs = match provider { + "github" => crate::github::full_name(url), + _ => base.as_deref().and_then(|b| crate::git::repo_path(b, url)), + }; + theirs.is_some_and(|t| t.eq_ignore_ascii_case(repo)) + }) + .collect()) +} + +/// A pull request changed (or was seen by a poll): keep it, when a service +/// of the team previews its repository or it's known already, and bring its +/// previews in line. Whether it's followed. +pub async fn pull_event(s: &AppState, team_id: &str, p: &Pull) -> ApiResult { + let mut tx = s.db.begin().await?; + let followed = !sources( + &mut tx, + team_id, + p.provider, + p.connection_id.as_deref(), + &p.repo, + ) + .await? + .is_empty(); + let repo = p.repo.to_lowercase(); + let known: Option = sqlx::query_scalar( + "SELECT id FROM pyo.pull_requests WHERE team_id = $1 AND provider = $2 AND source = $3 AND repo = $4 AND number = $5", + ) + .bind(team_id) + .bind(p.provider) + .bind(p.source()) + .bind(&repo) + .bind(p.number) + .fetch_optional(&mut *tx) + .await?; + if !followed && known.is_none() { + return Ok(false); + } + let id: String = sqlx::query_scalar( + "INSERT INTO pyo.pull_requests (id, team_id, provider, installation_id, connection_id, source, repo, number, title, url, author, head_ref, head_sha, base_ref, fork, labels, state, closed_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, CASE WHEN $17 = 'open' THEN NULL ELSE now() END) + ON CONFLICT (team_id, provider, source, repo, number) DO UPDATE SET + title = excluded.title, url = excluded.url, author = excluded.author, head_ref = excluded.head_ref, + base_ref = excluded.base_ref, fork = excluded.fork, labels = excluded.labels, state = excluded.state, + pushed_at = CASE WHEN excluded.head_sha <> '' AND pyo.pull_requests.head_sha <> excluded.head_sha THEN now() ELSE pyo.pull_requests.pushed_at END, + head_sha = CASE WHEN excluded.head_sha = '' THEN pyo.pull_requests.head_sha ELSE excluded.head_sha END, + closed_at = CASE WHEN excluded.state = 'open' THEN NULL ELSE coalesce(pyo.pull_requests.closed_at, now()) END, + updated_at = now() + RETURNING id", + ) + .bind(new_id("pr")) + .bind(team_id) + .bind(p.provider) + .bind(p.installation_id) + .bind(&p.connection_id) + .bind(p.source()) + .bind(&repo) + .bind(p.number) + .bind(p.title.chars().take(300).collect::()) + .bind(&p.url) + .bind(&p.author) + .bind(&p.head_ref) + .bind(&p.head_sha) + .bind(&p.base_ref) + .bind(p.fork) + .bind(&p.labels) + .bind(p.state) + .fetch_one(&mut *tx) + .await?; + tx.commit().await?; + reconcile(s, &id).await?; + Ok(true) +} + +// ── Deciding ─────────────────────────────────────────────────────────────── + +/// What a service's preview of a pull request should be. +#[derive(Debug, Clone, PartialEq)] +pub enum Decision { + /// Run it. `copy_secrets`: with the service's secret variables; + /// `secret_overrides`: with the secret preview variables. + Run { + copy_secrets: bool, + secret_overrides: bool, + }, + Remove { + reason: &'static str, + message: String, + }, +} + +pub fn decide(pull: &PullRow, s: &Settings, spec: &Value, now_ms: i64) -> Decision { + let remove = |reason: &'static str, message: String| Decision::Remove { reason, message }; + match pull.state.as_str() { + "merged" => return remove("merged", "Merged.".into()), + "open" => {} + _ => return remove("closed", "Closed.".into()), + } + if !s.enabled { + return remove("settings", "Previews are off for this service.".into()); + } + if spec["workloadKind"] == json!("CronJob") { + return remove("settings", "Cron jobs have no previews.".into()); + } + if pull.fork && s.forks == "off" { + return remove( + "fork", + "Pull requests from forks aren't deployed. The service's preview settings can allow it." + .into(), + ); + } + if s.pulls == "label" && !pull.labels.iter().any(|l| l.eq_ignore_ascii_case(&s.label)) { + return remove("label", format!("Add the {} label to deploy it.", s.label)); + } + if s.idle_days > 0 && now_ms - pull.pushed_ms > s.idle_days * 86_400_000 { + let days = if s.idle_days == 1 { + "a day".to_owned() + } else { + format!("{} days", s.idle_days) + }; + return remove( + "idle", + format!("Removed after {days} without a push. Push to bring it back."), + ); + } + let trusted = !pull.fork || s.forks == "secrets"; + Decision::Run { + copy_secrets: s.copy_secrets && trusted, + secret_overrides: trusted, + } +} + +/// The copy's port for its URL: the first one websites use, else the +/// first HTTP one. None for a service that serves no website. +fn web_port(spec: &Value) -> Option { + let ports = spec["ports"].as_array()?; + ports + .iter() + .find(|p| p["exposure"] == json!("http")) + .or_else(|| { + ports + .iter() + .find(|p| p["protocol"].as_str().is_none_or(|x| x == "HTTP")) + }) + .and_then(|p| p["name"].as_str()) + .filter(|n| !n.is_empty()) + .map(str::to_owned) +} + +/// The copy's configuration: the service's, built from the pull request's +/// head, with its own name, URL and variables. No volumes (they're +/// attached apart), cron jobs, autoscaling, public TCP or UDP ports or +/// secret store imports (unless secrets are copied); one replica. +pub fn copy_spec( + src: &Value, + s: &Settings, + name: &str, + domain: Option, + pull: &PullRow, + copy_secrets: bool, + secret_overrides: bool, +) -> Value { + let mut spec = src.clone(); + // Where it runs: the service's servers and tags (placement.rs), as + // `placement`. Nothing else pins it: it has no volumes of its own. + let placed = crate::placement::Placement::of(src); + if let Some(o) = spec.as_object_mut() { + o.remove("servers"); + o.remove("serverTags"); + o.remove("placement"); + if !placed.any() { + o.insert("placement".into(), placed.to_value()); + } + } + let url = domain + .as_ref() + .and_then(|d| d["hostname"].as_str()) + .map(|h| format!("https://{h}")); + let port = domain + .as_ref() + .and_then(|d| d["portName"].as_str()) + .map(str::to_owned); + let Some(o) = spec.as_object_mut() else { + return spec; + }; + for k in ["previews", "autoscale", "cronJobs", "description"] { + o.remove(k); + } + if !copy_secrets { + o.remove("secretImports"); + } + o.insert("name".into(), json!(name)); + o.insert("replicas".into(), json!(1)); + if let Some(src) = o.get_mut("source").and_then(Value::as_object_mut) { + src.insert("commit".into(), json!(pull.head_sha)); + src.insert("branch".into(), json!(pull.build_ref())); + src.insert("autoDeploy".into(), json!(false)); + } + if let Some(ports) = o.get_mut("ports").and_then(Value::as_array_mut) { + ports.retain(|p| !matches!(p["exposure"].as_str(), Some("nodeport" | "loadbalancer"))); + for p in ports.iter_mut() { + let theirs = port.as_deref().is_some_and(|n| p["name"] == json!(n)); + if p["exposure"] == json!("http") || theirs { + p["exposure"] = json!(if theirs { "http" } else { "internal" }); + } + } + } + o.insert("domains".into(), Value::Array(domain.into_iter().collect())); + let mut env: Vec = o + .get("env") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default() + .into_iter() + .filter(|e| copy_secrets || e["secret"] != json!(true)) + .collect(); + let mut set = |e: Value| match env.iter_mut().find(|x| x["key"] == e["key"]) { + Some(x) => *x = e, + None => env.push(e), + }; + for e in &s.env { + if e["secret"] == json!(true) && !secret_overrides { + continue; + } + set(e.clone()); + } + let mut ours = vec![ + ("PYO_PREVIEW", "1".to_owned()), + ("PYO_PULL_REQUEST", pull.number.to_string()), + ]; + if let Some(u) = url { + ours.push(("PYO_PREVIEW_URL", u)); + } + for (k, v) in ours { + set( + json!({ "id": format!("env_{}", k.to_lowercase()), "key": k, "value": v, "secret": false }), + ); + } + o.insert("env".into(), Value::Array(env)); + spec +} + +// ── Running ──────────────────────────────────────────────────────────────── + +async fn load_previews( + tx: &mut Transaction<'_, Postgres>, + pull_id: &str, +) -> sqlx::Result> { + sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT {PREVIEW_COLS} FROM pyo.previews WHERE pull_id = $1 ORDER BY created_at FOR UPDATE" + ))) + .bind(pull_id) + .fetch_all(&mut **tx) + .await +} + +/// Brings a pull request's previews in line with it and with its services' +/// settings: starts, redeploys, holds or removes them. The bot reports +/// what changed afterwards (a job). +pub async fn reconcile(s: &AppState, pull_id: &str) -> ApiResult<()> { + let mut wake: Vec = vec![]; + let mut tx = s.db.begin().await?; + let Some(pull) = load_pull(&mut tx, pull_id, true).await? else { + return Ok(()); + }; + let sources = sources( + &mut tx, + &pull.team_id, + &pull.provider, + pull.connection_id.as_deref(), + &pull.repo, + ) + .await?; + let previews = load_previews(&mut tx, pull_id).await?; + let now = now_ms(); + let mut changed = false; + // A service that stopped previewing (turned off, deleted, moved to + // another repository): its preview goes. + for p in &previews { + if p.state != "removed" && !sources.iter().any(|x| x.id == p.service_id) { + remove( + &mut tx, + p, + "settings", + "Previews are off for this service.", + &mut wake, + ) + .await?; + changed = true; + } + } + for src in &sources { + let settings = Settings::of(&src.spec); + let existing = previews.iter().find(|p| p.service_id == src.id); + match decide(&pull, &settings, &src.spec, now) { + Decision::Remove { reason, message } => { + if let Some(p) = existing.filter(|p| p.state != "removed") { + remove(&mut tx, p, reason, &message, &mut wake).await?; + changed = true; + } + } + Decision::Run { + copy_secrets, + secret_overrides, + } => { + changed |= run( + &mut tx, + &pull, + src, + &settings, + (copy_secrets, secret_overrides), + existing, + &mut wake, + ) + .await?; + } + } + } + if changed { + crate::jobs::enqueue(&mut *tx, "preview.report", json!({ "pullId": pull_id })).await?; + } + tx.commit().await?; + for c in wake { + s.wake(&c).await; + } + if changed { + s.wake(&format!("builders:{}", pull.team_id)).await; + } + Ok(()) +} + +/// Starts or redeploys a service's preview, or holds it over the limit. +/// Whether anything changed. +async fn run( + tx: &mut Transaction<'_, Postgres>, + pull: &PullRow, + src: &Source, + settings: &Settings, + secrets: (bool, bool), + p: Option<&PreviewRow>, + wake: &mut Vec, +) -> ApiResult { + if let Some(p) = p { + match p.state.as_str() { + // Removed by someone, nothing pushed since: it stays removed. + "removed" if p.removed_reason.as_deref() == Some("user") && p.sha == pull.head_sha => { + return Ok(false); + } + // Tried this commit already: the next push, or Redeploy. + "failed" if p.sha == pull.head_sha => return Ok(false), + "active" if p.sha == pull.head_sha && copy_alive(tx, p).await? => return Ok(false), + _ => {} + } + } + let starting = p.is_none_or(|p| matches!(p.state.as_str(), "removed" | "waiting")); + if starting { + let running: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pyo.previews WHERE service_id = $1 AND state IN ('active', 'failed') AND pull_id <> $2", + ) + .bind(&src.id) + .bind(&pull.id) + .fetch_one(&mut **tx) + .await?; + if running >= settings.limit { + let message = format!( + "{} previews of {} run already, its limit. This one starts when one of them goes.", + running, src.name + ); + return hold(tx, pull, src, p, &message).await; + } + } + start(tx, pull, src, settings, secrets, p, wake).await?; + Ok(true) +} + +/// Whether a preview's copy is there and not going. +async fn copy_alive(tx: &mut Transaction<'_, Postgres>, p: &PreviewRow) -> ApiResult { + let Some(copy) = &p.preview_service_id else { + return Ok(false); + }; + Ok(sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (SELECT 1 FROM pyo.services WHERE id = $1 AND NOT deleting)", + ) + .bind(copy) + .fetch_one(&mut **tx) + .await?) +} + +/// A preview that waits: over the limit, or for its last copy to go. +async fn hold( + tx: &mut Transaction<'_, Postgres>, + pull: &PullRow, + src: &Source, + p: Option<&PreviewRow>, + message: &str, +) -> ApiResult { + if let Some(p) = p { + if p.state == "waiting" && p.message.as_deref() == Some(message) { + return Ok(false); + } + sqlx::query("UPDATE pyo.previews SET state = 'waiting', message = $2, removed_reason = NULL, updated_at = now() WHERE id = $1") + .bind(&p.id) + .bind(message) + .execute(&mut **tx) + .await?; + return Ok(true); + } + let name = pick_name(tx, src, pull.number).await?; + sqlx::query("INSERT INTO pyo.previews (id, team_id, pull_id, service_id, name, state, message) VALUES ($1, $2, $3, $4, $5, 'waiting', $6)") + .bind(new_id("pvw")) + .bind(&src.team_id) + .bind(&pull.id) + .bind(&src.id) + .bind(&name) + .bind(message) + .execute(&mut **tx) + .await?; + Ok(true) +} + +/// A free name for a copy in the service's project. +async fn pick_name( + tx: &mut Transaction<'_, Postgres>, + src: &Source, + number: i64, +) -> ApiResult { + for name in [ + naming::label(&src.name, number, naming::NAME_MAX), + naming::label_salted(&src.name, number, naming::NAME_MAX, &src.id), + ] { + let taken: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.services WHERE project_id = $1 AND name = $2) + OR EXISTS (SELECT 1 FROM pyo.previews WHERE name = $2 AND service_id IN (SELECT id FROM pyo.services WHERE project_id = $1) AND service_id <> $3)", + ) + .bind(&src.project_id) + .bind(&name) + .bind(&src.id) + .fetch_one(&mut **tx) + .await?; + if !taken { + return Ok(name); + } + } + Err(ApiError::conflict(format!( + "{} has another service named like its preview.", + src.name + ))) +} + +/// Creates or updates the copy and deploys the pull request's head. A +/// deploy Pyo can't start (no builder, a check that failed) leaves the +/// preview failed, with why. +async fn start( + tx: &mut Transaction<'_, Postgres>, + pull: &PullRow, + src: &Source, + settings: &Settings, + (copy_secrets, secret_overrides): (bool, bool), + p: Option<&PreviewRow>, + wake: &mut Vec, +) -> ApiResult<()> { + let id = p.map(|p| p.id.clone()).unwrap_or_else(|| new_id("pvw")); + let name = match p { + Some(p) => p.name.clone(), + None => pick_name(tx, src, pull.number).await?, + }; + // The last copy is still going (its name is taken): wait for it. + let live_copy = match p { + Some(p) if copy_alive(tx, p).await? => p.preview_service_id.clone(), + _ => None, + }; + if live_copy.is_none() { + let busy: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.services WHERE project_id = $1 AND name = $2)", + ) + .bind(&src.project_id) + .bind(&name) + .fetch_one(&mut **tx) + .await?; + if busy { + return hold(tx, pull, src, p, "Starts once its last copy is gone.") + .await + .map(|_| ()); + } + } + let port = web_port(&src.spec); + let host = match &port { + None => Ok(None), + Some(_) => { + domain::host_for( + tx, + &src.cluster_id, + settings, + &src.name, + pull.number, + &src.id, + p.and_then(|p| p.hostname.as_deref()), + &id, + live_copy.as_deref(), + ) + .await? + } + }; + sqlx::query( + "INSERT INTO pyo.previews (id, team_id, pull_id, service_id, name, state) VALUES ($1, $2, $3, $4, $5, 'active') + ON CONFLICT (id) DO NOTHING", + ) + .bind(&id) + .bind(&src.team_id) + .bind(&pull.id) + .bind(&src.id) + .bind(&name) + .execute(&mut **tx) + .await?; + let host = match host { + Ok(h) => h, + Err(why) => { + fail(tx, &id, &pull.head_sha, &why).await?; + return Ok(()); + } + }; + // Its domain: the one it has when the host is the same (its DNS and + // certificate state stay), else a new one. + let current: Value = match &live_copy { + Some(c) => { + sqlx::query_scalar( + "SELECT coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1", + ) + .bind(c) + .fetch_one(&mut **tx) + .await? + } + None => json!([]), + }; + let domain = match (&host, &port) { + (Some(h), Some(port)) => Some( + current + .as_array() + .and_then(|ds| ds.iter().find(|d| d["hostname"] == json!(h)).cloned()) + .map(|mut d| { + d["portName"] = json!(port); + d + }) + .unwrap_or_else(|| domain::new_domain(h, port)), + ), + _ => None, + }; + let domain = match domain { + Some(d) => Some(domain::with_certificate(tx, &src.cluster_id, d).await?), + None => None, + }; + let mut spec = copy_spec( + &src.spec, + settings, + &name, + domain, + pull, + copy_secrets, + secret_overrides, + ); + crate::vault::get() + .seal_env(&src.team_id, &mut spec) + .await?; + let copy = match &live_copy { + Some(c) => { + let routes_changed = crate::routes::differ(¤t, &spec["domains"]); + sqlx::query("UPDATE pyo.services SET spec = $2, updated_at = now() WHERE id = $1") + .bind(c) + .bind(&spec) + .execute(&mut **tx) + .await?; + if routes_changed { + crate::routes::changed(tx, c, false).await?; + } + c.clone() + } + None => { + let c = new_id("svc"); + sqlx::query("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status, preview_of) VALUES ($1, $2, $3, $4, $5, $6, 'deploying', $7)") + .bind(&c) + .bind(&src.team_id) + .bind(&src.project_id) + .bind(&src.cluster_id) + .bind(&name) + .bind(&spec) + .bind(&src.id) + .execute(&mut **tx) + .await?; + c + } + }; + sqlx::query("UPDATE pyo.previews SET preview_service_id = $2, hostname = $3, state = 'active', removed_reason = NULL, updated_at = now() WHERE id = $1") + .bind(&id) + .bind(©) + .bind(&host) + .execute(&mut **tx) + .await?; + // A build of an older head still running: it stops first, and once + // it settled the next pass deploys this one. + let in_flight: Option<(String, String)> = sqlx::query_as( + "SELECT id, coalesce(data->'source'->>'commit', '') FROM pyo.deployments + WHERE service_id = $1 AND status NOT IN ('succeeded', 'failed', 'cancelled') ORDER BY created_at DESC LIMIT 1", + ) + .bind(©) + .fetch_optional(&mut **tx) + .await?; + if let Some((dep, commit)) = in_flight { + if commit == pull.head_sha { + sqlx::query("UPDATE pyo.previews SET sha = $2, deployment_id = $3, message = NULL WHERE id = $1") + .bind(&id) + .bind(&pull.head_sha) + .bind(&dep) + .execute(&mut **tx) + .await?; + } else { + wake.push(deploy::cancel(tx, &dep).await?); + } + return Ok(()); + } + let dep = new_id("dpl"); + let actor = if pull.author.is_empty() { + "Preview".to_owned() + } else { + pull.author.clone() + }; + let mut sp = sqlx::Acquire::begin(&mut **tx).await?; + let made = deploy::create( + &mut sp, + DeployRequest { + deployment_id: &dep, + service_id: ©, + trigger: "preview", + actor: &actor, + rollback_of: None, + retry_of: None, + commit: Some(&pull.head_sha), + upload: None, + }, + ) + .await; + match made { + Ok(cluster) => { + sp.commit().await?; + wake.push(cluster); + sqlx::query("UPDATE pyo.previews SET sha = $2, deployment_id = $3, message = NULL, updated_at = now() WHERE id = $1") + .bind(&id) + .bind(&pull.head_sha) + .bind(&dep) + .execute(&mut **tx) + .await?; + } + Err(e) => { + sp.rollback().await?; + fail(tx, &id, &pull.head_sha, &e.message).await?; + } + } + Ok(()) +} + +async fn fail(tx: &mut Transaction<'_, Postgres>, id: &str, sha: &str, why: &str) -> ApiResult<()> { + sqlx::query("UPDATE pyo.previews SET state = 'failed', sha = $2, message = $3, updated_at = now() WHERE id = $1") + .bind(id) + .bind(sha) + .bind(why) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Removes a preview: its copy goes from the cluster (as a deleted service +/// does), and it's kept as removed, with why. +async fn remove( + tx: &mut Transaction<'_, Postgres>, + p: &PreviewRow, + reason: &str, + message: &str, + wake: &mut Vec, +) -> ApiResult<()> { + if let Some(copy) = &p.preview_service_id { + delete_copy(tx, copy, wake).await?; + } + sqlx::query("UPDATE pyo.previews SET state = 'removed', removed_reason = $2, message = $3, updated_at = now() WHERE id = $1") + .bind(&p.id) + .bind(reason) + .bind(message) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Deletes a copy as DeleteService does: what runs stops, the agent removes +/// its objects, and the row goes when it reports back. +async fn delete_copy( + tx: &mut Transaction<'_, Postgres>, + copy: &str, + wake: &mut Vec, +) -> ApiResult<()> { + let row: Option<(String, bool)> = + sqlx::query_as("SELECT cluster_id, deleting FROM pyo.services WHERE id = $1 FOR UPDATE") + .bind(copy) + .fetch_optional(&mut **tx) + .await?; + let Some((cluster, deleting)) = row else { + return Ok(()); + }; + if deleting { + return Ok(()); + } + let service = crate::ops::service_ref(tx, copy).await?; + sqlx::query("UPDATE pyo.services SET deleting = true WHERE id = $1") + .bind(copy) + .execute(&mut **tx) + .await?; + sqlx::query("UPDATE pyo.build_jobs SET status = 'cancelled', finished_at = now() WHERE status IN ('queued', 'running') AND deployment_id IN (SELECT id FROM pyo.deployments WHERE service_id = $1)") + .bind(copy) + .execute(&mut **tx) + .await?; + sqlx::query("UPDATE pyo.deployments SET status = 'cancelled', finished_at = now() WHERE service_id = $1 AND status NOT IN ('succeeded', 'failed', 'cancelled')") + .bind(copy) + .execute(&mut **tx) + .await?; + deploy::enqueue(tx, &cluster, Command::DeleteService(service)).await?; + crate::sites::sync(tx, &cluster).await?; + wake.push(cluster); + Ok(()) +} + +// ── Hooks from the rest of Pyo ───────────────────────────────────────────── + +/// Whether a service is a preview's copy. +pub async fn is_copy<'e>(db: impl sqlx::PgExecutor<'e>, service_id: &str) -> sqlx::Result { + sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.services WHERE id = $1 AND preview_of IS NOT NULL)", + ) + .bind(service_id) + .fetch_one(db) + .await +} + +/// A deployment of a copy moved on (the "git.status" job, instead of a +/// commit status): the bot says so, and its pull request is brought in line +/// (a newer head may wait for this one to stop). +pub async fn deployment_changed(s: &AppState, deployment_id: &str) -> anyhow::Result { + let pull: Option = sqlx::query_scalar( + "SELECT p.pull_id FROM pyo.previews p JOIN pyo.deployments d ON d.service_id = p.preview_service_id WHERE d.id = $1", + ) + .bind(deployment_id) + .fetch_optional(&s.db) + .await?; + let Some(pull) = pull else { + return Ok(false); + }; + reconcile(s, &pull) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + crate::jobs::enqueue(&s.db, "preview.report", json!({ "pullId": pull })).await?; + Ok(true) +} + +/// A service's placement changed (and went live): its running copies +/// follow, in place too. One mid-deploy keeps it for its next deploy (a +/// push re-copies the service anyway). +pub async fn placement_changed( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + wake: &mut Vec, +) -> ApiResult<()> { + let spec: Value = sqlx::query_scalar("SELECT spec FROM pyo.services WHERE id = $1") + .bind(service_id) + .fetch_one(&mut **tx) + .await?; + let placed = crate::placement::Placement::of(&spec); + let value = if placed.any() { + Value::Null + } else { + placed.to_value() + }; + let copies: Vec<(String, Value)> = sqlx::query_as( + "SELECT id, spec FROM pyo.services WHERE preview_of = $1 AND NOT deleting FOR UPDATE", + ) + .bind(service_id) + .fetch_all(&mut **tx) + .await?; + for (copy, mut cspec) in copies { + if let Some(o) = cspec.as_object_mut() { + o.remove("servers"); + o.remove("serverTags"); + o.remove("placement"); + if !value.is_null() { + o.insert("placement".into(), value.clone()); + } + } + sqlx::query("UPDATE pyo.services SET spec = $2, updated_at = now() WHERE id = $1") + .bind(©) + .bind(&cspec) + .execute(&mut **tx) + .await?; + let mut sp = sqlx::Acquire::begin(&mut **tx).await?; + match crate::placement::go_live(&mut sp, ©, &cspec).await { + Ok(c) => { + sp.commit().await?; + wake.extend(c); + } + // A deploy is running: it goes out with the next one. + Err(_) => sp.rollback().await?, + } + } + Ok(()) +} + +/// A service is being deleted: its previews go with it (their copies too). +/// A copy deleted by hand: its preview stays removed until the next push. +pub async fn service_deleted( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + wake: &mut Vec, +) -> ApiResult<()> { + let rows: Vec = sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT {PREVIEW_COLS} FROM pyo.previews WHERE (service_id = $1 OR preview_service_id = $1) AND state <> 'removed' FOR UPDATE" + ))) + .bind(service_id) + .fetch_all(&mut **tx) + .await?; + for p in &rows { + let own = p.preview_service_id.as_deref() == Some(service_id); + let (reason, message) = if own { + ("user", "Removed. The next push brings it back.") + } else { + ("settings", "The service was deleted.") + }; + // The copy being deleted by hand is the caller's to delete. + if own { + sqlx::query("UPDATE pyo.previews SET state = 'removed', removed_reason = $2, message = $3, updated_at = now() WHERE id = $1") + .bind(&p.id) + .bind(reason) + .bind(message) + .execute(&mut **tx) + .await?; + } else { + remove(tx, p, reason, message, wake).await?; + } + crate::jobs::enqueue(&mut **tx, "preview.report", json!({ "pullId": p.pull_id })).await?; + } + Ok(()) +} + +/// A service's settings were saved: its open pull requests' previews follow +/// (on, off, a new limit or label), in the background. +pub async fn settings_saved( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + before: &Value, + after: &Value, +) -> ApiResult<()> { + if before.get("previews") == after.get("previews") && before["source"] == after["source"] { + return Ok(()); + } + crate::jobs::enqueue( + &mut **tx, + "preview.sync", + json!({ "serviceId": service_id }), + ) + .await?; + Ok(()) +} + +/// The "preview.sync" job: every known open pull request of the service's +/// repository, and a fresh look at the provider's open ones (previews just +/// turned on). +pub async fn sync_service(s: &AppState, service_id: &str) -> anyhow::Result<()> { + let row: Option<(String, Value)> = + sqlx::query_as("SELECT team_id, spec FROM pyo.services WHERE id = $1") + .bind(service_id) + .fetch_optional(&s.db) + .await?; + let Some((team, spec)) = row else { + return Ok(()); + }; + let src = &spec["source"]; + if Settings::of(&spec).enabled + && let Err(e) = poll_source(s, &team, src).await + { + tracing::info!(service = %service_id, error = %format!("{e:#}"), "previews: couldn't list pull requests"); + } + let pulls: Vec = sqlx::query_scalar( + "SELECT DISTINCT pull_id FROM pyo.previews WHERE service_id = $1 AND state <> 'removed' + UNION SELECT id FROM pyo.pull_requests WHERE team_id = $2 AND state = 'open'", + ) + .bind(service_id) + .bind(&team) + .fetch_all(&s.db) + .await?; + for p in pulls { + reconcile(s, &p) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + } + Ok(()) +} + +// ── The bot ──────────────────────────────────────────────────────────────── + +/// A preview with what the bot needs to say about it. +#[derive(sqlx::FromRow, Debug, Clone)] +pub struct View { + #[sqlx(flatten)] + pub row: PreviewRow, + pub service: String, + pub deployment_status: Option, + pub copy_left: bool, + pub updated_ms: i64, +} + +impl View { + pub fn shown(&self) -> Shown { + Shown::of( + &self.row.state, + self.deployment_status.as_deref(), + self.copy_left, + ) + } + + pub fn url(&self) -> Option { + self.row.hostname.as_ref().map(|h| format!("https://{h}")) + } +} + +async fn views(tx: &mut Transaction<'_, Postgres>, pull_id: &str) -> sqlx::Result> { + sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT {}, s.name AS service, d.status AS deployment_status, + (c.id IS NOT NULL) AS copy_left, pyo.ms(greatest(p.updated_at, coalesce(d.finished_at, d.created_at, p.updated_at))) AS updated_ms + FROM pyo.previews p JOIN pyo.services s ON s.id = p.service_id + LEFT JOIN pyo.deployments d ON d.id = p.deployment_id + LEFT JOIN pyo.services c ON c.id = p.preview_service_id + WHERE p.pull_id = $1 ORDER BY s.name", + PREVIEW_COLS + .split(", ") + .map(|c| format!("p.{c}")) + .collect::>() + .join(", ") + ))) + .bind(pull_id) + .fetch_all(&mut **tx) + .await +} + +/// One place a pull request lives (GitHub through the app, GitLab through +/// the team's connection): what the bot can do there. +pub trait Forge { + /// Posts the comment, or edits it in place (posting it again when it + /// was deleted). Its id. + async fn comment(&self, id: Option, body: &str) -> anyhow::Result; + /// Sets the check on `sha`: a new one when `id` is None. Its id. + async fn check( + &self, + id: Option, + sha: &str, + check: &bot::Check, + details: Option<&str>, + ) -> anyhow::Result>; + /// Brings the preview's deployment (and environment) on the provider in + /// line with how it's shown. + async fn deployment(&self, d: &mut Remote, shown: Shown) -> anyhow::Result<()>; +} + +/// A preview's deployment on the provider. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Remote { + /// The copy's name ("web-pr-42") and the service's ("web"). + pub name: String, + pub service: String, + pub sha: String, + pub head_ref: String, + pub url: Option, + pub logs: Option, + pub deployment_id: Option, + pub deployment_sha: Option, + pub environment_id: Option, +} + +/// The "preview.report" job: the bot says where a pull request's previews +/// stand, on the provider. Only what changed since it last said it. +pub async fn report(s: &AppState, pull_id: &str) -> anyhow::Result<()> { + let mut tx = s.db.begin().await?; + let Some(pull) = load_pull(&mut tx, pull_id, true).await? else { + return Ok(()); + }; + let views = views(&mut tx, pull_id).await?; + if views.is_empty() && pull.comment_id.is_none() { + return Ok(()); + } + let slug: String = sqlx::query_scalar("SELECT slug FROM pyo.teams WHERE id = $1") + .bind(&pull.team_id) + .fetch_one(&mut *tx) + .await?; + let out = match pull.provider.as_str() { + "github" => { + let Some(f) = github::Forge::for_pull(s, &pull).await? else { + return Ok(()); + }; + let base = format!("{}/{slug}", f.dashboard()); + say(&mut tx, &f, &pull, &views, &base).await + } + _ => { + let Some(f) = gitlab::Forge::for_pull(s, &pull).await? else { + return Ok(()); + }; + let base = format!("{}/{slug}", f.dashboard()); + say(&mut tx, &f, &pull, &views, &base).await + } + }; + tx.commit().await?; + out +} + +/// What the bot says, and what it keeps of it. Goes on past a call that +/// failed (and keeps what worked), then returns its error so the job tries +/// again. +pub async fn say( + tx: &mut Transaction<'_, Postgres>, + forge: &F, + pull: &PullRow, + views: &[View], + base: &str, +) -> anyhow::Result<()> { + let base = base.trim_end_matches('/'); + let logs = |v: &View| { + v.row + .deployment_id + .as_ref() + .filter(|_| base.starts_with("http")) + .map(|d| format!("{base}/deployments/{d}")) + }; + let rows: Vec = views + .iter() + .map(|v| bot::Row { + service: v.service.clone(), + shown: v.shown(), + url: v.url(), + message: v.row.message.clone(), + updated_ms: v.updated_ms, + logs: logs(v), + }) + .collect(); + let open = pull.state == "open"; + let mut first_error: Option = None; + let mut keep = |e: anyhow::Error| { + tracing::info!(pull = %pull.id, error = %format!("{e:#}"), "previews: the bot couldn't say it"); + if first_error.is_none() { + first_error = Some(e); + } + }; + + let body = bot::comment(&pull.team_id, &rows, open); + let h = bot::hash(&body); + if pull.comment_hash.as_deref() != Some(h.as_str()) { + match forge.comment(pull.comment_id, &body).await { + Ok(id) => { + sqlx::query( + "UPDATE pyo.pull_requests SET comment_id = $2, comment_hash = $3 WHERE id = $1", + ) + .bind(&pull.id) + .bind(id) + .bind(&h) + .execute(&mut **tx) + .await?; + } + Err(e) => keep(e), + } + } + + // The check, on the head. A closed pull request's check that was still + // running is finished, neutral. + let check = if open && !rows.is_empty() { + Some(bot::check(&rows)) + } else if !open && pull.check_sha.as_deref() == Some(pull.head_sha.as_str()) { + Some(bot::Check { + status: "completed", + conclusion: Some("neutral"), + title: "Removed".into(), + summary: "The pull request closed.".into(), + }) + } else { + None + }; + if let Some(c) = check { + // ":": a check that finished and builds again is a new + // one (GitHub keeps the finished one). + let key = format!( + "{}:{}", + c.status, + bot::hash(&format!("{}:{:?}", pull.head_sha, c)) + ); + if pull.check_hash.as_deref() != Some(key.as_str()) && !pull.head_sha.is_empty() { + let was_running = pull + .check_hash + .as_deref() + .is_some_and(|h| h.starts_with("in_progress:")); + let id = if pull.check_sha.as_deref() == Some(pull.head_sha.as_str()) + && (c.status != "in_progress" || was_running) + { + pull.check_id + } else { + None + }; + let details = rows.iter().find_map(|r| r.logs.clone()); + match forge + .check(id, &pull.head_sha, &c, details.as_deref()) + .await + { + Ok(id) => { + sqlx::query("UPDATE pyo.pull_requests SET check_id = $2, check_sha = $3, check_hash = $4 WHERE id = $1") + .bind(&pull.id) + .bind(id) + .bind(&pull.head_sha) + .bind(&key) + .execute(&mut **tx) + .await?; + } + Err(e) => keep(e), + } + } + } + + for v in views { + let shown = v.shown(); + // Nothing deployed yet: nothing to show on the provider. + if v.row.sha.is_empty() && v.row.remote_deployment_id.is_none() { + continue; + } + let key = format!( + "{}:{}:{}", + v.row.sha, + shown.key(), + v.row.hostname.as_deref().unwrap_or("") + ); + if v.row.reported.as_deref() == Some(key.as_str()) { + continue; + } + let mut r = Remote { + name: v.row.name.clone(), + service: v.service.clone(), + sha: v.row.sha.clone(), + head_ref: pull.head_ref.clone(), + url: v.url(), + logs: logs(v), + deployment_id: v.row.remote_deployment_id, + deployment_sha: v.row.remote_deployment_sha.clone(), + environment_id: v.row.remote_environment_id, + }; + let out = forge.deployment(&mut r, shown).await; + sqlx::query("UPDATE pyo.previews SET remote_deployment_id = $2, remote_deployment_sha = $3, remote_environment_id = $4, reported = $5 WHERE id = $1") + .bind(&v.row.id) + .bind(r.deployment_id) + .bind(&r.deployment_sha) + .bind(r.environment_id) + .bind(if out.is_ok() { Some(key.as_str()) } else { v.row.reported.as_deref() }) + .execute(&mut **tx) + .await?; + if let Err(e) = out { + keep(e); + } + } + match first_error { + Some(e) => Err(e), + None => Ok(()), + } +} + +// ── The loop ─────────────────────────────────────────────────────────────── + +/// Every 30 seconds, on one process: pull requests from providers that send +/// no webhooks (each minute; every 10 minutes everywhere, for missed ones), +/// previews waiting or idle, the clusters' preview domains, and GitHub's +/// permissions (every 30 minutes). +pub async fn runner(s: AppState) { + let mut tick = tokio::time::interval(Duration::from_secs(30)); + let mut n: u64 = 0; + loop { + tick.tick().await; + let i = n; + n += 1; + crate::bg::as_leader(&s.db, LOCK, || pass(&s, i)).await; + } +} + +async fn pass(s: &AppState, n: u64) { + if n.is_multiple_of(2) + && let Err(e) = poll(s, n.is_multiple_of(20)).await + { + tracing::warn!(error = %e.message, "previews: polling"); + } + if n.is_multiple_of(2) + && let Err(e) = sweep(s).await + { + tracing::warn!(error = %e.message, "previews: sweep"); + } + if let Err(e) = domain::tick(s).await { + tracing::warn!(error = %e.message, "previews: domains"); + } + if n.is_multiple_of(60) { + github::check_all(s).await; + } +} + +/// Open pull requests with previews that may have to move: waiting ones, +/// idle ones, ones whose deploy didn't start. Each is brought in line. +async fn sweep(s: &AppState) -> ApiResult<()> { + let pulls: Vec = sqlx::query_scalar( + "SELECT DISTINCT pr.id FROM pyo.pull_requests pr JOIN pyo.previews p ON p.pull_id = pr.id + WHERE (pr.state = 'open' AND p.state IN ('waiting', 'active', 'failed')) + OR (pr.state <> 'open' AND p.state <> 'removed')", + ) + .fetch_all(&s.db) + .await?; + for p in pulls { + if let Err(e) = reconcile(s, &p).await { + tracing::info!(pull = %p, error = %e.message, "previews: couldn't bring it in line"); + } + } + Ok(()) +} + +/// The repositories with previews on: their open pull requests, from the +/// provider. Those a webhook covers only every 10 minutes (`all`). +async fn poll(s: &AppState, all: bool) -> ApiResult<()> { + let rows: Vec<(String, Value)> = sqlx::query_as( + "SELECT DISTINCT team_id, spec->'source' FROM pyo.services + WHERE NOT deleting AND preview_of IS NULL AND coalesce((spec->'previews'->>'enabled')::bool, false)", + ) + .fetch_all(&s.db) + .await?; + let github_hooks = crate::github::app(&s.db) + .await? + .is_some_and(|a| a.webhook_active); + for (team, src) in rows { + let hooked = if src["installationId"].is_i64() { + github_hooks + } else { + gitlab::hooked(&s.db, &src).await.unwrap_or(false) + }; + if hooked && !all { + continue; + } + if let Err(e) = poll_source(s, &team, &src).await { + tracing::info!(repo = %src["repoUrl"], error = %format!("{e:#}"), "previews: couldn't list pull requests"); + } + } + Ok(()) +} + +/// One repository's open pull requests, and the ones Pyo has open that +/// aren't any more. +async fn poll_source(s: &AppState, team: &str, src: &Value) -> anyhow::Result<()> { + let (open, key): (Vec, (String, String, String)) = + if let Some(inst) = src["installationId"].as_i64() { + let Some(repo) = crate::github::full_name(src["repoUrl"].as_str().unwrap_or("")) else { + return Ok(()); + }; + let c = github::Client::for_installation(s, inst).await?; + ( + c.open_pulls(&repo, inst).await?, + ("github".into(), inst.to_string(), repo.to_lowercase()), + ) + } else if let Some(conn) = src["gitConnectionId"].as_str() { + let c = crate::git::load(&s.db, Some(team), conn) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + let Some(repo) = c.repo_of(src["repoUrl"].as_str().unwrap_or("")) else { + return Ok(()); + }; + let api = c + .api() + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + let list = api.merge_requests(&repo).await?; + ( + list.iter() + .filter_map(|v| gitlab::pull_of_api(v, conn, &repo)) + .collect(), + ("gitlab".into(), conn.to_owned(), repo.to_lowercase()), + ) + } else { + return Ok(()); + }; + for p in &open { + pull_event(s, team, p) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + } + // Known open, not in the list: closed or merged since. + let known: Vec = sqlx::query_scalar( + "SELECT number FROM pyo.pull_requests WHERE team_id = $1 AND provider = $2 AND source = $3 AND repo = $4 AND state = 'open'", + ) + .bind(team) + .bind(&key.0) + .bind(&key.1) + .bind(&key.2) + .fetch_all(&s.db) + .await?; + for n in known { + if open.iter().any(|p| p.number == n) { + continue; + } + let p = match key.0.as_str() { + "github" => { + let inst = key.1.parse().unwrap_or(0); + github::Client::for_installation(s, inst) + .await? + .pull(&key.2, n, inst) + .await? + } + _ => { + let c = crate::git::load(&s.db, Some(team), &key.1) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + let api = c + .api() + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + gitlab::pull_of_api(&api.merge_request(&key.2, n).await?, &key.1, &key.2) + } + }; + if let Some(p) = p { + pull_event(s, team, &p) + .await + .map_err(|e| anyhow::anyhow!("{}", e.message))?; + } + } + Ok(()) +} + +// ── The dashboard ────────────────────────────────────────────────────────── + +/// The previews the dashboard shows: those not removed, and those removed +/// in the last day. +pub async fn snapshot(db: &mut sqlx::PgConnection, team_ids: &[String]) -> ApiResult> { + #[derive(sqlx::FromRow)] + struct Listed { + #[sqlx(flatten)] + row: PreviewRow, + provider: String, + repo: String, + number: i64, + title: String, + url: String, + head_ref: String, + author: String, + fork: bool, + pull_state: String, + deployment_status: Option, + copy_left: bool, + created_ms: i64, + updated_ms: i64, + } + let rows: Vec = sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT {}, pr.provider, pr.repo, pr.number, pr.title, pr.url, pr.head_ref, pr.author, pr.fork, pr.state AS pull_state, + d.status AS deployment_status, (c.id IS NOT NULL) AS copy_left, + pyo.ms(p.created_at) AS created_ms, pyo.ms(greatest(p.updated_at, coalesce(d.finished_at, d.created_at, p.updated_at))) AS updated_ms + FROM pyo.previews p JOIN pyo.pull_requests pr ON pr.id = p.pull_id + LEFT JOIN pyo.deployments d ON d.id = p.deployment_id + LEFT JOIN pyo.services c ON c.id = p.preview_service_id + WHERE p.team_id = ANY($1) AND (p.state <> 'removed' OR c.id IS NOT NULL OR p.updated_at > now() - interval '1 day') + ORDER BY pr.number DESC, p.created_at", + PREVIEW_COLS + .split(", ") + .map(|c| format!("p.{c}")) + .collect::>() + .join(", ") + ))) + .bind(team_ids) + .fetch_all(&mut *db) + .await?; + Ok(rows + .into_iter() + .map(|r| { + let shown = Shown::of(&r.row.state, r.deployment_status.as_deref(), r.copy_left); + json!({ + "id": r.row.id, "teamId": r.row.team_id, "serviceId": r.row.service_id, + "previewServiceId": r.row.preview_service_id, + "provider": r.provider, "repo": r.repo, "number": r.number, "title": r.title, "url": r.url, + "branch": r.head_ref, "sha": r.row.sha, "author": r.author, "fork": r.fork, + "name": r.row.name, "hostname": r.row.hostname, + "status": shown.key(), "message": r.row.message, "deploymentId": r.row.deployment_id, + "pullState": r.pull_state, "createdAt": r.created_ms, "updatedAt": r.updated_ms, + }) + }) + .collect()) +} + +/// deletePreview: removes a preview now. The next push brings it back. +pub async fn delete( + tx: &mut Transaction<'_, Postgres>, + user: &User, + id: &str, + wake: &mut Vec, +) -> ApiResult { + let p = owned(tx, user, id).await?; + if p.state != "removed" { + remove( + tx, + &p, + "user", + "Removed. The next push brings it back.", + wake, + ) + .await?; + } + crate::jobs::enqueue(&mut **tx, "preview.report", json!({ "pullId": p.pull_id })).await?; + log_activity( + tx, + &p.team_id, + &user.name, + "preview.removed", + "info", + &format!("Removed the preview {}", p.name), + json!({ "kind": "service", "id": p.service_id, "label": p.name }), + json!({ "serviceId": p.service_id }), + ) + .await?; + Ok(json!({ "ok": true })) +} + +/// redeployPreview: the pull request's head again, once the call commits +/// (a job): a failed one is tried again, a waiting one starts when there's +/// room, a removed one comes back. +pub async fn redeploy( + tx: &mut Transaction<'_, Postgres>, + user: &User, + id: &str, +) -> ApiResult { + let p = owned(tx, user, id).await?; + // Forget what was tried: the next pass deploys the head again. + sqlx::query("UPDATE pyo.previews SET sha = '', state = CASE WHEN state = 'removed' THEN 'waiting' ELSE state END, removed_reason = NULL, updated_at = now() WHERE id = $1") + .bind(&p.id) + .execute(&mut **tx) + .await?; + log_activity( + tx, + &p.team_id, + &user.name, + "preview.redeployed", + "info", + &format!("Redeployed the preview {}", p.name), + json!({ "kind": "service", "id": p.service_id, "label": p.name }), + json!({ "serviceId": p.service_id }), + ) + .await?; + crate::jobs::enqueue( + &mut **tx, + "preview.reconcile", + json!({ "pullId": p.pull_id }), + ) + .await?; + Ok(json!({ "ok": true })) +} + +async fn owned(tx: &mut Transaction<'_, Postgres>, user: &User, id: &str) -> ApiResult { + let p: PreviewRow = sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT {PREVIEW_COLS} FROM pyo.previews WHERE id = $1 FOR UPDATE" + ))) + .bind(id) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(|| ApiError::not_found("Preview"))?; + require_role(tx, user, &p.team_id, Role::Developer).await?; + Ok(p) +} diff --git a/crates/pyo-api/src/previews/naming.rs b/crates/pyo-api/src/previews/naming.rs new file mode 100644 index 00000000..c95773d0 --- /dev/null +++ b/crates/pyo-api/src/previews/naming.rs @@ -0,0 +1,99 @@ +//! Names of previews: `-pr-`, as the copy's name in its project +//! and as the first label of its URL. + +use crate::ids::sha256_hex; + +/// A DNS label is at most 63 characters. +pub const LABEL_MAX: usize = 63; +/// A service's name is at most 40 (util.rs `slugify`). +pub const NAME_MAX: usize = 40; + +/// `-pr-`, at most `max` characters. A longer one keeps the +/// start of the service's name and a short hash of the whole, so two long +/// names that start alike stay apart: "a-very-long-…-3f9a1c-pr-42". +pub fn label(service: &str, number: i64, max: usize) -> String { + let full = format!("{service}-pr-{number}"); + if full.len() <= max { + return full; + } + let tail = format!("-pr-{number}"); + let hash = &sha256_hex(&full)[..6]; + let keep = max.saturating_sub(tail.len() + 1 + hash.len()); + let head: String = service.chars().take(keep).collect(); + let head = head.trim_end_matches('-'); + if head.is_empty() { + format!("{hash}{tail}") + } else { + format!("{head}-{hash}{tail}") + } +} + +/// The label again, told apart by a short hash of `salt` (the service's +/// id), for when another service already has the plain one. +pub fn label_salted(service: &str, number: i64, max: usize, salt: &str) -> String { + let h = &sha256_hex(salt)[..4]; + label(&format!("{service}-{h}"), number, max) +} + +/// A host under `suffix` ("203.0.113.7.nip.io", "tail1234.ts.net", +/// "preview.example.com"). +pub fn host(label: &str, suffix: &str) -> String { + format!("{label}.{}", suffix.trim_matches('.').to_ascii_lowercase()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn short_names_stay_as_they_are() { + assert_eq!(label("web", 42, LABEL_MAX), "web-pr-42"); + assert_eq!( + host("web-pr-42", "203.0.113.7.nip.io"), + "web-pr-42.203.0.113.7.nip.io" + ); + assert_eq!( + host("web-pr-42", ".Tail1234.ts.net."), + "web-pr-42.tail1234.ts.net" + ); + } + + #[test] + fn long_names_are_cut_with_a_hash() { + let long = "a-service-with-a-really-quite-long-name-for-testing-labels"; + let l = label(long, 1234, LABEL_MAX); + assert!(l.len() <= LABEL_MAX, "{l}"); + assert!(l.ends_with("-pr-1234"), "{l}"); + assert!(l.starts_with("a-service-with"), "{l}"); + // Stable, and apart from another long name that starts the same. + assert_eq!(l, label(long, 1234, LABEL_MAX)); + assert_ne!(l, label(&format!("{long}-two"), 1234, LABEL_MAX)); + // Service names are at most 40 characters. + let n = label(long, 7, NAME_MAX); + assert!(n.len() <= NAME_MAX, "{n}"); + assert!(n.ends_with("-pr-7")); + // Exactly at the limit is kept whole. + let exact = "x".repeat(LABEL_MAX - "-pr-1".len()); + assert_eq!(label(&exact, 1, LABEL_MAX), format!("{exact}-pr-1")); + assert_ne!( + label(&format!("{exact}y"), 1, LABEL_MAX), + format!("{exact}y-pr-1") + ); + } + + #[test] + fn no_dash_before_the_hash_twice() { + // A cut that ends on a dash doesn't leave "--". + let l = label("abcdefghij-klmnopqrst", 1, 20); + assert!(!l.contains("--"), "{l}"); + assert!(l.len() <= 20, "{l}"); + } + + #[test] + fn salted_labels_differ() { + let a = label_salted("web", 42, LABEL_MAX, "svc_a"); + let b = label_salted("web", 42, LABEL_MAX, "svc_b"); + assert_ne!(a, b); + assert!(a.starts_with("web-") && a.ends_with("-pr-42"), "{a}"); + } +} diff --git a/crates/pyo-api/src/previews/tests.rs b/crates/pyo-api/src/previews/tests.rs new file mode 100644 index 00000000..49e23192 --- /dev/null +++ b/crates/pyo-api/src/previews/tests.rs @@ -0,0 +1,987 @@ +//! Previews: the rules on their own, then against a real Postgres +//! (DATABASE_URL, a throwaway one): a pull request's life (open, push, +//! close, reopen, merge), limits, forks, labels, idle ones, removal by +//! hand, and what the bot says (a fake provider records it). + +use std::sync::Mutex; + +use serde_json::{Value, json}; +use sqlx::PgPool; + +use super::*; + +fn pull(state: &str) -> PullRow { + PullRow { + id: "pr_1".into(), + team_id: "team_1".into(), + provider: "github".into(), + installation_id: Some(7), + repo: "acme/shop".into(), + number: 42, + head_ref: "search".into(), + head_sha: "a".repeat(40), + state: state.into(), + pushed_ms: 1_000_000, + ..Default::default() + } +} + +fn on() -> Settings { + Settings { + enabled: true, + ..Default::default() + } +} + +// ── The rules ────────────────────────────────────────────────────────────── + +#[test] +fn settings_are_checked_and_filled_in() { + let git = + json!({ "type": "git", "repoUrl": "https://github.com/acme/shop", "installationId": 7 }); + let mut spec = json!({ "source": git, "previews": { "enabled": true } }); + check_settings(&mut spec).unwrap(); + let s = Settings::of(&spec); + assert_eq!( + ( + s.limit, + s.pulls.as_str(), + s.forks.as_str(), + s.access.as_str() + ), + (5, "all", "off", "public") + ); + assert!(!s.copy_secrets); + // Off is fine anywhere; on needs a repository Pyo reads pull requests of. + let mut image = json!({ "source": { "type": "image", "image": "nginx" }, "previews": { "enabled": false } }); + check_settings(&mut image).unwrap(); + let mut image = + json!({ "source": { "type": "image", "image": "nginx" }, "previews": { "enabled": true } }); + assert!(check_settings(&mut image).is_err()); + let mut plain = json!({ "source": { "type": "git", "repoUrl": "https://github.com/acme/shop" }, "previews": { "enabled": true } }); + assert!( + check_settings(&mut plain).is_err(), + "a public repository without the app" + ); + let mut gitlab = json!({ "source": { "type": "git", "repoUrl": "https://gitlab.com/a/b", "gitConnectionId": "gitc_1" }, "previews": { "enabled": true } }); + check_settings(&mut gitlab).unwrap(); + let mut cron = + json!({ "source": git, "workloadKind": "CronJob", "previews": { "enabled": true } }); + assert!(check_settings(&mut cron).is_err()); + for bad in [ + json!({ "limit": 0 }), + json!({ "limit": 51 }), + json!({ "idleDays": 91 }), + json!({ "pulls": "some" }), + json!({ "pulls": "label", "label": " " }), + json!({ "access": "secret" }), + json!({ "forks": "yes" }), + json!({ "env": [{ "key": "1X", "value": "" }] }), + json!({ "env": [{ "key": "A", "value": "" }, { "key": "A", "value": "" }] }), + ] { + let mut spec = json!({ "source": git, "previews": bad }); + assert!(check_settings(&mut spec).is_err(), "{bad}"); + } + // Null clears them. + let mut spec = json!({ "source": git, "previews": null }); + check_settings(&mut spec).unwrap(); + assert!(spec.get("previews").is_none()); + // New variables get an id. + let mut spec = + json!({ "source": git, "previews": { "env": [{ "key": " API_URL ", "value": "x" }] } }); + check_settings(&mut spec).unwrap(); + assert_eq!(spec["previews"]["env"][0]["key"], "API_URL"); + assert!( + spec["previews"]["env"][0]["id"] + .as_str() + .unwrap() + .starts_with("env_") + ); +} + +fn reason(d: Decision) -> &'static str { + match d { + Decision::Remove { reason, .. } => reason, + Decision::Run { .. } => "run", + } +} + +#[test] +fn what_runs_and_what_goes() { + let spec = json!({}); + let run = |p: &PullRow, s: &Settings| decide(p, s, &spec, 2_000_000); + assert_eq!( + run(&pull("open"), &on()), + Decision::Run { + copy_secrets: false, + secret_overrides: true + } + ); + assert_eq!(reason(run(&pull("closed"), &on())), "closed"); + assert_eq!(reason(run(&pull("merged"), &on())), "merged"); + assert_eq!(reason(run(&pull("open"), &Settings::default())), "settings"); + assert_eq!( + reason(decide( + &pull("open"), + &on(), + &json!({ "workloadKind": "CronJob" }), + 0 + )), + "settings" + ); + // Labels. + let label = Settings { + pulls: "label".into(), + label: "Preview".into(), + ..on() + }; + assert_eq!(reason(run(&pull("open"), &label)), "label"); + let mut labelled = pull("open"); + labelled.labels = vec!["preview".into()]; + assert_eq!(reason(run(&labelled, &label)), "run"); + // Idle: no push for a day. + let idle = Settings { + idle_days: 1, + ..on() + }; + assert_eq!( + reason(decide( + &pull("open"), + &idle, + &spec, + 1_000_000 + 86_400_000 - 1 + )), + "run" + ); + assert_eq!( + reason(decide( + &pull("open"), + &idle, + &spec, + 1_000_000 + 86_400_000 + 1 + )), + "idle" + ); + // Secrets: only when copied, and never for a fork unless it says so. + let secrets = Settings { + copy_secrets: true, + ..on() + }; + assert_eq!( + run(&pull("open"), &secrets), + Decision::Run { + copy_secrets: true, + secret_overrides: true + } + ); + let mut fork = pull("open"); + fork.fork = true; + assert_eq!( + reason(run(&fork, &secrets)), + "fork", + "forks are off by default" + ); + let no_secrets = Settings { + forks: "no-secrets".into(), + ..secrets.clone() + }; + assert_eq!( + run(&fork, &no_secrets), + Decision::Run { + copy_secrets: false, + secret_overrides: false + } + ); + let with = Settings { + forks: "secrets".into(), + ..secrets + }; + assert_eq!( + run(&fork, &with), + Decision::Run { + copy_secrets: true, + secret_overrides: true + } + ); +} + +#[test] +fn the_copy_is_the_service_from_the_head() { + let src = json!({ + "name": "web", "replicas": 4, "description": "Shop", + "source": { "type": "git", "repoUrl": "https://github.com/acme/shop", "branch": "main", "commit": "", "installationId": 7, "autoDeploy": true }, + "ports": [ + { "name": "http", "protocol": "HTTP", "containerPort": 3000, "exposure": "http" }, + { "name": "admin", "protocol": "HTTP", "containerPort": 3001, "exposure": "http" }, + { "name": "game", "protocol": "UDP", "containerPort": 7777, "exposure": "loadbalancer", "publicPort": 7777 }, + ], + "domains": [{ "hostname": "shop.example.com", "portName": "http" }], + "env": [ + { "id": "e1", "key": "MODE", "value": "production", "secret": false }, + { "id": "e2", "key": "DATABASE_URL", "value": "postgres://prod", "secret": true }, + { "id": "e3", "key": "API_URL", "value": "https://api.example.com", "secret": false }, + ], + "autoscale": { "min": 2, "max": 9 }, "cronJobs": [{ "id": "c1" }], "secretImports": [{ "store": "s" }], + "previews": { "enabled": true }, + }); + let s = Settings { + env: vec![ + json!({ "id": "o1", "key": "API_URL", "value": "https://api-staging.example.com", "secret": false }), + json!({ "id": "o2", "key": "STRIPE_KEY", "value": "sk_test", "secret": true }), + ], + ..on() + }; + let d = domain::new_domain("web-pr-42.203.0.113.7.nip.io", "http"); + let c = copy_spec(&src, &s, "web-pr-42", Some(d), &pull("open"), false, true); + assert_eq!(c["name"], "web-pr-42"); + assert_eq!(c["replicas"], 1); + assert_eq!(c["source"]["commit"], "a".repeat(40)); + assert_eq!(c["source"]["branch"], "search"); + assert_eq!(c["source"]["autoDeploy"], false); + for k in [ + "autoscale", + "cronJobs", + "secretImports", + "previews", + "description", + ] { + assert!(c.get(k).is_none(), "{k}"); + } + assert_eq!(c["domains"].as_array().unwrap().len(), 1); + assert_eq!(c["domains"][0]["hostname"], "web-pr-42.203.0.113.7.nip.io"); + // The public UDP port can't be had twice; one website port. + let ports = c["ports"].as_array().unwrap(); + assert_eq!(ports.len(), 2); + assert_eq!(ports[0]["exposure"], "http"); + assert_eq!(ports[1]["exposure"], "internal"); + let env = |c: &Value, k: &str| { + c["env"] + .as_array() + .unwrap() + .iter() + .find(|e| e["key"] == k) + .map(|e| e["value"].clone()) + }; + assert_eq!(env(&c, "MODE"), Some(json!("production"))); + assert_eq!(env(&c, "DATABASE_URL"), None, "secrets aren't copied"); + assert_eq!( + env(&c, "API_URL"), + Some(json!("https://api-staging.example.com")), + "overridden" + ); + assert_eq!( + env(&c, "STRIPE_KEY"), + Some(json!("sk_test")), + "a secret of the previews' own" + ); + assert_eq!(env(&c, "PYO_PREVIEW"), Some(json!("1"))); + assert_eq!(env(&c, "PYO_PULL_REQUEST"), Some(json!("42"))); + assert_eq!( + env(&c, "PYO_PREVIEW_URL"), + Some(json!("https://web-pr-42.203.0.113.7.nip.io")) + ); + // With secrets; a fork without them, built from the pull request's ref. + let c = copy_spec(&src, &s, "web-pr-42", None, &pull("open"), true, true); + assert!(env(&c, "DATABASE_URL").is_some()); + assert!(c["secretImports"].is_array()); + assert_eq!(c["domains"], json!([])); + let mut fork = pull("open"); + fork.fork = true; + let c = copy_spec(&src, &s, "web-pr-42", None, &fork, false, false); + assert_eq!(c["source"]["branch"], "refs/pull/42/head"); + assert!(env(&c, "STRIPE_KEY").is_none() && env(&c, "DATABASE_URL").is_none()); + fork.provider = "gitlab".into(); + assert_eq!(fork.build_ref(), "refs/merge-requests/42/head"); +} + +#[test] +fn the_copy_runs_where_the_service_does() { + let p = pull("open"); + // Picked servers and tags come along as `placement`. + let src = json!({ "name": "web", "placement": { "servers": ["server-1"], "tags": ["gpu"] } }); + let c = copy_spec(&src, &on(), "web-pr-42", None, &p, false, true); + assert_eq!(c["placement"], json!({ "servers": ["server-1"], "tags": ["gpu"] })); + // As saved before placement: the same, as `placement`. + let old = json!({ "name": "web", "servers": ["server-2"], "serverTags": ["fast"] }); + let c = copy_spec(&old, &on(), "web-pr-42", None, &p, false, true); + assert_eq!(c["placement"], json!({ "servers": ["server-2"], "tags": ["fast"] })); + assert!(c.get("servers").is_none() && c.get("serverTags").is_none()); + // Any server: none. + let any = json!({ "name": "web", "placement": { "servers": [], "tags": [] } }); + let c = copy_spec(&any, &on(), "web-pr-42", None, &p, false, true); + assert!(c.get("placement").is_none()); +} + +// ── Against 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(); +} + +fn state(db: PgPool) -> AppState { + let config = crate::Config { + agent_api_url: String::new(), + agent_image: String::new(), + waf_image: pyo_proto::system::WAF_IMAGE_DEFAULT.into(), + geoip_image: pyo_proto::system::GEOIP_IMAGE_DEFAULT.into(), + cookie_secure: false, + allow_signup: false, + builder_image: String::new(), + relay_addr: None, + }; + let (_stop, stopping) = tokio::sync::watch::channel(false); + AppState { + db: db.clone(), + config: std::sync::Arc::new(config), + observability: crate::observability::Observability::from_env(db), + sealer: std::sync::Arc::new(crate::secrets::Sealer::for_tests()), + wakers: Default::default(), + terminals: Default::default(), + stopping, + } +} + +/// A team with a cluster (its preview domain set), a ready builder, a +/// project, the GitHub App's installation and a service of a repository +/// with previews on. +struct World { + s: AppState, + team: String, + service: String, + inst: i64, + run: String, +} + +async fn world(settings: Value) -> World { + 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 run = crate::ids::new_id("t").replace('_', "-").to_lowercase(); + let (team, cluster, project, service) = ( + format!("team_{run}"), + format!("cl_{run}"), + format!("prj_{run}"), + format!("svc_{run}"), + ); + let inst = 800_000_000 + (pyo_proto::now_ms() % 100_000_000); + 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, preview_domain) VALUES ($1, $2, $1, $1, 'connected', now(), $3)") + .bind(&cluster) + .bind(&team) + .bind(json!({ "domain": format!("{run}.preview.test") })) + .execute(&db) + .await + .unwrap(); + q("INSERT INTO pyo.builders (id, team_id, name, kind, cluster_id, server, token_hash, status) VALUES ($1, $2, $1, 'cluster', $3, 's', $1, 'ready')") + .bind(format!("bld_{run}")) + .bind(&team) + .bind(&cluster) + .execute(&db) + .await + .unwrap(); + q("INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, 'shop', $3)") + .bind(&project) + .bind(&team) + .bind(format!("shop-{run}")) + .execute(&db) + .await + .unwrap(); + q("INSERT INTO pyo.github_installations (id, team_id, account, account_type) VALUES ($1, $2, 'acme', 'Organization')") + .bind(inst) + .bind(&team) + .execute(&db) + .await + .unwrap(); + let mut spec = json!({ + "name": "web", "replicas": 2, "resources": {}, "healthCheck": { "type": "none" }, + "source": { "type": "git", "repoUrl": format!("https://github.com/acme/shop-{run}"), "branch": "main", "commit": "", "installationId": inst }, + "ports": [{ "id": "port_1", "name": "http", "protocol": "HTTP", "containerPort": 3000, "exposure": "http" }], + "env": [ + { "id": "e1", "key": "MODE", "value": "production", "secret": false }, + { "id": "e2", "key": "DATABASE_URL", "value": "postgres://prod", "secret": true }, + ], + "domains": [], + "previews": settings, + }); + check_settings(&mut spec).unwrap(); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web', $5, 'running')") + .bind(&service) + .bind(&team) + .bind(&project) + .bind(&cluster) + .bind(&spec) + .execute(&db) + .await + .unwrap(); + World { + s: state(db), + team, + service, + inst, + run, + } +} + +impl World { + fn pr(&self, number: i64, sha: char, state: &'static str) -> Pull { + Pull { + provider: "github", + installation_id: Some(self.inst), + repo: format!("acme/shop-{}", self.run), + number, + title: format!("Change {number}"), + url: format!("https://github.com/acme/shop/pull/{number}"), + author: "ana".into(), + head_ref: format!("change-{number}"), + head_sha: sha.to_string().repeat(40), + base_ref: "main".into(), + state, + ..Default::default() + } + } + + async fn event(&self, p: &Pull) -> bool { + pull_event(&self.s, &self.team, p).await.unwrap() + } + + async fn preview(&self, number: i64) -> Option { + sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT {PREVIEW_COLS} FROM pyo.previews WHERE service_id = $1 AND pull_id = (SELECT id FROM pyo.pull_requests WHERE team_id = $2 AND number = $3)" + ))) + .bind(&self.service) + .bind(&self.team) + .bind(number) + .fetch_optional(&self.s.db) + .await + .unwrap() + } + + async fn pull_id(&self, number: i64) -> String { + sqlx::query_scalar("SELECT id FROM pyo.pull_requests WHERE team_id = $1 AND number = $2") + .bind(&self.team) + .bind(number) + .fetch_one(&self.s.db) + .await + .unwrap() + } + + /// The copy's deployments: (id, status, commit), newest first. + async fn deployments(&self, copy: &str) -> Vec<(String, String, String)> { + sqlx::query_as("SELECT id, status, data->'source'->>'commit' FROM pyo.deployments WHERE service_id = $1 ORDER BY created_at DESC") + .bind(copy) + .fetch_all(&self.s.db) + .await + .unwrap() + } + + /// What the agent reports at the end, then what follows it. + async fn settle(&self, dep: &str, status: &str) { + sqlx::query("UPDATE pyo.deployments SET status = $2, finished_at = now() WHERE id = $1") + .bind(dep) + .bind(status) + .execute(&self.s.db) + .await + .unwrap(); + deployment_changed(&self.s, dep).await.unwrap(); + } + + async fn jobs(&self, kind: &str, pull: &str) -> i64 { + sqlx::query_scalar( + "SELECT count(*) FROM pyo.jobs WHERE kind = $1 AND payload->>'pullId' = $2", + ) + .bind(kind) + .bind(pull) + .fetch_one(&self.s.db) + .await + .unwrap() + } + + async fn copy(&self, id: &str) -> (String, Value, bool, Option) { + sqlx::query_as("SELECT name, spec, deleting, preview_of FROM pyo.services WHERE id = $1") + .bind(id) + .fetch_one(&self.s.db) + .await + .unwrap() + } + + async fn delete_commands(&self, copy: &str) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM pyo.commands WHERE command->>'kind' = 'delete_service' AND command->>'serviceId' = $1") + .bind(copy) + .fetch_one(&self.s.db) + .await + .unwrap() + } + + /// The agent removed the copies being deleted. + async fn copies_gone(&self) { + sqlx::query("DELETE FROM pyo.services WHERE preview_of = $1 AND deleting") + .bind(&self.service) + .execute(&self.s.db) + .await + .unwrap(); + } + + async fn set_settings(&self, settings: Value) { + let mut spec: Value = sqlx::query_scalar("SELECT spec FROM pyo.services WHERE id = $1") + .bind(&self.service) + .fetch_one(&self.s.db) + .await + .unwrap(); + spec["previews"] = settings; + check_settings(&mut spec).unwrap(); + sqlx::query("UPDATE pyo.services SET spec = $2 WHERE id = $1") + .bind(&self.service) + .bind(&spec) + .execute(&self.s.db) + .await + .unwrap(); + } + + async fn member(&self) -> crate::auth::User { + let user = crate::auth::User { + id: format!("usr_{}", self.run), + name: "T".into(), + email: format!("{}@t.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, 'T', '')", + ) + .bind(&user.id) + .bind(&user.email) + .execute(&self.s.db) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $4, 'developer', 'active')") + .bind(format!("mem_{}", self.run)) + .bind(&self.team) + .bind(&user.id) + .bind(&user.email) + .execute(&self.s.db) + .await + .unwrap(); + user + } +} + +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn a_pull_requests_life() { + run_big(async { + let w = world(json!({ "enabled": true })).await; + // Another repository's pull request: not followed. + let mut other = w.pr(1, 'f', "open"); + other.repo = "acme/elsewhere".into(); + assert!(!w.event(&other).await); + + // Opened: a copy, deployed from the head. + assert!(w.event(&w.pr(42, 'a', "open")).await); + let p = w.preview(42).await.expect("a preview"); + assert_eq!((p.state.as_str(), p.name.as_str()), ("active", "web-pr-42")); + assert_eq!( + p.hostname.as_deref(), + Some(format!("web-pr-42.{}.preview.test", w.run).as_str()) + ); + let copy = p.preview_service_id.clone().unwrap(); + let (name, spec, deleting, of) = w.copy(©).await; + assert_eq!( + (name.as_str(), deleting, of.as_deref()), + ("web-pr-42", false, Some(w.service.as_str())) + ); + assert_eq!(spec["replicas"], 1); + assert_eq!(spec["source"]["commit"], "a".repeat(40)); + assert_eq!(spec["domains"][0]["hostname"], json!(p.hostname)); + let keys: Vec<&str> = spec["env"] + .as_array() + .unwrap() + .iter() + .filter_map(|e| e["key"].as_str()) + .collect(); + assert!( + keys.contains(&"MODE") && keys.contains(&"PYO_PREVIEW_URL"), + "{keys:?}" + ); + assert!(!keys.contains(&"DATABASE_URL"), "no secrets by default"); + let deps = w.deployments(©).await; + assert_eq!(deps.len(), 1); + assert_eq!( + (deps[0].1.as_str(), deps[0].2.as_str()), + ("queued", "a".repeat(40).as_str()) + ); + assert_eq!(p.deployment_id.as_deref(), Some(deps[0].0.as_str())); + let commit: String = sqlx::query_scalar( + "SELECT job->>'commit' FROM pyo.build_jobs WHERE deployment_id = $1", + ) + .bind(&deps[0].0) + .fetch_one(&w.s.db) + .await + .unwrap(); + assert_eq!(commit, "a".repeat(40)); + let pull = w.pull_id(42).await; + assert!( + w.jobs("preview.report", &pull).await >= 1, + "the bot says so" + ); + // The same event again changes nothing. + w.event(&w.pr(42, 'a', "open")).await; + assert_eq!(w.deployments(©).await.len(), 1); + + // A push while it builds: the old build stops first... + w.event(&w.pr(42, 'b', "open")).await; + assert_eq!(w.deployments(©).await.len(), 1); + let cancels: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.commands WHERE command->>'kind' = 'cancel' AND coalesce(command->>'deploymentId', command->>'deployment_id') = $1") + .bind(&deps[0].0) + .fetch_one(&w.s.db) + .await + .unwrap(); + assert_eq!(cancels, 1); + // ...and once it settled, the new head deploys, on the same copy and URL. + w.settle(&deps[0].0, "cancelled").await; + let deps = w.deployments(©).await; + assert_eq!(deps.len(), 2); + assert_eq!(deps[0].2, "b".repeat(40)); + let p2 = w.preview(42).await.unwrap(); + assert_eq!(p2.sha, "b".repeat(40)); + assert_eq!(p2.hostname, p.hostname); + assert_eq!(p2.preview_service_id.as_deref(), Some(copy.as_str())); + w.settle(&deps[0].0, "succeeded").await; + + // Closed: the copy goes. + w.event(&w.pr(42, 'b', "closed")).await; + let p3 = w.preview(42).await.unwrap(); + assert_eq!( + (p3.state.as_str(), p3.removed_reason.as_deref()), + ("removed", Some("closed")) + ); + assert!(w.copy(©).await.2, "deleting"); + assert_eq!(w.delete_commands(©).await, 1); + + // Reopened: back, on a new copy (the old one is still going, so it + // waits for it first). + w.event(&w.pr(42, 'b', "open")).await; + assert_eq!(w.preview(42).await.unwrap().state, "waiting"); + w.copies_gone().await; + reconcile(&w.s, &pull).await.unwrap(); + let p4 = w.preview(42).await.unwrap(); + assert_eq!(p4.state, "active"); + assert_ne!(p4.preview_service_id.as_deref(), Some(copy.as_str())); + assert_eq!(p4.hostname, p.hostname, "the same URL"); + + // Merged: removed, with why. + w.event(&w.pr(42, 'b', "merged")).await; + let p5 = w.preview(42).await.unwrap(); + assert_eq!( + (p5.state.as_str(), p5.removed_reason.as_deref()), + ("removed", Some("merged")) + ); + + // The service deleted: its other previews go too. + w.event(&w.pr(43, 'c', "open")).await; + let p6 = w.preview(43).await.unwrap(); + let mut tx = w.s.db.begin().await.unwrap(); + let mut wake = vec![]; + service_deleted(&mut tx, &w.service, &mut wake) + .await + .unwrap(); + tx.commit().await.unwrap(); + assert_eq!(w.preview(43).await.unwrap().state, "removed"); + assert_eq!( + w.delete_commands(p6.preview_service_id.as_deref().unwrap()) + .await, + 1 + ); + }); +} + +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn limits_forks_labels_idle_and_removal_by_hand() { + run_big(async { + let w = world(json!({ "enabled": true, "limit": 1 })).await; + w.event(&w.pr(1, 'a', "open")).await; + w.event(&w.pr(2, 'b', "open")).await; + assert_eq!(w.preview(1).await.unwrap().state, "active"); + let waiting = w.preview(2).await.unwrap(); + assert_eq!(waiting.state, "waiting"); + assert!(waiting.message.unwrap().contains("limit")); + // The first one closes: the second starts. + w.event(&w.pr(1, 'a', "closed")).await; + reconcile(&w.s, &w.pull_id(2).await).await.unwrap(); + assert_eq!(w.preview(2).await.unwrap().state, "active"); + + // Forks: not by default; without secrets when allowed. + let mut fork = w.pr(3, 'c', "open"); + fork.fork = true; + w.set_settings(json!({ "enabled": true, "limit": 5, "copySecrets": true })) + .await; + w.event(&fork).await; + assert!(w.preview(3).await.is_none(), "not deployed"); + w.set_settings( + json!({ "enabled": true, "limit": 5, "copySecrets": true, "forks": "no-secrets" }), + ) + .await; + w.event(&fork).await; + let p = w.preview(3).await.unwrap(); + let (_, spec, _, _) = w.copy(p.preview_service_id.as_deref().unwrap()).await; + assert_eq!(spec["source"]["branch"], "refs/pull/3/head"); + assert!( + !spec["env"] + .as_array() + .unwrap() + .iter() + .any(|e| e["key"] == "DATABASE_URL") + ); + // A pull request of the repository's own: secrets copied. + w.event(&w.pr(2, 'd', "open")).await; + let p2 = w.preview(2).await.unwrap(); + let (_, spec, _, _) = w.copy(p2.preview_service_id.as_deref().unwrap()).await; + assert!( + spec["env"] + .as_array() + .unwrap() + .iter() + .any(|e| e["key"] == "DATABASE_URL") + ); + + // Labels: without it the preview goes; with it, it's back. + w.set_settings( + json!({ "enabled": true, "pulls": "label", "label": "preview", "forks": "no-secrets" }), + ) + .await; + reconcile(&w.s, &w.pull_id(2).await).await.unwrap(); + let p = w.preview(2).await.unwrap(); + assert_eq!( + (p.state.as_str(), p.removed_reason.as_deref()), + ("removed", Some("label")) + ); + let mut labelled = w.pr(2, 'd', "open"); + labelled.labels = vec!["preview".into()]; + w.copies_gone().await; + w.event(&labelled).await; + assert_eq!(w.preview(2).await.unwrap().state, "active"); + + // Removed by hand: stays removed until a push. + w.set_settings(json!({ "enabled": true })).await; + let id = w.preview(2).await.unwrap().id; + let user = w.member().await; + let mut tx = w.s.db.begin().await.unwrap(); + let mut wake = vec![]; + delete(&mut tx, &user, &id, &mut wake).await.unwrap(); + tx.commit().await.unwrap(); + w.copies_gone().await; + w.event(&labelled).await; + let p = w.preview(2).await.unwrap(); + assert_eq!( + (p.state.as_str(), p.removed_reason.as_deref()), + ("removed", Some("user")) + ); + w.event(&w.pr(2, 'e', "open")).await; + assert_eq!( + w.preview(2).await.unwrap().state, + "active", + "a push brings it back" + ); + + // Idle: no push for longer than the setting. + w.set_settings(json!({ "enabled": true, "idleDays": 1 })) + .await; + sqlx::query( + "UPDATE pyo.pull_requests SET pushed_at = now() - interval '2 days' WHERE id = $1", + ) + .bind(w.pull_id(2).await) + .execute(&w.s.db) + .await + .unwrap(); + reconcile(&w.s, &w.pull_id(2).await).await.unwrap(); + let p = w.preview(2).await.unwrap(); + assert_eq!( + (p.state.as_str(), p.removed_reason.as_deref()), + ("removed", Some("idle")) + ); + + // Previews turned off: every one goes. + w.event(&w.pr(5, 'f', "open")).await; + assert_eq!(w.preview(5).await.unwrap().state, "active"); + w.set_settings(json!({ "enabled": false })).await; + reconcile(&w.s, &w.pull_id(5).await).await.unwrap(); + let p = w.preview(5).await.unwrap(); + assert_eq!( + (p.state.as_str(), p.removed_reason.as_deref()), + ("removed", Some("settings")) + ); + }); +} + +/// What a fake provider was asked. +#[derive(Default)] +struct Recorder { + calls: Mutex>, + fail_comments: bool, +} + +impl Forge for Recorder { + async fn comment(&self, id: Option, body: &str) -> anyhow::Result { + if self.fail_comments { + anyhow::bail!("GitHub refused to comment (403)"); + } + let first = body.lines().nth(1).unwrap_or("").to_owned(); + self.calls + .lock() + .unwrap() + .push(format!("comment {id:?} {first}")); + Ok(id.unwrap_or(9)) + } + async fn check( + &self, + id: Option, + sha: &str, + c: &bot::Check, + _: Option<&str>, + ) -> anyhow::Result> { + self.calls.lock().unwrap().push(format!( + "check {id:?} {} {} {:?}", + &sha[..1], + c.status, + c.conclusion + )); + Ok(Some(id.unwrap_or(5))) + } + async fn deployment(&self, d: &mut Remote, shown: bot::Shown) -> anyhow::Result<()> { + self.calls.lock().unwrap().push(format!( + "deployment {} {} {}", + d.name, + &d.sha[..1], + shown.key() + )); + d.deployment_id = Some(1); + d.deployment_sha = Some(d.sha.clone()); + Ok(()) + } +} + +impl Recorder { + fn take(&self) -> Vec { + std::mem::take(&mut *self.calls.lock().unwrap()) + } +} + +async fn say_now(w: &World, f: &Recorder, pull: &str) -> anyhow::Result<()> { + let mut tx = w.s.db.begin().await.unwrap(); + let p = load_pull(&mut tx, pull, true).await.unwrap().unwrap(); + let v = views(&mut tx, pull).await.unwrap(); + let out = say(&mut tx, f, &p, &v, "https://pyo.example.com/acme").await; + tx.commit().await.unwrap(); + out +} + +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn the_bot_says_only_what_changed() { + run_big(async { + let w = world(json!({ "enabled": true })).await; + w.event(&w.pr(7, 'a', "open")).await; + let pull = w.pull_id(7).await; + let f = Recorder::default(); + say_now(&w, &f, &pull).await.unwrap(); + assert_eq!( + f.take(), + vec![ + "comment None **Preview**", + "check None a in_progress None", + "deployment web-pr-7 a building" + ] + ); + // Nothing new: nothing said. + say_now(&w, &f, &pull).await.unwrap(); + assert!(f.take().is_empty()); + // Ready: the comment, check and deployment move on. + let dep = w.preview(7).await.unwrap().deployment_id.unwrap(); + w.settle(&dep, "succeeded").await; + say_now(&w, &f, &pull).await.unwrap(); + assert_eq!( + f.take(), + vec![ + "comment Some(9) **Preview**", + "check Some(5) a completed Some(\"success\")", + "deployment web-pr-7 a ready" + ] + ); + // A push: a new check on the new head. + w.event(&w.pr(7, 'b', "open")).await; + say_now(&w, &f, &pull).await.unwrap(); + let calls = f.take(); + assert!( + calls.contains(&"check None b in_progress None".to_owned()), + "{calls:?}" + ); + assert!( + calls.contains(&"deployment web-pr-7 b building".to_owned()), + "{calls:?}" + ); + // A failed build fails the check. + let dep = w.preview(7).await.unwrap().deployment_id.unwrap(); + w.settle(&dep, "failed").await; + say_now(&w, &f, &pull).await.unwrap(); + let calls = f.take(); + assert!( + calls.contains(&"check Some(5) b completed Some(\"failure\")".to_owned()), + "{calls:?}" + ); + // Closed: "Preview removed", and the deployment inactive. + w.event(&w.pr(7, 'b', "closed")).await; + say_now(&w, &f, &pull).await.unwrap(); + let calls = f.take(); + assert!( + calls.contains(&"comment Some(9) **Preview removed**".to_owned()), + "{calls:?}" + ); + assert!( + calls.contains(&"deployment web-pr-7 b removing".to_owned()), + "{calls:?}" + ); + // A provider that refuses: what worked is kept, and it's an error + // (the job tries again). + w.event(&w.pr(8, 'c', "open")).await; + let pull8 = w.pull_id(8).await; + let refusing = Recorder { + fail_comments: true, + ..Default::default() + }; + assert!(say_now(&w, &refusing, &pull8).await.is_err()); + let calls = refusing.take(); + assert!( + calls.iter().any(|c| c.starts_with("check None c")), + "{calls:?}" + ); + say_now(&w, &f, &pull8).await.unwrap(); + assert_eq!( + f.take(), + vec!["comment None **Preview**"], + "only the comment is left to say" + ); + }); +} diff --git a/crates/pyo-api/src/ratelimit.rs b/crates/pyo-api/src/ratelimit.rs index e00ffb31..4202dee6 100644 --- a/crates/pyo-api/src/ratelimit.rs +++ b/crates/pyo-api/src/ratelimit.rs @@ -1,10 +1,17 @@ -//! Rate limits for signing in, shared by every replica through Postgres. +//! Rate and abuse limits (signing in, sign-ups, API keys, invites, +//! webhooks, operations), shared by every replica through Postgres. //! //! One fixed window per (scope, key) in `pyo.rate_limits`. An attempt takes //! a slot first, atomically (one upsert), so parallel requests can't slip //! past the limit; credential checks give the slot back when they succeed, -//! so only failures count. Keys are client addresses (IPv6 by /64) or -//! accounts, stored as sha256. Blocked: 429 with Retry-After. +//! so only failures count. Keys are client addresses (IPv6 by /64), +//! accounts, teams or keys, stored as sha256. Blocked: 429 with +//! Retry-After. +//! +//! A limit with a backoff cap locks out for longer each time its window is +//! used up again within a day (twice the last time, up to the cap). Each +//! replica also remembers, for a minute at most, what Postgres refused, so +//! a client that keeps trying once it's blocked costs no queries. use std::{ convert::Infallible, @@ -22,28 +29,54 @@ use crate::{ ids::sha256_hex, }; -/// At most `max` attempts per `window_secs`. +/// At most `max` attempts per `window_secs`. With `backoff_cap_secs`, a +/// used-up window locks out until `window_secs` × 2^n after it started (n: +/// the times it was used up within a day before), at most that long. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Limit { pub scope: &'static str, pub max: i32, pub window_secs: i64, + pub backoff_cap_secs: i64, } +const MINUTE: i64 = 60; const MIN15: i64 = 15 * 60; const HOUR: i64 = 60 * 60; +const DAY: i64 = 24 * HOUR; /// Failed password sign-ins per client address (password spraying). pub const LOGIN_IP: Limit = Limit { scope: "login:ip", max: 30, window_secs: MIN15, + backoff_cap_secs: DAY, }; /// Failed password sign-ins per email, existing or not (targeted guessing). pub const LOGIN_ACCOUNT: Limit = Limit { scope: "login:account", max: 10, window_secs: MIN15, + // Short enough that someone else's wrong passwords can't keep the + // owner out for long (a passkey or a sign-in link still works). + backoff_cap_secs: HOUR, +}; +/// Wrong two-factor codes per account (signing in, turning it off, new +/// recovery codes): a stolen password alone can't guess its way through. +/// The cap is short, like the password's, so a stranger can't keep the +/// owner out for long (a passkey still works). +pub const TWO_FACTOR_ACCOUNT: Limit = Limit { + scope: "two-factor:account", + max: 5, + window_secs: MIN15, + backoff_cap_secs: HOUR, +}; +/// And per client address. +pub const TWO_FACTOR_IP: Limit = Limit { + scope: "two-factor:ip", + max: 30, + window_secs: MIN15, + backoff_cap_secs: DAY, }; /// Passkey sign-ins started per address (each one stores a challenge; the /// sign-in page starts one on every visit, for autofill). @@ -51,18 +84,21 @@ pub const PASSKEY_START_IP: Limit = Limit { scope: "passkey-start:ip", max: 60, window_secs: MIN15, + backoff_cap_secs: 0, }; /// Failed passkey sign-ins per address. pub const PASSKEY_FINISH_IP: Limit = Limit { scope: "passkey-finish:ip", max: 30, window_secs: MIN15, + backoff_cap_secs: 0, }; /// Wrong passwords before adding a passkey, per signed-in user. pub const PASSKEY_PASSWORD_USER: Limit = Limit { scope: "passkey-password:user", max: 10, window_secs: MIN15, + backoff_cap_secs: 0, }; /// Sign-ups per address (each hashes a password, makes an account, and /// says whether an email is taken). @@ -70,30 +106,109 @@ pub const SIGNUP_IP: Limit = Limit { scope: "signup:ip", max: 20, window_secs: HOUR, + backoff_cap_secs: 0, }; /// "Forgot password?" emails asked for per address. pub const FORGOT_IP: Limit = Limit { scope: "forgot:ip", max: 10, window_secs: HOUR, + backoff_cap_secs: 0, }; /// And per email, existing or not (so a mailbox can't be flooded). pub const FORGOT_ACCOUNT: Limit = Limit { scope: "forgot:account", max: 3, window_secs: HOUR, + backoff_cap_secs: 0, }; /// Sign-in links tried per address (wrong or used ones count). pub const SIGN_IN_LINK_IP: Limit = Limit { scope: "sign-in-link:ip", max: 30, window_secs: MIN15, + backoff_cap_secs: 0, }; /// MCP client registrations per address (unauthenticated, each one a row). pub const OAUTH_REGISTER_IP: Limit = Limit { scope: "oauth-register:ip", max: 30, window_secs: HOUR, + backoff_cap_secs: 0, +}; + +/// `pyo login` requests per address (unauthenticated, each one a row). +pub const CLI_LOGIN_IP: Limit = Limit { + scope: "cli-login:ip", + max: 30, + window_secs: MIN15, + backoff_cap_secs: 0, +}; + +/// Wrong API keys per address (each one a lookup, and a guess). +pub const API_KEY_WRONG_IP: Limit = Limit { + scope: "api-key-wrong:ip", + max: 30, + window_secs: MIN15, + backoff_cap_secs: DAY, +}; +/// Requests per API key (and per assistant's MCP token). +pub const API_KEY_REQUESTS: Limit = Limit { + scope: "api-key:key", + max: 600, + window_secs: MINUTE, + backoff_cap_secs: 0, +}; +/// Operations (changes) per account, from the dashboard, the API or MCP. +pub const OPS_USER: Limit = Limit { + scope: "ops:user", + max: 300, + window_secs: MINUTE, + backoff_cap_secs: 0, +}; +/// Operations per team, all its members and keys together. +pub const OPS_TEAM: Limit = Limit { + scope: "ops:team", + max: 600, + window_secs: MINUTE, + backoff_cap_secs: 0, +}; +/// Invites sent (and sent again) per team: each one may be an email. +pub const INVITES_TEAM: Limit = Limit { + scope: "invite:team", + max: 30, + window_secs: HOUR, + backoff_cap_secs: 0, +}; +/// Deploy hook calls with a token that isn't one, per address. +pub const DEPLOY_HOOK_WRONG_IP: Limit = Limit { + scope: "deploy-hook-wrong:ip", + max: 30, + window_secs: MIN15, + backoff_cap_secs: DAY, +}; +/// Deploys started through one deploy hook. +pub const DEPLOY_HOOK_CALLS: Limit = Limit { + scope: "deploy-hook:hook", + max: 60, + window_secs: HOUR, + backoff_cap_secs: 0, +}; +/// Git webhook deliveries (GitHub, GitLab) whose signature or secret is +/// wrong, per address. +pub const GIT_WEBHOOK_WRONG_IP: Limit = Limit { + scope: "git-webhook-wrong:ip", + max: 30, + window_secs: MIN15, + backoff_cap_secs: DAY, +}; +/// Signed Git webhook deliveries per GitHub App installation or GitLab +/// connection: a push storm can't queue builds without end. +pub const GIT_WEBHOOK_CALLS: Limit = Limit { + scope: "git-webhook:source", + max: 600, + window_secs: HOUR, + backoff_cap_secs: 0, }; /// The client's address as a rate-limit key: the TCP peer, or, when the @@ -117,11 +232,12 @@ impl FromRequestParts for ClientIp { .filter_map(|v| v.to_str().ok()) .collect::>() .join(","); - Ok(ClientIp(ip_key(&request_ip( - &peer, - &xff, - trusted_proxies(), - )))) + let cf = parts + .headers + .get("cf-connecting-ip") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + Ok(ClientIp(ip_key(&visitor_ip(&peer, cf, &xff, trusted_proxies())))) } } @@ -236,6 +352,20 @@ pub fn request_ip(peer: &str, forwarded_for: &str, proxies: &[Cidr]) -> String { ip.to_string() } +/// The visitor's address behind Cloudflare: its `CF-Connecting-IP`, but +/// only when the connection comes from a trusted proxy (Cloudflare's +/// ranges, or cloudflared on this machine, in `PYO_TRUSTED_PROXIES`): +/// anyone else could send that header. Otherwise as [`request_ip`]. +pub fn visitor_ip(peer: &str, cf_connecting_ip: &str, forwarded_for: &str, proxies: &[Cidr]) -> String { + let parsed = |s: &str| s.trim().trim_matches(['[', ']']).parse::().ok().map(|a| a.to_canonical()); + if let (Some(p), Some(cf)) = (parsed(peer), parsed(cf_connecting_ip)) + && (trusted(&p, proxies) || (p.is_loopback() && proxies.iter().any(|c| c.contains(&p)))) + { + return cf.to_string(); + } + request_ip(peer, forwarded_for, proxies) +} + pub fn ip_key(ip: &str) -> String { match ip.parse::().map(|a| a.to_canonical()) { Ok(IpAddr::V6(v)) => { @@ -247,18 +377,77 @@ pub fn ip_key(ip: &str) -> String { } } -/// "Too many attempts. Try again in N minutes." -pub fn too_many(retry_secs: i64) -> ApiError { +/// The 429 for `limit`: what there were too many of, and when to try again. +pub fn too_many_for(limit: &Limit, retry_secs: i64) -> ApiError { + let what = match limit.scope { + "api-key:key" | "ops:user" | "ops:team" | "deploy-hook:hook" | "git-webhook:source" => { + "requests" + } + "invite:team" => "invites", + "signup:ip" => "sign-ups", + _ => "attempts", + }; + too_many_of(what, retry_secs) +} + +fn too_many_of(what: &str, retry_secs: i64) -> ApiError { let secs = retry_secs.max(1); let mins = (secs + 59) / 60; - let msg = if mins == 1 { - "Too many attempts. Try again in 1 minute.".to_owned() + let msg = if secs < 60 { + format!("Too many {what}. Try again in {secs} seconds.") + } else if mins == 1 { + format!("Too many {what}. Try again in 1 minute.") + } else if mins < 120 { + format!("Too many {what}. Try again in {mins} minutes.") } else { - format!("Too many attempts. Try again in {mins} minutes.") + format!("Too many {what}. Try again in {} hours.", (mins + 59) / 60) }; ApiError::new(StatusCode::TOO_MANY_REQUESTS, msg).with_retry_after(secs as u64) } +type Blocked = std::collections::HashMap<(&'static str, String), std::time::Instant>; + +/// What this replica saw Postgres refuse, by (scope, key hash): blocked +/// until then. Kept a minute at most, so a key started over elsewhere +/// (its owner signed in) counts here again soon. +static BLOCKED: std::sync::Mutex> = std::sync::Mutex::new(None); +const BLOCKED_KEEP: std::time::Duration = std::time::Duration::from_secs(60); +const BLOCKED_MAX: usize = 50_000; + +fn blocked_here(scope: &'static str, hash: &str) -> Option { + let mut g = BLOCKED.lock().unwrap_or_else(|e| e.into_inner()); + let map = g.as_mut()?; + let key = (scope, hash.to_owned()); + let until = *map.get(&key)?; + let now = std::time::Instant::now(); + if until <= now { + map.remove(&key); + return None; + } + Some((until - now).as_secs() as i64 + 1) +} + +fn remember_blocked(scope: &'static str, hash: &str, retry_secs: i64) { + let mut g = BLOCKED.lock().unwrap_or_else(|e| e.into_inner()); + let map = g.get_or_insert_with(Default::default); + let now = std::time::Instant::now(); + if map.len() >= BLOCKED_MAX { + map.retain(|_, until| *until > now); + if map.len() >= BLOCKED_MAX { + return; + } + } + let keep = std::time::Duration::from_secs(retry_secs.max(1) as u64).min(BLOCKED_KEEP); + map.insert((scope, hash.to_owned()), now + keep); +} + +fn forget_blocked(scope: &'static str, hash: &str) { + let mut g = BLOCKED.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = g.as_mut() { + map.remove(&(scope, hash.to_owned())); + } +} + /// Take one slot from each limit, in order; if any is used up, give back /// the ones already taken and answer 429. pub async fn take(db: &PgPool, limits: &[(Limit, &str)]) -> ApiResult<()> { @@ -267,7 +456,7 @@ pub async fn take(db: &PgPool, limits: &[(Limit, &str)]) -> ApiResult<()> { for (l, k) in &limits[..i] { forgive(db, l, k).await?; } - return Err(too_many(retry)); + return Err(too_many_for(limit, retry)); } } Ok(()) @@ -276,13 +465,20 @@ pub async fn take(db: &PgPool, limits: &[(Limit, &str)]) -> ApiResult<()> { /// None: taken. Some(seconds): used up until then. async fn take_one(db: &PgPool, limit: &Limit, key: &str) -> sqlx::Result> { let key = sha256_hex(key); - // A window that ended starts over; otherwise count up while under max. + if let Some(retry) = blocked_here(limit.scope, &key) { + return Ok(Some(retry)); + } + // A window that ended starts over; otherwise count up while under max, + // and never while locked out. A window that starts a day after the + // last one forgets the lockouts before. let taken: Option = sqlx::query_scalar( "INSERT INTO pyo.rate_limits AS r (scope, key, window_start, count) VALUES ($1, $2, now(), 1) ON CONFLICT (scope, key) DO UPDATE SET + strikes = CASE WHEN r.window_start <= now() - interval '1 day' THEN 0 ELSE r.strikes END, count = CASE WHEN r.window_start <= now() - make_interval(secs => $3) THEN 1 ELSE r.count + 1 END, window_start = CASE WHEN r.window_start <= now() - make_interval(secs => $3) THEN now() ELSE r.window_start END - WHERE r.window_start <= now() - make_interval(secs => $3) OR r.count < $4 + WHERE coalesce(r.blocked_until <= now(), true) + AND (r.window_start <= now() - make_interval(secs => $3) OR r.count < $4) RETURNING count", ) .bind(limit.scope) @@ -294,24 +490,72 @@ async fn take_one(db: &PgPool, limit: &Limit, key: &str) -> sqlx::Result = sqlx::query_scalar("SELECT extract(epoch FROM window_start + make_interval(secs => $3) - now())::float8 FROM pyo.rate_limits WHERE scope = $1 AND key = $2") - .bind(limit.scope) - .bind(&key) - .bind(limit.window_secs as f64) - .fetch_optional(db) - .await?; - Ok(Some( - retry.map_or(limit.window_secs, |s| s.ceil() as i64).max(1), - )) + // Used up. With a backoff, the window's first refusal locks out for + // twice as long as the time before (the first time: to its end). + let retry: Option = sqlx::query_scalar( + "UPDATE pyo.rate_limits SET + strikes = CASE WHEN $4 > 0 AND coalesce(blocked_until <= now(), true) THEN strikes + 1 ELSE strikes END, + blocked_until = CASE WHEN $4 > 0 AND coalesce(blocked_until <= now(), true) + THEN window_start + make_interval(secs => least($3 * power(2, strikes), greatest($4, $3))) + ELSE blocked_until END + WHERE scope = $1 AND key = $2 + RETURNING extract(epoch FROM greatest(coalesce(blocked_until, window_start), window_start + make_interval(secs => $3)) - now())::float8", + ) + .bind(limit.scope) + .bind(&key) + .bind(limit.window_secs as f64) + .bind(limit.backoff_cap_secs as f64) + .fetch_optional(db) + .await?; + let retry = retry.map_or(limit.window_secs, |s| s.ceil() as i64).max(1); + remember_blocked(limit.scope, &key, retry); + Ok(Some(retry)) +} + +/// Whether `key` used up `limit`, without taking a slot: the seconds until +/// it may try again. For a check made in a transaction that shouldn't +/// write (an operation's team, which [`take_after`] counts once it's done). +pub async fn used_up( + conn: &mut sqlx::PgConnection, + limit: &Limit, + key: &str, +) -> sqlx::Result> { + let key = sha256_hex(key); + if let Some(retry) = blocked_here(limit.scope, &key) { + return Ok(Some(retry)); + } + let retry: Option = sqlx::query_scalar( + "SELECT extract(epoch FROM greatest(coalesce(blocked_until, window_start), window_start + make_interval(secs => $3)) - now())::float8 + FROM pyo.rate_limits + WHERE scope = $1 AND key = $2 + AND (blocked_until > now() OR (window_start > now() - make_interval(secs => $3) AND count >= $4))", + ) + .bind(limit.scope) + .bind(&key) + .bind(limit.window_secs as f64) + .bind(limit.max) + .fetch_optional(conn) + .await?; + Ok(retry.map(|s| (s.ceil() as i64).max(1))) +} + +/// Counts something already done against `limit`: the next one waits when +/// this used it up. +pub async fn take_after(db: &PgPool, limit: &Limit, key: &str) { + if let Err(e) = take_one(db, limit, key).await { + tracing::warn!(scope = limit.scope, error = %e, "rate limit not counted"); + } } /// Give back one slot: the attempt succeeded, or wasn't made. pub async fn forgive(db: &PgPool, limit: &Limit, key: &str) -> sqlx::Result<()> { + let hash = sha256_hex(key); + forget_blocked(limit.scope, &hash); sqlx::query( "UPDATE pyo.rate_limits SET count = greatest(count - 1, 0) WHERE scope = $1 AND key = $2", ) .bind(limit.scope) - .bind(sha256_hex(key)) + .bind(&hash) .execute(db) .await?; Ok(()) @@ -319,17 +563,20 @@ pub async fn forgive(db: &PgPool, limit: &Limit, key: &str) -> sqlx::Result<()> /// Start over: e.g. the account's owner signed in. pub async fn reset(db: &PgPool, limit: &Limit, key: &str) -> sqlx::Result<()> { + let hash = sha256_hex(key); + forget_blocked(limit.scope, &hash); sqlx::query("DELETE FROM pyo.rate_limits WHERE scope = $1 AND key = $2") .bind(limit.scope) - .bind(sha256_hex(key)) + .bind(&hash) .execute(db) .await?; Ok(()) } -/// Windows that ended long ago (the longest is an hour). +/// Windows that ended long ago (the longest is an hour) and lockouts over +/// for a day. pub async fn prune(db: &PgPool) -> sqlx::Result<()> { - sqlx::query("DELETE FROM pyo.rate_limits WHERE window_start < now() - interval '1 day'") + sqlx::query("DELETE FROM pyo.rate_limits WHERE window_start < now() - interval '1 day' AND coalesce(blocked_until < now() - interval '1 day', true)") .execute(db) .await?; Ok(()) @@ -353,20 +600,20 @@ mod tests { #[test] fn message_and_retry_after() { - let e = too_many(30); + let e = too_many_of("attempts", 30); assert_eq!(e.status, StatusCode::TOO_MANY_REQUESTS); - assert_eq!(e.message, "Too many attempts. Try again in 1 minute."); + assert_eq!(e.message, "Too many attempts. Try again in 30 seconds."); assert_eq!(e.retry_after, Some(30)); assert_eq!( - too_many(61).message, + too_many_of("attempts", 61).message, "Too many attempts. Try again in 2 minutes." ); assert_eq!( - too_many(900).message, + too_many_of("attempts", 900).message, "Too many attempts. Try again in 15 minutes." ); - assert_eq!(too_many(0).retry_after, Some(1)); - let r = axum::response::IntoResponse::into_response(too_many(120)); + assert_eq!(too_many_of("attempts", 0).retry_after, Some(1)); + let r = axum::response::IntoResponse::into_response(too_many_of("attempts", 120)); assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS); assert_eq!(r.headers()["retry-after"], "120"); } @@ -379,10 +626,22 @@ mod tests { PASSKEY_START_IP, PASSKEY_FINISH_IP, PASSKEY_PASSWORD_USER, + TWO_FACTOR_ACCOUNT, + TWO_FACTOR_IP, SIGNUP_IP, OAUTH_REGISTER_IP, + CLI_LOGIN_IP, crate::cloud::bootstrap::WRONG_CODE_SERVER, crate::cloud::bootstrap::WRONG_CODE_ALL, + API_KEY_WRONG_IP, + API_KEY_REQUESTS, + OPS_USER, + OPS_TEAM, + INVITES_TEAM, + DEPLOY_HOOK_WRONG_IP, + DEPLOY_HOOK_CALLS, + GIT_WEBHOOK_WRONG_IP, + GIT_WEBHOOK_CALLS, ]; for (i, a) in all.iter().enumerate() { assert!( @@ -393,6 +652,7 @@ mod tests { } // An account is guessed at less often than a shared address may fail. const { assert!(LOGIN_ACCOUNT.max < LOGIN_IP.max) }; + const { assert!(TWO_FACTOR_ACCOUNT.max < TWO_FACTOR_IP.max) }; } #[tokio::test] @@ -481,11 +741,13 @@ mod tests { scope: "test:a", max: 3, window_secs: 60, + backoff_cap_secs: 0, }; let other = Limit { scope: "test:b", max: 1, window_secs: 60, + backoff_cap_secs: 0, }; let key = format!("k{}", crate::ids::secret_token()); sqlx::query("DELETE FROM pyo.rate_limits WHERE scope LIKE 'test:%'") @@ -537,6 +799,8 @@ mod tests { // An ended window starts over. sqlx::query("UPDATE pyo.rate_limits SET window_start = now() - interval '2 minutes' WHERE scope = 'test:b'").execute(&db).await.unwrap(); + // (This replica remembers the refusal for up to a minute.) + forget_blocked(other.scope, &sha256_hex(&key)); take(&db, &[(other, &key)]).await.unwrap(); // Parallel attempts (other replicas) never exceed the limit. @@ -544,6 +808,7 @@ mod tests { scope: "test:c", max: 5, window_secs: 60, + backoff_cap_secs: 0, }; let tasks: Vec<_> = (0..20) .map(|_| { @@ -570,4 +835,312 @@ mod tests { .await .unwrap(); } + + #[test] + fn cloudflare_s_header_counts_only_from_a_trusted_proxy() { + let cf = [Cidr::parse("173.245.48.0/20").unwrap(), Cidr::parse("127.0.0.1/32").unwrap()]; + assert_eq!(visitor_ip("173.245.48.9", "203.0.113.7", "", &cf), "203.0.113.7"); + assert_eq!(visitor_ip("127.0.0.1", "203.0.113.7", "", &cf), "203.0.113.7"); + assert_eq!(visitor_ip("198.51.100.4", "203.0.113.7", "", &cf), "198.51.100.4"); + assert_eq!(visitor_ip("173.245.48.9", "", "", &cf), "173.245.48.9"); + } + + #[test] + fn plain_messages_for_each_kind() { + assert_eq!( + too_many_for(&OPS_TEAM, 20).message, + "Too many requests. Try again in 20 seconds." + ); + assert_eq!( + too_many_for(&INVITES_TEAM, 3600).message, + "Too many invites. Try again in 60 minutes." + ); + assert_eq!( + too_many_for(&LOGIN_IP, 4 * 3600).message, + "Too many attempts. Try again in 4 hours." + ); + assert_eq!(too_many_for(&API_KEY_REQUESTS, 5).retry_after, Some(5)); + } + + async fn test_db() -> PgPool { + let db = PgPool::connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL")) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + db + } + + /// Against a throwaway Postgres: a lockout doubles each time, up to its + /// cap, a success starts over, and a quiet day forgets. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn lockouts_back_off_and_start_over() { + let db = test_db().await; + let l = Limit { + scope: "test-backoff:a", + max: 2, + window_secs: 60, + backoff_cap_secs: 200, + }; + let key = format!("k{}", crate::ids::secret_token()); + let hash = sha256_hex(&key); + // The window (and its lockout) ended: what Postgres says from now. + let end_window = || async { + forget_blocked(l.scope, &hash); + sqlx::query("UPDATE pyo.rate_limits SET window_start = now() - interval '10 minutes', blocked_until = now() - interval '1 second' WHERE scope = $1 AND key = $2") + .bind(l.scope) + .bind(&hash) + .execute(&db) + .await + .unwrap(); + }; + let retry = |e: ApiError| e.retry_after.unwrap() as i64; + for _ in 0..2 { + take(&db, &[(l, &key)]).await.unwrap(); + } + let first = retry(take(&db, &[(l, &key)]).await.unwrap_err()); + assert!((55..=60).contains(&first), "{first}"); + // Refused again here without asking Postgres. + assert!(blocked_here(l.scope, &hash).is_some()); + end_window().await; + for _ in 0..2 { + take(&db, &[(l, &key)]).await.unwrap(); + } + let second = retry(take(&db, &[(l, &key)]).await.unwrap_err()); + assert!((115..=120).contains(&second), "twice as long: {second}"); + // Still locked out, though the window's minute is over. + forget_blocked(l.scope, &hash); + sqlx::query("UPDATE pyo.rate_limits SET window_start = window_start - interval '61 seconds', blocked_until = blocked_until - interval '61 seconds' WHERE scope = $1 AND key = $2") + .bind(l.scope) + .bind(&hash) + .execute(&db) + .await + .unwrap(); + let left = retry(take(&db, &[(l, &key)]).await.unwrap_err()); + assert!((50..=60).contains(&left), "{left}"); + end_window().await; + for _ in 0..2 { + take(&db, &[(l, &key)]).await.unwrap(); + } + let third = retry(take(&db, &[(l, &key)]).await.unwrap_err()); + assert!((195..=200).contains(&third), "up to the cap: {third}"); + // The owner signed in: back to the start. + reset(&db, &l, &key).await.unwrap(); + take(&db, &[(l, &key)]).await.unwrap(); + // A day after the last window, earlier lockouts are forgotten. + sqlx::query("UPDATE pyo.rate_limits SET strikes = 5, window_start = now() - interval '25 hours' WHERE scope = $1 AND key = $2") + .bind(l.scope) + .bind(&hash) + .execute(&db) + .await + .unwrap(); + for _ in 0..2 { + take(&db, &[(l, &key)]).await.unwrap(); + } + let fresh = retry(take(&db, &[(l, &key)]).await.unwrap_err()); + assert!((55..=60).contains(&fresh), "{fresh}"); + // Without a backoff, a used-up window only lasts its time. + let plain = Limit { + scope: "test-backoff:b", + backoff_cap_secs: 0, + ..l + }; + for _ in 0..2 { + take(&db, &[(plain, &key)]).await.unwrap(); + } + assert!(take(&db, &[(plain, &key)]).await.is_err()); + let blocked: Option = sqlx::query_scalar( + "SELECT pyo.ms(blocked_until) FROM pyo.rate_limits WHERE scope = $1 AND key = $2", + ) + .bind(plain.scope) + .bind(&hash) + .fetch_one(&db) + .await + .unwrap(); + assert!(blocked.is_none()); + let mut c = db.acquire().await.unwrap(); + assert!(used_up(&mut c, &plain, &key).await.unwrap().is_some()); + assert!( + used_up(&mut c, &plain, "someone else") + .await + .unwrap() + .is_none() + ); + // (Its own scopes: shared_windows_in_postgres clears test:*.) + sqlx::query("DELETE FROM pyo.rate_limits WHERE scope LIKE 'test-backoff:%'") + .execute(&db) + .await + .unwrap(); + } + + /// Against a throwaway Postgres: wrong API keys, a key's requests, a + /// team's operations and invites trip their limits with a plain 429, + /// and work again once the window is over. + #[test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + fn api_limits_trip_and_reset() { + std::thread::Builder::new() + .stack_size(64 << 20) + .spawn(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + .block_on(api_limits()) + }) + .unwrap() + .join() + .unwrap(); + } + + async fn api_limits() { + use serde_json::json; + let db = test_db().await; + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + let run = crate::ids::random_string(8).to_lowercase(); + let (user_id, team) = (format!("usr_rl{run}"), format!("team_rl{run}")); + let email = format!("rl{run}@limits.test"); + sqlx::query( + "INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $2, $1, '')", + ) + .bind(&user_id) + .bind(&email) + .execute(&db) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&db) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $4, 'owner', 'active')") + .bind(format!("mem_rl{run}")) + .bind(&team) + .bind(&user_id) + .bind(&email) + .execute(&db) + .await + .unwrap(); + let user = crate::auth::User { + id: user_id.clone(), + name: "rl".into(), + email: email.clone(), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + let s = crate::rls::tests::state(db.clone()); + // Fill a window as if it had been used up already. + let used = |limit: Limit, key: String| { + let db = db.clone(); + async move { + sqlx::query("INSERT INTO pyo.rate_limits (scope, key, window_start, count) VALUES ($1, $2, now(), $3) + ON CONFLICT (scope, key) DO UPDATE SET window_start = now(), count = $3, blocked_until = NULL") + .bind(limit.scope) + .bind(sha256_hex(&key)) + .bind(limit.max) + .execute(&db) + .await + .unwrap(); + } + }; + + // Wrong API keys from one address: a 429 once used up. + let ip = format!("198.51.100.{}", run.len()); + reset(&db, &API_KEY_WRONG_IP, &ip).await.unwrap(); + for _ in 0..API_KEY_WRONG_IP.max { + let e = crate::auth::key_user_from(&db, "pyo_wrong", &ip) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::UNAUTHORIZED); + } + let e = crate::auth::key_user_from(&db, "pyo_wrong", &ip) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::TOO_MANY_REQUESTS); + assert!(e.message.starts_with("Too many attempts."), "{}", e.message); + reset(&db, &API_KEY_WRONG_IP, &ip).await.unwrap(); + + // A key's requests. + let token = format!("pyo_{}", crate::ids::secret_token()); + sqlx::query("INSERT INTO pyo.api_tokens (id, user_id, name, prefix, token_hash, access) VALUES ($1, $2, 'k', 'pyo_', $3, 'full')") + .bind(format!("tok_rl{run}")) + .bind(&user_id) + .bind(sha256_hex(&token)) + .execute(&db) + .await + .unwrap(); + crate::auth::key_user_from(&db, &token, &ip).await.unwrap(); + used(API_KEY_REQUESTS, sha256_hex(&token)).await; + let e = crate::auth::key_user_from(&db, &token, &ip) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::TOO_MANY_REQUESTS); + assert!(e.message.starts_with("Too many requests."), "{}", e.message); + reset(&db, &API_KEY_REQUESTS, &sha256_hex(&token)) + .await + .unwrap(); + crate::auth::key_user_from(&db, &token, &ip).await.unwrap(); + + // A team's operations: counted once each is done, refused once the + // team used its minute up, and fine again after. + let project = |n: u32| json!({ "op": "createProject", "id": format!("prj_rl{run}{n}"), "teamId": team, "name": format!("p{n}"), "namespace": format!("p{n}-{run}") }); + crate::ops::run_json(&s, &user, project(1)).await.unwrap(); + let counted: i32 = + sqlx::query_scalar("SELECT count FROM pyo.rate_limits WHERE scope = $1 AND key = $2") + .bind(OPS_TEAM.scope) + .bind(sha256_hex(&team)) + .fetch_one(&db) + .await + .unwrap(); + assert!(counted >= 1); + used(OPS_TEAM, team.clone()).await; + let e = crate::ops::run_json(&s, &user, project(2)) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::TOO_MANY_REQUESTS); + assert!(e.message.starts_with("Too many requests."), "{}", e.message); + reset(&db, &OPS_TEAM, &team).await.unwrap(); + crate::ops::run_json(&s, &user, project(2)).await.unwrap(); + + // Invites per team. + let invite = |n: u32| json!({ "op": "inviteMember", "id": format!("mem_rl{run}i{n}"), "teamId": team, "email": format!("i{n}{run}@limits.test"), "role": "developer" }); + crate::ops::run_json(&s, &user, invite(1)).await.unwrap(); + used(INVITES_TEAM, team.clone()).await; + let e = crate::ops::run_json(&s, &user, invite(2)) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::TOO_MANY_REQUESTS); + assert!(e.message.starts_with("Too many invites."), "{}", e.message); + reset(&db, &INVITES_TEAM, &team).await.unwrap(); + crate::ops::run_json(&s, &user, invite(2)).await.unwrap(); + + // An account's operations, in every team. + used(OPS_USER, user_id.clone()).await; + let e = crate::ops::run_json(&s, &user, project(3)) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::TOO_MANY_REQUESTS); + reset(&db, &OPS_USER, &user_id).await.unwrap(); + + for k in [&team, &user_id] { + for l in [OPS_TEAM, OPS_USER, INVITES_TEAM] { + reset(&db, &l, k).await.unwrap(); + } + } + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + sqlx::query("DELETE FROM pyo.users WHERE id = $1") + .bind(&user_id) + .execute(&db) + .await + .unwrap(); + } } diff --git a/crates/pyo-api/src/recovery.rs b/crates/pyo-api/src/recovery.rs index 02a4b4ef..d858df8b 100644 --- a/crates/pyo-api/src/recovery.rs +++ b/crates/pyo-api/src/recovery.rs @@ -15,7 +15,11 @@ //! Only the token's sha256 is kept (pyo.sign_in_links). A link works once, //! for [`LINK_MINUTES`], and a new one for the same account replaces it. //! Using it sets the new password, ends the account's sessions and signs -//! this browser in. +//! this browser in. With two-factor on, a code comes first, as after a +//! 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). use crate::error::Json; use crate::error::Query; @@ -48,15 +52,25 @@ pub fn link_path(token: &str) -> String { /// A new sign-in link's secret for the account, replacing any earlier one. pub async fn new_link(conn: &mut sqlx::PgConnection, user_id: &str) -> ApiResult { + link(conn, user_id, false).await +} + +/// [`new_link`] made on the server Pyo runs on: it turns two-factor off. +pub async fn new_host_link(conn: &mut sqlx::PgConnection, user_id: &str) -> ApiResult { + link(conn, user_id, true).await +} + +async fn link(conn: &mut sqlx::PgConnection, user_id: &str, clears_two_factor: bool) -> ApiResult { let token = secret_token(); sqlx::query("DELETE FROM pyo.sign_in_links WHERE user_id = $1 OR expires_at < now()") .bind(user_id) .execute(&mut *conn) .await?; - sqlx::query("INSERT INTO pyo.sign_in_links (token_hash, user_id, expires_at) VALUES ($1, $2, now() + make_interval(mins => $3))") + sqlx::query("INSERT INTO pyo.sign_in_links (token_hash, user_id, expires_at, clears_two_factor) VALUES ($1, $2, now() + make_interval(mins => $3), $4)") .bind(sha256_hex(&token)) .bind(user_id) .bind(LINK_MINUTES) + .bind(clears_two_factor) .execute(&mut *conn) .await?; Ok(token) @@ -156,26 +170,26 @@ struct ResetBody { } /// A link used: the new password, every other session ended, and this -/// browser signed in. +/// browser signed in (or, with two-factor on, a code next). async fn reset( State(state): State, ClientIp(ip): ClientIp, headers: HeaderMap, jar: CookieJar, Json(body): Json, -) -> ApiResult<(CookieJar, Json)> { +) -> ApiResult<(CookieJar, Json)> { crate::auth::require_csrf(&headers)?; crate::auth::check_password(&body.password)?; ratelimit::take(&state.db, &[(ratelimit::SIGN_IN_LINK_IP, &ip)]).await?; let hash = crate::auth::hash_password(&body.password).await?; let mut tx = state.db.begin().await?; - let user_id: Option = sqlx::query_scalar( - "DELETE FROM pyo.sign_in_links WHERE token_hash = $1 AND expires_at > now() RETURNING user_id", + let row: Option<(String, bool)> = sqlx::query_as( + "DELETE FROM pyo.sign_in_links WHERE token_hash = $1 AND expires_at > now() RETURNING user_id, clears_two_factor", ) .bind(sha256_hex(body.token.trim())) .fetch_optional(&mut *tx) .await?; - let user_id = user_id.ok_or_else(used_or_expired)?; + let (user_id, clears_two_factor) = row.ok_or_else(used_or_expired)?; let (id, name, email, timezone, is_admin, must_set_up): (String, String, String, String, bool, bool) = sqlx::query_as("UPDATE pyo.users SET password_hash = $2 WHERE id = $1 RETURNING id, name, email, timezone, is_admin, must_set_up") .bind(&user_id) @@ -186,23 +200,51 @@ async fn reset( .bind(&user_id) .execute(&mut *tx) .await?; + let user = User { + id, + name, + email, + timezone, + is_admin, + must_set_up, + key: None, + }; + 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?; + crate::twofactor::notify_teams( + &mut tx, + &user, + "auth.two_factor_disabled", + "Turned off two-factor authentication with a sign-in link from the server", + ) + .await?; + } + let who = crate::audit::Who::person(&user); + crate::audit::account_event_in( + &mut tx, + &user.id, + &who, + crate::audit::Entry { + action: "auth.password_reset", + title: "Chose a new password with a sign-in link", + target: json!({}), + failed: false, + }, + ) + .await?; tx.commit().await?; ratelimit::forgive(&state.db, &ratelimit::SIGN_IN_LINK_IP, &ip).await?; - ratelimit::reset(&state.db, &ratelimit::LOGIN_ACCOUNT, &email).await?; - tracing::info!(user = %id, "password replaced with a sign-in link"); - let jar = crate::auth::start_session(&state, jar, &id, &headers).await?; - Ok(( - jar, - Json(User { - id, - name, - email, - timezone, - is_admin, - must_set_up, - key: None, - }), - )) + ratelimit::reset(&state.db, &ratelimit::LOGIN_ACCOUNT, &user.email).await?; + tracing::info!(user = %user.id, "password replaced with a sign-in link"); + if clears_two_factor && had_two_factor { + crate::twofactor::mail_user(&state, &user.email, "/profile", crate::mail::two_factor_off).await; + } else if had_two_factor { + let challenge = crate::twofactor::start_challenge(&state.db, &user.id, "link").await?; + return Ok((jar, Json(crate::twofactor::code_needed(&challenge)))); + } + let jar = crate::auth::start_session(&state, jar, &user.id, &headers).await?; + Ok((jar, Json(json!(user)))) } /// Can this sign-in link be shown to a team's owner, rather than only diff --git a/crates/pyo-api/src/registrydoor.rs b/crates/pyo-api/src/registrydoor.rs index f599c5b6..af038cb0 100644 --- a/crates/pyo-api/src/registrydoor.rs +++ b/crates/pyo-api/src/registrydoor.rs @@ -45,6 +45,93 @@ use serde_json::json; use crate::{AppState, deploy, ids::sha256_hex}; +/// With in-cluster registries (Pyo Cloud), each cluster's own registry +/// has a door of its own (pyo-agent registrydoor.rs) with the same rules. +/// It checks the team's tokens by their hashes, which Pyo sends each of the +/// team's clusters whenever they change ([`sync_clusters`]): the clusters +/// to wake come back. Nothing to send otherwise. +pub async fn sync_clusters( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + team_id: &str, + only: Option<&str>, +) -> crate::error::ApiResult> { + if !deploy::in_cluster_registries() { + return Ok(vec![]); + } + let tokens = team_tokens(tx, team_id).await?; + let clusters: Vec = sqlx::query_scalar( + "SELECT id FROM pyo.clusters WHERE team_id = $1 AND NOT same_cluster AND ($2::text IS NULL OR id = $2) ORDER BY created_at", + ) + .bind(team_id) + .bind(only) + .fetch_all(&mut **tx) + .await?; + for c in &clusters { + deploy::enqueue( + tx, + c, + pyo_proto::Command::SyncRegistryTokens(Box::new(tokens.clone())), + ) + .await?; + } + Ok(clusters) +} + +/// The team's working registry tokens as a cluster's door gets them: their +/// hashes, never the tokens. +pub(crate) async fn team_tokens( + conn: &mut sqlx::PgConnection, + team_id: &str, +) -> sqlx::Result { + let slug: String = sqlx::query_scalar("SELECT slug FROM pyo.teams WHERE id = $1") + .bind(team_id) + .fetch_one(&mut *conn) + .await?; + let rows: Vec<(String, String, Option)> = sqlx::query_as( + "SELECT token_hash, scope, extract(epoch FROM expires_at)::bigint FROM pyo.registry_tokens + WHERE team_id = $1 AND (expires_at IS NULL OR expires_at > now()) ORDER BY created_at", + ) + .bind(team_id) + .fetch_all(&mut *conn) + .await?; + Ok(pyo_proto::registry_door::RegistryTokens { + team_slug: team_path(&slug), + tokens: rows + .into_iter() + .map( + |(sha256, scope, expires_at)| pyo_proto::registry_door::RegistryToken { + sha256, + push: scope == "push", + expires_at, + }, + ) + .collect(), + }) +} + +/// A cluster's own registry's door by its name on the cluster's tailnet +/// ("registry..ts.net"), once the name works there. Pyo Cloud's +/// clusters only. The name comes with the cluster's Tailscale (made by its +/// agent, tailscale.rs): none before. +pub(crate) const CLUSTER_ADDRESS: &str = "SELECT n.name || '.' || (c.tailscale->>'suffix') + FROM pyo.clusters c JOIN pyo.cluster_tailnet_names n ON n.cluster_id = c.id + WHERE c.id = $1 AND NOT c.same_cluster AND n.kind = 'registry' AND n.retired_at IS NULL + AND n.error IS NULL AND cardinality(n.addrs) > 0 AND c.tailscale->>'suffix' IS NOT NULL + ORDER BY n.created_at LIMIT 1"; + +pub async fn cluster_address( + conn: &mut sqlx::PgConnection, + cluster_id: &str, +) -> sqlx::Result> { + if !deploy::in_cluster_registries() { + return Ok(None); + } + sqlx::query_scalar(CLUSTER_ADDRESS) + .bind(cluster_id) + .fetch_optional(conn) + .await +} + /// Where users push from: the registry's tailnet name /// ("registry..ts.net"). None until Tailscale is set up. pub fn address() -> Option { @@ -58,15 +145,7 @@ pub fn team_path(slug: &str) -> String { /// A team's own repository: "//", its three parts. pub(crate) fn parts(name: &str) -> Option<(&str, &str, &str)> { - let mut it = name.split('/'); - let (t, p, s) = (it.next()?, it.next()?, it.next()?); - let label = |x: &str| { - !x.is_empty() - && x.len() <= 63 - && x.bytes() - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') - }; - (it.next().is_none() && label(t) && label(p) && label(s) && t != "pyo").then_some((t, p, s)) + pyo_proto::registry_door::parts(name) } /// A team's own repository as users name it from the tailnet: @@ -188,93 +267,23 @@ pub(crate) fn not_theirs(slug: &str) -> String { ) } -/// What a request asks for: the repository it names (None for /v2/ itself) -/// and whether it writes. -#[derive(Debug, PartialEq)] -pub(crate) enum Wants { - Root, - Repo { name: String, write: bool }, - Other, -} +/// What a request asks for (pyo-proto registry_door.rs, the same rules as +/// a cluster's own registry's door). +pub(crate) use pyo_proto::registry_door::Wants; pub(crate) fn wants(method: &Method, path: &str) -> Wants { - let Some(rest) = path.strip_prefix("/v2/") else { - return Wants::Other; - }; - if rest.is_empty() { - return Wants::Root; - } - let name = ["/manifests/", "/blobs/", "/tags/list"] - .iter() - .filter_map(|m| rest.find(m)) - .min() - .map(|i| &rest[..i]); - match name { - Some(n) if !n.is_empty() => Wants::Repo { - name: n.to_owned(), - write: !matches!(*method, Method::GET | Method::HEAD), - }, - _ => Wants::Other, - } + pyo_proto::registry_door::wants(method.as_str(), path) } /// Whether a token for `slug` (with `push` or only pull) may do this, by /// the path alone (the door then checks the project, service and owner). pub(crate) fn allowed(slug: &str, push: bool, method: &Method, name: &str) -> bool { - let ours = parts(name).is_some_and(|(t, _, _)| t == slug); - match *method { - Method::GET | Method::HEAD => ours, - // Pushing: uploads, then the manifest. Deleting isn't offered. - Method::POST | Method::PUT | Method::PATCH => ours && push, - _ => false, - } + pyo_proto::registry_door::allowed(slug, push, method.as_str(), name) } -/// A query without a cross-repository mount from outside the team (the -/// registry then takes a plain upload instead). +/// A query without a cross-repository mount from outside the team. pub(crate) fn scoped_query(query: &str, slug: &str) -> String { - let prefix = format!("{}/", team_path(slug)); - // (Another repository of its own team is fine to mount from.) - let pairs: Vec<(&str, &str)> = query - .split('&') - .filter(|p| !p.is_empty()) - .map(|p| p.split_once('=').unwrap_or((p, ""))) - .collect(); - let foreign = pairs - .iter() - .any(|(k, v)| *k == "from" && !decode(v).starts_with(&prefix)); - pairs - .into_iter() - .filter(|(k, _)| !(foreign && (*k == "from" || *k == "mount"))) - .map(|(k, v)| format!("{k}={v}")) - .collect::>() - .join("&") -} - -/// Percent-decoding of a query value ("+" is a space). -fn decode(v: &str) -> String { - let b = v.as_bytes(); - let mut out = Vec::with_capacity(b.len()); - let mut i = 0; - while i < b.len() { - match b[i] { - b'%' if i + 2 < b.len() => match std::str::from_utf8(&b[i + 1..i + 3]) - .ok() - .and_then(|h| u8::from_str_radix(h, 16).ok()) - { - Some(x) => { - out.push(x); - i += 3; - continue; - } - None => out.push(b'%'), - }, - b'+' => out.push(b' '), - c => out.push(c), - } - i += 1; - } - String::from_utf8_lossy(&out).into_owned() + pyo_proto::registry_door::scoped_query(query, &team_path(slug)) } /// One client for every request through the door: no overall timeout (a @@ -843,4 +852,93 @@ mod tests { true )); } + + /// Against a throwaway Postgres: a cluster's door gets the team's + /// working tokens as hashes with their scope, never a token. + #[test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + fn a_clusters_door_gets_hashes_only() { + std::thread::Builder::new() + .stack_size(64 << 20) + .spawn(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + .block_on(hashes_only()) + }) + .unwrap() + .join() + .unwrap(); + } + + async fn hashes_only() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + let run = crate::ids::random_string(8).to_lowercase(); + let (team, user_id) = (format!("team_rd{run}"), format!("usr_rd{run}")); + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $2)") + .bind(&team) + .bind(format!("acme-{run}")) + .execute(&db) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $1 || '@rd.test', $1, '')").bind(&user_id).execute(&db).await.unwrap(); + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $3 || '@rd.test', 'owner', 'active')").bind(format!("mem_rd{run}")).bind(&team).bind(&user_id).execute(&db).await.unwrap(); + let user = crate::auth::User { + id: user_id.clone(), + name: "rd".into(), + email: format!("{user_id}@rd.test"), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + let s = crate::rls::tests::state(db.clone()); + let push = crate::ops::run_json(&s, &user, json!({ "op": "createRegistryToken", "id": format!("rtk_a{run}"), "teamId": team, "name": "ci" })).await.unwrap(); + let pull = crate::ops::run_json(&s, &user, json!({ "op": "createRegistryToken", "id": format!("rtk_b{run}"), "teamId": team, "name": "ro", "scope": "pull", "expiresInDays": 30 })).await.unwrap(); + let (push, pull) = ( + push["token"].as_str().unwrap(), + pull["token"].as_str().unwrap(), + ); + let mut c = db.acquire().await.unwrap(); + let t = team_tokens(&mut c, &team).await.unwrap(); + assert_eq!(t.team_slug, format!("acme-{run}")); + let now = pyo_proto::now_ms() / 1000; + assert!(t.find(push, now).unwrap().push); + let p = t.find(pull, now).unwrap(); + assert!(!p.push && p.expires_at.is_some_and(|e| e > now)); + let sent = + serde_json::to_string(&pyo_proto::Command::SyncRegistryTokens(Box::new(t))).unwrap(); + assert!( + !sent.contains(push) && !sent.contains(pull), + "never a token" + ); + // Revoked: gone from what the doors get. + crate::ops::run_json( + &s, + &user, + json!({ "op": "revokeRegistryToken", "id": format!("rtk_a{run}") }), + ) + .await + .unwrap(); + let t = team_tokens(&mut c, &team).await.unwrap(); + assert!(t.find(push, now).is_none() && t.find(pull, now).is_some()); + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + sqlx::query("DELETE FROM pyo.users WHERE id = $1") + .bind(&user_id) + .execute(&db) + .await + .unwrap(); + } } diff --git a/crates/pyo-api/src/requests.rs b/crates/pyo-api/src/requests.rs new file mode 100644 index 00000000..be54e94e --- /dev/null +++ b/crates/pyo-api/src/requests.rs @@ -0,0 +1,329 @@ +//! Kept requests, read from the clusters. Each cluster's traffic store +//! keeps its requests, connections and WAF findings (pyo-agent's traffic/); +//! Pyo asks the cluster's agent for the newest that match +//! (`QueryTraffic`), up to 500 at a time, and passes them on without +//! keeping them: the command's row, with the answer, is deleted once read. +//! The request explorer, its live tail, and the latest refusals and +//! findings on the firewall's and WAF's pages read them here. + +use std::{collections::BTreeMap, time::Duration}; + +use pyo_proto::traffic::{TrafficAnswer, TrafficQuery}; +use pyo_proto::{Command, CommandResult}; +use serde_json::{Value, json}; + +use crate::{ + AppState, deploy, + error::{ApiError, ApiResult}, + observability::{IpMode, LogFilter}, +}; + +/// How long a cluster gets to answer. +const WAIT: Duration = Duration::from_secs(15); + +/// Asks one cluster. The error is a plain sentence for the dashboard. +pub async fn ask(s: &AppState, cluster_id: &str, q: TrafficQuery) -> Result { + let mut tx = s.db.begin().await.map_err(|e| e.to_string())?; + let id = deploy::enqueue(&mut tx, cluster_id, Command::QueryTraffic(Box::new(q))) + .await + .map_err(|e| e.message)?; + tx.commit().await.map_err(|e| e.to_string())?; + s.wake(cluster_id).await; + let deadline = tokio::time::Instant::now() + WAIT; + let forget = || async { + let _ = sqlx::query("DELETE FROM pyo.commands WHERE id = $1").bind(&id).execute(&s.db).await; + }; + loop { + let row: Option<(String, Option)> = + sqlx::query_as("SELECT status, result FROM pyo.commands WHERE id = $1") + .bind(&id) + .fetch_optional(&s.db) + .await + .map_err(|e| e.to_string())?; + if let Some((status, result)) = row + && (status == "done" || status == "failed") + { + forget().await; + let r: CommandResult = result.and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default(); + if !r.ok { + return Err(r.message.unwrap_or_else(|| "The cluster couldn't read its requests.".into())); + } + return serde_json::from_value(r.data.unwrap_or_default()) + .map_err(|_| "The cluster's answer couldn't be read. Update its agent.".to_owned()); + } + if tokio::time::Instant::now() > deadline { + forget().await; + return Err("The cluster didn't answer in time. Is it connected?".into()); + } + tokio::time::sleep(Duration::from_millis(150)).await; + } +} + +/// The clusters a team's hosts are on: cluster id -> (its name, hosts). +pub async fn hosts_by_cluster( + s: &AppState, + team_id: &str, + hosts: &[String], +) -> ApiResult)>> { + let rows: Vec<(String, String, String)> = sqlx::query_as( + "SELECT DISTINCT a.cluster_id, c.name, lower(d->>'hostname') + FROM pyo.services a JOIN pyo.clusters c ON c.id = a.cluster_id, jsonb_array_elements(a.spec->'domains') d + WHERE a.team_id = $1 AND lower(d->>'hostname') = ANY($2)", + ) + .bind(team_id) + .bind(hosts) + .fetch_all(&s.db) + .await?; + let mut out: BTreeMap)> = BTreeMap::new(); + for (cluster, name, host) in rows { + let e = out.entry(cluster).or_insert_with(|| (name, vec![])); + e.1.push(host); + } + Ok(out) +} + +/// The same query to several clusters at once (each with its own part), +/// merged newest first. Returns the rows, whether there are older ones, +/// and the clusters that couldn't answer (name, why). +pub async fn ask_all( + s: &AppState, + asks: Vec<(String, String, TrafficQuery)>, + limit: usize, +) -> (Vec, bool, Vec<(String, String)>) { + let answers = futures::future::join_all(asks.into_iter().map(|(cluster, name, q)| async move { + (name, ask(s, &cluster, q).await) + })) + .await; + let mut rows = vec![]; + let mut more = false; + let mut failed = vec![]; + for (name, a) in answers { + match a { + Ok(a) => { + more |= a.more; + rows.extend(a.rows); + } + Err(why) => failed.push((name, why)), + } + } + rows.sort_by_key(|r| std::cmp::Reverse(r["at"].as_i64().unwrap_or(0))); + if rows.len() > limit { + more = true; + rows.truncate(limit); + } + (rows, more, failed) +} + +/// A kept request as the request log shows it. +fn request_row(r: &Value, mode: IpMode) -> Value { + json!({ + "at": r["at"], "host": r["host"], "method": r["method"], "path": r["path"], "url": r["url"], + "status": r["status"], "durationMs": r["durationMs"].as_f64().unwrap_or(0.0).round(), "bytes": r["bytes"], + "country": r["country"], "referrer": r["referrer"], "device": r["device"], "browser": r["browser"], + "userAgent": r["userAgent"], "server": r["server"], "blockedBy": r["blockedBy"], + "ip": mode.apply(r["ip"].as_str().unwrap_or("")), + }) +} + +fn range_ms(range: &str) -> i64 { + match range { + "1h" => 3_600_000, + "24h" => 86_400_000, + "30d" => 30 * 86_400_000, + _ => 7 * 86_400_000, + } +} + +/// The web server's request log for some of a team's hosts: newest +/// first, `limit` before `before`, from the clusters that keep them (and, +/// on a self-hosted Pyo, from what Pyo kept itself before 0.5). The first +/// page has the totals for the range when nothing but the website is +/// filtered. +pub async fn access_logs(s: &AppState, team_id: &str, hosts: &[String], f: &LogFilter, path: Option) -> ApiResult { + let obs = &s.observability; + if !obs.enabled().await { + return Err(crate::observability::off()); + } + let now = pyo_proto::now_ms(); + let since = now - range_ms(&f.range); + let before = if f.before > 0 { f.before } else { now + 1 }; + let limit = f.limit.clamp(1, pyo_proto::traffic::MAX_ROWS) as usize; + let clusters = hosts_by_cluster(s, team_id, hosts).await?; + let base = TrafficQuery { + rows: "requests".into(), + since_ms: since, + before_ms: before, + limit: limit as u32, + status: f.status.clone(), + method: f.method.clone(), + path: path.clone().filter(|p| !p.is_empty()), + q: f.q.clone(), + ..Default::default() + }; + let asks = clusters + .iter() + .map(|(id, (name, hosts))| (id.clone(), name.clone(), TrafficQuery { hosts: hosts.clone(), ..base.clone() })) + .collect(); + let mode = obs.current_ip_mode().await; + let (mut rows, mut more, failed) = ask_all(s, asks, limit).await; + let mut logs: Vec = rows.drain(..).map(|r| request_row(&r, mode)).collect(); + // What Pyo kept itself before 0.5 (self-hosted), older than the clusters' rows. + if obs.has_legacy().await && path.as_deref().unwrap_or("").is_empty() { + let legacy = LogFilter { before, limit: limit as u32, ..f.clone() }; + if let Ok(old) = obs.legacy_access_logs(team_id, hosts, &legacy).await { + logs.extend(old["logs"].as_array().cloned().unwrap_or_default()); + more |= old["next"].is_number(); + logs.sort_by_key(|r| std::cmp::Reverse(r["at"].as_i64().unwrap_or(0))); + if logs.len() > limit { + more = true; + logs.truncate(limit); + } + } + } else if !clusters.is_empty() && failed.len() == clusters.len() { + return Err(ApiError::new(axum::http::StatusCode::GATEWAY_TIMEOUT, failed[0].1.clone())); + } + let next = if more { logs.last().and_then(|l| l["at"].as_i64()) } else { None }; + let unfiltered = f.status.is_none() && f.method.is_none() && f.q.as_deref().unwrap_or("").trim().is_empty() && path.is_none(); + let summary = if f.before == 0 && unfiltered { + obs.request_summary(team_id, hosts, since / 1000).await.ok().flatten() + } else { + None + }; + Ok(json!({ + "logs": logs, + "next": next, + "ipMode": mode, + "summary": summary, + "unavailable": failed.iter().map(|(name, why)| json!({ "cluster": name, "error": why })).collect::>(), + })) +} + +/// The latest the firewall turned away for a service, and their busiest +/// sources (among the latest 500): requests to its websites and +/// connections to its ports, from its cluster. Best effort: empty, with +/// `recentError`, when the cluster can't answer. +pub async fn blocked_recent(s: &AppState, service_id: &str, range: &str, out: &mut Value) -> ApiResult<()> { + let Some((cluster, hosts, ports)) = service_targets(s, service_id).await? else { + return Ok(()); + }; + let since = pyo_proto::now_ms() - range_ms(range); + let mut asks = vec![]; + if !hosts.is_empty() { + asks.push((cluster.clone(), String::new(), TrafficQuery { rows: "requests".into(), hosts, blocked: true, since_ms: since, limit: 500, ..Default::default() })); + } + if !ports.is_empty() { + asks.push((cluster.clone(), String::new(), TrafficQuery { rows: "connections".into(), ports, outcome: Some("blocked".into()), since_ms: since, limit: 500, ..Default::default() })); + } + let (rows, _, failed) = ask_all(s, asks, 500).await; + let mode = s.observability.current_ip_mode().await; + let mut by_ip: BTreeMap = BTreeMap::new(); + for r in &rows { + let ip = mode.apply(r["ip"].as_str().unwrap_or("")); + if ip.is_empty() { + continue; + } + let e = by_ip.entry(ip).or_insert_with(|| (r["country"].as_str().unwrap_or("").to_owned(), 0.0)); + e.1 += 1.0; + } + let mut sources: Vec<(String, (String, f64))> = by_ip.into_iter().collect(); + sources.sort_by(|a, b| b.1.1.total_cmp(&a.1.1)); + sources.truncate(50); + out["sources"] = json!(sources.iter().map(|(ip, (country, n))| json!({ "ip": ip, "country": country, "count": n })).collect::>()); + out["recent"] = json!(rows.iter().take(50).map(|r| { + let website = r.get("host").is_some(); + json!({ + "at": r["at"], "serviceId": service_id, + "kind": if website { "website".to_owned() } else { r["protocol"].as_str().unwrap_or("tcp").to_lowercase() }, + "target": if website { r["host"].clone() } else { json!(r["port"].to_string()) }, + "ip": mode.apply(r["ip"].as_str().unwrap_or("")), "country": r["country"], + "rule": if website { r["blockedBy"].clone() } else { r["rule"].clone() }, + }) + }).collect::>()); + out["ipMode"] = json!(mode); + if let Some((_, why)) = failed.first() { + out["recentError"] = json!(why); + } + Ok(()) +} + +/// The WAF's latest findings for a service, and their busiest sources +/// (among the latest 500), from its cluster. +pub async fn waf_recent(s: &AppState, service_id: &str, range: &str, out: &mut Value) -> ApiResult<()> { + let Some((cluster, hosts, _)) = service_targets(s, service_id).await? else { + return Ok(()); + }; + if hosts.is_empty() { + return Ok(()); + } + let since = pyo_proto::now_ms() - range_ms(range); + let q = TrafficQuery { rows: "waf".into(), hosts, since_ms: since, limit: 500, ..Default::default() }; + let (rows, _, failed) = ask_all(s, vec![(cluster, String::new(), q)], 500).await; + let mode = s.observability.current_ip_mode().await; + let mut by_ip: BTreeMap = BTreeMap::new(); + for r in &rows { + let ip = mode.apply(r["ip"].as_str().unwrap_or("")); + if ip.is_empty() { + continue; + } + let e = by_ip.entry(ip).or_insert_with(|| (r["country"].as_str().unwrap_or("").to_owned(), 0.0, 0.0)); + if r["blocked"] == json!(true) { e.1 += 1.0 } else { e.2 += 1.0 } + } + let mut sources: Vec<(String, (String, f64, f64))> = by_ip.into_iter().collect(); + sources.sort_by(|a, b| (b.1.1 + b.1.2).total_cmp(&(a.1.1 + a.1.2))); + sources.truncate(50); + out["sources"] = json!(sources.iter().map(|(ip, (c, nb, nl))| json!({ "ip": ip, "country": c, "blocked": nb, "logged": nl })).collect::>()); + out["recent"] = json!(rows.iter().take(50).map(|r| json!({ + "at": r["at"], "serviceId": service_id, "host": r["host"], "method": r["method"], "url": r["url"], + "ip": mode.apply(r["ip"].as_str().unwrap_or("")), "country": r["country"], "blocked": r["blocked"], + "rules": r["rules"], "messages": r["messages"], "severity": r["severity"], + })).collect::>()); + out["ipMode"] = json!(mode); + if let Some((_, why)) = failed.first() { + out["recentError"] = json!(why); + } + Ok(()) +} + +/// A service's latest connections to its proxied ports, from its cluster. +pub async fn connections_recent(s: &AppState, service_id: &str, range: &str, out: &mut Value) -> ApiResult<()> { + let Some((cluster, _, ports)) = service_targets(s, service_id).await? else { + return Ok(()); + }; + if ports.is_empty() { + return Ok(()); + } + let since = pyo_proto::now_ms() - range_ms(range); + let q = TrafficQuery { rows: "connections".into(), ports, since_ms: since, limit: 50, ..Default::default() }; + let (rows, _, failed) = ask_all(s, vec![(cluster, String::new(), q)], 50).await; + let mode = s.observability.current_ip_mode().await; + out["recent"] = json!(rows.iter().map(|r| json!({ + "at": r["at"], "port": r["port"], "protocol": r["protocol"], "ip": mode.apply(r["ip"].as_str().unwrap_or("")), + "country": r["country"], "durationMs": r["durationMs"].as_f64().unwrap_or(0.0).round(), + "bytesIn": r["bytesIn"], "bytesOut": r["bytesOut"], "outcome": r["outcome"], + })).collect::>()); + out["ipMode"] = json!(mode); + if let Some((_, why)) = failed.first() { + out["recentError"] = json!(why); + } + Ok(()) +} + +/// A service's cluster, website hosts and proxied ports' keys. +async fn service_targets(s: &AppState, service_id: &str) -> ApiResult, Vec)>> { + let row: Option<(String, String, String, Value, Value)> = sqlx::query_as( + "SELECT a.cluster_id, p.namespace, a.name, a.spec->'domains', a.spec->'ports' + FROM pyo.services a JOIN pyo.projects p ON p.id = a.project_id WHERE a.id = $1", + ) + .bind(service_id) + .fetch_optional(&s.db) + .await?; + let Some((cluster, ns, name, domains, ports)) = row else { return Ok(None) }; + let hosts = domains + .as_array() + .into_iter() + .flatten() + .filter_map(|d| d["hostname"].as_str().map(str::to_lowercase)) + .collect(); + let ports = crate::totals::port_keys(&ns, &name, &ports).into_iter().map(|(k, _)| k).collect(); + Ok(Some((cluster, hosts, ports))) +} diff --git a/crates/pyo-api/src/retention.rs b/crates/pyo-api/src/retention.rs new file mode 100644 index 00000000..8f422efe --- /dev/null +++ b/crates/pyo-api/src/retention.rs @@ -0,0 +1,589 @@ +//! How long observability keeps what it stores. +//! +//! The installation's admin picks, in Settings › Observability: +//! analytics totals (the hourly traffic and port tables, and the WAF's rule +//! messages) 3, 6, 12 or 24 months; server, service and database metrics 7 +//! to 90 days; build and deploy logs 30 to 365 days. Saved in pyo.settings +//! 'observability' as `retention`. ClickHouse keeps each table by its own +//! TTL, so a change is an `ALTER TABLE … MODIFY TTL` (`apply`), made again +//! whenever the tables are set up, so tables made with another TTL follow +//! the setting. Build logs live in Postgres: jobs.rs prunes them by it. +//! +//! A team may keep its analytics shorter (Team settings, `analyticsMonths`: +//! 3, 6 or 12 months, never more than the installation). That is on Pyo +//! Cloud too, where teams share the tables. ClickHouse's TTL is per table, +//! so a team's shorter time is a cleanup once a day (`team_cleanup`): one +//! `ALTER TABLE … DELETE` per table for every such team at once. A per-row +//! TTL (a retention column on each row) was the other way: it would only +//! reach rows stored after a change, and every row would carry the column +//! through the hourly views. The cleanup applies a change to what's +//! already there. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicI64, Ordering}; + +use serde_json::{Value, json}; +use sqlx::PgPool; + +use crate::error::{ApiError, ApiResult}; +use crate::observability::ClickHouse; + +/// What the installation may keep analytics totals for, in months. +pub const ANALYTICS_MONTHS: [u8; 4] = [3, 6, 12, 24]; +/// What a team may pick, in months (never more than the installation). +pub const TEAM_ANALYTICS_MONTHS: [u8; 3] = [3, 6, 12]; +/// Metrics, in days (inclusive). +pub const METRICS_DAYS: (u16, u16) = (7, 90); +/// Build and deploy logs, in days (inclusive). +pub const BUILD_LOG_DAYS: (u16, u16) = (30, 365); + +/// The installation's retention ('retention' in pyo.settings +/// 'observability'). +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct Retention { + pub analytics_months: u8, + pub metrics_days: u16, + pub build_log_days: u16, +} + +impl Default for Retention { + fn default() -> Self { + Retention { analytics_months: 12, metrics_days: 30, build_log_days: 90 } + } +} + +impl Retention { + /// Why it can't be saved, if it can't. + pub fn check(&self) -> Result<(), &'static str> { + if !ANALYTICS_MONTHS.contains(&self.analytics_months) { + return Err("Keep analytics 3, 6, 12 or 24 months."); + } + if !(METRICS_DAYS.0..=METRICS_DAYS.1).contains(&self.metrics_days) { + return Err("Keep metrics 7 to 90 days."); + } + if !(BUILD_LOG_DAYS.0..=BUILD_LOG_DAYS.1).contains(&self.build_log_days) { + return Err("Keep build logs 30 to 365 days."); + } + Ok(()) + } + + /// From the saved 'observability' setting: each figure as saved, or its + /// default when it's missing or out of range. + pub fn from_setting(v: &Value) -> Self { + let r = &v["retention"]; + let d = Retention::default(); + let n = |k: &str| r[k].as_u64(); + Retention { + analytics_months: n("analyticsMonths") + .and_then(|m| u8::try_from(m).ok()) + .filter(|m| ANALYTICS_MONTHS.contains(m)) + .unwrap_or(d.analytics_months), + metrics_days: n("metricsDays") + .and_then(|m| u16::try_from(m).ok()) + .filter(|m| (METRICS_DAYS.0..=METRICS_DAYS.1).contains(m)) + .unwrap_or(d.metrics_days), + build_log_days: n("buildLogDays") + .and_then(|m| u16::try_from(m).ok()) + .filter(|m| (BUILD_LOG_DAYS.0..=BUILD_LOG_DAYS.1).contains(m)) + .unwrap_or(d.build_log_days), + } + } + + /// Each ClickHouse table's TTL for this retention, as ClickHouse + /// prints it back (`engine_full`), so `apply` can tell what changed. + pub fn ttls(&self) -> Vec<(&'static str, String)> { + let months = |col: &str| format!("{col} + toIntervalMonth({})", self.analytics_months); + let days = format!("ts + toIntervalDay({})", self.metrics_days); + vec![ + ("traffic_1h", months("ts")), + ("ports_1h", months("ts")), + ("waf_rules", months("seen")), + ("metrics", days.clone()), + ("node_metrics", days.clone()), + ("database_metrics", days), + ] + } +} + +/// The installation's retention, as saved (defaults when it isn't). +pub async fn load(db: &PgPool) -> ApiResult { + let v: Option = sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'observability'") + .fetch_optional(db) + .await?; + Ok(v.map(|v| Retention::from_setting(&v)).unwrap_or_default()) +} + +/// Save the installation's retention (its admin). Returns whether it +/// changed. +pub async fn save(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, r: &Retention) -> ApiResult { + r.check().map_err(ApiError::bad_request)?; + let v: Value = sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'observability'") + .fetch_optional(&mut **tx) + .await? + .unwrap_or_else(|| json!({})); + let changed = Retention::from_setting(&v) != *r; + sqlx::query( + "INSERT INTO pyo.settings (key, value) VALUES ('observability', jsonb_build_object('retention', $1::jsonb)) + ON CONFLICT (key) DO UPDATE SET value = pyo.settings.value || excluded.value, updated_at = now()", + ) + .bind(json!(r)) + .execute(&mut **tx) + .await?; + Ok(changed) +} + +/// Why a team's analytics months can't be saved, if they can't. 0 means +/// "as long as the installation". +pub fn check_team_months(months: u8, installation: &Retention) -> Result<(), String> { + if months == 0 { + return Ok(()); + } + if !TEAM_ANALYTICS_MONTHS.contains(&months) { + return Err("Keep analytics 3, 6 or 12 months.".into()); + } + if months > installation.analytics_months { + return Err(format!( + "This installation keeps analytics {} months at most.", + installation.analytics_months + )); + } + Ok(()) +} + +/// The TTL in a table's `engine_full`, or None when it has none. +fn ttl_of(engine_full: &str) -> Option<&str> { + let start = engine_full.find(" TTL ")? + 5; + let rest = &engine_full[start..]; + Some(rest.find(" SETTINGS ").map_or(rest, |end| &rest[..end]).trim()) +} + +/// The `ALTER TABLE … MODIFY TTL` statements that bring these tables +/// (name, engine_full) to the retention. Tables not made yet are left out: +/// they're made with the default and follow at the next `apply`. +pub fn ttl_changes(r: &Retention, tables: &[(String, String)]) -> Vec<(&'static str, String)> { + r.ttls() + .into_iter() + .filter_map(|(table, ttl)| { + let (_, engine) = tables.iter().find(|(n, _)| n == table)?; + (ttl_of(engine) != Some(ttl.as_str())) + .then(|| (table, format!("ALTER TABLE pyo_observability.{table} MODIFY TTL {ttl}"))) + }) + .collect() +} + +/// Bring the tables' TTLs to the retention. Returns the tables changed. +/// ClickHouse applies a new TTL to stored rows in the background. +pub async fn apply(ch: &ClickHouse, r: &Retention) -> anyhow::Result> { + let text = ch + .exec( + "SELECT name, engine_full FROM system.tables WHERE database = 'pyo_observability' FORMAT JSONEachRow", + None, + &[], + ) + .await?; + let tables: Vec<(String, String)> = text + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter_map(|v| Some((v["name"].as_str()?.to_owned(), v["engine_full"].as_str()?.to_owned()))) + .collect(); + let mut changed = vec![]; + for (table, sql) in ttl_changes(r, &tables) { + ch.exec(&sql, None, &[]).await?; + changed.push(table.to_owned()); + } + if !changed.is_empty() { + tracing::info!(tables = ?changed, "observability retention applied"); + } + Ok(changed) +} + +// ── Teams that keep analytics shorter ─────────────────────────────────────── + +/// The analytics tables and their time column. +const ANALYTICS_TABLES: [(&str, &str); 3] = [("traffic_1h", "ts"), ("ports_1h", "ts"), ("waf_rules", "seen")]; + +/// Team ids per statement (they're inlined in the SQL body). +const TEAMS_PER_STATEMENT: usize = 1000; + +fn quote(s: &str) -> String { + format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'")) +} + +/// The rows to remove from a table with time column `col`: each team's +/// older than its months before `now` (seconds). `teams`: months -> ids. +/// One condition per statement of at most `TEAMS_PER_STATEMENT` teams. +pub fn cleanup_conditions(teams: &BTreeMap>, col: &str, now: i64) -> Vec { + let mut all: Vec<(u8, &String)> = teams.iter().flat_map(|(m, ids)| ids.iter().map(move |id| (*m, id))).collect(); + all.sort(); + all.chunks(TEAMS_PER_STATEMENT) + .map(|chunk| { + let mut by_months: BTreeMap> = BTreeMap::new(); + for (m, id) in chunk { + by_months.entry(*m).or_default().push(quote(id)); + } + by_months + .into_iter() + .map(|(m, ids)| { + format!( + "(team_id IN ({}) AND {col} < subtractMonths(toDateTime({now}, 'UTC'), {m}))", + ids.join(", ") + ) + }) + .collect::>() + .join(" OR ") + }) + .collect() +} + +/// The teams keeping analytics shorter than the installation: months -> +/// team ids. +pub async fn shorter_teams(db: &PgPool, installation: &Retention) -> sqlx::Result>> { + let rows: Vec<(String, i16)> = sqlx::query_as( + "SELECT id, analytics_months FROM pyo.teams WHERE analytics_months IS NOT NULL AND analytics_months < $1 ORDER BY id", + ) + .bind(i16::from(installation.analytics_months)) + .fetch_all(db) + .await?; + let mut out: BTreeMap> = BTreeMap::new(); + for (id, m) in rows { + out.entry(m as u8).or_default().push(id); + } + Ok(out) +} + +/// Remove what teams keeping analytics shorter don't keep any more. A +/// table with a cleanup still running is left for the next time. Returns +/// the statements sent. +pub async fn team_cleanup(db: &PgPool, ch: &ClickHouse, now: i64) -> anyhow::Result { + let installation = load(db).await.map_err(|e| anyhow::anyhow!("{}", e.message))?; + let teams = shorter_teams(db, &installation).await?; + if teams.is_empty() { + return Ok(0); + } + let mut sent = 0; + for (table, col) in ANALYTICS_TABLES { + let running = ch + .exec( + &format!( + "SELECT count() FROM system.mutations WHERE database = 'pyo_observability' AND table = '{table}' AND NOT is_done" + ), + None, + &[], + ) + .await?; + if running.trim() != "0" { + continue; + } + for cond in cleanup_conditions(&teams, col, now) { + let n = ch.exec(&format!("SELECT count() FROM pyo_observability.{table} WHERE {cond}"), None, &[]).await?; + if n.trim() == "0" { + continue; + } + ch.exec(&format!("ALTER TABLE pyo_observability.{table} DELETE WHERE {cond}"), None, &[]).await?; + sent += 1; + } + } + if sent > 0 { + tracing::info!(statements = sent, "removed analytics teams keep shorter"); + } + Ok(sent) +} + +/// When `nightly` last ran (seconds), in this process. +static LAST_CLEANUP: AtomicI64 = AtomicI64::new(0); + +/// Once a day, from the sweeper (one process at a time): the teams' +/// shorter analytics. Waits while observability is off or starting. +pub async fn nightly(s: &crate::AppState) { + let now = pyo_proto::now_ms() / 1000; + if now - LAST_CLEANUP.load(Ordering::Relaxed) < 86_400 { + return; + } + let Some(ch) = s.observability.store().await else { return }; + if !s.observability.is_ready().await { + return; + } + LAST_CLEANUP.store(now, Ordering::Relaxed); + if let Err(e) = team_cleanup(&s.db, ch, now).await { + tracing::warn!(error = %format!("{e:#}"), "couldn't remove analytics teams keep shorter; trying again in an hour"); + LAST_CLEANUP.store(now - 86_400 + 3600, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings_are_checked() { + assert_eq!(Retention::default().check(), Ok(())); + let r = |a, m, b| Retention { analytics_months: a, metrics_days: m, build_log_days: b }; + assert!(r(24, 7, 365).check().is_ok()); + assert!(r(3, 90, 30).check().is_ok()); + assert!(r(13, 30, 90).check().is_err(), "13 months isn't a choice"); + assert!(r(1, 30, 90).check().is_err()); + assert!(r(12, 6, 90).check().is_err()); + assert!(r(12, 91, 90).check().is_err()); + assert!(r(12, 30, 29).check().is_err()); + assert!(r(12, 30, 366).check().is_err()); + } + + #[test] + fn saved_settings_fall_back_per_figure() { + assert_eq!(Retention::from_setting(&json!({ "enabled": true })), Retention::default()); + let v = json!({ "retention": { "analyticsMonths": 24, "metricsDays": 500, "buildLogDays": 30 } }); + assert_eq!( + Retention::from_setting(&v), + Retention { analytics_months: 24, metrics_days: 30, build_log_days: 30 } + ); + let v = json!({ "retention": { "analyticsMonths": 13, "metricsDays": 7, "buildLogDays": "x" } }); + assert_eq!( + Retention::from_setting(&v), + Retention { analytics_months: 12, metrics_days: 7, build_log_days: 90 } + ); + // What's saved reads back. + let r = Retention { analytics_months: 6, metrics_days: 14, build_log_days: 180 }; + assert_eq!(Retention::from_setting(&json!({ "retention": r })), r); + } + + #[test] + fn teams_pick_shorter_only() { + let at = |m| Retention { analytics_months: m, ..Default::default() }; + assert!(check_team_months(0, &at(3)).is_ok(), "as long as the installation"); + assert!(check_team_months(3, &at(12)).is_ok()); + assert!(check_team_months(12, &at(12)).is_ok()); + assert!(check_team_months(12, &at(24)).is_ok()); + assert!(check_team_months(24, &at(24)).is_err(), "teams pick 3, 6 or 12"); + assert!(check_team_months(9, &at(12)).is_err()); + assert_eq!( + check_team_months(12, &at(6)).unwrap_err(), + "This installation keeps analytics 6 months at most." + ); + } + + #[test] + fn ttls_change_only_what_differs() { + let r = Retention { analytics_months: 24, metrics_days: 14, build_log_days: 90 }; + let tables = vec![ + // Made before with the old 13 months. + ( + "traffic_1h".to_owned(), + "AggregatingMergeTree PARTITION BY toYYYYMM(ts) ORDER BY (team_id, host, ts, service_id) TTL ts + toIntervalMonth(13) SETTINGS non_replicated_deduplication_window = 1000, index_granularity = 8192".to_owned(), + ), + ( + "ports_1h".to_owned(), + "AggregatingMergeTree PARTITION BY toYYYYMM(ts) ORDER BY (team_id, service_id, port, protocol, ts) TTL ts + toIntervalMonth(24) SETTINGS index_granularity = 8192".to_owned(), + ), + ( + "waf_rules".to_owned(), + "ReplacingMergeTree(seen) ORDER BY (team_id, rule) TTL seen + toIntervalMonth(12) SETTINGS index_granularity = 8192".to_owned(), + ), + ( + "metrics".to_owned(), + "MergeTree PARTITION BY toYYYYMM(ts) ORDER BY (team_id, kind, id, ts) TTL ts + toIntervalDay(30) SETTINGS index_granularity = 8192".to_owned(), + ), + ("node_metrics".to_owned(), "MergeTree ORDER BY ts TTL ts + toIntervalDay(14)".to_owned()), + // traffic_1m (3 days) isn't the setting's; database_metrics isn't made yet. + ("traffic_1m".to_owned(), "AggregatingMergeTree TTL ts + toIntervalDay(3)".to_owned()), + ]; + let sql: Vec = ttl_changes(&r, &tables).into_iter().map(|(_, s)| s).collect(); + assert_eq!( + sql, + [ + "ALTER TABLE pyo_observability.traffic_1h MODIFY TTL ts + toIntervalMonth(24)", + "ALTER TABLE pyo_observability.waf_rules MODIFY TTL seen + toIntervalMonth(24)", + "ALTER TABLE pyo_observability.metrics MODIFY TTL ts + toIntervalDay(14)", + ] + ); + assert_eq!(ttl_of("MergeTree ORDER BY ts"), None); + } + + #[test] + fn cleanup_keeps_each_team_its_months() { + let mut teams = BTreeMap::new(); + teams.insert(3u8, vec!["team_a".to_owned()]); + teams.insert(6u8, vec!["team_b".to_owned(), "team_c".to_owned()]); + let c = cleanup_conditions(&teams, "ts", 1_800_000_000); + assert_eq!( + c, + ["(team_id IN ('team_a') AND ts < subtractMonths(toDateTime(1800000000, 'UTC'), 3)) OR \ + (team_id IN ('team_b', 'team_c') AND ts < subtractMonths(toDateTime(1800000000, 'UTC'), 6))"] + ); + // Quotes can't end the string. + assert_eq!(quote("a'b\\"), "'a\\'b\\\\'"); + // Many teams: a statement per thousand. + let many: BTreeMap> = [(3u8, (0..2500).map(|i| format!("team_{i:04}")).collect())].into(); + let c = cleanup_conditions(&many, "seen", 0); + assert_eq!(c.len(), 3); + assert!(c.iter().all(|s| s.starts_with("(team_id IN (") && s.contains("seen < "))); + } + + fn test_clickhouse() -> Option { + let url = std::env::var("PYO_TEST_CLICKHOUSE_URL").ok()?; + let password = std::env::var("PYO_TEST_CLICKHOUSE_PASSWORD").unwrap_or_default(); + Some(ClickHouse::new(url, "default".into(), password)) + } + + /// Tables as `ensure_schema` makes them, `traffic_1h` as it was made + /// before (13 months). + async fn fresh_tables(ch: &ClickHouse) { + ch.exec("DROP DATABASE IF EXISTS pyo_observability", None, &[]).await.unwrap(); + ch.exec("CREATE DATABASE pyo_observability", None, &[]).await.unwrap(); + for sql in crate::totals::schema() { + let sql = if sql.contains("pyo_observability.traffic_1h (") { + sql.replace("ts + INTERVAL 12 MONTH", "ts + INTERVAL 13 MONTH") + } else { + sql + }; + ch.exec(&sql, None, &[]).await.unwrap(); + } + for sql in crate::observability::schema_for_tests() { + ch.exec(sql, None, &[]).await.unwrap(); + } + } + + async fn wait_for_mutations(ch: &ClickHouse) { + for _ in 0..100 { + let n = ch + .exec("SELECT count() FROM system.mutations WHERE database = 'pyo_observability' AND NOT is_done", None, &[]) + .await + .unwrap(); + if n.trim() == "0" { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + panic!("mutations still running"); + } + + /// Against a throwaway ClickHouse (`PYO_TEST_CLICKHOUSE_URL`): every + /// table takes the setting's TTL, a table made with the old 13 months + /// included, and once they have it nothing more is changed. + #[tokio::test] + #[ignore = "needs a throwaway ClickHouse"] + async fn tables_follow_the_setting() { + let Some(ch) = test_clickhouse() else { return }; + fresh_tables(&ch).await; + // The defaults: only the table made with 13 months changes. + assert_eq!(apply(&ch, &Retention::default()).await.unwrap(), ["traffic_1h"]); + assert!(apply(&ch, &Retention::default()).await.unwrap().is_empty()); + let r = Retention { analytics_months: 24, metrics_days: 7, build_log_days: 365 }; + let mut changed = apply(&ch, &r).await.unwrap(); + changed.sort(); + assert_eq!(changed, ["database_metrics", "metrics", "node_metrics", "ports_1h", "traffic_1h", "waf_rules"]); + assert!(apply(&ch, &r).await.unwrap().is_empty(), "nothing left to change"); + let ttl = |t: &'static str| { + let ch = &ch; + async move { + let e = ch + .exec(&format!("SELECT engine_full FROM system.tables WHERE database = 'pyo_observability' AND name = '{t}'"), None, &[]) + .await + .unwrap(); + ttl_of(e.trim()).unwrap_or_default().to_owned() + } + }; + assert_eq!(ttl("traffic_1h").await, "ts + toIntervalMonth(24)"); + assert_eq!(ttl("waf_rules").await, "seen + toIntervalMonth(24)"); + assert_eq!(ttl("node_metrics").await, "ts + toIntervalDay(7)"); + assert_eq!(ttl("traffic_1m").await, "ts + toIntervalDay(3)", "minutes stay 3 days"); + // Shorter: stored rows past it go. + apply(&ch, &Retention { metrics_days: 30, ..r }).await.unwrap(); + let now = pyo_proto::now_ms() / 1000; + let rows = [10, 2] + .iter() + .map(|d| json!({ "ts": now - d * 86400, "team_id": "team_x", "cluster_id": "c", "kind": "server", "id": "s", "name": "s" }).to_string()) + .collect::>() + .join("\n"); + ch.insert("metrics", rows, "m").await.unwrap(); + assert_eq!(apply(&ch, &Retention { metrics_days: 7, ..r }).await.unwrap(), ["metrics", "node_metrics", "database_metrics"]); + wait_for_mutations(&ch).await; + let left = ch.exec("SELECT count() FROM pyo_observability.metrics", None, &[]).await.unwrap(); + assert_eq!(left.trim(), "1", "the 10-day-old sample is gone"); + ch.exec("DROP DATABASE pyo_observability", None, &[]).await.unwrap(); + } + + /// Against a throwaway Postgres (DATABASE_URL) and ClickHouse: a team + /// keeping 3 months loses what's older, one keeping 6 keeps 4 months + /// back, and one following the installation keeps everything. + #[tokio::test] + #[ignore = "needs DATABASE_URL and PYO_TEST_CLICKHOUSE_URL (throwaway ones)"] + async fn teams_keep_their_own_months() { + let (Ok(db_url), Some(ch)) = (std::env::var("DATABASE_URL"), test_clickhouse()) else { return }; + let pool = PgPool::connect(&db_url).await.unwrap(); + crate::migrate::run(&pool).await.unwrap(); + sqlx::query("DELETE FROM pyo.settings WHERE key = 'observability'").execute(&pool).await.unwrap(); + fresh_tables(&ch).await; + let run = crate::ids::new_id("t"); + let (three, six, all) = (format!("team_3{run}"), format!("team_6{run}"), format!("team_a{run}")); + for (team, months) in [(&three, Some(3i16)), (&six, Some(6)), (&all, None)] { + sqlx::query("INSERT INTO pyo.teams (id, name, slug, analytics_months) VALUES ($1, $1, $1, $2)") + .bind(team) + .bind(months) + .execute(&pool) + .await + .unwrap(); + } + // The column takes 3, 6 or 12 only. + assert!(sqlx::query("UPDATE pyo.teams SET analytics_months = 24 WHERE id = $1").bind(&three).execute(&pool).await.is_err()); + let now = pyo_proto::now_ms() / 1000 / 3600 * 3600; + let day = 86_400; + let mut traffic = String::new(); + let mut ports = String::new(); + let mut waf = String::new(); + for team in [&three, &six, &all] { + for days_ago in [300, 200, 120, 30, 1] { + let ts = now - days_ago * day; + traffic.push_str(&json!({ "ts": ts, "team_id": team, "service_id": "s", "host": "h", "requests": 1 }).to_string()); + traffic.push('\n'); + ports.push_str(&json!({ "ts": ts, "team_id": team, "service_id": "s", "port": 22, "protocol": "TCP", "connections": 1 }).to_string()); + ports.push('\n'); + waf.push_str(&json!({ "team_id": team, "rule": days_ago.to_string(), "message": "m", "seen": ts }).to_string()); + waf.push('\n'); + } + } + ch.insert("traffic_1h", traffic, "t").await.unwrap(); + ch.insert("ports_1h", ports, "p").await.unwrap(); + ch.insert("waf_rules", waf, "w").await.unwrap(); + + // 3 tables, one statement each. + assert_eq!(team_cleanup(&pool, &ch, now).await.unwrap(), 3); + wait_for_mutations(&ch).await; + let days_left = |table: &'static str, col: &'static str, team: String| { + let ch = &ch; + async move { + let text = ch + .exec( + &format!("SELECT intDiv({now} - toUnixTimestamp({col}), 86400) AS d FROM pyo_observability.{table} WHERE team_id = {{t:String}} ORDER BY d DESC"), + None, + &[("t", team)], + ) + .await + .unwrap(); + text.lines().map(|l| l.trim().parse::().unwrap()).collect::>() + } + }; + for (table, col) in ANALYTICS_TABLES { + assert_eq!(days_left(table, col, three.clone()).await, [30, 1], "{table}: 3 months"); + assert_eq!(days_left(table, col, six.clone()).await, [120, 30, 1], "{table}: 6 months"); + assert_eq!(days_left(table, col, all.clone()).await, [300, 200, 120, 30, 1], "{table}: the installation's"); + } + // Nothing left to remove: nothing sent. + assert_eq!(team_cleanup(&pool, &ch, now).await.unwrap(), 0); + + // The installation keeping 6 months: the 6-month team follows the + // table's TTL, the 3-month team still gets its cleanup. + let mut tx = pool.begin().await.unwrap(); + save(&mut tx, &Retention { analytics_months: 6, ..Default::default() }).await.unwrap(); + tx.commit().await.unwrap(); + let shorter = shorter_teams(&pool, &load(&pool).await.unwrap()).await.unwrap(); + assert!(shorter.get(&3).is_some_and(|t| t.contains(&three))); + assert!(!shorter.values().flatten().any(|t| t == &six || t == &all)); + + sqlx::query("DELETE FROM pyo.settings WHERE key = 'observability'").execute(&pool).await.unwrap(); + for team in [&three, &six, &all] { + sqlx::query("DELETE FROM pyo.teams WHERE id = $1").bind(team).execute(&pool).await.unwrap(); + } + ch.exec("DROP DATABASE pyo_observability", None, &[]).await.unwrap(); + } +} diff --git a/crates/pyo-api/src/rls.rs b/crates/pyo-api/src/rls.rs new file mode 100644 index 00000000..98e1d4e4 --- /dev/null +++ b/crates/pyo-api/src/rls.rs @@ -0,0 +1,565 @@ +//! Row security on team_id (migrations 0022 and 0032), behind the API's +//! own team checks: a check the code forgot still can't read or change +//! another team's rows. +//! +//! Pyo connects as its tables' owner, which row security doesn't hold back. +//! That is the bypass, and it stays the default: migrations, the agents' +//! and builders' endpoints, webhooks, background jobs and anything an +//! operator runs see every row. A request made for a person or an API key +//! lowers its transaction ([`scope`], [`begin`]) to the `pyo_team` role, +//! with the teams it may see in `pyo.team_ids`. There the policies show and +//! accept only those teams' rows: operations, the dashboard's `/state` +//! (and the MCP tools that read it), and the REST reads. Work that crosses +//! teams on purpose (a hostname is one team's across the installation, a +//! hosted build's billing tables) lifts the transaction back for that part +//! ([`lift`], then [`Lifted::lower`]). +//! +//! Both settings are local to the transaction: its connection goes back +//! to the pool as the owner. Self-hosted and hosted run the same policies. + +use sqlx::{PgConnection, PgPool, Postgres, Transaction}; + +use crate::auth::User; + +/// Lowers the transaction to the teams `user` may see: the ones they're an +/// active member of, within an API key's teams, leaving out the teams that +/// require two-factor while the account has none (all of them while it +/// must set it up first: twofactor.rs). One round trip. Again on a +/// lowered transaction it picks up teams joined since (a new team). +pub async fn scope(conn: &mut PgConnection, user: &User) -> sqlx::Result<()> { + let key_teams: Option> = user.key.as_ref().and_then(|k| k.teams.clone()); + sqlx::query( + "SELECT set_config('pyo.team_ids', pyo.member_team_ids($1, $2, $3), true), + set_config('role', 'pyo_team', true)", + ) + .bind(&user.id) + .bind(key_teams) + .bind(crate::hosted()) + .execute(conn) + .await?; + Ok(()) +} + +/// A transaction for a person's or API key's request, lowered to their +/// teams ([`scope`]). Reads go through it too, so a query that forgot its +/// team check still sees only theirs. Hold it only for the request's own +/// queries: anything that takes another connection from the pool meanwhile +/// waits on a pool this request already holds one of. +pub async fn begin(db: &PgPool, user: &User) -> sqlx::Result> { + let mut tx = db.begin().await?; + scope(&mut tx, user).await?; + Ok(tx) +} + +/// The teams a lowered transaction may see ([`scope`]): what its queries' +/// `team_id = ANY($1)` bind. Empty when it isn't lowered. +pub async fn team_ids(conn: &mut PgConnection) -> sqlx::Result> { + let ids: Option> = sqlx::query_scalar("SELECT pyo.team_scope()") + .fetch_one(conn) + .await?; + Ok(ids.unwrap_or_default()) +} + +/// A transaction lifted out of its team scope by [`lift`]. +#[must_use = "lower it again once the work across teams is done"] +pub struct Lifted { + was_scoped: bool, +} + +/// Lifts the transaction out of its team scope, for work that has to see +/// or change other teams' rows on purpose. Keep it to that work, then +/// [`Lifted::lower`] it again. A transaction that wasn't scoped stays as +/// it is. +pub async fn lift(conn: &mut PgConnection) -> sqlx::Result { + let was_scoped: bool = sqlx::query_scalar("SELECT current_user::text = 'pyo_team'") + .fetch_one(&mut *conn) + .await?; + if was_scoped { + sqlx::query("SELECT set_config('role', 'none', true)") + .execute(conn) + .await?; + } + Ok(Lifted { was_scoped }) +} + +impl Lifted { + /// Whether the transaction was lowered to a person's or API key's + /// teams: it's their request. + pub fn was_scoped(&self) -> bool { + self.was_scoped + } + + /// Back to the team scope the transaction had before [`lift`]. + pub async fn lower(self, conn: &mut PgConnection) -> sqlx::Result<()> { + if self.was_scoped { + sqlx::query("SELECT set_config('role', 'pyo_team', true)") + .execute(conn) + .await?; + } + Ok(()) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use axum::http::StatusCode; + use serde_json::{Value, json}; + use sqlx::PgPool; + + /// Tables with a team_id that row security doesn't cover, each with + /// why. A new team-owned table gets a policy in its migration, or a + /// place here with its reason. + const NOT_COVERED: &[(&str, &str)] = &[]; + + 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(); + } + + async fn db() -> PgPool { + let db = PgPool::connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL")) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + db + } + + /// Against a throwaway Postgres: every table with a team_id has row + /// security, or is one of [`NOT_COVERED`]. + #[test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + fn every_team_table_has_row_security_or_is_listed() { + run_big(async { + let db = db().await; + let rows: Vec<(String, bool)> = sqlx::query_as( + "SELECT c.relname::text, c.relrowsecurity FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'pyo' AND c.relkind = 'r' + AND EXISTS (SELECT 1 FROM pg_attribute a WHERE a.attrelid = c.oid AND a.attname = 'team_id' AND NOT a.attisdropped) + ORDER BY 1", + ) + .fetch_all(&db) + .await + .unwrap(); + let mut open: Vec<&str> = rows + .iter() + .filter(|(_, rls)| !rls) + .map(|(t, _)| t.as_str()) + .collect(); + let mut listed: Vec<&str> = NOT_COVERED.iter().map(|(t, _)| *t).collect(); + open.sort(); + listed.sort(); + assert_eq!(open, listed); + for t in [ + "services", + "deployments", + "data_keys", + "certificates", + "registry_logins", + "git_connections", + "alert_channels", + "secret_stores", + "clusters", + "projects", + "members", + "volumes", + "activity", + "audit_events", + "sandboxes", + ] { + assert!( + rows.iter().any(|(n, r)| n == t && *r), + "{t} has row security" + ); + } + }); + } + + /// Team A's request can't read or change team B's rows even when the + /// code checks nothing, and a check across teams still sees them. + #[test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + fn a_team_sees_only_its_own_rows() { + run_big(async { + let db = db().await; + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + let run = crate::ids::random_string(8).to_lowercase(); + let id = |p: &str, t: &str| format!("{p}_{t}{run}"); + let mut users = vec![]; + for t in ["a", "b"] { + let user = User { + id: id("usr", t), + name: t.into(), + email: format!("{t}{run}@rls.test"), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + let (team, cluster, project) = (id("team", t), id("cl", t), id("prj", t)); + let q = |sql: &'static str| sqlx::query(sql); + q("INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $2, $1, '')") + .bind(&user.id) + .bind(&user.email) + .execute(&db) + .await + .unwrap(); + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&db) + .await + .unwrap(); + q("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $4, 'admin', 'active')").bind(id("mem", t)).bind(&team).bind(&user.id).bind(&user.email).execute(&db).await.unwrap(); + q("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(&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 spec = json!({ + "source": { "type": "image", "image": "nginx", "reference": "1.27" }, + "replicas": 1, "env": [], "resources": {}, "healthCheck": { "type": "none" }, + "ports": [{ "id": "port_1", "name": "http", "protocol": "HTTP", "containerPort": 80, "exposure": "http" }], + "domains": [{ "id": "dom_1", "hostname": format!("{t}-{run}.example.com"), "portName": "http", "status": "active", "tls": "pending", "tlsMode": "auto", "redirectHttps": true, "createdAt": 1 }], + }); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web', $5, 'running')").bind(id("svc", t)).bind(&team).bind(&project).bind(&cluster).bind(&spec).execute(&db).await.unwrap(); + q("INSERT INTO pyo.deployments (id, team_id, project_id, service_id, cluster_id, status, data, spec) VALUES ($1, $2, $3, $4, $5, 'succeeded', '{}', '{}')").bind(id("dpl", t)).bind(&team).bind(&project).bind(id("svc", t)).bind(&cluster).execute(&db).await.unwrap(); + q("INSERT INTO pyo.deployment_logs (deployment_id, at, level, source, message) VALUES ($1, now(), 'info', 'build', 'secret line')").bind(id("dpl", t)).execute(&db).await.unwrap(); + q("INSERT INTO pyo.certificates (id, team_id, name, hostnames, issuer, not_before, not_after, fingerprint, chain_pem, key_sealed) VALUES ($1, $2, $1, '{}', 'x', now(), now(), 'f', 'pem', 'key')").bind(id("crt", t)).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.registry_logins (id, team_id, host, username, secret_sealed) VALUES ($1, $2, 'ghcr.io', 'u', 'sealed')").bind(id("rgl", t)).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.alert_channels (id, team_id, kind, name, target_sealed) VALUES ($1, $2, 'webhook', 'hook', 'sealed')").bind(id("alc", t)).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.git_connections (id, team_id, provider, base_url, token, webhook_secret) VALUES ($1, $2, 'gitlab', 'https://gitlab.com', 'sealed', 'sealed')").bind(id("gitc", t)).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.git_webhooks (connection_id, repo) VALUES ($1, 'group/repo')") + .bind(id("gitc", t)) + .execute(&db) + .await + .unwrap(); + q("INSERT INTO pyo.secret_stores (id, team_id, kind, name, addr, credential) VALUES ($1, $2, 'vault', 'v', 'https://v', 'sealed')").bind(id("sst", t)).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.data_keys (id, team_id, kek_id, wrapped) VALUES ($1, $2, 'local:x', 'wrapped')").bind(id("dk", t)).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.deploy_hooks (id, team_id, project_id, name, token_hash, token_sealed, created_by) VALUES ($1, $2, $3, 'h', $1, 'sealed', 'x')").bind(id("hook", t)).bind(&team).bind(&project).execute(&db).await.unwrap(); + q("INSERT INTO pyo.agent_keys (id, cluster_id, public_key, expires_at) VALUES ($1, $2, 'pk', now() + interval '1 day')").bind(id("ak", t)).bind(&cluster).execute(&db).await.unwrap(); + q("INSERT INTO pyo.commands (id, cluster_id, command) VALUES ($1, $2, '{\"kind\":\"deploy\",\"env\":[]}')").bind(id("cmd", t)).bind(&cluster).execute(&db).await.unwrap(); + q("INSERT INTO pyo.activity (id, team_id, data) VALUES ($1, $2, '{}')") + .bind(id("act", t)) + .bind(&team) + .execute(&db) + .await + .unwrap(); + q("INSERT INTO pyo.servers (id, cluster_id, name, report) VALUES ($1, $2, $1, '{}')").bind(id("srv", t)).bind(&cluster).execute(&db).await.unwrap(); + q("INSERT INTO pyo.builders (id, team_id, name, kind, cluster_id, token_hash) VALUES ($1, $2, $1, 'cluster', $3, $1)").bind(id("bld", t)).bind(&team).bind(&cluster).execute(&db).await.unwrap(); + q("INSERT INTO pyo.firewall_rules (id, team_id, service_id, action) VALUES ($1, $2, $3, 'block')").bind(id("fw", t)).bind(&team).bind(id("svc", t)).execute(&db).await.unwrap(); + q("INSERT INTO pyo.volumes (id, team_id, cluster_id, project_id, data) VALUES ($1, $2, $3, $4, '{\"name\":\"data\"}')").bind(id("vol", t)).bind(&team).bind(&cluster).bind(&project).execute(&db).await.unwrap(); + q("INSERT INTO pyo.backups (id, team_id, cluster_id, kind, trigger, label) VALUES ($1, $2, $3, 'volume', 'manual', 'x')").bind(id("bak", t)).bind(&team).bind(&cluster).execute(&db).await.unwrap(); + users.push(user); + } + let (a, b) = (&users[0], &users[1]); + + // (table, row of team a, row of team b), by the column that names it. + let rows: &[(&str, &str, &str)] = &[ + ("services", "id", "svc"), + ("deployments", "id", "dpl"), + ("deployment_logs", "deployment_id", "dpl"), + ("certificates", "id", "crt"), + ("registry_logins", "id", "rgl"), + ("alert_channels", "id", "alc"), + ("git_connections", "id", "gitc"), + ("git_webhooks", "connection_id", "gitc"), + ("secret_stores", "id", "sst"), + ("data_keys", "id", "dk"), + ("deploy_hooks", "id", "hook"), + ("agent_keys", "id", "ak"), + ("commands", "id", "cmd"), + ("clusters", "id", "cl"), + ("projects", "id", "prj"), + ("members", "id", "mem"), + ("activity", "id", "act"), + ("servers", "id", "srv"), + ("builders", "id", "bld"), + ("firewall_rules", "id", "fw"), + ("volumes", "id", "vol"), + ("backups", "id", "bak"), + ]; + let count = |table: &str, col: &str| { + sqlx::AssertSqlSafe(format!("SELECT count(*) FROM pyo.{table} WHERE {col} = $1")) + }; + + let mut tx = db.begin().await.unwrap(); + scope(&mut tx, a).await.unwrap(); + for (table, col, prefix) in rows { + let n: i64 = sqlx::query_scalar(count(table, col)) + .bind(id(prefix, "a")) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(n, 1, "team a sees its own {table}"); + let n: i64 = sqlx::query_scalar(count(table, col)) + .bind(id(prefix, "b")) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(n, 0, "team a doesn't see team b's {table}"); + } + // A query that forgot its team check reads and changes nothing of b's. + let spec: Option = + sqlx::query_scalar("SELECT spec FROM pyo.services WHERE id = $1") + .bind(id("svc", "b")) + .fetch_optional(&mut *tx) + .await + .unwrap(); + assert!(spec.is_none()); + let changed = sqlx::query("UPDATE pyo.services SET name = 'mine' WHERE id = $1") + .bind(id("svc", "b")) + .execute(&mut *tx) + .await + .unwrap() + .rows_affected(); + assert_eq!(changed, 0); + let gone = sqlx::query("DELETE FROM pyo.certificates WHERE team_id = $1") + .bind(id("team", "b")) + .execute(&mut *tx) + .await + .unwrap() + .rows_affected(); + assert_eq!(gone, 0); + let all: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pyo.registry_logins WHERE id LIKE '%' || $1", + ) + .bind(&run) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(all, 1, "only its own, also without naming one"); + // Nor writes a row for b. + let e = sqlx::query("INSERT INTO pyo.registry_logins (id, team_id, host, username, secret_sealed) VALUES ($1, $2, 'docker.io', 'u', 's')") + .bind(id("rgl", "x")) + .bind(id("team", "b")) + .execute(&mut *tx) + .await + .unwrap_err(); + assert_eq!( + e.as_database_error().and_then(|d| d.code()).as_deref(), + Some("42501"), + "{e}" + ); + tx.rollback().await.unwrap(); + + // Lifted for work across teams, then lowered again. + let mut tx = db.begin().await.unwrap(); + scope(&mut tx, a).await.unwrap(); + let lifted = lift(&mut tx).await.unwrap(); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.services WHERE id = $1") + .bind(id("svc", "b")) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(n, 1); + lifted.lower(&mut tx).await.unwrap(); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.services WHERE id = $1") + .bind(id("svc", "b")) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(n, 0); + tx.rollback().await.unwrap(); + + // An API key limited to other teams sees none of a's. + let mut keyed = a.clone(); + keyed.key = Some(crate::auth::KeyScope { + access: crate::auth::KeyAccess::Full, + teams: Some(vec![id("team", "z")]), + }); + let mut tx = db.begin().await.unwrap(); + scope(&mut tx, &keyed).await.unwrap(); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.services WHERE id = $1") + .bind(id("svc", "a")) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(n, 0); + tx.rollback().await.unwrap(); + + // The pool's own connections (agents, jobs) see every team's. + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.services WHERE id = ANY($1)") + .bind(vec![id("svc", "a"), id("svc", "b")]) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(n, 2, "the pool is back to the owner"); + + // Through the API: b's service isn't there for a, and b's + // hostname is still taken (that check goes across teams). + let s = state(db.clone()); + let svc = |t: &str, host: &str| { + json!({ + "id": id("svc", t), "projectId": id("prj", t), "clusterId": id("cl", t), "name": "web", + "source": { "type": "image", "image": "nginx", "reference": "1.27" }, + "replicas": 1, "env": [], "resources": {}, "healthCheck": { "type": "none" }, + "ports": [{ "id": "port_1", "name": "http", "protocol": "HTTP", "containerPort": 80, "exposure": "http" }], + "domains": [{ "id": "dom_1", "hostname": host, "portName": "http", "status": "active", "tls": "pending", "tlsMode": "auto", "redirectHttps": true, "createdAt": 1 }], + }) + }; + let e = crate::ops::run_json(&s, a, json!({ "op": "saveService", "service": svc("b", &format!("b-{run}.example.com")) })).await.unwrap_err(); + assert_eq!(e.status, StatusCode::NOT_FOUND, "{}", e.message); + let e = crate::ops::run_json(&s, a, json!({ "op": "saveService", "service": svc("a", &format!("b-{run}.example.com")) })).await.unwrap_err(); + assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message); + crate::ops::run_json(&s, a, json!({ "op": "saveService", "service": svc("a", &format!("a2-{run}.example.com")) })).await.unwrap(); + let _ = b; + + // The dashboard's snapshot (and MCP's reads, made from it) has + // all of a's and nothing of b's. + let snap = crate::snapshot::build(&db, a, "").await.unwrap(); + let shown = snap.to_string(); + for p in ["svc", "cl", "prj", "dpl", "srv", "bld", "vol", "act", "fw"] { + assert!(shown.contains(&id(p, "a")), "a's {p} in /state"); + } + assert!( + !shown.contains(&format!("b{run}")), + "nothing of b's in /state" + ); + // Its parts read only a's teams' rows even when handed b's team. + let mut tx = crate::rls::begin(&db, a).await.unwrap(); + assert_eq!(team_ids(&mut tx).await.unwrap(), vec![id("team", "a")]); + let teams_b = [id("team", "b")]; + assert!( + crate::databases::listing(&mut tx, &teams_b, None) + .await + .unwrap() + .is_empty() + ); + assert!( + crate::teambackup::volume_statuses(&mut tx, &teams_b[0]) + .await + .unwrap() + .is_empty() + ); + let (_, servers) = crate::cloud::snapshot(&mut tx, &teams_b).await.unwrap(); + assert_eq!(servers, json!([])); + assert!( + crate::sandbox::server_views(&mut tx, &teams_b, None) + .await + .unwrap() + .iter() + .all(|v| v["teamId"].is_null()) + ); + assert!( + crate::teambackup::snapshot(&mut tx, &teams_b) + .await + .unwrap() + .iter() + .all(|t| t["history"] == json!([])) + ); + tx.rollback().await.unwrap(); + + // REST reads: b's things aren't there for a. + use axum::extract::{Path, State}; + let session = |u: &User| crate::auth::SessionUser(u.clone()); + let Err(e) = + crate::ops::service_preview(State(s.clone()), session(a), Path(id("svc", "b"))) + .await + else { + panic!("b's service preview"); + }; + assert_eq!(e.status, StatusCode::NOT_FOUND); + let e = crate::ops::fetch_service_logs(&s, a, &id("svc", "b"), Default::default()) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::NOT_FOUND); + let e = crate::volumes::snapshots(State(s.clone()), session(a), Path(id("vol", "b"))) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::NOT_FOUND); + // The scoped transaction is what hides it: the same lookup as + // the owner finds it. + let mut tx = crate::rls::begin(&db, a).await.unwrap(); + let e = crate::ops::team_of(&mut tx, "volumes", &id("vol", "b")) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::NOT_FOUND); + tx.rollback().await.unwrap(); + let mut tx = db.begin().await.unwrap(); + assert_eq!( + crate::ops::team_of(&mut tx, "volumes", &id("vol", "b")) + .await + .unwrap(), + id("team", "b") + ); + tx.rollback().await.unwrap(); + + // MCP: a's service is there, b's isn't, and b's team isn't a's. + let got = crate::mcp::run_tool( + &s, + a, + "get_service", + &json!({ "service_id": id("svc", "a") }), + ) + .await + .unwrap(); + assert!(got.to_string().contains(&id("svc", "a"))); + assert!( + crate::mcp::run_tool( + &s, + a, + "get_service", + &json!({ "service_id": id("svc", "b") }) + ) + .await + .is_err() + ); + assert!( + crate::mcp::run_tool(&s, a, "list_services", &json!({ "team": id("team", "b") })) + .await + .is_err() + ); + let listed = crate::mcp::run_tool(&s, a, "list_servers", &json!({})) + .await + .unwrap(); + assert!(!listed.to_string().contains(&format!("b{run}"))); + + for t in ["a", "b"] { + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(id("team", t)) + .execute(&db) + .await + .unwrap(); + sqlx::query("DELETE FROM pyo.users WHERE id = $1") + .bind(id("usr", t)) + .execute(&db) + .await + .unwrap(); + } + }); + } + + pub(crate) fn state(db: PgPool) -> crate::AppState { + let config = crate::Config { + agent_api_url: String::new(), + agent_image: String::new(), + waf_image: pyo_proto::system::WAF_IMAGE_DEFAULT.into(), + geoip_image: pyo_proto::system::GEOIP_IMAGE_DEFAULT.into(), + cookie_secure: false, + allow_signup: false, + builder_image: String::new(), + relay_addr: None, + }; + let (_stop, stopping) = tokio::sync::watch::channel(false); + crate::AppState { + db: db.clone(), + config: std::sync::Arc::new(config), + observability: crate::observability::Observability::from_env(db), + sealer: std::sync::Arc::new(crate::secrets::Sealer::for_tests()), + wakers: Default::default(), + terminals: Default::default(), + stopping, + } + } +} diff --git a/crates/pyo-api/src/routes.rs b/crates/pyo-api/src/routes.rs index 5918b703..9719946d 100644 --- a/crates/pyo-api/src/routes.rs +++ b/crates/pyo-api/src/routes.rs @@ -161,8 +161,10 @@ async fn current(db: &PgPool, o: &mut Value) -> anyhow::Result<()> { } /// Its domains route now: each one whose DNS checks out is active, and its -/// certificate issued (an uploaded one), off, or on its way. With -/// `revision`, only while the service's domains are still that version. +/// certificate issued (an uploaded one), off, or on its way. Tailnet +/// domains keep their state: it follows the cluster's tailnet +/// (tailscale.rs). With `revision`, only while the service's domains are +/// still that version. pub async fn mark_routed( tx: &mut Transaction<'_, Postgres>, service_id: &str, @@ -170,12 +172,12 @@ pub async fn mark_routed( ) -> ApiResult<()> { sqlx::query( "UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', coalesce(( - SELECT jsonb_agg(d || jsonb_build_object( + SELECT jsonb_agg(CASE WHEN lower(d->>'hostname') LIKE '%.ts.net' THEN d ELSE d || jsonb_build_object( -- Ones still waiting for DNS stay so until the DNS watcher sees them resolve. 'status', CASE WHEN d->>'status' IN ('pending_dns', 'verifying') THEN d->>'status' ELSE 'active' END, 'tls', CASE WHEN coalesce(d->>'tlsMode', 'auto') = 'off' THEN 'disabled' WHEN d->>'tlsMode' = 'custom' OR d->>'tls' = 'issued' THEN 'issued' ELSE 'pending' END) - - CASE WHEN d->>'status' IN ('pending_dns', 'verifying') THEN '' ELSE 'error' END) + - CASE WHEN d->>'status' IN ('pending_dns', 'verifying') THEN '' ELSE 'error' END END) FROM jsonb_array_elements(spec->'domains') d), '[]')) WHERE id = $1 AND ($2::bigint IS NULL OR routes_revision = $2)", ) @@ -488,8 +490,11 @@ mod lifecycle_tests { "still waiting for DNS" ); - // old.example.com removed: gone live too. - let only_new = service(&live, "web", json!([domain("dom_new", &new_host)])); + // old.example.com removed: gone live too. Sent as the dashboard + // has the service, with what the API shows of it. + let mut only_new = service(&live, "web", json!([domain("dom_new", &new_host)])); + only_new["behindCdn"] = json!(null); + only_new["wafState"] = json!({ "state": "ready", "message": "" }); crate::ops::run_json( &s, &user, @@ -502,6 +507,7 @@ mod lifecycle_tests { (q.len(), q[0]["kind"].as_str(), hosts(&q[0])), (1, Some("sync_routes"), vec![new_host.clone()]) ); + assert!(!row(&live).await.1, "no pending change"); // A rollback to the first deployment (deployed with old.example.com) // keeps today's domains, and so does the version it falls back to. @@ -546,5 +552,43 @@ mod lifecycle_tests { let mut tx = db.begin().await.unwrap(); finished(&mut tx, &team, &json!({ "kind": "sync_routes", "service": { "serviceId": live }, "routesRevision": 2 }), true, None).await.unwrap(); tx.commit().await.unwrap(); + + // Its redirect to HTTPS turned off: live, no redeploy. + let mut plain = service( + &live, + "web", + json!([domain("dom_new", &new_host), domain("dom_old", &old_host)]), + ); + plain["domains"][0]["redirectHttps"] = json!(false); + plain["behindCdn"] = json!(null); + crate::ops::run_json(&s, &user, json!({ "op": "saveService", "service": plain })) + .await + .unwrap(); + let q = queued().await; + assert_eq!( + ( + q.len(), + q[0]["kind"].as_str(), + &q[0]["domains"][0]["redirectHttps"] + ), + (1, Some("sync_routes"), &json!(false)) + ); + assert!(!row(&live).await.1, "no pending change"); + + // Every domain removed, so its port is no longer "http": its routes + // go now, still no redeploy. + crate::ops::run_json( + &s, + &user, + json!({ "op": "saveService", "service": service(&live, "web", json!([])) }), + ) + .await + .unwrap(); + let q = queued().await; + assert_eq!( + (q.len(), q[0]["kind"].as_str(), hosts(&q[0]).len()), + (1, Some("sync_routes"), 0) + ); + assert!(!row(&live).await.1, "no pending change"); } } diff --git a/crates/pyo-api/src/sandbox/api.rs b/crates/pyo-api/src/sandbox/api.rs index 53d50d34..1ad56fca 100644 --- a/crates/pyo-api/src/sandbox/api.rs +++ b/crates/pyo-api/src/sandbox/api.rs @@ -73,11 +73,6 @@ pub struct TeamQuery { team: String, } -async fn team_read(s: &AppState, user: &crate::auth::User, team: &str) -> ApiResult<()> { - let mut c = s.db.acquire().await?; - super::require(&mut c, user, team, Need::Read).await -} - /// Sandboxes /// /// A team's sandboxes: their template, size, state, server and lifetime. @@ -94,18 +89,21 @@ pub(crate) async fn list( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - team_read(&s, &user, &q.team).await?; let live = match q.state.as_deref() { None | Some("live") => true, Some("all") => false, Some(_) => return Err(ApiError::bad_request("state is \"live\" or \"all\".")), }; let teams = [q.team.clone()]; - let mut c = s.db.acquire().await?; - let limits = super::limits::load(&mut c, &q.team).await?; - let in_use = super::limits::in_use(&mut c, &q.team).await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; + super::require(&mut tx, &user, &q.team, Need::Read).await?; + let limits = super::limits::load(&mut tx, &q.team).await?; + let in_use = super::limits::in_use(&mut tx, &q.team).await?; + let sandboxes = + super::sandbox_views_matching(&mut *tx, &teams, None, live, q.q.as_deref()).await?; + tx.commit().await?; Ok(Json(json!({ - "sandboxes": super::sandbox_views_matching(&s.db, &teams, None, live, q.q.as_deref()).await?, + "sandboxes": sandboxes, "limits": limits, "inUse": in_use, }))) @@ -379,11 +377,11 @@ pub(crate) async fn list_servers( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - team_read(&s, &user, &q.team).await?; - let teams = [q.team]; - Ok(Json( - json!({ "servers": super::server_views(&s.db, &teams, None).await? }), - )) + let mut tx = crate::rls::begin(&s.db, &user).await?; + super::require(&mut tx, &user, &q.team, Need::Read).await?; + let servers = super::server_views(&mut tx, &[q.team], None).await?; + tx.commit().await?; + Ok(Json(json!({ "servers": servers }))) } /// Add a sandbox server @@ -541,10 +539,13 @@ pub(crate) async fn list_templates( SessionUser(user): SessionUser, Query(q): Query, ) -> ApiResult> { - team_read(&s, &user, &q.team).await?; - let teams = [q.team]; + let mut tx = crate::rls::begin(&s.db, &user).await?; + super::require(&mut tx, &user, &q.team, Need::Read).await?; + let rows = super::stored_template_rows(&mut *tx, &[q.team], None).await?; + tx.commit().await?; + let rows = super::with_builtins(&s.db, None, rows).await; Ok(Json( - json!({ "templates": super::template_views_live(&s, &teams, None).await? }), + json!({ "templates": super::live_views(&s, rows).await }), )) } diff --git a/crates/pyo-api/src/sandbox/daemon.rs b/crates/pyo-api/src/sandbox/daemon.rs index 18e3c64d..3d0cbd98 100644 --- a/crates/pyo-api/src/sandbox/daemon.rs +++ b/crates/pyo-api/src/sandbox/daemon.rs @@ -1,5 +1,8 @@ //! Pyo's calls to a sandbox server's daemon, over the tailnet //! (`http://:7070`), each with a short-lived token Pyo signs. +//! A server that joined through a cluster is called through that cluster's +//! agent (pyo-proto's tailscale.rs `SandboxCall`): Pyo itself may be on no +//! tailnet (Pyo Cloud). use std::time::Duration; @@ -38,6 +41,24 @@ pub fn base_url(address: &str) -> String { pub struct Daemon { pub base: String, + /// The server's tailnet address, as Pyo keeps it. + address: String, +} + +/// Pyo's state, for calls through a cluster's agent (set at start). +static STATE: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Calls to sandbox servers that joined through a cluster go through that +/// cluster's agent from now on. +pub fn init(s: crate::AppState) { + let _ = STATE.set(s); +} + +/// What goes in a request. +enum Body { + None, + Json(Vec), + Bytes(Vec), } fn unreachable(e: reqwest::Error) -> DaemonError { @@ -52,24 +73,22 @@ fn unreachable(e: reqwest::Error) -> DaemonError { } /// A daemon's answer: its result, or its error. -async fn answer(r: reqwest::Response) -> Result { - let status = r.status(); - let body = r.bytes().await.map_err(unreachable)?; - if status.is_success() { - return serde_json::from_slice(&body).map_err(|e| { +fn answer(status: u16, body: &[u8]) -> Result { + if (200..300).contains(&status) { + return serde_json::from_slice(body).map_err(|e| { DaemonError::new( ErrorCode::Internal, format!("The sandbox server's answer didn't parse: {e}"), ) }); } - match serde_json::from_slice::(&body) { + match serde_json::from_slice::(body) { Ok(DaemonResult::Error { error }) => Err(error), _ => Err(DaemonError::new( ErrorCode::Internal, format!( "The sandbox server answered {status}: {}", - String::from_utf8_lossy(&body) + String::from_utf8_lossy(body) .chars() .take(200) .collect::() @@ -78,11 +97,130 @@ async fn answer(r: reqwest::Response) -> Result< } } +/// `path` with its query, encoded. +fn with_query(path: &str, query: &[(&str, &str)]) -> String { + if query.is_empty() { + return path.to_owned(); + } + let q = reqwest::Url::parse_with_params("http://q/", query) + .ok() + .and_then(|u| u.query().map(str::to_owned)) + .unwrap_or_default(); + format!("{path}?{q}") +} + impl Daemon { pub fn new(address: &str) -> Daemon { Daemon { base: base_url(address), + address: address.to_owned(), + } + } + + /// The cluster whose agent reaches this server, when it joined + /// through one. + async fn via(&self) -> Option<(&'static crate::AppState, String)> { + let s = STATE.get()?; + let c: Option = sqlx::query_scalar( + "SELECT via_cluster FROM pyo.sandbox_servers WHERE address = $1 AND via_cluster IS NOT NULL LIMIT 1", + ) + .bind(&self.address) + .fetch_optional(&s.db) + .await + .ok() + .flatten(); + c.map(|c| (s, c)) + } + + /// One call to the daemon: its status and body. Through the cluster's + /// agent when the server joined through one, else straight to it. + async fn call( + &self, + method: reqwest::Method, + path: &str, + token: &str, + body: Body, + timeout: Duration, + ) -> Result<(u16, Vec), DaemonError> { + if let Some((s, cluster)) = self.via().await { + return self.call_via(s, &cluster, method, path, token, body, timeout).await; } + let mut req = client() + .request(method, format!("{}{path}", self.base)) + .bearer_auth(token) + .timeout(timeout); + req = match body { + Body::None => req, + Body::Json(b) => req + .header(reqwest::header::CONTENT_TYPE, "application/json") + .body(b), + Body::Bytes(b) => req.body(b), + }; + let r = req.send().await.map_err(unreachable)?; + let status = r.status().as_u16(); + let body = r.bytes().await.map_err(unreachable)?; + Ok((status, body.to_vec())) + } + + #[allow(clippy::too_many_arguments)] + async fn call_via( + &self, + s: &crate::AppState, + cluster: &str, + method: reqwest::Method, + path: &str, + token: &str, + body: Body, + timeout: Duration, + ) -> Result<(u16, Vec), DaemonError> { + use base64::Engine as _; + let b64 = base64::engine::general_purpose::STANDARD; + let (body, raw) = match body { + Body::None => (None, false), + Body::Json(b) => (Some(String::from_utf8_lossy(&b).into_owned()), false), + Body::Bytes(b) => (Some(b64.encode(b)), true), + }; + // Files come back as bytes. + let raw = raw || (method == reqwest::Method::GET && path.contains("/files")); + let call = pyo_proto::tailscale::SandboxCall { + address: self.address.clone(), + method: method.as_str().to_owned(), + path: path.to_owned(), + token: token.to_owned(), + body, + raw, + content_type: None, + timeout_secs: timeout.as_secs().max(1), + }; + let (id, r) = crate::tailscale::ask( + s, + cluster, + pyo_proto::Command::SandboxCall(Box::new(call)), + timeout + Duration::from_secs(15), + ) + .await + .map_err(|e| { + DaemonError::new( + ErrorCode::Runtime, + format!("Pyo couldn't reach the sandbox server through its cluster: {}", e.message), + ) + })?; + crate::tailscale::forget_command(&s.db, &id).await; + let a: pyo_proto::tailscale::SandboxAnswer = r + .data + .and_then(|d| serde_json::from_value(d).ok()) + .ok_or_else(|| DaemonError::new(ErrorCode::Internal, "The cluster's agent gave no answer."))?; + if a.status == 0 { + return Err(DaemonError::new(ErrorCode::Runtime, a.body)); + } + let bytes = if raw && (200..300).contains(&a.status) { + b64.decode(&a.body).map_err(|_| { + DaemonError::new(ErrorCode::Internal, "The sandbox server's answer didn't parse.") + })? + } else { + a.body.into_bytes() + }; + Ok((a.status, bytes)) } pub async fn command( @@ -90,15 +228,12 @@ impl Daemon { token: &str, cmd: &DaemonCommand, ) -> Result { - let r = client() - .post(format!("{}/v1/commands", self.base)) - .bearer_auth(token) - .timeout(TIMEOUT) - .json(cmd) - .send() - .await - .map_err(unreachable)?; - match answer(r).await? { + let body = serde_json::to_vec(cmd) + .map_err(|e| DaemonError::new(ErrorCode::Internal, e.to_string()))?; + let (status, b) = self + .call(reqwest::Method::POST, "/v1/commands", token, Body::Json(body), TIMEOUT) + .await?; + match answer(status, &b)? { DaemonResult::Error { error } => Err(error), r => Ok(r), } @@ -120,14 +255,10 @@ impl Daemon { } pub async fn report(&self, token: &str) -> Result { - let r = client() - .get(format!("{}/v1/report", self.base)) - .bearer_auth(token) - .timeout(Duration::from_secs(10)) - .send() - .await - .map_err(unreachable)?; - answer(r).await + let (status, b) = self + .call(reqwest::Method::GET, "/v1/report", token, Body::None, Duration::from_secs(10)) + .await?; + answer(status, &b) } pub async fn exec( @@ -138,15 +269,18 @@ impl Daemon { ) -> Result { let wait = Duration::from_millis(req.timeout_ms.unwrap_or(60_000)) + Duration::from_secs(10); - let r = client() - .post(format!("{}/v1/sandboxes/{id}/exec", self.base)) - .bearer_auth(token) - .timeout(wait) - .json(req) - .send() - .await - .map_err(unreachable)?; - answer(r).await + let body = serde_json::to_vec(req) + .map_err(|e| DaemonError::new(ErrorCode::Internal, e.to_string()))?; + let (status, b) = self + .call( + reqwest::Method::POST, + &format!("/v1/sandboxes/{id}/exec"), + token, + Body::Json(body), + wait, + ) + .await?; + answer(status, &b) } pub async fn read_file( @@ -155,18 +289,19 @@ impl Daemon { id: &str, path: &str, ) -> Result, DaemonError> { - let r = client() - .get(format!("{}/v1/sandboxes/{id}/files", self.base)) - .query(&[("path", path)]) - .bearer_auth(token) - .timeout(TIMEOUT) - .send() - .await - .map_err(unreachable)?; - if r.status().is_success() { - return Ok(r.bytes().await.map_err(unreachable)?.to_vec()); + let (status, b) = self + .call( + reqwest::Method::GET, + &with_query(&format!("/v1/sandboxes/{id}/files"), &[("path", path)]), + token, + Body::None, + TIMEOUT, + ) + .await?; + if (200..300).contains(&status) { + return Ok(b); } - answer::(r).await.map(|_| vec![]) + answer::(status, &b).map(|_| vec![]) } pub async fn write_file( @@ -176,16 +311,16 @@ impl Daemon { path: &str, data: Vec, ) -> Result { - let r = client() - .put(format!("{}/v1/sandboxes/{id}/files", self.base)) - .query(&[("path", path)]) - .bearer_auth(token) - .timeout(TIMEOUT) - .body(data) - .send() - .await - .map_err(unreachable)?; - let v: serde_json::Value = answer(r).await?; + let (status, b) = self + .call( + reqwest::Method::PUT, + &with_query(&format!("/v1/sandboxes/{id}/files"), &[("path", path)]), + token, + Body::Bytes(data), + TIMEOUT, + ) + .await?; + let v: serde_json::Value = answer(status, &b)?; Ok(v["bytes"].as_u64().unwrap_or(0)) } } @@ -194,6 +329,15 @@ impl Daemon { mod tests { use super::*; + #[test] + fn queries_are_encoded() { + assert_eq!( + with_query("/v1/sandboxes/s1/files", &[("path", "/a b&c")]), + "/v1/sandboxes/s1/files?path=%2Fa+b%26c" + ); + assert_eq!(with_query("/v1/report", &[]), "/v1/report"); + } + #[test] fn urls() { assert_eq!(base_url("100.64.0.7"), "http://100.64.0.7:7070"); diff --git a/crates/pyo-api/src/sandbox/e2e.rs b/crates/pyo-api/src/sandbox/e2e.rs index 1497aebd..56a9eabf 100644 --- a/crates/pyo-api/src/sandbox/e2e.rs +++ b/crates/pyo-api/src/sandbox/e2e.rs @@ -427,9 +427,13 @@ async fn the_control_plane_drives_a_real_daemon() { // The runner reads the report: ready. super::runner::round(&s).await.unwrap(); - let srv = &super::server_views(&db, std::slice::from_ref(&team), Some(&server)) - .await - .unwrap()[0]; + let srv = &super::server_views( + &mut db.acquire().await.unwrap(), + std::slice::from_ref(&team), + Some(&server), + ) + .await + .unwrap()[0]; assert_eq!(srv["state"], "ready", "{srv}"); assert_eq!(srv["capability"]["runtime"], "firecracker"); @@ -588,9 +592,13 @@ async fn the_control_plane_drives_a_real_daemon() { let t0 = std::time::Instant::now(); loop { super::runner::round(&s).await.unwrap(); - let srv = &super::server_views(&db, std::slice::from_ref(&team), Some(&server)) - .await - .unwrap()[0]; + let srv = &super::server_views( + &mut db.acquire().await.unwrap(), + std::slice::from_ref(&team), + Some(&server), + ) + .await + .unwrap()[0]; let names: Vec<&str> = srv["templates"] .as_array() .unwrap() @@ -649,9 +657,13 @@ async fn the_control_plane_drives_a_real_daemon() { for _ in 0..3 { super::runner::round(&s).await.unwrap(); } - let srv = &super::server_views(&db, std::slice::from_ref(&team), Some(&server)) - .await - .unwrap()[0]; + let srv = &super::server_views( + &mut db.acquire().await.unwrap(), + std::slice::from_ref(&team), + Some(&server), + ) + .await + .unwrap()[0]; assert!( srv["templates"] .as_array() @@ -804,9 +816,13 @@ async fn the_control_plane_drives_a_real_daemon() { /// The templates a server reports ready, by the names it keeps them under. async fn ready_on(db: &PgPool, team: &str, server: &str) -> Vec { - let srv = &super::server_views(db, &[team.to_owned()], Some(server)) - .await - .unwrap()[0]; + let srv = &super::server_views( + &mut db.acquire().await.unwrap(), + &[team.to_owned()], + Some(server), + ) + .await + .unwrap()[0]; srv["templates"] .as_array() .unwrap() @@ -833,7 +849,7 @@ async fn wait_for(s: &crate::AppState, team: &str, server: &str, name: &str, gon } } -pub(super) fn test_state(db: PgPool) -> crate::AppState { +pub(crate) fn test_state(db: PgPool) -> crate::AppState { let config = crate::Config { agent_api_url: String::new(), agent_image: String::new(), diff --git a/crates/pyo-api/src/sandbox/edgecert.rs b/crates/pyo-api/src/sandbox/edgecert.rs index 97b692b4..6682d8e2 100644 --- a/crates/pyo-api/src/sandbox/edgecert.rs +++ b/crates/pyo-api/src/sandbox/edgecert.rs @@ -109,7 +109,11 @@ impl HttpClient for Reqwest { /// Pyo's ACME account at `directory`: made once and kept sealed in the /// settings, one per directory. -async fn account(s: &AppState, client: reqwest::Client, directory: &str) -> ApiResult { +pub(crate) async fn account( + s: &AppState, + client: reqwest::Client, + directory: &str, +) -> ApiResult { let saved: Option = sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'acme_account'") .fetch_optional(&s.db) @@ -170,7 +174,7 @@ pub(crate) trait Propagation { /// Asks Cloudflare's resolver over HTTPS until the record shows, for two /// minutes at most. The zone is at Cloudflare, so that's quick. -struct DnsOverHttps(reqwest::Client); +pub(crate) struct DnsOverHttps(pub(crate) reqwest::Client); impl Propagation for DnsOverHttps { async fn wait(&self, name: &str, value: &str) { @@ -342,7 +346,11 @@ impl Server { /// wildcard record. `team_ids` are the viewer's teams: an installation's /// server is offered the first of their connections that covers its /// domain. -pub async fn attach(db: &PgPool, team_ids: &[String], servers: &mut [Value]) -> sqlx::Result<()> { +pub async fn attach( + db: &mut sqlx::PgConnection, + team_ids: &[String], + servers: &mut [Value], +) -> sqlx::Result<()> { let ids: Vec = servers .iter() .filter(|v| v["edgeDomain"].is_string()) @@ -360,7 +368,7 @@ pub async fn attach(db: &PgPool, team_ids: &[String], servers: &mut [Value]) -> ) .bind(&ids) .bind(STALE_SECS) - .fetch_all(db) + .fetch_all(&mut *db) .await?; let accounts: Vec<(String, Value)> = sqlx::query_as( "SELECT team_id, zones FROM pyo.cloudflare_accounts WHERE team_id = ANY($1) @@ -369,7 +377,7 @@ pub async fn attach(db: &PgPool, team_ids: &[String], servers: &mut [Value]) -> ) .bind(team_ids) .bind(&ids) - .fetch_all(db) + .fetch_all(&mut *db) .await?; let zones = |team: &str| -> Vec { accounts @@ -458,7 +466,7 @@ async fn allowed(s: &AppState, user: &User, srv: &Server, req: &EdgeRequest) -> t.clone() } None => { - super::require_install_admin(user)?; + super::require_install_add(user)?; let t = req.team_id.clone().ok_or_else(|| { ApiError::bad_request("Pick the team whose Cloudflare connection to use.") })?; @@ -682,7 +690,20 @@ pub(crate) fn check( /// Checks and keeps an issued certificate, its key sealed. async fn save(s: &AppState, id: &str, domain: &str, issued: &Issued) -> Result<(), String> { let p = check(issued, domain, pyo_proto::now_ms() / 1000)?; - let sealed = s.sealer.seal(&p.key_pem).map_err(|e| e.to_string())?; + // A team's own server's key with the team's data key; the + // installation's servers' with the installation's key. + let team: Option = + sqlx::query_scalar("SELECT team_id FROM pyo.sandbox_servers WHERE id = $1") + .bind(id) + .fetch_optional(&s.db) + .await + .map_err(|e| e.to_string())? + .flatten(); + let sealed = match &team { + Some(t) => crate::vault::get().seal_credential(t, &p.key_pem).await, + None => s.sealer.seal(&p.key_pem), + } + .map_err(|e| e.to_string())?; sqlx::query( "UPDATE pyo.sandbox_edges SET state = 'ready', domain = $2, cert_pem = $3, key_sealed = $4, fingerprint = $5, not_before = to_timestamp($6), not_after = to_timestamp($7), @@ -715,9 +736,9 @@ async fn deliver(s: &AppState, id: &str) -> Result<(), String> { let Some((Some(address), Some(cert), Some(sealed))) = row else { return Err("The server hasn't joined, or there's no certificate.".into()); }; - let key = s - .sealer - .open(&sealed) + let key = crate::vault::get() + .open_credential(&s.sealer, &sealed) + .await .map_err(|_| "Pyo can't open the certificate's key.".to_owned())?; let signing = keys::signing_key(&s.db, &s.sealer) .await diff --git a/crates/pyo-api/src/sandbox/join.rs b/crates/pyo-api/src/sandbox/join.rs index b8f2e200..00116ba7 100644 --- a/crates/pyo-api/src/sandbox/join.rs +++ b/crates/pyo-api/src/sandbox/join.rs @@ -58,12 +58,14 @@ pub const WRONG_CODE_SERVER: Limit = Limit { scope: "sandbox-join:server", max: 10, window_secs: 15 * 60, + backoff_cap_secs: 0, }; /// Wrong codes from anywhere. pub const WRONG_CODE_ALL: Limit = Limit { scope: "sandbox-join:all", max: 60, window_secs: 15 * 60, + backoff_cap_secs: 0, }; /// A new code: 32 random bytes as hex. diff --git a/crates/pyo-api/src/sandbox/mod.rs b/crates/pyo-api/src/sandbox/mod.rs index dd23f87c..f03e1474 100644 --- a/crates/pyo-api/src/sandbox/mod.rs +++ b/crates/pyo-api/src/sandbox/mod.rs @@ -20,14 +20,14 @@ //! //! Sandboxes belong to a team, with an optional project as a label. Sandbox //! servers and templates belong to a team, or to the installation (no team), -//! which every team may use. Nothing here runs or shows until the first -//! sandbox server exists ([`available`]). +//! which every team may use on a self-hosted Pyo ([`shared`]). Nothing here +//! runs or shows until the first sandbox server exists ([`available`]). pub mod api; pub mod base; pub mod daemon; #[cfg(test)] -mod e2e; +pub(crate) mod e2e; pub mod edgecert; pub mod firstuse; pub mod images; @@ -82,13 +82,23 @@ pub fn format_ttl(secs: u64) -> String { out } +/// Whether the installation's own sandbox servers and templates (no team) +/// are there for every team: on a self-hosted Pyo only. A hosted Pyo serves +/// teams that don't trust each other, so there each team has only its own, +/// and none of the installation's can be added. Pyo's built-in templates +/// ([`base`]) are the same image everywhere and stay for every team. +pub fn shared() -> bool { + !crate::hosted() +} + /// Whether any of these teams can use a sandbox server: its own, or the /// installation's. Until then the sandbox tools stay hidden. pub async fn available(db: &PgPool, team_ids: &[String]) -> sqlx::Result { sqlx::query_scalar( - "SELECT EXISTS (SELECT 1 FROM pyo.sandbox_servers WHERE team_id IS NULL OR team_id = ANY($1))", + "SELECT EXISTS (SELECT 1 FROM pyo.sandbox_servers WHERE (team_id IS NULL AND $2) OR team_id = ANY($1))", ) .bind(team_ids) + .bind(shared()) .fetch_one(db) .await } @@ -187,6 +197,21 @@ fn require_install_admin(user: &User) -> ApiResult<()> { } } +/// Adding to the installation's own servers and templates, or changing +/// them: never on a hosted Pyo ([`shared`]). Removing them stays allowed. +fn require_install_add(user: &User) -> ApiResult<()> { + install_add(user, shared()) +} + +fn install_add(user: &User, shared: bool) -> ApiResult<()> { + if !shared { + return Err(ApiError::forbidden( + "Sandbox servers and templates belong to a team here. Pick the team.", + )); + } + require_install_admin(user) +} + /// A daemon's error as the API's. A token the server refuses is Pyo's /// problem, not the caller's. pub fn daemon_error(e: DaemonError) -> ApiError { @@ -268,8 +293,8 @@ pub async fn end( // ── Views ────────────────────────────────────────────────────────────────── /// Sandboxes as the API shows them. Env values are never kept, only names. -pub async fn sandbox_views( - db: &PgPool, +pub async fn sandbox_views<'e, E: sqlx::PgExecutor<'e>>( + db: E, team_ids: &[String], id: Option<&str>, live_only: bool, @@ -278,8 +303,8 @@ pub async fn sandbox_views( } /// [`sandbox_views`], only those whose name or id has `q` in it. -pub async fn sandbox_views_matching( - db: &PgPool, +pub async fn sandbox_views_matching<'e, E: sqlx::PgExecutor<'e>>( + db: E, team_ids: &[String], id: Option<&str>, live_only: bool, @@ -367,7 +392,7 @@ pub async fn sandbox_views_matching( /// Sandbox servers as the API shows them, with the one line the dashboard /// shows next to the runtime badge. pub async fn server_views( - db: &PgPool, + db: &mut sqlx::PgConnection, team_ids: &[String], id: Option<&str>, ) -> sqlx::Result> { @@ -387,12 +412,13 @@ pub async fn server_views( FROM pyo.cloud_servers c WHERE c.sandbox_server_id = s.id AND c.state <> 'deleted' ORDER BY c.created_at DESC LIMIT 1)) FROM pyo.sandbox_servers s - WHERE (s.team_id IS NULL OR s.team_id = ANY($1)) AND ($2::text IS NULL OR s.id = $2) + WHERE ((s.team_id IS NULL AND $3) OR s.team_id = ANY($1)) AND ($2::text IS NULL OR s.id = $2) ORDER BY s.team_id NULLS FIRST, s.name", ) .bind(team_ids) .bind(id) - .fetch_all(db) + .bind(shared()) + .fetch_all(&mut *db) .await?; for r in &mut rows { let cap = serde_json::from_value::(r["capability"].clone()).ok(); @@ -401,7 +427,7 @@ pub async fn server_views( // reports (or when it can run neither). r["runtime"] = json!(cap.and_then(|c| runtime_name(c.runtime))); } - edgecert::attach(db, team_ids, &mut rows).await?; + edgecert::attach(&mut *db, team_ids, &mut rows).await?; Ok(rows) } @@ -424,10 +450,16 @@ pub async fn template_views_live( team_ids: &[String], id: Option<&str>, ) -> sqlx::Result> { - let mut rows = template_rows(&s.db, team_ids, id).await?; + let rows = template_rows(&s.db, team_ids, id).await?; + Ok(live_views(s, rows).await) +} + +/// Template rows ([`template_rows`]) with how far each server got, asked +/// of the servers still making one. +pub(crate) async fn live_views(s: &AppState, mut rows: Vec) -> Vec { live::overlay(s, &mut rows).await; finish_template_views(&mut rows); - Ok(rows) + rows } /// The template views as Pyo has them, each server's with the `key` the @@ -437,7 +469,17 @@ async fn template_rows( team_ids: &[String], id: Option<&str>, ) -> sqlx::Result> { - let mut rows: Vec = sqlx::query_scalar( + let rows = stored_template_rows(db, team_ids, id).await?; + Ok(with_builtins(db, id, rows).await) +} + +/// The templates' rows as stored, without Pyo's own ones not added yet. +pub(crate) async fn stored_template_rows<'e, E: sqlx::PgExecutor<'e>>( + db: E, + team_ids: &[String], + id: Option<&str>, +) -> sqlx::Result> { + sqlx::query_scalar( "SELECT jsonb_build_object( 'id', t.id, 'teamId', t.team_id, 'name', t.name, 'source', t.source, 'state', t.state, 'builtin', t.builtin, 'revision', t.revision, @@ -459,20 +501,29 @@ async fn template_rows( OR (t.revision IS NOT NULL AND starts_with(x->>'name', t.id || '.')) ORDER BY x->>'name' = t.id || coalesce('.' || t.revision, '') DESC LIMIT 1) m ON true WHERE (s.team_id IS NULL OR s.team_id = t.team_id OR t.team_id IS NULL) - AND (s.team_id IS NULL OR s.team_id = ANY($1)) + AND ((s.team_id IS NULL AND $4) OR s.team_id = ANY($1)) AND (m.e IS NOT NULL OR s.state NOT IN ('joining', 'refused')) -- One made on first use: the servers that have it. AND (m.e IS NOT NULL OR t.id <> ALL($3)))) FROM pyo.sandbox_templates t - WHERE (t.team_id IS NULL OR t.team_id = ANY($1)) AND ($2::text IS NULL OR t.id = $2) + WHERE ((t.team_id IS NULL AND (t.builtin OR $4)) OR t.team_id = ANY($1)) AND ($2::text IS NULL OR t.id = $2) ORDER BY t.team_id NULLS FIRST, t.name", ) .bind(team_ids) .bind(id) .bind(base::ALL.map(|b| b.id).as_slice()) + .bind(shared()) .fetch_all(db) - .await?; - // Pyo's own are listed before they're added, as they will be. + .await +} + +/// Pyo's own templates are listed before they're added, as they will be, +/// and first, in their order. +pub(crate) async fn with_builtins( + db: &PgPool, + id: Option<&str>, + mut rows: Vec, +) -> Vec { for b in base::ALL { if id.is_none_or(|i| i == b.id) && !rows.iter().any(|r| r["id"] == b.id) { rows.push(base::listed(db, b).await); @@ -486,7 +537,7 @@ async fn template_rows( .unwrap_or(base::ALL.len()) }; rows.sort_by_key(place); - Ok(rows) + rows } /// Build errors in plain words, and without the servers' `key`. @@ -613,14 +664,24 @@ async fn template_for( tx: &mut PgConnection, team_id: &str, name: &str, +) -> ApiResult { + template_on(tx, team_id, name, shared()).await +} + +async fn template_on( + tx: &mut PgConnection, + team_id: &str, + name: &str, + shared: bool, ) -> ApiResult { let row: Option<(String, String, String, Option)> = sqlx::query_as( "SELECT id, name, state, revision FROM pyo.sandbox_templates - WHERE (team_id = $1 OR team_id IS NULL) AND (name = $2 OR id = $2) + WHERE (team_id = $1 OR (team_id IS NULL AND (builtin OR $3))) AND (name = $2 OR id = $2) ORDER BY team_id NULLS LAST LIMIT 1", ) .bind(team_id) .bind(name) + .bind(shared) .fetch_optional(tx) .await?; let Some((id, name, state, revision)) = row else { @@ -646,6 +707,14 @@ async fn template_for( pub async fn candidates( tx: &mut PgConnection, team_id: &str, +) -> ApiResult> { + candidates_on(tx, team_id, shared()).await +} + +async fn candidates_on( + tx: &mut PgConnection, + team_id: &str, + shared: bool, ) -> ApiResult> { #[derive(sqlx::FromRow)] struct Row { @@ -668,9 +737,10 @@ pub async fn candidates( WHERE x.server_id = s.id AND x.state NOT IN ('stopped', 'failed', 'paused') AND (x.state IN ('creating', 'resuming') OR s.last_report_at IS NULL OR x.created_at > s.last_report_at)), 0)::bigint AS pending_mib FROM pyo.sandbox_servers s - WHERE s.team_id IS NULL OR s.team_id = $1", + WHERE (s.team_id IS NULL AND $2) OR s.team_id = $1", ) .bind(team_id) + .bind(shared) .fetch_all(tx) .await?; Ok(rows @@ -949,16 +1019,18 @@ pub struct Found { } pub async fn find(s: &AppState, user: &User, id: &str, need: Need) -> ApiResult { + // Within the user's teams only (rls.rs): another team's sandbox isn't there. + let mut tx = crate::rls::begin(&s.db, user).await?; let row: Option<(String, Option, Option, String)> = sqlx::query_as( "SELECT x.team_id, x.server_id, sv.address, x.state FROM pyo.sandboxes x LEFT JOIN pyo.sandbox_servers sv ON sv.id = x.server_id WHERE x.id = $1", ) .bind(id) - .fetch_optional(&s.db) + .fetch_optional(&mut *tx) .await?; let (team_id, server_id, address, state) = row.ok_or_else(|| ApiError::not_found("Sandbox"))?; - let mut c = s.db.acquire().await?; - require(&mut c, user, &team_id, need).await?; + require(&mut tx, user, &team_id, need).await?; + tx.commit().await?; Ok(Found { id: id.to_owned(), team_id, @@ -1009,7 +1081,7 @@ impl Found { /// may use it and it lives. Null otherwise, and `connectionNote` says why. pub async fn get(s: &AppState, user: &User, id: &str) -> ApiResult { let f = find(s, user, id, Need::Read).await?; - let mut v = view(s, &f).await?; + let mut v = view(s, user, &f).await?; let mut c = s.db.acquire().await?; let may_use = require(&mut c, user, &f.team_id, Need::Use).await; drop(c); @@ -1029,11 +1101,12 @@ pub async fn get(s: &AppState, user: &User, id: &str) -> ApiResult { Ok(v) } -async fn view(s: &AppState, f: &Found) -> ApiResult { +async fn view(s: &AppState, user: &User, f: &Found) -> ApiResult { let teams = [f.team_id.clone()]; - sandbox_views(&s.db, &teams, Some(&f.id), false) - .await? - .into_iter() + let mut tx = crate::rls::begin(&s.db, user).await?; + let v = sandbox_views(&mut *tx, &teams, Some(&f.id), false).await?; + tx.commit().await?; + v.into_iter() .next() .ok_or_else(|| ApiError::not_found("Sandbox")) } @@ -1044,13 +1117,13 @@ async fn view(s: &AppState, f: &Found) -> ApiResult { pub async fn delete(s: &AppState, user: &User, id: &str) -> ApiResult { let f = find(s, user, id, Need::Use).await?; if f.is_final() { - return view(s, &f).await; + return view(s, user, &f).await; } let mut c = s.db.acquire().await?; // Its server was removed: nothing is left to end. if f.server_id.is_none() || f.address.is_none() { end(&mut c, id, "stopped", None).await?; - return view(s, &f).await; + return view(s, user, &f).await; } let (d, token, _) = f.daemon(s).await?; sqlx::query("UPDATE pyo.sandboxes SET state = 'stopping' WHERE id = $1 AND state NOT IN ('stopped', 'failed')") @@ -1067,7 +1140,7 @@ pub async fn delete(s: &AppState, user: &User, id: &str) -> ApiResult { tracing::warn!(%id, error = %e, "sandbox delete: the server didn't answer, trying again later") } } - view(s, &f).await + view(s, user, &f).await } /// Gives a sandbox another name. Its id stays, so nothing that uses it @@ -1080,7 +1153,7 @@ pub async fn rename(s: &AppState, user: &User, id: &str, name: &str) -> ApiResul .bind(&name) .execute(&s.db) .await?; - view(s, &f).await + view(s, user, &f).await } pub async fn pause(s: &AppState, user: &User, id: &str) -> ApiResult { @@ -1121,7 +1194,7 @@ async fn lifecycle( .map_err(daemon_error)?; let mut c = s.db.acquire().await?; save_status(&mut c, &st).await?; - view(s, &f).await + view(s, user, &f).await } /// Opens a sandbox port on its server's edge proxy and returns its URL. A @@ -1259,9 +1332,9 @@ pub async fn add_server(s: &AppState, user: &User, req: AddServer) -> ApiResult< let mut tx = s.db.begin().await?; match &req.team_id { Some(t) => require(&mut tx, user, t, Need::Manage).await?, - None => require_install_admin(user)?, + None => require_install_add(user)?, } - crate::cloud::needs_tailscale(&s.db).await?; + let via = crate::tailscale::team_key_cluster(&s.db, req.team_id.as_deref()).await?; let door = crate::deploy::registry_push(); let (false, Some(_)) = (door.is_empty(), crate::web::tailnet_api_url()) else { return Err(ApiError::conflict( @@ -1310,8 +1383,15 @@ pub async fn add_server(s: &AppState, user: &User, req: AddServer) -> ApiResult< }; let code = join::new_code(); join::keep(&mut tx, &id, &code).await?; + // Pyo reaches it through that cluster's agent. + sqlx::query("UPDATE pyo.sandbox_servers SET via_cluster = $2 WHERE id = $1") + .bind(&id) + .bind(&via) + .execute(&mut *tx) + .await?; let ts_key = crate::tailscale::join_key( s, + &via, &format!("Pyo: sandbox server {}", req.name), "a sandbox server", ) @@ -1346,7 +1426,7 @@ pub async fn add_server(s: &AppState, user: &User, req: AddServer) -> ApiResult< } .render(); let teams: Vec = req.team_id.iter().cloned().collect(); - let server = server_views(&s.db, &teams, Some(&id)) + let server = server_views(&mut *s.db.acquire().await?, &teams, Some(&id)) .await? .into_iter() .next(); @@ -1517,7 +1597,7 @@ pub async fn add_cloud_server(s: &AppState, user: &User, req: AddCloudServer) -> }; let mut tx = s.db.begin().await?; require(&mut tx, user, &req.team_id, Need::Manage).await?; - crate::cloud::needs_tailscale(&s.db).await?; + let via = crate::tailscale::team_key_cluster(&s.db, Some(&req.team_id)).await?; let door = crate::deploy::registry_push(); let api = crate::web::tailnet_api_url(); let (false, Some(api)) = (door.is_empty(), api) else { @@ -1554,16 +1634,18 @@ pub async fn add_cloud_server(s: &AppState, user: &User, req: AddCloudServer) -> ))); } let id = crate::ids::new_id("sbs"); - sqlx::query("INSERT INTO pyo.sandbox_servers (id, team_id, name, state, created_by, edge_domain) VALUES ($1, $2, $3, 'joining', $4, $5)") + sqlx::query("INSERT INTO pyo.sandbox_servers (id, team_id, name, state, created_by, edge_domain, via_cluster) VALUES ($1, $2, $3, 'joining', $4, $5, $6)") .bind(&id) .bind(&req.team_id) .bind(&req.name) .bind(&user.name) .bind(&edge) + .bind(&via) .execute(&mut *tx) .await?; let ts_key = crate::tailscale::join_key( s, + &via, &format!("Pyo: sandbox server {}", req.name), "a sandbox server", ) @@ -1620,10 +1702,14 @@ pub async fn add_cloud_server(s: &AppState, user: &User, req: AddCloudServer) -> ) .await?; tx.commit().await?; - let server = server_views(&s.db, std::slice::from_ref(&req.team_id), Some(&id)) - .await? - .into_iter() - .next(); + let server = server_views( + &mut *s.db.acquire().await?, + std::slice::from_ref(&req.team_id), + Some(&id), + ) + .await? + .into_iter() + .next(); Ok(json!({ "server": server, "cloudServer": made })) } @@ -1663,7 +1749,7 @@ pub async fn create_template(s: &AppState, user: &User, req: CreateTemplate) -> let mut tx = s.db.begin().await?; match &req.team_id { Some(t) => require(&mut tx, user, t, Need::Use).await?, - None => require_install_admin(user)?, + None => require_install_add(user)?, } let id = crate::ids::new_id("stp"); sqlx::query( @@ -1977,6 +2063,120 @@ mod tests { .unwrap(); } + /// Against a throwaway Postgres: the installation's servers and + /// templates are every team's on a self-hosted Pyo, and nobody's on a + /// hosted one, where Pyo's built-in templates stay and none of the + /// installation's can be added. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn the_installations_servers_and_templates_are_shared_only_when_self_hosted() { + let db = PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + let run = crate::ids::random_string(8); + let team = format!("tm_shared{run}"); + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, 'Shared', $1)") + .bind(&team) + .execute(&db) + .await + .unwrap(); + let (ours, installs) = (format!("sbs_ours{run}"), format!("sbs_inst{run}")); + for (id, owner) in [(&ours, Some(&team)), (&installs, None)] { + sqlx::query("INSERT INTO pyo.sandbox_servers (id, team_id, name, state, created_by) VALUES ($1, $2, $1, 'ready', 'test')") + .bind(id) + .bind(owner) + .execute(&db) + .await + .unwrap(); + } + let shared_template = format!("shared-{run}"); + sqlx::query("INSERT INTO pyo.sandbox_templates (id, team_id, name, source, state, created_by) VALUES ($1, NULL, $2, '{}', 'ready', 'test')") + .bind(format!("stp_inst{run}")) + .bind(&shared_template) + .execute(&db) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.sandbox_templates (id, team_id, name, source, state, created_by, builtin) VALUES ($1, NULL, $2, '{}', 'ready', 'test', true) ON CONFLICT DO NOTHING") + .bind(base::BASE.id) + .bind(base::BASE.name) + .execute(&db) + .await + .unwrap(); + + let mut tx = db.acquire().await.unwrap(); + let servers = |v: Vec<(scheduler::Candidate, String)>| { + let mut ids: Vec = v.into_iter().map(|(c, _)| c.id).collect(); + ids.retain(|i| i.ends_with(&run)); + ids.sort(); + ids + }; + let mut both = vec![installs.clone(), ours.clone()]; + both.sort(); + assert_eq!( + servers(candidates_on(&mut tx, &team, true).await.unwrap()), + both + ); + assert_eq!( + servers(candidates_on(&mut tx, &team, false).await.unwrap()), + vec![ours.clone()], + "hosted: the team's own server only" + ); + assert!( + template_on(&mut tx, &team, &shared_template, true) + .await + .is_ok() + ); + let e = template_on(&mut tx, &team, &shared_template, false) + .await + .err() + .unwrap(); + assert_eq!( + e.status, + StatusCode::NOT_FOUND, + "hosted: not the installation's" + ); + assert!( + template_on(&mut tx, &team, base::BASE.name, false) + .await + .is_ok(), + "Pyo's built-in template stays" + ); + + let admin = User { + id: "usr_admin".into(), + name: "Admin".into(), + email: "admin@shared.test".into(), + timezone: "UTC".into(), + is_admin: true, + must_set_up: false, + key: None, + }; + assert!(install_add(&admin, true).is_ok()); + assert_eq!( + install_add(&admin, false).unwrap_err().status, + StatusCode::FORBIDDEN, + "hosted: none of the installation's can be added" + ); + + drop(tx); + sqlx::query("DELETE FROM pyo.sandbox_servers WHERE id = $1") + .bind(&installs) + .execute(&db) + .await + .unwrap(); + sqlx::query("DELETE FROM pyo.sandbox_templates WHERE id = $1") + .bind(format!("stp_inst{run}")) + .execute(&db) + .await + .unwrap(); + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + } + #[test] fn create_without_a_template_uses_base() { let r: CreateSandbox = serde_json::from_value(json!({})).unwrap(); diff --git a/crates/pyo-api/src/sandbox/templates.rs b/crates/pyo-api/src/sandbox/templates.rs index d4d75662..38c8ba5a 100644 --- a/crates/pyo-api/src/sandbox/templates.rs +++ b/crates/pyo-api/src/sandbox/templates.rs @@ -90,9 +90,17 @@ pub fn older_ready<'a>( /// Whether a server may use a template: an installation's server takes /// every template, a team's server its team's and the installation's. -pub fn eligible(server_team: Option<&str>, template_team: Option<&str>) -> bool { - match (server_team, template_team) { - (None, _) | (_, None) => true, +/// Without [`super::shared`] (a hosted Pyo) an installation's server takes +/// none, and a team's server takes only Pyo's built-in templates of the +/// installation's. +pub fn eligible(server_team: Option<&str>, t: &Template) -> bool { + eligible_on(super::shared(), server_team, t) +} + +fn eligible_on(shared: bool, server_team: Option<&str>, t: &Template) -> bool { + match (server_team, t.team_id.as_deref()) { + (None, _) => shared, + (_, None) => shared || super::base::on_demand(&t.id), (Some(s), Some(t)) => s == t, } } @@ -200,7 +208,7 @@ pub fn plan( ) -> (Vec, Vec) { let mine: Vec<&Template> = templates .iter() - .filter(|t| eligible(server_team, t.team_id.as_deref())) + .filter(|t| eligible(server_team, t)) .collect(); let names: Vec = mine.iter().map(|t| t.server_name()).collect(); let wanted: HashSet<&str> = names.iter().map(String::as_str).collect(); @@ -336,7 +344,7 @@ pub async fn push(s: AppState, template_id: String) { .map_err(|e| anyhow::anyhow!(e.message))?; for (id, team, address, reports) in servers { let reports: Vec = serde_json::from_value(reports).unwrap_or_default(); - if !eligible(team.as_deref(), t.team_id.as_deref()) || !made_ahead(&t.id, &reports) { + if !eligible(team.as_deref(), &t) || !made_ahead(&t.id, &reports) { continue; } // The runner sends it once Pyo's registry door has an address. @@ -491,7 +499,7 @@ pub async fn update_states(db: &PgPool) -> sqlx::Result<()> { coalesce(bool_or(o.ready), false) FROM pyo.sandbox_templates t LEFT JOIN pyo.sandbox_servers s - ON s.team_id IS NULL OR t.team_id IS NULL OR s.team_id = t.team_id + ON (s.team_id IS NULL AND $1) OR (t.team_id IS NULL AND (t.builtin OR $1)) OR s.team_id = t.team_id LEFT JOIN LATERAL (SELECT x AS e FROM jsonb_array_elements(s.templates) x WHERE x->>'name' = t.id || coalesce('.' || t.revision, '') LIMIT 1) m ON true LEFT JOIN LATERAL (SELECT true AS ready FROM jsonb_array_elements(s.templates) x @@ -500,6 +508,7 @@ pub async fn update_states(db: &PgPool) -> sqlx::Result<()> { AND coalesce(x->>'state', 'ready') = 'ready' LIMIT 1) o ON true GROUP BY t.id", ) + .bind(super::shared()) .fetch_all(db) .await?; for (id, state, error, reports, missing, older_ready) in rows { @@ -607,10 +616,28 @@ mod tests { #[test] fn which_servers_take_which_templates() { - assert!(eligible(None, Some("tm_a")), "the installation's server"); - assert!(eligible(Some("tm_a"), None), "the installation's template"); - assert!(eligible(Some("tm_a"), Some("tm_a"))); - assert!(!eligible(Some("tm_a"), Some("tm_b"))); + let (a, b, i) = ( + t("stp_a", Some("tm_a")), + t("stp_b", Some("tm_b")), + t("stp_i", None), + ); + assert!(eligible(None, &a), "the installation's server"); + assert!(eligible(Some("tm_a"), &i), "the installation's template"); + assert!(eligible(Some("tm_a"), &a)); + assert!(!eligible(Some("tm_a"), &b)); + // A hosted Pyo: no installation's servers or templates, only Pyo's own. + let builtin = t(super::super::base::ALL[0].id, None); + assert!(!eligible_on(false, None, &a), "the installation's server"); + assert!( + !eligible_on(false, Some("tm_a"), &i), + "the installation's template" + ); + assert!( + eligible_on(false, Some("tm_a"), &builtin), + "Pyo's built-in one" + ); + assert!(eligible_on(false, Some("tm_a"), &a)); + assert!(!eligible_on(false, Some("tm_a"), &b)); } #[test] diff --git a/crates/pyo-api/src/secrets.rs b/crates/pyo-api/src/secrets.rs index 1eb88c33..2da1c9bb 100644 --- a/crates/pyo-api/src/secrets.rs +++ b/crates/pyo-api/src/secrets.rs @@ -1,13 +1,15 @@ -//! Sealing installation credentials at rest (GitHub app key, registry and -//! SMTP passwords, Tailscale keys, deploy hook tokens, certificate keys). -//! XSalsa20-Poly1305 (NaCl secretbox) with PYO_SECRET_KEY (64 hex chars); -//! each value gets its own random nonce. Stored as `sb1:` + base64(nonce || -//! ciphertext). Teams' own values use envelope encryption instead (vault.rs). +//! Sealing the installation's own credentials at rest (GitHub App key, +//! SMTP password, Tailscale keys, Pyo's backup store, sandbox signing +//! keys). XSalsa20-Poly1305 (NaCl secretbox) with PYO_SECRET_KEY (64 hex +//! chars); each value gets its own random nonce. Stored as `sb1:` + +//! base64(nonce || ciphertext). Teams' credentials are sealed with each +//! team's own data key instead (vault.rs `seal_credential`). Releases +//! before 0.5 sealed some of them here, and they still open. use base64::{Engine, engine::general_purpose::STANDARD}; use crypto_secretbox::{Key as BoxKey, Nonce as BoxNonce, XSalsa20Poly1305}; -const PREFIX: &str = "sb1:"; +pub(crate) const PREFIX: &str = "sb1:"; pub struct Sealer { secretbox: Option, @@ -103,4 +105,76 @@ mod tests { assert_ne!(s.seal("x").unwrap(), s.seal("x").unwrap()); assert!(s.open("bm90IHNlYWxlZA==").is_err(), "unsealed"); } + + /// The installation's key seals only the installation's own + /// credentials. A team's (a token, password or key it gave Pyo) is + /// sealed with the team's data key: vault.rs `seal_credential`. A new + /// use here gets a place in this list with its reason. + #[test] + fn the_installation_key_seals_only_the_installations_credentials() { + let allowed: &[(&str, usize, &str)] = &[ + ("github.rs", 1, "the installation's GitHub App"), + ( + "sandbox/keys.rs", + 1, + "the installation's sandbox signing keys", + ), + ( + "sandbox/edgecert.rs", + 2, + "the installation's ACME account and its own sandbox servers' certificates", + ), + ( + "cloud/bootstrap.rs", + 1, + "a new cloud server's one-time join material, burned when used or after 15 minutes", + ), + ( + "twofactor.rs", + 1, + "people's authenticator app secrets: they belong to accounts, not to a team", + ), + ( + "ops.rs", + 3, + "Pyo's own backup bucket, its SMTP password, and an invite's link in the email retry job", + ), + ]; + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut found: Vec<(String, usize)> = vec![]; + let mut dirs = vec![src.clone()]; + while let Some(d) = dirs.pop() { + for e in std::fs::read_dir(&d).unwrap() { + let path = e.unwrap().path(); + if path.is_dir() { + dirs.push(path); + continue; + } + let text = std::fs::read_to_string(&path).unwrap_or_default(); + // Tests seal what they like. + let text = text.split("#[cfg(test)]").next().unwrap_or(""); + // `s.sealer\n.seal(` too. + let squashed: String = text.chars().filter(|c| !c.is_whitespace()).collect(); + let n = squashed.matches("sealer.seal(").count(); + let name = path + .strip_prefix(&src) + .unwrap() + .to_string_lossy() + .into_owned(); + if n > 0 && name != "secrets.rs" { + found.push((name, n)); + } + } + } + found.sort(); + let mut want: Vec<(String, usize)> = allowed + .iter() + .map(|(f, n, _)| (f.to_string(), *n)) + .collect(); + want.sort(); + assert_eq!( + found, want, + "a team's credential goes through vault.rs seal_credential" + ); + } } diff --git a/crates/pyo-api/src/sites.rs b/crates/pyo-api/src/sites.rs index 9a9b70aa..7acb53a2 100644 --- a/crates/pyo-api/src/sites.rs +++ b/crates/pyo-api/src/sites.rs @@ -438,7 +438,15 @@ fn token_cluster(key: &[u8], token: &str) -> Option { (same && !cluster.is_empty()).then(|| cluster.to_owned()) } +/// A token for an agent that gives pyo-static no key of its own (one older +/// than component keys), where agents may still use tokens. async fn static_login(a: crate::agent::AgentCluster) -> ApiResult> { + if crate::agent_auth::refuse_tokens() { + return Err(ApiError::new( + StatusCode::GONE, + "pyo-static signs its requests with a key from its cluster's agent here.", + )); + } let token = reader_token(&a.id).ok_or_else(|| { ApiError::new( StatusCode::SERVICE_UNAVAILABLE, @@ -460,6 +468,16 @@ impl FromRequestParts for StaticReader { parts: &mut Parts, state: &AppState, ) -> Result { + // Its key (agent_auth.rs), made by the agent in its cluster. + if let Some(v) = parts.extensions.get::() { + if v.component != crate::agent_auth::STATIC { + return Err(ApiError::new(StatusCode::FORBIDDEN, "This key isn't pyo-static's.")); + } + return Ok(StaticReader { cluster_id: v.cluster_id.clone() }); + } + if crate::agent_auth::refuse_tokens() { + return Err(ApiError::new(StatusCode::UNAUTHORIZED, "pyo-static signs its requests here.")); + } let token = parts .headers .get("authorization") @@ -474,7 +492,8 @@ impl FromRequestParts for StaticReader { .bind(&cluster) .fetch_one(&state.db) .await?; - if !known { + // A cluster whose pyo-static has a key no longer reads with a token. + if !known || crate::agent_auth::has_key(&state.db, &cluster, crate::agent_auth::STATIC, None).await? { return Err(ApiError::new(StatusCode::UNAUTHORIZED, "Unknown token.")); } Ok(StaticReader { diff --git a/crates/pyo-api/src/snapshot.rs b/crates/pyo-api/src/snapshot.rs index 07016f00..c60cc37e 100644 --- a/crates/pyo-api/src/snapshot.rs +++ b/crates/pyo-api/src/snapshot.rs @@ -2,7 +2,7 @@ //! own shapes (dash/src/lib/pyo/types.ts). Postgres builds most of the JSON. use serde_json::{Value, json}; -use sqlx::PgPool; +use sqlx::{PgConnection, PgPool}; use crate::{auth::User, error::ApiResult}; @@ -13,7 +13,7 @@ const DEPLOYMENTS_WITH_LOGS: i64 = 30; const LOG_LINES: i64 = 400; /// Queries here are constants (two interpolate Pyo's own constants); ids are bound. -async fn values(db: &PgPool, sql: &str, team_ids: &[String]) -> ApiResult> { +async fn values(db: &mut PgConnection, sql: &str, team_ids: &[String]) -> ApiResult> { Ok( sqlx::query_scalar::<_, Value>(sqlx::AssertSqlSafe(sql.to_owned())) .bind(team_ids) @@ -23,37 +23,102 @@ async fn values(db: &PgPool, sql: &str, team_ids: &[String]) -> ApiResult ApiResult { + // The installation's own settings and the account's keys first, on the + // pool: the teams' transaction below takes no other connection while + // it's open, so a busy pool can't leave requests waiting on each other. let email = crate::mail::settings(db).await?; let github = crate::github::app(db).await?; - let mut team_ids: Vec = sqlx::query_scalar( - "SELECT team_id FROM pyo.members WHERE user_id = $1 AND status = 'active'", + let reached = crate::publicdash::reached(db).await?; + let public_dashboard = if user.is_admin { + crate::publicdash::snapshot(db).await? + } else { + Value::Null + }; + let control_backup = if user.is_admin { + crate::backup::snapshot(db).await? + } else { + Value::Null + }; + let updates = if user.is_admin { + crate::updates::snapshot(db).await? + } else { + Value::Null + }; + + let api_tokens: Vec = sqlx::query_scalar( + "SELECT jsonb_build_object('id', id, 'name', name, 'prefix', prefix, 'createdAt', pyo.ms(created_at), 'lastUsedAt', pyo.ms(last_used_at), + 'expiresAt', pyo.ms(expires_at), 'access', access, 'teamIds', team_ids) + FROM pyo.api_tokens WHERE user_id = $1 AND $2 ORDER BY created_at", + ) + .bind(&user.id) + // Keys don't list other keys. + .bind(user.key.is_none()) + .fetch_all(db) + .await?; + let mut oauth_grants: Vec = sqlx::query_scalar( + "SELECT jsonb_build_object('id', g.id, 'client', c.name, 'createdAt', pyo.ms(g.created_at), 'lastUsedAt', pyo.ms(g.last_used_at), 'scope', g.scope) + FROM pyo.oauth_grants g JOIN pyo.oauth_clients c ON c.id = g.client_id + WHERE g.user_id = $1 AND g.refresh_expires_at > now() ORDER BY g.created_at", ) .bind(&user.id) .fetch_all(db) .await?; - // An API key for some teams sees only those. - if let Some(allowed) = user.key.as_ref().and_then(|k| k.teams.as_ref()) { - team_ids.retain(|t| allowed.contains(t)); + // What each may do, in API key terms. + for g in &mut oauth_grants { + let access = crate::oauth::scope_access(g["scope"].as_str().unwrap_or("")); + g["access"] = json!(access.as_str()); + if let Some(o) = g.as_object_mut() { + o.remove("scope"); + } } + // Two-factor: the account's own, and the teams it can't open until + // it's on (twofactor.rs). The installation's security settings for + // its admin. + let two_factor = crate::twofactor::summary(db, &user.id).await?; + let security_settings = if user.is_admin { + json!(crate::audit::settings(db).await?) + } else { + Value::Null + }; + // Tailscale (Integrations › Tailscale): the client only for admins. + let tailscale = crate::tailscale::snapshot(db, user.is_admin).await?; + // `small`: the server Pyo runs on has under 3.5 GB of memory now (the + // dashboard suggests turning observability off, or on when it isn't). + let observability_settings = json!({ + "ipMode": crate::observability::ip_mode(db).await?, + "enabled": crate::observability::setting(db).await?, + "retention": crate::retention::load(db).await?, + "small": pyo_proto::memory::server_mib().map(|m| pyo_proto::memory::tier(m) == pyo_proto::memory::Tier::Small), + }); + + // The teams' rows through one transaction lowered to the teams the + // user (or the API key) may see (rls.rs): a query here that forgot its + // team check still can't show another team's. + let mut tx = crate::rls::begin(db, user).await?; + let db: &mut PgConnection = &mut tx; + let team_ids = crate::rls::team_ids(db).await?; let teams = values( - db, + &mut *db, "SELECT jsonb_build_object( 'id', id, 'name', name, 'slug', slug, 'description', description, 'createdAt', pyo.ms(created_at), 'defaultClusterId', default_cluster_id, - 'preferences', preferences) + 'preferences', preferences, 'agentUpdates', agent_updates, + 'analyticsMonths', analytics_months, + 'requireTwoFactor', require_two_factor, 'auditIps', audit_ips) FROM pyo.teams WHERE id = ANY($1) ORDER BY created_at", &team_ids, ) .await?; let members = values( - db, + &mut *db, "SELECT jsonb_build_object( 'id', m.id, 'teamId', m.team_id, 'name', coalesce(u.name, ''), 'email', m.email, -- Gravatar's key: sha256 of the trimmed, lowercased email. 'gravatar', encode(sha256(convert_to(lower(trim(m.email)), 'UTF8')), 'hex'), - 'role', m.role, 'status', m.status, 'joinedAt', pyo.ms(m.joined_at)) + 'role', m.role, 'status', m.status, 'joinedAt', pyo.ms(m.joined_at), + 'twoFactor', EXISTS (SELECT 1 FROM pyo.user_totp t WHERE t.user_id = m.user_id AND t.enabled_at IS NOT NULL)) FROM pyo.members m LEFT JOIN pyo.users u ON u.id = m.user_id WHERE m.team_id = ANY($1) ORDER BY m.joined_at", &team_ids, @@ -61,7 +126,7 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult>'podCidr', ''), 'serviceCidr', coalesce(capabilities->>'serviceCidr', ''), 'createdAt', pyo.ms(created_at), + -- Its connect command works until then, unless its agent connected (install.rs). + 'connectExpiresAt', CASE WHEN connect_token_used_at IS NULL THEN pyo.ms(connect_token_expires_at) END, + -- Its agent's last update (updates.rs), for a hosted Pyo's cluster page. + 'agentUpdate', (SELECT jsonb_build_object('status', m.status, 'message', m.result->>'message', 'at', pyo.ms(m.created_at)) + FROM pyo.commands m WHERE m.cluster_id = clusters.id AND m.command->>'kind' = 'update_agent' + ORDER BY m.created_at DESC LIMIT 1), 'lastSeenAt', coalesce(pyo.ms(last_seen_at), 0)) FROM pyo.clusters WHERE team_id = ANY($1) ORDER BY created_at", &team_ids, @@ -108,10 +181,10 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult = std::collections::HashSet::new(); let mut waf_active: std::collections::HashSet = std::collections::HashSet::new(); - let syncing = crate::bundles::syncing_firewall(db, &ids).await?; + let syncing = crate::bundles::syncing_firewall(&mut *db, &ids).await?; for c in &mut clusters { waf_rejected.extend( c["capabilities"]["wafRejected"] @@ -131,7 +204,7 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult = match &suffix { - Some(_) => sqlx::query_scalar( - "SELECT id FROM pyo.clusters WHERE team_id = ANY($1) - AND EXISTS (SELECT 1 FROM jsonb_array_elements(coalesce(capabilities->'tailnet', '[]')) t WHERE t->>'state' = 'Running')", - ) - .bind(&team_ids) - .fetch_all(db) - .await?, - None => Vec::new(), - }; + // The tailnet its tailnet domains are on: Tailscale set up on the + // cluster, and a server of it on the tailnet. And the cluster's + // Tailscale as the dashboard shows it (never a secret). + let tailnets: Vec<(String, Option, bool)> = sqlx::query_as( + "SELECT id, tailscale, + EXISTS (SELECT 1 FROM jsonb_array_elements(coalesce(capabilities->'tailnet', '[]')) t WHERE t->>'state' = 'Running') + FROM pyo.clusters WHERE team_id = ANY($1)", + ) + .bind(&team_ids) + .fetch_all(&mut *db) + .await?; for c in &mut clusters { - let on = c["id"] - .as_str() - .is_some_and(|id| on_tailnet.iter().any(|x| x == id)); - c["tailnet"] = json!(suffix.as_ref().filter(|_| on)); + let row = tailnets.iter().find(|r| c["id"] == json!(r.0)); + let t = row + .and_then(|r| r.1.clone()) + .and_then(|v| serde_json::from_value::(v).ok()); + let on = row.is_some_and(|r| r.2); + c["tailnet"] = json!(t.as_ref().and_then(|t| t.suffix.clone()).filter(|_| on)); + c["tailscale"] = t.as_ref().map(crate::tailscale::cluster_view).unwrap_or(Value::Null); } // Workloads come from each cluster's last heartbeat. let workloads = values( - db, + &mut *db, "SELECT w || jsonb_build_object( 'id', c.id || ':' || (w->>'namespace') || '/' || (w->>'name'), 'clusterId', c.id, @@ -201,19 +277,21 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult ApiResult ApiResult ApiResult ApiResult = sqlx::query_scalar( - "SELECT jsonb_build_object('id', id, 'name', name, 'prefix', prefix, 'createdAt', pyo.ms(created_at), 'lastUsedAt', pyo.ms(last_used_at), - 'expiresAt', pyo.ms(expires_at), 'access', access, 'teamIds', team_ids) - FROM pyo.api_tokens WHERE user_id = $1 AND $2 ORDER BY created_at", - ) - .bind(&user.id) - // Keys don't list other keys. - .bind(user.key.is_none()) - .fetch_all(db) - .await?; let registry_logins = values( - db, + &mut *db, "SELECT jsonb_build_object('id', id, 'teamId', team_id, 'host', host, 'username', username, 'verified', verified, 'createdAt', pyo.ms(created_at), 'lastUsedAt', pyo.ms(last_used_at)) FROM pyo.registry_logins WHERE team_id = ANY($1) ORDER BY host", @@ -311,7 +379,7 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult>() .join(", "); let alert_channels = values( - db, + &mut *db, &format!( "SELECT jsonb_build_object('id', id, 'teamId', team_id, 'kind', kind, 'name', name, 'hint', hint, 'events', to_jsonb(ARRAY(SELECT t FROM unnest(ARRAY[{topics}]) t WHERE NOT (t = ANY(muted)))), @@ -337,7 +405,7 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult ApiResult ApiResult = sqlx::query_scalar( - "SELECT jsonb_build_object('id', g.id, 'client', c.name, 'createdAt', pyo.ms(g.created_at), 'lastUsedAt', pyo.ms(g.last_used_at), 'scope', g.scope) - FROM pyo.oauth_grants g JOIN pyo.oauth_clients c ON c.id = g.client_id - WHERE g.user_id = $1 AND g.refresh_expires_at > now() ORDER BY g.created_at", - ) - .bind(&user.id) - .fetch_all(db) - .await?; - // What each may do, in API key terms. - for g in &mut oauth_grants { - let access = crate::oauth::scope_access(g["scope"].as_str().unwrap_or("")); - g["access"] = json!(access.as_str()); - if let Some(o) = g.as_object_mut() { - o.remove("scope"); - } - } // Hooks without their tokens; RevealDeployHook gives the URL. let deploy_hooks = values( - db, + &mut *db, "SELECT jsonb_build_object('id', id, 'teamId', team_id, 'projectId', project_id, 'serviceId', service_id, 'name', name, 'createdBy', created_by, 'createdAt', pyo.ms(created_at), 'lastUsedAt', pyo.ms(last_used_at)) FROM pyo.deploy_hooks WHERE team_id = ANY($1) ORDER BY created_at", &team_ids, ) .await?; - let github_installations = values( - db, + let mut github_installations = values( + &mut *db, "SELECT jsonb_build_object('id', id, 'teamId', team_id, 'account', account, 'accountType', account_type, - 'repositorySelection', repository_selection, 'createdAt', pyo.ms(created_at)) + 'repositorySelection', repository_selection, 'createdAt', pyo.ms(created_at), + 'permissions', permissions, 'events', events) FROM pyo.github_installations WHERE team_id = ANY($1) ORDER BY account", &team_ids, ) .await?; + // What previews still need approved on GitHub, and where. + for i in github_installations.iter_mut() { + crate::previews::github::show_installation(i); + } // Git connections, never their tokens. let git_connections = values( - db, + &mut *db, "SELECT jsonb_build_object('id', c.id, 'teamId', c.team_id, 'provider', c.provider, 'url', c.base_url, 'account', c.account, 'publicUrl', c.public_url, 'info', c.info, 'createdAt', pyo.ms(c.created_at), 'webhooks', coalesce((SELECT jsonb_agg(jsonb_build_object('repo', w.repo, 'active', w.hook_id IS NOT NULL, 'error', w.error) ORDER BY w.repo) @@ -419,23 +476,29 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult Value { /// Env values are sealed at rest. Plain ones are opened for the dashboard; /// secret ones never leave the API: blank, with `hasValue` saying one is set. async fn for_dashboard(mut services: Vec) -> ApiResult> { - let vault = crate::vault::get(); for service in services.iter_mut() { crate::template_source::show(service); let service_id = service["id"].clone(); - let Some(env) = service.get_mut("env").and_then(Value::as_array_mut) else { - continue; - }; - for e in env.iter_mut() { - let value = e["value"].as_str().unwrap_or("").to_owned(); - if e["secret"] == json!(true) { - e["hasValue"] = json!(!value.is_empty()); - e["value"] = json!(""); - } else if crate::vault::Vault::is_sealed(&value) { - // One unreadable value mustn't take the whole dashboard down. - match vault.open(&value).await { - Ok(v) => e["value"] = json!(v), - Err(err) => { - tracing::error!(service = %service_id, key = %e["key"], error = %err, "can't open an environment variable"); - e["value"] = json!(""); - } + // The service's variables, then its previews' (the same rules). + if let Some(env) = service.get_mut("env").and_then(Value::as_array_mut) { + shown_env(env, &service_id).await; + } + if let Some(env) = service + .get_mut("previews") + .and_then(|p| p.get_mut("env")) + .and_then(Value::as_array_mut) + { + shown_env(env, &service_id).await; + } + } + Ok(services) +} + +/// Variables as the dashboard gets them: a secret's value never (only that +/// it has one), the others opened. +async fn shown_env(env: &mut [Value], service_id: &Value) { + let vault = crate::vault::get(); + for e in env.iter_mut() { + let value = e["value"].as_str().unwrap_or("").to_owned(); + if e["secret"] == json!(true) { + e["hasValue"] = json!(!value.is_empty()); + e["value"] = json!(""); + } else if crate::vault::Vault::is_sealed(&value) { + // One unreadable value mustn't take the whole dashboard down. + match vault.open(&value).await { + Ok(v) => e["value"] = json!(v), + Err(err) => { + tracing::error!(service = %service_id, key = %e["key"], error = %err, "can't open an environment variable"); + e["value"] = json!(""); } } } } - Ok(services) } #[cfg(test)] diff --git a/crates/pyo-api/src/source_uploads.rs b/crates/pyo-api/src/source_uploads.rs new file mode 100644 index 00000000..8bb60d7d --- /dev/null +++ b/crates/pyo-api/src/source_uploads.rs @@ -0,0 +1,945 @@ +//! Folders sent with `pyo deploy`: built like a Git checkout by a builder in +//! the service's own cluster, then deployed. +//! +//! - **Upload:** the CLI packs the folder as a gzipped tar and says what it +//! is (`POST /source-uploads`: its team, size and SHA-256). It sends the +//! archive in parts of [`PART_SIZE`] (`PUT …/parts/{n}`, again when one +//! fails: a part sent twice replaces itself), asks which arrived +//! (`GET /source-uploads/{id}`) and finishes (`POST …/complete`), which +//! checks the SHA-256. Parts stay small enough for any proxy in front +//! (Cloudflare's 100 MB), so Pyo Cloud takes them the same way. +//! - **Where it waits:** in Pyo's own database (`pyo.source_upload_parts`), +//! which every web replica shares, for at most [`KEEP_HOURS`]. +//! - **Deploy:** `deploy` or `createService` with `uploadId` claims it for +//! one deployment (deploy.rs). Its build job names it, and the builder +//! that claims the job fetches it with its signed requests +//! (`GET /api/builder/v1/jobs/{id}/source`), then says it has it +//! (`DELETE` there): the archive is deleted from Pyo then. A cancelled or +//! finished deployment, or one that never got a builder, loses it too. + +use axum::{ + Router, + body::{Body, Bytes}, + extract::{DefaultBodyLimit, Path, State}, + http::{StatusCode, header}, + response::Response, + routing::{get, post, put}, +}; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::{PgPool, Postgres, Transaction}; + +use crate::{ + AppState, + auth::SessionUser, + builders::BuilderAuth, + error::{ApiError, ApiResult, ErrorBody, Json}, + ops::{Role, require_role}, +}; + +/// The size of each part but the last. +pub const PART_SIZE: u64 = 8 << 20; +/// How long an upload is kept: to be sent, then to be built. +pub const KEEP_HOURS: i64 = 2; +/// Uploads one team may have at once. +const MAX_WAITING: i64 = 10; + +/// The biggest archive Pyo takes: `PYO_SOURCE_UPLOAD_MAX_BYTES`, 500 MB by default. +pub fn max_bytes() -> u64 { + std::env::var("PYO_SOURCE_UPLOAD_MAX_BYTES") + .ok() + .and_then(|v| v.trim().parse().ok()) + .filter(|n| *n > 0) + .unwrap_or(500_000_000) +} + +pub fn routes() -> Router { + Router::new() + .route("/source-uploads", post(create)) + .route("/source-uploads/{id}", get(status)) + .route( + "/source-uploads/{id}/parts/{n}", + put(part).layer(DefaultBodyLimit::max(PART_SIZE as usize + 1024)), + ) + .route("/source-uploads/{id}/complete", post(complete)) +} + +/// For builders (signed): the archive of a build they're running. +pub fn builder_routes() -> Router { + Router::new().route("/jobs/{id}/source", get(fetch).delete(fetched)) +} + +/// Parts an archive of `size` bytes is sent in. +pub fn part_count(size: u64) -> u64 { + size.div_ceil(PART_SIZE) +} + +/// The size part `n` of an archive of `size` bytes must have, if there's +/// such a part. +pub fn part_len(size: u64, n: u64) -> Option { + let count = part_count(size); + if n >= count { + return None; + } + Some(if n + 1 == count { + size - n * PART_SIZE + } else { + PART_SIZE + }) +} + +/// Text from the CLI shown on the dashboard: no control characters, short. +fn label(s: &str) -> String { + s.chars().filter(|c| !c.is_control()).take(100).collect() +} + +/// "500 MB". +fn mb(b: u64) -> String { + format!("{} MB", b.div_ceil(1_000_000)) +} + +/// A folder about to be uploaded. +#[derive(Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct NewSourceUpload { + /// The team's id. + team_id: String, + /// The archive's size in bytes (a gzipped tar). + size: u64, + /// Its SHA-256, in lowercase hex. + sha256: String, + /// How many files it holds. + #[serde(default)] + files: u32, + /// The folder's name, shown with the deployment. + #[serde(default)] + folder: String, + /// The computer's name, shown as "Uploaded from …". + #[serde(default)] + machine: String, +} + +/// Start an upload +/// +/// The first step of deploying a folder: say what the archive is (a +/// gzipped tar of the folder) and get where its parts go. Send each part +/// with `uploadSourcePart`, then `completeSourceUpload`, then `deploy` (or +/// `createService`) with the `uploadId`. At most +/// `PYO_SOURCE_UPLOAD_MAX_BYTES` (500 MB by default). Kept for 2 hours. +#[utoipa::path(post, path = "/source-uploads", operation_id = "createSourceUpload", tag = "Deployments", + request_body = NewSourceUpload, + responses( + (status = 200, description = "`uploadId`, `partSize` (bytes in each part but the last), `parts` (how many) and `expiresAt`.", body = Object), + (status = 400, description = "Empty, or not a SHA-256.", body = ErrorBody), + (status = 403, description = "You can't deploy in this team.", body = ErrorBody), + (status = 413, description = "Bigger than this installation takes.", body = ErrorBody), + (status = 429, description = "Too many uploads waiting in this team.", body = ErrorBody), + ), + extensions(("x-pyo-access" = json!("deploy"))))] +pub async fn create( + State(s): State, + SessionUser(user): SessionUser, + Json(req): Json, +) -> ApiResult> { + if req.size == 0 { + return Err(ApiError::bad_request("The folder is empty.")); + } + let max = max_bytes(); + if req.size > max { + return Err(ApiError::new( + StatusCode::PAYLOAD_TOO_LARGE, + format!( + "The folder packs to {}, more than the {} Pyo takes. Leave out more in .pyoignore.", + mb(req.size), + mb(max) + ), + )); + } + let sha = req.sha256.trim().to_ascii_lowercase(); + if sha.len() != 64 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(ApiError::bad_request( + "sha256 is the archive's SHA-256, in hex.", + )); + } + let mut tx = s.db.begin().await?; + require_role(&mut tx, &user, &req.team_id, Role::Developer).await?; + let waiting: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pyo.source_uploads WHERE team_id = $1 AND expires_at > now()", + ) + .bind(&req.team_id) + .fetch_one(&mut *tx) + .await?; + if waiting >= MAX_WAITING { + return Err(ApiError::new( + StatusCode::TOO_MANY_REQUESTS, + "Too many uploads are waiting to be built in this team. Try again in a few minutes.", + )); + } + let id = crate::ids::new_id("src"); + let expires_at: i64 = sqlx::query_scalar( + "INSERT INTO pyo.source_uploads (id, team_id, size, sha256, files, folder, machine, created_by, expires_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, now() + make_interval(hours => $9)) RETURNING pyo.ms(expires_at)", + ) + .bind(&id) + .bind(&req.team_id) + .bind(req.size as i64) + .bind(&sha) + .bind(req.files as i32) + .bind(label(&req.folder)) + .bind(label(&req.machine)) + .bind(&user.name) + .bind(KEEP_HOURS as i32) + .fetch_one(&mut *tx) + .await?; + tx.commit().await?; + Ok(Json(json!({ + "uploadId": id, + "partSize": PART_SIZE, + "parts": part_count(req.size), + "expiresAt": expires_at, + }))) +} + +/// An upload the user may send to: its team's developers and up. +async fn mine( + tx: &mut Transaction<'_, Postgres>, + user: &crate::auth::User, + id: &str, +) -> ApiResult<(u64, String, String)> { + let row: Option<(String, i64, String, String)> = sqlx::query_as( + "SELECT team_id, size, sha256, state FROM pyo.source_uploads WHERE id = $1 AND expires_at > now()", + ) + .bind(id) + .fetch_optional(&mut **tx) + .await?; + let (team_id, size, sha, state) = row.ok_or_else(|| ApiError::not_found("Upload"))?; + require_role(tx, user, &team_id, Role::Developer).await?; + Ok((size as u64, sha, state)) +} + +/// Send a part +/// +/// Part `n` (from 0) of an upload's archive, as the request's body: exactly +/// `partSize` bytes, the last part what's left. Sending a part again +/// replaces it. +#[utoipa::path(put, path = "/source-uploads/{id}/parts/{n}", operation_id = "uploadSourcePart", tag = "Deployments", + params(("id" = String, Path, description = "The upload's id."), ("n" = u64, Path, description = "The part, from 0.")), + request_body(content = String, content_type = "application/octet-stream", description = "The part's bytes."), + responses( + (status = 200, description = "Stored.", body = Object), + (status = 400, description = "Not a part of this upload, or not its size.", body = ErrorBody), + (status = 404, description = "No such upload, or it expired.", body = ErrorBody), + (status = 409, description = "The upload is complete already.", body = ErrorBody), + ), + extensions(("x-pyo-access" = json!("deploy"))))] +pub async fn part( + State(s): State, + SessionUser(user): SessionUser, + Path((id, n)): Path<(String, u64)>, + body: Bytes, +) -> ApiResult> { + let mut tx = crate::rls::begin(&s.db, &user).await?; + let (size, _, state) = mine(&mut tx, &user, &id).await?; + if state != "uploading" { + return Err(ApiError::conflict("This upload is complete already.")); + } + let want = part_len(size, n).ok_or_else(|| { + ApiError::bad_request(format!("This upload has {} parts.", part_count(size))) + })?; + if body.len() as u64 != want { + return Err(ApiError::bad_request(format!( + "Part {n} is {want} bytes, not {}.", + body.len() + ))); + } + sqlx::query( + "INSERT INTO pyo.source_upload_parts (upload_id, n, data) VALUES ($1, $2, $3) + ON CONFLICT (upload_id, n) DO UPDATE SET data = excluded.data", + ) + .bind(&id) + .bind(n as i32) + .bind(body.as_ref()) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(Json(json!({ "ok": true }))) +} + +/// The parts of an upload Pyo has, in order. +async fn received(db: impl sqlx::PgExecutor<'_>, id: &str) -> sqlx::Result> { + sqlx::query_scalar("SELECT n FROM pyo.source_upload_parts WHERE upload_id = $1 ORDER BY n") + .bind(id) + .fetch_all(db) + .await +} + +/// An upload +/// +/// Which parts of an upload Pyo has (`received`), to send the rest after a +/// break, and its `state`: "uploading", "ready" (complete) or "used" (a +/// deployment builds it). +#[utoipa::path(get, path = "/source-uploads/{id}", operation_id = "getSourceUpload", tag = "Deployments", + params(("id" = String, Path, description = "The upload's id.")), + responses( + (status = 200, description = "`uploadId`, `state`, `parts` and `received`.", body = Object), + (status = 404, description = "No such upload, or it expired.", body = ErrorBody), + ), + extensions(("x-pyo-access" = json!("deploy"))))] +pub async fn status( + State(s): State, + SessionUser(user): SessionUser, + Path(id): Path, +) -> ApiResult> { + let mut tx = crate::rls::begin(&s.db, &user).await?; + let (size, _, state) = mine(&mut tx, &user, &id).await?; + let have = received(&mut *tx, &id).await?; + tx.commit().await?; + Ok(Json(json!({ + "uploadId": id, + "state": state, + "parts": part_count(size), + "received": have, + }))) +} + +/// The SHA-256 of an upload's parts, in order, read one at a time. +async fn digest(db: &PgPool, id: &str, count: u64) -> ApiResult { + use sha2::Digest; + let mut hash = sha2::Sha256::new(); + for n in 0..count { + let data: Vec = sqlx::query_scalar( + "SELECT data FROM pyo.source_upload_parts WHERE upload_id = $1 AND n = $2", + ) + .bind(id) + .bind(n as i32) + .fetch_one(db) + .await?; + hash.update(&data); + } + Ok(hex::encode(hash.finalize())) +} + +/// Finish an upload +/// +/// Once every part is sent: Pyo checks the archive against its SHA-256. +/// Then deploy it with `deploy` (or `createService`) and its `uploadId`. +#[utoipa::path(post, path = "/source-uploads/{id}/complete", operation_id = "completeSourceUpload", tag = "Deployments", + params(("id" = String, Path, description = "The upload's id.")), + responses( + (status = 200, description = "Complete.", body = Object), + (status = 400, description = "Parts are missing (`getSourceUpload` says which), or the archive isn't what was declared (the upload is gone then: start again).", body = ErrorBody), + (status = 404, description = "No such upload, or it expired.", body = ErrorBody), + ), + extensions(("x-pyo-access" = json!("deploy"))))] +pub async fn complete( + State(s): State, + SessionUser(user): SessionUser, + Path(id): Path, +) -> ApiResult> { + let mut tx = s.db.begin().await?; + let (size, sha, state) = mine(&mut tx, &user, &id).await?; + tx.commit().await?; + if state != "uploading" { + return Ok(Json(json!({ "ok": true }))); + } + let count = part_count(size); + let have = received(&s.db, &id).await?; + let missing: Vec = (0..count) + .filter(|n| !have.contains(&(*n as i32))) + .collect(); + if !missing.is_empty() { + return Err(ApiError::bad_request(format!( + "{} of {count} parts haven't arrived. Send them first.", + missing.len() + ))); + } + if digest(&s.db, &id, count).await? != sha { + delete(&s.db, &id).await?; + return Err(ApiError::bad_request( + "The upload doesn't match the folder that was packed. Deploy again.", + )); + } + sqlx::query( + "UPDATE pyo.source_uploads SET state = 'ready' WHERE id = $1 AND state = 'uploading'", + ) + .bind(&id) + .execute(&s.db) + .await?; + Ok(Json(json!({ "ok": true }))) +} + +/// An upload claimed for a deployment, as deploy.rs puts it in the +/// deployment's source and its build job. +pub struct Claimed { + pub job: pyo_proto::SourceUpload, + pub files: i32, + pub folder: String, + pub machine: String, +} + +/// Take a complete upload of the team for one deployment, once. +pub async fn claim( + tx: &mut Transaction<'_, Postgres>, + id: &str, + team_id: &str, + deployment_id: &str, +) -> ApiResult { + let row: Option<(i64, String, i32, String, String)> = sqlx::query_as( + "UPDATE pyo.source_uploads SET state = 'used', deployment_id = $3, expires_at = now() + make_interval(hours => $4) + WHERE id = $1 AND team_id = $2 AND state = 'ready' AND expires_at > now() + RETURNING size, sha256, files, folder, machine", + ) + .bind(id) + .bind(team_id) + .bind(deployment_id) + .bind(KEEP_HOURS as i32) + .fetch_optional(&mut **tx) + .await?; + let (size, sha256, files, folder, machine) = row.ok_or_else(|| { + ApiError::conflict( + "That upload isn't complete, was deployed already or expired. Deploy the folder again.", + ) + })?; + Ok(Claimed { + job: pyo_proto::SourceUpload { + id: id.to_owned(), + size: size as u64, + sha256, + }, + files, + folder, + machine, + }) +} + +/// A retried deployment builds the same upload, while Pyo still has it. +pub async fn reclaim( + tx: &mut Transaction<'_, Postgres>, + id: &str, + team_id: &str, + deployment_id: &str, +) -> ApiResult { + let row: Option<(i64, String)> = sqlx::query_as( + "UPDATE pyo.source_uploads SET deployment_id = $3, expires_at = now() + make_interval(hours => $4) + WHERE id = $1 AND team_id = $2 AND state = 'used' AND expires_at > now() + RETURNING size, sha256", + ) + .bind(id) + .bind(team_id) + .bind(deployment_id) + .bind(KEEP_HOURS as i32) + .fetch_optional(&mut **tx) + .await?; + let (size, sha256) = row.ok_or_else(|| { + ApiError::conflict( + "The folder sent for that deploy is gone. Deploy it again with pyo deploy.", + ) + })?; + Ok(pyo_proto::SourceUpload { + id: id.to_owned(), + size: size as u64, + sha256, + }) +} + +async fn delete(db: impl sqlx::PgExecutor<'_>, id: &str) -> sqlx::Result<()> { + sqlx::query("DELETE FROM pyo.source_uploads WHERE id = $1") + .bind(id) + .execute(db) + .await?; + Ok(()) +} + +/// A deployment that's done (or cancelled) doesn't need its upload. +pub async fn drop_for(db: impl sqlx::PgExecutor<'_>, deployment_id: &str) -> sqlx::Result<()> { + sqlx::query("DELETE FROM pyo.source_uploads WHERE deployment_id = $1") + .bind(deployment_id) + .execute(db) + .await?; + Ok(()) +} + +/// Uploads past their time, sent or not. +pub async fn sweep(db: &PgPool) -> sqlx::Result { + Ok( + sqlx::query("DELETE FROM pyo.source_uploads WHERE expires_at < now()") + .execute(db) + .await? + .rows_affected(), + ) +} + +/// The upload of a build this builder is running. +async fn job_upload( + s: &AppState, + b: &BuilderAuth, + job_id: &str, +) -> ApiResult { + let job: Option = sqlx::query_scalar( + "SELECT job FROM pyo.build_jobs WHERE id = $1 AND builder_id = $2 AND status = 'running'", + ) + .bind(job_id) + .bind(&b.id) + .fetch_optional(&s.db) + .await?; + let job = job.ok_or_else(|| { + ApiError::new( + StatusCode::GONE, + "This build isn't running any more (cancelled?).", + ) + })?; + serde_json::from_value(job["sourceUpload"].clone()) + .map_err(|_| ApiError::bad_request("This build has no uploaded folder.")) +} + +/// GET /api/builder/v1/jobs/{id}/source: the archive, streamed from its +/// parts in order. +async fn fetch( + State(s): State, + b: BuilderAuth, + Path(job_id): Path, +) -> ApiResult { + let up = job_upload(&s, &b, &job_id).await?; + let count = part_count(up.size); + let have = received(&s.db, &up.id).await?; + if have.len() as u64 != count { + return Err(ApiError::new( + StatusCode::GONE, + "The uploaded folder is no longer in Pyo. Deploy it again.", + )); + } + let (db, id) = (s.db.clone(), up.id.clone()); + let parts = futures::stream::unfold(0u64, move |n| { + let (db, id) = (db.clone(), id.clone()); + async move { + if n >= count { + return None; + } + let r: Result, sqlx::Error> = sqlx::query_scalar( + "SELECT data FROM pyo.source_upload_parts WHERE upload_id = $1 AND n = $2", + ) + .bind(&id) + .bind(n as i32) + .fetch_one(&db) + .await; + Some((r.map(Bytes::from).map_err(std::io::Error::other), n + 1)) + } + }); + Response::builder() + .header(header::CONTENT_TYPE, "application/gzip") + .header(header::CONTENT_LENGTH, up.size) + .header("x-pyo-sha256", &up.sha256) + .body(Body::from_stream(parts)) + .map_err(|e| ApiError::from(anyhow::Error::from(e))) +} + +/// DELETE /api/builder/v1/jobs/{id}/source: the builder has the archive, +/// so Pyo lets it go. +async fn fetched( + State(s): State, + b: BuilderAuth, + Path(job_id): Path, +) -> ApiResult> { + let up = job_upload(&s, &b, &job_id).await?; + delete(&s.db, &up.id).await?; + Ok(Json(json!({ "ok": true }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parts_cover_the_archive() { + assert_eq!(part_count(1), 1); + assert_eq!(part_count(PART_SIZE), 1); + assert_eq!(part_count(PART_SIZE + 1), 2); + assert_eq!(part_len(PART_SIZE + 1, 0), Some(PART_SIZE)); + assert_eq!(part_len(PART_SIZE + 1, 1), Some(1)); + assert_eq!(part_len(PART_SIZE + 1, 2), None); + assert_eq!(part_len(10, 0), Some(10)); + } + + #[test] + fn labels_are_short_and_plain() { + assert_eq!(label("my\napp\u{1b}[31m"), "myapp[31m"); + assert_eq!(label(&"x".repeat(300)).len(), 100); + assert_eq!(mb(500_000_000), "500 MB"); + assert_eq!(mb(1), "1 MB"); + } + + fn state(db: PgPool) -> AppState { + let config = crate::Config { + agent_api_url: String::new(), + agent_image: String::new(), + waf_image: String::new(), + geoip_image: String::new(), + cookie_secure: false, + allow_signup: false, + builder_image: String::new(), + relay_addr: None, + }; + let (_stop, stopping) = tokio::sync::watch::channel(false); + AppState { + db: db.clone(), + config: std::sync::Arc::new(config), + observability: crate::observability::Observability::from_env(db), + sealer: std::sync::Arc::new(crate::secrets::Sealer::for_tests()), + wakers: Default::default(), + terminals: Default::default(), + stopping, + } + } + + /// Against a throwaway Postgres (DATABASE_URL): a developer uploads a + /// folder in parts (one sent twice), completes it, and deploys it; the + /// build job names it; the builder running the job fetches exactly the + /// archive and lets it go, and Pyo deletes it. A deploy without an + /// upload reuses the image built last; a viewer can't upload. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn a_folder_goes_through_pyo_to_the_builder() { + use axum::http::{Method, Request}; + use sha2::Digest; + use tower::ServiceExt as _; + + let db = PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + let run = crate::ids::random_string(8).to_lowercase(); + let id = |p: &str| format!("{p}_{run}"); + let (team, cluster, project, svc) = (id("team"), id("cl"), id("prj"), id("svc")); + let q = |sql: &'static str| sqlx::query(sql); + let user = |uid: String| crate::auth::User { + id: uid.clone(), + name: uid, + email: String::new(), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + for u in [id("usr"), id("view")] { + q("INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $1 || '@t.test', $1, '')").bind(&u).execute(&db).await.unwrap(); + } + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&db) + .await + .unwrap(); + for (u, role) in [(id("usr"), "developer"), (id("view"), "viewer")] { + q("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1 || 'm', $2, $1, $1 || '@t.test', $3, 'active')").bind(&u).bind(&team).bind(role).execute(&db).await.unwrap(); + } + q("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(&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 spec = json!({ + "name": "web", "source": { "type": "upload", "dockerfilePath": "Dockerfile", "buildContext": ".", "buildArgs": [] }, + "env": [], "replicas": 1, + "resources": { "cpuRequest": 100, "cpuLimit": 500, "memoryRequest": 128, "memoryLimit": 256 }, + "healthCheck": { "type": "tcp", "path": "", "port": 8080, "command": "", "initialDelaySeconds": 10, "periodSeconds": 10, "auto": "default" }, + "ports": [{ "id": "port_1", "name": "http", "containerPort": 8080, "protocol": "HTTP", "exposure": "internal" }], + "domains": [], + }); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web', $5, 'stopped')").bind(&svc).bind(&team).bind(&project).bind(&cluster).bind(&spec).execute(&db).await.unwrap(); + let token = format!("tok{run}"); + q("INSERT INTO pyo.builders (id, team_id, name, kind, cluster_id, server, token_hash, status) VALUES ($1, $2, $1, 'cluster', $3, 's', $4, 'ready')") + .bind(id("bld")).bind(&team).bind(&cluster).bind(crate::ids::sha256_hex(&token)).execute(&db).await.unwrap(); + let s = state(db.clone()); + let dev = user(id("usr")); + + // An archive of two parts and a bit. + let mut archive = vec![0u8; (PART_SIZE * 2 + 5) as usize]; + rand::fill(&mut archive[..]); + let sha = hex::encode(sha2::Sha256::digest(&archive)); + let new = |sha: &str| NewSourceUpload { + team_id: team.clone(), + size: archive.len() as u64, + sha256: sha.to_owned(), + files: 2, + folder: "shop".into(), + machine: "laptop\n".into(), + }; + let e = create( + State(s.clone()), + SessionUser(user(id("view"))), + Json(new(&sha)), + ) + .await + .unwrap_err(); + assert_eq!(e.status, StatusCode::FORBIDDEN, "viewers can't upload"); + let started = create(State(s.clone()), SessionUser(dev.clone()), Json(new(&sha))) + .await + .unwrap() + .0; + assert_eq!(started["parts"], 3); + let up = started["uploadId"].as_str().unwrap().to_owned(); + let chunk = |n: usize| { + Bytes::copy_from_slice( + &archive[n * PART_SIZE as usize..((n + 1) * PART_SIZE as usize).min(archive.len())], + ) + }; + let send = |n: usize, b: Bytes| { + part( + State(s.clone()), + SessionUser(dev.clone()), + Path((up.clone(), n as u64)), + b, + ) + }; + assert_eq!( + send(0, Bytes::from_static(b"short")) + .await + .unwrap_err() + .status, + StatusCode::BAD_REQUEST + ); + assert_eq!( + send(3, chunk(2)).await.unwrap_err().status, + StatusCode::BAD_REQUEST + ); + send(0, chunk(0)).await.unwrap(); + send(2, chunk(2)).await.unwrap(); + // Not all there yet. + let st = status(State(s.clone()), SessionUser(dev.clone()), Path(up.clone())) + .await + .unwrap() + .0; + assert_eq!(st["received"], json!([0, 2])); + assert!( + complete(State(s.clone()), SessionUser(dev.clone()), Path(up.clone())) + .await + .is_err() + ); + send(1, chunk(1)).await.unwrap(); + send(1, chunk(1)).await.unwrap(); + complete(State(s.clone()), SessionUser(dev.clone()), Path(up.clone())) + .await + .unwrap(); + + // A wrong checksum: refused, and the upload is gone. + let bad = create( + State(s.clone()), + SessionUser(dev.clone()), + Json(new(&"0".repeat(64))), + ) + .await + .unwrap() + .0; + let bad = bad["uploadId"].as_str().unwrap().to_owned(); + for n in 0..3 { + part( + State(s.clone()), + SessionUser(dev.clone()), + Path((bad.clone(), n)), + chunk(n as usize), + ) + .await + .unwrap(); + } + assert_eq!( + complete( + State(s.clone()), + SessionUser(dev.clone()), + Path(bad.clone()) + ) + .await + .unwrap_err() + .status, + StatusCode::BAD_REQUEST + ); + assert!( + status(State(s.clone()), SessionUser(dev.clone()), Path(bad)) + .await + .is_err() + ); + + // Deployed: the build job names it, the deployment says where it came from. + let dep = id("dpl"); + let mut tx = db.begin().await.unwrap(); + crate::deploy::create( + &mut tx, + crate::deploy::DeployRequest { + deployment_id: &dep, + service_id: &svc, + trigger: "manual", + actor: "t", + rollback_of: None, + retry_of: None, + commit: None, + upload: Some(&up), + }, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + let (job_id, job): (String, Value) = + sqlx::query_as("SELECT id, job FROM pyo.build_jobs WHERE deployment_id = $1") + .bind(&dep) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(job["sourceUpload"]["id"], json!(up)); + assert_eq!(job["repoUrl"], ""); + let data: Value = sqlx::query_scalar("SELECT data FROM pyo.deployments WHERE id = $1") + .bind(&dep) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!( + ( + data["source"]["type"].as_str(), + data["source"]["machine"].as_str() + ), + (Some("upload"), Some("laptop")) + ); + assert_eq!(data["revisionLabel"], json!(&sha[..7])); + // Used once. + let mut tx = db.begin().await.unwrap(); + assert!(claim(&mut tx, &up, &team, "dpl_other").await.is_err()); + tx.rollback().await.unwrap(); + + // The builder: only while it runs the job. + let app = axum::Router::new() + .nest( + "/api/builder/v1", + crate::builders::routes().merge(builder_routes()), + ) + .with_state(s.clone()); + let call = |method: Method, path: String| { + let app = app.clone(); + let token = token.clone(); + async move { + let req = Request::builder() + .method(method) + .uri(path) + .header("authorization", format!("Bearer {token}")) + .body(Body::empty()) + .unwrap(); + let res = app.oneshot(req).await.unwrap(); + let st = res.status(); + ( + st, + axum::body::to_bytes(res.into_body(), 64 << 20) + .await + .unwrap(), + ) + } + }; + let path = format!("/api/builder/v1/jobs/{job_id}/source"); + assert_eq!( + call(Method::GET, path.clone()).await.0, + StatusCode::GONE, + "not claimed yet" + ); + q("UPDATE pyo.build_jobs SET status = 'running', builder_id = $2 WHERE id = $1") + .bind(&job_id) + .bind(id("bld")) + .execute(&db) + .await + .unwrap(); + let (st, body) = call(Method::GET, path.clone()).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body.len(), archive.len()); + assert!(body == archive, "the same bytes"); + assert_eq!(call(Method::DELETE, path.clone()).await.0, StatusCode::OK); + let left: i64 = + sqlx::query_scalar("SELECT count(*) FROM pyo.source_upload_parts WHERE upload_id = $1") + .bind(&up) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(left, 0, "deleted from Pyo once the builder has it"); + assert_eq!( + call(Method::GET, path).await.0, + StatusCode::GONE, + "gone once fetched" + ); + + // Built: deployed again without a folder, the image built last. + let image = format!( + "{}/pyo/services/{svc}@sha256:{}", + crate::deploy::registry().pull, + "a".repeat(64) + ); + q("UPDATE pyo.build_jobs SET status = 'succeeded' WHERE id = $1") + .bind(&job_id) + .execute(&db) + .await + .unwrap(); + q("UPDATE pyo.deployments SET status = 'succeeded', spec = spec || jsonb_build_object('image', $2::text) WHERE id = $1").bind(&dep).bind(&image).execute(&db).await.unwrap(); + q("UPDATE pyo.services SET current_deployment_id = $2 WHERE id = $1") + .bind(&svc) + .bind(&dep) + .execute(&db) + .await + .unwrap(); + let again = id("dpla"); + let mut tx = db.begin().await.unwrap(); + crate::deploy::create( + &mut tx, + crate::deploy::DeployRequest { + deployment_id: &again, + service_id: &svc, + trigger: "redeploy", + actor: "t", + rollback_of: None, + retry_of: None, + commit: None, + upload: None, + }, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + let (spec, data): (Value, Value) = + sqlx::query_as("SELECT spec, data FROM pyo.deployments WHERE id = $1") + .bind(&again) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(spec["image"], json!(image)); + assert_eq!(data["source"]["folder"], "shop"); + let jobs: i64 = + sqlx::query_scalar("SELECT count(*) FROM pyo.build_jobs WHERE deployment_id = $1") + .bind(&again) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(jobs, 0, "nothing to build"); + + // Expired uploads go. + let old = create(State(s.clone()), SessionUser(dev.clone()), Json(new(&sha))) + .await + .unwrap() + .0; + q("UPDATE pyo.source_uploads SET expires_at = now() - interval '1 minute' WHERE id = $1") + .bind(old["uploadId"].as_str().unwrap()) + .execute(&db) + .await + .unwrap(); + assert!(sweep(&db).await.unwrap() >= 1); + + q("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + for u in [id("usr"), id("view")] { + q("DELETE FROM pyo.users WHERE id = $1") + .bind(u) + .execute(&db) + .await + .unwrap(); + } + } +} diff --git a/crates/pyo-api/src/tailscale.rs b/crates/pyo-api/src/tailscale.rs index d3b64c19..6eb1370d 100644 --- a/crates/pyo-api/src/tailscale.rs +++ b/crates/pyo-api/src/tailscale.rs @@ -1,23 +1,34 @@ -//! Tailscale: the installation's OAuth client (Integrations › Tailscale) and -//! what Pyo does with it. +//! Tailscale, through each cluster's agent (pyo-proto's tailscale.rs). //! -//! - **The client** is installation-wide, set by an admin, kept sealed in -//! `pyo.settings` ('tailscale'). Only this process uses it. Scopes: -//! `devices:core` and `auth_keys` (both with `tag:pyo`), and `services`. -//! - **Joining**: each join command carries a fresh auth key from it: -//! single-use, preauthorized, `tag:pyo`, for an hour ([`join_key`]). +//! Every cluster keeps its own OAuth client, as a Secret in its pyo-system. +//! Pyo never holds a Tailscale credential: it passes a pasted token or +//! client to the cluster's agent in a signed command, and keeps only what +//! isn't secret (`pyo.clusters.tailscale`: the client's ID and hint, the +//! tailnet's suffix, Pyo's own names there, what the last sync said). +//! +//! - **Setup** ([`plan`], [`set_up`], [`save_client`]): the agent sets +//! the tailnet up and keeps the client. One per cluster: a cluster added +//! later gets its own from a freshly pasted token. +//! - **Joining** ([`join_key`]): the cluster's agent makes a single-use, +//! short-lived key. Pyo puts it into the join command and wipes it. //! - **Names on the tailnet** are Tailscale Services ("svc:blog" is -//! "blog..ts.net"): Pyo's own (`pyo`, `registry`) on the cluster -//! it runs on, and services' tailnet domains on theirs. [`tick`] keeps -//! them as the domains say: makes each (marked with this installation's -//! ID, [`marker`]), approves the cluster's servers as its hosts, deletes -//! the ones no longer used, and never touches one it didn't make. The -//! servers do the rest (the agent's tailnet.rs). - -use std::collections::{BTreeMap, BTreeSet}; -use std::sync::{Mutex, OnceLock}; -use std::time::{Duration, Instant}; - +//! "blog..ts.net"): Pyo's own (`pyo`, `registry`, `sandboxes`) +//! on the cluster it runs on, and services' tailnet domains on theirs. +//! [`tick`] sends each cluster what it should have +//! ([`pyo_proto::Command::TailscaleSync`]) when that changes, and +//! [`synced`] keeps what came back. The servers do the rest (the agent's +//! tailnet.rs). +//! - **Before this** the installation kept one client in `pyo.settings`. +//! [`hand_over`] passes it to the agent of the cluster Pyo runs on once, +//! then deletes it. + +use std::collections::BTreeSet; +use std::time::Duration; + +use pyo_proto::tailscale::{ + self as ts, LockWaiting, OwnName, SyncServer, TailnetSync, TailnetSynced, +}; +use pyo_proto::{Command, CommandResult}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sqlx::PgPool; @@ -25,55 +36,112 @@ use sqlx::PgPool; use crate::AppState; use crate::error::{ApiError, ApiResult}; -pub(crate) const API: &str = "https://api.tailscale.com/api/v2"; -/// The tag Pyo's servers and Services carry. -pub const TAG: &str = "tag:pyo"; -/// Names Pyo keeps for itself: services' domains can't take them. -pub const RESERVED: [&str; 3] = ["pyo", "registry", "sandboxes"]; +pub use ts::RESERVED; + /// Why a join or connect command can't be made yet. -pub const NEEDED: &str = "Servers join over your tailnet. Set up Tailscale in Integrations first."; +pub const NEEDED: &str = "Servers join over your tailnet. Set up Tailscale on the cluster first."; + +/// A pasted API access token: never printed, and passed on to the +/// cluster's agent as it is. +#[derive(Deserialize)] +#[serde(transparent)] +pub struct Token(String); + +impl Token { + pub fn into_inner(self) -> String { + self.0 + } +} -/// The saved client, and Pyo's own names on the tailnet. +impl std::fmt::Debug for Token { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Token(•••)") + } +} + +/// A cluster's Tailscale, as Pyo keeps it (`pyo.clusters.tailscale`). +/// Nothing in it is secret. #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] -pub struct Settings { +pub struct Tailnet { pub client_id: String, - pub secret_sealed: String, /// The secret's last characters, to tell it apart. + #[serde(default)] pub hint: String, - /// The dashboard's name ("pyo"), once picked or set. + /// The tailnet's MagicDNS suffix ("tail1234.ts.net"), as last seen. + #[serde(default)] + pub suffix: Option, + /// Pyo's own names, on the cluster Pyo runs on. #[serde(default)] pub dashboard_name: Option, - /// The registry's name ("registry"). #[serde(default)] pub registry_name: Option, - /// Sandboxes' web pages' name ("sandboxes"). Picked again by itself - /// when someone else has it on the tailnet. #[serde(default)] pub sandboxes_name: Option, - /// The tailnet's MagicDNS suffix ("tail1234.ts.net"), as last seen. #[serde(default)] - pub suffix: Option, + pub lock_waiting: Vec, + /// Pyo's machines on the tailnet, as last seen. + #[serde(default)] + pub machines: Vec, + /// Machines to take off the tailnet with the next sync. + #[serde(default)] + pub forget: Vec, + /// Older marks that are this cluster's too ([`hand_over`]). + #[serde(default)] + pub adopt: Vec, + /// What the last sync asked for (its hash), and when (ms). + #[serde(default)] + pub sent: String, + #[serde(default)] + pub sent_at: i64, + /// The last sync failed: tailnet domains it didn't make yet say so. + #[serde(default)] + pub sync_failed: bool, } -pub async fn settings(db: &PgPool) -> ApiResult> { - let v: Option = - sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'tailscale'") +/// A cluster's Tailscale, when it has one. +pub async fn of<'e>(db: impl sqlx::PgExecutor<'e>, cluster_id: &str) -> ApiResult> { + let v: Option> = + sqlx::query_scalar("SELECT tailscale FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) .fetch_optional(db) .await?; - Ok(v.and_then(|v| serde_json::from_value(v).ok())) + Ok(v.flatten().and_then(|v| serde_json::from_value(v).ok())) } -pub async fn save(db: &PgPool, s: &Settings) -> ApiResult<()> { - sqlx::query("INSERT INTO pyo.settings (key, value) VALUES ('tailscale', $1) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()") - .bind(serde_json::to_value(s).map_err(anyhow::Error::from)?) +/// Merges `fields` into a cluster's Tailscale, when it has one. +async fn patch<'e>( + db: impl sqlx::PgExecutor<'e>, + cluster_id: &str, + fields: Value, +) -> ApiResult<()> { + sqlx::query("UPDATE pyo.clusters SET tailscale = tailscale || $2::jsonb WHERE id = $1 AND tailscale IS NOT NULL") + .bind(cluster_id) + .bind(fields) .execute(db) .await?; Ok(()) } +/// The cluster Pyo runs on (self-hosted). +pub async fn host_cluster(db: &PgPool) -> ApiResult> { + Ok(sqlx::query_scalar( + "SELECT id FROM pyo.clusters WHERE same_cluster ORDER BY created_at LIMIT 1", + ) + .fetch_optional(db) + .await?) +} + +/// The Tailscale of the cluster Pyo runs on: the installation's tailnet. +pub async fn host(db: &PgPool) -> ApiResult> { + let Some(id) = host_cluster(db).await? else { + return Ok(None); + }; + Ok(of(db, &id).await?.map(|t| (id, t))) +} + /// This installation's ID (made once, kept with Pyo's data, so a restore -/// keeps it): what marks the Services it made. +/// keeps it): part of what marks the Services Pyo made. pub async fn install_id(db: &PgPool) -> ApiResult { let id = format!("{:032x}", rand::random::()); sqlx::query("INSERT INTO pyo.settings (key, value) VALUES ('install', jsonb_build_object('id', $1::text)) ON CONFLICT (key) DO NOTHING") @@ -87,672 +155,520 @@ pub async fn install_id(db: &PgPool) -> ApiResult { Ok(v) } -/// What a Service Pyo made says about itself (its comment). -pub fn marker(install: &str) -> String { - format!("Made by Pyo ({install})") -} - -// ── The API ───────────────────────────────────────────────────────────────── - -pub(crate) fn http() -> &'static reqwest::Client { - static C: OnceLock = OnceLock::new(); - C.get_or_init(|| { - reqwest::Client::builder() - .user_agent("pyo") - .timeout(Duration::from_secs(30)) - .build() - .expect("http client") - }) +/// What marks the Services a cluster makes, and the older marks it counts +/// as its own too. +async fn marks(db: &PgPool, cluster_id: &str, t: &Tailnet) -> ApiResult> { + let install = install_id(db).await?; + let mut out = vec![ts::marker(&install, cluster_id)]; + out.extend(t.adopt.iter().cloned()); + Ok(out) } -/// The OAuth client, with its access token while it lasts. -pub struct Client { - /// The API ("https://api.tailscale.com/api/v2"; a mock in tests). - base: String, - id: String, - secret: String, - token: Mutex>, -} +// ── Asking the agent ──────────────────────────────────────────────────────── -/// One per client ID and secret, so tokens are reused. -pub fn client(id: &str, secret: &str) -> std::sync::Arc { - static C: Mutex>> = Mutex::new(None); - let mut g = C.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(c) = g.as_ref().filter(|c| c.id == id && c.secret == secret) { - return c.clone(); +/// Sends a command to a cluster's agent and waits for its answer, up to +/// `wait`. A command the agent couldn't carry out is a 400 with its words. +pub(crate) async fn ask( + s: &AppState, + cluster_id: &str, + command: Command, + wait: Duration, +) -> ApiResult<(String, CommandResult)> { + let status: Option = + sqlx::query_scalar("SELECT status FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_optional(&s.db) + .await?; + match status.as_deref() { + None => return Err(ApiError::not_found("Cluster")), + Some("connected" | "degraded") => {} + Some(_) => { + return Err(ApiError::conflict( + "The cluster's agent isn't connected. Check the cluster first.", + )); + } } - let c = std::sync::Arc::new(Client { - id: id.to_owned(), - secret: secret.to_owned(), - token: Mutex::new(None), - base: API.to_owned(), - }); - *g = Some(c.clone()); - c -} - -#[cfg(test)] -fn test_client(base: &str) -> Client { - Client { - base: base.to_owned(), - id: "id".into(), - secret: "secret".into(), - token: Mutex::new(None), + let mut tx = s.db.begin().await?; + let id = crate::deploy::enqueue(&mut tx, cluster_id, command).await?; + tx.commit().await?; + s.wake(cluster_id).await; + let deadline = tokio::time::Instant::now() + wait; + loop { + let row: Option<(String, Option)> = + sqlx::query_as("SELECT status, result FROM pyo.commands WHERE id = $1") + .bind(&id) + .fetch_optional(&s.db) + .await?; + if let Some((status, result)) = row + && (status == "done" || status == "failed") + { + let r: CommandResult = result + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default(); + if !r.ok { + return Err(ApiError::bad_request( + r.message + .unwrap_or_else(|| "The cluster's agent couldn't do it.".into()), + )); + } + return Ok((id, r)); + } + if tokio::time::Instant::now() > deadline { + abandon(&s.db, &id).await; + return Err(ApiError::new( + axum::http::StatusCode::GATEWAY_TIMEOUT, + "The cluster's agent didn't answer in time. Is it connected?", + )); + } + tokio::time::sleep(Duration::from_millis(300)).await; } } -/// What a wanted name is on the tailnet. -#[derive(Debug, PartialEq)] -pub enum Claim { - /// Pyo's (made by this installation): its addresses. - Ours(Vec), - /// Someone else's, or one Pyo can't read. - Taken, -} - -/// A wanted name: Pyo's own Service, made now if there's none by that name -/// at all. Read directly first, whatever the list said: a name that -/// exists and isn't marked as this installation's is never written. -pub async fn claim(c: &Client, name: &str, mark: &str) -> anyhow::Result { - match c.service(name).await? { - Some((comment, addrs)) if comment == mark => Ok(Claim::Ours(addrs)), - Some(_) => Ok(Claim::Taken), - None => { - let addrs = c.create_service(name, mark).await?; - tracing::info!(name, "tailnet name made"); - Ok(Claim::Ours(addrs)) +/// A command no one waits for any more: not sent yet, it never is. Sent, +/// its secrets are blanked in Pyo's copy. +async fn abandon(db: &PgPool, id: &str) { + let r = async { + sqlx::query("DELETE FROM pyo.commands WHERE id = $1 AND status = 'pending'") + .bind(id) + .execute(db) + .await?; + let cmd: Option = + sqlx::query_scalar("SELECT command FROM pyo.commands WHERE id = $1") + .bind(id) + .fetch_optional(db) + .await?; + if let Some(mut cmd) = cmd + && crate::teambackup::wipe_command(&mut cmd) + { + sqlx::query("UPDATE pyo.commands SET command = $2 WHERE id = $1") + .bind(id) + .bind(cmd) + .execute(db) + .await?; } + Ok::<_, sqlx::Error>(()) + }; + if let Err(e) = r.await { + tracing::warn!(%id, error = %e, "couldn't drop an unanswered command"); } } -/// Deletes a Service only if its own record has this installation's mark. -pub async fn delete_if_ours(c: &Client, name: &str, mark: &str) -> anyhow::Result { - match c.service(name).await? { - Some((comment, _)) if comment == mark => { - c.delete_service(name).await?; - Ok(true) - } - _ => Ok(false), +/// A command whose answer carried something secret (a join key, a sandbox +/// token): gone once read. +pub(crate) async fn forget_command(db: &PgPool, id: &str) { + if let Err(e) = sqlx::query("DELETE FROM pyo.commands WHERE id = $1") + .bind(id) + .execute(db) + .await + { + tracing::warn!(%id, error = %e, "couldn't delete an answered command"); } } -/// The saved client, opened. -pub async fn saved_client(s: &AppState) -> ApiResult)>> { - let Some(cfg) = settings(&s.db).await? else { - return Ok(None); +/// Only the team's admins set Tailscale up on its cluster. +pub async fn require_cluster_admin( + s: &AppState, + user: &crate::auth::User, + cluster_id: &str, +) -> ApiResult<()> { + let team: String = sqlx::query_scalar("SELECT team_id FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_optional(&s.db) + .await? + .ok_or_else(|| ApiError::not_found("Cluster"))?; + let mut tx = s.db.begin().await?; + crate::ops::require_role(&mut tx, user, &team, crate::ops::Role::Admin).await?; + Ok(()) +} + +// ── Setting up ────────────────────────────────────────────────────────────── + +/// The setup's commands carry the pasted token: checked for shape here, so +/// a wrong paste never leaves Pyo. +fn token_shape(token: &str) -> ApiResult<()> { + let s = token.trim(); + let why = if s.starts_with("tskey-client-") { + "That's an OAuth client secret. Paste an API access token, or set up with an OAuth client instead." + } else if s.starts_with("tskey-auth-") { + "That's an auth key. Paste an API access token. It starts with tskey-api-." + } else if !s.starts_with("tskey-api-") || s.len() < 20 || s.contains(char::is_whitespace) { + "Paste an API access token. It starts with tskey-api-." + } else { + return Ok(()); }; - let secret = s.sealer.open(&cfg.secret_sealed)?; - let c = client(&cfg.client_id, &secret); - Ok(Some((cfg, c))) + Err(ApiError::bad_request(why)) } -/// What Tailscale said, as people read it. -#[derive(Debug)] -pub struct TsError { - pub status: u16, - pub message: String, +/// How long the setup may take on the cluster. +const SETUP_WAIT: Duration = Duration::from_secs(90); + +/// planTailscaleSetup: what setting the cluster's tailnet up would change. +pub async fn plan(s: &AppState, cluster_id: &str, token: String) -> ApiResult { + token_shape(&token)?; + let (_, r) = ask( + s, + cluster_id, + Command::TailscaleSetup { + token, + version: None, + }, + SETUP_WAIT, + ) + .await?; + Ok(json!({ "ok": true, "plan": r.data.unwrap_or(Value::Null) })) } -impl std::fmt::Display for TsError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "Tailscale answered {}: {}", self.status, self.message) +/// setUpTailscale: sets the cluster's tailnet up as reviewed. Pyo keeps +/// the client's ID and hint the agent says it kept. +pub async fn set_up( + s: &AppState, + cluster_id: &str, + token: String, + version: &str, +) -> ApiResult { + token_shape(&token)?; + let (_, r) = ask( + s, + cluster_id, + Command::TailscaleSetup { + token, + version: Some(version.to_owned()), + }, + SETUP_WAIT, + ) + .await?; + let mut out = r.data.unwrap_or(Value::Null); + if let Some(c) = out.as_object_mut().and_then(|o| o.remove("client")) + && let Some(id) = c["clientId"].as_str() + { + let hint = c["hint"].as_str().unwrap_or(""); + keep_client(s, cluster_id, id, hint, None).await?; } + Ok(out) } -impl std::error::Error for TsError {} - -/// What Tailscale answered: its body, and the ETag when there's one. -pub(crate) struct Reply { - pub text: String, - pub etag: Option, +/// Saves the cluster's client as Pyo shows it. Another tailnet: Pyo's +/// names there are picked again. +async fn keep_client( + s: &AppState, + cluster_id: &str, + id: &str, + hint: &str, + suffix: Option, +) -> ApiResult<()> { + let mut t = of(&s.db, cluster_id).await?.unwrap_or_default(); + if t.suffix.is_some() && suffix.is_some() && t.suffix != suffix { + t.dashboard_name = None; + t.registry_name = None; + t.sandboxes_name = None; + } + t.client_id = id.to_owned(); + t.hint = hint.to_owned(); + t.suffix = suffix.or(t.suffix); + // Synced again now. + t.sent = String::new(); + sqlx::query("UPDATE pyo.clusters SET tailscale = $2 WHERE id = $1") + .bind(cluster_id) + .bind(serde_json::to_value(&t).map_err(anyhow::Error::from)?) + .execute(&s.db) + .await?; + Ok(()) } -/// Sends a request to Tailscale's API. Anything but a 2xx is a [`TsError`] -/// with Tailscale's own message, and status 0 when it couldn't be reached. -pub(crate) async fn send(req: reqwest::RequestBuilder) -> Result { - let r = req.send().await.map_err(|e| TsError { - status: 0, - message: format!("Couldn't reach Tailscale: {}", e.without_url()), - })?; - let status = r.status().as_u16(); - let etag = r - .headers() - .get(reqwest::header::ETAG) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let text = r.text().await.unwrap_or_default(); - if !(200..300).contains(&status) { - let message = serde_json::from_str::(&text) - .ok() - .and_then(|v| v["message"].as_str().map(str::to_owned)) - .unwrap_or_else(|| text.trim().chars().take(300).collect()); - return Err(TsError { status, message }); - } - Ok(Reply { text, etag }) +/// saveTailscale: the cluster uses this OAuth client, once it signs in. +/// The secret goes to the agent sealed and is never kept by Pyo. +pub async fn save_client( + s: &AppState, + cluster_id: &str, + client_id: &str, + secret: Option<&str>, +) -> ApiResult { + let Some(secret) = secret.map(str::trim).filter(|x| !x.is_empty()) else { + return Err(ApiError::bad_request("Paste the client secret too.")); + }; + let (_, r) = ask( + s, + cluster_id, + Command::TailscaleClient { + client_id: client_id.trim().to_owned(), + secret: secret.to_owned(), + }, + SETUP_WAIT, + ) + .await?; + let state: ts::ClientState = r + .data + .and_then(|d| serde_json::from_value(d).ok()) + .unwrap_or_default(); + keep_client( + s, + cluster_id, + &state.client_id, + &state.hint, + state.suffix.clone(), + ) + .await?; + Ok(json!({ "ok": state.ok, "checks": state.checks })) } -impl Client { - pub(crate) async fn access_token(&self) -> anyhow::Result { - if let Some((t, at)) = self.token.lock().unwrap_or_else(|e| e.into_inner()).clone() - && at.elapsed() < Duration::from_secs(45 * 60) - { - return Ok(t); - } - let r = http() - .post(format!("{}/oauth/token", self.base)) - .header( - reqwest::header::CONTENT_TYPE, - "application/x-www-form-urlencoded", - ) - .body( - reqwest::Url::parse_with_params( - "http://form/", - &[ - ("client_id", self.id.as_str()), - ("client_secret", self.secret.as_str()), - ], - )? - .query() - .unwrap_or("") - .to_owned(), - ) - .send() - .await?; - let status = r.status().as_u16(); - let body: Value = r.json().await.unwrap_or(Value::Null); - let Some(t) = body["access_token"].as_str().filter(|_| status == 200) else { - return Err(TsError { - status, - message: body["message"] - .as_str() - .or(body["error_description"].as_str()) - .or(body["error"].as_str()) - .unwrap_or("the client ID or secret isn't right") - .to_owned(), - } - .into()); - }; - *self.token.lock().unwrap_or_else(|e| e.into_inner()) = - Some((t.to_owned(), Instant::now())); - Ok(t.to_owned()) - } - - async fn call( - &self, - method: reqwest::Method, - path: &str, - body: Option<&Value>, - ) -> anyhow::Result { - let token = self.access_token().await?; - let mut req = http() - .request(method, format!("{}{path}", self.base)) - .bearer_auth(token); - if let Some(b) = body { - req = req.json(b); - } - let text = send(req).await?.text; - Ok(if text.trim().is_empty() { - Value::Null - } else { - serde_json::from_str(&text)? - }) - } - - /// The tailnet's Services: name ("blog") → (comment, addresses). - pub async fn services(&self) -> anyhow::Result)>> { - let v = self - .call(reqwest::Method::GET, "/tailnet/-/services", None) - .await?; - Ok(v["vipServices"] - .as_array() - .into_iter() - .flatten() - .filter_map(|s| { - let name = s["name"].as_str()?.strip_prefix("svc:")?.to_owned(); - Some(( - name, - ( - s["comment"].as_str().unwrap_or("").to_owned(), - strings(&s["addrs"]), - ), - )) - }) - .collect()) - } - - /// Make a Service: ports 80 and 443, tagged, marked as Pyo's. Its - /// addresses come back. - pub async fn create_service(&self, name: &str, comment: &str) -> anyhow::Result> { - let body = json!({ "name": format!("svc:{name}"), "comment": comment, "ports": ["tcp:80", "tcp:443"], "tags": [TAG] }); - let v = self - .call( - reqwest::Method::PUT, - &format!("/tailnet/-/services/svc:{name}"), - Some(&body), - ) - .await?; - Ok(strings(&v["addrs"])) - } - - /// One Service, read directly: its comment and addresses, or None when - /// there's no such Service (404). The list leaves some out (Tailscale's - /// API reference: it has the Services of the admin console's - /// "Advertised" tab, so not one defined and hosted nowhere). Any other - /// answer is an error, 403 included ("access to the Service is - /// forbidden"), so a name Pyo can't read is never taken. - /// - /// There's no create-only write: PUT creates or updates, with no - /// If-Match or If-None-Match for Services (only the policy file has - /// ETags). So this read is what keeps Pyo off Services it didn't make. - pub async fn service(&self, name: &str) -> anyhow::Result)>> { - match self - .call( - reqwest::Method::GET, - &format!("/tailnet/-/services/svc:{name}"), - None, - ) - .await - { - Ok(v) => Ok(Some(( - v["comment"].as_str().unwrap_or("").to_owned(), - strings(&v["addrs"]), - ))), - Err(e) if e.downcast_ref::().is_some_and(|t| t.status == 404) => Ok(None), - Err(e) => Err(e), - } - } - - pub async fn delete_service(&self, name: &str) -> anyhow::Result<()> { - self.call( - reqwest::Method::DELETE, - &format!("/tailnet/-/services/svc:{name}"), - None, - ) - .await - .map(|_| ()) - } - - /// A Service's hosts: node ID → approved. - pub async fn hosts(&self, name: &str) -> anyhow::Result> { - let v = self - .call( - reqwest::Method::GET, - &format!("/tailnet/-/services/svc:{name}/devices"), - None, - ) - .await?; - Ok(v["hosts"] - .as_array() - .into_iter() - .flatten() - .filter_map(|h| { - Some(( - h["stableNodeID"].as_str()?.to_owned(), - h["approvalLevel"] - .as_str() - .is_some_and(|l| l.starts_with("approved")), - )) - }) - .collect()) +/// The Test button: the cluster's client, check by check. +pub async fn test_saved(s: &AppState, cluster_id: &str) -> ApiResult { + if of(&s.db, cluster_id).await?.is_none() { + return Err(ApiError::bad_request( + "Tailscale isn't set up on this cluster.", + )); } - - pub async fn approve(&self, name: &str, node: &str) -> anyhow::Result<()> { - self.call( - reqwest::Method::POST, - &format!("/tailnet/-/services/svc:{name}/device/{node}/approved"), - Some(&json!({ "approved": true })), - ) - .await - .map(|_| ()) + let (_, r) = ask(s, cluster_id, Command::TailscaleTest {}, SETUP_WAIT).await?; + let state: ts::ClientState = r + .data + .and_then(|d| serde_json::from_value(d).ok()) + .unwrap_or_default(); + if let Some(x) = &state.suffix { + patch(&s.db, cluster_id, json!({ "suffix": x })).await?; } + Ok(json!({ "ok": state.ok, "checks": state.checks })) +} - /// The tailnet's machines: (node ID, full name, tags). - pub async fn devices(&self) -> anyhow::Result)>> { - let v = self - .call(reqwest::Method::GET, "/tailnet/-/devices", None) +/// Forgets the cluster's client: Pyo's names on its tailnet are deleted +/// while it still can, and its servers take them off. Pyo forgets it even +/// when the agent can't be reached. +pub async fn remove(s: &AppState, cluster_id: &str) -> ApiResult<()> { + let Some(t) = of(&s.db, cluster_id).await? else { + return Ok(()); + }; + let names: Vec = + sqlx::query_scalar("SELECT name FROM pyo.cluster_tailnet_names WHERE cluster_id = $1") + .bind(cluster_id) + .fetch_all(&s.db) .await?; - Ok(v["devices"] - .as_array() - .into_iter() - .flatten() - .filter_map(|d| { - Some(( - d["nodeId"].as_str()?.to_owned(), - d["name"] - .as_str() - .unwrap_or("") - .trim_end_matches('.') - .to_owned(), - strings(&d["tags"]), - )) - }) - .collect()) + let marks = marks(&s.db, cluster_id, &t).await?; + if let Err(e) = ask( + s, + cluster_id, + Command::TailscaleRemove { names, marks }, + SETUP_WAIT, + ) + .await + { + tracing::warn!(cluster = %cluster_id, error = %e.message, "the agent couldn't remove Tailscale; Pyo forgets it anyway"); } - - /// The tailnet's machines with what Pyo's cloud servers need: their - /// hostname, and their key while Tailnet Lock waits for its signature. - pub async fn device_details(&self) -> anyhow::Result> { - let v = self - .call( - reqwest::Method::GET, - "/tailnet/-/devices?fields=default", - None, - ) + sqlx::query("UPDATE pyo.cluster_tailnet_names SET retired_at = coalesce(retired_at, now()), updated_at = now() WHERE cluster_id = $1") + .bind(cluster_id) + .execute(&s.db) + .await?; + sqlx::query("UPDATE pyo.clusters SET tailscale = NULL WHERE id = $1") + .bind(cluster_id) + .execute(&s.db) + .await?; + if host_cluster(&s.db).await?.as_deref() == Some(cluster_id) { + // Without the tailnet, the public dashboard is the way in again. + sqlx::query("DELETE FROM pyo.settings WHERE key = 'public_dashboard'") + .execute(&s.db) .await?; - Ok(v["devices"] - .as_array() - .into_iter() - .flatten() - .filter_map(|d| { - Some(Device { - node_id: d["nodeId"].as_str()?.to_owned(), - hostname: d["hostname"].as_str().unwrap_or("").to_owned(), - tags: strings(&d["tags"]), - node_key: d["nodeKey"].as_str().unwrap_or("").to_owned(), - lock_error: d["tailnetLockError"].as_str().unwrap_or("").to_owned(), - }) - }) - .collect()) - } - - /// Takes a machine off the tailnet (only tag:pyo ones: the client's - /// Devices › Core scope is for that tag). - pub async fn delete_device(&self, node: &str) -> anyhow::Result<()> { - if node.is_empty() || !node.bytes().all(|b| b.is_ascii_alphanumeric()) { - anyhow::bail!("not a node ID"); - } - match self - .call(reqwest::Method::DELETE, &format!("/device/{node}"), None) - .await - { - Err(e) if e.downcast_ref::().is_some_and(|t| t.status == 404) => Ok(()), - r => r.map(|_| ()), + for k in ["tailnet", "registry", "sandboxes"] { + save_address(&s.db, k, None).await?; } } + Ok(()) +} - pub async fn tag(&self, node: &str) -> anyhow::Result<()> { - self.call( - reqwest::Method::POST, - &format!("/device/{node}/tags"), - Some(&json!({ "tags": [TAG] })), - ) - .await - .map(|_| ()) +/// Renames Pyo's own name on the tailnet ("dashboard", "registry" or +/// "sandboxes"), on the cluster Pyo runs on. The old one goes once the new +/// one is made. +pub async fn rename(s: &AppState, kind: &str, name: &str) -> ApiResult<()> { + let name = name.trim().to_ascii_lowercase(); + let Some((cluster_id, mut t)) = host(&s.db).await? else { + return Err(ApiError::bad_request("Tailscale isn't set up.")); + }; + if !ts::valid_name(&name) { + return Err(ApiError::bad_request( + "Use one name: lowercase letters, digits and dashes.", + )); } - - /// A single-use, preauthorized auth key with `tag:pyo`, for an hour: - /// (its ID, the key). - pub async fn auth_key(&self, description: &str) -> anyhow::Result<(String, String)> { - let body = json!({ - "capabilities": { "devices": { "create": { "reusable": false, "ephemeral": false, "preauthorized": true, "tags": [TAG] } } }, - "expirySeconds": 3600, - "description": key_description(description), - }); - let v = self - .call(reqwest::Method::POST, "/tailnet/-/keys", Some(&body)) - .await?; - match (v["id"].as_str(), v["key"].as_str()) { - (Some(id), Some(k)) => Ok((id.to_owned(), k.to_owned())), - _ => anyhow::bail!("Tailscale made no key"), + let others = match kind { + "dashboard" => [&t.registry_name, &t.sandboxes_name], + "registry" => [&t.dashboard_name, &t.sandboxes_name], + "sandboxes" => [&t.dashboard_name, &t.registry_name], + _ => { + return Err(ApiError::bad_request( + "The kind is \"dashboard\", \"registry\" or \"sandboxes\".", + )); } + }; + let domain: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.cluster_tailnet_names WHERE cluster_id = $1 AND name = $2 AND kind = 'domain' AND retired_at IS NULL)", + ) + .bind(&cluster_id) + .bind(&name) + .fetch_one(&s.db) + .await?; + if others.iter().any(|o| o.as_deref() == Some(name.as_str())) || domain { + return Err(ApiError::conflict("Pyo uses this name already.")); } - - pub async fn delete_key(&self, id: &str) -> anyhow::Result<()> { - self.call( - reqwest::Method::DELETE, - &format!("/tailnet/-/keys/{id}"), - None, - ) - .await - .map(|_| ()) + if peer_names(&s.db, &cluster_id).await?.contains(&name) + || check_name(s, &cluster_id, &t, &name).await? == "taken" + { + return Err(ApiError::conflict("Taken on your tailnet")); } + match kind { + "dashboard" => t.dashboard_name = Some(name), + "registry" => t.registry_name = Some(name), + _ => t.sandboxes_name = Some(name), + } + patch( + &s.db, + &cluster_id, + json!({ "dashboardName": t.dashboard_name, "registryName": t.registry_name, "sandboxesName": t.sandboxes_name, "sent": "" }), + ) + .await } -/// What Tailscale takes as a key's description: letters, digits, spaces, -/// dashes and underscores, at most 50 characters. "Pyo: join web-1" -/// becomes "Pyo join web-1". -pub(crate) fn key_description(s: &str) -> String { - let kept: String = s - .chars() - .filter(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')) - .collect(); - let mut out = kept.split_whitespace().collect::>().join(" "); - out.truncate(50); - out.trim_end().to_owned() -} - -/// A machine on the tailnet ([`Client::device_details`]). -#[derive(Debug, Clone, PartialEq)] -pub struct Device { - pub node_id: String, - pub hostname: String, - pub tags: Vec, - /// "nodekey:…" - pub node_key: String, - /// Set while Tailnet Lock waits for this machine's key to be signed. - pub lock_error: String, -} - -/// Pyo's machines (tag:pyo) that Tailnet Lock keeps out until a signing -/// device signs their key: their hostname, and the command that signs it. -pub fn lock_waiting(devices: &[Device]) -> Vec<(String, String)> { - devices - .iter() - .filter(|d| { - !d.lock_error.is_empty() - && d.node_key.starts_with("nodekey:") - && d.tags.iter().any(|t| t == TAG) - }) - .map(|d| { - ( - d.hostname.clone(), - format!("tailscale lock sign {}", d.node_key), - ) - }) - .collect() -} - -#[derive(Deserialize, utoipa::IntoParams)] -#[into_params(parameter_in = Query)] -pub struct LockQuery { - /// The team adding the server (slug or id). - team: String, +/// What a name is on the cluster's tailnet: "free", "ours" or "taken". +async fn check_name(s: &AppState, cluster_id: &str, t: &Tailnet, name: &str) -> ApiResult { + let marks = marks(&s.db, cluster_id, t).await?; + let unchecked = + || ApiError::bad_request("Couldn't check the name on your tailnet. Try again in a minute."); + let (_, r) = ask( + s, + cluster_id, + Command::TailscaleCheckName { + name: name.to_owned(), + marks, + }, + Duration::from_secs(30), + ) + .await + .map_err(|e| { + tracing::warn!(error = %e.message, "tailnet name check failed"); + unchecked() + })?; + let c: ts::NameCheck = r + .data + .and_then(|d| serde_json::from_value(d).ok()) + .ok_or_else(unchecked)?; + Ok(c.state) } -/// Machines waiting for a Tailnet Lock signature -/// -/// With Tailnet Lock on, a new server stays off the tailnet until a -/// signing device signs its key. These are the ones Pyo's commands added -/// that wait, with the command to run on a signing device. Read from -/// Tailscale at most every 15 seconds. Empty without Tailscale set up. -#[utoipa::path(get, path = "/tailnet/lock", operation_id = "getTailnetLock", tag = "Servers", - params(LockQuery), - responses( - (status = 200, description = "`waiting`: each with `name` (the machine's hostname) and `signCommand`.", body = Object), - (status = 403, description = "Only owners and admins add servers.", body = crate::error::ErrorBody), - (status = 404, description = "No such team, or you aren't in it.", body = crate::error::ErrorBody), - ), - extensions(("x-pyo-access" = json!("read"))))] -pub async fn lock( - axum::extract::State(s): axum::extract::State, - crate::auth::SessionUser(user): crate::auth::SessionUser, - crate::error::Query(q): crate::error::Query, -) -> ApiResult> { - let mut tx = s.db.begin().await?; - crate::ops::require_role(&mut tx, &user, &q.team, crate::ops::Role::Admin).await?; - drop(tx); - /// When the list was read, and what it said. - type Seen = Option<(Instant, Vec<(String, String)>)>; - static SEEN: Mutex = Mutex::new(None); - let fresh = |seen: &Seen| { - seen.as_ref() - .filter(|(at, _)| at.elapsed() < Duration::from_secs(15)) - .map(|(_, w)| w.clone()) +/// Whether a tailnet domain someone typed for a service on a cluster can be +/// had: Pyo's reserved names and its own names are refused, and so is a +/// name something else on the cluster's tailnet has. +pub async fn check_domain(s: &AppState, cluster_id: &str, host: &str) -> ApiResult<()> { + let Some(t) = of(&s.db, cluster_id).await? else { + return Err(ApiError::bad_request( + "Tailnet domains need Tailscale. Set it up on the cluster.", + )); }; - let cached = fresh(&SEEN.lock().unwrap_or_else(|e| e.into_inner())); - let waiting = match cached { - Some(w) => w, - None => { - let w = match saved_client(&s).await? { - Some((_, c)) => match c.device_details().await { - Ok(d) => lock_waiting(&d), - Err(e) => { - tracing::warn!(error = %e, "tailnet lock: couldn't read the tailnet"); - Vec::new() - } - }, - None => Vec::new(), - }; - *SEEN.lock().unwrap_or_else(|e| e.into_inner()) = Some((Instant::now(), w.clone())); - w - } + let Some(suffix) = t.suffix.as_deref() else { + return Err(ApiError::bad_request( + "Pyo hasn't seen the cluster's tailnet yet. Try again in a minute.", + )); }; - let waiting: Vec = waiting - .into_iter() - .map(|(name, sign)| json!({ "name": name, "signCommand": sign })) - .collect(); - Ok(crate::error::Json(json!({ "waiting": waiting }))) -} - -fn strings(v: &Value) -> Vec { - v.as_array() - .map(|a| { - a.iter() - .filter_map(|x| x.as_str().map(str::to_owned)) - .collect() - }) - .unwrap_or_default() -} - -/// "server-1.tail1234.ts.net" → "tail1234.ts.net". -pub fn suffix_of(name: &str) -> Option { - let (_, rest) = name.trim_end_matches('.').split_once('.')?; - rest.ends_with(".ts.net").then(|| rest.to_ascii_lowercase()) -} - -/// A name on the tailnet: one DNS label. -pub fn valid_name(n: &str) -> bool { - !n.is_empty() - && n.len() <= 63 - && n.bytes() - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') - && !n.starts_with('-') - && !n.ends_with('-') -} - -/// The first free name: `base`, then `base-`, then `base--2`… -/// One of Pyo's own names that it keeps up to date: the one it has while -/// that isn't `taken` (someone else's Service, a machine, or another of -/// Pyo's names), else the first free one [`pick_name`] finds. -pub fn own_name( - current: Option<&str>, - base: &str, - more: &str, - taken: impl Fn(&str) -> bool, -) -> String { - match current { - Some(n) if !n.is_empty() && !taken(n) => n.to_owned(), - _ => pick_name(base, more, taken), - } -} - -pub fn pick_name(base: &str, more: &str, taken: impl Fn(&str) -> bool) -> String { - let cut = |x: &str| { - x.chars() - .take(63) - .collect::() - .trim_end_matches('-') - .to_owned() + let host = host.to_ascii_lowercase(); + let Some(label) = host.strip_suffix(&format!(".{suffix}")) else { + return Err(ApiError::bad_request(format!( + "A tailnet domain on this cluster ends with .{suffix}." + ))); }; - let first = cut(base); - if !taken(&first) { - return first; + if !ts::valid_name(label) { + return Err(ApiError::bad_request( + "Use one name: lowercase letters, digits and dashes.", + )); } - let second = cut(&format!("{base}-{more}")); - if !taken(&second) { - return second; + if RESERVED.contains(&label) + || t.dashboard_name.as_deref() == Some(label) + || t.registry_name.as_deref() == Some(label) + || t.sandboxes_name.as_deref() == Some(label) + { + return Err(ApiError::bad_request("Pyo uses this name itself.")); } - (2..) - .map(|i| cut(&format!("{base}-{more}-{i}"))) - .find(|n| !taken(n)) - .unwrap_or_default() + if peer_names(&s.db, cluster_id).await?.contains(label) + || check_name(s, cluster_id, &t, label).await? == "taken" + { + return Err(ApiError::conflict("Taken on your tailnet")); + } + Ok(()) } -// ── Checking the client ───────────────────────────────────────────────────── +// ── Join keys ─────────────────────────────────────────────────────────────── -/// One check of the Test button. -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Check { - pub name: &'static str, - pub ok: bool, - pub message: String, +/// The cluster whose agent makes a key for a machine joining a tailnet: +/// `cluster_id`, once Tailscale is set up on it. Else the cluster Pyo runs +/// on (self-hosted: the installation's tailnet). +pub async fn key_cluster(db: &PgPool, cluster_id: Option<&str>) -> ApiResult { + if let Some(c) = cluster_id + && of(db, c).await?.is_some() + { + return Ok(c.to_owned()); + } + match host(db).await? { + Some((h, _)) => Ok(h), + None => Err(ApiError::bad_request(NEEDED)), + } } -/// What the client can do, check by check, saying what's missing. -pub async fn test(c: &Client) -> (Vec, Option) { - let mut out = Vec::new(); - let mut suffix = None; - if let Err(e) = c.access_token().await { - out.push(Check { - name: "client", - ok: false, - message: format!("Couldn't sign in with it. {e}"), - }); - return (out, None); - } - out.push(Check { - name: "client", - ok: true, - message: "Signed in.".into(), - }); - match c.devices().await { - Ok(d) => { - suffix = d.iter().find_map(|(_, n, _)| suffix_of(n)); - out.push(Check { - name: "devices", - ok: true, - message: "Can read the tailnet's machines.".into(), - }); +/// The cluster whose tailnet a team's new sandbox server joins: one of the +/// team's clusters with Tailscale (a connected one first), else the +/// cluster Pyo runs on. The installation's own servers join Pyo's. +pub async fn team_key_cluster(db: &PgPool, team_id: Option<&str>) -> ApiResult { + if let Some(t) = team_id { + let c: Option = sqlx::query_scalar( + "SELECT id FROM pyo.clusters WHERE team_id = $1 AND tailscale IS NOT NULL + ORDER BY status IN ('connected', 'degraded') DESC, created_at LIMIT 1", + ) + .bind(t) + .fetch_optional(db) + .await?; + if let Some(c) = c { + return Ok(c); } - Err(e) => out.push(Check { - name: "devices", - ok: false, - message: format!("Needs the Devices › Core scope with tag:pyo. {e}"), - }), - } - match c.services().await { - Ok(_) => out.push(Check { - name: "services", - ok: true, - message: "Can manage Services.".into(), - }), - Err(e) => out.push(Check { - name: "services", - ok: false, - message: format!("Needs the Services scope. {e}"), - }), } - match c.auth_key("Pyo test").await { - Ok((id, _)) => { - let _ = c.delete_key(&id).await; - out.push(Check { name: "authKeys", ok: true, message: "Can make auth keys with tag:pyo.".into() }); - } - Err(e) => out.push(Check { - name: "authKeys", - ok: false, - message: format!("Needs the Auth Keys scope with tag:pyo, and tag:pyo in the tailnet policy's tagOwners. {e}"), - }), + key_cluster(db, None).await +} + +/// A join command's auth key, from the cluster's agent: single-use, +/// preauthorized, tag:pyo, an hour. Pyo keeps it only to put it in the +/// command. `server` names what's being added, e.g. "a sandbox server". +pub async fn join_key( + s: &AppState, + cluster_id: &str, + what: &str, + server: &'static str, +) -> ApiResult { + if of(&s.db, cluster_id).await?.is_none() { + return Err(ApiError::bad_request(NEEDED)); } - (out, suffix) + let (id, r) = ask( + s, + cluster_id, + Command::TailscaleKey { + description: what.to_owned(), + }, + Duration::from_secs(30), + ) + .await + .map_err(|e| { + tracing::warn!(error = %e.message, "the cluster made no auth key"); + ApiError::bad_request(format!( + "Couldn't get a Tailscale key from the cluster to add {server}. Check Tailscale on it." + )) + })?; + forget_command(&s.db, &id).await; + r.data + .as_ref() + .and_then(|d| d[ts::KEY_FIELD].as_str()) + .map(str::to_owned) + .ok_or_else(|| ApiError::bad_request("Tailscale made no auth key.")) } -// ── Keeping the Services ──────────────────────────────────────────────────── +// ── Keeping the names ─────────────────────────────────────────────────────── pub async fn runner(state: AppState) { loop { let st = state.clone(); crate::bg::as_leader(&state.db, crate::bg::LOCK_TAILSCALE, || async move { + if let Err(e) = hand_over(&st).await { + tracing::warn!(error = %e.message, "tailscale hand-over"); + } if let Err(e) = tick(&st).await { tracing::warn!(error = %format!("{e:?}"), "tailscale"); } @@ -804,340 +720,460 @@ pub async fn save_address(db: &PgPool, key: &str, host: Option<&str>) -> ApiResu Ok(()) } -/// The tailnet's machines as Pyo's servers see them (their tailscaled's -/// peers): the API's device list only shows what the client's tags allow. -async fn peer_names(db: &PgPool) -> ApiResult> { - Ok(servers(db) - .await? - .into_iter() - .flat_map(|s| s.status.peers) - .collect()) -} - -/// A server's Tailscale as its cluster last reported it. -#[derive(Debug, Clone)] -struct Server { - cluster_id: String, - status: pyo_proto::ServerTailnet, -} - -async fn servers(db: &PgPool) -> ApiResult> { - let rows: Vec<(String, Value)> = sqlx::query_as( - "SELECT id, coalesce(capabilities->'tailnet', '[]') FROM pyo.clusters WHERE status <> 'disconnected'", +/// A cluster's servers' Tailscale, as it last reported them. +async fn servers(db: &PgPool, cluster_id: &str) -> ApiResult> { + let v: Option = sqlx::query_scalar( + "SELECT coalesce(capabilities->'tailnet', '[]') FROM pyo.clusters WHERE id = $1", ) - .fetch_all(db) + .bind(cluster_id) + .fetch_optional(db) .await?; - Ok(rows + Ok(v.and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default()) +} + +/// The tailnet's machines as the cluster's servers see them (their +/// tailscaled's peers): the API's device list only shows what the client's +/// tags allow. +async fn peer_names(db: &PgPool, cluster_id: &str) -> ApiResult> { + Ok(servers(db, cluster_id) + .await? .into_iter() - .flat_map(|(cluster_id, v)| { - serde_json::from_value::>(v) - .unwrap_or_default() - .into_iter() - .map(move |status| Server { - cluster_id: cluster_id.clone(), - status, - }) - }) + .flat_map(|s| s.peers) .collect()) } -/// The names on the tailnet Pyo wants: (name, kind, cluster). -async fn wanted( +/// What a cluster's names on its tailnet should be. +async fn sync_for( db: &PgPool, - cfg: &Settings, - suffix: &str, -) -> ApiResult> { - let mut out = Vec::new(); - let host: Option = - sqlx::query_scalar("SELECT id FROM pyo.clusters WHERE same_cluster LIMIT 1") - .fetch_optional(db) + install: &str, + cluster_id: &str, + cluster_name: &str, + same_cluster: bool, + t: &Tailnet, +) -> ApiResult { + let more = crate::util::slugify(cluster_name); + let own = if same_cluster { + let o = |kind: &str, current: &Option, base: &str, keep: bool| OwnName { + kind: kind.into(), + current: current.clone(), + base: base.into(), + more: more.clone(), + keep, + }; + vec![ + o("dashboard", &t.dashboard_name, "pyo", true), + o("registry", &t.registry_name, "registry", true), + o("sandboxes", &t.sandboxes_name, "sandboxes", false), + ] + } else { + Vec::new() + }; + let mut domains: Vec = match &t.suffix { + Some(suffix) => { + let hosts: Vec = sqlx::query_scalar( + "SELECT lower(d->>'hostname') FROM pyo.services s, jsonb_array_elements(s.spec->'domains') d + WHERE s.cluster_id = $1 AND NOT s.deleting AND lower(d->>'hostname') LIKE '%.' || $2", + ) + .bind(cluster_id) + .bind(suffix) + .fetch_all(db) .await?; - if let Some(h) = &host { - if let Some(n) = &cfg.dashboard_name { - out.push((n.clone(), "dashboard", h.clone())); - } - if let Some(n) = &cfg.registry_name { - out.push((n.clone(), "registry", h.clone())); - } - if let Some(n) = &cfg.sandboxes_name { - out.push((n.clone(), "sandboxes", h.clone())); + hosts + .iter() + .filter_map(|h| h.strip_suffix(&format!(".{suffix}"))) + .filter(|l| ts::valid_name(l) && !RESERVED.contains(l)) + .map(str::to_owned) + .collect() } - } - let domains: Vec<(String, String)> = sqlx::query_as( - "SELECT s.cluster_id, lower(d->>'hostname') FROM pyo.services s, jsonb_array_elements(s.spec->'domains') d - WHERE NOT s.deleting AND lower(d->>'hostname') LIKE '%.' || $1", + None => Vec::new(), + }; + domains.sort(); + domains.dedup(); + let made: Vec = sqlx::query_scalar( + "SELECT name FROM pyo.cluster_tailnet_names WHERE cluster_id = $1 ORDER BY name", ) - .bind(suffix) + .bind(cluster_id) .fetch_all(db) .await?; - for (cluster, host) in domains { - if let Some(label) = host - .strip_suffix(&format!(".{suffix}")) - .filter(|l| valid_name(l)) - { - out.push((label.to_owned(), "domain", cluster)); - } - } - out.sort(); - out.dedup_by(|a, b| a.0 == b.0); - Ok(out) + let reported = servers(db, cluster_id).await?; + let mut peers: Vec = reported.iter().flat_map(|s| s.peers.clone()).collect(); + peers.sort(); + peers.dedup(); + let mut servers: Vec = reported + .into_iter() + .filter(|s| !s.node_id.is_empty()) + .map(|s| SyncServer { + server: s.server, + node_id: s.node_id, + advertised: s.advertised, + }) + .collect(); + servers.sort_by(|a, b| a.server.cmp(&b.server)); + let mut forget = t.forget.clone(); + forget.sort(); + forget.dedup(); + Ok(TailnetSync { + mark: ts::marker(install, cluster_id), + adopt: t.adopt.clone(), + own, + domains, + made, + peers, + servers, + forget, + }) +} + +/// A sync is sent again at least this often, for what changed on the +/// tailnet itself (a Service someone deleted, a host to approve). +const RESYNC_MS: i64 = 5 * 60 * 1000; + +/// The cluster's next [`tick`] sends its sync again, changed or not. +pub(crate) async fn send_again( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + cluster_id: &str, +) -> ApiResult<()> { + patch(&mut **tx, cluster_id, json!({ "sent": "" })).await } -/// Approvals asked for already: (Service, node). -static APPROVED: Mutex> = Mutex::new(BTreeSet::new()); +/// A cluster row as [`tick`] reads it: id, name, same cluster, status, and +/// its Tailscale. +type ClusterRow = (String, String, bool, String, Value); +/// One pass: each cluster with Tailscale gets its names synced when what +/// Pyo wants changed (or a while passed), then Pyo's addresses and the +/// services' tailnet domains follow what the servers report. pub async fn tick(s: &AppState) -> ApiResult<()> { - let Some((mut cfg, c)) = saved_client(s).await? else { - for k in ["tailnet", "registry", "sandboxes"] { - save_address(&s.db, k, None).await?; - } - return Ok(()); - }; let install = install_id(&s.db).await?; - let mark = marker(&install); - let devices = c.devices().await?; - let suffix = devices - .iter() - .find_map(|(_, n, _)| suffix_of(n)) - .or(cfg.suffix.clone()); - let Some(suffix) = suffix else { - return Ok(()); - }; - let remote = c.services().await?; - let ours = |n: &str| remote.get(n).is_some_and(|(cm, _)| *cm == mark); - let peers = peer_names(&s.db).await?; - let machine = |n: &str| { - peers.contains(n) - || devices - .iter() - .any(|(_, full, _)| full.split('.').next() == Some(n)) - }; - // Pyo's own names, picked once: "pyo", then "pyo-"… - let mut changed = cfg.suffix.as_deref() != Some(suffix.as_str()); - cfg.suffix = Some(suffix.clone()); - let host_cluster: Option = - sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE same_cluster LIMIT 1") - .fetch_optional(&s.db) - .await?; - if let Some(cluster) = &host_cluster { - let taken = |n: &str| (remote.contains_key(n) && !ours(n)) || machine(n); - let more = crate::util::slugify(cluster); - if cfg.dashboard_name.is_none() { - cfg.dashboard_name = Some(pick_name("pyo", &more, |n| taken(n))); - changed = true; + let rows: Vec = sqlx::query_as( + "SELECT id, name, same_cluster, status, tailscale FROM pyo.clusters WHERE tailscale IS NOT NULL", + ) + .fetch_all(&s.db) + .await?; + let now = pyo_proto::now_ms() as i64; + for (id, name, same, status, v) in &rows { + let Ok(t) = serde_json::from_value::(v.clone()) else { + continue; + }; + if !matches!(status.as_str(), "connected" | "degraded") { + continue; } - if cfg.registry_name.is_none() { - cfg.registry_name = Some(pick_name("registry", &more, |n| taken(n))); - changed = true; + let w = sync_for(&s.db, &install, id, name, *same, &t).await?; + let key = crate::ids::sha256_hex(&serde_json::to_string(&w).map_err(anyhow::Error::from)?); + if key == t.sent && now - t.sent_at < RESYNC_MS { + continue; } - // Sandboxes' name: kept while it's Pyo's to have, else the next - // free one, so another Pyo's or someone's own "sandboxes" stays as - // it is. - let domains: Vec = sqlx::query_scalar( - "SELECT name FROM pyo.tailnet_services WHERE kind = 'domain' AND retired_at IS NULL", + // One at a time: the agent answers each before the next is sent. + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.commands WHERE cluster_id = $1 AND command->>'kind' = 'tailscale_sync' + AND status IN ('pending', 'sent') AND created_at > now() - interval '5 minutes')", ) - .fetch_all(&s.db) + .bind(id) + .fetch_one(&s.db) .await?; - let others = [cfg.dashboard_name.clone(), cfg.registry_name.clone()]; - let name = own_name(cfg.sandboxes_name.as_deref(), "sandboxes", &more, |n| { - taken(n) || others.iter().flatten().any(|o| o == n) || domains.iter().any(|d| d == n) - }); - if cfg.sandboxes_name.as_deref() != Some(name.as_str()) { - if let Some(old) = &cfg.sandboxes_name { - tracing::info!( - old, - new = name, - "sandboxes' tailnet name is taken; picked another" - ); - } - cfg.sandboxes_name = Some(name); - changed = true; + if waiting { + continue; } + let mut tx = s.db.begin().await?; + crate::deploy::enqueue(&mut tx, id, Command::TailscaleSync(Box::new(w))).await?; + patch(&mut *tx, id, json!({ "sent": key, "sentAt": now })).await?; + tx.commit().await?; + s.wake(id).await; } - if changed { - save(&s.db, &cfg).await?; - } - let wanted = wanted(&s.db, &cfg, &suffix).await?; - let wanted_names: BTreeSet<&str> = wanted.iter().map(|w| w.0.as_str()).collect(); - for (name, kind, cluster) in &wanted { - let (addrs, error) = match remote.get(name.as_str()) { - Some((_, addrs)) if ours(name) => (addrs.clone(), None), - Some(_) => (Vec::new(), Some("Taken on your tailnet")), - None if machine(name) => (Vec::new(), Some("Taken on your tailnet")), - None => match claim(&c, name, &mark).await { - Ok(Claim::Ours(a)) => (a, None), - Ok(Claim::Taken) => (Vec::new(), Some("Taken on your tailnet")), - Err(e) => { - tracing::warn!(name, error = %e, "couldn't make the tailnet name"); - (Vec::new(), Some("Couldn't make it on your tailnet")) - } - }, - }; - sqlx::query( - "INSERT INTO pyo.tailnet_services (name, kind, cluster_id, addrs, error) VALUES ($1, $2, $3, $4, $5) - ON CONFLICT (name) DO UPDATE SET kind = excluded.kind, cluster_id = excluded.cluster_id, addrs = excluded.addrs, error = excluded.error, retired_at = NULL, updated_at = now() - WHERE (pyo.tailnet_services.kind, pyo.tailnet_services.cluster_id, pyo.tailnet_services.addrs, pyo.tailnet_services.error, pyo.tailnet_services.retired_at) IS DISTINCT FROM (excluded.kind, excluded.cluster_id, excluded.addrs, excluded.error, NULL)", + + // Pyo's own names, once a server keeps their certificate. + let mut ready = std::collections::BTreeMap::new(); + if let Some((id, _, _, _, v)) = rows.iter().find(|r| r.2) + && let Some(suffix) = v["suffix"].as_str() + { + let sv = servers(&s.db, id).await?; + let names: Vec<(String, String)> = sqlx::query_as( + "SELECT name, kind FROM pyo.cluster_tailnet_names WHERE cluster_id = $1 AND kind <> 'domain' + AND retired_at IS NULL AND error IS NULL AND cardinality(addrs) > 0", ) - .bind(name) - .bind(kind) - .bind(cluster) - .bind(&addrs) - .bind(error) - .execute(&s.db) - .await?; - } - // Ours, no longer used: deleted on the tailnet, and its servers take it - // off. Only names Pyo made (its own rows), each read again first. - let made: BTreeSet = sqlx::query_scalar("SELECT name FROM pyo.tailnet_services") + .bind(id) .fetch_all(&s.db) - .await? - .into_iter() - .collect(); - for name in remote - .keys() - .filter(|n| ours(n) && made.contains(*n) && !wanted_names.contains(n.as_str())) - { - match delete_if_ours(&c, name, &mark).await { - Ok(true) => tracing::info!(name, "tailnet name deleted"), - Ok(false) => tracing::warn!(name, "not deleted: not Pyo's on the tailnet"), - Err(e) => tracing::warn!(name, error = %e, "couldn't delete the tailnet name"), - } - } - sqlx::query("UPDATE pyo.tailnet_services SET retired_at = now(), updated_at = now() WHERE retired_at IS NULL AND NOT (name = ANY($1))") - .bind(wanted_names.iter().map(|n| n.to_string()).collect::>()) - .execute(&s.db) .await?; - sqlx::query("DELETE FROM pyo.tailnet_services WHERE retired_at < now() - interval '7 days'") - .execute(&s.db) - .await?; - - // The servers: tagged, and approved as hosts of their cluster's names. - let servers = servers(&s.db).await?; - let tagged: BTreeMap<&str, bool> = devices - .iter() - .map(|(id, _, tags)| (id.as_str(), tags.iter().any(|t| t == TAG))) - .collect(); - for sv in &servers { - let id = sv.status.node_id.as_str(); - if !id.is_empty() && tagged.get(id) == Some(&false) { - match c.tag(id).await { - Ok(()) => tracing::info!(server = %sv.status.server, "tagged tag:pyo"), - Err(e) => { - tracing::warn!(server = %sv.status.server, error = %e, "couldn't tag the server") - } + for (name, kind) in names { + if sv.iter().any(|x| x.certificates.contains(&name)) { + ready.insert(kind, format!("{name}.{suffix}")); } } } - for (name, _, cluster) in &wanted { - if !ours(name) && !remote.is_empty() && remote.contains_key(name.as_str()) { - continue; - } - let nodes: Vec<&str> = servers - .iter() - .filter(|sv| { - sv.cluster_id == *cluster && sv.status.advertised.iter().any(|a| a == name) - }) - .map(|sv| sv.status.node_id.as_str()) - .filter(|n| !n.is_empty()) - .collect(); - let asked = |n: &str| { - APPROVED - .lock() - .map(|a| a.contains(&(name.clone(), n.to_owned()))) - .unwrap_or(false) - }; - if nodes.iter().all(|n| asked(n)) { - continue; - } - let Ok(hosts) = c.hosts(name).await else { - continue; - }; - for n in nodes { - let ok = hosts.get(n) == Some(&true) || c.approve(name, n).await.is_ok(); - if ok && let Ok(mut a) = APPROVED.lock() { - a.insert((name.clone(), n.to_owned())); - } + for (key, kind) in [ + ("tailnet", "dashboard"), + ("registry", "registry"), + ("sandboxes", "sandboxes"), + ] { + save_address(&s.db, key, ready.get(kind).map(String::as_str)).await?; + } + + for (id, _, _, _, v) in &rows { + if let Ok(t) = serde_json::from_value::(v.clone()) { + follow_domains(&s.db, id, &t).await?; } } + Ok(()) +} - // Pyo's own names, once a server keeps their certificate. - let has_cert = |name: &str, cluster: &str| { - servers - .iter() - .any(|sv| sv.cluster_id == cluster && sv.status.certificates.iter().any(|c| c == name)) - }; - let host_id: Option = - sqlx::query_scalar("SELECT id FROM pyo.clusters WHERE same_cluster LIMIT 1") - .fetch_optional(&s.db) - .await?; - let ready = |kind: &str| { - wanted - .iter() - .find(|(n, k, cl)| { - *k == kind && ours(n) && host_id.as_deref() == Some(cl.as_str()) && has_cert(n, cl) - }) - .map(|(n, _, _)| format!("{n}.{suffix}")) +/// Why a tailnet domain the agent never made isn't live: its last sync +/// failed. +pub const SYNC_FAILED: &str = "Couldn't set it up on your tailnet. Check Tailscale on the cluster."; + +/// A tailnet domain's state, from what the cluster's agent and servers +/// report. `status` None: it stays as it is (still being set up, or live). +#[derive(Debug, PartialEq)] +pub struct DomainState { + pub status: Option<&'static str>, + pub tls: &'static str, + pub error: Option, +} + +/// `name`: the name as the agent left it (its addresses and error), None +/// before it made it. `served`: a server of the cluster advertises it. +/// `certified`: a server keeps its certificate. `sync_failed`: the +/// cluster's last sync failed. +pub fn domain_state( + name: Option<(&[String], Option<&str>)>, + served: bool, + certified: bool, + sync_failed: bool, +) -> DomainState { + let state = |status, tls, error: Option<&str>| DomainState { + status, + tls, + error: error.map(str::to_owned), }; - save_address(&s.db, "tailnet", ready("dashboard").as_deref()).await?; - save_address(&s.db, "registry", ready("registry").as_deref()).await?; - save_address(&s.db, "sandboxes", ready("sandboxes").as_deref()).await?; + match name { + Some((_, Some(e))) => state(Some("error"), "failed", Some(e)), + Some(_) if certified => state(Some("active"), "issued", None), + Some((addrs, None)) if served && !addrs.is_empty() => { + state(Some("active"), "pending", None) + } + None if sync_failed => state(Some("error"), "pending", Some(SYNC_FAILED)), + _ => state(None, "pending", None), + } +} - // Services' tailnet domains: their certificate as their state. - for (name, kind, cluster) in &wanted { - if *kind != "domain" { +/// A cluster's services' tailnet domains follow what its agent and servers +/// report: live once a server serves the name, with its certificate as +/// their HTTPS. Pyo can't look these names up itself: only devices on the +/// tailnet resolve them (and Pyo Cloud isn't on the team's tailnet). +async fn follow_domains(db: &PgPool, cluster_id: &str, t: &Tailnet) -> ApiResult<()> { + let Some(suffix) = t.suffix.as_deref() else { + return Ok(()); + }; + let sv = servers(db, cluster_id).await?; + let names: Vec<(String, Vec, Option)> = sqlx::query_as( + "SELECT name, addrs, error FROM pyo.cluster_tailnet_names WHERE cluster_id = $1 AND kind = 'domain' AND retired_at IS NULL", + ) + .bind(cluster_id) + .fetch_all(db) + .await?; + let mut hosts: Vec = sqlx::query_scalar( + "SELECT lower(d->>'hostname') FROM pyo.services s, jsonb_array_elements(s.spec->'domains') d + WHERE s.cluster_id = $1 AND NOT s.deleting AND lower(d->>'hostname') LIKE '%.' || $2", + ) + .bind(cluster_id) + .bind(suffix) + .fetch_all(db) + .await?; + hosts.sort(); + hosts.dedup(); + for host in hosts { + let Some(label) = host.strip_suffix(&format!(".{suffix}")) else { continue; - } - let host = format!("{name}.{suffix}"); - let (tls, error) = match remote.get(name.as_str()) { - _ if !ours(name) => ("failed", Some("Taken on your tailnet")), - _ if has_cert(name, cluster) => ("issued", None), - _ => ("pending", None), }; + let name = names + .iter() + .find(|(n, _, _)| n == label) + .map(|(_, a, e)| (a.as_slice(), e.as_deref())); + let st = domain_state( + name, + sv.iter().any(|x| x.advertised.iter().any(|a| a == label)), + sv.iter().any(|x| x.certificates.iter().any(|c| c == label)), + t.sync_failed, + ); + // Ones going live now, for the activity log. + let live: Vec<(String, String)> = if st.status == Some("active") { + sqlx::query_as( + "SELECT s.id, s.team_id FROM pyo.services s + WHERE s.cluster_id = $1 AND NOT s.deleting + AND EXISTS (SELECT 1 FROM jsonb_array_elements(s.spec->'domains') d + WHERE lower(d->>'hostname') = $2 AND d->>'status' IS DISTINCT FROM 'active')", + ) + .bind(cluster_id) + .bind(&host) + .fetch_all(db) + .await? + } else { + Vec::new() + }; + // Without a status: an error goes once the agent no longer reports it. sqlx::query( - "UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', ( - SELECT coalesce(jsonb_agg(CASE WHEN lower(d->>'hostname') = $2 - THEN (d - 'tlsError') || jsonb_strip_nulls(jsonb_build_object('tls', $3::text, 'tlsError', $4::text)) - ELSE d END), '[]') + "WITH x AS (SELECT $2::text AS host, $3::text AS tls, $4::text AS tls_error, $5::text AS status, $6::text AS error) + UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', ( + SELECT coalesce(jsonb_agg(CASE WHEN lower(d->>'hostname') = x.host + THEN (d - 'tlsError' - 'error') || jsonb_strip_nulls(jsonb_build_object( + 'status', coalesce(x.status, CASE WHEN d->>'status' = 'error' THEN 'pending_dns' ELSE d->>'status' END), + 'tls', x.tls, 'tlsError', x.tls_error, 'error', x.error)) + ELSE d END), '[]') FROM jsonb_array_elements(spec->'domains') d)) + FROM x WHERE cluster_id = $1 AND NOT deleting AND EXISTS (SELECT 1 FROM jsonb_array_elements(spec->'domains') d - WHERE lower(d->>'hostname') = $2 AND (coalesce(d->>'tls', '') <> $3 OR coalesce(d->>'tlsError', '') <> coalesce($4, '')))", + WHERE lower(d->>'hostname') = x.host + AND (coalesce(d->>'tls', '') <> x.tls OR coalesce(d->>'tlsError', '') <> coalesce(x.tls_error, '') + OR coalesce(d->>'error', '') <> coalesce(x.error, '') + OR d->>'status' IS DISTINCT FROM coalesce(x.status, CASE WHEN d->>'status' = 'error' THEN 'pending_dns' ELSE d->>'status' END)))", ) - .bind(cluster) + .bind(cluster_id) .bind(&host) - .bind(tls) - .bind(error) - .execute(&s.db) + .bind(st.tls) + .bind(st.error.as_ref().filter(|_| st.tls == "failed")) + .bind(st.status) + .bind(&st.error) + .execute(db) .await?; + for (service_id, team_id) in live { + let mut tx = db.begin().await?; + crate::ops::log_activity( + &mut tx, + &team_id, + "pyo", + "domain.verified", + "success", + &format!("{host} is on your tailnet now"), + json!({ "kind": "service", "id": service_id, "label": host }), + json!({ "serviceId": service_id }), + ) + .await?; + tx.commit().await?; + } } Ok(()) } -/// A row of `pyo.tailnet_services`: name, kind, cluster, addresses, -/// error, retired. -type ServiceRow = ( - String, - String, - Option, - Vec, - Option, - bool, -); +/// A sync's answer (agent.rs, when the agent reports it): the names as the +/// agent left them, the suffix, Pyo's own names as picked, and what Tailnet +/// Lock waits for. Older syncs' commands go. +pub async fn synced( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + cluster_id: &str, + command_id: &str, + r: &CommandResult, +) -> ApiResult<()> { + sqlx::query("DELETE FROM pyo.commands WHERE cluster_id = $1 AND command->>'kind' = 'tailscale_sync' AND id <> $2 AND status IN ('done', 'failed')") + .bind(cluster_id) + .bind(command_id) + .execute(&mut **tx) + .await?; + if !r.ok { + tracing::warn!(cluster = %cluster_id, error = ?r.message, "the cluster couldn't sync its tailnet names"); + // Tried again with the next pass. + return patch( + &mut **tx, + cluster_id, + json!({ "sent": "", "syncFailed": true }), + ) + .await; + } + let Some(done) = r + .data + .clone() + .and_then(|d| serde_json::from_value::(d).ok()) + else { + return Ok(()); + }; + let Some(t) = of(&mut **tx, cluster_id).await? else { + return Ok(()); + }; + for n in &done.names { + sqlx::query( + "INSERT INTO pyo.cluster_tailnet_names (cluster_id, name, kind, addrs, error) VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (cluster_id, name) DO UPDATE SET kind = excluded.kind, addrs = excluded.addrs, error = excluded.error, retired_at = NULL, updated_at = now() + WHERE (pyo.cluster_tailnet_names.kind, pyo.cluster_tailnet_names.addrs, pyo.cluster_tailnet_names.error, pyo.cluster_tailnet_names.retired_at) + IS DISTINCT FROM (excluded.kind, excluded.addrs, excluded.error, NULL)", + ) + .bind(cluster_id) + .bind(&n.name) + .bind(&n.kind) + .bind(&n.addrs) + .bind(&n.error) + .execute(&mut **tx) + .await?; + } + let kept: Vec = done.names.iter().map(|n| n.name.clone()).collect(); + sqlx::query("UPDATE pyo.cluster_tailnet_names SET retired_at = now(), updated_at = now() WHERE cluster_id = $1 AND retired_at IS NULL AND NOT (name = ANY($2))") + .bind(cluster_id) + .bind(&kept) + .execute(&mut **tx) + .await?; + sqlx::query("DELETE FROM pyo.cluster_tailnet_names WHERE cluster_id = $1 AND retired_at < now() - interval '7 days'") + .bind(cluster_id) + .execute(&mut **tx) + .await?; + let own = |kind: &str| { + done.names + .iter() + .find(|n| n.kind == kind) + .map(|n| n.name.clone()) + }; + let forget: Vec<&String> = t + .forget + .iter() + .filter(|n| !done.forgotten.contains(n)) + .collect(); + patch( + &mut **tx, + cluster_id, + json!({ + "suffix": done.suffix.clone().or(t.suffix.clone()), + "dashboardName": own("dashboard").or(t.dashboard_name.clone()), + "registryName": own("registry").or(t.registry_name.clone()), + "sandboxesName": own("sandboxes").or(t.sandboxes_name.clone()), + "lockWaiting": done.lock_waiting, + "machines": done.machines, + "forget": forget, + "syncFailed": false, + }), + ) + .await +} + +/// Takes a machine off a cluster's tailnet with its next sync. +pub async fn forget_machine(db: &PgPool, cluster_id: &str, node_id: &str) -> ApiResult<()> { + sqlx::query( + "UPDATE pyo.clusters SET tailscale = jsonb_set(tailscale, '{forget}', coalesce(tailscale->'forget', '[]') || to_jsonb($2::text)) + WHERE id = $1 AND tailscale IS NOT NULL AND NOT coalesce(tailscale->'forget', '[]') ? $2", + ) + .bind(cluster_id) + .bind(node_id) + .execute(db) + .await?; + Ok(()) +} + +/// A row of `pyo.cluster_tailnet_names`: name, kind, addresses, error, +/// retired. +type NameRow = (String, String, Vec, Option, bool); /// What a cluster's agent hosts on the tailnet (its heartbeat reply). None -/// without Tailscale set up. +/// without Tailscale set up on it, and no names to take off. pub async fn wanted_for( db: &PgPool, cluster_id: &str, same_cluster: bool, ) -> ApiResult> { - let rows: Vec = sqlx::query_as( - "SELECT name, kind, cluster_id, addrs, error, retired_at IS NOT NULL FROM pyo.tailnet_services", + let rows: Vec = sqlx::query_as( + "SELECT name, kind, addrs, error, retired_at IS NOT NULL FROM pyo.cluster_tailnet_names WHERE cluster_id = $1", ) + .bind(cluster_id) .fetch_all(db) .await?; - // Without Tailscale (removed): every server takes Pyo's names off. - let suffix = match settings(db).await?.and_then(|c| c.suffix) { + // Without Tailscale (removed): the servers take Pyo's names off. + let suffix = match of(db, cluster_id).await?.and_then(|t| t.suffix) { Some(x) => x, None if rows.is_empty() => return Ok(None), None => String::new(), @@ -1146,12 +1182,8 @@ pub async fn wanted_for( suffix: suffix.clone(), ..Default::default() }; - for (name, kind, cluster, addrs, error, retired) in rows { - let here = !suffix.is_empty() - && cluster.as_deref() == Some(cluster_id) - && !retired - && error.is_none() - && !addrs.is_empty(); + for (name, kind, addrs, error, retired) in rows { + let here = !suffix.is_empty() && !retired && error.is_none() && !addrs.is_empty(); if !here { w.retired.push(name); continue; @@ -1169,248 +1201,185 @@ pub async fn wanted_for( Ok(Some(w)) } -/// Tailscale made no auth key: the details go to the log, the user gets one -/// plain sentence and where to look. -/// `server` names what is being added, e.g. "a sandbox server". -fn no_auth_key(server: &'static str) -> impl FnOnce(anyhow::Error) -> ApiError { - move |e| { - tracing::warn!(error = %format!("{e:#}"), "Tailscale made no auth key"); - ApiError::bad_request(format!("Set up Tailscale in Integrations to add {server}.")) - } -} +// ── The installation's client, before clusters kept their own ────────────── -/// A join command's auth key: single-use, preauthorized, tag:pyo, an hour. -pub async fn join_key(s: &AppState, what: &str, server: &'static str) -> ApiResult { - let Some((_, c)) = saved_client(s).await? else { - return Err(ApiError::bad_request(NEEDED)); - }; - c.auth_key(what) - .await - .map(|(_, k)| k) - .map_err(no_auth_key(server)) +/// What `pyo.settings` ('tailscale') held before: the installation's +/// client and Pyo's names on its tailnet. +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Before { + client_id: String, + secret_sealed: String, + #[serde(default)] + dashboard_name: Option, + #[serde(default)] + registry_name: Option, + #[serde(default)] + sandboxes_name: Option, + #[serde(default)] + suffix: Option, } -/// Whether a tailnet domain someone typed can be had: Pyo's reserved names -/// and its own names are refused, and so is a name something else on the -/// tailnet has. -pub async fn check_domain(s: &AppState, host: &str) -> ApiResult<()> { - let Some((cfg, c)) = saved_client(s).await? else { - return Err(ApiError::bad_request( - "Tailnet domains need Tailscale. Set it up in Integrations.", - )); - }; - let Some(suffix) = cfg.suffix.as_deref() else { - return Err(ApiError::bad_request( - "Pyo hasn't seen your tailnet yet. Try again in a minute.", - )); - }; - let host = host.to_ascii_lowercase(); - let Some(label) = host.strip_suffix(&format!(".{suffix}")) else { - return Err(ApiError::bad_request(format!( - "A tailnet domain ends with .{suffix}." - ))); +/// An installation from before: its client goes, once, in a signed command +/// (sealed while queued), to the agent of the cluster Pyo runs on, and to +/// each other connected cluster that already has names or servers on the +/// tailnet, so nothing there stops working. Each counts the Services Pyo +/// made before as its own. Once every one keeps it, Pyo deletes its copy. +pub async fn hand_over(s: &AppState) -> ApiResult<()> { + let v: Option = + sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'tailscale'") + .fetch_optional(&s.db) + .await?; + let Some(before) = v.and_then(|v| serde_json::from_value::(v).ok()) else { + return Ok(()); }; - if !valid_name(label) { - return Err(ApiError::bad_request( - "Use one name: lowercase letters, digits and dashes.", - )); - } - if RESERVED.contains(&label) - || cfg.dashboard_name.as_deref() == Some(label) - || cfg.registry_name.as_deref() == Some(label) - || cfg.sandboxes_name.as_deref() == Some(label) - { - return Err(ApiError::bad_request("Pyo uses this name itself.")); - } - let mark = marker(&install_id(&s.db).await?); - let remote = c.services().await?; - let mine = remote.get(label).is_some_and(|(cm, _)| *cm == mark); - let machine = peer_names(&s.db).await?.contains(label) - || c.devices() - .await? - .iter() - .any(|(_, full, _)| full.split('.').next() == Some(label)); - if (remote.contains_key(label) && !mine) || machine { - return Err(ApiError::conflict("Taken on your tailnet")); - } - // The list can leave some out: the Service itself, read directly. - match c.service(label).await { - Ok(None) => Ok(()), - Ok(Some((comment, _))) if comment == mark => Ok(()), - Ok(Some(_)) => Err(ApiError::conflict("Taken on your tailnet")), - Err(e) => { - tracing::warn!(error = %format!("{e:#}"), "tailnet name check failed"); - Err(ApiError::bad_request( - "Couldn't check the name on your tailnet. Try again in a minute.", - )) - } + let host = host_cluster(&s.db).await?; + let others: Vec = sqlx::query_scalar( + "SELECT id FROM pyo.clusters c WHERE NOT same_cluster AND status IN ('connected', 'degraded') + AND (EXISTS (SELECT 1 FROM pyo.cluster_tailnet_names n WHERE n.cluster_id = c.id AND n.retired_at IS NULL) + OR EXISTS (SELECT 1 FROM jsonb_array_elements(coalesce(c.capabilities->'tailnet', '[]')) t WHERE coalesce(t->>'nodeId', '') <> '')) + ORDER BY created_at", + ) + .fetch_all(&s.db) + .await?; + let clusters: Vec = host.iter().cloned().chain(others).collect(); + if clusters.is_empty() { + return Ok(()); } + hand_over_to(s, &clusters, host.as_deref(), &before).await } -// ── Integrations › Tailscale ──────────────────────────────────────────────── - -/// Saves the OAuth client once it signs in (a missing secret keeps the saved -/// one), and says what it can do, check by check. -pub async fn save_client(s: &AppState, client_id: &str, secret: Option<&str>) -> ApiResult { - let client_id = client_id.trim(); - if client_id.is_empty() - || client_id.len() > 100 - || !client_id.bytes().all(|b| b.is_ascii_alphanumeric()) - { - return Err(ApiError::bad_request( - "Paste the client ID from Tailscale's Trust credentials page.", - )); - } - let saved = settings(&s.db).await?; - let secret = match secret.map(str::trim).filter(|x| !x.is_empty()) { - Some(x) - if x.starts_with("tskey-client-") - && x.len() > 20 - && !x.contains(char::is_whitespace) => - { - x.to_owned() - } - Some(_) => { - return Err(ApiError::bad_request( - "A client secret starts with tskey-client-.", - )); +async fn hand_over_to( + s: &AppState, + clusters: &[String], + host: Option<&str>, + before: &Before, +) -> ApiResult<()> { + let install = install_id(&s.db).await?; + let mut all = true; + for cluster_id in clusters { + if of(&s.db, cluster_id).await?.is_some() { + continue; } - None => match &saved { - Some(c) if c.client_id == client_id => s.sealer.open(&c.secret_sealed)?, - _ => return Err(ApiError::bad_request("Paste the client secret too.")), - }, - }; - if !s.sealer.enabled() { - return Err(ApiError::new( - axum::http::StatusCode::SERVICE_UNAVAILABLE, - "This installation has no PYO_SECRET_KEY, so it can't store the secret.", - )); - } - let (checks, suffix) = test(&client(client_id, &secret)).await; - if let Some(c) = checks.iter().find(|c| c.name == "client" && !c.ok) { - return Err(ApiError::bad_request(c.message.clone())); + let secret = s.sealer.open(&before.secret_sealed)?; + let r = ask( + s, + cluster_id, + Command::TailscaleClient { + client_id: before.client_id.clone(), + secret, + }, + SETUP_WAIT, + ) + .await; + let r = match r { + Ok((_, r)) => r, + Err(e) => { + tracing::warn!(cluster = %cluster_id, error = %e.message, "couldn't hand the Tailscale client over yet"); + all = false; + continue; + } + }; + let state: ts::ClientState = r + .data + .and_then(|d| serde_json::from_value(d).ok()) + .unwrap_or_default(); + let own = host == Some(cluster_id.as_str()); + let t = Tailnet { + client_id: state.client_id, + hint: state.hint, + suffix: state.suffix.or(before.suffix.clone()), + dashboard_name: before.dashboard_name.clone().filter(|_| own), + registry_name: before.registry_name.clone().filter(|_| own), + sandboxes_name: before.sandboxes_name.clone().filter(|_| own), + adopt: vec![ts::install_marker(&install)], + ..Default::default() + }; + sqlx::query("UPDATE pyo.clusters SET tailscale = $2 WHERE id = $1") + .bind(cluster_id) + .bind(serde_json::to_value(&t).map_err(anyhow::Error::from)?) + .execute(&s.db) + .await?; + tracing::info!(cluster = %cluster_id, "the installation's Tailscale client now lives in the cluster"); } - let mut cfg = saved.unwrap_or_default(); - // Another tailnet: Pyo's names there are picked again. - if cfg.suffix.is_some() && suffix.is_some() && cfg.suffix != suffix { - cfg.dashboard_name = None; - cfg.registry_name = None; - cfg.sandboxes_name = None; + if all { + sqlx::query("DELETE FROM pyo.settings WHERE key = 'tailscale'") + .execute(&s.db) + .await?; + tracing::info!("Pyo no longer keeps a Tailscale client"); } - cfg.client_id = client_id.to_owned(); - cfg.hint = format!("…{}", &secret[secret.len() - 4..]); - cfg.secret_sealed = s.sealer.seal(&secret)?; - cfg.suffix = suffix.or(cfg.suffix); - save(&s.db, &cfg).await?; - Ok(json!({ "ok": checks.iter().all(|c| c.ok), "checks": checks })) + Ok(()) } -/// The Test button: the saved client's checks. -pub async fn test_saved(s: &AppState) -> ApiResult { - let Some((mut cfg, c)) = saved_client(s).await? else { - return Err(ApiError::bad_request("Tailscale isn't set up.")); - }; - let (checks, suffix) = test(&c).await; - if suffix.is_some() && cfg.suffix != suffix { - cfg.suffix = suffix; - save(&s.db, &cfg).await?; - } - Ok(json!({ "ok": checks.iter().all(|c| c.ok), "checks": checks })) -} +// ── For the dashboard ─────────────────────────────────────────────────────── -/// Forgets the client: Pyo's Services on the tailnet are deleted while it -/// still can, and its servers take them off. -pub async fn remove(s: &AppState) -> ApiResult<()> { - if let Some((_, c)) = saved_client(s).await? { - let mark = marker(&install_id(&s.db).await?); - // Only names Pyo made (its own rows), and each checked again. - let made: Vec = sqlx::query_scalar("SELECT name FROM pyo.tailnet_services") - .fetch_all(&s.db) - .await?; - for name in &made { - if let Err(e) = delete_if_ours(&c, name, &mark).await { - tracing::warn!(name, error = %e, "couldn't delete the tailnet name"); - } - } - } - sqlx::query("UPDATE pyo.tailnet_services SET retired_at = coalesce(retired_at, now()), updated_at = now()") - .execute(&s.db) - .await?; - sqlx::query("DELETE FROM pyo.settings WHERE key = 'tailscale'") - .execute(&s.db) - .await?; - // Without the tailnet, the public dashboard is the way in again. - sqlx::query("DELETE FROM pyo.settings WHERE key = 'public_dashboard'") - .execute(&s.db) - .await?; - for k in ["tailnet", "registry", "sandboxes"] { - save_address(&s.db, k, None).await?; - } - Ok(()) +#[derive(Deserialize, utoipa::IntoParams)] +#[into_params(parameter_in = Query)] +pub struct LockQuery { + /// The team adding the server (slug or id). + team: String, } -/// Renames Pyo's own name on the tailnet ("dashboard", "registry" or -/// "sandboxes"). The old one goes once the new one is made. -pub async fn rename(s: &AppState, kind: &str, name: &str) -> ApiResult<()> { - let name = name.trim().to_ascii_lowercase(); - let Some((mut cfg, c)) = saved_client(s).await? else { - return Err(ApiError::bad_request("Tailscale isn't set up.")); - }; - if !valid_name(&name) { - return Err(ApiError::bad_request( - "Use one name: lowercase letters, digits and dashes.", - )); - } - let others = match kind { - "dashboard" => [&cfg.registry_name, &cfg.sandboxes_name], - "registry" => [&cfg.dashboard_name, &cfg.sandboxes_name], - "sandboxes" => [&cfg.dashboard_name, &cfg.registry_name], - _ => { - return Err(ApiError::bad_request( - "The kind is \"dashboard\", \"registry\" or \"sandboxes\".", - )); - } - }; - let domain: bool = sqlx::query_scalar( - "SELECT EXISTS (SELECT 1 FROM pyo.tailnet_services WHERE name = $1 AND kind = 'domain' AND retired_at IS NULL)", +/// Machines waiting for a Tailnet Lock signature +/// +/// With Tailnet Lock on, a new server stays off the tailnet until a +/// signing device signs its key. These are the ones on the team's +/// clusters' tailnets that wait, with the command to run on a signing +/// device, as each cluster last saw them. Empty without Tailscale set up. +#[utoipa::path(get, path = "/tailnet/lock", operation_id = "getTailnetLock", tag = "Servers", + params(LockQuery), + responses( + (status = 200, description = "`waiting`: each with `name` (the machine's hostname) and `signCommand`.", body = Object), + (status = 403, description = "Only owners and admins add servers.", body = crate::error::ErrorBody), + (status = 404, description = "No such team, or you aren't in it.", body = crate::error::ErrorBody), + ), + extensions(("x-pyo-access" = json!("read"))))] +pub async fn lock( + axum::extract::State(s): axum::extract::State, + crate::auth::SessionUser(user): crate::auth::SessionUser, + crate::error::Query(q): crate::error::Query, +) -> ApiResult> { + let mut tx = crate::rls::begin(&s.db, &user).await?; + crate::ops::require_role(&mut tx, &user, &q.team, crate::ops::Role::Admin).await?; + let team_id: String = sqlx::query_scalar("SELECT id FROM pyo.teams WHERE id = $1 OR slug = $1") + .bind(&q.team) + .fetch_one(&mut *tx) + .await?; + drop(tx); + let rows: Vec = sqlx::query_scalar( + "SELECT tailscale->'lockWaiting' FROM pyo.clusters WHERE (team_id = $1 OR same_cluster) AND tailscale ? 'lockWaiting'", ) - .bind(&name) - .fetch_one(&s.db) + .bind(&team_id) + .fetch_all(&s.db) .await?; - if others.iter().any(|o| o.as_deref() == Some(name.as_str())) || domain { - return Err(ApiError::conflict("Pyo uses this name already.")); - } - let mark = marker(&install_id(&s.db).await?); - let remote = c.services().await?; - let machine = peer_names(&s.db).await?.contains(&name) - || c.devices() - .await? - .iter() - .any(|(_, full, _)| full.split('.').next() == Some(name.as_str())); - let direct = c.service(&name).await?; - if remote.get(&name).is_some_and(|(cm, _)| *cm != mark) - || direct.is_some_and(|(cm, _)| cm != mark) - || machine - { - return Err(ApiError::conflict("Taken on your tailnet")); - } - match kind { - "dashboard" => cfg.dashboard_name = Some(name), - "registry" => cfg.registry_name = Some(name), - _ => cfg.sandboxes_name = Some(name), - } - save(&s.db, &cfg).await + let mut waiting: Vec = rows + .into_iter() + .flat_map(|v| serde_json::from_value::>(v).unwrap_or_default()) + .collect(); + waiting.sort_by(|a, b| a.name.cmp(&b.name)); + waiting.dedup(); + Ok(crate::error::Json(json!({ "waiting": waiting }))) } -/// For the dashboard: whether Tailscale is set up and Pyo's names on it; -/// the client (never the secret) only for admins. +/// A cluster's Tailscale for the dashboard: never a secret. +pub fn cluster_view(t: &Tailnet) -> Value { + json!({ + "clientId": t.client_id, + "hint": t.hint, + "suffix": t.suffix, + }) +} + +/// For the dashboard: the installation's tailnet (the cluster Pyo runs on) +/// and Pyo's names on it; the client (never the secret) only for admins. pub async fn snapshot(db: &PgPool, admin: bool) -> ApiResult { - let Some(cfg) = settings(db).await? else { + let Some((cluster_id, t)) = host(db).await? else { return Ok(Value::Null); }; let a = crate::web::addresses(); let mut v = json!({ - "suffix": cfg.suffix, + "clusterId": cluster_id, + "suffix": t.suffix, "dashboard": a.tailnet, "registry": a.registry, "sandboxes": a.sandboxes, @@ -1419,8 +1388,9 @@ pub async fn snapshot(db: &PgPool, admin: bool) -> ApiResult { }); if admin { let rows: Vec<(String, Option)> = sqlx::query_as( - "SELECT name, error FROM pyo.tailnet_services WHERE kind IN ('dashboard', 'registry', 'sandboxes') AND retired_at IS NULL", + "SELECT name, error FROM pyo.cluster_tailnet_names WHERE cluster_id = $1 AND kind IN ('dashboard', 'registry', 'sandboxes') AND retired_at IS NULL", ) + .bind(&cluster_id) .fetch_all(db) .await?; let error = |n: &Option| { @@ -1428,14 +1398,14 @@ pub async fn snapshot(db: &PgPool, admin: bool) -> ApiResult { .and_then(|n| rows.iter().find(|r| r.0 == *n)) .and_then(|r| r.1.clone()) }; - v["clientId"] = json!(cfg.client_id); - v["hint"] = json!(cfg.hint); - v["dashboardName"] = json!(cfg.dashboard_name); - v["dashboardError"] = json!(error(&cfg.dashboard_name)); - v["registryName"] = json!(cfg.registry_name); - v["registryError"] = json!(error(&cfg.registry_name)); - v["sandboxesName"] = json!(cfg.sandboxes_name); - v["sandboxesError"] = json!(error(&cfg.sandboxes_name)); + v["clientId"] = json!(t.client_id); + v["hint"] = json!(t.hint); + v["dashboardName"] = json!(t.dashboard_name); + v["dashboardError"] = json!(error(&t.dashboard_name)); + v["registryName"] = json!(t.registry_name); + v["registryError"] = json!(error(&t.registry_name)); + v["sandboxesName"] = json!(t.sandboxes_name); + v["sandboxesError"] = json!(error(&t.sandboxes_name)); v["hostName"] = json!(a.host_name); } Ok(v) @@ -1458,13 +1428,14 @@ async fn host_move(db: &PgPool) -> ApiResult { } /// When Pyo's server last got a key to join with: one at a time. -static HOST_KEY_AT: Mutex> = Mutex::new(None); +static HOST_KEY_AT: std::sync::Mutex> = std::sync::Mutex::new(None); /// Pyo's own server, on its timer (install.sh `host_units`): what its /// Tailscale says (`ip` and `name`, empty when it's not on a tailnet). Kept -/// as Pyo's tailnet address. Answers `{"state": "off"}` without Tailscale, -/// `{"state": "ok"}` once it's on the tailnet, or `{"state": "join", -/// "authKey"}` to join it (at most one key every ten minutes). +/// as Pyo's tailnet address. Answers `{"state": "off"}` without Tailscale +/// on Pyo's cluster, `{"state": "ok"}` once it's on the tailnet, or +/// `{"state": "join", "authKey"}` to join it (at most one key every ten +/// minutes, made by the cluster's agent). pub async fn host_report( s: &AppState, ip: &str, @@ -1488,14 +1459,14 @@ pub async fn host_report( let ip = ip.trim(); let ip = crate::freedomain::tailnet_v4(ip).map(|v| v.to_string()); let name = name.trim().trim_end_matches('.').to_ascii_lowercase(); - let name = (ip.is_some() && name.ends_with(".ts.net") && name.split('.').all(valid_name)) + let name = (ip.is_some() && name.ends_with(".ts.net") && name.split('.').all(ts::valid_name)) .then_some(name); let a = crate::web::addresses(); if a.host_ip != ip || a.host_name != name { save_address(&s.db, "hostIp", ip.as_deref()).await?; save_address(&s.db, "hostName", name.as_deref()).await?; } - let Some((_, c)) = saved_client(s).await? else { + let Some((cluster_id, _)) = host(&s.db).await? else { return Ok(json!({ "state": "off" })); }; if ip.is_some() { @@ -1506,226 +1477,552 @@ pub async fn host_report( if at.is_some_and(|t| t.elapsed() < Duration::from_secs(600)) { return Ok(json!({ "state": "wait" })); } - *at = Some(Instant::now()); + *at = Some(std::time::Instant::now()); } - let (_, key) = c - .auth_key("Pyo: its own server") - .await - .map_err(no_auth_key("this server"))?; + let key = join_key(s, &cluster_id, "Pyo: its own server", "this server").await?; tracing::info!("this machine: joining the tailnet"); Ok(json!({ "state": "join", "authKey": key })) } #[cfg(test)] mod tests { + use super::*; + + #[test] + fn a_tailnet_keeps_nothing_secret() { + let t = Tailnet { + client_id: "kC1".into(), + hint: "…WXYZ".into(), + suffix: Some("tail1.ts.net".into()), + ..Default::default() + }; + let text = serde_json::to_value(&t).unwrap().to_string(); + assert!(!text.to_lowercase().contains("secret"), "{text}"); + assert_eq!(cluster_view(&t)["clientId"], "kC1"); + } + + #[test] + fn tokens_are_checked_before_they_leave_pyo() { + assert!(token_shape("tskey-api-kAbc-0123456789abcdef").is_ok()); + assert!(token_shape("tskey-client-kAbc-0123456789abcdef").is_err()); + assert!(token_shape("tskey-auth-kAbc-0123456789abcdef").is_err()); + assert!(token_shape("nope").is_err()); + } + #[test] - fn key_descriptions_are_what_tailscale_takes() { - use super::key_description; - assert_eq!(key_description("Pyo: join web-1"), "Pyo join web-1"); + fn credentials_are_wiped_from_answered_commands() { + let mut setup = + json!({ "kind": "tailscale_setup", "token": "pyo1:sealed", "version": "v1" }); + assert!(crate::teambackup::wipe_command(&mut setup)); assert_eq!( - key_description("Pyo: sandbox server sbx_1"), - "Pyo sandbox server sbx_1" + setup, + json!({ "kind": "tailscale_setup", "token": "", "version": "v1" }) ); - assert_eq!(key_description("Pyo: its own server"), "Pyo its own server"); - let long = key_description(&format!("Pyo: join {}", "a".repeat(80))); - assert_eq!(long.len(), 50); + let mut client = + json!({ "kind": "tailscale_client", "clientId": "k1", "secret": "pyo1:sealed" }); + assert!(crate::teambackup::wipe_command(&mut client)); + assert_eq!(client["secret"], ""); + assert_eq!(client["clientId"], "k1"); + let mut other = json!({ "kind": "backup", "password": "pyo1:sealed" }); + assert!(!crate::teambackup::wipe_command(&mut other)); + assert_eq!(other["password"], "pyo1:sealed"); + } + + // Against a throwaway Postgres (DATABASE_URL), with a stand-in agent + // that answers the cluster's commands. + + async fn db() -> (AppState, String) { + let url = std::env::var("DATABASE_URL").expect("DATABASE_URL"); + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + crate::migrate::run(&pool).await.unwrap(); + crate::vault::init(crate::vault::Vault::new( + pool.clone(), + crate::vault::Provider::from_env(), + )); + let run = crate::ids::new_id("t"); + let (team, cluster) = (format!("team_{run}"), format!("cl_{run}")); + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash, status) VALUES ($1, $2, $1, $1, 'connected')") + .bind(&cluster) + .bind(&team) + .execute(&pool) + .await + .unwrap(); + (crate::sandbox::e2e::test_state(pool), cluster) } - use super::*; + /// The agent: takes the cluster's next command of `kind`, opened as it + /// would get it, and answers it with `data`. + async fn agent_answers(db: PgPool, cluster: String, kind: &str, data: Value) -> Value { + loop { + let row: Option<(String, Value)> = sqlx::query_as( + "SELECT id, command FROM pyo.commands WHERE cluster_id = $1 AND command->>'kind' = $2 AND status = 'pending' ORDER BY created_at LIMIT 1", + ) + .bind(&cluster) + .bind(kind) + .fetch_optional(&db) + .await + .unwrap(); + if let Some((id, mut cmd)) = row { + crate::vault::get().open_env(&mut cmd).await.unwrap(); + crate::teambackup::open_command(&mut cmd).await.unwrap(); + let r = CommandResult { + ok: true, + message: None, + logs: vec![], + data: Some(data), + }; + sqlx::query("UPDATE pyo.commands SET status = 'done', result = $2, done_at = now() WHERE id = $1") + .bind(&id) + .bind(serde_json::to_value(&r).unwrap()) + .execute(&db) + .await + .unwrap(); + return cmd; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + + async fn commands(db: &PgPool, cluster: &str, kind: &str) -> i64 { + sqlx::query_scalar( + "SELECT count(*) FROM pyo.commands WHERE cluster_id = $1 AND command->>'kind' = $2", + ) + .bind(cluster) + .bind(kind) + .fetch_one(db) + .await + .unwrap() + } - /// A mock Tailscale API: a Service ("docker", someone else's) that the - /// list leaves out but a direct read finds. Pyo must refuse the name and - /// never write to it. + /// An installation from before: its client goes to its cluster's agent + /// once, and Pyo keeps nothing of it but the ID and hint. #[tokio::test] - async fn a_service_the_list_leaves_out_is_never_written() { - use axum::{ - Json, Router, - extract::Path, - routing::{get, post}, + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn the_installations_client_goes_to_its_cluster_once() { + let (s, cluster) = db().await; + let secret = "tskey-client-kAbc-SECRETSECRET1234"; + let before = Before { + client_id: "kAbc".into(), + secret_sealed: s.sealer.seal(secret).unwrap(), + dashboard_name: Some("pyo".into()), + registry_name: Some("registry".into()), + suffix: Some("tail1.ts.net".into()), + ..Default::default() }; - use std::sync::Arc; - let writes: Arc>> = Arc::default(); - let w = writes.clone(); - let app = Router::new() - .route("/oauth/token", post(|| async { Json(json!({ "access_token": "t" })) })) - .route("/tailnet/-/services", get(|| async { Json(json!({ "vipServices": [] })) })) - .route( - "/tailnet/-/services/{svc}", - get(|Path(svc): Path| async move { - match svc.as_str() { - "svc:docker" => (axum::http::StatusCode::OK, Json(json!({ "name": "svc:docker", "comment": "the user's", "addrs": ["100.100.1.1"] }))), - "svc:mine" => (axum::http::StatusCode::OK, Json(json!({ "name": "svc:mine", "comment": "Made by Pyo (abc)", "addrs": ["100.100.1.2"] }))), - _ => (axum::http::StatusCode::NOT_FOUND, Json(json!({ "message": "not found" }))), - } - }) - .put({ - let w = w.clone(); - move |Path(svc): Path| { - let w = w.clone(); - async move { - w.lock().unwrap().push(format!("PUT {svc}")); - Json(json!({ "addrs": ["100.100.1.3"] })) - } - } - }) - .delete(move |Path(svc): Path| { - let w = w.clone(); - async move { - w.lock().unwrap().push(format!("DELETE {svc}")); - Json(json!({})) - } - }), - ); - 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 c = test_client(&format!("http://{addr}")); - let mark = marker("abc"); + let agent = tokio::spawn(agent_answers( + s.db.clone(), + cluster.clone(), + "tailscale_client", + json!({ "ok": true, "checks": [], "clientId": "kAbc", "hint": "…1234", "suffix": "tail1.ts.net" }), + )); + hand_over_to(&s, std::slice::from_ref(&cluster), Some(&cluster), &before) + .await + .unwrap(); + let sent = agent.await.unwrap(); + assert_eq!(sent["client_id"], "kAbc"); + assert_eq!(sent["secret"], secret, "the agent gets the secret"); + let t = of(&s.db, &cluster).await.unwrap().unwrap(); + assert_eq!((t.client_id.as_str(), t.hint.as_str()), ("kAbc", "…1234")); + assert_eq!(t.dashboard_name.as_deref(), Some("pyo")); + let install = install_id(&s.db).await.unwrap(); + assert_eq!(t.adopt, [ts::install_marker(&install)]); + let kept: Option = + sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'tailscale'") + .fetch_optional(&s.db) + .await + .unwrap(); + assert_eq!(kept, None, "Pyo's copy is deleted"); + let leaked: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pyo.clusters WHERE tailscale::text LIKE '%SECRETSECRET%'", + ) + .fetch_one(&s.db) + .await + .unwrap(); + assert_eq!(leaked, 0); + } + + /// A join key comes from the cluster's agent, and its command (with the + /// key in its answer) is gone once read. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn a_join_key_comes_from_the_cluster_and_is_not_kept() { + let (s, cluster) = db().await; assert!( - c.services().await.unwrap().is_empty(), - "the list leaves it out" - ); - assert_eq!(claim(&c, "docker", &mark).await.unwrap(), Claim::Taken); - assert!(!delete_if_ours(&c, "docker", &mark).await.unwrap()); - assert_eq!( - claim(&c, "mine", &mark).await.unwrap(), - Claim::Ours(vec!["100.100.1.2".into()]) - ); - assert_eq!( - claim(&c, "blog", &mark).await.unwrap(), - Claim::Ours(vec!["100.100.1.3".into()]) + join_key(&s, &cluster, "Pyo: join web-2", "this server") + .await + .is_err(), + "no Tailscale on it yet" ); - assert!(delete_if_ours(&c, "mine", &mark).await.unwrap()); - assert_eq!(*writes.lock().unwrap(), ["PUT svc:blog", "DELETE svc:mine"]); + sqlx::query("UPDATE pyo.clusters SET tailscale = '{\"clientId\": \"k1\"}' WHERE id = $1") + .bind(&cluster) + .execute(&s.db) + .await + .unwrap(); + let agent = tokio::spawn(agent_answers( + s.db.clone(), + cluster.clone(), + "tailscale_key", + json!({ ts::KEY_FIELD: "tskey-auth-k9-SECRET" }), + )); + let key = join_key(&s, &cluster, "Pyo: join web-2", "this server") + .await + .unwrap(); + assert_eq!(key, "tskey-auth-k9-SECRET"); + assert_eq!(agent.await.unwrap()["description"], "Pyo: join web-2"); + assert_eq!(commands(&s.db, &cluster, "tailscale_key").await, 0); + assert_eq!(key_cluster(&s.db, Some(&cluster)).await.unwrap(), cluster); } - #[test] - fn machines_waiting_for_a_signature() { - let d = |host: &str, tag: &str, key: &str, err: &str| Device { - node_id: "n".into(), - hostname: host.into(), - tags: vec![tag.into()], - node_key: key.into(), - lock_error: err.into(), + /// Pyo's calls to a sandbox server that joined through a cluster go + /// through that cluster's agent, and leave nothing behind. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn sandbox_calls_go_through_the_cluster() { + let (s, cluster) = db().await; + crate::sandbox::daemon::init(s.clone()); + let address = format!( + "100.64.{}.{}", + rand::random::() % 64, + 1 + rand::random::() % 250 + ); + sqlx::query("INSERT INTO pyo.sandbox_servers (id, name, state, created_by, address, via_cluster) VALUES ($1, $1, 'ready', 'test', $2, $3)") + .bind(crate::ids::new_id("sbs")) + .bind(&address) + .bind(&cluster) + .execute(&s.db) + .await + .unwrap(); + let agent = tokio::spawn(agent_answers( + s.db.clone(), + cluster.clone(), + "sandbox_call", + // Bytes both ways: the agent answers in base64 too. + json!({ "status": 200, "body": "eyJieXRlcyI6IDV9" }), + )); + let d = crate::sandbox::daemon::Daemon::new(&address); + let n = d + .write_file("tok", "sbx_1", "/a b", b"hello".to_vec()) + .await + .unwrap(); + assert_eq!(n, 5); + let sent = agent.await.unwrap(); + assert_eq!(sent["address"], json!(address)); + assert_eq!(sent["method"], "PUT"); + assert_eq!(sent["path"], "/v1/sandboxes/sbx_1/files?path=%2Fa+b"); + assert_eq!(sent["token"], "tok"); + assert_eq!(sent["raw"], true); + assert_eq!(sent["body"], "aGVsbG8="); + assert_eq!(commands(&s.db, &cluster, "sandbox_call").await, 0); + } + + /// A sync's answer: names kept, the rest retired, machines taken off + /// forgotten, and the servers told what to host. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn a_sync_answer_is_kept() { + let (s, cluster) = db().await; + sqlx::query("UPDATE pyo.clusters SET tailscale = '{\"clientId\": \"k1\", \"forget\": [\"n1\", \"n2\"]}' WHERE id = $1") + .bind(&cluster) + .execute(&s.db) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.cluster_tailnet_names (cluster_id, name, kind, addrs) VALUES ($1, 'old', 'domain', '{100.100.1.1}')") + .bind(&cluster) + .execute(&s.db) + .await + .unwrap(); + let done = TailnetSynced { + suffix: Some("tail1.ts.net".into()), + names: vec![ + ts::NameState { + name: "blog".into(), + kind: "domain".into(), + addrs: vec!["100.100.1.2".into()], + error: None, + }, + ts::NameState { + name: "shop".into(), + kind: "domain".into(), + addrs: vec![], + error: Some("Taken on your tailnet".into()), + }, + ], + forgotten: vec!["n1".into()], + ..Default::default() }; - let waiting = lock_waiting(&[ - d( - "sbx-1", - TAG, - "nodekey:ab12", - "tailnet lock: node key not signed", - ), - d("laptop", "tag:other", "nodekey:cd34", "not signed"), - d("web-1", TAG, "nodekey:ef56", ""), - ]); + let r = CommandResult { + ok: true, + message: None, + logs: vec![], + data: Some(serde_json::to_value(&done).unwrap()), + }; + let mut tx = s.db.begin().await.unwrap(); + synced(&mut tx, &cluster, "cmd_x", &r).await.unwrap(); + tx.commit().await.unwrap(); + let t = of(&s.db, &cluster).await.unwrap().unwrap(); + assert_eq!(t.suffix.as_deref(), Some("tail1.ts.net")); + assert_eq!(t.forget, ["n2"]); + let w = wanted_for(&s.db, &cluster, false).await.unwrap().unwrap(); + assert_eq!(w.suffix, "tail1.ts.net"); assert_eq!( - waiting, - [( - "sbx-1".to_owned(), - "tailscale lock sign nodekey:ab12".to_owned() - )] + w.services + .iter() + .map(|x| x.name.as_str()) + .collect::>(), + ["blog"] ); + let mut retired = w.retired.clone(); + retired.sort(); + assert_eq!(retired, ["old", "shop"]); } #[test] - fn names() { + fn a_tailnet_domain_is_live_once_a_server_serves_it() { + let addrs = vec!["100.100.1.2".to_owned()]; + let made = Some((addrs.as_slice(), None)); + let st = |name, served, certified, failed| domain_state(name, served, certified, failed); + // Not made yet, or made and not served yet: still being set up. + assert_eq!(st(None, false, false, false).status, None); + assert_eq!(st(made, false, false, false).status, None); + assert_eq!(st(Some((&[][..], None)), true, false, false).status, None); + // Served: live, its certificate on its way, then issued. assert_eq!( - suffix_of("server-1.tail1234.ts.net."), - Some("tail1234.ts.net".into()) + st(made, true, false, false), + DomainState { + status: Some("active"), + tls: "pending", + error: None + } ); - assert_eq!(suffix_of("example.com"), None); - assert!( - valid_name("blog-2") && !valid_name("Blog") && !valid_name("-a") && !valid_name("a.b") + assert_eq!( + st(made, true, true, false), + DomainState { + status: Some("active"), + tls: "issued", + error: None + } ); - let taken = ["pyo", "pyo-home"]; + assert_eq!(st(made, false, true, false).status, Some("active")); + // The agent couldn't make it. assert_eq!( - pick_name("pyo", "home", |n| taken.contains(&n)), - "pyo-home-2" + st( + Some((&[][..], Some("Taken on your tailnet"))), + false, + false, + false + ), + DomainState { + status: Some("error"), + tls: "failed", + error: Some("Taken on your tailnet".into()) + } ); + // The sync failed: only names it never made say so. + assert_eq!(st(None, false, false, true).status, Some("error")); assert_eq!( - pick_name("registry", "home", |n| taken.contains(&n)), - "registry" + st(None, false, false, true).error.as_deref(), + Some(SYNC_FAILED) ); - assert_eq!(pick_name("pyo", "home", |n| n == "pyo"), "pyo-home"); - let long = "a".repeat(70); - assert!(pick_name(&long, "x", |_| false).len() <= 63); - assert_eq!(marker("abc"), "Made by Pyo (abc)"); + assert_eq!(st(made, false, false, true).status, None); + assert_eq!(st(made, true, false, true).status, Some("active")); } - /// Sandboxes' name, as tick picks it from the tailnet's Services - /// (name to its comment, the marker of whoever made it) and machines. - fn sandboxes(current: Option<&str>, services: &[(&str, &str)], others: &[&str]) -> String { - let mark = marker("this"); - let ours = |n: &str| services.iter().any(|(s, m)| *s == n && *m == mark); - let taken = |n: &str| { - (services.iter().any(|(s, _)| *s == n) && !ours(n)) - || n == "laptop" - || others.contains(&n) + /// Services' tailnet domains follow the cluster: set up, live once a + /// server serves them, an error when the agent reports one, and never + /// looked up in DNS. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn tailnet_domains_follow_the_cluster() { + let (s, cluster) = db().await; + let team: String = sqlx::query_scalar("SELECT team_id FROM pyo.clusters WHERE id = $1") + .bind(&cluster) + .fetch_one(&s.db) + .await + .unwrap(); + let run = crate::ids::new_id("t"); + let suffix = format!("{}.ts.net", run.to_lowercase().replace('_', "-")); + let (project, service) = (format!("prj_{run}"), format!("svc_{run}")); + sqlx::query( + "INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, $1, $1)", + ) + .bind(&project) + .bind(&team) + .execute(&s.db) + .await + .unwrap(); + let domain = |id: &str, host: &str| json!({ "id": id, "hostname": host, "portName": "http", "status": "pending_dns", "tls": "pending", "tlsMode": "auto", "redirectHttps": false, "createdAt": 1 }); + let (blog, shop, wiki) = ( + format!("blog.{suffix}"), + format!("shop.{suffix}"), + format!("wiki.{suffix}"), + ); + let spec = json!({ "domains": [domain("dom_b", &blog), domain("dom_s", &shop), domain("dom_w", &wiki)] }); + sqlx::query("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec) VALUES ($1, $2, $3, $4, 'web', $5)") + .bind(&service) + .bind(&team) + .bind(&project) + .bind(&cluster) + .bind(&spec) + .execute(&s.db) + .await + .unwrap(); + let t = Tailnet { + client_id: "k1".into(), + suffix: Some(suffix.clone()), + ..Default::default() }; - own_name(current, "sandboxes", "home", taken) - } + sqlx::query("UPDATE pyo.clusters SET tailscale = $2 WHERE id = $1") + .bind(&cluster) + .bind(serde_json::to_value(&t).unwrap()) + .execute(&s.db) + .await + .unwrap(); + let state = || async { + let spec: Value = sqlx::query_scalar("SELECT spec FROM pyo.services WHERE id = $1") + .bind(&service) + .fetch_one(&s.db) + .await + .unwrap(); + spec["domains"] + .as_array() + .unwrap() + .iter() + .map(|d| { + ( + d["status"].as_str().unwrap_or("").to_owned(), + d["tls"].as_str().unwrap_or("").to_owned(), + d["error"].as_str().map(str::to_owned), + ) + }) + .collect::>() + }; + let pending = ("pending_dns".to_owned(), "pending".to_owned(), None); - #[test] - fn sandboxes_name_free() { - assert_eq!(sandboxes(None, &[], &["pyo", "registry"]), "sandboxes"); - } + // The DNS watcher leaves them alone: Pyo can't look them up. + crate::deploy::check_pending_dns(&s).await.unwrap(); + let checked: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pyo.services s, jsonb_array_elements(s.spec->'domains') d WHERE s.id = $1 AND d ? 'dnsCheckedAt'", + ) + .bind(&service) + .fetch_one(&s.db) + .await + .unwrap(); + assert_eq!(checked, 0); - #[test] - fn sandboxes_name_already_this_pyos() { - let mine = marker("this"); - // A Service this Pyo made before (a restart, an update, the name - // picked earlier): kept as it is. - assert_eq!( - sandboxes(None, &[("sandboxes", mine.as_str())], &[]), - "sandboxes" + // The sync failed before the agent made any: they say so. + let failed = CommandResult { + ok: false, + message: Some("x".into()), + logs: vec![], + data: None, + }; + let mut tx = s.db.begin().await.unwrap(); + synced(&mut tx, &cluster, "cmd_1", &failed).await.unwrap(); + tx.commit().await.unwrap(); + let t = of(&s.db, &cluster).await.unwrap().unwrap(); + assert!(t.sync_failed); + follow_domains(&s.db, &cluster, &t).await.unwrap(); + let failing = ( + "error".to_owned(), + "pending".to_owned(), + Some(SYNC_FAILED.to_owned()), ); - assert_eq!( - sandboxes(Some("sandboxes"), &[("sandboxes", mine.as_str())], &[]), - "sandboxes" + assert_eq!(state().await, [failing.clone(), failing.clone(), failing]); + + // The next sync made blog and wiki, and shop is someone else's. + let name = |n: &str, error: Option<&str>| ts::NameState { + name: n.into(), + kind: "domain".into(), + addrs: if error.is_some() { + vec![] + } else { + vec!["100.100.1.2".into()] + }, + error: error.map(str::to_owned), + }; + let done = TailnetSynced { + suffix: Some(suffix.clone()), + names: vec![ + name("blog", None), + name("shop", Some("Taken on your tailnet")), + name("wiki", None), + ], + ..Default::default() + }; + let ok = CommandResult { + ok: true, + message: None, + logs: vec![], + data: Some(serde_json::to_value(&done).unwrap()), + }; + let mut tx = s.db.begin().await.unwrap(); + synced(&mut tx, &cluster, "cmd_2", &ok).await.unwrap(); + tx.commit().await.unwrap(); + let t = of(&s.db, &cluster).await.unwrap().unwrap(); + assert!(!t.sync_failed); + follow_domains(&s.db, &cluster, &t).await.unwrap(); + let taken = ( + "error".to_owned(), + "failed".to_owned(), + Some("Taken on your tailnet".to_owned()), ); assert_eq!( - sandboxes( - Some("sandboxes-home"), - &[ - ("sandboxes", "someone's"), - ("sandboxes-home", mine.as_str()) - ], - &[] - ), - "sandboxes-home" + state().await, + [pending.clone(), taken.clone(), pending.clone()] ); - } - #[test] - fn sandboxes_name_someone_elses() { - let other = marker("another Pyo"); - assert_eq!( - sandboxes(None, &[("sandboxes", other.as_str())], &[]), - "sandboxes-home" - ); - assert_eq!(sandboxes(None, &[("sandboxes", "")], &[]), "sandboxes-home"); + // A server serves blog: live. Then it keeps blog's certificate. + let server = |certificates: Vec| json!([{ "server": "web-1", "nodeId": "n1", "advertised": ["blog"], "certificates": certificates }]); + let report = |v: Value| { + sqlx::query("UPDATE pyo.clusters SET capabilities = jsonb_set(coalesce(capabilities, '{}'), '{tailnet}', $2) WHERE id = $1") + .bind(&cluster) + .bind(v) + .execute(&s.db) + }; + report(server(vec![])).await.unwrap(); + follow_domains(&s.db, &cluster, &t).await.unwrap(); + let live = ("active".to_owned(), "pending".to_owned(), None); + assert_eq!(state().await, [live, taken.clone(), pending.clone()]); + let logged: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pyo.activity WHERE team_id = $1 AND data->>'type' = 'domain.verified'", + ) + .bind(&team) + .fetch_one(&s.db) + .await + .unwrap(); + assert_eq!(logged, 1); + report(server(vec!["blog".into()])).await.unwrap(); + follow_domains(&s.db, &cluster, &t).await.unwrap(); + let issued = ("active".to_owned(), "issued".to_owned(), None); assert_eq!( - sandboxes( - None, - &[("sandboxes", other.as_str()), ("sandboxes-home", "")], - &[] - ), - "sandboxes-home-2" + state().await, + [issued.clone(), taken.clone(), pending.clone()] ); + + // Its routes syncing leaves them as they are. + let mut tx = s.db.begin().await.unwrap(); + crate::routes::mark_routed(&mut tx, &service, None) + .await + .unwrap(); + tx.commit().await.unwrap(); + assert_eq!(state().await, [issued, taken, pending]); } #[test] - fn sandboxes_name_moves_on_when_taken() { - // Picked, then someone else made it first: the next free one, - // never theirs. Pyo's other names and machines count as taken. - assert_eq!( - sandboxes(Some("sandboxes"), &[("sandboxes", "theirs")], &[]), - "sandboxes-home" - ); - assert_eq!(sandboxes(Some("laptop"), &[], &[]), "sandboxes"); - assert_eq!( - sandboxes(Some("registry"), &[("sandboxes", "theirs")], &["registry"]), - "sandboxes-home" - ); + fn the_old_settings_are_read_for_the_hand_over() { + let v = json!({ + "clientId": "kC1", "secretSealed": "v1:abc", "hint": "…WXYZ", + "dashboardName": "pyo", "registryName": "registry", "suffix": "tail1.ts.net" + }); + let b: Before = serde_json::from_value(v).unwrap(); + assert_eq!(b.client_id, "kC1"); + assert_eq!(b.secret_sealed, "v1:abc"); + assert_eq!(b.dashboard_name.as_deref(), Some("pyo")); + assert_eq!(b.sandboxes_name, None); } } diff --git a/crates/pyo-api/src/teambackup.rs b/crates/pyo-api/src/teambackup.rs index 0c86e8c7..ed76ecbc 100644 --- a/crates/pyo-api/src/teambackup.rs +++ b/crates/pyo-api/src/teambackup.rs @@ -47,21 +47,42 @@ impl TeamSettings { } } -pub async fn settings(db: &PgPool, team_id: &str) -> anyhow::Result> { +pub async fn settings( + db: &mut sqlx::PgConnection, + team_id: &str, +) -> anyhow::Result> { let v: Option = sqlx::query_scalar("SELECT value FROM pyo.team_backup_settings WHERE team_id = $1") .bind(team_id) - .fetch_optional(db) + .fetch_optional(&mut *db) .await?; Ok(v.and_then(|v| serde_json::from_value(v).ok())) } +/// Whether teams may keep backups in Pyo's own store, and do by default: +/// a self-hosted Pyo with one. A hosted Pyo's store is outside every +/// team's cluster, so its teams back up to S3 buckets only. +pub fn store_on_pyo() -> bool { + team_store(crate::hosted(), backup::local_store().is_some()) +} + +fn team_store(hosted: bool, store: bool) -> bool { + !hosted && store +} + +/// What a team without a backup store is told. +pub const NO_STORE: &str = "Add an S3 bucket for the team's backups first (Backups)."; + /// The team's settings, or the default: this server's store, volumes off, -/// with a repository password made (and saved) on first use. -pub async fn effective(db: &PgPool, team_id: &str) -> anyhow::Result { - if let Some(s) = settings(db, team_id).await? { +/// with a repository password made (and saved) on first use. None to +/// default to: refused until the team adds a bucket. +pub async fn effective(db: &PgPool, team_id: &str) -> ApiResult { + if let Some(s) = settings(&mut *db.acquire().await?, team_id).await? { return Ok(s); } + if !store_on_pyo() { + return Err(crate::error::ApiError::conflict(NO_STORE)); + } let s = TeamSettings { base: backup::Settings::local_default(false), repo_password_sealed: repo_password(team_id, None).await?, @@ -146,7 +167,7 @@ pub struct Target { pub namespace: Option, } -pub async fn targets(db: &PgPool, team_id: &str) -> anyhow::Result> { +pub async fn targets(db: &mut sqlx::PgConnection, team_id: &str) -> anyhow::Result> { // Labelled "project / service": the same name can be in two projects. let services: Vec<(String, String, String, Value, bool)> = sqlx::query_as( "SELECT a.id, a.cluster_id, p.name || ' / ' || a.name, a.spec, a.current_deployment_id IS NOT NULL @@ -154,12 +175,12 @@ pub async fn targets(db: &PgPool, team_id: &str) -> anyhow::Result> WHERE a.team_id = $1 AND NOT a.deleting ORDER BY p.name, a.name", ) .bind(team_id) - .fetch_all(db) + .fetch_all(&mut *db) .await?; let volumes: Vec<(String, Option, String)> = sqlx::query_as("SELECT id, service_id, coalesce(data->>'name', id) FROM pyo.volumes WHERE team_id = $1 AND service_id IS NOT NULL AND NOT deleting ORDER BY data->>'name'") .bind(team_id) - .fetch_all(db) + .fetch_all(&mut *db) .await?; let mut out = Vec::new(); for (id, cluster, name, spec, deployed) in &services { @@ -194,7 +215,7 @@ pub async fn targets(db: &PgPool, team_id: &str) -> anyhow::Result> ORDER BY v.data->>'name'", ) .bind(team_id) - .fetch_all(db) + .fetch_all(&mut *db) .await?; for (vid, cluster, project, ns, vname) in detached { out.push(Target { @@ -248,13 +269,22 @@ pub async fn destination( ) -> anyhow::Result<(backup::Settings, String, String)> { let mut r = cfg.base.resolved()?; if cfg.base.is_local() { + anyhow::ensure!(store_on_pyo(), NO_STORE); let (key, secret) = backup::team_login(&state.db, team_id).await?; r.bucket = backup::team_bucket(team_id); r.access_key = key.clone(); return Ok((r, key, secret)); } - let (key, secret) = backup::credentials(state, &r, None)?; - Ok((r, key, secret)) + // The team's own bucket key, sealed with the team's data key (or with + // the installation's by a release before 0.5). + let sealed = r + .secret_sealed + .as_deref() + .ok_or_else(|| anyhow::anyhow!("Enter the secret key."))?; + let secret = crate::vault::get() + .open_credential(&state.sealer, sealed) + .await?; + Ok((r.clone(), r.access_key.clone(), secret)) } /// The region a backup signs with: Garage's own for the store on Pyo's @@ -300,7 +330,7 @@ pub async fn queue( let password = crate::vault::get().open(&cfg.repo_password_sealed).await?; let (_, access_key, secret) = destination(state, team_id, &cfg).await?; let mut n = 0; - for t in targets(&state.db, team_id).await? { + for t in targets(&mut *state.db.acquire().await?, team_id).await? { // One asked for by name runs; otherwise only what the team picked. match only { Some(o) if o != t.id => continue, @@ -428,8 +458,10 @@ async fn log_failed( } /// Backup commands carry the repository password and storage key: sealed -/// while queued, opened for the agent. -/// The secret fields of backup and database-setup commands. +/// while queued, opened for the agent. So do Tailscale's (a pasted API +/// access token, an OAuth client's secret) and a sandbox server call's +/// token, which are wiped once the agent answers ([`wipe_command`]). +/// The secret fields of these commands. fn secret_fields(cmd: &mut Value) -> Vec<&mut Value> { let kind = cmd["kind"].as_str().unwrap_or("").to_owned(); let Some(o) = cmd.as_object_mut() else { @@ -445,6 +477,9 @@ fn secret_fields(cmd: &mut Value) -> Vec<&mut Value> { | ("backup" | "list_snapshots" | "forget_snapshot" | "restore_volume", "secretKey") => { out.push(v) } + ("tailscale_setup", "token") + | ("tailscale_client", "secret") + | ("sandbox_call", "token") => out.push(v), ("backup", "connection") | ("db_setup", "admin") => { if let Some(p) = v.get_mut("password") { out.push(p); @@ -469,6 +504,20 @@ pub async fn seal_command(team_id: &str, cmd: &mut Value) -> anyhow::Result<()> Ok(()) } +/// 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. +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") { + return false; + } + for v in secret_fields(cmd) { + *v = json!(""); + } + true +} + pub async fn open_command(cmd: &mut Value) -> anyhow::Result<()> { for v in secret_fields(cmd) { if let Some(sealed) = v.as_str().map(str::to_owned) { @@ -546,7 +595,7 @@ async fn tick(state: &AppState) -> anyhow::Result<()> { /// backup would use, this server's store. None: nowhere to back up to. fn shown_settings(saved: Option) -> Option { saved.or_else(|| { - backup::local_store().map(|_| TeamSettings { + store_on_pyo().then(|| TeamSettings { base: backup::Settings::local_default(false), repo_password_sealed: String::new(), mode: all(), @@ -604,11 +653,11 @@ pub fn volume_status( /// Each of a team's volumes' `backup` (see [`volume_status`]), by id. pub async fn volume_statuses( - db: &PgPool, + db: &mut sqlx::PgConnection, team_id: &str, ) -> anyhow::Result> { - let cfg = shown_settings(settings(db, team_id).await?); - let targets: std::collections::HashSet = targets(db, team_id) + let cfg = shown_settings(settings(&mut *db, team_id).await?); + let targets: std::collections::HashSet = targets(&mut *db, team_id) .await? .into_iter() .filter_map(|t| t.volume_id) @@ -618,17 +667,17 @@ pub async fn volume_statuses( FROM pyo.backups WHERE team_id = $1 AND volume_id IS NOT NULL ORDER BY volume_id, created_at DESC", ) .bind(team_id) - .fetch_all(db) + .fetch_all(&mut *db) .await?; let good: Vec<(String, i64)> = sqlx::query_as( "SELECT volume_id, pyo.ms(max(coalesce(finished_at, created_at))) FROM pyo.backups WHERE team_id = $1 AND volume_id IS NOT NULL AND status = 'succeeded' GROUP BY volume_id", ) .bind(team_id) - .fetch_all(db) + .fetch_all(&mut *db) .await?; let ids: Vec = sqlx::query_scalar("SELECT id FROM pyo.volumes WHERE team_id = $1") .bind(team_id) - .fetch_all(db) + .fetch_all(&mut *db) .await?; Ok(ids .into_iter() @@ -645,11 +694,11 @@ pub async fn volume_statuses( } /// The dashboard's view: each of the user's teams' settings, targets and runs. -pub async fn snapshot(db: &PgPool, team_ids: &[String]) -> ApiResult> { +pub async fn snapshot(db: &mut sqlx::PgConnection, team_ids: &[String]) -> ApiResult> { let mut out = Vec::new(); for team in team_ids { // Nothing saved: what a backup would use (this server's store). - let cfg = shown_settings(settings(db, team).await?); + let cfg = shown_settings(settings(&mut *db, team).await?); let history: Vec = sqlx::query_scalar( "SELECT jsonb_build_object('id', id, 'serviceId', service_id, 'volumeId', volume_id, 'kind', kind, 'status', status, 'trigger', trigger, 'label', label, 'snapshotId', snapshot_id, 'sizeBytes', size_bytes, 'addedBytes', added_bytes, @@ -657,19 +706,21 @@ pub async fn snapshot(db: &PgPool, team_ids: &[String]) -> ApiResult> FROM pyo.backups WHERE team_id = $1 ORDER BY created_at DESC LIMIT 40", ) .bind(team) - .fetch_all(db) + .fetch_all(&mut *db) .await?; out.push(json!({ "teamId": team, "settings": cfg.as_ref().map(|c| { let mut p = c.base.public(); + // This server's store, for the team: none on a hosted Pyo. + p["localAvailable"] = json!(store_on_pyo()); p["repository"] = json!(repository(&c.base, team)); p["mode"] = json!(c.mode); p["exceptions"] = json!(c.exceptions); p }), - "databases": crate::database_backups::snapshot(db, team).await?, - "targets": targets(db, team).await.context("targets").map_err(crate::error::ApiError::from)?.into_iter().map(|t| { + "databases": crate::database_backups::snapshot(&mut *db, team).await?, + "targets": targets(&mut *db, team).await.context("targets").map_err(crate::error::ApiError::from)?.into_iter().map(|t| { let included = cfg.as_ref().is_none_or(|c| c.includes(&t.id)); let mut v = serde_json::to_value(&t).unwrap_or(Value::Null); v["included"] = json!(included); @@ -685,6 +736,112 @@ pub async fn snapshot(db: &PgPool, team_ids: &[String]) -> ApiResult> mod tests { use super::*; + #[test] + fn a_hosted_pyo_keeps_no_teams_backups() { + assert!(team_store(false, true)); + assert!(!team_store(true, true), "hosted: S3 buckets only"); + assert!(!team_store(false, false)); + assert!(!team_store(true, false)); + } + + /// Against a throwaway Postgres, on a Pyo without a store of its own + /// (as a hosted one is to its teams): nothing to default to, so the + /// team has no backup settings, a backup is refused with what to do, + /// and "this server" can't be picked. + #[test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + fn without_a_store_on_pyo_teams_add_a_bucket() { + if backup::local_store().is_some() { + eprintln!("PYO_BACKUP_STORE_* is set: skipped"); + return; + } + std::thread::Builder::new() + .stack_size(64 << 20) + .spawn(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + .block_on(without_a_store()) + }) + .unwrap() + .join() + .unwrap(); + } + + async fn without_a_store() { + 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 run = new_id("t"); + let (team, user_id) = (format!("team_{run}"), format!("usr_{run}")); + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&db) + .await + .unwrap(); + sqlx::query("INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $1 || '@b.test', $1, '')").bind(&user_id).execute(&db).await.unwrap(); + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $3 || '@b.test', 'owner', 'active')").bind(format!("mem_{run}")).bind(&team).bind(&user_id).execute(&db).await.unwrap(); + let shown = snapshot( + &mut db.acquire().await.unwrap(), + std::slice::from_ref(&team), + ) + .await + .unwrap(); + assert!(shown[0]["settings"].is_null(), "no default store"); + let e = effective(&db, &team).await.unwrap_err(); + assert_eq!(e.status, axum::http::StatusCode::CONFLICT); + assert_eq!(e.message, NO_STORE); + let user = crate::auth::User { + id: user_id.clone(), + name: "b".into(), + email: format!("{user_id}@b.test"), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + let s = crate::rls::tests::state(db.clone()); + let e = crate::ops::run_json(&s, &user, json!({ "op": "runTeamBackup", "teamId": team })) + .await + .unwrap_err(); + assert_eq!(e.status, axum::http::StatusCode::CONFLICT, "{}", e.message); + let e = crate::ops::run_json( + &s, + &user, + json!({ + "op": "saveTeamBackupSettings", "teamId": team, "destination": "local", + "enabled": true, "schedule": "daily", "hour": 2, "keep": 14, + "endpoint": "", "region": "", "bucket": "", "prefix": "", "accessKey": "", + }), + ) + .await + .unwrap_err(); + assert_eq!(e.status, axum::http::StatusCode::BAD_REQUEST); + assert!(e.message.ends_with("Add an S3 bucket."), "{}", e.message); + assert!( + settings(&mut db.acquire().await.unwrap(), &team) + .await + .unwrap() + .is_none() + ); + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + sqlx::query("DELETE FROM pyo.users WHERE id = $1") + .bind(&user_id) + .execute(&db) + .await + .unwrap(); + } + /// `volume.backup` worked out from a real database: DATABASE_URL= cargo test -p pyo-api -- --ignored volume_backup_status #[tokio::test] @@ -746,7 +903,9 @@ mod tests { .unwrap(); // Nowhere to back up to (no settings, no store of Pyo's): unsupported. if backup::local_store().is_none() { - let all = volume_statuses(&pool, &team).await.unwrap(); + let all = volume_statuses(&mut pool.acquire().await.unwrap(), &team) + .await + .unwrap(); assert!( all.values().all(|v| v["status"] == "unsupported"), "{all:?}" @@ -763,7 +922,9 @@ mod tests { exceptions: vec![off.clone()], }; save(&pool, &team, &cfg).await.unwrap(); - let all = volume_statuses(&pool, &team).await.unwrap(); + let all = volume_statuses(&mut pool.acquire().await.unwrap(), &team) + .await + .unwrap(); assert_eq!(all[&used]["status"], "enabled"); assert_eq!(all[&used]["schedule"], "daily"); assert_eq!(all[&off]["status"], "disabled"); @@ -773,7 +934,9 @@ mod tests { .execute(&pool) .await .unwrap(); - let v = &volume_statuses(&pool, &team).await.unwrap()[&used]; + let v = &volume_statuses(&mut pool.acquire().await.unwrap(), &team) + .await + .unwrap()[&used]; assert_eq!(v["status"], "failed"); assert!(v["lastAt"].as_i64().unwrap() < v["failedAt"].as_i64().unwrap()); // A good one after it: enabled again. @@ -782,7 +945,9 @@ mod tests { .await .unwrap(); assert_eq!( - volume_statuses(&pool, &team).await.unwrap()[&used]["status"], + volume_statuses(&mut pool.acquire().await.unwrap(), &team) + .await + .unwrap()[&used]["status"], "enabled" ); sqlx::query("DELETE FROM pyo.teams WHERE id = $1") diff --git a/crates/pyo-api/src/teamsec_tests.rs b/crates/pyo-api/src/teamsec_tests.rs new file mode 100644 index 00000000..0a476bea --- /dev/null +++ b/crates/pyo-api/src/teamsec_tests.rs @@ -0,0 +1,727 @@ +//! Team security end to end, against a throwaway Postgres (DATABASE_URL): +//! two-factor setup and sign-in, recovery codes, teams that require it, the +//! installation's and Pyo Cloud staff's rule, and the audit log with what +//! it records and who may read it. Through the real routes, as a browser. + +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; + +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(); +} + +struct Client { + app: Router, + cookie: Option, + ip: &'static str, +} + +impl Client { + async fn call( + &mut self, + method: Method, + path: &str, + body: Option, + ) -> (StatusCode, Value) { + let (st, bytes) = self.raw(method, path, body).await; + (st, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + } + + async fn raw( + &mut self, + method: Method, + path: &str, + body: Option, + ) -> (StatusCode, Vec) { + let mut req = Request::builder() + .method(method) + .uri(path) + .header("x-pyo-csrf", "1") + .header(header::USER_AGENT, "TestBrowser/1.0"); + if let Some(c) = &self.cookie { + req = req.header(header::COOKIE, c); + } + let mut req = match body { + Some(b) => req + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(b.to_string())) + .unwrap(), + None => req.body(Body::empty()).unwrap(), + }; + req.extensions_mut().insert(ConnectInfo( + format!("{}:4000", self.ip).parse::().unwrap(), + )); + let res = self.app.clone().oneshot(req).await.unwrap(); + let st = res.status(); + if let Some(c) = res.headers().get(header::SET_COOKIE) { + let c = c.to_str().unwrap(); + if c.starts_with("pyo_session=") { + self.cookie = Some(c.split(';').next().unwrap().to_owned()); + } + } + let bytes = axum::body::to_bytes(res.into_body(), 64 << 20) + .await + .unwrap(); + (st, bytes.to_vec()) + } + + async fn op(&mut self, op: Value) -> (StatusCode, Value) { + self.call(Method::POST, "/api/v1/ops", Some(op)).await + } +} + +/// The current code of an account's app, from its sealed secret. +async fn code_now(db: &PgPool, user: &str, offset_steps: i64) -> String { + let sealed: String = + sqlx::query_scalar("SELECT secret_sealed FROM pyo.user_totp WHERE user_id = $1") + .bind(user) + .fetch_one(db) + .await + .unwrap(); + let b32 = crate::secrets::Sealer::for_tests().open(&sealed).unwrap(); + let secret = totp_rs::Secret::try_from_base32(&b32).unwrap(); + let t = totp_rs::Builder::new().with_secret(secret).build().unwrap(); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + t.generate((now + offset_steps * 30) as u64).to_string() +} + +/// An audit row as the checks read it: action, outcome, via, ip, user +/// agent, actor name, actor id. +type Row = ( + String, + String, + String, + Option, + String, + String, + Option, +); + +async fn audit_rows(db: &PgPool, team: &str) -> Vec { + sqlx::query_as( + "SELECT action, outcome, via, ip, user_agent, actor_name, actor_id FROM pyo.audit_events WHERE team_id = $1 ORDER BY at, id", + ) + .bind(team) + .fetch_all(db) + .await + .unwrap() +} + +fn has(rows: &[Row], action: &str) -> bool { + rows.iter().any(|r| r.0 == action) +} + +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn two_factor_required_teams_and_the_audit_log() { + 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 id = |p: &str, t: &str| format!("{p}_{t}{run}"); + let (ada, bob) = (id("usr", "ada"), id("usr", "bob")); + let (team_a, team_b) = (id("team", "a"), id("team", "b")); + let email = |who: &str| format!("{who}{run}@teamsec.test"); + let hash = crate::auth::hash_password("correct horse battery") + .await + .unwrap(); + for (u, n) in [(&ada, "ada"), (&bob, "bob")] { + sqlx::query( + "INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $2, $3, $4)", + ) + .bind(u) + .bind(email(n)) + .bind(n) + .bind(&hash) + .execute(&db) + .await + .unwrap(); + } + for t in [&team_a, &team_b] { + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(t) + .execute(&db) + .await + .unwrap(); + } + // Ada owns A, Bob develops in A and B; B's owner is Ada too. + for (m, t, u, n, role) in [ + ("a1", &team_a, &ada, "ada", "owner"), + ("a2", &team_a, &bob, "bob", "developer"), + ("b1", &team_b, &ada, "ada", "owner"), + ("b2", &team_b, &bob, "bob", "developer"), + ] { + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $4, $5, 'active')") + .bind(id("mem", m)) + .bind(t) + .bind(u) + .bind(email(n)) + .bind(role) + .execute(&db) + .await + .unwrap(); + } + let mut a = Client { + app: app.clone(), + cookie: None, + ip: "203.0.113.7", + }; + let mut b = Client { + app: app.clone(), + cookie: None, + ip: "198.51.100.9", + }; + + // ── Signing in: recorded with address, browser and how. + let (st, _) = a + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("ada"), "password": "correct horse battery" })), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert!(a.cookie.is_some(), "no two-factor yet: signed in"); + let (st, _) = b + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("bob"), "password": "wrong password!" })), + ) + .await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + let (st, _) = b + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("bob"), "password": "correct horse battery" })), + ) + .await; + assert_eq!(st, StatusCode::OK); + let rows = audit_rows(&db, &team_a).await; + let sign_in = rows + .iter() + .find(|r| r.0 == "auth.sign_in" && r.5 == "ada") + .expect("Ada's sign-in"); + assert_eq!( + (sign_in.1.as_str(), sign_in.2.as_str()), + ("ok", "dashboard") + ); + assert_eq!(sign_in.3.as_deref(), Some("203.0.113.7")); + assert_eq!(sign_in.4, "TestBrowser/1.0"); + assert_eq!(sign_in.6.as_deref(), Some(ada.as_str())); + let failed = rows + .iter() + .find(|r| r.0 == "auth.sign_in_failed") + .expect("Bob's wrong password"); + assert_eq!((failed.1.as_str(), failed.5.as_str()), ("failed", "bob")); + assert!( + has(&audit_rows(&db, &team_b).await, "auth.sign_in_failed"), + "in each of Bob's teams" + ); + + // ── Setting up two-factor: the password, then a code. + let (st, _) = a + .call( + Method::POST, + "/api/auth/two-factor/setup", + Some(json!({ "password": "nope nope nope" })), + ) + .await; + assert_eq!(st, StatusCode::FORBIDDEN); + let (st, setup) = a + .call( + Method::POST, + "/api/auth/two-factor/setup", + Some(json!({ "password": "correct horse battery" })), + ) + .await; + assert_eq!(st, StatusCode::OK, "{setup}"); + assert!( + setup["uri"] + .as_str() + .unwrap() + .starts_with("otpauth://totp/Pyo:") + ); + assert!(setup["qr"].as_str().unwrap().contains(" = serde_json::from_value(on["recoveryCodes"].clone()).unwrap(); + assert_eq!(codes.len(), 10); + let (_, me) = a.call(Method::GET, "/api/auth/me", None).await; + assert_eq!(me["twoFactor"]["enabled"], true); + assert_eq!(me["twoFactor"]["recoveryCodesLeft"], 10); + assert!(has( + &audit_rows(&db, &team_a).await, + "auth.two_factor_enabled" + )); + + // ── Signing in now asks for a code, and gives no session first. + let mut a2 = Client { + app: app.clone(), + cookie: None, + ip: "203.0.113.7", + }; + let (st, first) = a2 + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("ada"), "password": "correct horse battery" })), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_eq!(first["twoFactor"], true); + assert!(a2.cookie.is_none(), "no session before the code"); + let challenge = first["challenge"].as_str().unwrap().to_owned(); + let (st, _) = a2 + .call( + Method::POST, + "/api/auth/login/code", + Some(json!({ "challenge": challenge, "code": "123456" })), + ) + .await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + assert!(a2.cookie.is_none()); + let (st, _) = a2 + .call( + Method::POST, + "/api/auth/login/code", + Some(json!({ "challenge": challenge, "code": codes[0] })), + ) + .await; + assert_eq!(st, StatusCode::OK, "a recovery code"); + assert!(a2.cookie.is_some()); + // The same recovery code again: no. + let mut a3 = Client { + app: app.clone(), + cookie: None, + ip: "203.0.113.7", + }; + let (_, first) = a3 + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("ada"), "password": "correct horse battery" })), + ) + .await; + let (st, _) = a3 + .call( + Method::POST, + "/api/auth/login/code", + Some(json!({ "challenge": first["challenge"], "code": codes[0] })), + ) + .await; + assert_eq!(st, StatusCode::UNAUTHORIZED, "a recovery code works once"); + let (st, _) = a3 + .call( + Method::POST, + "/api/auth/login/code", + Some(json!({ "challenge": first["challenge"], "code": codes[1] })), + ) + .await; + assert_eq!(st, StatusCode::OK); + let rows = audit_rows(&db, &team_a).await; + assert!(has(&rows, "auth.recovery_code_used")); + assert!( + rows.iter() + .any(|r| r.0 == "auth.sign_in_failed" && r.5 == "ada"), + "the wrong code" + ); + // A challenge alone isn't a session. + let (st, _) = Client { + app: app.clone(), + cookie: None, + ip: "203.0.113.7", + } + .call(Method::GET, "/api/v1/state", None) + .await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + + // ── A team that requires two-factor: Bob can't open it, his account still works. + let (st, out) = b + .op(json!({ "op": "setTeamSecurity", "teamId": team_a, "requireTwoFactor": true })) + .await; + assert_eq!(st, StatusCode::FORBIDDEN, "developers can't: {out}"); + let (st, out) = a.op(json!({ "op": "setTeamSecurity", "teamId": team_a, "requireTwoFactor": true, "auditIps": "anonymized" })).await; + assert_eq!(st, StatusCode::OK, "{out}"); + let (st, state) = b.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + let teams: Vec<&str> = state["teams"] + .as_array() + .unwrap() + .iter() + .filter_map(|t| t["id"].as_str()) + .collect(); + assert!( + !teams.contains(&team_a.as_str()) && teams.contains(&team_b.as_str()), + "{teams:?}" + ); + assert_eq!( + state["user"]["twoFactor"]["lockedTeams"][0]["id"], + json!(team_a) + ); + assert_eq!(state["user"]["twoFactor"]["setupNeeded"], false); + let (st, _) = b + .op(json!({ "op": "updateMemberRole", "id": id("mem", "a2"), "role": "viewer" })) + .await; + assert_eq!(st, StatusCode::NOT_FOUND, "team A is out of reach"); + // Ada's still in, with Bob shown without two-factor. + let (_, state) = a.call(Method::GET, "/api/v1/state", None).await; + let bob_member = state["members"] + .as_array() + .unwrap() + .iter() + .find(|m| m["id"] == json!(id("mem", "a2"))) + .unwrap() + .clone(); + assert_eq!(bob_member["twoFactor"], false); + assert_eq!( + state["teams"] + .as_array() + .unwrap() + .iter() + .find(|t| t["id"] == json!(team_a)) + .unwrap()["requireTwoFactor"], + true + ); + // Required: Ada can't turn hers off. + let code = code_now(&db, &ada, 1).await; + let (st, _) = a + .call( + Method::POST, + "/api/auth/two-factor/disable", + Some(json!({ "code": code })), + ) + .await; + assert_eq!(st, StatusCode::FORBIDDEN); + + // ── What the audit log records from here on: anonymized addresses. + let (st, out) = a + .op(json!({ "op": "updateMemberRole", "id": id("mem", "a2"), "role": "viewer" })) + .await; + assert_eq!(st, StatusCode::OK, "{out}"); + let (st, key) = a.op(json!({ "op": "createApiToken", "id": format!("tok_{run}"), "name": "deploy bot", "access": "read", "teamIds": [team_a] })).await; + assert_eq!(st, StatusCode::OK, "{key}"); + let rows = audit_rows(&db, &team_a).await; + let role = rows + .iter() + .find(|r| r.0 == "member.role_changed") + .expect("role change"); + assert_eq!(role.3.as_deref(), Some("203.0.113.0"), "anonymized"); + assert!(has(&rows, "api_key.created")); + assert!( + !has(&audit_rows(&db, &team_b).await, "api_key.created"), + "only the key's teams" + ); + let feed: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.activity WHERE team_id = $1 AND data->>'type' = 'api_key.created'").bind(&team_a).fetch_one(&db).await.unwrap(); + assert_eq!(feed, 1, "in the team's notifications too"); + // Using the key: recorded as the API, with its name. + let token = key["token"].as_str().unwrap().to_owned(); + let mut req = Request::builder() + .method(Method::GET) + .uri(format!("/api/v1/audit-log?team={team_a}")) + .header(header::AUTHORIZATION, format!("Bearer {token}")) + .body(Body::empty()) + .unwrap(); + req.extensions_mut() + .insert(ConnectInfo("192.0.2.1:1".parse::().unwrap())); + let res = app.clone().oneshot(req).await.unwrap(); + assert_eq!( + res.status(), + StatusCode::OK, + "owners may read it with a key too" + ); + let (st, out) = a + .op(json!({ "op": "revokeApiToken", "id": format!("tok_{run}") })) + .await; + assert_eq!(st, StatusCode::OK, "{out}"); + assert!(has(&audit_rows(&db, &team_a).await, "api_key.revoked")); + + // ── Reading it: owners and admins only. + let (st, log) = a + .call( + Method::GET, + &format!("/api/v1/audit-log?team={team_a}"), + None, + ) + .await; + assert_eq!(st, StatusCode::OK, "{log}"); + assert_eq!(log["ips"], "anonymized"); + assert_eq!(log["days"], 365); + assert!( + log["people"] + .as_array() + .unwrap() + .iter() + .any(|p| p["id"] == json!(ada)) + ); + let (_, only_auth) = a + .call( + Method::GET, + &format!("/api/v1/audit-log?team={team_a}&action=auth"), + None, + ) + .await; + assert!( + only_auth["events"] + .as_array() + .unwrap() + .iter() + .all(|e| e["action"].as_str().unwrap().starts_with("auth.")) + ); + let (_, only_bob) = a + .call( + Method::GET, + &format!("/api/v1/audit-log?team={team_a}&person={bob}"), + None, + ) + .await; + let events = only_bob["events"].as_array().unwrap(); + assert!(!events.is_empty() && events.iter().all(|e| e["actor"]["id"] == json!(bob))); + let (_, none) = a + .call( + Method::GET, + &format!("/api/v1/audit-log?team={team_a}&from=4102444800000"), + None, + ) + .await; + assert!( + none["events"].as_array().unwrap().is_empty(), + "a date filter" + ); + let (st, csv) = a + .raw( + Method::GET, + &format!("/api/v1/audit-log?team={team_a}&format=csv"), + None, + ) + .await; + assert_eq!(st, StatusCode::OK); + let csv = String::from_utf8(csv).unwrap(); + assert!(csv.starts_with("time,person,email,action,")); + assert!(csv.contains(",member.role_changed,")); + // Bob in team B is a developer: no. + let (st, _) = b + .call( + Method::GET, + &format!("/api/v1/audit-log?team={team_b}"), + None, + ) + .await; + assert_eq!(st, StatusCode::FORBIDDEN); + // And team A he can't open at all. + let (st, _) = b + .call( + Method::GET, + &format!("/api/v1/audit-log?team={team_a}"), + None, + ) + .await; + assert_eq!(st, StatusCode::NOT_FOUND); + + // ── Off again: the requirement first, then her own, with a code. + let (st, _) = a + .op(json!({ "op": "setTeamSecurity", "teamId": team_a, "requireTwoFactor": false })) + .await; + assert_eq!(st, StatusCode::OK); + let code = code_now(&db, &ada, 1).await; + let (st, out) = a + .call( + Method::POST, + "/api/auth/two-factor/disable", + Some(json!({ "code": code })), + ) + .await; + assert_eq!(st, StatusCode::OK, "{out}"); + assert!(has( + &audit_rows(&db, &team_b).await, + "auth.two_factor_disabled" + )); + let feed: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.activity WHERE team_id = $1 AND data->>'type' = 'auth.two_factor_disabled'").bind(&team_b).fetch_one(&db).await.unwrap(); + assert_eq!(feed, 1, "the team hears of it"); + assert!( + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM pyo.recovery_codes WHERE user_id = $1" + ) + .bind(&ada) + .fetch_one(&db) + .await + .unwrap() + == 0 + ); + + // ── Pyo Cloud staff (admins of a hosted Pyo) always need it; the + // installation's rule needs it of everyone. + sqlx::query("UPDATE pyo.users SET is_admin = true WHERE id = $1") + .bind(&ada) + .execute(&db) + .await + .unwrap(); + let teams_of = |user: String, hosted: bool| { + let db = db.clone(); + async move { + sqlx::query_scalar::<_, String>("SELECT pyo.member_team_ids($1, NULL, $2)") + .bind(user) + .bind(hosted) + .fetch_one(&db) + .await + .unwrap() + } + }; + assert_eq!( + teams_of(ada.clone(), true).await, + "", + "staff without two-factor: no teams" + ); + assert!( + !teams_of(ada.clone(), false).await.is_empty(), + "self-hosted admins: as before" + ); + assert!( + !teams_of(bob.clone(), true).await.is_empty(), + "everyone else on Cloud: as before" + ); + let staff_admin: bool = sqlx::query_scalar( + "SELECT is_admin AND NOT pyo.needs_two_factor(id, true) FROM pyo.users WHERE id = $1", + ) + .bind(&ada) + .fetch_one(&db) + .await + .unwrap(); + assert!(!staff_admin, "and no admin powers until it's on"); + sqlx::query("INSERT INTO pyo.user_totp (user_id, secret_sealed, enabled_at) VALUES ($1, 'sb1:x', now())").bind(&ada).execute(&db).await.unwrap(); + assert!( + !teams_of(ada.clone(), true).await.is_empty(), + "staff with two-factor: in" + ); + // The installation's rule, in a transaction of its own: other tests + // run beside this one on the same database. + let mut tx = db.begin().await.unwrap(); + sqlx::query("INSERT INTO pyo.settings (key, value) VALUES ('security', '{\"requireTwoFactor\": true, \"auditDays\": 365}') ON CONFLICT (key) DO UPDATE SET value = excluded.value") + .execute(&mut *tx) + .await + .unwrap(); + let (bobs, needs): (String, bool) = sqlx::query_as( + "SELECT pyo.member_team_ids($1, NULL, false), pyo.needs_two_factor($1, false)", + ) + .bind(&bob) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!( + (bobs.as_str(), needs), + ("", true), + "the installation requires it" + ); + let adas: String = sqlx::query_scalar("SELECT pyo.member_team_ids($1, NULL, false)") + .bind(&ada) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert!(!adas.is_empty(), "accounts with it: as before"); + tx.rollback().await.unwrap(); + + // Nothing a team's request can change or remove in its log. + let mut tx = db.begin().await.unwrap(); + let user = crate::auth::User { + id: ada.clone(), + name: "ada".into(), + email: email("ada"), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + crate::rls::scope(&mut tx, &user).await.unwrap(); + let n = sqlx::query("DELETE FROM pyo.audit_events WHERE team_id = $1") + .bind(&team_a) + .execute(&mut *tx) + .await + .unwrap() + .rows_affected(); + assert_eq!(n, 0, "append only"); + let n = sqlx::query("UPDATE pyo.audit_events SET title = 'x' WHERE team_id = $1") + .bind(&team_a) + .execute(&mut *tx) + .await + .unwrap() + .rows_affected(); + assert_eq!(n, 0); + tx.rollback().await.unwrap(); + + for t in [&team_a, &team_b] { + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(t) + .execute(&db) + .await + .unwrap(); + } + for u in [&ada, &bob] { + sqlx::query("DELETE FROM pyo.users WHERE id = $1") + .bind(u) + .execute(&db) + .await + .unwrap(); + } + }); +} diff --git a/crates/pyo-api/src/terminal.rs b/crates/pyo-api/src/terminal.rs index bfa45172..8001050d 100644 --- a/crates/pyo-api/src/terminal.rs +++ b/crates/pyo-api/src/terminal.rs @@ -4,7 +4,7 @@ //! open a shell and dial back to `/api/agent/v1/terminals/`; this process //! relays bytes between the two. With several web replicas the agent may land //! on another one, which forwards its socket to the replica holding the -//! browser (`relay`, its pod address). +//! browser (`relay`, its pod address) with a relay ticket ([`hand_over`]). use crate::error::Query; use std::{collections::HashMap, sync::Arc, time::Duration}; @@ -39,8 +39,11 @@ use crate::{ const MAX_SESSION: Duration = Duration::from_secs(4 * 3600); /// How long the browser waits for the agent to dial back. const AGENT_WAIT: Duration = Duration::from_secs(20); +/// The header a forwarded agent socket carries its relay ticket in. +const RELAY_TICKET: &str = "x-pyo-relay-ticket"; -/// Browser sockets waiting for their agent, by session id. +/// Sockets waiting for their agent's, by session id: terminals' and log +/// follows' (logfollow.rs). pub type Waiting = Arc>>>; pub fn routes() -> Router { @@ -48,7 +51,9 @@ pub fn routes() -> Router { } pub fn agent_routes() -> Router { - Router::new().route("/terminals/{id}", get(agent_side)) + Router::new() + .route("/terminals/{id}", get(agent_side)) + .route("/relay/{id}", get(relayed)) } fn text(f: &TerminalFrame) -> Message { @@ -57,7 +62,7 @@ fn text(f: &TerminalFrame) -> Message { /// A page on another site can open WebSockets with the user's cookie, so /// browsers must come from this origin. -fn same_origin(headers: &HeaderMap) -> bool { +pub(crate) fn same_origin(headers: &HeaderMap) -> bool { let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) else { return true; }; @@ -77,9 +82,36 @@ struct OpenQuery { /// One of TERMINAL_SHELLS. #[serde(default)] shell: String, + /// A command to run instead of a shell, as a JSON array of its words + /// (`pyo exec -- cmd args`). + #[serde(default)] + command: String, + /// "false": no TTY (separate output streams, for scripts and pipes). + #[serde(default)] + tty: String, } -/// GET /api/v1/services/{id}/terminal?replica=&shell= (WebSocket). +/// A command's words from the query (a JSON array), checked: at most 256 +/// words and 64 KiB, no NUL bytes. Empty: a shell. +fn command_words(q: &str) -> ApiResult> { + if q.is_empty() { + return Ok(vec![]); + } + let words: Vec = serde_json::from_str(q) + .map_err(|_| ApiError::bad_request("The command is a JSON array of strings."))?; + if words.len() > 256 + || words.iter().map(String::len).sum::() > 64 * 1024 + || words.iter().any(|w| w.contains('\0')) + { + return Err(ApiError::bad_request("That command is too long.")); + } + if words.first().is_some_and(|w| w.is_empty()) { + return Err(ApiError::bad_request("Name the command to run.")); + } + Ok(words) +} + +/// GET /api/v1/services/{id}/terminal?replica=&shell=&command=&tty= (WebSocket). async fn open( State(s): State, SessionUser(user): SessionUser, @@ -107,21 +139,30 @@ async fn open( { return Err(ApiError::bad_request("That isn't a replica name.")); } + let command = command_words(&q.command)?; + let tty = q.tty != "false"; if !same_origin(&headers) { return Err(ApiError::forbidden( "Open the terminal from the Pyo dashboard.", )); } - if user - .key - .as_ref() - .is_some_and(|k| k.access != KeyAccess::Full) - { - return Err(ApiError::forbidden( - "Terminals need an API key with full access.", - )); + // A shell needs a key with full access. One command (a migration from + // CI) also runs with a deploy key. + if let Some(k) = &user.key { + let ok = match k.access { + KeyAccess::Full => true, + KeyAccess::Deploy => !command.is_empty(), + _ => false, + }; + if !ok { + return Err(ApiError::forbidden(if command.is_empty() { + "Terminals need an API key with full access." + } else { + "Running a command needs an API key with deploy or full access." + })); + } } - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = ops::team_of(&mut tx, "services", &service_id).await?; // A shell can read the service's secrets and change its files: developers and up. ops::require_role(&mut tx, &user, &team_id, Role::Developer).await?; @@ -164,13 +205,19 @@ async fn open( .bind(&q.replica) .execute(&mut *tx) .await?; + // Not the command's words: they may hold secrets. + let what = if command.is_empty() { + format!("Opened a terminal in {}", service.name) + } else { + format!("Ran a command in {}", service.name) + }; ops::log_activity( &mut tx, &team_id, &user.name, "service.terminal", "info", - &format!("Opened a terminal in {}", service.name), + &what, json!({ "kind": "service", "id": service_id, "label": service.name }), json!({ "serviceId": service_id }), ) @@ -185,6 +232,8 @@ async fn open( service, pod: q.replica, shell, + command, + tty, }, ) .await?; @@ -219,7 +268,6 @@ async fn open( async fn agent_side( State(s): State, cluster: AgentCluster, - headers: HeaderMap, Path(id): Path, ws: WebSocketUpgrade, ) -> ApiResult { @@ -234,33 +282,99 @@ async fn agent_side( let Some((relay_addr,)) = row else { return Err(ApiError::not_found("Terminal session")); }; - let local = s.terminals.lock().await.remove(&id); + hand_over(&s, &id, relay_addr, ws, "Terminal session").await +} + +/// The agent's socket for session `id`, to whoever waits for it: on this +/// replica, or forwarded to `relay_addr`, the replica holding the other +/// end. Terminals and log follows. +/// +/// Only this replica can check the agent: a signed request's nonce is +/// spent here, and a client certificate ends here. So the hop carries a +/// relay ticket instead, a random secret good once for a minute, whose +/// hash this replica leaves in the database for the other one to take +/// ([`relayed`]). Whatever the agent sent is never passed on. +pub(crate) async fn hand_over( + s: &AppState, + id: &str, + relay_addr: Option, + ws: WebSocketUpgrade, + what: &str, +) -> ApiResult { + let local = s.terminals.lock().await.remove(id); if let Some(waiting) = local { return Ok(ws.on_upgrade(move |agent| async move { let _ = waiting.send(agent); })); } - // The browser is on another replica: forward this socket there. + // The other end is on another replica: forward this socket there. let Some(addr) = relay_addr.filter(|a| Some(a) != s.config.relay_addr.as_ref()) else { - return Err(ApiError::not_found("Terminal session")); + return Err(ApiError::not_found(what)); }; - let mut req = format!("ws://{addr}/api/agent/v1/terminals/{id}") + let ticket = crate::ids::random_string(48); + sqlx::query("INSERT INTO pyo.relay_tickets (hash, session_id) VALUES ($1, $2)") + .bind(crate::ids::sha256_hex(&ticket)) + .bind(id) + .execute(&s.db) + .await?; + let _ = + sqlx::query("DELETE FROM pyo.relay_tickets WHERE created_at < now() - interval '1 minute'") + .execute(&s.db) + .await; + let mut req = format!("ws://{addr}/api/agent/v1/relay/{id}") .into_client_request() .map_err(anyhow::Error::from)?; - if let Some(auth) = headers.get(header::AUTHORIZATION) { - req.headers_mut() - .insert(header::AUTHORIZATION, auth.clone()); - } + req.headers_mut().insert( + RELAY_TICKET, + header::HeaderValue::from_str(&ticket).map_err(anyhow::Error::from)?, + ); let (upstream, _) = tokio_tungstenite::connect_async(req).await.map_err(|e| { ApiError::from(anyhow::anyhow!( - "couldn't reach the replica holding this terminal: {e}" + "couldn't reach the replica holding this session: {e}" )) })?; Ok(ws.on_upgrade(move |agent| forward(agent, upstream))) } +/// GET /api/agent/v1/relay/{id} (WebSocket): an agent's socket another +/// replica checked and forwarded here ([`hand_over`]), with its ticket. +/// Handed to whoever waits for it on this replica, never forwarded again. +async fn relayed( + State(s): State, + headers: HeaderMap, + Path(id): Path, + ws: WebSocketUpgrade, +) -> ApiResult { + let ticket = headers + .get(RELAY_TICKET) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + let taken = !ticket.is_empty() + && sqlx::query( + "DELETE FROM pyo.relay_tickets WHERE hash = $1 AND session_id = $2 AND created_at > now() - interval '1 minute'", + ) + .bind(crate::ids::sha256_hex(ticket)) + .bind(&id) + .execute(&s.db) + .await? + .rows_affected() + == 1; + if !taken { + return Err(ApiError::new( + axum::http::StatusCode::UNAUTHORIZED, + "This relay ticket is unknown or was used.", + )); + } + let Some(waiting) = s.terminals.lock().await.remove(&id) else { + return Err(ApiError::not_found("Session")); + }; + Ok(ws.on_upgrade(move |agent| async move { + let _ = waiting.send(agent); + })) +} + /// Shuttle frames between the browser and the agent until either side closes. -async fn relay(browser: WebSocket, agent: WebSocket) { +pub(crate) async fn relay(browser: WebSocket, agent: WebSocket) { let (mut b_tx, mut b_rx) = browser.split(); let (mut a_tx, mut a_rx) = agent.split(); let up = async { @@ -340,4 +454,144 @@ mod tests { assert!(same_origin(&h(None))); assert!(!same_origin(&h(Some("https://evil.example")))); } + + #[test] + fn command_words_are_checked() { + assert_eq!(command_words("").unwrap(), Vec::::new()); + assert_eq!(command_words(r#"["ls","-la"]"#).unwrap(), ["ls", "-la"]); + assert!(command_words("ls -la").is_err()); + assert!(command_words(r#"[""]"#).is_err()); + assert!(command_words(r#"["a\u0000b"]"#).is_err()); + let long = serde_json::to_string(&vec!["x"; 300]).unwrap(); + assert!(command_words(&long).is_err()); + } + + /// A web replica on a port of its own, like a pod: the agent's routes + /// behind the signed request check. + async fn replica(db: &sqlx::PgPool) -> (AppState, String) { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap().to_string(); + let mut s = crate::rls::tests::state(db.clone()); + let mut config = (*s.config).clone(); + config.relay_addr = Some(addr.clone()); + s.config = Arc::new(config); + let app = Router::new() + .nest( + "/api/agent/v1", + agent_routes() + .merge(crate::logfollow::agent_routes()) + .layer(axum::middleware::from_fn_with_state( + s.clone(), + crate::agent_auth::signed, + )), + ) + .with_state(s.clone()); + tokio::spawn(async move { axum::serve(l, app).await }); + (s, addr) + } + + /// Against a throwaway Postgres: an agent's signed socket (no bearer + /// token, as on Pyo Cloud) lands on another web replica than the one + /// holding the reader. It reaches the reader all the same, and the + /// hop's ticket works once and can't be made up. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn a_signed_agent_socket_reaches_the_reader_on_another_replica() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + let run = crate::ids::random_string(8); + let (team, cluster, project, service) = ( + format!("team_r{run}"), + format!("cl_r{run}"), + format!("prj_r{run}"), + format!("svc_r{run}"), + ); + 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) VALUES ($1, $2, $1, $1, 'connected', now())").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(); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web', '{}', 'running')").bind(&service).bind(&team).bind(&project).bind(&cluster).execute(&db).await.unwrap(); + let key = pyo_proto::agentauth::RequestKey::from_pkcs8( + &pyo_proto::agentauth::RequestKey::generate_pkcs8().unwrap(), + ) + .unwrap(); + let key_id = format!("akey_r{run}"); + q("INSERT INTO pyo.agent_keys (id, cluster_id, public_key, expires_at) VALUES ($1, $2, $3, now() + interval '1 hour')").bind(&key_id).bind(&cluster).bind(key.public_key()).execute(&db).await.unwrap(); + + let (_a, a_addr) = replica(&db).await; + let (b, b_addr) = replica(&db).await; + // The reader follows on B. + let follow = new_id("lgf"); + q("INSERT INTO pyo.log_follows (id, team_id, service_id, relay) VALUES ($1, $2, $3, $4)") + .bind(&follow) + .bind(&team) + .bind(&service) + .bind(&b_addr) + .execute(&db) + .await + .unwrap(); + let (send, recv) = oneshot::channel(); + b.terminals.lock().await.insert(follow.clone(), send); + + // The agent dials A. + let path = format!("/api/agent/v1/log-follows/{follow}"); + let mut req = format!("ws://{a_addr}{path}") + .into_client_request() + .unwrap(); + for (h, v) in key.sign(&key_id, "GET", &path, b"", pyo_proto::now_ms() / 1000) { + req.headers_mut().insert(h, v.parse().unwrap()); + } + let (mut agent, _) = tokio_tungstenite::connect_async(req) + .await + .expect("the agent's socket is taken"); + let mut reader_end = tokio::time::timeout(Duration::from_secs(5), recv) + .await + .expect("B gets the agent's socket") + .unwrap(); + let hello = r#"{"type":"lines","lines":[]}"#; + agent.send(tungstenite::Message::text(hello)).await.unwrap(); + match reader_end.recv().await { + Some(Ok(Message::Text(t))) => assert_eq!(t.as_str(), hello), + other => panic!("the agent's frame, not {other:?}"), + } + + // The ticket went with the hop, and one made up gets nothing. + let left: i64 = + sqlx::query_scalar("SELECT count(*) FROM pyo.relay_tickets WHERE session_id = $1") + .bind(&follow) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(left, 0); + let (send, _recv) = oneshot::channel(); + b.terminals.lock().await.insert(follow.clone(), send); + let mut forged = format!("ws://{b_addr}/api/agent/v1/relay/{follow}") + .into_client_request() + .unwrap(); + forged + .headers_mut() + .insert(RELAY_TICKET, "made-up".parse().unwrap()); + assert!(tokio_tungstenite::connect_async(forged).await.is_err()); + assert!( + b.terminals.lock().await.contains_key(&follow), + "the reader still waits for its agent" + ); + + q("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + } } diff --git a/crates/pyo-api/src/totals.rs b/crates/pyo-api/src/totals.rs new file mode 100644 index 00000000..a67dd5da --- /dev/null +++ b/crates/pyo-api/src/totals.rs @@ -0,0 +1,999 @@ +//! Traffic totals: what each cluster's traffic store adds up per minute +//! (pyo-proto's traffic.rs), the only website and port traffic Pyo keeps. +//! Raw requests and visitors' addresses stay in the clusters. +//! +//! Minutes go into `traffic_1m` and `ports_1m`, kept 3 days (an hour or a +//! day, and the one before it); a materialized view adds them up per hour +//! into `traffic_1h` and `ports_1h`, kept 12 months by default (the +//! installation's retention, or a team's shorter one: retention.rs). All +//! four are AggregatingMergeTree tables of simple aggregates: sums, maps +//! that add up (`sumMap`) and HyperLogLog registers that merge (`maxMap`), +//! so rows for the same key (a late minute, a part not merged yet) add up +//! when read. A batch is stored once, however often the agent sends it +//! (its id is ClickHouse's insert deduplication token). +//! +//! The analytics page, the firewall's and the WAF's pages, port +//! connections and the per-server figures read only these, so they work +//! with a cluster offline. Ranges of an hour or a day read minutes; a week +//! or a month read hours. + +use std::collections::{BTreeMap, HashMap}; + +use pyo_proto::traffic::{ + self as t, HLL_M, HostTotals, LATENCY_BUCKETS, PortTotals, TotalsBatch, TrafficContext, hll_sql, + latency_quantile, +}; +use serde_json::{Value, json}; + +use crate::error::{ApiError, ApiResult}; +use crate::observability::{ClickHouse, Observability, bar_steps}; + +/// The columns both website tables have, as ClickHouse types. +const TRAFFIC_COLUMNS: &str = " + ts DateTime('UTC'), + team_id LowCardinality(String), + service_id LowCardinality(String), + host LowCardinality(String), + cluster_id SimpleAggregateFunction(anyLast, LowCardinality(String)), + project_id SimpleAggregateFunction(anyLast, LowCardinality(String)), + requests SimpleAggregateFunction(sum, UInt64), + pageviews SimpleAggregateFunction(sum, UInt64), + bytes SimpleAggregateFunction(sum, UInt64), + errors SimpleAggregateFunction(sum, UInt64), + duration_ms SimpleAggregateFunction(sum, Float64), + statuses SimpleAggregateFunction(sumMap, Map(String, UInt64)), + methods SimpleAggregateFunction(sumMap, Map(String, UInt64)), + latency SimpleAggregateFunction(sumMap, Map(UInt16, UInt64)), + visitors SimpleAggregateFunction(maxMap, Map(UInt16, UInt8)), + countries SimpleAggregateFunction(sumMap, Map(String, UInt64)), + paths SimpleAggregateFunction(sumMap, Map(String, UInt64)), + pages SimpleAggregateFunction(sumMap, Map(String, UInt64)), + referrers SimpleAggregateFunction(sumMap, Map(String, UInt64)), + devices SimpleAggregateFunction(sumMap, Map(String, UInt64)), + browsers SimpleAggregateFunction(sumMap, Map(String, UInt64)), + params SimpleAggregateFunction(sumMap, Map(String, UInt64)), + servers SimpleAggregateFunction(sumMap, Map(String, UInt64)), + server_errors SimpleAggregateFunction(sumMap, Map(String, UInt64)), + server_latency SimpleAggregateFunction(sumMap, Map(String, UInt64)), + blocked SimpleAggregateFunction(sumMap, Map(String, UInt64)), + blocked_countries SimpleAggregateFunction(sumMap, Map(String, UInt64)), + blocked_paths SimpleAggregateFunction(sumMap, Map(String, UInt64)), + waf_blocked SimpleAggregateFunction(sumMap, Map(String, UInt64)), + waf_logged SimpleAggregateFunction(sumMap, Map(String, UInt64)), + waf_countries SimpleAggregateFunction(sumMap, Map(String, UInt64)), + waf_paths SimpleAggregateFunction(sumMap, Map(String, UInt64)), + waf_visitors SimpleAggregateFunction(maxMap, Map(UInt16, UInt8))"; + +const PORT_COLUMNS: &str = " + ts DateTime('UTC'), + team_id LowCardinality(String), + service_id LowCardinality(String), + port UInt16, + protocol LowCardinality(String), + cluster_id SimpleAggregateFunction(anyLast, LowCardinality(String)), + project_id SimpleAggregateFunction(anyLast, LowCardinality(String)), + connections SimpleAggregateFunction(sum, UInt64), + bytes_in SimpleAggregateFunction(sum, UInt64), + bytes_out SimpleAggregateFunction(sum, UInt64), + duration SimpleAggregateFunction(sumMap, Map(UInt16, UInt64)), + outcomes SimpleAggregateFunction(sumMap, Map(String, UInt64)), + countries SimpleAggregateFunction(sumMap, Map(String, UInt64)), + visitors SimpleAggregateFunction(maxMap, Map(UInt16, UInt8)), + blocked SimpleAggregateFunction(sumMap, Map(String, UInt64)), + blocked_countries SimpleAggregateFunction(sumMap, Map(String, UInt64))"; + +/// Each column's merge (for the hourly views): sum, sumMap, maxMap or anyLast. +fn merges(columns: &str) -> Vec<(String, &'static str)> { + columns + .lines() + .filter_map(|l| { + let l = l.trim().trim_end_matches(','); + let (name, ty) = l.split_once(' ')?; + let f = if ty.starts_with("SimpleAggregateFunction(sumMap") { + "sumMap" + } else if ty.starts_with("SimpleAggregateFunction(maxMap") { + "maxMap" + } else if ty.starts_with("SimpleAggregateFunction(sum") { + "sum" + } else if ty.starts_with("SimpleAggregateFunction(anyLast") { + "anyLast" + } else { + return None; + }; + Some((name.to_owned(), f)) + }) + .collect() +} + +/// The statements that make the totals' tables and views. +pub fn schema() -> Vec { + let table = |name: &str, cols: &str, key: &str, part: &str, ttl: &str| { + format!( + "CREATE TABLE IF NOT EXISTS pyo_observability.{name} ({cols}) ENGINE = AggregatingMergeTree \ + PARTITION BY {part} ORDER BY ({key}) TTL {ttl} SETTINGS non_replicated_deduplication_window = 1000" + ) + }; + let view = |name: &str, from: &str, to: &str, cols: &str, keys: &str| { + let merged = merges(cols) + .into_iter() + .map(|(c, f)| format!("{f}({c}) AS {c}")) + .collect::>() + .join(", "); + format!( + "CREATE MATERIALIZED VIEW IF NOT EXISTS pyo_observability.{name} TO pyo_observability.{to} AS \ + SELECT toStartOfHour(m.ts) AS ts, {keys}, {merged} FROM pyo_observability.{from} AS m GROUP BY ts, {keys}" + ) + }; + vec![ + table("traffic_1m", TRAFFIC_COLUMNS, "team_id, host, ts, service_id", "toYYYYMMDD(ts)", "ts + INTERVAL 3 DAY"), + table("traffic_1h", TRAFFIC_COLUMNS, "team_id, host, ts, service_id", "toYYYYMM(ts)", "ts + INTERVAL 12 MONTH"), + view("traffic_1h_mv", "traffic_1m", "traffic_1h", TRAFFIC_COLUMNS, "team_id, service_id, host"), + table("ports_1m", PORT_COLUMNS, "team_id, service_id, port, protocol, ts", "toYYYYMMDD(ts)", "ts + INTERVAL 3 DAY"), + table("ports_1h", PORT_COLUMNS, "team_id, service_id, port, protocol, ts", "toYYYYMM(ts)", "ts + INTERVAL 12 MONTH"), + view("ports_1h_mv", "ports_1m", "ports_1h", PORT_COLUMNS, "team_id, service_id, port, protocol"), + // The WAF's rule messages, by team (custom rules are the team's own). + "CREATE TABLE IF NOT EXISTS pyo_observability.waf_rules (team_id LowCardinality(String), rule String, message String, seen DateTime('UTC')) \ + ENGINE = ReplacingMergeTree(seen) ORDER BY (team_id, rule) TTL seen + INTERVAL 12 MONTH" + .to_owned(), + ] +} + +// ── Taking totals in ──────────────────────────────────────────────────────── + +/// A batch's limits, so a cluster can't store more than real traffic makes. +const MAX_ROWS: usize = 20_000; +const MAX_KEYS: usize = 250; + +fn capped(m: &BTreeMap, max_len: usize) -> BTreeMap { + m.iter() + .filter(|(k, _)| k.len() <= max_len) + .take(MAX_KEYS) + .map(|(k, v)| (k.clone(), v.clone())) + .collect() +} + +fn hll(m: &t::Hll) -> BTreeMap { + m.iter() + .filter(|(i, r)| (**i as usize) < HLL_M && **r > 0 && **r <= 64) + .map(|(i, r)| (*i, *r)) + .collect() +} + +fn hist(m: &BTreeMap) -> BTreeMap { + m.iter().filter(|(b, _)| **b <= LATENCY_BUCKETS).map(|(b, n)| (*b, *n)).collect() +} + +/// Who a host or port belongs to. +#[derive(Clone, Debug)] +pub struct Owner { + pub team_id: String, + pub project_id: String, + pub service_id: String, +} + +/// One host's minute as a `traffic_1m` row. +pub fn host_row(cluster_id: &str, o: &Owner, h: &HostTotals) -> Value { + json!({ + "ts": h.minute, "team_id": o.team_id, "service_id": o.service_id, "host": h.host, + "cluster_id": cluster_id, "project_id": o.project_id, + "requests": h.requests, "pageviews": h.pageviews.min(h.requests), "bytes": h.bytes, "errors": h.errors.min(h.requests), + "duration_ms": if h.duration_ms.is_finite() { h.duration_ms.max(0.0) } else { 0.0 }, + "statuses": capped(&h.statuses, 8), "methods": capped(&h.methods, 16), "latency": hist(&h.latency), + "visitors": hll(&h.visitors), "countries": capped(&h.countries, 8), + "paths": capped(&h.paths, 400), "pages": capped(&h.pages, 400), "referrers": capped(&h.referrers, 260), + "devices": capped(&h.devices, 32), "browsers": capped(&h.browsers, 64), "params": capped(&h.params, 300), + "servers": capped(&h.servers, 260), "server_errors": capped(&h.server_errors, 260), "server_latency": capped(&h.server_latency, 270), + "blocked": capped(&h.blocked, 200), "blocked_countries": capped(&h.blocked_countries, 8), "blocked_paths": capped(&h.blocked_paths, 400), + "waf_blocked": capped(&h.waf_blocked, 16), "waf_logged": capped(&h.waf_logged, 16), + "waf_countries": capped(&h.waf_countries, 10), "waf_paths": capped(&h.waf_paths, 400), "waf_visitors": hll(&h.waf_visitors), + }) +} + +pub fn port_row(cluster_id: &str, o: &Owner, port: u16, p: &PortTotals) -> Value { + json!({ + "ts": p.minute, "team_id": o.team_id, "service_id": o.service_id, "port": port, + "protocol": if p.protocol == "UDP" { "UDP" } else { "TCP" }, + "cluster_id": cluster_id, "project_id": o.project_id, + "connections": p.connections, "bytes_in": p.bytes_in, "bytes_out": p.bytes_out, + "duration": hist(&p.duration), "outcomes": capped(&p.outcomes, 16), "countries": capped(&p.countries, 8), + "visitors": hll(&p.visitors), "blocked": capped(&p.blocked, 200), "blocked_countries": capped(&p.blocked_countries, 8), + }) +} + +impl Observability { + /// Stores a batch of a cluster's totals: its services' hosts and ports + /// only (Pyo's view of them, not the cluster's), minutes from the + /// last week. Returns the rows stored. + pub async fn ingest_totals(&self, cluster_id: &str, b: &TotalsBatch) -> ApiResult { + let Some(ch) = self.store().await else { + return Ok(0); + }; + if !self.is_ready().await { + return Err(ApiError::new(axum::http::StatusCode::SERVICE_UNAVAILABLE, "Observability storage is starting.")); + } + let now = pyo_proto::now_ms() / 1000; + let fresh = |minute: i64| minute % 60 == 0 && minute > now - 7 * 86400 && minute < now + 300; + let owners = self.owners().await?; + let mut hosts = String::new(); + let mut n = 0; + let mut teams: Vec = vec![]; + for h in b.hosts.iter().take(MAX_ROWS) { + let host = h.host.to_lowercase(); + let Some(o) = owners.get(&host).filter(|o| o.cluster_id == cluster_id) else { continue }; + if !fresh(h.minute) { + continue; + } + let owner = Owner { team_id: o.team_id.clone(), project_id: o.project_id.clone(), service_id: o.service_id.clone() }; + if !teams.contains(&owner.team_id) { + teams.push(owner.team_id.clone()); + } + let mut h = h.clone(); + h.host = host; + hosts.push_str(&host_row(cluster_id, &owner, &h).to_string()); + hosts.push('\n'); + n += 1; + } + let routes = if b.ports.is_empty() { Default::default() } else { self.port_routes().await? }; + let mut ports = String::new(); + for p in b.ports.iter().take(MAX_ROWS) { + let Some((o, port)) = routes.get(&(cluster_id.to_owned(), p.key.clone())) else { continue }; + if !fresh(p.minute) { + continue; + } + let owner = Owner { team_id: o.team_id.clone(), project_id: o.project_id.clone(), service_id: o.service_id.clone() }; + ports.push_str(&port_row(cluster_id, &owner, *port, p).to_string()); + ports.push('\n'); + n += 1; + } + // Stored once per batch, however often it's sent. + let token = |table: &str| format!("{cluster_id}:{}:{table}", b.id.chars().take(100).collect::()); + if !hosts.is_empty() { + ch.insert("traffic_1m", hosts, &token("traffic")).await?; + } + if !ports.is_empty() { + ch.insert("ports_1m", ports, &token("ports")).await?; + } + if !b.waf_messages.is_empty() && !teams.is_empty() { + let mut rows = String::new(); + for team in &teams { + for (rule, msg) in b.waf_messages.iter().take(500) { + if rule.len() <= 16 { + let msg: String = msg.chars().take(300).collect(); + rows.push_str(&json!({ "team_id": team, "rule": rule, "message": msg, "seen": now }).to_string()); + rows.push('\n'); + } + } + } + ch.insert("waf_rules", rows, &token("waf")).await?; + } + Ok(n) + } +} + +/// Pyo's view of a cluster's traffic for its traffic store: its services' +/// hosts and proxied ports, their firewalls, the IP setting and the +/// cluster's team's limits. +pub async fn context(db: &sqlx::PgPool, cluster_id: &str, team_id: &str) -> ApiResult { + let mut tx = db.begin().await?; + let rows: Vec<(String, String, String, Value, Value)> = sqlx::query_as( + "SELECT a.id, p.namespace, a.name, a.spec->'domains', a.spec->'ports' + FROM pyo.services a JOIN pyo.projects p ON p.id = a.project_id + WHERE a.cluster_id = $1 AND NOT a.deleting", + ) + .bind(cluster_id) + .fetch_all(&mut *tx) + .await?; + let mut ctx = TrafficContext::default(); + for (id, ns, name, domains, ports) in rows { + for d in domains.as_array().into_iter().flatten() { + if let Some(h) = d["hostname"].as_str() { + ctx.hosts.insert(h.to_lowercase(), id.clone()); + } + } + for (key, port) in port_keys(&ns, &name, &ports) { + ctx.ports.insert(key, (id.clone(), port)); + } + let f = crate::firewall::for_service(&mut tx, &id).await?; + if !f.is_unrestricted() { + ctx.firewalls.insert(id, f); + } + } + let prefs: Value = sqlx::query_scalar("SELECT preferences FROM pyo.teams WHERE id = $1") + .bind(team_id) + .fetch_optional(&mut *tx) + .await? + .unwrap_or_default(); + tx.commit().await?; + let (mb, days) = t::limits_from(&prefs); + ctx.max_mb = mb; + ctx.max_days = days; + ctx.ip_mode = serde_json::to_value(crate::observability::ip_mode(db).await?) + .ok() + .and_then(|v| v.as_str().map(str::to_owned)) + .unwrap_or_else(|| "none".into()); + Ok(ctx) +} + +/// A service's proxied ports as the cluster names them: its route +/// (`---`) and where the proxy listens +/// (`/`), each with the public port. +pub fn port_keys(ns: &str, name: &str, ports: &Value) -> Vec<(String, u16)> { + let mut out = vec![]; + for p in ports.as_array().into_iter().flatten().filter_map(crate::deploy::port_spec).filter(|p| p.proxied()) { + let public = p.public() as u16; + out.push((format!("{ns}-{name}-{}-{}", p.transport().to_lowercase(), p.public()), public)); + out.push((format!("{}/{}", p.transport(), pyo_proto::proxy_listen_port(p.public())), public)); + } + out +} + +// ── Reading totals ────────────────────────────────────────────────────────── + +/// Which table a range reads, its buckets, and the window: (table suffix, +/// points, step, start, end). The last bucket holds `now`. +pub fn window(range: &str, now: i64) -> (&'static str, i64, i64, i64, i64) { + let (table, points, step) = match range { + "1h" => ("1m", 60, 60), + "24h" => ("1m", 48, 1800), + "30d" => ("1h", 30, 86400), + _ => ("1h", 42, 14400), + }; + let end = (now / step + 1) * step; + (table, points, step, end - points * step, end) +} + +fn num(v: &Value, k: &str) -> f64 { + v[k].as_f64() + .or_else(|| v[k].as_str().and_then(|s| s.parse().ok())) + .filter(|x| x.is_finite()) + .unwrap_or(0.0) +} + +/// A map column as returned (an object) as (key, count) pairs, largest first. +fn pairs(v: &Value) -> Vec<(String, f64)> { + let mut out: Vec<(String, f64)> = v + .as_object() + .into_iter() + .flatten() + .map(|(k, n)| (k.clone(), n.as_f64().or_else(|| n.as_str().and_then(|s| s.parse().ok())).unwrap_or(0.0))) + .collect(); + out.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))); + out +} + +/// A latency map column as a histogram. +fn histogram(v: &Value) -> BTreeMap { + v.as_object() + .into_iter() + .flatten() + .filter_map(|(k, n)| Some((k.parse().ok()?, n.as_u64().or_else(|| n.as_str().and_then(|s| s.parse().ok()))?))) + .collect() +} + +fn q(h: &BTreeMap, q: f64) -> f64 { + latency_quantile(h, q).round() +} + +/// `[a,b]` as a ClickHouse array literal parameter. +pub fn array_param(items: &[String]) -> String { + format!( + "[{}]", + items + .iter() + .map(|h| format!("'{}'", h.replace(['\\', '\''], ""))) + .collect::>() + .join(",") + ) +} + +impl Observability { + /// The analytics page's data for a set of hostnames of one team, from + /// the totals. + pub async fn query(&self, team_id: &str, hosts: &[String], range: &str) -> ApiResult { + let ch = self.reader().await?; + let (table, points, step, start, end) = window(range, pyo_proto::now_ms() / 1000); + let prev_start = start - points * step; + let hosts_param = array_param(hosts); + let p = |s: i64, e: i64| -> Vec<(&'static str, String)> { + vec![ + ("team", team_id.to_owned()), + ("hosts", hosts_param.clone()), + ("start", s.to_string()), + ("end", e.to_string()), + ("step", step.to_string()), + ] + }; + let from = format!("pyo_observability.traffic_{table}"); + const W: &str = "team_id = {team:String} AND has({hosts:Array(String)}, host) AND ts >= toDateTime({start:Int64}) AND ts < toDateTime({end:Int64})"; + let visitors = hll_sql("maxMap(visitors)"); + let summary_sql = format!( + "SELECT sum(requests) AS requests, sum(pageviews) AS pageviews, sum(bytes) / 1e6 AS mb, sum(errors) AS errors, + sumMap(latency) AS latency, sumMap(statuses) AS statuses, {visitors} AS visitors + FROM {from} WHERE {W}" + ); + let top = |col: &str, limit: u32| { + format!( + "SELECT k, sum(v) AS n FROM {from} ARRAY JOIN mapKeys({col}) AS k, mapValues({col}) AS v WHERE {W} GROUP BY k ORDER BY n DESC, k LIMIT {limit}" + ) + }; + let (cur, prev, series, paths, pages, refs, countries, devices, browsers, params) = tokio::try_join!( + ch.rows(summary_sql.clone(), p(start, end)), + ch.rows(summary_sql.clone(), p(prev_start, start)), + ch.rows( + format!( + "SELECT toUnixTimestamp(toStartOfInterval(ts, toIntervalSecond({{step:Int64}}))) AS b, sum(requests) AS requests, + sum(pageviews) AS pageviews, sum(bytes) / 1e6 AS mb, sum(errors) AS errors, sumMap(latency) AS latency, {visitors} AS visitors + FROM {from} WHERE {W} GROUP BY b ORDER BY b" + ), + p(start, end) + ), + ch.rows(top("paths", 25), p(start, end)), + ch.rows(top("pages", 100), p(start, end)), + ch.rows(top("referrers", 25), p(start, end)), + ch.rows(top("countries", 25), p(start, end)), + ch.rows(top("devices", 10), p(start, end)), + ch.rows(top("browsers", 15), p(start, end)), + ch.rows(top("params", 30), p(start, end)), + )?; + let c = cur.first().cloned().unwrap_or_default(); + let pv = prev.first().cloned().unwrap_or_default(); + let requests = num(&c, "requests"); + let lat = histogram(&c["latency"]); + let by_bucket: HashMap = series.iter().map(|r| (r["b"].as_i64().unwrap_or(0), r)).collect(); + let series: Vec = (0..points) + .map(|i| { + let b = start + i * step; + let r = by_bucket.get(&b); + let g = |k: &str| r.map(|r| num(r, k)).unwrap_or(0.0); + let h = r.map(|r| histogram(&r["latency"])).unwrap_or_default(); + json!({ + "at": b * 1000, + "requests": g("requests"), "pageviews": g("pageviews"), "visitors": g("visitors").round(), "bandwidthMb": g("mb"), "errors": g("errors"), + "p50": q(&h, 0.5), "p95": q(&h, 0.95), "p99": q(&h, 0.99), + }) + }) + .collect(); + let statuses = pairs(&c["statuses"]); + let status_codes: Vec = ["2xx", "3xx", "4xx", "5xx"] + .iter() + .map(|code| json!({ "code": code, "count": statuses.iter().find(|s| s.0 == *code).map(|s| s.1).unwrap_or(0.0) })) + .collect(); + let kv = |rows: &[Value], key: &str, label: &str| -> Vec { + rows.iter().map(|r| json!({ key: r["k"], label: num(r, "n") })).collect() + }; + let path_of = |url: &str| url.split('?').next().unwrap_or(url).to_owned(); + let summary = json!({ + "range": range, + "requests": requests, + "estimatedVisitors": num(&c, "visitors").round(), + "pageviews": num(&c, "pageviews"), + "bandwidthMb": num(&c, "mb"), + "errorRate": if requests > 0.0 { num(&c, "errors") / requests } else { 0.0 }, + "latency": { "p50": q(&lat, 0.5), "p95": q(&lat, 0.95), "p99": q(&lat, 0.99) }, + "statusCodes": status_codes, + "topPaths": kv(&paths, "path", "requests"), + "referrers": kv(&refs, "source", "views"), + "countries": countries.iter().map(|r| json!({ "code": r["k"].as_str().filter(|c| !c.is_empty()).unwrap_or("??"), "requests": num(r, "n") })).collect::>(), + "pages": pages.iter().map(|r| { let url = r["k"].as_str().unwrap_or(""); json!({ "url": url, "path": path_of(url), "views": num(r, "n") }) }).collect::>(), + "devices": kv(&devices, "label", "views"), + "browsers": kv(&browsers, "label", "views"), + "queryParams": params.iter().map(|r| json!({ "key": r["k"], "requests": num(r, "n"), "redacted": t::sensitive(r["k"].as_str().unwrap_or("")) })).collect::>(), + }); + let prev_requests = num(&pv, "requests"); + Ok(json!({ + "summary": summary, + "series": series, + "previous": { + "requests": prev_requests, + "estimatedVisitors": num(&pv, "visitors").round(), + "pageviews": num(&pv, "pageviews"), + "errorRate": if prev_requests > 0.0 { num(&pv, "errors") / prev_requests } else { 0.0 }, + }, + })) + } + + /// The request explorer's totals for some hosts over a range: requests, + /// bytes, errors and response times. None without storage. + pub async fn request_summary(&self, team_id: &str, hosts: &[String], since_s: i64) -> ApiResult> { + let Some(ch) = self.store().await else { return Ok(None) }; + let table = if pyo_proto::now_ms() / 1000 - since_s <= 2 * 86400 { "1m" } else { "1h" }; + let r = ch + .rows( + format!( + "SELECT sum(requests) AS requests, sum(bytes) AS bytes, sumMap(statuses) AS statuses, sumMap(latency) AS latency + FROM pyo_observability.traffic_{table} + WHERE team_id = {{team:String}} AND has({{hosts:Array(String)}}, host) AND ts >= toDateTime({{since:Int64}})" + ), + vec![("team", team_id.to_owned()), ("hosts", array_param(hosts)), ("since", since_s.to_string())], + ) + .await?; + let r = r.first().cloned().unwrap_or_default(); + let s = pairs(&r["statuses"]); + let count = |c: &str| s.iter().find(|x| x.0 == c).map(|x| x.1).unwrap_or(0.0); + let h = histogram(&r["latency"]); + Ok(Some(json!({ + "requests": num(&r, "requests"), "bytes": num(&r, "bytes"), + "serverErrors": count("5xx"), "clientErrors": count("4xx"), + "p50": q(&h, 0.5), "p95": q(&h, 0.95), + }))) + } + + /// Requests, server errors and response times per answering server, + /// for some hostnames over the last `hours`. Empty without storage. + pub async fn per_server(&self, team_id: &str, hosts: &[String], hours: i64) -> ApiResult> { + let Some(ch) = self.store().await else { return Ok(vec![]) }; + if hosts.is_empty() { + return Ok(vec![]); + } + let since = pyo_proto::now_ms() / 1000 - hours * 3600; + let r = ch + .rows( + "SELECT sumMap(servers) AS servers, sumMap(server_errors) AS errors, sumMap(server_latency) AS latency + FROM pyo_observability.traffic_1h + WHERE team_id = {team:String} AND has({hosts:Array(String)}, host) AND ts >= toStartOfHour(toDateTime({since:Int64}))" + .into(), + vec![("team", team_id.to_owned()), ("hosts", array_param(hosts)), ("since", since.to_string())], + ) + .await?; + let r = r.first().cloned().unwrap_or_default(); + let errors: HashMap = pairs(&r["errors"]).into_iter().collect(); + // "|" -> requests, per server. + let mut hists: HashMap> = HashMap::new(); + for (k, n) in pairs(&r["latency"]) { + if let Some((server, b)) = k.rsplit_once('|') + && let Ok(b) = b.parse::() + { + *hists.entry(server.to_owned()).or_default().entry(b).or_insert(0) += n as u64; + } + } + Ok(pairs(&r["servers"]) + .into_iter() + .map(|(node, requests)| { + let h = hists.get(&node).cloned().unwrap_or_default(); + let total: u64 = h.values().sum(); + let avg = if total > 0 { + h.iter().map(|(b, n)| t::latency_of(*b) * *n as f64).sum::() / total as f64 + } else { + 0.0 + }; + json!({ "node": node, "requests": requests, "errors": errors.get(&node).copied().unwrap_or(0.0), + "avgMs": (avg * 10.0).round() / 10.0, "p95Ms": q(&h, 0.95) }) + }) + .collect()) + } + + /// Requests per answering server per hour, for the last `hours` + /// (sparklines). Empty without storage. + pub async fn per_server_hourly(&self, team_id: &str, hosts: &[String], hours: i64) -> ApiResult> { + let Some(ch) = self.store().await else { return Ok(vec![]) }; + if hosts.is_empty() { + return Ok(vec![]); + } + let since = pyo_proto::now_ms() / 1000 - hours * 3600; + let rows = ch + .rows( + "SELECT toUnixTimestamp(ts) AS hour, sumMap(servers) AS servers + FROM pyo_observability.traffic_1h + WHERE team_id = {team:String} AND has({hosts:Array(String)}, host) AND ts >= toStartOfHour(toDateTime({since:Int64})) + GROUP BY hour" + .into(), + vec![("team", team_id.to_owned()), ("hosts", array_param(hosts)), ("since", since.to_string())], + ) + .await?; + Ok(rows + .iter() + .flat_map(|r| { + let hour = r["hour"].clone(); + pairs(&r["servers"]).into_iter().map(move |(node, n)| json!({ "node": node, "hour": hour, "requests": n })) + }) + .collect()) + } + + /// A service's connections to its public TCP and UDP ports through the + /// gateway: per port, over time, by country and outcome. The latest + /// ones are the cluster's (`recent`, added by the caller). + pub async fn connections(&self, team_id: &str, service_id: &str, range: &str) -> ApiResult { + let ch = self.reader().await?; + let (table, points, step, start, end) = bar_window(range); + let p = || -> Vec<(&'static str, String)> { + vec![ + ("team", team_id.to_owned()), + ("service", service_id.to_owned()), + ("start", start.to_string()), + ("end", end.to_string()), + ("step", step.to_string()), + ] + }; + let from = format!("pyo_observability.ports_{table}"); + const W: &str = "team_id = {team:String} AND service_id = {service:String} AND ts >= toDateTime({start:Int64}) AND ts < toDateTime({end:Int64})"; + let clients = hll_sql("maxMap(visitors)"); + let (ports, series, countries, outcomes) = tokio::try_join!( + ch.rows(format!("SELECT port, protocol, sum(connections) AS c, {clients} AS v, sum(bytes_in) AS bin, sum(bytes_out) AS bout, sumMap(duration) AS d, sumMap(outcomes) AS o FROM {from} WHERE {W} GROUP BY port, protocol ORDER BY port"), p()), + ch.rows(format!("SELECT toUnixTimestamp(toStartOfInterval(ts, toIntervalSecond({{step:Int64}}))) AS b, sum(connections) AS c, {clients} AS v, sum(bytes_in) + sum(bytes_out) AS bytes FROM {from} WHERE {W} GROUP BY b ORDER BY b"), p()), + ch.rows(format!("SELECT k, sum(v) AS n FROM {from} ARRAY JOIN mapKeys(countries) AS k, mapValues(countries) AS v WHERE {W} GROUP BY k ORDER BY n DESC LIMIT 25"), p()), + ch.rows(format!("SELECT k, sum(v) AS n FROM {from} ARRAY JOIN mapKeys(outcomes) AS k, mapValues(outcomes) AS v WHERE {W} GROUP BY k"), p()), + )?; + let by_bucket: HashMap = series.iter().map(|r| (r["b"].as_i64().unwrap_or(0), r)).collect(); + let series: Vec = (0..points) + .map(|i| { + let b = start + i * step; + let r = by_bucket.get(&b); + let g = |k: &str| r.map(|r| num(r, k)).unwrap_or(0.0); + json!({ "at": b * 1000, "connections": g("c"), "clients": g("v").round(), "bytes": g("bytes") }) + }) + .collect(); + Ok(json!({ + "range": range, + "ports": ports.iter().map(|r| { + let d = histogram(&r["d"]); + let o: HashMap = pairs(&r["o"]).into_iter().collect(); + let out = |k: &str| o.get(k).copied().unwrap_or(0.0); + json!({ + "port": r["port"], "protocol": r["protocol"], "connections": num(r, "c"), "clients": num(r, "v").round(), + "bytesIn": num(r, "bin"), "bytesOut": num(r, "bout"), "durationP50Ms": q(&d, 0.5), "durationP95Ms": q(&d, 0.95), + "blocked": out("blocked"), "limited": out("limited"), "unreachable": out("unreachable"), + }) + }).collect::>(), + "series": series, + "countries": countries.iter().map(|r| json!({ "code": r["k"].as_str().filter(|c| !c.is_empty()).unwrap_or("??"), "connections": num(r, "n") })).collect::>(), + "outcomes": outcomes.iter().map(|r| json!({ "outcome": r["k"], "count": num(r, "n") })).collect::>(), + "recent": [], + })) + } + + /// What the firewall turned away for these services: over time, per + /// rule, country and website path. Sources and the latest are the + /// cluster's (added by the caller). + pub async fn blocked(&self, team_id: &str, services: &[String], range: &str) -> ApiResult { + let ch = self.reader().await?; + let (table, _, step, start, end) = bar_window(range); + let p = || -> Vec<(&'static str, String)> { + vec![ + ("team", team_id.to_owned()), + ("services", array_param(services)), + ("start", start.to_string()), + ("end", end.to_string()), + ("step", step.to_string()), + ] + }; + const W: &str = "team_id = {team:String} AND has({services:Array(String)}, service_id) AND ts >= toDateTime({start:Int64}) AND ts < toDateTime({end:Int64})"; + // Website requests and port connections, as one. + let both = |col: &str| { + format!( + "(SELECT ts, {col} AS m FROM pyo_observability.traffic_{table} WHERE {W} UNION ALL SELECT ts, {col} AS m FROM pyo_observability.ports_{table} WHERE {W})" + ) + }; + let (rules, countries, paths, series) = tokio::try_join!( + ch.rows(format!("SELECT k, sum(v) AS n FROM {} ARRAY JOIN mapKeys(m) AS k, mapValues(m) AS v GROUP BY k ORDER BY n DESC LIMIT 50", both("blocked")), p()), + ch.rows(format!("SELECT k, sum(v) AS n FROM {} ARRAY JOIN mapKeys(m) AS k, mapValues(m) AS v GROUP BY k ORDER BY n DESC LIMIT 25", both("blocked_countries")), p()), + ch.rows(format!("SELECT k, sum(v) AS n FROM pyo_observability.traffic_{table} ARRAY JOIN mapKeys(blocked_paths) AS k, mapValues(blocked_paths) AS v WHERE {W} GROUP BY k ORDER BY n DESC LIMIT 25"), p()), + ch.rows(format!("SELECT toUnixTimestamp(toStartOfInterval(ts, toIntervalSecond({{step:Int64}}))) AS b, sum(arraySum(mapValues(m))) AS c FROM {} GROUP BY b", both("blocked")), p()), + )?; + Ok(json!({ + "range": range, + "total": rules.iter().map(|r| num(r, "n")).sum::(), + "series": crate::observability::bar_series(&series, range, |r| json!({ "count": r.map(|r| num(r, "c")).unwrap_or(0.0) })), + "rules": rules.iter().map(|r| json!({ "rule": r["k"], "count": num(r, "n") })).collect::>(), + "countries": countries.iter().map(|r| json!({ "country": r["k"], "count": num(r, "n") })).collect::>(), + "paths": paths.iter().map(|r| json!({ "path": r["k"], "count": num(r, "n") })).collect::>(), + "sources": [], + "recent": [], + })) + } + + /// The WAF's findings for these services: blocked and logged requests + /// over time, per rule, domain, country and path, and the custom + /// rules' match counts. Sources and the latest are the cluster's. + pub async fn waf_hits(&self, team_id: &str, services: &[String], range: &str) -> ApiResult { + let ch = self.reader().await?; + let (table, _, step, start, end) = bar_window(range); + let p = || -> Vec<(&'static str, String)> { + vec![ + ("team", team_id.to_owned()), + ("services", array_param(services)), + ("start", start.to_string()), + ("end", end.to_string()), + ("step", step.to_string()), + ] + }; + let from = format!("pyo_observability.traffic_{table}"); + const W: &str = "team_id = {team:String} AND has({services:Array(String)}, service_id) AND ts >= toDateTime({start:Int64}) AND ts < toDateTime({end:Int64})"; + let clients = hll_sql("maxMap(waf_visitors)"); + let split = |col: &str, limit: u32| { + format!( + "SELECT substring(k, 3) AS key, sumIf(v, startsWith(k, 'b:')) AS nb, sumIf(v, startsWith(k, 'l:')) AS nl + FROM {from} ARRAY JOIN mapKeys({col}) AS k, mapValues({col}) AS v WHERE {W} GROUP BY key ORDER BY nb + nl DESC LIMIT {limit}" + ) + }; + let (totals, blocked, logged, hosts, series, countries, paths, messages) = tokio::try_join!( + ch.rows(format!("SELECT sum(arraySum(mapValues(waf_blocked))) AS nb, sum(arraySum(mapValues(waf_logged))) AS nl, {clients} AS v FROM {from} WHERE {W}"), p()), + ch.rows(format!("SELECT k, sum(v) AS n FROM {from} ARRAY JOIN mapKeys(waf_blocked) AS k, mapValues(waf_blocked) AS v WHERE {W} GROUP BY k"), p()), + ch.rows(format!("SELECT k, sum(v) AS n FROM {from} ARRAY JOIN mapKeys(waf_logged) AS k, mapValues(waf_logged) AS v WHERE {W} GROUP BY k"), p()), + ch.rows(format!("SELECT host, sum(arraySum(mapValues(waf_blocked))) AS nb, sum(arraySum(mapValues(waf_logged))) AS nl FROM {from} WHERE {W} GROUP BY host HAVING nb + nl > 0 ORDER BY nb + nl DESC LIMIT 25"), p()), + ch.rows(format!("SELECT toUnixTimestamp(toStartOfInterval(ts, toIntervalSecond({{step:Int64}}))) AS b, sum(arraySum(mapValues(waf_blocked))) AS nb, sum(arraySum(mapValues(waf_logged))) AS nl FROM {from} WHERE {W} GROUP BY b"), p()), + ch.rows(split("waf_countries", 25), p()), + ch.rows(split("waf_paths", 25), p()), + ch.rows("SELECT rule, argMax(message, seen) AS message FROM pyo_observability.waf_rules WHERE team_id = {team:String} GROUP BY rule".into(), vec![("team", team_id.to_owned())]), + )?; + let t = totals.first().cloned().unwrap_or_default(); + let msg: HashMap = messages + .iter() + .map(|r| (r["rule"].as_str().unwrap_or("").to_owned(), r["message"].as_str().unwrap_or("").to_owned())) + .collect(); + // Every rule's matches, blocked or only logged. + let mut by_rule: BTreeMap = BTreeMap::new(); + for r in blocked.iter().chain(logged.iter()) { + if let Ok(rule) = r["k"].as_str().unwrap_or("").parse::() { + *by_rule.entry(rule).or_insert(0.0) += num(r, "n"); + } + } + // Custom rules are numbered from 1000000 (pyo_proto::WAF_RULE_IDS); + // the Core Rule Set's from 949000 are its scoring, not findings. + let mut rules: Vec<(u64, f64)> = by_rule + .iter() + .filter(|(r, _)| **r < 949_000 || **r >= 1_000_000) + .map(|(r, n)| (*r, *n)) + .collect(); + rules.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))); + rules.truncate(25); + Ok(json!({ + "range": range, + "blocked": num(&t, "nb"), "logged": num(&t, "nl"), "clients": num(&t, "v").round(), + "rules": rules.iter().map(|(r, n)| json!({ "rule": r, "message": msg.get(&r.to_string()).cloned().unwrap_or_default(), "count": n })).collect::>(), + "hosts": hosts.iter().map(|r| json!({ "host": r["host"], "blocked": num(r, "nb"), "logged": num(r, "nl") })).collect::>(), + "series": crate::observability::bar_series(&series, range, |r| json!({ "blocked": r.map(|r| num(r, "nb")).unwrap_or(0.0), "logged": r.map(|r| num(r, "nl")).unwrap_or(0.0) })), + "countries": countries.iter().map(|r| json!({ "country": r["key"], "blocked": num(r, "nb"), "logged": num(r, "nl") })).collect::>(), + "paths": paths.iter().map(|r| json!({ "path": r["key"], "blocked": num(r, "nb"), "logged": num(r, "nl") })).collect::>(), + "custom": by_rule.iter().filter(|(r, _)| **r >= 1_000_000).map(|(r, n)| json!({ "rule": r, "count": n })).collect::>(), + "sources": [], + "recent": [], + })) + } +} + +/// The firewall's, WAF's and connections' windows: like `window`, ending +/// now (`bar_steps`). +fn bar_window(range: &str) -> (&'static str, i64, i64, i64, i64) { + let (points, step) = bar_steps(range); + let table = if step < 3600 { "1m" } else { "1h" }; + let end = (pyo_proto::now_ms() / 1000 / step + 1) * step; + (table, points, step, end - points * step, end) +} + +impl ClickHouse { + /// Inserts JSON rows into a table, stored once per `token`. + pub async fn insert(&self, table: &str, rows: String, token: &str) -> anyhow::Result<()> { + self.exec_with( + &format!("INSERT INTO pyo_observability.{table} FORMAT JSONEachRow"), + Some(rows), + &[], + &[("insert_deduplication_token", token.to_owned()), ("deduplicate_blocks_in_dependent_materialized_views", "1".into())], + ) + .await + .map(|_| ()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hourly_views_merge_every_column() { + let s = schema(); + assert_eq!(s.len(), 7); + let view = &s[2]; + assert!(view.contains("sumMap(statuses) AS statuses")); + assert!(view.contains("maxMap(visitors) AS visitors")); + assert!(view.contains("sum(requests) AS requests")); + assert!(view.contains("anyLast(cluster_id) AS cluster_id")); + // Every aggregate column is in the view, and nothing else but the keys. + assert_eq!(merges(TRAFFIC_COLUMNS).len(), 29); + assert_eq!(merges(PORT_COLUMNS).len(), 11); + assert!(s[0].contains("TTL ts + INTERVAL 3 DAY") && s[1].contains("TTL ts + INTERVAL 12 MONTH")); + } + + #[test] + fn windows_pick_their_table() { + let now = 1_794_737_009; + for (range, table) in [("1h", "1m"), ("24h", "1m"), ("7d", "1h"), ("30d", "1h")] { + let (tb, points, step, start, end) = window(range, now); + assert_eq!(tb, table); + assert_eq!(end - start, points * step); + assert!(start <= now && now < end && end - step <= now); + } + } + + #[test] + fn rows_keep_to_their_limits() { + let o = Owner { team_id: "t".into(), project_id: "p".into(), service_id: "s".into() }; + let mut h = HostTotals { minute: 60, host: "a.example".into(), requests: 2, pageviews: 9, errors: 1, ..Default::default() }; + for i in 0..400 { + h.paths.insert(format!("/{i}"), 1); + } + h.paths.insert("/".repeat(1000), 1); + h.visitors.insert(5, 3); + h.visitors.insert(9999, 3); + h.latency.insert(500, 1); + let r = host_row("c", &o, &h); + assert_eq!(r["pageviews"], 2, "never more page views than requests"); + assert_eq!(r["paths"].as_object().unwrap().len(), MAX_KEYS); + assert_eq!(r["visitors"], json!({ "5": 3 })); + assert_eq!(r["latency"], json!({})); + } + + #[test] + fn port_keys_are_the_clusters() { + let ports = json!([{ "name": "db", "containerPort": 5432, "protocol": "TCP", "exposure": "loadbalancer", "publicPort": 5432 }, + { "name": "web", "containerPort": 80, "protocol": "TCP", "exposure": "public" }]); + let keys = port_keys("shop", "db", &ports); + assert_eq!(keys, [("shop-db-tcp-5432".to_owned(), 5432), ("TCP/5432".to_owned(), 5432)]); + } + + /// Against a throwaway ClickHouse (`PYO_TEST_CLICKHOUSE_URL`, user + /// `default`, password in `PYO_TEST_CLICKHOUSE_PASSWORD`): minutes go in + /// once however often they're sent, add up into hours, and every page + /// reads them back. + #[tokio::test] + #[ignore = "needs a throwaway ClickHouse"] + async fn clickhouse_end_to_end() { + let Ok(url) = std::env::var("PYO_TEST_CLICKHOUSE_URL") else { return }; + let password = std::env::var("PYO_TEST_CLICKHOUSE_PASSWORD").unwrap_or_default(); + let ch = ClickHouse::new(url.clone(), "default".into(), password.clone()); + ch.exec("DROP DATABASE IF EXISTS pyo_observability", None, &[]).await.unwrap(); + ch.exec("CREATE DATABASE pyo_observability", None, &[]).await.unwrap(); + for sql in schema() { + ch.exec(&sql, None, &[]).await.unwrap(); + } + let db = sqlx::postgres::PgPoolOptions::new().acquire_timeout(std::time::Duration::from_millis(200)).connect_lazy("postgres://nobody@127.0.0.1:1/none").unwrap(); + let obs = Observability::with(db, Some(ClickHouse::new(url, "default".into(), password))); + let o = Owner { team_id: "team_1".into(), project_id: "prj_1".into(), service_id: "svc_1".into() }; + let now = pyo_proto::now_ms() / 1000 / 60 * 60; + let minute = |m: i64, host: &str, visitors: std::ops::Range| { + let mut h = HostTotals { minute: now - m * 60, host: host.into(), requests: 10, pageviews: 4, bytes: 1000, errors: 1, duration_ms: 200.0, ..Default::default() }; + h.statuses.insert("2xx".into(), 9); + h.statuses.insert("5xx".into(), 1); + h.latency.insert(t::latency_bucket(20.0), 10); + for v in visitors { + t::hll_insert(&mut h.visitors, v.wrapping_mul(0x9e3779b97f4a7c15)); + } + h.paths.insert("/".into(), 6); + h.paths.insert("/api".into(), 4); + h.pages.insert("/?token=[redacted]".into(), 4); + h.referrers.insert("news.example".into(), 3); + h.countries.insert("ID".into(), 7); + h.countries.insert("".into(), 3); + h.params.insert("token".into(), 4); + h.servers.insert("sg-1".into(), 10); + h.server_errors.insert("sg-1".into(), 1); + h.server_latency.insert(format!("sg-1|{}", t::latency_bucket(20.0)), 10); + h.blocked.insert("office".into(), 2); + h.blocked_countries.insert("DE".into(), 2); + h.blocked_paths.insert("/admin".into(), 2); + h.waf_blocked.insert("942100".into(), 1); + h.waf_logged.insert("1000001".into(), 2); + h.waf_countries.insert("b:DE".into(), 1); + h.waf_countries.insert("l:ID".into(), 2); + h.waf_paths.insert("b:/login".into(), 1); + host_row("cl_1", &o, &h).to_string() + }; + // Three minutes, the same 100 visitors in each, and 50 new ones. + let rows = [minute(3, "a.example", 0..100), minute(2, "a.example", 0..100), minute(1, "a.example", 50..150)].join("\n"); + ch.insert("traffic_1m", rows.clone(), "cl_1:b1:traffic").await.unwrap(); + // Sent again (the agent didn't hear back): stored once. + ch.insert("traffic_1m", rows, "cl_1:b1:traffic").await.unwrap(); + // Someone else's host on the same team isn't in these hosts. + ch.insert("traffic_1m", minute(1, "b.example", 0..5), "cl_1:b2:traffic").await.unwrap(); + let mut p = PortTotals { minute: now - 60, key: "k".into(), protocol: "TCP".into(), connections: 4, bytes_in: 10, bytes_out: 20, ..Default::default() }; + p.outcomes.insert("ok".into(), 3); + p.outcomes.insert("blocked".into(), 1); + p.blocked.insert("office".into(), 1); + p.duration.insert(t::latency_bucket(1000.0), 4); + t::hll_insert(&mut p.visitors, 42); + ch.insert("ports_1m", port_row("cl_1", &o, 5432, &p).to_string(), "cl_1:b3:ports").await.unwrap(); + ch.insert("waf_rules", json!({ "team_id": "team_1", "rule": "942100", "message": "SQL Injection", "seen": now }).to_string(), "w").await.unwrap(); + + let hosts = vec!["a.example".to_owned()]; + for range in ["1h", "7d"] { + let a = obs.query("team_1", &hosts, range).await.unwrap(); + let s = &a["summary"]; + assert_eq!(s["requests"], 30.0, "{range}: stored once"); + assert_eq!(s["pageviews"], 12.0); + // HyperLogLog: within a few percent. + assert!((s["estimatedVisitors"].as_f64().unwrap() - 150.0).abs() <= 8.0, "{range}: {}", s["estimatedVisitors"]); + assert_eq!(s["statusCodes"][3], json!({ "code": "5xx", "count": 3.0 })); + assert_eq!(s["topPaths"][0], json!({ "path": "/", "requests": 18.0 })); + assert_eq!(s["pages"][0]["path"], "/"); + assert_eq!(s["countries"][1], json!({ "code": "??", "requests": 9.0 })); + assert_eq!(s["queryParams"][0]["redacted"], true); + assert!((s["errorRate"].as_f64().unwrap() - 0.1).abs() < 1e-9); + assert!(s["latency"]["p50"].as_f64().unwrap() > 15.0); + let points: f64 = a["series"].as_array().unwrap().iter().map(|p| p["requests"].as_f64().unwrap()).sum(); + assert_eq!(points, 30.0, "{range}"); + } + let sum = obs.request_summary("team_1", &hosts, now - 3600).await.unwrap().unwrap(); + assert_eq!((sum["requests"].as_f64(), sum["serverErrors"].as_f64()), (Some(30.0), Some(3.0))); + let servers = obs.per_server("team_1", &hosts, 24).await.unwrap(); + assert_eq!(servers[0]["node"], "sg-1"); + assert_eq!(servers[0]["errors"], 3.0); + assert!(servers[0]["p95Ms"].as_f64().unwrap() > 15.0); + let hourly = obs.per_server_hourly("team_1", &hosts, 24).await.unwrap(); + assert_eq!(hourly.iter().map(|r| r["requests"].as_f64().unwrap()).sum::(), 30.0); + let services = vec!["svc_1".to_owned()]; + let b = obs.blocked("team_1", &services, "24h").await.unwrap(); + // Two refusals in each of four minutes (both hosts), and a connection. + assert_eq!(b["total"], 9.0, "{b}"); + let w = obs.waf_hits("team_1", &services, "24h").await.unwrap(); + assert_eq!((w["blocked"].as_f64(), w["logged"].as_f64()), (Some(4.0), Some(8.0))); + assert_eq!(w["rules"][0]["message"], "", "the custom rule's message isn't known"); + assert!(w["rules"].as_array().unwrap().iter().any(|r| r["message"] == "SQL Injection")); + assert_eq!(w["custom"][0]["rule"], 1000001); + assert_eq!(w["countries"].as_array().unwrap().len(), 2); + let c = obs.connections("team_1", "svc_1", "1h").await.unwrap(); + assert_eq!(c["ports"][0]["connections"], 4.0); + assert_eq!(c["ports"][0]["blocked"], 1.0); + assert_eq!(c["ports"][0]["clients"], 1.0); + } + + + /// Against a throwaway Postgres (DATABASE_URL) and ClickHouse: a + /// cluster's totals are stored for its own services' hosts and ports + /// only, and its context names them with their firewalls and the + /// team's limits. + #[tokio::test] + #[ignore = "needs DATABASE_URL and PYO_TEST_CLICKHOUSE_URL (throwaway ones)"] + async fn a_cluster_stores_only_its_services_traffic() { + let (Ok(db_url), Ok(ch_url)) = (std::env::var("DATABASE_URL"), std::env::var("PYO_TEST_CLICKHOUSE_URL")) else { return }; + let pool = sqlx::PgPool::connect(&db_url).await.unwrap(); + crate::migrate::run(&pool).await.unwrap(); + let password = std::env::var("PYO_TEST_CLICKHOUSE_PASSWORD").unwrap_or_default(); + let ch = ClickHouse::new(ch_url.clone(), "default".into(), password.clone()); + ch.exec("CREATE DATABASE IF NOT EXISTS pyo_observability", None, &[]).await.unwrap(); + for sql in schema() { + ch.exec(&sql, None, &[]).await.unwrap(); + } + let run = crate::ids::new_id("t"); + let (team, one, two) = (format!("team_{run}"), format!("cl1_{run}"), format!("cl2_{run}")); + let q = |sql: &'static str| sqlx::query(sql); + q("INSERT INTO pyo.teams (id, name, slug, preferences) VALUES ($1, $1, $1, '{\"requestLogs\": {\"maxMb\": 2048, \"maxDays\": 3}}')").bind(&team).execute(&pool).await.unwrap(); + for c in [&one, &two] { + q("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash) VALUES ($1, $2, $1, $1)").bind(c).bind(&team).execute(&pool).await.unwrap(); + } + q("INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, 'p', 'shop')").bind(format!("prj_{run}")).bind(&team).execute(&pool).await.unwrap(); + let spec = |host: &str| json!({ "domains": [{ "id": "d", "hostname": host }], "ports": [{ "name": "db", "containerPort": 5432, "protocol": "TCP", "exposure": "loadbalancer", "publicPort": 5432 }] }); + let (web, other) = (format!("svc1_{run}"), format!("svc2_{run}")); + let host = format!("{run}.example.com").to_lowercase(); + let elsewhere = format!("x{run}.example.com").to_lowercase(); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec) VALUES ($1, $2, $3, $4, 'web', $5)").bind(&web).bind(&team).bind(format!("prj_{run}")).bind(&one).bind(spec(&host)).execute(&pool).await.unwrap(); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec) VALUES ($1, $2, $3, $4, 'api', $5)").bind(&other).bind(&team).bind(format!("prj_{run}")).bind(&two).bind(spec(&elsewhere)).execute(&pool).await.unwrap(); + q("INSERT INTO pyo.firewall_rules (id, service_id, team_id, action, operator, sources, position) VALUES ($1, $2, $3, 'block', 'in', '{DE}', 0)").bind(format!("fw_{run}")).bind(&web).bind(&team).execute(&pool).await.unwrap(); + + let ctx = context(&pool, &one, &team).await.unwrap(); + assert_eq!(ctx.hosts.get(&host), Some(&web)); + assert!(!ctx.hosts.contains_key(&elsewhere), "another cluster's"); + assert_eq!(ctx.ports.get("shop-web-tcp-5432"), Some(&(web.clone(), 5432))); + assert_eq!(ctx.ports.get("TCP/5432"), Some(&(web.clone(), 5432))); + assert_eq!(ctx.firewalls[&web].rules[0].sources, ["DE"]); + assert_eq!((ctx.max_mb, ctx.max_days, ctx.ip_mode.as_str()), (2048, 3, "none")); + + let obs = Observability::with(pool.clone(), Some(ClickHouse::new(ch_url, "default".into(), password))); + obs.ensure_ready_for_tests().await; + let minute = pyo_proto::now_ms() / 1000 / 60 * 60 - 60; + let h = |host: &str| HostTotals { minute, host: host.into(), requests: 5, ..Default::default() }; + let batch = TotalsBatch { + id: "b1".into(), + hosts: vec![h(&host.to_uppercase()), h(&elsewhere), h("scanner.example.net"), HostTotals { minute: minute - 30 * 86400, ..h(&host) }], + ports: vec![PortTotals { minute, key: "shop-web-tcp-5432".into(), protocol: "TCP".into(), connections: 2, ..Default::default() }], + ..Default::default() + }; + assert_eq!(obs.ingest_totals(&one, &batch).await.unwrap(), 2, "its own host (any case) and port, this month"); + let stored = ch + .rows("SELECT host, team_id, service_id, sum(requests) AS n FROM pyo_observability.traffic_1m WHERE team_id = {team:String} GROUP BY host, team_id, service_id".into(), vec![("team", team.clone())]) + .await + .unwrap(); + assert_eq!(stored.len(), 1); + assert_eq!((stored[0]["host"].as_str(), stored[0]["service_id"].as_str(), stored[0]["n"].as_f64()), (Some(host.as_str()), Some(web.as_str()), Some(5.0))); + q("DELETE FROM pyo.teams WHERE id = $1").bind(&team).execute(&pool).await.unwrap(); + } + +} diff --git a/crates/pyo-api/src/traffic.rs b/crates/pyo-api/src/traffic.rs index acbd5da4..02544768 100644 --- a/crates/pyo-api/src/traffic.rs +++ b/crates/pyo-api/src/traffic.rs @@ -279,7 +279,7 @@ pub async fn get( SessionUser(user): SessionUser, Path(id): Path, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team = team_of(&mut tx, "services", &id).await?; require_role(&mut tx, &user, &team, Role::Viewer).await?; let (cluster_id, spec, runtime): (String, Value, Value) = diff --git a/crates/pyo-api/src/twofactor.rs b/crates/pyo-api/src/twofactor.rs new file mode 100644 index 00000000..e85646d9 --- /dev/null +++ b/crates/pyo-api/src/twofactor.rs @@ -0,0 +1,881 @@ +//! Two-factor authentication with an authenticator app (TOTP, RFC 6238). +//! +//! Set up on the profile page: the account's password first, then a QR code +//! (or the secret to type in), then one code from the app to confirm. That +//! turns it on and shows 10 one-time recovery codes, once. The secret is +//! sealed with the installation's key (it's the account's, not a team's); +//! only the recovery codes' sha256 is kept. +//! +//! Signing in with a password (or a sign-in link) then asks for a code +//! from the app or a recovery code ([`start_challenge`], `/login/code`). A +//! passkey is enough on its own: it already proves the device and the +//! person. Each code works once (the last accepted time step is kept), and +//! wrong codes count per account and address (ratelimit.rs). +//! +//! Turning it off, or making new recovery codes, takes a code too. It +//! can't be turned off while it's required: a team the account is in +//! requires it (Team › Security), the installation does (Settings › +//! Security), or the account is Pyo Cloud staff (an admin of a hosted +//! Pyo). Until then those teams are out of reach (rls.rs leaves them out +//! of the request's scope), and staff aren't admins, but the account and +//! its profile still work, so it can be set up. + +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::{Router, extract::State, http::HeaderMap, routing::post}; +use axum_extra::extract::CookieJar; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::{PgConnection, PgPool}; +use totp_rs::{Algorithm, Builder, Secret, Totp}; + +use crate::{ + AppState, + audit::{self, Entry, Who}, + auth::{SessionUser, User, password_matches, require_csrf, start_session}, + error::{ApiError, ApiResult, Json}, + ids::{secret_token, sha256_hex}, + ratelimit::{self, ClientIp}, +}; + +/// Recovery codes made at a time. +pub const RECOVERY_CODES: usize = 10; +/// How long the code step of a sign-in waits. +const CHALLENGE_MINUTES: i32 = 5; +/// Codes one sign-in may try before it starts over. +const CHALLENGE_TRIES: i32 = 5; +const STEP: u64 = 30; + +pub fn routes() -> Router { + Router::new() + .route("/login/code", post(login_code)) + .route("/two-factor/setup", post(setup)) + .route("/two-factor/enable", post(enable)) + .route("/two-factor/disable", post(disable)) + .route("/two-factor/recovery-codes", post(new_recovery_codes)) +} + +// ── Codes ────────────────────────────────────────────────────────────────── + +fn totp(secret: &[u8]) -> ApiResult { + Builder::new() + .with_algorithm(Algorithm::SHA1) + .with_digits(6) + .with_skew(1) + .with_step_duration(STEP) + .with_secret(Secret::from(secret.to_vec())) + .build() + .map_err(|e| anyhow::anyhow!("authenticator secret: {e:?}").into()) +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// The time step `code` is good for at `time`, if it's the app's code and +/// newer than `last_step` (a code works once). +fn check_code(secret: &[u8], code: &str, time: u64, last_step: u64) -> Option { + let code: String = code.chars().filter(|c| !c.is_whitespace()).collect(); + if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) { + return None; + } + totp(secret) + .ok()? + .check(&code, time) + .filter(|step| *step > last_step) +} + +/// Letters and digits that can't be mistaken for each other. +const RECOVERY_ALPHABET: &[u8] = b"abcdefghjkmnpqrstuvwxyz23456789"; + +/// One recovery code: `xxxxx-xxxxx` (about 49 bits). +fn recovery_code() -> String { + let mut bytes = [0u8; 10]; + rand::fill(&mut bytes); + let chars: String = bytes + .iter() + .map(|b| RECOVERY_ALPHABET[*b as usize % RECOVERY_ALPHABET.len()] as char) + .collect(); + format!("{}-{}", &chars[..5], &chars[5..]) +} + +/// A recovery code as typed: case, spaces and the dash don't matter. +fn normalize_recovery(code: &str) -> Option { + let c: String = code + .chars() + .filter(|c| c.is_ascii_alphanumeric()) + .map(|c| c.to_ascii_lowercase()) + .collect(); + (c.len() == 10).then_some(c) +} + +fn recovery_hash(code: &str) -> Option { + normalize_recovery(code).map(|c| sha256_hex(&c)) +} + +/// New recovery codes for the account, replacing the old ones. +async fn replace_recovery_codes(conn: &mut PgConnection, user_id: &str) -> ApiResult> { + let codes: Vec = (0..RECOVERY_CODES).map(|_| recovery_code()).collect(); + sqlx::query("DELETE FROM pyo.recovery_codes WHERE user_id = $1") + .bind(user_id) + .execute(&mut *conn) + .await?; + for c in &codes { + sqlx::query("INSERT INTO pyo.recovery_codes (user_id, code_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING") + .bind(user_id) + .bind(recovery_hash(c)) + .execute(&mut *conn) + .await?; + } + Ok(codes) +} + +/// Which kind of code worked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Used { + App, + Recovery, +} + +/// Checks a code from the app, or a recovery code (used up), for an account +/// with two-factor on. Wrong ones count against the account and address. +async fn verify(state: &AppState, user_id: &str, ip: &str, code: &str) -> ApiResult> { + ratelimit::take( + &state.db, + &[ + (ratelimit::TWO_FACTOR_ACCOUNT, user_id), + (ratelimit::TWO_FACTOR_IP, ip), + ], + ) + .await?; + let used = verify_once(&state.db, &state.sealer, user_id, code, now()).await?; + if used.is_some() { + ratelimit::reset(&state.db, &ratelimit::TWO_FACTOR_ACCOUNT, user_id).await?; + ratelimit::forgive(&state.db, &ratelimit::TWO_FACTOR_IP, ip).await?; + } + Ok(used) +} + +/// [`verify`] without the limits, at `time`. +async fn verify_once( + db: &PgPool, + sealer: &crate::secrets::Sealer, + user_id: &str, + code: &str, + time: u64, +) -> ApiResult> { + let mut tx = db.begin().await?; + // Locked: two requests with the same code can't both get in. + let row: Option<(String, i64)> = sqlx::query_as( + "SELECT secret_sealed, last_step FROM pyo.user_totp WHERE user_id = $1 AND enabled_at IS NOT NULL FOR UPDATE", + ) + .bind(user_id) + .fetch_optional(&mut *tx) + .await?; + let Some((sealed, last_step)) = row else { + return Ok(None); + }; + let secret = open_secret(sealer, &sealed)?; + if let Some(step) = check_code(&secret, code, time, last_step.max(0) as u64) { + sqlx::query("UPDATE pyo.user_totp SET last_step = $2 WHERE user_id = $1") + .bind(user_id) + .bind(step as i64) + .execute(&mut *tx) + .await?; + tx.commit().await?; + return Ok(Some(Used::App)); + } + let Some(hash) = recovery_hash(code) else { + return Ok(None); + }; + let n = sqlx::query( + "UPDATE pyo.recovery_codes SET used_at = now() WHERE user_id = $1 AND code_hash = $2 AND used_at IS NULL", + ) + .bind(user_id) + .bind(hash) + .execute(&mut *tx) + .await? + .rows_affected(); + tx.commit().await?; + Ok((n == 1).then_some(Used::Recovery)) +} + +fn open_secret(sealer: &crate::secrets::Sealer, sealed: &str) -> ApiResult> { + let b32 = sealer + .open(sealed) + .map_err(|e| anyhow::anyhow!("authenticator secret: {e}"))?; + Secret::try_from_base32(&b32) + .map(|s| s.as_bytes().to_vec()) + .map_err(|e| anyhow::anyhow!("authenticator secret: {e:?}").into()) +} + +// ── State ────────────────────────────────────────────────────────────────── + +/// Whether the account has two-factor on. +pub async fn enabled(db: impl sqlx::PgExecutor<'_>, user_id: &str) -> sqlx::Result { + sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.user_totp WHERE user_id = $1 AND enabled_at IS NOT NULL)", + ) + .bind(user_id) + .fetch_one(db) + .await +} + +/// Why the account must keep two-factor, if it must: the installation, Pyo +/// Cloud's staff rule, or the first team that requires it. +async fn required_by(db: &PgPool, user_id: &str) -> ApiResult> { + let s = audit::settings(db).await?; + if s.require_two_factor { + return Ok(Some("This Pyo requires two-factor authentication.".into())); + } + let admin: bool = sqlx::query_scalar("SELECT is_admin FROM pyo.users WHERE id = $1") + .bind(user_id) + .fetch_optional(db) + .await? + .unwrap_or(false); + if crate::hosted() && admin { + return Ok(Some( + "Pyo Cloud staff always use two-factor authentication.".into(), + )); + } + let team: Option = sqlx::query_scalar( + "SELECT t.name FROM pyo.members m JOIN pyo.teams t ON t.id = m.team_id + WHERE m.user_id = $1 AND m.status = 'active' AND t.require_two_factor ORDER BY t.name LIMIT 1", + ) + .bind(user_id) + .fetch_optional(db) + .await?; + Ok(team.map(|t| format!("{t} requires two-factor authentication."))) +} + +/// What the dashboard shows about the account's two-factor: `enabled`, +/// `recoveryCodesLeft`, `required` (the installation or the staff rule +/// requires it of this account), `setupNeeded` (required and not on yet: +/// only the profile works) and `lockedTeams` (teams it can't open until +/// it's on). +pub async fn summary(db: &PgPool, user_id: &str) -> ApiResult { + let (on, left, setup_needed, admin): (bool, i64, bool, bool) = sqlx::query_as( + "SELECT EXISTS (SELECT 1 FROM pyo.user_totp WHERE user_id = $1 AND enabled_at IS NOT NULL), + (SELECT count(*) FROM pyo.recovery_codes WHERE user_id = $1 AND used_at IS NULL), + pyo.needs_two_factor($1, $2), + coalesce((SELECT is_admin FROM pyo.users WHERE id = $1), false)", + ) + .bind(user_id) + .bind(crate::hosted()) + .fetch_one(db) + .await?; + let required = (crate::hosted() && admin) || audit::settings(db).await?.require_two_factor; + let locked: Vec = sqlx::query_scalar( + "SELECT jsonb_build_object('id', t.id, 'name', t.name, 'slug', t.slug) + FROM pyo.members m JOIN pyo.teams t ON t.id = m.team_id + WHERE m.user_id = $1 AND m.status = 'active' AND NOT $2 AND ($3 OR t.require_two_factor) + ORDER BY t.created_at", + ) + .bind(user_id) + .bind(on) + .bind(setup_needed) + .fetch_all(db) + .await?; + Ok(json!({ + "enabled": on, + "recoveryCodesLeft": if on { left } else { 0 }, + "required": required, + "setupNeeded": setup_needed, + "lockedTeams": locked, + })) +} + +// ── Signing in ───────────────────────────────────────────────────────────── + +/// A sign-in that needs its code next: its secret, for `/login/code`. +pub async fn start_challenge(db: &PgPool, user_id: &str, method: &str) -> ApiResult { + sqlx::query("DELETE FROM pyo.sign_in_challenges WHERE expires_at < now() OR user_id = $1") + .bind(user_id) + .execute(db) + .await?; + let token = secret_token(); + sqlx::query( + "INSERT INTO pyo.sign_in_challenges (token_hash, user_id, method, expires_at) + VALUES ($1, $2, $3, now() + make_interval(mins => $4))", + ) + .bind(sha256_hex(&token)) + .bind(user_id) + .bind(method) + .bind(CHALLENGE_MINUTES) + .execute(db) + .await?; + Ok(token) +} + +/// What a sign-in answers once the password is right: the account, or +/// that a code comes next. +pub fn code_needed(challenge: &str) -> Value { + json!({ "twoFactor": true, "challenge": challenge }) +} + +#[derive(Deserialize)] +struct CodeBody { + challenge: String, + code: String, +} + +async fn login_code( + State(state): State, + ClientIp(ip): ClientIp, + headers: HeaderMap, + jar: CookieJar, + Json(body): Json, +) -> ApiResult<(CookieJar, Json)> { + require_csrf(&headers)?; + let hash = sha256_hex(body.challenge.trim()); + // A try used up whatever the answer. + let row: Option<(String, String, i32)> = sqlx::query_as( + "UPDATE pyo.sign_in_challenges SET attempts = attempts + 1 + WHERE token_hash = $1 AND expires_at > now() RETURNING user_id, method, attempts", + ) + .bind(&hash) + .fetch_optional(&state.db) + .await?; + let Some((user_id, method, attempts)) = row else { + return Err(ApiError::bad_request("That took too long. Sign in again.")); + }; + if attempts > CHALLENGE_TRIES { + sqlx::query("DELETE FROM pyo.sign_in_challenges WHERE token_hash = $1") + .bind(&hash) + .execute(&state.db) + .await?; + return Err(ApiError::bad_request( + "Too many wrong codes. Sign in again.", + )); + } + let user = sqlx::query_as::<_, User>( + "SELECT id, name, email, timezone, is_admin, must_set_up FROM pyo.users WHERE id = $1", + ) + .bind(&user_id) + .fetch_one(&state.db) + .await?; + let Some(used) = verify(&state, &user_id, &ip, &body.code).await? else { + audit::account_event( + &state.db, + &user_id, + &Who::person(&user), + Entry { + action: "auth.sign_in_failed", + title: "Wrong two-factor code", + target: json!({}), + failed: true, + }, + ) + .await; + return Err(ApiError::new( + axum::http::StatusCode::UNAUTHORIZED, + "That code didn't work. Try the newest one.", + )); + }; + sqlx::query("DELETE FROM pyo.sign_in_challenges WHERE token_hash = $1") + .bind(&hash) + .execute(&state.db) + .await?; + let how = match (method.as_str(), used) { + ("link", Used::App) => "Signed in with a sign-in link and a code", + ("link", Used::Recovery) => "Signed in with a sign-in link and a recovery code", + (_, Used::App) => "Signed in with a password and a code", + (_, Used::Recovery) => "Signed in with a password and a recovery code", + }; + audit::account_event( + &state.db, + &user_id, + &Who::person(&user), + Entry { + action: if used == Used::Recovery { + "auth.recovery_code_used" + } else { + "auth.sign_in" + }, + title: how, + target: json!({}), + failed: false, + }, + ) + .await; + let jar = start_session(&state, jar, &user_id, &headers).await?; + Ok((jar, Json(user))) +} + +// ── Managing ─────────────────────────────────────────────────────────────── + +/// Two-factor is managed from a browser session, never with an API key. +fn browser_only(user: &User) -> ApiResult<()> { + if user.key.is_some() { + Err(ApiError::forbidden("Manage two-factor in the dashboard.")) + } else { + Ok(()) + } +} + +#[derive(Deserialize)] +struct SetupBody { + password: String, +} + +/// A new secret to scan, waiting for its first code. Takes the password: +/// a stolen session alone can't put its own app on the account. +async fn setup( + State(state): State, + headers: HeaderMap, + SessionUser(user): SessionUser, + Json(body): Json, +) -> ApiResult> { + require_csrf(&headers)?; + browser_only(&user)?; + if enabled(&state.db, &user.id).await? { + return Err(ApiError::conflict("Two-factor is already on.")); + } + ratelimit::take(&state.db, &[(ratelimit::PASSKEY_PASSWORD_USER, &user.id)]).await?; + if !password_matches(&state.db, &user.id, &body.password).await? { + return Err(ApiError::forbidden("Wrong password.")); + } + ratelimit::reset(&state.db, &ratelimit::PASSKEY_PASSWORD_USER, &user.id).await?; + if !state.sealer.enabled() { + return Err(ApiError::bad_request( + "This Pyo has no secret key (PYO_SECRET_KEY) to keep the app's secret with.", + )); + } + let mut raw = [0u8; 20]; + rand::fill(&mut raw); + let secret = Secret::from(raw.to_vec()).to_base32(); + let sealed = state.sealer.seal(&secret)?; + sqlx::query( + "INSERT INTO pyo.user_totp (user_id, secret_sealed) VALUES ($1, $2) + ON CONFLICT (user_id) DO UPDATE SET secret_sealed = excluded.secret_sealed, created_at = now(), last_step = 0 + WHERE pyo.user_totp.enabled_at IS NULL", + ) + .bind(&user.id) + .bind(&sealed) + .execute(&state.db) + .await?; + let uri = otpauth_uri(&secret, &user.email); + Ok(Json(json!({ + "secret": grouped(&secret), + "uri": uri, + "qr": qr_svg(&uri)?, + }))) +} + +/// What an authenticator app scans. +fn otpauth_uri(secret: &str, email: &str) -> String { + let enc = |s: &str| -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'@' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() + }; + format!( + "otpauth://totp/Pyo:{}?secret={secret}&issuer=Pyo&algorithm=SHA1&digits=6&period={STEP}", + enc(email) + ) +} + +/// The secret in groups of four, easier to type. +fn grouped(secret: &str) -> String { + secret + .as_bytes() + .chunks(4) + .map(|c| String::from_utf8_lossy(c).into_owned()) + .collect::>() + .join(" ") +} + +fn qr_svg(uri: &str) -> ApiResult { + let code = qrcode::QrCode::new(uri.as_bytes()).map_err(|e| anyhow::anyhow!("QR code: {e}"))?; + Ok(code + .render::() + .min_dimensions(200, 200) + .quiet_zone(true) + .dark_color(qrcode::render::svg::Color("#000000")) + .light_color(qrcode::render::svg::Color("#ffffff")) + .build()) +} + +#[derive(Deserialize)] +struct CodeOnly { + code: String, +} + +/// The first code from the app: two-factor is on, and here are the +/// recovery codes, shown this once. +async fn enable( + State(state): State, + ClientIp(ip): ClientIp, + headers: HeaderMap, + SessionUser(user): SessionUser, + Json(body): Json, +) -> ApiResult> { + require_csrf(&headers)?; + browser_only(&user)?; + ratelimit::take( + &state.db, + &[ + (ratelimit::TWO_FACTOR_ACCOUNT, &user.id), + (ratelimit::TWO_FACTOR_IP, &ip), + ], + ) + .await?; + let mut tx = state.db.begin().await?; + let row: Option = sqlx::query_scalar( + "SELECT secret_sealed FROM pyo.user_totp WHERE user_id = $1 AND enabled_at IS NULL FOR UPDATE", + ) + .bind(&user.id) + .fetch_optional(&mut *tx) + .await?; + let sealed = row.ok_or_else(|| ApiError::bad_request("Start the setup again."))?; + let secret = open_secret(&state.sealer, &sealed)?; + let Some(step) = check_code(&secret, &body.code, now(), 0) else { + return Err(ApiError::bad_request( + "That code didn't work. Try the newest one.", + )); + }; + sqlx::query("UPDATE pyo.user_totp SET enabled_at = now(), last_step = $2 WHERE user_id = $1") + .bind(&user.id) + .bind(step as i64) + .execute(&mut *tx) + .await?; + let codes = replace_recovery_codes(&mut tx, &user.id).await?; + audit::account_event_in( + &mut tx, + &user.id, + &Who::person(&user), + Entry { + action: "auth.two_factor_enabled", + title: "Turned on two-factor authentication", + target: json!({}), + failed: false, + }, + ) + .await?; + tx.commit().await?; + ratelimit::reset(&state.db, &ratelimit::TWO_FACTOR_ACCOUNT, &user.id).await?; + ratelimit::forgive(&state.db, &ratelimit::TWO_FACTOR_IP, &ip).await?; + Ok(Json(json!({ "recoveryCodes": codes }))) +} + +/// Off, with a code (from the app or a recovery code), unless it's +/// required. The account's teams hear of it, and the account by email. +async fn disable( + State(state): State, + ClientIp(ip): ClientIp, + headers: HeaderMap, + SessionUser(user): SessionUser, + Json(body): Json, +) -> ApiResult> { + require_csrf(&headers)?; + browser_only(&user)?; + if !enabled(&state.db, &user.id).await? { + return Err(ApiError::conflict("Two-factor is already off.")); + } + if let Some(why) = required_by(&state.db, &user.id).await? { + return Err(ApiError::forbidden(format!( + "{why} It can't be turned off." + ))); + } + if verify(&state, &user.id, &ip, &body.code).await?.is_none() { + return Err(ApiError::bad_request( + "That code didn't work. Try the newest one.", + )); + } + let mut tx = state.db.begin().await?; + turn_off(&mut tx, &user.id).await?; + notify_teams( + &mut tx, + &user, + "auth.two_factor_disabled", + "Turned off two-factor authentication", + ) + .await?; + tx.commit().await?; + mail_user(&state, &user.email, "/profile", crate::mail::two_factor_off).await; + Ok(Json(json!({ "ok": true }))) +} + +/// Two-factor off for the account: its secret and recovery codes go. +pub async fn turn_off(conn: &mut PgConnection, user_id: &str) -> sqlx::Result<()> { + sqlx::query("DELETE FROM pyo.user_totp WHERE user_id = $1") + .bind(user_id) + .execute(&mut *conn) + .await?; + sqlx::query("DELETE FROM pyo.recovery_codes WHERE user_id = $1") + .bind(user_id) + .execute(&mut *conn) + .await?; + sqlx::query("DELETE FROM pyo.sign_in_challenges WHERE user_id = $1") + .bind(user_id) + .execute(&mut *conn) + .await?; + Ok(()) +} + +/// New recovery codes (the old ones stop working), with a code. +async fn new_recovery_codes( + State(state): State, + ClientIp(ip): ClientIp, + headers: HeaderMap, + SessionUser(user): SessionUser, + Json(body): Json, +) -> ApiResult> { + require_csrf(&headers)?; + browser_only(&user)?; + if verify(&state, &user.id, &ip, &body.code).await?.is_none() { + return Err(ApiError::bad_request( + "That code didn't work. Try the newest one.", + )); + } + let mut tx = state.db.begin().await?; + let codes = replace_recovery_codes(&mut tx, &user.id).await?; + audit::account_event_in( + &mut tx, + &user.id, + &Who::person(&user), + Entry { + action: "auth.recovery_codes_created", + title: "Made new recovery codes", + target: json!({}), + failed: false, + }, + ) + .await?; + tx.commit().await?; + Ok(Json(json!({ "recoveryCodes": codes }))) +} + +/// An entry in the activity of each of the account's teams (the bell, the +/// team's alerts and the audit log). +pub async fn notify_teams( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + user: &User, + kind: &str, + title: &str, +) -> ApiResult<()> { + notify_teams_in(tx, user, None, kind, title).await +} + +/// [`notify_teams`] for some of them (None: all). +pub async fn notify_teams_in( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + user: &User, + only: Option<&[String]>, + kind: &str, + title: &str, +) -> ApiResult<()> { + let teams: Vec = sqlx::query_scalar( + "SELECT team_id FROM pyo.members WHERE user_id = $1 AND status = 'active' AND ($2::text[] IS NULL OR team_id = ANY ($2)) ORDER BY team_id", + ) + .bind(&user.id) + .bind(only) + .fetch_all(&mut **tx) + .await?; + for team in teams { + crate::ops::log_activity( + tx, + &team, + &user.name, + kind, + "warning", + title, + json!({ "kind": "member", "id": user.id, "label": user.email }), + json!({}), + ) + .await?; + } + Ok(()) +} + +/// An email to the account, when this Pyo sends email. Never fails the +/// request: a failure is logged. +pub async fn mail_user( + state: &AppState, + to: &str, + path: &str, + template: impl FnOnce(&str) -> (String, String, String), +) { + let Ok(Some(cfg)) = crate::mail::settings(&state.db).await else { + return; + }; + let (subject, text, html) = template(&cfg.link(path)); + if let Err(e) = crate::mail::send(state, &cfg, to, &subject, text, html).await { + tracing::warn!(error = %format!("{e:#}"), "security email not sent"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SECRET: &[u8] = b"12345678901234567890"; + + /// RFC 6238's SHA-1 test vectors (the last 6 digits), and each code + /// working once. + #[test] + fn codes_follow_the_rfc_and_work_once() { + let t = totp(SECRET).unwrap(); + assert_eq!(t.generate(59).to_string(), "287082"); + assert_eq!(t.generate(1_111_111_109).to_string(), "081804"); + assert_eq!(t.generate(1_234_567_890).to_string(), "005924"); + let step = check_code(SECRET, "287 082", 59, 0).expect("good at its time"); + assert_eq!(step, 1); + // The step before and after still count (clocks drift). + assert!(check_code(SECRET, "287082", 59 + 30, 0).is_some()); + assert!(check_code(SECRET, "287082", 59 + 90, 0).is_none()); + // Used once: not again. + assert!(check_code(SECRET, "287082", 59, step).is_none()); + assert!(check_code(SECRET, "28708", 59, 0).is_none()); + assert!(check_code(SECRET, "abcdef", 59, 0).is_none()); + } + + #[test] + fn recovery_codes_read_easily() { + let c = recovery_code(); + assert_eq!(c.len(), 11); + assert_eq!(&c[5..6], "-"); + assert!( + c.chars() + .filter(|c| *c != '-') + .all(|ch| RECOVERY_ALPHABET.contains(&(ch as u8))) + ); + assert_ne!(recovery_code(), recovery_code()); + assert_eq!(recovery_hash("ABCDE-FGHJK"), recovery_hash(" abcde fghjk ")); + assert_eq!(recovery_hash("abc"), None); + } + + #[test] + fn the_app_gets_a_uri_and_a_qr_code() { + let uri = otpauth_uri("JBSWY3DPEHPK3PXP", "ada+ops@example.com"); + assert_eq!( + uri, + "otpauth://totp/Pyo:ada%2Bops@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Pyo&algorithm=SHA1&digits=6&period=30" + ); + assert!(qr_svg(&uri).unwrap().starts_with(" PgPool { + let db = PgPool::connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL")) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + db + } + + /// Against a throwaway Postgres: a code from the app works once, a + /// recovery code works once, and nothing works for an account that + /// hasn't confirmed its app. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn codes_and_recovery_codes_work_once() { + let db = db().await; + let sealer = crate::secrets::Sealer::for_tests(); + let user = format!("usr_{}", crate::ids::random_string(8).to_lowercase()); + sqlx::query("INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $1 || '@2fa.test', 'T', '')") + .bind(&user) + .execute(&db) + .await + .unwrap(); + let b32 = Secret::from(SECRET.to_vec()).to_base32(); + sqlx::query("INSERT INTO pyo.user_totp (user_id, secret_sealed) VALUES ($1, $2)") + .bind(&user) + .bind(sealer.seal(&b32).unwrap()) + .execute(&db) + .await + .unwrap(); + // Not confirmed yet: no code counts, and it isn't on. + assert_eq!( + verify_once(&db, &sealer, &user, "287082", 59) + .await + .unwrap(), + None + ); + assert!(!enabled(&db, &user).await.unwrap()); + sqlx::query("UPDATE pyo.user_totp SET enabled_at = now() WHERE user_id = $1") + .bind(&user) + .execute(&db) + .await + .unwrap(); + assert!(enabled(&db, &user).await.unwrap()); + assert_eq!( + verify_once(&db, &sealer, &user, "287082", 59) + .await + .unwrap(), + Some(Used::App) + ); + assert_eq!( + verify_once(&db, &sealer, &user, "287082", 59) + .await + .unwrap(), + None, + "the same code again" + ); + let mut conn = db.acquire().await.unwrap(); + let codes = replace_recovery_codes(&mut conn, &user).await.unwrap(); + assert_eq!(codes.len(), RECOVERY_CODES); + let stored: Vec = + sqlx::query_scalar("SELECT code_hash FROM pyo.recovery_codes WHERE user_id = $1") + .bind(&user) + .fetch_all(&db) + .await + .unwrap(); + assert!( + !stored.iter().any(|h| codes.contains(h)), + "only hashes are kept" + ); + let typed = codes[3].to_uppercase(); + assert_eq!( + verify_once(&db, &sealer, &user, &typed, 10_000) + .await + .unwrap(), + Some(Used::Recovery) + ); + assert_eq!( + verify_once(&db, &sealer, &user, &codes[3], 10_000) + .await + .unwrap(), + None, + "a recovery code works once" + ); + let left: Value = summary(&db, &user).await.unwrap(); + assert_eq!(left["enabled"], true); + assert_eq!(left["recoveryCodesLeft"], 9); + // New codes: the old ones stop working. + let fresh = replace_recovery_codes(&mut conn, &user).await.unwrap(); + assert_eq!( + verify_once(&db, &sealer, &user, &codes[4], 10_000) + .await + .unwrap(), + None + ); + assert_eq!( + verify_once(&db, &sealer, &user, &fresh[0], 10_000) + .await + .unwrap(), + Some(Used::Recovery) + ); + turn_off(&mut conn, &user).await.unwrap(); + assert!(!enabled(&db, &user).await.unwrap()); + assert_eq!( + verify_once(&db, &sealer, &user, &fresh[1], 10_000) + .await + .unwrap(), + None + ); + sqlx::query("DELETE FROM pyo.users WHERE id = $1") + .bind(&user) + .execute(&db) + .await + .unwrap(); + } +} diff --git a/crates/pyo-api/src/updates.rs b/crates/pyo-api/src/updates.rs index 595e7332..ede3f1a4 100644 --- a/crates/pyo-api/src/updates.rs +++ b/crates/pyo-api/src/updates.rs @@ -15,6 +15,12 @@ //! every cluster's agent is moved to the new agent image. Each step is a //! row in pyo.updates that the worker moves along, so it carries on across //! the very restarts it causes. +//! - A hosted Pyo (Pyo Cloud) is updated by whoever runs it, never from +//! here. Its agents follow its version ([`hosted_agents`]): each team has +//! automatic agent updates (the default), or chooses when, and then +//! updates a cluster's agent from the cluster's page +//! ([`update_cluster_agent`]). Either way it's the same `UpdateAgent` +//! command, signed for the cluster like every other. use std::time::Duration; @@ -751,6 +757,11 @@ pub async fn start( version: &str, user: Option<&crate::auth::User>, ) -> ApiResult { + if crate::hosted() { + return Err(ApiError::bad_request( + "This Pyo is updated by the people who run it. Its agents follow on their own.", + )); + } // One start at a time, across processes. let mut tx = s.db.begin().await?; sqlx::query("SELECT pg_advisory_xact_lock($1)") @@ -822,6 +833,123 @@ pub async fn start( Ok(id) } +// ── Agents on a hosted Pyo ───────────────────────────────────────────────── + +/// A team's agent updates: "auto" (the default) or "manual" (it chooses when). +pub const AGENT_UPDATE_MODES: [&str; 2] = ["auto", "manual"]; + +/// Clusters whose agent may be moved to this Pyo's: online, able to update +/// itself, not on this version, and without an update to this image sent +/// in the last hour (or failed in the last six). `$1`: this version, `$2`: +/// the agent image, `$3`: only teams with automatic updates. +const HOSTED_CANDIDATES: &str = "SELECT c.id, coalesce(c.agent_version, '') FROM pyo.clusters c JOIN pyo.teams t ON t.id = c.team_id + WHERE c.status <> 'pending' AND c.last_seen_at > now() - interval '2 minutes' + AND coalesce((c.capabilities->>'updates')::int, 0) >= 1 + AND c.agent_version IS DISTINCT FROM $1 + AND (NOT $3 OR t.agent_updates = 'auto') + AND NOT EXISTS (SELECT 1 FROM pyo.commands m + WHERE m.cluster_id = c.id AND m.command->>'kind' = 'update_agent' AND m.command->>'image' = $2 + AND m.created_at > now() - CASE WHEN m.status = 'failed' THEN interval '6 hours' ELSE interval '1 hour' END)"; + +/// Whether `agent` is older than this Pyo (an agent newer, or of a build +/// with no version, is left alone). +fn agent_behind(agent: &str) -> bool { + newer(current(), agent) +} + +/// Agents run only images pinned by digest: `PYO_AGENT_IMAGE` has to be one. +const UNPINNED: &str = "This Pyo's agent image isn't pinned by digest, so agents can't update to it."; + +/// Queues the update of one cluster's agent to this Pyo's image. +async fn send_update(s: &AppState, cluster_id: &str) -> ApiResult { + if !pyo_proto::pinned_image(&s.config.agent_image) { + return Err(ApiError::bad_request(UNPINNED)); + } + let mut tx = s.db.begin().await?; + let id = crate::deploy::enqueue( + &mut tx, + cluster_id, + Command::UpdateAgent { + image: s.config.agent_image.clone(), + }, + ) + .await?; + tx.commit().await?; + s.wake(cluster_id).await; + Ok(id) +} + +/// A hosted Pyo's automatic agent updates: every minute, each cluster of a +/// team with automatic updates whose agent is behind gets the update. +pub async fn hosted_agents(s: AppState) { + if !crate::hosted() { + return; + } + if !pyo_proto::pinned_image(&s.config.agent_image) { + tracing::warn!(image = %s.config.agent_image, "{UNPINNED} Automatic agent updates are off."); + return; + } + loop { + let st = s.clone(); + let ran = crate::bg::as_leader(&s.db, crate::bg::LOCK_AGENT_UPDATES, || async move { + let due: Vec<(String, String)> = sqlx::query_as(HOSTED_CANDIDATES) + .bind(current()) + .bind(&st.config.agent_image) + .bind(true) + .fetch_all(&st.db) + .await?; + for (cluster, agent) in due.into_iter().filter(|(_, a)| agent_behind(a)) { + let cmd = send_update(&st, &cluster).await?; + tracing::info!(%cluster, from = %agent, to = current(), command = %cmd, "updating a cluster's agent"); + } + ApiResult::Ok(()) + }) + .await; + if let Some(Err(e)) = ran { + tracing::warn!(error = %e.message, "hosted agent updates"); + } + tokio::time::sleep(Duration::from_secs(60)).await; + } +} + +/// A cluster's agent, updated now to this Pyo's version: for a hosted Pyo +/// (self-hosted ones update from the Updates page). Fails when it's on it +/// already, isn't reachable, or an update is on its way. +pub async fn update_cluster_agent(s: &AppState, cluster_id: &str) -> ApiResult { + if !crate::hosted() { + return Err(ApiError::bad_request("Update agents from Settings › Updates.")); + } + let row: Option<(Option, bool, i32)> = sqlx::query_as( + "SELECT agent_version, coalesce(last_seen_at > now() - interval '2 minutes', false), coalesce((capabilities->>'updates')::int, 0) + FROM pyo.clusters WHERE id = $1", + ) + .bind(cluster_id) + .fetch_optional(&s.db) + .await?; + let (agent, online, updates) = row.ok_or_else(|| ApiError::not_found("Cluster"))?; + let agent = agent.unwrap_or_default(); + if !agent_behind(&agent) { + return Err(ApiError::bad_request(format!("Its agent is on {} already.", current()))); + } + if !online { + return Err(ApiError::bad_request("Its agent isn't reachable. Update it once it's back.")); + } + if updates < 1 { + return Err(ApiError::bad_request("Its agent is too old to update itself. Run its connect command again.")); + } + let busy: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.commands WHERE cluster_id = $1 AND command->>'kind' = 'update_agent' + AND status IN ('pending', 'sent') AND created_at > now() - interval '10 minutes')", + ) + .bind(cluster_id) + .fetch_one(&s.db) + .await?; + if busy { + return Err(ApiError::conflict("Its agent is updating.")); + } + send_update(s, cluster_id).await +} + // ── Moving an update along (worker) ──────────────────────────────────────── pub async fn runner(state: AppState) { @@ -838,6 +966,10 @@ pub async fn runner(state: AppState) { } async fn tick(s: &AppState) -> ApiResult<()> { + // Updated by whoever runs it: its agents follow (hosted_agents). + if crate::hosted() { + return Ok(()); + } let cfg = settings(&s.db).await?; if cfg.check && !checks_off_by_env() { let c = checked(&s.db).await?; @@ -1648,3 +1780,78 @@ mod tests { ); } } + +#[cfg(test)] +mod hosted_tests { + use super::*; + + #[test] + fn only_older_agents_are_behind() { + let v = current(); + assert!(!agent_behind(v)); + assert!(agent_behind("0.0.1")); + assert!(!agent_behind("99.0.0")); + // A build with no version is left alone. + assert!(!agent_behind("")); + } + + /// Against a throwaway Postgres: the clusters due an update are those + /// online, able to update, behind, of teams with automatic updates (or + /// any team, asked for by hand), without an update to this image sent in + /// the last hour or failed in the last six. + #[tokio::test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres)"] + async fn agents_of_teams_with_automatic_updates_are_due() { + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").unwrap()).await.unwrap(); + crate::migrate::run(&db).await.unwrap(); + let run = crate::ids::random_string(8); + let (auto, manual) = (format!("team_u{run}"), format!("team_m{run}")); + let q = |sql: &'static str| sqlx::query(sql); + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)").bind(&auto).execute(&db).await.unwrap(); + q("INSERT INTO pyo.teams (id, name, slug, agent_updates) VALUES ($1, $1, $1, 'manual')").bind(&manual).execute(&db).await.unwrap(); + let image = format!("agent:{run}"); + let add = |id: &str, team: &str, version: &str, online: bool, updates: i32| { + let (db, id, team, version) = (db.clone(), format!("{id}{run}"), team.to_owned(), version.to_owned()); + async move { + sqlx::query("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash, status, agent_version, last_seen_at, capabilities) + VALUES ($1, $2, $1, $1, 'connected', $3, now() - CASE WHEN $4 THEN interval '0' ELSE interval '1 hour' END, $5)") + .bind(&id).bind(&team).bind(&version).bind(online).bind(json!({ "updates": updates })).execute(&db).await.unwrap(); + id + } + }; + let behind = add("cl_b", &auto, "0.0.1", true, 1).await; + let theirs = add("cl_m", &manual, "0.0.1", true, 1).await; + let current_one = add("cl_c", &auto, current(), true, 1).await; + let offline = add("cl_o", &auto, "0.0.1", false, 1).await; + let too_old = add("cl_t", &auto, "0.0.1", true, 0).await; + let sent = add("cl_s", &auto, "0.0.1", true, 1).await; + let failed_long_ago = add("cl_f", &auto, "0.0.1", true, 1).await; + let failed_now = add("cl_n", &auto, "0.0.1", true, 1).await; + let cmd = |id: &str, cluster: &str, status: &str, age: &str| { + let (db, id, cluster, status, age, image) = (db.clone(), format!("{id}{run}"), cluster.to_owned(), status.to_owned(), age.to_owned(), image.clone()); + async move { + sqlx::query("INSERT INTO pyo.commands (id, cluster_id, command, status, created_at) VALUES ($1, $2, $3, $4, now() - $5::interval)") + .bind(&id).bind(&cluster).bind(json!({ "kind": "update_agent", "image": image })).bind(&status).bind(&age).execute(&db).await.unwrap(); + } + }; + cmd("cmd_s", &sent, "done", "10 minutes").await; + cmd("cmd_f", &failed_long_ago, "failed", "7 hours").await; + cmd("cmd_n", &failed_now, "failed", "2 hours").await; + let due = |only_auto: bool| { + let (db, image, run) = (db.clone(), image.clone(), run.clone()); + async move { + let rows: Vec<(String, String)> = sqlx::query_as(HOSTED_CANDIDATES).bind(current()).bind(&image).bind(only_auto).fetch_all(&db).await.unwrap(); + let mut ids: Vec = rows.into_iter().filter(|(id, a)| id.ends_with(&run) && agent_behind(a)).map(|r| r.0).collect(); + ids.sort(); + ids + } + }; + let mut want = vec![behind.clone(), failed_long_ago.clone()]; + want.sort(); + assert_eq!(due(true).await, want); + assert!(due(false).await.contains(&theirs)); + for not in [¤t_one, &offline, &too_old, &sent, &failed_now] { + assert!(!due(false).await.contains(not), "{not} isn't due"); + } + } +} diff --git a/crates/pyo-api/src/vault.rs b/crates/pyo-api/src/vault.rs index 450ffcfb..c2590b63 100644 --- a/crates/pyo-api/src/vault.rs +++ b/crates/pyo-api/src/vault.rs @@ -352,6 +352,31 @@ impl Vault { )) } + /// Seals a team's credential (a token, password or private key) with + /// the team's data key. Never stored in the clear: refused when there's + /// no key to seal with. + pub async fn seal_credential(&self, team_id: &str, plain: &str) -> anyhow::Result { + ensure!( + self.provider.is_some(), + "this installation has no secret key (PYO_SECRET_KEY) to seal it with" + ); + self.seal(team_id, plain).await + } + + /// Opens a team's credential: sealed with the team's data key, or with + /// the installation's key by a release before 0.5. + pub async fn open_credential( + &self, + sealer: &crate::secrets::Sealer, + value: &str, + ) -> anyhow::Result { + if value.starts_with(crate::secrets::PREFIX) { + return sealer.open(value); + } + ensure!(Self::is_sealed(value), "a credential that isn't sealed"); + self.open(value).await + } + /// Open a sealed value; anything else is returned as it is. pub async fn open(&self, value: &str) -> anyhow::Result { let Some(rest) = value.strip_prefix(PREFIX) else { @@ -662,4 +687,164 @@ mod tests { visit_env(&mut doc, &mut |v| seen.push(v.as_str().unwrap().to_owned())); assert_eq!(seen, ["1", "2"]); } + + /// Against a throwaway Postgres, with PYO_SECRET_KEY set: the + /// credentials a team stores (deploy hook tokens, certificate keys, + /// its cluster's registry token) are sealed with that team's data key, + /// and ones an older release sealed with the installation's key open. + #[test] + #[ignore = "needs DATABASE_URL (a throwaway Postgres) and PYO_SECRET_KEY"] + fn team_credentials_are_sealed_with_the_teams_key() { + std::thread::Builder::new() + .stack_size(64 << 20) + .spawn(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + .block_on(team_credentials()) + }) + .unwrap() + .join() + .unwrap(); + } + + async fn team_credentials() { + std::env::var("PYO_SECRET_KEY").expect("PYO_SECRET_KEY"); + let db = PgPool::connect(&std::env::var("DATABASE_URL").unwrap()) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + init(Vault::new(db.clone(), Provider::from_env())); + let v = get(); + let run = crate::ids::random_string(8).to_lowercase(); + let (user_id, team, other) = ( + format!("usr_v{run}"), + format!("team_v{run}"), + format!("team_w{run}"), + ); + let (cluster, project) = (format!("cl_v{run}"), format!("prj_v{run}")); + for t in [&team, &other] { + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(t) + .execute(&db) + .await + .unwrap(); + } + sqlx::query("INSERT INTO pyo.users (id, email, name, password_hash) VALUES ($1, $1 || '@vault.test', $1, '')").bind(&user_id).execute(&db).await.unwrap(); + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $3 || '@vault.test', 'owner', 'active')").bind(format!("mem_v{run}")).bind(&team).bind(&user_id).execute(&db).await.unwrap(); + sqlx::query("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash) VALUES ($1, $2, $1, $1)").bind(&cluster).bind(&team).execute(&db).await.unwrap(); + sqlx::query( + "INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, 'p', $1)", + ) + .bind(&project) + .bind(&team) + .execute(&db) + .await + .unwrap(); + let user = crate::auth::User { + id: user_id.clone(), + name: "v".into(), + email: format!("{user_id}@vault.test"), + timezone: "UTC".into(), + is_admin: false, + must_set_up: false, + key: None, + }; + let s = crate::rls::tests::state(db.clone()); + // Sealed with this team's key: another team's can't take it as its own. + let the_teams = |sealed: String| { + let team = team.clone(); + let other = other.clone(); + async move { + assert!(sealed.starts_with(PREFIX), "{sealed}"); + v.check_owner(&team, &sealed).await.unwrap(); + assert!(v.check_owner(&other, &sealed).await.is_err()); + } + }; + + // A deploy hook's token. + let hook = format!("hook_v{run}"); + let made = crate::ops::run_json( + &s, + &user, + json!({ "op": "createDeployHook", "id": hook, "projectId": project, "name": "ci" }), + ) + .await + .unwrap(); + let sealed: String = + sqlx::query_scalar("SELECT token_sealed FROM pyo.deploy_hooks WHERE id = $1") + .bind(&hook) + .fetch_one(&db) + .await + .unwrap(); + the_teams(sealed).await; + let shown = + crate::ops::run_json(&s, &user, json!({ "op": "revealDeployHook", "id": hook })) + .await + .unwrap(); + assert_eq!(shown["path"], made["path"]); + + // An uploaded certificate's key. + let key = rcgen::KeyPair::generate().unwrap(); + let cert = rcgen::CertificateParams::new(vec![format!("v{run}.example.com")]) + .unwrap() + .self_signed(&key) + .unwrap(); + let crt = format!("crt_v{run}"); + crate::ops::run_json(&s, &user, json!({ "op": "uploadCertificate", "id": crt, "teamId": team, "name": "", "certificate": cert.pem(), "privateKey": key.serialize_pem() })).await.unwrap(); + let sealed: String = + sqlx::query_scalar("SELECT key_sealed FROM pyo.certificates WHERE id = $1") + .bind(&crt) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!( + v.open_credential(&s.sealer, &sealed).await.unwrap(), + key.serialize_pem() + ); + the_teams(sealed).await; + + // The cluster's registry token: made once, the same after. + let mut tx = db.begin().await.unwrap(); + let token = crate::ops::registry_token(&mut tx, &s, &cluster) + .await + .unwrap(); + assert_eq!( + crate::ops::registry_token(&mut tx, &s, &cluster) + .await + .unwrap(), + token + ); + tx.commit().await.unwrap(); + let sealed: String = + sqlx::query_scalar("SELECT registry_token_sealed FROM pyo.clusters WHERE id = $1") + .bind(&cluster) + .fetch_one(&db) + .await + .unwrap(); + the_teams(sealed).await; + + // From a release before 0.5: sealed with the installation's key. + let old = s.sealer.seal("an old token").unwrap(); + assert_eq!( + v.open_credential(&s.sealer, &old).await.unwrap(), + "an old token" + ); + // Never a credential stored in the clear. + assert!(v.open_credential(&s.sealer, "in the clear").await.is_err()); + + for t in [&team, &other] { + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(t) + .execute(&db) + .await + .unwrap(); + } + sqlx::query("DELETE FROM pyo.users WHERE id = $1") + .bind(&user_id) + .execute(&db) + .await + .unwrap(); + } } diff --git a/crates/pyo-api/src/volumes.rs b/crates/pyo-api/src/volumes.rs index 534ea852..e57b0f1e 100644 --- a/crates/pyo-api/src/volumes.rs +++ b/crates/pyo-api/src/volumes.rs @@ -125,30 +125,10 @@ pub fn placement_refusal( server_tags: &[String], server_location: &str, ) -> Option { - let servers: Vec<&str> = spec["servers"] - .as_array() - .into_iter() - .flatten() - .filter_map(|s| s.as_str()) - .filter(|s| !s.is_empty()) - .collect(); - if !servers.is_empty() && !servers.contains(&server) { + let placement = crate::placement::Placement::of(spec); + if !placement.takes(server, server_tags) { return Some(format!( - "{service} only runs on {}, and this volume's data is on {server}.", - servers.join(", ") - )); - } - let missing: Vec<&str> = spec["serverTags"] - .as_array() - .into_iter() - .flatten() - .filter_map(|t| t.as_str()) - .filter(|t| !server_tags.iter().any(|s| s == t)) - .collect(); - if !missing.is_empty() { - return Some(format!( - "{service} runs on servers tagged {}, and {server}, where this volume's data is, isn't.", - missing.join(", ") + "{service} doesn't run on {server}, where this volume's data is. Pick {server} in its Resources first." )); } let want = spec["location"].as_str().unwrap_or(""); @@ -168,7 +148,7 @@ pub fn placement_refusal( /// The server a volume's data is pinned to: the one it was made on, when /// its storage class keeps data on one server's disk (or isn't known). -async fn pinned_server( +pub(crate) async fn pinned_server( tx: &mut Transaction<'_, Postgres>, cluster_id: &str, data: &Value, @@ -512,7 +492,7 @@ async fn repo_for( team_id: &str, cluster_id: &str, ) -> ApiResult { - let Some(cfg) = crate::teambackup::settings(&s.db, team_id).await? else { + let Some(cfg) = crate::teambackup::settings(tx, team_id).await? else { return Err(ApiError::conflict( "This team has no backups yet. Set them up under Backups.", )); @@ -733,7 +713,7 @@ pub(crate) async fn snapshots( SessionUser(user): SessionUser, axum::extract::Path(id): axum::extract::Path, ) -> ApiResult> { - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "volumes", &id).await?; require_role(&mut tx, &user, &team_id, Role::Developer).await?; let (_, cluster_id, _, deleting, data, namespace) = volume_row(&mut tx, &id).await?; @@ -844,7 +824,7 @@ pub(crate) async fn delete_snapshot( "Pick one of the volume's snapshots (its id).", )); } - let mut tx = s.db.begin().await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "volumes", &id).await?; require_role(&mut tx, &user, &team_id, Role::Admin).await?; let (_, cluster_id, service_id, deleting, data, namespace) = volume_row(&mut tx, &id).await?; @@ -1692,7 +1672,7 @@ mod tests { assert!( placement_refusal("web", &spec(json!({ "servers": ["b"] })), "a", &[], "") .unwrap() - .contains("only runs on b") + .contains("doesn't run on a") ); assert!( placement_refusal( @@ -1704,6 +1684,7 @@ mod tests { ) .is_none() ); + // Any tag picked will do. assert!( placement_refusal( "web", @@ -1712,8 +1693,17 @@ mod tests { &tags, "" ) - .unwrap() - .contains("tagged ssd") + .is_none() + ); + assert!( + placement_refusal( + "web", + &spec(json!({ "placement": { "servers": ["b"], "tags": ["ssd"] } })), + "a", + &tags, + "" + ) + .is_some() ); assert!( placement_refusal( diff --git a/crates/pyo-builder/Cargo.toml b/crates/pyo-builder/Cargo.toml index bd2f8f19..f0110b52 100644 --- a/crates/pyo-builder/Cargo.toml +++ b/crates/pyo-builder/Cargo.toml @@ -8,13 +8,15 @@ publish.workspace = true [dependencies] anyhow = "1.0.104" base64 = "0.23.1" +flate2 = "1" futures = "0.3.34" hex = "0.4.3" -pyo-proto = { version = "0.4.5", path = "../pyo-proto" } +pyo-proto = { version = "0.5.0", path = "../pyo-proto", features = ["command-signing"] } reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls", "stream"] } serde = "1.0.229" serde_json = "1.0.154" sha2 = "0.11.1" +tar = { version = "0.4.46", default-features = false } tokio = { version = "1.54.1", features = ["full"] } tokio-util = { version = "0.7.20", features = ["io"] } tracing = "0.1.44" diff --git a/crates/pyo-builder/src/main.rs b/crates/pyo-builder/src/main.rs index 374b4d15..9e9fce50 100644 --- a/crates/pyo-builder/src/main.rs +++ b/crates/pyo-builder/src/main.rs @@ -1,4 +1,5 @@ -//! Pyo builder: turns Git sources into images. +//! Pyo builder: turns Git sources (and folders sent with `pyo deploy`) +//! into images. //! //! Runs next to a BuildKit daemon (as a pod pinned to a server) and dials //! out to the Pyo API: it long-polls for build jobs, resolves @@ -15,6 +16,7 @@ mod git; mod site; mod source; +mod upload; use std::{process::Stdio, time::Duration}; @@ -22,7 +24,7 @@ use anyhow::Context; use pyo_proto::{ AGENT_VERSION_HEADER, BuildJob, BuildProgress, BuildResult, BuilderHeartbeat, LogLine, now_ms, }; -use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue}; +use reqwest::header::{HeaderMap, HeaderValue}; use tokio::{ io::{AsyncBufReadExt, BufReader}, process::Command, @@ -32,9 +34,61 @@ use tracing_subscriber::EnvFilter; const VERSION: &str = env!("CARGO_PKG_VERSION"); +/// How the builder proves who it is to Pyo. +pub enum Auth { + /// Its own key, made by the agent in its cluster: every request signed + /// (pyo-proto `agentauth`). + Key(String, pyo_proto::agentauth::RequestKey), + /// Its token, from an agent that gives builders no key (older). + Token(String), +} + +impl Auth { + /// From `PYO_BUILDER_KEY_ID` and `PYO_BUILDER_KEY`, else `PYO_BUILDER_TOKEN`. + fn from_env() -> anyhow::Result { + let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty()); + if let (Some(id), Some(key)) = (var("PYO_BUILDER_KEY_ID"), var("PYO_BUILDER_KEY")) { + use base64::Engine as _; + let pkcs8 = base64::engine::general_purpose::STANDARD + .decode(key.trim()) + .context("PYO_BUILDER_KEY isn't base64")?; + let key = pyo_proto::agentauth::RequestKey::from_pkcs8(&pkcs8).map_err(anyhow::Error::msg)?; + return Ok(Self::Key(id, key)); + } + let token = var("PYO_BUILDER_TOKEN").context("PYO_BUILDER_KEY or PYO_BUILDER_TOKEN is required")?; + Ok(Self::Token(token)) + } + + /// `req` to `url`, signed over its body (`body`), or with the token. + pub fn sign(&self, req: reqwest::RequestBuilder, method: &str, url: &str, body: &[u8]) -> reqwest::RequestBuilder { + self.sign_hashed(req, method, url, &pyo_proto::agentauth::body_sha256(body)) + } + + /// The same for a streamed body, given by its hex SHA-256 (sent in + /// `x-pyo-sha256` too). + pub fn sign_hashed(&self, req: reqwest::RequestBuilder, method: &str, url: &str, body_sha256: &str) -> reqwest::RequestBuilder { + match self { + Auth::Key(id, key) => { + let path = reqwest::Url::parse(url) + .map(|u| match u.query() { + Some(q) => format!("{}?{q}", u.path()), + None => u.path().to_owned(), + }) + .unwrap_or_default(); + key.sign_hashed(id, method, &path, body_sha256, now_ms() / 1000) + .into_iter() + .fold(req, |r, (k, v)| r.header(k, v)) + } + Auth::Token(t) => req.bearer_auth(t), + } + } +} + struct Builder { http: reqwest::Client, - /// Its token: also its login at Pyo's registry door (username `pyo-builder`). + auth: Auth, + /// Its login at Pyo's registry door (username `pyo-builder`), when it + /// pushes there; empty for a cluster's own registry. token: String, base: String, buildkit: String, @@ -54,18 +108,17 @@ async fn main() -> anyhow::Result<()> { ) .init(); let url = std::env::var("PYO_API_URL").context("PYO_API_URL is required")?; - let token = std::env::var("PYO_BUILDER_TOKEN").context("PYO_BUILDER_TOKEN is required")?; + let auth = Auth::from_env()?; + let token = std::env::var("PYO_BUILDER_TOKEN").unwrap_or_default(); let mut headers = HeaderMap::new(); - let mut auth = HeaderValue::from_str(&format!("Bearer {token}"))?; - auth.set_sensitive(true); - headers.insert(AUTHORIZATION, auth); headers.insert(AGENT_VERSION_HEADER, HeaderValue::from_static(VERSION)); let builder = std::sync::Arc::new(Builder { http: reqwest::Client::builder() .default_headers(headers) .connect_timeout(Duration::from_secs(10)) .build()?, - token: token.clone(), + auth, + token, base: format!("{}/api/builder/v1", url.trim_end_matches('/')), buildkit: std::env::var("BUILDKIT_HOST") .unwrap_or_else(|_| "unix:///run/buildkit/buildkitd.sock".into()), @@ -212,6 +265,16 @@ fn line(level: &str, source: &str, message: &str) -> LogLine { } } +/// A build that failed before it ran, and why. +fn fail(commit: &str, message: String) -> anyhow::Result { + Ok(BuildResult { + ok: false, + commit: commit.to_owned(), + message: Some(message), + ..Default::default() + }) +} + impl Builder { /// Does BuildKit answer? (`buildctl debug workers`, with a timeout.) async fn buildkit_ready(&self) -> bool { @@ -266,13 +329,14 @@ impl Builder { } async fn post(&self, path: &str, body: &T) -> anyhow::Result<()> { - let res = self + let url = format!("{}{path}", self.base); + let bytes = serde_json::to_vec(body)?; + let req = self .http - .post(format!("{}{path}", self.base)) + .post(&url) .timeout(Duration::from_secs(20)) - .json(body) - .send() - .await?; + .header(reqwest::header::CONTENT_TYPE, "application/json"); + let res = self.auth.sign(req, "POST", &url, &bytes).body(bytes).send().await?; if !res.status().is_success() { anyhow::bail!("{}: {}", res.status(), res.text().await.unwrap_or_default()); } @@ -280,12 +344,9 @@ impl Builder { } async fn next_job(&self) -> anyhow::Result> { - let res = self - .http - .get(format!("{}/jobs?wait=25", self.base)) - .timeout(Duration::from_secs(40)) - .send() - .await?; + let url = format!("{}/jobs?wait=25", self.base); + let req = self.http.get(&url).timeout(Duration::from_secs(40)); + let res = self.auth.sign(req, "GET", &url, b"").send().await?; if !res.status().is_success() { anyhow::bail!("{}: {}", res.status(), res.text().await.unwrap_or_default()); } @@ -317,7 +378,64 @@ impl Builder { result } + /// A folder sent with `pyo deploy`: fetched from Pyo into `dir`, + /// checked, then Pyo is told it can let it go. + async fn fetch_upload( + &self, + job: &BuildJob, + up: &pyo_proto::SourceUpload, + root: &std::path::Path, + dir: &std::path::Path, + ) -> anyhow::Result { + use futures::StreamExt; + use sha2::Digest; + use tokio::io::AsyncWriteExt; + let url = format!("{}/jobs/{}/source", self.base, job.id); + let req = self.http.get(&url).timeout(Duration::from_secs(1800)); + let res = self.auth.sign(req, "GET", &url, b"").send().await?; + if !res.status().is_success() { + let status = res.status(); + let text = res.text().await.unwrap_or_default(); + let why = serde_json::from_str::(&text) + .ok() + .and_then(|v| v["error"].as_str().map(str::to_owned)) + .unwrap_or_else(|| status.to_string()); + anyhow::bail!(why); + } + let path = root.join("source.tar.gz"); + let mut file = tokio::fs::File::create(&path).await?; + let mut hash = sha2::Sha256::new(); + let mut got = 0u64; + let mut body = res.bytes_stream(); + while let Some(chunk) = body.next().await { + let chunk = chunk.context("the download broke off")?; + got += chunk.len() as u64; + if got > up.size { + anyhow::bail!("it's bigger than it should be"); + } + hash.update(&chunk); + file.write_all(&chunk).await?; + } + file.flush().await?; + drop(file); + if got != up.size || hex::encode(hash.finalize()) != up.sha256 { + anyhow::bail!("it isn't what was uploaded"); + } + // Pyo deletes its copy now; a failure here only leaves it to expire. + let req = self.http.delete(&url).timeout(Duration::from_secs(20)); + if let Err(e) = self.auth.sign(req, "DELETE", &url, b"").send().await { + tracing::warn!(job = %job.id, error = %e, "couldn't tell Pyo the upload arrived"); + } + let (path2, dir2) = (path.clone(), dir.to_owned()); + let files = tokio::task::spawn_blocking(move || upload::extract(&path2, &dir2)).await??; + let _ = std::fs::remove_file(&path); + Ok(files) + } + async fn build_inner(&self, job: &BuildJob) -> anyhow::Result { + if let Some(up) = &job.source_upload { + return self.build_upload(job, up).await; + } let commit = if job.commit.is_empty() { match git::resolve(&job.repo_url, &job.branch).await { Ok(c) => c, @@ -349,14 +467,6 @@ impl Builder { // A temporary checkout, deleted when `ws` drops at the end of the build. let ws = source::Workspace::new(&job.id)?; - let fail = |commit: &str, message: String| { - Ok(BuildResult { - ok: false, - commit: commit.to_owned(), - message: Some(message), - ..Default::default() - }) - }; if let Err(e) = source::checkout( &job.repo_url, &job.branch, @@ -371,16 +481,80 @@ impl Builder { { return fail(&commit, format!("Couldn't get the code: {e:#}")); } + let short = short.to_owned(); + self.build_source(job, &ws, commit, short).await + } + + /// A folder sent with `pyo deploy`: fetched, then built like a checkout. + async fn build_upload( + &self, + job: &BuildJob, + up: &pyo_proto::SourceUpload, + ) -> anyhow::Result { + tracing::info!(job = %job.id, upload = %up.id, size = up.size, "build of an uploaded folder"); + self.progress( + &job.id, + BuildProgress { + stage: "building".into(), + logs: vec![line( + "info", + "builder", + &format!( + "Getting the uploaded folder ({:.1} MB)", + up.size as f64 / 1_000_000.0 + ), + )], + ..Default::default() + }, + ) + .await; + let ws = source::Workspace::new(&job.id)?; + match self.fetch_upload(job, up, &ws.root, &ws.src()).await { + Ok(files) => { + self.progress( + &job.id, + BuildProgress { + logs: vec![line( + "info", + "builder", + &format!("Building the uploaded folder ({files} files)"), + )], + ..Default::default() + }, + ) + .await + } + Err(e) => return fail("", format!("Couldn't get the uploaded folder: {e:#}")), + } + let short = up.sha256.chars().take(12).collect(); + self.build_source(job, &ws, String::new(), short).await + } + + /// Build what's in the workspace (`commit` empty for an upload; `short` + /// tags the image). + async fn build_source( + &self, + job: &BuildJob, + ws: &source::Workspace, + commit: String, + short: String, + ) -> anyhow::Result { + let short = short.as_str(); let app_dir = match source::inside(&ws.src(), &job.build_context) { Ok(d) if d.is_dir() => d, Ok(_) => { - return fail( - &commit, + let message = if job.source_upload.is_some() { + format!( + "The folder has no {} directory. Check the build context.", + job.build_context + ) + } else { format!( "The repository has no {} directory at this commit. Check the build context.", job.build_context - ), - ); + ) + }; + return fail(&commit, message); } Err(e) => return fail(&commit, format!("{e:#}")), }; @@ -790,7 +964,7 @@ impl Builder { ), ) .await; - match site::upload(&self.http, &self.base, job, &m, &on_disk).await { + match site::upload(&self.http, &self.auth, &self.base, job, &m, &on_disk).await { Ok(()) => Some(pyo_proto::site::SiteUpload { files: m.files.len() as u64, bytes, diff --git a/crates/pyo-builder/src/site.rs b/crates/pyo-builder/src/site.rs index fff51e49..74d3faaa 100644 --- a/crates/pyo-builder/src/site.rs +++ b/crates/pyo-builder/src/site.rs @@ -235,13 +235,16 @@ async fn check(res: reqwest::Response) -> anyhow::Result<()> { /// Uploads the folder through Pyo: its manifest, each file, then done. pub async fn upload( http: &reqwest::Client, + auth: &crate::Auth, base: &str, job: &str, m: &SiteManifest, on_disk: &[PathBuf], ) -> anyhow::Result<()> { let jobs = format!("{base}/jobs/{job}/site"); - check(http.post(&jobs).json(m).send().await?).await?; + let manifest = serde_json::to_vec(m)?; + let req = http.post(&jobs).header("content-type", "application/json"); + check(auth.sign(req, "POST", &jobs, &manifest).body(manifest).send().await?).await?; let mut sends = futures::stream::iter(m.files.iter().zip(on_disk)) .map(|(f, p)| { let url = format!("{jobs}/files/{}", encode_path(&f.path)); @@ -252,10 +255,12 @@ pub async fn upload( let file = tokio::fs::File::open(p).await?; let body = reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::new(file)); let r = async { + let req = http + .put(&url) + .header("x-pyo-sha256", &f.sha256) + .header("content-length", f.size); check( - http.put(&url) - .header("x-pyo-sha256", &f.sha256) - .header("content-length", f.size) + auth.sign_hashed(req, "PUT", &url, &f.sha256) .body(body) .timeout(std::time::Duration::from_secs(600)) .send() @@ -278,7 +283,8 @@ pub async fn upload( while let Some(r) = sends.next().await { r?; } - check(http.post(format!("{jobs}/done")).send().await?).await + let done = format!("{jobs}/done"); + check(auth.sign(http.post(&done), "POST", &done, b"").send().await?).await } #[cfg(test)] diff --git a/crates/pyo-builder/src/upload.rs b/crates/pyo-builder/src/upload.rs new file mode 100644 index 00000000..62e39789 --- /dev/null +++ b/crates/pyo-builder/src/upload.rs @@ -0,0 +1,112 @@ +//! A folder sent with `pyo deploy` instead of a Git checkout: a gzipped tar +//! fetched from Pyo, checked against its SHA-256, and unpacked into the +//! build's workspace. Nothing in it may land outside the workspace. + +use std::{io::Read, path::Path}; + +use anyhow::{Context, bail}; + +/// The most an archive may unpack to, and its most entries. +const MAX_UNPACKED: u64 = 8 << 30; +const MAX_ENTRIES: u64 = 500_000; + +/// Unpack `archive` (a .tar.gz) into `dest`: files, folders and symbolic +/// links only, every path inside `dest`. Returns how many files. +pub fn extract(archive: &Path, dest: &Path) -> anyhow::Result { + let file = std::fs::File::open(archive).context("couldn't open the archive")?; + extract_from(file, dest) +} + +fn extract_from(r: impl Read, dest: &Path) -> anyhow::Result { + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(r)); + tar.set_preserve_permissions(false); + tar.set_preserve_mtime(false); + tar.set_unpack_xattrs(false); + tar.set_overwrite(true); + let (mut files, mut total, mut entries) = (0u64, 0u64, 0u64); + for entry in tar.entries().context("not a gzipped tar")? { + let mut entry = entry.context("the archive is damaged")?; + entries += 1; + if entries > MAX_ENTRIES { + bail!("the folder has more than {MAX_ENTRIES} files"); + } + let kind = entry.header().entry_type(); + if !(kind.is_file() || kind.is_dir() || kind.is_symlink()) { + continue; + } + total += entry.header().size().unwrap_or(0); + if total > MAX_UNPACKED { + bail!("the folder unpacks to more than {} GB", MAX_UNPACKED >> 30); + } + let path = entry + .path() + .context("a file name isn't valid")? + .into_owned(); + // unpack_in refuses absolute paths and "..", and never writes + // through a link out of `dest`. + if !entry + .unpack_in(dest) + .with_context(|| format!("couldn't unpack {}", path.display()))? + { + bail!("{} points outside the folder", path.display()); + } + if kind.is_file() { + files += 1; + } + } + Ok(files) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn archive( + build: impl FnOnce(&mut tar::Builder>>), + ) -> Vec { + let mut b = tar::Builder::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::fast(), + )); + build(&mut b); + b.into_inner().unwrap().finish().unwrap() + } + + fn file(b: &mut tar::Builder>>, path: &str, body: &[u8]) { + let mut h = tar::Header::new_gnu(); + h.set_size(body.len() as u64); + h.set_mode(0o644); + h.set_entry_type(tar::EntryType::Regular); + // Written by hand: the builder refuses "..", so bad names get past it. + let name = h.as_old_mut().name.as_mut(); + name.fill(0); + name[..path.len()].copy_from_slice(path.as_bytes()); + h.set_cksum(); + b.append(&h, body).unwrap(); + } + + #[test] + fn unpacks_files_and_folders() { + let dir = std::env::temp_dir().join(format!("pyo-upload-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let a = archive(|b| { + file(b, "Dockerfile", b"FROM scratch\n"); + file(b, "src/main.rs", b"fn main() {}\n"); + }); + assert_eq!(extract_from(&a[..], &dir).unwrap(), 2); + assert_eq!( + std::fs::read(dir.join("src/main.rs")).unwrap(), + b"fn main() {}\n" + ); + + let bad = archive(|b| file(b, "../escape", b"x")); + let out = dir.join("inner"); + std::fs::create_dir_all(&out).unwrap(); + assert!(extract_from(&bad[..], &out).is_err()); + assert!(!dir.join("escape").exists()); + + assert!(extract_from(&b"not an archive"[..], &out).is_err()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/pyo-cli/Cargo.toml b/crates/pyo-cli/Cargo.toml index d956d147..5dca1999 100644 --- a/crates/pyo-cli/Cargo.toml +++ b/crates/pyo-cli/Cargo.toml @@ -14,8 +14,11 @@ path = "src/main.rs" anyhow = "1.0.104" clap = { version = "4.5", features = ["derive", "env"] } crossterm = "0.29" +flate2 = "1" futures = "0.3.34" hex = "0.4.3" +hostname = "0.4" +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"] } @@ -23,10 +26,11 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" serde_path_to_error = "0.1.20" sha2 = "0.11.1" +tar = { version = "0.4.46", default-features = false } tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "io-util", "io-std", "time", "sync", "fs"] } tokio-tungstenite = { version = "0.29", features = ["rustls-tls-native-roots"] } toml = "0.9" -pyo-proto = { version = "0.4.5", path = "../pyo-proto" } +pyo-proto = { version = "0.5.0", path = "../pyo-proto" } [dev-dependencies] # The JSON Schema of pyo.jsonc, written from the config types by a test. diff --git a/crates/pyo-cli/src/api.rs b/crates/pyo-cli/src/api.rs index 9f9bb7b9..9ba46590 100644 --- a/crates/pyo-cli/src/api.rs +++ b/crates/pyo-cli/src/api.rs @@ -84,6 +84,18 @@ impl Api { .await } + /// Raw bytes, e.g. a part of an upload. + pub async fn put_bytes(&self, path: &str, body: Vec) -> Result { + self.send( + self.http + .put(format!("{}{path}", self.base)) + .header("content-type", "application/octet-stream") + .timeout(std::time::Duration::from_secs(300)) + .body(body), + ) + .await + } + pub async fn delete(&self, path: &str) -> Result { self.send(self.http.delete(format!("{}{path}", self.base))) .await diff --git a/crates/pyo-cli/src/config.rs b/crates/pyo-cli/src/config.rs index c564b6da..003a0c62 100644 --- a/crates/pyo-cli/src/config.rs +++ b/crates/pyo-cli/src/config.rs @@ -336,6 +336,27 @@ fn set_service(text: &str, id: &str) -> Result { Ok(root.to_string()) } +/// Set `deploy.replicas` in pyo.jsonc to `n`, keeping everything else as +/// it is, comments too. For a file that sets it already. +pub fn write_replicas(path: &Path, n: u32) -> Result<()> { + let text = fs::read_to_string(path)?; + fs::write(path, set_replicas(&text, n)?)?; + Ok(()) +} + +/// `text` with `deploy.replicas` set to `n`, and nothing else changed. +fn set_replicas(text: &str, n: u32) -> Result { + use jsonc_parser::cst::{CstInputValue, CstRootNode}; + let root = CstRootNode::parse(text, &parse_options())?; + let prop = root + .object_value() + .and_then(|o| o.object_value("deploy")) + .and_then(|d| d.get("replicas")) + .context("the file doesn't set deploy.replicas")?; + prop.set_value(CstInputValue::Number(n.to_string())); + Ok(root.to_string()) +} + /// "500m" → 500, "1.5" or "1.5 cores" → 1500 (millicores). pub fn parse_cpu(s: &str) -> Result { let s = s.trim(); @@ -525,6 +546,35 @@ mod tests { assert!(set_service("[]", "svc_new").is_err()); } + #[test] + fn scale_changes_only_the_replicas() { + let text = set_replicas(FULL, 5).unwrap(); + assert_eq!(text, FULL.replace("\"replicas\": 2", "\"replicas\": 5")); + assert_eq!(parse(&text).unwrap().deploy.replicas, Some(5)); + // Across lines, with comments. + let text = "{\n \"deploy\": {\n // more for launch day\n \"replicas\": 2, // was 1\n },\n}\n"; + assert_eq!( + set_replicas(text, 40).unwrap(), + text.replace("\"replicas\": 2", "\"replicas\": 40") + ); + // Nothing to change: the file doesn't set it. + assert!(set_replicas("{ \"deploy\": { \"port\": 80 } }", 3).is_err()); + assert!(set_replicas("{ \"service\": \"svc_a\" }", 3).is_err()); + assert!(set_replicas("[]", 3).is_err()); + // write_replicas changes the file. + let dir = temp("scale"); + let path = dir.join(FILE); + fs::write(&path, FULL).unwrap(); + write_replicas(&path, 3).unwrap(); + assert_eq!(load(&path).unwrap().deploy.replicas, Some(3)); + assert!( + fs::read_to_string(&path) + .unwrap() + .contains("// written by pyo link") + ); + fs::remove_dir_all(dir).unwrap(); + } + /// The JSON Schema, from the types above: draft 7, which editors know /// best, with each object's settings inline so their descriptions show. fn schema_json() -> String { diff --git a/crates/pyo-cli/src/domain.rs b/crates/pyo-cli/src/domain.rs index 842c2996..cf9c2e49 100644 --- a/crates/pyo-cli/src/domain.rs +++ b/crates/pyo-cli/src/domain.rs @@ -102,6 +102,14 @@ fn state(d: &Value, deployed: bool) -> (Tone, String) { } let host = d["hostname"].as_str().unwrap_or(""); if d["status"] != json!("active") { + // Tailnet domains have no DNS to wait for: Pyo sets them up. + if pyo_proto::system::is_tailnet_host(host) { + return if d["status"] == json!("error") { + (Tone::Broken, "Tailscale failed".into()) + } else { + (Tone::Busy, "Setting up on Tailscale…".into()) + }; + } if is_free(host) { return (Tone::Busy, "Checking DNS…".into()); } @@ -553,6 +561,14 @@ mod tests { state(&d("active", "issued", "auto"), false).1, "Live after first deploy" ); + let tn = |status: &str| json!({ "hostname": "blog.tail1.ts.net", "status": status, "tls": "pending", "tlsMode": "auto" }); + assert_eq!( + state(&tn("pending_dns"), true).1, + "Setting up on Tailscale…" + ); + let failed = state(&tn("error"), true); + assert!(failed.0 == Tone::Broken && failed.1 == "Tailscale failed"); + assert_eq!(state(&tn("active"), true).1, "Issuing certificate…"); assert_eq!(https(&d("active", "issued", "auto")), "Let's Encrypt"); assert_eq!(https(&d("active", "disabled", "off")), "off"); } diff --git a/crates/pyo-cli/src/dotenv.rs b/crates/pyo-cli/src/dotenv.rs index ff887476..e9fabbc4 100644 --- a/crates/pyo-cli/src/dotenv.rs +++ b/crates/pyo-cli/src/dotenv.rs @@ -147,8 +147,90 @@ pub fn last_wins(entries: Vec<(String, String)>) -> (Vec<(String, String)>, Vec< (out, repeated) } +/// `value` as a .env file writes it: as it is when that reads back the +/// same, else in double quotes with \n \r \t \" \\ escaped. +pub fn quote(value: &str) -> String { + let plain = !value.is_empty() + && value.trim() == value + && !value + .chars() + .any(|c| c.is_whitespace() || "#\"'$\\`".contains(c)); + if plain || value.is_empty() { + return value.to_owned(); + } + let mut out = String::with_capacity(value.len() + 2); + out.push('"'); + for c in value.chars() { + match c { + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// A .env file of the service's variables. Secrets: their value when +/// `revealed` has it, else empty, with a comment above. +pub fn write(header: &str, vars: &[(String, Option)]) -> String { + let mut out = format!("# {header}\n"); + for (k, v) in vars { + match v { + Some(v) => out.push_str(&format!("{k}={}\n", quote(v))), + None => out.push_str(&format!( + "# {k} is a secret. Owners and admins can pull it with --secrets.\n{k}=\n" + )), + } + } + out +} + #[cfg(test)] mod tests { + #[test] + fn written_values_read_back_the_same() { + let values = [ + "plain", + "", + "with space", + " lead", + "a#b", + "quote\"d", + "single'q", + "$HOME", + "back\\slash", + "two\nlines", + "tab\there", + "url://x?a=b&c=d", + ]; + let vars: Vec<(String, Option)> = values + .iter() + .enumerate() + .map(|(i, v)| (format!("K{i}"), Some(v.to_string()))) + .chain([("SECRET".to_string(), None)]) + .collect(); + let text = write("From Pyo: acme/shop/api", &vars); + let parsed = parse(&text); + assert!(parsed.invalid.is_empty(), "{:?}", parsed.invalid); + for (i, v) in values.iter().enumerate() { + assert_eq!( + parsed.entries[i], + (format!("K{i}"), v.to_string()), + "{text}" + ); + } + assert_eq!( + parsed.entries.last().unwrap(), + &("SECRET".into(), String::new()) + ); + assert!(text.contains("# SECRET is a secret.")); + assert_eq!(quote("plain"), "plain"); + } + use super::*; fn e(pairs: &[(&str, &str)]) -> Vec<(String, String)> { diff --git a/crates/pyo-cli/src/exec.rs b/crates/pyo-cli/src/exec.rs index 98b45175..a99cc0d3 100644 --- a/crates/pyo-cli/src/exec.rs +++ b/crates/pyo-cli/src/exec.rs @@ -1,11 +1,15 @@ -//! `pyo exec`: a shell in one of the service's replicas, over the same -//! WebSocket as the dashboard's terminal. Keys go up as binary frames, the -//! shell's output comes down as binary, and JSON text frames carry resize, -//! ready, error and exit (pyo_proto::TerminalFrame). +//! `pyo exec`: a shell in one of the service's replicas, or one command +//! (`pyo exec -- cmd args`), over the same WebSocket as the dashboard's +//! terminal. Keys or stdin go up as binary frames, output comes down as +//! binary (without a TTY, each frame starts with its stream), and JSON text +//! frames carry resize, end of input, ready, error and exit +//! (pyo_proto::TerminalFrame). + +use std::io::IsTerminal; use anyhow::{Context, Result, bail}; use futures::{SinkExt, StreamExt}; -use pyo_proto::TerminalFrame; +use pyo_proto::{STREAM_STDERR, TerminalFrame}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest, http::HeaderValue}; @@ -27,78 +31,222 @@ impl Drop for Raw { } } -pub async fn run( - api: &Api, - service: Option<&str>, - replica: Option, - shell: Option, -) -> Result<()> { - let t = service::target(api, service).await?; - let ws_base = api - .base +/// A command ended with this exit code: `pyo` exits with it too. +#[derive(Debug)] +pub struct Exited(pub i32); + +impl std::fmt::Display for Exited { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "exited with {}", self.0) + } +} + +impl std::error::Error for Exited {} + +/// What `pyo exec` runs, and how. +#[derive(Default)] +pub struct Opts { + pub replica: Option, + pub shell: Option, + /// A command instead of a shell. + pub command: Vec, + /// A TTY or not; by default one when stdin and stdout are terminals. + pub tty: Option, + /// Send stdin even when it's a terminal (without a TTY). + pub stdin: bool, +} + +/// Whether a command gets a TTY: as asked, else when both ends are terminals. +pub fn wants_tty(asked: Option, stdin_tty: bool, stdout_tty: bool) -> bool { + asked.unwrap_or(stdin_tty && stdout_tty) +} + +/// The terminal endpoint's URL, its query encoded. +pub fn socket_url(base: &str, service_id: &str, o: &Opts, tty: bool) -> Result { + let ws_base = base .replacen("https://", "wss://", 1) .replacen("http://", "ws://", 1); - let mut url = format!( - "{ws_base}/api/v1/services/{}/terminal?shell={}", - t.id, - shell.as_deref().unwrap_or("auto") - ); - if let Some(r) = &replica { - url.push_str(&format!("&replica={r}")); + let mut url = reqwest::Url::parse(&format!("{ws_base}/api/v1/services/{service_id}/terminal")) + .context("Pyo's address isn't a URL")?; + { + let mut q = url.query_pairs_mut(); + q.append_pair("shell", o.shell.as_deref().unwrap_or("auto")); + if let Some(r) = &o.replica { + q.append_pair("replica", r); + } + if !o.command.is_empty() { + q.append_pair("command", &serde_json::to_string(&o.command)?); + if !tty { + q.append_pair("tty", "false"); + } + } } - let mut req = url.into_client_request()?; + Ok(url.to_string()) +} + +/// Why Pyo turned the terminal down: its message, else what failed. +fn refused(e: tokio_tungstenite::tungstenite::Error) -> anyhow::Error { + refused_with(e, "Can't open a terminal on the service") +} + +/// Why Pyo turned a WebSocket down: its message, else `what` and what failed. +pub(crate) fn refused_with(e: tokio_tungstenite::tungstenite::Error, what: &str) -> anyhow::Error { + use tokio_tungstenite::tungstenite::Error; + if let Error::Http(res) = &e { + let msg = res + .body() + .as_deref() + .and_then(|b| serde_json::from_slice::(b).ok()) + .and_then(|v| v["error"].as_str().map(str::to_owned)); + if let Some(m) = msg { + return anyhow::anyhow!(m); + } + } + anyhow::Error::from(e).context(what.to_owned()) +} + +pub async fn run(api: &Api, service: Option<&str>, o: Opts) -> Result<()> { + let t = service::target(api, service).await?; + let tty = o.command.is_empty() + || wants_tty( + o.tty, + std::io::stdin().is_terminal(), + std::io::stdout().is_terminal(), + ); + let mut req = socket_url(&api.base, &t.id, &o, tty)?.into_client_request()?; req.headers_mut().insert( "authorization", HeaderValue::from_str(&format!("Bearer {}", api.token()))?, ); let (ws, _) = tokio_tungstenite::connect_async(req) .await - .context("Can't open a terminal on the service")?; + .map_err(refused)?; let (mut up, mut down) = ws.split(); - eprintln!( - "Connecting to {}…", - t.service()["name"].as_str().unwrap_or("the service") - ); - let _raw = Raw::on()?; - if let Ok((cols, rows)) = crossterm::terminal::size() { + let name = t.service()["name"].as_str().unwrap_or("the service"); + if o.command.is_empty() { + eprintln!("Connecting to {name}…"); + } + let raw = if tty { Some(Raw::on()?) } else { None }; + if tty && let Ok((cols, rows)) = crossterm::terminal::size() { up.send(Message::text(serde_json::to_string( &TerminalFrame::Resize { cols, rows }, )?)) .await?; } + // Without a TTY, stdin goes up when it's a pipe or file (or -i), then + // its end. A terminal's stdin isn't read: the command gets none. + let mut send_stdin = tty || o.stdin || !std::io::stdin().is_terminal(); + if !send_stdin { + up.send(Message::text(serde_json::to_string( + &TerminalFrame::StdinEnd, + )?)) + .await?; + } let mut stdin = tokio::io::stdin(); let mut stdout = tokio::io::stdout(); - let mut buf = [0u8; 4096]; + let mut stderr = tokio::io::stderr(); + let mut buf = vec![0u8; 32 * 1024]; let mut size = crossterm::terminal::size().unwrap_or((80, 24)); let mut tick = tokio::time::interval(std::time::Duration::from_millis(500)); - loop { + let code: Option = loop { tokio::select! { - n = stdin.read(&mut buf) => { + n = stdin.read(&mut buf), if send_stdin => { let n = n?; - if n == 0 { break; } + if n == 0 { + // End of input: a shell's session ends, a command's stdin closes. + if tty && o.command.is_empty() { break None; } + send_stdin = false; + up.send(Message::text(serde_json::to_string(&TerminalFrame::StdinEnd)?)).await?; + continue; + } up.send(Message::binary(buf[..n].to_vec())).await?; } m = down.next() => match m { - Some(Ok(Message::Binary(b))) => { stdout.write_all(&b).await?; stdout.flush().await?; } + Some(Ok(Message::Binary(b))) => { + if tty { + stdout.write_all(&b).await?; + stdout.flush().await?; + } else if let Some((stream, rest)) = b.split_first() { + if *stream == STREAM_STDERR { + stderr.write_all(rest).await?; + stderr.flush().await?; + } else { + stdout.write_all(rest).await?; + stdout.flush().await?; + } + } + } Some(Ok(Message::Text(t))) => match serde_json::from_str::(t.as_str()) { - Ok(TerminalFrame::Exit) => break, - Ok(TerminalFrame::Error { message }) => { drop(_raw); bail!(message); } + Ok(TerminalFrame::Exit { code }) => break code, + Ok(TerminalFrame::Error { message }) => { drop(raw); bail!(message); } _ => {} }, - Some(Ok(Message::Close(_))) | None => break, + Some(Ok(Message::Close(_))) | None => { + if o.command.is_empty() { break None; } + drop(raw); + bail!("The connection closed before the command finished."); + } Some(Ok(_)) => {} Some(Err(e)) => return Err(e.into()), }, // Follow the window's size (no SIGWINCH on every platform). - _ = tick.tick() => { + _ = tick.tick(), if tty => { if let Ok(s) = crossterm::terminal::size() && s != size { size = s; up.send(Message::text(serde_json::to_string(&TerminalFrame::Resize { cols: s.0, rows: s.1 })?)).await?; } } } + }; + drop(raw); + let _ = up.close().await; + match code { + Some(c) if c != 0 => Err(Exited(c).into()), + _ => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_tty_only_between_terminals_unless_asked() { + assert!(wants_tty(None, true, true)); + assert!(!wants_tty(None, false, true), "piped input"); + assert!(!wants_tty(None, true, false), "output to a file"); + assert!(wants_tty(Some(true), false, false)); + assert!(!wants_tty(Some(false), true, true)); + } + + #[test] + fn the_command_goes_in_the_query_as_json() { + let o = Opts { + command: vec!["sh".into(), "-c".into(), "echo a && echo b".into()], + replica: Some("web-1".into()), + ..Default::default() + }; + let u = socket_url("https://pyo.example.com", "svc_1", &o, false).unwrap(); + assert!(u.starts_with( + "wss://pyo.example.com/api/v1/services/svc_1/terminal?shell=auto&replica=web-1&command=" + )); + let parsed = reqwest::Url::parse(&u).unwrap(); + let cmd = parsed + .query_pairs() + .find(|(k, _)| k == "command") + .unwrap() + .1; + assert_eq!( + serde_json::from_str::>(&cmd).unwrap(), + o.command + ); + assert!(u.ends_with("&tty=false")); + let shell = socket_url("http://localhost:8000", "svc_1", &Opts::default(), true).unwrap(); + assert_eq!( + shell, + "ws://localhost:8000/api/v1/services/svc_1/terminal?shell=auto" + ); } - Ok(()) } diff --git a/crates/pyo-cli/src/login.rs b/crates/pyo-cli/src/login.rs index 5953b560..906e26d8 100644 --- a/crates/pyo-cli/src/login.rs +++ b/crates/pyo-cli/src/login.rs @@ -1,17 +1,12 @@ -//! `pyo login`: approve the CLI in the browser (it listens on localhost -//! for the answer), or pass an API key for CI and machines without one. +//! `pyo login`: approve the CLI in the browser with the code it shows, or +//! pass an API key for CI and machines without one. use std::time::Duration; +use crate::{api::Api, config::Credentials, ui}; use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use tokio::{ - io::{AsyncReadExt, AsyncWriteExt}, - net::TcpListener, -}; - -use crate::{api::Api, config::Credentials, ui}; pub async fn run(url: Option, token: Option, expires: &str) -> Result<()> { let saved = Credentials::load()?; @@ -60,111 +55,104 @@ fn random_hex(n: usize) -> String { hex::encode(b) } -fn machine_name() -> String { +/// This computer's name, as the sign-in and "Uploaded from …" show it. +pub(crate) fn machine_name() -> String { std::fs::read_to_string("/etc/hostname") .ok() .map(|s| s.trim().to_owned()) .filter(|s| !s.is_empty()) + .or_else(|| { + hostname::get() + .ok() + .map(|h| h.to_string_lossy().into_owned()) + .filter(|s| !s.is_empty()) + }) .or_else(|| std::env::var("HOSTNAME").ok()) .or_else(|| std::env::var("COMPUTERNAME").ok()) .unwrap_or_default() } -/// Open the approval page and wait for its answer on localhost. The key -/// expires after `expires` ("30d", "90d", "1y" or "never"). +/// POST JSON to Pyo: its answer, or the error it gives. +async fn post(http: &reqwest::Client, url: &str, body: Value) -> Result { + let res = http.post(url).json(&body).send().await?; + let ok = res.status().is_success(); + let v: Value = res.json().await.unwrap_or(Value::Null); + if !ok { + bail!( + "{}", + v["error"] + .as_str() + .unwrap_or("Sign-in failed. Run pyo login again.") + ); + } + Ok(v) +} + +/// Ask Pyo for a sign-in, show its code, open the approval page and wait +/// for the answer there. Nothing comes back from the browser: the CLI +/// polls Pyo with a verifier only it knows, so this works over SSH too. +/// The key expires after `expires` ("30d", "90d", "1y" or "never"). async fn browser_login(url: &str, expires: &str) -> Result { - let listener = TcpListener::bind("127.0.0.1:0") - .await - .context("Can't listen on localhost")?; - let port = listener.local_addr()?.port(); + let http = reqwest::Client::builder() + .user_agent(concat!("pyo-cli/", env!("CARGO_PKG_VERSION"))) + .timeout(Duration::from_secs(20)) + .build()?; let verifier = random_hex(32); - let challenge = hex::encode(Sha256::digest(verifier.as_bytes())); - let state = random_hex(16); - let page = format!( - "{url}/cli-login?{}", - [ - ("port", port.to_string()), - ("state", state.clone()), - ("challenge", challenge), - ("name", machine_name()) - ] - .iter() - .map(|(k, v)| format!("{k}={}", encode(v))) - .collect::>() - .join("&") - ); - println!("Opening your browser to approve this computer…"); + let started = post( + &http, + &format!("{url}/api/cli/start"), + json!({ + "challenge": hex::encode(Sha256::digest(verifier.as_bytes())), + "name": machine_name(), + "client": format!("pyo {} on {}", env!("CARGO_PKG_VERSION"), std::env::consts::OS), + "expires": expires, + }), + ) + .await + .map_err(|e| match e.downcast_ref::() { + Some(_) => anyhow::anyhow!("Can't reach {url}"), + None => e, + })?; + let (Some(id), Some(code)) = (started["id"].as_str(), started["code"].as_str()) else { + bail!("{url} didn't answer like a Pyo."); + }; + let wait = Duration::from_secs(started["expiresIn"].as_u64().unwrap_or(600)); + let every = Duration::from_secs(started["interval"].as_u64().unwrap_or(2).clamp(1, 10)); + let page = format!("{url}/cli-login?id={}", encode(id)); + println!("Your code: {}", ui::bold(code)); + println!("Type it in your browser to approve this computer."); println!("If it doesn't open, go to:\n {page}\n"); ui::open(&page); - let code = tokio::time::timeout(Duration::from_secs(300), wait_for_code(&listener, &state)) - .await - .context( - "Timed out waiting for approval. Run pyo login again, or use: pyo login --token pyo_…", - )??; - - let res: Value = reqwest::Client::new() - .post(format!("{url}/api/cli/token")) - .json(&json!({ "code": code, "verifier": verifier, "expires": expires })) - .send() - .await - .with_context(|| format!("Can't reach {url}"))? - .json() - .await?; - res["token"].as_str().map(str::to_owned).with_context(|| { - res["error"] - .as_str() - .unwrap_or("Sign-in failed.") - .to_owned() - }) -} - -/// The browser comes back to http://127.0.0.1:/callback?state=…&code=… -async fn wait_for_code(listener: &TcpListener, state: &str) -> Result { - loop { - let (mut sock, _) = listener.accept().await?; - let mut buf = vec![0u8; 8192]; - let n = sock.read(&mut buf).await.unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]); - let Some(target) = req.lines().next().and_then(|l| l.split_whitespace().nth(1)) else { - continue; - }; - let Some(query) = target.strip_prefix("/callback?") else { - let _ = sock - .write_all( - b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ) - .await; - continue; + let deadline = tokio::time::Instant::now() + wait; + while tokio::time::Instant::now() < deadline { + tokio::time::sleep(every).await; + let res = match http + .post(format!("{url}/api/cli/token")) + .json(&json!({ "id": id, "verifier": verifier })) + .send() + .await + { + Ok(r) => r, + // Offline for a moment: ask again. + Err(_) => continue, }; - let params: Vec<(String, String)> = query - .split('&') - .filter_map(|kv| kv.split_once('=')) - .map(|(k, v)| (k.to_owned(), decode(v))) - .collect(); - let get = |k: &str| params.iter().find(|(x, _)| x == k).map(|(_, v)| v.clone()); - let (title, result) = if get("state").as_deref() != Some(state) { - ( - "This sign-in doesn't match", - Err(anyhow::anyhow!( - "The answer didn't match this login. Run pyo login again." - )), - ) - } else if get("error").is_some() { - ("Cancelled", Err(anyhow::anyhow!("Sign-in was cancelled."))) - } else if let Some(code) = get("code") { - ("You're signed in. You can close this tab.", Ok(code)) - } else { + let status = res.status(); + let v: Value = res.json().await.unwrap_or(Value::Null); + if let Some(token) = v["token"].as_str() { + return Ok(token.to_owned()); + } + if status.is_success() || status.as_u16() == 429 || status.is_server_error() { continue; - }; - let body = format!( - "Pyo CLI

{title}

" + } + bail!( + "{}", + v["error"] + .as_str() + .unwrap_or("Sign-in failed. Run pyo login again.") ); - let _ = sock - .write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()) - .await; - return result; } + bail!("This sign-in expired. Run pyo login again, or use: pyo login --token pyo_…") } fn encode(s: &str) -> String { @@ -178,36 +166,12 @@ fn encode(s: &str) -> String { .collect() } -fn decode(s: &str) -> String { - let b = s.as_bytes(); - let mut out = Vec::with_capacity(b.len()); - let mut i = 0; - while i < b.len() { - match b[i] { - b'+' => out.push(b' '), - b'%' if i + 2 < b.len() => { - match u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or(""), 16) { - Ok(v) => { - out.push(v); - i += 2; - } - Err(_) => out.push(b'%'), - } - } - c => out.push(c), - } - i += 1; - } - String::from_utf8_lossy(&out).into_owned() -} - #[cfg(test)] mod tests { #[test] fn url_coding() { assert_eq!(super::encode("a b/c"), "a%20b%2Fc"); - assert_eq!(super::decode("a%20b%2Fc"), "a b/c"); - assert_eq!(super::decode("100%"), "100%"); + assert_eq!(super::encode("clg_x-1"), "clg_x-1"); assert_eq!( super::normalize("pyo.example.com/").unwrap(), "https://pyo.example.com" diff --git a/crates/pyo-cli/src/main.rs b/crates/pyo-cli/src/main.rs index 86cb699c..06c0cd59 100644 --- a/crates/pyo-cli/src/main.rs +++ b/crates/pyo-cli/src/main.rs @@ -14,6 +14,7 @@ mod exec; mod firewall; mod import; mod login; +mod pack; mod registry; mod sandbox; mod server; @@ -91,19 +92,35 @@ enum Command { /// "api", "shop/api" or "team/shop/api". Without it, pick from a list. service: Option, }, - /// Apply pyo.jsonc and deploy, then follow it to the end. With -f, import - /// a Docker Compose file instead: see what it makes, then deploy it. + /// Apply pyo.jsonc and deploy, then follow it to the end. + /// + /// 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. Deploy { #[command(flatten)] which: Which, /// Start it and exit, without following it. #[arg(long)] detach: bool, + /// Send this folder, also for a service built from Git. + #[arg(long, conflicts_with = "file")] + local: bool, + /// Send .env files too (they're left out by default). + #[arg(long, conflicts_with = "file")] + include_env: bool, + /// 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")] + project: Option, /// A Docker Compose file to import as a new project (a .env next to /// it is read too). #[arg(long, short = 'f')] file: Option, - /// The team to import into (slug or id). Defaults to your first team. + /// 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. @@ -122,13 +139,22 @@ enum Command { #[arg(long)] json: bool, }, - /// The service's recent logs. + /// The service's logs, from every replica. Logs { #[command(flatten)] which: Which, /// Keep printing new lines. #[arg(long, short)] follow: bool, + /// Only lines since then: 30s, 10m, 2h or 1d. + #[arg(long)] + since: Option, + /// One replica, by its name as the lines show it. + #[arg(long)] + replica: Option, + /// The latest deployment's build and deploy log instead. + #[arg(long, conflicts_with_all = ["since", "replica"])] + build: bool, }, /// Environment variables. Env { @@ -149,7 +175,41 @@ enum Command { #[command(flatten)] which: Which, }, - /// A shell in the service. + /// Where the service runs: any server, or only the servers and tags + /// given. It moves over right away, without a redeploy. Without + /// options, shows where it runs now. + Place { + #[command(flatten)] + which: Which, + /// A server to run on, by name (repeatable). + #[arg(long = "server")] + servers: Vec, + /// Run on every server with this tag, tagged now or later (repeatable). + #[arg(long = "tag")] + tags: Vec, + /// Run on any server. + #[arg(long, conflicts_with_all = ["servers", "tags"])] + any: bool, + }, + /// How many replicas the service runs. It changes right away, without + /// a redeploy, and in pyo.jsonc too. Without a number, shows how many + /// run now and where. + Scale { + /// The number of replicas, 1 or more. + #[arg(value_parser = clap::value_parser!(u32).range(1..=i32::MAX as i64))] + replicas: Option, + #[command(flatten)] + which: Which, + /// Don't ask: go ahead with a very large change. + #[arg(long, short = 'y')] + yes: bool, + }, + /// A shell in the service, or one command: pyo exec -- . + /// + /// A command runs as it is, without a shell (use sh -c for one). It + /// gets a terminal when stdin and stdout are one, else its output and + /// errors stay apart, piped input goes to it, and pyo exits with its + /// exit code. Exec { #[command(flatten)] which: Which, @@ -157,8 +217,20 @@ enum Command { #[arg(long)] replica: Option, /// bash, sh, zsh or ash. Defaults to whichever the service has. - #[arg(long)] + #[arg(long, conflicts_with = "command")] shell: Option, + /// Give the command a terminal. + #[arg(short = 't', long = "tty", conflicts_with = "no_tty")] + tty: bool, + /// Never give the command a terminal. + #[arg(short = 'T', long = "no-tty")] + no_tty: bool, + /// Send stdin to the command even from a terminal (end it with Ctrl-D). + #[arg(short = 'i', long = "interactive")] + interactive: bool, + /// The command and its arguments, after --. + #[arg(last = true, value_name = "COMMAND")] + command: Vec, }, /// Open the service on the dashboard. Open { @@ -644,12 +716,22 @@ enum EnvCommand { deploy: bool, }, /// Write the variables to a .env file. + /// + /// Secrets are listed with an empty value, unless --secrets: owners and + /// admins get their values. Pull { - #[arg(default_value = ".env")] + /// The file to write. + #[arg(default_value = ".env", conflicts_with = "out")] file: String, + /// The file to write, as an option. + #[arg(long = "file", short = 'o', value_name = "FILE")] + out: Option, /// Overwrite the file. #[arg(long)] force: bool, + /// Write secrets' values too. Owners and admins. + #[arg(long)] + secrets: bool, }, } @@ -662,14 +744,22 @@ async fn main() { _ => upgrade::Check::start(), }; let result = run(cli).await; - if let Err(e) = &result { - eprintln!("{} {e:#}", ui::red("error:")); - } + // A command run with pyo exec: its own exit code, nothing more said. + let code = match &result { + Ok(()) => 0, + Err(e) => match e.downcast_ref::() { + Some(exec::Exited(c)) => *c, + None => { + eprintln!("{} {e:#}", ui::red("error:")); + 1 + } + }, + }; if let Some(check) = check { check.finish(); } - if result.is_err() { - std::process::exit(1); + if code != 0 { + std::process::exit(code); } } @@ -766,24 +856,52 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { .await } Command::Deploy { - which, detach, yes, .. + which, + detach, + yes, + local, + include_env, + name, + project, + team, + cluster, + .. } => { service::deploy( &config::client(url, token)?, which.service.as_deref(), detach, yes, + service::Folder { + local, + with_env: include_env, + name, + project, + team, + cluster, + }, ) .await } Command::Status { which, json } => { service::status(&config::client(url, token)?, which.service.as_deref(), json).await } - Command::Logs { which, follow } => { + Command::Logs { + which, + follow, + since, + replica, + build, + } => { service::logs( &config::client(url, token)?, which.service.as_deref(), - follow, + service::LogsOpts { + follow, + since, + replica, + build, + }, ) .await } @@ -830,7 +948,12 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { ) .await } - EnvCommand::Pull { file, force } => service::env_pull(&api, s, &file, force).await, + EnvCommand::Pull { + file, + out, + force, + secrets, + } => service::env_pull(&api, s, &out.unwrap_or(file), force, secrets).await, } } Command::Rollback { deployment, which } => { @@ -844,16 +967,59 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { Command::Restart { which } => { service::restart(&config::client(url, token)?, which.service.as_deref()).await } + Command::Place { + which, + servers, + tags, + any, + } => { + service::place( + &config::client(url, token)?, + which.service.as_deref(), + servers, + tags, + any, + ) + .await + } + Command::Scale { + replicas, + which, + yes, + } => { + service::scale( + &config::client(url, token)?, + which.service.as_deref(), + replicas, + yes, + ) + .await + } Command::Exec { which, replica, shell, + tty, + no_tty, + interactive, + command, } => { exec::run( &config::client(url, token)?, which.service.as_deref(), - replica, - shell, + exec::Opts { + replica, + shell, + command, + tty: if tty { + Some(true) + } else if no_tty { + Some(false) + } else { + None + }, + stdin: interactive, + }, ) .await } @@ -1113,6 +1279,104 @@ mod tests { walk(&Cli::command(), "pyo"); } + #[test] + fn new_commands_parse() { + let parse = |args: &[&str]| Cli::try_parse_from(args).map(|c| c.command); + let Ok(Command::Exec { + command, + tty, + no_tty, + .. + }) = parse(&["pyo", "exec", "-s", "api", "-T", "--", "ls", "-la", "/app"]) + else { + panic!("exec didn't parse"); + }; + assert_eq!(command, ["ls", "-la", "/app"]); + assert!(no_tty && !tty); + assert!(parse(&["pyo", "exec", "-t", "-T", "--", "ls"]).is_err()); + assert!(matches!( + parse(&["pyo", "exec"]), + Ok(Command::Exec { command, .. }) if command.is_empty() + )); + assert!(matches!( + parse(&["pyo", "logs", "-f", "--since", "10m", "--replica", "x2kfp"]), + Ok(Command::Logs { + follow: true, + since: Some(_), + replica: Some(_), + build: false, + .. + }) + )); + assert!(parse(&["pyo", "logs", "--build", "--since", "1h"]).is_err()); + assert!(matches!( + parse(&[ + "pyo", + "deploy", + "--local", + "--name", + "web", + "--project", + "shop" + ]), + Ok(Command::Deploy { + local: true, + name: Some(_), + project: Some(_), + .. + }) + )); + assert!(parse(&["pyo", "deploy", "--local", "-f", "compose.yml"]).is_err()); + let Ok(Command::Env { + command: Some(EnvCommand::Pull { + file, out, secrets, .. + }), + .. + }) = parse(&["pyo", "env", "pull", "--file", "prod.env", "--secrets"]) + else { + panic!("env pull didn't parse"); + }; + assert_eq!( + (file.as_str(), out.as_deref(), secrets), + (".env", Some("prod.env"), true) + ); + } + + #[test] + fn scale_parses() { + let parse = |args: &[&str]| Cli::try_parse_from(args).map(|c| c.command); + let Ok(Command::Scale { + replicas, + which, + yes, + }) = parse(&["pyo", "scale", "3", "-s", "shop/api"]) + else { + panic!("scale didn't parse"); + }; + assert_eq!( + (replicas, which.service.as_deref(), yes), + (Some(3), Some("shop/api"), false) + ); + assert!(matches!( + parse(&["pyo", "scale", "-s", "api", "40", "--yes"]), + Ok(Command::Scale { + replicas: Some(40), + yes: true, + .. + }) + )); + // No number: shows what runs now. + assert!(matches!( + parse(&["pyo", "scale"]), + Ok(Command::Scale { replicas: None, .. }) + )); + // At least 1, and no more than Kubernetes counts. + assert!(parse(&["pyo", "scale", "0"]).is_err()); + assert!(parse(&["pyo", "scale", "-1"]).is_err()); + assert!(parse(&["pyo", "scale", "2147483648"]).is_err()); + assert!(parse(&["pyo", "scale", "two"]).is_err()); + } + #[test] fn sandbox_commands_map_to_the_api() { let parse = |args: &[&str]| Cli::try_parse_from(args).map(|c| c.command); diff --git a/crates/pyo-cli/src/pack.rs b/crates/pyo-cli/src/pack.rs new file mode 100644 index 00000000..ad816f46 --- /dev/null +++ b/crates/pyo-cli/src/pack.rs @@ -0,0 +1,549 @@ +//! `pyo deploy` from a folder: pack it as a gzipped tar and send it to Pyo +//! in parts, which hands it to a builder in the service's cluster. +//! +//! What goes in: every file, dotfiles too, except what `.gitignore` (and +//! `.git/info/exclude`) and `.pyoignore` leave out, `.git`, and +//! `node_modules` (a `!node_modules/` line in `.pyoignore` keeps it). `.env` +//! files (`.env`, `.env.local`, `prod.env`) stay out unless asked for +//! (`.env.example` and the like go in). + +use std::{ + collections::BTreeMap, + io::{IsTerminal, Read, Seek, Write}, + path::{Path, PathBuf}, + time::{Duration, Instant}, +}; + +use anyhow::{Context, Result, bail}; +use serde_json::{Value, json}; + +use crate::{api::Api, ui}; + +/// The most Pyo takes, packed. +pub const MAX_BYTES: u64 = 500_000_000; +/// What a folder leaves out unless its ignore files keep it. +const DEFAULT_IGNORES: &str = "node_modules/\n"; + +/// A file to pack: its path in the archive and on disk, and its size. +pub struct Entry { + pub rel: PathBuf, + pub abs: PathBuf, + pub size: u64, +} + +/// A `.env` file, kept out unless asked for. Examples and templates of one +/// (`.env.example`, `.env.sample`, …) aren't. +pub fn is_env_file(name: &str) -> bool { + let env = name == ".env" || name.starts_with(".env.") || name.ends_with(".env"); + env && !matches!( + name.rsplit('.').next().unwrap_or(""), + "example" | "sample" | "template" | "dist" | "defaults" + ) +} + +/// The files of `root` to pack, in order. +pub fn list(root: &Path, with_env: bool) -> Result> { + // The defaults as an ignore file of the lowest precedence, so the + // folder's own files can keep what they leave out. + let defaults = std::env::temp_dir().join(format!("pyo-defaults-{}.ignore", std::process::id())); + std::fs::write(&defaults, DEFAULT_IGNORES)?; + let mut walk = ignore::WalkBuilder::new(root); + walk.hidden(false) + .ignore(false) + .git_ignore(true) + .git_exclude(true) + .git_global(false) + .require_git(false) + .parents(true) + .follow_links(false) + .add_custom_ignore_filename(".pyoignore") + .sort_by_file_name(|a, b| a.cmp(b)) + .filter_entry(move |e| { + let name = e.file_name().to_string_lossy(); + if name == ".git" { + return false; + } + with_env || !(e.file_type().is_some_and(|t| !t.is_dir()) && is_env_file(&name)) + }); + if let Some(e) = walk.add_ignore(&defaults) { + let _ = std::fs::remove_file(&defaults); + return Err(e.into()); + } + let mut out = vec![]; + let result = (|| -> Result<()> { + for e in walk.build() { + let e = e?; + let Some(t) = e.file_type() else { continue }; + if t.is_dir() { + continue; + } + let rel = e + .path() + .strip_prefix(root) + .unwrap_or(e.path()) + .to_path_buf(); + if rel.as_os_str().is_empty() { + continue; + } + let size = if t.is_file() { + e.metadata().map(|m| m.len()).unwrap_or(0) + } else { + 0 + }; + out.push(Entry { + rel, + abs: e.path().to_path_buf(), + size, + }); + } + Ok(()) + })(); + let _ = std::fs::remove_file(&defaults); + result?; + Ok(out) +} + +/// A packed folder, in a temporary file removed when it drops. +pub struct Packed { + pub path: PathBuf, + pub size: u64, + pub sha256: String, + pub files: usize, +} + +impl Drop for Packed { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } +} + +/// Counts and hashes what's written, and stops at `limit` bytes. +struct Counted { + inner: W, + n: u64, + limit: u64, + hash: sha2::Sha256, +} + +impl Write for Counted { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + use sha2::Digest; + if self.n + buf.len() as u64 > self.limit { + return Err(std::io::Error::other(TooBig)); + } + let n = self.inner.write(buf)?; + self.hash.update(&buf[..n]); + self.n += n as u64; + Ok(n) + } + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + +#[derive(Debug)] +struct TooBig; + +impl std::fmt::Display for TooBig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("too big") + } +} + +impl std::error::Error for TooBig {} + +/// "12.3 MB", "980 KB". +pub fn size_text(b: u64) -> String { + if b >= 1_000_000 { + format!("{:.1} MB", b as f64 / 1_000_000.0) + } else { + format!("{} KB", b.div_ceil(1000)) + } +} + +/// The biggest folders and files at the top, for a folder that's too big. +fn biggest(files: &[Entry]) -> String { + let mut by: BTreeMap = BTreeMap::new(); + for f in files { + let top = f + .rel + .components() + .next() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .unwrap_or_default(); + *by.entry(top).or_default() += f.size; + } + let mut v: Vec<(String, u64)> = by.into_iter().collect(); + v.sort_by_key(|e| std::cmp::Reverse(e.1)); + v.iter() + .take(3) + .map(|(n, s)| format!("{n} {}", size_text(*s))) + .collect::>() + .join(", ") +} + +/// Pack `files` of `root` into a temporary .tar.gz, at most `limit` bytes. +/// `tick` hears how many files are in so far. +pub fn pack(files: &[Entry], limit: u64, mut tick: impl FnMut(usize)) -> Result { + use sha2::Digest; + let path = std::env::temp_dir().join(format!( + "pyo-deploy-{}-{}.tar.gz", + std::process::id(), + crate::api::now_ms() + )); + let file = std::fs::File::create(&path).context("Couldn't write the archive")?; + let mut packed = Packed { + path, + size: 0, + sha256: String::new(), + files: 0, + }; + let counted = Counted { + inner: std::io::BufWriter::new(file), + n: 0, + limit, + hash: sha2::Sha256::new(), + }; + let gz = flate2::write::GzEncoder::new(counted, flate2::Compression::default()); + let mut tar = tar::Builder::new(gz); + // The same files give the same archive: no times, owners or modes + // beyond "executable". + tar.mode(tar::HeaderMode::Deterministic); + tar.follow_symlinks(false); + let too_big = |e: &std::io::Error| e.get_ref().is_some_and(|i| i.is::()); + let mut n = 0; + for f in files { + if let Err(e) = tar.append_path_with_name(&f.abs, &f.rel) { + if too_big(&e) { + bail!( + "The folder packs to more than {}, the most Pyo takes. Leave out more in .pyoignore. Biggest: {}.", + size_text(limit), + biggest(files) + ); + } + return Err(e).with_context(|| format!("Couldn't pack {}", f.rel.display())); + } + n += 1; + tick(n); + } + let gz = tar.into_inner().map_err(|e| { + if too_big(&e) { + anyhow::anyhow!( + "The folder packs to more than {}, the most Pyo takes. Leave out more in .pyoignore.", + size_text(limit) + ) + } else { + anyhow::Error::from(e) + } + })?; + let mut counted = gz.finish()?; + counted.flush()?; + packed.size = counted.n; + packed.sha256 = hex::encode(counted.hash.finalize()); + packed.files = n; + Ok(packed) +} + +/// One line that rewrites itself on a terminal, at most every 100 ms. +struct Progress { + tty: bool, + last: Option, +} + +impl Progress { + fn new() -> Self { + Self { + tty: std::io::stderr().is_terminal(), + last: None, + } + } + + fn show(&mut self, text: &str, force: bool) { + if !self.tty { + return; + } + if !force + && self + .last + .is_some_and(|t| t.elapsed() < Duration::from_millis(100)) + { + return; + } + self.last = Some(Instant::now()); + eprint!("\r\x1b[2K{}", ui::dim(text)); + let _ = std::io::stderr().flush(); + } + + fn done(&mut self) { + if self.tty && self.last.is_some() { + eprint!("\r\x1b[2K"); + let _ = std::io::stderr().flush(); + } + } +} + +/// Pack `root` and upload it for `team_id`: the upload's id, ready to deploy. +pub async fn upload(api: &Api, team_id: &str, root: &Path, with_env: bool) -> Result { + let mut progress = Progress::new(); + progress.show("Packing…", true); + let dir = root.to_path_buf(); + let (files, packed) = tokio::task::spawn_blocking(move || -> Result<(usize, Packed)> { + let files = list(&dir, with_env)?; + if files.is_empty() { + bail!("There's nothing to deploy in {}.", dir.display()); + } + let total = files.len(); + let mut p = Progress::new(); + let packed = pack(&files, MAX_BYTES, |n| { + p.show(&format!("Packing {n} of {total} files…"), false) + }); + p.done(); + Ok((total, packed?)) + }) + .await??; + progress.done(); + eprintln!( + "{} Packed {files} file{}, {}", + ui::green("✓"), + if files == 1 { "" } else { "s" }, + size_text(packed.size) + ); + + let folder = root + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let started = api + .post( + "/api/v1/source-uploads", + &json!({ + "teamId": team_id, + "size": packed.size, + "sha256": packed.sha256, + "files": packed.files, + "folder": folder, + "machine": crate::login::machine_name(), + }), + ) + .await?; + let id = started["uploadId"] + .as_str() + .context("Pyo gave no upload id")? + .to_owned(); + let part_size = started["partSize"].as_u64().unwrap_or(8 << 20).max(1); + let parts = packed.size.div_ceil(part_size); + + let mut file = std::fs::File::open(&packed.path)?; + let mut sent = 0u64; + let mut send_parts = |todo: Vec| { + let mut out = vec![]; + for n in todo { + let len = part_size.min(packed.size - n * part_size); + let mut buf = vec![0u8; len as usize]; + file.seek(std::io::SeekFrom::Start(n * part_size))?; + file.read_exact(&mut buf)?; + out.push((n, buf)); + } + Ok::<_, std::io::Error>(out) + }; + // In batches, so a big folder isn't read into memory at once. + let mut todo: Vec = (0..parts).collect(); + for round in 0..3 { + for chunk in todo.clone().chunks(4) { + for (n, buf) in send_parts(chunk.to_vec())? { + let len = buf.len() as u64; + let path = format!("/api/v1/source-uploads/{id}/parts/{n}"); + let mut tries = 0; + loop { + match api.put_bytes(&path, buf.clone()).await { + Ok(_) => break, + Err(e) if tries < 4 => { + tries += 1; + progress.show(&format!("Retrying a part: {e}"), true); + tokio::time::sleep(Duration::from_secs(1 << tries)).await; + } + Err(_) if round < 2 => break, + Err(e) => { + progress.done(); + return Err(e.context("The upload broke off. Try again.")); + } + } + } + sent += len; + progress.show( + &format!( + "Uploading {} of {} ({}%)", + size_text(sent.min(packed.size)), + size_text(packed.size), + sent.min(packed.size) * 100 / packed.size.max(1) + ), + false, + ); + } + } + // What Pyo has: send the rest again. + let st = api.get(&format!("/api/v1/source-uploads/{id}")).await?; + let have: Vec = st["received"] + .as_array() + .map(|a| a.iter().filter_map(Value::as_u64).collect()) + .unwrap_or_default(); + todo = (0..parts).filter(|n| !have.contains(n)).collect(); + if todo.is_empty() { + break; + } + } + progress.done(); + if !todo.is_empty() { + bail!("The upload broke off. Try again."); + } + api.post(&format!("/api/v1/source-uploads/{id}/complete"), &json!({})) + .await?; + eprintln!("{} Uploaded {}", ui::green("✓"), size_text(packed.size)); + Ok(id) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Dir(PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn folder(files: &[(&str, &str)]) -> Dir { + let d = std::env::temp_dir().join(format!( + "pyo-pack-test-{}-{}", + std::process::id(), + crate::api::new_id("t") + )); + for (p, body) in files { + let p = d.join(p); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, body).unwrap(); + } + Dir(d) + } + + fn names(root: &Path, with_env: bool) -> Vec { + list(root, with_env) + .unwrap() + .iter() + .map(|e| e.rel.to_string_lossy().replace('\\', "/")) + .collect() + } + + #[test] + fn env_files_are_secrets_but_examples_arent() { + for n in [".env", ".env.local", ".env.production", "prod.env", "a.env"] { + assert!(is_env_file(n), "{n}"); + } + for n in [ + ".env.example", + ".env.local.sample", + ".env.template", + ".envrc", + "env", + "env.ts", + ] { + assert!(!is_env_file(n), "{n}"); + } + } + + #[test] + fn ignore_files_and_defaults() { + let d = folder(&[ + ("Dockerfile", "FROM scratch"), + (".gitignore", "dist/\n*.log\n"), + (".pyoignore", "secret.txt\n"), + (".git/HEAD", "ref"), + (".env", "A=1"), + (".env.example", "A="), + ("app.log", "x"), + ("dist/out.js", "x"), + ("node_modules/a/index.js", "x"), + ("secret.txt", "x"), + ("src/.hidden", "x"), + ("src/main.rs", "x"), + ]); + assert_eq!( + names(&d.0, false), + [ + ".env.example", + ".gitignore", + ".pyoignore", + "Dockerfile", + "src/.hidden", + "src/main.rs" + ] + ); + assert!(names(&d.0, true).contains(&".env".to_owned())); + } + + #[test] + fn pyoignore_can_keep_node_modules() { + let d = folder(&[ + (".pyoignore", "!node_modules/\n"), + ("node_modules/a/index.js", "x"), + ("index.js", "x"), + ]); + assert!(names(&d.0, false).contains(&"node_modules/a/index.js".to_owned())); + } + + #[test] + fn packs_the_same_files_the_same_way() { + let d = folder(&[("a.txt", "hello"), ("b/c.txt", "world")]); + let files = list(&d.0, false).unwrap(); + let mut ticks = 0; + let one = pack(&files, MAX_BYTES, |_| ticks += 1).unwrap(); + assert_eq!((one.files, ticks), (2, 2)); + let two = pack(&files, MAX_BYTES, |_| {}).unwrap(); + assert_eq!(one.sha256, two.sha256); + assert_eq!(std::fs::metadata(&one.path).unwrap().len(), one.size); + // It unpacks to the same files. + let gz = flate2::read::GzDecoder::new(std::fs::File::open(&one.path).unwrap()); + let mut tar = tar::Archive::new(gz); + let mut got: Vec<(String, String)> = tar + .entries() + .unwrap() + .map(|e| { + let mut e = e.unwrap(); + let mut s = String::new(); + e.read_to_string(&mut s).unwrap(); + (e.path().unwrap().to_string_lossy().into_owned(), s) + }) + .collect(); + got.sort(); + assert_eq!( + got, + [ + ("a.txt".into(), "hello".into()), + ("b/c.txt".into(), "world".into()) + ] + ); + let path = one.path.clone(); + drop(one); + assert!(!path.exists(), "the archive is removed"); + } + + #[test] + fn a_folder_over_the_limit_says_what_is_big() { + let mut noise = vec![0u8; 100_000]; + rand::fill(&mut noise[..]); + let big = hex::encode(noise); + let d = folder(&[("data/blob.txt", &big), ("small.txt", "x")]); + let files = list(&d.0, false).unwrap(); + let e = pack(&files, 1000, |_| {}).err().unwrap().to_string(); + assert!(e.contains("more than 1 KB"), "{e}"); + assert!(e.contains("Biggest: data"), "{e}"); + } + + #[test] + fn sizes_in_words() { + assert_eq!(size_text(12_345_678), "12.3 MB"); + assert_eq!(size_text(980_001), "981 KB"); + assert_eq!(size_text(1), "1 KB"); + } +} diff --git a/crates/pyo-cli/src/service.rs b/crates/pyo-cli/src/service.rs index 8f80ffb1..30e02e64 100644 --- a/crates/pyo-cli/src/service.rs +++ b/crates/pyo-cli/src/service.rs @@ -6,6 +6,7 @@ use std::{collections::HashSet, io::IsTerminal, path::PathBuf, time::Duration}; use anyhow::{Context, Result, bail}; +use pyo_proto::{LogFrame, LogLine}; use serde_json::{Value, json}; use crate::{ @@ -119,57 +120,309 @@ fn confirmed(answer: &str) -> bool { matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") } -pub async fn deploy(api: &Api, service: Option<&str>, detach: bool, yes: bool) -> Result<()> { +/// How `pyo deploy` sends a folder, and what a new service from one is. +#[derive(Default)] +pub struct Folder { + /// Send the working copy, even for a service built from Git. + pub local: bool, + /// Send .env files too. + pub with_env: bool, + /// A new service's name, project, team and cluster. + pub name: Option, + pub project: Option, + pub team: Option, + pub cluster: Option, +} + +/// An operation that may ask to confirm a very large replica change: +/// asked here, or `-y`. +async fn confirmed_op(api: &Api, name: &str, body: Value, yes: bool) -> Result { + let send = |confirm: bool| { + let mut b = body.clone(); + b["confirm"] = json!(confirm); + api.op(name, b) + }; + match send(yes).await { + Err(e) if e.downcast_ref::().is_some() => { + if !confirmed(&ui::ask(&format!("{e} [y/N] "))?) { + bail!("Not deployed."); + } + send(true).await + } + r => r, + } +} + +/// A folder is built by one of the team's builders: said before it's +/// packed and sent. +fn has_builder(state: &State, team_id: &str) -> Result<()> { + let ready = state.0["builders"] + .as_array() + .into_iter() + .flatten() + .any(|b| b["teamId"] == json!(team_id) && b["status"] == json!("ready")); + if !ready { + bail!("Deploying a folder needs a builder. Add one in Builders, then deploy again."); + } + Ok(()) +} + +/// The folder a deploy sends: pyo.jsonc's, else this one. +fn folder_of(file: Option<&std::path::Path>) -> Result { + match file + .and_then(|f| f.parent()) + .filter(|p| !p.as_os_str().is_empty()) + { + Some(p) => Ok(p.to_path_buf()), + None => Ok(std::env::current_dir()?), + } +} + +pub async fn deploy( + api: &Api, + service: Option<&str>, + detach: bool, + yes: bool, + folder: Folder, +) -> Result<()> { + // A folder that isn't linked yet: a new service from it. + if service.is_none() { + let file = config::find()?; + let linked = match &file { + Some(p) => config::load(p)?.service.is_some(), + None => false, + }; + if !linked { + return create_from_folder(api, file, detach, yes, folder).await; + } + } let t = target(api, service).await?; let mut service = t.service().clone(); + let kind = service["source"]["type"].as_str().unwrap_or("").to_owned(); + let name = service["name"].as_str().unwrap_or("").to_owned(); + if folder.local && !matches!(kind.as_str(), "git" | "upload") { + bail!("{name} runs an image, so it isn't built from a folder."); + } let changes = match &t.file { Some((_, f)) => apply(&mut service, f)?, None => vec![], }; + for c in &changes { + println!("{} {c}", ui::dim("·")); + } let dep = new_id("dpl"); - let done = if changes.is_empty() { + let done = if kind == "upload" || folder.local { + let root = folder_of(t.file.as_ref().map(|(p, _)| p.as_path()))?; + let team_id = service["teamId"].as_str().unwrap_or("").to_owned(); + has_builder(&t.state, &team_id)?; + let upload = crate::pack::upload(api, &team_id, &root, folder.with_env).await?; + if !changes.is_empty() { + confirmed_op(api, "saveService", json!({ "service": service }), yes).await?; + } + api.op( + "deploy", + json!({ "serviceId": t.id, "deploymentId": dep, "trigger": "manual", "uploadId": upload }), + ) + .await? + } else if changes.is_empty() { api.op( "deploy", json!({ "serviceId": t.id, "deploymentId": dep, "trigger": "manual" }), ) .await? } else { - for c in &changes { - println!("{} {c}", ui::dim("·")); - } - let save = |confirm: bool| { - api.op( - "saveService", - json!({ "service": service, "deploymentId": dep, "trigger": "manual", "confirm": confirm }), - ) - }; - match save(yes).await { - Err(e) if e.downcast_ref::().is_some() => { - // A very large replica change: asked here, or -y. - if !confirmed(&ui::ask(&format!("{e} [y/N] "))?) { - bail!("Not deployed."); - } - save(true).await? - } - r => r?, - } + confirmed_op( + api, + "saveService", + json!({ "service": service, "deploymentId": dep, "trigger": "manual" }), + yes, + ) + .await? }; // Replicas that don't fit on the servers wait for room. if let Some(w) = done["warning"].as_str() { println!("{}", ui::yellow(w)); } let url = t.state.deployment_url(&api.base, &service, &dep); - println!( - "Deploying {} {}", - ui::bold(service["name"].as_str().unwrap_or("")), - ui::dim(&url) - ); + println!("Deploying {} {}", ui::bold(&name), ui::dim(&url)); if detach { return Ok(()); } watch(api, &dep).await } +/// A service name from a folder's: lowercase letters, digits and dashes. +pub fn slug(s: &str) -> String { + let mut out = String::new(); + for c in s.trim().chars().flat_map(char::to_lowercase) { + if c.is_ascii_alphanumeric() { + out.push(c); + } else if !out.ends_with('-') && !out.is_empty() { + out.push('-'); + } + } + let out: String = out.trim_matches('-').chars().take(40).collect(); + let out = out.trim_end_matches('-').to_owned(); + match out.chars().next() { + Some(c) if c.is_ascii_alphabetic() => out, + Some(_) => format!("app-{out}"), + None => "app".into(), + } +} + +/// A new service built from a folder, as the dashboard makes one: one +/// HTTP port (8080 until the build says another), a check that it's open. +fn new_service(id: &str, team_id: &str, project_id: &str, cluster_id: &str, name: &str) -> Value { + json!({ + "id": id, "teamId": team_id, "projectId": project_id, "clusterId": cluster_id, + "name": name, "description": "", + "source": { "type": "upload", "dockerfilePath": "Dockerfile", "buildContext": ".", "buildArgs": [] }, + "env": [], + "resources": { "cpuRequest": 100, "cpuLimit": 500, "memoryRequest": 128, "memoryLimit": 256 }, + "replicas": 1, + "healthCheck": { "type": "tcp", "path": "", "port": 8080, "command": "", "initialDelaySeconds": 10, "periodSeconds": 10, "auto": "default" }, + "ports": [{ "id": new_id("port"), "name": "http", "containerPort": 8080, "protocol": "HTTP", "exposure": "internal" }], + "domains": [], + }) +} + +/// The project a new service goes in: `--project` (made when there's none +/// by that name), else picked, else the team's only one. +async fn pick_project( + api: &Api, + state: &State, + team_id: &str, + want: Option<&str>, + default_name: &str, +) -> Result { + let projects: Vec<&Value> = state.0["projects"] + .as_array() + .into_iter() + .flatten() + .filter(|p| p["teamId"] == json!(team_id)) + .collect(); + let make = |name: String| async move { + let id = new_id("prj"); + api.op( + "createProject", + json!({ "id": id, "teamId": team_id, "name": name, "namespace": slug(&name) }), + ) + .await?; + ui::ok(&format!("Created project {}", ui::bold(&name))); + Ok::<_, anyhow::Error>(id) + }; + if let Some(w) = want { + return match projects + .iter() + .find(|p| p["id"] == json!(w) || p["name"] == json!(w) || p["namespace"] == json!(w)) + { + Some(p) => Ok(p["id"].as_str().unwrap_or("").to_owned()), + None => make(w.to_owned()).await, + }; + } + if !std::io::stdin().is_terminal() { + return match projects.as_slice() { + [] => make(default_name.to_owned()).await, + [p] => Ok(p["id"].as_str().unwrap_or("").to_owned()), + _ => bail!("Say which project with --project."), + }; + } + let mut names: Vec = projects + .iter() + .map(|p| p["name"].as_str().unwrap_or("").to_owned()) + .collect(); + names.push("A new project".into()); + let i = ui::choose("Which project?", &names)?; + if i < projects.len() { + return Ok(projects[i]["id"].as_str().unwrap_or("").to_owned()); + } + let name = ui::ask(&format!("Project name ({default_name}): "))?; + make(if name.is_empty() { + default_name.to_owned() + } else { + name + }) + .await +} + +/// `pyo deploy` in a folder no service is linked to: make one from it, +/// link the folder, upload it and follow the deploy. +async fn create_from_folder( + api: &Api, + file: Option, + detach: bool, + yes: bool, + f: Folder, +) -> Result<()> { + let root = folder_of(file.as_deref())?; + let folder = root + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let (team_id, cluster_id) = + crate::compose::team_and_cluster(api, f.team.as_deref(), f.cluster.as_deref()).await?; + let state = api.state().await?; + has_builder(&state, &team_id)?; + let suggested = slug(&folder); + let name = match f.name { + Some(n) => n, + None if std::io::stdin().is_terminal() => { + println!( + "{}", + ui::dim("No service is linked to this folder. Pyo makes one from it.") + ); + let a = ui::ask(&format!("Service name ({suggested}): "))?; + if a.is_empty() { suggested.clone() } else { a } + } + None => suggested.clone(), + }; + if slug(&name) != name { + bail!( + "\"{name}\" can't be a service name. Try {}: lowercase letters, digits and dashes.", + slug(&name) + ); + } + let project_id = pick_project(api, &state, &team_id, f.project.as_deref(), &name).await?; + let id = new_id("svc"); + let mut service = new_service(&id, &team_id, &project_id, &cluster_id, &name); + if let Some(p) = &file { + for c in apply(&mut service, &config::load(p)?)? { + println!("{} {c}", ui::dim("·")); + } + } + let upload = crate::pack::upload(api, &team_id, &root, f.with_env).await?; + let dep = new_id("dpl"); + let done = confirmed_op( + api, + "createService", + json!({ "service": service, "deploymentId": dep, "uploadId": upload }), + yes, + ) + .await?; + let path = config::write_service(file.as_deref(), &id)?; + let state = api.state().await?; + let label = state + .service(&id) + .map(|s| state.path_of(s)) + .unwrap_or(name.clone()); + ui::ok(&format!( + "Created {} and linked it in {}", + ui::bold(&label), + path.display() + )); + if let Some(w) = done["warning"].as_str() { + println!("{}", ui::yellow(w)); + } + let url = state.deployment_url(&api.base, &service, &dep); + println!("Deploying {} {}", ui::bold(&name), ui::dim(&url)); + if detach { + return Ok(()); + } + watch(api, &dep).await?; + println!("{}", ui::dim("Give it an address: pyo domain add --free")); + Ok(()) +} + /// Follow a deployment to the end: its stages and build log. Fails when it does. pub async fn watch(api: &Api, dep: &str) -> Result<()> { println!( @@ -294,8 +547,10 @@ pub fn apply(service: &mut Value, f: &ServiceFile) -> Result> { || b.context.is_some() || !b.args.is_empty() { - if kind != "git" { - bail!("pyo.jsonc: build is for services built from Git. This one is from {kind}."); + if kind != "git" && kind != "upload" { + bail!( + "pyo.jsonc: build is for services built from Git or a folder. This one is from {kind}." + ); } if let Some(v) = &b.branch { set( @@ -586,33 +841,286 @@ pub async fn status(api: &Api, service: Option<&str>, as_json: bool) -> Result<( // ── logs ─────────────────────────────────────────────────────────────── -pub async fn logs(api: &Api, service: Option<&str>, follow: bool) -> Result<()> { +/// What `pyo logs` reads. +#[derive(Default)] +pub struct LogsOpts { + pub follow: bool, + /// "10m", "2h", "1d": only lines since then. + pub since: Option, + /// One replica: its name, or the end of it. + pub replica: Option, + /// The latest deployment's build and deploy log instead. + pub build: bool, +} + +/// "30s", "10m", "2h", "1d" in milliseconds. +pub fn parse_since(s: &str) -> Result { + let s = s.trim(); + let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len())); + let n: i64 = n + .parse() + .ok() + .filter(|n| *n > 0) + .with_context(|| format!("--since takes a time like 30s, 10m, 2h or 1d, not {s:?}."))?; + let ms = match unit { + "s" => 1000, + "m" | "" => 60_000, + "h" => 3_600_000, + "d" => 86_400_000, + _ => bail!("--since takes a time like 30s, 10m, 2h or 1d, not {s:?}."), + }; + Ok(n.saturating_mul(ms).min(7 * 86_400_000)) +} + +/// A replica's name, short: without the service's name in front. +fn short_replica<'a>(service: &str, pod: &'a str) -> &'a str { + pod.strip_prefix(service) + .and_then(|r| r.strip_prefix('-')) + .filter(|r| !r.is_empty()) + .unwrap_or(pod) +} + +/// Whether `--replica` means this one: its name, short name or its end. +fn is_replica(service: &str, pod: &str, want: &str) -> bool { + pod == want || short_replica(service, pod) == want || pod.ends_with(&format!("-{want}")) +} + +pub async fn logs(api: &Api, service: Option<&str>, o: LogsOpts) -> Result<()> { let t = target(api, service).await?; - let path = format!("/api/v1/services/{}/logs", t.id); - let mut last = 0i64; - let mut seen: HashSet = HashSet::new(); - loop { - let r = api.get(&path).await?; - for l in r["logs"].as_array().into_iter().flatten() { - let at = l["at"].as_i64().unwrap_or(0); - let key = format!("{at}{}{}", l["source"], l["message"]); - if at < last || !seen.insert(key) { + if o.build { + return build_logs(api, &t, o.follow).await; + } + let name = t.service()["name"].as_str().unwrap_or("").to_owned(); + let since = match &o.since { + Some(s) => Some(now_ms() - parse_since(s)?), + None => None, + }; + // The whole name narrows what the cluster reads; a short one is matched here. + let exact = o + .replica + .clone() + .filter(|r| r.starts_with(&format!("{name}-"))); + let mut p = LogPrinter { + name, + replica: o.replica.clone(), + last: since.unwrap_or(0), + floor: since.unwrap_or(0), + seen: HashSet::new(), + }; + if !o.follow { + let mut q: Vec<(&str, String)> = vec![]; + if let Some(r) = &exact { + q.push(("replica", r.clone())); + } + if let Some(s) = since { + q.push(("since", s.to_string())); + } + let r = api + .get(&format!("/api/v1/services/{}/logs?{}", t.id, query(&q))) + .await?; + p.print(&serde_json::from_value::>(r["logs"].clone()).unwrap_or_default()); + return Ok(()); + } + follow_logs(api, &t.id, exact.as_deref(), since, &mut p).await +} + +/// `k=v&k=v` (replica names and times need no encoding). +fn query(q: &[(&str, String)]) -> String { + q.iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join("&") +} + +/// Prints log lines once each, in the order they come. +struct LogPrinter { + name: String, + /// `--replica`: its name, short name or the end of it. + replica: Option, + /// The newest line's time printed. + last: i64, + /// Lines before this are old (the start of this read or follow). + floor: i64, + /// The lines printed at `last`: a follow from there sends them again. + seen: HashSet, +} + +impl LogPrinter { + /// Whether to print this line: wanted, and not printed before. + fn take(&mut self, l: &LogLine) -> bool { + if self + .replica + .as_deref() + .is_some_and(|w| !is_replica(&self.name, &l.source, w)) + { + return false; + } + let key = format!("{}\u{0}{}\u{0}{}", l.at, l.source, l.message); + if l.at < self.floor || (l.at == self.floor && self.seen.contains(&key)) { + return false; + } + if l.at > self.last { + self.last = l.at; + self.seen.clear(); + } + if l.at == self.last { + self.seen.insert(key); + } + true + } + + fn print(&mut self, lines: &[LogLine]) { + for l in lines { + if !self.take(l) { continue; } - last = last.max(at); - let src = l["source"].as_str().unwrap_or(""); - let msg = ui::log_text( - l["message"].as_str().unwrap_or(""), - l["level"].as_str().unwrap_or("info"), + let msg = ui::log_text(&l.message, &l.level); + println!( + "{} {} {msg}", + ui::dim(&ui::clock(l.at)), + ui::replica(short_replica(&self.name, &l.source)) ); - println!("{} {} {msg}", ui::dim(&ui::clock(at)), ui::dim(src)); } - if !follow { + } +} + +/// A follow that ends sooner than this went wrong: wait before the next. +const FOLLOW_SHORT: Duration = Duration::from_secs(10); + +/// Follows a service's logs over one WebSocket (one signed command for the +/// cluster), opening another when it ends: the first shows the last 100 +/// lines (or those since `since`), the next ones go on from the newest line. +async fn follow_logs( + api: &Api, + service_id: &str, + exact: Option<&str>, + since: Option, + p: &mut LogPrinter, +) -> Result<()> { + let started = now_ms(); + let mut first = true; + let mut wait = Duration::from_secs(3); + loop { + let mut q: Vec<(&str, String)> = vec![]; + if let Some(r) = exact { + q.push(("replica", r.to_owned())); + } + if first && since.is_none() { + q.push(("tail", "100".into())); + } else { + // Nothing printed yet: from when following began. + let from = if p.last > 0 { p.last } else { started }; + q.push(("since", from.to_string())); + } + p.floor = if first { since.unwrap_or(0) } else { p.last }; + let opened = tokio::time::Instant::now(); + let mut got = false; + let ended = follow_once(api, service_id, &query(&q), p, &mut got).await; + // Lines came: whatever happens next, it's a blip. + let was_first = first && !got; + first = false; + match ended { + // The first one fails: say why, as a read would. + Err(e) if was_first => return Err(e), + Err(e) => eprintln!("{} {e:#}", ui::yellow("!")), + // Ended after a while (it lasts an hour at most): go on at once. + Ok(()) if opened.elapsed() >= FOLLOW_SHORT => { + wait = Duration::from_secs(3); + continue; + } + Ok(()) => {} + } + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(60)); + } +} + +/// One follow, until Pyo or the cluster closes it. `got`: lines came. +async fn follow_once( + api: &Api, + service_id: &str, + query: &str, + p: &mut LogPrinter, + got: &mut bool, +) -> Result<()> { + use futures::StreamExt; + use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest, http::HeaderValue}; + let ws_base = api + .base + .replacen("https://", "wss://", 1) + .replacen("http://", "ws://", 1); + let mut req = format!("{ws_base}/api/v1/services/{service_id}/logs/follow?{query}") + .into_client_request()?; + req.headers_mut().insert( + "authorization", + HeaderValue::from_str(&format!("Bearer {}", api.token()))?, + ); + let (ws, _) = tokio_tungstenite::connect_async(req) + .await + .map_err(|e| crate::exec::refused_with(e, "Can't follow the service's logs"))?; + let (_up, mut down) = ws.split(); + while let Some(m) = down.next().await { + match m.context("The log follow broke")? { + Message::Text(t) => match serde_json::from_str::(&t) { + Ok(LogFrame::Lines { lines }) => { + *got = true; + p.print(&lines); + } + Ok(LogFrame::Error { message }) => bail!(message), + // A database's pods and events: not a service's. + Ok(LogFrame::Pods { .. } | LogFrame::Events { .. }) | Err(_) => {} + }, + Message::Close(_) => break, + _ => {} + } + } + Ok(()) +} + +/// The latest deployment's log: the build, then the rollout. Followed to +/// its end with `follow`; fails when the deployment did. +async fn build_logs(api: &Api, t: &Target, follow: bool) -> Result<()> { + let Some(dep) = t + .state + .deployments_of(&t.id) + .first() + .map(|d| d["id"].clone()) + else { + bail!( + "{} has no deployments yet.", + t.service()["name"].as_str().unwrap_or("") + ); + }; + let dep = dep.as_str().unwrap_or("").to_owned(); + let mut seen: HashSet = HashSet::new(); + let mut fresh: Option = None; + loop { + let st = fresh.as_ref().unwrap_or(&t.state); + let Some(d) = st.deployment(&dep) else { + bail!("That deployment is gone."); + }; + for l in d["logs"].as_array().into_iter().flatten() { + let key = l["id"] + .as_str() + .map(str::to_owned) + .unwrap_or_else(|| format!("{}{}", l["at"], l["message"])); + if seen.insert(key) { + print_line(l); + } + } + let status = d["status"].as_str().unwrap_or(""); + let done = matches!(status, "succeeded" | "failed" | "cancelled"); + if done || !follow { + if status == "failed" { + bail!( + "Deploy failed: {}", + d["failure"]["message"].as_str().unwrap_or("it failed.") + ); + } return Ok(()); } - // Only lines at the newest timestamp can repeat. - seen.retain(|k| k.starts_with(&last.to_string())); - tokio::time::sleep(Duration::from_secs(2)).await; + tokio::time::sleep(Duration::from_millis(1500)).await; + fresh = Some(api.state().await?); } } @@ -703,36 +1211,63 @@ pub async fn env_unset( .await } -/// Write the variables to a .env file; secrets are listed, not written. -pub async fn env_pull(api: &Api, service: Option<&str>, file: &str, force: bool) -> Result<()> { +/// Write the variables to a .env file. Secrets' values only with +/// `secrets`, for owners and admins (each one revealed is logged), else +/// they're listed empty, with a comment. +pub async fn env_pull( + api: &Api, + service: Option<&str>, + file: &str, + force: bool, + secrets: bool, +) -> Result<()> { let t = target(api, service).await?; if std::path::Path::new(file).exists() && !force { bail!("{file} exists. Overwrite it with --force."); } - let mut out = format!("# From Pyo: {}\n", t.state.path_of(t.service())); - let mut secrets = 0; + let mut vars: Vec<(String, Option)> = vec![]; + let mut hidden = 0; for e in t.service()["env"].as_array().into_iter().flatten() { - let k = e["key"].as_str().unwrap_or(""); - if e["secret"] == json!(true) { - out.push_str(&format!("# {k} is secret\n")); - secrets += 1; + let k = e["key"].as_str().unwrap_or("").to_owned(); + if e["secret"] != json!(true) { + vars.push((k, Some(e["value"].as_str().unwrap_or("").to_owned()))); + } else if secrets { + let r = api + .op( + "revealSecret", + json!({ "serviceId": t.id, "envId": e["id"] }), + ) + .await + .map_err(|err| { + if err.to_string().contains("owners and admins") { + anyhow::anyhow!( + "Only team owners and admins can pull secret values. Pull without --secrets." + ) + } else { + err + } + })?; + vars.push((k, Some(r["value"].as_str().unwrap_or("").to_owned()))); } else { - let v = e["value"].as_str().unwrap_or(""); - let quoted = if v.chars().any(|c| c.is_whitespace() || "#\"'$".contains(c)) { - format!("\"{}\"", v.replace('\\', "\\\\").replace('"', "\\\"")) - } else { - v.to_owned() - }; - out.push_str(&format!("{k}={quoted}\n")); + hidden += 1; + vars.push((k, None)); } } - std::fs::write(file, out)?; + let text = crate::dotenv::write( + &format!("From Pyo: {}", t.state.path_of(t.service())), + &vars, + ); + write_private(std::path::Path::new(file), &text) + .with_context(|| format!("Couldn't write {file}"))?; ui::ok(&format!( - "Wrote {file}{}", - if secrets > 0 { + "Wrote {} variable{} to {file}{}", + vars.len(), + if vars.len() == 1 { "" } else { "s" }, + if hidden > 0 { format!( - " ({secrets} secret{} left out)", - if secrets == 1 { "" } else { "s" } + ". {hidden} secret{} left empty: --secrets pulls {}", + if hidden == 1 { "" } else { "s" }, + if hidden == 1 { "it" } else { "them" } ) } else { String::new() @@ -741,6 +1276,20 @@ pub async fn env_pull(api: &Api, service: Option<&str>, file: &str, force: bool) Ok(()) } +/// A file only you can read (on Unix), since it may hold secrets. +fn write_private(path: &std::path::Path, text: &str) -> std::io::Result<()> { + use std::io::Write; + let mut open = std::fs::OpenOptions::new(); + open.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + open.mode(0o600); + } + let mut f = open.open(path)?; + f.write_all(text.as_bytes()) +} + /// How `env push` treats keys the service has already. #[derive(Clone, Copy, PartialEq)] pub enum Existing { @@ -1002,6 +1551,188 @@ pub async fn restart(api: &Api, service: Option<&str>) -> Result<()> { Ok(()) } +/// Where a service runs, in words: "any server", or its servers and tags. +fn placement_words(service: &Value) -> String { + let list = |v: &Value| -> Vec { + v.as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }; + // Services saved before `placement` kept `servers` and `serverTags`. + let (servers, tags) = match service.get("placement") { + Some(p) => (list(&p["servers"]), list(&p["tags"])), + None => (list(&service["servers"]), list(&service["serverTags"])), + }; + let mut parts = servers; + parts.extend(tags.iter().map(|t| format!("servers tagged {t}"))); + if parts.is_empty() { + return "any server".to_owned(); + } + and_list(parts) +} + +/// "a", "a and b", "a, b and c". +fn and_list(mut parts: Vec) -> String { + match parts.len() { + 0 => String::new(), + 1 => parts.remove(0), + n => format!("{} and {}", parts[..n - 1].join(", "), parts[n - 1]), + } +} + +/// Show or change where the service runs. A change goes live right away. +pub async fn place( + api: &Api, + service: Option<&str>, + servers: Vec, + tags: Vec, + any: bool, +) -> Result<()> { + let t = target(api, service).await?; + let mut s = t.service().clone(); + let name = s["name"].as_str().unwrap_or("").to_owned(); + if !any && servers.is_empty() && tags.is_empty() { + println!("{name} runs on {}", placement_words(&s)); + return Ok(()); + } + s["placement"] = json!({ "servers": servers, "tags": tags }); + if let Some(o) = s.as_object_mut() { + o.remove("servers"); + o.remove("serverTags"); + } + api.op("saveService", json!({ "service": s })).await?; + ui::ok(&format!("{name} runs on {}", placement_words(&s))); + Ok(()) +} + +// ── scale ────────────────────────────────────────────────────────────── + +/// "1 replica", "3 replicas". +fn replicas_count(n: i64) -> String { + if n == 1 { + "1 replica".to_owned() + } else { + format!("{n} replicas") + } +} + +/// How many replicas a service runs and on which servers, in words: +/// "api runs 3 replicas: 2 on dev-1 and 1 on dev-2". +fn scale_words(s: &Value) -> String { + let name = s["name"].as_str().unwrap_or(""); + if s["currentDeploymentId"].as_str().is_none() { + return format!("{name} isn't deployed yet"); + } + if s["status"] == json!("stopped") { + return format!("{name} is stopped"); + } + let mut line = match ( + s["autoscale"]["min"].as_i64(), + s["autoscale"]["max"].as_i64(), + ) { + (Some(lo), Some(hi)) => format!("{name} autoscales from {lo} to {hi} replicas"), + _ => format!( + "{name} runs {}", + replicas_count(s["replicas"].as_i64().unwrap_or(1)) + ), + }; + let mut on = std::collections::BTreeMap::<&str, i64>::new(); + let mut waiting = 0; + for r in s["runtime"]["replicas"].as_array().into_iter().flatten() { + match r["server"].as_str().filter(|s| !s.is_empty()) { + _ if r["waiting"] == json!(true) => waiting += 1, + Some(server) => *on.entry(server).or_default() += 1, + None => {} + } + } + let mut parts: Vec = on.iter().map(|(s, n)| format!("{n} on {s}")).collect(); + if waiting > 0 { + parts.push(format!("{waiting} waiting for room")); + } + if !parts.is_empty() { + line.push_str(": "); + line.push_str(&and_list(parts)); + } + line +} + +/// Why the API asks first: what follows its question, if anything. +/// "Scale to 40 replicas? That's more than 10 times the 2 it has now." +fn confirm_reason(msg: &str) -> Option<&str> { + msg.split_once("? ") + .map(|(_, why)| why.trim()) + .filter(|why| !why.is_empty()) +} + +/// Show how many replicas the service runs, or change it. A change goes +/// live right away, and pyo.jsonc's replicas follow so the next deploy +/// keeps it. +pub async fn scale( + api: &Api, + service: Option<&str>, + replicas: Option, + yes: bool, +) -> Result<()> { + let t = target(api, service).await?; + let s = t.service(); + let Some(n) = replicas else { + println!("{}", scale_words(s)); + return Ok(()); + }; + let name = s["name"].as_str().unwrap_or(""); + let before = if s["status"] == json!("stopped") { + 0 + } else { + s["replicas"].as_i64().unwrap_or(1) + }; + let send = |confirm: bool| { + api.op( + "scaleService", + json!({ "id": t.id, "replicas": n, "confirm": confirm }), + ) + }; + let done = match send(yes).await { + Err(e) if e.downcast_ref::().is_some() => { + let q = format!("Scale {name} from {before} to {n} replicas?"); + if let Some(why) = confirm_reason(&e.to_string()) { + println!("{}", ui::dim(why)); + } + if !std::io::stdin().is_terminal() { + bail!("{q} No terminal to ask on: pass --yes to confirm."); + } + if !confirmed(&ui::ask(&format!("{q} [y/N] "))?) { + bail!("Not scaled."); + } + send(true).await? + } + r => r?, + }; + ui::ok(&format!("{name} now runs {}", replicas_count(n.into()))); + // Replicas that don't fit on the servers wait for room. + if let Some(w) = done["warning"].as_str() { + println!("{}", ui::yellow(w)); + } + // pyo.jsonc's replicas, or the next pyo deploy scales it back. + if let Some((path, f)) = &t.file + && f.service.as_deref() == Some(t.id.as_str()) + && let Some(old) = f.deploy.replicas.filter(|&r| r != i64::from(n)) + { + match config::write_replicas(path, n) { + Ok(()) => println!("{}", ui::dim(&format!("Set replicas to {n} in pyo.jsonc"))), + Err(_) => println!( + "{}", + ui::yellow(&format!( + "pyo.jsonc still says {old} replicas. Set it to {n}, or the next pyo deploy scales back to {old}." + )) + ), + } + } + Ok(()) +} + pub async fn open(api: &Api, service: Option<&str>) -> Result<()> { let t = target(api, service).await?; let url = t.state.service_url(&api.base, t.service()); @@ -1014,6 +1745,38 @@ pub async fn open(api: &Api, service: Option<&str>) -> Result<()> { mod tests { use super::*; + #[test] + fn followed_lines_print_once_in_the_order_they_come() { + let line = |at: i64, source: &str, message: &str| LogLine { + at, + level: "info".into(), + source: source.into(), + message: message.into(), + }; + let mut p = LogPrinter { + name: "web".into(), + replica: None, + last: 0, + floor: 0, + seen: HashSet::new(), + }; + // Two replicas stream at once: an older line after a newer one still prints. + assert!(p.take(&line(20, "web-a", "x"))); + assert!(p.take(&line(10, "web-b", "y"))); + assert!(p.take(&line(20, "web-b", "z"))); + // The next follow goes on from the newest line: those at it come again. + p.floor = p.last; + assert!(!p.take(&line(10, "web-b", "y"))); + assert!(!p.take(&line(20, "web-a", "x"))); + assert!(!p.take(&line(20, "web-b", "z"))); + assert!(p.take(&line(20, "web-a", "new at the same time"))); + assert!(p.take(&line(21, "web-a", "w"))); + // --replica a + p.replica = Some("a".into()); + assert!(!p.take(&line(30, "web-b", "v"))); + assert!(p.take(&line(30, "web-a", "v"))); + } + fn service() -> Value { json!({ "source": { "type": "git", "branch": "main", "dockerfilePath": "Dockerfile", "buildContext": "." }, @@ -1029,6 +1792,70 @@ mod tests { config::parse(text).unwrap() } + #[test] + fn placement_in_words() { + assert_eq!(placement_words(&json!({})), "any server"); + assert_eq!( + placement_words(&json!({ "placement": { "servers": ["server-1"], "tags": ["gpu"] } })), + "server-1 and servers tagged gpu" + ); + // Saved before placement: its tags read as tags picked. + assert_eq!( + placement_words(&json!({ "serverTags": ["gpu", "eu"] })), + "servers tagged gpu and servers tagged eu" + ); + assert_eq!( + placement_words(&json!({ "placement": { "servers": ["a", "b"], "tags": [] } })), + "a and b" + ); + } + + #[test] + fn scale_in_words() { + let mut s = json!({ "name": "api", "replicas": 3 }); + assert_eq!(scale_words(&s), "api isn't deployed yet"); + s["currentDeploymentId"] = json!("dpl_a"); + // Before the servers report: the setting only. + assert_eq!(scale_words(&s), "api runs 3 replicas"); + s["runtime"] = json!({ "replicas": [ + { "name": "api-a", "server": "dev-2", "ready": true }, + { "name": "api-b", "server": "dev-1", "ready": true }, + { "name": "api-c", "server": "dev-2", "ready": false }, + ] }); + assert_eq!( + scale_words(&s), + "api runs 3 replicas: 1 on dev-1 and 2 on dev-2" + ); + s["runtime"]["replicas"][2] = + json!({ "name": "api-c", "server": "", "ready": false, "waiting": true }); + assert_eq!( + scale_words(&s), + "api runs 3 replicas: 1 on dev-1, 1 on dev-2 and 1 waiting for room" + ); + s["autoscale"] = json!({ "min": 2, "max": 5 }); + assert!( + scale_words(&s).starts_with("api autoscales from 2 to 5 replicas: "), + "{}", + scale_words(&s) + ); + s["status"] = json!("stopped"); + assert_eq!(scale_words(&s), "api is stopped"); + assert_eq!( + scale_words(&json!({ "name": "api", "replicas": 1, "currentDeploymentId": "dpl_a" })), + "api runs 1 replica" + ); + } + + #[test] + fn says_why_a_large_change_asks() { + assert_eq!( + confirm_reason("Scale to 40 replicas? That's more than 10 times the 2 it has now."), + Some("That's more than 10 times the 2 it has now.") + ); + assert_eq!(confirm_reason("Scale to 40 replicas?"), None); + assert_eq!(confirm_reason("Scale to 40 replicas? "), None); + } + #[test] fn stages_in_words() { assert_eq!(stage_label("waiting_ready"), "Running health check"); diff --git a/crates/pyo-cli/src/ui.rs b/crates/pyo-cli/src/ui.rs index 890a1499..263c895b 100644 --- a/crates/pyo-cli/src/ui.rs +++ b/crates/pyo-cli/src/ui.rs @@ -37,6 +37,16 @@ pub fn yellow(s: &str) -> String { paint("33", s) } +/// A replica's name in front of its log lines: a color of its own, so +/// lines of different replicas tell apart. +pub fn replica(name: &str) -> String { + const CODES: [&str; 5] = ["36", "35", "34", "33", "32"]; + let h = name + .bytes() + .fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(b as usize)); + paint(CODES[h % CODES.len()], name) +} + /// A log line's text. On a terminal: its own ANSI colors (nothing else /// that moves the cursor or retitles the window), else tinted by its /// level. Otherwise plain text. diff --git a/crates/pyo-envd/Cargo.toml b/crates/pyo-envd/Cargo.toml index 306c88a2..09353f11 100644 --- a/crates/pyo-envd/Cargo.toml +++ b/crates/pyo-envd/Cargo.toml @@ -12,5 +12,5 @@ publish.workspace = true [dependencies] libc = "0.2.191" -pyo-proto = { version = "0.4.5", path = "../pyo-proto" } +pyo-proto = { version = "0.5.0", path = "../pyo-proto" } serde_json.workspace = true diff --git a/crates/pyo-flows/Cargo.toml b/crates/pyo-flows/Cargo.toml index ab8eac56..b0c52c97 100644 --- a/crates/pyo-flows/Cargo.toml +++ b/crates/pyo-flows/Cargo.toml @@ -8,7 +8,7 @@ publish.workspace = true [dependencies] anyhow = "1.0.104" libc = "0.2.191" -pyo-proto = { version = "0.4.5", path = "../pyo-proto" } +pyo-proto = { version = "0.5.0", path = "../pyo-proto" } reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls"] } serde_json = "1.0.154" tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "time", "sync"] } diff --git a/crates/pyo-proto/Cargo.toml b/crates/pyo-proto/Cargo.toml index 2d65ceae..46dc93a1 100644 --- a/crates/pyo-proto/Cargo.toml +++ b/crates/pyo-proto/Cargo.toml @@ -12,8 +12,13 @@ ring = { version = "0.17.14", optional = true } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" serde_norway = "0.9.42" +jiff = "0.2.38" sha2 = "0.11.1" utoipa = { version = "5.5.0", optional = true } +# The agent CA's certificates (agent_ca.rs). +rcgen = { version = "0.14", default-features = false, features = ["pem", "x509-parser", "ring"], optional = true } +time = { version = "0.3", optional = true } +x509-parser = { version = "0.18", optional = true } [dev-dependencies] # The admission policy's patterns (CEL `matches` is RE2, which this follows). @@ -24,3 +29,6 @@ regex = "1.13.1" openapi = ["dep:utoipa"] # Signing and checking sandbox tokens (pyo-api and pyo-sandbox). sandbox-token = ["dep:ring", "dep:base64"] +command-signing = ["dep:ring", "dep:base64"] +# Issuing the agent CA's certificates (pyo-api, and Pyo Cloud's signer). +agent-ca = ["dep:rcgen", "dep:time", "dep:x509-parser", "dep:ring"] diff --git a/crates/pyo-proto/src/agent_ca.rs b/crates/pyo-proto/src/agent_ca.rs new file mode 100644 index 00000000..b412f521 --- /dev/null +++ b/crates/pyo-proto/src/agent_ca.rs @@ -0,0 +1,171 @@ +//! The agent CA's certificates (pyo-api's mTLS agent endpoint): what they +//! hold, whatever holds the CA's key. Pyo's own CA keeps a key file; +//! Pyo Cloud's signer keeps the key in a KMS. Both issue through here, so +//! an agent's certificate looks the same either way. +//! +//! - The CA: "Pyo agent CA", may sign certificates but not other CAs, ten +//! years. +//! - An agent's client certificate: its cluster as a URI name +//! (`pyo://team//cluster/`), client authentication only, +//! [`CERT_HOURS`] long, a random serial. +//! - The endpoint's server certificate: its DNS names or IPs, server +//! authentication only, a year. +//! +//! The key behind an [`Issuer`] is any [`SigningKey`]: rcgen's own, or one +//! that asks a KMS. + +pub use rcgen::{Issuer, PublicKeyData, SigningKey, SubjectPublicKeyInfo}; +use rcgen::{ + CertificateParams, CertificateSigningRequestParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa, + KeyUsagePurpose, SanType, SerialNumber, +}; + +/// A client certificate's lifetime. +pub const CERT_HOURS: i64 = 24; + +/// A certificate the CA issued. +#[derive(Debug, Clone)] +pub struct Issued { + /// Hex, without leading zero bytes (as agent_tls reads it back). + pub serial: String, + pub pem: String, + /// When it expires, ms since the epoch. + pub not_after_ms: i64, +} + +fn err(e: impl std::fmt::Display) -> String { + e.to_string() +} + +/// The CA's own certificate (PEM), self-signed by its key. +pub fn ca_cert(key: &impl SigningKey) -> Result { + let mut p = CertificateParams::new(Vec::::new()).map_err(err)?; + let mut dn = DistinguishedName::new(); + dn.push(DnType::CommonName, "Pyo agent CA"); + p.distinguished_name = dn; + p.is_ca = IsCa::Ca(rcgen::BasicConstraints::Constrained(0)); + p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + let now = time::OffsetDateTime::now_utc(); + p.not_before = now - time::Duration::hours(1); + p.not_after = now + time::Duration::days(3650); + Ok(p.self_signed(key).map_err(err)?.pem()) +} + +/// The issuer for the CA certificate `ca_pem`, signing with `key`. +pub fn issuer(ca_pem: &str, key: S) -> Result, String> { + Issuer::from_ca_cert_pem(ca_pem, key).map_err(err) +} + +/// The public key (SubjectPublicKeyInfo, DER) of a certificate (PEM). +pub fn cert_public_key(pem: &str) -> Result, String> { + let der = cert_der(pem)?; + let (_, cert) = x509_parser::parse_x509_certificate(&der).map_err(err)?; + Ok(cert.public_key().raw.to_vec()) +} + +/// A certificate's DER from its PEM. +pub fn cert_der(pem: &str) -> Result, String> { + let (_, p) = x509_parser::pem::parse_x509_pem(pem.as_bytes()).map_err(err)?; + if p.label != "CERTIFICATE" { + return Err("not a certificate".into()); + } + Ok(p.contents) +} + +/// A team or cluster id as certificates carry them. +fn plain_id(s: &str) -> bool { + (1..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} + +fn random_serial() -> Result, String> { + let mut serial = [0u8; 16]; + ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut serial).map_err(|_| "no randomness".to_owned())?; + // Positive, as X.509 wants. + serial[0] &= 0x7f; + Ok(serial.to_vec()) +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +/// A client certificate for a cluster's agent, from its CSR (the agent's +/// own key; the CSR's own names are ignored). +pub fn issue_client(issuer: &Issuer<'_, impl SigningKey>, csr_pem: &str, team: &str, cluster: &str) -> Result { + if !plain_id(team) || !plain_id(cluster) { + return Err("a team and cluster id are letters, digits, _ and -".into()); + } + let mut csr = CertificateSigningRequestParams::from_pem(csr_pem).map_err(err)?; + let mut p = CertificateParams::new(Vec::::new()).map_err(err)?; + p.subject_alt_names = vec![SanType::URI(format!("pyo://team/{team}/cluster/{cluster}").try_into().map_err(err)?)]; + let mut dn = DistinguishedName::new(); + dn.push(DnType::CommonName, cluster); + p.distinguished_name = dn; + let now = time::OffsetDateTime::now_utc(); + p.not_before = now - time::Duration::minutes(5); + let not_after = now + time::Duration::hours(CERT_HOURS); + p.not_after = not_after; + let serial = random_serial()?; + let serial_hex = hex(&serial).trim_start_matches("00").to_owned(); + p.serial_number = Some(SerialNumber::from(serial)); + p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; + csr.params = p; + let cert = csr.signed_by(issuer).map_err(err)?; + Ok(Issued { serial: serial_hex, pem: cert.pem(), not_after_ms: (not_after.unix_timestamp_nanos() / 1_000_000) as i64 }) +} + +/// The agent endpoint's own certificate for `names` (DNS names or IPs), +/// from its CSR. +pub fn issue_server(issuer: &Issuer<'_, impl SigningKey>, csr_pem: &str, names: &[String]) -> Result { + if names.is_empty() { + return Err("no names".into()); + } + let mut csr = CertificateSigningRequestParams::from_pem(csr_pem).map_err(err)?; + let mut p = CertificateParams::new(Vec::::new()).map_err(err)?; + for n in names { + p.subject_alt_names.push(match n.parse::() { + Ok(ip) => SanType::IpAddress(ip), + Err(_) => SanType::DnsName(n.as_str().try_into().map_err(err)?), + }); + } + let mut dn = DistinguishedName::new(); + dn.push(DnType::CommonName, names[0].as_str()); + p.distinguished_name = dn; + let now = time::OffsetDateTime::now_utc(); + p.not_before = now - time::Duration::hours(1); + p.not_after = now + time::Duration::days(365); + p.serial_number = Some(SerialNumber::from(random_serial()?)); + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + csr.params = p; + Ok(csr.signed_by(issuer).map_err(err)?.pem()) +} + +/// A CSR (PEM) for `key`, for [`issue_client`] or [`issue_server`]. +pub fn csr(key: &rcgen::KeyPair) -> Result { + CertificateParams::new(Vec::::new()).map_err(err)?.serialize_request(key).map_err(err)?.pem().map_err(err) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn certificates_chain_to_the_ca_and_name_their_cluster() { + let ca_key = rcgen::KeyPair::generate().unwrap(); + let ca = ca_cert(&ca_key).unwrap(); + assert_eq!(cert_public_key(&ca).unwrap(), ca_key.subject_public_key_info()); + let iss = issuer(&ca, &ca_key).unwrap(); + let agent = rcgen::KeyPair::generate().unwrap(); + let c = issue_client(&iss, &csr(&agent).unwrap(), "team_a", "cl_1").unwrap(); + let der = cert_der(&c.pem).unwrap(); + let (_, x) = x509_parser::parse_x509_certificate(&der).unwrap(); + assert_eq!(hex(x.raw_serial()).trim_start_matches("00"), c.serial); + assert!(format!("{:?}", x.subject_alternative_name()).contains("pyo://team/team_a/cluster/cl_1")); + assert_eq!(x.public_key().raw, agent.subject_public_key_info()); + // Ids that would bend the URI are refused. + assert!(issue_client(&iss, &csr(&agent).unwrap(), "team_a", "cl_1/cluster/cl_2").is_err()); + assert!(issue_server(&iss, &csr(&agent).unwrap(), &["agent.pyo.dev".into(), "10.0.0.1".into()]).is_ok()); + assert!(issue_server(&iss, &csr(&agent).unwrap(), &[]).is_err()); + } +} diff --git a/crates/pyo-proto/src/agentauth.rs b/crates/pyo-proto/src/agentauth.rs new file mode 100644 index 00000000..c34e34c0 --- /dev/null +++ b/crates/pyo-proto/src/agentauth.rs @@ -0,0 +1,212 @@ +//! Signed agent requests: who an agent is, carried in each request, so it +//! survives a proxy that ends TLS (Cloudflare in front of agent.pyo.dev). +//! +//! The agent makes an Ed25519 key in its cluster at enrollment and sends +//! Pyo only the public half, for a key id. Every request then carries: +//! +//! ```text +//! pyo-agent-key: +//! pyo-agent-signature: t=,n=,s= +//! ``` +//! +//! over `pyo-agent-req1`, the key id, the method, the path with its query, +//! the time, the nonce and the SHA-256 of the body, one per line. Pyo checks +//! it against the key it registered, refuses a time more than +//! [`MAX_SKEW_SECS`] off and a nonce it has seen, and takes the cluster from +//! the key: never from anything a proxy could add. +//! +//! The cluster's other components sign the same way with keys of their +//! own (Pyo's builders, pyo-static), which the agent makes in the cluster +//! and registers. A body too large to hold (a file a builder uploads) is +//! signed by the hash it declares in [`BODY_SHA256_HEADER`]: Pyo checks the +//! signature against that, and the body against it as it streams. + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; +use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey}; +use sha2::{Digest, Sha256}; + +pub const KEY_HEADER: &str = "pyo-agent-key"; +pub const SIGNATURE_HEADER: &str = "pyo-agent-signature"; +/// The hex SHA-256 of a body signed by its hash ([`RequestKey::sign_hashed`]). +pub const BODY_SHA256_HEADER: &str = "x-pyo-sha256"; +/// How far a request's time may be from Pyo's clock. +pub const MAX_SKEW_SECS: i64 = 60; +const PREFIX: &str = "pyo-agent-req1"; + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +/// What gets signed. +pub fn message(key_id: &str, method: &str, path: &str, t: i64, nonce: &str, body: &[u8]) -> Vec { + message_hashed(key_id, method, path, t, nonce, &body_sha256(body)) +} + +/// What gets signed, given the body's hex SHA-256. +pub fn message_hashed(key_id: &str, method: &str, path: &str, t: i64, nonce: &str, body_sha256: &str) -> Vec { + format!( + "{PREFIX}\n{key_id}\n{}\n{path}\n{t}\n{nonce}\n{}", + method.to_ascii_uppercase(), + body_sha256.to_ascii_lowercase() + ) + .into_bytes() +} + +/// A body's hex SHA-256. +pub fn body_sha256(body: &[u8]) -> String { + hex(&Sha256::digest(body)) +} + +/// An agent's request key. +pub struct RequestKey { + key: Ed25519KeyPair, +} + +impl RequestKey { + pub fn generate_pkcs8() -> Result, String> { + let rng = ring::rand::SystemRandom::new(); + Ed25519KeyPair::generate_pkcs8(&rng) + .map(|d| d.as_ref().to_vec()) + .map_err(|e| format!("couldn't make a key: {e}")) + } + + pub fn from_pkcs8(pkcs8: &[u8]) -> Result { + Ed25519KeyPair::from_pkcs8(pkcs8) + .map(|key| Self { key }) + .map_err(|e| format!("not an Ed25519 key: {e}")) + } + + /// The public key, base64url: what enrollment sends. + pub fn public_key(&self) -> String { + B64.encode(self.key.public_key().as_ref()) + } + + /// The two headers for a request, signed at `t` (unix seconds). + pub fn sign(&self, key_id: &str, method: &str, path: &str, body: &[u8], t: i64) -> [(&'static str, String); 2] { + self.sign_hashed(key_id, method, path, &body_sha256(body), t) + } + + /// The same for a body given by its hex SHA-256 (one that's streamed: + /// send that hash in [`BODY_SHA256_HEADER`] too). + pub fn sign_hashed(&self, key_id: &str, method: &str, path: &str, body_sha256: &str, t: i64) -> [(&'static str, String); 2] { + let mut n = [0u8; 16]; + let _ = ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut n); + let nonce = B64.encode(n); + let sig = self.key.sign(&message_hashed(key_id, method, path, t, &nonce, body_sha256)); + [ + (KEY_HEADER, key_id.to_owned()), + (SIGNATURE_HEADER, format!("t={t},n={nonce},s={}", B64.encode(sig.as_ref()))), + ] + } +} + +/// A signature header's parts: time, nonce and signature. +pub fn parse(header: &str) -> Option<(i64, String, Vec)> { + let (mut t, mut n, mut s) = (None, None, None); + for part in header.split(',') { + match part.trim().split_once('=')? { + ("t", v) => t = v.parse().ok(), + ("n", v) if (8..=64).contains(&v.len()) => n = Some(v.to_owned()), + ("s", v) => s = B64.decode(v).ok(), + _ => {} + } + } + Some((t?, n?, s?)) +} + +/// Why a request's signature doesn't hold. +#[derive(Debug, Clone, PartialEq)] +pub enum Bad { + Malformed, + Stale, + Signature, +} + +impl std::fmt::Display for Bad { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Bad::Malformed => "The request's signature can't be read.", + Bad::Stale => "The request's time is too far from Pyo's clock.", + Bad::Signature => "The request's signature doesn't match its key.", + }) + } +} + +/// Checks a request against the registered public key (base64url). On +/// success, its nonce, which the caller must not have seen before. +pub fn verify( + public_key: &str, + key_id: &str, + method: &str, + path: &str, + body: &[u8], + header: &str, + now: i64, +) -> Result { + verify_hashed(public_key, key_id, method, path, &body_sha256(body), header, now) +} + +/// [`verify`], given the body's hex SHA-256 (the caller then checks the +/// body against it). +pub fn verify_hashed( + public_key: &str, + key_id: &str, + method: &str, + path: &str, + body_sha256: &str, + header: &str, + now: i64, +) -> Result { + let (t, nonce, sig) = parse(header).ok_or(Bad::Malformed)?; + if (now - t).abs() > MAX_SKEW_SECS { + return Err(Bad::Stale); + } + let key = B64.decode(public_key).map_err(|_| Bad::Signature)?; + UnparsedPublicKey::new(&ED25519, key) + .verify(&message_hashed(key_id, method, path, t, &nonce, body_sha256), &sig) + .map_err(|_| Bad::Signature)?; + Ok(nonce) +} + +/// A public key as enrollment sends it: 32 bytes, base64url. +pub fn valid_public_key(k: &str) -> bool { + B64.decode(k.trim()).is_ok_and(|b| b.len() == 32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signed_requests_check_out_and_nothing_else_does() { + let k = RequestKey::from_pkcs8(&RequestKey::generate_pkcs8().unwrap()).unwrap(); + let pk = k.public_key(); + let now = 1_800_000_000; + let [_, (_, sig)] = k.sign("key_1", "post", "/api/agent/v1/heartbeat", b"{}", now); + assert!(verify(&pk, "key_1", "POST", "/api/agent/v1/heartbeat", b"{}", &sig, now + 30).is_ok()); + assert_eq!(verify(&pk, "key_1", "POST", "/api/agent/v1/heartbeat", b"{}", &sig, now + 61), Err(Bad::Stale)); + assert_eq!(verify(&pk, "key_1", "POST", "/api/agent/v1/heartbeat", b"{ }", &sig, now), Err(Bad::Signature)); + assert_eq!(verify(&pk, "key_1", "POST", "/api/agent/v1/commands", b"{}", &sig, now), Err(Bad::Signature)); + assert_eq!(verify(&pk, "key_2", "POST", "/api/agent/v1/heartbeat", b"{}", &sig, now), Err(Bad::Signature)); + assert_eq!(verify(&pk, "key_1", "GET", "/api/agent/v1/heartbeat", b"{}", &sig, now), Err(Bad::Signature)); + let other = RequestKey::from_pkcs8(&RequestKey::generate_pkcs8().unwrap()).unwrap(); + assert_eq!(verify(&other.public_key(), "key_1", "POST", "/api/agent/v1/heartbeat", b"{}", &sig, now), Err(Bad::Signature)); + assert_eq!(verify(&pk, "key_1", "POST", "/x", b"", "t=1", now), Err(Bad::Malformed)); + assert!(valid_public_key(&pk)); + } + + #[test] + fn a_streamed_body_is_signed_by_its_hash() { + let k = RequestKey::from_pkcs8(&RequestKey::generate_pkcs8().unwrap()).unwrap(); + let pk = k.public_key(); + let now = 1_800_000_000; + let file = b"

hi

"; + let path = "/api/builder/v1/jobs/j1/site/files/index.html"; + let [_, (_, sig)] = k.sign_hashed("key_1", "PUT", path, &body_sha256(file), now); + assert!(verify_hashed(&pk, "key_1", "PUT", path, &body_sha256(file), &sig, now).is_ok()); + // The same as signing the body itself. + assert!(verify(&pk, "key_1", "PUT", path, file, &sig, now).is_ok()); + assert_eq!(verify_hashed(&pk, "key_1", "PUT", path, &body_sha256(b"other"), &sig, now), Err(Bad::Signature)); + } +} diff --git a/crates/pyo-proto/src/lib.rs b/crates/pyo-proto/src/lib.rs index 3eb3c97b..9ce6ca5b 100644 --- a/crates/pyo-proto/src/lib.rs +++ b/crates/pyo-proto/src/lib.rs @@ -7,6 +7,8 @@ use serde::{Deserialize, Serialize}; +#[cfg(feature = "agent-ca")] +pub mod agent_ca; pub mod ansi; pub mod bundles; pub mod database_names; @@ -15,9 +17,16 @@ pub mod firewall; pub mod flows; pub mod memory; pub mod rbac; +pub mod registry_door; pub mod sandbox; +#[cfg(feature = "command-signing")] +pub mod agentauth; +#[cfg(feature = "command-signing")] +pub mod signing; pub mod site; pub mod system; +pub mod tailscale; +pub mod traffic; /// Bumped on breaking changes; the API rejects agents it doesn't speak. pub const PROTOCOL_VERSION: u32 = 1; @@ -29,6 +38,48 @@ pub const AGENT_VERSION_HEADER: &str = "x-pyo-agent-version"; /// rollouts the previous process was watching are handed out again. pub const AGENT_INSTANCE_HEADER: &str = "x-pyo-agent-instance"; +/// A random value the agent sends with each request whose answer it acts +/// on (the heartbeat, a certificate, a registry login). A Pyo with a +/// signer signs the answer bound to it ([`SignedReplyWire`]), so an answer +/// can't be replayed for another request. +pub const REPLY_NONCE_HEADER: &str = "x-pyo-reply-nonce"; + +/// Whether a reply nonce looks like one an agent makes: 8 to 64 base64url +/// characters. +pub fn valid_reply_nonce(n: &str) -> bool { + (8..=64).contains(&n.len()) && n.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// An answer to the agent with the signer's signature (pyo-proto +/// `signing`, `pyoreply1`), beside the plain fields: `reply` is the exact +/// JSON that was signed. An agent given `PYO_COMMAND_KEY` acts only on +/// `reply`, and only once its signature checks out. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SignedReplyWire { + pub claims: String, + pub sig: String, + pub kid: String, + pub reply: String, + /// When a session key signed it: the trusted key's statement that the + /// session key may (`signing`, `pyodel1`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub delegation: Option, +} + +/// A trusted key's statement that a session key may sign for a while +/// (pyo-proto `signing`, `pyodel1`). Pyo Cloud's signer keeps its key in a +/// KMS and signs replies with a session key it holds only in memory, so +/// the KMS signs a few times an hour instead of on every heartbeat. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DelegationWire { + pub claims: String, + pub sig: String, + /// The trusted key that signed it. + pub kid: String, +} + // ── Heartbeat: what the agent sees ───────────────────────────────────────── #[derive(Debug, Clone, Serialize, Deserialize, Default)] @@ -62,6 +113,11 @@ pub struct Heartbeat { /// (`UpgradePyo`, `UpdateAgent`); 0 from agents older than that. #[serde(default)] pub updates: u32, + /// The agent gives Pyo's builders and pyo-static keys of their own + /// (`/component-keys`), and relays Vector's data: their bearer tokens + /// can go. False from older agents. + #[serde(default)] + pub component_keys: bool, /// What the agent may do in this cluster, and the customer's switches. #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option, @@ -872,6 +928,25 @@ pub struct VolumeReport { pub struct CommandEnvelope { pub id: String, pub command: Command, + /// The signer's signature over this command, when the API has a signer + /// (Pyo Cloud). An agent given `PYO_COMMAND_KEY` runs only signed + /// commands, and runs the signed JSON, not `command`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub signed: Option, +} + +/// [`signing::SignedCommand`] on the wire (pyo-proto's signing code is +/// behind the `command-signing` feature; the shape isn't). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SignedCommandWire { + pub claims: String, + pub sig: String, + pub kid: String, + pub command: String, + /// When a session key signed it ([`DelegationWire`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub delegation: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -888,6 +963,18 @@ pub enum Command { service: ServiceRef, replicas: i32, }, + /// Change where a service's pods may run, in place: its pods move over + /// one at a time with the same image (a rollout, not a deploy). Its + /// cron jobs follow. + Place { + service: ServiceRef, + #[serde(default)] + server_names: Vec, + #[serde(default)] + server_tags: Vec, + #[serde(default)] + cron_jobs: Vec, + }, /// Make a service's cron jobs match this list, built from its live pods. SyncCronJobs { service: ServiceRef, @@ -919,6 +1006,28 @@ pub enum Command { FetchLogs { service: ServiceRef, tail_lines: i64, + /// Only lines from the last this many seconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + since_seconds: Option, + /// Only this replica (pod), by name. + #[serde(default, skip_serializing_if = "String::is_empty")] + replica: String, + }, + /// Follow the service's pods' output: the agent dials back to + /// `/api/agent/v1/log-follows/` over a WebSocket, sends the + /// recent lines as [`FetchLogs`](Command::FetchLogs) reads them, then + /// each new line as it's printed (see [`LogFrame`]). It stops when Pyo + /// closes the socket, or after [`LOG_FOLLOW_SECS`]. + FollowLogs { + session_id: String, + service: ServiceRef, + tail_lines: i64, + /// Only lines from the last this many seconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + since_seconds: Option, + /// Only this replica (pod), by name. + #[serde(default, skip_serializing_if = "String::is_empty")] + replica: String, }, /// Stop watching a rollout and report it cancelled. Cancel { @@ -984,6 +1093,14 @@ pub enum Command { /// One of [`TERMINAL_SHELLS`]. #[serde(default)] shell: String, + /// A command to run instead of a shell (`pyo exec -- cmd args`), + /// started as it is, without a shell. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + command: Vec, + /// With a terminal (keys, colors, one output stream). Without one, + /// output frames carry their stream ([`TerminalFrame`]). + #[serde(default = "yes")] + tty: bool, }, /// Only to the agent on the cluster Pyo runs on: update Pyo to a /// release. The agent runs the new release's upgrader as a Job in @@ -1080,11 +1197,77 @@ pub enum Command { #[serde(default)] since_seconds: Option, }, + /// Follow a database's output, as [`FollowLogs`](Command::FollowLogs) + /// follows a service's: the agent dials back to + /// `/api/agent/v1/log-follows/` and sends its pods' parts + /// ([`LogFrame::Pods`]), the recent lines and events as + /// [`FetchDatabaseLogs`](Command::FetchDatabaseLogs) reads them, then new + /// lines as they're printed and the pods and events when they change. + FollowDatabaseLogs { + session_id: String, + namespace: String, + name: String, + tail_lines: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + since_seconds: Option, + }, /// Before an import into a database: connect to the source (its /// version, extensions and whether every table can be read) and check /// the database to import into is empty, from a short Job in the /// team's databases namespace. `data` has what it found. CheckDatabaseImport(Box), + /// Kept requests, connections or WAF findings from the cluster's + /// traffic store, newest first (traffic.rs). `data` is a + /// [`traffic::TrafficAnswer`]. + QueryTraffic(Box), + /// Set the cluster's tailnet up from a pasted Tailscale API access + /// token (tailscale.rs). Without `version`: only read the tailnet and + /// say what would change (`data` is the plan). With the plan's + /// `version`: make those changes, create the cluster's OAuth client + /// and keep it in pyo-system, and delete the token (`data` is what + /// happened). Nothing secret comes back. + TailscaleSetup { + token: String, + #[serde(default)] + version: Option, + }, + /// Use this OAuth client from now on, once it signs in: pasted by hand, + /// or the one Pyo kept before clusters kept their own. `data` is a + /// [`tailscale::ClientState`]. + TailscaleClient { + client_id: String, + secret: String, + }, + /// Check the cluster's OAuth client again, scope by scope. `data` is a + /// [`tailscale::ClientState`]. + TailscaleTest {}, + /// Keep the cluster's names on its tailnet as Pyo wants them. `data` is + /// a [`tailscale::TailnetSynced`]. + TailscaleSync(Box), + /// A single-use, preauthorized auth key with tag:pyo, for an hour, for + /// a machine joining the tailnet. `data` has it as + /// [`tailscale::KEY_FIELD`]. + TailscaleKey { + description: String, + }, + /// Whether a name is free on the cluster's tailnet, Pyo's (one of + /// `marks`) or someone else's. `data` is a [`tailscale::NameCheck`]. + TailscaleCheckName { + name: String, + marks: Vec, + }, + /// Delete these names on the tailnet (only those marked with one of + /// `marks`), then forget the cluster's OAuth client. + TailscaleRemove { + names: Vec, + marks: Vec, + }, + /// Call a sandbox server's daemon on the cluster's tailnet. `data` is a + /// [`tailscale::SandboxAnswer`]. + SandboxCall(Box), + /// 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), } // ── Releases and updates ─────────────────────────────────────────────────── @@ -1391,20 +1574,54 @@ pub fn collect_images(v: &serde_json::Value, out: &mut Vec) { } /// Control messages on a terminal WebSocket, sent as text frames. Keystrokes -/// and shell output are binary frames. +/// and shell output are binary frames. Without a TTY, output frames start +/// with their stream ([`STREAM_STDOUT`] or [`STREAM_STDERR`]); input frames +/// are stdin as it is. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum TerminalFrame { /// Browser to shell: the terminal's size changed. Resize { cols: u16, rows: u16 }, + /// Client to shell: no more input (stdin is closed). + StdinEnd, /// Shell to browser: connected to this replica. Ready { pod: String }, /// Shell to browser: it couldn't start or broke, and why. Error { message: String }, - /// Shell to browser: the shell exited. - Exit, + /// Shell to browser: the shell or command exited, with its exit code + /// when known. + Exit { + #[serde(default, skip_serializing_if = "Option::is_none")] + code: Option, + }, } +/// What a log follow's WebSocket carries, as text frames, from the agent to +/// whoever follows ([`Command::FollowLogs`]). +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum LogFrame { + /// Lines, each replica's oldest first. Empty now and then while + /// nothing is printed, so idle connections stay open. + Lines { lines: Vec }, + /// It couldn't follow, and why. + Error { message: String }, + /// A database's pods, each with the labels that tell its part, by name + /// ([`Command::FollowDatabaseLogs`]): first, then when they change. + Pods { pods: serde_json::Value }, + /// The cluster's events about a database, all of them: first, then + /// when they change. + Events { events: Vec }, +} + +/// The longest a log follow lasts. Whoever follows longer opens another. +pub const LOG_FOLLOW_SECS: u64 = 3600; + +/// The first byte of an output frame without a TTY: standard output. +pub const STREAM_STDOUT: u8 = 1; +/// The first byte of an output frame without a TTY: standard error. +pub const STREAM_STDERR: u8 = 2; + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BuilderSpec { @@ -1413,6 +1630,9 @@ pub struct BuilderSpec { pub server: String, /// URL the builder dials out to. pub api_url: String, + /// Its login at Pyo's registry door (username `pyo-builder`), when it + /// pushes there; empty for a cluster's own registry. Agents that give + /// builders keys sign with those on Pyo's API; older ones send this. pub token: String, pub image: String, /// Registry the builder pushes to over plain HTTP (host:port). @@ -1483,6 +1703,21 @@ pub struct BuildJob { /// uploads it (site.rs). Off for a service set to run as a service. #[serde(default)] pub upload_site: bool, + /// A folder sent with `pyo deploy` to build instead of a Git checkout: + /// the builder fetches it from Pyo, which deletes it once it has. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_upload: Option, +} + +/// A folder uploaded to build (a gzipped tar), as a build job names it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceUpload { + pub id: String, + /// In bytes. + pub size: u64, + /// Hex SHA-256 of the archive. + pub sha256: String, } /// A step of a build. `stage` is "building" or "pushing" (or empty for logs only). @@ -1621,9 +1856,14 @@ pub struct DeploySpec { /// `topology.kubernetes.io/region` for a service pinned to a location. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub node_selector: std::collections::BTreeMap, - /// Servers picked by name: its pods run only on these. + /// Servers picked by name. With `server_tags`, its pods run only on + /// these servers and on servers with any of those tags. Both empty: + /// any server. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub server_names: Vec, + /// Tags picked: every server that has one of them, now or later. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub server_tags: Vec, /// The team's login for the image's registry, when it has one: the /// agent fetches it (never stored here) and pulls with it. #[serde(default, skip_serializing_if = "String::is_empty")] @@ -1685,6 +1925,10 @@ pub struct WafSettings { pub threshold: u32, } +fn yes() -> bool { + true +} + fn is_zero(n: &u32) -> bool { *n == 0 } @@ -2412,6 +2656,31 @@ pub struct ServerTags { /// which services placed by tag select. pub const TAG_LABEL_PREFIX: &str = "pyo/tag-"; +/// The node affinity that keeps a service's pods on the servers picked by +/// name (`kubernetes.io/hostname`) and on servers with any of the tags +/// picked: one term each, and Kubernetes takes any term. Nothing picked: +/// any server, said as a term every server matches, so that a rollout +/// always sets it and takes back what a placement change set in place. +pub fn placement_affinity(server_names: &[String], server_tags: &[String]) -> serde_json::Value { + let mut terms: Vec = vec![]; + if !server_names.is_empty() { + terms.push(serde_json::json!({ "matchExpressions": [ + { "key": "kubernetes.io/hostname", "operator": "In", "values": server_names } + ] })); + } + for t in server_tags.iter().filter_map(|t| valid_tag(t)) { + terms.push(serde_json::json!({ "matchExpressions": [ + { "key": format!("{TAG_LABEL_PREFIX}{t}"), "operator": "In", "values": ["true"] } + ] })); + } + if terms.is_empty() { + terms.push(serde_json::json!({ "matchExpressions": [ + { "key": "kubernetes.io/hostname", "operator": "Exists" } + ] })); + } + serde_json::json!({ "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": terms } } }) +} + /// A tag as people type it, if it's one: lowercase letters, digits and /// dashes, up to 32 (it ends up in a label name). pub fn valid_tag(tag: &str) -> Option { @@ -2588,6 +2857,37 @@ mod location_tests { assert!(format!("tag-{}", "x".repeat(32)).len() <= 63); } + #[test] + fn placement_is_one_affinity_term_per_pick() { + let terms = |names: &[&str], tags: &[&str]| { + let names: Vec = names.iter().map(|s| s.to_string()).collect(); + let tags: Vec = tags.iter().map(|s| s.to_string()).collect(); + placement_affinity(&names, &tags)["nodeAffinity"] + ["requiredDuringSchedulingIgnoredDuringExecution"]["nodeSelectorTerms"] + .clone() + }; + // Nothing picked: every server, still said, so a rollout sets it. + assert_eq!( + terms(&[], &[]), + serde_json::json!([{ "matchExpressions": [{ "key": "kubernetes.io/hostname", "operator": "Exists" }] }]) + ); + // Servers by name, and each tag on its own: any of them will do. + assert_eq!( + terms(&["server-1", "gpu-box"], &["gpu", "eu"]), + serde_json::json!([ + { "matchExpressions": [{ "key": "kubernetes.io/hostname", "operator": "In", "values": ["server-1", "gpu-box"] }] }, + { "matchExpressions": [{ "key": "pyo/tag-gpu", "operator": "In", "values": ["true"] }] }, + { "matchExpressions": [{ "key": "pyo/tag-eu", "operator": "In", "values": ["true"] }] }, + ]) + ); + // A tag that can't be a label is left out, not sent. + assert_eq!(terms(&[], &["a b"]).as_array().unwrap().len(), 1); + assert_eq!( + terms(&[], &["a b"])[0]["matchExpressions"][0]["operator"], + "Exists" + ); + } + #[test] fn labels() { assert_eq!( diff --git a/crates/pyo-proto/src/registry_door.rs b/crates/pyo-proto/src/registry_door.rs new file mode 100644 index 00000000..08b33890 --- /dev/null +++ b/crates/pyo-proto/src/registry_door.rs @@ -0,0 +1,227 @@ +//! A registry's door: who may push and pull what, by a team's registry +//! token. Pyo's own door (pyo-api registrydoor.rs) and a cluster's own +//! registry's door (pyo-agent registrydoor.rs, Pyo Cloud's clusters, which +//! keep the images they build) go by the same rules: a team's token pushes +//! and pulls `//` of its own team only, and a pull +//! token only pulls. +//! +//! A cluster never sees a token: Pyo sends it the tokens' SHA-256 (hex) +//! with what each may do ([`RegistryTokens`], a signed command), and the +//! cluster's door hashes what a client logs in with. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// The cluster's team's registry tokens, as its door checks them. All of +/// them each time: the door keeps exactly these. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegistryTokens { + /// The team's slug: its images are under it. + pub team_slug: String, + pub tokens: Vec, +} + +/// One registry token, never the token itself. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegistryToken { + /// Lowercase hex SHA-256 of the token. + pub sha256: String, + /// It may push too (else only pull). + pub push: bool, + /// Unix seconds it stops working; never when None. + #[serde(default)] + pub expires_at: Option, +} + +impl RegistryTokens { + /// The token a client logged in with, while it works (unix seconds + /// `now`). Compared in constant time. + pub fn find(&self, password: &str, now: i64) -> Option<&RegistryToken> { + let got = hex(&Sha256::digest(password.as_bytes())); + self.tokens.iter().find(|t| { + t.sha256.len() == got.len() + && t.sha256 + .bytes() + .zip(got.bytes()) + .fold(0u8, |a, (x, y)| a | (x ^ y)) + == 0 + && t.expires_at.is_none_or(|e| e > now) + }) + } +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +/// A team's own repository: "//", its three parts. +pub fn parts(name: &str) -> Option<(&str, &str, &str)> { + let mut it = name.split('/'); + let (t, p, s) = (it.next()?, it.next()?, it.next()?); + let label = |x: &str| { + !x.is_empty() + && x.len() <= 63 + && x.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + }; + (it.next().is_none() && label(t) && label(p) && label(s) && t != "pyo").then_some((t, p, s)) +} + +/// What a request asks for: the repository it names (None for /v2/ itself) +/// and whether it writes. +#[derive(Debug, PartialEq, Eq)] +pub enum Wants { + Root, + Repo { name: String, write: bool }, + Other, +} + +fn reads(method: &str) -> bool { + matches!(method, "GET" | "HEAD") +} + +pub fn wants(method: &str, path: &str) -> Wants { + let Some(rest) = path.strip_prefix("/v2/") else { + return Wants::Other; + }; + if rest.is_empty() { + return Wants::Root; + } + let name = ["/manifests/", "/blobs/", "/tags/list"] + .iter() + .filter_map(|m| rest.find(m)) + .min() + .map(|i| &rest[..i]); + match name { + Some(n) if !n.is_empty() => Wants::Repo { + name: n.to_owned(), + write: !reads(method), + }, + _ => Wants::Other, + } +} + +/// Whether a token for `slug` (with `push` or only pull) may do this, by +/// the path alone. +pub fn allowed(slug: &str, push: bool, method: &str, name: &str) -> bool { + let ours = parts(name).is_some_and(|(t, _, _)| t == slug); + match method { + "GET" | "HEAD" => ours, + // Pushing: uploads, then the manifest. Deleting isn't offered. + "POST" | "PUT" | "PATCH" => ours && push, + _ => false, + } +} + +/// A query without a cross-repository mount from outside the team (the +/// registry then takes a plain upload instead). +pub fn scoped_query(query: &str, slug: &str) -> String { + let prefix = format!("{slug}/"); + // (Another repository of its own team is fine to mount from.) + let pairs: Vec<(&str, &str)> = query + .split('&') + .filter(|p| !p.is_empty()) + .map(|p| p.split_once('=').unwrap_or((p, ""))) + .collect(); + let foreign = pairs + .iter() + .any(|(k, v)| *k == "from" && !decode(v).starts_with(&prefix)); + pairs + .into_iter() + .filter(|(k, _)| !(foreign && (*k == "from" || *k == "mount"))) + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join("&") +} + +/// Percent-decoding of a query value ("+" is a space). +fn decode(v: &str) -> String { + let b = v.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + match b[i] { + b'%' if i + 2 < b.len() => match std::str::from_utf8(&b[i + 1..i + 3]) + .ok() + .and_then(|h| u8::from_str_radix(h, 16).ok()) + { + Some(x) => { + out.push(x); + i += 3; + continue; + } + None => out.push(b'%'), + }, + b'+' => out.push(b' '), + c => out.push(c), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_token_by_its_hash_while_it_works() { + let t = RegistryTokens { + team_slug: "acme".into(), + tokens: vec![ + RegistryToken { + sha256: hex(&Sha256::digest(b"pyo_reg_a")), + push: true, + expires_at: None, + }, + RegistryToken { + sha256: hex(&Sha256::digest(b"pyo_reg_b")), + push: false, + expires_at: Some(100), + }, + ], + }; + assert!(t.find("pyo_reg_a", 1_000).unwrap().push); + assert!(!t.find("pyo_reg_b", 99).unwrap().push); + assert!(t.find("pyo_reg_b", 100).is_none(), "expired"); + assert!(t.find("pyo_reg_c", 0).is_none()); + assert!(t.find("", 0).is_none()); + } + + #[test] + fn a_teams_own_repositories_only() { + assert_eq!(wants("GET", "/v2/"), Wants::Root); + assert_eq!( + wants("PUT", "/v2/acme/shop/api/manifests/1"), + Wants::Repo { + name: "acme/shop/api".into(), + write: true + } + ); + assert_eq!( + wants("HEAD", "/v2/acme/shop/api/blobs/sha256:x"), + Wants::Repo { + name: "acme/shop/api".into(), + write: false + } + ); + assert_eq!(wants("GET", "/v2/_catalog"), Wants::Other); + assert!(allowed("acme", true, "PUT", "acme/shop/api")); + assert!(allowed("acme", false, "GET", "acme/shop/api")); + assert!(!allowed("acme", false, "PUT", "acme/shop/api"), "pull only"); + assert!(!allowed("acme", true, "GET", "other/shop/api")); + assert!(!allowed("acme", true, "DELETE", "acme/shop/api")); + assert!(!allowed("pyo", true, "GET", "pyo/shop/api")); + assert!(parts("acme/shop").is_none() && parts("acme/shop/api/x").is_none()); + assert_eq!( + scoped_query("mount=sha256:1&from=other%2Fx%2Fy", "acme"), + "" + ); + assert_eq!( + scoped_query("mount=sha256:1&from=acme%2Fx%2Fy", "acme"), + "mount=sha256:1&from=acme%2Fx%2Fy" + ); + } +} diff --git a/crates/pyo-proto/src/signing.rs b/crates/pyo-proto/src/signing.rs new file mode 100644 index 00000000..ce0ae755 --- /dev/null +++ b/crates/pyo-proto/src/signing.rs @@ -0,0 +1,757 @@ +//! Signed commands: a command the agent runs only when a signer it trusts +//! signed it for its own cluster. +//! +//! A hosted Pyo (Pyo Cloud) keeps its signing key out of the API: a separate +//! signer signs each command, so a database write or a bug in the API alone +//! can't send work to a customer's cluster. The agent is told the signer's +//! public key at install (`PYO_COMMAND_KEY`) and refuses anything else. +//! +//! ```text +//! sig = Ed25519("pyocmd1." + base64url(claims JSON)) +//! ``` +//! +//! The claims name the command (its id and kind), the cluster it's for, a +//! sequence number that only grows per cluster, when it was signed and when +//! it expires, and the SHA-256 of the command's exact JSON. The signer never +//! sees the command itself, so the secrets in it (sealed env values opened +//! for the agent) never reach it. +//! +//! Answers the agent acts on (the heartbeat's reply: labels, taints, public +//! traffic, observability; a certificate; a registry login) are signed the +//! same way, under their own prefix so neither passes for the other: +//! +//! ```text +//! sig = Ed25519("pyoreply1." + base64url(reply claims JSON)) +//! ``` +//! +//! The reply claims name the cluster, the nonce the agent sent with its +//! request ([`crate::REPLY_NONCE_HEADER`]), when it was signed and when it +//! expires, and the SHA-256 of the reply's exact JSON. The nonce ties an +//! answer to one request: an old answer can't be played back for a new one. +//! +//! A trusted key may hand signing to a session key for a while (at most +//! [`MAX_DELEGATION_MS`]), so a key kept in a KMS signs a few times an hour +//! rather than every heartbeat's reply: +//! +//! ```text +//! sig = Ed25519("pyodel1." + base64url(delegation claims JSON)) +//! ``` +//! +//! The delegation names the session key, what it may sign ([`PURPOSE_REPLIES`], +//! [`PURPOSE_COMMANDS`]) and when. A command or reply signed by the session +//! key carries the delegation; the agent checks the delegation against its +//! trusted keys, then the signature against the session key, and takes it +//! only when it was signed and expires inside the delegation's window. +//! Kinds in [`ROOT_ONLY_KINDS`] are never taken from a session key. + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; +use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +pub const PREFIX: &str = "pyocmd1"; +/// How long a signed command may wait to be run. +pub const TTL_MS: u64 = 10 * 60 * 1000; +/// Clock difference allowed between the signer and the cluster. +pub const LEEWAY_MS: u64 = 2 * 60 * 1000; +pub const REPLY_PREFIX: &str = "pyoreply1"; +/// How long a signed reply is good for (it answers a request made now). +pub const REPLY_TTL_MS: u64 = 60 * 1000; +pub const DELEGATION_PREFIX: &str = "pyodel1"; +/// The longest a session key may sign for, from one delegation. +pub const MAX_DELEGATION_MS: u64 = 2 * 60 * 60 * 1000; +/// A session key may sign replies. +pub const PURPOSE_REPLIES: &str = "replies"; +/// A session key may sign commands (but never [`ROOT_ONLY_KINDS`]). +pub const PURPOSE_COMMANDS: &str = "commands"; +/// Command kinds an agent takes only with a trusted key's own signature: +/// an agent update names the image every customer's agent will run. +pub const ROOT_ONLY_KINDS: &[&str] = &["update_agent"]; + +/// What a trusted key signs to let a session key sign. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DelegationClaims { + pub v: u32, + /// The session key's public half, base64url. + pub key: String, + /// What it may sign ([`PURPOSE_REPLIES`], [`PURPOSE_COMMANDS`]). + pub purposes: Vec, + /// Good from, and until (ms since the epoch). What the session key + /// signs must be signed and expire inside this window. + pub nbf: u64, + pub exp: u64, + /// Grows with every delegation the signer makes (for its audit log). + pub serial: u64, +} + +impl DelegationClaims { + /// The claims as sent (base64url JSON), and the exact bytes signed. + pub fn signing_input(&self) -> (String, Vec) { + let c = B64.encode(serde_json::to_vec(self).unwrap_or_default()); + let m = format!("{DELEGATION_PREFIX}.{c}").into_bytes(); + (c, m) + } +} + +impl Claims { + /// The claims as sent (base64url JSON), and the exact bytes signed. + /// For signers whose key is elsewhere (a KMS, a session key). + pub fn signing_input(&self) -> (String, Vec) { + let c = B64.encode(serde_json::to_vec(self).unwrap_or_default()); + let m = message(&c); + (c, m) + } +} + +impl ReplyClaims { + /// The claims as sent (base64url JSON), and the exact bytes signed. + pub fn signing_input(&self) -> (String, Vec) { + let c = B64.encode(serde_json::to_vec(self).unwrap_or_default()); + let m = reply_message(&c); + (c, m) + } +} + +/// Whether `sig` is `public_key`'s Ed25519 signature over `message`. +pub fn verify_ed25519(public_key: &[u8], message: &[u8], sig: &[u8]) -> bool { + UnparsedPublicKey::new(&ED25519, public_key).verify(message, sig).is_ok() +} + +/// A public key's base64url form, as `PYO_COMMAND_KEY` and delegations hold it. +pub fn encode_key(public_key: &[u8]) -> String { + B64.encode(public_key) +} + +/// What the signer signs for a reply. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReplyClaims { + pub v: u32, + /// The cluster it's for. + pub cluster: String, + /// The nonce of the request it answers. + pub nonce: String, + /// Signed at, and expires at (ms since the epoch). + pub iat: u64, + pub exp: u64, + /// Hex SHA-256 of [`crate::SignedReplyWire::reply`]. + pub sha256: String, +} + +/// What the signer signs. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Claims { + pub v: u32, + /// The command's id (pyo.commands). + pub id: String, + /// The cluster it's for. + pub cluster: String, + /// Grows with every command signed for this cluster. + pub seq: u64, + /// Signed at, and expires at (ms since the epoch). + pub iat: u64, + pub exp: u64, + /// The command's `kind`, so the signer can refuse kinds by policy. + pub kind: String, + /// Hex SHA-256 of [`SignedCommand::command`]. + pub sha256: String, +} + +/// A command with its signature, as the API hands it to the agent. +pub use crate::SignedCommandWire as SignedCommand; + +/// A short id for a public key: hex of the first 8 bytes of its SHA-256. +pub fn key_id(public_key: &[u8]) -> String { + hex8(&Sha256::digest(public_key)) +} + +fn hex8(b: &[u8]) -> String { + b.iter().take(8).map(|x| format!("{x:02x}")).collect() +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|x| format!("{x:02x}")).collect() +} + +fn message(claims_b64: &str) -> Vec { + format!("{PREFIX}.{claims_b64}").into_bytes() +} + +/// A new reply nonce: 16 random bytes, base64url. +pub fn new_nonce() -> String { + let mut n = [0u8; 16]; + let _ = ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut n); + B64.encode(n) +} + +fn reply_message(claims_b64: &str) -> Vec { + format!("{REPLY_PREFIX}.{claims_b64}").into_bytes() +} + +/// A signing key (the signer's), from its PKCS#8 document. +pub struct Signer { + key: Ed25519KeyPair, + kid: String, +} + +impl Signer { + pub fn from_pkcs8(pkcs8: &[u8]) -> Result { + let key = Ed25519KeyPair::from_pkcs8(pkcs8).map_err(|e| format!("not an Ed25519 key: {e}"))?; + let kid = key_id(key.public_key().as_ref()); + Ok(Self { key, kid }) + } + + /// A new key's PKCS#8 document. + pub fn generate_pkcs8() -> Result, String> { + let rng = ring::rand::SystemRandom::new(); + Ed25519KeyPair::generate_pkcs8(&rng) + .map(|d| d.as_ref().to_vec()) + .map_err(|e| format!("couldn't make a key: {e}")) + } + + /// The public key, base64url (what `PYO_COMMAND_KEY` holds). + pub fn public_key(&self) -> String { + B64.encode(self.key.public_key().as_ref()) + } + + pub fn kid(&self) -> &str { + &self.kid + } + + /// The public key's raw bytes. + pub fn public_key_bytes(&self) -> &[u8] { + self.key.public_key().as_ref() + } + + /// Signs claims for a command whose JSON hashes to `claims.sha256`. + /// The command itself is attached by the caller ([`SignedCommand::command`]). + pub fn sign(&self, claims: &Claims) -> (String, String) { + let (c, m) = claims.signing_input(); + (c, B64.encode(self.key.sign(&m).as_ref())) + } + + /// Signs a reply's claims (its JSON hashes to `claims.sha256`). + pub fn sign_reply(&self, claims: &ReplyClaims) -> (String, String) { + let (c, m) = claims.signing_input(); + (c, B64.encode(self.key.sign(&m).as_ref())) + } + + /// Lets another key sign for a while ([`DelegationClaims`]). + pub fn delegate(&self, claims: &DelegationClaims) -> crate::DelegationWire { + let (c, m) = claims.signing_input(); + crate::DelegationWire { claims: c, sig: B64.encode(self.key.sign(&m).as_ref()), kid: self.kid.clone() } + } + + /// The raw Ed25519 signature over `message`. + pub fn sign_raw(&self, message: &[u8]) -> Vec { + self.key.sign(message).as_ref().to_vec() + } +} + +/// Why a command was refused. +#[derive(Debug, Clone, PartialEq)] +pub enum Refused { + Unsigned, + UnknownKey, + BadSignature, + BadClaims, + OtherCluster, + Replayed { seq: u64, last: u64 }, + Expired, + NotYetValid, + Tampered, + IdMismatch, + /// A reply to another request (its nonce isn't the one sent). + OtherRequest, + /// Signed by a session key whose delegation isn't a trusted key's (or + /// can't be read, or is longer than [`MAX_DELEGATION_MS`]). + BadDelegation, + /// Signed by a session key whose delegation expired (or isn't good yet). + DelegationExpired, + /// Signed by a session key outside its delegation's window. + OutsideDelegation, + /// Signed by a session key that may not sign this. + NotDelegated, +} + +impl std::fmt::Display for Refused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Refused::Unsigned => write!(f, "it isn't signed"), + Refused::UnknownKey => write!(f, "it's signed with a key this cluster doesn't trust"), + Refused::BadSignature => write!(f, "its signature doesn't match"), + Refused::BadClaims => write!(f, "its signed details can't be read"), + Refused::OtherCluster => write!(f, "it was signed for another cluster"), + Refused::Replayed { seq, last } => write!(f, "it was already used (number {seq}, last run {last})"), + Refused::Expired => write!(f, "it expired"), + Refused::NotYetValid => write!(f, "it's dated in the future"), + Refused::Tampered => write!(f, "it was changed after it was signed"), + Refused::IdMismatch => write!(f, "its id doesn't match what was signed"), + Refused::OtherRequest => write!(f, "it answers another request"), + Refused::BadDelegation => write!(f, "its session key wasn't handed over by a key this cluster trusts"), + Refused::DelegationExpired => write!(f, "its session key's time is over"), + Refused::OutsideDelegation => write!(f, "it was signed outside its session key's time"), + Refused::NotDelegated => write!(f, "its session key may not sign it"), + } + } +} + +/// The keys an agent trusts, from `PYO_COMMAND_KEY` (base64url public keys, +/// comma separated, so a new key can be added before the old one goes). +#[derive(Clone, Debug, Default)] +pub struct TrustedKeys { + keys: Vec<(String, Vec)>, + /// Delegations already checked against `keys` (the latest few). Their + /// windows are still checked on every use. + delegations: std::sync::Arc>>, +} + +/// A delegation checked against a trusted key: its claims and session key. +type Checked = (crate::DelegationWire, DelegationClaims, Vec); + +/// A signature's checked origin: a trusted key, or a session key it +/// handed signing to (with that delegation's claims). +enum Origin { + Trusted, + Session(DelegationClaims), +} + +/// How many checked delegations an agent keeps. +const DELEGATION_CACHE: usize = 4; + +impl TrustedKeys { + pub fn parse(v: &str) -> Result { + let mut keys = vec![]; + for k in v.split(',').map(str::trim).filter(|k| !k.is_empty()) { + let raw = B64.decode(k).map_err(|_| format!("{k} isn't base64url"))?; + if raw.len() != 32 { + return Err(format!("{k} isn't an Ed25519 public key")); + } + keys.push((key_id(&raw), raw)); + } + if keys.is_empty() { + return Err("no keys".into()); + } + Ok(Self { keys, delegations: Default::default() }) + } + + pub fn is_empty(&self) -> bool { + self.keys.is_empty() + } + + fn trusted(&self, kid: &str) -> Option<&[u8]> { + self.keys.iter().find(|(k, _)| k == kid).map(|(_, k)| k.as_slice()) + } + + /// A delegation's claims and session key, once it checks out against + /// a trusted key (from the cache when it was checked before). + fn delegation(&self, d: &crate::DelegationWire) -> Result<(DelegationClaims, Vec), Refused> { + if let Ok(cache) = self.delegations.lock() + && let Some((_, c, k)) = cache.iter().find(|(w, _, _)| w == d) + { + return Ok((c.clone(), k.clone())); + } + let root = self.trusted(&d.kid).ok_or(Refused::BadDelegation)?; + let sig = B64.decode(&d.sig).map_err(|_| Refused::BadDelegation)?; + let msg = format!("{DELEGATION_PREFIX}.{}", d.claims).into_bytes(); + if !verify_ed25519(root, &msg, &sig) { + return Err(Refused::BadDelegation); + } + let raw = B64.decode(&d.claims).map_err(|_| Refused::BadDelegation)?; + let c: DelegationClaims = serde_json::from_slice(&raw).map_err(|_| Refused::BadDelegation)?; + let key = B64.decode(&c.key).map_err(|_| Refused::BadDelegation)?; + if c.v != 1 || key.len() != 32 || c.exp <= c.nbf || c.exp - c.nbf > MAX_DELEGATION_MS { + return Err(Refused::BadDelegation); + } + if let Ok(mut cache) = self.delegations.lock() { + if cache.len() >= DELEGATION_CACHE { + cache.remove(0); + } + cache.push((d.clone(), c.clone(), key.clone())); + } + Ok((c, key)) + } + + /// Checks `sig` over `msg` from the key `kid`: a trusted key, or a + /// session key whose delegation lets it sign for `purpose` now. + fn check_signature( + &self, + kid: &str, + delegation: Option<&crate::DelegationWire>, + purpose: &str, + msg: &[u8], + sig: &str, + now_ms: u64, + ) -> Result { + let sig = B64.decode(sig).map_err(|_| Refused::BadSignature)?; + let Some(d) = delegation else { + let key = self.trusted(kid).ok_or(Refused::UnknownKey)?; + return verify_ed25519(key, msg, &sig).then_some(Origin::Trusted).ok_or(Refused::BadSignature); + }; + let (c, key) = self.delegation(d)?; + if key_id(&key) != kid { + return Err(Refused::UnknownKey); + } + if !c.purposes.iter().any(|p| p == purpose) { + return Err(Refused::NotDelegated); + } + if now_ms > c.exp.saturating_add(LEEWAY_MS) || c.nbf > now_ms.saturating_add(LEEWAY_MS) { + return Err(Refused::DelegationExpired); + } + if !verify_ed25519(&key, msg, &sig) { + return Err(Refused::BadSignature); + } + Ok(Origin::Session(c)) + } + + /// Checks a signed command for `cluster`, given the last sequence number + /// this cluster ran. On success, the claims and the command's JSON. + pub fn verify( + &self, + signed: Option<&SignedCommand>, + envelope_id: &str, + cluster: &str, + last_seq: u64, + now_ms: u64, + ) -> Result { + let s = signed.ok_or(Refused::Unsigned)?; + let origin = + self.check_signature(&s.kid, s.delegation.as_ref(), PURPOSE_COMMANDS, &message(&s.claims), &s.sig, now_ms)?; + let raw = B64.decode(&s.claims).map_err(|_| Refused::BadClaims)?; + let c: Claims = serde_json::from_slice(&raw).map_err(|_| Refused::BadClaims)?; + if c.v != 1 { + return Err(Refused::BadClaims); + } + if let Origin::Session(d) = &origin { + if ROOT_ONLY_KINDS.contains(&c.kind.as_str()) { + return Err(Refused::NotDelegated); + } + if c.iat < d.nbf || c.exp > d.exp { + return Err(Refused::OutsideDelegation); + } + } + if c.cluster != cluster { + return Err(Refused::OtherCluster); + } + if c.id != envelope_id { + return Err(Refused::IdMismatch); + } + if sha256_hex(s.command.as_bytes()) != c.sha256 { + return Err(Refused::Tampered); + } + if now_ms > c.exp.saturating_add(LEEWAY_MS) { + return Err(Refused::Expired); + } + if c.iat > now_ms.saturating_add(LEEWAY_MS) { + return Err(Refused::NotYetValid); + } + if c.seq <= last_seq { + return Err(Refused::Replayed { seq: c.seq, last: last_seq }); + } + Ok(c) + } + + /// Checks a signed reply for `cluster`, to the request sent with + /// `nonce`. On success, the reply's JSON (what was signed). + pub fn verify_reply<'a>( + &self, + signed: Option<&'a crate::SignedReplyWire>, + cluster: &str, + nonce: &str, + now_ms: u64, + ) -> Result<&'a str, Refused> { + let s = signed.ok_or(Refused::Unsigned)?; + let origin = + self.check_signature(&s.kid, s.delegation.as_ref(), PURPOSE_REPLIES, &reply_message(&s.claims), &s.sig, now_ms)?; + let raw = B64.decode(&s.claims).map_err(|_| Refused::BadClaims)?; + let c: ReplyClaims = serde_json::from_slice(&raw).map_err(|_| Refused::BadClaims)?; + if c.v != 1 { + return Err(Refused::BadClaims); + } + if let Origin::Session(d) = &origin + && (c.iat < d.nbf || c.exp > d.exp) + { + return Err(Refused::OutsideDelegation); + } + if c.cluster != cluster { + return Err(Refused::OtherCluster); + } + if nonce.is_empty() || c.nonce != nonce { + return Err(Refused::OtherRequest); + } + if sha256_hex(s.reply.as_bytes()) != c.sha256 { + return Err(Refused::Tampered); + } + if now_ms > c.exp.saturating_add(LEEWAY_MS) { + return Err(Refused::Expired); + } + if c.iat > now_ms.saturating_add(LEEWAY_MS) { + return Err(Refused::NotYetValid); + } + Ok(&s.reply) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn setup() -> (Signer, TrustedKeys) { + let s = Signer::from_pkcs8(&Signer::generate_pkcs8().unwrap()).unwrap(); + let t = TrustedKeys::parse(&s.public_key()).unwrap(); + (s, t) + } + + fn signed(s: &Signer, cluster: &str, seq: u64, command: &str, now: u64) -> SignedCommand { + let claims = Claims { + v: 1, + id: "cmd_1".into(), + cluster: cluster.into(), + seq, + iat: now, + exp: now + TTL_MS, + kind: "restart".into(), + sha256: sha256_hex(command.as_bytes()), + }; + let (c, sig) = s.sign(&claims); + SignedCommand { claims: c, sig, kid: s.kid().into(), command: command.into(), delegation: None } + } + + #[test] + fn a_good_command_passes() { + let (s, t) = setup(); + let x = signed(&s, "cl_a", 5, r#"{"kind":"restart"}"#, 1_000_000); + let c = t.verify(Some(&x), "cmd_1", "cl_a", 4, 1_000_000).unwrap(); + assert_eq!(c.seq, 5); + } + + #[test] + fn everything_else_is_refused() { + let (s, t) = setup(); + let now = 1_000_000; + let x = signed(&s, "cl_a", 5, r#"{"kind":"restart"}"#, now); + assert_eq!(t.verify(None, "cmd_1", "cl_a", 0, now), Err(Refused::Unsigned)); + assert_eq!(t.verify(Some(&x), "cmd_1", "cl_b", 0, now), Err(Refused::OtherCluster)); + assert_eq!(t.verify(Some(&x), "cmd_2", "cl_a", 0, now), Err(Refused::IdMismatch)); + assert_eq!(t.verify(Some(&x), "cmd_1", "cl_a", 5, now), Err(Refused::Replayed { seq: 5, last: 5 })); + assert_eq!(t.verify(Some(&x), "cmd_1", "cl_a", 0, now + TTL_MS + LEEWAY_MS + 1), Err(Refused::Expired)); + let mut tampered = x.clone(); + tampered.command = r#"{"kind":"delete_namespace"}"#.into(); + assert_eq!(t.verify(Some(&tampered), "cmd_1", "cl_a", 0, now), Err(Refused::Tampered)); + let mut forged = x.clone(); + forged.claims = B64.encode(br#"{"v":1}"#); + assert_eq!(t.verify(Some(&forged), "cmd_1", "cl_a", 0, now), Err(Refused::BadSignature)); + let (other, _) = setup(); + let mut wrong_key = signed(&other, "cl_a", 5, r#"{"kind":"restart"}"#, now); + assert_eq!(t.verify(Some(&wrong_key), "cmd_1", "cl_a", 0, now), Err(Refused::UnknownKey)); + // Another key's signature under a trusted key id. + wrong_key.kid = s.kid().into(); + assert_eq!(t.verify(Some(&wrong_key), "cmd_1", "cl_a", 0, now), Err(Refused::BadSignature)); + } + + fn reply(s: &Signer, cluster: &str, nonce: &str, body: &str, now: u64) -> crate::SignedReplyWire { + let claims = ReplyClaims { + v: 1, + cluster: cluster.into(), + nonce: nonce.into(), + iat: now, + exp: now + REPLY_TTL_MS, + sha256: sha256_hex(body.as_bytes()), + }; + let (c, sig) = s.sign_reply(&claims); + crate::SignedReplyWire { claims: c, sig, kid: s.kid().into(), reply: body.into(), delegation: None } + } + + #[test] + fn a_good_reply_passes() { + let (s, t) = setup(); + let now = 1_000_000; + let r = reply(&s, "cl_a", "nonce-1234", r#"{"publicTraffic":true}"#, now); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now + 5_000), Ok(r#"{"publicTraffic":true}"#)); + } + + #[test] + fn bad_replies_are_refused() { + let (s, t) = setup(); + let now = 1_000_000; + let r = reply(&s, "cl_a", "nonce-1234", r#"{"publicTraffic":false}"#, now); + // Unsigned, where signing is required. + assert_eq!(t.verify_reply(None, "cl_a", "nonce-1234", now), Err(Refused::Unsigned)); + // Another cluster's. + assert_eq!(t.verify_reply(Some(&r), "cl_b", "nonce-1234", now), Err(Refused::OtherCluster)); + // Played back for a later request. + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-5678", now), Err(Refused::OtherRequest)); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "", now), Err(Refused::OtherRequest)); + // Too old. + assert_eq!( + t.verify_reply(Some(&r), "cl_a", "nonce-1234", now + REPLY_TTL_MS + LEEWAY_MS + 1), + Err(Refused::Expired) + ); + // Dated ahead. + let ahead = reply(&s, "cl_a", "nonce-1234", "{}", now + LEEWAY_MS + 60_000); + assert_eq!(t.verify_reply(Some(&ahead), "cl_a", "nonce-1234", now), Err(Refused::NotYetValid)); + // Changed after signing. + let mut tampered = r.clone(); + tampered.reply = r#"{"publicTraffic":true}"#.into(); + assert_eq!(t.verify_reply(Some(&tampered), "cl_a", "nonce-1234", now), Err(Refused::Tampered)); + // Signed by a key the cluster doesn't trust. + let (other, _) = setup(); + let mut forged = reply(&other, "cl_a", "nonce-1234", "{}", now); + assert_eq!(t.verify_reply(Some(&forged), "cl_a", "nonce-1234", now), Err(Refused::UnknownKey)); + forged.kid = s.kid().into(); + assert_eq!(t.verify_reply(Some(&forged), "cl_a", "nonce-1234", now), Err(Refused::BadSignature)); + } + + #[test] + fn a_reply_signature_is_no_command_signature() { + let (s, t) = setup(); + let now = 1_000_000; + let body = r#"{"kind":"restart"}"#; + // A reply's claims and signature passed off as a command's. + let r = reply(&s, "cl_a", "nonce-1234", body, now); + let as_command = SignedCommand { claims: r.claims.clone(), sig: r.sig.clone(), kid: r.kid.clone(), command: body.into(), delegation: None }; + assert_eq!(t.verify(Some(&as_command), "cmd_1", "cl_a", 0, now), Err(Refused::BadSignature)); + // And a command's as a reply's. + let c = signed(&s, "cl_a", 1, body, now); + let as_reply = crate::SignedReplyWire { claims: c.claims, sig: c.sig, kid: c.kid, reply: body.into(), delegation: None }; + assert_eq!(t.verify_reply(Some(&as_reply), "cl_a", "nonce-1234", now), Err(Refused::BadSignature)); + } + + /// A session key, and the root's delegation to it. + fn session(root: &Signer, purposes: &[&str], nbf: u64, exp: u64) -> (Signer, crate::DelegationWire) { + let k = Signer::from_pkcs8(&Signer::generate_pkcs8().unwrap()).unwrap(); + let d = root.delegate(&DelegationClaims { + v: 1, + key: k.public_key(), + purposes: purposes.iter().map(|p| p.to_string()).collect(), + nbf, + exp, + serial: 1, + }); + (k, d) + } + + const HOUR: u64 = 60 * 60 * 1000; + + #[test] + fn a_session_key_signs_replies_and_commands_it_was_given() { + let (root, t) = setup(); + let now = 10 * HOUR; + let (k, d) = session(&root, &[PURPOSE_REPLIES, PURPOSE_COMMANDS], now - 1000, now + HOUR); + let mut r = reply(&k, "cl_a", "nonce-1234", "{}", now); + r.delegation = Some(d.clone()); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Ok("{}")); + // Checked once, then from the cache: the same answer. + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now + 1), Ok("{}")); + let mut c = signed(&k, "cl_a", 5, r#"{"kind":"restart"}"#, now); + c.delegation = Some(d); + assert_eq!(t.verify(Some(&c), "cmd_1", "cl_a", 4, now).map(|c| c.seq), Ok(5)); + // Without its delegation, the session key is just an unknown key. + c.delegation = None; + assert_eq!(t.verify(Some(&c), "cmd_1", "cl_a", 4, now), Err(Refused::UnknownKey)); + } + + #[test] + fn an_expired_delegation_is_refused() { + let (root, t) = setup(); + let now = 10 * HOUR; + let (k, d) = session(&root, &[PURPOSE_REPLIES], now - 2 * HOUR + 1000, now - HOUR); + // Signed while the delegation held, checked after it ended. + let mut r = reply(&k, "cl_a", "nonce-1234", "{}", now - HOUR - REPLY_TTL_MS); + r.delegation = Some(d.clone()); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::DelegationExpired)); + // And one that isn't good yet. + let (k, d) = session(&root, &[PURPOSE_REPLIES], now + HOUR, now + 2 * HOUR); + let mut r = reply(&k, "cl_a", "nonce-1234", "{}", now + HOUR); + r.delegation = Some(d); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::DelegationExpired)); + } + + #[test] + fn a_delegation_not_signed_by_a_trusted_key_is_refused() { + let (_, t) = setup(); + let (other, _) = setup(); + let now = 10 * HOUR; + let (k, d) = session(&other, &[PURPOSE_REPLIES], now - 1000, now + HOUR); + let mut r = reply(&k, "cl_a", "nonce-1234", "{}", now); + r.delegation = Some(d.clone()); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::BadDelegation)); + // Under a trusted key's id. + let (root, t) = setup(); + let mut forged = d; + forged.kid = root.kid().into(); + r.delegation = Some(forged.clone()); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::BadDelegation)); + // A trusted delegation changed after signing (a longer window). + let (k, d) = session(&root, &[PURPOSE_REPLIES], now - 1000, now + HOUR); + let mut c: DelegationClaims = serde_json::from_slice(&B64.decode(&d.claims).unwrap()).unwrap(); + c.exp = now + 100 * HOUR; + let changed = crate::DelegationWire { claims: c.signing_input().0, ..d }; + let mut r = reply(&k, "cl_a", "nonce-1234", "{}", now); + r.delegation = Some(changed); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::BadDelegation)); + // Signed by the root, but longer than an agent accepts. + let (k, d) = session(&root, &[PURPOSE_REPLIES], now - 1000, now + MAX_DELEGATION_MS); + let mut r = reply(&k, "cl_a", "nonce-1234", "{}", now); + r.delegation = Some(d); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::BadDelegation)); + // Another session key's signature under this delegation. + let (_, d) = session(&root, &[PURPOSE_REPLIES], now - 1000, now + HOUR); + let (k2, _) = session(&root, &[PURPOSE_REPLIES], now - 1000, now + HOUR); + let mut r = reply(&k2, "cl_a", "nonce-1234", "{}", now); + r.delegation = Some(d); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::UnknownKey)); + } + + #[test] + fn a_session_key_is_refused_outside_its_window() { + let (root, t) = setup(); + let now = 10 * HOUR; + let (k, d) = session(&root, &[PURPOSE_REPLIES, PURPOSE_COMMANDS], now, now + HOUR); + // Dated before the delegation starts. + let mut r = reply(&k, "cl_a", "nonce-1234", "{}", now - 30_000); + r.delegation = Some(d.clone()); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::OutsideDelegation)); + // Good past the delegation's end. + let mut c = signed(&k, "cl_a", 1, "{}", now + HOUR - 60_000); + c.delegation = Some(d); + assert_eq!(t.verify(Some(&c), "cmd_1", "cl_a", 0, now + HOUR - 60_000), Err(Refused::OutsideDelegation)); + } + + #[test] + fn a_session_key_signs_only_what_it_was_given() { + let (root, t) = setup(); + let now = 10 * HOUR; + let (k, d) = session(&root, &[PURPOSE_REPLIES], now - 1000, now + HOUR); + // Replies only: no commands. + let mut c = signed(&k, "cl_a", 1, "{}", now); + c.delegation = Some(d); + assert_eq!(t.verify(Some(&c), "cmd_1", "cl_a", 0, now), Err(Refused::NotDelegated)); + // Commands only: no replies. + let (k, d) = session(&root, &[PURPOSE_COMMANDS], now - 1000, now + HOUR); + let mut r = reply(&k, "cl_a", "nonce-1234", "{}", now); + r.delegation = Some(d.clone()); + assert_eq!(t.verify_reply(Some(&r), "cl_a", "nonce-1234", now), Err(Refused::NotDelegated)); + // Never an agent update, which only the trusted key signs. + let body = r#"{"kind":"update_agent","image":"evil.example/agent:1"}"#; + let claims = Claims { + v: 1, + id: "cmd_1".into(), + cluster: "cl_a".into(), + seq: 1, + iat: now, + exp: now + TTL_MS, + kind: "update_agent".into(), + sha256: sha256_hex(body.as_bytes()), + }; + let (c, sig) = k.sign(&claims); + let update = SignedCommand { claims: c, sig, kid: k.kid().into(), command: body.into(), delegation: Some(d) }; + assert_eq!(t.verify(Some(&update), "cmd_1", "cl_a", 0, now), Err(Refused::NotDelegated)); + let (c, sig) = root.sign(&claims); + let update = SignedCommand { claims: c, sig, kid: root.kid().into(), command: body.into(), delegation: None }; + assert!(t.verify(Some(&update), "cmd_1", "cl_a", 0, now).is_ok()); + } +} diff --git a/crates/pyo-proto/src/system.rs b/crates/pyo-proto/src/system.rs index 32e2a4e6..7b478240 100644 --- a/crates/pyo-proto/src/system.rs +++ b/crates/pyo-proto/src/system.rs @@ -82,10 +82,11 @@ pub const ACCESS_LOG_FIELDS: [(&str, &str); 20] = [ pub const ACCESS_LOG_CONTENT_TYPE: (&str, &str) = ("content_type", "%RESP(CONTENT-TYPE)%"); /// The GeoIP country database the proxies place visitors with, for the -/// firewall's country rules (GeoLite2 Country, as analytics uses GeoLite2 -/// City): an image with just the file (deploy/images/geoip.Dockerfile, -/// built with each release), mounted read-only as an image volume, so the -/// proxies need no credentials or downloads for it. +/// firewall's country rules (GeoLite2 Country): an image with just the file +/// (deploy/images/geoip.Dockerfile, built with each release), mounted +/// read-only as an image volume, so the proxies need no credentials or +/// downloads for it. The WAF and the traffic store (pyo-agent's traffic/, +/// for analytics' countries) mount the same image: one copy per cluster. /// /// Its image comes from the installation (`PYO_GEOIP_IMAGE`), like the /// WAF's: the agent's install manifest gives it to the agent and pins it in diff --git a/crates/pyo-proto/src/tailscale.rs b/crates/pyo-proto/src/tailscale.rs new file mode 100644 index 00000000..35eace81 --- /dev/null +++ b/crates/pyo-proto/src/tailscale.rs @@ -0,0 +1,367 @@ +//! Tailscale through the agent: what Pyo asks a cluster's agent to do on the +//! cluster's tailnet, and what comes back. +//! +//! Each cluster keeps its own Tailscale OAuth client, as a Secret in +//! pyo-system ([`SECRET`]). Pyo never holds it: the setup (one pasted API +//! access token), join keys, Tailscale Services and their approvals all +//! run in the agent, as signed commands. Answers carry no secret, except a +//! join key ([`KEY_FIELD`]), which Pyo passes into a join command once and +//! then wipes. + +use serde::{Deserialize, Serialize}; + +/// The tag Pyo's servers and Services carry. +pub const TAG: &str = "tag:pyo"; +/// Names Pyo keeps for itself: services' domains can't take them. +pub const RESERVED: [&str; 3] = ["pyo", "registry", "sandboxes"]; +/// The cluster's OAuth client: a Secret in pyo-system, with +/// [`SECRET_ID`] and [`SECRET_KEY`]. +pub const SECRET: &str = "pyo-tailscale"; +pub const SECRET_ID: &str = "client-id"; +pub const SECRET_KEY: &str = "client-secret"; +/// Where a join key comes back in a [`crate::Command::TailscaleKey`] result. +pub const KEY_FIELD: &str = "authKey"; + +/// What a Service Pyo made says about itself (its comment): the +/// installation and the cluster whose client made it. +pub fn marker(install: &str, cluster: &str) -> String { + format!("Made by Pyo ({install} {cluster})") +} + +/// The marker Pyo used before each cluster had its own client: the +/// installation's only. The cluster that takes over the installation's +/// client counts these as its own too. +pub fn install_marker(install: &str) -> String { + format!("Made by Pyo ({install})") +} + +/// "server-1.tail1234.ts.net" → "tail1234.ts.net". +pub fn suffix_of(name: &str) -> Option { + let (_, rest) = name.trim_end_matches('.').split_once('.')?; + rest.ends_with(".ts.net").then(|| rest.to_ascii_lowercase()) +} + +/// A name on the tailnet: one DNS label. +pub fn valid_name(n: &str) -> bool { + !n.is_empty() + && n.len() <= 63 + && n.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !n.starts_with('-') + && !n.ends_with('-') +} + +/// One of Pyo's own names that it keeps up to date: the one it has while +/// that isn't `taken` (someone else's Service, a machine, or another of +/// Pyo's names), else the first free one [`pick_name`] finds. +pub fn own_name( + current: Option<&str>, + base: &str, + more: &str, + taken: impl Fn(&str) -> bool, +) -> String { + match current { + Some(n) if !n.is_empty() && !taken(n) => n.to_owned(), + _ => pick_name(base, more, taken), + } +} + +/// The first free name: `base`, then `base-`, then `base--2`… +pub fn pick_name(base: &str, more: &str, taken: impl Fn(&str) -> bool) -> String { + let cut = |x: &str| { + x.chars() + .take(63) + .collect::() + .trim_end_matches('-') + .to_owned() + }; + let first = cut(base); + if !taken(&first) { + return first; + } + let second = cut(&format!("{base}-{more}")); + if !taken(&second) { + return second; + } + (2..) + .map(|i| cut(&format!("{base}-{more}-{i}"))) + .find(|n| !taken(n)) + .unwrap_or_default() +} + +/// What Tailscale takes as a key's description: letters, digits, spaces, +/// dashes and underscores, at most 50 characters. "Pyo: join web-1" +/// becomes "Pyo join web-1". +pub fn key_description(s: &str) -> String { + let kept: String = s + .chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')) + .collect(); + let mut out = kept.split_whitespace().collect::>().join(" "); + out.truncate(50); + out.trim_end().to_owned() +} + +/// One of Pyo's own names on the tailnet (only on the cluster Pyo runs on): +/// "dashboard", "registry" or "sandboxes". +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OwnName { + pub kind: String, + /// The name it has now, when it has one. + #[serde(default)] + pub current: Option, + /// "pyo", "registry" or "sandboxes". + pub base: String, + /// What makes it unique when `base` is taken (the cluster's name). + pub more: String, + /// Kept even when someone else has it ("Taken on your tailnet"), + /// rather than picked again: the dashboard's and the registry's, which + /// people may have bookmarked. + #[serde(default)] + pub keep: bool, +} + +/// One of the cluster's servers on the tailnet. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SyncServer { + pub server: String, + /// Its stable node ID. + pub node_id: String, + /// The Services it advertises ("blog"). + #[serde(default)] + pub advertised: Vec, +} + +/// The cluster's names on its tailnet, as Pyo wants them +/// ([`crate::Command::TailscaleSync`]). The agent makes each (marked +/// [`TailnetSync::mark`]), approves the cluster's servers as its hosts, +/// tags the servers, deletes the ones Pyo made that are no longer wanted, +/// and never touches a Service it didn't make. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TailnetSync { + /// What marks the Services this cluster makes. + pub mark: String, + /// Older marks that are this cluster's too (the installation's, for the + /// cluster that took over its client). + #[serde(default)] + pub adopt: Vec, + /// Pyo's own names, picked here when they have none yet. + #[serde(default)] + pub own: Vec, + /// Services' tailnet domains on this cluster ("blog"). + #[serde(default)] + pub domains: Vec, + /// Names Pyo made for this cluster before: deleted when no longer + /// wanted (each read again first). + #[serde(default)] + pub made: Vec, + /// The tailnet's machines as the cluster's servers see them. + #[serde(default)] + pub peers: Vec, + #[serde(default)] + pub servers: Vec, + /// Machines to take off the tailnet (node IDs of tag:pyo machines + /// whose server was deleted). + #[serde(default)] + pub forget: Vec, +} + +/// One name, as the agent left it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NameState { + pub name: String, + /// "dashboard", "registry", "sandboxes" or "domain". + pub kind: String, + /// Its VIPs, IPv4 then IPv6. + #[serde(default)] + pub addrs: Vec, + /// Why it isn't working, as people read it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// A machine Tailnet Lock keeps out until a signing device signs its key. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LockWaiting { + pub name: String, + pub sign_command: String, +} + +/// What a [`TailnetSync`] did (its result's `data`). +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TailnetSynced { + /// The tailnet's MagicDNS suffix ("tail1234.ts.net"), when seen. + #[serde(default)] + pub suffix: Option, + /// Every wanted name (own ones as picked). + #[serde(default)] + pub names: Vec, + /// Names deleted on the tailnet. + #[serde(default)] + pub deleted: Vec, + #[serde(default)] + pub lock_waiting: Vec, + /// Pyo's machines on the tailnet (tag:pyo). + #[serde(default)] + pub machines: Vec, + /// Machines taken off the tailnet, of [`TailnetSync::forget`]. + #[serde(default)] + pub forgotten: Vec, +} + +/// One of Pyo's machines on the tailnet (tag:pyo). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Machine { + pub node_id: String, + pub hostname: String, + /// Tailnet Lock waits for its key to be signed: the command that signs it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sign_command: Option, +} + +/// What a name typed for a tailnet domain is on the cluster's tailnet +/// ([`crate::Command::TailscaleCheckName`]'s `data`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NameCheck { + /// "free", "ours" or "taken". + pub state: String, + #[serde(default)] + pub suffix: Option, +} + +/// One check of the client (Test, or after saving it). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Check { + pub name: String, + pub ok: bool, + pub message: String, +} + +/// What [`crate::Command::TailscaleClient`] and +/// [`crate::Command::TailscaleTest`] say (their `data`). +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientState { + pub ok: bool, + pub checks: Vec, + #[serde(default)] + pub client_id: String, + /// The secret's last characters, to tell it apart. + #[serde(default)] + pub hint: String, + #[serde(default)] + pub suffix: Option, +} + +/// A call to a sandbox server's daemon on the cluster's tailnet +/// ([`crate::Command::SandboxCall`]): Pyo can't reach the tailnet when it +/// runs elsewhere (Pyo Cloud), so the cluster's agent makes it. Only the +/// daemon's own API, on its port, at a tailnet address. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SandboxCall { + /// The server's tailnet address (100.64.0.0/10 or fd7a:115c:a1e0::/48). + pub address: String, + /// "GET", "POST", "PUT" or "DELETE". + pub method: String, + /// "/v1/…". + pub path: String, + /// The short-lived token Pyo signed for this call. + pub token: String, + /// JSON, or base64 bytes with `raw`. + #[serde(default)] + pub body: Option, + /// The body is bytes (base64), and so is the answer. + #[serde(default)] + pub raw: bool, + #[serde(default)] + pub content_type: Option, + pub timeout_secs: u64, +} + +/// The daemon's answer ([`SandboxCall`]'s `data`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SandboxAnswer { + /// 0 when it couldn't be reached. + pub status: u16, + /// Text, or base64 for a raw call. + pub body: String, + #[serde(default)] + pub content_type: Option, +} + +/// Whether `ip` is an address on a tailnet: 100.64.0.0/10 or +/// fd7a:115c:a1e0::/48. +pub fn tailnet_ip(ip: &str) -> bool { + match ip.parse::() { + Ok(std::net::IpAddr::V4(v)) => { + let o = v.octets(); + o[0] == 100 && (64..128).contains(&o[1]) + } + Ok(std::net::IpAddr::V6(v)) => { + let s = v.segments(); + s[0] == 0xfd7a && s[1] == 0x115c && s[2] == 0xa1e0 + } + Err(_) => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn key_descriptions_are_what_tailscale_takes() { + assert_eq!(key_description("Pyo: join web-1"), "Pyo join web-1"); + assert_eq!( + key_description("Pyo: sandbox server sbx_1"), + "Pyo sandbox server sbx_1" + ); + let long = key_description(&format!("Pyo: join {}", "a".repeat(80))); + assert_eq!(long.len(), 50); + } + + #[test] + fn names() { + assert_eq!( + suffix_of("server-1.tail1234.ts.net."), + Some("tail1234.ts.net".into()) + ); + assert_eq!(suffix_of("example.com"), None); + assert!( + valid_name("blog-2") && !valid_name("Blog") && !valid_name("-a") && !valid_name("a.b") + ); + let taken = ["pyo", "pyo-home"]; + assert_eq!( + pick_name("pyo", "home", |n| taken.contains(&n)), + "pyo-home-2" + ); + assert_eq!( + pick_name("registry", "home", |n| taken.contains(&n)), + "registry" + ); + assert_eq!(pick_name("pyo", "home", |n| n == "pyo"), "pyo-home"); + let long = "a".repeat(70); + assert!(pick_name(&long, "x", |_| false).len() <= 63); + assert_eq!(marker("abc", "cl_1"), "Made by Pyo (abc cl_1)"); + assert_eq!(install_marker("abc"), "Made by Pyo (abc)"); + } + + #[test] + fn tailnet_addresses() { + assert!(tailnet_ip("100.64.0.7") && tailnet_ip("100.127.255.1")); + assert!(tailnet_ip("fd7a:115c:a1e0::1")); + assert!(!tailnet_ip("100.128.0.1") && !tailnet_ip("10.0.0.1")); + assert!(!tailnet_ip("169.254.169.254") && !tailnet_ip("localhost")); + } +} diff --git a/crates/pyo-proto/src/traffic.rs b/crates/pyo-proto/src/traffic.rs new file mode 100644 index 00000000..2c956fea --- /dev/null +++ b/crates/pyo-proto/src/traffic.rs @@ -0,0 +1,989 @@ +//! Website and port traffic, as each cluster keeps it and Pyo stores it. +//! +//! The gateway's access log stays in the cluster: pyo-agent's traffic store +//! cleans each line there (sensitive query values redacted, the visitor's +//! country looked up, a daily-salted visitor hash made from the address), keeps +//! the cleaned requests in hourly files, and adds up per-minute totals per +//! host and per proxied port. Only the totals go to Pyo. Everything both sides +//! need is here: reading Envoy's lines, the totals and their mergeable +//! sketches (a HyperLogLog for visitors, a log-scale histogram for response +//! times, top lists), the stored rows and the queries Pyo sends for them. + +use std::collections::{BTreeMap, HashMap}; +use std::net::IpAddr; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Query parameters whose values are never kept. +pub const SENSITIVE: [&str; 15] = [ + "token", + "password", + "passwd", + "secret", + "apikey", + "api_key", + "auth", + "session", + "signature", + "email", + "otp", + "jwt", + "credential", + "code", + "invite", +]; + +/// Top lists kept per host and minute. +pub const TOP_PATHS: usize = 50; +pub const TOP_PAGES: usize = 50; +pub const TOP_REFERRERS: usize = 20; +pub const TOP_PARAMS: usize = 20; +pub const TOP_BLOCKED_PATHS: usize = 20; +/// Most rows a query answers with. +pub const MAX_ROWS: u32 = 500; + +/// "/a?token=x&page=2" -> ("/a", "/a?token=[redacted]&page=2", ["token","page"], ["token"]). +pub fn split_url(raw: &str) -> (String, String, Vec, Vec) { + let raw: String = raw.chars().take(2000).collect(); + let (path, query) = match raw.split_once('?') { + Some((p, q)) => (p.to_owned(), q.to_owned()), + None => (raw.clone(), String::new()), + }; + if query.is_empty() { + return (path.clone(), path, vec![], vec![]); + } + let mut keys = vec![]; + let mut redacted = vec![]; + let parts: Vec = query + .split('&') + .filter(|kv| !kv.is_empty()) + .map(|kv| { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + let lower = k.to_ascii_lowercase(); + if !keys.contains(&k.to_owned()) { + keys.push(k.to_owned()); + } + if sensitive(&lower) { + if !redacted.contains(&k.to_owned()) { + redacted.push(k.to_owned()); + } + format!("{k}=[redacted]") + } else if v.is_empty() { + k.to_owned() + } else { + format!("{k}={v}") + } + }) + .collect(); + (path.clone(), format!("{path}?{}", parts.join("&")), keys, redacted) +} + +/// Whether a query parameter's values are never kept (by its name, any case). +pub fn sensitive(key: &str) -> bool { + let lower = key.to_ascii_lowercase(); + SENSITIVE.iter().any(|s| lower.contains(s)) +} + +/// An address as the installation's IP setting keeps it: "none" (nothing), +/// "anonymized" (the last part removed: 203.0.113.0, 2001:db8:85a3::) or +/// "full". +pub fn mask_ip(mode: &str, ip: &str) -> String { + match (mode, ip.parse::()) { + ("full", Ok(a)) => a.to_string(), + ("anonymized", Ok(IpAddr::V4(v))) => { + let [a, b, c, _] = v.octets(); + std::net::Ipv4Addr::new(a, b, c, 0).to_string() + } + ("anonymized", Ok(IpAddr::V6(v))) => { + let s = v.segments(); + std::net::Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0).to_string() + } + _ => String::new(), + } +} + +/// Why the proxy answered a request (or ended a connection) itself: +/// "blocked" (an IP or country rule), "rate-limit", or empty. +pub fn refusal(details: &str, termination: &str, status: u64) -> String { + if [details, termination] + .iter() + .any(|d| d.starts_with("rbac_access_denied_matched_policy[")) + { + return "blocked".into(); + } + if status == 429 && details.contains("rate_limited") { + return "rate-limit".into(); + } + String::new() +} + +// ── The gateway's lines ───────────────────────────────────────────────────── + +/// One access log line from the gateway (Envoy's JSON, fields in +/// system.rs). +#[derive(Debug, Default, PartialEq)] +pub struct AccessLine { + pub host: String, + pub ts_ms: Option, + pub peer: String, + pub forwarded_for: String, + pub real_ip: String, + pub user_agent: String, + pub status: u64, + pub method: String, + pub path: String, + pub content_type: String, + pub referer: String, + pub duration_ms: f64, + pub bytes: u64, + pub node: String, + /// The visitor as the proxy saw them (a PROXY protocol header's address, + /// or the peer). + pub remote: String, + /// TCP and UDP ports: bytes from the visitor, the route + /// (`tcproute/pyo-gateway//rule/0`), Envoy's flags and how the + /// connection ended. + pub bytes_in: u64, + pub upstream: String, + pub upstream_host: String, + pub local_port: u64, + pub flags: String, + pub termination: String, + /// Why the proxy answered itself (a firewall rule, a rate limit). + pub details: String, +} + +/// Which proxied port a connection line is about. +#[derive(Debug, PartialEq)] +pub enum PortKey<'a> { + /// By its route (TCP connections that reached it). + Route(&'a str), + /// By where the proxy listens for it (UDP sessions, which don't name + /// their route, and TCP connections turned away before one). + Listen(u16), +} + +/// An RFC 3339 time in milliseconds. +pub fn parse_time_ms(s: &str) -> Option { + s.parse::().ok().map(|t| t.as_millisecond()) +} + +impl AccessLine { + pub fn read(l: &Value) -> Self { + // Envoy writes null for a header that wasn't there. + let s = |k: &str| l[k].as_str().unwrap_or("").to_owned(); + let n = |k: &str| { + l[k].as_u64() + .or_else(|| l[k].as_str().and_then(|v| v.parse().ok())) + .unwrap_or(0) + }; + AccessLine { + host: s("host"), + ts_ms: l["start_time"].as_str().and_then(parse_time_ms), + peer: s("peer"), + forwarded_for: s("x_forwarded_for"), + real_ip: s("x_real_ip"), + user_agent: s("user_agent"), + status: n("status"), + method: s("method"), + path: s("path"), + content_type: s("content_type"), + referer: s("referer"), + duration_ms: l["duration_ms"] + .as_f64() + .or_else(|| l["duration_ms"].as_str().and_then(|v| v.parse().ok())) + .unwrap_or(0.0), + bytes: n("bytes"), + node: s("PyoNode"), + remote: s("remote"), + bytes_in: n("bytes_in"), + upstream: s("upstream"), + upstream_host: s("upstream_host"), + local_port: n("local_port"), + flags: s("flags"), + termination: s("termination"), + details: s("details"), + } + } + + /// The visitor: the address the proxy placed them at (a PROXY protocol + /// header's, else the connection's), as its firewall and rate limits + /// see them; the TCP peer for lines without it. Never X-Forwarded-For + /// or X-Real-Ip: whoever reaches the proxy could write any address there + /// (`client_policy_spec`). + pub fn visitor_ip(&self) -> &str { + if self.remote.is_empty() { + &self.peer + } else { + &self.remote + } + } + + /// A connection to a public TCP or UDP port (no HTTP request in it): its + /// protocol and which port. TCP connections name their route + /// (`tcproute/pyo-gateway//rule/`); UDP sessions don't, but go + /// somewhere (`upstream_host`); a TCP connection the limit turned away + /// has neither. + pub fn port_key(&self) -> Option<(&'static str, PortKey<'_>)> { + if !self.method.is_empty() || !self.host.is_empty() { + return None; + } + if let Some(rest) = self + .upstream + .strip_prefix("tcproute/") + .or_else(|| self.upstream.strip_prefix("udproute/")) + { + let proto = if self.upstream.starts_with("tcp") { "TCP" } else { "UDP" }; + // //rule/ + let route = rest.split('/').nth(1)?; + return Some((proto, PortKey::Route(route))); + } + let port = u16::try_from(self.local_port).ok().filter(|p| *p > 0)?; + if !self.upstream.is_empty() { + return None; + } + Some(( + if self.upstream_host.is_empty() { "TCP" } else { "UDP" }, + PortKey::Listen(port), + )) + } + + /// How a connection went: "ok", "blocked" (an IP rule), "limited" (the + /// connection limit) or "unreachable" (the service didn't answer). + pub fn outcome(&self) -> &'static str { + let t = self.termination.to_ascii_lowercase(); + let f = self.flags.as_str(); + if t.contains("rbac") { + "blocked" + } else if t.contains("limit") + || f.contains("UO") + || f.contains("OL") + || (self.upstream.is_empty() && self.upstream_host.is_empty()) + { + "limited" + } else if ["UF", "UH", "URX", "NR", "UMSDR"] + .iter() + .any(|x| f.split(',').any(|y| y == *x)) + { + "unreachable" + } else { + "ok" + } + } +} + +/// A port's key in the totals and the context: its route's name, or +/// "/". +pub fn port_key_string(proto: &str, key: &PortKey<'_>) -> String { + match key { + PortKey::Route(r) => (*r).to_owned(), + PortKey::Listen(p) => format!("{proto}/{p}"), + } +} + +// ── Sketches ──────────────────────────────────────────────────────────────── + +/// HyperLogLog precision: 2^11 registers, about 2.3% error. Registers are +/// kept sparse (only the ones set) and merge by taking the larger, so +/// minutes add up to hours and hours to months without counting a visitor +/// twice (ClickHouse's `maxMap`). +pub const HLL_P: u32 = 11; +pub const HLL_M: usize = 1 << HLL_P; + +/// A visitor hash's register and its value (the leading zeros after the +/// register bits, plus one). +pub fn hll_register(hash: u64) -> (u16, u8) { + let idx = (hash >> (64 - HLL_P)) as u16; + let rest = hash << HLL_P; + let rank = (rest.leading_zeros().min(64 - HLL_P) + 1) as u8; + (idx, rank) +} + +/// Sparse HyperLogLog registers (register -> value). +pub type Hll = BTreeMap; + +pub fn hll_insert(h: &mut Hll, hash: u64) { + let (i, r) = hll_register(hash); + let e = h.entry(i).or_insert(0); + if r > *e { + *e = r; + } +} + +pub fn hll_merge(into: &mut Hll, from: &Hll) { + for (i, r) in from { + let e = into.entry(*i).or_insert(0); + if r > e { + *e = *r; + } + } +} + +/// How many distinct hashes the registers saw (HyperLogLog's estimate, +/// linear counting while most registers are empty). Pyo's queries work +/// out the same in SQL (`hll_sql`). +pub fn hll_estimate(h: &Hll) -> f64 { + let m = HLL_M as f64; + let set: Vec = h.values().copied().filter(|v| *v > 0).collect(); + let zeros = m - set.len() as f64; + let sum = zeros + set.iter().map(|v| 2f64.powi(-(*v as i32))).sum::(); + let alpha = 0.7213 / (1.0 + 1.079 / m); + let e = alpha * m * m / sum; + if e <= 2.5 * m && zeros > 0.0 { + m * (m / zeros).ln() + } else { + e + } +} + +/// The same estimate in ClickHouse SQL, for a `Map(UInt16, UInt8)` +/// expression of merged registers. +pub fn hll_sql(registers: &str) -> String { + let m = HLL_M; + let r = registers; + let e = format!( + "({m} * {m} * (0.7213 / (1 + 1.079 / {m})) / (({m} - length({r})) + arraySum(x -> pow(2, -toInt32(x)), mapValues({r}))))" + ); + format!("if({e} <= 2.5 * {m} AND length({r}) < {m}, {m} * log({m} / ({m} - length({r}))), {e})") +} + +/// Response time buckets: 0 for under a millisecond, then each 25% longer +/// than the one before, up to about 15 minutes. +pub const LATENCY_GROWTH: f64 = 1.25; +pub const LATENCY_BUCKETS: u16 = 62; + +pub fn latency_bucket(ms: f64) -> u16 { + if ms.is_nan() || ms < 1.0 { + return 0; + } + ((ms.ln() / LATENCY_GROWTH.ln()).floor() as i64 + 1).clamp(1, LATENCY_BUCKETS as i64) as u16 +} + +/// A bucket's time in milliseconds: the middle of its range (geometric). +pub fn latency_of(bucket: u16) -> f64 { + if bucket == 0 { + return 0.5; + } + let lo = LATENCY_GROWTH.powi(bucket as i32 - 1); + lo * LATENCY_GROWTH.sqrt() +} + +/// A quantile (0..1) of a histogram (bucket -> count), in milliseconds. +pub fn latency_quantile(hist: &BTreeMap, q: f64) -> f64 { + let total: u64 = hist.values().sum(); + if total == 0 { + return 0.0; + } + let want = (q * total as f64).ceil().max(1.0) as u64; + let mut seen = 0; + for (b, n) in hist { + seen += n; + if seen >= want { + return latency_of(*b); + } + } + hist.keys().last().map(|b| latency_of(*b)).unwrap_or(0.0) +} + +/// The top keys of a stream with bounded memory (Space-Saving): at most +/// `cap` keys are counted; a new key takes the place of the smallest, +/// starting from its count. Keys that matter keep their exact counts. +#[derive(Debug, Clone)] +pub struct TopK { + cap: usize, + counts: HashMap, +} + +impl TopK { + pub fn new(cap: usize) -> Self { + TopK { cap: cap.max(1), counts: HashMap::new() } + } + + pub fn add(&mut self, key: &str, n: u64) { + if let Some(c) = self.counts.get_mut(key) { + *c += n; + return; + } + if self.counts.len() < self.cap { + self.counts.insert(key.to_owned(), n); + return; + } + let Some((min_key, min)) = self + .counts + .iter() + .min_by_key(|(_, c)| **c) + .map(|(k, c)| (k.clone(), *c)) + else { + return; + }; + self.counts.remove(&min_key); + self.counts.insert(key.to_owned(), min + n); + } + + /// The `n` largest, as a map. + pub fn top(&self, n: usize) -> BTreeMap { + let mut v: Vec<(&String, &u64)> = self.counts.iter().collect(); + v.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0))); + v.into_iter().take(n).map(|(k, c)| (k.clone(), *c)).collect() + } + + pub fn len(&self) -> usize { + self.counts.len() + } + + pub fn is_empty(&self) -> bool { + self.counts.is_empty() + } +} + +// ── Totals (cluster -> Pyo) ───────────────────────────────────────────────── + +/// One host's website traffic in one minute. Maps add up across minutes +/// (ClickHouse's `sumMap`), `visitors` and `wafVisitors` merge as +/// HyperLogLogs (`maxMap`). +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct HostTotals { + /// The minute's start, in seconds since 1970. + pub minute: i64, + pub host: String, + pub requests: u64, + pub pageviews: u64, + pub bytes: u64, + /// 5xx answers. + pub errors: u64, + /// All requests' time, for averages. + pub duration_ms: f64, + /// "2xx".."5xx" (and "1xx", "0xx" for none) -> requests. + pub statuses: BTreeMap, + pub methods: BTreeMap, + /// Response time bucket (`latency_bucket`) -> requests. + pub latency: BTreeMap, + pub visitors: Hll, + /// Country code ("" unknown) -> requests. + pub countries: BTreeMap, + /// Top paths -> requests. + pub paths: BTreeMap, + /// Top page URLs (redacted) -> page views. + pub pages: BTreeMap, + /// Top referring sites -> page views ("Direct" for none). + pub referrers: BTreeMap, + pub devices: BTreeMap, + pub browsers: BTreeMap, + /// Top query parameter names -> requests (values never). + pub params: BTreeMap, + /// The server that answered -> requests, 5xx answers. + pub servers: BTreeMap, + pub server_errors: BTreeMap, + /// "|" -> requests. + pub server_latency: BTreeMap, + /// The firewall's refusals: rule (or "blocked", "rate-limit", "cdn") + /// -> requests, by country and top paths. + pub blocked: BTreeMap, + pub blocked_countries: BTreeMap, + pub blocked_paths: BTreeMap, + /// The WAF's findings: rule number -> requests it blocked, or only + /// logged; "b:" or "l:" by country and top paths. + pub waf_blocked: BTreeMap, + pub waf_logged: BTreeMap, + pub waf_countries: BTreeMap, + pub waf_paths: BTreeMap, + pub waf_visitors: Hll, +} + +/// One proxied TCP or UDP port's connections in one minute. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct PortTotals { + pub minute: i64, + /// The route's name, or "/" (`port_key_string`). + pub key: String, + pub protocol: String, + pub connections: u64, + pub bytes_in: u64, + pub bytes_out: u64, + /// Duration bucket -> connections. + pub duration: BTreeMap, + /// "ok", "blocked", "limited", "unreachable" -> connections. + pub outcomes: BTreeMap, + pub countries: BTreeMap, + pub visitors: Hll, + /// Rule -> connections the firewall refused, and by country. + pub blocked: BTreeMap, + pub blocked_countries: BTreeMap, +} + +/// What a cluster sends: its finished minutes, and the WAF's rule +/// messages seen in them (rule number -> message). +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct TotalsBatch { + /// The batch's id, so Pyo stores a batch sent twice once. + pub id: String, + pub hosts: Vec, + pub ports: Vec, + pub waf_messages: BTreeMap, +} + +// ── What a cluster needs from Pyo ─────────────────────────────────────────── + +/// Pyo's view of a cluster's traffic, sent to its traffic store: which +/// hosts and ports are services' (other traffic isn't kept), each +/// service's firewall (to name the rule behind a refusal), and how much is +/// kept. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct TrafficContext { + /// Host -> service id. + pub hosts: BTreeMap, + /// Port key (`port_key_string`) -> (service id, public port). + pub ports: BTreeMap, + /// Service id -> its firewall. + pub firewalls: BTreeMap, + /// The installation's IP setting: "none", "anonymized" or "full". + pub ip_mode: String, + /// The team's limits on what's kept here. + pub max_mb: u64, + pub max_days: u32, +} + +/// What's kept by default: 1 GB or 7 days, whichever comes first. +pub const DEFAULT_MAX_MB: u64 = 1024; +pub const DEFAULT_MAX_DAYS: u32 = 7; +/// The team setting's bounds. +pub const MAX_MB_RANGE: (u64, u64) = (100, 20 * 1024); +pub const MAX_DAYS_RANGE: (u32, u32) = (1, 31); + +/// A team's limits (`preferences.requestLogs`), within bounds. +pub fn limits_from(prefs: &Value) -> (u64, u32) { + let r = &prefs["requestLogs"]; + let mb = r["maxMb"] + .as_u64() + .unwrap_or(DEFAULT_MAX_MB) + .clamp(MAX_MB_RANGE.0, MAX_MB_RANGE.1); + let days = r["maxDays"] + .as_u64() + .map(|d| d as u32) + .unwrap_or(DEFAULT_MAX_DAYS) + .clamp(MAX_DAYS_RANGE.0, MAX_DAYS_RANGE.1); + (mb, days) +} + +// ── Kept requests and queries (Pyo -> cluster) ────────────────────────────── + +/// One request as the cluster keeps it. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct RequestRow { + pub at: i64, + pub host: String, + pub method: String, + pub path: String, + /// The path and query, sensitive values redacted. + pub url: String, + pub status: u16, + pub duration_ms: f64, + pub bytes: u64, + pub country: String, + pub referrer: String, + pub device: String, + pub browser: String, + /// As the IP setting keeps it ("" for none). + pub ip: String, + pub user_agent: String, + pub server: String, + /// The firewall rule that refused it ("" when it got through). + pub blocked_by: String, + /// The WAF blocked it. + pub waf: bool, +} + +/// One connection to a proxied port. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct ConnectionRow { + pub at: i64, + pub key: String, + pub service_id: String, + pub port: u16, + pub protocol: String, + pub ip: String, + pub country: String, + pub duration_ms: f64, + pub bytes_in: u64, + pub bytes_out: u64, + pub outcome: String, + pub rule: String, + pub server: String, +} + +/// One WAF finding. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct WafRow { + pub at: i64, + pub host: String, + pub method: String, + pub path: String, + pub url: String, + pub ip: String, + pub country: String, + pub blocked: bool, + pub rules: Vec, + pub messages: Vec, + pub severity: String, + pub server: String, +} + +/// Which kept rows Pyo asks a cluster for: newest first, before +/// `before_ms`, back to `since_ms`. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct TrafficQuery { + /// "requests", "connections" or "waf" (not `kind`: that's the + /// command's tag). + pub rows: String, + /// Requests and WAF findings: only these hosts. + pub hosts: Vec, + /// Connections: only these port keys. + pub ports: Vec, + pub since_ms: i64, + pub before_ms: i64, + pub limit: u32, + /// "1xx".."5xx". + pub status: Option, + pub method: Option, + /// Paths starting with this. + pub path: Option, + /// Text in the host or URL (any case). + pub q: Option, + /// Requests the firewall refused only. + pub blocked: bool, + /// Connections that ended so ("blocked", …). + pub outcome: Option, +} + +/// A cluster's answer: rows (newest first), and whether there are older +/// ones (`more`). +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct TrafficAnswer { + pub rows: Vec, + pub more: bool, + /// The oldest time the cluster still keeps (ms), when it has any. + pub kept_since: Option, + /// It stopped reading before the end of the range (too much to read + /// in one go); the rows are still the newest that match. + pub partial: bool, +} + +impl TrafficQuery { + pub fn limit(&self) -> usize { + self.limit.clamp(1, MAX_ROWS) as usize + } + + fn text(&self) -> Option { + self.q + .as_deref() + .map(str::trim) + .filter(|q| !q.is_empty()) + .map(|q| q.to_lowercase()) + } + + fn status_class(&self) -> Option { + self.status + .as_deref() + .and_then(|s| s.strip_suffix("xx")) + .and_then(|d| d.parse::().ok()) + .filter(|d| (1..=5).contains(d)) + } + + pub fn matches_request(&self, r: &RequestRow) -> bool { + (self.hosts.is_empty() || self.hosts.iter().any(|h| h == &r.host)) + && self.status_class().is_none_or(|c| r.status / 100 == c) + && self + .method + .as_deref() + .filter(|m| !m.is_empty()) + .is_none_or(|m| r.method.eq_ignore_ascii_case(m)) + && self + .path + .as_deref() + .filter(|p| !p.is_empty()) + .is_none_or(|p| r.path.starts_with(p)) + && (!self.blocked || !r.blocked_by.is_empty()) + && self.text().is_none_or(|q| { + r.url.to_lowercase().contains(&q) || r.host.to_lowercase().contains(&q) + }) + } + + pub fn matches_connection(&self, r: &ConnectionRow) -> bool { + (self.ports.is_empty() || self.ports.iter().any(|k| k == &r.key)) + && self + .outcome + .as_deref() + .filter(|o| !o.is_empty()) + .is_none_or(|o| r.outcome == o) + } + + pub fn matches_waf(&self, r: &WafRow) -> bool { + (self.hosts.is_empty() || self.hosts.iter().any(|h| h == &r.host)) + && self + .path + .as_deref() + .filter(|p| !p.is_empty()) + .is_none_or(|p| r.path.starts_with(p)) + && self.text().is_none_or(|q| { + r.url.to_lowercase().contains(&q) || r.host.to_lowercase().contains(&q) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// The proxy's access log, as Vector sends it: every field analytics uses + /// comes from a field the proxy writes. + #[test] + fn access_log_fields() { + let envoy = json!({ "bytes": 354, "client_ip": "203.0.113.9", "content_type": "text/html; charset=utf-8", "duration_ms": 6, "host": "shop.example.com", + "method": "GET", "path": "/x?a=1", "peer": "10.42.0.1", "referer": "https://a.example/", "start_time": "2026-11-06T12:28:32.253Z", "status": 200, + "user_agent": "Mozilla/5", "x_forwarded_for": "203.0.113.9,10.0.2.2", "x_real_ip": null, "PyoNode": "sg-1" }); + let a = AccessLine::read(&envoy); + assert_eq!( + a, + AccessLine { + host: "shop.example.com".into(), + ts_ms: Some(1793968112253), + peer: "10.42.0.1".into(), + forwarded_for: "203.0.113.9,10.0.2.2".into(), + real_ip: String::new(), + user_agent: "Mozilla/5".into(), + status: 200, + method: "GET".into(), + path: "/x?a=1".into(), + content_type: "text/html; charset=utf-8".into(), + referer: "https://a.example/".into(), + duration_ms: 6.0, + bytes: 354, + node: "sg-1".into(), + ..Default::default() + } + ); + assert_eq!(a.port_key(), None, "a website request"); + // Whatever X-Forwarded-For says, the visitor is who the proxy saw. + assert_eq!(a.visitor_ip(), "10.42.0.1"); + // Every key the proxy writes is one this reads (and the reverse). + let mut written: Vec<&str> = crate::system::ACCESS_LOG_FIELDS.iter().map(|(k, _)| *k).collect(); + written.push(crate::system::ACCESS_LOG_CONTENT_TYPE.0); + written.sort(); + let mut read = vec![ + "host", "start_time", "peer", "x_forwarded_for", "x_real_ip", "user_agent", "status", "method", "path", + "content_type", "referer", "duration_ms", "bytes", "remote", "local_port", "bytes_in", "upstream", + "upstream_host", "flags", "termination", "details", + ]; + read.sort(); + assert_eq!(written, read); + } + + #[test] + fn connection_lines() { + // Envoy's line for a TCP connection: no HTTP fields. + let tcp = AccessLine::read( + &json!({ "start_time": "2026-11-06T12:28:32.253Z", "peer": "10.0.2.2", "remote": "203.0.113.9", "local_port": "16379", "bytes": "120", "bytes_in": 64, + "duration_ms": 5012, "upstream": "tcproute/pyo-gateway/shop-cache-tcp-6379/rule/0", "flags": "-", "termination": null, "host": null, "method": null }), + ); + assert_eq!(tcp.port_key(), Some(("TCP", PortKey::Route("shop-cache-tcp-6379")))); + assert_eq!( + (tcp.bytes_in, tcp.bytes, tcp.duration_ms, tcp.remote.as_str(), tcp.outcome()), + (64, 120, 5012.0, "203.0.113.9", "ok") + ); + // As Envoy Gateway v1.9.3 logs them: a UDP session (no route named, + // after a minute without packets), and a TCP connection the limit + // turned away (nothing upstream). + let udp = AccessLine::read( + &json!({ "bytes": 123, "bytes_in": 55, "duration_ms": 60004, "flags": "-", "host": null, "local_port": 10053, "method": null, "peer": "10.0.2.2", "remote": "10.0.2.2", "status": 0, "upstream": null, "upstream_host": "10.43.152.148:53" }), + ); + assert_eq!((udp.port_key(), udp.outcome()), (Some(("UDP", PortKey::Listen(10053))), "ok")); + let limited = AccessLine::read( + &json!({ "bytes": 0, "bytes_in": 0, "duration_ms": 0, "flags": "-", "local_port": 6379, "peer": "10.0.2.2", "upstream": null, "upstream_host": null }), + ); + assert_eq!((limited.port_key(), limited.outcome()), (Some(("TCP", PortKey::Listen(6379))), "limited")); + let outcome = |flags: &str, termination: &str| { + AccessLine { + upstream: "tcproute/x/y/rule/0".into(), + flags: flags.into(), + termination: termination.into(), + ..Default::default() + } + .outcome() + }; + assert_eq!(outcome("-", "rbac_access_denied_matched_policy[deny]"), "blocked"); + assert_eq!(outcome("UF,URX", ""), "unreachable"); + assert_eq!(outcome("UO", ""), "limited"); + assert_eq!(port_key_string("UDP", &PortKey::Listen(10053)), "UDP/10053"); + assert_eq!(port_key_string("TCP", &PortKey::Route("r")), "r"); + } + + #[test] + fn visitors_are_who_the_proxy_saw() { + let line = |peer: &str, remote: &str, xff: &str, real: &str| AccessLine { + peer: peer.into(), + remote: remote.into(), + forwarded_for: xff.into(), + real_ip: real.into(), + ..Default::default() + }; + assert_eq!(line("203.0.113.7", "203.0.113.7", "1.2.3.4", "").visitor_ip(), "203.0.113.7"); + assert_eq!( + line("100.101.102.103", "100.101.102.103", "198.51.100.9", "198.51.100.10").visitor_ip(), + "100.101.102.103" + ); + assert_eq!(line("10.0.2.2", "198.51.100.9", "6.6.6.6", "").visitor_ip(), "198.51.100.9"); + assert_eq!(line("203.0.113.7", "", "6.6.6.6", "").visitor_ip(), "203.0.113.7"); + } + + #[test] + fn redacts_sensitive_values() { + let (path, url, keys, redacted) = split_url("/reset?email=a@b.c&token=xyz&page=2"); + assert_eq!(path, "/reset"); + assert_eq!(url, "/reset?email=[redacted]&token=[redacted]&page=2"); + assert_eq!(keys, vec!["email", "token", "page"]); + assert_eq!(redacted, vec!["email", "token"]); + assert_eq!(split_url("/signup?invite=abc").1, "/signup?invite=[redacted]"); + assert_eq!(split_url("/").1, "/"); + assert_eq!(split_url("/a?x").1, "/a?x"); + assert!(sensitive("X-Api_Key") && !sensitive("page")); + } + + #[test] + fn ip_masks() { + assert_eq!(mask_ip("none", "203.0.113.7"), ""); + assert_eq!(mask_ip("anonymized", "203.0.113.7"), "203.0.113.0"); + assert_eq!(mask_ip("anonymized", "2001:db8:85a3:1:2:3:4:5"), "2001:db8:85a3::"); + assert_eq!(mask_ip("full", "203.0.113.7"), "203.0.113.7"); + assert_eq!(mask_ip("full", "not-an-ip"), ""); + } + + #[test] + fn refusals() { + assert_eq!(refusal("rbac_access_denied_matched_policy[DENY]", "", 403), "blocked"); + assert_eq!(refusal("", "rbac_access_denied_matched_policy[none]", 0), "blocked"); + assert_eq!(refusal("local_rate_limited", "", 429), "rate-limit"); + assert_eq!(refusal("via_upstream", "", 403), ""); + } + + fn splitmix(mut x: u64) -> u64 { + x = x.wrapping_add(0x9e3779b97f4a7c15); + let mut z = x; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb); + z ^ (z >> 31) + } + + /// A handful of visitors reads as exact; more are within a few + /// percent; merging minutes counts a visitor once. + #[test] + fn hll_counts_and_merges() { + for n in [1u64, 7, 100, 1000, 20_000, 300_000] { + let mut h = Hll::new(); + for i in 0..n { + hll_insert(&mut h, splitmix(i)); + } + let e = hll_estimate(&h); + let err = (e - n as f64).abs() / n as f64; + let ok = if n < 100 { (e - n as f64).abs() < 1.0 } else { err < 0.05 }; + assert!(ok, "n={n} estimate={e}"); + } + // Two minutes with the same 500 visitors and 500 new ones: 1000. + let (mut a, mut b) = (Hll::new(), Hll::new()); + for i in 0..500 { + hll_insert(&mut a, splitmix(i)); + hll_insert(&mut b, splitmix(i)); + hll_insert(&mut b, splitmix(10_000 + i)); + } + hll_merge(&mut a, &b); + assert!((hll_estimate(&a) - 1000.0).abs() < 30.0, "{}", hll_estimate(&a)); + assert_eq!(hll_estimate(&Hll::new()), 0.0); + // A register's value is its leading zeros plus one, at most 54. + assert_eq!(hll_register(0), (0, 54)); + assert_eq!(hll_register(u64::MAX), (2047, 1)); + } + + #[test] + fn latency_quantiles() { + assert_eq!(latency_bucket(0.2), 0); + assert_eq!(latency_bucket(f64::NAN), 0); + assert_eq!(latency_bucket(1.0), 1); + assert_eq!(latency_bucket(1e12), LATENCY_BUCKETS); + let mut h = BTreeMap::new(); + for ms in 1..=1000 { + *h.entry(latency_bucket(ms as f64)).or_insert(0) += 1; + } + for (q, want) in [(0.5, 500.0), (0.95, 950.0), (0.99, 990.0)] { + let got = latency_quantile(&h, q); + assert!((got - want).abs() / want < 0.13, "q={q} got={got}"); + } + assert_eq!(latency_quantile(&BTreeMap::new(), 0.5), 0.0); + } + + #[test] + fn top_k_keeps_the_heavy_keys() { + let mut t = TopK::new(10); + for i in 0..1000 { + t.add("/", 1); + if i % 2 == 0 { + t.add("/about", 1); + } + t.add(&format!("/noise/{i}"), 1); + } + let top = t.top(2); + assert_eq!(top.keys().collect::>(), ["/", "/about"]); + assert_eq!(top["/"], 1000); + assert_eq!(top["/about"], 500); + assert_eq!(t.len(), 10); + } + + #[test] + fn team_limits() { + assert_eq!(limits_from(&json!({})), (DEFAULT_MAX_MB, DEFAULT_MAX_DAYS)); + assert_eq!(limits_from(&json!({ "requestLogs": { "maxMb": 5, "maxDays": 90 } })), (100, 31)); + assert_eq!(limits_from(&json!({ "requestLogs": { "maxMb": 2048, "maxDays": 3 } })), (2048, 3)); + } + + /// The query rides in a command tagged by `kind`. + #[test] + fn a_query_is_a_command() { + let q = TrafficQuery { rows: "waf".into(), hosts: vec!["a.example".into()], limit: 5, ..Default::default() }; + let c = crate::Command::QueryTraffic(Box::new(q.clone())); + let v = serde_json::to_value(&c).unwrap(); + assert_eq!((v["kind"].as_str(), v["rows"].as_str()), (Some("query_traffic"), Some("waf"))); + let back: crate::Command = serde_json::from_value(v).unwrap(); + assert!(matches!(back, crate::Command::QueryTraffic(b) if *b == q)); + } + + #[test] + fn query_filters() { + let r = RequestRow { + host: "shop.example.com".into(), + method: "POST".into(), + path: "/api/cart".into(), + url: "/api/cart?id=1".into(), + status: 503, + ..Default::default() + }; + let q = |v: Value| serde_json::from_value::(v).unwrap(); + assert!(q(json!({ "rows": "requests" })).matches_request(&r)); + assert!(q(json!({ "hosts": ["shop.example.com"], "status": "5xx", "method": "post", "path": "/api" })).matches_request(&r)); + assert!(!q(json!({ "hosts": ["other.example.com"] })).matches_request(&r)); + assert!(!q(json!({ "status": "2xx" })).matches_request(&r)); + assert!(!q(json!({ "path": "/cart" })).matches_request(&r)); + assert!(q(json!({ "q": "CART?ID" })).matches_request(&r)); + assert!(!q(json!({ "blocked": true })).matches_request(&r)); + assert_eq!(q(json!({ "limit": 9000 })).limit(), MAX_ROWS as usize); + assert_eq!(q(json!({})).limit(), 1); + } +} diff --git a/crates/pyo-sandbox/Cargo.toml b/crates/pyo-sandbox/Cargo.toml index c2445247..49371151 100644 --- a/crates/pyo-sandbox/Cargo.toml +++ b/crates/pyo-sandbox/Cargo.toml @@ -16,7 +16,7 @@ http-body-util = "0.1.5" hyper = { version = "1.12.0", features = ["client", "http1", "server"] } hyper-util = { version = "0.1.21", features = ["tokio"] } libc = "0.2.191" -pyo-proto = { version = "0.4.5", path = "../pyo-proto", features = ["sandbox-token"] } +pyo-proto = { version = "0.5.0", path = "../pyo-proto", features = ["sandbox-token"] } serde.workspace = true serde_json.workspace = true tokio.workspace = true diff --git a/crates/pyo-static/Cargo.toml b/crates/pyo-static/Cargo.toml index 31273f70..3f8c4de4 100644 --- a/crates/pyo-static/Cargo.toml +++ b/crates/pyo-static/Cargo.toml @@ -10,8 +10,9 @@ publish.workspace = true anyhow.workspace = true axum = { version = "0.8.9", default-features = false, features = ["http1", "tokio", "json"] } futures.workspace = true +base64 = "0.23.1" hex = "0.4.3" -pyo-proto = { version = "0.4.5", path = "../pyo-proto" } +pyo-proto = { version = "0.5.0", path = "../pyo-proto", features = ["command-signing"] } reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls", "stream"] } serde.workspace = true serde_json.workspace = true diff --git a/crates/pyo-static/src/cache.rs b/crates/pyo-static/src/cache.rs index 64608fbc..b1404823 100644 --- a/crates/pyo-static/src/cache.rs +++ b/crates/pyo-static/src/cache.rs @@ -67,6 +67,14 @@ impl Deploy { } } +/// How pyo-static proves who it is to Pyo. +enum Login { + /// Its key id and PKCS#8 key (standard base64): every request signed. + Key(String, String), + /// The cluster's token, from an agent that gives it no key (older). + Token(String), +} + pub struct Cache { dir: PathBuf, login: PathBuf, @@ -131,17 +139,22 @@ impl Cache { }) } - /// Pyo's address and the token, from the login Secret (re-read each - /// time: it can change while the server runs). - fn login(&self) -> anyhow::Result<(String, String)> { + /// Pyo's address and how to prove who this is, from the login Secret + /// (re-read each time: it can change while the server runs). + fn login(&self) -> anyhow::Result<(String, Login)> { let read = |k: &str| { std::fs::read_to_string(self.login.join(k)) .map(|s| s.trim().to_owned()) .ok() .filter(|s| !s.is_empty()) }; - match (read("url"), read("token")) { - (Some(u), Some(t)) => Ok((u.trim_end_matches('/').to_owned(), t)), + let Some(url) = read("url") else { + bail!("no login to Pyo yet (the pyo-static-login Secret is empty)"); + }; + let url = url.trim_end_matches('/').to_owned(); + match (read("key-id"), read("key"), read("token")) { + (Some(id), Some(key), _) => Ok((url, Login::Key(id, key))), + (_, _, Some(t)) => Ok((url, Login::Token(t))), _ => bail!("no login to Pyo yet (the pyo-static-login Secret is empty)"), } } @@ -158,14 +171,30 @@ impl Cache { } async fn get(&self, path: &str) -> anyhow::Result { - let (url, token) = self.login()?; - let res = self - .http - .get(format!("{url}/api/static/v1/{path}")) - .bearer_auth(token) - .timeout(Duration::from_secs(300)) - .send() - .await?; + let (url, login) = self.login()?; + let full = format!("{url}/api/static/v1/{path}"); + let mut req = self.http.get(&full).timeout(Duration::from_secs(300)); + req = match login { + // Signed with its own key (pyo-proto `agentauth`), made by the + // agent in this cluster. + Login::Key(id, key) => { + use base64::Engine as _; + let pkcs8 = base64::engine::general_purpose::STANDARD + .decode(key) + .map_err(|_| anyhow::anyhow!("the login's key isn't base64"))?; + let key = pyo_proto::agentauth::RequestKey::from_pkcs8(&pkcs8).map_err(anyhow::Error::msg)?; + let u = reqwest::Url::parse(&full)?; + let signed = match u.query() { + Some(q) => format!("{}?{q}", u.path()), + None => u.path().to_owned(), + }; + key.sign(&id, "GET", &signed, b"", pyo_proto::now_ms() / 1000) + .into_iter() + .fold(req, |r, (k, v)| r.header(k, v)) + } + Login::Token(t) => req.bearer_auth(t), + }; + let res = req.send().await?; if !res.status().is_success() { bail!("Pyo answered {}", res.status()); } diff --git a/dash/scripts/domain-state.test.ts b/dash/scripts/domain-state.test.ts new file mode 100644 index 00000000..daef47cb --- /dev/null +++ b/dash/scripts/domain-state.test.ts @@ -0,0 +1,41 @@ +// A domain's one status label. +// bun test dash/scripts/domain-state.test.ts +import { expect, test } from "bun:test"; +import { domainState } from "../src/components/pyo/DomainState"; +import type { Domain } from "../src/lib/pyo/types"; + +const domain = (hostname: string, d: Partial = {}): Domain => ({ + id: "dom_1", + hostname, + portName: "http", + status: "pending_dns", + tls: "pending", + tlsMode: "auto", + redirectHttps: true, + createdAt: 1, + ...d, +}); + +test("a tailnet domain is set up, not waiting for DNS", () => { + expect(domainState(domain("blog.tail1.ts.net"), [])).toEqual({ + tone: "busy", + text: "Setting up on Tailscale…", + }); + expect( + domainState( + domain("blog.tail1.ts.net", { status: "error", error: "Taken on your tailnet" }), + [], + ), + ).toEqual({ tone: "broken", text: "Tailscale failed", hint: "Taken on your tailnet" }); + expect( + domainState(domain("blog.tail1.ts.net", { status: "active" }), []).text, + ).toBe("Issuing certificate…"); + expect( + domainState(domain("blog.tail1.ts.net", { status: "active", tls: "issued" }), []), + ).toEqual({ tone: "ok", text: "HTTPS", hint: "Tailscale certificate" }); +}); + +test("other domains still wait for DNS", () => { + expect(domainState(domain("app.203.0.113.7.nip.io"), []).text).toBe("Checking DNS…"); + expect(domainState(domain("shop.example.com"), []).text).toBe("Waiting for DNS"); +}); diff --git a/dash/src/components/auth/AuthForm.tsx b/dash/src/components/auth/AuthForm.tsx index a21304e8..c2eca3e7 100644 --- a/dash/src/components/auth/AuthForm.tsx +++ b/dash/src/components/auth/AuthForm.tsx @@ -3,7 +3,7 @@ import { ArrowRightIcon, FingerprintIcon } from "@phosphor-icons/react"; import { Link } from "@tanstack/react-router"; import { type FormEvent, useEffect, useRef, useState } from "react"; import { site } from "~/config/site"; -import { auth } from "~/lib/pyo/backend"; +import { auth, needsCode } from "~/lib/pyo/backend"; import { passkeyAutofillSupported, passkeyCancelled, @@ -14,6 +14,7 @@ import type { User } from "~/lib/pyo/types"; import { safeNextPath } from "~/lib/validation"; import { Alert } from "../ui/Alert"; import { Button } from "../ui/Button"; +import { CodeStep } from "./CodeStep"; export const labelClass = "mb-1.5 block text-[12.5px] font-medium text-foreground"; @@ -44,6 +45,8 @@ export function AuthForm({ const [signupOpen, setSignupOpen] = useState(true); const [canReset, setCanReset] = useState(false); const [canPasskey, setCanPasskey] = useState(false); + /** The password was right and two-factor is on: the code comes next. */ + const [challenge, setChallenge] = useState(null); const autofill = useRef(null); useEffect(() => { @@ -118,16 +121,34 @@ export function AuthForm({ setLoading(true); setError(""); try { - const user = signup + const res = signup ? await auth.signup(name.trim(), address, password, invite) : await auth.login(address, password); - done(user); + if (needsCode(res)) { + setChallenge(res.challenge); + setLoading(false); + return; + } + done(res); } catch (e) { setError(e instanceof Error ? e.message : "That didn't work. Try again."); setLoading(false); } } + if (challenge) + return ( + { + setChallenge(null); + setPassword(""); + setError(why); + }} + /> + ); + return ( <>
diff --git a/dash/src/components/auth/CodeStep.tsx b/dash/src/components/auth/CodeStep.tsx new file mode 100644 index 00000000..d125170e --- /dev/null +++ b/dash/src/components/auth/CodeStep.tsx @@ -0,0 +1,112 @@ +import { ArrowRightIcon } from "@phosphor-icons/react"; +import { type FormEvent, useState } from "react"; +import { auth } from "~/lib/pyo/backend"; +import type { User } from "~/lib/pyo/types"; +import { Alert } from "../ui/Alert"; +import { Button } from "../ui/Button"; +import { inputClass, labelClass } from "./AuthForm"; + +/** + * Signing in with two-factor on: after the password (or a sign-in link), + * a code from the authenticator app, or one of the recovery codes. + */ +export function CodeStep({ + challenge, + onDone, + onRestart, +}: { + challenge: string; + onDone: (user: User) => void; + /** The sign-in timed out or ran out of tries: start over, saying why. */ + onRestart: (why: string) => void; +}) { + const [recovery, setRecovery] = useState(false); + const [code, setCode] = useState(""); + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + + async function submit(event: FormEvent) { + event.preventDefault(); + const value = code.trim(); + if (!value) + return setError(recovery ? "Enter a recovery code." : "Enter the code."); + setLoading(true); + setError(""); + try { + onDone(await auth.loginCode(challenge, value)); + } catch (e) { + const message = + e instanceof Error ? e.message : "That didn't work. Try again."; + if (/sign in again/i.test(message)) return onRestart(message); + setError(message); + setCode(""); + setLoading(false); + } + } + + return ( + <> +
+

+ Two-factor authentication +

+

+ {recovery + ? "Enter one of your recovery codes." + : "Enter the code from your authenticator app."} +

+
+
+
+ + + setCode( + recovery + ? e.target.value + : e.target.value.replace(/\D/g, "").slice(0, 6), + ) + } + placeholder={recovery ? "xxxxx-xxxxx" : "000000"} + inputMode={recovery ? "text" : "numeric"} + autoComplete="one-time-code" + autoCapitalize="off" + spellCheck={false} + autoFocus + /> +
+ {error ? {error} : null} + +
+

+ +

+ + ); +} diff --git a/dash/src/components/auth/RecoveryForms.tsx b/dash/src/components/auth/RecoveryForms.tsx index 30f847a0..04ca1722 100644 --- a/dash/src/components/auth/RecoveryForms.tsx +++ b/dash/src/components/auth/RecoveryForms.tsx @@ -1,10 +1,12 @@ import { ArrowRightIcon } from "@phosphor-icons/react"; import { Link } from "@tanstack/react-router"; import { type FormEvent, useEffect, useState } from "react"; -import { auth } from "~/lib/pyo/backend"; +import { auth, needsCode } from "~/lib/pyo/backend"; +import type { User } from "~/lib/pyo/types"; import { Alert } from "../ui/Alert"; import { Button } from "../ui/Button"; import { inputClass, labelClass } from "./AuthForm"; +import { CodeStep } from "./CodeStep"; function Heading({ title, sub }: { title: string; sub: string }) { return ( @@ -94,6 +96,10 @@ export function ForgotForm() { ); } +function signedIn(user: User) { + window.location.assign(user.mustSetUp ? "/setup" : "/"); +} + /** A sign-in link: choose a new password, then on into Pyo. */ export function ResetForm({ token }: { token: string }) { const [email, setEmail] = useState(null); @@ -101,6 +107,8 @@ export function ResetForm({ token }: { token: string }) { const [error, setError] = useState(""); const [dead, setDead] = useState(""); const [loading, setLoading] = useState(false); + /** Two-factor is on: the new password is saved, a code signs in. */ + const [challenge, setChallenge] = useState(null); useEffect(() => { if (!token) { @@ -122,14 +130,25 @@ export function ResetForm({ token }: { token: string }) { setLoading(true); setError(""); try { - const user = await auth.resetPassword(token, password); - window.location.assign(user.mustSetUp ? "/setup" : "/"); + const res = await auth.resetPassword(token, password); + if (needsCode(res)) return setChallenge(res.challenge); + signedIn(res); } catch (e) { setError(e instanceof Error ? e.message : "That didn't work. Try again."); setLoading(false); } } + if (challenge) + return ( + window.location.assign("/login")} + /> + ); + if (dead) return ( <> diff --git a/dash/src/components/pyo/AddDomainDialog.tsx b/dash/src/components/pyo/AddDomainDialog.tsx index f1c2e52f..0ee9ecf2 100644 --- a/dash/src/components/pyo/AddDomainDialog.tsx +++ b/dash/src/components/pyo/AddDomainDialog.tsx @@ -11,6 +11,8 @@ import { useCloudflareFor, type CloudflareChoice, } from "~/components/pyo/Cloudflare"; +import { SetUpTailscaleLink } from "~/components/pyo/Tailscale"; +import { AppLink } from "~/components/ui/AppLink"; import { Button } from "~/components/ui/Button"; import { Dialog } from "~/components/ui/Dialog"; import { @@ -24,22 +26,24 @@ import { import { HOSTNAME } from "~/lib/pyo/format"; import { clusterTailnet, - freeDomainIp, - freeHostname, - tailnetHostname, + hostnameUsed, + unusedHostname, } from "~/lib/pyo/freeDomain"; import { api, servicesIn, usePyo } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; import type { Application, TlsMode } from "~/lib/pyo/types"; -/** Your own domain (a DNS record to make), or a free one: nip.io or the tailnet. */ +/** + * Your own domain (a DNS record to make), a free one on nip.io at the + * cluster's public IP, or a private one on the tailnet (Tailscale). + */ type Kind = "own" | "public" | "tailnet"; /** One DNS label. */ const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/; /** - * Add a domain: your own or a free one, its hostname, the service it routes to (asked when it isn't + * Add a domain: your own, a free one 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. */ @@ -85,23 +89,28 @@ export function AddDomainDialog({ }); const port = portName || httpPorts[0]?.name || ""; const cluster = s.clusters.find((c) => c.id === app?.clusterId); - const freeIp = app ? freeDomainIp(s, app.clusterId) : undefined; + // Free domains go on the public IP, whatever the cluster's free domains + // use by default: traffic goes straight to its servers. + const freeIp = cluster?.publicIp ?? undefined; const tailnet = app ? clusterTailnet(s, app.clusterId) : undefined; const namespace = s.projects.find((p) => p.id === app?.projectId)?.namespace ?? "app"; - // A free kind the picked service's cluster doesn't have: back to your own. - const k: Kind = - (kind === "public" && !freeIp) || (kind === "tailnet" && !tailnet) - ? "own" - : kind; + // Picked, but the service's cluster has none: a note says why. + const missing = + !!app && + ((kind === "public" && !freeIp) || (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 : ""; const suggested = - !app || k === "own" + !app || k === "own" || missing ? "" - : (k === "public" - ? freeHostname(app, namespace, freeIp!) - : tailnetHostname(s, app, namespace, tailnet!) + : // The first name nothing uses yet ("web-2" when "web" is). + unusedHostname( + s, + k === "public" ? `${app.name}-${namespace}` : app.name, + suffix!, ).slice(0, -suffix!.length - 1); const name = label ?? suggested; const hostname = k === "own" ? ownHost : `${name}.${suffix}`; @@ -115,18 +124,17 @@ export function AddDomainDialog({ (!hostname || covers(c, hostname)), ); const cert = matching.find((c) => c.id === certificateId) ?? matching[0]; - const taken = s.services.some((a) => - a.domains.some((d) => d.hostname === hostname), - ); - const error = - k !== "own" && !LABEL.test(name) + const taken = hostnameUsed(s, hostname); + const error = missing + ? "Pick another option." + : k !== "own" && !LABEL.test(name) ? "Use lowercase letters, digits and hyphens." : !HOSTNAME.test(hostname) ? "Enter a valid hostname, e.g. app.example.com." : !app ? "Pick the service it routes to." : taken - ? "This hostname is already routed to a service." + ? `${hostname} is already used.` : k !== "tailnet" && tlsMode === "custom" && !cert ? `Upload a certificate valid for ${hostname}, or pick another HTTPS option.` : ""; @@ -183,7 +191,7 @@ export function AddDomainDialog({ - @@ -228,183 +236,194 @@ export function AddDomainDialog({ onSelect={() => setKind("own")} /> { setKind("public"); setLabel(null); }} /> { setKind("tailnet"); setLabel(null); }} /> - - {(p) => - k === "own" ? ( - - setOwnHost(e.target.value.trim().toLowerCase()) - } - placeholder="shop.example.com" - /> + {missing && cluster ? ( +

+ {k === "tailnet" ? ( + cluster.tailscale || + (s.tailscale && s.tailscale.clusterId === cluster.id) ? ( + `${cluster.name} is still joining your tailnet.` + ) : ( + <> + Tailscale isn't set up on {cluster.name}.{" "} + + + ) + ) : cluster.publicTraffic === false ? ( + <> + Public traffic is off on {cluster.name}.{" "} + + Cluster settings + + ) : ( -

- - setLabel(e.target.value.trim().toLowerCase()) - } - spellCheck={false} - autoComplete="off" - className={`${groupInputClass} flex-1 pr-0 font-mono text-[12px]`} - /> - - .{suffix} - -
- ) - } -
- {k === "own" ? ( - - ) : null} - {httpPorts.length > 1 ? ( - - {(p) => ( - + `No public IP found on ${cluster.name} yet.` )} - +

) : null} - {k === "tailnet" ? null : ( - m.value === tlsMode)?.hint} - > - {(p) => ( - + setOwnHost(e.target.value.trim().toLowerCase()) + } + placeholder="shop.example.com" + /> + ) : ( +
+ + setLabel(e.target.value.trim().toLowerCase()) + } + spellCheck={false} + autoComplete="off" + className={`${groupInputClass} flex-1 pr-0 font-mono text-[12px]`} + /> + + .{suffix} + +
+ ) + } +
+ {k === "own" ? ( + + ) : null} + {httpPorts.length > 1 ? ( + + {(p) => ( + + )} + + ) : null} + {k === "tailnet" ? null : ( + m.value === tlsMode)?.hint} > - {TLS_MODES.map((m) => ( - - ))} - + {(p) => ( + + )} + )} - - )} - {k !== "tailnet" && tlsMode === "custom" ? ( - - Certificate - - - } - hint={ - cert - ? `${cert.hostnames.join(", ")} · ${expiry(cert).text}` - : hostname - ? `No certificate covers ${hostname} yet.` - : undefined - } - > - {(p) => ( - setCertificateId(e.target.value)} + disabled={!matching.length} + > + {matching.length ? ( + matching.map((c) => ( + + )) + ) : ( + + )} + )} - - )} - - ) : null} - {k !== "tailnet" && tlsMode !== "off" ? ( - - ) : null} + + ) : null} + {k !== "tailnet" && tlsMode !== "off" ? ( + + ) : null} + + )}

- Token shown once + Works once, for an hour {thisMachine ? null : " · "} {thisMachine ? null : ( {free && !d.domains.some((x) => x.hostname === free) ? ( ) : null} {!hasTailnet && d.clusterId ? ( @@ -1389,12 +1385,9 @@ export function DomainsStep({ d, set, errors }: StepProps) { disabled={!tailnetFree} onClick={() => add(tailnetFree)} > - Tailnet domain + Tailscale ) : null} - {free && !hasPublic ? (

@@ -1408,12 +1401,26 @@ export function DomainsStep({ d, set, errors }: StepProps) { ) : null} {tailnetFree && !hasTailnet ? (

- On your tailnet:{" "} + On Tailscale:{" "} {tailnetFree}

) : !tailnet && d.clusterId ? (

- No tailnet domain without Tailscale. + {cluster?.tailscale ? ( + "Joining your tailnet." + ) : ( + <> + Tailscale isn't set up on this cluster.{" "} + + Set up Tailscale + + + )}

) : null} @@ -1596,7 +1603,7 @@ function ServerLine({ n }: { n: ClusterServer }) { /** * Placed by tag: pick from the tags clusters and servers already have. A - * server matches when it, or its cluster, has every picked tag; the cluster + * server matches when it, or its cluster, has a picked tag; the cluster * follows the matches. */ function TagPlacement({ @@ -1621,7 +1628,7 @@ function TagPlacement({ const picked = d.serverTags; const matching = (tags: string[]) => tags.length - ? nodes.filter((n) => tags.every((t) => tagsOf(n).includes(t))) + ? nodes.filter((n) => tags.some((t) => tagsOf(n).includes(t))) : []; const matches = matching(picked); const inClusters = clusters.filter((c) => @@ -1688,11 +1695,11 @@ function TagPlacement({ {!picked.length ? (

- Runs only on servers with every tag you pick. + Runs only on servers with a tag you pick.

) : !matches.length ? (

- No server has all of these tags. Pick fewer. + No server has these tags.

) : ( <> @@ -1723,7 +1730,7 @@ function TagPlacement({ ))}

- Servers tagged later are used from its next deploy. + Servers tagged later are used too.

)} diff --git a/dash/src/components/shell/AppShell.tsx b/dash/src/components/shell/AppShell.tsx index 336d1a87..cfe56def 100644 --- a/dash/src/components/shell/AppShell.tsx +++ b/dash/src/components/shell/AppShell.tsx @@ -66,6 +66,7 @@ import { servicePath, DB_SECTION_LABEL, isDbSection, + roleIn, } from "~/lib/pyo/store"; import { TeamSwitcher } from "./TeamSwitcher"; import { CrumbSwitcher, type Switcher } from "./CrumbSwitcher"; @@ -309,6 +310,7 @@ function Sidebar({ const meta = useQuery("meta", fetchMeta); const features = meta.status === "success" ? meta.data.features : []; const s = usePyo(); + const teamAdmin = ["owner", "admin"].includes(roleIn(s) ?? ""); // A project's or service's pages (//...) count as Projects. const inProject = !!projectByRef(s, pathname.split("/").filter(Boolean)[0] ?? ""); const items = navLinks(NAV_GROUPS.flatMap((g) => g.items)); @@ -366,7 +368,7 @@ function Sidebar({ {NAV_GROUPS.map((g, i) => (
{g.label ?

{g.label}

: null} -
    {g.items.filter((it) => !it.feature || features.includes(it.feature)).map(link)}
+
    {g.items.filter((it) => (!it.feature || features.includes(it.feature)) && (!it.admin || teamAdmin)).map(link)}
))} @@ -539,6 +541,7 @@ const TAB_LABELS: Record = { members: "Members", integrations: "Integrations", notifications: "Notifications", + "audit-log": "Audit log", "api-keys": "API keys", mcp: "MCP", profile: "Profile", diff --git a/dash/src/components/shell/CrumbSwitcher.tsx b/dash/src/components/shell/CrumbSwitcher.tsx index 9a2e11e3..51494c12 100644 --- a/dash/src/components/shell/CrumbSwitcher.tsx +++ b/dash/src/components/shell/CrumbSwitcher.tsx @@ -6,7 +6,7 @@ import { databaseHref, projectPath, servicePath, - usePyo, + listedServices, usePyo, type PyoState, } from "~/lib/pyo/store"; import { databaseTabs, serviceTabs, tabPaths } from "~/lib/pyo/tabs"; @@ -45,7 +45,7 @@ function itemsFor(s: PyoState, sw: Switcher): MenuItem[] { } if (sw.kind === "service") { const projectId = s.services.find((a) => a.id === sw.id)?.projectId; - const apps = s.services.filter((a) => a.projectId === projectId); + const apps = listedServices(s).filter((a) => a.projectId === projectId); return [ { type: "label", label: "Services" }, ...apps.map((a) => ({ diff --git a/dash/src/components/shell/nav.ts b/dash/src/components/shell/nav.ts index 55d204cd..23057ae2 100644 --- a/dash/src/components/shell/nav.ts +++ b/dash/src/components/shell/nav.ts @@ -8,6 +8,7 @@ import { GaugeIcon, GlobeIcon, HammerIcon, + ListMagnifyingGlassIcon, NetworkIcon, PlugsConnectedIcon, ShieldCheckIcon, @@ -30,6 +31,8 @@ export type NavLink = { match?: string[]; /** Shown only when the API lists this feature (GET /api/v1/meta). */ feature?: string; + /** Only for the team's owners and admins. */ + admin?: boolean; }; export type NavItem = NavLink & { icon: Icon; @@ -117,8 +120,9 @@ export const NAV_GROUPS: { label?: string; items: NavItem[] }[] = [ { label: "Settings", href: "/settings", icon: SlidersHorizontalIcon, exact: true }, { label: "Members", href: "/members", icon: UsersIcon }, { label: "Notifications", href: "/notifications", icon: BellIcon }, + { label: "Audit log", href: "/audit-log", icon: ListMagnifyingGlassIcon, admin: true }, { label: "Integrations", href: "/integrations", icon: PlugsConnectedIcon }, - { label: "Billing", href: "/settings/billing", icon: CreditCardIcon, feature: "billing" }, + { label: "Billing", href: "/settings/billing", icon: CreditCardIcon, feature: "billing", admin: true }, ], }, ]; diff --git a/dash/src/components/ui/Badge.tsx b/dash/src/components/ui/Badge.tsx index cfeb041b..e0d75e1a 100644 --- a/dash/src/components/ui/Badge.tsx +++ b/dash/src/components/ui/Badge.tsx @@ -6,7 +6,6 @@ import type { DeploymentStatus, ServerStatus, TlsStatus, - VolumeStatus, WorkloadStatus, } from "~/lib/pyo/types"; @@ -214,22 +213,6 @@ export function WorkloadStatusBadge({ status }: { status: WorkloadStatus }) { ); } -export const volumeTone: Record = { - bound: "success", - pending: "progress", - degraded: "warning", - error: "danger", -}; - -export function VolumeStatusBadge({ status }: { status: VolumeStatus }) { - return ( - - ); -} - /** Marks UI that shows simulated, not real, operations. */ export function SimulatedBadge({ className = "" }: { className?: string }) { return ( diff --git a/dash/src/components/ui/Field.tsx b/dash/src/components/ui/Field.tsx index d0f2f85c..6fd31aaf 100644 --- a/dash/src/components/ui/Field.tsx +++ b/dash/src/components/ui/Field.tsx @@ -518,14 +518,16 @@ export function Checkbox({ onChange, label, disabled, + className = "", }: { checked: boolean; onChange: (v: boolean) => void; label: ReactNode; disabled?: boolean; + className?: string; }) { return ( -