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
fix(email): restrict CRM team scope to primary inboxes (#3994)
gbirman6940f1dc1cc8
diff --git a/rust/cloud-storage/.sqlx/query-124901aaedcea50030b2b8039c8ef509d980650a4c5d0fca7053cba0c2543155.json b/rust/cloud-storage/.sqlx/query-36f475918166109c36d93d8942503e4016b5fbf0eb92a2f49eb22831a6e13818.jsonsimilarity index 74%rename from rust/cloud-storage/.sqlx/query-124901aaedcea50030b2b8039c8ef509d980650a4c5d0fca7053cba0c2543155.jsonrename to rust/cloud-storage/.sqlx/query-36f475918166109c36d93d8942503e4016b5fbf0eb92a2f49eb22831a6e13818.jsonindex 6923dd89fd..3ba3940499 100644--- a/rust/cloud-storage/.sqlx/query-124901aaedcea50030b2b8039c8ef509d980650a4c5d0fca7053cba0c2543155.json+++ b/rust/cloud-storage/.sqlx/query-36f475918166109c36d93d8942503e4016b5fbf0eb92a2f49eb22831a6e13818.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT c.id, LOWER(c.email_address) AS \"email_lower!\"\n FROM email_contacts c\n JOIN email_links el ON el.id = c.link_id\n JOIN team_user tu ON tu.user_id = el.macro_id\n WHERE tu.team_id = $1\n AND LOWER(c.email_address) = ANY($2)\n ",+ "query": "\n SELECT c.id, LOWER(c.email_address) AS \"email_lower!\"\n FROM email_contacts c\n JOIN email_links el ON el.id = c.link_id\n JOIN team_user tu ON tu.user_id = el.macro_id\n WHERE tu.team_id = $1\n AND el.is_primary\n AND LOWER(c.email_address) = ANY($2)\n ","describe": {"columns": [{@@ -25,5 +25,5 @@null]},- "hash": "124901aaedcea50030b2b8039c8ef509d980650a4c5d0fca7053cba0c2543155"+ "hash": "36f475918166109c36d93d8942503e4016b5fbf0eb92a2f49eb22831a6e13818"}diff --git a/rust/cloud-storage/.sqlx/query-2443fe54c4008a741bf932783b861f1049c87b024003d7a6781ed24d82f095e8.json b/rust/cloud-storage/.sqlx/query-c54744aa091017a10ceba8dc5ebc387f9c4e52b7135d491724fad116a773ab56.jsonsimilarity index 72%rename from rust/cloud-storage/.sqlx/query-2443fe54c4008a741bf932783b861f1049c87b024003d7a6781ed24d82f095e8.jsonrename to rust/cloud-storage/.sqlx/query-c54744aa091017a10ceba8dc5ebc387f9c4e52b7135d491724fad116a773ab56.jsonindex 15f9c1c609..28da2d4dd6 100644--- a/rust/cloud-storage/.sqlx/query-2443fe54c4008a741bf932783b861f1049c87b024003d7a6781ed24d82f095e8.json+++ b/rust/cloud-storage/.sqlx/query-c54744aa091017a10ceba8dc5ebc387f9c4e52b7135d491724fad116a773ab56.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT l.id\n FROM email_labels l\n JOIN email_links el ON el.id = l.link_id\n JOIN team_user tu ON tu.user_id = el.macro_id\n WHERE l.name = 'TRASH' AND tu.team_id = $1\n ",+ "query": "\n SELECT l.id\n FROM email_labels l\n JOIN email_links el ON el.id = l.link_id\n JOIN team_user tu ON tu.user_id = el.macro_id\n WHERE l.name = 'TRASH' AND tu.team_id = $1\n AND el.is_primary\n ","describe": {"columns": [{@@ -18,5 +18,5 @@false]},- "hash": "2443fe54c4008a741bf932783b861f1049c87b024003d7a6781ed24d82f095e8"+ "hash": "c54744aa091017a10ceba8dc5ebc387f9c4e52b7135d491724fad116a773ab56"}diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_scope.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_scope.sqlindex 7bae48a214..b17fd5642e 100644--- a/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_scope.sql+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_scope.sql@@ -196,3 +196,59 @@ VALUES('33330002-0000-0000-0000-000000000002', '11110002-0000-0000-0000-000000000002'),-- Carol INBOX('33330003-0000-0000-0000-000000000001', '11110003-0000-0000-0000-000000000001');++-- == Alice's connected secondary (non-primary) link ==+-- Same macro_id as alice's primary link but a different email_address — a+-- personal mailbox connected as an extra inbox. Team-scoped queries must+-- never read it: its threads, contacts, and labels stay out of CRM scope.+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES+ ('a0000004-0000-0000-0000-000000000004', 'macro|[email protected]', 'fa_alice_personal', '[email protected]', 'GMAIL', true, NOW(), NOW());++INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES+ -- [email protected] also corresponded with alice's personal mailbox+ ('c0000012-0000-0000-0000-000000000012', 'a0000004-0000-0000-0000-000000000004', '[email protected]', 'Outsider', NOW(), NOW()),+ -- an address known ONLY to the personal mailbox+ ('c0000013-0000-0000-0000-000000000013', 'a0000004-0000-0000-0000-000000000004', '[email protected]', 'Secret', NOW(), NOW());++INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)+VALUES+ ('11110004-0000-0000-0000-000000000001', 'a0000004-0000-0000-0000-000000000004', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),+ ('11110004-0000-0000-0000-000000000002', 'a0000004-0000-0000-0000-000000000004', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW());++-- tp1: personal inbox thread from [email protected] (matches CRM filters,+-- must NOT appear in team-scoped results)+-- tp2: personal inbox thread from [email protected] (its contact must not+-- resolve under team scope)+INSERT INTO email_threads (+ id, provider_id, link_id, inbox_visible, is_read,+ latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts,+ created_at, updated_at+)+VALUES+ ('22220004-0000-0000-0000-000000000001', 'tp1', 'a0000004-0000-0000-0000-000000000004',+ true, false, '2026-04-08 10:00:00+00', NULL, '2026-04-08 10:00:00+00', NOW(), NOW()),+ ('22220004-0000-0000-0000-000000000002', 'tp2', 'a0000004-0000-0000-0000-000000000004',+ true, false, '2026-04-09 10:00:00+00', NULL, '2026-04-09 10:00:00+00', NOW(), NOW());++INSERT INTO email_messages (+ id, thread_id, link_id, provider_id, from_contact_id,+ subject, snippet, internal_date_ts,+ is_draft, is_sent, is_starred, is_read,+ created_at, updated_at+)+VALUES+ ('33330004-0000-0000-0000-000000000001', '22220004-0000-0000-0000-000000000001',+ 'a0000004-0000-0000-0000-000000000004', 'mp1', 'c0000012-0000-0000-0000-000000000012',+ 'Alice personal acme', 'personal from acme', '2026-04-08 10:00:00+00',+ false, false, false, false, NOW(), NOW()),+ ('33330004-0000-0000-0000-000000000002', '22220004-0000-0000-0000-000000000002',+ 'a0000004-0000-0000-0000-000000000004', 'mp2', 'c0000013-0000-0000-0000-000000000013',+ 'Alice personal secret', 'personal from secret', '2026-04-09 10:00:00+00',+ false, false, false, false, NOW(), NOW());++INSERT INTO email_message_labels (message_id, label_id)+VALUES+ ('33330004-0000-0000-0000-000000000001', '11110004-0000-0000-0000-000000000001'),+ ('33330004-0000-0000-0000-000000000002', '11110004-0000-0000-0000-000000000001');diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rsindex 2d9eac0f9b..7d0f53f2cf 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs@@ -23,8 +23,11 @@ struct QueryParams {user_id: String,resolved: ResolvedFilters,/// When `Some(team_id)`, the "Owned" candidate source expands from- /// `t.link_id = ANY($link_ids)` to `t.link_id IN (links of every member- /// of $team_id)`. Set only after CRM scope has been validated upstream.+ /// `t.link_id = ANY($link_ids)` to `t.link_id IN (primary links of every+ /// member of $team_id)`. A link is primary when its `email_address` is+ /// the owning member's own macro_id email — connected secondary+ /// mailboxes never feed team-scoped results. Set only after CRM scope+ /// has been validated upstream./// Also switches the candidate select into dedupe mode: team-member/// copies of the same conversation collapse to one row (see/// [`build_query`]).@@ -153,8 +156,10 @@ fn push_thread_candidate_select(builder.push_bind(params.link_ids.clone());builder.push(")");}- // CRM-scoped query: expand to every email_link owned by any- // member of the team. The receipt has already been validated+ // CRM-scoped query: expand to every primary email_link owned by+ // any member of the team. Non-primary links (connected secondary+ // mailboxes, whose address differs from the owner's macro_id+ // email) are excluded. The receipt has already been validated// upstream, so the team_id is trusted here.Some(team_id) => {builder.push(@@ -165,7 +170,7 @@ fn push_thread_candidate_select(WHERE tu.team_id = "#,);builder.push_bind(team_id);- builder.push(")");+ builder.push(" AND el.is_primary)");}},ThreadCandidateSource::Shared => {diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rsindex 12207b6860..569f55d173 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rs@@ -166,8 +166,11 @@ pub(super) fn can_short_circuit(ast: &Expr<EmailLiteral>, resolved: &ResolvedFil/// per-mailbox query) and each address resolves to at most one contact_id;/// the TRASH lookup returns at most one label id.///-/// When `team_id` is `Some`, the scope expands to every `link_id` owned by-/// any user on the team. The same email address may now resolve to multiple+/// When `team_id` is `Some`, the scope expands to every primary `link_id`+/// owned by any user on the team — a link is primary when its+/// `email_address` is the owner's own macro_id email, so connected+/// secondary mailboxes stay out of scope. The same email address may now+/// resolve to multiple/// contact_ids (one per team member who has corresponded with that address),/// and the TRASH lookup returns one label id per team link. The SQL builder/// uses `= ANY($ids)` predicates so messages in *any* team mailbox match.@@ -199,6 +202,7 @@ pub(super) async fn resolve_filters(JOIN email_links el ON el.id = l.link_idJOIN team_user tu ON tu.user_id = el.macro_idWHERE l.name = 'TRASH' AND tu.team_id = $1+ AND el.is_primary"#,team_id,)@@ -235,6 +239,7 @@ pub(super) async fn resolve_filters(JOIN email_links el ON el.id = c.link_idJOIN team_user tu ON tu.user_id = el.macro_idWHERE tu.team_id = $1+ AND el.is_primaryAND LOWER(c.email_address) = ANY($2)"#,team_id,diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rsindex 5552f08c7c..a976c680f2 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs@@ -1074,3 +1074,166 @@ async fn crm_scope_dedupe_mid_thread_join_copies_stay_separate(Ok(())}++// =====================================================================+// Non-primary links — alice has a connected secondary mailbox+// ([email protected]) on the same macro_id. Team scope must only+// read primary links (email_address = the owner's macro_id email), so the+// personal link's threads/contacts/labels never feed team-scoped results.+// =====================================================================++const ALICE_PERSONAL_LINK_ID: &str = "a0000004-0000-0000-0000-000000000004";+const TP1_ALICE_PERSONAL_INBOX_ACME: &str = "22220004-0000-0000-0000-000000000001";+const TP2_ALICE_PERSONAL_INBOX_SECRET: &str = "22220004-0000-0000-0000-000000000002";++// =====================================================================+// 23. Broad team-scoped query: alice's personal-mailbox threads must not+// appear even though their senders match the filter and the link's+// macro_id is a team member.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_crm_scope")+ )+)]+async fn crm_scope_excludes_non_primary_link_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "com".to_string(),+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(+ !ids.contains(TP1_ALICE_PERSONAL_INBOX_ACME),+ "alice's personal-mailbox thread must not appear in team scope"+ );+ assert!(+ !ids.contains(TP2_ALICE_PERSONAL_INBOX_SECRET),+ "alice's personal-mailbox thread must not appear in team scope"+ );+ assert!(ids.contains(TA1_ALICE_INBOX_ACME), "primary link still in");+ assert!(ids.contains(TB1_BOB_INBOX_ACME), "primary link still in");+ assert_eq!(+ ids.len(),+ 4,+ "expected only the 4 primary-link inbox threads, got: {:?}",+ ids+ );++ Ok(())+}++// =====================================================================+// 24. Complete sender under team scope: the address resolves on alice's+// primary, bob's, AND alice's personal link — only the primary-link+// threads come back.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_crm_scope")+ )+)]+async fn crm_scope_complete_sender_skips_non_primary_link(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(complete(+ "[email protected]",+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert!(+ !ids.contains(TP1_ALICE_PERSONAL_INBOX_ACME),+ "personal-mailbox thread from the same sender must not appear"+ );+ assert_eq!(ids.len(), 2, "expected 2 threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 25. An address whose only contact rows live on a non-primary link must+// not resolve under team scope — the query short-circuits to empty+// instead of surfacing the personal mailbox's thread.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_crm_scope")+ )+)]+async fn crm_scope_non_primary_only_contact_does_not_resolve(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(complete(+ "[email protected]",+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(+ ids.is_empty(),+ "[email protected] only exists in alice's personal mailbox; got: {:?}",+ ids+ );++ Ok(())+}++// =====================================================================+// 26. The per-user "Me" path (no team_id) stays multi-inbox-wide: with+// both of alice's links in link_ids, personal-mailbox threads are+// returned alongside primary ones.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_crm_scope")+ )+)]+async fn me_path_still_spans_non_primary_links(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let primary_link = Uuid::parse_str(ALICE_LINK_ID)?;+ let personal_link = Uuid::parse_str(ALICE_PERSONAL_LINK_ID)?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "com".to_string(),+ ))));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results = dynamic::dynamic_email_thread_cursor(+ &pool,+ &[primary_link, personal_link],+ 100,+ &view,+ query,+ "macro|[email protected]",+ None,+ )+ .await?;+ let ids: std::collections::HashSet<String> =+ results.into_iter().map(|r| r.id.to_string()).collect();++ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TA3_ALICE_INBOX_OTHER));+ assert!(ids.contains(TP1_ALICE_PERSONAL_INBOX_ACME));+ assert!(ids.contains(TP2_ALICE_PERSONAL_INBOX_SECRET));+ assert!(!ids.contains(TA2_ALICE_TRASH_ACME), "TRASH excluded");+ assert_eq!(ids.len(), 4, "expected 4 threads, got: {:?}", ids);++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260611154355_add_email_links_is_primary.sql b/rust/cloud-storage/macro_db_client/migrations/20260611154355_add_email_links_is_primary.sqlnew file mode 100644index 0000000000..5d6a2fc3b8--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260611154355_add_email_links_is_primary.sql@@ -0,0 +1,7 @@+-- A link is primary when its email_address is the owning user's own+-- macro_id email (macro_id is the string 'macro|{email}', lowercased).+-- Non-primary links are connected secondary mailboxes. Stored generated+-- so the flag can never drift from the columns that define it.+ALTER TABLE email_links+ ADD COLUMN is_primary boolean NOT NULL+ GENERATED ALWAYS AS (macro_id = 'macro|' || lower(email_address::text)) STORED;