From 5f6a72a380a9a210c7f08357600e1997c637a539 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Thu, 12 Nov 2026 09:16:37 -0600 Subject: [PATCH] fix(nixos): cloudflared --token-file for pm/lab tunnels + lab /ready watchdog (#8933) --- nixos/services/lab-tunnel/default.nix | 58 ++++++++-- .../lab-tunnel/lab-tunnel-watchdog.sh | 30 +++++ .../lab-tunnel/lab-tunnel-watchdog.test.sh | 105 ++++++++++++++++++ .../services/lab-tunnel/tunnel-units.test.sh | 76 +++++++++++++ nixos/services/pm-stack/default.nix | 19 ++-- pm-stack/deploy.sh | 14 ++- 6 files changed, 279 insertions(+), 23 deletions(-) create mode 100644 nixos/services/lab-tunnel/lab-tunnel-watchdog.sh create mode 100755 nixos/services/lab-tunnel/lab-tunnel-watchdog.test.sh create mode 100755 nixos/services/lab-tunnel/tunnel-units.test.sh diff --git a/nixos/services/lab-tunnel/default.nix b/nixos/services/lab-tunnel/default.nix index b354c68760..bcdb775e15 100644 --- a/nixos/services/lab-tunnel/default.nix +++ b/nixos/services/lab-tunnel/default.nix @@ -32,9 +32,11 @@ # the first lab node and is tracked on #6455. # # Runtime state + the secret stay on the machine, never in this repo: -# ~/lab-tunnel/tunnel.env (mode 600) carries TUNNEL_TOKEN, rendered -# by the operator from BWS (cloudflare.tunnel.lab-cluster-token) — -# the same arrangement as ~/pm-stack/tunnel.env for pm-tunnel. +# ~/lab-tunnel/tunnel.token (mode 600) carries the raw tunnel token, +# rendered by the operator from BWS (cloudflare.tunnel.lab-cluster-token) +# and read by cloudflared via --token-file (#8933: the token never +# enters the connector's argv) — the same arrangement as +# ~/pm-stack/tunnel.token for pm-tunnel. { config, lib, @@ -45,6 +47,22 @@ let cfg = config.services.lab-tunnel; cloudflared = "${pkgs.cloudflared}/bin/cloudflared"; python3 = "${pkgs.python3}/bin/python3"; + + # The port cloudflared serves its metrics + /ready endpoint on + # (loopback only; pm-tunnel uses 20242). The watchdog below reads + # /ready from it, mirroring pm-tunnel's #6992 recovery path (#8933). + tunnelMetricsPort = 20243; + + tunnelWatchdog = pkgs.writeShellScript "lab-tunnel-watchdog" ( + lib.replaceStrings + [ "@curl@" "@systemctl@" "@readyUrl@" ] + [ + "${pkgs.curl}/bin/curl" + "/run/current-system/sw/bin/systemctl" + "http://127.0.0.1:${toString tunnelMetricsPort}/ready" + ] + (builtins.readFile ./lab-tunnel-watchdog.sh) + ); home = "/home/${cfg.user}"; stateDir = "${home}/lab-tunnel"; statusDir = pkgs.writeTextDir "index.html" '' @@ -93,19 +111,41 @@ in }; Service = { Type = "simple"; - # tunnel.env is operator-rendered from BWS - # (cloudflare.tunnel.lab-cluster-token); systemd expands - # TUNNEL_TOKEN from this EnvironmentFile in ExecStart, - # exactly as pm-tunnel's hand-written unit relied on. - EnvironmentFile = "${stateDir}/tunnel.env"; + # tunnel.token is operator-rendered from BWS + # (cloudflare.tunnel.lab-cluster-token) as a raw-token + # file; cloudflared reads it via --token-file so the + # token stays out of the process argv (#8933). # --protocol http2 (#5647): the default QUIC transport # kept dropping on this host's network path. - ExecStart = "${cloudflared} tunnel --no-autoupdate --protocol http2 run --token \${TUNNEL_TOKEN}"; + ExecStart = "${cloudflared} tunnel --no-autoupdate --protocol http2 --metrics 127.0.0.1:${toString tunnelMetricsPort} run --token-file ${stateDir}/tunnel.token"; Restart = "on-failure"; RestartSec = 5; }; Install.WantedBy = [ "default.target" ]; }; + + lab-tunnel-watchdog = { + Unit = { + Description = "lab-tunnel watchdog — restart lab-tunnel when its edge connections stay down (#8933, mirroring pm-tunnel #6992)"; + After = [ "lab-tunnel.service" ]; + }; + Service = { + Type = "oneshot"; + ExecStart = "${tunnelWatchdog}"; + }; + }; + }; + + systemd.user.timers = { + lab-tunnel-watchdog = { + Unit.Description = "Check lab-tunnel edge readiness every 2 minutes (#8933)"; + Timer = { + OnBootSec = "2min"; + OnUnitActiveSec = "2min"; + Unit = "lab-tunnel-watchdog.service"; + }; + Install.WantedBy = [ "timers.target" ]; + }; }; }; }; diff --git a/nixos/services/lab-tunnel/lab-tunnel-watchdog.sh b/nixos/services/lab-tunnel/lab-tunnel-watchdog.sh new file mode 100644 index 0000000000..021fa28aca --- /dev/null +++ b/nixos/services/lab-tunnel/lab-tunnel-watchdog.sh @@ -0,0 +1,30 @@ +# lab-tunnel-watchdog — restart lab-tunnel when its edge connections +# stay down (#8933, mirroring pm-tunnel's #6992 watchdog). +# +# cloudflared can stay process-alive with no live edge connections; +# its own /ready endpoint is the truth (200 = at least one live edge +# connection). Three consecutive failures (the timer runs every 2 +# minutes) restart lab-tunnel; any success resets the counter. +# +# Placeholders @curl@, @systemctl@ and @readyUrl@ are substituted by +# the NixOS module (nixos/services/lab-tunnel/default.nix, via +# lib.replaceStrings on this file) and by lab-tunnel-watchdog.test.sh +# (with stub binaries) — keep them intact. +stateDir="$HOME/.local/state/lab-tunnel-watchdog" +mkdir -p "$stateDir" +countFile="$stateDir/consecutive-failures" +count=0 +if [ -f "$countFile" ]; then + count=$(cat "$countFile") +fi +if @curl@ -fsS -m 10 "@readyUrl@" >/dev/null 2>&1; then + echo 0 > "$countFile" + exit 0 +fi +count=$((count + 1)) +echo "$count" > "$countFile" +echo "lab-tunnel-watchdog: /ready failed ($count consecutive)" >&2 +if [ "$count" -ge 3 ]; then + echo 0 > "$countFile" + exec @systemctl@ --user restart lab-tunnel.service +fi diff --git a/nixos/services/lab-tunnel/lab-tunnel-watchdog.test.sh b/nixos/services/lab-tunnel/lab-tunnel-watchdog.test.sh new file mode 100755 index 0000000000..fd901e14d0 --- /dev/null +++ b/nixos/services/lab-tunnel/lab-tunnel-watchdog.test.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# Test for nixos/services/lab-tunnel/lab-tunnel-watchdog.sh (#8933). +# +# Oracle: pm-tunnel-watchdog semantics (code#6992), which the lab +# watchdog mirrors exactly: +# - /ready success: counter resets to 0, never a restart. +# - /ready failure (HTTP error or probe/connection error alike): +# the consecutive-failure counter increments by one per run. +# - At 3 consecutive failures: exactly one +# `systemctl --user restart lab-tunnel.service`, counter resets. +# +# curl and systemctl are stubs; the watchdog under test is this +# repo's script with its @curl@/@systemctl@/@readyUrl@ placeholders +# substituted by the stubs, exactly as the NixOS module substitutes +# the real paths. No network, no systemd, no credential is touched. +set -uo pipefail + +here="$(dirname -- "$(realpath -- "$0")")" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/stubbin" "$work/home" + +cat >"$work/stubbin/curl" <<'STUB' +#!/usr/bin/env bash +# Behavior is driven by $CURL_MODE_FILE: ok | httpfail | connerr +mode="$(cat "$CURL_MODE_FILE")" +case "$mode" in +ok) exit 0 ;; +httpfail) exit 22 ;; +connerr) exit 7 ;; +*) exit 99 ;; +esac +STUB + +cat >"$work/stubbin/systemctl" <<'STUB' +#!/usr/bin/env bash +echo "$@" >>"$RESTART_LOG" +exit 0 +STUB +chmod +x "$work/stubbin/curl" "$work/stubbin/systemctl" + +export CURL_MODE_FILE="$work/curl-mode" +export RESTART_LOG="$work/restarts.log" +export HOME="$work/home" + +sed -e "s|@curl@|$work/stubbin/curl|g" \ + -e "s|@systemctl@|$work/stubbin/systemctl|g" \ + -e "s|@readyUrl@|http://127.0.0.1:9/ready|g" \ + "$here/lab-tunnel-watchdog.sh" >"$work/watchdog.sh" + +countFile="$HOME/.local/state/lab-tunnel-watchdog/consecutive-failures" +failures=0 + +check() { # check + if [[ "$2" == "$3" ]]; then + echo "PASS: $1" + else + echo "FAIL: $1 (expected [$2], got [$3])" + failures=$((failures + 1)) + fi +} + +counter() { cat "$countFile" 2>/dev/null || echo "missing"; } +restarts() { grep -c '' "$RESTART_LOG" 2>/dev/null || echo 0; } +run_watchdog() { bash "$work/watchdog.sh" >/dev/null 2>&1; } + +# 1. Healthy: /ready succeeds — counter 0, no restart. +echo ok >"$CURL_MODE_FILE" +run_watchdog +check "healthy run leaves counter at 0" "0" "$(counter)" +check "healthy run never restarts" "0" "$(restarts)" + +# 2. Degraded: HTTP failure on /ready counts up; restart at 3. +echo httpfail >"$CURL_MODE_FILE" +run_watchdog +check "first failure counts 1" "1" "$(counter)" +check "first failure does not restart" "0" "$(restarts)" +run_watchdog +check "second failure counts 2" "2" "$(counter)" +run_watchdog +check "third failure resets counter" "0" "$(counter)" +check "third failure restarts exactly once" "1" "$(restarts)" +check "restart targets lab-tunnel.service" \ + "--user restart lab-tunnel.service" "$(cat "$RESTART_LOG")" + +# 3. Probe error (connection refused) counts as a failure too. +echo connerr >"$CURL_MODE_FILE" +run_watchdog +check "probe error counts as a failure" "1" "$(counter)" +check "probe error alone does not restart" "1" "$(restarts)" + +# 4. A success after failures resets the counter, no restart. +echo httpfail >"$CURL_MODE_FILE" +run_watchdog +check "failure after probe error counts 2" "2" "$(counter)" +echo ok >"$CURL_MODE_FILE" +run_watchdog +check "success resets the counter" "0" "$(counter)" +check "success does not restart" "1" "$(restarts)" + +if [[ $failures -gt 0 ]]; then + echo "lab-tunnel-watchdog.test.sh: $failures check(s) failed" >&2 + exit 1 +fi +echo "lab-tunnel-watchdog.test.sh: all checks passed" diff --git a/nixos/services/lab-tunnel/tunnel-units.test.sh b/nixos/services/lab-tunnel/tunnel-units.test.sh new file mode 100755 index 0000000000..f439f6326c --- /dev/null +++ b/nixos/services/lab-tunnel/tunnel-units.test.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Rendered-unit shape test for issue #8933 (pm + lab Cloudflare tunnels). +# +# Oracle: issue #8933's acceptance criteria. In these NixOS modules +# the systemd unit's command line is the literal `ExecStart` string +# in the module (modulo store paths), so asserting on that string is +# asserting on the rendered unit: +# - neither tunnel's ExecStart carries a token: no `--token ` +# argument and no TUNNEL_TOKEN expansion anywhere in either module; +# - both ExecStarts pass the token via `--token-file` pointing at a +# dedicated token file; +# - lab-tunnel serves a loopback metrics//ready endpoint on a port +# distinct from pm-tunnel's 20242 and has a watchdog service + +# 2-minute timer; pm-tunnel's watchdog is untouched; +# - pm-stack/deploy.sh renders the raw tunnel.token (mode 600) the +# pm unit now points at. +set -uo pipefail + +here="$(dirname -- "$(realpath -- "$0")")" +pm_module="$here/../pm-stack/default.nix" +lab_module="$here/default.nix" +deploy_sh="$here/../../../pm-stack/deploy.sh" +failures=0 + +expect_present() { # expect_present + if grep -qF -- "$2" "$1"; then + echo "PASS: $3" + else + echo "FAIL: $3 (pattern not found in $1: $2)" + failures=$((failures + 1)) + fi +} + +expect_absent() { # expect_absent + if grep -qF -- "$2" "$1"; then + echo "FAIL: $3 (forbidden pattern present in $1: $2)" + failures=$((failures + 1)) + else + echo "PASS: $3" + fi +} + +for module in "$pm_module" "$lab_module"; do + expect_absent "$module" 'TUNNEL_TOKEN' \ + "$module: no TUNNEL_TOKEN expansion remains" + expect_absent "$module" 'run --token ' \ + "$module: no --token argument in ExecStart" + expect_present "$module" '--token-file' \ + "$module: ExecStart uses --token-file" +done + +expect_present "$pm_module" '--token-file ${stackDir}/tunnel.token' \ + "pm-tunnel reads ~/pm-stack/tunnel.token" +expect_present "$lab_module" '--token-file ${stateDir}/tunnel.token' \ + "lab-tunnel reads ~/lab-tunnel/tunnel.token" +expect_present "$lab_module" '--metrics 127.0.0.1:${toString tunnelMetricsPort}' \ + "lab-tunnel serves loopback metrics//ready" +expect_present "$lab_module" 'tunnelMetricsPort = 20243' \ + "lab metrics port 20243 is distinct from pm-tunnel's 20242" +expect_present "$lab_module" 'lab-tunnel-watchdog' \ + "lab-tunnel watchdog service is defined" +expect_present "$lab_module" 'OnUnitActiveSec = "2min"' \ + "lab-tunnel watchdog runs on a 2-minute timer" +expect_present "$pm_module" 'pm-tunnel-watchdog' \ + "pm-tunnel watchdog is preserved" + +expect_present "$deploy_sh" '> tunnel.token' \ + "deploy.sh renders the raw tunnel.token" +expect_present "$deploy_sh" 'chmod 600 tunnel.token' \ + "deploy.sh renders tunnel.token at mode 600" + +if [[ $failures -gt 0 ]]; then + echo "tunnel-units.test.sh: $failures check(s) failed" >&2 + exit 1 +fi +echo "tunnel-units.test.sh: all checks passed" diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index 0c0874be37..afad8847d2 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -51,10 +51,10 @@ # The Kaneo stack is the exception to the checkout model: pm-kaneo # runs deploy.sh from the ~/pm-stack deployment dir, because the # rendered .env, the compose project, and the pm-stack_postgres_data -# volume live there. deploy.sh also renders ~/pm-stack/tunnel.env, -# which pm-tunnel consumes — systemd expands TUNNEL_TOKEN from that -# EnvironmentFile in the tunnel's ExecStart, exactly as the -# hand-written unit relied on. (The tunnel's ingress is managed in +# volume live there. deploy.sh also renders ~/pm-stack/tunnel.token, +# which pm-tunnel consumes via cloudflared's --token-file flag +# (#8933: the token never enters the tunnel's ExecStart argv; the +# older tunnel.env rendering is kept for rollback only). (The tunnel's ingress is managed in # Cloudflare: kaneo.security.cab -> http://localhost:5173 and # dispatch.security.cab -> http://localhost:4879.) # @@ -444,11 +444,10 @@ in Service = { Type = "simple"; WorkingDirectory = "${stackDir}"; - # tunnel.env is rendered by the pm-kaneo deploy flow - # (deploy.sh); systemd expands TUNNEL_TOKEN from this - # EnvironmentFile in ExecStart, exactly as the hand-written - # unit relied on. - EnvironmentFile = "${stackDir}/tunnel.env"; + # tunnel.token is rendered by the pm-kaneo deploy flow + # (deploy.sh) from the same SOPS secret as the old + # tunnel.env; cloudflared reads it via --token-file so + # the token stays out of the process argv (#8933). # Wait until the edge hostname resolves (#6992). TimeoutStartSec = 300; ExecStartPre = "${waitForDns}"; @@ -460,7 +459,7 @@ in # pm-dispatch callers with 502 ("error code: 502") even # though pm-dispatch itself was healthy. HTTP/2 runs over # TCP and does not depend on the UDP path QUIC needs. - ExecStart = "${cloudflared} tunnel --no-autoupdate --protocol http2 --metrics 127.0.0.1:${toString tunnelMetricsPort} run --token \${TUNNEL_TOKEN}"; + ExecStart = "${cloudflared} tunnel --no-autoupdate --protocol http2 --metrics 127.0.0.1:${toString tunnelMetricsPort} run --token-file ${stackDir}/tunnel.token"; Restart = "on-failure"; RestartSec = 5; }; diff --git a/pm-stack/deploy.sh b/pm-stack/deploy.sh index 2c23d126c8..6d0e6d8879 100755 --- a/pm-stack/deploy.sh +++ b/pm-stack/deploy.sh @@ -4,7 +4,9 @@ # Renders .env (mode 600) from the SOPS-encrypted secrets in # ../secrets/pm-stack.sops.yaml (relative to this repo checkout), then # pulls and (re)creates the containers, then renders the Cloudflare -# Tunnel token file used by the pm-tunnel systemd user unit. +# Tunnel token files used by the pm-tunnel systemd user unit +# (tunnel.token, read by cloudflared via --token-file, #8933; the +# legacy tunnel.env env-file rendering is kept for rollback). # # Usage: # ./deploy.sh render env, pull images, start/refresh stack @@ -70,11 +72,15 @@ render() { } >.env chmod 600 .env - # cloudflared reads TUNNEL_TOKEN from its environment; the systemd - # unit (systemd/pm-tunnel.service) loads this file. + # cloudflared reads the tunnel token from tunnel.token via + # --token-file (#8933: never through the connector's argv or + # environment). tunnel.env is still rendered for rollback to the + # pre-#8933 unit; nothing consumes it in the current unit. + printf '%s' "$(get cloudflare_tunnel_token)" > tunnel.token + chmod 600 tunnel.token echo "TUNNEL_TOKEN=$(get cloudflare_tunnel_token)" >tunnel.env chmod 600 tunnel.env - echo "rendered .env and tunnel.env from $SECRETS_FILE" + echo "rendered .env, tunnel.token and tunnel.env from $SECRETS_FILE" } case "${1:-deploy}" in