From b2780eb4f9069d4f00f69a19a0dc1773a09d5265 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 13 Sep 2026 06:43:26 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=83=EF=B8=8F=20feat:=20VPS=20deploy=20?= =?UTF-8?q?workflow=20+=20exe-relative=20migrations=20+=20CORS=20anywhere?= =?UTF-8?q?=20mode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - .github/workflows/main.yml: im-style deploy on push to main — pinned ubuntu-24.04 runner, Postgres sidecar (max_connections=500) for the per-test-database suite, clippy -D warnings + full nextest gate, --release build under SQLX_OFFLINE, SSH release-dir swap + systemd user unit restart, /health gated on THIS build's process (MainPID exe) with rollback, independent after-the-fact verify. - deploy/hezarfen.service: the shipped user unit; secrets and deployment knobs live in ~/hezarfen/hezarfen.env on the server (never in-repo). - migrations_path: fall back to migrations/ beside the executable when the compile-time CARGO_MANIFEST_DIR path is absent — a deployed binary was looking for its schema on the build machine and aborting boot. - CORS_ALLOWED_ORIGINS=*: anywhere-mode, every origin mirrored WITH credentials ("allow CORS to anywhere for now"); SameSite=Lax stays the cross-site guard. Default mirror mode unchanged; test pins star mode. --- .env.example | 7 +- .github/workflows/main.yml | 266 +++++++++++++++++++++++++++++++++++++ deploy/hezarfen.service | 41 ++++++ src/database.rs | 27 +++- src/lib.rs | 23 +++- tests/integration.rs | 40 ++++++ 6 files changed, 394 insertions(+), 10 deletions(-) create mode 100644 .github/workflows/main.yml create mode 100644 deploy/hezarfen.service diff --git a/.env.example b/.env.example index 90339c9..bb52a2d 100644 --- a/.env.example +++ b/.env.example @@ -25,8 +25,13 @@ RUST_LOG=info,hezarfen_backend=debug # Comma-separated CORS allowlist for browser clients on other origins; listed # origins may send credentials (the session cookie). Leave unset to reflect the # request's Origin (dev-friendly) — but without credentials, so a cookie-using -# browser frontend must be listed here explicitly. +# browser frontend must be listed here explicitly. A lone `*` reflects every +# origin WITH credentials ("anywhere, for now"): SameSite=Lax still keeps +# third-party sites from riding the cookie cross-site, so what this opens is +# same-site origins (your own subdomains/ports) — replace it with the real +# origins once the frontends are known. # CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com +# CORS_ALLOWED_ORIGINS=* # Per-IP rate limits (requests per minute). AUTH covers /auth/login and # /auth/register only (brute-force protection); API covers every route. diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..bffcfbe --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,266 @@ +# Deploys to the VPS on every push to main, im-style (see im's +# .github/workflows/main.yml): the whole suite gates the deploy, the release +# lands as one swapped directory, and the service must answer /health from +# this build's process — or the previous release is rolled back. +# +# One-time prerequisites, outside the workflow's reach: +# * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER (im's values +# work if this deploys as the same user); +# * `loginctl enable-linger ` on the server unless the deploy user +# already has it (im's does) — user units need a running user manager; +# * a Postgres the backend can reach, and ~/hezarfen/hezarfen.env (0600) +# with at least DATABASE_URL — see deploy/hezarfen.service for the keys. + +on: + push: + branches: + - main + +# The deploy swaps a release directory and restarts one service; two of them +# racing would leave the binary and the running process from different builds. +concurrency: + group: deploy + cancel-in-progress: false + +env: + # A gnu binary links against the runner's glibc, so the runner is pinned + # (see runs-on below) to the same 24.04 the server runs; the day either + # side moves, the pin is what forces a conscious decision rather than a + # broken deploy. In exchange: no cross-toolchain, and the linker is + # rustc's default bundled lld. + TARGET: x86_64-unknown-linux-gnu + # The systemd user unit that owns the process. See deploy/hezarfen.service. + SERVICE: hezarfen + # The deploy lives in this subdirectory of the SSH user's home. The home + # itself is resolved on the server ($HOME), so switching the deploy user + # moves the path with it — a baked-in absolute path once kept pointing at + # the previous user's home and failed the deploy on permissions. + DEPLOY_SUBDIR: hezarfen + # The unit reads its secrets from this file on the server; the deploy + # never writes it, only checks it exists and holds DATABASE_URL. + ENV_FILE_NAME: hezarfen.env + # The Postgres the test suite mints its per-test databases on. Credentials + # and port match the harness default (HEZARFEN_TEST_DATABASE_URL), so the + # tests need no extra environment — only the server, with the raised + # connection ceiling the parallel suite exhausts (see compose.yaml). + PG_USER: hezarfen + PG_PASSWORD: hezarfen + # sqlx's compile-time macros verify every query against the committed .sqlx + # cache, so the build must never reach for a live database (same as the + # Containerfile). + SQLX_OFFLINE: "true" + +jobs: + deploy: + name: Deploy + # Pinned, not `latest`: ubuntu-latest floating to the next LTS would + # one day ship a glibc newer than the server's, and the gnu binary + # would stop running there. See the TARGET comment above. + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Rust + run: rustup toolchain install stable --profile minimal + + - name: Cache cargo + uses: Swatinem/rust-cache@v2 + with: + cache-all-crates: true + # Bump when the target, the profile or any rustflags change: the + # key does not otherwise see those, and a run that restores the + # old key reports it up-to-date at save time — discarding the + # recompiled dependencies and silently recompiling them on every + # later run. + prefix-key: v1-rust-gnu + + # The suite mints a control+school database pair per test; the default + # 100-connection ceiling runs out under that, so the server gets the + # same 500 the compose stack runs (see compose.yaml). + - name: Start Postgres + run: | + docker run -d --name hezarfen-pg \ + -e POSTGRES_USER="$PG_USER" -e POSTGRES_PASSWORD="$PG_PASSWORD" \ + -p 127.0.0.1:5432:5432 \ + postgres:18-alpine -c max_connections=500 + for _ in $(seq 1 30); do + docker exec hezarfen-pg pg_isready -U "$PG_USER" && break + sleep 1 + done + docker exec hezarfen-pg pg_isready -U "$PG_USER" + + - name: Install cargo-nextest + uses: taiki-e/install-action@v2 + with: + tool: cargo-nextest + + # Zero clippy warnings is a standing project rule; CI is what keeps it. + - name: Clippy + run: cargo clippy --all-targets --locked -- -D warnings + + # A broken build must never reach the server: the whole suite gates + # the deploy (doc_sync included, so README drift blocks it too). + - name: Test + run: cargo nextest run + + - name: Build the release + run: | + set -euo pipefail + cargo build --release --locked --target "$TARGET" + mkdir -p stage + cp "target/$TARGET/release/hezarfen_backend" stage/hezarfen_backend + # The migrators resolve `migrations/` beside the binary when the + # compile-time checkout path is absent (see migrations_path), so + # the schema ships with the release it belongs to. + cp -r migrations stage/migrations + cp deploy/hezarfen.service stage/hezarfen.service + strip stage/hezarfen_backend + ls -l stage + + - name: Install SSH keys + run: | + mkdir -p ~/.ssh + echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa + ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts + + - name: Upload the release + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + + # The server's login shell is not bash, and ssh would hand this + # script to it; `bash -s` takes it on stdin instead, so the login + # shell only ever parses one plain command. + # + # The deploy path is $DEPLOY_SUBDIR under the SSH user's home, + # resolved on the server as $HOME: there is no path secret to go + # stale, and switching the deploy user moves the deploy with it. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' + set -euo pipefail + case "$1" in + ''|/*|*..*) + echo "Refusing a broad deploy subdirectory: '$1'" >&2 + exit 1 + ;; + esac + deploy_path=$HOME/$1 + # The deploy path is the service's working tree: hezarfen.env and + # data/ live there and are never touched from here. Only 'current' + # is replaced. + mkdir -p -- "$deploy_path" + rm -rf -- "$deploy_path/current.new" + mkdir -p -- "$deploy_path/current.new" + REMOTE + # stdin carries the tarball, so the script cannot; the extraction + # still goes through bash -c because the login shell is not bash + # and would not expand $HOME. + tar -C stage -czf - . | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1/current.new\"' -- '$DEPLOY_SUBDIR'" + + - name: Swap and restart + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + + # bash -s for the same reason as above: the login shell is not + # bash and must never see this script. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE' + set -euo pipefail + deploy_path=$HOME/$1 + service=$2 + env_file=$deploy_path/$3 + export XDG_RUNTIME_DIR=/run/user/$(id -u) + # Read before anything moves: the env file is the operator's, on + # the server, written once (see deploy/hezarfen.service for the + # keys). A missing file or a missing DATABASE_URL is a failure to + # stop on, not one to roll back from. + if [ ! -f "$env_file" ]; then + echo "missing $env_file — create it (0600) with at least DATABASE_URL; see deploy/hezarfen.service" >&2 + exit 1 + fi + chmod 0600 -- "$env_file" + if ! grep -q '^DATABASE_URL=' "$env_file"; then + echo "no DATABASE_URL in $env_file" >&2 + exit 1 + fi + # The unit defaults to 8080; the env file may override. + port=$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$env_file" | tail -n1) + port=${port:-8080} + mkdir -p -- "$deploy_path/data/files" + chmod +x -- "$deploy_path/current.new/hezarfen_backend" + rm -rf -- "$deploy_path/current.previous" + if [ -e "$deploy_path/current" ]; then + mv -- "$deploy_path/current" "$deploy_path/current.previous" + fi + mv -- "$deploy_path/current.new" "$deploy_path/current" + # The unit ships with the release: a freshly provisioned box has + # no unit until the first deploy writes it, and a changed unit + # lands with the code that needs it. Enabling is idempotent. + mkdir -p -- "$HOME/.config/systemd/user" + install -m 644 -- "$deploy_path/current/hezarfen.service" "$HOME/.config/systemd/user/$service.service" + systemctl --user daemon-reload + systemctl --user enable -- "$service" + systemctl --user restart "$service" + # The unit is Type=simple, so a restart returns before the new + # process has bound its port — and before an old one has let go + # of it. Wait for the health route rather than a clock: /health + # answers 503 (curl -f fails) while the database is unreachable, + # so a 200 here already means status "ok". + rollback() { + rm -rf -- "$deploy_path/current" + mv -- "$deploy_path/current.previous" "$deploy_path/current" + systemctl --user restart "$service" + } + for _ in $(seq 1 30); do + served=$(curl -fsS "http://127.0.0.1:$port/health" 2>/dev/null) || { sleep 1; continue; } + # A stale process from an older deploy can answer too, so the + # running binary must be THIS release's, or it rolls back. + pid=$(systemctl --user show -p MainPID --value "$service") + exe=$(readlink "/proc/$pid/exe") + case "$exe" in + "$deploy_path/current/hezarfen_backend") ;; + *) + echo "/health answered, but the process is '$exe' — not this release; rolling back" >&2 + rollback + exit 1 + ;; + esac + echo 'hezarfen is up' + rm -rf -- "$deploy_path/current.previous" + exit 0 + done + echo 'hezarfen did not answer /health; rolling back' >&2 + rollback + exit 1 + REMOTE + + # The independent after-the-fact check: the process answering must + # still be this release's, and the validation contract must be served. + - name: Verify the served API + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + # One remote script, im-style: mixing runner-side and server-side + # variables in nested ssh quoting once shipped a check that failed + # on a healthy deploy. Everything happens inside the heredoc. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE' + set -euo pipefail + deploy_path=$HOME/$1 + service=$2 + env_file=$deploy_path/$3 + export XDG_RUNTIME_DIR=/run/user/$(id -u) + port=$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$env_file" | tail -n1) + port=${port:-8080} + pid=$(systemctl --user show -p MainPID --value "$service") + exe=$(readlink "/proc/$pid/exe") + [ "$exe" = "$deploy_path/current/hezarfen_backend" ] || { + echo "serving '$exe', not the current release" >&2 + exit 1 + } + curl -fsS "http://127.0.0.1:$port/health" | grep -q '"status":"ok"' + curl -fsS -o /dev/null "http://127.0.0.1:$port/limits" + echo 'health ok, limits served' + REMOTE + + - name: Cleaning + run: rm -rf ~/.ssh diff --git a/deploy/hezarfen.service b/deploy/hezarfen.service new file mode 100644 index 0000000..0f238e8 --- /dev/null +++ b/deploy/hezarfen.service @@ -0,0 +1,41 @@ +# The systemd user unit the deploy installs to ~/.config/systemd/user/ and +# restarts. The release layout: ~/hezarfen/current/hezarfen_backend with +# migrations/ beside the binary (the app resolves the schema there when the +# compile-time checkout path is absent — see migrations_path in the source). +# +# ~/hezarfen/hezarfen.env (0600, written once by hand, never by the deploy) +# carries the deployment's own values and overrides the Environment= lines +# below: +# DATABASE_URL required — a Postgres with the control database +# (first boot creates the schema; each school is +# minted as its own database by the builder API) +# BUILDER_USERNAME/PASSWORD first-boot operator seed +# AI_QUIC_ADDR + AI_SHARED_TOKEN the AI bridge (UDP); unset = off +# COOKIE_SECURE=true behind TLS +# CORS_ALLOWED_ORIGINS a lone `*` reflects any origin with credentials +# ("anywhere, for now"); list the real origins +# once the frontends are known +# TRUST_PROXY=true client IPs from X-Forwarded-For behind a proxy +# +# The service binds loopback only by default — terminate TLS on a reverse +# proxy and forward to 127.0.0.1:8080. + +[Unit] +Description=Hezarfen backend (school management API) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +ExecStart=%h/hezarfen/current/hezarfen_backend +WorkingDirectory=%h/hezarfen/current +Environment=HOST=127.0.0.1 +Environment=PORT=8080 +Environment=FILES_PATH=%h/hezarfen/data/files +Environment=RUST_LOG=info,hezarfen_backend=debug +EnvironmentFile=%h/hezarfen/hezarfen.env +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=default.target diff --git a/src/database.rs b/src/database.rs index a333bbd..80887de 100644 --- a/src/database.rs +++ b/src/database.rs @@ -6,7 +6,8 @@ //! shared rate-limit window) and `migrations/school` for every school //! database. They are applied by two separate [`sqlx::migrate::Migrator`]s — //! the compile-time `migrate!` macro cannot be aimed at two directories, so -//! each is constructed at runtime from its path under `CARGO_MANIFEST_DIR`. +//! each is resolved at runtime from the checkout's `CARGO_MANIFEST_DIR` or, +//! for a deployed binary, from beside the executable (see [`migrations_path`]). //! Their table names are disjoint by design, which is what lets one prepare //! database carry the union for the compile-time `query!` checks. @@ -183,11 +184,27 @@ fn is_dial_error(err: &sqlx::Error) -> bool { ) } -/// The `migrations/` directory under `CARGO_MANIFEST_DIR`. Two sets -/// cannot both feed the compile-time `migrate!` macro, so both are resolved -/// from their paths at runtime. +/// The `migrations/` directory: the one under `CARGO_MANIFEST_DIR` (the +/// dev/CI checkout) when that exists, else the one beside the executable. +/// Two sets cannot both feed the compile-time `migrate!` macro, so both are +/// resolved from their paths at runtime — and the compile-time path is baked +/// on the build machine, so a binary deployed outside a checkout (the release +/// layout ships `migrations/` next to the binary) must fall back to its own +/// directory or look for the schema where it was compiled. fn migrations_path(set: &str) -> std::path::PathBuf { - Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")).join(set) + let manifest = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")).join(set); + if manifest.is_dir() { + return manifest; + } + if let Ok(exe) = std::env::current_exe() + && let Some(dir) = exe.parent() + { + let beside = dir.join("migrations").join(set); + if beside.is_dir() { + return beside; + } + } + manifest } async fn migrator(set: &str) -> Result { diff --git a/src/lib.rs b/src/lib.rs index 882f03f..711c4d1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -505,14 +505,22 @@ fn cors_allowlist_from_env() -> Vec { /// /// With no allowlist (dev) the caller's origin is mirrored, but WITHOUT /// credentials: mirror + credentials would let any website ride a visitor's -/// session cookie, so the two must NEVER be recombined (the cookie's -/// `SameSite=Lax` in `web/auth.rs` is the only other guard on that door). A -/// cross-origin dev frontend can't send the Lax cookie anyway, so credentials +/// session cookie, so the two must never be recombined by default (the +/// cookie's `SameSite=Lax` in `web/auth.rs` is the other guard on that door). +/// A cross-origin dev frontend can't send the Lax cookie anyway, so credentials /// bought nothing in mirror mode; a credentialed browser frontend requires /// listing its origin in `CORS_ALLOWED_ORIGINS`. /// +/// One deliberate exception — `CORS_ALLOWED_ORIGINS=*` ("allow CORS to +/// anywhere for now", ordered 2026-09-13): a `*` entry mirrors every origin +/// WITH credentials, for a deployment whose frontend origins are not settled +/// yet. `SameSite=Lax` is what still holds the door: a Lax cookie never rides +/// a cross-site fetch, so what this opens is same-site origins (the +/// deployment's own subdomains and ports), not third-party websites. Replace +/// the `*` with the real origins once they are known. +/// /// Takes the allowlist as a parameter (env read once in `build_router`) so -/// tests can exercise both modes without racing on process-global env vars. +/// tests can exercise the modes without racing on process-global env vars. pub fn cors_layer(allowlist: Vec) -> CorsLayer { let layer = CorsLayer::new() .allow_methods([ @@ -527,6 +535,13 @@ pub fn cors_layer(allowlist: Vec) -> CorsLayer { // on 429s and `Content-Disposition` (original filename) on downloads. .expose_headers([header::RETRY_AFTER, header::CONTENT_DISPOSITION]); + // A `*` entry anywhere in the list asks for anywhere-mode: every origin + // mirrored AND credentialed (the exception paragraph above). + if allowlist.iter().any(|origin| origin == "*") { + return layer + .allow_origin(AllowOrigin::mirror_request()) + .allow_credentials(true); + } if allowlist.is_empty() { layer .allow_origin(AllowOrigin::mirror_request()) diff --git a/tests/integration.rs b/tests/integration.rs index 0618d86..38d5646 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -6794,6 +6794,46 @@ async fn cors_allowlist_mode_credits_only_listed_origins() { ); } +/// Star mode (`CORS_ALLOWED_ORIGINS=*`): every origin is reflected AND +/// credentialed — the deliberate "anywhere, for now" mode for a deployment +/// whose frontend origins are not settled. `SameSite=Lax` (pinned by its own +/// test above) is what keeps third-party sites from riding the cookie +/// cross-site; this opens the door to same-site origins only. +#[tokio::test] +async fn cors_star_mode_reflects_any_origin_with_credentials() { + async fn probe(origin: &str) -> axum::http::HeaderMap { + let app = axum::Router::new() + .route("/ping", axum::routing::get(|| async { "pong" })) + .layer(hezarfen_backend::cors_layer(vec!["*".parse().unwrap()])); + let req = Request::builder() + .method("GET") + .uri("/ping") + .header("origin", origin) + .body(Body::empty()) + .unwrap(); + app.oneshot(req).await.unwrap().headers().clone() + } + + let any = probe("https://frontends.example").await; + assert_eq!( + any.get("access-control-allow-origin").unwrap(), + "https://frontends.example", + "star mode must reflect the caller's origin, never the literal `*`" + ); + assert_eq!( + any.get("access-control-allow-credentials").unwrap(), + "true", + "star mode exists so unlisted frontends can send the session cookie" + ); + + let other = probe("https://anything-else.example").await; + assert_eq!( + other.get("access-control-allow-origin").unwrap(), + "https://anything-else.example", + "every origin qualifies in star mode, not just the first one seen" + ); +} + /// Both CORS modes share one layer base, so a single probe proves the exposed /// headers: without them, cross-origin JS reads `null` for the documented /// `Retry-After` (429s) and `Content-Disposition` (download filename) headers.