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.

feat(email): rehost external signature images to static-file-service (#4357)

Evan Hutnikd8bf468073b1
diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.ts
index 268626628e..1afb2a8058 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -45,6 +45,7 @@ import type {
SendMessageResponse,
SharedInboxConflictResponse,
UnblockSenderRequest,
+ UnresolvedSignatureImagesError,
UpdateLabelBatchRequest,
UpdateLabelBatchResponse,
UpdateThreadLabelRequest,
@@ -2279,6 +2280,11 @@ export type patchSettingsResponse401 = {
status: 401;
};
+export type patchSettingsResponse422 = {
+ data: UnresolvedSignatureImagesError;
+ status: 422;
+};
+
export type patchSettingsResponse500 = {
data: ErrorResponse;
status: 500;
@@ -2290,6 +2296,7 @@ export type patchSettingsResponseSuccess = patchSettingsResponse200 & {
export type patchSettingsResponseError = (
| patchSettingsResponse400
| patchSettingsResponse401
+ | patchSettingsResponse422
| patchSettingsResponse500
) & {
headers: Headers;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
index da7bf90bab..0e07502fae 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
@@ -263,6 +263,7 @@ export * from './threadPreviewCursorViewedAt';
export * from './threadProviderId';
export * from './threadSummary';
export * from './unblockSenderRequest';
+export * from './unresolvedSignatureImagesError';
export * from './updateLabelBatchRequest';
export * from './updateLabelBatchResponse';
export * from './updateThreadLabelRequest';
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/unresolvedSignatureImagesError.ts b/js/app/packages/service-clients/service-email/generated/schemas/unresolvedSignatureImagesError.ts
new file mode 100644
index 0000000000..0c338ac654
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/unresolvedSignatureImagesError.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Body returned with a 422 when signature images can't be loaded.
+ */
+export interface UnresolvedSignatureImagesError {
+ /** @minimum 0 */
+ unresolved_image_count: number;
+}
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index 0070a203f6..0c97d28718 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -2124,6 +2124,16 @@
}
}
},
+ "422": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UnresolvedSignatureImagesError"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -5044,6 +5054,18 @@
}
}
},
+ "UnresolvedSignatureImagesError": {
+ "type": "object",
+ "description": "Body returned with a 422 when signature images can't be loaded.",
+ "required": ["unresolved_image_count"],
+ "properties": {
+ "unresolved_image_count": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ }
+ }
+ },
"UpdateLabelBatchRequest": {
"type": "object",
"required": ["message_ids", "label_id", "value"],
diff --git a/rust/cloud-storage/email_service/src/api/email/settings/patch.rs b/rust/cloud-storage/email_service/src/api/email/settings/patch.rs
index 60f31c83ab..473c3fe07e 100644
--- a/rust/cloud-storage/email_service/src/api/email/settings/patch.rs
+++ b/rust/cloud-storage/email_service/src/api/email/settings/patch.rs
@@ -3,6 +3,7 @@ use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
+use email_service::util::process_pre_insert::sfs_map;
use email_service::util::sanitizer::sanitize_html_fragment;
use model::response::ErrorResponse;
use models_email::service::link::Link;
@@ -15,15 +16,34 @@ use utoipa::ToSchema;
pub enum PatchSettingsError {
#[error("Failed to update settings")]
DatabaseError(#[from] anyhow::Error),
+ /// At least one signature image couldn't be fetched (e.g. pasted from
+ /// another webmail account, so reachable only by that session) and would
+ /// render broken for recipients. The whole patch is rejected atomically —
+ /// nothing is persisted — so the client can have the user re-add them.
+ #[error("{0} signature image(s) could not be loaded")]
+ UnresolvedSignatureImages(u32),
+}
+
+/// Body returned with a 422 when signature images can't be loaded.
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct UnresolvedSignatureImagesError {
+ pub unresolved_image_count: u32,
}
impl IntoResponse for PatchSettingsError {
fn into_response(self) -> Response {
- let status_code = match &self {
- PatchSettingsError::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
- };
-
- (status_code, self.to_string()).into_response()
+ match self {
+ PatchSettingsError::DatabaseError(_) => {
+ (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response()
+ }
+ PatchSettingsError::UnresolvedSignatureImages(count) => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(UnresolvedSignatureImagesError {
+ unresolved_image_count: count,
+ }),
+ )
+ .into_response(),
+ }
}
}
@@ -48,6 +68,7 @@ pub struct PatchSettingsResponse {
(status = 200, body = PatchSettingsResponse),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
+ (status = 422, body = UnresolvedSignatureImagesError),
(status = 500, body = ErrorResponse),
)
)]
@@ -62,6 +83,28 @@ pub async fn patch_settings_handler(
let mut settings = api_settings.settings;
settings.signature = settings.signature.map(|html| sanitize_html_fragment(&html));
+ // Move externally-hosted signature images onto SFS so they render durably
+ // for recipients. If any image can't be fetched (e.g. Gmail/Outlook embedded
+ // URLs that need that account's session, or dead links), it would render
+ // broken for recipients — so reject the whole patch atomically (before any
+ // write) and report the count, so the client can have the user re-add them.
+ // A rehost *error* (vs. an unresolved image) never blocks the save.
+ if let Some(signature) = settings.signature.clone() {
+ match sfs_map::rehost_html_images(&ctx.db, &ctx.sfs_client, &signature).await {
+ Ok((rehosted, unresolved)) => {
+ if unresolved > 0 {
+ return Err(PatchSettingsError::UnresolvedSignatureImages(
+ unresolved as u32,
+ ));
+ }
+ settings.signature = Some(rehosted);
+ }
+ Err(e) => {
+ tracing::warn!(error = ?e, "signature image rehost failed; persisting signature unchanged");
+ }
+ }
+ }
+
let patch = service::settings::SettingsPatch::new(settings, link.id);
let updated_settings = email_db_client::settings::patch_settings(&ctx.db, patch).await?;
diff --git a/rust/cloud-storage/email_service/src/util/process_pre_insert/sfs_map.rs b/rust/cloud-storage/email_service/src/util/process_pre_insert/sfs_map.rs
index 51d6748a5f..b25ec89e7f 100644
--- a/rust/cloud-storage/email_service/src/util/process_pre_insert/sfs_map.rs
+++ b/rust/cloud-storage/email_service/src/util/process_pre_insert/sfs_map.rs
@@ -97,6 +97,59 @@ pub async fn store_message_images(
Ok(())
}
+/// Rehosts every publicly-fetchable `<img>` in an HTML fragment onto SFS and
+/// rewrites the markup to the stable URLs. Returns the rewritten HTML and the
+/// number of remote images that could NOT be fetched (e.g. auth-gated
+/// webmail-embedded URLs like Gmail's `disp=emb`) so the caller can warn the
+/// user to re-add them.
+///
+/// Provider-agnostic on purpose: it only does unauthenticated HTTP GETs, so
+/// anything requiring a provider session simply lands in the unresolved count
+/// instead of needing per-provider (Gmail/Outlook/…) resolution. Already-SFS
+/// images are skipped so re-saving a signature doesn't re-upload them.
+#[tracing::instrument(skip(db, sfs_client, html), err)]
+pub async fn rehost_html_images(
+ db: &PgPool,
+ sfs_client: &StaticFileServiceClient,
+ html: &str,
+) -> anyhow::Result<(String, usize)> {
+ if cfg!(not(feature = "sfs_map")) {
+ return Ok((html.to_string(), 0));
+ }
+
+ let urls: HashSet<String> = extract_all_image_urls(html)?
+ .into_iter()
+ // Skip images we never rehost: ones already on SFS (so a re-save doesn't
+ // re-upload them) and Barracuda link-protected URLs (which cache_images
+ // also excludes). Counting either as unresolved would wrongly 422 the save.
+ .filter(|url| {
+ !url.contains("static-file-service")
+ && !url.starts_with("https://linkprotect.cudasvc.com")
+ })
+ .collect();
+
+ if urls.is_empty() {
+ return Ok((html.to_string(), 0));
+ }
+
+ let sfs_map = cache_images(db, sfs_client, urls.clone()).await?;
+
+ // Remote images we couldn't move to SFS stay as-is and are counted so the
+ // caller can tell the user which ones won't render for recipients.
+ let unresolved = urls
+ .iter()
+ .filter(|url| !sfs_map.contains_key(*url))
+ .count();
+
+ let new_html = if sfs_map.is_empty() {
+ html.to_string()
+ } else {
+ rewrite_html_image_links(html, &sfs_map)?
+ };
+
+ Ok((new_html, unresolved))
+}
+
// extracts the src/srcset attributes from all <img> tags in the passed HTML
#[tracing::instrument(skip(html_content), err)]
fn extract_all_image_urls(html_content: &str) -> anyhow::Result<HashSet<String>> {