Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions deploy/cap-staging/Caddyfile.example
Original file line number Diff line number Diff line change
@@ -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
}
}
26 changes: 26 additions & 0 deletions deploy/cap-staging/README.md
Original file line number Diff line number Diff line change
@@ -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.
82 changes: 82 additions & 0 deletions deploy/cap-staging/compose.example.yaml
Original file line number Diff line number Diff line change
@@ -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
20 changes: 20 additions & 0 deletions deploy/cap-staging/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Shifter Cap staging pilot</title>
<style>
body { font: 1rem/1.55 Georgia, serif; max-width: 44rem; margin: 10vh auto; padding: 1.5rem;
color: #17372e; background: #f4f2e8; }
button { font: inherit; padding: .45rem .8rem; }
</style>
<main>
<h1>Shifter Cap staging pilot</h1>
<p>This page tests session creation only. It does not open a proxy connection or use production credentials.</p>
<cap-widget id="captcha"></cap-widget>
<p id="result" role="status">Loading the staging verifier…</p>
<button id="start" disabled>Create staging session</button>
<button id="replay" disabled>Check replay rejection</button>
</main>
<script defer src="/pilot.js"></script>
</html>
71 changes: 71 additions & 0 deletions deploy/cap-staging/pilot.js
Original file line number Diff line number Diff line change
@@ -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."; });
54 changes: 53 additions & 1 deletion src/captcha.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -27,6 +27,32 @@ pub async fn verify(state: &State, token: &str, hostname: &str) -> Result<bool,
if state.cfg.captcha_secret.is_empty() {
return Err(());
}
if state.cfg.cap_staging {
let site_key = &state.cfg.captcha_site_key;
if !cap_site_matches(token, site_key) {
return Ok(false);
}
// The pilot's isolated Compose network is the only Cap verifier target.
let response = state
.captcha_client
.post(format!("http://capd:3000/{site_key}/siteverify"))
.json(&serde_json::json!({
"secret": state.cfg.captcha_secret,
"response": token,
}))
.send()
.await
.map_err(|_| ())?;
return match response.status().as_u16() {
200 => response
.json::<CapVerification>()
.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")
Expand All @@ -44,9 +70,35 @@ pub async fn verify(state: &State, token: &str, hostname: &str) -> Result<bool,
Ok(valid(&result, hostname, now_ms()))
}

#[derive(Deserialize)]
struct CapVerification {
success: bool,
}

fn cap_site_matches(token: &str, site_key: &str) -> 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;
Expand Down
Loading