Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email): let inbox delegates open email attachment documents (#6064)

gbirmand6c03da314cf
diff --git a/.sqlx/query-42f11323f1ef8158152eac2e80b8c5f2565184548e269274b19ad675c8e414f5.json b/.sqlx/query-42f11323f1ef8158152eac2e80b8c5f2565184548e269274b19ad675c8e414f5.json
deleted file mode 100644
index 29ccc7f5e0..0000000000
--- a/.sqlx/query-42f11323f1ef8158152eac2e80b8c5f2565184548e269274b19ad675c8e414f5.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: document link share permission\n SELECT\n share_permission.\"linkShareAccessLevel\"::text AS access_level\n FROM \"Document\" document\n JOIN \"DocumentPermission\" document_permission\n ON document_permission.\"documentId\" = document.id\n JOIN \"SharePermission\" share_permission\n ON share_permission.id = document_permission.\"sharePermissionId\"\n WHERE document.id = $3\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n share_permission.\"linkShare\" = 'PUBLIC'\n OR (\n share_permission.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = document.owner\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n ) AS combined_access\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "TextArray",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "42f11323f1ef8158152eac2e80b8c5f2565184548e269274b19ad675c8e414f5"
-}
diff --git a/.sqlx/query-9a7907bed661dcc50e55fc6763766da981e1bc7a1530a8a44c869d11e3f52124.json b/.sqlx/query-9a7907bed661dcc50e55fc6763766da981e1bc7a1530a8a44c869d11e3f52124.json
new file mode 100644
index 0000000000..8f25378810
--- /dev/null
+++ b/.sqlx/query-9a7907bed661dcc50e55fc6763766da981e1bc7a1530a8a44c869d11e3f52124.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: document link share permission\n SELECT\n share_permission.\"linkShareAccessLevel\"::text AS access_level\n FROM \"Document\" document\n JOIN \"DocumentPermission\" document_permission\n ON document_permission.\"documentId\" = document.id\n JOIN \"SharePermission\" share_permission\n ON share_permission.id = document_permission.\"sharePermissionId\"\n WHERE document.id = $3\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n share_permission.\"linkShare\" = 'PUBLIC'\n OR (\n share_permission.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = document.owner\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n\n UNION ALL\n -- Source 3: email-attachment documents inherit access from any\n -- linked thread the caller can reach. Owning or being delegated\n -- the thread's inbox (macro_user_links) grants Edit, mirroring\n -- calendar-event delegation. A thread-level entity_access grant\n -- inherits as View regardless of its level: a SHA-deduped document\n -- can back attachments in other threads with different audiences,\n -- so a per-thread share must not confer write access to it.\n SELECT CASE\n WHEN l.macro_id = $4\n OR EXISTS (\n SELECT 1\n FROM macro_user_links mul\n WHERE mul.link_id = l.id\n AND mul.primary_macro_id = $4\n )\n THEN 'edit'\n ELSE 'view'\n END AS access_level\n FROM document_email de\n JOIN email_attachments ea ON ea.id = de.email_attachment_id\n JOIN email_messages em ON em.id = ea.message_id\n JOIN email_threads t ON t.id = em.thread_id\n JOIN email_links l ON l.id = t.link_id\n WHERE de.document_id = $3\n AND (\n l.macro_id = $4\n OR EXISTS (\n SELECT 1\n FROM macro_user_links mul\n WHERE mul.link_id = l.id\n AND mul.primary_macro_id = $4\n )\n OR EXISTS (\n SELECT 1\n FROM entity_access thread_access\n WHERE thread_access.entity_id = t.id\n AND thread_access.entity_type = 'email_thread'\n AND thread_access.source_id = ANY($2)\n )\n )\n ) AS combined_access\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "9a7907bed661dcc50e55fc6763766da981e1bc7a1530a8a44c869d11e3f52124"
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index a1a9014aa3..c1ae9f45e3 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -71,10 +71,13 @@ impl AccessRepository for PgAccessRepository {
let source_ids = queries::get_user_source_ids(&self.pool, user_id)
.await
.map_err(anyhow_access_error)?;
- Ok(
- queries::document_access::get_document_access(&self.pool, &document_uuid, &source_ids)
- .await?,
+ Ok(queries::document_access::get_document_access(
+ &self.pool,
+ &document_uuid,
+ &source_ids,
+ user_id,
)
+ .await?)
}
#[tracing::instrument(err, skip(self))]
@@ -270,8 +273,13 @@ impl AccessRepository for PgAccessRepository {
let access = match entity_type {
EntityType::Document => {
- queries::document_access::get_document_access(&self.pool, &entity_uuid, &source_ids)
- .await
+ queries::document_access::get_document_access(
+ &self.pool,
+ &entity_uuid,
+ &source_ids,
+ None,
+ )
+ .await
}
EntityType::Chat => {
queries::chat_access::get_chat_access(&self.pool, &entity_uuid, &source_ids).await
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
index 44fa4ccce4..d10844edfd 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
@@ -4,6 +4,7 @@
mod test;
use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use sqlx::PgPool;
use std::str::FromStr;
@@ -13,6 +14,7 @@ pub async fn get_document_access(
pool: &PgPool,
document_id: &uuid::Uuid,
source_ids: &SourceIds,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, sqlx::Error> {
// Check share permission access only
if source_ids.0.is_empty() {
@@ -35,6 +37,8 @@ pub async fn get_document_access(
return Ok(access_level);
}
+ let user_id_str = user_id.map(AsRef::as_ref).unwrap_or("");
+
let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(
r#"
SELECT access_level FROM (
@@ -68,11 +72,54 @@ pub async fn get_document_access(
)
)
)
+
+ UNION ALL
+ -- Source 3: email-attachment documents inherit access from any
+ -- linked thread the caller can reach. Owning or being delegated
+ -- the thread's inbox (macro_user_links) grants Edit, mirroring
+ -- calendar-event delegation. A thread-level entity_access grant
+ -- inherits as View regardless of its level: a SHA-deduped document
+ -- can back attachments in other threads with different audiences,
+ -- so a per-thread share must not confer write access to it.
+ SELECT CASE
+ WHEN l.macro_id = $4
+ OR EXISTS (
+ SELECT 1
+ FROM macro_user_links mul
+ WHERE mul.link_id = l.id
+ AND mul.primary_macro_id = $4
+ )
+ THEN 'edit'
+ ELSE 'view'
+ END AS access_level
+ FROM document_email de
+ JOIN email_attachments ea ON ea.id = de.email_attachment_id
+ JOIN email_messages em ON em.id = ea.message_id
+ JOIN email_threads t ON t.id = em.thread_id
+ JOIN email_links l ON l.id = t.link_id
+ WHERE de.document_id = $3
+ AND (
+ l.macro_id = $4
+ OR EXISTS (
+ SELECT 1
+ FROM macro_user_links mul
+ WHERE mul.link_id = l.id
+ AND mul.primary_macro_id = $4
+ )
+ OR EXISTS (
+ SELECT 1
+ FROM entity_access thread_access
+ WHERE thread_access.entity_id = t.id
+ AND thread_access.entity_type = 'email_thread'
+ AND thread_access.source_id = ANY($2)
+ )
+ )
) AS combined_access
"#,
document_id,
&source_ids.0,
- &document_id.to_string()
+ &document_id.to_string(),
+ user_id_str,
)
.fetch_all(pool)
.await?;
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs
index 9f30b3019f..4bca3296df 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs
@@ -1,5 +1,6 @@
use super::*;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
use uuid::Uuid;
@@ -144,7 +145,7 @@ async fn public_link_allows_anonymous_access(pool: PgPool) -> anyhow::Result<()>
insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, Some("PUBLIC"), Some("view"))
.await?;
- let access = get_document_access(&pool, &document_id, &SourceIds(vec![])).await?;
+ let access = get_document_access(&pool, &document_id, &SourceIds(vec![]), None).await?;
assert_eq!(access, Some(AccessLevel::View));
Ok(())
@@ -156,7 +157,7 @@ async fn null_link_denies_access(pool: PgPool) -> anyhow::Result<()> {
let document_id = insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, None, None).await?;
let source_ids = SourceIds(vec!["macro|[email protected]".to_string()]);
- let access = get_document_access(&pool, &document_id, &source_ids).await?;
+ let access = get_document_access(&pool, &document_id, &source_ids, None).await?;
assert_eq!(access, None);
Ok(())
@@ -171,7 +172,7 @@ async fn team_link_allows_same_team_access(pool: PgPool) -> anyhow::Result<()> {
insert_link_shared_document(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("comment")).await?;
let source_ids = SourceIds(vec![owner_team_id.to_string()]);
- let access = get_document_access(&pool, &document_id, &source_ids).await?;
+ let access = get_document_access(&pool, &document_id, &source_ids, None).await?;
assert_eq!(access, Some(AccessLevel::Comment));
Ok(())
@@ -186,7 +187,7 @@ async fn team_link_denies_other_team_access(pool: PgPool) -> anyhow::Result<()>
insert_link_shared_document(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("comment")).await?;
let source_ids = SourceIds(vec![Uuid::new_v4().to_string()]);
- let access = get_document_access(&pool, &document_id, &source_ids).await?;
+ let access = get_document_access(&pool, &document_id, &source_ids, None).await?;
assert_eq!(access, None);
Ok(())
@@ -200,7 +201,7 @@ async fn team_link_denies_anonymous_access(pool: PgPool) -> anyhow::Result<()> {
let document_id =
insert_link_shared_document(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("edit")).await?;
- let access = get_document_access(&pool, &document_id, &SourceIds(vec![])).await?;
+ let access = get_document_access(&pool, &document_id, &SourceIds(vec![]), None).await?;
assert_eq!(access, None);
Ok(())
@@ -213,7 +214,7 @@ async fn team_link_denies_access_when_owner_has_no_team(pool: PgPool) -> anyhow:
insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, Some("TEAM"), Some("edit")).await?;
let source_ids = SourceIds(vec![Uuid::new_v4().to_string()]);
- let access = get_document_access(&pool, &document_id, &source_ids).await?;
+ let access = get_document_access(&pool, &document_id, &source_ids, None).await?;
assert_eq!(access, None);
Ok(())
@@ -225,7 +226,7 @@ async fn public_link_requires_an_access_level(pool: PgPool) -> anyhow::Result<()
let document_id =
insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, Some("PUBLIC"), None).await?;
- let access = get_document_access(&pool, &document_id, &SourceIds(vec![])).await?;
+ let access = get_document_access(&pool, &document_id, &SourceIds(vec![]), None).await?;
assert_eq!(access, None);
Ok(())
@@ -242,8 +243,282 @@ async fn returns_highest_link_or_explicit_access_level(pool: PgPool) -> anyhow::
insert_document_entity_access(&pool, document_id, REQUESTER, AccessLevel::Edit).await?;
let source_ids = SourceIds(vec![REQUESTER.to_string()]);
- let access = get_document_access(&pool, &document_id, &source_ids).await?;
+ let access = get_document_access(&pool, &document_id, &source_ids, None).await?;
assert_eq!(access, Some(AccessLevel::Edit));
Ok(())
}
+
+// ---------------------------------------------------------------------------
+// Email-attachment documents: access inherited from the linked thread
+// (inbox owner, macro_user_links delegation, or a thread-level grant)
+// ---------------------------------------------------------------------------
+
+const INBOX_OWNER: &str = "macro|[email protected]";
+const DELEGATE: &str = "macro|[email protected]";
+const OTHER_USER: &str = "macro|[email protected]";
+
+fn user(s: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(s.to_string()).unwrap()
+}
+
+/// Runs `get_document_access` as an authenticated `user_id` whose only source
+/// id is itself, so any grant must come through a user-keyed arm.
+async fn access_as(pool: &PgPool, document_id: &Uuid, user_id: &str) -> Option<AccessLevel> {
+ let requester = user(user_id);
+ let source_ids = SourceIds(vec![user_id.to_string()]);
+ get_document_access(pool, document_id, &source_ids, Some(&*requester))
+ .await
+ .unwrap()
+}
+
+/// A bare "Document" row owned by `owner` — no share permission, and no
+/// entity_access rows (unlike prod, where the owner gets one at creation), so
+/// tests observe the email arm alone.
+async fn insert_document(pool: &PgPool, owner: &str) -> Uuid {
+ let document_id = Uuid::new_v4();
+ sqlx::query!(
+ r#"INSERT INTO "Document" (id, name, owner) VALUES ($1, 'Email Attachment', $2)"#,
+ document_id.to_string(),
+ owner,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ document_id
+}
+
+/// An inbox link for `owner_macro_id` holding one thread with one message.
+/// Returns `(link_id, thread_id)`.
+async fn insert_link_and_thread(pool: &PgPool, owner_macro_id: &str) -> (Uuid, 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!("{link_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();
+
+ (link_id, thread_id)
+}
+
+/// A message + attachment on `thread_id`, with the attachment linked to
+/// `document_id` via document_email.
+async fn attach_document_to_thread(
+ pool: &PgPool,
+ link_id: Uuid,
+ thread_id: Uuid,
+ document_id: Uuid,
+) {
+ let message_id = Uuid::new_v4();
+ let attachment_id = Uuid::new_v4();
+
+ sqlx::query!(
+ r#"INSERT INTO email_messages (id, thread_id, link_id) VALUES ($1, $2, $3)"#,
+ message_id,
+ thread_id,
+ link_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+
+ sqlx::query!(
+ r#"INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type)
+ VALUES ($1, $2, $3, 'report.pdf', 'application/pdf')"#,
+ attachment_id,
+ message_id,
+ attachment_id.to_string(),
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+
+ sqlx::query!(
+ r#"INSERT INTO document_email (document_id, email_attachment_id) VALUES ($1, $2)"#,
+ document_id.to_string(),
+ attachment_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+/// Inbox + thread + message + attachment linked to a fresh document owned by
+/// `owner_macro_id`. Returns `(link_id, thread_id, document_id)`.
+async fn insert_attachment_document(pool: &PgPool, owner_macro_id: &str) -> (Uuid, Uuid, Uuid) {
+ let document_id = insert_document(pool, owner_macro_id).await;
+ let (link_id, thread_id) = insert_link_and_thread(pool, owner_macro_id).await;
+ attach_document_to_thread(pool, link_id, thread_id, document_id).await;
+ (link_id, thread_id, document_id)
+}
+
+/// `primary_macro_id` is delegated `child_macro_id`'s `link_id` inbox.
+async fn insert_delegation(
+ pool: &PgPool,
+ primary_macro_id: &str,
+ child_macro_id: &str,
+ link_id: Uuid,
+) {
+ sqlx::query!(
+ r#"INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)
+ VALUES ($1, $2, $3)"#,
+ primary_macro_id,
+ child_macro_id,
+ link_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn insert_thread_entity_access(
+ pool: &PgPool,
+ thread_id: Uuid,
+ source_id: &str,
+ level: AccessLevel,
+) {
+ let level_str = level.to_string();
+ sqlx::query!(
+ r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, 'email_thread', $2, 'user', $3::text::"AccessLevel")"#,
+ thread_id,
+ source_id,
+ level_str,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_delegate_gets_edit_on_attachment_document(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, INBOX_OWNER).await?;
+ insert_user(&pool, DELEGATE).await?;
+ let (link_id, _, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+ insert_delegation(&pool, DELEGATE, INBOX_OWNER, link_id).await;
+
+ assert_eq!(
+ access_as(&pool, &document_id, DELEGATE).await,
+ Some(AccessLevel::Edit)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_inbox_owner_gets_edit_without_entity_access_row(pool: PgPool) -> anyhow::Result<()> {
+ // The owner normally holds an entity_access Owner row from document
+ // creation; this proves the email arm alone also reaches them.
+ insert_user(&pool, INBOX_OWNER).await?;
+ let (_, _, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+
+ assert_eq!(
+ access_as(&pool, &document_id, INBOX_OWNER).await,
+ Some(AccessLevel::Edit)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_thread_grant_gives_view_capped_below_thread_level(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // An Edit grant on the thread inherits as View on the attachment document.
+ insert_user(&pool, INBOX_OWNER).await?;
+ insert_user(&pool, OTHER_USER).await?;
+ let (_, thread_id, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+ insert_thread_entity_access(&pool, thread_id, OTHER_USER, AccessLevel::Edit).await;
+
+ assert_eq!(
+ access_as(&pool, &document_id, OTHER_USER).await,
+ Some(AccessLevel::View)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_no_thread_relationship_denies_access(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, INBOX_OWNER).await?;
+ insert_user(&pool, OTHER_USER).await?;
+ let (_, _, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+
+ assert_eq!(access_as(&pool, &document_id, OTHER_USER).await, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_delegation_on_another_link_denies_access(pool: PgPool) -> anyhow::Result<()> {
+ // The delegate holds a grant on a different inbox of the same owner; the
+ // link-scoped delegation must not reach this attachment.
+ insert_user(&pool, INBOX_OWNER).await?;
+ insert_user(&pool, DELEGATE).await?;
+ let (_, _, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+ let (other_link_id, _) = insert_link_and_thread(&pool, INBOX_OWNER).await;
+ insert_delegation(&pool, DELEGATE, INBOX_OWNER, other_link_id).await;
+
+ assert_eq!(access_as(&pool, &document_id, DELEGATE).await, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_any_linked_thread_grants_access(pool: PgPool) -> anyhow::Result<()> {
+ // SHA dedupe links one document to attachments in several threads; access
+ // to any one of them is enough.
+ insert_user(&pool, INBOX_OWNER).await?;
+ insert_user(&pool, DELEGATE).await?;
+ let (_, _, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+ let (second_link_id, second_thread_id) = insert_link_and_thread(&pool, INBOX_OWNER).await;
+ attach_document_to_thread(&pool, second_link_id, second_thread_id, document_id).await;
+ insert_delegation(&pool, DELEGATE, INBOX_OWNER, second_link_id).await;
+
+ assert_eq!(
+ access_as(&pool, &document_id, DELEGATE).await,
+ Some(AccessLevel::Edit)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_arm_never_grants_anonymous_access(pool: PgPool) -> anyhow::Result<()> {
+ // With no user the anonymous branch runs and consults only PUBLIC link
+ // shares — the email relationship grants nothing.
+ insert_user(&pool, INBOX_OWNER).await?;
+ let (_, _, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+
+ let access = get_document_access(&pool, &document_id, &SourceIds(vec![]), None).await?;
+
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_direct_document_grant_wins_over_inherited_view(pool: PgPool) -> anyhow::Result<()> {
+ // Thread-grant inheritance contributes View; a direct document Edit grant
+ // must win the max.
+ insert_user(&pool, INBOX_OWNER).await?;
+ insert_user(&pool, OTHER_USER).await?;
+ let (_, thread_id, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+ insert_thread_entity_access(&pool, thread_id, OTHER_USER, AccessLevel::View).await;
+ insert_document_entity_access(&pool, document_id, OTHER_USER, AccessLevel::Edit).await?;
+
+ assert_eq!(
+ access_as(&pool, &document_id, OTHER_USER).await,
+ Some(AccessLevel::Edit)
+ );
+ Ok(())
+}
diff --git a/crates/macro_db_client/fixtures/document_access_via_email_thread.sql b/crates/macro_db_client/fixtures/document_access_via_email_thread.sql
deleted file mode 100644
index 60f2b953d9..0000000000
--- a/crates/macro_db_client/fixtures/document_access_via_email_thread.sql
+++ /dev/null
@@ -1,78 +0,0 @@
--- Fixture for testing document access inherited from email thread permissions.
--- Sets up documents that are email attachments linked to threads, with various
--- thread permission configurations.
-
-TRUNCATE TABLE public."User", public."Project", public."Document", public."SharePermission",
- public."DocumentPermission", public."ProjectPermission", public."EmailThreadPermission",
- public.entity_access, public.email_links, public.email_threads, public.email_messages,
- public.email_attachments, public.document_email RESTART IDENTITY CASCADE;
-
-------------------------------------------------------------
--- Users
-------------------------------------------------------------
-INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id")
-VALUES ('a1111111-1111-1111-1111-111111111111', 'user_thread', '[email protected]', 'stripe_user_thread'),
- ('a2222222-2222-2222-2222-222222222222', 'user_none', '[email protected]', 'stripe_user_none'),
- ('a3333333-3333-3333-3333-333333333333', 'user_both', '[email protected]', 'stripe_user_both');
-INSERT INTO public."User" ("id", "email", "macro_user_id")
-VALUES ('user-thread-access', '[email protected]', 'a1111111-1111-1111-1111-111111111111'), -- Has thread access only
- ('user-no-access', '[email protected]', 'a2222222-2222-2222-2222-222222222222'), -- Has no access at all
- ('user-both-access', '[email protected]', 'a3333333-3333-3333-3333-333333333333'); -- Has both direct doc and thread access
-
-------------------------------------------------------------
--- Email infrastructure: link, thread, message, attachment
-------------------------------------------------------------
-INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
-VALUES ('a0000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'a0000000-0000-0000-0000-000000000001',
- '[email protected]', 'GMAIL', true, NOW(), NOW());
-
-INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
-VALUES ('a0000000-0000-0000-0000-000000000010', 'a0000000-0000-0000-0000-000000000001', false, false, NOW(), NOW()),
- ('a0000000-0000-0000-0000-000000000020', 'a0000000-0000-0000-0000-000000000001', false, false, NOW(), NOW());
-
-INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, internal_date_ts,
- has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
-VALUES ('a0000000-0000-0000-0000-000000000100', 'a0000000-0000-0000-0000-000000000010',
- 'a0000000-0000-0000-0000-000000000001', 'provider-msg-1', false, NOW(), true, false, false, false, NOW(), NOW()),
- ('a0000000-0000-0000-0000-000000000200', 'a0000000-0000-0000-0000-000000000020',
- 'a0000000-0000-0000-0000-000000000001', 'provider-msg-2', false, NOW(), true, false, false, false, NOW(), NOW());
-
-INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)
-VALUES ('a0000000-0000-0000-0000-000000001000', 'a0000000-0000-0000-0000-000000000100', 'prov-att-1', 'report.pdf', 'application/pdf', NOW()),
- ('a0000000-0000-0000-0000-000000002000', 'a0000000-0000-0000-0000-000000000200', 'prov-att-2', 'invoice.pdf', 'application/pdf', NOW());
-
-------------------------------------------------------------
--- Documents (email attachments uploaded as documents)
-------------------------------------------------------------
--- d-attachment: linked to thread 1 via email attachment, no direct permissions
--- d-attachment-with-direct: linked to thread 2 via email attachment, also has direct access
--- d-not-attachment: regular document, not linked to any email
-INSERT INTO public."Document" ("id", "name", "owner")
-VALUES ('dddddddd-dddd-dddd-dddd-100000000001', 'Email Attachment Doc', 'user-thread-access'),
- ('dddddddd-dddd-dddd-dddd-100000000002', 'Email Attachment With Direct Access', 'user-both-access'),
- ('dddddddd-dddd-dddd-dddd-100000000003', 'Regular Document', 'user-no-access');
-
--- Link documents to email attachments
-INSERT INTO document_email (document_id, email_attachment_id)
-VALUES ('dddddddd-dddd-dddd-dddd-100000000001', 'a0000000-0000-0000-0000-000000001000'),
- ('dddddddd-dddd-dddd-dddd-100000000002', 'a0000000-0000-0000-0000-000000002000');
-
-------------------------------------------------------------
--- Thread permissions (via EmailThreadPermission + SharePermission)
-------------------------------------------------------------
-INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")
-VALUES ('sp-thread-1', NULL, NULL),
- ('sp-thread-2', NULL, NULL);
-
-INSERT INTO public."EmailThreadPermission" ("threadId", "sharePermissionId", "userId")
-VALUES ('a0000000-0000-0000-0000-000000000010', 'sp-thread-1', 'user-thread-access'),
- ('a0000000-0000-0000-0000-000000000020', 'sp-thread-2', 'user-both-access');
-
--- user-thread-access has view on thread 1 (so should get view on d-attachment)
--- user-both-access has edit on thread 2
-INSERT INTO public.entity_access ("entity_id", "entity_type", "source_id", "source_type", "access_level")
-VALUES
- ('a0000000-0000-0000-0000-000000000010', 'thread', 'user-thread-access', 'user', 'view'),
- ('a0000000-0000-0000-0000-000000000020', 'thread', 'user-both-access', 'user', 'edit'),
- -- user-both-access also has direct view on d-attachment-with-direct (thread gives edit, so edit should win)
- ('dddddddd-dddd-dddd-dddd-100000000002', 'document', 'user-both-access', 'user', 'view');