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
Hexify GET /unfurl endpoint into new unfurl crate (#3410)
Evan Hutnikc937ad9dab9c
diff --git a/js/app/packages/service-clients/service-unfurl/generated/client.ts b/js/app/packages/service-clients/service-unfurl/generated/client.tsindex 12e7910c8a..d075f3decb 100644--- a/js/app/packages/service-clients/service-unfurl/generated/client.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/client.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type {+ GetUnfurl500,GetUnfurlBulkBody,GetUnfurlBulkResponse,GetUnfurlParams,@@ -62,34 +63,28 @@ export const proxyRequestHandler = async (} as proxyRequestHandlerResponse;};+/**+ * On success returns `200` with a [`GetUnfurlResponse`] body. On any+failure returns `500` with a JSON `null` body — the response type is an+`Option<GetUnfurlResponse>` so this contract is reflected in the+signature and OpenAPI spec.+ * @summary Unfurl the URL passed via the `url` query parameter and return its+extracted metadata (title, description, image, favicon).+ */export type getUnfurlResponse200 = {data: GetUnfurlResponse;status: 200;};-export type getUnfurlResponse401 = {- data: string;- status: 401;-};--export type getUnfurlResponse404 = {- data: string;- status: 404;-};-export type getUnfurlResponse500 = {- data: string;+ data: GetUnfurl500;status: 500;};export type getUnfurlResponseSuccess = getUnfurlResponse200 & {headers: Headers;};-export type getUnfurlResponseError = (- | getUnfurlResponse401- | getUnfurlResponse404- | getUnfurlResponse500-) & {+export type getUnfurlResponseError = getUnfurlResponse500 & {headers: Headers;};diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurl500.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurl500.tsnew file mode 100644index 0000000000..0f16ddd1e0--- /dev/null+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurl500.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * unfurl_service+ * OpenAPI spec version: 0.1.0+ */+import type { GetUnfurlResponse } from './getUnfurlResponse';++export type GetUnfurl500 = null | GetUnfurlResponse;diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlParams.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlParams.tsindex 4e7d760516..b3bbd4cb8f 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlParams.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlParams.ts@@ -7,7 +7,7 @@export type GetUnfurlParams = {/**- * URL to unfold+ * The URL to unfurl.*/url: string;};diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlQueryParams.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlQueryParams.tsindex 3f4bb8dc8d..13cc375a2b 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlQueryParams.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlQueryParams.ts@@ -5,6 +5,10 @@* OpenAPI spec version: 0.1.0*/+/**+ * Query parameters for `GET /unfurl`.+ */export interface GetUnfurlQueryParams {+ /** The URL to unfurl. */url: string;}diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponse.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponse.tsindex 0ef2b4766d..9950e6dc91 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponse.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponse.ts@@ -8,10 +8,20 @@ import type { GetUnfurlResponseDescription } from './getUnfurlResponseDescriptioimport type { GetUnfurlResponseFaviconUrl } from './getUnfurlResponseFaviconUrl';import type { GetUnfurlResponseImageUrl } from './getUnfurlResponseImageUrl';+/**+ * Unfurl response for a single URL: the URL itself plus any metadata that+was extracted from the page's `<head>` (title, description, image,+favicon).+ */export interface GetUnfurlResponse {+ /** The page description (from `og:description`), if any. */description?: GetUnfurlResponseDescription;+ /** The page's favicon URL, if any. */favicon_url?: GetUnfurlResponseFaviconUrl;+ /** The page's preview image URL (from `og:image`), if any. */image_url?: GetUnfurlResponseImageUrl;+ /** The page title (from custom URL parser, Open Graph, or `<title>`). */title: string;+ /** The URL that was unfurled. */url: string;}diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseDescription.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseDescription.tsindex 8a623c1da8..e4b86049d3 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseDescription.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseDescription.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * The page description (from `og:description`), if any.+ */export type GetUnfurlResponseDescription = string | null;diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseFaviconUrl.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseFaviconUrl.tsindex a49c4ef8bf..d9ef0031b0 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseFaviconUrl.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseFaviconUrl.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * The page's favicon URL, if any.+ */export type GetUnfurlResponseFaviconUrl = string | null;diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseImageUrl.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseImageUrl.tsindex cd985628b8..d136461956 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseImageUrl.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/getUnfurlResponseImageUrl.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * The page's preview image URL (from `og:image`), if any.+ */export type GetUnfurlResponseImageUrl = string | null;diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/index.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/index.tsindex aecc5b6120..a76b2da68b 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/index.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/+export * from './getUnfurl500';export * from './getUnfurlBulkBody';export * from './getUnfurlBulkResponse';export * from './getUnfurlParams';diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOf.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOf.tsindex d97cefa622..c2f7b42704 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOf.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOf.ts@@ -8,10 +8,20 @@ import type { VecItemOneOfDescription } from './vecItemOneOfDescription';import type { VecItemOneOfFaviconUrl } from './vecItemOneOfFaviconUrl';import type { VecItemOneOfImageUrl } from './vecItemOneOfImageUrl';+/**+ * Unfurl response for a single URL: the URL itself plus any metadata that+was extracted from the page's `<head>` (title, description, image,+favicon).+ */export type VecItemOneOf = {+ /** The page description (from `og:description`), if any. */description?: VecItemOneOfDescription;+ /** The page's favicon URL, if any. */favicon_url?: VecItemOneOfFaviconUrl;+ /** The page's preview image URL (from `og:image`), if any. */image_url?: VecItemOneOfImageUrl;+ /** The page title (from custom URL parser, Open Graph, or `<title>`). */title: string;+ /** The URL that was unfurled. */url: string;};diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfDescription.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfDescription.tsindex 67c17ed48e..55d5632382 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfDescription.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfDescription.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * The page description (from `og:description`), if any.+ */export type VecItemOneOfDescription = string | null;diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfFaviconUrl.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfFaviconUrl.tsindex ef2cf1c029..bf031f8ef4 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfFaviconUrl.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfFaviconUrl.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * The page's favicon URL, if any.+ */export type VecItemOneOfFaviconUrl = string | null;diff --git a/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfImageUrl.ts b/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfImageUrl.tsindex 04045e866f..759bb055f4 100644--- a/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfImageUrl.ts+++ b/js/app/packages/service-clients/service-unfurl/generated/schemas/vecItemOneOfImageUrl.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * The page's preview image URL (from `og:image`), if any.+ */export type VecItemOneOfImageUrl = string | null;diff --git a/js/app/packages/service-clients/service-unfurl/openapi.json b/js/app/packages/service-clients/service-unfurl/openapi.jsonindex 389ad6a741..1b387844a3 100644--- a/js/app/packages/service-clients/service-unfurl/openapi.json+++ b/js/app/packages/service-clients/service-unfurl/openapi.json@@ -31,12 +31,14 @@"/unfurl": {"get": {"tags": ["unfurl"],+ "summary": "Unfurl the URL passed via the `url` query parameter and return its\nextracted metadata (title, description, image, favicon).",+ "description": "On success returns `200` with a [`GetUnfurlResponse`] body. On any\nfailure returns `500` with a JSON `null` body — the response type is an\n`Option<GetUnfurlResponse>` so this contract is reflected in the\nsignature and OpenAPI spec.","operationId": "get_unfurl","parameters": [{"name": "url","in": "query",- "description": "URL to unfold",+ "description": "The URL to unfurl.","required": true,"schema": {"type": "string"@@ -45,7 +47,7 @@],"responses": {"200": {- "description": "",+ "description": "Unfurled metadata for the URL.","content": {"application/json": {"schema": {@@ -54,32 +56,19 @@}}},- "401": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- },- "404": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- },"500": {- "description": "",+ "description": "Unfurl failed; response body is JSON null.","content": {- "text/plain": {+ "application/json": {"schema": {- "type": "string"+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/GetUnfurlResponse"+ }+ ]}}}@@ -172,31 +161,39 @@},"GetUnfurlQueryParams": {"type": "object",+ "description": "Query parameters for `GET /unfurl`.","required": ["url"],"properties": {"url": {- "type": "string"+ "type": "string",+ "description": "The URL to unfurl."}}},"GetUnfurlResponse": {"type": "object",+ "description": "Unfurl response for a single URL: the URL itself plus any metadata that\nwas extracted from the page's `<head>` (title, description, image,\nfavicon).","required": ["url", "title"],"properties": {"description": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The page description (from `og:description`), if any."},"favicon_url": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The page's favicon URL, if any."},"image_url": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The page's preview image URL (from `og:image`), if any."},"title": {- "type": "string"+ "type": "string",+ "description": "The page title (from custom URL parser, Open Graph, or `<title>`)."},"url": {- "type": "string"+ "type": "string",+ "description": "The URL that was unfurled."}}},@@ -218,22 +215,28 @@},{"type": "object",+ "description": "Unfurl response for a single URL: the URL itself plus any metadata that\nwas extracted from the page's `<head>` (title, description, image,\nfavicon).","required": ["url", "title"],"properties": {"description": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The page description (from `og:description`), if any."},"favicon_url": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The page's favicon URL, if any."},"image_url": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The page's preview image URL (from `og:image`), if any."},"title": {- "type": "string"+ "type": "string",+ "description": "The page title (from custom URL parser, Open Graph, or `<title>`)."},"url": {- "type": "string"+ "type": "string",+ "description": "The URL that was unfurled."}}}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex d4beb0936b..79435cbd83 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -11770,6 +11770,25 @@ version = "1.20.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"+[[package]]+name = "unfurl"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum",+ "bytes",+ "futures",+ "mockall",+ "reqwest 0.13.3",+ "scraper",+ "serde",+ "thiserror 2.0.17",+ "tokio",+ "tracing",+ "url",+ "utoipa",+]+[[package]]name = "unfurl_service"version = "0.1.0"@@ -11791,6 +11810,7 @@ dependencies = ["tower 0.5.3","tower-http","tracing",+ "unfurl","url","utoipa","utoipa-swagger-ui",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 0f501d3568..868d9e485f 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -40,6 +40,7 @@ members = ["sha_cleanup_worker","static_file_service","tools/native_app_server",+ "unfurl","unfurl_service","upload_extractor_lambda_handler","upload_extractor_lambda_trigger",diff --git a/rust/cloud-storage/unfurl/Cargo.toml b/rust/cloud-storage/unfurl/Cargo.tomlnew file mode 100644index 0000000000..ae6e21b642--- /dev/null+++ b/rust/cloud-storage/unfurl/Cargo.toml@@ -0,0 +1,30 @@+[package]+edition = "2024"+name = "unfurl"+publish = false+version = "0.1.0"++[features]+all = ["axum", "inbound", "outbound", "ports"]+axum = ["inbound", "dep:axum", "dep:utoipa"]+inbound = ["ports"]+outbound = ["dep:bytes", "dep:futures", "dep:reqwest", "dep:scraper", "dep:tokio", "ports"]+ports = []++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true, optional = true }+bytes = { workspace = true, optional = true }+futures = { workspace = true, optional = true }+reqwest = { workspace = true, features = ["stream"], optional = true }+scraper = { workspace = true, optional = true }+serde = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true, optional = true }+tracing = { workspace = true }+url = { workspace = true }+utoipa = { workspace = true, optional = true }++[dev-dependencies]+mockall = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt"] }diff --git a/rust/cloud-storage/unfurl/src/domain.rs b/rust/cloud-storage/unfurl/src/domain.rsnew file mode 100644index 0000000000..6979cb4971--- /dev/null+++ b/rust/cloud-storage/unfurl/src/domain.rs@@ -0,0 +1,10 @@+//! Domain layer for the unfurl crate.++pub mod favicon;+pub mod models;+pub mod url_parsers;++#[cfg(feature = "ports")]+pub mod ports;+#[cfg(feature = "ports")]+pub mod service;diff --git a/rust/cloud-storage/unfurl/src/domain/favicon.rs b/rust/cloud-storage/unfurl/src/domain/favicon.rsnew file mode 100644index 0000000000..e4ebb937be--- /dev/null+++ b/rust/cloud-storage/unfurl/src/domain/favicon.rs@@ -0,0 +1,36 @@+//! Favicon helpers used to fill in a default favicon when meta-tag extraction+//! didn't produce one.++use std::collections::HashMap;+use url::Url;++/// Returns the conventional `<scheme>://<host>[:<port>]/favicon.ico` URL for+/// the given input URL.+pub fn favico_url(url: &str) -> Result<String, anyhow::Error> {+ let url = Url::parse(url).map_err(|e| anyhow::anyhow!("failed to parse url: {e}"))?;+ let host = url.host().ok_or_else(|| anyhow::anyhow!("no host"))?;+ let scheme = url.scheme();+ let port = url+ .port()+ .map(|port| format!(":{port}"))+ .unwrap_or_default();+ Ok(format!("{scheme}://{host}{port}/favicon.ico"))+}++/// Inserts a conventional `/favicon.ico` URL into `meta_tags` when one wasn't+/// already extracted from the page's `<link>` tags.+pub fn append_optimistic_favico(+ mut meta_tags: HashMap<String, String>,+ url: &str,+) -> HashMap<String, String> {+ let optimistic_url = favico_url(url)+ .inspect_err(|err| tracing::debug!(error=?err, "could not form favicon url"));++ if !meta_tags.contains_key("favicon")+ && let Ok(url) = optimistic_url+ {+ meta_tags.insert("favicon".to_string(), url);+ }++ meta_tags+}diff --git a/rust/cloud-storage/unfurl/src/domain/models.rs b/rust/cloud-storage/unfurl/src/domain/models.rsnew file mode 100644index 0000000000..ab45782bec--- /dev/null+++ b/rust/cloud-storage/unfurl/src/domain/models.rs@@ -0,0 +1,164 @@+//! Domain models for the unfurl crate.++use std::collections::HashMap;++use serde::{Deserialize, Serialize};+use thiserror::Error;+use url::Url;++use super::url_parsers::parse_custom_title;++/// Unfurl response for a single URL: the URL itself plus any metadata that+/// was extracted from the page's `<head>` (title, description, image,+/// favicon).+#[derive(Debug, Serialize, Deserialize, Default, Clone, Eq, PartialEq)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub struct GetUnfurlResponse {+ /// The URL that was unfurled.+ pub url: String,+ /// The page title (from custom URL parser, Open Graph, or `<title>`).+ pub title: String,+ /// The page description (from `og:description`), if any.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+ /// The page's preview image URL (from `og:image`), if any.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub image_url: Option<String>,+ /// The page's favicon URL, if any.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub favicon_url: Option<String>,+}++impl GetUnfurlResponse {+ /// Resolve the title for `url`, given previously-extracted `metatags`.+ ///+ /// Custom URL parsers (Notion, Figma, Linear) win over meta tags so that+ /// services which embed their titles in URLs but render generic HTML+ /// titles still produce useful previews. Falls back to `og:title`,+ /// `og:site_name`, `<title>`, and finally the URL string itself.+ pub fn get_title(url: &str, metatags: &HashMap<String, String>) -> String {+ if let Some(custom_title) = parse_custom_title(url) {+ return custom_title;+ }++ let properties = ["property:og:title", "property:og:site_name", "title"];+ let title = properties.iter().find_map(|p| metatags.get(*p));++ match title {+ Some(s) => s.to_string(),+ None => url.to_string(),+ }+ }++ /// Build a response by combining the URL and extracted meta tags.+ pub fn new(url: &str, metatags: &HashMap<String, String>) -> Self {+ let title = Self::get_title(url, metatags);+ let description = metatags+ .get("property:og:description")+ .map(|s| s.to_string());+ let image_url = metatags.get("property:og:image").map(|s| s.to_string());++ let mut favicon_url = metatags.get("favicon").map(|s| s.to_string());++ // Resolve favicon URL to absolute path against the page URL.+ if let Ok(base_url) = Url::parse(url)+ && let Some(furl) = favicon_url.as_deref()+ && let Ok(joined) = base_url.join(furl)+ {+ favicon_url = Some(joined.to_string());+ }++ GetUnfurlResponse {+ url: url.to_string(),+ title,+ description,+ image_url,+ favicon_url,+ }+ }+}++/// Convenience alias for a list of nullable unfurl responses (one entry per+/// requested URL; `None` means the unfurl failed for that URL).+pub type GetUnfurlResponseList = Vec<Option<GetUnfurlResponse>>;++/// Errors that can occur in the unfurl domain.+#[derive(Debug, Error)]+pub enum UnfurlErr {+ /// The underlying fetcher failed to retrieve or parse the page.+ #[error(transparent)]+ Fetch(#[from] anyhow::Error),+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_extract_opengraph() {+ let mut tags: HashMap<String, String> = HashMap::new();+ tags.insert("property:og:title".to_string(), "hello".to_string());+ tags.insert(+ "property:og:description".to_string(),+ "this is a description".to_string(),+ );+ tags.insert("property:og:image".to_string(), "foo.jpg".to_string());++ let link = GetUnfurlResponse::new("localhost", &tags);++ assert_eq!(link.url, "localhost");+ assert_eq!(link.title, "hello");+ assert_eq!(link.description.as_deref(), Some("this is a description"));+ assert_eq!(link.image_url.as_deref(), Some("foo.jpg"));+ }++ #[test]+ fn test_og_title_before_sitename() {+ let mut tags = HashMap::new();+ tags.insert(+ "property:og:site_name".to_string(),+ "website title".to_string(),+ );+ tags.insert("property:og:title".to_string(), "hello".to_string());++ let response = GetUnfurlResponse::new("localhost", &tags);+ assert_eq!(response.title, "hello");+ }++ #[test]+ fn test_fallback_to_title_tag() {+ let mut tags = HashMap::new();+ tags.insert("title".to_string(), "Website Title".to_string());++ let response = GetUnfurlResponse::new("localhost", &tags);+ assert_eq!(response.title, "Website Title");+ }++ #[test]+ fn test_custom_url_title_parsing_notion() {+ let empty_tags = HashMap::new();++ let notion_url = "https://www.notion.so/macrocom/Enterprise-Product-Bottlenecks-5acb869109a747c1a1a92bbf1891ff2d";+ assert_eq!(+ GetUnfurlResponse::get_title(notion_url, &empty_tags),+ "Enterprise Product Bottlenecks"+ );++ assert_eq!(+ GetUnfurlResponse::get_title("https://www.notion.so", &empty_tags),+ "Notion"+ );+ }++ #[test]+ fn test_custom_url_falls_back_to_metadata() {+ let mut tags = HashMap::new();+ tags.insert(+ "property:og:title".to_string(),+ "Regular Website Title".to_string(),+ );++ let title = GetUnfurlResponse::get_title("https://example.com/some/page", &tags);+ assert_eq!(title, "Regular Website Title");+ }+}diff --git a/rust/cloud-storage/unfurl/src/domain/ports.rs b/rust/cloud-storage/unfurl/src/domain/ports.rsnew file mode 100644index 0000000000..d0b552020a--- /dev/null+++ b/rust/cloud-storage/unfurl/src/domain/ports.rs@@ -0,0 +1,36 @@+//! Inbound and outbound ports for the unfurl domain.++use std::collections::HashMap;++use crate::domain::models::{GetUnfurlResponse, UnfurlErr};++/// Outbound port: fetches and parses meta tags from a given URL.+///+/// Implementations live in `outbound/` (e.g. the reqwest + scraper adapter).+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+pub trait UnfurlFetcher: Send + Sync + 'static {+ /// Adapter-specific error type. The service converts these into+ /// [`UnfurlErr::Fetch`] via [`anyhow::Error`].+ type Err: Send;++ /// Fetch the given URL and extract its `<meta>` / `<title>` /+ /// favicon entries into a flat key/value map.+ ///+ /// Keys follow the conventions used downstream by+ /// [`GetUnfurlResponse::get_title`] — `property:og:title`,+ /// `property:og:description`, `property:og:image`, `title`, `favicon`.+ fn fetch_meta_tags(+ &self,+ url: &str,+ ) -> impl Future<Output = Result<HashMap<String, String>, Self::Err>> + Send;+}++/// Inbound port: the unfurl feature exposed to adapters (HTTP, tools, …).+pub trait UnfurlService: Send + Sync + 'static {+ /// Unfurl a single URL, returning a [`GetUnfurlResponse`] with title,+ /// description, image, and favicon as available.+ fn unfurl(+ &self,+ url: &str,+ ) -> impl Future<Output = Result<GetUnfurlResponse, UnfurlErr>> + Send;+}diff --git a/rust/cloud-storage/unfurl/src/domain/service.rs b/rust/cloud-storage/unfurl/src/domain/service.rsnew file mode 100644index 0000000000..5fb06b1ef8--- /dev/null+++ b/rust/cloud-storage/unfurl/src/domain/service.rs@@ -0,0 +1,85 @@+//! Service implementation that drives the [`UnfurlFetcher`] port and turns+//! its raw meta-tag output into a [`GetUnfurlResponse`].++use crate::domain::{+ favicon::append_optimistic_favico,+ models::{GetUnfurlResponse, UnfurlErr},+ ports::{UnfurlFetcher, UnfurlService},+};++/// Default [`UnfurlService`] implementation, parameterized over an+/// [`UnfurlFetcher`] adapter.+pub struct UnfurlServiceImpl<F> {+ fetcher: F,+}++impl<F> UnfurlServiceImpl<F>+where+ F: UnfurlFetcher,+{+ /// Construct a new service over the given fetcher.+ pub fn new(fetcher: F) -> Self {+ Self { fetcher }+ }+}++impl<F> UnfurlService for UnfurlServiceImpl<F>+where+ F: UnfurlFetcher,+ anyhow::Error: From<F::Err>,+{+ #[tracing::instrument(err, skip(self))]+ async fn unfurl(&self, url: &str) -> Result<GetUnfurlResponse, UnfurlErr> {+ let tags = self+ .fetcher+ .fetch_meta_tags(url)+ .await+ .map_err(|e| UnfurlErr::Fetch(e.into()))?;+ let tags = append_optimistic_favico(tags, url);+ Ok(GetUnfurlResponse::new(url, &tags))+ }+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use super::*;+ use crate::domain::ports::MockUnfurlFetcher;++ #[tokio::test]+ async fn unfurl_returns_response_built_from_fetcher_tags() {+ let mut fetcher = MockUnfurlFetcher::new();+ fetcher.expect_fetch_meta_tags().returning(|_| {+ Box::pin(async move {+ let mut tags = HashMap::new();+ tags.insert("property:og:title".to_string(), "Title".to_string());+ tags.insert("property:og:description".to_string(), "Desc".to_string());+ Ok(tags)+ })+ });+ let service = UnfurlServiceImpl::new(fetcher);++ let res = service.unfurl("https://example.com/page").await.unwrap();+ assert_eq!(res.url, "https://example.com/page");+ assert_eq!(res.title, "Title");+ assert_eq!(res.description.as_deref(), Some("Desc"));+ // optimistic favicon is filled in when the page didn't provide one+ assert_eq!(+ res.favicon_url.as_deref(),+ Some("https://example.com/favicon.ico")+ );+ }++ #[tokio::test]+ async fn unfurl_surfaces_fetcher_errors() {+ let mut fetcher = MockUnfurlFetcher::new();+ fetcher+ .expect_fetch_meta_tags()+ .returning(|_| Box::pin(async move { Err(anyhow::anyhow!("boom")) }));+ let service = UnfurlServiceImpl::new(fetcher);++ let err = service.unfurl("https://example.com").await.unwrap_err();+ assert!(matches!(err, UnfurlErr::Fetch(_)));+ }+}diff --git a/rust/cloud-storage/unfurl_service/src/unfurl/url_parsers.rs b/rust/cloud-storage/unfurl/src/domain/url_parsers.rssimilarity index 74%rename from rust/cloud-storage/unfurl_service/src/unfurl/url_parsers.rsrename to rust/cloud-storage/unfurl/src/domain/url_parsers.rsindex 0a9ff50e0e..2bee51ca68 100644--- a/rust/cloud-storage/unfurl_service/src/unfurl/url_parsers.rs+++ b/rust/cloud-storage/unfurl/src/domain/url_parsers.rs@@ -6,11 +6,10 @@ use url::Url;/// Parses Notion URLs to extract document titles/// Supports formats like:/// - notion.so/workspace/Title-With-Dashes-uuid-/// - notion.so/Title-With-Dashes-uuid+/// - notion.so/Title-With-Dashes-uuidpub fn parse_notion_title(url: &str) -> Option<String> {let parsed_url = Url::parse(url).ok()?;- // Check if this is a Notion domainif !parsed_url.host_str()?.contains("notion.so") {return None;}@@ -18,10 +17,8 @@ pub fn parse_notion_title(url: &str) -> Option<String> {let path = parsed_url.path();let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();- // Look for the last segment that contains both a title and UUID- // Pattern: [workspace/]title-with-dashes-uuidlet title_segment = segments.iter().rev().find(|segment| {- // Check if segment has UUID pattern at the end (32 hex chars without dashes)+ // UUID at end is 32 hex chars without dashessegment.len() > 32&& segment.chars()@@ -30,20 +27,12 @@ pub fn parse_notion_title(url: &str) -> Option<String> {.all(|c| c.is_ascii_hexdigit())})?;- // Extract title part (everything before the last 33 characters: -uuid)if title_segment.len() > 33 {let title_part = &title_segment[..title_segment.len() - 33];let title = title_part.replace('-', " ");- // Capitalize first letter of each wordlet formatted_title = title.split_whitespace()- .map(|word| {- let mut chars: Vec<char> = word.chars().collect();- if !chars.is_empty() {- chars[0] = chars[0].to_uppercase().next().unwrap_or(chars[0]);- }- chars.into_iter().collect::<String>()- })+ .map(capitalize_first).collect::<Vec<String>>().join(" ");@@ -61,7 +50,6 @@ pub fn parse_notion_title(url: &str) -> Option<String> {pub fn parse_figma_title(url: &str) -> Option<String> {let parsed_url = Url::parse(url).ok()?;- // Check if this is a Figma domainif !parsed_url.host_str()?.contains("figma.com") {return None;}@@ -69,20 +57,12 @@ pub fn parse_figma_title(url: &str) -> Option<String> {let path = parsed_url.path();let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();- // Pattern: figma.com/design/file-id/title-with-dashesif segments.len() >= 3 && segments[0] == "design" {let title_segment = segments[2];let title = title_segment.replace('-', " ");- // Capitalize first letter of each wordlet formatted_title = title.split_whitespace()- .map(|word| {- let mut chars: Vec<char> = word.chars().collect();- if !chars.is_empty() {- chars[0] = chars[0].to_uppercase().next().unwrap_or(chars[0]);- }- chars.into_iter().collect::<String>()- })+ .map(capitalize_first).collect::<Vec<String>>().join(" ");@@ -100,7 +80,6 @@ pub fn parse_figma_title(url: &str) -> Option<String> {pub fn parse_linear_title(url: &str) -> Option<String> {let parsed_url = Url::parse(url).ok()?;- // Check if this is a Linear domainif !parsed_url.host_str()?.contains("linear.app") {return None;}@@ -108,20 +87,12 @@ pub fn parse_linear_title(url: &str) -> Option<String> {let path = parsed_url.path();let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();- // Pattern: linear.app/team/issue/ticket-id/title-with-dashesif segments.len() >= 4 && segments[1] == "issue" {let title_segment = segments[3];let title = title_segment.replace('-', " ");- // Capitalize first letter of each wordlet formatted_title = title.split_whitespace()- .map(|word| {- let mut chars: Vec<char> = word.chars().collect();- if !chars.is_empty() {- chars[0] = chars[0].to_uppercase().next().unwrap_or(chars[0]);- }- chars.into_iter().collect::<String>()- })+ .map(capitalize_first).collect::<Vec<String>>().join(" ");@@ -133,13 +104,12 @@ pub fn parse_linear_title(url: &str) -> Option<String> {None}-/// Attempts to parse a title from the URL using custom parsers for known services-/// Returns the service name as fallback if parsing fails+/// Attempts to parse a title from the URL using custom parsers for known services.+/// Returns the service name as fallback if parsing fails on a recognized host.pub fn parse_custom_title(url: &str) -> Option<String> {let parsed_url = Url::parse(url).ok()?;let host = parsed_url.host_str()?;- // Try Notion parserif host.contains("notion.so") {if let Some(title) = parse_notion_title(url) {return Some(title);@@ -147,7 +117,6 @@ pub fn parse_custom_title(url: &str) -> Option<String> {return Some("Notion".to_string());}- // Try Figma parserif host.contains("figma.com") {if let Some(title) = parse_figma_title(url) {return Some(title);@@ -155,7 +124,6 @@ pub fn parse_custom_title(url: &str) -> Option<String> {return Some("Figma".to_string());}- // Try Linear parserif host.contains("linear.app") {if let Some(title) = parse_linear_title(url) {return Some(title);@@ -166,34 +134,38 @@ pub fn parse_custom_title(url: &str) -> Option<String> {None}+fn capitalize_first(word: &str) -> String {+ let mut chars: Vec<char> = word.chars().collect();+ if !chars.is_empty() {+ chars[0] = chars[0].to_uppercase().next().unwrap_or(chars[0]);+ }+ chars.into_iter().collect()+}+#[cfg(test)]mod tests {use super::*;#[test]fn test_notion_title_parsing() {- // Test with workspacelet url1 = "https://www.notion.so/macrocom/Enterprise-Product-Bottlenecks-5acb869109a747c1a1a92bbf1891ff2d";assert_eq!(parse_notion_title(url1),Some("Enterprise Product Bottlenecks".to_string()));- // Test without workspacelet url2 = "https://www.notion.so/Macro-Work-Thoughts-e52b32630b2e45fab665b3e5c566cf3b";assert_eq!(parse_notion_title(url2),Some("Macro Work Thoughts".to_string()));- // Test with longer workspace namelet url3 = "https://www.notion.so/craft-ventures/Craft-Ventures-Operating-Playbooks-9db7bdccfc0f47be96076c122513691c";assert_eq!(parse_notion_title(url3),Some("Craft Ventures Operating Playbooks".to_string()));- // Test invalid URLassert_eq!(parse_notion_title("https://google.com"), None);}@@ -208,7 +180,6 @@ mod tests {let url2 = "https://www.figma.com/design/VWgAP7zMauuWKkeS3CmWk3/AI-side-panel?node-id=0-1&p=f&t=SqdP6D2w2rZ5iSjV-0";assert_eq!(parse_figma_title(url2), Some("AI Side Panel".to_string()));- // Test invalid URLassert_eq!(parse_figma_title("https://google.com"), None);}@@ -226,29 +197,23 @@ mod tests {Some("Add Macro Permissions To Jwt Token".to_string()));- // Test invalid URLassert_eq!(parse_linear_title("https://google.com"), None);}#[test]fn test_custom_title_fallback() {- // Test that it returns service name when parsing failsassert_eq!(parse_custom_title("https://www.notion.so"),Some("Notion".to_string()));-assert_eq!(parse_custom_title("https://www.figma.com"),Some("Figma".to_string()));-assert_eq!(parse_custom_title("https://linear.app"),Some("Linear".to_string()));-- // Test that it returns None for non-supported servicesassert_eq!(parse_custom_title("https://google.com"), None);}}diff --git a/rust/cloud-storage/unfurl/src/inbound.rs b/rust/cloud-storage/unfurl/src/inbound.rsnew file mode 100644index 0000000000..418a209c9b--- /dev/null+++ b/rust/cloud-storage/unfurl/src/inbound.rs@@ -0,0 +1,4 @@+//! Inbound adapters that drive the unfurl domain.++#[cfg(feature = "axum")]+pub mod axum_router;diff --git a/rust/cloud-storage/unfurl/src/inbound/axum_router.rs b/rust/cloud-storage/unfurl/src/inbound/axum_router.rsnew file mode 100644index 0000000000..4cf08f4434--- /dev/null+++ b/rust/cloud-storage/unfurl/src/inbound/axum_router.rs@@ -0,0 +1,99 @@+//! Axum HTTP adapter for the unfurl service.++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{Query, State},+ http::StatusCode,+ routing::get,+};+use serde::Deserialize;+use utoipa::{IntoParams, ToSchema};++use crate::domain::{models::GetUnfurlResponse, ports::UnfurlService};++/// Axum state for the unfurl router, holding a shared reference to a+/// [`UnfurlService`] implementation.+pub struct UnfurlRouterState<T> {+ inner: Arc<T>,+}++impl<T> Clone for UnfurlRouterState<T> {+ fn clone(&self) -> Self {+ Self {+ inner: Arc::clone(&self.inner),+ }+ }+}++impl<T> UnfurlRouterState<T>+where+ T: UnfurlService,+{+ /// Wrap the given service in router state.+ pub fn new(service: T) -> Self {+ Self {+ inner: Arc::new(service),+ }+ }+}++/// Build the unfurl router. The single `GET /` route is mounted at the+/// crate's `/unfurl` path by the consuming service.+pub fn unfurl_router<S, T>(state: UnfurlRouterState<T>) -> Router<S>+where+ S: Send + Sync + 'static,+ T: UnfurlService,+{+ Router::new()+ .route("/", get(get_unfurl_handler::<T>))+ .with_state(state)+}++/// Query parameters for `GET /unfurl`.+#[derive(Debug, Deserialize, IntoParams, ToSchema)]+#[into_params(parameter_in = Query)]+pub struct GetUnfurlQueryParams {+ /// The URL to unfurl.+ pub url: String,+}++/// Unfurl the URL passed via the `url` query parameter and return its+/// extracted metadata (title, description, image, favicon).+///+/// On success returns `200` with a [`GetUnfurlResponse`] body. On any+/// failure returns `500` with a JSON `null` body — the response type is an+/// `Option<GetUnfurlResponse>` so this contract is reflected in the+/// signature and OpenAPI spec.+#[utoipa::path(+ get,+ tag = "unfurl",+ operation_id = "get_unfurl",+ path = "/unfurl",+ responses(+ (status = 200, body = GetUnfurlResponse, description = "Unfurled metadata for the URL."),+ (+ status = 500,+ body = Option<GetUnfurlResponse>,+ description = "Unfurl failed; response body is JSON null."+ ),+ ),+ params(GetUnfurlQueryParams)+)]+#[tracing::instrument(skip(state))]+pub async fn get_unfurl_handler<T>(+ State(state): State<UnfurlRouterState<T>>,+ Query(params): Query<GetUnfurlQueryParams>,+) -> (StatusCode, Json<Option<GetUnfurlResponse>>)+where+ T: UnfurlService,+{+ match state.inner.unfurl(¶ms.url).await {+ Ok(response) => (StatusCode::OK, Json(Some(response))),+ Err(e) => {+ tracing::warn!(error = %e, url = %params.url, "unfurl failed");+ (StatusCode::INTERNAL_SERVER_ERROR, Json(None))+ }+ }+}diff --git a/rust/cloud-storage/unfurl/src/lib.rs b/rust/cloud-storage/unfurl/src/lib.rsnew file mode 100644index 0000000000..9ae5f4bafc--- /dev/null+++ b/rust/cloud-storage/unfurl/src/lib.rs@@ -0,0 +1,13 @@+#![deny(missing_docs)]+//! Hexagonal crate for the URL unfurl feature.+//!+//! - `domain` — pure models, ports, and service logic (no I/O deps).+//! - `inbound` — HTTP / tool adapters that drive the domain.+//! - `outbound` — concrete adapters the domain drives (e.g. the reqwest-backed+//! meta-tag fetcher).++pub mod domain;+#[cfg(feature = "inbound")]+pub mod inbound;+#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/rust/cloud-storage/unfurl/src/outbound.rs b/rust/cloud-storage/unfurl/src/outbound.rsnew file mode 100644index 0000000000..77a338f016--- /dev/null+++ b/rust/cloud-storage/unfurl/src/outbound.rs@@ -0,0 +1,7 @@+//! Outbound adapters that the domain drives.++mod http_safety;+mod reqwest_fetcher;+mod resolver;++pub use reqwest_fetcher::ReqwestUnfurlFetcher;diff --git a/rust/cloud-storage/unfurl/src/outbound/http_safety.rs b/rust/cloud-storage/unfurl/src/outbound/http_safety.rsnew file mode 100644index 0000000000..2146c10a12--- /dev/null+++ b/rust/cloud-storage/unfurl/src/outbound/http_safety.rs@@ -0,0 +1,284 @@+//! HTTP fetch safety helpers: URL validation, private-IP blocking,+//! upstream-request execution, and content-type / content-length checks.+//!+//! These keep the unfurl service from being abused as a server-side+//! request forgery vector against the internal network.++use std::error::Error;+use std::net::IpAddr;++use reqwest::StatusCode;+use thiserror::Error;+use url::Url;++/// Errors that can occur while fetching a URL for unfurling.+#[derive(Debug, Error)]+pub(super) enum FetchError {+ /// The requested URL could not be parsed.+ #[error("invalid URL: {0}")]+ InvalidUrl(String),+ /// The URL used a scheme other than http/https.+ #[error("only http/https URLs are allowed")]+ InvalidScheme,+ /// The URL had no host.+ #[error("missing host")]+ MissingHost,+ /// DNS lookup for the URL's host failed.+ #[error("DNS lookup failed: {0}")]+ DnsLookupFailed(std::io::Error),+ /// The host resolved to a private / internal IP address.+ #[error("requests to private/internal IPs are not allowed")]+ PrivateIp,+ /// Upstream timed out while we were waiting for a response.+ #[error("timeout fetching upstream: {0}")]+ UpstreamTimeout(String),+ /// Upstream connection failed.+ #[error("connection error fetching upstream: {0}")]+ UpstreamConnect(String),+ /// Upstream sent us into too many redirects.+ #[error("too many redirects fetching upstream: {0}")]+ UpstreamRedirect(String),+ /// Generic network error from the upstream request.+ #[error("network error fetching upstream: {0}")]+ UpstreamNetwork(String),+ /// Upstream returned a non-2xx status code.+ #[error("upstream returned status {0}")]+ UpstreamStatus(StatusCode),+ /// Upstream returned an unsupported content-type for unfurling.+ #[error("unexpected content-type: {0}")]+ UnexpectedContentType(String),+ /// Upstream response was larger than the configured size cap.+ #[error("response exceeds max size of {max} bytes (Content-Length: {content_length})")]+ ResponseTooLarge {+ /// The reported `Content-Length` header on the response.+ content_length: u64,+ /// The configured maximum allowed size.+ max: u64,+ },+ /// Error while reading the upstream response body stream.+ #[error("error reading upstream response: {0}")]+ ResponseRead(String),+}++pub(super) 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(super) 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(super) 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()+ // 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+/// `reqwest_fetcher::extract_meta_tags` needs to see 3xx responses so it can+/// run [`assert_not_internal`] against each hop before following.+pub(super) async fn send_request(+ http_client: &reqwest::Client,+ url: &Url,+) -> Result<reqwest::Response, FetchError> {+ 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)+ }+ })+}++/// 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.+pub(super) fn redirect_target(+ current: &Url,+ response: &reqwest::Response,+) -> Result<Url, FetchError> {+ let location = response+ .headers()+ .get(reqwest::header::LOCATION)+ .ok_or_else(|| {+ FetchError::UpstreamRedirect("redirect response missing Location header".into())+ })?+ .to_str()+ .map_err(|e| FetchError::UpstreamRedirect(format!("invalid Location header: {e}")))?;++ let mut next = current.join(location).map_err(|e| {+ FetchError::UpstreamRedirect(format!("could not parse redirect target {location}: {e}"))+ })?;++ if next.scheme() != "http" && next.scheme() != "https" {+ return Err(FetchError::InvalidScheme);+ }+ next.set_fragment(None);++ Ok(next)+}++pub(super) 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(super) 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(super) 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 tests {+ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};++ use super::*;++ #[test]+ fn ipv6_loopback_is_blocked() {+ assert!(is_private_ip(&IpAddr::V6(Ipv6Addr::LOCALHOST)));+ }++ #[test]+ fn ipv6_unspecified_is_blocked() {+ assert!(is_private_ip(&IpAddr::V6(Ipv6Addr::UNSPECIFIED)));+ }++ #[test]+ fn ipv6_unique_local_is_blocked() {+ // fc00::/7 — IPv6 equivalent of RFC1918.+ assert!(is_private_ip(&IpAddr::V6(+ "fc00::1".parse::<Ipv6Addr>().unwrap()+ )));+ assert!(is_private_ip(&IpAddr::V6(+ "fd12:3456:789a::1".parse::<Ipv6Addr>().unwrap()+ )));+ }++ #[test]+ fn ipv6_link_local_is_blocked() {+ // fe80::/10 — only reachable on the local link.+ assert!(is_private_ip(&IpAddr::V6(+ "fe80::1".parse::<Ipv6Addr>().unwrap()+ )));+ assert!(is_private_ip(&IpAddr::V6(+ "febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff"+ .parse::<Ipv6Addr>()+ .unwrap()+ )));+ }++ #[test]+ fn ipv6_mapped_v4_loopback_is_blocked() {+ // ::ffff:127.0.0.1 should be treated as 127.0.0.1.+ assert!(is_private_ip(&IpAddr::V6(+ "::ffff:127.0.0.1".parse::<Ipv6Addr>().unwrap()+ )));+ // ::ffff:10.0.0.1 should be treated as RFC1918 10.0.0.0/8.+ assert!(is_private_ip(&IpAddr::V6(+ "::ffff:10.0.0.1".parse::<Ipv6Addr>().unwrap()+ )));+ }++ #[test]+ fn ipv6_public_is_allowed() {+ // 2001:4860:4860::8888 — Google public DNS.+ assert!(!is_private_ip(&IpAddr::V6(+ "2001:4860:4860::8888".parse::<Ipv6Addr>().unwrap()+ )));+ }++ #[test]+ fn ipv4_public_is_allowed() {+ assert!(!is_private_ip(&IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))));+ }++ #[test]+ fn ipv4_private_ranges_blocked() {+ assert!(is_private_ip(&IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))));+ assert!(is_private_ip(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));+ assert!(is_private_ip(&IpAddr::V4(Ipv4Addr::new(172, 16, 0, 1))));+ assert!(is_private_ip(&IpAddr::V4(Ipv4Addr::LOCALHOST)));+ assert!(is_private_ip(&IpAddr::V4(Ipv4Addr::UNSPECIFIED)));+ assert!(is_private_ip(&IpAddr::V4(Ipv4Addr::BROADCAST)));+ }+}diff --git a/rust/cloud-storage/unfurl/src/outbound/reqwest_fetcher.rs b/rust/cloud-storage/unfurl/src/outbound/reqwest_fetcher.rsnew file mode 100644index 0000000000..8e1398d38c--- /dev/null+++ b/rust/cloud-storage/unfurl/src/outbound/reqwest_fetcher.rs@@ -0,0 +1,276 @@+//! Reqwest + scraper-backed adapter implementing [`UnfurlFetcher`].++use std::collections::HashMap;+use std::sync::Arc;++use futures::StreamExt;+use scraper::{Html, Selector};+use thiserror::Error;+use url::Url;++use super::http_safety::{+ FetchError, assert_not_internal, build_error_chain, check_content_length, content_type_of,+ redirect_target, send_request, validate_url,+};+use super::resolver::PrivateIpFilteringResolver;+use crate::domain::ports::UnfurlFetcher;++/// 1 MB cap on HTML response size for meta-tag extraction.+const MAX_HTML_SIZE: u64 = 1024 * 1024;++/// Maximum number of redirects to follow per unfurl fetch. Matches the+/// previous reqwest-managed `Policy::limited(5)` behaviour.+const MAX_REDIRECTS: u8 = 5;++/// Default request timeout for an unfurl fetch.+const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8);++/// Default connect timeout for an unfurl fetch.+const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);++/// Concrete [`UnfurlFetcher`] backed by a `reqwest::Client` and the+/// `scraper` HTML parser.+///+/// SSRF mitigations baked into the client:+///+/// 1. **Redirects disabled** at the reqwest level so the manual loop in+/// [`extract_meta_tags`] 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.+pub struct ReqwestUnfurlFetcher {+ client: reqwest::Client,+}++impl ReqwestUnfurlFetcher {+ /// Build a fetcher with a dedicated HTTP client.+ ///+ /// Owning the client construction keeps the SSRF mitigation+ /// (no reqwest-level redirect-follow + per-hop internal-IP preflight ++ /// rebinding-safe DNS resolver) inseparable from the fetcher's type —+ /// callers can't accidentally hand in a redirect-following or+ /// unfiltered client.+ pub fn new() -> anyhow::Result<Self> {+ let client = reqwest::Client::builder()+ .redirect(reqwest::redirect::Policy::none())+ .dns_resolver(Arc::new(PrivateIpFilteringResolver))+ .timeout(REQUEST_TIMEOUT)+ .connect_timeout(CONNECT_TIMEOUT)+ .build()?;+ Ok(Self { client })+ }+}++impl UnfurlFetcher for ReqwestUnfurlFetcher {+ type Err = anyhow::Error;++ async fn fetch_meta_tags(&self, url: &str) -> Result<HashMap<String, String>, Self::Err> {+ extract_meta_tags(&self.client, url)+ .await+ .map_err(anyhow::Error::from)+ }+}++#[derive(Debug, Error)]+enum UnfurlFetchError {+ #[error(transparent)]+ Fetch(#[from] FetchError),+ #[error("failed to parse document: {0}")]+ Parse(anyhow::Error),+}++#[tracing::instrument(err(Debug), skip(client))]+async fn extract_meta_tags(+ client: &reqwest::Client,+ raw_url: &str,+) -> Result<HashMap<String, String>, UnfurlFetchError> {+ let mut url = validate_url(raw_url)?;+ let mut redirects_remaining = MAX_REDIRECTS;++ let response = loop {+ assert_not_internal(&url).await?;+ let response = send_request(client, &url).await?;+ let status = response.status();++ if status.is_redirection() {+ if redirects_remaining == 0 {+ return Err(FetchError::UpstreamRedirect(format!(+ "exceeded maximum of {MAX_REDIRECTS} redirects"+ ))+ .into());+ }+ let next = redirect_target(&url, &response)?;+ tracing::debug!(from = %url, to = %next, "following redirect");+ redirects_remaining -= 1;+ url = next;+ continue;+ }++ if !status.is_success() {+ return Err(FetchError::UpstreamStatus(status).into());+ }++ break response;+ };++ let content_type = content_type_of(&response);+ if !is_html_content_type(&content_type) {+ return Err(FetchError::UnexpectedContentType(content_type).into());+ }++ check_content_length(&response, MAX_HTML_SIZE, raw_url)?;++ let html_content = read_body_capped(response, MAX_HTML_SIZE).await?;++ parse_document(&html_content, &url).map_err(UnfurlFetchError::Parse)+}++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 = 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}"+ )))+ })+}++#[tracing::instrument(skip(html_content))]+fn parse_document(html_content: &str, url: &Url) -> Result<HashMap<String, String>, anyhow::Error> {+ fn no_tag(tag: &str) -> anyhow::Error {+ anyhow::anyhow!("Missing expected tag: [{tag}]")+ }++ let document = Html::parse_document(html_content);++ let meta_selector = Selector::parse("meta").map_err(|_| no_tag("meta"))?;++ let mut meta_tags = HashMap::new();++ for element in document.select(&meta_selector) {+ if let Some(name) = element.value().attr("name")+ && let Some(content) = element.value().attr("content")+ {+ meta_tags.insert(format!("name:{name}"), content.to_string());+ }++ if let Some(property) = element.value().attr("property")+ && let Some(content) = element.value().attr("content")+ {+ meta_tags.insert(format!("property:{property}"), content.to_string());+ }+ }++ let title_tag = Selector::parse("title").map_err(|_| no_tag("title"))?;+ for element in document.select(&title_tag) {+ meta_tags.insert("title".to_string(), element.inner_html());+ }++ if let Some(favicon) = find_favicon(&document, url) {+ meta_tags.insert("favicon".to_string(), favicon);+ }+ Ok(meta_tags)+}++fn find_favicon(document: &Html, base_url: &Url) -> Option<String> {+ let links_selector = Selector::parse("link").ok()?;++ for element in document.select(&links_selector) {+ if let Some(rel) = element.value().attr("rel")+ && rel+ .split_whitespace()+ .any(|r| r.to_lowercase().contains("icon"))+ && let Some(href) = element.value().attr("href")+ {+ if let Ok(abs_url) = base_url.join(href) {+ return Some(abs_url.to_string());+ } else {+ return Some(href.to_string());+ }+ }+ }++ None+}++#[cfg(test)]+mod tests {+ use std::str::FromStr;++ use super::*;++ #[test]+ fn test_parse_document_extracts_og_title() {+ let document_content = [+ "<html>",+ "<head>",+ "<meta property=\"og:title\" content=\"hello\" />",+ "</head>",+ "</html>",+ ]+ .join("\n");+ let url = Url::from_str("http://example.com").unwrap();+ let tags = parse_document(&document_content, &url).unwrap();++ assert_eq!(+ tags.get("property:og:title").map(String::as_str),+ Some("hello")+ );+ }++ #[test]+ fn test_parse_document_extracts_title_tag() {+ let document_content = [+ "<html>",+ "<head>",+ "<title>Website Title</title>",+ "</head>",+ "</html>",+ ]+ .join("\n");+ let url = Url::from_str("http://example.com").unwrap();+ let tags = parse_document(&document_content, &url).unwrap();+ assert_eq!(tags.get("title").map(String::as_str), Some("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"));+ }+}diff --git a/rust/cloud-storage/unfurl/src/outbound/resolver.rs b/rust/cloud-storage/unfurl/src/outbound/resolver.rsnew file mode 100644index 0000000000..04ec9f9372--- /dev/null+++ b/rust/cloud-storage/unfurl/src/outbound/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::http_safety::assert_not_internal++use std::net::SocketAddr;++use reqwest::dns::{Addrs, Name, Resolve, Resolving};++use super::http_safety::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/unfurl_service/Cargo.toml b/rust/cloud-storage/unfurl_service/Cargo.tomlindex 032aa35902..dd24b3328e 100644--- a/rust/cloud-storage/unfurl_service/Cargo.toml+++ b/rust/cloud-storage/unfurl_service/Cargo.toml@@ -33,6 +33,7 @@ tokio = { workspace = true }tower = { workspace = true }tower-http = { workspace = true }tracing = { workspace = true }+unfurl = { path = "../unfurl", features = ["axum", "outbound"] }url = { workspace = true }utoipa = { workspace = true, features = ["axum_extras", "chrono", "uuid"] }utoipa-swagger-ui = { workspace = true, features = ["axum"] }diff --git a/rust/cloud-storage/unfurl_service/examples/test_parers.rs b/rust/cloud-storage/unfurl_service/examples/test_parers.rsindex d459a8be36..94f14ce3e3 100644--- a/rust/cloud-storage/unfurl_service/examples/test_parers.rs+++ b/rust/cloud-storage/unfurl_service/examples/test_parers.rs@@ -1,4 +1,4 @@-use unfurl_service::url_parsers::{+use unfurl::domain::url_parsers::{parse_custom_title, parse_figma_title, parse_linear_title, parse_notion_title,};diff --git a/rust/cloud-storage/unfurl_service/src/api/mod.rs b/rust/cloud-storage/unfurl_service/src/api/mod.rsindex b890cf748e..1d952734ce 100644--- a/rust/cloud-storage/unfurl_service/src/api/mod.rs+++ b/rust/cloud-storage/unfurl_service/src/api/mod.rs@@ -1,4 +1,8 @@use crate::api::context::ApiContext;+use ::unfurl::{+ domain::{ports::UnfurlFetcher, service::UnfurlServiceImpl},+ inbound::axum_router::UnfurlRouterState,+};use anyhow::Context;use axum::Router;use utoipa::OpenApi;@@ -10,11 +14,19 @@ mod proxy;pub(crate) mod swagger;mod unfurl;-pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<()> {+pub async fn setup_and_serve<F>(+ state: ApiContext,+ unfurl_state: UnfurlRouterState<UnfurlServiceImpl<F>>,+ port: usize,+) -> anyhow::Result<()>+where+ F: UnfurlFetcher,+ anyhow::Error: From<F::Err>,+{let cors = macro_cors::cors_layer();let env = state.environment;- let app = api_router()+ let app = api_router(unfurl_state).with_state(state).merge(health::router()).layer(cors)@@ -35,9 +47,13 @@ pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<(.context("error starting service")}-fn api_router() -> Router<ApiContext> {+fn api_router<F>(unfurl_state: UnfurlRouterState<UnfurlServiceImpl<F>>) -> Router<ApiContext>+where+ F: UnfurlFetcher,+ anyhow::Error: From<F::Err>,+{Router::new()- .nest("/unfurl", unfurl::router())+ .nest("/unfurl", unfurl::router(unfurl_state)).nest("/proxy", proxy::router())}@@ -47,6 +63,7 @@ mod tests {use super::*;use crate::unfurl::{GetUnfurlResponse, GetUnfurlResponseList};+ use ::unfurl::outbound::ReqwestUnfurlFetcher;use axum::{body::Body,http::{Request, StatusCode},@@ -62,9 +79,15 @@ mod tests {}}+ fn test_unfurl_state() -> UnfurlRouterState<UnfurlServiceImpl<ReqwestUnfurlFetcher>> {+ UnfurlRouterState::new(UnfurlServiceImpl::new(+ ReqwestUnfurlFetcher::new().expect("build unfurl fetcher"),+ ))+ }+#[tokio::test]async fn test_not_found() {- let api = api_router().with_state(test_state());+ let api = api_router(test_unfurl_state()).with_state(test_state());let response = api.oneshot(@@ -83,7 +106,7 @@ mod tests {#[tokio::test]async fn test_unfurl_url_nonexistent() {- let api = api_router().with_state(test_state());+ let api = api_router(test_unfurl_state()).with_state(test_state());let response = api.oneshot(@@ -110,7 +133,7 @@ mod tests {#[ignore]#[tokio::test]async fn test_unfurl_hello_url() {- let api = api_router().with_state(test_state());+ let api = api_router(test_unfurl_state()).with_state(test_state());let response = api.oneshot(@@ -142,7 +165,7 @@ mod tests {#[ignore]#[tokio::test]async fn test_bulk() {- let api = api_router().with_state(test_state());+ let api = api_router(test_unfurl_state()).with_state(test_state());let body = GetUnfurlBulkBody {url_list: ["https://hello.com", "https://example.com"]@@ -180,7 +203,7 @@ mod tests {#[ignore]#[tokio::test]async fn test_bulk_404_links() {- let api = api_router().with_state(test_state());+ let api = api_router(test_unfurl_state()).with_state(test_state());let body = GetUnfurlBulkBody {url_list: [diff --git a/rust/cloud-storage/unfurl_service/src/api/swagger.rs b/rust/cloud-storage/unfurl_service/src/api/swagger.rsindex d2292e0909..3731170d64 100644--- a/rust/cloud-storage/unfurl_service/src/api/swagger.rs+++ b/rust/cloud-storage/unfurl_service/src/api/swagger.rs@@ -1,10 +1,9 @@+use ::unfurl::domain::models::GetUnfurlResponse;+use ::unfurl::inbound::axum_router::{self, GetUnfurlQueryParams};use utoipa::OpenApi;use super::proxy::{self, ProxyParams};-use super::unfurl::get_unfurl::{- self, GetUnfurlBulkBody, GetUnfurlBulkResponse, GetUnfurlQueryParams,-};-use crate::unfurl::GetUnfurlResponse;+use super::unfurl::get_unfurl::{self, GetUnfurlBulkBody, GetUnfurlBulkResponse};#[derive(OpenApi)]#[openapi(@@ -12,7 +11,7 @@ use crate::unfurl::GetUnfurlResponse;terms_of_service = "https://macro.com/terms",),paths(- get_unfurl::get_unfurl_handler,+ axum_router::get_unfurl_handler,get_unfurl::get_bulk_unfurl_handler,proxy::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.rsindex ff7ff44f53..e595ba5188 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,12 +1,9 @@use axum::extract::Json;-use axum::extract::Query;use axum::extract::State;use axum::http::StatusCode;-use crate::unfurl::{- GetUnfurlResponse, GetUnfurlResponseList, append_optimistic_favico, extract_meta_tags,- fetch_links_async,-};+use crate::unfurl::GetUnfurlResponseList;+use crate::unfurl::fetch_links_async;use serde::{Deserialize, Serialize};use utoipa::ToSchema;@@ -20,40 +17,6 @@ pub struct GetUnfurlBulkBody {pub url_list: Vec<String>,}-#[derive(Deserialize, ToSchema, Debug)]-pub struct GetUnfurlQueryParams {- url: String,-}--#[utoipa::path(get,- tag = "unfurl",- operation_id = "get_unfurl",- path = "/unfurl", responses(- (status = 200, body=GetUnfurlResponse),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String)),- params(- ("url"=String, Query, description="URL to unfold"),- )-)]-#[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(&http_client, ¶ms.url).await {- Ok(t) => append_optimistic_favico(t, params.url.as_str()),- Err(e) => {- tracing::warn!(error = %e, url = %params.url, "unfurl failed");- return (StatusCode::INTERNAL_SERVER_ERROR, Json(None));- }- };-- let response = GetUnfurlResponse::new(¶ms.url, &tags);- (StatusCode::OK, Json(Some(response)))-}-#[utoipa::path(post,tag = "unfurl",operation_id = "get_unfurl_bulk",@@ -65,8 +28,6 @@ pub async fn get_unfurl_handler(request_body(content = GetUnfurlBulkBody,description = "JSON list of URLs",content_type="application/json",- // TODO: update- //example=json!(["https://macro.com", "https://github.com"])))]#[tracing::instrument(skip(http_client, body))]pub async fn get_bulk_unfurl_handler(diff --git a/rust/cloud-storage/unfurl_service/src/api/unfurl/mod.rs b/rust/cloud-storage/unfurl_service/src/api/unfurl/mod.rsindex 826893dc97..9e3f8e894e 100644--- a/rust/cloud-storage/unfurl_service/src/api/unfurl/mod.rs+++ b/rust/cloud-storage/unfurl_service/src/api/unfurl/mod.rs@@ -1,9 +1,21 @@-use axum::{Router, routing::get, routing::post};+use ::unfurl::{+ domain::{ports::UnfurlFetcher, service::UnfurlServiceImpl},+ inbound::axum_router::{UnfurlRouterState, unfurl_router},+};+use axum::{Router, routing::post};++use crate::api::context::ApiContext;pub mod get_unfurl;-pub fn router() -> Router<crate::api::context::ApiContext> {+/// Build the `/unfurl` subtree: hexified GET handler from the `unfurl` crate+/// plus the legacy `POST /bulk` handler living in this service.+pub fn router<F>(unfurl_state: UnfurlRouterState<UnfurlServiceImpl<F>>) -> Router<ApiContext>+where+ F: UnfurlFetcher,+ anyhow::Error: From<F::Err>,+{Router::new()- .route("/", get(get_unfurl::get_unfurl_handler)).route("/bulk", post(get_unfurl::get_bulk_unfurl_handler))+ .merge(unfurl_router(unfurl_state))}diff --git a/rust/cloud-storage/unfurl_service/src/main.rs b/rust/cloud-storage/unfurl_service/src/main.rsindex b7b40d067c..ee620f3cd0 100644--- a/rust/cloud-storage/unfurl_service/src/main.rs+++ b/rust/cloud-storage/unfurl_service/src/main.rs@@ -3,6 +3,10 @@ mod api;mod config;mod http_safety;mod unfurl;+use ::unfurl::{+ domain::service::UnfurlServiceImpl, inbound::axum_router::UnfurlRouterState,+ outbound::ReqwestUnfurlFetcher,+};use anyhow::Context;use config::Config;use macro_entrypoint::MacroEntrypoint;@@ -28,6 +32,13 @@ async fn main() -> anyhow::Result<()> {http_client,};- api::setup_and_serve(state, config.port).await?;+ // ReqwestUnfurlFetcher owns its own client with redirects disabled to+ // close the SSRF redirect-bypass: a 302 → internal IP must not be+ // followed past the assert_not_internal preflight on the original URL.+ let unfurl_fetcher =+ ReqwestUnfurlFetcher::new().context("failed to build unfurl http client")?;+ let unfurl_state = UnfurlRouterState::new(UnfurlServiceImpl::new(unfurl_fetcher));++ api::setup_and_serve(state, unfurl_state, config.port).await?;Ok(())}diff --git a/rust/cloud-storage/unfurl_service/src/unfurl/mod.rs b/rust/cloud-storage/unfurl_service/src/unfurl/mod.rsindex 084be70a9c..b954a8323b 100644--- a/rust/cloud-storage/unfurl_service/src/unfurl/mod.rs+++ b/rust/cloud-storage/unfurl_service/src/unfurl/mod.rs@@ -1,18 +1,24 @@-pub mod url_parsers;--use anyhow::{Context, Error};+use anyhow::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;++pub use ::unfurl::domain::favicon::append_optimistic_favico;+pub use ::unfurl::domain::models::{GetUnfurlResponse, GetUnfurlResponseList};++// Re-exported through `crate::unfurl_service::{favico_url, url_parsers}` for+// external consumers (see `lib.rs`). Not consumed inside this binary itself,+// so the bin target sees them as unused without the allow.+#[allow(unused_imports)]+pub use ::unfurl::domain::favicon::favico_url;+#[allow(unused_imports)]+pub use ::unfurl::domain::url_parsers;/// 1 MB max HTML response size for meta-tag extraction.pub const MAX_HTML_SIZE: u64 = 1024 * 1024;@@ -20,20 +26,6 @@ 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)]-pub struct GetUnfurlResponse {- pub url: String,- pub title: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub description: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub image_url: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub favicon_url: Option<String>,-}-#[tracing::instrument]fn parse_document(html_content: &str, url: &Url) -> Result<HashMap<String, String>, Error> {fn no_tag(tag: &str) -> Error {@@ -184,33 +176,6 @@ async fn read_body_capped(})}-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"))?;- let scheme = url.scheme();- let port = url- .port()- .map(|port| format!(":{}", port))- .unwrap_or_default();- Ok(format!("{}://{}{}/favicon.ico", scheme, port, host))-}--pub fn append_optimistic_favico(- mut meta_tags: HashMap<String, String>,- url: &str,-) -> HashMap<String, String> {- let optimistic_url = favico_url(url)- .inspect_err(|err| tracing::debug!(error=?err, "could not form favicon url"));-- if !meta_tags.contains_key("favicon")- && let Ok(url) = optimistic_url- {- meta_tags.insert("favicon".to_string(), url);- }-- meta_tags-}-pub async fn extract_meta_tags(client: &reqwest::Client,url: &str,@@ -251,64 +216,6 @@ pub async fn extract_meta_tags_mock(Err(UnfurlFetchError::Parse(anyhow::anyhow!("not found")))}-impl GetUnfurlResponse {- pub fn get_title(url: &str, metatags: &HashMap<String, String>) -> String {- // First try custom URL parsing for known services- if let Some(custom_title) = parse_custom_title(url) {- return custom_title;- }-- // Fall back to metadata extraction- let mut title = None;-- let properties = ["property:og:title", "property:og:site_name", "title"];-- for prop in properties {- title = metatags.get(prop);- if title.is_some() {- break;- }- }-- let title = match title {- Some(s) => s,- None => url,- };-- title.to_string()- }-- pub fn new(url: &str, metatags: &HashMap<String, String>) -> Self {- let title = Self::get_title(url, metatags);-- let description = metatags- .get("property:og:description")- .map(|s| s.to_string());-- // TODO: prioritize ol:image:secure_url over og:image if both exist- let image_url = metatags.get("property:og:image").map(|s| s.to_string());-- let mut favicon_url = metatags.get("favicon").map(|s| s.to_string());-- // Resolve favicon URL to absolute path- if let Ok(base_url) = Url::parse(url)- && let Some(furl) = favicon_url- {- // TODO: better error handling?- let base_url = base_url.join(&furl).unwrap();- favicon_url = Some(base_url.to_string());- }-- GetUnfurlResponse {- url: url.to_string(),- title: title.to_string(),- description,- image_url,- favicon_url,- }- }-}-pub async fn fetch_links_async(client: &reqwest::Client,links: &[String],