From 8298537b3448d5aa1298096891d65c16de20fa34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Dec 2026 22:04:36 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20one-line=20runner=20install?= =?UTF-8?q?:=20/api/v1/ci/runners/install.sh=20sets=20up=20packages,=20a?= =?UTF-8?q?=20ci=20user=20with=20subids=20and=20linger,=20downloads=20the?= =?UTF-8?q?=20forge=20binary=20with=20the=20registration=20token=20(sha256?= =?UTF-8?q?=20checked),=20runs=20check,=20registers=20and=20starts=20the?= =?UTF-8?q?=20user=20service;=20--uninstall=20removes=20it;=20the=20token?= =?UTF-8?q?=20page=20shows=20the=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web-app/src/ci/api.rs | 40 +++++ crates/forge-web-app/src/ci/api_tests.rs | 37 +++++ crates/forge-web-app/src/ci/install.sh | 141 ++++++++++++++++++ .../src/pages/admin_runners.rs | 14 +- crates/forge-web/src/routes.snap | 2 + docs/ci.md | 16 ++ 6 files changed, 241 insertions(+), 9 deletions(-) create mode 100644 crates/forge-web-app/src/ci/install.sh diff --git a/crates/forge-web-app/src/ci/api.rs b/crates/forge-web-app/src/ci/api.rs index 84bd227..42daa3c 100644 --- a/crates/forge-web-app/src/ci/api.rs +++ b/crates/forge-web-app/src/ci/api.rs @@ -476,6 +476,46 @@ async fn runner_binary(cx: &Cx) -> topcoat::Result { } } +const INSTALL_SCRIPT: &str = include_str!("install.sh"); + +#[route(GET "/api/v1/ci/runners/install.sh")] +async fn runner_install_script(cx: &Cx) -> topcoat::Result { + let state = context::(cx); + let script = INSTALL_SCRIPT + .replace("@URL@", state.config.base_url.trim_end_matches('/')) + .replace("@TARGET@", &self_update::target()); + let mut res = Response::new(Body::from(script)); + res.headers_mut().insert( + http::header::CONTENT_TYPE, + HeaderValue::from_static("text/x-shellscript; charset=utf-8"), + ); + Ok(res) +} + +#[route(GET "/api/v1/ci/runners/install/forge")] +async fn runner_install_binary(cx: &Cx) -> topcoat::Result { + let state = context::(cx); + let Some(token) = bearer_token(headers(cx)) else { + return Ok(*unauthorized()); + }; + let hash = forge_core::token::hash_token(token); + match state.store.registration_token_used(&hash).await { + Ok(false) => {} + Ok(true) => return Ok(*unauthorized()), + Err(e) => return Ok(*api::internal(e)), + } + match self_update::binary_response().await { + Ok(res) => Ok(res), + Err(e) => { + tracing::error!(error = %e, "ci: serving the install binary failed"); + Ok(api::error( + StatusCode::INTERNAL_SERVER_ERROR, + "the binary is unavailable", + )) + } + } +} + fn empty(status: StatusCode) -> Response { let mut res = Response::new(topcoat::router::Body::empty()); *res.status_mut() = status; diff --git a/crates/forge-web-app/src/ci/api_tests.rs b/crates/forge-web-app/src/ci/api_tests.rs index 5cdb80b..b35aaad 100644 --- a/crates/forge-web-app/src/ci/api_tests.rs +++ b/crates/forge-web-app/src/ci/api_tests.rs @@ -1381,3 +1381,40 @@ async fn claim_and_heartbeat_store_the_runner_build() { Some("0.1.0 (4d21658, 2026-10-19)") ); } + +#[tokio::test] +async fn install_script_and_binary_follow_the_registration_token() { + let env = bare(|_| {}).await; + let script = send( + &env.router, + "GET", + "/api/v1/ci/runners/install.sh", + &[], + Vec::new(), + ) + .await; + assert_eq!(script.status, 200); + let text = String::from_utf8(script.body).unwrap(); + assert!(!text.contains("@URL@") && !text.contains("@TARGET@")); + + let uri = "/api/v1/ci/runners/install/forge"; + let token = env + .store + .create_registration_token(&env.owner_id, 24) + .await + .unwrap(); + assert_eq!( + send(&env.router, "GET", uri, &[], Vec::new()).await.status, + 401 + ); + let sent = send(&env.router, "GET", uri, &[bearer(&token)], Vec::new()).await; + assert_eq!(sent.status, 200); + assert!(sent.headers.contains_key("forge-binary-sha256")); + env.store.register_runner(&token, "r", &[]).await.unwrap(); + assert_eq!( + send(&env.router, "GET", uri, &[bearer(&token)], Vec::new()) + .await + .status, + 401 + ); +} diff --git a/crates/forge-web-app/src/ci/install.sh b/crates/forge-web-app/src/ci/install.sh new file mode 100644 index 0000000..f2fd6a3 --- /dev/null +++ b/crates/forge-web-app/src/ci/install.sh @@ -0,0 +1,141 @@ +#!/bin/sh +set -eu + +URL='@URL@' +TARGET='@TARGET@' + +fail() { + echo "error: $*" >&2 + exit 1 +} + +as_user() { + systemd-run --machine="$RUNNER_USER@.host" --user --wait --pipe --quiet "$@" /dev/null && return 0 + start=$(cat /etc/subuid /etc/subgid 2>/dev/null | awk -F: 'BEGIN { m = 100000 } { e = $2 + $3; if (e > m) m = e } END { print m }') + usermod "$flag" "$start-$((start + 65535))" "$RUNNER_USER" +} + +install_packages() { + if command -v dnf >/dev/null; then + dnf install -y git passt shadow-utils systemd-container curl /dev/null; then + apt-get update /dev/null 2>&1 || fail "there is no user $RUNNER_USER" + home=$(getent passwd "$RUNNER_USER" | cut -d: -f6) + [ -f "$home/.config/forge-runner/runner.toml" ] || fail "$RUNNER_USER has no forge runner, so it is not removed" + loginctl disable-linger "$RUNNER_USER" || true + loginctl terminate-user "$RUNNER_USER" 2>/dev/null || true + pkill -KILL -u "$RUNNER_USER" || true + sleep 1 + userdel -r "$RUNNER_USER" 2>/dev/null || true + case $home in + /home/?*) [ -d "$home" ] && rm -rf --one-file-system -- "$home" ;; + esac + sed -i "/^$RUNNER_USER:/d" /etc/subuid /etc/subgid + echo "removed $RUNNER_USER. Delete the runner at $URL/admin/runners too." +} + +install_runner() { + [ -n "$TOKEN" ] || fail "--token is required" + [ "$(uname -m)-linux" = "$TARGET" ] || fail "this forge serves a $TARGET binary, this host is $(uname -m)-linux" + command -v systemctl >/dev/null || fail "systemd is required" + + install_packages + + id "$RUNNER_USER" >/dev/null 2>&1 || useradd -m "$RUNNER_USER" + add_range /etc/subuid --add-subuids + add_range /etc/subgid --add-subgids + loginctl enable-linger "$RUNNER_USER" + systemctl start "user@$(id -u "$RUNNER_USER").service" + + home=$(getent passwd "$RUNNER_USER" | cut -d: -f6) + group=$(id -gn "$RUNNER_USER") + bin="$home/.local/bin/forge" + unit_dir="$home/.config/systemd/user" + runuser -u "$RUNNER_USER" -- mkdir -p "$home/.local/bin" "$unit_dir" + + tmp=$(mktemp) + trap 'rm -f "$tmp" "$tmp.h"' EXIT + curl -fsS -H "Authorization: Bearer $TOKEN" -D "$tmp.h" -o "$tmp" "$URL/api/v1/ci/runners/install/forge" \ + || fail "download failed: the token may be wrong, used or expired" + want=$(grep -i '^forge-binary-sha256:' "$tmp.h" | cut -d: -f2 | tr -d ' \r') + got=$(sha256sum "$tmp" | cut -d' ' -f1) + [ -n "$want" ] && [ "$want" = "$got" ] || fail "the downloaded binary does not match its checksum" + install -o "$RUNNER_USER" -g "$group" -m 755 "$tmp" "$bin" + + as_user "$bin" runner check || fail "runner check failed: fix the FAIL lines above and run this again" + + if [ -f "$home/.config/forge-runner/runner.toml" ]; then + echo "already registered, keeping $home/.config/forge-runner/runner.toml" + elif [ -n "$LABELS" ]; then + as_user "$bin" runner register --url "$URL" --token "$TOKEN" --name "$NAME" --labels "$LABELS" + else + as_user "$bin" runner register --url "$URL" --token "$TOKEN" --name "$NAME" + fi + + cat >"$unit_dir/forge-runner.service" <<'EOF' +[Unit] +Description=forge CI runner +After=network-online.target +Wants=network-online.target + +[Service] +ExecStart=%h/.local/bin/forge runner run --config %h/.config/forge-runner/runner.toml +Restart=on-failure +RestartSec=10 +TimeoutStopSec=120 + +[Install] +WantedBy=default.target +EOF + chown "$RUNNER_USER:$group" "$unit_dir/forge-runner.service" + user_ctl daemon-reload + user_ctl enable --now forge-runner.service + echo "runner $NAME is running as $RUNNER_USER. Logs: journalctl _SYSTEMD_USER_UNIT=forge-runner.service -f" +} + +main() { + RUNNER_USER=ci + TOKEN= + NAME=$(hostname) + LABELS= + MODE=install + while [ $# -gt 0 ]; do + case $1 in + --token) TOKEN=$2; shift 2 ;; + --name) NAME=$2; shift 2 ;; + --labels) LABELS=$2; shift 2 ;; + --user) RUNNER_USER=$2; shift 2 ;; + --uninstall) MODE=uninstall; shift ;; + *) fail "unknown option: $1" ;; + esac + done + [ "$(id -u)" = 0 ] || fail "run this as root" + case $RUNNER_USER in + root | "" | *[!a-z0-9_-]*) fail "--user must be a plain non-root user name" ;; + esac + if [ "$MODE" = uninstall ]; then + uninstall + else + install_runner + fi +} + +main "$@" diff --git a/crates/forge-web-pages/src/pages/admin_runners.rs b/crates/forge-web-pages/src/pages/admin_runners.rs index 15bd045..dc77ff9 100644 --- a/crates/forge-web-pages/src/pages/admin_runners.rs +++ b/crates/forge-web-pages/src/pages/admin_runners.rs @@ -253,7 +253,7 @@ fn back_to_list(notice: &str) -> SeeOther { fn register_command(base_url: &str, token: &str) -> String { format!( - "forge runner register \\\n --url {} \\\n --token {token} \\\n --name \\\n --labels linux,x86_64 \\\n --config ~/.config/forge-runner/runner.toml", + "curl -fsSL {}/api/v1/ci/runners/install.sh | sudo sh -s -- --token {token}", base_url.trim_end_matches('/') ) } @@ -302,7 +302,7 @@ async fn runners_view( if rows.is_empty() {

(g::t(lang, K::AddARunner))

-
"forge runner register --url  --token  --name  --labels linux,x86_64"
+
"curl -fsSL /api/v1/ci/runners/install.sh | sudo sh -s -- --token "
} @@ -1888,14 +1888,14 @@ mod tests { let cmd = register_command("https://forge.example/", "tok123"); assert_eq!( cmd, - "forge runner register \\\n --url https://forge.example \\\n --token tok123 \\\n --name \\\n --labels linux,x86_64 \\\n --config ~/.config/forge-runner/runner.toml" + "curl -fsSL https://forge.example/api/v1/ci/runners/install.sh | sudo sh -s -- --token tok123" ); } fn token_from(page: &str) -> String { page.split("--token ") .nth(1) - .and_then(|rest| rest.split(' ').next()) + .and_then(|rest| rest.split([' ', '<']).next()) .expect("token") .to_owned() } @@ -2011,11 +2011,7 @@ mod tests { .await; assert_eq!(status, 200); let token = token_from(&created); - assert!(created.contains("forge runner register \\\n --url")); - assert!( - created.contains("--name <name> \\\n --labels linux,x86_64 \\\n --config ~/.config/forge-runner/runner.toml"), - "placeholder is escaped" - ); + assert!(created.contains("/api/v1/ci/runners/install.sh | sudo sh -s -- --token ")); assert_eq!( created.matches(&token).count(), 2, diff --git a/crates/forge-web/src/routes.snap b/crates/forge-web/src/routes.snap index 37acb1f..0dca597 100644 --- a/crates/forge-web/src/routes.snap +++ b/crates/forge-web/src/routes.snap @@ -240,6 +240,8 @@ route /api/v1/ci/runners/binary Only([GET]) route /api/v1/ci/runners/claim Only([POST]) route /api/v1/ci/runners/config Only([GET]) route /api/v1/ci/runners/config Only([PUT]) +route /api/v1/ci/runners/install.sh Only([GET]) +route /api/v1/ci/runners/install/forge Only([GET]) route /api/v1/ci/runners/log Only([POST]) route /api/v1/ci/runners/metrics Only([POST]) route /api/v1/ci/runners/register Only([POST]) diff --git a/docs/ci.md b/docs/ci.md index 929cac6..3e5e958 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -483,6 +483,22 @@ binary, so an operator deploys one file. The default `builtin` executor needs no The `forge-runner` binary is a development and test convenience only. It has the same subcommands, but operators should use `forge runner`, which the examples below show. +### Quick install + +On a fresh Linux host with systemd and `dnf` or `apt-get`, create a registration token at +`/admin/runners` and run the command the page shows, as root: + +```sh +curl -fsSL https://forge.example/api/v1/ci/runners/install.sh | sudo sh -s -- --token +``` + +It installs `git`, `passt`, `newuidmap` and `systemd-container`, creates the user `ci` with a +subordinate id range and lingering, downloads the forge's own binary (the token authorizes the +download, and the script checks its sha256), runs `forge runner check`, registers, and starts the +systemd user service. Options: `--name` (default: the hostname), `--labels`, `--user` (default +`ci`). `--uninstall` removes the runner user, its files and its id ranges; it refuses a user that +has no `runner.toml`. The steps below do the same by hand. + ### 1. Check the host The builtin executor needs: