VPS deploy workflow + exe-relative migrations + CORS anywhere mode
Browse files at this commitb2780eb4f9069d4f00f69a19a0dc1773a09d5265Parent: 1cdee07- feat
- VPS deploy workflow + exe-relative migrations + CORS anywhere mode
6 changed files +394 -10
- .env.example +6 -1
- .github/workflows/main.yml +266 -0
- deploy/hezarfen.service +41 -0
- src/database.rs +22 -5
- src/lib.rs +19 -4
- tests/integration.rs +40 -0
.env.examplemodified+6 -1
| @@ -25,8 +25,13 @@ RUST_LOG=info,hezarfen_backend=debug | |||
| 25 | # Comma-separated CORS allowlist for browser clients on other origins; listed | 25 | # Comma-separated CORS allowlist for browser clients on other origins; listed |
| 26 | # origins may send credentials (the session cookie). Leave unset to reflect the | 26 | # origins may send credentials (the session cookie). Leave unset to reflect the |
| 27 | # request's Origin (dev-friendly) — but without credentials, so a cookie-using | 27 | # request's Origin (dev-friendly) — but without credentials, so a cookie-using |
| 28 | -# browser frontend must be listed here explicitly. | 28 | +# browser frontend must be listed here explicitly. A lone `*` reflects every |
| 29 | +# origin WITH credentials ("anywhere, for now"): SameSite=Lax still keeps | ||
| 30 | +# third-party sites from riding the cookie cross-site, so what this opens is | ||
| 31 | +# same-site origins (your own subdomains/ports) — replace it with the real | ||
| 32 | +# origins once the frontends are known. | ||
| 29 | # CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com | 33 | # CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com |
| 34 | +# CORS_ALLOWED_ORIGINS=* | ||
| 30 | 35 | ||
| 31 | # Per-IP rate limits (requests per minute). AUTH covers /auth/login and | 36 | # Per-IP rate limits (requests per minute). AUTH covers /auth/login and |
| 32 | # /auth/register only (brute-force protection); API covers every route. | 37 | # /auth/register only (brute-force protection); API covers every route. |
.github/workflows/main.ymladded+266 -0
| @@ -0,0 +1,266 @@ | |||
| 1 | +# Deploys to the VPS on every push to main, im-style (see im's | ||
| 2 | +# .github/workflows/main.yml): the whole suite gates the deploy, the release | ||
| 3 | +# lands as one swapped directory, and the service must answer /health from | ||
| 4 | +# this build's process — or the previous release is rolled back. | ||
| 5 | +# | ||
| 6 | +# One-time prerequisites, outside the workflow's reach: | ||
| 7 | +# * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER (im's values | ||
| 8 | +# work if this deploys as the same user); | ||
| 9 | +# * `loginctl enable-linger <user>` on the server unless the deploy user | ||
| 10 | +# already has it (im's does) — user units need a running user manager; | ||
| 11 | +# * a Postgres the backend can reach, and ~/hezarfen/hezarfen.env (0600) | ||
| 12 | +# with at least DATABASE_URL — see deploy/hezarfen.service for the keys. | ||
| 13 | + | ||
| 14 | +on: | ||
| 15 | + push: | ||
| 16 | + branches: | ||
| 17 | + - main | ||
| 18 | + | ||
| 19 | +# The deploy swaps a release directory and restarts one service; two of them | ||
| 20 | +# racing would leave the binary and the running process from different builds. | ||
| 21 | +concurrency: | ||
| 22 | + group: deploy | ||
| 23 | + cancel-in-progress: false | ||
| 24 | + | ||
| 25 | +env: | ||
| 26 | + # A gnu binary links against the runner's glibc, so the runner is pinned | ||
| 27 | + # (see runs-on below) to the same 24.04 the server runs; the day either | ||
| 28 | + # side moves, the pin is what forces a conscious decision rather than a | ||
| 29 | + # broken deploy. In exchange: no cross-toolchain, and the linker is | ||
| 30 | + # rustc's default bundled lld. | ||
| 31 | + TARGET: x86_64-unknown-linux-gnu | ||
| 32 | + # The systemd user unit that owns the process. See deploy/hezarfen.service. | ||
| 33 | + SERVICE: hezarfen | ||
| 34 | + # The deploy lives in this subdirectory of the SSH user's home. The home | ||
| 35 | + # itself is resolved on the server ($HOME), so switching the deploy user | ||
| 36 | + # moves the path with it — a baked-in absolute path once kept pointing at | ||
| 37 | + # the previous user's home and failed the deploy on permissions. | ||
| 38 | + DEPLOY_SUBDIR: hezarfen | ||
| 39 | + # The unit reads its secrets from this file on the server; the deploy | ||
| 40 | + # never writes it, only checks it exists and holds DATABASE_URL. | ||
| 41 | + ENV_FILE_NAME: hezarfen.env | ||
| 42 | + # The Postgres the test suite mints its per-test databases on. Credentials | ||
| 43 | + # and port match the harness default (HEZARFEN_TEST_DATABASE_URL), so the | ||
| 44 | + # tests need no extra environment — only the server, with the raised | ||
| 45 | + # connection ceiling the parallel suite exhausts (see compose.yaml). | ||
| 46 | + PG_USER: hezarfen | ||
| 47 | + PG_PASSWORD: hezarfen | ||
| 48 | + # sqlx's compile-time macros verify every query against the committed .sqlx | ||
| 49 | + # cache, so the build must never reach for a live database (same as the | ||
| 50 | + # Containerfile). | ||
| 51 | + SQLX_OFFLINE: "true" | ||
| 52 | + | ||
| 53 | +jobs: | ||
| 54 | + deploy: | ||
| 55 | + name: Deploy | ||
| 56 | + # Pinned, not `latest`: ubuntu-latest floating to the next LTS would | ||
| 57 | + # one day ship a glibc newer than the server's, and the gnu binary | ||
| 58 | + # would stop running there. See the TARGET comment above. | ||
| 59 | + runs-on: ubuntu-24.04 | ||
| 60 | + steps: | ||
| 61 | + - name: Checkout | ||
| 62 | + uses: actions/checkout@v4 | ||
| 63 | + | ||
| 64 | + - name: Set up Rust | ||
| 65 | + run: rustup toolchain install stable --profile minimal | ||
| 66 | + | ||
| 67 | + - name: Cache cargo | ||
| 68 | + uses: Swatinem/rust-cache@v2 | ||
| 69 | + with: | ||
| 70 | + cache-all-crates: true | ||
| 71 | + # Bump when the target, the profile or any rustflags change: the | ||
| 72 | + # key does not otherwise see those, and a run that restores the | ||
| 73 | + # old key reports it up-to-date at save time — discarding the | ||
| 74 | + # recompiled dependencies and silently recompiling them on every | ||
| 75 | + # later run. | ||
| 76 | + prefix-key: v1-rust-gnu | ||
| 77 | + | ||
| 78 | + # The suite mints a control+school database pair per test; the default | ||
| 79 | + # 100-connection ceiling runs out under that, so the server gets the | ||
| 80 | + # same 500 the compose stack runs (see compose.yaml). | ||
| 81 | + - name: Start Postgres | ||
| 82 | + run: | | ||
| 83 | + docker run -d --name hezarfen-pg \ | ||
| 84 | + -e POSTGRES_USER="$PG_USER" -e POSTGRES_PASSWORD="$PG_PASSWORD" \ | ||
| 85 | + -p 127.0.0.1:5432:5432 \ | ||
| 86 | + postgres:18-alpine -c max_connections=500 | ||
| 87 | + for _ in $(seq 1 30); do | ||
| 88 | + docker exec hezarfen-pg pg_isready -U "$PG_USER" && break | ||
| 89 | + sleep 1 | ||
| 90 | + done | ||
| 91 | + docker exec hezarfen-pg pg_isready -U "$PG_USER" | ||
| 92 | + | ||
| 93 | + - name: Install cargo-nextest | ||
| 94 | + uses: taiki-e/install-action@v2 | ||
| 95 | + with: | ||
| 96 | + tool: cargo-nextest | ||
| 97 | + | ||
| 98 | + # Zero clippy warnings is a standing project rule; CI is what keeps it. | ||
| 99 | + - name: Clippy | ||
| 100 | + run: cargo clippy --all-targets --locked -- -D warnings | ||
| 101 | + | ||
| 102 | + # A broken build must never reach the server: the whole suite gates | ||
| 103 | + # the deploy (doc_sync included, so README drift blocks it too). | ||
| 104 | + - name: Test | ||
| 105 | + run: cargo nextest run | ||
| 106 | + | ||
| 107 | + - name: Build the release | ||
| 108 | + run: | | ||
| 109 | + set -euo pipefail | ||
| 110 | + cargo build --release --locked --target "$TARGET" | ||
| 111 | + mkdir -p stage | ||
| 112 | + cp "target/$TARGET/release/hezarfen_backend" stage/hezarfen_backend | ||
| 113 | + # The migrators resolve `migrations/` beside the binary when the | ||
| 114 | + # compile-time checkout path is absent (see migrations_path), so | ||
| 115 | + # the schema ships with the release it belongs to. | ||
| 116 | + cp -r migrations stage/migrations | ||
| 117 | + cp deploy/hezarfen.service stage/hezarfen.service | ||
| 118 | + strip stage/hezarfen_backend | ||
| 119 | + ls -l stage | ||
| 120 | + | ||
| 121 | + - name: Install SSH keys | ||
| 122 | + run: | | ||
| 123 | + mkdir -p ~/.ssh | ||
| 124 | + echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa | ||
| 125 | + ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts | ||
| 126 | + | ||
| 127 | + - name: Upload the release | ||
| 128 | + run: | | ||
| 129 | + set -euo pipefail | ||
| 130 | + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" | ||
| 131 | + | ||
| 132 | + # The server's login shell is not bash, and ssh would hand this | ||
| 133 | + # script to it; `bash -s` takes it on stdin instead, so the login | ||
| 134 | + # shell only ever parses one plain command. | ||
| 135 | + # | ||
| 136 | + # The deploy path is $DEPLOY_SUBDIR under the SSH user's home, | ||
| 137 | + # resolved on the server as $HOME: there is no path secret to go | ||
| 138 | + # stale, and switching the deploy user moves the deploy with it. | ||
| 139 | + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' | ||
| 140 | + set -euo pipefail | ||
| 141 | + case "$1" in | ||
| 142 | + ''|/*|*..*) | ||
| 143 | + echo "Refusing a broad deploy subdirectory: '$1'" >&2 | ||
| 144 | + exit 1 | ||
| 145 | + ;; | ||
| 146 | + esac | ||
| 147 | + deploy_path=$HOME/$1 | ||
| 148 | + # The deploy path is the service's working tree: hezarfen.env and | ||
| 149 | + # data/ live there and are never touched from here. Only 'current' | ||
| 150 | + # is replaced. | ||
| 151 | + mkdir -p -- "$deploy_path" | ||
| 152 | + rm -rf -- "$deploy_path/current.new" | ||
| 153 | + mkdir -p -- "$deploy_path/current.new" | ||
| 154 | + REMOTE | ||
| 155 | + # stdin carries the tarball, so the script cannot; the extraction | ||
| 156 | + # still goes through bash -c because the login shell is not bash | ||
| 157 | + # and would not expand $HOME. | ||
| 158 | + tar -C stage -czf - . | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1/current.new\"' -- '$DEPLOY_SUBDIR'" | ||
| 159 | + | ||
| 160 | + - name: Swap and restart | ||
| 161 | + run: | | ||
| 162 | + set -euo pipefail | ||
| 163 | + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" | ||
| 164 | + | ||
| 165 | + # bash -s for the same reason as above: the login shell is not | ||
| 166 | + # bash and must never see this script. | ||
| 167 | + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE' | ||
| 168 | + set -euo pipefail | ||
| 169 | + deploy_path=$HOME/$1 | ||
| 170 | + service=$2 | ||
| 171 | + env_file=$deploy_path/$3 | ||
| 172 | + export XDG_RUNTIME_DIR=/run/user/$(id -u) | ||
| 173 | + # Read before anything moves: the env file is the operator's, on | ||
| 174 | + # the server, written once (see deploy/hezarfen.service for the | ||
| 175 | + # keys). A missing file or a missing DATABASE_URL is a failure to | ||
| 176 | + # stop on, not one to roll back from. | ||
| 177 | + if [ ! -f "$env_file" ]; then | ||
| 178 | + echo "missing $env_file — create it (0600) with at least DATABASE_URL; see deploy/hezarfen.service" >&2 | ||
| 179 | + exit 1 | ||
| 180 | + fi | ||
| 181 | + chmod 0600 -- "$env_file" | ||
| 182 | + if ! grep -q '^DATABASE_URL=' "$env_file"; then | ||
| 183 | + echo "no DATABASE_URL in $env_file" >&2 | ||
| 184 | + exit 1 | ||
| 185 | + fi | ||
| 186 | + # The unit defaults to 8080; the env file may override. | ||
| 187 | + port=$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$env_file" | tail -n1) | ||
| 188 | + port=${port:-8080} | ||
| 189 | + mkdir -p -- "$deploy_path/data/files" | ||
| 190 | + chmod +x -- "$deploy_path/current.new/hezarfen_backend" | ||
| 191 | + rm -rf -- "$deploy_path/current.previous" | ||
| 192 | + if [ -e "$deploy_path/current" ]; then | ||
| 193 | + mv -- "$deploy_path/current" "$deploy_path/current.previous" | ||
| 194 | + fi | ||
| 195 | + mv -- "$deploy_path/current.new" "$deploy_path/current" | ||
| 196 | + # The unit ships with the release: a freshly provisioned box has | ||
| 197 | + # no unit until the first deploy writes it, and a changed unit | ||
| 198 | + # lands with the code that needs it. Enabling is idempotent. | ||
| 199 | + mkdir -p -- "$HOME/.config/systemd/user" | ||
| 200 | + install -m 644 -- "$deploy_path/current/hezarfen.service" "$HOME/.config/systemd/user/$service.service" | ||
| 201 | + systemctl --user daemon-reload | ||
| 202 | + systemctl --user enable -- "$service" | ||
| 203 | + systemctl --user restart "$service" | ||
| 204 | + # The unit is Type=simple, so a restart returns before the new | ||
| 205 | + # process has bound its port — and before an old one has let go | ||
| 206 | + # of it. Wait for the health route rather than a clock: /health | ||
| 207 | + # answers 503 (curl -f fails) while the database is unreachable, | ||
| 208 | + # so a 200 here already means status "ok". | ||
| 209 | + rollback() { | ||
| 210 | + rm -rf -- "$deploy_path/current" | ||
| 211 | + mv -- "$deploy_path/current.previous" "$deploy_path/current" | ||
| 212 | + systemctl --user restart "$service" | ||
| 213 | + } | ||
| 214 | + for _ in $(seq 1 30); do | ||
| 215 | + served=$(curl -fsS "http://127.0.0.1:$port/health" 2>/dev/null) || { sleep 1; continue; } | ||
| 216 | + # A stale process from an older deploy can answer too, so the | ||
| 217 | + # running binary must be THIS release's, or it rolls back. | ||
| 218 | + pid=$(systemctl --user show -p MainPID --value "$service") | ||
| 219 | + exe=$(readlink "/proc/$pid/exe") | ||
| 220 | + case "$exe" in | ||
| 221 | + "$deploy_path/current/hezarfen_backend") ;; | ||
| 222 | + *) | ||
| 223 | + echo "/health answered, but the process is '$exe' — not this release; rolling back" >&2 | ||
| 224 | + rollback | ||
| 225 | + exit 1 | ||
| 226 | + ;; | ||
| 227 | + esac | ||
| 228 | + echo 'hezarfen is up' | ||
| 229 | + rm -rf -- "$deploy_path/current.previous" | ||
| 230 | + exit 0 | ||
| 231 | + done | ||
| 232 | + echo 'hezarfen did not answer /health; rolling back' >&2 | ||
| 233 | + rollback | ||
| 234 | + exit 1 | ||
| 235 | + REMOTE | ||
| 236 | + | ||
| 237 | + # The independent after-the-fact check: the process answering must | ||
| 238 | + # still be this release's, and the validation contract must be served. | ||
| 239 | + - name: Verify the served API | ||
| 240 | + run: | | ||
| 241 | + set -euo pipefail | ||
| 242 | + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" | ||
| 243 | + # One remote script, im-style: mixing runner-side and server-side | ||
| 244 | + # variables in nested ssh quoting once shipped a check that failed | ||
| 245 | + # on a healthy deploy. Everything happens inside the heredoc. | ||
| 246 | + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE' | ||
| 247 | + set -euo pipefail | ||
| 248 | + deploy_path=$HOME/$1 | ||
| 249 | + service=$2 | ||
| 250 | + env_file=$deploy_path/$3 | ||
| 251 | + export XDG_RUNTIME_DIR=/run/user/$(id -u) | ||
| 252 | + port=$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$env_file" | tail -n1) | ||
| 253 | + port=${port:-8080} | ||
| 254 | + pid=$(systemctl --user show -p MainPID --value "$service") | ||
| 255 | + exe=$(readlink "/proc/$pid/exe") | ||
| 256 | + [ "$exe" = "$deploy_path/current/hezarfen_backend" ] || { | ||
| 257 | + echo "serving '$exe', not the current release" >&2 | ||
| 258 | + exit 1 | ||
| 259 | + } | ||
| 260 | + curl -fsS "http://127.0.0.1:$port/health" | grep -q '"status":"ok"' | ||
| 261 | + curl -fsS -o /dev/null "http://127.0.0.1:$port/limits" | ||
| 262 | + echo 'health ok, limits served' | ||
| 263 | + REMOTE | ||
| 264 | + | ||
| 265 | + - name: Cleaning | ||
| 266 | + run: rm -rf ~/.ssh | ||
deploy/hezarfen.serviceadded+41 -0
| @@ -0,0 +1,41 @@ | |||
| 1 | +# The systemd user unit the deploy installs to ~/.config/systemd/user/ and | ||
| 2 | +# restarts. The release layout: ~/hezarfen/current/hezarfen_backend with | ||
| 3 | +# migrations/ beside the binary (the app resolves the schema there when the | ||
| 4 | +# compile-time checkout path is absent — see migrations_path in the source). | ||
| 5 | +# | ||
| 6 | +# ~/hezarfen/hezarfen.env (0600, written once by hand, never by the deploy) | ||
| 7 | +# carries the deployment's own values and overrides the Environment= lines | ||
| 8 | +# below: | ||
| 9 | +# DATABASE_URL required — a Postgres with the control database | ||
| 10 | +# (first boot creates the schema; each school is | ||
| 11 | +# minted as its own database by the builder API) | ||
| 12 | +# BUILDER_USERNAME/PASSWORD first-boot operator seed | ||
| 13 | +# AI_QUIC_ADDR + AI_SHARED_TOKEN the AI bridge (UDP); unset = off | ||
| 14 | +# COOKIE_SECURE=true behind TLS | ||
| 15 | +# CORS_ALLOWED_ORIGINS a lone `*` reflects any origin with credentials | ||
| 16 | +# ("anywhere, for now"); list the real origins | ||
| 17 | +# once the frontends are known | ||
| 18 | +# TRUST_PROXY=true client IPs from X-Forwarded-For behind a proxy | ||
| 19 | +# | ||
| 20 | +# The service binds loopback only by default — terminate TLS on a reverse | ||
| 21 | +# proxy and forward to 127.0.0.1:8080. | ||
| 22 | + | ||
| 23 | +[Unit] | ||
| 24 | +Description=Hezarfen backend (school management API) | ||
| 25 | +After=network-online.target | ||
| 26 | +Wants=network-online.target | ||
| 27 | + | ||
| 28 | +[Service] | ||
| 29 | +Type=simple | ||
| 30 | +ExecStart=%h/hezarfen/current/hezarfen_backend | ||
| 31 | +WorkingDirectory=%h/hezarfen/current | ||
| 32 | +Environment=HOST=127.0.0.1 | ||
| 33 | +Environment=PORT=8080 | ||
| 34 | +Environment=FILES_PATH=%h/hezarfen/data/files | ||
| 35 | +Environment=RUST_LOG=info,hezarfen_backend=debug | ||
| 36 | +EnvironmentFile=%h/hezarfen/hezarfen.env | ||
| 37 | +Restart=on-failure | ||
| 38 | +RestartSec=2 | ||
| 39 | + | ||
| 40 | +[Install] | ||
| 41 | +WantedBy=default.target | ||
src/database.rsmodified+22 -5
| @@ -6,7 +6,8 @@ | |||
| 6 | //! shared rate-limit window) and `migrations/school` for every school | 6 | //! shared rate-limit window) and `migrations/school` for every school |
| 7 | //! database. They are applied by two separate [`sqlx::migrate::Migrator`]s — | 7 | //! database. They are applied by two separate [`sqlx::migrate::Migrator`]s — |
| 8 | //! the compile-time `migrate!` macro cannot be aimed at two directories, so | 8 | //! the compile-time `migrate!` macro cannot be aimed at two directories, so |
| 9 | -//! each is constructed at runtime from its path under `CARGO_MANIFEST_DIR`. | 9 | +//! each is resolved at runtime from the checkout's `CARGO_MANIFEST_DIR` or, |
| 10 | +//! for a deployed binary, from beside the executable (see [`migrations_path`]). | ||
| 10 | //! Their table names are disjoint by design, which is what lets one prepare | 11 | //! Their table names are disjoint by design, which is what lets one prepare |
| 11 | //! database carry the union for the compile-time `query!` checks. | 12 | //! database carry the union for the compile-time `query!` checks. |
| 12 | 13 | ||
| @@ -183,11 +184,27 @@ fn is_dial_error(err: &sqlx::Error) -> bool { | |||
| 183 | ) | 184 | ) |
| 184 | } | 185 | } |
| 185 | 186 | ||
| 186 | -/// The `migrations/<set>` directory under `CARGO_MANIFEST_DIR`. Two sets | 187 | +/// The `migrations/<set>` directory: the one under `CARGO_MANIFEST_DIR` (the |
| 187 | -/// cannot both feed the compile-time `migrate!` macro, so both are resolved | 188 | +/// dev/CI checkout) when that exists, else the one beside the executable. |
| 188 | -/// from their paths at runtime. | 189 | +/// Two sets cannot both feed the compile-time `migrate!` macro, so both are |
| 190 | +/// resolved from their paths at runtime — and the compile-time path is baked | ||
| 191 | +/// on the build machine, so a binary deployed outside a checkout (the release | ||
| 192 | +/// layout ships `migrations/` next to the binary) must fall back to its own | ||
| 193 | +/// directory or look for the schema where it was compiled. | ||
| 189 | fn migrations_path(set: &str) -> std::path::PathBuf { | 194 | fn migrations_path(set: &str) -> std::path::PathBuf { |
| 190 | - Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")).join(set) | 195 | + let manifest = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")).join(set); |
| 196 | + if manifest.is_dir() { | ||
| 197 | + return manifest; | ||
| 198 | + } | ||
| 199 | + if let Ok(exe) = std::env::current_exe() | ||
| 200 | + && let Some(dir) = exe.parent() | ||
| 201 | + { | ||
| 202 | + let beside = dir.join("migrations").join(set); | ||
| 203 | + if beside.is_dir() { | ||
| 204 | + return beside; | ||
| 205 | + } | ||
| 206 | + } | ||
| 207 | + manifest | ||
| 191 | } | 208 | } |
| 192 | 209 | ||
| 193 | async fn migrator(set: &str) -> Result<Migrator, AppError> { | 210 | async fn migrator(set: &str) -> Result<Migrator, AppError> { |
src/lib.rsmodified+19 -4
| @@ -505,14 +505,22 @@ fn cors_allowlist_from_env() -> Vec<HeaderValue> { | |||
| 505 | /// | 505 | /// |
| 506 | /// With no allowlist (dev) the caller's origin is mirrored, but WITHOUT | 506 | /// With no allowlist (dev) the caller's origin is mirrored, but WITHOUT |
| 507 | /// credentials: mirror + credentials would let any website ride a visitor's | 507 | /// credentials: mirror + credentials would let any website ride a visitor's |
| 508 | -/// session cookie, so the two must NEVER be recombined (the cookie's | 508 | +/// session cookie, so the two must never be recombined by default (the |
| 509 | -/// `SameSite=Lax` in `web/auth.rs` is the only other guard on that door). A | 509 | +/// cookie's `SameSite=Lax` in `web/auth.rs` is the other guard on that door). |
| 510 | -/// cross-origin dev frontend can't send the Lax cookie anyway, so credentials | 510 | +/// A cross-origin dev frontend can't send the Lax cookie anyway, so credentials |
| 511 | /// bought nothing in mirror mode; a credentialed browser frontend requires | 511 | /// bought nothing in mirror mode; a credentialed browser frontend requires |
| 512 | /// listing its origin in `CORS_ALLOWED_ORIGINS`. | 512 | /// listing its origin in `CORS_ALLOWED_ORIGINS`. |
| 513 | /// | 513 | /// |
| 514 | +/// One deliberate exception — `CORS_ALLOWED_ORIGINS=*` ("allow CORS to | ||
| 515 | +/// anywhere for now", ordered 2026-09-13): a `*` entry mirrors every origin | ||
| 516 | +/// WITH credentials, for a deployment whose frontend origins are not settled | ||
| 517 | +/// yet. `SameSite=Lax` is what still holds the door: a Lax cookie never rides | ||
| 518 | +/// a cross-site fetch, so what this opens is same-site origins (the | ||
| 519 | +/// deployment's own subdomains and ports), not third-party websites. Replace | ||
| 520 | +/// the `*` with the real origins once they are known. | ||
| 521 | +/// | ||
| 514 | /// Takes the allowlist as a parameter (env read once in `build_router`) so | 522 | /// Takes the allowlist as a parameter (env read once in `build_router`) so |
| 515 | -/// tests can exercise both modes without racing on process-global env vars. | 523 | +/// tests can exercise the modes without racing on process-global env vars. |
| 516 | pub fn cors_layer(allowlist: Vec<HeaderValue>) -> CorsLayer { | 524 | pub fn cors_layer(allowlist: Vec<HeaderValue>) -> CorsLayer { |
| 517 | let layer = CorsLayer::new() | 525 | let layer = CorsLayer::new() |
| 518 | .allow_methods([ | 526 | .allow_methods([ |
| @@ -527,6 +535,13 @@ pub fn cors_layer(allowlist: Vec<HeaderValue>) -> CorsLayer { | |||
| 527 | // on 429s and `Content-Disposition` (original filename) on downloads. | 535 | // on 429s and `Content-Disposition` (original filename) on downloads. |
| 528 | .expose_headers([header::RETRY_AFTER, header::CONTENT_DISPOSITION]); | 536 | .expose_headers([header::RETRY_AFTER, header::CONTENT_DISPOSITION]); |
| 529 | 537 | ||
| 538 | + // A `*` entry anywhere in the list asks for anywhere-mode: every origin | ||
| 539 | + // mirrored AND credentialed (the exception paragraph above). | ||
| 540 | + if allowlist.iter().any(|origin| origin == "*") { | ||
| 541 | + return layer | ||
| 542 | + .allow_origin(AllowOrigin::mirror_request()) | ||
| 543 | + .allow_credentials(true); | ||
| 544 | + } | ||
| 530 | if allowlist.is_empty() { | 545 | if allowlist.is_empty() { |
| 531 | layer | 546 | layer |
| 532 | .allow_origin(AllowOrigin::mirror_request()) | 547 | .allow_origin(AllowOrigin::mirror_request()) |
tests/integration.rsmodified+40 -0
| @@ -6794,6 +6794,46 @@ async fn cors_allowlist_mode_credits_only_listed_origins() { | |||
| 6794 | ); | 6794 | ); |
| 6795 | } | 6795 | } |
| 6796 | 6796 | ||
| 6797 | +/// Star mode (`CORS_ALLOWED_ORIGINS=*`): every origin is reflected AND | ||
| 6798 | +/// credentialed — the deliberate "anywhere, for now" mode for a deployment | ||
| 6799 | +/// whose frontend origins are not settled. `SameSite=Lax` (pinned by its own | ||
| 6800 | +/// test above) is what keeps third-party sites from riding the cookie | ||
| 6801 | +/// cross-site; this opens the door to same-site origins only. | ||
| 6802 | +#[tokio::test] | ||
| 6803 | +async fn cors_star_mode_reflects_any_origin_with_credentials() { | ||
| 6804 | + async fn probe(origin: &str) -> axum::http::HeaderMap { | ||
| 6805 | + let app = axum::Router::new() | ||
| 6806 | + .route("/ping", axum::routing::get(|| async { "pong" })) | ||
| 6807 | + .layer(hezarfen_backend::cors_layer(vec!["*".parse().unwrap()])); | ||
| 6808 | + let req = Request::builder() | ||
| 6809 | + .method("GET") | ||
| 6810 | + .uri("/ping") | ||
| 6811 | + .header("origin", origin) | ||
| 6812 | + .body(Body::empty()) | ||
| 6813 | + .unwrap(); | ||
| 6814 | + app.oneshot(req).await.unwrap().headers().clone() | ||
| 6815 | + } | ||
| 6816 | + | ||
| 6817 | + let any = probe("https://frontends.example").await; | ||
| 6818 | + assert_eq!( | ||
| 6819 | + any.get("access-control-allow-origin").unwrap(), | ||
| 6820 | + "https://frontends.example", | ||
| 6821 | + "star mode must reflect the caller's origin, never the literal `*`" | ||
| 6822 | + ); | ||
| 6823 | + assert_eq!( | ||
| 6824 | + any.get("access-control-allow-credentials").unwrap(), | ||
| 6825 | + "true", | ||
| 6826 | + "star mode exists so unlisted frontends can send the session cookie" | ||
| 6827 | + ); | ||
| 6828 | + | ||
| 6829 | + let other = probe("https://anything-else.example").await; | ||
| 6830 | + assert_eq!( | ||
| 6831 | + other.get("access-control-allow-origin").unwrap(), | ||
| 6832 | + "https://anything-else.example", | ||
| 6833 | + "every origin qualifies in star mode, not just the first one seen" | ||
| 6834 | + ); | ||
| 6835 | +} | ||
| 6836 | + | ||
| 6797 | /// Both CORS modes share one layer base, so a single probe proves the exposed | 6837 | /// Both CORS modes share one layer base, so a single probe proves the exposed |
| 6798 | /// headers: without them, cross-origin JS reads `null` for the documented | 6838 | /// headers: without them, cross-origin JS reads `null` for the documented |
| 6799 | /// `Retry-After` (429s) and `Content-Disposition` (download filename) headers. | 6839 | /// `Retry-After` (429s) and `Content-Disposition` (download filename) headers. |