Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(email): grant project-scoped email thread access (#4556)

Evan Hutnikb2043c47442e
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 7440e15c91..9db837139b 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -132,6 +132,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -152,6 +154,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -456,6 +459,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -546,6 +550,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -729,6 +734,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -824,6 +830,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -1065,6 +1072,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"ip_extractor",
@@ -1191,6 +1199,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -1706,6 +1715,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -1765,6 +1775,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -1778,6 +1790,7 @@
"model_user",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -1836,6 +1849,8 @@
"email_refresh_handler",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -1854,6 +1869,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -1877,6 +1893,8 @@
"email_scheduled_handler",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -1895,6 +1913,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -1926,6 +1945,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"gmail_client",
@@ -1995,6 +2015,8 @@
"email_service_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -2008,6 +2030,7 @@
"model_user",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -2029,6 +2052,8 @@
"email_sfs_delete_handler",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -2047,6 +2072,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -2346,6 +2372,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"foreign_entity",
"frecency",
@@ -2520,6 +2547,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -3173,6 +3201,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -3255,6 +3284,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -3486,6 +3516,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -3504,6 +3536,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -3527,6 +3560,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -3545,6 +3580,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -3857,6 +3893,7 @@
"ensure_exists",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -3942,6 +3979,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -4021,6 +4059,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -4087,6 +4126,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -4106,6 +4147,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -4145,6 +4187,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"fusionauth",
@@ -4250,6 +4293,7 @@
"email_utils",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"foreign_entity",
"frecency",
@@ -4315,6 +4359,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -4329,6 +4375,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -4472,6 +4519,7 @@
"embedding",
"entity_access",
"entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -4543,6 +4591,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"invite_email",
@@ -4564,6 +4614,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -4611,6 +4662,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -4629,6 +4682,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
@@ -4653,6 +4707,8 @@
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_db_utils",
+ "entity_access_management",
"filter_ast",
"frecency",
"item_filters",
@@ -4671,6 +4727,7 @@
"models_ai_projection",
"models_bulk_upload",
"models_email",
+ "models_entity_access_management",
"models_pagination",
"models_permissions",
"non_empty",
diff --git a/js/app/packages/block-project/component/Block.tsx b/js/app/packages/block-project/component/Block.tsx
index b96115e6c4..6db7fb0525 100644
--- a/js/app/packages/block-project/component/Block.tsx
+++ b/js/app/packages/block-project/component/Block.tsx
@@ -208,6 +208,8 @@ const ProjectEntityList = (props: {
// Filter emails by project
emailProjectId: [props.projectId],
},
+ // Default 'inbox' view would hide archived/outbound-only threads
+ emailView: 'all',
})}
>
<SoupViewList customScrollbarHidden={true} scopeId={props.scopeId} />
diff --git a/rust/cloud-storage/.sqlx/query-775a3c1e4a6365516cc07a60cdfe1913f1fa8606bdb384b8e697cb5c723cf40b.json b/rust/cloud-storage/.sqlx/query-2038e9067126322569af303a5008cc0e58c09fa4cc0ac7d907ea2d7f0cf91e31.json
similarity index 66%
rename from rust/cloud-storage/.sqlx/query-775a3c1e4a6365516cc07a60cdfe1913f1fa8606bdb384b8e697cb5c723cf40b.json
rename to rust/cloud-storage/.sqlx/query-2038e9067126322569af303a5008cc0e58c09fa4cc0ac7d907ea2d7f0cf91e31.json
index 5c4142face..5e84f18efd 100644
--- a/rust/cloud-storage/.sqlx/query-775a3c1e4a6365516cc07a60cdfe1913f1fa8606bdb384b8e697cb5c723cf40b.json
+++ b/rust/cloud-storage/.sqlx/query-2038e9067126322569af303a5008cc0e58c09fa4cc0ac7d907ea2d7f0cf91e31.json
@@ -1,6 +1,6 @@
{
"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 = 'email_thread'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: items share permission\n SELECT\n \"publicAccessLevel\"::text AS access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $3\n )\n ) AS combined_access\n ",
+ "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 = 'email_thread'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: items share permission\n SELECT\n \"publicAccessLevel\"::text AS access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $3\n )\n\n UNION ALL\n -- Source 3: access to the thread's containing project grants View\n SELECT 'view' AS access_level\n FROM email_threads t\n JOIN entity_access pea ON pea.entity_id::text = t.project_id\n AND pea.entity_type = 'project'\n AND pea.source_id = ANY($2)\n WHERE t.id = $1::uuid\n ) AS combined_access\n ",
"describe": {
"columns": [
{
@@ -20,5 +20,5 @@
null
]
},
- "hash": "775a3c1e4a6365516cc07a60cdfe1913f1fa8606bdb384b8e697cb5c723cf40b"
+ "hash": "2038e9067126322569af303a5008cc0e58c09fa4cc0ac7d907ea2d7f0cf91e31"
}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index b1c4f588f8..2e685f510e 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4618,6 +4618,7 @@ dependencies = [
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_management",
"filter_ast",
"frecency",
"futures",
@@ -4782,6 +4783,7 @@ dependencies = [
"email_db_client",
"email_utils",
"entity_access",
+ "entity_access_management",
"filter_ast",
"frecency",
"futures",
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index aa8dac4218..605bb082a6 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -193,6 +193,9 @@ pub async fn build_tool_service_context_from_env(
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
0,
);
let channels_service = ChannelListServiceImpl::new(
@@ -281,6 +284,9 @@ pub async fn build_tool_service_context_from_env(
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),
sqs_client,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
0,
)),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 56bbd90fd5..b1cdff3cfa 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -52,17 +52,29 @@ pub type ToolCrmService = crm::domain::service::CrmServiceImpl<
crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,
>;
+/// Type alias for the entity access management service implementation.
+pub type ToolEamService =
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl<
+ entity_access_management::outbound::PgRepository,
+ >;
+
/// Type alias for the email service implementation
pub type ToolEmailService = EmailServiceImpl<
EmailPgRepo,
ToolFrecencyService,
email::domain::ports::NoOpEnqueuer,
ToolCrmService,
+ ToolEamService,
>;
/// Type alias for the send-capable email service implementation used by user tools.
-pub type ToolUserEmailService =
- EmailServiceImpl<EmailPgRepo, ToolFrecencyService, sqs_client::SQS, ToolCrmService>;
+pub type ToolUserEmailService = EmailServiceImpl<
+ EmailPgRepo,
+ ToolFrecencyService,
+ sqs_client::SQS,
+ ToolCrmService,
+ ToolEamService,
+>;
/// Type alias for the channel list service implementation.
pub type ToolCommsService = ChannelListServiceImpl<
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 0832e17ee3..a1b196e20e 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -170,6 +170,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
0,
);
let channels_service = ChannelListServiceImpl::new(
@@ -288,6 +291,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
),
sqs_client.clone(),
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
0,
)),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 927f75d439..918fdfc091 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -224,6 +224,9 @@ async fn main() -> anyhow::Result<()> {
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
0,
);
let channels_service = ChannelListServiceImpl::new(
@@ -349,6 +352,9 @@ async fn main() -> anyhow::Result<()> {
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
sqs_client.clone(),
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
0,
)),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 5d07252f6d..e05025d64b 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -111,6 +111,7 @@ type DssEmailService = EmailServiceImpl<
FrecencyQueryServiceImpl<FrecencyPgStorage>,
email::domain::ports::NoOpEnqueuer,
DssCrmService,
+ EntityAccessManagementService,
>;
/// CRM router state.
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index ea6d74e2ae..35b531f30d 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -258,6 +258,9 @@ async fn main() -> anyhow::Result<()> {
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
0,
);
let readonly_email_service = ReadonlyEmailPreviewAdapter(EmailServiceImpl::new(
@@ -265,6 +268,9 @@ async fn main() -> anyhow::Result<()> {
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(readonly_db.clone()),
+ ),
0,
));
let system_properties_service =
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index dc4065635f..5775ce25ce 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -45,6 +45,9 @@ anyhow = { workspace = true }
async-trait = { workspace = true, optional = true }
base64 = { workspace = true }
entity_access = { path = "../entity_access" }
+entity_access_management = { path = "../entity_access_management", default-features = false, features = [
+ "ports",
+] }
futures = { workspace = true }
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_shared.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_shared.sql
index 3fd77f7d9d..c1861585be 100644
--- a/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_shared.sql
+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_dedupe_shared.sql
@@ -62,4 +62,4 @@ VALUES
-- Direct share of faye's thread with dave
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
VALUES
- ('55550003-0000-0000-0000-000000000001'::uuid, 'thread', 'macro|[email protected]', 'user', 'view');
+ ('55550003-0000-0000-0000-000000000001'::uuid, 'email_thread', 'macro|[email protected]', 'user', 'view');
diff --git a/rust/cloud-storage/email/fixtures/email_project_scope.sql b/rust/cloud-storage/email/fixtures/email_project_scope.sql
new file mode 100644
index 0000000000..5e9c83e984
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_project_scope.sql
@@ -0,0 +1,103 @@
+-- Fixture for project-scoped dynamic query tests. Builds on
+-- email_dynamic_query + email_shared_threads (user1/link aaaa, user2/link bbbb,
+-- shared project cccccccc with a 'view' grant for user1, thread 102 in it).
+--
+-- Adds:
+-- * user1's own threads filed into projects (301 in shared cccccccc,
+-- 302 in user2's private project)
+-- * a team-granted project (dddd0000) with a user2 thread (105)
+-- * a private user2 project (eeee0000) with a user2 thread (106)
+-- * a non-inbox user2 thread in the shared project (107)
+
+-- == Team: user1 is a member, project dddd0000 is granted to the team ==
+INSERT INTO team (id, name, owner_id)
+VALUES ('77770000-0000-0000-0000-000000007777', 'Scope Team', 'macro|[email protected]');
+
+INSERT INTO team_user (user_id, team_id, team_role)
+VALUES
+ ('macro|[email protected]', '77770000-0000-0000-0000-000000007777', 'owner'),
+ ('macro|[email protected]', '77770000-0000-0000-0000-000000007777', 'member');
+
+-- == Projects owned by user2 ==
+INSERT INTO "Project" (id, name, "userId", "createdAt", "updatedAt")
+VALUES
+ ('dddd0000-0000-0000-0000-00000000dddd', 'Team Project', 'macro|[email protected]', NOW(), NOW()),
+ ('eeee0000-0000-0000-0000-00000000eeee', 'Private Project', 'macro|[email protected]', NOW(), NOW());
+
+-- Team grant on the team project. No grants at all on the private project.
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+VALUES ('dddd0000-0000-0000-0000-00000000dddd'::uuid, 'project', '77770000-0000-0000-0000-000000007777', 'team', 'view');
+
+-- == user1's own threads filed into projects ==
+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, project_id
+)
+VALUES
+ -- Thread 301: user1's own thread in the shared project cccccccc
+ ('20000301-0000-0000-0000-000000000301', 'own_in_shared_project', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ true, false, '2024-03-01 10:00:00+00', NULL, '2024-03-01 10:00:00+00', NOW(), NOW(),
+ 'cccccccc-cccc-cccc-cccc-cccccccccccc'),
+
+ -- Thread 302: user1's own thread filed into user2's PRIVATE project
+ -- (owned-branch visibility must not depend on project access)
+ ('20000302-0000-0000-0000-000000000302', 'own_in_private_project', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ true, false, '2024-03-02 10:00:00+00', NULL, '2024-03-02 10:00:00+00', NOW(), NOW(),
+ 'eeee0000-0000-0000-0000-00000000eeee');
+
+-- == user2's threads ==
+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, project_id
+)
+VALUES
+ -- Thread 105: in the team-granted project
+ ('20000105-0000-0000-0000-000000000105', 'team_project_thread', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ true, false, '2024-03-05 10:00:00+00', NULL, '2024-03-05 10:00:00+00', NOW(), NOW(),
+ 'dddd0000-0000-0000-0000-00000000dddd'),
+
+ -- Thread 106: in user2's private project (user1 must never see it)
+ ('20000106-0000-0000-0000-000000000106', 'private_project_thread', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ true, false, '2024-03-06 10:00:00+00', NULL, '2024-03-06 10:00:00+00', NOW(), NOW(),
+ 'eeee0000-0000-0000-0000-00000000eeee'),
+
+ -- Thread 107: in the shared project but NOT inbox-visible (archived,
+ -- outbound-only) — view filters must still apply to widened threads
+ ('20000107-0000-0000-0000-000000000107', 'archived_project_thread', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ false, false, NULL, '2024-03-07 10:00:00+00', '2024-03-07 10:00:00+00', NOW(), NOW(),
+ 'cccccccc-cccc-cccc-cccc-cccccccccccc');
+
+-- == Messages (the query's lateral requires one per thread) ==
+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
+ ('30000301-0000-0000-0000-000000000301', '20000301-0000-0000-0000-000000000301',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'own_shared_msg', '40000001-0000-0000-0000-000000000001',
+ 'Own In Shared Project', 'My thread in the shared project', '2024-03-01 10:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ ('30000302-0000-0000-0000-000000000302', '20000302-0000-0000-0000-000000000302',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'own_private_msg', '40000001-0000-0000-0000-000000000001',
+ 'Own In Private Project', 'My thread in a project I lost access to', '2024-03-02 10:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ ('30000105-0000-0000-0000-000000000105', '20000105-0000-0000-0000-000000000105',
+ 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'team_project_msg', '40000005-0000-0000-0000-000000000005',
+ 'Team Project Thread', 'Visible through the team grant', '2024-03-05 10:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ ('30000106-0000-0000-0000-000000000106', '20000106-0000-0000-0000-000000000106',
+ 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'private_project_msg', '40000005-0000-0000-0000-000000000005',
+ 'Private Project Thread', 'Should stay hidden from user1', '2024-03-06 10:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ ('30000107-0000-0000-0000-000000000107', '20000107-0000-0000-0000-000000000107',
+ 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'archived_project_msg', '40000005-0000-0000-0000-000000000005',
+ 'Archived Project Thread', 'Outbound-only thread in the shared project', '2024-03-07 10:00:00+00',
+ false, true, false, false, NOW(), NOW());
diff --git a/rust/cloud-storage/email/fixtures/email_shared_threads.sql b/rust/cloud-storage/email/fixtures/email_shared_threads.sql
index 521addcf18..fc836a95c9 100644
--- a/rust/cloud-storage/email/fixtures/email_shared_threads.sql
+++ b/rust/cloud-storage/email/fixtures/email_shared_threads.sql
@@ -68,11 +68,11 @@ VALUES
-- Direct share: thread 101 shared with user1
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
-VALUES ('20000101-0000-0000-0000-000000000101'::uuid, 'thread', 'macro|[email protected]', 'user', 'view');
+VALUES ('20000101-0000-0000-0000-000000000101'::uuid, 'email_thread', 'macro|[email protected]', 'user', 'view');
-- Denormalized row: thread 102 inherits access from the shared project
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
-VALUES ('20000102-0000-0000-0000-000000000102'::uuid, 'thread', 'macro|[email protected]', 'user', 'view', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
+VALUES ('20000102-0000-0000-0000-000000000102'::uuid, 'email_thread', 'macro|[email protected]', 'user', 'view', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
-- == Messages for user2's threads ==
INSERT INTO email_messages (
diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rs
index ebba506dd1..3b843809ab 100644
--- a/rust/cloud-storage/email/src/domain/service/draft.rs
+++ b/rust/cloud-storage/email/src/domain/service/draft.rs
@@ -12,7 +12,7 @@ use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>
+impl<T, U, E, CS, Eam> EmailServiceImpl<T, U, E, CS, Eam>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rs
index 26f5783a0d..1921a17d3d 100644
--- a/rust/cloud-storage/email/src/domain/service/mod.rs
+++ b/rust/cloud-storage/email/src/domain/service/mod.rs
@@ -17,44 +17,50 @@ use crm::domain::service::CrmService;
use entity_access::domain::models::{
AccessLevel, EditAccessLevel, EntityAccessReceipt, EntityPermission, ViewAccessLevel,
};
+use entity_access_management::domain::ports::EntityAccessManagementService;
use frecency::domain::ports::FrecencyQueryService;
+use model_entity::EntityType;
use models_pagination::{PaginatedCursor, SimpleSortMethod};
use uuid::Uuid;
#[derive(Clone)]
-pub struct EmailServiceImpl<T, U, E, CS> {
+pub struct EmailServiceImpl<T, U, E, CS, Eam> {
pub(crate) email_repo: T,
pub(crate) frecency_service: U,
pub(crate) enqueuer: E,
pub(crate) crm_service: CS,
+ pub(crate) entity_access_management_service: Eam,
pub(crate) sent_undo_delay_secs: u32,
}
-impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>
+impl<T, U, E, CS, Eam> EmailServiceImpl<T, U, E, CS, Eam>
where
T: EmailRepo,
U: FrecencyQueryService,
E: EmailMessageEnqueuer,
CS: CrmService,
+ Eam: EntityAccessManagementService,
{
pub fn new(
email_repo: T,
frecency_service: U,
enqueuer: E,
crm_service: CS,
+ entity_access_management_service: Eam,
sent_undo_delay_secs: u32,
- ) -> EmailServiceImpl<T, U, E, CS> {
+ ) -> EmailServiceImpl<T, U, E, CS, Eam> {
EmailServiceImpl {
email_repo,
frecency_service,
enqueuer,
crm_service,
+ entity_access_management_service,
sent_undo_delay_secs,
}
}
}
-impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS> {
+impl<T, U, E, CS, Eam> EmailServiceImpl<T, U, E, CS, Eam> {
/// Validate and normalize email filter input.
fn validate_email_filter_input(
input: UpsertEmailFilterInput,
@@ -114,12 +120,13 @@ impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS> {
}
}
-impl<T, U, E, CS> EmailService for EmailServiceImpl<T, U, E, CS>
+impl<T, U, E, CS, Eam> EmailService for EmailServiceImpl<T, U, E, CS, Eam>
where
T: EmailRepo,
U: FrecencyQueryService,
E: EmailMessageEnqueuer,
CS: CrmService,
+ Eam: EntityAccessManagementService,
anyhow::Error: From<T::Err>,
anyhow::Error: From<E::Err>,
{
@@ -268,6 +275,32 @@ where
return Err(EmailErr::ThreadNotFound);
}
+ // Sync denormalized entity_access rows for the containing project.
+ // Best-effort: the project assignment itself already succeeded.
+ if old_project_id.as_deref() != project_id {
+ if let Some(old) = old_project_id
+ .as_deref()
+ .and_then(|p| Uuid::parse_str(p).ok())
+ {
+ let _ = self
+ .entity_access_management_service
+ .remove_entity_from_project(&thread_id, EntityType::EmailThread, &old)
+ .await
+ .inspect_err(
+ |e| tracing::error!(error=?e, project_id=%old, "unable to remove thread project access"),
+ );
+ }
+ if let Some(new) = project_id.and_then(|p| Uuid::parse_str(p).ok()) {
+ let _ = self
+ .entity_access_management_service
+ .add_entity_to_project(&thread_id, EntityType::EmailThread, &new)
+ .await
+ .inspect_err(
+ |e| tracing::error!(error=?e, project_id=%new, "unable to add thread project access"),
+ );
+ }
+ }
+
Ok(old_project_id)
}
diff --git a/rust/cloud-storage/email/src/domain/service/previews.rs b/rust/cloud-storage/email/src/domain/service/previews.rs
index b3533b92e4..3ad0e1dfeb 100644
--- a/rust/cloud-storage/email/src/domain/service/previews.rs
+++ b/rust/cloud-storage/email/src/domain/service/previews.rs
@@ -19,7 +19,7 @@ use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>
+impl<T, U, E, CS, Eam> EmailServiceImpl<T, U, E, CS, Eam>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/send.rs b/rust/cloud-storage/email/src/domain/service/send.rs
index a5c1af530e..f6dd0770e3 100644
--- a/rust/cloud-storage/email/src/domain/service/send.rs
+++ b/rust/cloud-storage/email/src/domain/service/send.rs
@@ -8,7 +8,7 @@ use frecency::domain::ports::FrecencyQueryService;
use super::EmailServiceImpl;
-impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>
+impl<T, U, E, CS, Eam> EmailServiceImpl<T, U, E, CS, Eam>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/thread.rs b/rust/cloud-storage/email/src/domain/service/thread.rs
index 775b57bc2b..828d615b4b 100644
--- a/rust/cloud-storage/email/src/domain/service/thread.rs
+++ b/rust/cloud-storage/email/src/domain/service/thread.rs
@@ -27,7 +27,7 @@ struct ThreadFetchResult {
is_owner: bool,
}
-impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>
+impl<T, U, E, CS, Eam> EmailServiceImpl<T, U, E, CS, Eam>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/thread_labels.rs b/rust/cloud-storage/email/src/domain/service/thread_labels.rs
index 8d41c92401..fe3a5265a8 100644
--- a/rust/cloud-storage/email/src/domain/service/thread_labels.rs
+++ b/rust/cloud-storage/email/src/domain/service/thread_labels.rs
@@ -7,7 +7,7 @@ use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>
+impl<T, U, E, CS, Eam> EmailServiceImpl<T, U, E, CS, Eam>
where
T: EmailRepo,
U: FrecencyQueryService,
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.rs
index c5efde436d..5b9f7ae26c 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
@@ -3,9 +3,11 @@ use super::resolve::{ResolvedFilters, can_short_circuit, resolve_filters};
use crate::domain::models::{PreviewView, PreviewViewStandardLabel};
use crate::outbound::email_pg_repo::db_types::*;
use chrono::{DateTime, Utc};
+use entity_access::outbound::get_user_source_ids;
use filter_ast::Expr;
use item_filters::SharedEmailFilter;
use item_filters::ast::email::EmailLiteral;
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Query, SimpleSortMethod};
use recursion::CollapsibleExt;
use sqlx::{PgPool, Postgres, QueryBuilder, Row};
@@ -32,11 +34,23 @@ struct QueryParams {
/// copies of the same conversation collapse to one row (see
/// [`build_query`]).
team_id: Option<Uuid>,
+ /// When `Some`, a project-scoped candidate source is UNIONed in: every
+ /// thread with this `project_id`, gated on the caller's entity_access
+ /// sources granting access to the project itself. Set only when the
+ /// filter AST carries a (non-negated) `ProjectId` literal.
+ project_scope: Option<ProjectScope>,
+}
+
+/// See [`QueryParams::project_scope`].
+struct ProjectScope {
+ project_ids: Vec<String>,
+ source_ids: Vec<String>,
}
enum ThreadCandidateSource {
Owned,
Shared,
+ Project,
}
/// `email_user_history` (`uh`) only drives ordering/cursoring for the
@@ -80,7 +94,7 @@ fn push_shared_cte(builder: &mut QueryBuilder<'static, Postgres>, params: &Query
SELECT entity_id AS thread_id
FROM entity_access
WHERE source_id = ANY(SELECT source_id FROM user_source_ids)
- AND entity_type = 'thread'
+ AND entity_type = 'email_thread'
)"#,
);
}
@@ -235,6 +249,33 @@ fn push_thread_candidate_select(
ThreadCandidateSource::Shared => {
builder.push("t.id IN (SELECT thread_id FROM SharedEmailThreads)");
}
+ // All threads in the requested projects, across every inbox — each
+ // row gated on the caller's sources having an entity_access grant
+ // on that row's project (same check as thread_access.rs Source 3).
+ ThreadCandidateSource::Project => {
+ let scope = params
+ .project_scope
+ .as_ref()
+ .expect("Project candidate source requires project_scope");
+ builder.push("t.project_id = ANY(");
+ builder.push_bind(scope.project_ids.clone());
+ builder.push(
+ r#") AND EXISTS (
+ SELECT 1 FROM entity_access pea
+ WHERE pea.entity_id::text = t.project_id
+ AND pea.entity_type = 'project'
+ AND pea.source_id = ANY("#,
+ );
+ builder.push_bind(scope.source_ids.clone());
+ builder.push("))");
+ // Shared=Only means "not my own threads" — keep the project
+ // widening for teammates' threads but exclude the caller's.
+ if matches!(params.shared, SharedEmailFilter::Only) {
+ builder.push(" AND NOT (t.link_id = ANY(");
+ builder.push_bind(params.link_ids.clone());
+ builder.push("))");
+ }
+ }
}
// Belt-and-suspenders killswitch check that covers both the Owned and
@@ -373,10 +414,11 @@ fn build_query(
None
} else {
// Owned-only, non-team queries can scope the CTE's contact/message
- // scans to the caller's links; shared/team candidates include
- // threads from other links, so scoping there would drop rows.
+ // scans to the caller's links; shared/team/project candidates
+ // include threads from other links, so scoping there would drop rows.
let link_scope = (matches!(params.shared, SharedEmailFilter::Exclude)
- && params.team_id.is_none())
+ && params.team_id.is_none()
+ && params.project_scope.is_none())
.then_some(params.link_ids.as_slice());
build_matching_threads_cte_body(email_filter, &params.resolved, link_scope)
};
@@ -514,6 +556,24 @@ fn build_query(
),
}
+ // Project-scoped source is additive: callers without project access
+ // still get their own (and shared) threads from the branches above.
+ if params.project_scope.is_some() {
+ builder.push(
+ r#"
+ UNION
+ "#,
+ );
+ push_thread_candidate_select(
+ &mut builder,
+ view,
+ email_filter,
+ &params,
+ sort_ts_field,
+ ThreadCandidateSource::Project,
+ );
+ }
+
if params.team_id.is_some() {
builder.push(
r#"
@@ -712,6 +772,13 @@ fn debug_build_query_sql_full(
use sqlx::Execute;
let shared = extract_shared_filter(email_filter);
+ // Mirror the real path's scope derivation with a fixed source id in
+ // place of the get_user_source_ids DB lookup.
+ let project_ids = extract_project_filter(email_filter);
+ let project_scope = (!project_ids.is_empty()).then(|| ProjectScope {
+ project_ids,
+ source_ids: vec!["test-user".to_string()],
+ });
let is_important = matches!(
view,
PreviewView::StandardLabel(PreviewViewStandardLabel::Important)
@@ -731,6 +798,7 @@ fn debug_build_query_sql_full(
user_id: "test-user".to_string(),
resolved,
team_id,
+ project_scope,
},
)
.build()
@@ -752,6 +820,23 @@ fn extract_shared_filter(ast: &Expr<EmailLiteral>) -> SharedEmailFilter {
)
}
+/// Every `ProjectId` literal in the tree. A negated `ProjectId` ("not in
+/// project X") must not widen the candidate set, so anything under a `Not`
+/// is ignored.
+fn extract_project_filter(ast: &Expr<EmailLiteral>) -> Vec<String> {
+ ast.collapse_frames(
+ |frame: filter_ast::ExprFrame<Vec<String>, EmailLiteral>| match frame {
+ filter_ast::ExprFrame::Literal(EmailLiteral::ProjectId(id)) => vec![id],
+ filter_ast::ExprFrame::And(mut a, b) | filter_ast::ExprFrame::Or(mut a, b) => {
+ a.extend(b);
+ a
+ }
+ filter_ast::ExprFrame::Not(_) => Vec::new(),
+ _ => Vec::new(),
+ },
+ )
+}
+
/// Fetches a paginated list of thread previews with dynamic filtering based on EmailLiteral AST.
/// This function provides a flexible alternative to the hardcoded view-specific queries,
/// combining view-specific filters (Inbox, Sent, Drafts, etc.) with custom email filters
@@ -796,6 +881,27 @@ pub(crate) async fn dynamic_email_thread_cursor(
let email_filter = query.filter();
let shared = extract_shared_filter(email_filter);
+ // Project-scoped queries widen the candidate set to every thread in the
+ // project, so resolve the caller's entity_access sources up front (the
+ // lookup is memoized for 30s). On failure, degrade to the un-widened
+ // query rather than erroring — the scope can only ever add rows.
+ let project_ids = extract_project_filter(email_filter);
+ let project_scope = if project_ids.is_empty() {
+ None
+ } else {
+ let user = MacroUserIdStr::parse_from_str(user_id).ok();
+ match get_user_source_ids(pool, user.as_deref()).await {
+ Ok(source_ids) => Some(ProjectScope {
+ project_ids,
+ source_ids: source_ids.0,
+ }),
+ Err(e) => {
+ tracing::error!(error=?e, "unable to fetch source ids for project-scoped email query");
+ None
+ }
+ }
+ };
+
let is_important = matches!(
view,
PreviewView::StandardLabel(PreviewViewStandardLabel::Important)
@@ -826,6 +932,7 @@ pub(crate) async fn dynamic_email_thread_cursor(
user_id: user_id.to_string(),
resolved,
team_id,
+ project_scope,
},
);
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs
index 92f7684821..24466d7bd3 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs
@@ -1452,3 +1452,121 @@ fn test_matching_threads_unscoped_without_link_scope() {
assert!(!debug.contains("link_id = ANY("));
}
+
+#[test]
+fn test_build_query_project_filter_adds_access_gated_union_branch() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let expr = Expr::Literal(EmailLiteral::ProjectId(
+ "96a9e31b-4ea0-48c5-b72e-4ac275546501".to_string(),
+ ));
+ let sql = super::query::debug_build_query_sql(&view, &expr);
+
+ // Project branch is UNIONed alongside the owned branch, not a replacement.
+ assert!(
+ sql.contains("t.link_id = ANY(") || sql.contains("t.link_id = links.link_id"),
+ "owned branch must remain: {sql}"
+ );
+ assert!(
+ sql.contains("UNION"),
+ "project branch must be a UNION: {sql}"
+ );
+ // Candidate set widens to the whole project, gated on project access.
+ assert!(
+ sql.contains("t.project_id = ANY("),
+ "project branch must filter on project_id: {sql}"
+ );
+ assert!(
+ sql.contains("pea.entity_id::text = t.project_id")
+ && sql.contains("pea.entity_type = 'project'")
+ && sql.contains("pea.source_id = ANY("),
+ "project branch must gate on entity_access project rows: {sql}"
+ );
+}
+
+#[test]
+fn test_build_query_negated_project_filter_does_not_widen() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let expr = Expr::is_not(Expr::Literal(EmailLiteral::ProjectId(
+ "96a9e31b-4ea0-48c5-b72e-4ac275546501".to_string(),
+ )));
+ let sql = super::query::debug_build_query_sql(&view, &expr);
+
+ assert!(
+ !sql.contains("pea.entity_type = 'project'"),
+ "negated project filter must not add the project candidate branch: {sql}"
+ );
+}
+
+#[test]
+fn test_build_query_no_project_filter_has_no_project_branch() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let expr = Expr::Literal(EmailLiteral::CalendarOnly(false));
+ let sql = super::query::debug_build_query_sql(&view, &expr);
+
+ assert!(
+ !sql.contains("pea.entity_type = 'project'"),
+ "project branch must only appear for project-scoped filters: {sql}"
+ );
+}
+
+#[test]
+fn test_build_query_multi_project_filter_widens_all_projects() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let expr = Expr::or(
+ Expr::Literal(EmailLiteral::ProjectId(
+ "96a9e31b-4ea0-48c5-b72e-4ac275546501".to_string(),
+ )),
+ Expr::Literal(EmailLiteral::ProjectId(
+ "159f7ca9-4ea0-48c5-b72e-4ac275546501".to_string(),
+ )),
+ );
+ let sql = super::query::debug_build_query_sql(&view, &expr);
+
+ // One project branch carrying every requested id via = ANY, gated per
+ // row so access is checked against each thread's own project.
+ assert_eq!(
+ sql.matches("t.project_id = ANY(").count(),
+ 1,
+ "multi-project filters must widen through a single ANY branch: {sql}"
+ );
+ assert!(
+ sql.contains("pea.entity_id::text = t.project_id"),
+ "access gate must be per-row: {sql}"
+ );
+}
+
+#[test]
+fn test_build_query_shared_only_project_branch_excludes_owned() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let expr = Expr::and(
+ Expr::Literal(EmailLiteral::ProjectId(
+ "96a9e31b-4ea0-48c5-b72e-4ac275546501".to_string(),
+ )),
+ Expr::Literal(EmailLiteral::Shared(item_filters::SharedEmailFilter::Only)),
+ );
+ let sql = super::query::debug_build_query_sql(&view, &expr);
+
+ assert!(
+ sql.contains("AND NOT (t.link_id = ANY("),
+ "Shared=Only must exclude the caller's own threads from the project branch: {sql}"
+ );
+}
+
+#[test]
+fn test_build_query_shared_include_project_branch_keeps_owned() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let expr = Expr::and(
+ Expr::Literal(EmailLiteral::ProjectId(
+ "96a9e31b-4ea0-48c5-b72e-4ac275546501".to_string(),
+ )),
+ Expr::Literal(EmailLiteral::Shared(
+ item_filters::SharedEmailFilter::Include,
+ )),
+ );
+ let sql = super::query::debug_build_query_sql(&view, &expr);
+
+ assert!(
+ !sql.contains("AND NOT (t.link_id = ANY("),
+ "Shared=Include must not exclude owned threads from the project branch: {sql}"
+ );
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
index c1a59199d7..c277d27a2e 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
@@ -6,6 +6,7 @@ mod labels;
mod link;
mod message;
mod preview;
+mod project_scope_dynamic_query;
mod thread;
mod thread_labels;
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/project_scope_dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/project_scope_dynamic_query.rs
new file mode 100644
index 0000000000..a313319b4f
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/project_scope_dynamic_query.rs
@@ -0,0 +1,362 @@
+//! DB tests for the project-scoped candidate branch of the dynamic email
+//! query: a (non-negated) `ProjectId` filter widens results to every thread
+//! in that project when the caller's entity_access sources grant access to
+//! the project itself.
+//!
+//! Fixtures: user1 (link aaaa) is the caller. user2 (link bbbb) owns the
+//! shared project `cccccccc` (user-source grant to user1), the team project
+//! `dddd0000` (team-source grant via user1's team), and the private project
+//! `eeee0000` (no grants).
+
+use super::*;
+
+const USER1: &str = "macro|[email protected]";
+const SHARED_PROJECT: &str = "cccccccc-cccc-cccc-cccc-cccccccccccc";
+const TEAM_PROJECT: &str = "dddd0000-0000-0000-0000-00000000dddd";
+const PRIVATE_PROJECT: &str = "eeee0000-0000-0000-0000-00000000eeee";
+
+const OWN_IN_SHARED: &str = "20000301-0000-0000-0000-000000000301";
+const OWN_IN_PRIVATE: &str = "20000302-0000-0000-0000-000000000302";
+const USER2_IN_SHARED: &str = "20000102-0000-0000-0000-000000000102";
+const USER2_IN_TEAM: &str = "20000105-0000-0000-0000-000000000105";
+const USER2_IN_PRIVATE: &str = "20000106-0000-0000-0000-000000000106";
+const USER2_ARCHIVED_IN_SHARED: &str = "20000107-0000-0000-0000-000000000107";
+const USER2_DIRECT_SHARE: &str = "20000101-0000-0000-0000-000000000101";
+
+fn user1_link() -> Uuid {
+ Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap()
+}
+
+fn project_filter(project_id: &str) -> Arc<Expr<EmailLiteral>> {
+ Arc::new(Expr::Literal(EmailLiteral::ProjectId(
+ project_id.to_string(),
+ )))
+}
+
+async fn run_query(
+ pool: &Pool<Postgres>,
+ view: PreviewViewStandardLabel,
+ filter: Arc<Expr<EmailLiteral>>,
+ user_id: &str,
+) -> anyhow::Result<Vec<String>> {
+ let results = dynamic::dynamic_email_thread_cursor(
+ pool,
+ &[user1_link()],
+ 50,
+ &PreviewView::StandardLabel(view),
+ Query::new(None, SimpleSortMethod::UpdatedAt, filter),
+ user_id,
+ None,
+ )
+ .await?;
+ Ok(results.iter().map(|r| r.id.to_string()).collect())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn project_access_widens_to_other_users_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let ids = run_query(
+ &pool,
+ PreviewViewStandardLabel::All,
+ project_filter(SHARED_PROJECT),
+ USER1,
+ )
+ .await?;
+
+ // Own thread + user2's threads in the project, newest first (All-view
+ // sort key is latest_non_spam_message_ts).
+ assert_eq!(
+ ids,
+ vec![
+ USER2_ARCHIVED_IN_SHARED.to_string(),
+ OWN_IN_SHARED.to_string(),
+ USER2_IN_SHARED.to_string(),
+ ],
+ "project access should surface every thread in the project"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn widened_rows_carry_owning_link_metadata(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let results = dynamic::dynamic_email_thread_cursor(
+ &pool,
+ &[user1_link()],
+ 50,
+ &PreviewView::StandardLabel(PreviewViewStandardLabel::All),
+ Query::new(
+ None,
+ SimpleSortMethod::UpdatedAt,
+ project_filter(SHARED_PROJECT),
+ ),
+ USER1,
+ None,
+ )
+ .await?;
+
+ let user2_row = results
+ .iter()
+ .find(|r| r.id.to_string() == USER2_IN_SHARED)
+ .expect("user2's project thread should be returned");
+ assert_eq!(
+ user2_row.owner_id, "macro|[email protected]",
+ "widened thread must report its real owner"
+ );
+ assert_eq!(
+ user2_row.link_id.to_string(),
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
+ "widened thread must report its owning link"
+ );
+ assert_eq!(
+ user2_row.project_id.as_deref(),
+ Some(SHARED_PROJECT),
+ "widened thread must carry its project id"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn team_sourced_project_grant_widens(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let ids = run_query(
+ &pool,
+ PreviewViewStandardLabel::All,
+ project_filter(TEAM_PROJECT),
+ USER1,
+ )
+ .await?;
+
+ assert_eq!(
+ ids,
+ vec![USER2_IN_TEAM.to_string()],
+ "a team-source grant on the project should widen like a user grant"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn no_project_access_returns_only_own_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let ids = run_query(
+ &pool,
+ PreviewViewStandardLabel::All,
+ project_filter(PRIVATE_PROJECT),
+ USER1,
+ )
+ .await?;
+
+ // user1 has a thread of their own filed into the private project; the
+ // owned branch keeps returning it, but no widening happens.
+ assert_eq!(
+ ids,
+ vec![OWN_IN_PRIVATE.to_string()],
+ "without project access only the caller's own threads may match"
+ );
+ assert!(
+ !ids.contains(&USER2_IN_PRIVATE.to_string()),
+ "another user's thread in an inaccessible project must stay hidden"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn view_filters_apply_to_widened_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let ids = run_query(
+ &pool,
+ PreviewViewStandardLabel::Inbox,
+ project_filter(SHARED_PROJECT),
+ USER1,
+ )
+ .await?;
+
+ // Thread 107 is in the project and accessible, but archived/outbound-only
+ // — the Inbox view filter must still exclude it.
+ assert_eq!(
+ ids,
+ vec![OWN_IN_SHARED.to_string(), USER2_IN_SHARED.to_string()],
+ "inbox view constraints must apply to project-widened threads too"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn negated_project_filter_does_not_widen(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let filter = Arc::new(Expr::is_not(Expr::Literal(EmailLiteral::ProjectId(
+ SHARED_PROJECT.to_string(),
+ ))));
+ let ids = run_query(&pool, PreviewViewStandardLabel::All, filter, USER1).await?;
+
+ assert!(
+ !ids.contains(&USER2_IN_SHARED.to_string())
+ && !ids.contains(&USER2_ARCHIVED_IN_SHARED.to_string()),
+ "a negated project filter must not pull in other users' threads"
+ );
+ assert!(
+ ids.contains(&OWN_IN_PRIVATE.to_string()),
+ "own threads outside the negated project should still match"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn shared_include_and_project_scope_do_not_duplicate(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ // Thread 102 qualifies through BOTH the shared branch (denormalized
+ // thread-level row) and the project branch — it must come back once.
+ let filter = Arc::new(Expr::and(
+ Expr::Literal(EmailLiteral::ProjectId(SHARED_PROJECT.to_string())),
+ Expr::Literal(EmailLiteral::Shared(
+ item_filters::SharedEmailFilter::Include,
+ )),
+ ));
+ let ids = run_query(&pool, PreviewViewStandardLabel::All, filter, USER1).await?;
+
+ assert_eq!(
+ ids.iter().filter(|id| *id == USER2_IN_SHARED).count(),
+ 1,
+ "shared + project branches must dedupe: {ids:?}"
+ );
+ assert!(
+ !ids.contains(&USER2_DIRECT_SHARE.to_string()),
+ "directly-shared thread outside the project must be excluded by the project filter"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn unparseable_user_id_skips_widening(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ // An empty/invalid user id yields no entity_access sources, so the
+ // project branch matches nothing and only owned threads return.
+ let ids = run_query(
+ &pool,
+ PreviewViewStandardLabel::All,
+ project_filter(SHARED_PROJECT),
+ "",
+ )
+ .await?;
+
+ assert_eq!(
+ ids,
+ vec![OWN_IN_SHARED.to_string()],
+ "no resolvable sources → owned threads only"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn shared_only_with_project_scope_excludes_owned_threads(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ // Shared=Only means "not my own threads": the project widening must keep
+ // teammates' threads but never return the caller's own.
+ let filter = Arc::new(Expr::and(
+ Expr::Literal(EmailLiteral::ProjectId(SHARED_PROJECT.to_string())),
+ Expr::Literal(EmailLiteral::Shared(item_filters::SharedEmailFilter::Only)),
+ ));
+ let ids = run_query(&pool, PreviewViewStandardLabel::All, filter, USER1).await?;
+
+ assert_eq!(
+ ids,
+ vec![
+ USER2_ARCHIVED_IN_SHARED.to_string(),
+ USER2_IN_SHARED.to_string(),
+ ],
+ "Shared=Only + project scope must return only other users' project threads"
+ );
+ assert!(
+ !ids.contains(&OWN_IN_SHARED.to_string()),
+ "the caller's own project thread must be excluded under Shared=Only"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads", "email_project_scope")
+ )
+)]
+async fn multi_project_filter_widens_every_accessible_project(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let filter = Arc::new(Expr::or(
+ Expr::Literal(EmailLiteral::ProjectId(SHARED_PROJECT.to_string())),
+ Expr::Literal(EmailLiteral::ProjectId(TEAM_PROJECT.to_string())),
+ ));
+ let ids = run_query(&pool, PreviewViewStandardLabel::All, filter, USER1).await?;
+
+ assert_eq!(
+ ids,
+ vec![
+ USER2_ARCHIVED_IN_SHARED.to_string(), // 2024-03-07
+ USER2_IN_TEAM.to_string(), // 2024-03-05
+ OWN_IN_SHARED.to_string(), // 2024-03-01
+ USER2_IN_SHARED.to_string(), // 2024-02-02
+ ],
+ "an OR of project ids must widen every project the caller can access"
+ );
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index d3c70ef435..de78e5c265 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -94,6 +94,7 @@ doppler-config = { workspace = true }
ego-tree = { workspace = true }
email = { path = "../email", features = ["axum", "gmail_token", "inbound", "outbound"] }
entity_access = { path = "../entity_access", default-features = false, features = ["outbound"] }
+entity_access_management = { path = "../entity_access_management" }
email_db_client = { path = "../email_db_client" }
email_utils = { path = "../email_utils" }
filter_ast = { path = "../filter_ast" }
diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rs
index 86f651d4d6..7a9dfd7664 100644
--- a/rust/cloud-storage/email_service/src/api/context.rs
+++ b/rust/cloud-storage/email_service/src/api/context.rs
@@ -12,6 +12,7 @@ use email::{
use email_service::config::Config;
use email_service::util::redis::RedisClient;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use entity_access_management::domain::service::EntityAccessManagementServiceImpl;
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiKey;
@@ -20,6 +21,8 @@ use std::sync::Arc;
use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};
pub(crate) type EmailEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
+pub(crate) type EmailEntityAccessManagementService =
+ EntityAccessManagementServiceImpl<entity_access_management::outbound::PgRepository>;
pub(crate) type EmailSvc = EmailServiceImpl<
EmailPgRepo,
FrecencyQueryServiceImpl<FrecencyPgStorage>,
@@ -28,6 +31,7 @@ pub(crate) type EmailSvc = EmailServiceImpl<
crm::outbound::companies_repo::CompaniesRepositoryImpl,
crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,
>,
+ EmailEntityAccessManagementService,
>;
#[derive(Clone, FromRef)]
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index 4db6447d48..9e430a003b 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -138,6 +138,9 @@ async fn main() -> anyhow::Result<()> {
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
(*sqs_client).clone(),
crm_service,
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
config.sent_undo_delay_secs,
));
let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
diff --git a/rust/cloud-storage/entity_access/src/outbound.rs b/rust/cloud-storage/entity_access/src/outbound.rs
index 0e7bd3cfbf..48275ae85e 100644
--- a/rust/cloud-storage/entity_access/src/outbound.rs
+++ b/rust/cloud-storage/entity_access/src/outbound.rs
@@ -4,4 +4,4 @@
mod pg_access_repo;
-pub use pg_access_repo::PgAccessRepository;
+pub use pg_access_repo::{PgAccessRepository, SourceIds, get_user_source_ids};
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
index 5911edf5de..95c1926e20 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
@@ -2,6 +2,8 @@
mod queries;
+pub use queries::{SourceIds, get_user_source_ids};
+
#[cfg(test)]
mod test;
diff --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.rs
index 327c866c56..710695a076 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
@@ -34,7 +34,7 @@ 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>);
+pub struct SourceIds(pub Vec<String>);
/// Grabs the users source ids for the entity access table
/// NOTE: This could return an empty list in the event the user is not logged in and attempting to review a resource
@@ -48,7 +48,7 @@ pub(in crate::outbound::pg_access_repo) struct SourceIds(pub Vec<String>);
convert = r#"{format!("{}", user_id.map(AsRef::as_ref).unwrap_or(""))}"#,
)
)]
-pub(in crate::outbound::pg_access_repo) async fn get_user_source_ids(
+pub async fn get_user_source_ids(
pool: &Pool<Postgres>,
user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> anyhow::Result<SourceIds> {
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.rs
index 4de3631f2d..da2a2f258d 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
@@ -71,9 +71,10 @@ pub async fn get_thread_access(
return Ok(access_level.and_then(|level| AccessLevel::from_str(&level).ok()));
}
- // Owner is handled above and short-circuits. The remaining two sources —
- // share-permission/entity_access and team-CRM — can only grant access, so
- // run them concurrently and take the highest level across both.
+ // Owner is handled above and short-circuits. The remaining sources —
+ // share-permission/entity_access (including View via the thread's
+ // containing project) and team-CRM — can only grant access, so run them
+ // concurrently and take the highest level across both.
let thread_id_str = thread_id.to_string();
let share_fut = sqlx::query_scalar!(
@@ -96,6 +97,15 @@ pub async fn get_thread_access(
AND id IN (
SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $3
)
+
+ UNION ALL
+ -- Source 3: access to the thread's containing project grants View
+ SELECT 'view' AS access_level
+ FROM email_threads t
+ JOIN entity_access pea ON pea.entity_id::text = t.project_id
+ AND pea.entity_type = 'project'
+ AND pea.source_id = ANY($2)
+ WHERE t.id = $1::uuid
) AS combined_access
"#,
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.rs
index 12ebe10063..740caf7e8a 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
@@ -965,3 +965,109 @@ async fn denies_when_every_participant_is_on_requesters_domain(pool: PgPool) ->
assert_eq!(access_as_requester(&pool, &thread_id).await, None);
Ok(())
}
+
+// ---------------------------------------------------------------------------
+// Project containment source
+// ---------------------------------------------------------------------------
+
+/// A "Project" row owned by `owner_user_id`. Returns the project id (TEXT column).
+async fn insert_project(pool: &PgPool, owner_user_id: &str) -> String {
+ let project_id = Uuid::new_v4().to_string();
+ sqlx::query!(
+ r#"INSERT INTO "Project" (id, name, "userId") VALUES ($1, 'Test Project', $2)"#,
+ project_id,
+ owner_user_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ project_id
+}
+
+async fn set_thread_project(pool: &PgPool, thread_id: Uuid, project_id: &str) {
+ sqlx::query!(
+ r#"UPDATE email_threads SET project_id = $2 WHERE id = $1"#,
+ thread_id,
+ project_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn insert_project_access(
+ pool: &PgPool,
+ project_id: &str,
+ source_id: &str,
+ level: AccessLevel,
+) {
+ let project_uuid = Uuid::parse_str(project_id).unwrap();
+ 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, 'project', $2, 'user', $3::text::"AccessLevel")"#,
+ project_uuid,
+ source_id,
+ level_str,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn project_access_grants_view_on_contained_thread(pool: PgPool) -> anyhow::Result<()> {
+ // Project access is capped at View regardless of the project-level grant.
+ insert_user(&pool, OWNER, "[email protected]").await;
+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;
+ let project_id = insert_project(&pool, OWNER).await;
+ set_thread_project(&pool, thread_id, &project_id).await;
+ insert_project_access(&pool, &project_id, REQUESTER, AccessLevel::Edit).await;
+
+ assert_eq!(
+ access_as_requester(&pool, &thread_id).await,
+ Some(AccessLevel::View)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn denies_when_thread_project_not_shared_with_requester(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER, "[email protected]").await;
+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;
+ let project_id = insert_project(&pool, OWNER).await;
+ set_thread_project(&pool, thread_id, &project_id).await;
+ insert_project_access(&pool, &project_id, OTHER, AccessLevel::Edit).await;
+
+ assert_eq!(access_as_requester(&pool, &thread_id).await, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn direct_thread_grant_wins_over_project_view(pool: PgPool) -> anyhow::Result<()> {
+ // Thread-level Edit beats the project-derived View.
+ insert_user(&pool, OWNER, "[email protected]").await;
+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;
+ let project_id = insert_project(&pool, OWNER).await;
+ set_thread_project(&pool, thread_id, &project_id).await;
+ insert_project_access(&pool, &project_id, REQUESTER, AccessLevel::View).await;
+ insert_entity_access(&pool, thread_id, REQUESTER, AccessLevel::Edit).await;
+
+ assert_eq!(
+ access_as_requester(&pool, &thread_id).await,
+ Some(AccessLevel::Edit)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn no_project_grant_when_thread_has_no_project(pool: PgPool) -> anyhow::Result<()> {
+ // Requester can access a project, but the thread isn't in one.
+ insert_user(&pool, OWNER, "[email protected]").await;
+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;
+ let project_id = insert_project(&pool, OWNER).await;
+ insert_project_access(&pool, &project_id, REQUESTER, AccessLevel::Edit).await;
+
+ assert_eq!(access_as_requester(&pool, &thread_id).await, None);
+ Ok(())
+}
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 10bb48bd8c..4107184d03 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -155,6 +155,9 @@ async fn build_tool_context(
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
0,
);
let channels_service = ChannelListServiceImpl::new(
@@ -249,6 +252,9 @@ async fn build_tool_context(
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
sqs_client,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
0,
)),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 0358321ca1..42c037e01a 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -85,6 +85,9 @@ pub async fn build_tool_service_context(
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
0,
);
let channels_service = ChannelListServiceImpl::new(
@@ -162,6 +165,9 @@ pub async fn build_tool_service_context(
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),
sqs_client,
crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
0,
)),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),