From 85cc567f16786c81669bcff4a3fe0cb76298fade Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 12:30:58 +1300 Subject: [PATCH 1/2] app/: the gallery's rate limit keys on the request's address through the trusted proxies (behind Cloudflare's tunnel no hop comes from Cloudflare's ranges, so the cf-connecting-ip range check never applied); each process names its database connections from DB_APPLICATION_NAME (SET application_name), for Postgres's per-process metrics --- app/Cargo.lock | 1 - app/Cargo.toml | 1 - app/src/config.rs | 49 +++++++++++++++++++++++------------------ app/src/http/gallery.rs | 46 ++++---------------------------------- 4 files changed, 32 insertions(+), 65 deletions(-) diff --git a/app/Cargo.lock b/app/Cargo.lock index af0bece3..352842da 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -4735,7 +4735,6 @@ dependencies = [ "hmac 0.12.1", "image", "include_dir", - "ipnet", "laravel-rust", "oauth-provider", "oauth-provider-laravel", diff --git a/app/Cargo.toml b/app/Cargo.toml index 107a1131..dcabfa90 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -38,7 +38,6 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12" globset = "0.4" -ipnet = "2" schemars = "1" tracing = "0.1" include_dir = "0.7" diff --git a/app/src/config.rs b/app/src/config.rs index 16ee0e7c..619378c2 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -48,34 +48,14 @@ pub struct Cloudflare { pub purge_token: String, } -/// Cloudflare's published edge ranges (https://www.cloudflare.com/ips/), for [`Gallery::cloudflare_ip_ranges`]. -pub const CLOUDFLARE_IP_RANGES: &str = "173.245.48.0/20,103.21.244.0/22,103.22.200.0/22,103.31.4.0/22,141.101.64.0/18,\ -108.162.192.0/18,190.93.240.0/20,188.114.96.0/20,197.234.240.0/22,198.41.128.0/17,162.158.0.0/15,104.16.0.0/13,\ -104.24.0.0/14,172.64.0.0/13,131.0.72.0/22,2400:cb00::/32,2606:4700::/32,2803:f800::/32,2405:b500::/32,2405:8100::/32,\ -2a06:98c0::/29,2c0f:f248::/32"; - /// The public gallery (`http::gallery`). #[derive(Clone, Debug, Section)] pub struct Gallery { - /// The networks whose `cf-connecting-ip` header is believed: Cloudflare's edge, comma-separated. A request from - /// anywhere else is limited by its own address, so a client can't rotate the header to dodge the rate limit. - #[env("VISUALCI_CLOUDFLARE_IP_RANGES", default = "")] - pub cloudflare_ip_ranges: String, /// The most gallery credits one project is charged in a day: images past it are served free. #[env("VISUALCI_GALLERY_DAILY_CREDITS", default = 50_000)] pub daily_credits: i64, } -impl Gallery { - /// The Cloudflare networks: the configured ones, else the published list. - #[must_use] - pub fn cloudflare_networks(&self) -> Vec { - let list = - if self.cloudflare_ip_ranges.trim().is_empty() { CLOUDFLARE_IP_RANGES } else { &self.cloudflare_ip_ranges }; - list.split(',').filter_map(|n| n.trim().parse().ok()).collect() - } -} - /// The proxies in front of the app whose `X-Forwarded-For` is believed (`TRUSTED_PROXIES`, comma-separated; the /// cluster's network by default). Behind them, a request's address is the nearest one that isn't a trusted proxy: /// Cloudflare's edge, or a client that reached the ingress directly. @@ -89,6 +69,13 @@ pub fn trusted_proxies() -> Vec { .collect() } +/// A safe `application_name`: letters, digits, dashes and underscores, at most 63 characters; anything else is ignored. +fn application_name(name: &str) -> Option { + let name = name.trim(); + (!name.is_empty() && name.len() <= 63 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')) + .then(|| name.to_string()) +} + /// The database: `Database::from_env` (`DATABASE_URL`, `DB_MAX_CONNECTIONS`, default 10 per process), with a short wait /// for a pooled connection (`DB_ACQUIRE_TIMEOUT`, seconds, default 5). A burst of CI builds that takes every /// connection then answers 503 with Retry-After at once (`http::busy`), rather than holding each request for the @@ -100,8 +87,28 @@ fn database(env: &laravel::config::Env) -> laravel::config::database::Database { let default = database.default.clone(); if let Some(connection) = database.connections.remove(&default) { let seconds = i64::try_from(seconds).unwrap_or(5); - let connection = connection.acquire_timeout(laravel::time::SignedDuration::from_secs(seconds)); + let mut connection = connection.acquire_timeout(laravel::time::SignedDuration::from_secs(seconds)); + // Which process a connection belongs to, in Postgres's metrics and pg_stat_activity (`visualci-web`, + // `visualci-worker`, `visualci-scheduler`). The deploy sets it beside the URL from the database's Secret. + if let Some(name) = env.get::("DB_APPLICATION_NAME").and_then(|n| application_name(&n)) { + connection = + connection.initialize(laravel::db::sqlx::AssertSqlSafe(format!("SET application_name = '{name}'"))); + } database.connections.insert(default, connection); } database } + +#[cfg(test)] +mod tests { + use super::application_name; + + #[test] + fn an_application_name_is_used_only_when_it_is_safe() { + assert_eq!(application_name(" visualci-web ").as_deref(), Some("visualci-web")); + assert_eq!(application_name("visualci_worker").as_deref(), Some("visualci_worker")); + assert_eq!(application_name(""), None); + assert_eq!(application_name("web'; DROP TABLE x; --"), None); + assert_eq!(application_name(&"a".repeat(64)), None); + } +} diff --git a/app/src/http/gallery.rs b/app/src/http/gallery.rs index 4d9c2e2c..73dc950c 100644 --- a/app/src/http/gallery.rs +++ b/app/src/http/gallery.rs @@ -11,8 +11,6 @@ use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; -use std::net::IpAddr; - use axum::http::{HeaderValue, StatusCode, header}; use axum::response::{IntoResponse, Response}; use laravel::http::Request; @@ -31,18 +29,6 @@ pub fn routes(route: &mut Router) { route.get("/g/{org}/{project}/{*path}", image); } -/// The caller's address, for the rate limit. `hop` is the address that reached our ingress (the kernel reads it from -/// the trusted proxies' `X-Forwarded-For`): when it's Cloudflare's edge, the client is the one Cloudflare names in -/// `cf-connecting-ip`; from anywhere else that header is the client's own claim, so the hop itself is the caller. -#[must_use] -pub fn caller(hop: IpAddr, cf_connecting_ip: Option<&str>, cloudflare: &[ipnet::IpNet]) -> String { - let from_cloudflare = cloudflare.iter().any(|n| n.contains(&hop)); - match cf_connecting_ip.map(str::trim).and_then(|v| v.parse::().ok()) { - Some(client) if from_cloudflare => client.to_string(), - _ => hop.to_string(), - } -} - /// Whether this address may make another request now. fn allowed(address: &str) -> bool { static WINDOWS: OnceLock>> = OnceLock::new(); @@ -84,9 +70,10 @@ fn guard(request: &Request) -> Option { if request.uri().query().is_some() { return Some(status(StatusCode::NOT_FOUND, "not found")); } - let settings = laravel::config(); - let networks = settings.section::().cloudflare_networks(); - if !allowed(&caller(request.ip(), request.header("cf-connecting-ip"), &networks)) { + // The caller: the request's address resolved through the trusted proxies (`TRUSTED_PROXIES`). Behind Cloudflare's + // tunnel and Envoy, that's the client Cloudflare names (no hop comes from Cloudflare's own ranges), and a client + // can't choose it by sending headers of its own. + if !allowed(&request.ip().to_string()) { let mut r = status(StatusCode::TOO_MANY_REQUESTS, "slow down"); r.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from_static("60")); return Some(r); @@ -163,28 +150,3 @@ async fn serve(org: &str, slug: &str, path: &str, if_none_match: Option<&str>) - } Ok(public(r)) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cloudflare_names_the_client_only_when_the_request_came_from_cloudflare() { - let cloudflare: Vec = vec!["173.245.48.0/20".parse().unwrap(), "2606:4700::/32".parse().unwrap()]; - let edge: IpAddr = "173.245.48.7".parse().unwrap(); - let elsewhere: IpAddr = "203.0.113.9".parse().unwrap(); - assert_eq!(caller(edge, Some("198.51.100.4"), &cloudflare), "198.51.100.4"); - assert_eq!(caller("2606:4700::1".parse().unwrap(), Some("2001:db8::5"), &cloudflare), "2001:db8::5"); - // A client that reaches the origin directly can't pick its own address, however it rotates the header. - assert_eq!(caller(elsewhere, Some("198.51.100.4"), &cloudflare), "203.0.113.9"); - assert_eq!(caller(elsewhere, Some("198.51.100.5"), &cloudflare), "203.0.113.9"); - assert_eq!(caller(edge, Some("not an address"), &cloudflare), "173.245.48.7"); - assert_eq!(caller(edge, None, &cloudflare), "173.245.48.7"); - } - - #[test] - fn the_published_cloudflare_ranges_parse() { - let gallery = crate::config::Gallery { cloudflare_ip_ranges: String::new(), daily_credits: 1 }; - assert_eq!(gallery.cloudflare_networks().len(), crate::config::CLOUDFLARE_IP_RANGES.split(',').count()); - } -} From 343d0f2f751231e0f8b75fee1f126f8282825e61 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 12:38:27 +1300 Subject: [PATCH 2/2] app/: a test that a client can't choose its rate-limit key: behind a trusted proxy, request.ip() is the right-most X-Forwarded-For entry that isn't one, so a forged first entry changes nothing --- app/tests/proxies.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 app/tests/proxies.rs diff --git a/app/tests/proxies.rs b/app/tests/proxies.rs new file mode 100644 index 00000000..c124f2e1 --- /dev/null +++ b/app/tests/proxies.rs @@ -0,0 +1,31 @@ +//! Behind the trusted proxies (`TRUSTED_PROXIES`, Envoy's nodes in production), a request's address is the right-most +//! `X-Forwarded-For` entry that isn't a trusted proxy: the client Cloudflare appended, never an address the client +//! sent itself. The public gallery's rate limit keys on it, so rotating a forged first entry doesn't dodge the limit. +//! Its own test binary: the gallery's rate-limit counter is per process. + +use laravel::testing::prelude::*; + +#[laravel::test] +async fn a_client_cant_choose_its_rate_limit_key_with_its_own_x_forwarded_for(app: Application) -> laravel::Result<()> { + let client = "198.51.100.77"; + for n in 0..120 { + // A forged first entry, different every time; the proxy appended the real client after it. + let forwarded = format!("1.2.3.{n}, {client}"); + let response = + app.get("/g/no-such-org/project.json").with_ip([10, 42, 0, 5]).header("x-forwarded-for", &forwarded).await; + assert_ne!(response.status(), 429, "request {n} was limited early"); + } + let limited = app + .get("/g/no-such-org/project.json") + .with_ip([10, 42, 0, 5]) + .header("x-forwarded-for", format!("9.9.9.9, {client}")) + .await; + limited.assert_status(429); + // Another client behind the same proxy has its own limit. + app.get("/g/no-such-org/project.json") + .with_ip([10, 42, 0, 5]) + .header("x-forwarded-for", "1.2.3.4, 198.51.100.78") + .await + .assert_status(404); + Ok(()) +}