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-service): Send attachments with emails (#858)

Evan Hutnikae0cfa5438dc
diff --git a/infra/stacks/email-service/attachments-bucket.ts b/infra/stacks/email-service/attachments-bucket.ts
index cf7ae0fe50..eab6f077d3 100644
--- a/infra/stacks/email-service/attachments-bucket.ts
+++ b/infra/stacks/email-service/attachments-bucket.ts
@@ -33,11 +33,10 @@ export class EmailAttachmentsBucket extends pulumi.ComponentResource {
transferAcceleration: stack === 'prod',
lifecycleRules: [
{
- id: `email-attachments-${stack}-cleanup`,
+ id: `temp-files-1d-${stack}`,
enabled: true,
- expiration: {
- days: 1,
- },
+ prefix: 'temp/',
+ expiration: { days: 1 },
},
],
});
@@ -103,6 +102,7 @@ export class EmailAttachmentsBucket extends pulumi.ComponentResource {
Action: [
's3:GetObject',
's3:PutObject',
+ 's3:DeleteObject',
's3:GetObjectAttributes',
's3:ListBucket',
],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 97d92fd4b8..fef875cb89 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3193,6 +3193,7 @@ dependencies = [
"mime_guess",
"model",
"model-entity",
+ "model_file_type",
"model_notifications",
"models_email",
"models_opensearch",
@@ -7579,6 +7580,8 @@ version = "0.1.0"
dependencies = [
"anyhow",
"aws-sdk-s3",
+ "base64 0.22.1",
+ "hex",
"tracing",
]
diff --git a/rust/cloud-storage/document_storage_service/src/service/s3/put_presigned_url.rs b/rust/cloud-storage/document_storage_service/src/service/s3/put_presigned_url.rs
index 9c492f2b2b..fe9a11d066 100644
--- a/rust/cloud-storage/document_storage_service/src/service/s3/put_presigned_url.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/s3/put_presigned_url.rs
@@ -19,7 +19,7 @@ pub(in crate::service::s3) async fn put_presigned_url(
if cfg!(feature = "local") {
return Ok("fake".to_string());
}
- // Allows the app 2 minutes to grab the document
+ // Allows the app 2 minutes to upload the document
let expiry_duration = Duration::from_secs(2 * 60);
// Convert the hex SHA256 hash to binary
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-099d255a2a214f5c4ed3ee9d5d8389dfd3ad004eb3572fb7d724b407bdb2c2e3.json b/rust/cloud-storage/email_db_client/.sqlx/query-099d255a2a214f5c4ed3ee9d5d8389dfd3ad004eb3572fb7d724b407bdb2c2e3.json
new file mode 100644
index 0000000000..5c08a070c2
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-099d255a2a214f5c4ed3ee9d5d8389dfd3ad004eb3572fb7d724b407bdb2c2e3.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS(\n SELECT 1\n FROM email_messages\n WHERE id = $1 AND link_id = $2 AND is_draft = true\n ) as \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "099d255a2a214f5c4ed3ee9d5d8389dfd3ad004eb3572fb7d724b407bdb2c2e3"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-16975c8ff9585b8da53ace00a26851f992232834de508dac16ff58d9da1cbc2a.json b/rust/cloud-storage/email_db_client/.sqlx/query-16975c8ff9585b8da53ace00a26851f992232834de508dac16ff58d9da1cbc2a.json
new file mode 100644
index 0000000000..b0e63bec06
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-16975c8ff9585b8da53ace00a26851f992232834de508dac16ff58d9da1cbc2a.json
@@ -0,0 +1,21 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO email_attachments_drafts (\n id, draft_id, file_name, content_type, sha, size, s3_key\n )\n -- if the message belongs to a different link_id, nothing will be returned from this\n -- and thus nothing will be inserted\n SELECT $1, $2, $3, $4, $5, $6, $7\n FROM email_messages m\n WHERE m.id = $2 AND m.link_id = $8\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Int4",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "16975c8ff9585b8da53ace00a26851f992232834de508dac16ff58d9da1cbc2a"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-473db34286d4aeefece0b6a97cea69cad83d20908c700d750a4047ce5bee30f4.json b/rust/cloud-storage/email_db_client/.sqlx/query-473db34286d4aeefece0b6a97cea69cad83d20908c700d750a4047ce5bee30f4.json
new file mode 100644
index 0000000000..f182e4bc32
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-473db34286d4aeefece0b6a97cea69cad83d20908c700d750a4047ce5bee30f4.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM email_attachments_drafts ead\n USING email_messages m\n WHERE ead.draft_id = m.id\n AND ead.id = $1 AND ead.draft_id = $2 AND m.link_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "473db34286d4aeefece0b6a97cea69cad83d20908c700d750a4047ce5bee30f4"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-5ee7a600e71709918f23db0066f39b2a7a87880e5a9c6aa565ac85e0efdde85d.json b/rust/cloud-storage/email_db_client/.sqlx/query-5ee7a600e71709918f23db0066f39b2a7a87880e5a9c6aa565ac85e0efdde85d.json
new file mode 100644
index 0000000000..db49ce7734
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-5ee7a600e71709918f23db0066f39b2a7a87880e5a9c6aa565ac85e0efdde85d.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT SUM(ead.size)::BIGINT\n FROM email_attachments_drafts ead\n JOIN email_messages m ON ead.draft_id = m.id\n WHERE ead.draft_id = $1 AND m.link_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sum",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "5ee7a600e71709918f23db0066f39b2a7a87880e5a9c6aa565ac85e0efdde85d"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-93df91392a72cc298609b453dc95621e7690af924a1af7bb4748dc704ed8897d.json b/rust/cloud-storage/email_db_client/.sqlx/query-93df91392a72cc298609b453dc95621e7690af924a1af7bb4748dc704ed8897d.json
new file mode 100644
index 0000000000..aedc40a8c4
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-93df91392a72cc298609b453dc95621e7690af924a1af7bb4748dc704ed8897d.json
@@ -0,0 +1,59 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT ead.id, ead.draft_id, ead.file_name, ead.content_type, ead.sha, ead.size, ead.s3_key\n FROM email_attachments_drafts ead\n JOIN email_messages m ON ead.draft_id = m.id\n WHERE ead.draft_id = $1 AND m.link_id = $2\n ORDER BY ead.file_name ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "draft_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "file_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "sha",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "size",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 6,
+ "name": "s3_key",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "93df91392a72cc298609b453dc95621e7690af924a1af7bb4748dc704ed8897d"
+}
diff --git a/rust/cloud-storage/email_db_client/fixtures/draft_attachments.sql b/rust/cloud-storage/email_db_client/fixtures/draft_attachments.sql
new file mode 100644
index 0000000000..352ad15d2b
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/fixtures/draft_attachments.sql
@@ -0,0 +1,123 @@
+-- SQL fixture for draft_attachments tests
+-- Tests insert, fetch, delete, and total size operations for draft attachments
+
+------------------------------------------------------------
+-- User Link
+------------------------------------------------------------
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000d01', 'macro|[email protected]', '00000000-0000-0000-0000-000000000d01',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Second link for testing cross-link access prevention
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000d02', 'macro|[email protected]', '00000000-0000-0000-0000-000000000d02',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Contact
+------------------------------------------------------------
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000cd001',
+ '00000000-0000-0000-0000-000000000d01',
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Thread
+------------------------------------------------------------
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000d201',
+ '00000000-0000-0000-0000-000000000d01',
+ true, false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Draft Message 1: Has multiple attachments (for fetch and total size tests)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000d501',
+ '00000000-0000-0000-0000-00000000d201',
+ '00000000-0000-0000-0000-000000000d01',
+ 'provider-draft-501',
+ FALSE,
+ '00000000-0000-0000-0000-0000000cd001',
+ '2025-01-05 10:00:00 +00:00',
+ true, false, false, true, NOW(), NOW());
+
+-- Attachment 1: alpha_file.pdf (size: 1000)
+INSERT INTO email_attachments_drafts (id, draft_id, file_name, content_type, sha, size, s3_key, created_at)
+VALUES ('00000000-0000-0000-0000-0000000da001',
+ '00000000-0000-0000-0000-00000000d501',
+ 'alpha_file.pdf',
+ 'application/pdf',
+ 'sha256_alpha',
+ 1000,
+ 's3://bucket/alpha_file.pdf',
+ NOW());
+
+-- Attachment 2: bravo_image.png (size: 2000)
+INSERT INTO email_attachments_drafts (id, draft_id, file_name, content_type, sha, size, s3_key, created_at)
+VALUES ('00000000-0000-0000-0000-0000000da002',
+ '00000000-0000-0000-0000-00000000d501',
+ 'bravo_image.png',
+ 'image/png',
+ 'sha256_bravo',
+ 2000,
+ 's3://bucket/bravo_image.png',
+ NOW());
+
+-- Attachment 3: zulu_doc.docx (size: 3000)
+INSERT INTO email_attachments_drafts (id, draft_id, file_name, content_type, sha, size, s3_key, created_at)
+VALUES ('00000000-0000-0000-0000-0000000da003',
+ '00000000-0000-0000-0000-00000000d501',
+ 'zulu_doc.docx',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'sha256_zulu',
+ 3000,
+ 's3://bucket/zulu_doc.docx',
+ NOW());
+
+------------------------------------------------------------
+-- Draft Message 2: Empty draft (no attachments, for insert test)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000d502',
+ '00000000-0000-0000-0000-00000000d201',
+ '00000000-0000-0000-0000-000000000d01',
+ 'provider-draft-502',
+ FALSE,
+ '00000000-0000-0000-0000-0000000cd001',
+ '2025-01-05 11:00:00 +00:00',
+ false, false, false, true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Draft Message 3: Single attachment (for delete test)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000d503',
+ '00000000-0000-0000-0000-00000000d201',
+ '00000000-0000-0000-0000-000000000d01',
+ 'provider-draft-503',
+ FALSE,
+ '00000000-0000-0000-0000-0000000cd001',
+ '2025-01-05 12:00:00 +00:00',
+ true, false, false, true, NOW(), NOW());
+
+-- Attachment for delete test
+INSERT INTO email_attachments_drafts (id, draft_id, file_name, content_type, sha, size, s3_key, created_at)
+VALUES ('00000000-0000-0000-0000-0000000da004',
+ '00000000-0000-0000-0000-00000000d503',
+ 'delete_me.txt',
+ 'text/plain',
+ 'sha256_delete',
+ 500,
+ 's3://bucket/delete_me.txt',
+ NOW());
\ No newline at end of file
diff --git a/rust/cloud-storage/email_db_client/fixtures/draft_exists_with_id.sql b/rust/cloud-storage/email_db_client/fixtures/draft_exists_with_id.sql
new file mode 100644
index 0000000000..5618e43382
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/fixtures/draft_exists_with_id.sql
@@ -0,0 +1,64 @@
+-- SQL fixture for draft_exists_with_id tests
+-- Tests checking existence of draft messages by id and link_id
+
+------------------------------------------------------------
+-- User Links
+------------------------------------------------------------
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000e01', 'macro|[email protected]', '00000000-0000-0000-0000-000000000e01',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Second link for testing cross-link access prevention
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000e02', 'macro|[email protected]', '00000000-0000-0000-0000-000000000e02',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Contact
+------------------------------------------------------------
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000ce001',
+ '00000000-0000-0000-0000-000000000e01',
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Thread
+------------------------------------------------------------
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e201',
+ '00000000-0000-0000-0000-000000000e01',
+ true, false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 1: Draft message (is_draft = true)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e501',
+ '00000000-0000-0000-0000-00000000e201',
+ '00000000-0000-0000-0000-000000000e01',
+ 'provider-msg-e501',
+ FALSE,
+ '00000000-0000-0000-0000-0000000ce001',
+ '2025-01-05 10:00:00 +00:00',
+ false, false, false, true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 2: Non-draft message (is_draft = false)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e502',
+ '00000000-0000-0000-0000-00000000e201',
+ '00000000-0000-0000-0000-000000000e01',
+ 'provider-msg-e502',
+ TRUE,
+ '00000000-0000-0000-0000-0000000ce001',
+ '2025-01-05 11:00:00 +00:00',
+ false, true, false, false, NOW(), NOW());
\ No newline at end of file
diff --git a/rust/cloud-storage/email_db_client/src/attachments/draft/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/draft/mod.rs
new file mode 100644
index 0000000000..1fba2667ef
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/attachments/draft/mod.rs
@@ -0,0 +1,125 @@
+use models_email::{db, service};
+use sqlx::types::Uuid;
+use sqlx::{Executor, PgPool, Postgres};
+
+#[cfg(test)]
+mod test;
+
+/// Inserts a new draft attachment metadata record.
+#[tracing::instrument(skip(executor, attachment), err)]
+pub async fn insert_draft_attachment<'e, E>(
+ executor: E,
+ link_id: Uuid,
+ attachment: service::attachment::AttachmentDraft,
+) -> anyhow::Result<()>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ let db_att: db::attachment::AttachmentDraft = attachment.into();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO email_attachments_drafts (
+ id, draft_id, file_name, content_type, sha, size, s3_key
+ )
+ -- if the message belongs to a different link_id, nothing will be returned from this
+ -- and thus nothing will be inserted
+ SELECT $1, $2, $3, $4, $5, $6, $7
+ FROM email_messages m
+ WHERE m.id = $2 AND m.link_id = $8
+ "#,
+ db_att.id,
+ db_att.draft_id,
+ db_att.file_name,
+ db_att.content_type,
+ db_att.sha,
+ db_att.size,
+ db_att.s3_key,
+ link_id
+ )
+ .execute(executor)
+ .await?;
+
+ Ok(())
+}
+
+/// Returns the sum of the size of all attachments for a given draft_id.
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_total_attachments_size_by_draft_id(
+ pool: &PgPool,
+ link_id: Uuid,
+ draft_id: Uuid,
+) -> anyhow::Result<i32> {
+ let total_size: Option<i64> = sqlx::query_scalar!(
+ r#"
+ SELECT SUM(ead.size)::BIGINT
+ FROM email_attachments_drafts ead
+ JOIN email_messages m ON ead.draft_id = m.id
+ WHERE ead.draft_id = $1 AND m.link_id = $2
+ "#,
+ draft_id,
+ link_id
+ )
+ .fetch_one(pool)
+ .await?;
+
+ Ok(total_size.unwrap_or(0) as i32)
+}
+
+/// Deletes a draft attachment record given the draft_id and attachment_id.
+#[tracing::instrument(skip(executor), err)]
+pub async fn delete_draft_attachment<'e, E>(
+ executor: E,
+ link_id: Uuid,
+ draft_id: Uuid,
+ attachment_id: Uuid,
+) -> anyhow::Result<u64>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ let result = sqlx::query!(
+ r#"
+ DELETE FROM email_attachments_drafts ead
+ USING email_messages m
+ WHERE ead.draft_id = m.id
+ AND ead.id = $1 AND ead.draft_id = $2 AND m.link_id = $3
+ "#,
+ attachment_id,
+ draft_id,
+ link_id
+ )
+ .execute(executor)
+ .await?;
+
+ Ok(result.rows_affected())
+}
+
+/// Fetches all draft attachments for a given draft_id.
+#[tracing::instrument(skip(pool), err)]
+pub async fn fetch_draft_attachments_by_draft_id(
+ pool: &PgPool,
+ link_id: Uuid,
+ draft_id: Uuid,
+) -> anyhow::Result<Vec<service::attachment::AttachmentDraft>> {
+ let db_attachments = sqlx::query_as!(
+ db::attachment::AttachmentDraft,
+ r#"
+ SELECT ead.id, ead.draft_id, ead.file_name, ead.content_type, ead.sha, ead.size, ead.s3_key
+ FROM email_attachments_drafts ead
+ JOIN email_messages m ON ead.draft_id = m.id
+ WHERE ead.draft_id = $1 AND m.link_id = $2
+ ORDER BY ead.file_name ASC
+ "#,
+ draft_id,
+ link_id
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let service_attachments = db_attachments
+ .into_iter()
+ .map(service::attachment::AttachmentDraft::from)
+ .collect();
+
+ Ok(service_attachments)
+}
diff --git a/rust/cloud-storage/email_db_client/src/attachments/draft/test.rs b/rust/cloud-storage/email_db_client/src/attachments/draft/test.rs
new file mode 100644
index 0000000000..094b4ddab4
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/attachments/draft/test.rs
@@ -0,0 +1,236 @@
+use crate::attachments::draft::{
+ delete_draft_attachment, fetch_draft_attachments_by_draft_id,
+ get_total_attachments_size_by_draft_id, insert_draft_attachment,
+};
+use anyhow::Result;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use models_email::service;
+use sqlx::types::Uuid;
+use sqlx::{Pool, Postgres};
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn fetch_draft_attachments_returns_attachments_ordered_by_filename(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d501")?;
+
+ let res = fetch_draft_attachments_by_draft_id(&pool, link_id, draft_id).await?;
+
+ assert_eq!(res.len(), 3);
+
+ // Verify ordering by filename ASC
+ assert_eq!(res[0].file_name, "alpha_file.pdf");
+ assert_eq!(res[1].file_name, "bravo_image.png");
+ assert_eq!(res[2].file_name, "zulu_doc.docx");
+
+ // Verify other fields
+ assert_eq!(res[0].content_type, "application/pdf");
+ assert_eq!(res[0].size, 1000);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn fetch_draft_attachments_returns_empty_for_wrong_link_id(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d02")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d501")?;
+
+ let res = fetch_draft_attachments_by_draft_id(&pool, wrong_link_id, draft_id).await?;
+
+ assert_eq!(res.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn get_total_attachments_size_returns_correct_sum(pool: Pool<Postgres>) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d501")?;
+
+ let total_size = get_total_attachments_size_by_draft_id(&pool, link_id, draft_id).await?;
+
+ // 1000 + 2000 + 3000 = 6000
+ assert_eq!(total_size, 6000);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn get_total_attachments_size_returns_zero_for_empty_draft(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d502")?;
+
+ let total_size = get_total_attachments_size_by_draft_id(&pool, link_id, draft_id).await?;
+
+ assert_eq!(total_size, 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn get_total_attachments_size_returns_zero_for_wrong_link_id(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d02")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d501")?;
+
+ let total_size = get_total_attachments_size_by_draft_id(&pool, wrong_link_id, draft_id).await?;
+
+ assert_eq!(total_size, 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn delete_draft_attachment_removes_attachment(pool: Pool<Postgres>) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d503")?;
+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000da004")?;
+
+ // Verify attachment exists before delete
+ let before = fetch_draft_attachments_by_draft_id(&pool, link_id, draft_id).await?;
+ assert_eq!(before.len(), 1);
+
+ let rows_affected = delete_draft_attachment(&pool, link_id, draft_id, attachment_id).await?;
+
+ assert_eq!(rows_affected, 1);
+
+ // Verify attachment is deleted
+ let after = fetch_draft_attachments_by_draft_id(&pool, link_id, draft_id).await?;
+ assert_eq!(after.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn delete_draft_attachment_returns_zero_for_wrong_link_id(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d02")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d503")?;
+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000da004")?;
+
+ let rows_affected =
+ delete_draft_attachment(&pool, wrong_link_id, draft_id, attachment_id).await?;
+
+ assert_eq!(rows_affected, 0);
+
+ // Verify attachment still exists with correct link_id
+ let correct_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+ let attachments = fetch_draft_attachments_by_draft_id(&pool, correct_link_id, draft_id).await?;
+ assert_eq!(attachments.len(), 1);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn delete_draft_attachment_returns_zero_for_nonexistent_attachment(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d503")?;
+ let nonexistent_id = Uuid::parse_str("00000000-0000-0000-0000-0000000dffff")?;
+
+ let rows_affected = delete_draft_attachment(&pool, link_id, draft_id, nonexistent_id).await?;
+
+ assert_eq!(rows_affected, 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn insert_draft_attachment_creates_new_attachment(pool: Pool<Postgres>) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d502")?;
+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000da099")?;
+
+ let attachment = service::attachment::AttachmentDraft {
+ id: attachment_id,
+ draft_id,
+ file_name: "new_attachment.pdf".to_string(),
+ content_type: "application/pdf".to_string(),
+ sha: "sha256_new".to_string(),
+ size: 5000,
+ s3_key: "s3://bucket/new_attachment.pdf".to_string(),
+ };
+
+ // Verify no attachments before insert
+ let before = fetch_draft_attachments_by_draft_id(&pool, link_id, draft_id).await?;
+ assert_eq!(before.len(), 0);
+
+ insert_draft_attachment(&pool, link_id, attachment).await?;
+
+ // Verify attachment was created
+ let after = fetch_draft_attachments_by_draft_id(&pool, link_id, draft_id).await?;
+ assert_eq!(after.len(), 1);
+ assert_eq!(after[0].file_name, "new_attachment.pdf");
+ assert_eq!(after[0].size, 5000);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("draft_attachments"))
+)]
+async fn insert_draft_attachment_does_nothing_for_wrong_link_id(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d02")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000d502")?;
+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000da098")?;
+
+ let attachment = service::attachment::AttachmentDraft {
+ id: attachment_id,
+ draft_id,
+ file_name: "should_not_insert.pdf".to_string(),
+ content_type: "application/pdf".to_string(),
+ sha: "sha256_no_insert".to_string(),
+ size: 1234,
+ s3_key: "s3://bucket/should_not_insert.pdf".to_string(),
+ };
+
+ // Insert with wrong link_id (should not insert anything)
+ insert_draft_attachment(&pool, wrong_link_id, attachment).await?;
+
+ // Verify nothing was inserted (check with correct link_id)
+ let correct_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+ let attachments = fetch_draft_attachments_by_draft_id(&pool, correct_link_id, draft_id).await?;
+ assert_eq!(attachments.len(), 0);
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_db_client/src/attachments/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/mod.rs
index 4e019a5465..58e443ddce 100644
--- a/rust/cloud-storage/email_db_client/src/attachments/mod.rs
+++ b/rust/cloud-storage/email_db_client/src/attachments/mod.rs
@@ -1,4 +1,4 @@
+pub mod draft;
pub mod marco;
pub mod provider;
-
pub mod sfs;
diff --git a/rust/cloud-storage/email_db_client/src/messages/get.rs b/rust/cloud-storage/email_db_client/src/messages/get.rs
index a4fd128bd1..fe4bbd7398 100644
--- a/rust/cloud-storage/email_db_client/src/messages/get.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/get.rs
@@ -418,3 +418,27 @@ pub async fn get_message_to_send(
},
))
}
+
+/// Returns `true` if a message with `is_draft = true` exists for the given (link_id, id).
+#[tracing::instrument(skip(pool), err)]
+pub async fn draft_exists_with_id(
+ pool: &PgPool,
+ link_id: Uuid,
+ db_id: Uuid,
+) -> anyhow::Result<bool> {
+ let exists: bool = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS(
+ SELECT 1
+ FROM email_messages
+ WHERE id = $1 AND link_id = $2 AND is_draft = true
+ ) as "exists!"
+ "#,
+ db_id,
+ link_id
+ )
+ .fetch_one(pool)
+ .await?;
+
+ Ok(exists)
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/mod.rs b/rust/cloud-storage/email_db_client/src/messages/mod.rs
index ff13229cee..dae9ac5b36 100644
--- a/rust/cloud-storage/email_db_client/src/messages/mod.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/mod.rs
@@ -6,4 +6,6 @@ pub mod get_simple_messages;
pub mod insert;
pub mod replying_to_id;
pub mod scheduled;
+#[cfg(test)]
+mod test;
pub mod update;
diff --git a/rust/cloud-storage/email_db_client/src/messages/test.rs b/rust/cloud-storage/email_db_client/src/messages/test.rs
new file mode 100644
index 0000000000..b9e6b56a42
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/messages/test.rs
@@ -0,0 +1,73 @@
+use crate::messages::get::draft_exists_with_id;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::types::Uuid;
+use sqlx::{Pool, Postgres};
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("draft_exists_with_id"))
+)]
+async fn draft_exists_with_id_returns_true_for_existing_draft(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
+
+ let exists = draft_exists_with_id(&pool, link_id, draft_id).await?;
+
+ assert!(exists);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("draft_exists_with_id"))
+)]
+async fn draft_exists_with_id_returns_false_for_non_draft_message(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let non_draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e502")?;
+
+ let exists = draft_exists_with_id(&pool, link_id, non_draft_id).await?;
+
+ assert!(!exists);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("draft_exists_with_id"))
+)]
+async fn draft_exists_with_id_returns_false_for_wrong_link_id(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e02")?;
+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
+
+ let exists = draft_exists_with_id(&pool, wrong_link_id, draft_id).await?;
+
+ assert!(!exists);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("draft_exists_with_id"))
+)]
+async fn draft_exists_with_id_returns_false_for_nonexistent_message(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let nonexistent_id = Uuid::parse_str("00000000-0000-0000-0000-00000000efff")?;
+
+ let exists = draft_exists_with_id(&pool, link_id, nonexistent_id).await?;
+
+ assert!(!exists);
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 04e1ab2184..461cbdda34 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -85,6 +85,7 @@ macro_uuid = { path = "../macro_uuid" }
mime_guess = "2.0.5"
model = { path = "../model" }
model-entity = { path = "../model-entity" }
+model_file_type = { path = "../model_file_type" }
model_notifications = { path = "../model_notifications" }
models_email = { path = "../models_email" }
models_opensearch = { path = "../models_opensearch" }
diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
index debfff0030..b5d0b72aaa 100644
--- a/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
@@ -82,12 +82,8 @@ pub async fn handler(
let bucket = &ctx.config.attachment_bucket;
// Create an object key that combines link_id and attachment_id
- let object_key = format!(
- "{}/{}-{}",
- link.id,
- attachment_id,
- db_attachment.filename.clone().unwrap_or_default()
- );
+ let object_key =
+ crate::generate_temp_attachment_s3_key!(link.id, attachment_id, db_attachment.filename);
// check if it exists in s3 already
let exists = ctx
@@ -192,23 +188,15 @@ pub async fn upload_single_attachment(
.db_id
.ok_or_else(|| anyhow::anyhow!("Attachment must have a db_id to generate an object key"))?;
- // Create an object key that combines link_id and attachment_id
- let object_key = format!(
- "{}/{}-{}",
- link_id,
- attachment_id,
- attachment.filename.clone().unwrap_or_default()
- );
-
// Upload the attachment data to S3
match state
.s3_client
- .put(bucket, &object_key, attachment_data.as_slice())
+ .put(bucket, object_key, attachment_data.as_slice())
.await
{
Ok(_) => {
// Generate a presigned URL for the uploaded attachment
- let presigned_url = get_presigned_url(state, &object_key)
+ let presigned_url = get_presigned_url(state, object_key)
.await
.with_context(|| {
format!(
@@ -266,3 +254,15 @@ async fn get_presigned_url(state: &ApiContext, key: &str) -> anyhow::Result<Stri
let signed_url = get_signed_url(&constructed_url, &signed_options)?;
Ok(signed_url)
}
+
+#[macro_export]
+macro_rules! generate_temp_attachment_s3_key {
+ ($link_id:expr, $attachment_id:expr, $filename:expr) => {
+ format!(
+ "temp/{}/{}-{}",
+ $link_id,
+ $attachment_id,
+ $filename.clone().unwrap_or_default()
+ )
+ };
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/add_attachment.rs b/rust/cloud-storage/email_service/src/api/email/drafts/add_attachment.rs
new file mode 100644
index 0000000000..b840188989
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/add_attachment.rs
@@ -0,0 +1,196 @@
+use crate::api::context::ApiContext;
+use crate::generate_attachment_s3_key;
+use axum::extract::{Path, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
+use model::document::FileTypeExt;
+use model::response::ErrorResponse;
+use model_file_type::{ContentType, FileType};
+use models_email::service;
+use models_email::service::link::Link;
+use std::str::FromStr;
+use strum_macros::AsRefStr;
+use thiserror::Error;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum AddDraftAttachmentError {
+ #[error("Validation error: {0}")]
+ Validation(String),
+
+ #[error("Draft not found")]
+ DraftNotFound,
+
+ #[error("Internal error")]
+ InternalError(#[from] anyhow::Error),
+}
+
+impl IntoResponse for AddDraftAttachmentError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ AddDraftAttachmentError::Validation(_) => StatusCode::BAD_REQUEST,
+ AddDraftAttachmentError::DraftNotFound => StatusCode::NOT_FOUND,
+ AddDraftAttachmentError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().as_str(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+pub struct PathParams {
+ pub id: Uuid,
+}
+
+/// The request passed to send a message
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct AddDraftAttachmentRequest {
+ /// The name of the file being uploaded.
+ pub file_name: String,
+ /// The SHA256 hash of the file being uploaded.
+ pub sha: String,
+ /// The size of the file in bytes.
+ pub size: i32,
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct AddDraftAttachmentResponse {
+ /// The ID of the attachment in the database.
+ pub attachment_id: Uuid,
+ /// The URL to upload the attachment to.
+ pub upload_url: String,
+ /// The MIME type of the attachment.
+ pub content_type: String,
+}
+
+/// Add an attachment to a draft.
+#[utoipa::path(
+ post,
+ tag = "Drafts",
+ path = "/email/drafts/{id}/attachments",
+ operation_id = "add_draft_attachment",
+ request_body = AddDraftAttachmentRequest,
+ responses(
+ (status = 201, body = AddDraftAttachmentResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ link: Extension<Link>,
+ Path(PathParams { id: draft_id }): Path<PathParams>,
+ Json(req): Json<AddDraftAttachmentRequest>,
+) -> Result<Json<AddDraftAttachmentResponse>, AddDraftAttachmentError> {
+ validate_request(&ctx, link.id, draft_id, &req).await?;
+
+ let (file_name, file_type) = match FileType::split_suffix_match(req.file_name.as_str()) {
+ Some((file_name, extension)) => {
+ let file_type: Option<FileType> = FileType::from_str(extension).ok();
+ (file_name.to_string(), file_type)
+ }
+ None => (req.file_name, None),
+ };
+
+ let content_type: ContentType = file_type.into();
+
+ let attachment_id = macro_uuid::generate_uuid_v7();
+ let s3_key = generate_attachment_s3_key!(draft_id, attachment_id);
+ let mime_type = content_type.mime_type().to_string();
+
+ let attachment = service::attachment::AttachmentDraft {
+ id: attachment_id,
+ draft_id,
+ file_name: file_name.clone(),
+ content_type: mime_type.clone(),
+ sha: req.sha.clone(),
+ size: req.size,
+ s3_key: s3_key.clone(),
+ };
+
+ // insert attachment into db
+ email_db_client::attachments::draft::insert_draft_attachment(&ctx.db, link.id, attachment)
+ .await?;
+
+ // generate presigned url
+ let upload_url = ctx
+ .s3_client
+ .put_presigned_url(&ctx.config.attachment_bucket, &s3_key, &req.sha, &mime_type)
+ .await?;
+
+ Ok(Json(AddDraftAttachmentResponse {
+ attachment_id,
+ upload_url,
+ content_type: mime_type.to_string(),
+ }))
+}
+
+async fn validate_request(
+ ctx: &ApiContext,
+ link_id: Uuid,
+ draft_id: Uuid,
+ req: &AddDraftAttachmentRequest,
+) -> Result<(), AddDraftAttachmentError> {
+ if req.file_name.trim().is_empty() {
+ return Err(AddDraftAttachmentError::Validation(
+ "File name cannot be empty".to_string(),
+ ));
+ }
+ if req.file_name.len() > 255 {
+ return Err(AddDraftAttachmentError::Validation(
+ "File name must be less than 256 characters".to_string(),
+ ));
+ }
+ if req.sha.len() != 64 || !req.sha.chars().all(|c| c.is_ascii_hexdigit()) {
+ return Err(AddDraftAttachmentError::Validation(
+ "SHA256 must be 64 hex characters".to_string(),
+ ));
+ }
+ if req.size <= 0 {
+ return Err(AddDraftAttachmentError::Validation(
+ "File size must be greater than 0".to_string(),
+ ));
+ }
+
+ // 25MB total encoded limit enforced by Gmail. Base64 adds ~33% overhead.
+ // 25 / 1.33 = ~18.8MB. We use 18,000,000 bytes as the safe raw limit.
+ const MAX_RAW_TOTAL_SIZE_BYTES: i32 = 18_000_000;
+
+ if req.size > MAX_RAW_TOTAL_SIZE_BYTES {
+ return Err(AddDraftAttachmentError::Validation(format!(
+ "File size ({} bytes) exceeds the safe limit for email delivery (18MB).",
+ req.size
+ )));
+ }
+
+ // ensure draft exists. doing this late as possible in validation to avoid unnecessary db queries
+ if !email_db_client::messages::get::draft_exists_with_id(&ctx.db, link_id, draft_id).await? {
+ return Err(AddDraftAttachmentError::DraftNotFound);
+ }
+
+ let current_total_size =
+ email_db_client::attachments::draft::get_total_attachments_size_by_draft_id(
+ &ctx.db, link_id, draft_id,
+ )
+ .await?;
+
+ if (current_total_size + req.size) > MAX_RAW_TOTAL_SIZE_BYTES {
+ return Err(AddDraftAttachmentError::Validation(format!(
+ "Combined attachments size exceeds the safe limit for email delivery (18MB). Current total: {} bytes.",
+ current_total_size
+ )));
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/delete.rs b/rust/cloud-storage/email_service/src/api/email/drafts/delete.rs
index 0d1300e89b..120da8dca9 100644
--- a/rust/cloud-storage/email_service/src/api/email/drafts/delete.rs
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/delete.rs
@@ -3,6 +3,7 @@ use axum::Extension;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
+use email_service::util::gmail::send::cleanup_draft_attachments;
use model::response::{EmptyResponse, ErrorResponse};
use models_email::service::link::Link;
use models_opensearch::SearchEntityType;
@@ -84,6 +85,13 @@ pub async fn handler(
return Err(DeleteDraftError::NotADraft(draft_id));
}
+ // Fetch draft attachments before deletion so we can clean up S3
+ let draft_attachments =
+ email_db_client::attachments::draft::fetch_draft_attachments_by_draft_id(
+ &ctx.db, link.id, draft_id,
+ )
+ .await?;
+
let mut tx = ctx.db.begin().await?;
let result = email_db_client::messages::delete::delete_message_with_tx(
@@ -97,6 +105,25 @@ pub async fn handler(
Ok(deleted_thread) => {
tx.commit().await?;
+ // cleanup attachments in the background
+ if !draft_attachments.is_empty() {
+ let db = ctx.db.clone();
+ let s3_client = ctx.s3_client.clone();
+ let bucket = ctx.config.attachment_bucket.clone();
+ let link_id = link.id;
+ tokio::spawn(async move {
+ cleanup_draft_attachments(
+ db,
+ &s3_client,
+ bucket,
+ link_id,
+ draft_id,
+ draft_attachments,
+ )
+ .await;
+ });
+ }
+
if let Some(thread_id) = deleted_thread {
tokio::spawn(async move {
let _ = ctx
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
index d18f895502..b4a7206a40 100644
--- a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
@@ -1,5 +1,7 @@
+pub(crate) mod add_attachment;
pub(crate) mod create;
pub(crate) mod delete;
+pub(crate) mod remove_attachment;
use axum::Router;
use axum::routing::{delete, post};
@@ -10,8 +12,21 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
.route("/", post(create::handler))
.route("/:id", delete(delete::handler))
+ .route("/:id/attachments", post(add_attachment::handler))
+ .route(
+ "/:id/attachments/:attachment_id",
+ delete(remove_attachment::handler),
+ )
.layer(axum::middleware::from_fn_with_state(
state.email_service,
crate::api::middleware::link::attach_link_context,
))
}
+
+/// generate an S3 key for an attachment based on the draft_id and attachment_id.
+#[macro_export]
+macro_rules! generate_attachment_s3_key {
+ ($draft_id:expr, $attachment_id:expr) => {
+ format!("draft/{}/{}", $draft_id, $attachment_id)
+ };
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/remove_attachment.rs b/rust/cloud-storage/email_service/src/api/email/drafts/remove_attachment.rs
new file mode 100644
index 0000000000..8049fffee9
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/remove_attachment.rs
@@ -0,0 +1,97 @@
+use crate::api::context::ApiContext;
+use crate::generate_attachment_s3_key;
+use axum::extract::{Path, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
+use model::response::{EmptyResponse, ErrorResponse};
+use models_email::service::link::Link;
+use strum_macros::AsRefStr;
+use thiserror::Error;
+use uuid::Uuid;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum RemoveDraftAttachmentError {
+ #[error("Draft not found")]
+ DraftNotFound,
+
+ #[error("Attachment not found")]
+ AttachmentNotFound,
+
+ #[error("Internal error")]
+ InternalError(#[from] anyhow::Error),
+}
+
+impl IntoResponse for RemoveDraftAttachmentError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ RemoveDraftAttachmentError::DraftNotFound
+ | RemoveDraftAttachmentError::AttachmentNotFound => StatusCode::NOT_FOUND,
+ RemoveDraftAttachmentError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().as_str(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+pub struct PathParams {
+ pub id: Uuid,
+ pub attachment_id: Uuid,
+}
+
+/// Remove an attachment from a draft.
+#[utoipa::path(
+ delete,
+ tag = "Drafts",
+ path = "/email/drafts/{id}/attachments/{attachment_id}",
+ operation_id = "remove_draft_attachment",
+ responses(
+ (status = 201, body = EmptyResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ link: Extension<Link>,
+ Path(PathParams {
+ id: draft_id,
+ attachment_id,
+ }): Path<PathParams>,
+) -> Result<impl IntoResponse, RemoveDraftAttachmentError> {
+ // ensure draft exists
+ if !email_db_client::messages::get::draft_exists_with_id(&ctx.db, link.id, draft_id).await? {
+ return Err(RemoveDraftAttachmentError::DraftNotFound);
+ }
+
+ let rows_affected = email_db_client::attachments::draft::delete_draft_attachment(
+ &ctx.db,
+ link.id,
+ draft_id,
+ attachment_id,
+ )
+ .await?;
+
+ if rows_affected == 0 {
+ return Err(RemoveDraftAttachmentError::AttachmentNotFound);
+ }
+
+ let s3_key = generate_attachment_s3_key!(draft_id, attachment_id);
+
+ // will not error if attachment does not exist in S3
+ ctx.s3_client
+ .delete(&ctx.config.attachment_bucket, &s3_key)
+ .await?;
+
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/send.rs b/rust/cloud-storage/email_service/src/api/email/messages/send.rs
index e5b91e3f60..f25febdcd0 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/send.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/send.rs
@@ -36,32 +36,45 @@ pub enum SendMessageError {
#[error("Failed to send message via Gmail")]
GmailSendError(#[from] anyhow::Error),
- #[error("A database transaction error occurred")]
- TransactionError(#[from] sqlx::Error),
+ #[error("Failed to fetch attachments for message: {0}")]
+ AttachmentError(anyhow::Error),
+
+ #[error("Internal error")]
+ InternalError(#[from] sqlx::Error),
}
impl IntoResponse for SendMessageError {
fn into_response(self) -> Response {
let status_code = match &self {
SendMessageError::Validation(e) => e.status_code(),
- SendMessageError::SenderContactNotFound => StatusCode::INTERNAL_SERVER_ERROR,
SendMessageError::Base64DecodeError(_) | SendMessageError::Utf8Error(_) => {
StatusCode::BAD_REQUEST
}
- SendMessageError::GmailSendError(_) | SendMessageError::TransactionError(_) => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
+ SendMessageError::SenderContactNotFound
+ | SendMessageError::GmailSendError(_)
+ | SendMessageError::AttachmentError(_)
+ | SendMessageError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
- if status_code.is_server_error() {
- tracing::error!(
- nested_error = ?self,
- error_type = "SendMessageError",
- variant = self.as_ref(),
- "Internal server error");
- }
+ let error_message = match &self {
+ SendMessageError::AttachmentError(_) => {
+ "Failed to fetch attachments for message".to_string()
+ }
+ SendMessageError::Validation(_)
+ | SendMessageError::SenderContactNotFound
+ | SendMessageError::Base64DecodeError(_)
+ | SendMessageError::Utf8Error(_)
+ | SendMessageError::GmailSendError(_)
+ | SendMessageError::InternalError(_) => self.to_string(),
+ };
- (status_code, self.to_string()).into_response()
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: error_message.as_str(),
+ }),
+ )
+ .into_response()
}
}
@@ -91,7 +104,7 @@ pub struct SendMessageResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, gmail_token, request_body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, user_context, gmail_token, request_body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
pub async fn send_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
@@ -141,6 +154,17 @@ pub async fn send_handler(
// processed message post-send
let before_send_ts = Utc::now();
+ // Include attachments for message
+ let db_attachments = send::fetch_and_attach_draft_attachments(
+ &ctx.db,
+ &ctx.s3_client,
+ ctx.config.attachment_bucket.as_str(),
+ &link,
+ &mut message_to_send,
+ )
+ .await
+ .map_err(SendMessageError::AttachmentError)?;
+
ctx.gmail_client
.send_message(
gmail_token.as_str(),
@@ -159,6 +183,25 @@ pub async fn send_handler(
match result {
Ok(_) => {
tx.commit().await?;
+
+ // Cleanup attachments in the background
+ if let (Some(draft_id), Some(attachments)) = (message_to_send.db_id, db_attachments) {
+ let db = ctx.db.clone();
+ let bucket = ctx.config.attachment_bucket.clone();
+ let link_id = link.id;
+ tokio::spawn(async move {
+ send::cleanup_draft_attachments(
+ db,
+ &ctx.s3_client,
+ bucket,
+ link_id,
+ draft_id,
+ attachments,
+ )
+ .await;
+ });
+ }
+
Ok((
StatusCode::CREATED,
Json(SendMessageResponse {
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index 946dda5eee..134dd7df20 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -3,6 +3,9 @@ use crate::api::email::attachments::get_document_id::GetAttachmentDocumentIDResp
use crate::api::email::backfill::cancel::CancelBackfillParams;
use crate::api::email::backfill::get::{GetActiveBackfillJobResponse, GetBackfillJobResponse};
use crate::api::email::contacts::list::ListContactsResponse;
+use crate::api::email::drafts::add_attachment::{
+ AddDraftAttachmentRequest, AddDraftAttachmentResponse,
+};
use crate::api::email::drafts::create::{CreateDraftRequest, CreateDraftResponse};
use crate::api::email::init::InitResponse;
use crate::api::email::labels::create::CreateLabelRequest;
@@ -44,6 +47,8 @@ use utoipa::OpenApi;
email::init::handler,
email::drafts::create::handler,
email::drafts::delete::handler,
+ email::drafts::add_attachment::handler,
+ email::drafts::remove_attachment::handler,
email::messages::get::handler,
email::messages::get::batch_handler,
email::messages::labels::handler,
@@ -73,6 +78,8 @@ use utoipa::OpenApi;
// Draft types
CreateDraftRequest,
CreateDraftResponse,
+ AddDraftAttachmentRequest,
+ AddDraftAttachmentResponse,
// Init types
InitResponse,
// Label types
diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
index a9bbf73bf3..20125790f8 100644
--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
@@ -22,6 +22,8 @@ async fn main() -> anyhow::Result<()> {
.load()
.await;
+ let s3_client = s3_client::S3::new(aws_sdk_s3::Client::new(&aws_config));
+
let secretsmanager_client = secretsmanager_client::SecretsManager::new(
aws_sdk_secretsmanager::Client::new(&aws_config),
);
@@ -334,6 +336,8 @@ async fn main() -> anyhow::Result<()> {
let gmail_client_scheduled = gmail_client.clone();
let auth_service_client_scheduled = auth_service_client.clone();
let redis_client_scheduled = redis_client.clone();
+ let s3_client_scheduled = s3_client.clone();
+ let attachment_bucket_scheduled = config.attachment_bucket.clone();
// send scheduled emails
tokio::spawn(async move {
email_service::pubsub::scheduled::worker::run_worker(
@@ -342,6 +346,8 @@ async fn main() -> anyhow::Result<()> {
gmail_client_scheduled,
auth_service_client_scheduled,
redis_client_scheduled,
+ s3_client_scheduled,
+ attachment_bucket_scheduled,
)
.await;
});
diff --git a/rust/cloud-storage/email_service/src/pubsub/scheduled/context.rs b/rust/cloud-storage/email_service/src/pubsub/scheduled/context.rs
index 8e5f25e1e0..0f0ce1febf 100644
--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/context.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/context.rs
@@ -10,4 +10,6 @@ pub struct ScheduledContext {
pub gmail_client: GmailClient,
pub auth_service_client: AuthServiceClient,
pub redis_client: RedisClient,
+ pub s3_client: s3_client::S3,
+ pub attachment_bucket: String,
}
diff --git a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
index 9822e6a716..6f97e2d51b 100644
--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
@@ -1,6 +1,8 @@
use crate::pubsub::scheduled::context::ScheduledContext;
use crate::pubsub::util::{fetch_access_token_for_link, fetch_link};
-use crate::util::gmail::send::generate_email_threading_headers;
+use crate::util::gmail::send::{
+ cleanup_draft_attachments, fetch_and_attach_draft_attachments, generate_email_threading_headers,
+};
use anyhow::Context;
use email_db_client::messages::scheduled::get_scheduled_message;
use models_email::service::message::MessageToSend;
@@ -59,6 +61,16 @@ pub async fn process_message(
generate_email_threading_headers(&ctx.db, message_to_send.replying_to_id, data.link_id)
.await;
+ // Include attachments for message
+ let db_attachments = fetch_and_attach_draft_attachments(
+ &ctx.db,
+ &ctx.s3_client,
+ ctx.attachment_bucket.as_str(),
+ &link,
+ &mut message_to_send,
+ )
+ .await?;
+
// send message to gmail api
ctx.gmail_client
.send_message(
@@ -89,6 +101,26 @@ pub async fn process_message(
.commit()
.await
.context("Failed to commit transaction")?;
+
+ // Cleanup attachments in the background after successful send
+ if let (Some(draft_id), Some(attachments)) = (message_to_send.db_id, db_attachments)
+ {
+ let db = ctx.db.clone();
+ let s3_client = ctx.s3_client.clone();
+ let bucket = ctx.attachment_bucket.clone();
+ let link_id = link.id;
+ tokio::spawn(async move {
+ cleanup_draft_attachments(
+ db,
+ &s3_client,
+ bucket,
+ link_id,
+ draft_id,
+ attachments,
+ )
+ .await;
+ });
+ }
}
Err(e) => {
if let Err(rollback_err) = tx.as_mut().rollback().await {
diff --git a/rust/cloud-storage/email_service/src/pubsub/scheduled/worker.rs b/rust/cloud-storage/email_service/src/pubsub/scheduled/worker.rs
index b4ead0133b..496fb972e0 100644
--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/worker.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/worker.rs
@@ -12,6 +12,8 @@ pub async fn run_worker(
gmail_client: gmail_client::GmailClient,
auth_service_client: AuthServiceClient,
redis_client: RedisClient,
+ s3_client: s3_client::S3,
+ attachment_bucket: String,
) {
let ctx = ScheduledContext {
db,
@@ -19,6 +21,8 @@ pub async fn run_worker(
gmail_client,
auth_service_client,
redis_client,
+ s3_client,
+ attachment_bucket,
};
loop {
let worker_result = tokio::spawn({
diff --git a/rust/cloud-storage/email_service/src/util/gmail/send.rs b/rust/cloud-storage/email_service/src/util/gmail/send.rs
index 1a98368993..ad701b807f 100644
--- a/rust/cloud-storage/email_service/src/util/gmail/send.rs
+++ b/rust/cloud-storage/email_service/src/util/gmail/send.rs
@@ -1,3 +1,7 @@
+use anyhow::Context;
+use models_email::service::attachment::{AttachmentDraft, AttachmentToSend};
+use models_email::service::link::Link;
+use models_email::service::message;
use sqlx::PgPool;
use uuid::Uuid;
@@ -49,3 +53,92 @@ pub async fn generate_email_threading_headers(
(None, None)
}
}
+
+/// Fetch any attachments the user previously added to the draft from s3 and attach them to the message
+/// being sent. Return the attachment metadata so we can use it to delete the attachments from s3
+/// after the message is sent.
+#[tracing::instrument(
+ skip(db, s3_client, message_to_send),
+ fields(message_db_id = ?message_to_send.db_id)
+)]
+pub async fn fetch_and_attach_draft_attachments(
+ db: &sqlx::PgPool,
+ s3_client: &s3_client::S3,
+ bucket: &str,
+ link: &Link,
+ message_to_send: &mut message::MessageToSend,
+) -> anyhow::Result<Option<Vec<AttachmentDraft>>> {
+ if let Some(db_id) = message_to_send.db_id {
+ let db_attachments =
+ email_db_client::attachments::draft::fetch_draft_attachments_by_draft_id(
+ db, link.id, db_id,
+ )
+ .await
+ .context("unable to fetch draft attachments from database")?;
+
+ if !db_attachments.is_empty() {
+ let fetch_futures = db_attachments.iter().map(|db_attachment| async move {
+ let attachment_data = s3_client
+ .get(bucket, &db_attachment.s3_key)
+ .await
+ .with_context(|| {
+ format!(
+ "Failed to fetch attachment from S3 (key: {})",
+ db_attachment.s3_key
+ )
+ })?;
+
+ Ok::<AttachmentToSend, anyhow::Error>(AttachmentToSend {
+ file_name: db_attachment.file_name.clone(),
+ content_type: db_attachment.content_type.clone(),
+ data: attachment_data,
+ })
+ });
+
+ let attachments_to_send = futures::future::try_join_all(fetch_futures).await?;
+
+ message_to_send.attachments = Some(attachments_to_send);
+ return Ok(Some(db_attachments));
+ }
+ }
+ Ok(None)
+}
+
+#[tracing::instrument(skip(db, s3_client))]
+pub async fn cleanup_draft_attachments(
+ db: sqlx::PgPool,
+ s3_client: &s3_client::S3,
+ bucket: String,
+ link_id: Uuid,
+ draft_id: Uuid,
+ attachments: Vec<AttachmentDraft>,
+) {
+ for attachment in attachments {
+ // Delete from S3
+ if let Err(e) = s3_client.delete(&bucket, &attachment.s3_key).await {
+ tracing::error!(
+ error = ?e,
+ s3_key = %attachment.s3_key,
+ "Failed to delete draft attachment from S3 during cleanup; skipping database deletion"
+ );
+ continue;
+ }
+
+ // Delete from DB
+ if let Err(e) = email_db_client::attachments::draft::delete_draft_attachment(
+ &db,
+ link_id,
+ draft_id,
+ attachment.id,
+ )
+ .await
+ {
+ tracing::error!(
+ error = ?e,
+ attachment_id = attachment.id.to_string(),
+ draft_id = draft_id.to_string(),
+ "Failed to delete draft attachment from database during cleanup"
+ );
+ }
+ }
+}
diff --git a/rust/cloud-storage/gmail_client/src/messages.rs b/rust/cloud-storage/gmail_client/src/messages.rs
index 4b274cbf05..183c79004b 100644
--- a/rust/cloud-storage/gmail_client/src/messages.rs
+++ b/rust/cloud-storage/gmail_client/src/messages.rs
@@ -171,10 +171,15 @@ pub(crate) async fn send_message(
builder = builder.html_body(html_body);
}
- let email_string = builder
- .write_to_string()
- .context("building message error")?;
- let base64_email_content = URL_SAFE_NO_PAD.encode(email_string.as_bytes());
+ if let Some(attachments) = message.attachments.take() {
+ for att in attachments {
+ builder = builder.attachment(att.content_type, att.file_name, att.data);
+ }
+ }
+
+ let email_bytes = builder.write_to_vec().context("building message error")?;
+
+ let base64_email_content = URL_SAFE_NO_PAD.encode(email_bytes);
let payload = SendMessagePayload {
raw: base64_email_content,
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260106210823_email_attachments_drafts.sql b/rust/cloud-storage/macro_db_client/migrations/20260106210823_email_attachments_drafts.sql
new file mode 100644
index 0000000000..4afcaae1f0
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260106210823_email_attachments_drafts.sql
@@ -0,0 +1,13 @@
+CREATE TABLE email_attachments_drafts
+(
+ id UUID PRIMARY KEY,
+ draft_id UUID NOT NULL REFERENCES email_messages (id) ON DELETE CASCADE,
+ file_name TEXT NOT NULL,
+ content_type TEXT NOT NULL,
+ sha TEXT NOT NULL,
+ size INTEGER NOT NULL,
+ s3_key TEXT NOT NULL UNIQUE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX idx_email_attachments_drafts_message_db_id ON email_attachments_drafts (draft_id);
\ No newline at end of file
diff --git a/rust/cloud-storage/models_email/src/email/db/attachment.rs b/rust/cloud-storage/models_email/src/email/db/attachment.rs
index 3c578f0af6..94c1fd9729 100644
--- a/rust/cloud-storage/models_email/src/email/db/attachment.rs
+++ b/rust/cloud-storage/models_email/src/email/db/attachment.rs
@@ -48,3 +48,35 @@ impl From<crate::service::attachment::AttachmentSfs> for AttachmentSfs {
}
}
}
+
+#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
+pub struct AttachmentDraft {
+ /// Unique identifier for the attachment.
+ pub id: Uuid,
+ /// The ID of the draft message this attachment belongs to.
+ pub draft_id: Uuid,
+ /// Original file name of the attachment.
+ pub file_name: String,
+ /// MIME type of the attachment (e.g., "application/pdf", "image/png").
+ pub content_type: String,
+ /// SHA-256 hash of the file content for integrity verification.
+ pub sha: String,
+ /// File size in bytes.
+ pub size: i32,
+ /// S3 object key where the attachment content is stored.
+ pub s3_key: String,
+}
+
+impl From<crate::service::attachment::AttachmentDraft> for AttachmentDraft {
+ fn from(service: crate::service::attachment::AttachmentDraft) -> Self {
+ Self {
+ id: service.id,
+ draft_id: service.draft_id,
+ file_name: service.file_name,
+ content_type: service.content_type,
+ sha: service.sha,
+ size: service.size,
+ s3_key: service.s3_key,
+ }
+ }
+}
diff --git a/rust/cloud-storage/models_email/src/email/service/attachment.rs b/rust/cloud-storage/models_email/src/email/service/attachment.rs
index 56b75bdf3e..ecf4ad7fd1 100644
--- a/rust/cloud-storage/models_email/src/email/service/attachment.rs
+++ b/rust/cloud-storage/models_email/src/email/service/attachment.rs
@@ -86,3 +86,43 @@ pub enum AttachmentUploadDestination {
Dss,
Sfs,
}
+
+#[derive(Debug, Clone)]
+pub struct AttachmentDraft {
+ /// Unique identifier for the attachment.
+ pub id: Uuid,
+ /// The ID of the draft message this attachment belongs to.
+ pub draft_id: Uuid,
+ /// Original file name of the attachment.
+ pub file_name: String,
+ /// MIME type of the attachment (e.g., "application/pdf", "image/png").
+ pub content_type: String,
+ /// SHA-256 hash of the file content for integrity verification.
+ pub sha: String,
+ /// File size in bytes.
+ pub size: i32,
+ /// S3 object key where the attachment content is stored.
+ pub s3_key: String,
+}
+
+impl From<crate::db::attachment::AttachmentDraft> for AttachmentDraft {
+ fn from(db: crate::db::attachment::AttachmentDraft) -> Self {
+ Self {
+ id: db.id,
+ draft_id: db.draft_id,
+ file_name: db.file_name,
+ content_type: db.content_type,
+ sha: db.sha,
+ size: db.size,
+ s3_key: db.s3_key,
+ }
+ }
+}
+
+/// The attachment data we need to include when sending a message to a provider.
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct AttachmentToSend {
+ pub file_name: String,
+ pub content_type: String,
+ pub data: Vec<u8>,
+}
diff --git a/rust/cloud-storage/models_email/src/email/service/message.rs b/rust/cloud-storage/models_email/src/email/service/message.rs
index db2055fe66..970908ef59 100644
--- a/rust/cloud-storage/models_email/src/email/service/message.rs
+++ b/rust/cloud-storage/models_email/src/email/service/message.rs
@@ -2,7 +2,7 @@ use crate::db;
use crate::email::service::address::ContactInfo;
use crate::email::service::attachment::Attachment;
use crate::email::service::label::{LabelInfo, system_labels};
-use crate::service::attachment::AttachmentMacro;
+use crate::service::attachment::{AttachmentMacro, AttachmentToSend};
use crate::service::body_parsing::body_parsed::{
get_body_parsed_for_message, get_body_parsed_linkless_for_message,
};
@@ -275,7 +275,7 @@ pub struct MessageToSend {
pub body_text: Option<String>,
pub body_html: Option<String>,
pub body_macro: Option<String>,
- pub attachments: Option<Vec<Attachment>>,
+ pub attachments: Option<Vec<AttachmentToSend>>,
pub attachments_macro: Option<Vec<AttachmentMacro>>,
pub headers_json: Option<JsonValue>,
pub send_time: Option<DateTime<Utc>>,
diff --git a/rust/cloud-storage/s3_client/Cargo.toml b/rust/cloud-storage/s3_client/Cargo.toml
index 2e07e2ae83..2a546e054e 100644
--- a/rust/cloud-storage/s3_client/Cargo.toml
+++ b/rust/cloud-storage/s3_client/Cargo.toml
@@ -7,4 +7,6 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
aws-sdk-s3 = { workspace = true }
+base64 = { workspace = true }
+hex = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/s3_client/src/lib.rs b/rust/cloud-storage/s3_client/src/lib.rs
index e655ce32ad..a168499350 100644
--- a/rust/cloud-storage/s3_client/src/lib.rs
+++ b/rust/cloud-storage/s3_client/src/lib.rs
@@ -40,6 +40,18 @@ impl S3 {
put::put(&self.inner, bucket, key, content).await
}
+ /// Generates a presigned URL for uploading a file to a bucket.
+ #[tracing::instrument(skip(self))]
+ pub async fn put_presigned_url(
+ &self,
+ bucket: &str,
+ key: &str,
+ sha: &str,
+ mime_type: &str,
+ ) -> anyhow::Result<String> {
+ put::put_presigned_url(&self.inner, bucket, key, sha, mime_type).await
+ }
+
/// Checks if a given key exists in the bucket.
#[tracing::instrument(skip(self))]
pub async fn exists(&self, bucket: &str, key: &str) -> anyhow::Result<bool> {
diff --git a/rust/cloud-storage/s3_client/src/put.rs b/rust/cloud-storage/s3_client/src/put.rs
index 3d843d7f18..4c7943fc63 100644
--- a/rust/cloud-storage/s3_client/src/put.rs
+++ b/rust/cloud-storage/s3_client/src/put.rs
@@ -1,3 +1,9 @@
+use anyhow::Context;
+use aws_sdk_s3::presigning::PresigningConfig;
+use base64::Engine;
+use std::time::Duration;
+use tracing::instrument;
+
#[tracing::instrument(skip(client))]
pub async fn put(
client: &aws_sdk_s3::Client,
@@ -15,3 +21,33 @@ pub async fn put(
.await?;
Ok(())
}
+
+/// generates a presigned URL for uploading a file to a bucket
+#[instrument(skip(client))]
+pub async fn put_presigned_url(
+ client: &aws_sdk_s3::Client,
+ bucket: &str,
+ key: &str,
+ sha: &str,
+ mime_type: &str,
+) -> anyhow::Result<String> {
+ // Allows the app 2 minutes to grab the document
+ let expiry_duration = Duration::from_secs(2 * 60);
+
+ // Convert the hex SHA256 hash to binary
+ let payload_sha256_bytes = hex::decode(sha).context("able to decode hex sha")?;
+ // Encode the binary hash into base64
+ let base64_encoded_sha = base64::engine::general_purpose::STANDARD.encode(payload_sha256_bytes);
+
+ // Generate the presigned URL.
+ let presigned_url = client
+ .put_object()
+ .bucket(bucket)
+ .key(key)
+ .content_type(mime_type)
+ .checksum_sha256(base64_encoded_sha)
+ .presigned(PresigningConfig::expires_in(expiry_duration)?)
+ .await?;
+
+ Ok(presigned_url.uri().to_string())
+}
diff --git a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip
index f50b0e414e..ef7b364caa 100644
Binary files a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip differ