Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(image_proxy_service): potential ssrf attack vector (#3959)
Will Hutchinsonccb7365db730
diff --git a/rust/cloud-storage/image_proxy_service/src/api/mod.rs b/rust/cloud-storage/image_proxy_service/src/api/mod.rsindex 823cd1de9f..18784ae2ee 100644--- a/rust/cloud-storage/image_proxy_service/src/api/mod.rs+++ b/rust/cloud-storage/image_proxy_service/src/api/mod.rs@@ -8,7 +8,7 @@ use utoipa_swagger_ui::SwaggerUi;pub mod context;mod health;-mod proxy;+pub(crate) mod proxy;pub(crate) mod swagger;pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<()> {diff --git a/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs b/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rsindex c8e7230473..312608ed0b 100644--- a/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs+++ b/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs@@ -1,3 +1,5 @@+mod resolver;+use axum::Router;use axum::body::Body;use axum::extract::{Query, State};@@ -10,12 +12,51 @@ use serde::Deserialize;use std::error::Error;use std::fmt;use std::net::IpAddr;+use std::sync::Arc;use url::Url;use utoipa::ToSchema;+use resolver::PrivateIpFilteringResolver;+/// 10 MB max image sizeconst MAX_IMAGE_SIZE: u64 = 10 * 1024 * 1024;+/// Maximum number of redirects to follow per proxied fetch. Matches the+/// previous reqwest-managed `Policy::limited(5)` behaviour.+const MAX_REDIRECTS: u8 = 5;++/// Default request timeout for a proxied fetch.+const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);++/// Default connect timeout for a proxied fetch.+const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);++/// Build the HTTP client used to fetch upstream images.+///+/// SSRF mitigations baked into the client:+///+/// 1. **Redirects disabled** at the reqwest level so the manual loop in+/// [`proxy_request_handler`] can run [`assert_not_internal`] on every hop+/// and follows up to [`MAX_REDIRECTS`] redirects itself.+/// 2. **Private-IP-filtering DNS resolver** ([`PrivateIpFilteringResolver`])+/// enforces the same private-IP check at the moment reqwest actually+/// connects, closing the DNS-rebinding TOCTOU window where the preflight+/// and the connect attempt could see different answers from the+/// authoritative DNS server.+///+/// Owning the client construction here keeps the mitigation inseparable from+/// the handler that relies on it — callers can't accidentally hand in a+/// redirect-following or unfiltered client.+pub(crate) fn build_http_client() -> anyhow::Result<reqwest::Client> {+ let client = reqwest::Client::builder()+ .timeout(REQUEST_TIMEOUT)+ .connect_timeout(CONNECT_TIMEOUT)+ .redirect(reqwest::redirect::Policy::none())+ .dns_resolver(Arc::new(PrivateIpFilteringResolver))+ .build()?;+ Ok(client)+}+#[derive(Debug)]pub enum ProxyError {InvalidUrl(String),@@ -101,10 +142,33 @@ pub async fn proxy_request_handler(State(http_client): State<reqwest::Client>,_ip: ClientIp,) -> Result<Response, ProxyError> {- let validated_url = validate_url(¶ms.url)?;- assert_not_internal(&validated_url).await?;+ let mut url = validate_url(¶ms.url)?;+ let mut redirects_remaining = MAX_REDIRECTS;++ let response = loop {+ assert_not_internal(&url).await?;+ let response = send_request(&http_client, &url).await?;+ let status = response.status();++ if status.is_redirection() {+ if redirects_remaining == 0 {+ return Err(ProxyError::UpstreamRedirect(format!(+ "exceeded maximum of {MAX_REDIRECTS} redirects"+ )));+ }+ let next = redirect_target(&url, &response)?;+ tracing::debug!(from = %url, to = %next, "following redirect");+ redirects_remaining -= 1;+ url = next;+ continue;+ }- let response = send_request(&http_client, &validated_url).await?;+ if !status.is_success() {+ return Err(ProxyError::UpstreamStatus(status));+ }++ break response;+ };let content_type = extract_content_type(&response)?;@@ -165,17 +229,28 @@ fn is_private_ip(ip: &IpAddr) -> bool {if let Some(mapped_v4) = v6.to_ipv4_mapped() {return is_private_ip(&IpAddr::V4(mapped_v4));}- v6.is_loopback() || v6.is_unspecified()+ v6.is_loopback()+ || v6.is_unspecified()+ // fc00::/7 — Unique Local Addresses (IPv6 equivalent of RFC1918).+ || v6.is_unique_local()+ // fe80::/10 — Link-local; reachable on the local segment only.+ || v6.is_unicast_link_local()}}}+/// Issue a GET against `url`. The response is returned without inspecting its+/// status — the caller decides how to handle 3xx (redirect-follow) vs 4xx /+/// 5xx (error). This is intentional: the redirect loop in+/// [`proxy_request_handler`] needs to see 3xx responses so it can run+/// [`assert_not_internal`] against each hop before following.async fn send_request(http_client: &reqwest::Client,url: &Url,) -> Result<reqwest::Response, ProxyError> {- let response = http_client.get(url.as_str()).send().await.map_err(|e| {+ http_client.get(url.as_str()).send().await.map_err(|e| {let error_chain = build_error_chain(&e);+ tracing::warn!(url = %url, error = %error_chain, "upstream request failed");if e.is_timeout() {ProxyError::UpstreamTimeout(error_chain)} else if e.is_connect() {@@ -185,13 +260,35 @@ async fn send_request(} else {ProxyError::UpstreamNetwork(error_chain)}+ })+}++/// Resolve the `Location` header of a 3xx response into the next URL to+/// fetch, applying the same scheme / fragment hygiene as [`validate_url`].+///+/// Does **not** check the target's IPs — the caller must run+/// [`assert_not_internal`] on the returned URL before issuing the next+/// request, so a 302 → internal-IP cannot bypass the preflight.+fn redirect_target(current: &Url, response: &reqwest::Response) -> Result<Url, ProxyError> {+ let location = response+ .headers()+ .get(reqwest::header::LOCATION)+ .ok_or_else(|| {+ ProxyError::UpstreamRedirect("redirect response missing Location header".into())+ })?+ .to_str()+ .map_err(|e| ProxyError::UpstreamRedirect(format!("invalid Location header: {e}")))?;++ let mut next = current.join(location).map_err(|e| {+ ProxyError::UpstreamRedirect(format!("could not parse redirect target {location}: {e}"))})?;- if !response.status().is_success() {- return Err(ProxyError::UpstreamStatus(response.status()));+ if next.scheme() != "http" && next.scheme() != "https" {+ return Err(ProxyError::InvalidScheme);}+ next.set_fragment(None);- Ok(response)+ Ok(next)}fn extract_content_type(response: &reqwest::Response) -> Result<String, ProxyError> {diff --git a/rust/cloud-storage/image_proxy_service/src/api/proxy/resolver.rs b/rust/cloud-storage/image_proxy_service/src/api/proxy/resolver.rsnew file mode 100644index 0000000000..2aab7fdf1b--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/api/proxy/resolver.rs@@ -0,0 +1,66 @@+//! Custom reqwest DNS resolver that filters private / internal IP addresses+//! at connect time.+//!+//! This closes a DNS-rebinding TOCTOU window: [`assert_not_internal`] runs+//! once at preflight, but reqwest performs its own DNS lookup when it+//! actually opens the connection. An attacker controlling the authoritative+//! DNS server could return a public IP at preflight and an internal IP at+//! connect time. By plugging this resolver into [`reqwest::Client`] via+//! [`reqwest::ClientBuilder::dns_resolver`], the same private-IP filter is+//! enforced at the exact moment reqwest is about to connect — no window for+//! the answer to change between check and use.+//!+//! [`assert_not_internal`]: super::assert_not_internal++use std::net::SocketAddr;++use reqwest::dns::{Addrs, Name, Resolve, Resolving};++use super::is_private_ip;++/// reqwest DNS resolver that drops private / internal IPs from the answer+/// set and errors out if nothing public remains.+pub(super) struct PrivateIpFilteringResolver;++impl Resolve for PrivateIpFilteringResolver {+ fn resolve(&self, name: Name) -> Resolving {+ Box::pin(async move {+ let hostname = name.as_str().to_owned();+ // Port is irrelevant for resolution; reqwest overrides it with+ // the URL's port before connecting. Use 0 as a placeholder.+ let lookup = match tokio::net::lookup_host(format!("{hostname}:0")).await {+ Ok(iter) => iter,+ Err(e) => {+ return Err(Box::new(e) as Box<dyn std::error::Error + Send + Sync>);+ }+ };++ let filtered: Vec<SocketAddr> = lookup+ .filter(|sa| {+ let allowed = !is_private_ip(&sa.ip());+ if !allowed {+ tracing::warn!(+ host = %hostname,+ ip = %sa.ip(),+ "dropped resolved private/internal IP from connection candidates"+ );+ }+ allowed+ })+ .collect();++ if filtered.is_empty() {+ return Err(Box::new(std::io::Error::new(+ std::io::ErrorKind::PermissionDenied,+ format!(+ "all resolved IPs for {hostname} are private/internal; refusing to connect"+ ),+ ))+ as Box<dyn std::error::Error + Send + Sync>);+ }++ let iter: Addrs = Box::new(filtered.into_iter());+ Ok(iter)+ })+ }+}diff --git a/rust/cloud-storage/image_proxy_service/src/api/proxy/test.rs b/rust/cloud-storage/image_proxy_service/src/api/proxy/test.rsindex 5f2737ff1a..d8aa68ecbc 100644--- a/rust/cloud-storage/image_proxy_service/src/api/proxy/test.rs+++ b/rust/cloud-storage/image_proxy_service/src/api/proxy/test.rs@@ -90,6 +90,22 @@ fn test_is_private_ip_unspecified() {assert!(is_private_ip(&"::".parse().unwrap()));}+#[test]+fn test_is_private_ip_v6_unique_local() {+ // fc00::/7 — IPv6 equivalent of RFC1918.+ assert!(is_private_ip(&"fc00::1".parse().unwrap()));+ assert!(is_private_ip(&"fd12:3456:789a::1".parse().unwrap()));+}++#[test]+fn test_is_private_ip_v6_link_local() {+ // fe80::/10 — only reachable on the local link.+ assert!(is_private_ip(&"fe80::1".parse().unwrap()));+ assert!(is_private_ip(+ &"febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff".parse().unwrap()+ ));+}+#[test]fn test_is_private_ip_mapped_v4() {// ::ffff:127.0.0.1 — IPv4-mapped loopback@@ -111,6 +127,54 @@ fn test_is_private_ip_public() {assert!(!is_private_ip(&"2607:f8b0:4004:800::200e".parse().unwrap()));}+fn response_with_status_and_location(status: u16, location: Option<&str>) -> reqwest::Response {+ let mut builder = axum::http::Response::builder().status(status);+ if let Some(location) = location {+ builder = builder.header("Location", location);+ }+ builder.body("").unwrap().into()+}++#[test]+fn test_redirect_target_absolute_location() {+ let current = Url::parse("https://example.com/image.png").unwrap();+ let response = response_with_status_and_location(302, Some("https://cdn.example.com/img.png"));+ let next = redirect_target(¤t, &response).unwrap();+ assert_eq!(next.as_str(), "https://cdn.example.com/img.png");+}++#[test]+fn test_redirect_target_relative_location() {+ let current = Url::parse("https://example.com/a/image.png").unwrap();+ let response = response_with_status_and_location(302, Some("/b/image.png"));+ let next = redirect_target(¤t, &response).unwrap();+ assert_eq!(next.as_str(), "https://example.com/b/image.png");+}++#[test]+fn test_redirect_target_strips_fragment() {+ let current = Url::parse("https://example.com/image.png").unwrap();+ let response = response_with_status_and_location(302, Some("https://example.com/img.png#frag"));+ let next = redirect_target(¤t, &response).unwrap();+ assert_eq!(next.as_str(), "https://example.com/img.png");+}++#[test]+fn test_redirect_target_rejects_non_http_scheme() {+ let current = Url::parse("https://example.com/image.png").unwrap();+ let response = response_with_status_and_location(302, Some("ftp://example.com/img.png"));+ let result = redirect_target(¤t, &response);+ assert!(matches!(result, Err(ProxyError::InvalidScheme)));+}++#[test]+fn test_redirect_target_missing_location() {+ let current = Url::parse("https://example.com/image.png").unwrap();+ let response = response_with_status_and_location(302, None);+ let result = redirect_target(¤t, &response);+ assert!(matches!(result, Err(ProxyError::UpstreamRedirect(_))));+}+#[tokio::test]async fn test_assert_not_internal_blocks_loopback() {let url = Url::parse("http://127.0.0.1/secret").unwrap();diff --git a/rust/cloud-storage/image_proxy_service/src/main.rs b/rust/cloud-storage/image_proxy_service/src/main.rsindex 446b5a878a..cec6c98a36 100644--- a/rust/cloud-storage/image_proxy_service/src/main.rs+++ b/rust/cloud-storage/image_proxy_service/src/main.rs@@ -23,12 +23,7 @@ async fn main() -> anyhow::Result<()> {JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;- let http_client = reqwest::Client::builder()- .timeout(std::time::Duration::from_secs(15))- .connect_timeout(std::time::Duration::from_secs(5))- .redirect(reqwest::redirect::Policy::limited(5))- .build()- .context("failed to build http client")?;+ let http_client = api::proxy::build_http_client().context("failed to build http client")?;let state = api::context::ApiContext {jwt_args,