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(tooling): entity access management cli (#6355)

Will Hutchinsoncd035dfa8138
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index e12a8b0816..b5362708ae 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -62,6 +62,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/embedding",
@@ -163,6 +164,7 @@
"crates/cowlike",
"crates/cursor_api_key",
"crates/cursor_cloud_agents",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/embedding",
@@ -523,6 +525,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -537,6 +540,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -586,6 +590,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -601,6 +606,7 @@
"crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -839,6 +845,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -1247,6 +1254,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1261,6 +1269,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -1331,6 +1340,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -1354,6 +1364,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -1453,6 +1464,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1468,6 +1480,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -1652,6 +1665,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1666,6 +1680,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -1706,6 +1721,7 @@
"crates/channel_sender",
"crates/chat",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1716,6 +1732,7 @@
"crates/kafka_util",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -1762,6 +1779,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -1842,6 +1860,7 @@
"crates/bot_token",
"crates/collab_surface",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/harness_id",
@@ -1849,6 +1868,7 @@
"crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_sync_service_jwt",
@@ -1860,6 +1880,7 @@
"crates/model_file_type",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/non_empty",
@@ -1885,6 +1906,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1899,6 +1921,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -1952,6 +1975,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -2054,12 +2078,14 @@
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/harness_id",
"crates/harness_token",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_tower_layers",
@@ -2071,6 +2097,7 @@
"crates/model_file_type",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/non_empty",
@@ -2301,6 +2328,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2311,6 +2339,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -2365,6 +2394,7 @@
"crates/contacts",
"crates/cowlike",
"crates/cursor_cloud_agents",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2379,6 +2409,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -2462,6 +2493,7 @@
"crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -2925,6 +2957,7 @@
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/embedding",
@@ -2992,6 +3025,7 @@
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/embedding",
@@ -3058,6 +3092,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -3145,6 +3180,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -3163,6 +3199,7 @@
"crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -3264,6 +3301,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -3335,6 +3373,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -3410,6 +3449,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/email",
@@ -3501,6 +3541,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_service_client",
@@ -3520,6 +3561,7 @@
"crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -3566,6 +3608,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -3687,12 +3730,14 @@
"crates/bot_id",
"crates/bot_token",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/harness_id",
"crates/harness_token",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
@@ -3703,6 +3748,7 @@
"crates/model_file_type",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/non_empty",
@@ -3741,6 +3787,7 @@
"crates/bot_id",
"crates/bot_token",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_mutation",
@@ -3748,6 +3795,7 @@
"crates/harness_token",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
@@ -3758,6 +3806,7 @@
"crates/model_file_type",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/non_empty",
@@ -3773,6 +3822,7 @@
"crates/bot_id",
"crates/bot_token",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/favorites",
@@ -3780,6 +3830,7 @@
"crates/harness_token",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
@@ -3790,6 +3841,7 @@
"crates/model_file_type",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/non_empty",
@@ -3808,6 +3860,7 @@
"crates/bot_id",
"crates/bot_token",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/filter_ast",
@@ -3817,6 +3870,7 @@
"crates/item_filters",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
@@ -3827,6 +3881,7 @@
"crates/model_file_type",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/non_empty",
@@ -3872,6 +3927,7 @@
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/embedding",
@@ -3989,6 +4045,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4005,6 +4062,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -4075,6 +4133,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -4095,6 +4154,7 @@
"crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -4147,6 +4207,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -4254,6 +4315,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -4390,6 +4452,7 @@
"crates/bot_id",
"crates/bot_token",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/graphql_permission",
@@ -4397,6 +4460,7 @@
"crates/harness_token",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
@@ -4407,6 +4471,7 @@
"crates/model_file_type",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/non_empty",
@@ -4425,6 +4490,7 @@
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4439,6 +4505,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -4490,6 +4557,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -4694,6 +4762,7 @@
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4705,6 +4774,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -4838,6 +4908,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4854,6 +4925,7 @@
"crates/lexical_mention_extractor",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -5630,6 +5702,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -5649,6 +5722,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -5718,6 +5792,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -5737,6 +5812,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -5791,6 +5867,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5805,6 +5882,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -6033,6 +6111,7 @@
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -6045,6 +6124,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -6106,6 +6186,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -6177,6 +6258,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -6273,6 +6355,7 @@
"crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -6356,6 +6439,7 @@
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -6366,6 +6450,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -6406,6 +6491,7 @@
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -6416,6 +6502,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -6496,6 +6583,7 @@
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/entity_access",
"crates/harness_id",
@@ -6505,6 +6593,7 @@
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -6520,6 +6609,7 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/non_empty",
@@ -6710,6 +6800,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -6823,6 +6914,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -6844,6 +6936,7 @@
"crates/macro_authorization",
"crates/macro_aws_config",
"crates/macro_db_client",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -6913,6 +7006,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -6932,6 +7026,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -7033,6 +7128,7 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email_db_client",
"crates/email_utils",
@@ -7146,6 +7242,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -7166,6 +7263,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -7237,6 +7335,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -7257,6 +7356,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -7317,6 +7417,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -7340,6 +7441,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -7403,6 +7505,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -7424,6 +7527,7 @@
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -7485,6 +7589,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -7571,6 +7676,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -7589,6 +7695,7 @@
"crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_event_broker",
@@ -7917,6 +8024,7 @@
"crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/dynamodb_client",
@@ -7990,6 +8098,7 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/dynamodb_client",
"crates/email",
@@ -8132,6 +8241,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
"crates/email",
diff --git a/.sqlx/query-24414db0c6d21f0278232ad9ac55d82a6ef8fed8fd44fe2d9cd48f6a7b16fa31.json b/.sqlx/query-24414db0c6d21f0278232ad9ac55d82a6ef8fed8fd44fe2d9cd48f6a7b16fa31.json
new file mode 100644
index 0000000000..4491becebb
--- /dev/null
+++ b/.sqlx/query-24414db0c6d21f0278232ad9ac55d82a6ef8fed8fd44fe2d9cd48f6a7b16fa31.json
@@ -0,0 +1,30 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH source_pairs AS (\n SELECT DISTINCT stored_for_id, stored_for_auth_entity\n FROM UNNEST($2::text[], $3::text[])\n AS source_rows(stored_for_id, stored_for_auth_entity)\n )\n SELECT\n fe.stored_for_id AS \"stored_for_id!\",\n fe.stored_for_auth_entity AS \"stored_for_auth_entity!\"\n FROM foreign_entity fe\n JOIN source_pairs s\n ON s.stored_for_id = fe.stored_for_id\n AND s.stored_for_auth_entity = fe.stored_for_auth_entity\n WHERE fe.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "stored_for_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "stored_for_auth_entity!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "24414db0c6d21f0278232ad9ac55d82a6ef8fed8fd44fe2d9cd48f6a7b16fa31"
+}
diff --git a/.sqlx/query-4e9d79b57b5c11e0d725eddcb59c52b0613854015e771fb77381e4e3bf84493b.json b/.sqlx/query-4e9d79b57b5c11e0d725eddcb59c52b0613854015e771fb77381e4e3bf84493b.json
new file mode 100644
index 0000000000..25d12df9e9
--- /dev/null
+++ b/.sqlx/query-4e9d79b57b5c11e0d725eddcb59c52b0613854015e771fb77381e4e3bf84493b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT pea.entity_id::text AS \"project_id!\"\n FROM email_threads t\n JOIN entity_access pea\n 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 ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "project_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4e9d79b57b5c11e0d725eddcb59c52b0613854015e771fb77381e4e3bf84493b"
+}
diff --git a/.sqlx/query-539ebdf36e054cdc7278729549d608006a2fc1c3c719680bce5765c14e671dee.json b/.sqlx/query-539ebdf36e054cdc7278729549d608006a2fc1c3c719680bce5765c14e671dee.json
new file mode 100644
index 0000000000..fa21518f1d
--- /dev/null
+++ b/.sqlx/query-539ebdf36e054cdc7278729549d608006a2fc1c3c719680bce5765c14e671dee.json
@@ -0,0 +1,30 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id AS thread_id,\n CASE\n WHEN l.macro_id = $3 THEN 'inbox_owner'\n WHEN EXISTS (\n SELECT 1\n FROM macro_user_links mul\n WHERE mul.link_id = l.id\n AND mul.primary_macro_id = $3\n ) THEN 'inbox_delegate'\n ELSE 'thread_grant'\n END AS \"reason!\"\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 = $1\n AND (\n l.macro_id = $3\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 = $3\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 ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "reason!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "539ebdf36e054cdc7278729549d608006a2fc1c3c719680bce5765c14e671dee"
+}
diff --git a/.sqlx/query-62d15e0108eef038a7a372f2350f8ccdae9f901b1c0e662c69b9e982a5dea5c8.json b/.sqlx/query-62d15e0108eef038a7a372f2350f8ccdae9f901b1c0e662c69b9e982a5dea5c8.json
new file mode 100644
index 0000000000..da2d38d2f8
--- /dev/null
+++ b/.sqlx/query-62d15e0108eef038a7a372f2350f8ccdae9f901b1c0e662c69b9e982a5dea5c8.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" share_permission\n JOIN \"DocumentPermission\" document_permission\n ON document_permission.\"sharePermissionId\" = share_permission.id\n WHERE share_permission.\"linkShare\" = 'PUBLIC'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND document_permission.\"documentId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "62d15e0108eef038a7a372f2350f8ccdae9f901b1c0e662c69b9e982a5dea5c8"
+}
diff --git a/.sqlx/query-6625b55e3954fe13657e431acf2b82691c5125c4173e4e3112da46c37f683361.json b/.sqlx/query-6625b55e3954fe13657e431acf2b82691c5125c4173e4e3112da46c37f683361.json
new file mode 100644
index 0000000000..a914468a53
--- /dev/null
+++ b/.sqlx/query-6625b55e3954fe13657e431acf2b82691c5125c4173e4e3112da46c37f683361.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n \"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\"\n WHERE \"linkShare\" = 'PUBLIC'\n AND \"linkShareAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "6625b55e3954fe13657e431acf2b82691c5125c4173e4e3112da46c37f683361"
+}
diff --git a/.sqlx/query-a0c27d152a84789384d5ddc59c0687e6a3ff0792632e59fed664b7a6167e700a.json b/.sqlx/query-a0c27d152a84789384d5ddc59c0687e6a3ff0792632e59fed664b7a6167e700a.json
new file mode 100644
index 0000000000..d62eff0082
--- /dev/null
+++ b/.sqlx/query-a0c27d152a84789384d5ddc59c0687e6a3ff0792632e59fed664b7a6167e700a.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" sp\n WHERE sp.\"linkShare\" = 'PUBLIC'\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n AND sp.id IN (\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" = $1\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "a0c27d152a84789384d5ddc59c0687e6a3ff0792632e59fed664b7a6167e700a"
+}
diff --git a/.sqlx/query-a37593776fe36baa9236d8f75d1aca053d92bfdd33330dc2f416558b673f844a.json b/.sqlx/query-a37593776fe36baa9236d8f75d1aca053d92bfdd33330dc2f416558b673f844a.json
new file mode 100644
index 0000000000..5f04717487
--- /dev/null
+++ b/.sqlx/query-a37593776fe36baa9236d8f75d1aca053d92bfdd33330dc2f416558b673f844a.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n l.macro_id AS \"mailbox_owner!\",\n (l.macro_id = $2) AS \"is_owner!\"\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND (\n l.macro_id = $2\n OR EXISTS (\n SELECT 1\n FROM public.macro_user_links mul\n WHERE mul.link_id = l.id\n AND mul.primary_macro_id = $2\n )\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "mailbox_owner!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "is_owner!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "a37593776fe36baa9236d8f75d1aca053d92bfdd33330dc2f416558b673f844a"
+}
diff --git a/.sqlx/query-a488a5d061a11020b64ad1dfebe52bce7df08d64b53ab9c7e873af213ff3a667.json b/.sqlx/query-a488a5d061a11020b64ad1dfebe52bce7df08d64b53ab9c7e873af213ff3a667.json
new file mode 100644
index 0000000000..68174cf9af
--- /dev/null
+++ b/.sqlx/query-a488a5d061a11020b64ad1dfebe52bce7df08d64b53ab9c7e873af213ff3a667.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT event.owner_id = $2 AS \"is_owner!\"\n FROM calendar_events event\n WHERE event.id = $1\n AND (\n event.owner_id = $2\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = event.source_link_id\n AND link.primary_macro_id = $2\n )\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "is_owner!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "a488a5d061a11020b64ad1dfebe52bce7df08d64b53ab9c7e873af213ff3a667"
+}
diff --git a/.sqlx/query-a89f68176169e0f3bc042c5782d5a09fc36af25197564768414bebabc1fc156b.json b/.sqlx/query-a89f68176169e0f3bc042c5782d5a09fc36af25197564768414bebabc1fc156b.json
new file mode 100644
index 0000000000..9ee7c4e81a
--- /dev/null
+++ b/.sqlx/query-a89f68176169e0f3bc042c5782d5a09fc36af25197564768414bebabc1fc156b.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" sp\n JOIN \"ChatPermission\" cp ON cp.\"sharePermissionId\" = sp.id\n WHERE cp.\"chatId\" = $1\n AND sp.\"linkShare\" = 'PUBLIC'\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "a89f68176169e0f3bc042c5782d5a09fc36af25197564768414bebabc1fc156b"
+}
diff --git a/.sqlx/query-b8c05125895f4c325da647bebffb2db1950fd2277202062b81ceadee2a7c5b77.json b/.sqlx/query-b8c05125895f4c325da647bebffb2db1950fd2277202062b81ceadee2a7c5b77.json
new file mode 100644
index 0000000000..bf4e656b19
--- /dev/null
+++ b/.sqlx/query-b8c05125895f4c325da647bebffb2db1950fd2277202062b81ceadee2a7c5b77.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n owner_tu.team_id AS \"owner_team_id!\"\n FROM \"SharePermission\" sp\n JOIN \"ChatPermission\" cp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON c.id = cp.\"chatId\"\n JOIN team_user owner_tu\n ON owner_tu.user_id = c.\"userId\"\n AND owner_tu.team_id::text = ANY($2)\n WHERE cp.\"chatId\" = $1\n AND sp.\"linkShare\" = 'TEAM'\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_team_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ true,
+ false
+ ]
+ },
+ "hash": "b8c05125895f4c325da647bebffb2db1950fd2277202062b81ceadee2a7c5b77"
+}
diff --git a/.sqlx/query-cf53541f8a737c46ac505cb6511044d4e1571addbaa8c0c56f099378188b9c66.json b/.sqlx/query-cf53541f8a737c46ac505cb6511044d4e1571addbaa8c0c56f099378188b9c66.json
new file mode 100644
index 0000000000..3a30e7dcd0
--- /dev/null
+++ b/.sqlx/query-cf53541f8a737c46ac505cb6511044d4e1571addbaa8c0c56f099378188b9c66.json
@@ -0,0 +1,65 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n source_type AS \"source_type!: EntityAccessSourceType\",\n source_id,\n access_level AS \"access_level!: AccessLevel\",\n granted_from_project_id\n FROM entity_access\n WHERE entity_id = $1\n AND entity_type = $2\n AND source_id = ANY($3)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "source_type!: EntityAccessSourceType",
+ "type_info": {
+ "Custom": {
+ "name": "entity_access_source_type",
+ "kind": {
+ "Enum": [
+ "channel",
+ "team",
+ "user"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "source_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "granted_from_project_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "cf53541f8a737c46ac505cb6511044d4e1571addbaa8c0c56f099378188b9c66"
+}
diff --git a/.sqlx/query-cfe9d5b1e363c8b0e2b2fbfe4caa006ca5e7668b10410232d8ffe05316d65272.json b/.sqlx/query-cfe9d5b1e363c8b0e2b2fbfe4caa006ca5e7668b10410232d8ffe05316d65272.json
new file mode 100644
index 0000000000..0c0834a063
--- /dev/null
+++ b/.sqlx/query-cfe9d5b1e363c8b0e2b2fbfe4caa006ca5e7668b10410232d8ffe05316d65272.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n owner_team.team_id AS \"owner_team_id!\"\n FROM \"SharePermission\" sp\n JOIN \"ProjectPermission\" pp ON pp.\"sharePermissionId\" = sp.id\n JOIN \"Project\" p ON p.id = pp.\"projectId\"\n JOIN team_user owner_team\n ON owner_team.user_id = p.\"userId\"\n AND owner_team.team_id::text = ANY($2)\n WHERE pp.\"projectId\" = $1\n AND sp.\"linkShare\" = 'TEAM'\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_team_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ true,
+ false
+ ]
+ },
+ "hash": "cfe9d5b1e363c8b0e2b2fbfe4caa006ca5e7668b10410232d8ffe05316d65272"
+}
diff --git a/.sqlx/query-d74790877ddb0911dfc195c545fe984857acecb5e83e45464a522405f0b0be03.json b/.sqlx/query-d74790877ddb0911dfc195c545fe984857acecb5e83e45464a522405f0b0be03.json
new file mode 100644
index 0000000000..7cbe9dcae9
--- /dev/null
+++ b/.sqlx/query-d74790877ddb0911dfc195c545fe984857acecb5e83e45464a522405f0b0be03.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH thread_owner AS (\n SELECT el.macro_id\n FROM email_threads t\n JOIN email_links el ON el.id = t.link_id\n WHERE t.id = $1::uuid\n ),\n shared_teams AS (\n SELECT tcs.team_id, requester.team_role\n FROM team_user requester\n JOIN team_user owner_member ON owner_member.team_id = requester.team_id\n JOIN thread_owner o ON o.macro_id = owner_member.user_id\n JOIN team_crm_settings tcs ON tcs.team_id = requester.team_id\n WHERE requester.user_id = $2\n AND tcs.crm_enabled\n ),\n participants AS (\n SELECT DISTINCT LOWER(ec.email_address) AS email\n FROM email_messages m\n JOIN email_contacts ec ON ec.id = m.from_contact_id\n WHERE m.thread_id = $1::uuid\n UNION\n SELECT DISTINCT LOWER(ec.email_address)\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts ec ON ec.id = r.contact_id\n WHERE m.thread_id = $1::uuid\n )\n SELECT st.team_id, st.team_role AS \"team_role!: TeamRole\"\n FROM shared_teams st\n WHERE EXISTS (\n SELECT 1\n FROM participants p\n WHERE split_part(p.email, '@', 2) <> split_part(LOWER($2), '@', 2)\n )\n AND NOT EXISTS (\n SELECT 1\n FROM participants p\n JOIN crm_contacts ct ON ct.email = p.email\n JOIN crm_companies c ON c.id = ct.company_id\n WHERE c.team_id = st.team_id\n AND split_part(p.email, '@', 2) <> split_part(LOWER($2), '@', 2)\n AND (\n NOT c.email_sync\n OR (\n (ct.hidden OR c.hidden)\n AND st.team_role = 'member'\n )\n )\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "d74790877ddb0911dfc195c545fe984857acecb5e83e45464a522405f0b0be03"
+}
diff --git a/.sqlx/query-e68554daf5eb02338102760b6632243ecd9a4139517a7c70ac38e29b7758f01c.json b/.sqlx/query-e68554daf5eb02338102760b6632243ecd9a4139517a7c70ac38e29b7758f01c.json
new file mode 100644
index 0000000000..dd09baead3
--- /dev/null
+++ b/.sqlx/query-e68554daf5eb02338102760b6632243ecd9a4139517a7c70ac38e29b7758f01c.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n owner_team.team_id AS \"owner_team_id!\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id, created_by\n FROM calls\n WHERE id = $1\n\n UNION ALL\n\n SELECT share_permission_id, created_by\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ) call_item ON call_item.share_permission_id = share_permission.id\n JOIN team_user owner_team\n ON owner_team.user_id = call_item.created_by\n AND owner_team.team_id::text = ANY($2)\n WHERE share_permission.\"linkShare\" = 'TEAM'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_team_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ true,
+ false
+ ]
+ },
+ "hash": "e68554daf5eb02338102760b6632243ecd9a4139517a7c70ac38e29b7758f01c"
+}
diff --git a/.sqlx/query-ed9cce412861d253700f4104a1edeb21f5a7fb97646af2451e799643fe419f5a.json b/.sqlx/query-ed9cce412861d253700f4104a1edeb21f5a7fb97646af2451e799643fe419f5a.json
new file mode 100644
index 0000000000..9564fc0288
--- /dev/null
+++ b/.sqlx/query-ed9cce412861d253700f4104a1edeb21f5a7fb97646af2451e799643fe419f5a.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (\n SELECT 1 FROM reminder WHERE id = $1 AND user_id = $2\n ) AS \"owns!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owns!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "ed9cce412861d253700f4104a1edeb21f5a7fb97646af2451e799643fe419f5a"
+}
diff --git a/.sqlx/query-f5ada3959e142c6abff493c03c8f57a0f34b09ca5dd5ff1a1062d6b03706ee26.json b/.sqlx/query-f5ada3959e142c6abff493c03c8f57a0f34b09ca5dd5ff1a1062d6b03706ee26.json
new file mode 100644
index 0000000000..a73a079eb7
--- /dev/null
+++ b/.sqlx/query-f5ada3959e142c6abff493c03c8f57a0f34b09ca5dd5ff1a1062d6b03706ee26.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n owner_tu.team_id AS \"owner_team_id!\"\n FROM \"SharePermission\" sp\n JOIN team_user owner_tu\n ON owner_tu.team_id::text = ANY($2)\n WHERE sp.\"linkShareAccessLevel\" IS NOT NULL\n AND sp.\"linkShare\" = 'TEAM'\n AND sp.id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n )\n AND EXISTS (\n SELECT 1\n FROM email_threads t\n JOIN email_links l ON l.id = t.link_id\n WHERE t.id = $3::uuid\n AND owner_tu.user_id = l.macro_id\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_team_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ false
+ ]
+ },
+ "hash": "f5ada3959e142c6abff493c03c8f57a0f34b09ca5dd5ff1a1062d6b03706ee26"
+}
diff --git a/.sqlx/query-f99d012fe06786291fde33923dd5db92c98951968e1a5d1e07cb1bdee0552038.json b/.sqlx/query-f99d012fe06786291fde33923dd5db92c98951968e1a5d1e07cb1bdee0552038.json
new file mode 100644
index 0000000000..a115aed897
--- /dev/null
+++ b/.sqlx/query-f99d012fe06786291fde33923dd5db92c98951968e1a5d1e07cb1bdee0552038.json
@@ -0,0 +1,47 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n cp.role::text as \"role?\",\n c.channel_type::text as \"channel_type!\",\n c.org_id as \"org_id?\",\n c.team_id as \"team_id?\",\n EXISTS (\n SELECT 1\n FROM team_user tu\n WHERE tu.user_id = $2 AND tu.team_id = c.team_id\n ) as \"is_team_member!\"\n FROM comms_channels c\n LEFT JOIN comms_channel_participants cp\n ON cp.channel_id = c.id AND cp.user_id = $2 AND cp.left_at IS NULL\n WHERE c.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "role?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_type!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "org_id?",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "team_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "is_team_member!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ true,
+ true,
+ null
+ ]
+ },
+ "hash": "f99d012fe06786291fde33923dd5db92c98951968e1a5d1e07cb1bdee0552038"
+}
diff --git a/.sqlx/query-fcd4b2c0a70c138c4efcc3698f6fe4522197997819944c08284ce264554b1012.json b/.sqlx/query-fcd4b2c0a70c138c4efcc3698f6fe4522197997819944c08284ce264554b1012.json
new file mode 100644
index 0000000000..e1e246c8c9
--- /dev/null
+++ b/.sqlx/query-fcd4b2c0a70c138c4efcc3698f6fe4522197997819944c08284ce264554b1012.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id\n FROM calls\n WHERE id = $1\n\n UNION ALL\n\n SELECT share_permission_id\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShare\" = 'PUBLIC'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "fcd4b2c0a70c138c4efcc3698f6fe4522197997819944c08284ce264554b1012"
+}
diff --git a/.sqlx/query-ff96096a9ac83c19f76d4392d718e18a042b3358de4837f0e6eb7c4f263ea7c9.json b/.sqlx/query-ff96096a9ac83c19f76d4392d718e18a042b3358de4837f0e6eb7c4f263ea7c9.json
new file mode 100644
index 0000000000..60000f0db0
--- /dev/null
+++ b/.sqlx/query-ff96096a9ac83c19f76d4392d718e18a042b3358de4837f0e6eb7c4f263ea7c9.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n owner_team.team_id AS \"owner_team_id!\"\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 JOIN team_user owner_team\n ON owner_team.user_id = document.owner\n AND owner_team.team_id::text = ANY($2)\n WHERE document.id = $1\n AND share_permission.\"linkShare\" = 'TEAM'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_team_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ true,
+ false
+ ]
+ },
+ "hash": "ff96096a9ac83c19f76d4392d718e18a042b3358de4837f0e6eb7c4f263ea7c9"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 747a1214e3..86d39b1f4a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6193,16 +6193,20 @@ dependencies = [
"axum",
"bot_id",
"cached",
+ "clap",
"cool_asserts",
+ "database_env_vars",
"futures",
"macro_authorization",
"macro_db_migrator",
+ "macro_entrypoint",
"macro_user_id",
"mockall",
"model",
"model-entity",
"model-error-response",
"model_user",
+ "models_entity_access_management",
"models_permissions",
"rootcause",
"serde",
diff --git a/crates/entity_access/Cargo.toml b/crates/entity_access/Cargo.toml
index 9d36e53aca..c9ed57914f 100644
--- a/crates/entity_access/Cargo.toml
+++ b/crates/entity_access/Cargo.toml
@@ -4,6 +4,11 @@ name = "entity_access"
publish = false
version = "0.1.0"
+[[bin]]
+name = "explain_access"
+path = "src/bin/explain_access.rs"
+required-features = ["explain_binary"]
+
[features]
axum = [
"dep:axum",
@@ -12,6 +17,13 @@ axum = [
"dep:model-error-response",
]
default = ["axum", "inbound", "outbound", "ports"]
+explain_binary = [
+ "dep:clap",
+ "dep:database_env_vars",
+ "dep:macro_entrypoint",
+ "outbound",
+ "ports",
+]
inbound = ["axum", "ports"]
outbound = ["dep:cached", "ports"]
ports = ["dep:tokio"]
@@ -32,8 +44,13 @@ bot_id = { path = "../bot_id" }
rootcause = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
+models_entity_access_management = { path = "../models_entity_access_management" }
models_permissions = { path = "../models_permissions" }
+clap = { workspace = true, optional = true }
+database_env_vars = { path = "../database_env_vars", optional = true }
+macro_entrypoint = { path = "../macro_entrypoint", optional = true }
+
# Async runtime (for ports)
tokio = { workspace = true, optional = true }
diff --git a/crates/entity_access/src/bin/explain_access.rs b/crates/entity_access/src/bin/explain_access.rs
new file mode 100644
index 0000000000..af6818122d
--- /dev/null
+++ b/crates/entity_access/src/bin/explain_access.rs
@@ -0,0 +1,71 @@
+use clap::{Parser, ValueEnum};
+use database_env_vars::DatabaseUrl;
+use entity_access::{
+ domain::{explain::ExplainAccessServiceImpl, models::EntityType, ports::ExplainAccessService},
+ outbound::PgExplainAccessRepository,
+};
+use macro_entrypoint::MacroEntrypoint;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::postgres::PgPoolOptions;
+use std::str::FromStr;
+
+#[derive(Clone, Copy, Debug, ValueEnum)]
+enum OutputFormat {
+ Text,
+ Json,
+}
+
+#[derive(Debug, Parser)]
+#[command(version, about = "Explain how a user has access to an entity")]
+struct Args {
+ /// Macro user id, for example `macro|[email protected]`.
+ #[arg(long)]
+ user: String,
+
+ /// Entity id.
+ #[arg(long)]
+ entity_id: String,
+
+ /// Entity type (`document`, `email_thread`, `thread`, …).
+ #[arg(long, value_parser = parse_cli_entity_type)]
+ entity_type: EntityType,
+
+ /// Output format.
+ #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
+ format: OutputFormat,
+}
+
+fn parse_cli_entity_type(value: &str) -> Result<EntityType, String> {
+ let normalized = if value == "thread" {
+ "email_thread"
+ } else {
+ value
+ };
+ EntityType::from_str(normalized).map_err(|_| format!("invalid entity type: {value}"))
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ MacroEntrypoint::default().init();
+
+ let args = Args::parse();
+ let user = MacroUserIdStr::try_from(args.user)?;
+ let database_url = DatabaseUrl::new()?;
+ let pool = PgPoolOptions::new()
+ .min_connections(1)
+ .max_connections(5)
+ .connect(database_url.as_ref())
+ .await?;
+
+ let service = ExplainAccessServiceImpl::new(PgExplainAccessRepository::new(pool));
+ let explanation = service
+ .explain_access(&user, &args.entity_id, args.entity_type)
+ .await?;
+
+ match args.format {
+ OutputFormat::Text => print!("{explanation}"),
+ OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&explanation)?),
+ }
+
+ Ok(())
+}
diff --git a/crates/entity_access/src/domain.rs b/crates/entity_access/src/domain.rs
index 732527f23b..e05641305e 100644
--- a/crates/entity_access/src/domain.rs
+++ b/crates/entity_access/src/domain.rs
@@ -9,3 +9,6 @@ pub mod ports;
#[cfg(feature = "ports")]
pub mod service;
+
+#[cfg(feature = "explain_binary")]
+pub mod explain;
diff --git a/crates/entity_access/src/domain/explain.rs b/crates/entity_access/src/domain/explain.rs
new file mode 100644
index 0000000000..f6270f9555
--- /dev/null
+++ b/crates/entity_access/src/domain/explain.rs
@@ -0,0 +1,66 @@
+//! Explain how a user can reach an entity.
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::{
+ models::{AccessError, AccessExplanation, Entity, EntityType},
+ ports::{ExplainAccessRepository, ExplainAccessService},
+};
+use macro_user_id::{
+ cowlike::CowLike, lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr,
+};
+
+/// Orchestrates labeled access explanations.
+#[derive(Clone)]
+pub struct ExplainAccessServiceImpl<R> {
+ repo: R,
+}
+
+impl<R> ExplainAccessServiceImpl<R>
+where
+ R: ExplainAccessRepository,
+{
+ /// Create a new explain service.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+}
+
+impl<R> ExplainAccessService for ExplainAccessServiceImpl<R>
+where
+ R: ExplainAccessRepository,
+{
+ #[tracing::instrument(err, skip(self))]
+ async fn explain_access(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<AccessExplanation, AccessError> {
+ if !supports_explain(entity_type) {
+ return Err(AccessError::BadRequest("Unsupported entity type"));
+ }
+
+ let grants = self
+ .repo
+ .list_access_grants(user_id, entity_id, entity_type)
+ .await?;
+
+ Ok(AccessExplanation::from_grants(
+ MacroUserIdStr(user_id.clone().into_owned()),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ grants,
+ ))
+ }
+}
+
+fn supports_explain(entity_type: EntityType) -> bool {
+ !matches!(
+ entity_type,
+ EntityType::User | EntityType::ChannelMessage | EntityType::Skill
+ )
+}
diff --git a/crates/entity_access/src/domain/explain/test.rs b/crates/entity_access/src/domain/explain/test.rs
new file mode 100644
index 0000000000..c32920171a
--- /dev/null
+++ b/crates/entity_access/src/domain/explain/test.rs
@@ -0,0 +1,82 @@
+use super::*;
+use crate::domain::{
+ models::{AccessError, AccessGrant, AccessLevel, EntityPermission, EntityType},
+ ports::{ExplainAccessRepository, ExplainAccessService},
+};
+use std::future::Future;
+
+#[derive(Clone)]
+struct FakeRepo {
+ grants: Vec<AccessGrant>,
+}
+
+impl ExplainAccessRepository for FakeRepo {
+ fn list_access_grants(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> impl Future<Output = Result<Vec<AccessGrant>, AccessError>> + Send {
+ let grants = self.grants.clone();
+ async move { Ok(grants) }
+ }
+}
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+#[tokio::test]
+async fn unsupported_types_are_bad_request() {
+ let service = ExplainAccessServiceImpl::new(FakeRepo { grants: vec![] });
+ let user = user();
+
+ for entity_type in [
+ EntityType::User,
+ EntityType::ChannelMessage,
+ EntityType::Skill,
+ ] {
+ let error = service
+ .explain_access(&user, "id", entity_type)
+ .await
+ .unwrap_err();
+ assert!(matches!(error, AccessError::BadRequest(_)));
+ }
+}
+
+#[tokio::test]
+async fn empty_grants_are_success_with_no_access() {
+ let service = ExplainAccessServiceImpl::new(FakeRepo { grants: vec![] });
+ let user = user();
+
+ let explanation = service
+ .explain_access(&user, "doc-1", EntityType::Document)
+ .await
+ .unwrap();
+
+ assert_eq!(explanation.effective, None);
+ assert!(explanation.grants.is_empty());
+}
+
+#[tokio::test]
+async fn service_keeps_repo_grants_and_computes_effective() {
+ let service = ExplainAccessServiceImpl::new(FakeRepo {
+ grants: vec![AccessGrant::PublicLink {
+ access_level: AccessLevel::Comment,
+ }],
+ });
+ let user = user();
+
+ let explanation = service
+ .explain_access(&user, "doc-1", EntityType::Document)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ explanation.effective,
+ Some(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment
+ })
+ );
+ assert_eq!(explanation.grants.len(), 1);
+}
diff --git a/crates/entity_access/src/domain/models.rs b/crates/entity_access/src/domain/models.rs
index bc82821d9d..9239bd9be3 100644
--- a/crates/entity_access/src/domain/models.rs
+++ b/crates/entity_access/src/domain/models.rs
@@ -9,8 +9,16 @@ use macro_user_id::user_id::MacroUserIdStr;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
+#[cfg(feature = "explain_binary")]
+mod access_explanation;
+
+#[cfg(feature = "explain_binary")]
+pub use access_explanation::{
+ AccessExplanation, AccessGrant, EmailAttachmentReason, ForeignEntityAuthEntity,
+};
pub use bot_id::{BotId, BotIdStr};
pub use model_entity::EntityType;
+pub use models_entity_access_management::EntityAccessSourceType;
pub use models_permissions::share_permission::access_level::AccessLevel;
pub use models_permissions::share_permission::access_level::{
CommentAccessLevel, EditAccessLevel, OwnerAccessLevel, ViewAccessLevel,
@@ -208,7 +216,7 @@ pub trait RequiredPermission: std::fmt::Debug + Send + Sync + 'static {
///
/// Items (documents, chats, projects, threads) use access levels.
/// Channels use view-only permission or participant roles.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EntityPermission {
@@ -378,7 +386,7 @@ pub enum ChannelRoleResult {
}
/// A given entity
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Entity {
/// The id of the entity
pub entity_id: String,
diff --git a/crates/entity_access/src/domain/models/access_explanation.rs b/crates/entity_access/src/domain/models/access_explanation.rs
new file mode 100644
index 0000000000..5bf5ca70f2
--- /dev/null
+++ b/crates/entity_access/src/domain/models/access_explanation.rs
@@ -0,0 +1,448 @@
+#[cfg(test)]
+mod test;
+
+use std::fmt::{Display, Formatter, Result as FmtResult};
+
+use macro_user_id::user_id::MacroUserIdStr;
+use models_entity_access_management::EntityAccessSourceType;
+use serde::Serialize;
+use uuid::Uuid;
+
+use super::{AccessLevel, Entity, EntityPermission, ParticipantRole, TeamRole};
+
+/// Every matching grant path for a user on one entity, plus the strongest
+/// permission those grants imply.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct AccessExplanation {
+ /// The user whose access was explained.
+ pub user_id: MacroUserIdStr<'static>,
+ /// The entity that was queried.
+ pub entity: Entity,
+ /// The strongest permission implied by [`Self::grants`].
+ ///
+ /// `None` when no grant matched. That is a successful answer, not an error.
+ pub effective: Option<EntityPermission>,
+ /// Every grant path that matched. Empty means the user has no access.
+ pub grants: Vec<AccessGrant>,
+}
+
+impl AccessExplanation {
+ /// Build an explanation from already-resolved grants.
+ pub fn from_grants(
+ user_id: MacroUserIdStr<'static>,
+ entity: Entity,
+ grants: Vec<AccessGrant>,
+ ) -> Self {
+ let effective = strongest_permission(&grants);
+ Self {
+ user_id,
+ entity,
+ effective,
+ grants,
+ }
+ }
+
+ /// The effective access level when the permission is item-shaped.
+ pub fn effective_access_level(&self) -> Option<AccessLevel> {
+ match self.effective {
+ Some(EntityPermission::AccessLevel { access_level }) => Some(access_level),
+ _ => None,
+ }
+ }
+}
+
+impl Display for AccessExplanation {
+ fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+ writeln!(f, "user: {}", self.user_id)?;
+ writeln!(
+ f,
+ "entity: {} / {}",
+ self.entity.entity_type, self.entity.entity_id
+ )?;
+ match self.effective {
+ Some(permission) => writeln!(f, "effective: {}", format_permission(&permission))?,
+ None => writeln!(f, "effective: none")?,
+ }
+ writeln!(f)?;
+ if self.grants.is_empty() {
+ writeln!(f, "grants: none")?;
+ } else {
+ writeln!(f, "grants:")?;
+ for grant in &self.grants {
+ writeln!(f, " - {grant}")?;
+ }
+ }
+ Ok(())
+ }
+}
+
+/// Why a document is reachable through an attached email thread.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum EmailAttachmentReason {
+ /// The caller owns the attached thread's inbox.
+ InboxOwner,
+ /// The caller is delegated the attached thread's inbox.
+ InboxDelegate,
+ /// The caller has an `entity_access` row on the attached thread.
+ ThreadGrant,
+}
+
+impl EmailAttachmentReason {
+ fn access_level(self) -> AccessLevel {
+ match self {
+ Self::InboxOwner | Self::InboxDelegate => AccessLevel::Edit,
+ Self::ThreadGrant => AccessLevel::View,
+ }
+ }
+
+ fn parse_db(value: &str) -> Option<Self> {
+ match value {
+ "inbox_owner" => Some(Self::InboxOwner),
+ "inbox_delegate" => Some(Self::InboxDelegate),
+ "thread_grant" => Some(Self::ThreadGrant),
+ _ => None,
+ }
+ }
+}
+
+impl Display for EmailAttachmentReason {
+ fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+ f.write_str(match self {
+ Self::InboxOwner => "inbox_owner",
+ Self::InboxDelegate => "inbox_delegate",
+ Self::ThreadGrant => "thread_grant",
+ })
+ }
+}
+
+/// Principal kind stored on a foreign entity row.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ForeignEntityAuthEntity {
+ /// Stored for a user.
+ User,
+ /// Stored for a team.
+ Team,
+}
+
+impl ForeignEntityAuthEntity {
+ /// Wire value stored in `foreign_entity.stored_for_auth_entity`.
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::User => "user",
+ Self::Team => "team",
+ }
+ }
+
+ fn parse_db(value: &str) -> Option<Self> {
+ match value {
+ "user" => Some(Self::User),
+ "team" => Some(Self::Team),
+ _ => None,
+ }
+ }
+}
+
+impl Display for ForeignEntityAuthEntity {
+ fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+ f.write_str(self.as_str())
+ }
+}
+
+/// One concrete path that grants a user access to an entity.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum AccessGrant {
+ /// A matching `entity_access` row.
+ EntityAccess {
+ /// Who the row was granted to.
+ source_type: EntityAccessSourceType,
+ /// User id, channel id, or team id.
+ source_id: String,
+ /// Level stored on the row.
+ access_level: AccessLevel,
+ /// Present when the row was copied from a parent project share.
+ granted_from_project_id: Option<String>,
+ },
+ /// `SharePermission` with `linkShare = PUBLIC`.
+ PublicLink {
+ /// Level on the public link.
+ access_level: AccessLevel,
+ },
+ /// `SharePermission` with `linkShare = TEAM`, via the owner's team.
+ TeamLink {
+ /// Level on the team link.
+ access_level: AccessLevel,
+ /// The owner's team that matched the caller's source ids.
+ owner_team_id: Uuid,
+ },
+ /// The caller owns the email thread's inbox.
+ InboxOwner,
+ /// The caller is the primary on a delegated inbox.
+ InboxDelegate {
+ /// The mailbox owner whose inbox was delegated.
+ mailbox_owner: MacroUserIdStr<'static>,
+ },
+ /// The thread's containing project has an `entity_access` row for the caller.
+ ContainingProject {
+ /// The project that granted View.
+ project_id: String,
+ },
+ /// A document reachable because it is attached to a thread the caller can see.
+ EmailAttachmentThread {
+ /// The linked email thread.
+ thread_id: Uuid,
+ /// Which thread path produced this grant.
+ reason: EmailAttachmentReason,
+ },
+ /// CRM access via membership on the entity's owning team.
+ CrmTeam {
+ /// The team that owns the CRM row.
+ team_id: Uuid,
+ /// The caller's role on that team.
+ team_role: TeamRole,
+ /// Mapped access level after hidden-row rules.
+ access_level: AccessLevel,
+ },
+ /// An active channel participant row.
+ ChannelParticipant {
+ /// Stored participant role.
+ role: ParticipantRole,
+ },
+ /// A public channel with no participant row defaults to Member.
+ ChannelPublicDefault,
+ /// A team channel visible because the caller is on the owning team.
+ ChannelTeamViewOnly {
+ /// The channel's owning team.
+ team_id: Uuid,
+ },
+ /// Direct `team_user` membership on the requested team.
+ TeamMembership {
+ /// Role on that team.
+ role: TeamRole,
+ },
+ /// The caller set the reminder.
+ ReminderOwner,
+ /// The caller owns the calendar event.
+ CalendarOwner,
+ /// The caller is delegated the event's source inbox.
+ CalendarInboxDelegate,
+ /// A foreign entity stored for a matching source pair.
+ ForeignEntity {
+ /// The stored-for principal.
+ stored_for_id: String,
+ /// User or team.
+ stored_for_auth_entity: ForeignEntityAuthEntity,
+ },
+ /// Current static-file policy. Every caller gets View.
+ StaticFileAlwaysView,
+}
+
+impl AccessGrant {
+ /// The permission this grant confers by itself.
+ pub fn permission(&self) -> EntityPermission {
+ match self {
+ Self::EntityAccess { access_level, .. }
+ | Self::PublicLink { access_level }
+ | Self::TeamLink { access_level, .. }
+ | Self::CrmTeam { access_level, .. } => EntityPermission::AccessLevel {
+ access_level: *access_level,
+ },
+ Self::ContainingProject { .. } => EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ },
+ Self::EmailAttachmentThread { reason, .. } => EntityPermission::AccessLevel {
+ access_level: reason.access_level(),
+ },
+ Self::InboxOwner | Self::ReminderOwner | Self::CalendarOwner => {
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ }
+ }
+ Self::InboxDelegate { .. } => EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ Self::CalendarInboxDelegate => EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ Self::StaticFileAlwaysView | Self::ForeignEntity { .. } => {
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ }
+ }
+ Self::ChannelParticipant { role } => EntityPermission::ChannelRole { role: *role },
+ Self::ChannelPublicDefault => EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ },
+ Self::ChannelTeamViewOnly { .. } => EntityPermission::ChannelViewOnly,
+ Self::TeamMembership { role } => EntityPermission::TeamRole { role: *role },
+ }
+ }
+
+ pub(crate) fn email_attachment_reason(value: &str) -> Option<EmailAttachmentReason> {
+ EmailAttachmentReason::parse_db(value)
+ }
+
+ pub(crate) fn foreign_entity_auth(value: &str) -> Option<ForeignEntityAuthEntity> {
+ ForeignEntityAuthEntity::parse_db(value)
+ }
+}
+
+impl Display for AccessGrant {
+ fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+ match self {
+ Self::EntityAccess {
+ source_type,
+ source_id,
+ access_level,
+ granted_from_project_id,
+ } => {
+ write!(
+ f,
+ "entity_access {} {source_id} {access_level}",
+ format_source_type(*source_type)
+ )?;
+ if let Some(project_id) = granted_from_project_id {
+ write!(f, " granted_from_project {project_id}")?;
+ }
+ Ok(())
+ }
+ Self::PublicLink { access_level } => write!(f, "public_link {access_level}"),
+ Self::TeamLink {
+ access_level,
+ owner_team_id,
+ } => write!(f, "team_link {owner_team_id} {access_level}"),
+ Self::InboxOwner => write!(f, "inbox_owner"),
+ Self::InboxDelegate { mailbox_owner } => {
+ write!(f, "inbox_delegate mailbox={mailbox_owner}")
+ }
+ Self::ContainingProject { project_id } => {
+ write!(f, "containing_project {project_id}")
+ }
+ Self::EmailAttachmentThread { thread_id, reason } => {
+ write!(f, "email_attachment_thread {thread_id} {reason}")
+ }
+ Self::CrmTeam {
+ team_id,
+ team_role,
+ access_level,
+ } => write!(
+ f,
+ "crm_team {team_id} role={} {access_level}",
+ format_team_role(*team_role)
+ ),
+ Self::ChannelParticipant { role } => {
+ write!(f, "channel_participant {}", format_participant_role(*role))
+ }
+ Self::ChannelPublicDefault => write!(f, "channel_public_default"),
+ Self::ChannelTeamViewOnly { team_id } => {
+ write!(f, "channel_team_view_only {team_id}")
+ }
+ Self::TeamMembership { role } => {
+ write!(f, "team_membership {}", format_team_role(*role))
+ }
+ Self::ReminderOwner => write!(f, "reminder_owner"),
+ Self::CalendarOwner => write!(f, "calendar_owner"),
+ Self::CalendarInboxDelegate => write!(f, "calendar_inbox_delegate"),
+ Self::ForeignEntity {
+ stored_for_id,
+ stored_for_auth_entity,
+ } => write!(
+ f,
+ "foreign_entity stored_for={stored_for_id} auth={stored_for_auth_entity}"
+ ),
+ Self::StaticFileAlwaysView => write!(f, "static_file_always_view"),
+ }
+ }
+}
+
+fn strongest_permission(grants: &[AccessGrant]) -> Option<EntityPermission> {
+ grants
+ .iter()
+ .map(AccessGrant::permission)
+ .reduce(stronger_permission)
+}
+
+fn stronger_permission(left: EntityPermission, right: EntityPermission) -> EntityPermission {
+ match (left, right) {
+ (
+ EntityPermission::AccessLevel { access_level: left },
+ EntityPermission::AccessLevel {
+ access_level: right,
+ },
+ ) => EntityPermission::AccessLevel {
+ access_level: left.max(right),
+ },
+ (EntityPermission::TeamRole { role: left }, EntityPermission::TeamRole { role: right }) => {
+ EntityPermission::TeamRole {
+ role: left.max(right),
+ }
+ }
+ (
+ EntityPermission::ChannelRole { role: left },
+ EntityPermission::ChannelRole { role: right },
+ ) => EntityPermission::ChannelRole {
+ role: stronger_participant_role(left, right),
+ },
+ (EntityPermission::ChannelViewOnly, other @ EntityPermission::ChannelRole { .. })
+ | (other @ EntityPermission::ChannelRole { .. }, EntityPermission::ChannelViewOnly) => {
+ other
+ }
+ (EntityPermission::ChannelViewOnly, EntityPermission::ChannelViewOnly) => {
+ EntityPermission::ChannelViewOnly
+ }
+ (left, _) => left,
+ }
+}
+
+fn stronger_participant_role(left: ParticipantRole, right: ParticipantRole) -> ParticipantRole {
+ if participant_rank(left) >= participant_rank(right) {
+ left
+ } else {
+ right
+ }
+}
+
+fn participant_rank(role: ParticipantRole) -> u8 {
+ match role {
+ ParticipantRole::Member => 1,
+ ParticipantRole::Admin => 2,
+ ParticipantRole::Owner => 3,
+ }
+}
+
+fn format_permission(permission: &EntityPermission) -> String {
+ match permission {
+ EntityPermission::AccessLevel { access_level } => access_level.to_string(),
+ EntityPermission::ChannelViewOnly => "channel_view_only".to_string(),
+ EntityPermission::ChannelRole { role } => {
+ format!("channel_{}", format_participant_role(*role))
+ }
+ EntityPermission::TeamRole { role } => format!("team_{}", format_team_role(*role)),
+ }
+}
+
+fn format_source_type(source_type: EntityAccessSourceType) -> &'static str {
+ match source_type {
+ EntityAccessSourceType::User => "user",
+ EntityAccessSourceType::Channel => "channel",
+ EntityAccessSourceType::Team => "team",
+ }
+}
+
+fn format_team_role(role: TeamRole) -> &'static str {
+ match role {
+ TeamRole::Member => "member",
+ TeamRole::Admin => "admin",
+ TeamRole::Owner => "owner",
+ }
+}
+
+fn format_participant_role(role: ParticipantRole) -> &'static str {
+ match role {
+ ParticipantRole::Member => "member",
+ ParticipantRole::Admin => "admin",
+ ParticipantRole::Owner => "owner",
+ }
+}
diff --git a/crates/entity_access/src/domain/models/access_explanation/test.rs b/crates/entity_access/src/domain/models/access_explanation/test.rs
new file mode 100644
index 0000000000..26f6a8daaa
--- /dev/null
+++ b/crates/entity_access/src/domain/models/access_explanation/test.rs
@@ -0,0 +1,177 @@
+use super::*;
+use crate::domain::models::{
+ AccessLevel, EmailAttachmentReason, Entity, EntityPermission, EntityType, ParticipantRole,
+};
+use models_entity_access_management::EntityAccessSourceType;
+use uuid::Uuid;
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn document() -> Entity {
+ Entity {
+ entity_id: "doc-1".to_string(),
+ entity_type: EntityType::Document,
+ }
+}
+
+#[test]
+fn empty_grants_mean_no_access() {
+ let explanation = AccessExplanation::from_grants(user(), document(), vec![]);
+
+ assert_eq!(explanation.effective, None);
+ assert_eq!(explanation.effective_access_level(), None);
+ assert!(explanation.grants.is_empty());
+}
+
+#[test]
+fn strongest_access_level_wins() {
+ let grants = vec![
+ AccessGrant::PublicLink {
+ access_level: AccessLevel::View,
+ },
+ AccessGrant::EntityAccess {
+ source_type: EntityAccessSourceType::User,
+ source_id: "macro|[email protected]".to_string(),
+ access_level: AccessLevel::Edit,
+ granted_from_project_id: None,
+ },
+ AccessGrant::TeamLink {
+ access_level: AccessLevel::Comment,
+ owner_team_id: Uuid::nil(),
+ },
+ ];
+
+ let explanation = AccessExplanation::from_grants(user(), document(), grants);
+
+ assert_eq!(
+ explanation.effective,
+ Some(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit
+ })
+ );
+}
+
+#[test]
+fn inbox_owner_is_owner() {
+ let explanation = AccessExplanation::from_grants(
+ user(),
+ Entity {
+ entity_id: "thread-1".to_string(),
+ entity_type: EntityType::EmailThread,
+ },
+ vec![
+ AccessGrant::InboxOwner,
+ AccessGrant::PublicLink {
+ access_level: AccessLevel::View,
+ },
+ ],
+ );
+
+ assert_eq!(
+ explanation.effective_access_level(),
+ Some(AccessLevel::Owner)
+ );
+}
+
+#[test]
+fn channel_participant_beats_team_view_only() {
+ let explanation = AccessExplanation::from_grants(
+ user(),
+ Entity {
+ entity_id: "channel-1".to_string(),
+ entity_type: EntityType::Channel,
+ },
+ vec![
+ AccessGrant::ChannelTeamViewOnly {
+ team_id: Uuid::nil(),
+ },
+ AccessGrant::ChannelParticipant {
+ role: ParticipantRole::Admin,
+ },
+ ],
+ );
+
+ assert_eq!(
+ explanation.effective,
+ Some(EntityPermission::ChannelRole {
+ role: ParticipantRole::Admin
+ })
+ );
+}
+
+#[test]
+fn calendar_delegate_is_edit() {
+ assert_eq!(
+ AccessGrant::CalendarInboxDelegate.permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit
+ }
+ );
+}
+
+#[test]
+fn containing_project_is_view() {
+ assert_eq!(
+ AccessGrant::ContainingProject {
+ project_id: "project-1".to_string(),
+ }
+ .permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View
+ }
+ );
+}
+
+#[test]
+fn channel_public_default_is_member() {
+ assert_eq!(
+ AccessGrant::ChannelPublicDefault.permission(),
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Member
+ }
+ );
+}
+
+#[test]
+fn email_attachment_reason_maps_level() {
+ let thread_id = Uuid::nil();
+ assert_eq!(
+ AccessGrant::EmailAttachmentThread {
+ thread_id,
+ reason: EmailAttachmentReason::InboxOwner,
+ }
+ .permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit
+ }
+ );
+ assert_eq!(
+ AccessGrant::EmailAttachmentThread {
+ thread_id,
+ reason: EmailAttachmentReason::ThreadGrant,
+ }
+ .permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View
+ }
+ );
+}
+
+#[test]
+fn display_lists_each_grant() {
+ let explanation = AccessExplanation::from_grants(
+ user(),
+ document(),
+ vec![AccessGrant::PublicLink {
+ access_level: AccessLevel::View,
+ }],
+ );
+ let rendered = explanation.to_string();
+
+ assert!(rendered.contains("user: macro|[email protected]"));
+ assert!(rendered.contains("entity: document / doc-1"));
+ assert!(rendered.contains("effective: view"));
+ assert!(rendered.contains("public_link view"));
+}
diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rs
index c7d4c5f940..4eb5473b7c 100644
--- a/crates/entity_access/src/domain/ports.rs
+++ b/crates/entity_access/src/domain/ports.rs
@@ -8,6 +8,8 @@ use crate::domain::models::{
CrmEntityAccess, EntityAccessReceipt, EntityPermission, RequiredPermission, TeamRole,
UserTeamInfo, ViewAccessLevel,
};
+#[cfg(feature = "explain_binary")]
+use crate::domain::models::{AccessExplanation, AccessGrant};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};
use std::{collections::HashMap, future::Future};
use uuid::Uuid;
@@ -239,6 +241,37 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<Option<UserTeamInfo>, AccessError>> + Send;
}
+/// Repository that returns labeled grant paths instead of a collapsed level.
+#[cfg(feature = "explain_binary")]
+pub trait ExplainAccessRepository: Clone + Send + Sync + 'static {
+ /// List every grant path that gives `user_id` access to the entity.
+ ///
+ /// Returns an empty list when the user has no access. Unsupported entity
+ /// types are rejected by [`ExplainAccessService`], not here.
+ fn list_access_grants(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> impl Future<Output = Result<Vec<AccessGrant>, AccessError>> + Send;
+}
+
+/// Service that explains how a user can reach an entity.
+#[cfg(feature = "explain_binary")]
+pub trait ExplainAccessService: Clone + Send + Sync + 'static {
+ /// Explain every grant path for `user_id` on the entity.
+ ///
+ /// Empty grants and `effective: None` mean no access. That is success.
+ /// [`AccessError::BadRequest`] is reserved for unsupported types and
+ /// malformed ids.
+ fn explain_access(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> impl Future<Output = Result<AccessExplanation, AccessError>> + Send;
+}
+
/// Service for checking entity access levels.
///
/// This service orchestrates access checks using the repository.
diff --git a/crates/entity_access/src/outbound.rs b/crates/entity_access/src/outbound.rs
index 9ce3e900a8..a7f1a31393 100644
--- a/crates/entity_access/src/outbound.rs
+++ b/crates/entity_access/src/outbound.rs
@@ -3,7 +3,11 @@
//! These modules contain concrete implementations of the domain ports.
mod pg_access_repo;
+#[cfg(feature = "explain_binary")]
+mod pg_explain_access_repo;
pub use pg_access_repo::{
PgAccessRepository, SourceIds, get_team_scope_source_ids, get_user_source_ids,
};
+#[cfg(feature = "explain_binary")]
+pub use pg_explain_access_repo::PgExplainAccessRepository;
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index c1ae9f45e3..52564300b2 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -1,6 +1,6 @@
//! PostgreSQL implementation of the AccessRepository trait.
-mod queries;
+pub(crate) mod queries;
pub use queries::{SourceIds, get_team_scope_source_ids, get_user_source_ids};
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries.rs b/crates/entity_access/src/outbound/pg_access_repo/queries.rs
index 1b1d160bb8..bcd28f2c3b 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries.rs
@@ -15,6 +15,11 @@ use macro_user_id::{
use model_entity::EntityType;
use sqlx::{Pool, Postgres};
+#[cfg(feature = "explain_binary")]
+use crate::domain::models::{AccessGrant, AccessLevel};
+#[cfg(feature = "explain_binary")]
+use models_entity_access_management::EntityAccessSourceType;
+
pub mod agent_session_access;
pub mod call_access;
pub mod call_channel;
@@ -232,3 +237,45 @@ pub(in crate::outbound::pg_access_repo) async fn get_entity_users(
.into_iter()
.collect())
}
+
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(skip(pool, source_ids), err)]
+pub async fn list_entity_access_grants(
+ pool: &Pool<Postgres>,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ source_ids: &SourceIds,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ if source_ids.0.is_empty() {
+ return Ok(vec![]);
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ source_type AS "source_type!: EntityAccessSourceType",
+ source_id,
+ access_level AS "access_level!: AccessLevel",
+ granted_from_project_id
+ FROM entity_access
+ WHERE entity_id = $1
+ AND entity_type = $2
+ AND source_id = ANY($3)
+ "#,
+ entity_id,
+ entity_type.as_ref(),
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| AccessGrant::EntityAccess {
+ source_type: row.source_type,
+ source_id: row.source_id,
+ access_level: row.access_level,
+ granted_from_project_id: row.granted_from_project_id,
+ })
+ .collect())
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
index cd5710c048..adae55e8ff 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
@@ -1,6 +1,12 @@
//! Query for agent session access level.
+#[cfg(feature = "explain_binary")]
+use crate::{
+ domain::models::AccessGrant, outbound::pg_access_repo::queries::list_entity_access_grants,
+};
use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};
+#[cfg(feature = "explain_binary")]
+use model_entity::EntityType;
use sqlx::PgPool;
use std::str::FromStr;
@@ -46,3 +52,13 @@ pub async fn get_agent_session_access(
Ok(highest_level)
}
+
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(err, skip(pool, source_ids))]
+pub async fn explain_agent_session_access(
+ pool: &PgPool,
+ agent_session_id: &uuid::Uuid,
+ source_ids: &SourceIds,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ list_entity_access_grants(pool, agent_session_id, EntityType::AgentSession, source_ids).await
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access.rs
index 5ec904ea6c..0e2f2a087e 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access.rs
@@ -3,7 +3,13 @@
#[cfg(test)]
mod test;
+#[cfg(feature = "explain_binary")]
+use crate::{
+ domain::models::AccessGrant, outbound::pg_access_repo::queries::list_entity_access_grants,
+};
use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};
+#[cfg(feature = "explain_binary")]
+use model_entity::EntityType;
use sqlx::PgPool;
use std::str::FromStr;
@@ -99,3 +105,83 @@ pub async fn get_call_access(
Ok(highest_level)
}
+
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(err, skip(pool, source_ids))]
+pub async fn explain_call_access(
+ pool: &PgPool,
+ call_id: &uuid::Uuid,
+ source_ids: &SourceIds,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let mut grants = list_entity_access_grants(pool, call_id, EntityType::Call, source_ids).await?;
+
+ let public_levels = sqlx::query_scalar!(
+ r#"
+ SELECT
+ share_permission."linkShareAccessLevel" AS "access_level!: AccessLevel"
+ FROM "SharePermission" share_permission
+ JOIN (
+ SELECT share_permission_id
+ FROM calls
+ WHERE id = $1
+
+ UNION ALL
+
+ SELECT share_permission_id
+ FROM call_records
+ WHERE id = $1
+ LIMIT 1
+ ) call_item ON call_item.share_permission_id = share_permission.id
+ WHERE share_permission."linkShare" = 'PUBLIC'
+ AND share_permission."linkShareAccessLevel" IS NOT NULL
+ "#,
+ call_id,
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(
+ public_levels
+ .into_iter()
+ .map(|access_level| AccessGrant::PublicLink { access_level }),
+ );
+
+ if source_ids.0.is_empty() {
+ return Ok(grants);
+ }
+
+ let team_rows = sqlx::query!(
+ r#"
+ SELECT
+ share_permission."linkShareAccessLevel" AS "access_level!: AccessLevel",
+ owner_team.team_id AS "owner_team_id!"
+ FROM "SharePermission" share_permission
+ JOIN (
+ SELECT share_permission_id, created_by
+ FROM calls
+ WHERE id = $1
+
+ UNION ALL
+
+ SELECT share_permission_id, created_by
+ FROM call_records
+ WHERE id = $1
+ LIMIT 1
+ ) call_item ON call_item.share_permission_id = share_permission.id
+ JOIN team_user owner_team
+ ON owner_team.user_id = call_item.created_by
+ AND owner_team.team_id::text = ANY($2)
+ WHERE share_permission."linkShare" = 'TEAM'
+ AND share_permission."linkShareAccessLevel" IS NOT NULL
+ "#,
+ call_id,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(team_rows.into_iter().map(|row| AccessGrant::TeamLink {
+ access_level: row.access_level,
+ owner_team_id: row.owner_team_id,
+ }));
+
+ Ok(grants)
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
index fb974627e3..8369563fb6 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
@@ -3,6 +3,8 @@
#[cfg(test)]
mod test;
+#[cfg(feature = "explain_binary")]
+use crate::domain::models::AccessGrant;
use crate::domain::models::{ChannelRoleResult, ParticipantRole};
use bot_id::BotIdStr;
use sqlx::PgPool;
@@ -13,6 +15,8 @@ struct ChannelRoleRow {
role: Option<String>,
channel_type: String,
org_id: Option<i64>,
+ #[cfg_attr(not(feature = "explain_binary"), allow(dead_code))]
+ team_id: Option<Uuid>,
is_team_member: bool,
}
@@ -31,34 +35,19 @@ fn parse_role(s: &str) -> ParticipantRole {
}
}
-/// Get the user's role in a channel, considering channel type rules.
-///
-/// Returns a [`ChannelRoleResult`] that distinguishes between:
-/// - `Role(role)`: user has access with this role
-/// - `ViewOnly`: user belongs to the team that owns the team channel
-/// - `NoAccess`: channel exists but user has no access
-/// - `NotFound`: channel does not exist
-///
-/// Channel type rules:
-/// - Public channels: non-participants default to Member
-/// - Organization channels: default to Member only if user's org matches
-/// - Team channels: matching team members receive ViewOnly
-/// - Private/DM: require explicit participation
-#[tracing::instrument(err, skip(pool))]
-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
-pub async fn get_channel_role(
+async fn fetch_channel_role_row(
pool: &PgPool,
channel_id: &Uuid,
user_id: &str,
- user_org_id: Option<i64>,
-) -> Result<ChannelRoleResult, sqlx::Error> {
- let row = sqlx::query_as!(
+) -> Result<Option<ChannelRoleRow>, sqlx::Error> {
+ sqlx::query_as!(
ChannelRoleRow,
r#"
SELECT
cp.role::text as "role?",
c.channel_type::text as "channel_type!",
c.org_id as "org_id?",
+ c.team_id as "team_id?",
EXISTS (
SELECT 1
FROM team_user tu
@@ -73,9 +62,31 @@ pub async fn get_channel_role(
user_id,
)
.fetch_optional(pool)
- .await?;
+ .await
+}
- let Some(row) = row else {
+/// Get the user's role in a channel, considering channel type rules.
+///
+/// Returns a [`ChannelRoleResult`] that distinguishes between:
+/// - `Role(role)`: user has access with this role
+/// - `ViewOnly`: user belongs to the team that owns the team channel
+/// - `NoAccess`: channel exists but user has no access
+/// - `NotFound`: channel does not exist
+///
+/// Channel type rules:
+/// - Public channels: non-participants default to Member
+/// - Organization channels: default to Member only if user's org matches
+/// - Team channels: matching team members receive ViewOnly
+/// - Private/DM: require explicit participation
+#[tracing::instrument(err, skip(pool))]
+#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
+pub async fn get_channel_role(
+ pool: &PgPool,
+ channel_id: &Uuid,
+ user_id: &str,
+ user_org_id: Option<i64>,
+) -> Result<ChannelRoleResult, sqlx::Error> {
+ let Some(row) = fetch_channel_role_row(pool, channel_id, user_id).await? else {
return Ok(ChannelRoleResult::NotFound);
};
@@ -114,6 +125,34 @@ pub async fn get_channel_role(
Ok(ChannelRoleResult::NoAccess)
}
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(err, skip(pool))]
+pub async fn explain_channel_access(
+ pool: &PgPool,
+ channel_id: &Uuid,
+ user_id: &str,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let Some(row) = fetch_channel_role_row(pool, channel_id, user_id).await? else {
+ return Ok(vec![]);
+ };
+
+ if let Some(stored_role) = row.role.as_deref() {
+ return Ok(vec![AccessGrant::ChannelParticipant {
+ role: parse_role(stored_role),
+ }]);
+ }
+
+ match row.channel_type.as_str() {
+ "public" => Ok(vec![AccessGrant::ChannelPublicDefault]),
+ "team" if row.is_team_member => Ok(row
+ .team_id
+ .map(|team_id| AccessGrant::ChannelTeamViewOnly { team_id })
+ .into_iter()
+ .collect()),
+ _ => Ok(vec![]),
+ }
+}
+
/// Get a bot's channel role while operating in its owning team's scope.
///
/// An active participant row grants its stored role in any channel. Without an
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs
index 2f52aacce6..c83ccffb6c 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs
@@ -110,6 +110,17 @@ async fn matching_team_member_without_participant_is_view_only(pool: PgPool) ->
let role = get_channel_role(&pool, &channel_id, "macro|[email protected]", None).await?;
assert_eq!(role, ChannelRoleResult::ViewOnly);
+
+ #[cfg(feature = "explain_binary")]
+ {
+ let grants = explain_channel_access(&pool, &channel_id, "macro|[email protected]").await?;
+ assert_eq!(
+ grants,
+ vec![crate::domain::models::AccessGrant::ChannelTeamViewOnly {
+ team_id: TEAM_ALPHA
+ }]
+ );
+ }
Ok(())
}
@@ -126,6 +137,17 @@ async fn active_team_channel_participant_receives_stored_role(pool: PgPool) -> a
let role = get_channel_role(&pool, &channel_id, user_id, None).await?;
assert_eq!(role, ChannelRoleResult::Role(ParticipantRole::Admin));
+
+ #[cfg(feature = "explain_binary")]
+ {
+ let grants = explain_channel_access(&pool, &channel_id, user_id).await?;
+ assert_eq!(
+ grants,
+ vec![crate::domain::models::AccessGrant::ChannelParticipant {
+ role: ParticipantRole::Admin
+ }]
+ );
+ }
Ok(())
}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs
index 659b9f3b5b..cd76ba8497 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs
@@ -3,7 +3,13 @@
#[cfg(test)]
mod test;
+#[cfg(feature = "explain_binary")]
+use crate::{
+ domain::models::AccessGrant, outbound::pg_access_repo::queries::list_entity_access_grants,
+};
use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};
+#[cfg(feature = "explain_binary")]
+use model_entity::EntityType;
use sqlx::PgPool;
use std::str::FromStr;
@@ -82,3 +88,65 @@ pub async fn get_chat_access(
Ok(highest_level)
}
+
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(err, skip(pool, source_ids))]
+pub async fn explain_chat_access(
+ pool: &PgPool,
+ chat_id: &uuid::Uuid,
+ source_ids: &SourceIds,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let mut grants = list_entity_access_grants(pool, chat_id, EntityType::Chat, source_ids).await?;
+ let chat_id_str = chat_id.to_string();
+
+ let public_levels = sqlx::query_scalar!(
+ r#"
+ SELECT
+ sp."linkShareAccessLevel" AS "access_level!: AccessLevel"
+ FROM "SharePermission" sp
+ JOIN "ChatPermission" cp ON cp."sharePermissionId" = sp.id
+ WHERE cp."chatId" = $1
+ AND sp."linkShare" = 'PUBLIC'
+ AND sp."linkShareAccessLevel" IS NOT NULL
+ "#,
+ &chat_id_str
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(
+ public_levels
+ .into_iter()
+ .map(|access_level| AccessGrant::PublicLink { access_level }),
+ );
+
+ if source_ids.0.is_empty() {
+ return Ok(grants);
+ }
+
+ let team_rows = sqlx::query!(
+ r#"
+ SELECT
+ sp."linkShareAccessLevel" AS "access_level!: AccessLevel",
+ owner_tu.team_id AS "owner_team_id!"
+ FROM "SharePermission" sp
+ JOIN "ChatPermission" cp ON cp."sharePermissionId" = sp.id
+ JOIN "Chat" c ON c.id = cp."chatId"
+ JOIN team_user owner_tu
+ ON owner_tu.user_id = c."userId"
+ AND owner_tu.team_id::text = ANY($2)
+ WHERE cp."chatId" = $1
+ AND sp."linkShare" = 'TEAM'
+ AND sp."linkShareAccessLevel" IS NOT NULL
+ "#,
+ &chat_id_str,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(team_rows.into_iter().map(|row| AccessGrant::TeamLink {
+ access_level: row.access_level,
+ owner_team_id: row.owner_team_id,
+ }));
+
+ Ok(grants)
+}
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 d10844edfd..66ce6d13e6 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
@@ -3,8 +3,14 @@
#[cfg(test)]
mod test;
+#[cfg(feature = "explain_binary")]
+use crate::{
+ domain::models::AccessGrant, outbound::pg_access_repo::queries::list_entity_access_grants,
+};
use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+#[cfg(feature = "explain_binary")]
+use model_entity::EntityType;
use sqlx::PgPool;
use std::str::FromStr;
@@ -131,3 +137,155 @@ pub async fn get_document_access(
Ok(highest_level)
}
+
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(err, skip(pool, source_ids))]
+pub async fn explain_document_access(
+ pool: &PgPool,
+ document_id: &uuid::Uuid,
+ source_ids: &SourceIds,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let mut grants =
+ list_entity_access_grants(pool, document_id, EntityType::Document, source_ids).await?;
+ grants.extend(explain_document_link_shares(pool, document_id, source_ids).await?);
+
+ if let Some(user_id) = user_id {
+ grants.extend(
+ explain_document_email_attachments(pool, document_id, source_ids, user_id).await?,
+ );
+ }
+
+ Ok(grants)
+}
+
+#[cfg(feature = "explain_binary")]
+async fn explain_document_link_shares(
+ pool: &PgPool,
+ document_id: &uuid::Uuid,
+ source_ids: &SourceIds,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let document_id_str = document_id.to_string();
+ let mut grants = Vec::new();
+
+ let public_levels = sqlx::query_scalar!(
+ r#"
+ SELECT
+ share_permission."linkShareAccessLevel" AS "access_level!: AccessLevel"
+ FROM "SharePermission" share_permission
+ JOIN "DocumentPermission" document_permission
+ ON document_permission."sharePermissionId" = share_permission.id
+ WHERE share_permission."linkShare" = 'PUBLIC'
+ AND share_permission."linkShareAccessLevel" IS NOT NULL
+ AND document_permission."documentId" = $1
+ "#,
+ &document_id_str
+ )
+ .fetch_all(pool)
+ .await?;
+
+ grants.extend(
+ public_levels
+ .into_iter()
+ .map(|access_level| AccessGrant::PublicLink { access_level }),
+ );
+
+ if source_ids.0.is_empty() {
+ return Ok(grants);
+ }
+
+ let team_rows = sqlx::query!(
+ r#"
+ SELECT
+ share_permission."linkShareAccessLevel" AS "access_level!: AccessLevel",
+ owner_team.team_id AS "owner_team_id!"
+ FROM "Document" document
+ JOIN "DocumentPermission" document_permission
+ ON document_permission."documentId" = document.id
+ JOIN "SharePermission" share_permission
+ ON share_permission.id = document_permission."sharePermissionId"
+ JOIN team_user owner_team
+ ON owner_team.user_id = document.owner
+ AND owner_team.team_id::text = ANY($2)
+ WHERE document.id = $1
+ AND share_permission."linkShare" = 'TEAM'
+ AND share_permission."linkShareAccessLevel" IS NOT NULL
+ "#,
+ &document_id_str,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ grants.extend(team_rows.into_iter().map(|row| AccessGrant::TeamLink {
+ access_level: row.access_level,
+ owner_team_id: row.owner_team_id,
+ }));
+
+ Ok(grants)
+}
+
+#[cfg(feature = "explain_binary")]
+async fn explain_document_email_attachments(
+ pool: &PgPool,
+ document_id: &uuid::Uuid,
+ source_ids: &SourceIds,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let user_id_str = user_id.as_ref();
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ t.id AS thread_id,
+ CASE
+ WHEN l.macro_id = $3 THEN 'inbox_owner'
+ WHEN EXISTS (
+ SELECT 1
+ FROM macro_user_links mul
+ WHERE mul.link_id = l.id
+ AND mul.primary_macro_id = $3
+ ) THEN 'inbox_delegate'
+ ELSE 'thread_grant'
+ END AS "reason!"
+ 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 = $1
+ AND (
+ l.macro_id = $3
+ OR EXISTS (
+ SELECT 1
+ FROM macro_user_links mul
+ WHERE mul.link_id = l.id
+ AND mul.primary_macro_id = $3
+ )
+ 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)
+ )
+ )
+ "#,
+ &document_id.to_string(),
+ &source_ids.0,
+ user_id_str,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .filter_map(|row| {
+ AccessGrant::email_attachment_reason(&row.reason).map(|reason| {
+ AccessGrant::EmailAttachmentThread {
+ thread_id: row.thread_id,
+ reason,
+ }
+ })
+ })
+ .collect())
+}
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 4bca3296df..4444013efc 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
@@ -522,3 +522,142 @@ async fn email_direct_document_grant_wins_over_inherited_view(pool: PgPool) -> a
);
Ok(())
}
+
+#[cfg(feature = "explain_binary")]
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn explain_lists_public_and_entity_access_and_matches_effective(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ const REQUESTER: &str = "macro|[email protected]";
+
+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;
+ let document_id =
+ insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, Some("PUBLIC"), Some("comment"))
+ .await?;
+ insert_document_entity_access(&pool, document_id, REQUESTER, AccessLevel::Edit).await?;
+ let source_ids = SourceIds(vec![REQUESTER.to_string()]);
+ let requester = user(REQUESTER);
+
+ let access = get_document_access(&pool, &document_id, &source_ids, Some(&*requester)).await?;
+ let grants =
+ explain_document_access(&pool, &document_id, &source_ids, Some(&*requester)).await?;
+ let explanation = crate::domain::models::AccessExplanation::from_grants(
+ requester,
+ crate::domain::models::Entity {
+ entity_id: document_id.to_string(),
+ entity_type: crate::domain::models::EntityType::Document,
+ },
+ grants.clone(),
+ );
+
+ assert_eq!(explanation.effective_access_level(), access);
+ assert!(grants.iter().any(|grant| matches!(
+ grant,
+ crate::domain::models::AccessGrant::PublicLink {
+ access_level: AccessLevel::Comment
+ }
+ )));
+ assert!(grants.iter().any(|grant| matches!(
+ grant,
+ crate::domain::models::AccessGrant::EntityAccess {
+ access_level: AccessLevel::Edit,
+ ..
+ }
+ )));
+ Ok(())
+}
+
+#[cfg(feature = "explain_binary")]
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn explain_email_attachment_reasons(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, INBOX_OWNER).await?;
+ insert_user(&pool, DELEGATE).await?;
+ insert_user(&pool, OTHER_USER).await?;
+ let (link_id, thread_id, document_id) = insert_attachment_document(&pool, INBOX_OWNER).await;
+ insert_delegation(&pool, DELEGATE, INBOX_OWNER, link_id).await;
+ insert_thread_entity_access(&pool, thread_id, OTHER_USER, AccessLevel::Edit).await;
+
+ let owner = user(INBOX_OWNER);
+ let owner_grants = explain_document_access(
+ &pool,
+ &document_id,
+ &SourceIds(vec![INBOX_OWNER.to_string()]),
+ Some(&*owner),
+ )
+ .await?;
+ assert!(owner_grants.iter().any(|grant| matches!(
+ grant,
+ crate::domain::models::AccessGrant::EmailAttachmentThread {
+ reason: crate::domain::models::EmailAttachmentReason::InboxOwner,
+ ..
+ }
+ )));
+
+ let delegate = user(DELEGATE);
+ let delegate_grants = explain_document_access(
+ &pool,
+ &document_id,
+ &SourceIds(vec![DELEGATE.to_string()]),
+ Some(&*delegate),
+ )
+ .await?;
+ assert!(delegate_grants.iter().any(|grant| matches!(
+ grant,
+ crate::domain::models::AccessGrant::EmailAttachmentThread {
+ reason: crate::domain::models::EmailAttachmentReason::InboxDelegate,
+ ..
+ }
+ )));
+
+ let other = user(OTHER_USER);
+ let other_grants = explain_document_access(
+ &pool,
+ &document_id,
+ &SourceIds(vec![OTHER_USER.to_string()]),
+ Some(&*other),
+ )
+ .await?;
+ assert!(other_grants.iter().any(|grant| matches!(
+ grant,
+ crate::domain::models::AccessGrant::EmailAttachmentThread {
+ reason: crate::domain::models::EmailAttachmentReason::ThreadGrant,
+ ..
+ }
+ )));
+ Ok(())
+}
+
+#[cfg(feature = "explain_binary")]
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn explain_team_link_matches_access_level(pool: PgPool) -> anyhow::Result<()> {
+ let owner_team_id = Uuid::new_v4();
+ insert_user(&pool, OWNER_WITH_TEAM).await?;
+ add_owner_to_team(&pool, OWNER_WITH_TEAM, owner_team_id).await?;
+ let document_id =
+ insert_link_shared_document(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("comment")).await?;
+ let requester = user("macro|[email protected]");
+ let source_ids = SourceIds(vec![owner_team_id.to_string()]);
+
+ let access = get_document_access(&pool, &document_id, &source_ids, Some(&*requester)).await?;
+ let grants =
+ explain_document_access(&pool, &document_id, &source_ids, Some(&*requester)).await?;
+ let explanation = crate::domain::models::AccessExplanation::from_grants(
+ requester,
+ crate::domain::models::Entity {
+ entity_id: document_id.to_string(),
+ entity_type: crate::domain::models::EntityType::Document,
+ },
+ grants.clone(),
+ );
+
+ assert_eq!(access, Some(AccessLevel::Comment));
+ assert_eq!(explanation.effective_access_level(), access);
+ assert!(grants.iter().any(|grant| matches!(
+ grant,
+ crate::domain::models::AccessGrant::TeamLink {
+ access_level: AccessLevel::Comment,
+ owner_team_id: id
+ } if *id == owner_team_id
+ )));
+ Ok(())
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/foreign_entity_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/foreign_entity_access.rs
index ec595157e6..0aa046cfd8 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/foreign_entity_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/foreign_entity_access.rs
@@ -3,6 +3,9 @@
use sqlx::PgPool;
use uuid::Uuid;
+#[cfg(feature = "explain_binary")]
+use crate::domain::models::AccessGrant;
+
/// Check whether any stored-for source pair grants access to a foreign entity.
#[tracing::instrument(err, skip(pool, source_ids, source_auth_entities))]
pub async fn has_foreign_entity_access(
@@ -44,3 +47,54 @@ pub async fn has_foreign_entity_access(
.fetch_one(pool)
.await
}
+
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(err, skip(pool, source_ids, source_auth_entities))]
+pub async fn list_foreign_entity_grants(
+ pool: &PgPool,
+ foreign_entity_id: &Uuid,
+ source_ids: &[String],
+ source_auth_entities: &[String],
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ if source_ids.is_empty()
+ || source_auth_entities.is_empty()
+ || source_ids.len() != source_auth_entities.len()
+ {
+ return Ok(vec![]);
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ WITH source_pairs AS (
+ SELECT DISTINCT stored_for_id, stored_for_auth_entity
+ FROM UNNEST($2::text[], $3::text[])
+ AS source_rows(stored_for_id, stored_for_auth_entity)
+ )
+ SELECT
+ fe.stored_for_id AS "stored_for_id!",
+ fe.stored_for_auth_entity AS "stored_for_auth_entity!"
+ FROM foreign_entity fe
+ JOIN source_pairs s
+ ON s.stored_for_id = fe.stored_for_id
+ AND s.stored_for_auth_entity = fe.stored_for_auth_entity
+ WHERE fe.id = $1
+ "#,
+ foreign_entity_id,
+ source_ids,
+ source_auth_entities,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .filter_map(|row| {
+ AccessGrant::foreign_entity_auth(&row.stored_for_auth_entity).map(
+ |stored_for_auth_entity| AccessGrant::ForeignEntity {
+ stored_for_id: row.stored_for_id,
+ stored_for_auth_entity,
+ },
+ )
+ })
+ .collect())
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/project_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/project_access.rs
index 2677fc7e46..3d89aa486f 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/project_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/project_access.rs
@@ -3,7 +3,13 @@
#[cfg(test)]
mod test;
+#[cfg(feature = "explain_binary")]
+use crate::{
+ domain::models::AccessGrant, outbound::pg_access_repo::queries::list_entity_access_grants,
+};
use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};
+#[cfg(feature = "explain_binary")]
+use model_entity::EntityType;
use sqlx::PgPool;
use std::str::FromStr;
@@ -84,3 +90,67 @@ pub async fn get_project_access(
Ok(highest_level)
}
+
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(err, skip(pool, source_ids))]
+pub async fn explain_project_access(
+ pool: &PgPool,
+ project_id: &uuid::Uuid,
+ source_ids: &SourceIds,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let mut grants =
+ list_entity_access_grants(pool, project_id, EntityType::Project, source_ids).await?;
+ let project_id_str = project_id.to_string();
+
+ let public_levels = sqlx::query_scalar!(
+ r#"
+ SELECT
+ sp."linkShareAccessLevel" AS "access_level!: AccessLevel"
+ FROM "SharePermission" sp
+ WHERE sp."linkShare" = 'PUBLIC'
+ AND sp."linkShareAccessLevel" IS NOT NULL
+ AND sp.id IN (
+ SELECT "sharePermissionId" FROM "ProjectPermission" WHERE "projectId" = $1
+ )
+ "#,
+ &project_id_str
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(
+ public_levels
+ .into_iter()
+ .map(|access_level| AccessGrant::PublicLink { access_level }),
+ );
+
+ if source_ids.0.is_empty() {
+ return Ok(grants);
+ }
+
+ let team_rows = sqlx::query!(
+ r#"
+ SELECT
+ sp."linkShareAccessLevel" AS "access_level!: AccessLevel",
+ owner_team.team_id AS "owner_team_id!"
+ FROM "SharePermission" sp
+ JOIN "ProjectPermission" pp ON pp."sharePermissionId" = sp.id
+ JOIN "Project" p ON p.id = pp."projectId"
+ JOIN team_user owner_team
+ ON owner_team.user_id = p."userId"
+ AND owner_team.team_id::text = ANY($2)
+ WHERE pp."projectId" = $1
+ AND sp."linkShare" = 'TEAM'
+ AND sp."linkShareAccessLevel" IS NOT NULL
+ "#,
+ &project_id_str,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(team_rows.into_iter().map(|row| AccessGrant::TeamLink {
+ access_level: row.access_level,
+ owner_team_id: row.owner_team_id,
+ }));
+
+ Ok(grants)
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
index 2231c2ff1c..1b5e8ee9c0 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
@@ -4,7 +4,16 @@
mod test;
use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};
+#[cfg(feature = "explain_binary")]
+use crate::{
+ domain::models::{AccessGrant, TeamRole},
+ outbound::pg_access_repo::queries::list_entity_access_grants,
+};
+#[cfg(feature = "explain_binary")]
+use macro_user_id::user_id::MacroUserIdStr;
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+#[cfg(feature = "explain_binary")]
+use model_entity::EntityType;
use sqlx::PgPool;
use std::str::FromStr;
use uuid::Uuid;
@@ -259,3 +268,246 @@ pub async fn get_thread_access(
Ok([highest_level, crm_level].into_iter().flatten().max())
}
+
+#[cfg(feature = "explain_binary")]
+#[tracing::instrument(err, skip(pool, source_ids))]
+pub async fn explain_thread_access(
+ pool: &PgPool,
+ thread_id: &Uuid,
+ source_ids: &SourceIds,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let mut grants = Vec::new();
+ if let Some(user_id) = user_id {
+ grants.extend(explain_thread_inbox(pool, thread_id, user_id).await?);
+ grants.extend(explain_thread_crm(pool, thread_id, user_id).await?);
+ }
+
+ grants.extend(
+ list_entity_access_grants(pool, thread_id, EntityType::EmailThread, source_ids).await?,
+ );
+ grants.extend(explain_thread_link_shares(pool, thread_id, source_ids).await?);
+ if !source_ids.0.is_empty() {
+ grants.extend(explain_thread_containing_project(pool, thread_id, source_ids).await?);
+ }
+
+ Ok(grants)
+}
+
+#[cfg(feature = "explain_binary")]
+async fn explain_thread_inbox(
+ pool: &PgPool,
+ thread_id: &Uuid,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let user_id_str = user_id.as_ref();
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ l.macro_id AS "mailbox_owner!",
+ (l.macro_id = $2) AS "is_owner!"
+ FROM public.email_threads t
+ JOIN public.email_links l ON l.id = t.link_id
+ WHERE t.id = $1::uuid
+ AND (
+ l.macro_id = $2
+ OR EXISTS (
+ SELECT 1
+ FROM public.macro_user_links mul
+ WHERE mul.link_id = l.id
+ AND mul.primary_macro_id = $2
+ )
+ )
+ "#,
+ thread_id,
+ user_id_str
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ let Some(row) = row else {
+ return Ok(vec![]);
+ };
+
+ if row.is_owner {
+ Ok(vec![AccessGrant::InboxOwner])
+ } else {
+ let mailbox_owner = MacroUserIdStr::try_from(row.mailbox_owner)
+ .map_err(|error| sqlx::Error::Decode(error.into()))?;
+ Ok(vec![AccessGrant::InboxDelegate { mailbox_owner }])
+ }
+}
+
+#[cfg(feature = "explain_binary")]
+async fn explain_thread_link_shares(
+ pool: &PgPool,
+ thread_id: &Uuid,
+ source_ids: &SourceIds,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let thread_id_str = thread_id.to_string();
+ let mut grants = Vec::new();
+
+ let public_levels = sqlx::query_scalar!(
+ r#"
+ SELECT
+ "linkShareAccessLevel" AS "access_level!: AccessLevel"
+ FROM "SharePermission"
+ WHERE "linkShare" = 'PUBLIC'
+ AND "linkShareAccessLevel" IS NOT NULL
+ AND id IN (
+ SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $1
+ )
+ "#,
+ &thread_id_str
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(
+ public_levels
+ .into_iter()
+ .map(|access_level| AccessGrant::PublicLink { access_level }),
+ );
+
+ if source_ids.0.is_empty() {
+ return Ok(grants);
+ }
+
+ let team_rows = sqlx::query!(
+ r#"
+ SELECT
+ sp."linkShareAccessLevel" AS "access_level!: AccessLevel",
+ owner_tu.team_id AS "owner_team_id!"
+ FROM "SharePermission" sp
+ JOIN team_user owner_tu
+ ON owner_tu.team_id::text = ANY($2)
+ WHERE sp."linkShareAccessLevel" IS NOT NULL
+ AND sp."linkShare" = 'TEAM'
+ AND sp.id IN (
+ SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $1
+ )
+ AND EXISTS (
+ SELECT 1
+ FROM email_threads t
+ JOIN email_links l ON l.id = t.link_id
+ WHERE t.id = $3::uuid
+ AND owner_tu.user_id = l.macro_id
+ )
+ "#,
+ &thread_id_str,
+ &source_ids.0,
+ thread_id,
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(team_rows.into_iter().map(|row| AccessGrant::TeamLink {
+ access_level: row.access_level,
+ owner_team_id: row.owner_team_id,
+ }));
+
+ Ok(grants)
+}
+
+#[cfg(feature = "explain_binary")]
+async fn explain_thread_containing_project(
+ pool: &PgPool,
+ thread_id: &Uuid,
+ source_ids: &SourceIds,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT DISTINCT pea.entity_id::text AS "project_id!"
+ 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
+ "#,
+ thread_id,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| AccessGrant::ContainingProject {
+ project_id: row.project_id,
+ })
+ .collect())
+}
+
+#[cfg(feature = "explain_binary")]
+async fn explain_thread_crm(
+ pool: &PgPool,
+ thread_id: &Uuid,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Vec<AccessGrant>, sqlx::Error> {
+ let user_id_str = user_id.as_ref();
+ let rows = sqlx::query!(
+ r#"
+ WITH thread_owner AS (
+ SELECT el.macro_id
+ FROM email_threads t
+ JOIN email_links el ON el.id = t.link_id
+ WHERE t.id = $1::uuid
+ ),
+ shared_teams AS (
+ SELECT tcs.team_id, requester.team_role
+ FROM team_user requester
+ JOIN team_user owner_member ON owner_member.team_id = requester.team_id
+ JOIN thread_owner o ON o.macro_id = owner_member.user_id
+ JOIN team_crm_settings tcs ON tcs.team_id = requester.team_id
+ WHERE requester.user_id = $2
+ AND tcs.crm_enabled
+ ),
+ participants AS (
+ SELECT DISTINCT LOWER(ec.email_address) AS email
+ FROM email_messages m
+ JOIN email_contacts ec ON ec.id = m.from_contact_id
+ WHERE m.thread_id = $1::uuid
+ UNION
+ SELECT DISTINCT LOWER(ec.email_address)
+ FROM email_messages m
+ JOIN email_message_recipients r ON r.message_id = m.id
+ JOIN email_contacts ec ON ec.id = r.contact_id
+ WHERE m.thread_id = $1::uuid
+ )
+ SELECT st.team_id, st.team_role AS "team_role!: TeamRole"
+ FROM shared_teams st
+ WHERE EXISTS (
+ SELECT 1
+ FROM participants p
+ WHERE split_part(p.email, '@', 2) <> split_part(LOWER($2), '@', 2)
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM participants p
+ JOIN crm_contacts ct ON ct.email = p.email
+ JOIN crm_companies c ON c.id = ct.company_id
+ WHERE c.team_id = st.team_id
+ AND split_part(p.email, '@', 2) <> split_part(LOWER($2), '@', 2)
+ AND (
+ NOT c.email_sync
+ OR (
+ (ct.hidden OR c.hidden)
+ AND st.team_role = 'member'
+ )
+ )
+ )
+ "#,
+ thread_id,
+ user_id_str
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| AccessGrant::CrmTeam {
+ team_id: row.team_id,
+ team_role: row.team_role,
+ access_level: AccessLevel::Comment,
+ })
+ .collect())
+}
diff --git a/crates/entity_access/src/outbound/pg_explain_access_repo.rs b/crates/entity_access/src/outbound/pg_explain_access_repo.rs
new file mode 100644
index 0000000000..429444d3ca
--- /dev/null
+++ b/crates/entity_access/src/outbound/pg_explain_access_repo.rs
@@ -0,0 +1,262 @@
+use crate::domain::{
+ models::{AccessError, AccessGrant, EntityType, ForeignEntityAuthEntity, UserTeamInfo},
+ ports::ExplainAccessRepository,
+};
+use crate::outbound::pg_access_repo::queries;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// PostgreSQL-backed implementation of [`ExplainAccessRepository`].
+#[derive(Clone)]
+pub struct PgExplainAccessRepository {
+ pool: PgPool,
+}
+
+impl PgExplainAccessRepository {
+ /// Create a new explain repository.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+fn foreign_entity_source_pairs(
+ user_id: &MacroUserId<Lowercase<'_>>,
+ user_team: Option<UserTeamInfo>,
+) -> (Vec<String>, Vec<String>) {
+ let mut source_ids = vec![user_id.as_ref().to_string()];
+ let mut source_auth_entities = vec![ForeignEntityAuthEntity::User.as_str().to_string()];
+
+ if let Some(user_team) = user_team {
+ source_ids.push(user_team.team_id.to_string());
+ source_auth_entities.push(ForeignEntityAuthEntity::Team.as_str().to_string());
+ }
+
+ (source_ids, source_auth_entities)
+}
+
+fn parse_uuid(entity_id: &str, message: &'static str) -> Result<Uuid, AccessError> {
+ Uuid::parse_str(entity_id).map_err(|_| AccessError::BadRequest(message))
+}
+
+impl ExplainAccessRepository for PgExplainAccessRepository {
+ #[tracing::instrument(err, skip(self))]
+ async fn list_access_grants(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<Vec<AccessGrant>, AccessError> {
+ match entity_type {
+ EntityType::Document => {
+ let document_id = parse_uuid(entity_id, "Invalid document ID format")?;
+ let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(queries::document_access::explain_document_access(
+ &self.pool,
+ &document_id,
+ &source_ids,
+ Some(user_id),
+ )
+ .await?)
+ }
+ EntityType::Chat => {
+ let chat_id = parse_uuid(entity_id, "Invalid chat ID format")?;
+ let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(
+ queries::chat_access::explain_chat_access(&self.pool, &chat_id, &source_ids)
+ .await?,
+ )
+ }
+ EntityType::Project => {
+ let project_id = parse_uuid(entity_id, "Invalid project ID format")?;
+ let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(queries::project_access::explain_project_access(
+ &self.pool,
+ &project_id,
+ &source_ids,
+ )
+ .await?)
+ }
+ EntityType::EmailThread => {
+ let thread_id = parse_uuid(entity_id, "Invalid thread ID format")?;
+ let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(queries::thread_access::explain_thread_access(
+ &self.pool,
+ &thread_id,
+ &source_ids,
+ Some(user_id),
+ )
+ .await?)
+ }
+ EntityType::Call => {
+ let call_id = parse_uuid(entity_id, "Invalid call ID format")?;
+ let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(
+ queries::call_access::explain_call_access(&self.pool, &call_id, &source_ids)
+ .await?,
+ )
+ }
+ EntityType::AgentSession => {
+ let session_id = parse_uuid(entity_id, "Invalid agent session ID format")?;
+ let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(queries::agent_session_access::explain_agent_session_access(
+ &self.pool,
+ &session_id,
+ &source_ids,
+ )
+ .await?)
+ }
+ EntityType::Channel => {
+ let channel_id = parse_uuid(entity_id, "Invalid channel ID format")?;
+ Ok(queries::channel_role::explain_channel_access(
+ &self.pool,
+ &channel_id,
+ user_id.as_ref(),
+ )
+ .await?)
+ }
+ EntityType::CrmCompany => {
+ let company_id = parse_uuid(entity_id, "Invalid CRM company ID format")?;
+ Ok(queries::crm_company_access::get_crm_company_access(
+ &self.pool,
+ &company_id,
+ user_id,
+ )
+ .await?
+ .map(|access| AccessGrant::CrmTeam {
+ team_id: access.team_id,
+ team_role: access.team_role,
+ access_level: access.access_level,
+ })
+ .into_iter()
+ .collect())
+ }
+ EntityType::CrmContact => {
+ let contact_id = parse_uuid(entity_id, "Invalid CRM contact ID format")?;
+ Ok(queries::crm_contact_access::get_crm_contact_access(
+ &self.pool,
+ &contact_id,
+ user_id,
+ )
+ .await?
+ .map(|access| AccessGrant::CrmTeam {
+ team_id: access.team_id,
+ team_role: access.team_role,
+ access_level: access.access_level,
+ })
+ .into_iter()
+ .collect())
+ }
+ EntityType::Team => {
+ let team_id = parse_uuid(entity_id, "Invalid team ID format")?;
+ Ok(queries::team_access::get_user_team(&self.pool, user_id)
+ .await?
+ .filter(|team| team.team_id == team_id)
+ .map(|team| AccessGrant::TeamMembership { role: team.role })
+ .into_iter()
+ .collect())
+ }
+ EntityType::Reminder => {
+ let reminder_id = parse_uuid(entity_id, "Invalid reminder ID format")?;
+ explain_reminder_access(&self.pool, &reminder_id, user_id).await
+ }
+ EntityType::CalendarEvent => {
+ let event_id = parse_uuid(entity_id, "Invalid calendar event ID format")?;
+ explain_calendar_event_access(&self.pool, &event_id, user_id).await
+ }
+ EntityType::ForeignEntity => {
+ let foreign_entity_id = parse_uuid(entity_id, "Invalid foreign entity ID format")?;
+ let user_team = queries::team_access::get_user_team(&self.pool, user_id).await?;
+ let (source_ids, source_auth_entities) =
+ foreign_entity_source_pairs(user_id, user_team);
+ Ok(queries::foreign_entity_access::list_foreign_entity_grants(
+ &self.pool,
+ &foreign_entity_id,
+ &source_ids,
+ &source_auth_entities,
+ )
+ .await?)
+ }
+ EntityType::StaticFile => Ok(vec![AccessGrant::StaticFileAlwaysView]),
+ EntityType::User | EntityType::ChannelMessage | EntityType::Skill => Ok(vec![]),
+ }
+ }
+}
+
+async fn explain_reminder_access(
+ pool: &PgPool,
+ reminder_id: &Uuid,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Vec<AccessGrant>, AccessError> {
+ let owns = sqlx::query_scalar!(
+ r#"SELECT EXISTS (
+ SELECT 1 FROM reminder WHERE id = $1 AND user_id = $2
+ ) AS "owns!""#,
+ reminder_id,
+ user_id.as_ref(),
+ )
+ .fetch_one(pool)
+ .await?;
+
+ Ok(owns
+ .then_some(AccessGrant::ReminderOwner)
+ .into_iter()
+ .collect())
+}
+
+async fn explain_calendar_event_access(
+ pool: &PgPool,
+ event_id: &Uuid,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Vec<AccessGrant>, AccessError> {
+ let is_owner = sqlx::query_scalar!(
+ r#"
+ SELECT event.owner_id = $2 AS "is_owner!"
+ FROM calendar_events event
+ WHERE event.id = $1
+ AND (
+ event.owner_id = $2
+ OR EXISTS (
+ SELECT 1
+ FROM macro_user_links link
+ WHERE link.link_id = event.source_link_id
+ AND link.primary_macro_id = $2
+ )
+ )
+ "#,
+ event_id,
+ user_id.as_ref(),
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(is_owner
+ .map(|is_owner| {
+ if is_owner {
+ AccessGrant::CalendarOwner
+ } else {
+ AccessGrant::CalendarInboxDelegate
+ }
+ })
+ .into_iter()
+ .collect())
+}
+
+fn anyhow_access_error(e: anyhow::Error) -> AccessError {
+ match e.downcast::<sqlx::Error>() {
+ Ok(sqlx_error) => AccessError::from(sqlx_error),
+ Err(other) => AccessError::Internal(rootcause::report!(other).into_dynamic()),
+ }
+}
diff --git a/crates/models_entity_access_management/src/lib.rs b/crates/models_entity_access_management/src/lib.rs
index 68db472374..2c86fb38f9 100644
--- a/crates/models_entity_access_management/src/lib.rs
+++ b/crates/models_entity_access_management/src/lib.rs
@@ -3,7 +3,8 @@
//! Contains common models for entity_access_management that need to be shared across multiple crates.
/// Entity access source type
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "db", derive(sqlx::Type))]
#[cfg_attr(
feature = "db",