Cloudflare Turnstile on e-mail sign-up and password reset, and a limit per address
- The sign-up and "forgot password" forms carry a token from Cloudflare Turnstile's widget (managed, shown only when Cloudflare asks for a click); the backend checks it before an e-mail goes out. Off without TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY (development); the site key comes to the page through /v1/config. - At most ten such e-mail requests an hour per visitor address, so a script cannot make the site mail thousands of strangers. - The privacy notice (HU, EN) mentions Turnstile with Cloudflare. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -110,6 +110,10 @@ pub struct Config {
|
||||
/// Object storage of the uploaded photos (see [`crate::storage`]); `None`
|
||||
/// when `S3_ENDPOINT` is not set (photo uploads are then refused).
|
||||
pub storage: Option<crate::storage::StorageConfig>,
|
||||
/// `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`: Cloudflare Turnstile
|
||||
/// on the e-mail sign-up and password reset forms (see [`crate::turnstile`]);
|
||||
/// `None` without both (development): no check.
|
||||
pub turnstile: Option<crate::turnstile::TurnstileConfig>,
|
||||
/// `S3_CREATE_BUCKET` (default false): create the bucket at startup if it
|
||||
/// is missing (development; in production it is made in the console).
|
||||
pub storage_create_bucket: bool,
|
||||
@@ -226,6 +230,14 @@ impl Config {
|
||||
Some("open") => SignupMode::Open,
|
||||
Some(other) => bail!("invalid SIGNUP_MODE '{other}': use 'invite' or 'open'"),
|
||||
},
|
||||
turnstile: match (var("TURNSTILE_SITE_KEY"), var("TURNSTILE_SECRET_KEY")) {
|
||||
(Some(site_key), Some(secret)) => Some(crate::turnstile::TurnstileConfig {
|
||||
site_key,
|
||||
secret,
|
||||
verify_url: var("TURNSTILE_VERIFY_URL").unwrap_or_else(|| crate::turnstile::VERIFY_URL.to_string()),
|
||||
}),
|
||||
_ => None,
|
||||
},
|
||||
storage: match var("S3_ENDPOINT") {
|
||||
None => None,
|
||||
Some(endpoint) => Some(crate::storage::StorageConfig {
|
||||
@@ -279,6 +291,7 @@ impl Config {
|
||||
max_charts_per_user: 50,
|
||||
free_person_slots: 5,
|
||||
signup_mode: SignupMode::Open,
|
||||
turnstile: None,
|
||||
storage: Some(crate::storage::StorageConfig {
|
||||
endpoint: format!("{horoscope_api_url}/s3"),
|
||||
bucket: "photos".into(),
|
||||
|
||||
@@ -23,6 +23,7 @@ mod storage;
|
||||
mod stripe;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod turnstile;
|
||||
mod views;
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -49,6 +50,9 @@ pub struct AppState {
|
||||
pub calculator_limiter: LoginLimiter,
|
||||
/// The public place search (typing makes several calls), per visitor address.
|
||||
pub places_limiter: LoginLimiter,
|
||||
/// E-mail sign-ups and password reset requests, per visitor address (each
|
||||
/// sends an e-mail, so a script must not send thousands).
|
||||
pub signup_limiter: LoginLimiter,
|
||||
/// Share visits already counted (link and visitor address, for half an hour):
|
||||
/// a reload is not a new visit, without storing anything in the browser.
|
||||
pub share_visits: LoginLimiter,
|
||||
@@ -70,6 +74,7 @@ impl AppState {
|
||||
calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)),
|
||||
places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)),
|
||||
share_visits: LoginLimiter::new(1, Duration::from_secs(30 * 60)),
|
||||
signup_limiter: LoginLimiter::new(10, Duration::from_secs(60 * 60)),
|
||||
models: models::Catalog::new(&config.openrouter_models_url),
|
||||
stripe: stripe::Client::default(),
|
||||
storage: config.storage.clone().map(storage::Storage::new),
|
||||
|
||||
@@ -227,6 +227,19 @@ pub struct RegisterRequest {
|
||||
invite_token: Option<String>,
|
||||
/// The slug of the shared link the visitor came from.
|
||||
referral: Option<String>,
|
||||
/// Cloudflare Turnstile's token (see [`crate::turnstile`]).
|
||||
#[serde(default)]
|
||||
turnstile_token: Option<String>,
|
||||
}
|
||||
|
||||
/// Before a sign-up or reset e-mail goes out: at most a few per visitor
|
||||
/// address an hour, and Cloudflare Turnstile's check when it is set up.
|
||||
async fn not_a_robot(state: &AppState, headers: &axum::http::HeaderMap, token: Option<&str>) -> Result<(), ApiError> {
|
||||
let ip = super::client_ip(headers);
|
||||
if let Some(ip) = &ip {
|
||||
state.signup_limiter.hit(ip)?;
|
||||
}
|
||||
crate::turnstile::verify(state.config.turnstile.as_ref(), token, ip.as_deref()).await
|
||||
}
|
||||
|
||||
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
|
||||
@@ -244,10 +257,12 @@ pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> {
|
||||
/// password instead), so the form does not reveal who is registered.
|
||||
pub async fn register(
|
||||
State(state): St,
|
||||
headers: axum::http::HeaderMap,
|
||||
WithRejection(Json(req), _): Body<RegisterRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
password_login_enabled(&state)?;
|
||||
let email = normalize_email(&req.email)?;
|
||||
not_a_robot(&state, &headers, req.turnstile_token.as_deref()).await?;
|
||||
let locale = validate_locale(&state, req.locale.as_deref())?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
@@ -553,6 +568,9 @@ pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> Api
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResetRequest {
|
||||
email: String,
|
||||
/// Cloudflare Turnstile's token (see [`crate::turnstile`]).
|
||||
#[serde(default)]
|
||||
turnstile_token: Option<String>,
|
||||
}
|
||||
|
||||
/// Forgotten password: a link to set a new one (also adds a password to a
|
||||
@@ -560,9 +578,11 @@ pub struct ResetRequest {
|
||||
/// whether the address is registered.
|
||||
pub async fn request_password_reset(
|
||||
State(state): St,
|
||||
headers: axum::http::HeaderMap,
|
||||
WithRejection(Json(req), _): Body<ResetRequest>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
password_login_enabled(&state)?;
|
||||
not_a_robot(&state, &headers, req.turnstile_token.as_deref()).await?;
|
||||
let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) };
|
||||
let mut tx = state.db.begin().await?;
|
||||
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE"))
|
||||
|
||||
@@ -233,5 +233,7 @@ async fn public_config(State(state): St) -> Json<Value> {
|
||||
"referral_rewards": c.referral_rewards,
|
||||
"signup_mode": c.signup_mode.as_str(),
|
||||
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
||||
// Cloudflare Turnstile on the e-mail sign-up and reset forms (null: none).
|
||||
"turnstile_site_key": c.turnstile.as_ref().map(|t| t.site_key.clone()),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -226,12 +226,20 @@ async fn fake_s3(
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloudflare Turnstile: the token "ok" with the test secret passes.
|
||||
async fn fake_turnstile(axum::Form(form): axum::Form<std::collections::HashMap<String, String>>) -> Json<Value> {
|
||||
let ok = form.get("secret").map(String::as_str) == Some("test-secret")
|
||||
&& form.get("response").map(String::as_str) == Some("ok");
|
||||
Json(json!({ "success": ok, "error-codes": if ok { json!([]) } else { json!(["invalid-input-response"]) } }))
|
||||
}
|
||||
|
||||
async fn fake_services_with(s3: FakeS3) -> String {
|
||||
let objects = Router::new().route("/s3/photos/{*key}", get(fake_s3).put(fake_s3).delete(fake_s3)).with_state(s3);
|
||||
let app = Router::new()
|
||||
.merge(objects)
|
||||
.route("/billingo/documents/{id}/download", get(fake_billingo_pdf))
|
||||
.route("/openrouter/models", get(fake_openrouter_models))
|
||||
.route("/turnstile/siteverify", post(fake_turnstile))
|
||||
.route("/v1/checkout/sessions", post(fake_stripe_create))
|
||||
.route("/v1/checkout/sessions/{id}", get(fake_stripe_get))
|
||||
.route("/v1/refunds", post(fake_stripe_refund))
|
||||
@@ -4031,3 +4039,42 @@ async fn a_gift_can_be_e_mailed_at_a_chosen_time(pool: PgPool) {
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn email_sign_up_checks_turnstile_and_limits_each_address(pool: PgPool) {
|
||||
let app = TestApp::with_config(pool, |c| {
|
||||
c.turnstile = Some(crate::turnstile::TurnstileConfig {
|
||||
site_key: "site-key".into(),
|
||||
secret: "test-secret".into(),
|
||||
verify_url: format!("{}/turnstile/siteverify", c.horoscope_api_url),
|
||||
});
|
||||
})
|
||||
.await;
|
||||
assert_eq!(app.get("/v1/config", None).await.body["turnstile_site_key"], "site-key");
|
||||
let ip = [("x-real-ip", "203.0.113.50")];
|
||||
let sign_up = |token: Option<&str>| json!({ "email": "anna@example.com", "turnstile_token": token });
|
||||
|
||||
// No token or a wrong one: no account, no e-mail.
|
||||
for token in [None, Some("rossz")] {
|
||||
let r = app.call_with("POST", "/v1/auth/register", None, Some(sign_up(token)), &ip).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST, "{}", r.body);
|
||||
}
|
||||
let users: i64 = sqlx::query_scalar("SELECT count(*) FROM users").fetch_one(&app.pool).await.unwrap();
|
||||
assert_eq!(users, 0);
|
||||
let r = app.call_with("POST", "/v1/auth/register", None, Some(sign_up(Some("ok"))), &ip).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
let reset = |token: Option<&str>| json!({ "email": "anna@example.com", "turnstile_token": token });
|
||||
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(None)), &ip).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
|
||||
// Ten e-mail requests an hour from one address (the four above count too).
|
||||
for _ in 0..6 {
|
||||
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &ip).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
}
|
||||
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &ip).await;
|
||||
assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
|
||||
let elsewhere = [("x-real-ip", "198.51.100.60")];
|
||||
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &elsewhere).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Cloudflare Turnstile: the e-mail sign-up and the password reset forms
|
||||
//! carry a token from Cloudflare's widget (usually invisible), checked here
|
||||
//! before an e-mail goes out. Without the keys (development) there is no
|
||||
//! check. Cloudflare not answering counts as a failed check.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::error::ApiError;
|
||||
|
||||
pub const VERIFY_URL: &str = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TurnstileConfig {
|
||||
/// Public: the page's widget uses it (`/v1/config`).
|
||||
pub site_key: String,
|
||||
pub secret: String,
|
||||
pub verify_url: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Answer {
|
||||
success: bool,
|
||||
#[serde(default, rename = "error-codes")]
|
||||
error_codes: Vec<String>,
|
||||
}
|
||||
|
||||
fn client() -> &'static reqwest::Client {
|
||||
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
|
||||
CLIENT.get_or_init(|| reqwest::Client::builder().timeout(Duration::from_secs(8)).build().expect("an HTTP client"))
|
||||
}
|
||||
|
||||
fn refused() -> ApiError {
|
||||
ApiError::BadRequest("Kérjük, igazold, hogy nem robot vagy (az ellenőrzés nem sikerült), és próbáld újra.".into())
|
||||
}
|
||||
|
||||
/// Checks the widget's token (with the visitor's address, when known).
|
||||
pub async fn verify(config: Option<&TurnstileConfig>, token: Option<&str>, ip: Option<&str>) -> Result<(), ApiError> {
|
||||
let Some(config) = config else { return Ok(()) };
|
||||
let token = token.map(str::trim).filter(|t| !t.is_empty() && t.len() <= 2048).ok_or_else(refused)?;
|
||||
let mut form = vec![("secret", config.secret.as_str()), ("response", token)];
|
||||
if let Some(ip) = ip {
|
||||
form.push(("remoteip", ip));
|
||||
}
|
||||
let answer: Answer = match client().post(&config.verify_url).form(&form).send().await {
|
||||
Ok(res) => res.json().await.map_err(|e| {
|
||||
tracing::warn!(error = %e, "turnstile answer not understood");
|
||||
refused()
|
||||
})?,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "turnstile not reachable");
|
||||
return Err(refused());
|
||||
}
|
||||
};
|
||||
if answer.success {
|
||||
Ok(())
|
||||
} else {
|
||||
tracing::info!(codes = ?answer.error_codes, "turnstile check failed");
|
||||
Err(refused())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user