diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 86be61aa26..6eb982ac3a 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -2310,7 +2310,12 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { ); } handles.push(tokio::spawn(async move { - if let Err(e) = axum::serve(listener, web_router).await { + if let Err(e) = axum::serve( + listener, + web_router.into_make_service_with_connect_info::(), + ) + .await + { tracing::error!("web server error: {}", e); } })); diff --git a/pkgs/id/crates/id-web/src/lib.rs b/pkgs/id/crates/id-web/src/lib.rs index 4bd4aea784..ccdf5f973d 100644 --- a/pkgs/id/crates/id-web/src/lib.rs +++ b/pkgs/id/crates/id-web/src/lib.rs @@ -68,7 +68,7 @@ pub use markdown::{ use axum::Router; use iroh_blobs::api::Store; -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::sync::Mutex; @@ -237,6 +237,153 @@ impl Drop for SavePermit { } } +/// Default number of successful registrations one source may complete +/// inside [`DEFAULT_REGISTER_WINDOW`] before the register handler starts +/// refusing with 429 (#1766). +pub const DEFAULT_REGISTER_LIMIT: usize = 10; + +/// Default registration rate-limit window (#1766). +pub const DEFAULT_REGISTER_WINDOW: Duration = Duration::from_secs(60); + +/// Per-source rate limiter for `POST /api/identity/register` (#1766). +/// +/// The identity store's admission cap bounds how many identities can +/// exist, but the register handler itself was unthrottled: a caller on +/// a non-loopback bind could burn request-rate CPU/IO and squat cap +/// slots with junk registrations. This limiter follows the +/// [`SaveRateLimiter`] pattern — a per-key map whose entries are swept +/// once they can no longer refuse, so the map holds only sources +/// active inside the current window (#1713 discipline). +/// +/// The key is the request's source (the peer IP, supplied by the +/// listener's connect-info; see `identity_register_handler` in +/// `routes.rs`). Forwarded headers are never consulted: on the +/// directly exposed listener they are client-spoofable (the +/// `security.rs` doctrine). Only *successful* registrations are +/// counted — a refusal at the admission cap or a failed attempt does +/// not consume budget. The check/record split means a concurrent +/// burst can overshoot the limit by the number of requests in flight; +/// that tolerance is immaterial against the sustained-rate +/// cap-squatting this limiter exists to stop. +#[derive(Debug, Clone)] +pub struct RegisterRateLimiter { + /// Map of source key → timestamps of successful registrations + /// inside the current window, oldest first. + attempts: Arc>>>, + /// Maximum successful registrations per source inside `window`. + pub limit: usize, + /// Sliding window length. + pub window: Duration, +} + +impl RegisterRateLimiter { + /// Create a new registration rate limiter. + pub fn new(limit: usize, window: Duration) -> Self { + Self { + attempts: Arc::new(Mutex::new(HashMap::new())), + limit, + window, + } + } + + /// Drop one source's aged-out timestamps; returns the number of + /// in-window registrations remaining for it. + fn prune(times: &mut VecDeque, now: Instant, window: Duration) -> usize { + while times + .front() + .is_some_and(|t| now.duration_since(*t) >= window) + { + times.pop_front(); + } + times.len() + } + + /// Check whether a registration from `source` is allowed now. + /// + /// Returns `Ok(())` if the source is under its limit, or + /// `Err(remaining)` with the time until the oldest in-window + /// registration ages out and a new one is allowed. + pub async fn check(&self, source: &str) -> Result<(), Duration> { + if self.limit == 0 { + return Err(self.window); + } + let mut map = self.attempts.lock().await; + let now = Instant::now(); + if let Some(times) = map.get_mut(source) { + if Self::prune(times, now, self.window) >= self.limit { + // The front is the oldest in-window registration + // (prune kept it because it is younger than the + // window), so the remaining wait is exact. + let oldest = *times.front().unwrap_or(&now); + return Err(self + .window + .checked_sub(now.duration_since(oldest)) + .unwrap_or(Duration::ZERO)); + } + if times.is_empty() { + map.remove(source); + } + } + Ok(()) + } + + /// Record a successful registration from `source`. + pub async fn record(&self, source: &str) { + let mut map = self.attempts.lock().await; + let now = Instant::now(); + // Sweep every source's aged-out entries: they can no longer + // refuse a registration, and keeping them would grow the map + // by one entry for every source ever seen (#1713). + map.retain(|_, times| Self::prune(times, now, self.window) > 0); + map.entry(source.to_owned()).or_default().push_back(now); + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod register_rate_limiter_tests { + use super::*; + + #[tokio::test] + async fn under_limit_is_allowed_and_over_limit_is_refused() { + let limiter = RegisterRateLimiter::new(2, Duration::from_secs(60)); + limiter.check("203.0.113.7").await.unwrap(); + limiter.record("203.0.113.7").await; + limiter.check("203.0.113.7").await.unwrap(); + limiter.record("203.0.113.7").await; + let remaining = limiter.check("203.0.113.7").await.unwrap_err(); + assert!(remaining > Duration::ZERO && remaining <= Duration::from_secs(60)); + } + + #[tokio::test] + async fn sources_are_independent() { + let limiter = RegisterRateLimiter::new(1, Duration::from_secs(60)); + limiter.record("198.51.100.1").await; + assert!(limiter.check("198.51.100.1").await.is_err()); + limiter.check("198.51.100.2").await.unwrap(); + } + + #[tokio::test] + async fn window_expiry_allows_registration_again() { + let limiter = RegisterRateLimiter::new(1, Duration::from_millis(60)); + limiter.record("192.0.2.9").await; + assert!(limiter.check("192.0.2.9").await.is_err()); + tokio::time::sleep(Duration::from_millis(90)).await; + limiter.check("192.0.2.9").await.unwrap(); + } + + #[tokio::test] + async fn zero_window_never_refuses() { + // The routes tests disable the save limiter with a ZERO + // cooldown; a ZERO window is the same off switch here. + let limiter = RegisterRateLimiter::new(1, Duration::ZERO); + for _ in 0..5 { + limiter.record("203.0.113.99").await; + limiter.check("203.0.113.99").await.unwrap(); + } + } +} + /// Dynamic publication path mounts (#2147 slice 3): mount path -> /// world name, shared by every clone of an [`AppState`] (all web /// listeners of one serve process) and by the serve-owned publication @@ -357,6 +504,8 @@ pub struct AppState { pub tag_store: Arc, /// Per-file save rate limiter. pub save_limiter: SaveRateLimiter, + /// Per-source registration rate limiter (#1766). + pub register_limiter: RegisterRateLimiter, /// Serializes filename-tag claims (upload name resolution, create /// existence check, save tag assignment) and the filename-keyed /// metadata writes across clones of this state (#2363, #8407). @@ -411,6 +560,7 @@ impl std::fmt::Debug for AppState { .field("node_id", &self.node_id) .field("tag_store", &"") .field("save_limiter", &self.save_limiter) + .field("register_limiter", &self.register_limiter) .field("identity", &self.identity) .field("local_events", &"") .field("world", &self.world) @@ -474,6 +624,10 @@ impl AppState { node_id, tag_store, save_limiter: SaveRateLimiter::new(DEFAULT_SAVE_COOLDOWN), + register_limiter: RegisterRateLimiter::new( + DEFAULT_REGISTER_LIMIT, + DEFAULT_REGISTER_WINDOW, + ), upload_name_lock: Arc::new(Mutex::new(())), identity: IdentityStore::new_with_max_identities( secret_key, diff --git a/pkgs/id/crates/id-web/src/routes.rs b/pkgs/id/crates/id-web/src/routes.rs index 7fd64d32c3..a3e1d49451 100644 --- a/pkgs/id/crates/id-web/src/routes.rs +++ b/pkgs/id/crates/id-web/src/routes.rs @@ -2,12 +2,13 @@ //! //! Defines all the Axum routes and their handlers for serving the web UI. +use std::net::SocketAddr; use std::time::{SystemTime, UNIX_EPOCH}; use axum::{ Form, Json, Router, body::Body, - extract::{DefaultBodyLimit, Multipart, Path, Query, State}, + extract::{ConnectInfo, DefaultBodyLimit, Multipart, Path, Query, State}, http::{HeaderMap, StatusCode, header}, response::{Html, IntoResponse, Redirect, Response}, routing::{get, post}, @@ -2094,6 +2095,99 @@ struct DeleteResponse { /// The file remains in the store and can be restored by removing the "deleted" tag. /// Soft-deleted files are hidden from the file list. +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod identity_register_rate_limit_tests { + use std::{sync::Arc, time::Duration}; + + use axum::{body::to_bytes, extract::State}; + use iroh::endpoint::{Endpoint, RelayMode, presets}; + use iroh_blobs::{api::Store, store::mem::MemStore}; + use iroh_docs::protocol::Docs; + use iroh_gossip::net::Gossip; + + use super::*; + use id_store::tags::TagStore; + + use crate::{AppState, RegisterRateLimiter}; + + async fn state_with_limit(limit: usize) -> AppState { + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap(); + let store: Store = MemStore::new().into(); + let gossip = Gossip::builder().spawn(endpoint.clone()); + let docs = Docs::memory() + .spawn(endpoint.clone(), store.clone(), gossip) + .await + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let tags = Arc::new( + TagStore::init_in(&docs, "register-limit-test", dir.path().join("meta")) + .await + .unwrap(), + ); + let mut state = AppState::new( + store, + None, + "register-limit-test".to_owned(), + tags, + [7; 32], + dir.path().join(".identity.redb"), + ) + .await + .unwrap(); + state.register_limiter = RegisterRateLimiter::new(limit, Duration::from_secs(60)); + state + } + + async fn register(state: &AppState, name: &str) -> Response { + identity_register_handler( + State(state.clone()), + ConnectInfo("203.0.113.7:12345".parse().unwrap()), + Json(IdentityRegisterRequest { + name: Some(name.to_owned()), + }), + ) + .await + .into_response() + } + + async fn response_json(response: Response) -> serde_json::Value { + serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap() + } + + #[tokio::test] + async fn register_is_rate_limited_per_source_with_an_observable_429() { + let state = state_with_limit(2).await; + + // Under the limit: registrations succeed. + let first = register(&state, "one").await; + assert_eq!(first.status(), StatusCode::OK); + let first_body = response_json(first).await; + let token = first_body["token"].as_str().unwrap().to_owned(); + let second = register(&state, "two").await; + assert_eq!(second.status(), StatusCode::OK); + + // Over the limit: a structured 429 with a Retry-After header. + let third = register(&state, "three").await; + assert_eq!(third.status(), StatusCode::TOO_MANY_REQUESTS); + assert!(third.headers().contains_key(header::RETRY_AFTER)); + let third_body = response_json(third).await; + assert_eq!(third_body["error"], "registration_rate_limited"); + assert_eq!(third_body["reason"], "rate_limited"); + + // The limit is on registration only: /api/identity/me for an + // already-registered identity is unaffected. + let me = identity_me_handler(State(state.clone()), Query(IdentityMeQuery { token })) + .await + .into_response(); + assert_eq!(me.status(), StatusCode::OK); + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod save_publication_tests { @@ -4230,10 +4324,44 @@ struct IdentityUpdateNameRequest { /// for future reconnection. async fn identity_register_handler( State(state): State, + connect_info: ConnectInfo, Json(req): Json, ) -> impl IntoResponse { + // #1766 (remainder): throttle registrations per source. The key is + // the peer IP from the listener's connect-info — forwarded headers + // are client-spoofable on the direct listener and are never + // consulted (security.rs doctrine). The `id serve` listener wiring + // supplies connect-info (id-cli serve.rs); a surface that served + // this router without it would reject the request, and no such + // production surface exists (the program router served by + // publication listeners carries no identity routes). Only + // successful registrations are recorded, so a refusal at the + // admission cap below does not consume a source's budget. + let source = connect_info.0.ip().to_string(); + if let Err(remaining) = state.register_limiter.check(&source).await { + #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] + let secs = remaining.as_secs_f64().ceil() as u64; + tracing::info!( + "[identity] Registration rate limited for source {source}: {secs}s remaining" + ); + // Structured refusal, same shape as the save limiter's + // (#2244): machine-readable reason + retry value in the body, + // `Retry-After` header alongside. + return ( + StatusCode::TOO_MANY_REQUESTS, + [(header::RETRY_AFTER, secs.to_string())], + Json(serde_json::json!({ + "error": "registration_rate_limited", + "detail": format!("Too many registrations from this source. Try again in {secs}s."), + "reason": "rate_limited", + "retry_after_ms": secs.saturating_mul(1_000), + })), + ) + .into_response(); + } match state.identity.register(req.name).await { Ok((token, identity)) => { + state.register_limiter.record(&source).await; tracing::info!("[identity] Registered new client: {}", identity.client_id); ( StatusCode::OK,