From b88ad1edf9b9b114632ed7312c68d0e21ad3f16c Mon Sep 17 00:00:00 2001 From: Horiz Date: Fri, 27 Nov 2026 03:56:37 +0900 Subject: [PATCH] feat(auth): add per-IP rate limit for login and OAuth token endpoints Replaces Cloudflare ruleset auth_rate_limit (F-05 c1), which stopped applying when torosaba.net left the Cloudflare Tunnel for the direct path on 2026-11-27. 20 requests per 10 seconds per client IP on /login, /oauth/register and /oauth/token; the 21st request starts a 10 second block answered with 429 and Retry-After: 10. Client IP comes from the X-Toro-Client-Ip header set by toro-edge (Caddy strips client-supplied values). No new dependency. --- src/lib.rs | 4 + src/rate_limit.rs | 231 ++++++++++++++++++++++++++++++++++++++++++++ src/routes.rs | 15 ++- tests/rate_limit.rs | 63 ++++++++++++ tests/security.rs | 11 ++- 5 files changed, 321 insertions(+), 3 deletions(-) create mode 100644 src/rate_limit.rs create mode 100644 tests/rate_limit.rs diff --git a/src/lib.rs b/src/lib.rs index e06d923..4f79445 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ pub mod http; pub mod internal; pub mod jwt; pub mod oauth; +pub mod rate_limit; pub mod reject_log; pub mod routes; pub mod site; @@ -43,6 +44,8 @@ pub struct App { /// 使い終わった認可コードの jti と有効期限 (再利用を断るため) pub used_codes: Mutex>, pub requests: Semaphore, + /// auth のレート制限 (F-05 c1)。対象は /login、/oauth/register、/oauth/token。 + pub auth_rate_limit: rate_limit::AuthRateLimit, pub tokens: auth::tokens::TokenStore, /// ブラウザのセッションの世代 (ログアウトで進めて、前のセッションを失効させる) pub sessions: auth::generations::SessionGenerations, @@ -73,6 +76,7 @@ impl App { http, used_codes: Mutex::new(HashMap::new()), requests: Semaphore::new(MAX_CONCURRENT_REQUESTS), + auth_rate_limit: rate_limit::AuthRateLimit::new(), }) } diff --git a/src/rate_limit.rs b/src/rate_limit.rs new file mode 100644 index 0000000..72f33a4 --- /dev/null +++ b/src/rate_limit.rs @@ -0,0 +1,231 @@ +//! auth のレート制限。Cloudflare の ruleset `auth_rate_limit` (F-05 c1) の同等措置。 +//! +//! 2026-11-27 03:00 JST の DNS 切替で torosaba.net が Cloudflare Tunnel を離れ、 +//! 直接経路となったため、Cloudflare 側の規則は適用されなくなった。その代替として、 +//! 対象の 3 経路への要求をこのサービス内で数える。 +//! +//! 規則: クライアント IP ごとに直近 10 秒で 20 件まで。21 件目で 10 秒間の遮断に入る。 +//! 遮断中の要求は数えない。遮断が明けたら計数は空の状態から始まる。 +//! +//! クライアント IP は toro-edge が設定する `X-Toro-Client-Ip` から読む。Caddy が +//! 客の書いた値を除去し、`Cf-Connecting-Ip` へ接続元の IP を入れるため、この値は +//! 信頼できる。ヘッダーが無い場合(直接のコンソール経路)は 1 つの共有キーで数える。 +//! Cloudflare の規則も直接の迂回路には適用されなかったため、この扱いは整合する。 +//! +//! 制限超過への応答は 429 Too Many Requests と `Retry-After: 10` である。 +//! 2026-11-20 の実測では Cloudflare の block も 21 件目から 429 を返し、 +//! 10 秒後に復帰したため、応答は同一である。 + +use std::collections::{HashMap, VecDeque}; +use std::net::IpAddr; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use axum::http::HeaderMap; + +/// 制限の対象経路。Cloudflare の規則と同一。 +pub const LIMITED_PATHS: [&str; 3] = ["/login", "/oauth/register", "/oauth/token"]; +/// 計数する時間幅(秒)。 +pub const WINDOW_SECS: u64 = 10; +/// 1 つの時間幅あたりに許す要求数。 +pub const MAX_REQUESTS: usize = 20; +/// 制限超過後に遮断する時間(秒)。 +pub const BLOCK_SECS: u64 = 10; +/// `Retry-After` ヘッダーの値。`BLOCK_SECS` と同一。 +pub const RETRY_AFTER: &str = "10"; + +/// toro-edge が設定するクライアント IP のヘッダー。 +const CLIENT_IP_HEADER: &str = "x-toro-client-ip"; + +/// 制限の対象経路かどうか。 +pub fn is_limited_path(path: &str) -> bool { + LIMITED_PATHS.contains(&path) +} + +/// 要求元の識別子。 +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum ClientKey { + /// ヘッダーから読んだクライアント IP。 + Ip(IpAddr), + /// ヘッダーが無い直接接続。すべて 1 つの共有キーで数える。 + Direct, +} + +/// 要求ヘッダーから要求元の識別子を読み取る。 +pub fn client_key(headers: &HeaderMap) -> ClientKey { + let Some(value) = headers.get(CLIENT_IP_HEADER) else { + return ClientKey::Direct; + }; + let Ok(text) = value.to_str() else { + return ClientKey::Direct; + }; + // 複数値の場合は先頭だけを見る。 + let first = text.split(',').next().unwrap_or("").trim(); + match first.parse::() { + Ok(ip) => ClientKey::Ip(ip), + Err(_) => ClientKey::Direct, + } +} + +#[derive(Debug, Default)] +struct Entry { + /// 直近の要求時刻。古いものから順に入る。 + hits: VecDeque, + /// 遮断中の場合は遮断の終了時刻。 + blocked_until: Option, +} + +#[derive(Debug, Default)] +struct State { + entries: HashMap, +} + +/// auth のレート制限。1 プロセス内で共有する。 +#[derive(Debug, Default)] +pub struct AuthRateLimit { + state: Mutex, +} + +impl AuthRateLimit { + pub fn new() -> Self { + Self::default() + } + + /// 要求を許す場合は true。制限超過の場合は false。 + pub fn allow(&self, key: &ClientKey) -> bool { + self.allow_at(key, Instant::now()) + } + + fn allow_at(&self, key: &ClientKey, now: Instant) -> bool { + let mut state = self.state.lock().expect("rate limit lock"); + let window = Duration::from_secs(WINDOW_SECS); + // 活動の無い項目を捨てて地図の肥大を防ぐ。 + state.entries.retain(|_, entry| { + entry.blocked_until.is_some_and(|until| until > now) + || entry + .hits + .back() + .is_some_and(|last| now.saturating_duration_since(*last) < window) + }); + let entry = state.entries.entry(key.clone()).or_default(); + if let Some(until) = entry.blocked_until { + if now < until { + return false; + } + entry.blocked_until = None; + } + while entry + .hits + .front() + .is_some_and(|first| now.saturating_duration_since(*first) >= window) + { + entry.hits.pop_front(); + } + if entry.hits.len() >= MAX_REQUESTS { + entry.blocked_until = Some(now + Duration::from_secs(BLOCK_SECS)); + return false; + } + entry.hits.push_back(now); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn limiter() -> AuthRateLimit { + AuthRateLimit::new() + } + + fn key(ip: &str) -> ClientKey { + ClientKey::Ip(ip.parse().unwrap()) + } + + #[test] + fn allows_twenty_then_blocks() { + let limit = limiter(); + let key = key("203.0.113.7"); + let now = Instant::now(); + for _ in 0..MAX_REQUESTS { + assert!(limit.allow_at(&key, now)); + } + assert!(!limit.allow_at(&key, now)); + } + + #[test] + fn block_lasts_ten_seconds_then_allows() { + let limit = limiter(); + let key = key("203.0.113.7"); + let now = Instant::now(); + for _ in 0..MAX_REQUESTS { + assert!(limit.allow_at(&key, now)); + } + assert!(!limit.allow_at(&key, now)); + // 遮断中は 9 秒後でも通らない。 + assert!(!limit.allow_at(&key, now + Duration::from_secs(9))); + // 10 秒後に遮断が明け、計数は空から始まる。 + assert!(limit.allow_at(&key, now + Duration::from_secs(10))); + } + + #[test] + fn window_slides() { + let limit = limiter(); + let key = key("203.0.113.7"); + let now = Instant::now(); + for _ in 0..MAX_REQUESTS { + assert!(limit.allow_at(&key, now)); + } + // 10 秒後には最初の 20 件が時間幅の外へ出るため通る。 + assert!(limit.allow_at(&key, now + Duration::from_secs(10))); + } + + #[test] + fn keys_are_independent() { + let limit = limiter(); + let first = key("203.0.113.7"); + let second = key("198.51.100.1"); + let now = Instant::now(); + for _ in 0..MAX_REQUESTS { + assert!(limit.allow_at(&first, now)); + } + assert!(!limit.allow_at(&first, now)); + assert!(limit.allow_at(&second, now)); + } + + #[test] + fn client_key_reads_the_edge_header() { + let mut headers = HeaderMap::new(); + headers.insert(CLIENT_IP_HEADER, "203.0.113.7".parse().unwrap()); + assert_eq!(client_key(&headers), key("203.0.113.7")); + + headers.insert(CLIENT_IP_HEADER, "2001:db8::1".parse().unwrap()); + assert_eq!(client_key(&headers), key("2001:db8::1")); + + // 複数値の場合は先頭だけを見る。 + headers.insert( + CLIENT_IP_HEADER, + "203.0.113.7, 198.51.100.1".parse().unwrap(), + ); + assert_eq!(client_key(&headers), key("203.0.113.7")); + + // 値が IP ではない場合は直接接続として扱う。 + headers.insert(CLIENT_IP_HEADER, "not-an-ip".parse().unwrap()); + assert_eq!(client_key(&headers), ClientKey::Direct); + + // ヘッダーが無い場合も直接接続として扱う。 + let empty = HeaderMap::new(); + assert_eq!(client_key(&empty), ClientKey::Direct); + } + + #[test] + fn limited_paths_match_the_cloudflare_rule() { + assert!(is_limited_path("/login")); + assert!(is_limited_path("/oauth/register")); + assert!(is_limited_path("/oauth/token")); + assert!(!is_limited_path("/")); + assert!(!is_limited_path("/oauth/authorize")); + assert!(!is_limited_path("/oauth/userinfo")); + assert!(!is_limited_path("/healthz")); + } +} diff --git a/src/routes.rs b/src/routes.rs index 239a1ac..0afb61c 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -12,7 +12,7 @@ use axum::response::Response; use serde_json::json; use crate::http::{self, Ctx}; -use crate::{App, auth, home, oauth, static_files}; +use crate::{App, auth, home, oauth, rate_limit, static_files}; const MAX_BODY_BYTES: usize = 2 * 1024 * 1024; @@ -41,6 +41,19 @@ async fn answer(app: &App, request: Request) -> Response { let ctx = Ctx::new(&parts, Default::default(), &app.cfg); return http::json(&ctx, &json!({ "ok": true }), 200); } + // auth のレート制限 (F-05 c1 の Cloudflare 規則の同等措置)。本体の処理の前に断る。 + if rate_limit::is_limited_path(parts.uri.path()) { + let key = rate_limit::client_key(&parts.headers); + if !app.auth_rate_limit.allow(&key) { + let ctx = Ctx::new(&parts, Default::default(), &app.cfg); + let mut res = http::json(&ctx, &json!({ "error": "Too Many Requests" }), 429); + res.headers_mut().insert( + header::RETRY_AFTER, + HeaderValue::from_static(rate_limit::RETRY_AFTER), + ); + return res; + } + } // 同時に処理する数を限り、ボディの分も含めてメモリの使用量に上限を設ける let Ok(_permit) = app.requests.try_acquire() else { return http::busy(); diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs new file mode 100644 index 0000000..82205f6 --- /dev/null +++ b/tests/rate_limit.rs @@ -0,0 +1,63 @@ +//! auth のレート制限の統合試験。 +//! +//! 対象は /login、/oauth/register、/oauth/token。要求元の識別子は toro-edge が +//! 設定する `X-Toro-Client-Ip` ヘッダーから読むため、試験ではヘッダーで IP を変える。 + +mod common; + +use axum::http::header; +use common::{TestServer, start}; + +const CLIENT_IP: &str = "x-toro-client-ip"; +const LOGIN: &str = "/login?redirect=https://wiki.torosaba.net/"; + +async fn login(server: &TestServer, ip: &str) -> reqwest::Response { + server + .client + .get(server.url(LOGIN)) + .header(CLIENT_IP, ip) + .send() + .await + .unwrap() +} + +#[tokio::test] +async fn twenty_first_request_from_one_ip_is_blocked() { + let server = start().await; + let ip = "203.0.113.7"; + for _ in 0..20 { + let res = login(&server, ip).await; + assert_eq!(res.status(), 302); + } + let blocked = login(&server, ip).await; + assert_eq!(blocked.status(), 429); + assert_eq!(blocked.headers()[header::RETRY_AFTER], "10"); + let body: serde_json::Value = blocked.json().await.unwrap(); + assert_eq!(body["error"], "Too Many Requests"); +} + +#[tokio::test] +async fn limit_is_per_client_ip() { + let server = start().await; + for _ in 0..20 { + assert_eq!(login(&server, "203.0.113.7").await.status(), 302); + } + assert_eq!(login(&server, "203.0.113.7").await.status(), 429); + // 別の IP は制限にかからない。 + assert_eq!(login(&server, "198.51.100.1").await.status(), 302); +} + +#[tokio::test] +async fn other_paths_are_not_limited() { + let server = start().await; + for _ in 0..25 { + let res = server + .client + .get(server.url("/.well-known/openid-configuration")) + .header(CLIENT_IP, "203.0.113.7") + .send() + .await + .unwrap(); + assert_eq!(res.status(), 200); + } +} diff --git a/tests/security.rs b/tests/security.rs index 25ba845..bd887a8 100644 --- a/tests/security.rs +++ b/tests/security.rs @@ -554,10 +554,17 @@ async fn health_checks_answer_even_when_every_slot_is_taken() { let address = server.base.strip_prefix("http://").unwrap(); // ボディを送らないまま待つ接続で、同時処理の枠 (256) をすべて埋める let mut streams = Vec::new(); - for _ in 0..256 { + // /oauth/token はレート制限の対象のため、要求ごとに別のクライアント IP を + // 入れて制限にかからないようにする。 + for i in 0..256 { let mut stream = tokio::net::TcpStream::connect(address).await.unwrap(); stream - .write_all(b"POST /oauth/token HTTP/1.1\r\nHost: x\r\nContent-Length: 10\r\n\r\n") + .write_all( + format!( + "POST /oauth/token HTTP/1.1\r\nHost: x\r\nX-Toro-Client-Ip: 10.0.{i}.1\r\nContent-Length: 10\r\n\r\n" + ) + .as_bytes(), + ) .await .unwrap(); streams.push(stream);