Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(unfurl): Improvements to unfurl service to have it match what we do for similar functionality in other services (#2679)

Will Hutchinson8a7a30f36e38
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 03fcee282e..046c89f76f 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -11429,6 +11429,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"axum",
+ "bytes",
"futures",
"http 1.3.1",
"http-body-util",
diff --git a/rust/cloud-storage/unfurl_service/Cargo.toml b/rust/cloud-storage/unfurl_service/Cargo.toml
index a4ff3fc95f..032aa35902 100644
--- a/rust/cloud-storage/unfurl_service/Cargo.toml
+++ b/rust/cloud-storage/unfurl_service/Cargo.toml
@@ -17,7 +17,8 @@ mock = []
[dependencies]
anyhow = { workspace = true }
-axum = { workspace = true }
+axum = { workspace = true, features = ["macros"] }
+bytes = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
http-body-util = { workspace = true }
diff --git a/rust/cloud-storage/unfurl_service/src/api/context.rs b/rust/cloud-storage/unfurl_service/src/api/context.rs
index 8b13789179..f05ccb2b60 100644
--- a/rust/cloud-storage/unfurl_service/src/api/context.rs
+++ b/rust/cloud-storage/unfurl_service/src/api/context.rs
@@ -1 +1,8 @@
+use axum::extract::FromRef;
+use macro_env::Environment;
+#[derive(Clone, FromRef)]
+pub struct ApiContext {
+ pub environment: Environment,
+ pub http_client: reqwest::Client,
+}
diff --git a/rust/cloud-storage/unfurl_service/src/api/mod.rs b/rust/cloud-storage/unfurl_service/src/api/mod.rs
index 3338674d84..b890cf748e 100644
--- a/rust/cloud-storage/unfurl_service/src/api/mod.rs
+++ b/rust/cloud-storage/unfurl_service/src/api/mod.rs
@@ -1,7 +1,6 @@
-use crate::config::Config;
+use crate::api::context::ApiContext;
use anyhow::Context;
use axum::Router;
-use tower::ServiceBuilder;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
@@ -11,22 +10,24 @@ mod proxy;
pub(crate) mod swagger;
mod unfurl;
-pub async fn setup_and_serve(config: &Config) -> anyhow::Result<()> {
+pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<()> {
let cors = macro_cors::cors_layer();
+ let env = state.environment;
let app = api_router()
- .layer(cors.clone())
- .merge(health::router().layer(cors))
+ .with_state(state)
+ .merge(health::router())
+ .layer(cors)
.merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()));
- let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", config.port))
+ let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))
.await
.unwrap();
tracing::info!(
"\n📜 unfurl_service 📜\nenvironment {:?}\nport: {}",
- &config.environment,
- &config.port
+ &env,
+ &port
);
axum::serve(listener, app.into_make_service())
@@ -34,10 +35,10 @@ pub async fn setup_and_serve(config: &Config) -> anyhow::Result<()> {
.context("error starting service")
}
-fn api_router() -> Router {
+fn api_router() -> Router<ApiContext> {
Router::new()
- .nest("/unfurl", unfurl::router().layer(ServiceBuilder::new()))
- .nest("/proxy", proxy::router().layer(ServiceBuilder::new()))
+ .nest("/unfurl", unfurl::router())
+ .nest("/proxy", proxy::router())
}
#[cfg(test)]
@@ -51,11 +52,19 @@ mod tests {
http::{Request, StatusCode},
};
use http_body_util::BodyExt; // for `collect`
+ use macro_env::Environment;
use tower::ServiceExt;
+ fn test_state() -> ApiContext {
+ ApiContext {
+ environment: Environment::Local,
+ http_client: reqwest::Client::new(),
+ }
+ }
+
#[tokio::test]
async fn test_not_found() {
- let api = api_router();
+ let api = api_router().with_state(test_state());
let response = api
.oneshot(
@@ -74,7 +83,7 @@ mod tests {
#[tokio::test]
async fn test_unfurl_url_nonexistent() {
- let api = api_router();
+ let api = api_router().with_state(test_state());
let response = api
.oneshot(
@@ -101,7 +110,7 @@ mod tests {
#[ignore]
#[tokio::test]
async fn test_unfurl_hello_url() {
- let api = api_router();
+ let api = api_router().with_state(test_state());
let response = api
.oneshot(
@@ -133,7 +142,7 @@ mod tests {
#[ignore]
#[tokio::test]
async fn test_bulk() {
- let api = api_router();
+ let api = api_router().with_state(test_state());
let body = GetUnfurlBulkBody {
url_list: ["https://hello.com", "https://example.com"]
@@ -171,7 +180,7 @@ mod tests {
#[ignore]
#[tokio::test]
async fn test_bulk_404_links() {
- let api = api_router();
+ let api = api_router().with_state(test_state());
let body = GetUnfurlBulkBody {
url_list: [
diff --git a/rust/cloud-storage/unfurl_service/src/api/proxy/mod.rs b/rust/cloud-storage/unfurl_service/src/api/proxy/mod.rs
index d058581b9b..4bb459835b 100644
--- a/rust/cloud-storage/unfurl_service/src/api/proxy/mod.rs
+++ b/rust/cloud-storage/unfurl_service/src/api/proxy/mod.rs
@@ -1,14 +1,21 @@
use axum::Router;
use axum::body::Body;
-use axum::extract::Query;
+use axum::extract::{Query, State};
use axum::http::Request;
-use axum::response::{IntoResponse, Response};
+use axum::response::Response;
use axum::routing::get;
-use reqwest::{self, StatusCode};
use serde::Deserialize;
use std::collections::HashSet;
use utoipa::{self, ToSchema};
+use crate::http_safety::{
+ FetchError, apply_size_limit, assert_not_internal, build_error_chain, check_content_length,
+ validate_url,
+};
+
+/// 2 MB max proxied response size.
+const MAX_RESPONSE_SIZE: u64 = 2 * 1024 * 1024;
+
#[derive(Debug, ToSchema, Deserialize)]
pub struct ProxyParams {
pub url: String,
@@ -19,12 +26,15 @@ pub struct ProxyParams {
path="/proxy",
params(("url" = String, Query, description = "The url to proxy from")),
)]
-#[tracing::instrument]
+#[tracing::instrument(err(Debug), skip(http_client, request))]
pub async fn proxy_request_handler(
Query(params): Query<ProxyParams>,
+ State(http_client): State<reqwest::Client>,
request: Request<Body>,
-) -> Result<impl IntoResponse, impl IntoResponse> {
- let client = reqwest::Client::new();
+) -> Result<Response, FetchError> {
+ let validated_url = validate_url(&params.url)?;
+ assert_not_internal(&validated_url).await?;
+
let excluded_headers: HashSet<&str> = [
"connection",
"keep-alive",
@@ -40,32 +50,54 @@ pub async fn proxy_request_handler(
.into_iter()
.collect();
- // Build proxied request with forwarded headers
- let mut req_builder = client.get(&params.url);
+ let mut req_builder = http_client.get(validated_url.as_str());
for (key, value) in request.headers().iter() {
if !excluded_headers.contains(key.as_str()) {
req_builder = req_builder.header(key, value);
}
}
- let response = req_builder
- .send()
- .await
- .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?;
- let mut response_builder = Response::builder().status(response.status());
+ let response = req_builder.send().await.map_err(|e| {
+ let error_chain = build_error_chain(&e);
+ tracing::warn!(url = %validated_url, error = %error_chain, "upstream proxy request failed");
+ if e.is_timeout() {
+ FetchError::UpstreamTimeout(error_chain)
+ } else if e.is_connect() {
+ FetchError::UpstreamConnect(error_chain)
+ } else if e.is_redirect() {
+ FetchError::UpstreamRedirect(error_chain)
+ } else {
+ FetchError::UpstreamNetwork(error_chain)
+ }
+ })?;
+ if !response.status().is_success() {
+ return Err(FetchError::UpstreamStatus(response.status()));
+ }
+
+ check_content_length(&response, MAX_RESPONSE_SIZE, &params.url)?;
+
+ let status = response.status();
+ let mut response_builder = Response::builder().status(status);
for (header, value) in response.headers() {
response_builder = response_builder.header(header, value);
}
+
+ let size_limited = apply_size_limit(
+ response.bytes_stream(),
+ MAX_RESPONSE_SIZE,
+ params.url.clone(),
+ );
+
response_builder
.header("Cross-Origin-Resource-Policy", "cross-origin")
- .body(Body::from_stream(response.bytes_stream()))
+ .body(Body::from_stream(size_limited))
.map_err(|e| {
tracing::error!(error=?e, "could not stream chunks");
- (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
+ FetchError::ResponseBuild(e)
})
}
-pub fn router() -> Router {
+pub fn router() -> Router<crate::api::context::ApiContext> {
Router::new().route("/", get(proxy_request_handler))
}
diff --git a/rust/cloud-storage/unfurl_service/src/api/unfurl/get_unfurl.rs b/rust/cloud-storage/unfurl_service/src/api/unfurl/get_unfurl.rs
index 91632128f7..ff7ff44f53 100644
--- a/rust/cloud-storage/unfurl_service/src/api/unfurl/get_unfurl.rs
+++ b/rust/cloud-storage/unfurl_service/src/api/unfurl/get_unfurl.rs
@@ -1,5 +1,6 @@
use axum::extract::Json;
use axum::extract::Query;
+use axum::extract::State;
use axum::http::StatusCode;
use crate::unfurl::{
@@ -36,13 +37,17 @@ pub struct GetUnfurlQueryParams {
("url"=String, Query, description="URL to unfold"),
)
)]
-#[tracing::instrument]
+#[tracing::instrument(skip(http_client))]
pub async fn get_unfurl_handler(
+ State(http_client): State<reqwest::Client>,
Query(params): Query<GetUnfurlQueryParams>,
) -> (StatusCode, Json<Option<GetUnfurlResponse>>) {
- let tags = match extract_meta_tags(&params.url).await {
+ let tags = match extract_meta_tags(&http_client, &params.url).await {
Ok(t) => append_optimistic_favico(t, params.url.as_str()),
- Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(None)),
+ Err(e) => {
+ tracing::warn!(error = %e, url = %params.url, "unfurl failed");
+ return (StatusCode::INTERNAL_SERVER_ERROR, Json(None));
+ }
};
let response = GetUnfurlResponse::new(&params.url, &tags);
@@ -63,11 +68,12 @@ pub async fn get_unfurl_handler(
// TODO: update
//example=json!(["https://macro.com", "https://github.com"])
))]
-#[tracing::instrument]
+#[tracing::instrument(skip(http_client, body))]
pub async fn get_bulk_unfurl_handler(
+ State(http_client): State<reqwest::Client>,
body: Json<GetUnfurlBulkBody>,
) -> (StatusCode, Json<GetUnfurlBulkResponse>) {
- let links = fetch_links_async(&body.url_list).await;
+ let links = fetch_links_async(&http_client, &body.url_list).await;
let response = GetUnfurlBulkResponse { responses: links };
(StatusCode::OK, Json(response))
}
diff --git a/rust/cloud-storage/unfurl_service/src/api/unfurl/mod.rs b/rust/cloud-storage/unfurl_service/src/api/unfurl/mod.rs
index 668e27c461..826893dc97 100644
--- a/rust/cloud-storage/unfurl_service/src/api/unfurl/mod.rs
+++ b/rust/cloud-storage/unfurl_service/src/api/unfurl/mod.rs
@@ -2,7 +2,7 @@ use axum::{Router, routing::get, routing::post};
pub mod get_unfurl;
-pub fn router() -> Router {
+pub fn router() -> Router<crate::api::context::ApiContext> {
Router::new()
.route("/", get(get_unfurl::get_unfurl_handler))
.route("/bulk", post(get_unfurl::get_bulk_unfurl_handler))
diff --git a/rust/cloud-storage/unfurl_service/src/http_safety/mod.rs b/rust/cloud-storage/unfurl_service/src/http_safety/mod.rs
new file mode 100644
index 0000000000..2b680a9232
--- /dev/null
+++ b/rust/cloud-storage/unfurl_service/src/http_safety/mod.rs
@@ -0,0 +1,218 @@
+use axum::response::{IntoResponse, Response};
+use futures::StreamExt;
+use reqwest::StatusCode;
+use std::error::Error;
+use std::fmt;
+use std::net::IpAddr;
+use url::Url;
+
+#[derive(Debug)]
+pub enum FetchError {
+ InvalidUrl(String),
+ InvalidScheme,
+ MissingHost,
+ DnsLookupFailed(std::io::Error),
+ PrivateIp,
+ UpstreamTimeout(String),
+ UpstreamConnect(String),
+ UpstreamRedirect(String),
+ UpstreamNetwork(String),
+ UpstreamStatus(StatusCode),
+ UnexpectedContentType(String),
+ ResponseTooLarge { content_length: u64, max: u64 },
+ ResponseRead(String),
+ ResponseBuild(axum::http::Error),
+}
+
+impl fmt::Display for FetchError {
+ 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: {chain}"),
+ Self::UpstreamConnect(chain) => {
+ write!(f, "connection error fetching upstream: {chain}")
+ }
+ Self::UpstreamRedirect(chain) => {
+ write!(f, "too many redirects fetching upstream: {chain}")
+ }
+ Self::UpstreamNetwork(chain) => write!(f, "network error fetching upstream: {chain}"),
+ Self::UpstreamStatus(status) => write!(f, "upstream returned status {status}"),
+ Self::UnexpectedContentType(ct) => write!(f, "unexpected content-type: {ct}"),
+ Self::ResponseTooLarge {
+ content_length,
+ max,
+ } => write!(
+ f,
+ "response exceeds max size of {max} bytes (Content-Length: {content_length})"
+ ),
+ Self::ResponseRead(chain) => write!(f, "error reading upstream response: {chain}"),
+ Self::ResponseBuild(e) => write!(f, "could not build response: {e}"),
+ }
+ }
+}
+
+impl IntoResponse for FetchError {
+ 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(_)
+ | Self::ResponseRead(_) => StatusCode::BAD_GATEWAY,
+ Self::UnexpectedContentType(_) => StatusCode::UNSUPPORTED_MEDIA_TYPE,
+ Self::ResponseTooLarge { .. } => StatusCode::UNPROCESSABLE_ENTITY,
+ Self::ResponseBuild(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ (status, self.to_string()).into_response()
+ }
+}
+
+pub fn validate_url(raw_url: &str) -> Result<Url, FetchError> {
+ let mut url = Url::parse(raw_url).map_err(|e| FetchError::InvalidUrl(e.to_string()))?;
+
+ if url.scheme() != "http" && url.scheme() != "https" {
+ return Err(FetchError::InvalidScheme);
+ }
+
+ url.set_fragment(None);
+ Ok(url)
+}
+
+pub async fn assert_not_internal(url: &Url) -> Result<(), FetchError> {
+ let host = url.host_str().ok_or(FetchError::MissingHost)?;
+
+ let port = url.port_or_known_default().unwrap_or(80);
+ let addrs = tokio::net::lookup_host(format!("{host}:{port}"))
+ .await
+ .map_err(FetchError::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(FetchError::PrivateIp);
+ }
+ }
+
+ Ok(())
+}
+
+pub 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()
+ }
+ }
+}
+
+pub async fn send_request(
+ http_client: &reqwest::Client,
+ url: &Url,
+) -> Result<reqwest::Response, FetchError> {
+ let response = 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() {
+ FetchError::UpstreamTimeout(error_chain)
+ } else if e.is_connect() {
+ FetchError::UpstreamConnect(error_chain)
+ } else if e.is_redirect() {
+ FetchError::UpstreamRedirect(error_chain)
+ } else {
+ FetchError::UpstreamNetwork(error_chain)
+ }
+ })?;
+
+ if !response.status().is_success() {
+ return Err(FetchError::UpstreamStatus(response.status()));
+ }
+
+ Ok(response)
+}
+
+pub fn content_type_of(response: &reqwest::Response) -> String {
+ response
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("application/octet-stream")
+ .to_string()
+}
+
+pub fn check_content_length(
+ response: &reqwest::Response,
+ max: u64,
+ original_url: &str,
+) -> Result<(), FetchError> {
+ if let Some(content_length) = response.content_length() {
+ tracing::info!(
+ content_length,
+ url = original_url,
+ "upstream content length"
+ );
+ if content_length > max {
+ return Err(FetchError::ResponseTooLarge {
+ content_length,
+ max,
+ });
+ }
+ }
+ Ok(())
+}
+
+pub fn apply_size_limit<S: futures::Stream<Item = Result<bytes::Bytes, reqwest::Error>> + Send>(
+ stream: S,
+ max: u64,
+ url: String,
+) -> impl futures::Stream<Item = Result<bytes::Bytes, axum::Error>> + Send + use<S> {
+ let mut bytes_received: u64 = 0;
+
+ 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 {
+ tracing::warn!(
+ bytes_received,
+ max,
+ url = url,
+ "response exceeded max size during streaming"
+ );
+ return Err(axum::Error::new(std::io::Error::other(format!(
+ "response exceeded max size of {max} bytes during streaming"
+ ))));
+ }
+ Ok(chunk)
+ })
+}
+
+pub 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
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/unfurl_service/src/http_safety/test.rs b/rust/cloud-storage/unfurl_service/src/http_safety/test.rs
new file mode 100644
index 0000000000..c4913323b0
--- /dev/null
+++ b/rust/cloud-storage/unfurl_service/src/http_safety/test.rs
@@ -0,0 +1,100 @@
+use super::*;
+
+#[test]
+fn test_validate_url_accepts_https() {
+ let result = validate_url("https://example.com/page");
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().as_str(), "https://example.com/page");
+}
+
+#[test]
+fn test_validate_url_accepts_http() {
+ let result = validate_url("http://example.com/page");
+ assert!(result.is_ok());
+}
+
+#[test]
+fn test_validate_url_rejects_ftp() {
+ let result = validate_url("ftp://example.com/file");
+ assert!(matches!(result, Err(FetchError::InvalidScheme)));
+}
+
+#[test]
+fn test_validate_url_rejects_data_uri() {
+ let result = validate_url("data:text/html;base64,abc");
+ assert!(result.is_err());
+}
+
+#[test]
+fn test_validate_url_rejects_invalid() {
+ let result = validate_url("not a url");
+ assert!(matches!(result, Err(FetchError::InvalidUrl(_))));
+}
+
+#[test]
+fn test_validate_url_strips_fragment() {
+ let result = validate_url("https://example.com/page#section");
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().as_str(), "https://example.com/page");
+}
+
+#[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() {
+ assert!(is_private_ip(&"::ffff:127.0.0.1".parse().unwrap()));
+ assert!(is_private_ip(&"::ffff:169.254.169.254".parse().unwrap()));
+ assert!(is_private_ip(&"::ffff:10.0.0.1".parse().unwrap()));
+ assert!(is_private_ip(&"::ffff:192.168.1.1".parse().unwrap()));
+ 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(FetchError::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(FetchError::PrivateIp)));
+}
+
+#[tokio::test]
+async fn test_assert_not_internal_allows_public() {
+ let url = Url::parse("https://example.com/page").unwrap();
+ let result = assert_not_internal(&url).await;
+ assert!(result.is_ok());
+}
diff --git a/rust/cloud-storage/unfurl_service/src/lib.rs b/rust/cloud-storage/unfurl_service/src/lib.rs
index 03bf6f68d1..e4fe74f71c 100644
--- a/rust/cloud-storage/unfurl_service/src/lib.rs
+++ b/rust/cloud-storage/unfurl_service/src/lib.rs
@@ -1,2 +1,3 @@
+pub mod http_safety;
mod unfurl;
pub use unfurl::*;
diff --git a/rust/cloud-storage/unfurl_service/src/main.rs b/rust/cloud-storage/unfurl_service/src/main.rs
index 417f12ad4b..b7b40d067c 100644
--- a/rust/cloud-storage/unfurl_service/src/main.rs
+++ b/rust/cloud-storage/unfurl_service/src/main.rs
@@ -1,6 +1,7 @@
#![recursion_limit = "256"]
mod api;
mod config;
+mod http_safety;
mod unfurl;
use anyhow::Context;
use config::Config;
@@ -14,6 +15,19 @@ async fn main() -> anyhow::Result<()> {
let config = Config::from_env().context("expected to be able to generate config")?;
tracing::trace!("initialized config");
- api::setup_and_serve(&config).await?;
+
+ let http_client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(8))
+ .connect_timeout(std::time::Duration::from_secs(3))
+ .redirect(reqwest::redirect::Policy::limited(5))
+ .build()
+ .context("failed to build http client")?;
+
+ let state = api::context::ApiContext {
+ environment: config.environment,
+ http_client,
+ };
+
+ api::setup_and_serve(state, config.port).await?;
Ok(())
}
diff --git a/rust/cloud-storage/unfurl_service/src/openapi.rs b/rust/cloud-storage/unfurl_service/src/openapi.rs
index 775dc59b53..2a20f2ecc1 100644
--- a/rust/cloud-storage/unfurl_service/src/openapi.rs
+++ b/rust/cloud-storage/unfurl_service/src/openapi.rs
@@ -2,6 +2,7 @@
mod api;
mod config;
+mod http_safety;
mod unfurl;
use utoipa::OpenApi;
diff --git a/rust/cloud-storage/unfurl_service/src/unfurl/mod.rs b/rust/cloud-storage/unfurl_service/src/unfurl/mod.rs
index 5fd748d250..084be70a9c 100644
--- a/rust/cloud-storage/unfurl_service/src/unfurl/mod.rs
+++ b/rust/cloud-storage/unfurl_service/src/unfurl/mod.rs
@@ -1,14 +1,25 @@
pub mod url_parsers;
use anyhow::{Context, Error};
+use futures::StreamExt;
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use url::Url;
use utoipa::ToSchema;
+use crate::http_safety::{
+ FetchError, assert_not_internal, check_content_length, content_type_of, send_request,
+ validate_url,
+};
use url_parsers::parse_custom_title;
+/// 1 MB max HTML response size for meta-tag extraction.
+pub const MAX_HTML_SIZE: u64 = 1024 * 1024;
+
+/// Cap on concurrent outbound requests for `fetch_links_async`.
+pub const BULK_CONCURRENCY: usize = 16;
+
pub type GetUnfurlResponseList = Vec<Option<GetUnfurlResponse>>;
#[derive(Debug, Serialize, Deserialize, ToSchema, Default, Clone, Eq, PartialEq)]
@@ -88,26 +99,91 @@ fn find_favicon(document: &Html, base_url: &Url) -> Option<String> {
None
}
-#[tracing::instrument]
+
+#[derive(Debug)]
+pub enum UnfurlFetchError {
+ Fetch(FetchError),
+ Parse(Error),
+}
+
+impl std::fmt::Display for UnfurlFetchError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Fetch(e) => write!(f, "{e}"),
+ Self::Parse(e) => write!(f, "{e}"),
+ }
+ }
+}
+
+impl From<FetchError> for UnfurlFetchError {
+ fn from(e: FetchError) -> Self {
+ Self::Fetch(e)
+ }
+}
+
+#[tracing::instrument(err(Debug), skip(client))]
pub async fn extract_meta_tags_prod(
- url: &str,
-) -> Result<HashMap<String, String>, Box<dyn std::error::Error + Send + Sync>> {
- // Fetch the HTML content
- // TODO: how to handle malicious input?
+ client: &reqwest::Client,
+ raw_url: &str,
+) -> Result<HashMap<String, String>, UnfurlFetchError> {
+ let url = validate_url(raw_url)?;
+ assert_not_internal(&url).await?;
- use http::StatusCode;
- let url = Url::parse(url).context("invalid url")?;
+ let response = send_request(client, &url).await?;
- let response = reqwest::get(url.clone()).await?;
- if response.status() != StatusCode::OK {
- return Err(anyhow::anyhow!("Site refused with code: {}", response.status()).into());
+ let content_type = content_type_of(&response);
+ if !is_html_content_type(&content_type) {
+ return Err(FetchError::UnexpectedContentType(content_type).into());
}
- let html_content = response.text().await?;
- let meta_tags = parse_document(&html_content, &url)?;
+
+ check_content_length(&response, MAX_HTML_SIZE, raw_url)?;
+
+ let html_content = read_body_capped(response, MAX_HTML_SIZE).await?;
+
+ let meta_tags = parse_document(&html_content, &url).map_err(UnfurlFetchError::Parse)?;
Ok(meta_tags)
}
+fn is_html_content_type(content_type: &str) -> bool {
+ // `content_type` may include charset, e.g. "text/html; charset=utf-8".
+ let primary = content_type
+ .split(';')
+ .next()
+ .unwrap_or(content_type)
+ .trim()
+ .to_ascii_lowercase();
+ primary == "text/html" || primary == "application/xhtml+xml"
+}
+
+async fn read_body_capped(
+ response: reqwest::Response,
+ max: u64,
+) -> Result<String, UnfurlFetchError> {
+ let mut stream = response.bytes_stream();
+ let mut buf: Vec<u8> = Vec::new();
+ while let Some(chunk) = stream.next().await {
+ let chunk = chunk.map_err(|e| {
+ let chain = crate::http_safety::build_error_chain(&e);
+ tracing::warn!(error = %chain, "error reading unfurl response body");
+ UnfurlFetchError::Fetch(FetchError::ResponseRead(chain))
+ })?;
+ if (buf.len() as u64) + (chunk.len() as u64) > max {
+ tracing::warn!(max, "unfurl response exceeded max size during streaming");
+ return Err(UnfurlFetchError::Fetch(FetchError::ResponseTooLarge {
+ content_length: (buf.len() as u64) + (chunk.len() as u64),
+ max,
+ }));
+ }
+ buf.extend_from_slice(&chunk);
+ }
+ String::from_utf8(buf).map_err(|e| {
+ UnfurlFetchError::Fetch(FetchError::ResponseRead(format!(
+ "response body was not valid UTF-8: {e}"
+ )))
+ })
+}
+
pub fn favico_url(url: &str) -> Result<String, anyhow::Error> {
let url = Url::parse(url).context("failed to parse url")?;
let host = url.host().ok_or_else(|| anyhow::anyhow!("no host"))?;
@@ -136,18 +212,19 @@ pub fn append_optimistic_favico(
}
pub async fn extract_meta_tags(
+ client: &reqwest::Client,
url: &str,
-) -> Result<HashMap<String, String>, Box<dyn std::error::Error + Send + Sync>> {
+) -> Result<HashMap<String, String>, UnfurlFetchError> {
if cfg!(feature = "mock") {
extract_meta_tags_mock(url).await
} else {
- extract_meta_tags_prod(url).await
+ extract_meta_tags_prod(client, url).await
}
}
pub async fn extract_meta_tags_mock(
url: &str,
-) -> Result<HashMap<String, String>, Box<dyn std::error::Error + Send + Sync>> {
+) -> Result<HashMap<String, String>, UnfurlFetchError> {
if url == "https://hello.com" {
let mut m = HashMap::new();
m.insert("property:og:title".to_string(), "Hello".to_string());
@@ -171,7 +248,7 @@ pub async fn extract_meta_tags_mock(
return Ok(m);
}
- Err("not found".into())
+ Err(UnfurlFetchError::Parse(anyhow::anyhow!("not found")))
}
impl GetUnfurlResponse {
@@ -232,16 +309,29 @@ impl GetUnfurlResponse {
}
}
-pub async fn fetch_links_async(links: &[String]) -> GetUnfurlResponseList {
- let futures = links.iter().map(|url| async move {
- extract_meta_tags(url)
- .await
- .ok()
- .map(|tags| append_optimistic_favico(tags, url))
- .map(|tags| GetUnfurlResponse::new(url, &tags))
- });
-
- futures::future::join_all(futures).await
+pub async fn fetch_links_async(
+ client: &reqwest::Client,
+ links: &[String],
+) -> GetUnfurlResponseList {
+ futures::stream::iter(links.iter().cloned())
+ .map(|url| {
+ let client = client.clone();
+ async move {
+ match extract_meta_tags(&client, &url).await {
+ Ok(tags) => {
+ let tags = append_optimistic_favico(tags, &url);
+ Some(GetUnfurlResponse::new(&url, &tags))
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, url = %url, "bulk unfurl failed for url");
+ None
+ }
+ }
+ }
+ })
+ .buffered(BULK_CONCURRENCY)
+ .collect()
+ .await
}
#[cfg(test)]
@@ -399,7 +489,10 @@ mod tests {
#[cfg(feature = "mock")]
#[tokio::test]
async fn test_extract_meta_tags_mock() {
- let tags = extract_meta_tags("https://hello.com").await.unwrap();
+ let client = reqwest::Client::new();
+ let tags = extract_meta_tags(&client, "https://hello.com")
+ .await
+ .unwrap();
assert!(tags.contains_key("property:og:title"));
let title = tags.get("property:og:title").unwrap();
assert_eq!(title, "Hello");
@@ -481,4 +574,13 @@ mod tests {
let title = GetUnfurlResponse::get_title(regular_url, &tags);
assert_eq!(title, "Regular Website Title");
}
+
+ #[test]
+ fn test_is_html_content_type() {
+ assert!(is_html_content_type("text/html"));
+ assert!(is_html_content_type("text/html; charset=utf-8"));
+ assert!(is_html_content_type("application/xhtml+xml"));
+ assert!(!is_html_content_type("image/png"));
+ assert!(!is_html_content_type("application/json"));
+ }
}