From 93058afe38c2255536b79ff8fb67dca64e6e86ee Mon Sep 17 00:00:00 2001 From: Cristian Date: Thu, 19 Nov 2026 14:54:40 +0200 Subject: [PATCH] Add isolated staging-only Cap CAPTCHA pilot --- deploy/cap-staging/Caddyfile.example | 34 ++++++++ deploy/cap-staging/README.md | 26 ++++++ deploy/cap-staging/compose.example.yaml | 82 +++++++++++++++++++ deploy/cap-staging/index.html | 20 +++++ deploy/cap-staging/pilot.js | 71 ++++++++++++++++ src/captcha.rs | 54 ++++++++++++- src/config.rs | 103 +++++++++++++++++++++++- 7 files changed, 385 insertions(+), 5 deletions(-) create mode 100644 deploy/cap-staging/Caddyfile.example create mode 100644 deploy/cap-staging/README.md create mode 100644 deploy/cap-staging/compose.example.yaml create mode 100644 deploy/cap-staging/index.html create mode 100644 deploy/cap-staging/pilot.js diff --git a/deploy/cap-staging/Caddyfile.example b/deploy/cap-staging/Caddyfile.example new file mode 100644 index 0000000..0cd394d --- /dev/null +++ b/deploy/cap-staging/Caddyfile.example @@ -0,0 +1,34 @@ +{$CAP_STAGING_HOST} { + header X-Robots-Tag "noindex, nofollow" + header X-Content-Type-Options nosniff + header Content-Security-Policy "frame-ancestors 'none'" + @widget path /assets/* /{$CAP_STAGING_SITE_KEY}/challenge /{$CAP_STAGING_SITE_KEY}/redeem + handle @widget { + reverse_proxy 127.0.0.1:13000 { + header_up X-Forwarded-For {remote_host} + } + } + @config { + method GET + path /api/v1/config + } + handle @config { + reverse_proxy 127.0.0.1:13001 + } + @session { + method POST + path /api/v1/sessions + } + handle @session { + header Cache-Control no-store + reverse_proxy 127.0.0.1:13001 + } + @pilot path / /pilot.js + handle @pilot { + root * {$CAP_STAGING_PAGE_DIR} + file_server + } + handle { + respond 404 + } +} diff --git a/deploy/cap-staging/README.md b/deploy/cap-staging/README.md new file mode 100644 index 0000000..43c2537 --- /dev/null +++ b/deploy/cap-staging/README.md @@ -0,0 +1,26 @@ +# Cap staging pilot + +Run this on a dedicated staging host. It starts Cap, its private Valkey, and a +development-mode copy of the real Shifter session API with a separate private +Redis. There is no gateway or production upstream credential. Production +refuses `CAPTCHA_PROVIDER=cap-staging` and still defaults to reCAPTCHA. + +1. Set `CAP_STAGING_HOST` to a new, dedicated DNS name and generate a private + `CAP_ADMIN_KEY`. Start only `valkey` and `capd` using the example Compose file. +2. Open the Cap dashboard via an SSH tunnel to host loopback port 13000. Create a + dedicated site key with the single staging origin. Enable self-hosted widget + files. Set Cap's trusted forwarding mode to X-Forwarded-For; only the local + ingress proxy and this dedicated host may reach capd. +3. Set `CAP_STAGING_SITE_KEY` and point `CAP_STAGING_SECRET_PATH` at a private + file readable by API container UID 10001. Start `redis` and `api`. Keep both + databases on their separate internal networks and never publish their ports. +4. Install the example Caddyfile with the exact host, public site key and + static page directory substituted. Only the widget assets, challenge, + redeem, public config and session-creation paths are exposed. The Cap + admin endpoints and siteverify remain private. +5. Load the staging page in a browser, solve the challenge, create a staging + session, and confirm the replay check rejects the same token. Also check + wrong-origin and wrong-site-token rejection. Do not migrate live origins. + +This checks the CAPTCHA-to-session flow, not a live Wisp tunnel or a production +browser SDK migration. Store only example settings in Git. diff --git a/deploy/cap-staging/compose.example.yaml b/deploy/cap-staging/compose.example.yaml new file mode 100644 index 0000000..42e9389 --- /dev/null +++ b/deploy/cap-staging/compose.example.yaml @@ -0,0 +1,82 @@ +name: shifter-cap-staging +services: + capd: + image: tiago2/cap:4@sha256:d8c8af1b871c4b10adefbc388844ee6de497c6d96923698ffa1aa4567316e86f + environment: + ADMIN_KEY: ${CAP_ADMIN_KEY:?set an isolated Cap admin key} + VALKEY_URL: redis://valkey:6379 + ports: ["127.0.0.1:13000:3000"] + networks: [challenge, cap_state] + volumes: [cap-data:/usr/src/app/data] + depends_on: + valkey: {condition: service_healthy} + mem_limit: 512m + restart: unless-stopped + valkey: + image: valkey/valkey:9-alpine@sha256:4d67e1af80c653bd46c0bbe8de438c81a6535ab5a39b22f2100028f314005663 + command: [valkey-server, --appendonly, "yes", --maxmemory, 128mb, --maxmemory-policy, noeviction] + networks: [cap_state] + volumes: [valkey-data:/data] + healthcheck: + test: [CMD, valkey-cli, ping] + interval: 3s + timeout: 2s + retries: 15 + mem_limit: 256m + restart: unless-stopped + redis: + image: redis:7.4-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499 + command: [redis-server, --appendonly, "yes", --maxmemory, 96mb, --maxmemory-policy, noeviction] + networks: [session_state] + volumes: [redis-data:/data] + healthcheck: + test: [CMD, redis-cli, ping] + interval: 3s + timeout: 2s + retries: 15 + mem_limit: 192m + restart: unless-stopped + api: + image: shifter-cap-pilot:local + build: ../.. + environment: + APP_ENV: development + ROLE: api + SHIFTER_REGION: fra + REDIS_URL: redis://redis:6379/ + CONTROL_ORIGIN: https://${CAP_STAGING_HOST:?set the staging-only DNS name} + RUNTIME_ORIGIN: https://runtime.invalid + SESSION_SECONDS: "120" + CAPTCHA_PROVIDER: cap-staging + CAP_STAGING_SITE_KEY: ${CAP_STAGING_SITE_KEY:-unconfigured} + CAP_STAGING_SECRET_FILE: /run/secrets/cap_site_secret + secrets: [cap_site_secret] + ports: ["127.0.0.1:13001:3000"] + networks: [challenge, session_state] + depends_on: + redis: {condition: service_healthy} + read_only: true + tmpfs: [/tmp] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 256m + restart: unless-stopped +secrets: + cap_site_secret: + file: ${CAP_STAGING_SECRET_PATH:-./cap-site.secret} +volumes: + cap-data: + valkey-data: + redis-data: +networks: + challenge: {} + cap_state: + internal: true + driver_opts: + com.docker.network.bridge.gateway_mode_ipv4: isolated + com.docker.network.bridge.gateway_mode_ipv6: isolated + session_state: + internal: true + driver_opts: + com.docker.network.bridge.gateway_mode_ipv4: isolated + com.docker.network.bridge.gateway_mode_ipv6: isolated diff --git a/deploy/cap-staging/index.html b/deploy/cap-staging/index.html new file mode 100644 index 0000000..b7644bf --- /dev/null +++ b/deploy/cap-staging/index.html @@ -0,0 +1,20 @@ + + + + +Shifter Cap staging pilot + +
+

Shifter Cap staging pilot

+

This page tests session creation only. It does not open a proxy connection or use production credentials.

+ +

Loading the staging verifier…

+ + +
+ + diff --git a/deploy/cap-staging/pilot.js b/deploy/cap-staging/pilot.js new file mode 100644 index 0000000..43a98b9 --- /dev/null +++ b/deploy/cap-staging/pilot.js @@ -0,0 +1,71 @@ +"use strict"; + +const widget = document.querySelector("#captcha"); +const result = document.querySelector("#result"); +const start = document.querySelector("#start"); +const replay = document.querySelector("#replay"); +let token; +let submitted; + +async function verify(response) { + const reply = await fetch("/api/v1/sessions", { + method: "POST", + headers: {"Content-Type": "application/json"}, + body: JSON.stringify({country: "de", captchaToken: response}), + }); + const data = await reply.json(); + return {status: reply.status, created: reply.ok && Boolean(data.session), code: data.code}; +} + +async function init() { + const reply = await fetch("/api/v1/config"); + if (!reply.ok) throw new Error("Staging configuration is unavailable"); + const {captchaSiteKey} = await reply.json(); + if (!/^[a-zA-Z0-9_-]{1,64}$/.test(captchaSiteKey)) throw new Error("Invalid staging site key"); + widget.setAttribute("data-cap-api-endpoint", `${location.origin}/${captchaSiteKey}/`); + window.CAP_CUSTOM_WASM_URL = "/assets/cap_wasm_bg.wasm"; + window.CAP_CUSTOM_HASHWX_URL = "/assets/hashwx.wasm"; + window.CAP_ISOLATE = true; + widget.addEventListener("solve", (event) => { + token = event.detail.token; + start.disabled = false; + result.textContent = "Challenge solved. Create a staging session to verify the token."; + }); + widget.addEventListener("error", () => { + start.disabled = true; + result.textContent = "Challenge unavailable or rejected."; + }); + const script = document.createElement("script"); + script.src = "/assets/widget.js"; + script.onerror = () => { result.textContent = "Could not load the self-hosted widget."; }; + document.head.append(script); + result.textContent = "Complete the challenge to start."; +} + +start.onclick = async () => { + start.disabled = true; + submitted = token; + try { + const response = await verify(submitted); + result.textContent = response.created + ? "PASS: Cap verified and Shifter created a staging session." + : `Session rejected: ${response.code || response.status}`; + replay.disabled = !response.created; + } catch { + result.textContent = "Staging verifier unavailable."; + } +}; + +replay.onclick = async () => { + replay.disabled = true; + try { + const response = await verify(submitted); + result.textContent = response.status === 403 && response.code === "CAPTCHA_REJECTED" + ? "PASS: Shifter rejected reuse of the solved token." + : "FAIL: replay was not rejected as expected."; + } catch { + result.textContent = "Could not check replay."; + } +}; + +init().catch(() => { result.textContent = "Staging configuration is unavailable."; }); diff --git a/src/captcha.rs b/src/captcha.rs index 77e07a3..29f9340 100644 --- a/src/captcha.rs +++ b/src/captcha.rs @@ -1,4 +1,4 @@ -//! Google verification is always server-side; no configurable production verifier URL. +//! Production keeps server-side Google verification. Cap is a staging-only pilot. use crate::{State, config::now_ms}; use serde::Deserialize; @@ -27,6 +27,32 @@ pub async fn verify(state: &State, token: &str, hostname: &str) -> Result response + .json::() + .await + .map(|result| result.success) + .map_err(|_| ()), + 400 | 403 | 404 => Ok(false), + _ => Err(()), + }; + } let response = state .captcha_client .post("https://www.google.com/recaptcha/api/siteverify") @@ -44,9 +70,35 @@ pub async fn verify(state: &State, token: &str, hostname: &str) -> Result bool { + let mut parts = token.split(':'); + parts.next() == Some(site_key) + && parts.next().is_some_and(|part| !part.is_empty()) + && parts.next().is_some_and(|part| !part.is_empty()) + && parts.next().is_none() +} + #[cfg(test)] mod tests { use super::*; + + #[test] + fn cap_requires_the_expected_site_key_and_token_shape() { + assert!(cap_site_matches("pilot:challenge:answer", "pilot")); + for token in [ + "other:challenge:answer", + "pilot::answer", + "pilot:answer", + "pilot:x:y:z", + ] { + assert!(!cap_site_matches(token, "pilot")); + } + } #[test] fn verifier_rejects_expiry_hostname_failure_and_quota_errors() { let now = 1_700_000_000_000; diff --git a/src/config.rs b/src/config.rs index a78f600..5afd3dd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -173,6 +173,7 @@ pub struct Config { pub integrations: Vec, pub captcha_site_key: String, pub captcha_secret: String, + pub cap_staging: bool, pub runtime_origin: String, pub region: String, pub upstream_host: String, @@ -273,6 +274,35 @@ pub fn validate_captcha(site_key: &str, secret: &str, production: bool) -> Resul Ok(()) } +fn validate_cap_staging( + environment: &str, + role: &str, + control_origin: &str, + entries: &[Integration], + site_key: &str, + secret: &str, +) -> Result<()> { + if environment != "development" + || role != "api" + || !control_origin.starts_with("https://") + || control_origin.contains('*') + || entries.len() != 1 + || entries[0].origin != control_origin + { + bail!("Cap pilot requires a development API with one exact HTTPS control origin"); + } + if site_key.is_empty() + || site_key.len() > 64 + || !site_key + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"-_".contains(&c)) + || secret.is_empty() + { + bail!("Cap pilot requires a site key and a private site secret"); + } + Ok(()) +} + #[derive(Deserialize)] struct Secrets { shifter: Account, @@ -342,12 +372,25 @@ impl Config { if !["api", "gateway"].contains(&role.as_str()) { bail!("invalid ROLE"); } - let captcha_site_key = val("RECAPTCHA_SITE_KEY", ""); + let cap_staging = match val("CAPTCHA_PROVIDER", "recaptcha").as_str() { + "recaptcha" => false, + "cap-staging" => true, + _ => bail!("unknown CAPTCHA_PROVIDER"), + }; + if cap_staging && (environment != "development" || role != "api") { + bail!("Cap pilot is disabled outside a development API"); + } + let (site_key_var, secret_file_var) = if cap_staging { + ("CAP_STAGING_SITE_KEY", "CAP_STAGING_SECRET_FILE") + } else { + ("RECAPTCHA_SITE_KEY", "RECAPTCHA_SECRET_FILE") + }; + let captcha_site_key = val(site_key_var, ""); // Only the API process receives the verification secret. let captcha_secret = if role == "api" { - match env::var("RECAPTCHA_SECRET_FILE") { + match env::var(secret_file_var) { Ok(path) if !path.is_empty() => std::fs::read_to_string(path) - .map_err(|_| anyhow::anyhow!("cannot read RECAPTCHA_SECRET_FILE"))? + .map_err(|_| anyhow::anyhow!("cannot read {secret_file_var}"))? .trim() .to_owned(), _ => String::new(), @@ -355,7 +398,16 @@ impl Config { } else { String::new() }; - if role == "api" { + if cap_staging { + validate_cap_staging( + &environment, + &role, + &control_origin, + &integrations, + &captcha_site_key, + &captcha_secret, + )?; + } else if role == "api" { validate_captcha(&captcha_site_key, &captcha_secret, production)?; } let region = val("SHIFTER_REGION", "blr"); @@ -419,6 +471,7 @@ impl Config { integrations, captcha_site_key, captcha_secret, + cap_staging, runtime_origin, region, upstream_host, @@ -583,6 +636,48 @@ mod tests { ); } + #[test] + fn cap_is_restricted_to_a_single_https_development_api_origin() { + let origin = "https://staging.example.com"; + let entries = [Integration { + origin: origin.into(), + site: "pilot".into(), + }]; + let valid = |environment, role, control, site_key, secret| { + validate_cap_staging(environment, role, control, &entries, site_key, secret) + }; + assert!(valid("development", "api", origin, "cap_key", "secret").is_ok()); + for environment in ["production", "test"] { + assert!(valid(environment, "api", origin, "cap_key", "secret").is_err()); + } + assert!(valid("development", "gateway", origin, "cap_key", "secret").is_err()); + assert!( + valid( + "development", + "api", + "http://staging.example.com", + "cap_key", + "secret" + ) + .is_err() + ); + assert!( + valid( + "development", + "api", + "https://example.com", + "cap_key", + "secret" + ) + .is_err() + ); + assert!(valid("development", "api", origin, "../admin", "secret").is_err()); + assert!(valid("development", "api", origin, "cap_key", "").is_err()); + assert!( + validate_cap_staging("development", "api", origin, &[], "cap_key", "secret").is_err() + ); + } + #[test] fn wildcard_origins_match_subdomains_and_exact_entries_win() { let value = r#"[{"origin":"https://*.example.com","site":"wild"},{"origin":"https://example.com","site":"apex"},{"origin":"https://pinned.example.com","site":"pinned"}]"#;