Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): support shared/delegated inboxes across reads and writes (#3717)
gbirman9600410eea27
diff --git a/rust/cloud-storage/.sqlx/query-c1c20d7762c16e50a8ec9d7fec86b41cb97712cdfb74480980aa7f138c8ff20e.json b/rust/cloud-storage/.sqlx/query-2c1df8ba2035cc1f63f9d566e8ac763f4d0b5e28370570971935d29237a0211a.jsonsimilarity index 80%rename from rust/cloud-storage/.sqlx/query-c1c20d7762c16e50a8ec9d7fec86b41cb97712cdfb74480980aa7f138c8ff20e.jsonrename to rust/cloud-storage/.sqlx/query-2c1df8ba2035cc1f63f9d566e8ac763f4d0b5e28370570971935d29237a0211a.jsonindex 20f461611a..4e5c86734c 100644--- a/rust/cloud-storage/.sqlx/query-c1c20d7762c16e50a8ec9d7fec86b41cb97712cdfb74480980aa7f138c8ff20e.json+++ b/rust/cloud-storage/.sqlx/query-2c1df8ba2035cc1f63f9d566e8ac763f4d0b5e28370570971935d29237a0211a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.created_at, l.updated_at\n FROM email_threads t\n JOIN email_links l ON l.id = t.link_id\n WHERE t.id = $1 AND l.fusionauth_user_id = $2\n ",+ "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.created_at, l.updated_at\n FROM email_threads t\n JOIN email_links l ON l.id = t.link_id\n WHERE t.id = $1\n AND (\n l.macro_id = $2\n OR EXISTS (\n SELECT 1 FROM macro_user_links mul\n WHERE mul.child_macro_id = l.macro_id AND mul.primary_macro_id = $2\n )\n )\n ","describe": {"columns": [{@@ -70,5 +70,5 @@false]},- "hash": "c1c20d7762c16e50a8ec9d7fec86b41cb97712cdfb74480980aa7f138c8ff20e"+ "hash": "2c1df8ba2035cc1f63f9d566e8ac763f4d0b5e28370570971935d29237a0211a"}diff --git a/rust/cloud-storage/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json b/rust/cloud-storage/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.jsondeleted file mode 100644index 44d3a67e72..0000000000--- a/rust/cloud-storage/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND l.macro_id = $2\n ) AS \"exists!\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "exists!",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60"-}diff --git a/rust/cloud-storage/.sqlx/query-392aaf2a2b9c1d3b0a30fdaed7107209446a4893f7f44b1d5c19cfa9fd387695.json b/rust/cloud-storage/.sqlx/query-392aaf2a2b9c1d3b0a30fdaed7107209446a4893f7f44b1d5c19cfa9fd387695.jsonnew file mode 100644index 0000000000..5bf800b64e--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-392aaf2a2b9c1d3b0a30fdaed7107209446a4893f7f44b1d5c19cfa9fd387695.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND (\n l.macro_id = $2\n OR EXISTS (\n SELECT 1\n FROM public.macro_user_links mul\n WHERE mul.child_macro_id = l.macro_id\n AND mul.primary_macro_id = $2\n )\n )\n ) AS \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "392aaf2a2b9c1d3b0a30fdaed7107209446a4893f7f44b1d5c19cfa9fd387695"+}diff --git a/rust/cloud-storage/.sqlx/query-cd1b9c3eb3d9efe710902559ff97a12bd84caee88e8fb5d9f6f8ae2aa4dc06ec.json b/rust/cloud-storage/.sqlx/query-a81b373188c98bdfa52a878a659909f73796aef0302323f7930fe4d17ccfe6af.jsonsimilarity index 80%rename from rust/cloud-storage/.sqlx/query-cd1b9c3eb3d9efe710902559ff97a12bd84caee88e8fb5d9f6f8ae2aa4dc06ec.jsonrename to rust/cloud-storage/.sqlx/query-a81b373188c98bdfa52a878a659909f73796aef0302323f7930fe4d17ccfe6af.jsonindex 160af11a14..c03715ba1e 100644--- a/rust/cloud-storage/.sqlx/query-cd1b9c3eb3d9efe710902559ff97a12bd84caee88e8fb5d9f6f8ae2aa4dc06ec.json+++ b/rust/cloud-storage/.sqlx/query-a81b373188c98bdfa52a878a659909f73796aef0302323f7930fe4d17ccfe6af.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.created_at, l.updated_at\n FROM email_messages m\n JOIN email_links l ON l.id = m.link_id\n WHERE m.id = $1 AND l.fusionauth_user_id = $2\n ",+ "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.created_at, l.updated_at\n FROM email_messages m\n JOIN email_links l ON l.id = m.link_id\n WHERE m.id = $1\n AND (\n l.macro_id = $2\n OR EXISTS (\n SELECT 1 FROM macro_user_links mul\n WHERE mul.child_macro_id = l.macro_id AND mul.primary_macro_id = $2\n )\n )\n ","describe": {"columns": [{@@ -70,5 +70,5 @@false]},- "hash": "cd1b9c3eb3d9efe710902559ff97a12bd84caee88e8fb5d9f6f8ae2aa4dc06ec"+ "hash": "a81b373188c98bdfa52a878a659909f73796aef0302323f7930fe4d17ccfe6af"}diff --git a/rust/cloud-storage/.sqlx/query-ac30668bed9f5d19db9e0a0cacda6ee156a13fae34c5ccb129794c9d16e95e10.json b/rust/cloud-storage/.sqlx/query-ac30668bed9f5d19db9e0a0cacda6ee156a13fae34c5ccb129794c9d16e95e10.jsondeleted file mode 100644index b0fb258d2d..0000000000--- a/rust/cloud-storage/.sqlx/query-ac30668bed9f5d19db9e0a0cacda6ee156a13fae34c5ccb129794c9d16e95e10.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT l.macro_id\n FROM email_threads et\n JOIN email_links l ON et.link_id = l.id\n WHERE et.id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "macro_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false- ]- },- "hash": "ac30668bed9f5d19db9e0a0cacda6ee156a13fae34c5ccb129794c9d16e95e10"-}diff --git a/rust/cloud-storage/.sqlx/query-b39489dade5d8c0fd17bacd9413969f502fe88c58012d041623d1689aa8cbbf1.json b/rust/cloud-storage/.sqlx/query-b39489dade5d8c0fd17bacd9413969f502fe88c58012d041623d1689aa8cbbf1.jsondeleted file mode 100644index 871b5047f5..0000000000--- a/rust/cloud-storage/.sqlx/query-b39489dade5d8c0fd17bacd9413969f502fe88c58012d041623d1689aa8cbbf1.json+++ /dev/null@@ -1,73 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, created_at, updated_at\n FROM email_links\n WHERE fusionauth_user_id = $1\n ORDER BY created_at DESC\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "macro_id",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "fusionauth_user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "email_address",- "type_info": "Varchar"- },- {- "ordinal": 4,- "name": "provider: _",- "type_info": {- "Custom": {- "name": "email_user_provider_enum",- "kind": {- "Enum": [- "GMAIL"- ]- }- }- }- },- {- "ordinal": 5,- "name": "is_sync_active",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "updated_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- false,- false- ]- },- "hash": "b39489dade5d8c0fd17bacd9413969f502fe88c58012d041623d1689aa8cbbf1"-}diff --git a/rust/cloud-storage/.sqlx/query-de8329eb43d809c9055c9530784594572d9da9387c41873beacfb4a615e964cb.json b/rust/cloud-storage/.sqlx/query-de8329eb43d809c9055c9530784594572d9da9387c41873beacfb4a615e964cb.jsonnew file mode 100644index 0000000000..fc174aa223--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-de8329eb43d809c9055c9530784594572d9da9387c41873beacfb4a615e964cb.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT l.macro_id AS \"macro_id!\"\n FROM email_threads et\n JOIN email_links l ON et.link_id = l.id\n WHERE et.id = $1\n UNION\n SELECT mul.primary_macro_id\n FROM email_threads et\n JOIN email_links l ON et.link_id = l.id\n JOIN macro_user_links mul ON mul.child_macro_id = l.macro_id\n WHERE et.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "macro_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "de8329eb43d809c9055c9530784594572d9da9387c41873beacfb4a615e964cb"+}diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rsindex e8418d4afc..30fd603328 100644--- a/rust/cloud-storage/email/src/domain/ports.rs+++ b/rust/cloud-storage/email/src/domain/ports.rs@@ -74,19 +74,12 @@ pub trait EmailRepo: Send + Sync + 'static {macro_id: MacroUserIdStr<'_>,) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;- /// Returns every email_link owned by the given fusionauth user, one row per- /// linked inbox, ordered newest first.- fn links_by_fusionauth_user_id(- &self,- fusionauth_user_id: &str,- ) -> impl Future<Output = Result<Vec<Link>, Self::Err>> + Send;-/// Resolve the inbox owning a thread, only when that inbox belongs to the/// given fusionauth user.fn owned_link_for_thread(&self,thread_id: Uuid,- fusionauth_user_id: &str,+ macro_id: MacroUserIdStr<'_>,) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;/// Returns every inbox accessible to `macro_id`: their own email_links plus@@ -344,21 +337,12 @@ pub trait EmailService: Send + Sync + 'static {macro_id: MacroUserIdStr<'_>,) -> impl Future<Output = Result<Vec<Link>, EmailErr>> + Send;- /// Fetch every inbox owned by the caller, keyed on their fusionauth user id- /// (one row per linked inbox). The read-side multi-inbox union resolves over- /// these; the single-inbox mutating extractor selects one by header or by- /// primary-email match.- fn get_links_by_fusionauth_user_id(- &self,- auth_id: &str,- ) -> impl Future<Output = Result<Vec<Link>, EmailErr>> + Send;-- /// Resolve the inbox owning a thread, scoped to the caller's own inboxes.- /// Lets thread-targeted mutations derive the inbox from the thread instead- /// of an `X-Email-Link-Id` header.+ /// Resolve the inbox owning a thread, scoped to the caller's own and+ /// delegated inboxes. Lets thread-targeted mutations derive the inbox from+ /// the thread instead of an `X-Email-Link-Id` header.fn get_owned_link_for_thread(&self,- auth_id: &str,+ macro_id: MacroUserIdStr<'_>,thread_id: Uuid,) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rsindex 5f3f2f5d58..25cb914ff8 100644--- a/rust/cloud-storage/email/src/domain/service/mod.rs+++ b/rust/cloud-storage/email/src/domain/service/mod.rs@@ -159,23 +159,13 @@ where.map_err(|e| EmailErr::RepoErr(e.into()))}- async fn get_links_by_fusionauth_user_id(- &self,- auth_id: &str,- ) -> Result<Vec<crate::domain::models::Link>, EmailErr> {- self.email_repo- .links_by_fusionauth_user_id(auth_id)- .await- .map_err(|e| EmailErr::RepoErr(e.into()))- }-async fn get_owned_link_for_thread(&self,- auth_id: &str,+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,thread_id: uuid::Uuid,) -> Result<Option<crate::domain::models::Link>, EmailErr> {self.email_repo- .owned_link_for_thread(thread_id, auth_id)+ .owned_link_for_thread(thread_id, macro_id).await.map_err(|e| EmailErr::RepoErr(e.into()))}diff --git a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rsindex 76ae4e0d8c..dcaede14bb 100644--- a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs@@ -167,24 +167,23 @@ whereasync fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {let header_link_id = parse_link_id_header(parts)?;- let Cached(MacroUserExtractor {- macro_user_id,- user_context,- ..- }) = parts.extract_with_state(state).await?;+ let Cached(MacroUserExtractor { macro_user_id, .. }) =+ parts.extract_with_state(state).await?;+ let account_email = macro_user_id.0.email_str().to_string();let links = <EmailRouterState<U>>::from_ref(state).inner- .get_links_by_fusionauth_user_id(&user_context.fusion_user_id)+ .get_inboxes_for_macro_id(macro_user_id).await?;- let link = resolve_target_link(links, header_link_id, macro_user_id.0.email_str())?;+ let link = resolve_target_link(links, header_link_id, &account_email)?;Ok(Self(link, PhantomData))}}-/// Extractor that resolves *every* inbox the caller owns, for the multi-inbox-/// read union. Read endpoints fan out over all returned links. A caller with no-/// linked inboxes yields an empty `Vec` (and hence empty results) rather than a-/// 404 — the union over zero inboxes is empty, not missing.+/// Extractor that resolves *every* inbox the caller can read — their own inboxes+/// plus any delegated/shared inboxes reachable via `macro_user_links`. Read+/// endpoints fan out over all returned links. A caller with no inboxes yields an+/// empty `Vec` (and hence empty results) rather than a 404 — the union over zero+/// inboxes is empty, not missing.pub struct MultiEmailLinkExtractor<U>(pub Vec<Link>, pub PhantomData<U>);impl<U> Clone for MultiEmailLinkExtractor<U> {@@ -202,11 +201,11 @@ wheretype Rejection = EmailLinkErr;async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {- let Cached(MacroUserExtractor { user_context, .. }) =+ let Cached(MacroUserExtractor { macro_user_id, .. }) =parts.extract_with_state(state).await?;let links = <EmailRouterState<U>>::from_ref(state).inner- .get_links_by_fusionauth_user_id(&user_context.fusion_user_id)+ .get_inboxes_for_macro_id(macro_user_id).await?;Ok(Self(links, PhantomData))}diff --git a/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs b/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rsindex f3f2d3a056..7d7cc29e70 100644--- a/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs+++ b/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs@@ -118,11 +118,11 @@ pub async fn update_thread_labels_handler<T: EmailService, G: GmailTokenProviderPath(thread_id): Path<Uuid>,Json(body): Json<UpdateThreadLabelRequest>,) -> Result<Json<UpdateThreadLabelsResponse>, UpdateThreadLabelError> {- // Resolve the inbox from the thread (scoped to the caller's own inboxes),- // then use that inbox's own Gmail token.+ // Resolve the inbox from the thread (scoped to the caller's own and delegated+ // inboxes), then use that inbox's own Gmail token.let link = state.inner- .get_owned_link_for_thread(¯o_user.user_context.fusion_user_id, thread_id)+ .get_owned_link_for_thread(macro_user.macro_user_id, thread_id).await?.ok_or_else(|| UpdateThreadLabelError::NotFound("Thread not found".to_string()))?;diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rsindex 6fb071cf45..f96826c4f8 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs@@ -71,39 +71,11 @@ pub(super) async fn link_by_fusionauth_email_provider(.map_err(|e| sqlx::Error::Decode(Box::new(e)))}-#[tracing::instrument(err, skip(pool))]-pub(super) async fn links_by_fusionauth_user_id(- pool: &PgPool,- fusionauth_user_id: &str,-) -> Result<Vec<Link>, sqlx::Error> {- let db_links: Vec<DbLink> = sqlx::query_as!(- DbLink,- r#"- SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",- is_sync_active, created_at, updated_at- FROM email_links- WHERE fusionauth_user_id = $1- ORDER BY created_at DESC- "#,- fusionauth_user_id- )- .fetch_all(pool)- .await?;-- db_links- .into_iter()- .map(|v| {- v.try_into_model()- .map_err(|e| sqlx::Error::Decode(Box::new(e)))- })- .collect()-}-#[tracing::instrument(err, skip(pool))]pub(super) async fn owned_link_for_thread(pool: &PgPool,thread_id: Uuid,- fusionauth_user_id: &str,+ macro_id: MacroUserIdStr<'_>,) -> Result<Option<Link>, sqlx::Error> {let db_link: Option<DbLink> = sqlx::query_as!(DbLink,@@ -112,10 +84,17 @@ pub(super) async fn owned_link_for_thread(l.is_sync_active, l.created_at, l.updated_atFROM email_threads tJOIN email_links l ON l.id = t.link_id- WHERE t.id = $1 AND l.fusionauth_user_id = $2+ WHERE t.id = $1+ AND (+ l.macro_id = $2+ OR EXISTS (+ SELECT 1 FROM macro_user_links mul+ WHERE mul.child_macro_id = l.macro_id AND mul.primary_macro_id = $2+ )+ )"#,thread_id,- fusionauth_user_id+ macro_id.as_ref()).fetch_optional(pool).await?;diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rsindex 71982f8986..75eda20e8d 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs@@ -97,19 +97,12 @@ impl EmailRepo for EmailPgRepo {link::link_by_macro_id(&self.pool, macro_id).await}- async fn links_by_fusionauth_user_id(- &self,- fusionauth_user_id: &str,- ) -> Result<Vec<Link>, Self::Err> {- link::links_by_fusionauth_user_id(&self.pool, fusionauth_user_id).await- }-async fn owned_link_for_thread(&self,thread_id: Uuid,- fusionauth_user_id: &str,+ macro_id: MacroUserIdStr<'_>,) -> Result<Option<Link>, Self::Err> {- link::owned_link_for_thread(&self.pool, thread_id, fusionauth_user_id).await+ link::owned_link_for_thread(&self.pool, thread_id, macro_id).await}async fn inboxes_for_macro_id(diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rsindex c9289e2e0a..2d4247f024 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs@@ -67,43 +67,76 @@ async fn test_link_by_fusionauth_and_macro_id_wrong_macro_id(}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn test_links_by_fusionauth_user_id_returns_all_owned_inboxes(+async fn test_inboxes_for_macro_id_includes_own_and_delegated(pool: Pool<Postgres>,) -> anyhow::Result<()> {+ // macro_user_links FK-references "User" (which FK-references macro_user), so+ // the delegating and delegated accounts must exist as real users.sqlx::query(r#"- INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)- VALUES- ('a1000000-0000-0000-0000-000000000001'::uuid, 'macro|[email protected]', 'fa-alice', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '1 hour', NOW()),- ('a2000000-0000-0000-0000-000000000002'::uuid, 'macro|[email protected]', 'fa-alice', '[email protected]', 'GMAIL', true, NOW(), NOW()),- ('b1000000-0000-0000-0000-000000000001'::uuid, 'macro|[email protected]', 'fa-bob', '[email protected]', 'GMAIL', true, NOW(), NOW())+ INSERT INTO "macro_user" (id, username, email, stripe_customer_id) VALUES+ ('c1000000-0000-0000-0000-000000000001', 'alice', '[email protected]', 'stripe_alice'),+ ('c2000000-0000-0000-0000-000000000002', 'shared', '[email protected]', 'stripe_shared')"#,).execute(&pool).await?;- let repo = EmailPgRepo::new(pool);- let links = repo.links_by_fusionauth_user_id("fa-alice").await?;+ sqlx::query(+ r#"+ INSERT INTO "User" (id, email, name, macro_user_id) VALUES+ ('macro|[email protected]', '[email protected]', 'Alice', 'c1000000-0000-0000-0000-000000000001'),+ ('macro|[email protected]', '[email protected]', 'Shared Inbox', 'c2000000-0000-0000-0000-000000000002')+ "#,+ )+ .execute(&pool)+ .await?;- assert_eq!(links.len(), 2, "should return both of fa-alice's inboxes");- // ordered by created_at DESC: the newer work inbox comes first- assert_eq!(links[0].email_address.0.as_ref(), "[email protected]");- assert_eq!(links[1].email_address.0.as_ref(), "[email protected]");- assert!(links.iter().all(|l| l.fusionauth_user_id == "fa-alice"));+ sqlx::query(+ r#"+ INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at) VALUES+ ('a1000000-0000-0000-0000-000000000001'::uuid, 'macro|[email protected]', 'fa-alice', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '2 hours', NOW()),+ ('a2000000-0000-0000-0000-000000000002'::uuid, 'macro|[email protected]', 'fa-alice', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '1 hour', NOW()),+ ('5e000000-0000-0000-0000-000000000003'::uuid, 'macro|[email protected]', 'fa-shared', '[email protected]', 'GMAIL', true, NOW(), NOW()),+ ('b0000000-0000-0000-0000-000000000004'::uuid, 'macro|[email protected]', 'fa-bob', '[email protected]', 'GMAIL', true, NOW(), NOW())+ "#,+ )+ .execute(&pool)+ .await?;- Ok(())-}+ // alice is the primary; shared@ is delegated to her. bob is unrelated.+ sqlx::query(+ r#"+ INSERT INTO macro_user_links (primary_macro_id, child_macro_id) VALUES+ ('macro|[email protected]', 'macro|[email protected]')+ "#,+ )+ .execute(&pool)+ .await?;-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn test_links_by_fusionauth_user_id_empty_when_no_inboxes(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {let repo = EmailPgRepo::new(pool);- let links = repo.links_by_fusionauth_user_id("fa-nobody").await?;+ let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let links = repo.inboxes_for_macro_id(macro_id).await?;++ let emails: std::collections::HashSet<&str> =+ links.iter().map(|l| l.email_address.0.as_ref()).collect();++ assert_eq!(+ links.len(),+ 3,+ "alice's two own inboxes plus the one delegated inbox"+ );+ assert!(emails.contains("[email protected]"));+ assert!(emails.contains("[email protected]"));+ assert!(+ emails.contains("[email protected]"),+ "delegated inbox must be included"+ );assert!(- links.is_empty(),- "user with no inboxes should yield empty vec"+ !emails.contains("[email protected]"),+ "unrelated inbox must be excluded");+Ok(())}@@ -169,3 +202,87 @@ async fn test_link_by_fusionauth_email_provider_wrong_fusionauth(Ok(())}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_owned_link_for_thread_resolves_own_and_delegated(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // macro_user_links FK-references "User" (which FK-references macro_user).+ sqlx::query(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES+ ('d1000000-0000-0000-0000-000000000001'::uuid, 'child', '[email protected]', 'stripe_child'),+ ('d2000000-0000-0000-0000-000000000002'::uuid, 'primary', '[email protected]', 'stripe_primary'),+ ('d3000000-0000-0000-0000-000000000003'::uuid, 'stranger', '[email protected]', 'stripe_stranger')+ "#,+ )+ .execute(&pool)+ .await?;++ sqlx::query(+ r#"+ INSERT INTO "User" (id, email, macro_user_id) VALUES+ ('macro|[email protected]', '[email protected]', 'd1000000-0000-0000-0000-000000000001'::uuid),+ ('macro|[email protected]', '[email protected]', 'd2000000-0000-0000-0000-000000000002'::uuid),+ ('macro|[email protected]', '[email protected]', 'd3000000-0000-0000-0000-000000000003'::uuid)+ "#,+ )+ .execute(&pool)+ .await?;++ sqlx::query(+ r#"+ INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at) VALUES+ ('c0000000-0000-0000-0000-000000000001'::uuid, 'macro|[email protected]', 'fa-child', '[email protected]', 'GMAIL', true, NOW(), NOW())+ "#,+ )+ .execute(&pool)+ .await?;++ sqlx::query(+ r#"INSERT INTO email_threads (id, link_id)+ VALUES ('c0000000-0000-0000-0000-0000000000ff'::uuid, 'c0000000-0000-0000-0000-000000000001'::uuid)"#,+ )+ .execute(&pool)+ .await?;++ sqlx::query(+ r#"INSERT INTO macro_user_links (primary_macro_id, child_macro_id)+ VALUES ('macro|[email protected]', 'macro|[email protected]')"#,+ )+ .execute(&pool)+ .await?;++ let repo = EmailPgRepo::new(pool);+ let thread_id = Uuid::parse_str("c0000000-0000-0000-0000-0000000000ff")?;+ let link_id = Uuid::parse_str("c0000000-0000-0000-0000-000000000001")?;++ // delegate resolves the shared inbox+ let delegated = repo+ .owned_link_for_thread(+ thread_id,+ MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ )+ .await?;+ assert_eq!(delegated.map(|l| l.id), Some(link_id));++ // owner resolves their own inbox+ let owned = repo+ .owned_link_for_thread(+ thread_id,+ MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ )+ .await?;+ assert_eq!(owned.map(|l| l.id), Some(link_id));++ // an unrelated but real user resolves nothing+ let none = repo+ .owned_link_for_thread(+ thread_id,+ MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ )+ .await?;+ assert!(none.is_none());++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/links/get.rs b/rust/cloud-storage/email_db_client/src/links/get.rsindex ef3b06b35f..9031ae1f4d 100644--- a/rust/cloud-storage/email_db_client/src/links/get.rs+++ b/rust/cloud-storage/email_db_client/src/links/get.rs@@ -6,6 +6,9 @@ use sqlx::types::Uuid;use crate::links::types::{DbLink, DbUserProvider};+#[cfg(test)]+mod test;+/// fetches a link given an email address and provider.#[tracing::instrument(skip(pool), err)]pub async fn fetch_link_by_email(@@ -147,15 +150,16 @@ pub async fn fetch_links_by_fusionauth_user_id(Ok(service_links?)}-/// Resolves the inbox (email_link) that owns a thread, but only when the thread's-/// inbox belongs to the given fusionauth user. Returns `None` when the thread-/// doesn't exist or its inbox isn't one the caller owns — callers map that to a-/// not-found/unauthorized response. Lets mutating thread routes derive the inbox-/// from the thread instead of an `X-Email-Link-Id` header.+/// Resolves the inbox (email_link) that owns a thread, but only when that inbox+/// belongs to the given macro user or is delegated to them via macro_user_links.+/// Returns `None` when the thread doesn't exist or its inbox isn't one the caller+/// owns or has delegated access to — callers map that to a not-found/unauthorized+/// response. Lets mutating thread routes derive the inbox from the thread instead+/// of an `X-Email-Link-Id` header.#[tracing::instrument(skip(pool), err)]pub async fn fetch_owned_link_for_thread(pool: &PgPool,- fusionauth_user_id: &str,+ macro_id: &str,thread_id: Uuid,) -> anyhow::Result<Option<link::Link>> {let db_link = sqlx::query_as!(@@ -165,10 +169,17 @@ pub async fn fetch_owned_link_for_thread(l.is_sync_active, l.created_at, l.updated_atFROM email_threads tJOIN email_links l ON l.id = t.link_id- WHERE t.id = $1 AND l.fusionauth_user_id = $2+ WHERE t.id = $1+ AND (+ l.macro_id = $2+ OR EXISTS (+ SELECT 1 FROM macro_user_links mul+ WHERE mul.child_macro_id = l.macro_id AND mul.primary_macro_id = $2+ )+ )"#,thread_id,- fusionauth_user_id+ macro_id).fetch_optional(pool).await?;@@ -177,11 +188,11 @@ pub async fn fetch_owned_link_for_thread(}/// Resolves the inbox (email_link) that owns a message, scoped to the caller's-/// own inboxes. See [`fetch_owned_link_for_thread`].+/// own and delegated inboxes. See [`fetch_owned_link_for_thread`].#[tracing::instrument(skip(pool), err)]pub async fn fetch_owned_link_for_message(pool: &PgPool,- fusionauth_user_id: &str,+ macro_id: &str,message_id: Uuid,) -> anyhow::Result<Option<link::Link>> {let db_link = sqlx::query_as!(@@ -191,10 +202,17 @@ pub async fn fetch_owned_link_for_message(l.is_sync_active, l.created_at, l.updated_atFROM email_messages mJOIN email_links l ON l.id = m.link_id- WHERE m.id = $1 AND l.fusionauth_user_id = $2+ WHERE m.id = $1+ AND (+ l.macro_id = $2+ OR EXISTS (+ SELECT 1 FROM macro_user_links mul+ WHERE mul.child_macro_id = l.macro_id AND mul.primary_macro_id = $2+ )+ )"#,message_id,- fusionauth_user_id+ macro_id).fetch_optional(pool).await?;diff --git a/rust/cloud-storage/email_db_client/src/links/get/test.rs b/rust/cloud-storage/email_db_client/src/links/get/test.rsnew file mode 100644index 0000000000..6027911416--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/links/get/test.rs@@ -0,0 +1,159 @@+use crate::links::get::{fetch_owned_link_for_message, fetch_owned_link_for_thread};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::types::Uuid;+use sqlx::{Pool, Postgres};++const CHILD: &str = "macro|[email protected]"; // owns the inbox+const PRIMARY: &str = "macro|[email protected]"; // delegate+const STRANGER: &str = "macro|[email protected]"; // no relationship++/// macro_user + "User" rows so macro_user_links FKs resolve.+async fn insert_user(pool: &Pool<Postgres>, macro_id: &str, email: &str) {+ let macro_uuid = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $4)"#,+ macro_uuid,+ macro_id,+ email,+ macro_id,+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,+ macro_id,+ email,+ macro_uuid,+ )+ .execute(pool)+ .await+ .unwrap();+}++/// A link owned by `macro_id` with one thread and one message on it.+/// Returns `(link_id, thread_id, message_id)`.+async fn insert_inbox_with_thread_and_message(+ pool: &Pool<Postgres>,+ macro_id: &str,+ email: &str,+) -> (Uuid, Uuid, Uuid) {+ let link_id = Uuid::new_v4();+ let thread_id = Uuid::new_v4();+ let contact_id = Uuid::new_v4();+ let message_id = Uuid::new_v4();++ sqlx::query!(+ r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)+ VALUES ($1, $2, $2, $3, 'GMAIL')"#,+ link_id,+ macro_id,+ email,+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"INSERT INTO email_threads (id, link_id) VALUES ($1, $2)"#,+ thread_id,+ link_id,+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"INSERT INTO email_contacts (id, link_id, email_address) VALUES ($1, $2, $3)"#,+ contact_id,+ link_id,+ "[email protected]",+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"INSERT INTO email_messages (id, thread_id, link_id, from_contact_id)+ VALUES ($1, $2, $3, $4)"#,+ message_id,+ thread_id,+ link_id,+ contact_id,+ )+ .execute(pool)+ .await+ .unwrap();++ (link_id, thread_id, message_id)+}++async fn insert_delegation(pool: &Pool<Postgres>, primary: &str, child: &str) {+ sqlx::query!(+ r#"INSERT INTO macro_user_links (primary_macro_id, child_macro_id) VALUES ($1, $2)"#,+ primary,+ child,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn resolves_inbox_for_owner_and_delegate(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ insert_user(&pool, PRIMARY, "[email protected]").await;+ let (link_id, thread_id, message_id) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;+ insert_delegation(&pool, PRIMARY, CHILD).await;++ // Delegate resolves the shared inbox from both thread and message.+ assert_eq!(+ fetch_owned_link_for_thread(&pool, PRIMARY, thread_id)+ .await?+ .map(|l| l.id),+ Some(link_id)+ );+ assert_eq!(+ fetch_owned_link_for_message(&pool, PRIMARY, message_id)+ .await?+ .map(|l| l.id),+ Some(link_id)+ );++ // Owner still resolves their own inbox.+ assert_eq!(+ fetch_owned_link_for_thread(&pool, CHILD, thread_id)+ .await?+ .map(|l| l.id),+ Some(link_id)+ );++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn resolves_nothing_for_unrelated_caller(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ insert_user(&pool, PRIMARY, "[email protected]").await;+ insert_user(&pool, STRANGER, "[email protected]").await;+ let (_link_id, thread_id, message_id) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;+ insert_delegation(&pool, PRIMARY, CHILD).await;++ // STRANGER is a real user who neither owns nor is delegated the inbox.+ assert!(+ fetch_owned_link_for_thread(&pool, STRANGER, thread_id)+ .await?+ .is_none()+ );+ assert!(+ fetch_owned_link_for_message(&pool, STRANGER, message_id)+ .await?+ .is_none()+ );++ Ok(())+}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.rsindex 336a2a1d3d..9df516144c 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@@ -45,21 +45,19 @@ pub async fn handler() -> Result<Response, Response> {// Resolve which of the caller's inboxes owns this attachment. Each inbox is a// distinct Google account, so the owning link also determines the Gmail token.- let links = email_db_client::links::get::fetch_links_by_fusionauth_user_id(- &ctx.db,- &user_context.fusion_user_id,- )- .await- .map_err(|e| {- tracing::warn!(error=?e, "error fetching links");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "error fetching attachment".into(),- }),- )- .into_response()- })?;+ let links =+ email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, &user_context.user_id)+ .await+ .map_err(|e| {+ tracing::warn!(error=?e, "error fetching links");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "error fetching attachment".into(),+ }),+ )+ .into_response()+ })?;let mut owned = None;for link in links {diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/list.rs b/rust/cloud-storage/email_service/src/api/email/contacts/list.rsindex cb27ae0ce1..42b578645f 100644--- a/rust/cloud-storage/email_service/src/api/email/contacts/list.rs+++ b/rust/cloud-storage/email_service/src/api/email/contacts/list.rs@@ -34,21 +34,19 @@ pub async fn list_contacts_handler(State(ctx): State<ApiContext>,user_context: Extension<UserContext>,) -> Result<Response, Response> {- let links = email_db_client::links::get::fetch_links_by_fusionauth_user_id(- &ctx.db,- &user_context.fusion_user_id,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to fetch links");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to fetch links".into(),- }),- )- .into_response()- })?;+ let links =+ email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, &user_context.user_id)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "unable to fetch links");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to fetch links".into(),+ }),+ )+ .into_response()+ })?;let mut contacts: HashMap<Uuid, Vec<ContactInfoWithInteraction>> =HashMap::with_capacity(links.len());diff --git a/rust/cloud-storage/email_service/src/api/email/messages/get.rs b/rust/cloud-storage/email_service/src/api/email/messages/get.rsindex cef461d660..1cdada8360 100644--- a/rust/cloud-storage/email_service/src/api/email/messages/get.rs+++ b/rust/cloud-storage/email_service/src/api/email/messages/get.rs@@ -12,13 +12,11 @@ use std::collections::HashSet;use strum_macros::AsRefStr;use thiserror::Error;-/// The set of link ids the caller owns — every message read unions across these.-async fn owned_link_ids(- ctx: &ApiContext,- fusionauth_user_id: &str,-) -> anyhow::Result<HashSet<Uuid>> {+/// The set of link ids the caller can read — own plus delegated/shared inboxes;+/// every message read unions across these.+async fn owned_link_ids(ctx: &ApiContext, macro_id: &str) -> anyhow::Result<HashSet<Uuid>> {Ok(- email_db_client::links::get::fetch_links_by_fusionauth_user_id(&ctx.db, fusionauth_user_id)+ email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, macro_id).await?.into_iter().map(|link| link.id)@@ -94,7 +92,7 @@ pub async fn handler(return Err(GetMessageError::MessageNotFound);};- let link_ids = owned_link_ids(&ctx, &user_context.fusion_user_id).await?;+ let link_ids = owned_link_ids(&ctx, &user_context.user_id).await?;if link_ids.contains(&message.link_id) {Ok(Json(message).into_response())} else {@@ -132,7 +130,7 @@ pub async fn batch_handler(return Err(GetMessageError::MessageNotFound);}- let link_ids = owned_link_ids(&ctx, &user_context.fusion_user_id).await?;+ let link_ids = owned_link_ids(&ctx, &user_context.user_id).await?;let accessible_messages = messages.into_iter().filter(|msg| link_ids.contains(&msg.link_id))diff --git a/rust/cloud-storage/email_service/src/api/email/messages/labels.rs b/rust/cloud-storage/email_service/src/api/email/messages/labels.rsindex ee2d3a98e8..3214eb7133 100644--- a/rust/cloud-storage/email_service/src/api/email/messages/labels.rs+++ b/rust/cloud-storage/email_service/src/api/email/messages/labels.rs@@ -60,11 +60,11 @@ pub async fn handler(.into_response());}- // Resolve the inbox from the batch's messages (scoped to the caller's own- // inboxes); a single label op targets messages in one inbox.+ // Resolve the inbox from the batch's messages (scoped to the caller's own and+ // delegated inboxes); a single label op targets messages in one inbox.let link = email_db_client::links::get::fetch_owned_link_for_message(&ctx.db,- &user_context.fusion_user_id,+ &user_context.user_id,body.message_ids[0],).awaitdiff --git a/rust/cloud-storage/email_service/src/api/email/threads/archived.rs b/rust/cloud-storage/email_service/src/api/email/threads/archived.rsindex 3808ba9f09..399425d328 100644--- a/rust/cloud-storage/email_service/src/api/email/threads/archived.rs+++ b/rust/cloud-storage/email_service/src/api/email/threads/archived.rs@@ -75,10 +75,11 @@ pub async fn archived_handler() -> Result<Response, ArchiveThreadError> {let is_archiving = body.value;- // Resolve the inbox from the thread itself, scoped to the caller's own inboxes.+ // Resolve the inbox from the thread itself, scoped to the caller's own and+ // delegated inboxes.let link = email_db_client::links::get::fetch_owned_link_for_thread(&ctx.db,- &user_context.fusion_user_id,+ &user_context.user_id,thread_id,).await?diff --git a/rust/cloud-storage/email_service/src/api/email/threads/get.rs b/rust/cloud-storage/email_service/src/api/email/threads/get.rsindex f7431de4cc..e817930a48 100644--- a/rust/cloud-storage/email_service/src/api/email/threads/get.rs+++ b/rust/cloud-storage/email_service/src/api/email/threads/get.rs@@ -98,15 +98,13 @@ pub async fn get_thread_messages_handler() -> Result<Response, GetThreadError> {let p = process_get_thread_params(&query_params)?;- let link_ids: HashSet<Uuid> = email_db_client::links::get::fetch_links_by_fusionauth_user_id(- &ctx.db,- &user_context.fusion_user_id,- )- .await- .context("Failed to fetch links")?- .into_iter()- .map(|link| link.id)- .collect();+ let link_ids: HashSet<Uuid> =+ email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, &user_context.user_id)+ .await+ .context("Failed to fetch links")?+ .into_iter()+ .map(|link| link.id)+ .collect();let messages =email_db_client::messages::get_parsed::get_paginated_parsed_messages_by_thread_id(diff --git a/rust/cloud-storage/email_service/src/api/email/threads/seen.rs b/rust/cloud-storage/email_service/src/api/email/threads/seen.rsindex 9220b86882..af96d0e95a 100644--- a/rust/cloud-storage/email_service/src/api/email/threads/seen.rs+++ b/rust/cloud-storage/email_service/src/api/email/threads/seen.rs@@ -72,10 +72,11 @@ pub async fn seen_handler(user_context: Extension<UserContext>,Path(PathParams { id: thread_id }): Path<PathParams>,) -> Result<Response, SeenThreadError> {- // Resolve the inbox from the thread itself, scoped to the caller's own inboxes.+ // Resolve the inbox from the thread itself, scoped to the caller's own and+ // delegated inboxes.let link = email_db_client::links::get::fetch_owned_link_for_thread(&ctx.db,- &user_context.fusion_user_id,+ &user_context.user_id,thread_id,).awaitdiff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rsindex cd8a6cb782..90532713a4 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs@@ -27,6 +27,9 @@ pub mod project_access;pub mod team_access;pub mod thread_access;+#[cfg(test)]+mod test;+/// Type safety for source ids for entity_access table#[derive(Debug, Clone)]pub(in crate::outbound::pg_access_repo) struct SourceIds(pub Vec<String>);@@ -88,25 +91,36 @@ pub(in crate::outbound::pg_access_repo) async fn get_entity_users(entity_id: &uuid::Uuid,entity_type: EntityType,) -> anyhow::Result<Vec<MacroUserIdStr<'static>>> {- // because we don't store entity_access per email we need to also grab the owner of the email to append to the list+ // because we don't store entity_access per email we need to also grab the owner+ // of the email to append to the list, plus any primary that delegates the inbox+ // via macro_user_links (shared inbox)let mut email_owner: Vec<MacroUserIdStr> = if let EntityType::EmailThread = entity_type {- let owner = sqlx::query_scalar!(+ let macro_ids = sqlx::query_scalar!(r#"- SELECT l.macro_id+ SELECT l.macro_id AS "macro_id!"FROM email_threads etJOIN email_links l ON et.link_id = l.idWHERE et.id = $1+ UNION+ SELECT mul.primary_macro_id+ FROM email_threads et+ JOIN email_links l ON et.link_id = l.id+ JOIN macro_user_links mul ON mul.child_macro_id = l.macro_id+ WHERE et.id = $1"#,entity_id)- .fetch_one(pool)+ .fetch_all(pool).await?;- vec![- MacroUserIdStr::parse_from_str(owner.as_str())- .context("macro user id should be valid")?- .into_owned(),- ]+ macro_ids+ .into_iter()+ .map(|macro_id| {+ MacroUserIdStr::parse_from_str(macro_id.as_str())+ .map(|u| u.into_owned())+ .context("macro user id should be valid")+ })+ .collect::<anyhow::Result<Vec<_>>>()?} else {vec![]};diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/test.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/test.rsnew file mode 100644index 0000000000..9c85b96692--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/test.rs@@ -0,0 +1,84 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++const OWNER: &str = "macro|[email protected]";+const DELEGATE: &str = "macro|[email protected]";++/// macro_user + "User" rows so macro_user_links FKs resolve.+async fn insert_user(pool: &PgPool, user_id: &str, email: &str) {+ let macro_uuid = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $4)"#,+ macro_uuid,+ user_id,+ email,+ user_id,+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,+ user_id,+ email,+ macro_uuid,+ )+ .execute(pool)+ .await+ .unwrap();+}++/// An empty link + thread owned by `owner_macro_id`. Returns the thread id.+async fn insert_thread(pool: &PgPool, owner_macro_id: &str) -> Uuid {+ let link_id = Uuid::new_v4();+ let thread_id = Uuid::new_v4();++ sqlx::query!(+ r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)+ VALUES ($1, $2, $2, $3, 'GMAIL')"#,+ link_id,+ owner_macro_id,+ format!("{owner_macro_id}@mail.test"),+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"INSERT INTO email_threads (id, link_id) VALUES ($1, $2)"#,+ thread_id,+ link_id,+ )+ .execute(pool)+ .await+ .unwrap();++ thread_id+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_entity_users_includes_inbox_delegate(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, DELEGATE, "[email protected]").await;+ let thread_id = insert_thread(&pool, OWNER).await;++ sqlx::query!(+ r#"INSERT INTO macro_user_links (primary_macro_id, child_macro_id) VALUES ($1, $2)"#,+ DELEGATE,+ OWNER,+ )+ .execute(&pool)+ .await+ .unwrap();++ let users = get_entity_users(&pool, &thread_id, EntityType::EmailThread).await?;+ let ids: std::collections::HashSet<String> = users.iter().map(|u| u.to_string()).collect();++ assert!(ids.contains(OWNER), "inbox owner must be included");+ assert!(ids.contains(DELEGATE), "inbox delegate must be included");+ Ok(())+}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rsindex 95d329bdcd..e178dea19e 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs@@ -19,7 +19,8 @@ pub async fn get_thread_access() -> Result<Option<AccessLevel>, sqlx::Error> {let user_id_str = user_id.map(AsRef::as_ref).unwrap_or("");- // Thread-specific: check if user is the thread owner via email_links+ // Thread-specific: the caller owns the thread's inbox, or a macro_user_links+ // edge delegates that inbox to the caller (the caller is its primary).let is_owner = sqlx::query_scalar!(r#"SELECT EXISTS (@@ -27,7 +28,15 @@ pub async fn get_thread_access(FROM public.email_threads tJOIN public.email_links l ON l.id = t.link_idWHERE t.id = $1::uuid- AND l.macro_id = $2+ AND (+ l.macro_id = $2+ OR EXISTS (+ SELECT 1+ FROM public.macro_user_links mul+ WHERE mul.child_macro_id = l.macro_id+ AND mul.primary_macro_id = $2+ )+ )) AS "exists!""#,thread_id,diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rsindex eee7f57929..d1e78ef244 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs@@ -315,6 +315,52 @@ async fn returns_none_when_thread_does_not_exist(pool: PgPool) -> anyhow::ResultOk(())}+// ---------------------------------------------------------------------------+// Delegated / shared inboxes (macro_user_links)+// ---------------------------------------------------------------------------++/// `primary_macro_id` is delegated `child_macro_id`'s inbox. Both must exist in "User".+async fn insert_delegation(pool: &PgPool, primary_macro_id: &str, child_macro_id: &str) {+ sqlx::query!(+ r#"INSERT INTO macro_user_links (primary_macro_id, child_macro_id) VALUES ($1, $2)"#,+ primary_macro_id,+ child_macro_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delegated_inbox_grants_access(pool: PgPool) -> anyhow::Result<()> {+ // OWNER's inbox is delegated to REQUESTER via macro_user_links; the thread is+ // owned by OWNER's inbox, so the delegate gets owner-equivalent access.+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, REQUESTER, "[email protected]").await;+ let (_link_id, thread_id) = create_link_and_thread(&pool, OWNER).await;+ insert_delegation(&pool, REQUESTER, OWNER).await;++ assert_eq!(+ access_as_requester(&pool, &thread_id).await,+ Some(AccessLevel::Owner)+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delegation_scoped_to_the_primary(pool: PgPool) -> anyhow::Result<()> {+ // The inbox is delegated to OTHER, not REQUESTER. REQUESTER neither owns nor+ // is delegated the inbox, so it gets no access.+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, REQUESTER, "[email protected]").await;+ insert_user(&pool, OTHER, "[email protected]").await;+ let (_link_id, thread_id) = create_link_and_thread(&pool, OWNER).await;+ insert_delegation(&pool, OTHER, OWNER).await;++ assert_eq!(access_as_requester(&pool, &thread_id).await, None);+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn unauthenticated_user_never_gets_crm_access(pool: PgPool) -> anyhow::Result<()> {// Even a fully-synced thread is invisible to an unauthenticated caller: withdiff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rsindex 559cd53980..17f7899d85 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs@@ -167,16 +167,9 @@ impl EmailService for MockEmail {Ok(Vec::new())}- async fn get_links_by_fusionauth_user_id(- &self,- _auth_id: &str,- ) -> Result<Vec<email::domain::models::Link>, email::domain::models::EmailErr> {- Ok(Vec::new())- }-async fn get_owned_link_for_thread(&self,- _auth_id: &str,+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,_thread_id: uuid::Uuid,) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {Ok(None)@@ -463,16 +456,9 @@ impl EmailService for MockEmailLinkResult {(self.get_link_result)().map(|opt| opt.into_iter().collect())}- async fn get_links_by_fusionauth_user_id(- &self,- _auth_id: &str,- ) -> Result<Vec<email::domain::models::Link>, email::domain::models::EmailErr> {- (self.get_link_result)().map(|opt| opt.into_iter().collect())- }-async fn get_owned_link_for_thread(&self,- _auth_id: &str,+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,_thread_id: uuid::Uuid,) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {(self.get_link_result)()