Skip to content
Merged
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
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -43,6 +44,8 @@ pub struct App {
/// 使い終わった認可コードの jti と有効期限 (再利用を断るため)
pub used_codes: Mutex<HashMap<String, i64>>,
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,
Expand Down Expand Up @@ -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(),
})
}

Expand Down
231 changes: 231 additions & 0 deletions src/rate_limit.rs
Original file line number Diff line number Diff line change
@@ -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::<IpAddr>() {
Ok(ip) => ClientKey::Ip(ip),
Err(_) => ClientKey::Direct,
}
}

#[derive(Debug, Default)]
struct Entry {
/// 直近の要求時刻。古いものから順に入る。
hits: VecDeque<Instant>,
/// 遮断中の場合は遮断の終了時刻。
blocked_until: Option<Instant>,
}

#[derive(Debug, Default)]
struct State {
entries: HashMap<ClientKey, Entry>,
}

/// auth のレート制限。1 プロセス内で共有する。
#[derive(Debug, Default)]
pub struct AuthRateLimit {
state: Mutex<State>,
}

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"));
}
}
15 changes: 14 additions & 1 deletion src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
Expand Down
63 changes: 63 additions & 0 deletions tests/rate_limit.rs
Original file line number Diff line number Diff line change
@@ -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);
}
}
11 changes: 9 additions & 2 deletions tests/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down