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(email): forward attachments across inboxes (#8251)

Jacob Beckerman360d91a67d4d
diff --git a/.sqlx/query-020ad49dd342e529563c91a7d2403de9196482e24765f4b2c93d2da50273d69c.json b/.sqlx/query-700065c1f792018d70813197362247a36e6379b82d71444aab73e5cd702d4b94.json
similarity index 52%
rename from .sqlx/query-020ad49dd342e529563c91a7d2403de9196482e24765f4b2c93d2da50273d69c.json
rename to .sqlx/query-700065c1f792018d70813197362247a36e6379b82d71444aab73e5cd702d4b94.json
index 3b06227108..ddda8930ad 100644
--- a/.sqlx/query-020ad49dd342e529563c91a7d2403de9196482e24765f4b2c93d2da50273d69c.json
+++ b/.sqlx/query-700065c1f792018d70813197362247a36e6379b82d71444aab73e5cd702d4b94.json
@@ -1,40 +1,45 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n eaf.attachment_id,\n eaf.message_id AS draft_id,\n ea.provider_attachment_id,\n orig_msg.provider_id AS \"message_provider_id!\",\n ea.filename,\n ea.mime_type,\n ea.size_bytes\n FROM email_attachments_fwd eaf\n JOIN email_messages draft_msg ON eaf.message_id = draft_msg.id\n JOIN email_attachments ea ON eaf.attachment_id = ea.id\n JOIN email_messages orig_msg ON ea.message_id = orig_msg.id\n WHERE eaf.message_id = $1 AND draft_msg.link_id = $2\n ORDER BY ea.filename ASC\n ",
+ "query": "\n SELECT\n orig_msg.link_id AS source_link_id,\n eaf.attachment_id,\n eaf.message_id AS draft_id,\n ea.provider_attachment_id,\n orig_msg.provider_id AS \"message_provider_id!\",\n ea.filename,\n ea.mime_type,\n ea.size_bytes\n FROM email_attachments_fwd eaf\n JOIN email_messages draft_msg ON eaf.message_id = draft_msg.id\n JOIN email_attachments ea ON eaf.attachment_id = ea.id\n JOIN email_messages orig_msg ON ea.message_id = orig_msg.id\n WHERE eaf.message_id = $1 AND draft_msg.link_id = $2\n ORDER BY ea.filename ASC\n ",
"describe": {
"columns": [
{
"ordinal": 0,
- "name": "attachment_id",
+ "name": "source_link_id",
"type_info": "Uuid"
},
{
"ordinal": 1,
- "name": "draft_id",
+ "name": "attachment_id",
"type_info": "Uuid"
},
{
"ordinal": 2,
+ "name": "draft_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
"name": "provider_attachment_id",
"type_info": "Text"
},
{
- "ordinal": 3,
+ "ordinal": 4,
"name": "message_provider_id!",
"type_info": "Text"
},
{
- "ordinal": 4,
+ "ordinal": 5,
"name": "filename",
"type_info": "Varchar"
},
{
- "ordinal": 5,
+ "ordinal": 6,
"name": "mime_type",
"type_info": "Varchar"
},
{
- "ordinal": 6,
+ "ordinal": 7,
"name": "size_bytes",
"type_info": "Int8"
}
@@ -46,6 +51,7 @@
]
},
"nullable": [
+ false,
false,
false,
true,
@@ -55,5 +61,5 @@
true
]
},
- "hash": "020ad49dd342e529563c91a7d2403de9196482e24765f4b2c93d2da50273d69c"
+ "hash": "700065c1f792018d70813197362247a36e6379b82d71444aab73e5cd702d4b94"
}
diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.md
index c30a94d260..c78fafd470 100644
--- a/crates/email/AGENTS.md
+++ b/crates/email/AGENTS.md
@@ -49,6 +49,8 @@ tools — hexagonal, heavily feature-gated.
## Gotchas
+- Forwarded-attachment registration and delivery authorize the authenticated caller
+ in `domain/forwarded_attachments.rs`; recheck source access after scheduled delays.
- The feature matrix (`ports`/`inbound`/`outbound`/`http_client`/`s3`/
`gmail_token`/`ai_tools`/`attachment`/`calendar_invitations`/`axum`) gates
most modules; check `Cargo.toml`'s `[features]` block for which one a new
diff --git a/crates/email/src/domain.rs b/crates/email/src/domain.rs
index 03dae585c4..42376b4dfb 100644
--- a/crates/email/src/domain.rs
+++ b/crates/email/src/domain.rs
@@ -5,6 +5,8 @@ pub mod calendar_invitation_parser;
pub mod events;
#[cfg(feature = "ports")]
pub mod followup;
+#[cfg(feature = "ports")]
+pub mod forwarded_attachments;
#[cfg(feature = "calendar_invitations")]
pub mod invitation_extraction;
#[cfg(feature = "calendar_invitations")]
diff --git a/crates/email/src/domain/forwarded_attachments.rs b/crates/email/src/domain/forwarded_attachments.rs
new file mode 100644
index 0000000000..8f690d2f62
--- /dev/null
+++ b/crates/email/src/domain/forwarded_attachments.rs
@@ -0,0 +1,164 @@
+//! Authorize source inboxes when registering and delivering forwarded attachments.
+
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use crate::domain::models::{AttachmentForwarded, MessageAttachment};
+
+/// A provider attachment together with the inbox whose credentials can read it.
+#[derive(Debug, Clone)]
+pub struct ForwardedAttachmentSource {
+ /// The original message's inbox, which may differ from the sending inbox.
+ pub source_link_id: Uuid,
+ /// The registered original attachment and its provider identifiers.
+ pub attachment: AttachmentForwarded,
+}
+
+/// Persistence facts needed to authorize and register forwarded attachments.
+pub trait ForwardedAttachmentRepo: Send + Sync {
+ /// Repository failures are preserved in the domain error.
+ type Err: std::error::Error + Send + Sync + 'static;
+
+ /// Return the caller's own and delegated inboxes.
+ fn accessible_inboxes(
+ &self,
+ actor: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<Uuid>, Self::Err>> + Send;
+ /// Check that the destination is still a draft in the selected inbox.
+ fn draft_exists(
+ &self,
+ link_id: Uuid,
+ draft_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Resolve attachment metadata and its original inbox.
+ fn source_attachment(
+ &self,
+ attachment_id: Uuid,
+ ) -> impl Future<Output = Result<Option<(Uuid, MessageAttachment)>, Self::Err>> + Send;
+ /// Idempotently register the original attachment on the destination draft.
+ fn insert(
+ &self,
+ link_id: Uuid,
+ draft_id: Uuid,
+ attachment_id: Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Read registrations scoped to the destination inbox, including source inboxes.
+ fn registered_sources(
+ &self,
+ link_id: Uuid,
+ draft_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<ForwardedAttachmentSource>, Self::Err>> + Send;
+}
+
+/// Missing and inaccessible resources share the same public error.
+#[derive(Debug, thiserror::Error)]
+pub enum ForwardedAttachmentError {
+ /// The destination draft is missing or inaccessible.
+ #[error("Draft not found")]
+ DraftNotFound,
+ /// The source attachment is missing or inaccessible.
+ #[error("Attachment not found")]
+ AttachmentNotFound,
+ /// A persistence operation failed.
+ #[error("Internal error")]
+ Internal(rootcause::Report),
+}
+
+/// Owns source access policy; adapters provide only persisted facts.
+#[derive(Clone)]
+pub struct ForwardedAttachmentService<R> {
+ repo: R,
+}
+
+impl<R: ForwardedAttachmentRepo> ForwardedAttachmentService<R> {
+ /// Construct with the email repository adapter.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+
+ /// Register a source the authenticated caller can read on their selected draft.
+ #[tracing::instrument(skip(self, actor), fields(source_link_id = tracing::field::Empty, source_accessible = tracing::field::Empty), err)]
+ pub async fn add(
+ &self,
+ actor: &MacroUserIdStr<'_>,
+ link_id: Uuid,
+ draft_id: Uuid,
+ attachment_id: Uuid,
+ ) -> Result<MessageAttachment, ForwardedAttachmentError> {
+ let inboxes = self
+ .repo
+ .accessible_inboxes(actor)
+ .await
+ .map_err(internal)?;
+ if !inboxes.contains(&link_id)
+ || !self
+ .repo
+ .draft_exists(link_id, draft_id)
+ .await
+ .map_err(internal)?
+ {
+ return Err(ForwardedAttachmentError::DraftNotFound);
+ }
+ let (source_link_id, attachment) = self
+ .repo
+ .source_attachment(attachment_id)
+ .await
+ .map_err(internal)?
+ .ok_or(ForwardedAttachmentError::AttachmentNotFound)?;
+ let accessible = inboxes.contains(&source_link_id);
+ tracing::Span::current().record("source_link_id", tracing::field::display(source_link_id));
+ tracing::Span::current().record("source_accessible", accessible);
+ if !accessible {
+ return Err(ForwardedAttachmentError::AttachmentNotFound);
+ }
+ self.repo
+ .insert(link_id, draft_id, attachment_id)
+ .await
+ .map_err(internal)?;
+ Ok(attachment)
+ }
+
+ /// Recheck cross-inbox sources at delivery, including after a scheduled delay.
+ /// Legacy same-inbox sends predate actor attribution and remain deliverable.
+ #[tracing::instrument(skip(self, actor), fields(source_accessible = tracing::field::Empty), err)]
+ pub async fn for_delivery(
+ &self,
+ actor: Option<&MacroUserIdStr<'_>>,
+ link_id: Uuid,
+ draft_id: Uuid,
+ ) -> Result<Vec<ForwardedAttachmentSource>, ForwardedAttachmentError> {
+ let sources = self
+ .repo
+ .registered_sources(link_id, draft_id)
+ .await
+ .map_err(internal)?;
+ if sources
+ .iter()
+ .all(|source| source.source_link_id == link_id)
+ {
+ return Ok(sources);
+ }
+ let actor = actor.ok_or(ForwardedAttachmentError::AttachmentNotFound)?;
+ let inboxes = self
+ .repo
+ .accessible_inboxes(actor)
+ .await
+ .map_err(internal)?;
+ let accessible = inboxes.contains(&link_id)
+ && sources
+ .iter()
+ .all(|source| inboxes.contains(&source.source_link_id));
+ tracing::Span::current().record("source_accessible", accessible);
+ if !accessible {
+ return Err(ForwardedAttachmentError::AttachmentNotFound);
+ }
+ Ok(sources)
+ }
+}
+
+fn internal(error: impl std::error::Error + Send + Sync + 'static) -> ForwardedAttachmentError {
+ ForwardedAttachmentError::Internal(rootcause::Report::new(error).into())
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/email/src/domain/forwarded_attachments/test.rs b/crates/email/src/domain/forwarded_attachments/test.rs
new file mode 100644
index 0000000000..1e22ac242b
--- /dev/null
+++ b/crates/email/src/domain/forwarded_attachments/test.rs
@@ -0,0 +1,170 @@
+use super::*;
+use std::{convert::Infallible, sync::Mutex};
+
+const SOURCE: Uuid = Uuid::from_u128(1);
+const SENDING: Uuid = Uuid::from_u128(2);
+const PRIVATE: Uuid = Uuid::from_u128(3);
+const DRAFT: Uuid = Uuid::from_u128(4);
+const ATTACHMENT: Uuid = Uuid::from_u128(5);
+
+struct Repo {
+ inboxes: Mutex<Vec<Uuid>>,
+ source: Uuid,
+ exists: bool,
+ inserted: Mutex<Vec<(Uuid, Uuid, Uuid)>>,
+}
+
+impl Repo {
+ fn new(source: Uuid) -> Self {
+ Self {
+ inboxes: Mutex::new(vec![SOURCE, SENDING]),
+ source,
+ exists: true,
+ inserted: Mutex::new(vec![]),
+ }
+ }
+}
+
+impl ForwardedAttachmentRepo for Repo {
+ type Err = Infallible;
+ async fn accessible_inboxes(&self, actor: &MacroUserIdStr<'_>) -> Result<Vec<Uuid>, Self::Err> {
+ // The selected sending inbox belongs to someone else. Its owner's private
+ // inbox must never replace the authenticated delegate's accessible set.
+ assert_eq!(actor.as_ref(), "macro|[email protected]");
+ Ok(self.inboxes.lock().unwrap().clone())
+ }
+ async fn draft_exists(&self, link: Uuid, draft: Uuid) -> Result<bool, Self::Err> {
+ assert_eq!((link, draft), (SENDING, DRAFT));
+ Ok(self.exists)
+ }
+ async fn source_attachment(
+ &self,
+ id: Uuid,
+ ) -> Result<Option<(Uuid, MessageAttachment)>, Self::Err> {
+ Ok((id == ATTACHMENT).then(|| {
+ (
+ self.source,
+ MessageAttachment {
+ db_id: id,
+ provider_id: Some("provider-attachment".into()),
+ filename: Some("report.pdf".into()),
+ mime_type: Some("application/pdf".into()),
+ size_bytes: Some(123),
+ sfs_id: None,
+ content_id: None,
+ },
+ )
+ }))
+ }
+ async fn insert(&self, link: Uuid, draft: Uuid, attachment: Uuid) -> Result<(), Self::Err> {
+ self.inserted
+ .lock()
+ .unwrap()
+ .push((link, draft, attachment));
+ Ok(())
+ }
+ async fn registered_sources(
+ &self,
+ link: Uuid,
+ draft: Uuid,
+ ) -> Result<Vec<ForwardedAttachmentSource>, Self::Err> {
+ assert_eq!((link, draft), (SENDING, DRAFT));
+ Ok(vec![ForwardedAttachmentSource {
+ source_link_id: self.source,
+ attachment: AttachmentForwarded {
+ attachment_id: ATTACHMENT,
+ draft_id: DRAFT,
+ provider_attachment_id: Some("provider-attachment".into()),
+ message_provider_id: "source-message".into(),
+ filename: Some("report.pdf".into()),
+ mime_type: Some("application/pdf".into()),
+ size_bytes: Some(123),
+ },
+ }])
+ }
+}
+
+#[tokio::test]
+async fn registers_an_owned_source_on_a_delegated_sending_inbox() {
+ let service = ForwardedAttachmentService::new(Repo::new(SOURCE));
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let attachment = service
+ .add(&actor, SENDING, DRAFT, ATTACHMENT)
+ .await
+ .unwrap();
+ assert_eq!(attachment.filename.as_deref(), Some("report.pdf"));
+ assert_eq!(
+ *service.repo.inserted.lock().unwrap(),
+ [(SENDING, DRAFT, ATTACHMENT)]
+ );
+ let sources = service
+ .for_delivery(Some(&actor), SENDING, DRAFT)
+ .await
+ .unwrap();
+ assert_eq!(sources[0].source_link_id, SOURCE);
+ assert_eq!(sources[0].attachment.message_provider_id, "source-message");
+}
+
+#[tokio::test]
+async fn inaccessible_and_missing_sources_have_the_same_error_without_registration() {
+ let service = ForwardedAttachmentService::new(Repo::new(PRIVATE));
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ for attachment in [ATTACHMENT, Uuid::nil()] {
+ let error = service
+ .add(&actor, SENDING, DRAFT, attachment)
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ ForwardedAttachmentError::AttachmentNotFound
+ ));
+ assert_eq!(error.to_string(), "Attachment not found");
+ }
+ assert!(service.repo.inserted.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn missing_or_inaccessible_drafts_never_register_an_attachment() {
+ let mut repo = Repo::new(SOURCE);
+ repo.exists = false;
+ let service = ForwardedAttachmentService::new(repo);
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ for sending in [SENDING, PRIVATE] {
+ assert!(matches!(
+ service.add(&actor, sending, DRAFT, ATTACHMENT).await,
+ Err(ForwardedAttachmentError::DraftNotFound)
+ ));
+ }
+ assert!(service.repo.inserted.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn revoking_source_access_after_registration_blocks_scheduled_delivery() {
+ let service = ForwardedAttachmentService::new(Repo::new(SOURCE));
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ service
+ .add(&actor, SENDING, DRAFT, ATTACHMENT)
+ .await
+ .unwrap();
+ *service.repo.inboxes.lock().unwrap() = vec![SENDING];
+ assert!(matches!(
+ service.for_delivery(Some(&actor), SENDING, DRAFT).await,
+ Err(ForwardedAttachmentError::AttachmentNotFound)
+ ));
+}
+
+#[tokio::test]
+async fn cross_inbox_delivery_requires_a_recorded_actor() {
+ let service = ForwardedAttachmentService::new(Repo::new(SOURCE));
+ assert!(matches!(
+ service.for_delivery(None, SENDING, DRAFT).await,
+ Err(ForwardedAttachmentError::AttachmentNotFound)
+ ));
+}
+
+#[tokio::test]
+async fn legacy_same_inbox_delivery_does_not_require_an_actor() {
+ let service = ForwardedAttachmentService::new(Repo::new(SENDING));
+ let sources = service.for_delivery(None, SENDING, DRAFT).await.unwrap();
+ assert_eq!(sources[0].source_link_id, SENDING);
+}
diff --git a/crates/email_db_client/AGENTS.md b/crates/email_db_client/AGENTS.md
index 905cdb21fb..3d5d50d451 100644
--- a/crates/email_db_client/AGENTS.md
+++ b/crates/email_db_client/AGENTS.md
@@ -43,6 +43,8 @@ cleanup, and backfill.
## Gotchas
+- Forwarded-attachment delivery reads preserve `source_link_id` from the original
+ message; the destination draft inbox is only the query access scope.
- Quote and alias camelCase columns to Rust field names; check
`crates/macro_db_client/migrations/` for real column spelling, don't guess.
diff --git a/crates/email_db_client/src/attachments/forwarded.rs b/crates/email_db_client/src/attachments/forwarded.rs
index 18f7ec10f5..7cb2c5038e 100644
--- a/crates/email_db_client/src/attachments/forwarded.rs
+++ b/crates/email_db_client/src/attachments/forwarded.rs
@@ -1,4 +1,4 @@
-use models_email::{db, service};
+use models_email::db;
use sqlx::types::Uuid;
use sqlx::{Executor, PgPool, Postgres};
@@ -64,6 +64,19 @@ where
Ok(result.rows_affected())
}
+/// Provider download facts scoped to a draft, retaining the original inbox.
+#[derive(Debug, sqlx::FromRow)]
+pub struct ForwardedAttachmentForSend {
+ pub source_link_id: Uuid,
+ pub attachment_id: Uuid,
+ pub draft_id: Uuid,
+ pub provider_attachment_id: Option<String>,
+ pub message_provider_id: String,
+ pub filename: Option<String>,
+ pub mime_type: Option<String>,
+ pub size_bytes: Option<i64>,
+}
+
/// Fetches all forwarded attachments for a given draft, joining email_attachments
/// for metadata and email_messages for the original message's provider_id.
#[tracing::instrument(skip(pool), err)]
@@ -71,11 +84,12 @@ pub async fn fetch_forwarded_attachments_by_draft_id(
pool: &PgPool,
link_id: Uuid,
draft_id: Uuid,
-) -> anyhow::Result<Vec<service::attachment::AttachmentForwarded>> {
- let db_attachments = sqlx::query_as!(
- db::attachment::AttachmentForwarded,
+) -> anyhow::Result<Vec<ForwardedAttachmentForSend>> {
+ let attachments = sqlx::query_as!(
+ ForwardedAttachmentForSend,
r#"
SELECT
+ orig_msg.link_id AS source_link_id,
eaf.attachment_id,
eaf.message_id AS draft_id,
ea.provider_attachment_id,
@@ -96,12 +110,7 @@ pub async fn fetch_forwarded_attachments_by_draft_id(
.fetch_all(pool)
.await?;
- let service_attachments = db_attachments
- .into_iter()
- .map(service::attachment::AttachmentForwarded::from)
- .collect();
-
- Ok(service_attachments)
+ Ok(attachments)
}
/// Fetches forwarded attachments for multiple draft IDs and returns a map keyed by draft_id.
diff --git a/crates/email_db_client/src/attachments/forwarded/test.rs b/crates/email_db_client/src/attachments/forwarded/test.rs
index 72838a2d11..0bddf7f4e7 100644
--- a/crates/email_db_client/src/attachments/forwarded/test.rs
+++ b/crates/email_db_client/src/attachments/forwarded/test.rs
@@ -245,3 +245,36 @@ async fn fetch_forwarded_attachments_in_bulk_excludes_drafts_without_attachments
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))
+)]
+async fn cross_inbox_forward_keeps_the_source_inbox_for_provider_download(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let source = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;
+ let destination = Uuid::parse_str("00000000-0000-0000-0000-000000000f02")?;
+ let draft = Uuid::parse_str("00000000-0000-0000-0000-00000000f501")?;
+ sqlx::query!(
+ "UPDATE email_messages SET link_id = $1 WHERE id = $2",
+ destination,
+ draft
+ )
+ .execute(&pool)
+ .await?;
+ let attachments = fetch_forwarded_attachments_by_draft_id(&pool, destination, draft).await?;
+ assert_eq!(attachments.len(), 2);
+ assert!(
+ attachments
+ .iter()
+ .all(|attachment| attachment.source_link_id == source)
+ );
+ assert_eq!(attachments[0].message_provider_id, "gmail-original-msg-001");
+ assert!(
+ fetch_forwarded_attachments_by_draft_id(&pool, source, draft)
+ .await?
+ .is_empty()
+ );
+ Ok(())
+}
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index 77d9fcffc7..fb2f5ada96 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -314,6 +314,13 @@ During send or discard, its sender and scheduling controls cannot change the ope
Attachments that can be opened are buttons named by their filename; Tab to one
and press Enter or Space. Removal is a separate button named `Remove <filename>`.
Removing a forwarded file keeps the received original.
+To forward from another inbox, open Forward, expand the forwarding envelope on
+desktop, and select a different account in From (already visible on mobile).
+Forwarded files must remain attached after switching to an owned or delegated
+inbox, saving, and reopening the draft. Send must fetch the original files from
+the receiving inbox while using the selected From inbox for delivery. A scheduled
+cross-inbox forward must not download a source whose inbox access was revoked
+after saving.
When checking draft autosave, edit the body of a draft with uploaded or forwarded
attachments, wait for the save, and reopen it; the attachments should remain visible.
In a long thread, scroll away from the bottom while a draft save is pending.
diff --git a/services/email_service/AGENTS.md b/services/email_service/AGENTS.md
index 7ddd76891e..ba470a7fb1 100644
--- a/services/email_service/AGENTS.md
+++ b/services/email_service/AGENTS.md
@@ -46,6 +46,8 @@ the gateway `/email` prefix.
## Gotchas
+- Forwarded attachments use the source inbox's provider credentials; the email
+ domain rechecks the scheduled actor's access before cross-inbox downloads.
- Macro's own digest emails are filtered out of Signal/email notifications
(#7039) — don't reintroduce a path that notifies on our own sends.
- Long attachment names are truncated to the DSS limit before upload (#7893);
diff --git a/services/email_service/src/api/context.rs b/services/email_service/src/api/context.rs
index 309476b4fe..dca7b8813b 100644
--- a/services/email_service/src/api/context.rs
+++ b/services/email_service/src/api/context.rs
@@ -66,6 +66,9 @@ pub(crate) struct ApiContext {
calendar_events::outbound::pg::PgCalendarRepository,
>,
>,
+ pub forwarded_attachments: email::domain::forwarded_attachments::ForwardedAttachmentService<
+ crate::outbound::forwarded_attachments::PgForwardedAttachmentRepo,
+ >,
pub db: sqlx::Pool<sqlx::Postgres>,
pub auth_service_client: Arc<authentication_service_client::AuthServiceClient>,
// The raw client is retained only for Gmail webhook JWKS/JWT authentication.
diff --git a/services/email_service/src/api/email/drafts/add_forwarded_attachment.rs b/services/email_service/src/api/email/drafts/add_forwarded_attachment.rs
index 381c0eca7f..1245338850 100644
--- a/services/email_service/src/api/email/drafts/add_forwarded_attachment.rs
+++ b/services/email_service/src/api/email/drafts/add_forwarded_attachment.rs
@@ -1,35 +1,26 @@
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
+use email::domain::forwarded_attachments::ForwardedAttachmentError;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use models_email::service::link::Link;
-use strum_macros::AsRefStr;
-use thiserror::Error;
use utoipa::{IntoParams, ToSchema};
use uuid::Uuid;
-#[derive(Debug, Error, AsRefStr)]
-pub enum AddForwardedAttachmentError {
- #[error("Draft not found")]
- DraftNotFound,
-
- #[error("Attachment not found")]
- AttachmentNotFound,
-
- #[error("Internal error")]
- InternalError(#[from] anyhow::Error),
-}
+#[derive(Debug, thiserror::Error)]
+#[error(transparent)]
+pub struct AddForwardedAttachmentError(#[from] ForwardedAttachmentError);
impl IntoResponse for AddForwardedAttachmentError {
fn into_response(self) -> Response {
- let status_code = match &self {
- AddForwardedAttachmentError::DraftNotFound
- | AddForwardedAttachmentError::AttachmentNotFound => StatusCode::NOT_FOUND,
- AddForwardedAttachmentError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ let status_code = match &self.0 {
+ ForwardedAttachmentError::DraftNotFound
+ | ForwardedAttachmentError::AttachmentNotFound => StatusCode::NOT_FOUND,
+ ForwardedAttachmentError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
-
(
status_code,
Json(ErrorResponse {
@@ -78,38 +69,23 @@ pub struct AddForwardedAttachmentResponse {
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx), err)]
+#[tracing::instrument(skip(ctx, authorization, link), fields(link_id = %link.id), err)]
pub async fn handler(
State(ctx): State<ApiContext>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
link: Extension<Link>,
Path(PathParams { id: draft_id }): Path<PathParams>,
Json(req): Json<AddForwardedAttachmentRequest>,
) -> Result<(StatusCode, Json<AddForwardedAttachmentResponse>), AddForwardedAttachmentError> {
- // Ensure draft exists and belongs to this link
- if !email_db_client::messages::get::draft_exists_with_id(&ctx.db, link.id, draft_id).await? {
- return Err(AddForwardedAttachmentError::DraftNotFound);
- }
-
- // Verify the attachment exists in email_attachments and belongs to this link
- let result = email_db_client::attachments::provider::fetch_attachment_by_id(
- &ctx.db,
- req.attachment_id,
- link.id,
- )
- .await?;
-
- let Some((attachment, _message_provider_id)) = result else {
- return Err(AddForwardedAttachmentError::AttachmentNotFound);
- };
-
- // Insert the forwarded attachment link
- email_db_client::attachments::forwarded::insert_forwarded_attachment(
- &ctx.db,
- link.id,
- draft_id,
- req.attachment_id,
- )
- .await?;
+ let attachment = ctx
+ .forwarded_attachments
+ .add(
+ &authorization.authorization.user.macro_user_id,
+ link.id,
+ draft_id,
+ req.attachment_id,
+ )
+ .await?;
Ok((
StatusCode::CREATED,
diff --git a/services/email_service/src/outbound.rs b/services/email_service/src/outbound.rs
index e2ced4ccb6..314e07365d 100644
--- a/services/email_service/src/outbound.rs
+++ b/services/email_service/src/outbound.rs
@@ -6,3 +6,6 @@ pub mod invitation_extraction;
pub mod email_api;
/// Persistence and provider adapters for scheduled-delivery claims.
pub mod scheduled_delivery;
+
+/// Forwarded-attachment persistence facts.
+pub mod forwarded_attachments;
diff --git a/services/email_service/src/outbound/forwarded_attachments.rs b/services/email_service/src/outbound/forwarded_attachments.rs
new file mode 100644
index 0000000000..44186a4628
--- /dev/null
+++ b/services/email_service/src/outbound/forwarded_attachments.rs
@@ -0,0 +1,121 @@
+//! PostgreSQL facts for forwarded-attachment authorization and source selection.
+use email::domain::forwarded_attachments::{ForwardedAttachmentRepo, ForwardedAttachmentSource};
+use email::domain::models::{AttachmentForwarded, MessageAttachment};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+/// Adapter for existing email attachment queries.
+#[derive(Clone)]
+pub struct PgForwardedAttachmentRepo(pub sqlx::PgPool);
+
+/// Preserve database errors across the domain port.
+#[derive(Debug, thiserror::Error)]
+#[error(transparent)]
+pub struct ForwardedAttachmentRepoError(#[from] anyhow::Error);
+
+impl ForwardedAttachmentRepo for PgForwardedAttachmentRepo {
+ type Err = ForwardedAttachmentRepoError;
+
+ #[tracing::instrument(skip(self, actor), err)]
+ async fn accessible_inboxes(&self, actor: &MacroUserIdStr<'_>) -> Result<Vec<Uuid>, Self::Err> {
+ Ok(
+ email_db_client::links::get::fetch_inboxes_for_macro_id(&self.0, actor.as_ref())
+ .await?
+ .into_iter()
+ .map(|link| link.id)
+ .collect(),
+ )
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn draft_exists(&self, link_id: Uuid, draft_id: Uuid) -> Result<bool, Self::Err> {
+ Ok(
+ email_db_client::messages::get::draft_exists_with_id(&self.0, link_id, draft_id)
+ .await?,
+ )
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn source_attachment(
+ &self,
+ attachment_id: Uuid,
+ ) -> Result<Option<(Uuid, MessageAttachment)>, Self::Err> {
+ let Some((_, source_link_id)) =
+ email_db_client::attachments::provider::get_thread_id_for_attachment(
+ &self.0,
+ attachment_id,
+ )
+ .await?
+ else {
+ return Ok(None);
+ };
+ Ok(
+ email_db_client::attachments::provider::fetch_attachment_by_id(
+ &self.0,
+ attachment_id,
+ source_link_id,
+ )
+ .await?
+ .map(|(attachment, _)| {
+ (
+ source_link_id,
+ MessageAttachment {
+ db_id: attachment.db_id,
+ provider_id: attachment.provider_id,
+ filename: attachment.filename,
+ mime_type: attachment.mime_type,
+ size_bytes: attachment.size_bytes,
+ sfs_id: attachment.sfs_id,
+ content_id: attachment.content_id,
+ },
+ )
+ }),
+ )
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn insert(
+ &self,
+ link_id: Uuid,
+ draft_id: Uuid,
+ attachment_id: Uuid,
+ ) -> Result<(), Self::Err> {
+ Ok(
+ email_db_client::attachments::forwarded::insert_forwarded_attachment(
+ &self.0,
+ link_id,
+ draft_id,
+ attachment_id,
+ )
+ .await?,
+ )
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn registered_sources(
+ &self,
+ link_id: Uuid,
+ draft_id: Uuid,
+ ) -> Result<Vec<ForwardedAttachmentSource>, Self::Err> {
+ Ok(
+ email_db_client::attachments::forwarded::fetch_forwarded_attachments_by_draft_id(
+ &self.0, link_id, draft_id,
+ )
+ .await?
+ .into_iter()
+ .map(|source| ForwardedAttachmentSource {
+ source_link_id: source.source_link_id,
+ attachment: AttachmentForwarded {
+ attachment_id: source.attachment_id,
+ draft_id: source.draft_id,
+ provider_attachment_id: source.provider_attachment_id,
+ message_provider_id: source.message_provider_id,
+ filename: source.filename,
+ mime_type: source.mime_type,
+ size_bytes: source.size_bytes,
+ },
+ })
+ .collect(),
+ )
+ }
+}
diff --git a/services/email_service/src/outbound/scheduled_delivery.rs b/services/email_service/src/outbound/scheduled_delivery.rs
index b31d8ee26f..f005d5c6ec 100644
--- a/services/email_service/src/outbound/scheduled_delivery.rs
+++ b/services/email_service/src/outbound/scheduled_delivery.rs
@@ -24,6 +24,9 @@ use uuid::Uuid;
/// Concrete worker adapters, wired by the scheduled worker's composition root.
pub struct ScheduledDeliveryAdapter {
pub db: sqlx::PgPool,
+ pub forwarded_attachments: email::domain::forwarded_attachments::ForwardedAttachmentService<
+ crate::outbound::forwarded_attachments::PgForwardedAttachmentRepo,
+ >,
pub email_api: GmailApi,
pub s3_client: s3_client::S3,
pub attachment_bucket: String,
@@ -212,7 +215,15 @@ impl ScheduledMessageSender<ScheduledClaim, SentDelivery> for ScheduledDeliveryA
.await?;
// Include forwarded attachments (fetched from Gmail at send time)
- fetch_and_attach_forwarded_attachments(&ctx.db, &ctx.email_api, link, &mut message_to_send)
+ let actor = data
+ .actor_id
+ .as_deref()
+ .and_then(|actor| MacroUserIdStr::parse_from_str(actor).ok());
+ let sources = ctx
+ .forwarded_attachments
+ .for_delivery(actor.as_ref(), link.id, data.message_id)
+ .await?;
+ fetch_and_attach_forwarded_attachments(&ctx.email_api, &sources, &mut message_to_send)
.await?;
let send_request = SendRequest {
diff --git a/services/email_service/src/pubsub/scheduled/context.rs b/services/email_service/src/pubsub/scheduled/context.rs
index 2866b7373c..5e5eca997c 100644
--- a/services/email_service/src/pubsub/scheduled/context.rs
+++ b/services/email_service/src/pubsub/scheduled/context.rs
@@ -19,6 +19,12 @@ impl ScheduledContext {
) -> crate::outbound::scheduled_delivery::ScheduledDeliveryAdapter {
crate::outbound::scheduled_delivery::ScheduledDeliveryAdapter {
db: self.db.clone(),
+ forwarded_attachments:
+ email::domain::forwarded_attachments::ForwardedAttachmentService::new(
+ crate::outbound::forwarded_attachments::PgForwardedAttachmentRepo(
+ self.db.clone(),
+ ),
+ ),
email_api: self.email_api.clone(),
s3_client: self.s3_client.clone(),
attachment_bucket: self.attachment_bucket.clone(),
diff --git a/services/email_service/src/server.rs b/services/email_service/src/server.rs
index 6a745bc14e..0ed9bcf1e8 100644
--- a/services/email_service/src/server.rs
+++ b/services/email_service/src/server.rs
@@ -234,6 +234,10 @@ pub async fn run() -> anyhow::Result<()> {
invitation_resolver: Arc::new(CalendarInvitationResolver::new(PgCalendarRepository::new(
db.clone(),
))),
+ forwarded_attachments:
+ email::domain::forwarded_attachments::ForwardedAttachmentService::new(
+ crate::outbound::forwarded_attachments::PgForwardedAttachmentRepo(db.clone()),
+ ),
db,
internal_api_key: config.internal_api_key.clone(),
config: Arc::new(config),
diff --git a/services/email_service/src/util/gmail/send.rs b/services/email_service/src/util/gmail/send.rs
index a75f334061..f7a23c3572 100644
--- a/services/email_service/src/util/gmail/send.rs
+++ b/services/email_service/src/util/gmail/send.rs
@@ -1,5 +1,9 @@
-use crate::outbound::email_api::GmailApi;
use anyhow::Context;
+use email::domain::forwarded_attachments::ForwardedAttachmentSource;
+use email_api_client::domain::{
+ ports::{MailboxAttachmentClient, ProviderRateLimiter, ProviderTokenSource},
+ service::EmailApiClientServiceImpl,
+};
use models_email::service::attachment::{AttachmentDraft, AttachmentToSend};
use models_email::service::link::Link;
use models_email::service::message;
@@ -109,35 +113,29 @@ pub async fn fetch_and_attach_draft_attachments(
/// Forwarded attachments reference original Gmail attachments, so their data is fetched
/// from Gmail at send time rather than from S3.
#[tracing::instrument(
- skip(db, email_api, message_to_send),
- fields(message_db_id = ?message_to_send.db_id), err
+ skip(email_api, sources, message_to_send),
+ fields(message_db_id = ?message_to_send.db_id, source_count = sources.len()), err
)]
-pub async fn fetch_and_attach_forwarded_attachments(
- db: &PgPool,
- email_api: &GmailApi,
- link: &Link,
+pub async fn fetch_and_attach_forwarded_attachments<R, T, L>(
+ email_api: &EmailApiClientServiceImpl<R, T, L>,
+ sources: &[ForwardedAttachmentSource],
message_to_send: &mut message::MessageToSend,
-) -> anyhow::Result<()> {
- let Some(db_id) = message_to_send.db_id else {
- return Ok(());
- };
-
- let fwd_attachments =
- email_db_client::attachments::forwarded::fetch_forwarded_attachments_by_draft_id(
- db, link.id, db_id,
- )
- .await
- .context("unable to fetch forwarded attachments from database")?;
-
- if fwd_attachments.is_empty() {
+) -> anyhow::Result<()>
+where
+ R: MailboxAttachmentClient,
+ T: ProviderTokenSource,
+ L: ProviderRateLimiter,
+{
+ if sources.is_empty() {
return Ok(());
}
- let fetch_futures = fwd_attachments.iter().map(|fwd_att| async move {
+ let fetch_futures = sources.iter().map(|source| async move {
+ let fwd_att = &source.attachment;
let provider_att_id = fwd_att.provider_attachment_id.as_deref().unwrap_or_default();
let data = email_api
- .get_attachment(link.id, &fwd_att.message_provider_id, provider_att_id)
+ .get_attachment(source.source_link_id, &fwd_att.message_provider_id, provider_att_id)
.await
.with_context(|| {
format!(
@@ -201,3 +199,6 @@ pub async fn cleanup_draft_attachments(
}
}
}
+
+#[cfg(test)]
+mod test;
diff --git a/services/email_service/src/util/gmail/send/test.rs b/services/email_service/src/util/gmail/send/test.rs
new file mode 100644
index 0000000000..ae972373ac
--- /dev/null
+++ b/services/email_service/src/util/gmail/send/test.rs
@@ -0,0 +1,103 @@
+use super::*;
+use email::domain::models::AttachmentForwarded;
+use email_api_client::domain::{
+ models::{AccessToken, EmailApiError, TokenError, TokenFreshness},
+ ports::AlwaysAllowRateLimiter,
+};
+
+const SOURCE: Uuid = Uuid::from_u128(1);
+const SENDING: Uuid = Uuid::from_u128(2);
+
+struct Tokens;
+impl ProviderTokenSource for Tokens {
+ async fn get_access_token(
+ &self,
+ link_id: Uuid,
+ _: TokenFreshness,
+ ) -> Result<AccessToken, TokenError> {
+ assert_eq!(
+ link_id, SOURCE,
+ "download must use the original inbox, not the sender"
+ );
+ Ok(AccessToken::new("source-inbox-token"))
+ }
+ async fn get_access_token_for_link(
+ &self,
+ _: &Link,
+ _: TokenFreshness,
+ ) -> Result<AccessToken, TokenError> {
+ panic!("forwarding uses the source inbox id");
+ }
+ async fn get_access_token_health_neutral(
+ &self,
+ _: &Link,
+ _: TokenFreshness,
+ ) -> Result<AccessToken, TokenError> {
+ panic!("forwarding uses the source inbox id");
+ }
+}
+struct Provider;
+impl MailboxAttachmentClient for Provider {
+ async fn get_attachment(
+ &self,
+ token: &AccessToken,
+ message_id: &str,
+ attachment_id: &str,
+ ) -> Result<Vec<u8>, EmailApiError> {
+ assert_eq!(token.expose_secret(), "source-inbox-token");
+ assert_eq!(
+ (message_id, attachment_id),
+ ("original-message", "original-attachment")
+ );
+ Ok(b"pdf bytes".to_vec())
+ }
+}
+
+#[tokio::test]
+async fn forwarding_uses_source_credentials_and_preserves_existing_attachments() {
+ let api = EmailApiClientServiceImpl::new(Provider, Tokens, AlwaysAllowRateLimiter);
+ let sources = [ForwardedAttachmentSource {
+ source_link_id: SOURCE,
+ attachment: AttachmentForwarded {
+ attachment_id: Uuid::from_u128(3),
+ draft_id: Uuid::from_u128(4),
+ provider_attachment_id: Some("original-attachment".into()),
+ message_provider_id: "original-message".into(),
+ filename: Some("report.pdf".into()),
+ mime_type: Some("application/pdf".into()),
+ size_bytes: Some(9),
+ },
+ }];
+ let mut message = message::MessageToSend {
+ db_id: Some(Uuid::from_u128(4)),
+ provider_id: None,
+ replying_to_id: None,
+ provider_thread_id: None,
+ thread_db_id: None,
+ link_id: SENDING,
+ subject: "Forward".into(),
+ to: None,
+ cc: None,
+ bcc: None,
+ body_text: None,
+ body_html: None,
+ body_macro: None,
+ headers_json: None,
+ send_time: None,
+ attachments: Some(vec![AttachmentToSend {
+ file_name: "local.txt".into(),
+ content_type: "text/plain".into(),
+ data: b"local".to_vec(),
+ }]),
+ };
+ fetch_and_attach_forwarded_attachments(&api, &sources, &mut message)
+ .await
+ .unwrap();
+ let attachments = message.attachments.unwrap();
+ assert_eq!(attachments.len(), 2);
+ assert_eq!(attachments[0].data, b"local");
+ assert_eq!(attachments[1].file_name, "report.pdf");
+ assert_eq!(attachments[1].content_type, "application/pdf");
+ assert_eq!(attachments[1].data, b"pdf bytes");
+ assert_eq!(message.link_id, SENDING);
+}