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
1 change: 0 additions & 1 deletion app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
49 changes: 28 additions & 21 deletions app/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ipnet::IpNet> {
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.
Expand All @@ -89,6 +69,13 @@ pub fn trusted_proxies() -> Vec<String> {
.collect()
}

/// A safe `application_name`: letters, digits, dashes and underscores, at most 63 characters; anything else is ignored.
fn application_name(name: &str) -> Option<String> {
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
Expand All @@ -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::<String>("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);
}
}
46 changes: 4 additions & 42 deletions app/src/http/gallery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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::<IpAddr>().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<Mutex<HashMap<String, (Instant, u32)>>> = OnceLock::new();
Expand Down Expand Up @@ -84,9 +70,10 @@ fn guard(request: &Request) -> Option<Response> {
if request.uri().query().is_some() {
return Some(status(StatusCode::NOT_FOUND, "not found"));
}
let settings = laravel::config();
let networks = settings.section::<crate::config::Gallery>().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);
Expand Down Expand Up @@ -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<ipnet::IpNet> = 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());
}
}
31 changes: 31 additions & 0 deletions app/tests/proxies.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
Loading