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): Hardening image fetch logic (#1858)
Evan Hutnik8b1ea0ed7c4e
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex f88900a1d5..430268a810 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5005,6 +5005,8 @@ dependencies = ["anyhow","aws-sdk-secretsmanager","axum",+ "bytes",+ "futures","http-body-util","macro_auth","macro_aws_config",@@ -5021,6 +5023,7 @@ dependencies = ["tower 0.5.2","tower-http","tracing",+ "url","utoipa","utoipa-swagger-ui",]diff --git a/rust/cloud-storage/image_proxy_service/Cargo.toml b/rust/cloud-storage/image_proxy_service/Cargo.tomlindex 5dd74e5af1..601cad5e43 100644--- a/rust/cloud-storage/image_proxy_service/Cargo.toml+++ b/rust/cloud-storage/image_proxy_service/Cargo.toml@@ -27,7 +27,10 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"tracking",] }model = { path = "../model" }+bytes = { workspace = true }+futures = { workspace = true }reqwest = { workspace = true, features = ["stream"] }+url = { workspace = true }secretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }serde_json = { workspace = true }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 2126316dc6..ac4a669fdc 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@@ -3,12 +3,86 @@ use axum::body::Body;use axum::extract::{Query, State};use axum::response::{IntoResponse, Response};use axum::routing::get;+use futures::StreamExt;use reqwest::StatusCode;use serde::Deserialize;+use std::error::Error;+use std::fmt;+use std::net::IpAddr;+use url::Url;use utoipa::ToSchema;-/// 5 MB max image size-const MAX_IMAGE_SIZE: u64 = 5 * 1024 * 1024;+/// 10 MB max image size+const MAX_IMAGE_SIZE: u64 = 10 * 1024 * 1024;++#[derive(Debug)]+pub enum ProxyError {+ InvalidUrl(String),+ InvalidScheme,+ MissingHost,+ DnsLookupFailed(std::io::Error),+ PrivateIp,+ UpstreamTimeout(String),+ UpstreamConnect(String),+ UpstreamRedirect(String),+ UpstreamNetwork(String),+ UpstreamStatus(reqwest::StatusCode),+ NotAnImage(String),+ ImageTooLarge { content_length: u64 },+ ResponseBuild(axum::http::Error),+}++impl fmt::Display for ProxyError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::InvalidUrl(e) => write!(f, "invalid URL: {e}"),+ Self::InvalidScheme => write!(f, "only http/https URLs are allowed"),+ Self::MissingHost => write!(f, "missing host"),+ Self::DnsLookupFailed(e) => write!(f, "DNS lookup failed: {e}"),+ Self::PrivateIp => write!(f, "requests to private/internal IPs are not allowed"),+ Self::UpstreamTimeout(chain) => {+ write!(f, "timeout fetching upstream image: {chain}")+ }+ Self::UpstreamConnect(chain) => {+ write!(f, "connection error fetching upstream image: {chain}")+ }+ Self::UpstreamRedirect(chain) => {+ write!(f, "too many redirects fetching upstream image: {chain}")+ }+ Self::UpstreamNetwork(chain) => {+ write!(f, "network error fetching upstream image: {chain}")+ }+ Self::UpstreamStatus(status) => write!(f, "upstream returned status {status}"),+ Self::NotAnImage(ct) => write!(f, "upstream content-type is not an image: {ct}"),+ Self::ImageTooLarge { content_length } => write!(+ f,+ "image exceeds max size of {MAX_IMAGE_SIZE} bytes (Content-Length: {content_length})"+ ),+ Self::ResponseBuild(e) => write!(f, "could not build response: {e}"),+ }+ }+}++impl IntoResponse for ProxyError {+ fn into_response(self) -> Response {+ let status = match &self {+ Self::InvalidUrl(_)+ | Self::InvalidScheme+ | Self::MissingHost+ | Self::DnsLookupFailed(_) => StatusCode::BAD_REQUEST,+ Self::PrivateIp => StatusCode::FORBIDDEN,+ Self::UpstreamTimeout(_) => StatusCode::GATEWAY_TIMEOUT,+ Self::UpstreamConnect(_)+ | Self::UpstreamRedirect(_)+ | Self::UpstreamNetwork(_)+ | Self::UpstreamStatus(_) => StatusCode::BAD_GATEWAY,+ Self::NotAnImage(_) => StatusCode::UNSUPPORTED_MEDIA_TYPE,+ Self::ImageTooLarge { .. } => StatusCode::UNPROCESSABLE_ENTITY,+ Self::ResponseBuild(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };+ (status, self.to_string()).into_response()+ }+}#[derive(Debug, ToSchema, Deserialize)]pub struct ProxyParams {@@ -24,27 +98,101 @@ pub struct ProxyParams {pub async fn proxy_request_handler(Query(params): Query<ProxyParams>,State(http_client): State<reqwest::Client>,-) -> Result<impl IntoResponse, impl IntoResponse> {- if !params.url.starts_with("http://") && !params.url.starts_with("https://") {- return Err((- StatusCode::BAD_REQUEST,- "only http/https URLs are allowed".to_string(),- ));+) -> Result<Response, ProxyError> {+ let validated_url = validate_url(¶ms.url)?;+ assert_not_internal(&validated_url).await?;++ let response = send_request(&http_client, &validated_url).await?;++ let content_type = extract_content_type(&response)?;++ check_content_length(&response, ¶ms.url)?;++ let size_limited_stream = apply_size_limit(response.bytes_stream(), params.url.clone());++ Response::builder()+ .header("Content-Type", &content_type)+ .header("Cache-Control", "public, max-age=31536000, immutable")+ .header("Cross-Origin-Resource-Policy", "cross-origin")+ .body(Body::from_stream(size_limited_stream))+ .map_err(|e| {+ tracing::error!(error=?e, "could not stream chunks");+ ProxyError::ResponseBuild(e)+ })+}++fn validate_url(raw_url: &str) -> Result<Url, ProxyError> {+ let mut url = Url::parse(raw_url).map_err(|e| ProxyError::InvalidUrl(e.to_string()))?;++ if url.scheme() != "http" && url.scheme() != "https" {+ return Err(ProxyError::InvalidScheme);}- let response = http_client- .get(¶ms.url)- .send()+ url.set_fragment(None);+ Ok(url)+}++async fn assert_not_internal(url: &Url) -> Result<(), ProxyError> {+ let host = url.host_str().ok_or(ProxyError::MissingHost)?;++ let port = url.port_or_known_default().unwrap_or(80);+ let addrs = tokio::net::lookup_host(format!("{host}:{port}")).await- .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?;+ .map_err(ProxyError::DnsLookupFailed)?;++ for addr in addrs {+ if is_private_ip(&addr.ip()) {+ tracing::warn!(host, ip = %addr.ip(), "blocked request to private/internal IP");+ return Err(ProxyError::PrivateIp);+ }+ }++ Ok(())+}++fn is_private_ip(ip: &IpAddr) -> bool {+ match ip {+ IpAddr::V4(v4) => {+ v4.is_loopback()+ || v4.is_private()+ || v4.is_link_local()+ || v4.is_unspecified()+ || v4.is_broadcast()+ }+ IpAddr::V6(v6) => {+ if let Some(mapped_v4) = v6.to_ipv4_mapped() {+ return is_private_ip(&IpAddr::V4(mapped_v4));+ }+ v6.is_loopback() || v6.is_unspecified()+ }+ }+}++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| {+ let error_chain = build_error_chain(&e);+ if e.is_timeout() {+ ProxyError::UpstreamTimeout(error_chain)+ } else if e.is_connect() {+ ProxyError::UpstreamConnect(error_chain)+ } else if e.is_redirect() {+ ProxyError::UpstreamRedirect(error_chain)+ } else {+ ProxyError::UpstreamNetwork(error_chain)+ }+ })?;if !response.status().is_success() {- return Err((- StatusCode::BAD_GATEWAY,- format!("upstream returned status {}", response.status()),- ));+ return Err(ProxyError::UpstreamStatus(response.status()));}+ Ok(response)+}++fn extract_content_type(response: &reqwest::Response) -> Result<String, ProxyError> {let content_type = response.headers().get(reqwest::header::CONTENT_TYPE)@@ -52,37 +200,62 @@ pub async fn proxy_request_handler(.unwrap_or("application/octet-stream").to_string();- let content_length = response- .headers()- .get(reqwest::header::CONTENT_LENGTH)- .and_then(|v| v.to_str().ok())- .and_then(|v| v.parse::<u64>().ok());+ if !content_type.starts_with("image/") {+ return Err(ProxyError::NotAnImage(content_type));+ }- tracing::info!(content_length=?content_length.unwrap_or(0), content_type=%content_type, "image content length");+ Ok(content_type)+}- if content_length.is_some_and(|len| len > MAX_IMAGE_SIZE) {- return Err((- StatusCode::UNPROCESSABLE_ENTITY,- format!("image exceeds max size of {MAX_IMAGE_SIZE} bytes"),- ));+fn check_content_length(+ response: &reqwest::Response,+ original_url: &str,+) -> Result<(), ProxyError> {+ if let Some(content_length) = response.content_length() {+ tracing::info!(+ content_length,+ url = original_url,+ "upstream content length"+ );+ if content_length > MAX_IMAGE_SIZE {+ return Err(ProxyError::ImageTooLarge { content_length });+ }}+ Ok(())+}- if !content_type.starts_with("image/") {- return Err((- StatusCode::UNSUPPORTED_MEDIA_TYPE,- format!("upstream content-type is not an image: {content_type}"),- ));- }+fn apply_size_limit<S: futures::Stream<Item = Result<bytes::Bytes, reqwest::Error>> + Send>(+ stream: S,+ url: String,+) -> impl futures::Stream<Item = Result<bytes::Bytes, axum::Error>> + Send + use<S> {+ let mut bytes_received: u64 = 0;- Response::builder()- .header("Content-Type", &content_type)- .header("Cache-Control", "public, max-age=31536000, immutable")- .header("Cross-Origin-Resource-Policy", "cross-origin")- .body(Body::from_stream(response.bytes_stream()))- .map_err(|e| {- tracing::error!(error=?e, "could not stream chunks");- (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())- })+ stream.map(move |chunk_result: Result<bytes::Bytes, reqwest::Error>| {+ let chunk = chunk_result.map_err(axum::Error::new)?;+ bytes_received += chunk.len() as u64;+ if bytes_received > MAX_IMAGE_SIZE {+ tracing::warn!(+ bytes_received,+ max = MAX_IMAGE_SIZE,+ url = url,+ "image exceeded max size during streaming"+ );+ return Err(axum::Error::new(std::io::Error::other(format!(+ "image exceeded max size of {MAX_IMAGE_SIZE} bytes during streaming"+ ))));+ }+ Ok(chunk)+ })+}++fn build_error_chain(err: &reqwest::Error) -> String {+ let mut chain = format!("{err}");+ let mut source = err.source();+ while let Some(cause) = source {+ chain.push_str(&format!("\nCaused by: {cause}"));+ source = cause.source();+ }+ chain}pub fn router() -> Router<crate::api::context::ApiContext> {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 c1d80956b7..af45aa98b4 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@@ -6,3 +6,107 @@ fn test_proxy_params_deserialization() {serde_json::from_str(r#"{"url":"https://example.com/image.png"}"#).unwrap();assert_eq!(params.url, "https://example.com/image.png");}++#[test]+fn test_validate_url_accepts_https() {+ let result = validate_url("https://example.com/image.png");+ assert!(result.is_ok());+ assert_eq!(result.unwrap().as_str(), "https://example.com/image.png");+}++#[test]+fn test_validate_url_accepts_http() {+ let result = validate_url("http://example.com/image.png");+ assert!(result.is_ok());+}++#[test]+fn test_validate_url_rejects_ftp() {+ let result = validate_url("ftp://example.com/image.png");+ assert!(matches!(result, Err(ProxyError::InvalidScheme)));+}++#[test]+fn test_validate_url_rejects_data_uri() {+ let result = validate_url("data:image/png;base64,abc");+ assert!(result.is_err());+}++#[test]+fn test_validate_url_rejects_invalid() {+ let result = validate_url("not a url");+ assert!(matches!(result, Err(ProxyError::InvalidUrl(_))));+}++#[test]+fn test_validate_url_strips_fragment() {+ let result = validate_url("https://example.com/image.png#section");+ assert!(result.is_ok());+ assert_eq!(result.unwrap().as_str(), "https://example.com/image.png");+}++#[test]+fn test_is_private_ip_loopback() {+ assert!(is_private_ip(&"127.0.0.1".parse().unwrap()));+ assert!(is_private_ip(&"::1".parse().unwrap()));+}++#[test]+fn test_is_private_ip_private_ranges() {+ assert!(is_private_ip(&"10.0.0.1".parse().unwrap()));+ assert!(is_private_ip(&"172.16.0.1".parse().unwrap()));+ assert!(is_private_ip(&"192.168.1.1".parse().unwrap()));+}++#[test]+fn test_is_private_ip_link_local() {+ assert!(is_private_ip(&"169.254.169.254".parse().unwrap()));+}++#[test]+fn test_is_private_ip_unspecified() {+ assert!(is_private_ip(&"0.0.0.0".parse().unwrap()));+ assert!(is_private_ip(&"::".parse().unwrap()));+}++#[test]+fn test_is_private_ip_mapped_v4() {+ // ::ffff:127.0.0.1 — IPv4-mapped loopback+ assert!(is_private_ip(&"::ffff:127.0.0.1".parse().unwrap()));+ // ::ffff:169.254.169.254 — IPv4-mapped AWS metadata+ assert!(is_private_ip(&"::ffff:169.254.169.254".parse().unwrap()));+ // ::ffff:10.0.0.1 — IPv4-mapped private+ assert!(is_private_ip(&"::ffff:10.0.0.1".parse().unwrap()));+ // ::ffff:192.168.1.1 — IPv4-mapped private+ assert!(is_private_ip(&"::ffff:192.168.1.1".parse().unwrap()));+ // ::ffff:8.8.8.8 — IPv4-mapped public should be allowed+ assert!(!is_private_ip(&"::ffff:8.8.8.8".parse().unwrap()));+}++#[test]+fn test_is_private_ip_public() {+ assert!(!is_private_ip(&"8.8.8.8".parse().unwrap()));+ assert!(!is_private_ip(&"1.1.1.1".parse().unwrap()));+ assert!(!is_private_ip(&"2607:f8b0:4004:800::200e".parse().unwrap()));+}++#[tokio::test]+async fn test_assert_not_internal_blocks_loopback() {+ let url = Url::parse("http://127.0.0.1/secret").unwrap();+ let result = assert_not_internal(&url).await;+ assert!(matches!(result, Err(ProxyError::PrivateIp)));+}++#[tokio::test]+async fn test_assert_not_internal_blocks_metadata_endpoint() {+ let url = Url::parse("http://169.254.169.254/latest/meta-data/").unwrap();+ let result = assert_not_internal(&url).await;+ assert!(matches!(result, Err(ProxyError::PrivateIp)));+}++#[tokio::test]+async fn test_assert_not_internal_allows_public() {+ let url = Url::parse("https://example.com/image.png").unwrap();+ let result = assert_not_internal(&url).await;+ assert!(result.is_ok());+}diff --git a/rust/cloud-storage/image_proxy_service/src/main.rs b/rust/cloud-storage/image_proxy_service/src/main.rsindex 63bd3d2f27..446b5a878a 100644--- a/rust/cloud-storage/image_proxy_service/src/main.rs+++ b/rust/cloud-storage/image_proxy_service/src/main.rs@@ -23,7 +23,12 @@ async fn main() -> anyhow::Result<()> {JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;- let http_client = reqwest::Client::new();+ 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 state = api::context::ApiContext {jwt_args,