Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(bot): update EntityAccessReceipt to support bot authorization access (#4804)
Will Hutchinsonb5efffaf58f2
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex c8709cd951..4a899195b5 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -819,6 +819,7 @@"crates/ai_toolset","crates/ai_usage","crates/attachment",+ "crates/bot_id","crates/chat","crates/cowlike","crates/document_sub_type",@@ -1001,6 +1002,7 @@"crates/ai_toolset","crates/ai_usage","crates/attachment",+ "crates/bot_id","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -2414,6 +2416,7 @@"crates/ai_toolset","crates/ai_usage","crates/attachment",+ "crates/bot_id","crates/cowlike","crates/document_sub_type","crates/entity_access",@@ -2460,6 +2463,7 @@"crates/ai_toolset","crates/ai_usage","crates/attachment",+ "crates/bot_id","crates/cowlike","crates/document_sub_type","crates/entity_access",@@ -2488,6 +2492,7 @@"crates/ai_toolset","crates/ai_usage","crates/attachment",+ "crates/bot_id","crates/cowlike","crates/document_sub_type","crates/entity_access",diff --git a/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.json b/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.jsonindex d4a1902ef1..0c0204cf7b 100644--- a/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.json+++ b/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.json@@ -28,7 +28,8 @@"THREAD","USER","COMPANY",- "TASK"+ "TASK",+ "CALL_RECORD"]}}@@ -65,7 +66,8 @@"THREAD","USER","COMPANY",- "TASK"+ "TASK",+ "CALL_RECORD"]}}diff --git a/.sqlx/query-54a58d0c472902a9860bdbc30efd2b732654c5b3aa505e44961e1308ecf76cc1.json b/.sqlx/query-54a58d0c472902a9860bdbc30efd2b732654c5b3aa505e44961e1308ecf76cc1.jsonnew file mode 100644index 0000000000..f402a46a6e--- /dev/null+++ b/.sqlx/query-54a58d0c472902a9860bdbc30efd2b732654c5b3aa505e44961e1308ecf76cc1.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH active_bot AS (\n SELECT team_id\n FROM bots\n WHERE id = $2 AND deleted_at IS NULL\n )\n SELECT cp.channel_id::text\n FROM active_bot\n JOIN comms_channel_participants cp\n ON cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT team_id::text\n FROM active_bot\n WHERE team_id IS NOT NULL\n UNION ALL\n SELECT $1\n FROM active_bot\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "channel_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "54a58d0c472902a9860bdbc30efd2b732654c5b3aa505e44961e1308ecf76cc1"+}diff --git a/.sqlx/query-5a00a889e19a6d8d323bef2edf0764f7ad93f1478369b70ac9243ab211745d21.json b/.sqlx/query-5a00a889e19a6d8d323bef2edf0764f7ad93f1478369b70ac9243ab211745d21.jsonnew file mode 100644index 0000000000..302bf6af2e--- /dev/null+++ b/.sqlx/query-5a00a889e19a6d8d323bef2edf0764f7ad93f1478369b70ac9243ab211745d21.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT cp.role::text as \"role?\"\n FROM comms_channels c\n LEFT JOIN comms_channel_participants cp\n ON cp.channel_id = c.id\n AND cp.user_id = $2\n AND cp.left_at IS NULL\n AND EXISTS (\n SELECT 1\n FROM bots b\n WHERE b.id = $3 AND b.deleted_at IS NULL\n )\n WHERE c.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "role?",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "5a00a889e19a6d8d323bef2edf0764f7ad93f1478369b70ac9243ab211745d21"+}diff --git a/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json b/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.jsonindex 5cb39eefda..de71e6fb4f 100644--- a/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json+++ b/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json@@ -28,7 +28,8 @@"THREAD","USER","COMPANY",- "TASK"+ "TASK",+ "CALL_RECORD"]}}@@ -66,7 +67,8 @@"THREAD","USER","COMPANY",- "TASK"+ "TASK",+ "CALL_RECORD"]}}diff --git a/Cargo.lock b/Cargo.lockindex 2acb30fd59..0287f6c9a9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5070,6 +5070,7 @@ version = "0.1.0"dependencies = ["anyhow","axum",+ "bot_id","cached","cool_asserts","macro_db_migrator",diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rsindex 6185cb8735..d92ed7f1a1 100644--- a/crates/bots/src/inbound/axum_router/tests.rs+++ b/crates/bots/src/inbound/axum_router/tests.rs@@ -11,7 +11,7 @@ use axum::{};use entity_access::domain::{models::{- AccessError, AccessLevel, CallChannelInfo, EntityPermission, EntityType,+ AccessError, AccessLevel, BotId, CallChannelInfo, EntityPermission, EntityType,ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,},ports::EntityAccessService,@@ -207,6 +207,15 @@ impl EntityAccessService for TestAccessService {unimplemented!()}+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ unimplemented!()+ }+async fn get_access_level(&self,_user_id: Option<&MacroUserId<Lowercase<'_>>>,diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rsindex 4963c5f936..3e398d8806 100644--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs@@ -1,6 +1,6 @@use super::*;use crate::domain::models::{- AuthenticatedBot, Bot, BotChannel, BotId, BotKind, BotOwner, BotToken, CreateBotRequest,+ AuthenticatedBot, Bot, BotChannel, BotKind, BotOwner, BotToken, CreateBotRequest,CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,};use axum::{@@ -11,7 +11,7 @@ use axum::{use channels::domain::models::PostMessageResponse;use entity_access::domain::{models::{- AccessError, AccessLevel, CallChannelInfo, EntityPermission, EntityType,+ AccessError, AccessLevel, BotId, CallChannelInfo, EntityPermission, EntityType,ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,},ports::EntityAccessService,@@ -264,6 +264,15 @@ impl EntityAccessService for TestAccessService {unimplemented!()}+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ unimplemented!()+ }+async fn get_access_level(&self,_user_id: Option<&MacroUserId<Lowercase<'_>>>,diff --git a/crates/channels/src/inbound/axum_router.rs b/crates/channels/src/inbound/axum_router.rsindex e8e9c7b79f..9373f20a65 100644--- a/crates/channels/src/inbound/axum_router.rs+++ b/crates/channels/src/inbound/axum_router.rs@@ -121,6 +121,7 @@ fn actor_from_receipt<T: RequiredPermission>() -> Result<Sender, ChannelsHandlerErr> {match receipt.auth() {EntityAccessAuth::Authenticated(user_id) => Ok(Sender::new_from_user(user_id.clone())),+ EntityAccessAuth::Bot(bot_id) => Ok(Sender::new_from_bot(bot_id.bot_id())),EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => Err(ChannelsHandlerErr::BadRequest("authenticated actor required"),),diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rsindex ad5b1b0ef3..52837e669b 100644--- a/crates/channels/src/inbound/axum_router/test.rs+++ b/crates/channels/src/inbound/axum_router/test.rs@@ -16,8 +16,9 @@ use axum::{};use entity_access::domain::{models::{- AccessError, AccessLevel, EntityAccessReceipt, EntityPermission, EntityType,- ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,+ AccessError, AccessLevel, BotId, Entity, EntityAccessReceipt, EntityPermission, EntityType,+ MemberParticipantRole, ParticipantRole as EntityParticipantRole, RequiredPermission,+ UserTeamInfo,},ports::EntityAccessService,};@@ -91,6 +92,15 @@ impl EntityAccessService for TestAccessService {Err(self.access_err())}+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(self.access_err())+ }+async fn get_access_level(&self,_user_id: Option<&MacroUserId<Lowercase<'_>>>,@@ -182,6 +192,26 @@ impl EntityAccessService for TestAccessService {}}+#[test]+fn bot_actor_from_receipt_uses_canonical_principal() {+ let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));+ let receipt = EntityAccessReceipt::<MemberParticipantRole>::try_new_bot(+ bot_id.into_storage_id(),+ Entity {+ entity_id: Uuid::new_v4().to_string(),+ entity_type: EntityType::Channel,+ },+ EntityPermission::ChannelRole {+ role: EntityParticipantRole::Member,+ },+ )+ .unwrap();++ let sender = actor_from_receipt(&receipt).unwrap();++ assert_eq!(sender.as_ref(), bot_id.into_storage_id().as_ref());+}+// --- Mock services (business logic only, no auth concerns) ---struct MockService;diff --git a/crates/chat/src/inbound/test.rs b/crates/chat/src/inbound/test.rsindex 79b147dd6d..f8d44c0cf0 100644--- a/crates/chat/src/inbound/test.rs+++ b/crates/chat/src/inbound/test.rs@@ -16,8 +16,8 @@ use crate::domain::ports::ChatService;use crate::inbound::http::router::{ChatRouterState, chat_id_router};use ai_toolset::tool_object::UserToolResponse;use entity_access::domain::models::{- AccessError, AccessLevel, EditAccessLevel, EntityAccessReceipt, EntityPermission, EntityType,- OwnerAccessLevel, UserTeamInfo, ViewAccessLevel,+ AccessError, AccessLevel, BotId, EditAccessLevel, EntityAccessReceipt, EntityPermission,+ EntityType, OwnerAccessLevel, UserTeamInfo, ViewAccessLevel,};use entity_access::domain::ports::EntityAccessService;use macro_user_id::lowercased::Lowercase;@@ -360,6 +360,18 @@ impl EntityAccessService for MockAccessService {unreachable!("not used by ChatAccessLevelExtractor")}+ async fn generate_bot_entity_access_receipt<+ T: entity_access::domain::models::RequiredPermission,+ >(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> std::result::Result<entity_access::domain::models::EntityAccessReceipt<T>, AccessError>+ {+ unreachable!("not used by ChatAccessLevelExtractor")+ }+async fn get_access_level(&self,_user_id: Option<&MacroUserId<Lowercase<'_>>>,diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex 9537515cca..aeff02f5a4 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -6,7 +6,7 @@ use email::domain::models::{UpsertEmailFilterInput,};use entity_access::domain::models::{- AccessError, AccessLevel, CallChannelInfo, EditAccessLevel, EntityAccessReceipt,+ AccessError, AccessLevel, BotId, CallChannelInfo, EditAccessLevel, EntityAccessReceipt,EntityPermission, EntityType, RequiredPermission, UserTeamInfo, ViewAccessLevel,};use graphql_common::GraphqlSoupRequestParts;@@ -165,6 +165,15 @@ impl EntityAccessService for CountingEntityAccessService {Err(AccessError::Internal)}+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(AccessError::Internal)+ }+async fn get_access_level(&self,_user_id: Option<&MacroUserId<Lowercase<'_>>>,diff --git a/crates/connection/src/domain/service.rs b/crates/connection/src/domain/service.rsindex 901217c23e..d374ffe172 100644--- a/crates/connection/src/domain/service.rs+++ b/crates/connection/src/domain/service.rs@@ -62,7 +62,8 @@ impl<E: EntityAccessService, Cgw: ConnectionGateway> ConnectionService}).collect::<Vec<MacroUserId<Lowercase<'a>>>>()}- entity_access::domain::models::EntityAccessAuth::Unauthenticated+ entity_access::domain::models::EntityAccessAuth::Bot(_)+ | entity_access::domain::models::EntityAccessAuth::Unauthenticated| entity_access::domain::models::EntityAccessAuth::Internal => {users.into_iter().map(|s| s.0.to_owned()).collect()}diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex bdd62fccf5..d67c1af44f 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -138,7 +138,9 @@ fn pending_content_for_file_type(file_type: Option<FileType>) -> DocumentContentfn event_actor_user_id(auth: &EntityAccessAuth) -> Option<MacroUserIdStr<'static>> {match auth {EntityAccessAuth::Authenticated(user_id) => Some(user_id.clone()),- EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => None,+ EntityAccessAuth::Bot(_)+ | EntityAccessAuth::Unauthenticated+ | EntityAccessAuth::Internal => None,}}@@ -621,7 +623,9 @@ impl<.get_user_view_location(user_id.as_ref(), &document_id).await.map_err(|e| DocumentError::Internal(e.into()))?,- EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => None,+ EntityAccessAuth::Bot(_)+ | EntityAccessAuth::Unauthenticated+ | EntityAccessAuth::Internal => None,};let access_level = match entity_access_receipt.entity_permission() {@@ -848,9 +852,9 @@ impl<context.team_task_id,)}- EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => {- ("macro".to_string(), None, None)- }+ EntityAccessAuth::Bot(_)+ | EntityAccessAuth::Unauthenticated+ | EntityAccessAuth::Internal => ("macro".to_string(), None, None),};let branch_name = build_task_branch_name(@@ -905,6 +909,7 @@ impl<source_ids.extend(team_ids.into_iter().map(SourceId::team));Some(source_ids)}+ EntityAccessAuth::Bot(_) => Some(Vec::new()),EntityAccessAuth::Unauthenticated => Some(Vec::new()),EntityAccessAuth::Internal => None,};diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rsindex 90f3ac9f71..d36331d037 100644--- a/crates/documents/src/domain/service/tests.rs+++ b/crates/documents/src/domain/service/tests.rs@@ -83,6 +83,20 @@ fn internal_receipt(document_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {EntityAccessReceipt::dangerously_assert_internal_user(document_id, EntityType::Document)}+fn bot_id() -> entity_access::domain::models::BotId {+ entity_access::domain::models::BotId::new_from_uuid(uuid::uuid!(+ "00000000-0000-0000-0000-000000000123"+ ))+}++fn bot_receipt(document_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {+ EntityAccessReceipt::dangerously_assert_bot(+ bot_id().into_storage_id(),+ document_id,+ EntityType::Document,+ )+}+struct TestUploadUrlPort;impl PresignedUploadUrlPort for TestUploadUrlPort {@@ -583,6 +597,78 @@ fn assert_shallow_pull_request_with_foreign_entity_id();}+#[tokio::test]+async fn bot_document_has_no_saved_user_view_location() {+ let mut repo = make_mock_repo();+ let metadata = make_test_metadata();++ repo.expect_get_document_metadata()+ .return_once(move |_| Box::pin(std::future::ready(Ok(metadata))));+ repo.expect_get_user_view_location().times(0);+ repo.expect_get_persisted_document_content()+ .return_once(|_| {+ Box::pin(std::future::ready(Ok(Some(DocumentContent::ready(+ DocumentContentLocation::ObjectStorage,+ )))))+ });+ repo.expect_get_team_task_metadata()+ .return_once(|_| Box::pin(std::future::ready(Ok(None))));++ let response = make_test_service(repo)+ .get_document(bot_receipt("doc-1"))+ .await+ .unwrap();++ assert_eq!(response.view_location, None);+}++#[tokio::test]+async fn bot_lifecycle_event_has_no_actor_user_id() {+ let mut repo = make_mock_repo();+ repo.expect_soft_delete_document()+ .withf(|id| id == "doc-1")+ .return_once(|_| Box::pin(std::future::ready(Ok(()))));++ let (service, event_broker) = make_test_service_with_event_broker(repo);+ let receipt = EntityAccessReceipt::<OwnerAccessLevel>::dangerously_assert_bot(+ bot_id().into_storage_id(),+ "doc-1",+ EntityType::Document,+ );++ service.delete_document(receipt, None).await.unwrap();++ let published = event_broker.published();+ let published = published.lock().unwrap();+ assert_eq!(published.len(), 1);+ assert_eq!(+ published[0].payload["metadata"]["actor_user_id"],+ serde_json::Value::Null+ );+}++#[tokio::test]+async fn bot_task_branch_uses_macro_fallback() {+ let document_id = "00000000-0000-0000-0000-000000000124";+ let service = make_test_service(make_mock_repo());++ let response = service+ .get_task_branch_name(bot_receipt(document_id), "Fix bot auth".to_string())+ .await+ .unwrap();++ assert_eq!(+ response.branch_name,+ build_task_branch_name(+ "macro",+ None,+ None,+ &short_id_for_entity_id(document_id).unwrap(),+ "Fix bot auth",+ )+ );+}+#[tokio::test]async fn test_get_document_happy_path() {let mut repo = make_mock_repo();@@ -639,6 +725,50 @@ async fn test_soft_delete_document() {assert!(result.is_ok());}+#[tokio::test]+async fn bot_pull_request_does_not_hydrate_foreign_entity() {+ let document_id = "00000000-0000-0000-0000-000000000125";+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();+ let foreign_entity_id = uuid::uuid!("00000000-0000-0000-0000-000000000126");+ let mut repo = make_mock_repo();++ repo.expect_get_task_github_pull_request_keys()+ .withf(move |task_short_id| task_short_id == expected_short_id)+ .return_once(|_| {+ Box::pin(std::future::ready(Ok(vec![+ "macro/repo/pull/17".to_string(),+ ])))+ });++ let service = make_test_service_with_foreign_entities(+ repo,+ vec![make_foreign_entity(+ foreign_entity_id,+ "macro/repo/pull/17",+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,+ bot_id().into_storage_id().as_ref(),+ "bot",+ )],+ );++ let response = service+ .get_task_github_pull_requests(+ bot_receipt(document_id),+ &task_document_context(document_id),+ )+ .await+ .unwrap();++ assert_eq!(response.pull_requests.len(), 1);+ assert_raw_pull_request(+ &response.pull_requests[0],+ "macro/repo/pull/17",+ "macro",+ "repo",+ 17,+ );+}+#[tokio::test]async fn test_get_task_github_pull_requests_returns_raw_refs_for_authenticated_user() {let document_id = "00000000-0000-0000-0000-000000000001";diff --git a/crates/entity_access/Cargo.toml b/crates/entity_access/Cargo.tomlindex e6b7e18fdf..6d1122e64a 100644--- a/crates/entity_access/Cargo.toml+++ b/crates/entity_access/Cargo.toml@@ -27,6 +27,7 @@ tracing = { workspace = true }uuid = { workspace = true }# Domain models (always included)+bot_id = { path = "../bot_id" }macro_user_id = { path = "../macro_user_id" }model-entity = { path = "../model-entity" }models_permissions = { path = "../models_permissions" }diff --git a/crates/entity_access/src/domain/models.rs b/crates/entity_access/src/domain/models.rsindex 4830e4c584..8f72494a60 100644--- a/crates/entity_access/src/domain/models.rs+++ b/crates/entity_access/src/domain/models.rs@@ -1,11 +1,15 @@//! Domain models for entity access.+#[cfg(test)]+mod test;+use std::marker::PhantomData;use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};use uuid::Uuid;+pub use bot_id::{BotId, BotIdStr};pub use model_entity::EntityType;pub use models_permissions::share_permission::access_level::AccessLevel;pub use models_permissions::share_permission::access_level::{@@ -258,6 +262,8 @@ pub struct Entity {pub enum EntityAccessAuth {/// The user is authenticatedAuthenticated(MacroUserIdStr<'static>),+ /// A bot is authenticated.+ Bot(BotIdStr<'static>),/// The user is unauthenticatedUnauthenticated,/// Internally authenticated@@ -313,11 +319,32 @@ impl<T: RequiredPermission> EntityAccessReceipt<T> {)}- /// get the authenticated user or error+ /// Creates an access receipt for an authenticated bot after validating the provided permission.+ pub fn try_new_bot(+ bot_id: BotIdStr<'static>,+ entity: Entity,+ entity_permission: EntityPermission,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Self::try_new(EntityAccessAuth::Bot(bot_id), entity, entity_permission)+ }++ /// Get the authenticated user or return an authorization error.pub fn get_authenticated_user(&self) -> Result<&MacroUserIdStr<'static>, AccessError> {match &self.auth {EntityAccessAuth::Authenticated(user) => Ok(user),- _ => Err(AccessError::Unauthorized),+ EntityAccessAuth::Bot(_)+ | EntityAccessAuth::Unauthenticated+ | EntityAccessAuth::Internal => Err(AccessError::Unauthorized),+ }+ }++ /// Get the authenticated bot or return an authorization error.+ pub fn get_authenticated_bot(&self) -> Result<&BotIdStr<'static>, AccessError> {+ match &self.auth {+ EntityAccessAuth::Bot(bot_id) => Ok(bot_id),+ EntityAccessAuth::Authenticated(_)+ | EntityAccessAuth::Unauthenticated+ | EntityAccessAuth::Internal => Err(AccessError::Unauthorized),}}@@ -380,6 +407,30 @@ impl<T: RequiredPermission> EntityAccessReceipt<T> {_marker: PhantomData,}}++ /// Dangerously generates an `EntityAccessReceipt` for an authenticated bot+ /// without performing the underlying access check.+ ///+ /// **NOTE** This is intended for tests. It **DOES NOT** assert the+ /// existence of the item or that the bot actually has the required+ /// permission.+ pub fn dangerously_assert_bot(+ bot_id: BotIdStr<'static>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> EntityAccessReceipt<T> {+ EntityAccessReceipt {+ auth: EntityAccessAuth::Bot(bot_id),+ entity: Entity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ entity_permission: EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner,+ },+ _marker: PhantomData,+ }+ }}/// Information about a call's channel association and share permission.diff --git a/crates/entity_access/src/domain/models/test.rs b/crates/entity_access/src/domain/models/test.rsnew file mode 100644index 0000000000..aecc260bfa--- /dev/null+++ b/crates/entity_access/src/domain/models/test.rs@@ -0,0 +1,77 @@+use super::*;++fn bot_id() -> BotId {+ BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"))+}++fn document() -> Entity {+ Entity {+ entity_id: "document-1".to_string(),+ entity_type: EntityType::Document,+ }+}++#[test]+fn bot_auth_serializes_as_canonical_storage_principal() {+ let serialized =+ serde_json::to_value(EntityAccessAuth::Bot(bot_id().into_storage_id())).unwrap();++ assert_eq!(+ serialized,+ serde_json::json!("bot|00000000-0000-0000-0000-000000000123")+ );+}++#[test]+fn try_new_bot_enforces_required_permission() {+ let result = EntityAccessReceipt::<EditAccessLevel>::try_new_bot(+ bot_id().into_storage_id(),+ document(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ );++ assert!(matches!(result, Err(AccessError::Unauthorized)));+}++#[test]+fn bot_receipt_returns_bot_and_rejects_authenticated_user() {+ let receipt = EntityAccessReceipt::<ViewAccessLevel>::try_new_bot(+ bot_id().into_storage_id(),+ document(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ )+ .unwrap();++ assert_eq!(+ receipt.get_authenticated_bot().unwrap(),+ &bot_id().into_storage_id()+ );+ assert!(matches!(+ receipt.get_authenticated_user(),+ Err(AccessError::Unauthorized)+ ));+}++#[test]+fn dangerously_assert_bot_creates_owner_level_test_receipt() {+ let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_bot(+ bot_id().into_storage_id(),+ "document-1",+ EntityType::Document,+ );++ assert_eq!(+ receipt.get_authenticated_bot().unwrap(),+ &bot_id().into_storage_id()+ );+ assert!(matches!(+ receipt.entity_permission(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner+ }+ ));+}diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rsindex 728240b11f..aebee8229d 100644--- a/crates/entity_access/src/domain/ports.rs+++ b/crates/entity_access/src/domain/ports.rs@@ -4,7 +4,7 @@use super::models::EntityType;use crate::domain::models::{- AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, CrmEntityAccess,+ AccessError, AccessLevel, BotId, CallChannelInfo, ChannelRoleResult, CrmEntityAccess,EntityAccessReceipt, EntityPermission, RequiredPermission, UserTeamInfo,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};@@ -51,6 +51,29 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {user_id: Option<&MacroUserId<Lowercase<'_>>>,) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;+ /// Get the highest access level a bot has for an entity resolved through+ /// `entity_access` source IDs (document, chat, project, email thread, or call).+ ///+ /// A bot's sources are the channels it actively participates in (using its+ /// canonical `bot|<uuid>` principal), its owning team when team-scoped, and+ /// the bot principal itself.+ fn get_bot_entity_access(+ &self,+ bot_id: BotId,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;++ /// Get the role a bot explicitly holds in a channel.+ ///+ /// Public and organization channels do not implicitly admit bots; an active+ /// participant row for the bot's canonical principal is required.+ fn get_bot_channel_role(+ &self,+ channel_id: &Uuid,+ bot_id: BotId,+ ) -> impl Future<Output = Result<ChannelRoleResult, AccessError>> + Send;+/// Check whether a user has access to a foreign entity.////// Foreign entity access is boolean because it only maps to [`AccessLevel::View`]@@ -169,6 +192,22 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {entity_type: EntityType,) -> impl Future<Output = Result<EntityAccessReceipt<T>, AccessError>> + Send;+ /// Generates an [`EntityAccessReceipt<T>`] for an authenticated bot.+ ///+ /// Document, chat, project, email-thread, and call permissions are resolved+ /// from the bot's entity-access sources. Channel permissions require an+ /// explicit active participant role; public and organization channels do+ /// not implicitly admit bots. All other entity types are unsupported.+ ///+ /// The type parameter `T` specifies the minimum permission required.+ /// Returns an error if the bot does not satisfy that requirement.+ fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ bot_id: BotId,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<EntityAccessReceipt<T>, AccessError>> + Send;+/// Get the access level a user has for an entity.////// Returns `None` if the user has no access to the entity.@@ -288,6 +327,15 @@ impl EntityAccessService for NoOpEntityAccessService {Err(AccessError::Internal)}+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(AccessError::Internal)+ }+async fn get_access_level(&self,_user_id: Option<&MacroUserId<Lowercase<'_>>>,diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rsindex 66381a7f7a..35f3de91a6 100644--- a/crates/entity_access/src/domain/service.rs+++ b/crates/entity_access/src/domain/service.rs@@ -5,9 +5,9 @@ use std::str::FromStr;use crate::domain::{models::{- AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, CrmEntityAccess, Entity,- EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission,- UserTeamInfo,+ AccessError, AccessLevel, BotId, CallChannelInfo, ChannelRoleResult, CrmEntityAccess,+ Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,+ RequiredPermission, UserTeamInfo,},ports::{AccessRepository, EntityAccessService},};@@ -163,6 +163,45 @@ where})}+ #[tracing::instrument(err, skip(self))]+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ bot_id: BotId,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ let entity_permission = match entity_type {+ EntityType::Document+ | EntityType::Chat+ | EntityType::Project+ | EntityType::EmailThread+ | EntityType::Call => {+ let access_level = self+ .repo+ .get_bot_entity_access(bot_id, entity_id, entity_type)+ .await?+ .ok_or(AccessError::Unauthorized)?;+ EntityPermission::AccessLevel { access_level }+ }+ EntityType::Channel => {+ let channel_id = Uuid::from_str(entity_id)+ .map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;+ let result = self.repo.get_bot_channel_role(&channel_id, bot_id).await?;+ channel_role_result_to_permission(result)?+ }+ _ => return Err(AccessError::BadRequest("Unsupported bot entity type")),+ };++ EntityAccessReceipt::try_new_bot(+ bot_id.into_storage_id(),+ Entity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ entity_permission,+ )+ }+#[tracing::instrument(err, skip(self))]async fn get_access_level(&self,diff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rsindex a0a7f74ef4..706b1f9516 100644--- a/crates/entity_access/src/domain/service/test.rs+++ b/crates/entity_access/src/domain/service/test.rs@@ -3,12 +3,16 @@#[allow(unused_imports)]use super::*;use crate::domain::models::{- AdminParticipantRole, CallChannelInfo, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,- MemberParticipantRole, OwnerParticipantRole, ParticipantRole, UserTeamInfo, ViewAccessLevel,+ AdminParticipantRole, BotId, CallChannelInfo, CommentAccessLevel, EditAccessLevel,+ EntityAccessAuth, MemberParticipantRole, OwnerParticipantRole, ParticipantRole, UserTeamInfo,+ ViewAccessLevel,};use macro_user_id::user_id::MacroUserIdStr;use models_permissions::share_permission::access_level::OwnerAccessLevel;-use std::sync::Arc;+use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+};use tokio::sync::Mutex;/// Mock repository for testing.@@ -19,6 +23,10 @@ struct MockRepo {project_access: Arc<Mutex<Option<AccessLevel>>>,thread_access: Arc<Mutex<Option<AccessLevel>>>,call_access: Arc<Mutex<Option<AccessLevel>>>,+ bot_entity_access: Arc<Mutex<Option<AccessLevel>>>,+ bot_entity_access_calls: Arc<AtomicUsize>,+ bot_channel_role: Arc<Mutex<ChannelRoleResult>>,+ bot_channel_role_calls: Arc<AtomicUsize>,foreign_entity_access: Arc<Mutex<bool>>,crm_company_access: Arc<Mutex<Option<AccessLevel>>>,crm_contact_access: Arc<Mutex<Option<AccessLevel>>>,@@ -41,6 +49,10 @@ impl MockRepo {project_access: Arc::new(Mutex::new(None)),thread_access: Arc::new(Mutex::new(None)),call_access: Arc::new(Mutex::new(None)),+ bot_entity_access: Arc::new(Mutex::new(None)),+ bot_entity_access_calls: Arc::new(AtomicUsize::new(0)),+ bot_channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),+ bot_channel_role_calls: Arc::new(AtomicUsize::new(0)),foreign_entity_access: Arc::new(Mutex::new(false)),crm_company_access: Arc::new(Mutex::new(None)),crm_contact_access: Arc::new(Mutex::new(None)),@@ -82,6 +94,21 @@ impl MockRepo {self}+ fn with_bot_entity_access(mut self, level: AccessLevel) -> Self {+ self.bot_entity_access = Arc::new(Mutex::new(Some(level)));+ self+ }++ fn with_bot_channel_role(mut self, result: ChannelRoleResult) -> Self {+ self.bot_channel_role = Arc::new(Mutex::new(result));+ self+ }++ fn bot_repository_calls(&self) -> usize {+ self.bot_entity_access_calls.load(Ordering::SeqCst)+ + self.bot_channel_role_calls.load(Ordering::SeqCst)+ }+fn with_foreign_entity_access(mut self, has_access: bool) -> Self {self.foreign_entity_access = Arc::new(Mutex::new(has_access));self@@ -188,6 +215,25 @@ impl AccessRepository for MockRepo {Ok(*self.call_access.lock().await)}+ async fn get_bot_entity_access(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ self.bot_entity_access_calls.fetch_add(1, Ordering::SeqCst);+ Ok(*self.bot_entity_access.lock().await)+ }++ async fn get_bot_channel_role(+ &self,+ _channel_id: &Uuid,+ _bot_id: BotId,+ ) -> Result<ChannelRoleResult, AccessError> {+ self.bot_channel_role_calls.fetch_add(1, Ordering::SeqCst);+ Ok(*self.bot_channel_role.lock().await)+ }+async fn has_foreign_entity_access(&self,_foreign_entity_id: &str,@@ -271,6 +317,10 @@ fn test_user_id() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()}+fn test_bot_id() -> BotId {+ BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"))+}+fn user_id(s: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from(s.to_string()).unwrap()}@@ -740,6 +790,161 @@ async fn test_generate_receipt_document_no_access_returns_unauthorized() {assert!(matches!(result, Err(AccessError::Unauthorized)));}+#[tokio::test]+async fn generate_bot_entity_access_receipt_document_with_sufficient_access() {+ let bot_id = test_bot_id();+ let repo = MockRepo::new().with_bot_entity_access(AccessLevel::Edit);+ let service = EntityAccessServiceImpl::new(repo);++ let receipt = service+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(+ bot_id,+ "doc-1",+ EntityType::Document,+ )+ .await+ .unwrap();++ assert!(matches!(receipt.auth(), EntityAccessAuth::Bot(id) if id.bot_id() == bot_id));+ assert_eq!(receipt.get_authenticated_bot().unwrap().bot_id(), bot_id);+ assert!(matches!(+ receipt.get_authenticated_user(),+ Err(AccessError::Unauthorized)+ ));+ assert_eq!(receipt.entity().entity_id, "doc-1");+ assert_eq!(receipt.entity().entity_type, EntityType::Document);+ assert!(matches!(+ receipt.entity_permission(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Edit+ }+ ));+}++#[tokio::test]+async fn generate_bot_entity_access_receipt_document_with_insufficient_permission() {+ let repo = MockRepo::new().with_bot_entity_access(AccessLevel::View);+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .generate_bot_entity_access_receipt::<EditAccessLevel>(+ test_bot_id(),+ "doc-1",+ EntityType::Document,+ )+ .await;++ assert!(matches!(result, Err(AccessError::Unauthorized)));+}++#[tokio::test]+async fn generate_bot_entity_access_receipt_document_with_no_access() {+ let service = EntityAccessServiceImpl::new(MockRepo::new());++ let result = service+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(+ test_bot_id(),+ "doc-1",+ EntityType::Document,+ )+ .await;++ assert!(matches!(result, Err(AccessError::Unauthorized)));+}++#[tokio::test]+async fn generate_bot_entity_access_receipt_channel_member_role_succeeds() {+ let bot_id = test_bot_id();+ let repo =+ MockRepo::new().with_bot_channel_role(ChannelRoleResult::Role(ParticipantRole::Member));+ let service = EntityAccessServiceImpl::new(repo);++ let receipt = service+ .generate_bot_entity_access_receipt::<MemberParticipantRole>(+ bot_id,+ "11111111-1111-1111-1111-111111111111",+ EntityType::Channel,+ )+ .await+ .unwrap();++ assert_eq!(receipt.get_authenticated_bot().unwrap().bot_id(), bot_id);+ assert!(matches!(+ receipt.entity_permission(),+ EntityPermission::ChannelRole {+ role: ParticipantRole::Member+ }+ ));+}++#[tokio::test]+async fn generate_bot_entity_access_receipt_channel_no_access_is_unauthorized() {+ let repo = MockRepo::new().with_bot_channel_role(ChannelRoleResult::NoAccess);+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .generate_bot_entity_access_receipt::<MemberParticipantRole>(+ test_bot_id(),+ "11111111-1111-1111-1111-111111111111",+ EntityType::Channel,+ )+ .await;++ assert!(matches!(result, Err(AccessError::Unauthorized)));+}++#[tokio::test]+async fn generate_bot_entity_access_receipt_channel_not_found_is_preserved() {+ let repo = MockRepo::new().with_bot_channel_role(ChannelRoleResult::NotFound);+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .generate_bot_entity_access_receipt::<MemberParticipantRole>(+ test_bot_id(),+ "11111111-1111-1111-1111-111111111111",+ EntityType::Channel,+ )+ .await;++ assert!(matches!(result, Err(AccessError::NotFound(_))));+}++#[tokio::test]+async fn generate_bot_entity_access_receipt_malformed_channel_id_is_bad_request() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo.clone());++ let result = service+ .generate_bot_entity_access_receipt::<MemberParticipantRole>(+ test_bot_id(),+ "not-a-uuid",+ EntityType::Channel,+ )+ .await;++ assert!(matches!(result, Err(AccessError::BadRequest(_))));+ assert_eq!(repo.bot_repository_calls(), 0);+}++#[tokio::test]+async fn generate_bot_entity_access_receipt_unsupported_types_are_bad_request() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo.clone());++ for entity_type in [EntityType::CrmCompany, EntityType::Team] {+ let result = service+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(+ test_bot_id(),+ "unsupported-entity",+ entity_type,+ )+ .await;++ assert!(matches!(result, Err(AccessError::BadRequest(_))));+ }+ assert_eq!(repo.bot_repository_calls(), 0);+}+#[tokio::test]async fn test_generate_receipt_foreign_entity_view_requirement_succeeds() {let repo = MockRepo::new().with_foreign_entity_access(true);diff --git a/crates/entity_access/src/outbound.rs b/crates/entity_access/src/outbound.rsindex 48275ae85e..d1138bb246 100644--- a/crates/entity_access/src/outbound.rs+++ b/crates/entity_access/src/outbound.rs@@ -4,4 +4,4 @@mod pg_access_repo;-pub use pg_access_repo::{PgAccessRepository, SourceIds, get_user_source_ids};+pub use pg_access_repo::{PgAccessRepository, SourceIds, get_bot_source_ids, get_user_source_ids};diff --git a/crates/entity_access/src/outbound/pg_access_repo/mod.rs b/crates/entity_access/src/outbound/pg_access_repo/mod.rsindex 95c1926e20..ef72881e8c 100644--- a/crates/entity_access/src/outbound/pg_access_repo/mod.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/mod.rs@@ -2,15 +2,15 @@mod queries;-pub use queries::{SourceIds, get_user_source_ids};+pub use queries::{SourceIds, get_bot_source_ids, get_user_source_ids};#[cfg(test)]mod test;use crate::domain::{models::{- AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, CrmEntityAccess, EntityType,- UserTeamInfo,+ AccessError, AccessLevel, BotId, CallChannelInfo, ChannelRoleResult, CrmEntityAccess,+ EntityType, UserTeamInfo,},ports::AccessRepository,};@@ -136,6 +136,75 @@ impl AccessRepository for PgAccessRepository {Ok(queries::call_access::get_call_access(&self.pool, &call_uuid, &source_ids).await?)}+ #[tracing::instrument(err, skip(self))]+ async fn get_bot_entity_access(+ &self,+ bot_id: BotId,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ let entity_uuid = entity_id+ .parse::<Uuid>()+ .map_err(|_| AccessError::BadRequest("Invalid entity ID format"))?;+ let bot_principal = bot_id.into_storage_id();+ let source_ids = queries::get_bot_source_ids(&self.pool, &bot_principal)+ .await+ .map_err(|_| AccessError::Internal)?;++ let access = match entity_type {+ EntityType::Document => {+ queries::document_access::get_document_access(&self.pool, &entity_uuid, &source_ids)+ .await+ }+ EntityType::Chat => {+ queries::chat_access::get_chat_access(&self.pool, &entity_uuid, &source_ids).await+ }+ EntityType::Project => {+ queries::project_access::get_project_access(&self.pool, &entity_uuid, &source_ids)+ .await+ }+ EntityType::EmailThread => {+ queries::thread_access::get_thread_access(+ &self.pool,+ &entity_uuid,+ &source_ids,+ None,+ )+ .await+ }+ EntityType::Call => {+ queries::call_access::get_call_access(&self.pool, &entity_uuid, &source_ids).await+ }+ EntityType::User+ | EntityType::Channel+ | EntityType::ChannelMessage+ | EntityType::Team+ | EntityType::ForeignEntity+ | EntityType::StaticFile+ | EntityType::CrmCompany+ | EntityType::CrmContact => {+ return Err(AccessError::BadRequest(+ "Unsupported entity type for bot access",+ ));+ }+ };++ access.map_err(AccessError::from)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_bot_channel_role(+ &self,+ channel_id: &Uuid,+ bot_id: BotId,+ ) -> Result<ChannelRoleResult, AccessError> {+ let bot_principal = bot_id.into_storage_id();+ Ok(+ queries::channel_role::get_bot_channel_role(&self.pool, channel_id, &bot_principal)+ .await?,+ )+ }+#[tracing::instrument(err, skip(self))]async fn has_foreign_entity_access(&self,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.rsindex ac7ca7753d..868b34db89 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@@ -1,6 +1,10 @@//! Queries for channel role resolution.+#[cfg(test)]+mod test;+use crate::domain::models::{ChannelRoleResult, ParticipantRole};+use bot_id::BotIdStr;use sqlx::PgPool;use uuid::Uuid;@@ -90,3 +94,46 @@ pub async fn get_channel_role(None => ChannelRoleResult::NoAccess,})}++/// Get a bot's explicit role in a channel.+///+/// Unlike [`get_channel_role`], public and organization channels do not grant a+/// default role. The bot must exist, not be soft-deleted, and have an active+/// participant row.+#[tracing::instrument(err, skip(pool))]+pub async fn get_bot_channel_role(+ pool: &PgPool,+ channel_id: &Uuid,+ bot_principal: &BotIdStr<'_>,+) -> Result<ChannelRoleResult, sqlx::Error> {+ let row = sqlx::query!(+ r#"+ SELECT cp.role::text as "role?"+ FROM comms_channels c+ LEFT JOIN comms_channel_participants cp+ ON cp.channel_id = c.id+ AND cp.user_id = $2+ AND cp.left_at IS NULL+ AND EXISTS (+ SELECT 1+ FROM bots b+ WHERE b.id = $3 AND b.deleted_at IS NULL+ )+ WHERE c.id = $1+ "#,+ channel_id,+ bot_principal.as_ref(),+ bot_principal.as_uuid(),+ )+ .fetch_optional(pool)+ .await?;++ let Some(row) = row else {+ return Ok(ChannelRoleResult::NotFound);+ };++ Ok(match row.role.as_deref() {+ Some(role) => ChannelRoleResult::Role(parse_role(role)),+ None => ChannelRoleResult::NoAccess,+ })+}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.rsnew file mode 100644index 0000000000..dd4d5f4be5--- /dev/null+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs@@ -0,0 +1,135 @@+use super::*;+use bot_id::{BotId, BotIdStr};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;++async fn insert_public_channel(pool: &PgPool, channel_id: Uuid) {+ sqlx::query!(+ r#"+ INSERT INTO comms_channels (id, name, channel_type, owner_id)+ VALUES ($1, 'Bot Channel', 'public', 'owner')+ "#,+ channel_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_bot(pool: &PgPool, bot_principal: &BotIdStr<'_>) {+ sqlx::query!(+ r#"+ INSERT INTO bots (id, kind, name, handle)+ VALUES ($1, 'system', 'Test Bot', $2)+ "#,+ bot_principal.as_uuid(),+ format!("test-bot-{}", bot_principal.as_uuid()),+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_bot_participant(+ pool: &PgPool,+ channel_id: Uuid,+ bot_principal: &BotIdStr<'_>,+ departed: bool,+) {+ sqlx::query!(+ r#"+ INSERT INTO comms_channel_participants (channel_id, role, user_id, left_at)+ VALUES (+ $1,+ 'admin',+ $2,+ CASE WHEN $3 THEN now() ELSE NULL END+ )+ "#,+ channel_id,+ bot_principal.as_ref(),+ departed,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_channel_role_active_participant_receives_stored_role(+ pool: PgPool,+) -> anyhow::Result<()> {+ let channel_id = Uuid::new_v4();+ let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();+ insert_public_channel(&pool, channel_id).await;+ insert_bot(&pool, &principal).await;+ insert_bot_participant(&pool, channel_id, &principal, false).await;++ let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;++ assert_eq!(role, ChannelRoleResult::Role(ParticipantRole::Admin));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_channel_role_public_channel_non_participant_has_no_access(+ pool: PgPool,+) -> anyhow::Result<()> {+ let channel_id = Uuid::new_v4();+ let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();+ insert_public_channel(&pool, channel_id).await;+ insert_bot(&pool, &principal).await;++ let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;++ assert_eq!(role, ChannelRoleResult::NoAccess);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_channel_role_departed_participant_has_no_access(pool: PgPool) -> anyhow::Result<()> {+ let channel_id = Uuid::new_v4();+ let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();+ insert_public_channel(&pool, channel_id).await;+ insert_bot(&pool, &principal).await;+ insert_bot_participant(&pool, channel_id, &principal, true).await;++ let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;++ assert_eq!(role, ChannelRoleResult::NoAccess);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_channel_role_soft_deleted_participant_has_no_access(+ pool: PgPool,+) -> anyhow::Result<()> {+ let channel_id = Uuid::new_v4();+ let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();+ insert_public_channel(&pool, channel_id).await;+ insert_bot(&pool, &principal).await;+ insert_bot_participant(&pool, channel_id, &principal, false).await;+ sqlx::query!(+ "UPDATE bots SET deleted_at = now() WHERE id = $1",+ principal.as_uuid(),+ )+ .execute(&pool)+ .await?;++ let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;++ assert_eq!(role, ChannelRoleResult::NoAccess);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_channel_role_unknown_channel_is_not_found(pool: PgPool) -> anyhow::Result<()> {+ let channel_id = Uuid::new_v4();+ let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();+ insert_bot(&pool, &principal).await;++ let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;++ assert_eq!(role, ChannelRoleResult::NotFound);+ Ok(())+}diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/mod.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/mod.rsindex 710695a076..0fdb7878dc 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/mod.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/mod.rs@@ -6,7 +6,7 @@use cached::proc_macro::cached;use anyhow::Context;-+use bot_id::BotIdStr;use macro_user_id::{cowlike::CowLike,lowercased::Lowercase,@@ -77,6 +77,49 @@ pub async fn get_user_source_ids(}}+/// Grabs a bot's active channel, owning team, and principal source ids.+#[tracing::instrument(skip(pool), err)]+#[cfg_attr(+ not(test),+ cached(+ time = 30,+ result = true,+ key = "String",+ convert = r#"{bot_id.to_string()}"#,+ )+)]+pub async fn get_bot_source_ids(+ pool: &Pool<Postgres>,+ bot_id: &BotIdStr<'_>,+) -> anyhow::Result<SourceIds> {+ let source_ids = sqlx::query_scalar!(+ r#"+ WITH active_bot AS (+ SELECT team_id+ FROM bots+ WHERE id = $2 AND deleted_at IS NULL+ )+ SELECT cp.channel_id::text+ FROM active_bot+ JOIN comms_channel_participants cp+ ON cp.user_id = $1 AND cp.left_at IS NULL+ UNION ALL+ SELECT team_id::text+ FROM active_bot+ WHERE team_id IS NOT NULL+ UNION ALL+ SELECT $1+ FROM active_bot+ "#,+ bot_id.as_ref(),+ bot_id.as_uuid(),+ )+ .fetch_all(pool)+ .await?;++ Ok(SourceIds(source_ids.into_iter().flatten().collect()))+}+/// Grabs all user IDs with access to an entity via the entity_access table.#[tracing::instrument(skip(pool), err)]#[cfg_attr(diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/test.rsindex 2adb59ff3c..561557786e 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/test.rs@@ -1,10 +1,14 @@+use std::collections::HashSet;+use super::*;+use bot_id::BotId;use macro_db_migrator::MACRO_DB_MIGRATIONS;use sqlx::PgPool;use uuid::Uuid;const OWNER: &str = "macro|[email protected]";const DELEGATE: &str = "macro|[email protected]";+const BOT_OWNER: &str = "macro|[email protected]";/// macro_user + "User" rows so macro_user_links FKs resolve.async fn insert_user(pool: &PgPool, user_id: &str, email: &str) {@@ -32,6 +36,77 @@ async fn insert_user(pool: &PgPool, user_id: &str, email: &str) {.unwrap();}+async fn insert_team(pool: &PgPool, team_id: Uuid) {+ insert_user(pool, BOT_OWNER, "[email protected]").await;+ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Bot Team', $2)"#,+ team_id,+ BOT_OWNER,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_owned_bot(+ pool: &PgPool,+ bot_id: BotId,+ owner_user_id: Option<&str>,+ team_id: Option<Uuid>,+) {+ sqlx::query!(+ r#"+ INSERT INTO bots (id, kind, owner_user_id, team_id, name, handle)+ VALUES ($1, 'owned', $2, $3, 'Test Bot', 'test-bot')+ "#,+ bot_id.as_uuid(),+ owner_user_id,+ team_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_channel(pool: &PgPool, channel_id: Uuid) {+ sqlx::query!(+ r#"+ INSERT INTO comms_channels (id, name, channel_type, owner_id)+ VALUES ($1, 'Bot Channel', 'public', $2)+ "#,+ channel_id,+ BOT_OWNER,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_bot_participant(pool: &PgPool, channel_id: Uuid, bot_id: BotId, departed: bool) {+ let principal = bot_id.into_storage_id();+ sqlx::query!(+ r#"+ INSERT INTO comms_channel_participants (channel_id, role, user_id, left_at)+ VALUES (+ $1,+ 'member',+ $2,+ CASE WHEN $3 THEN now() ELSE NULL END+ )+ "#,+ channel_id,+ principal.as_ref(),+ departed,+ )+ .execute(pool)+ .await+ .unwrap();+}++fn source_id_set(source_ids: SourceIds) -> HashSet<String> {+ source_ids.0.into_iter().collect()+}+/// An empty link + thread owned by `owner_macro_id`. Returns `(link_id, thread_id)`.async fn insert_thread(pool: &PgPool, owner_macro_id: &str, email: &str) -> (Uuid, Uuid) {let link_id = Uuid::new_v4();@@ -60,6 +135,86 @@ async fn insert_thread(pool: &PgPool, owner_macro_id: &str, email: &str) -> (Uui(link_id, thread_id)}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_source_ids_team_scoped_bot_includes_channels_team_and_principal(+ pool: PgPool,+) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let bot_principal = bot_id.into_storage_id();+ let team_id = Uuid::new_v4();+ let first_channel_id = Uuid::new_v4();+ let second_channel_id = Uuid::new_v4();+ insert_team(&pool, team_id).await;+ insert_owned_bot(&pool, bot_id, None, Some(team_id)).await;+ insert_channel(&pool, first_channel_id).await;+ insert_channel(&pool, second_channel_id).await;+ insert_bot_participant(&pool, first_channel_id, bot_id, false).await;+ insert_bot_participant(&pool, second_channel_id, bot_id, false).await;++ let source_ids = source_id_set(get_bot_source_ids(&pool, &bot_principal).await?);+ let expected = HashSet::from([+ first_channel_id.to_string(),+ second_channel_id.to_string(),+ team_id.to_string(),+ bot_principal.to_string(),+ ]);++ assert_eq!(source_ids, expected);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_source_ids_user_scoped_bot_does_not_inherit_owner(pool: PgPool) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let bot_principal = bot_id.into_storage_id();+ insert_owned_bot(&pool, bot_id, Some(BOT_OWNER), None).await;++ let source_ids = source_id_set(get_bot_source_ids(&pool, &bot_principal).await?);++ assert_eq!(source_ids, HashSet::from([bot_principal.to_string()]));+ assert!(!source_ids.contains(BOT_OWNER));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_source_ids_soft_deleted_bot_has_no_sources(pool: PgPool) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let bot_principal = bot_id.into_storage_id();+ let team_id = Uuid::new_v4();+ let channel_id = Uuid::new_v4();+ insert_team(&pool, team_id).await;+ insert_owned_bot(&pool, bot_id, None, Some(team_id)).await;+ insert_channel(&pool, channel_id).await;+ insert_bot_participant(&pool, channel_id, bot_id, false).await;+ sqlx::query!(+ "UPDATE bots SET deleted_at = now() WHERE id = $1",+ bot_id.as_uuid(),+ )+ .execute(&pool)+ .await?;++ let source_ids = source_id_set(get_bot_source_ids(&pool, &bot_principal).await?);++ assert!(source_ids.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_source_ids_excludes_departed_channels(pool: PgPool) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let bot_principal = bot_id.into_storage_id();+ let channel_id = Uuid::new_v4();+ insert_owned_bot(&pool, bot_id, Some(BOT_OWNER), None).await;+ insert_channel(&pool, channel_id).await;+ insert_bot_participant(&pool, channel_id, bot_id, true).await;++ let source_ids = source_id_set(get_bot_source_ids(&pool, &bot_principal).await?);++ assert_eq!(source_ids, HashSet::from([bot_principal.to_string()]));+ assert!(!source_ids.contains(&channel_id.to_string()));+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn get_entity_users_includes_inbox_delegate(pool: PgPool) -> anyhow::Result<()> {insert_user(&pool, OWNER, "[email protected]").await;diff --git a/crates/entity_access/src/outbound/pg_access_repo/test.rs b/crates/entity_access/src/outbound/pg_access_repo/test.rsindex 8d75fa9891..851d96ee51 100644--- a/crates/entity_access/src/outbound/pg_access_repo/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/test.rs@@ -1,6 +1,9 @@use super::PgAccessRepository;use crate::domain::{- models::{AccessError, AccessLevel, CrmEntityAccess},+ models::{+ AccessError, AccessLevel, BotId, ChannelRoleResult, CrmEntityAccess, EntityType,+ ParticipantRole,+ },ports::AccessRepository,};use macro_db_migrator::MACRO_DB_MIGRATIONS;@@ -449,3 +452,327 @@ async fn crm_contact_access_rejects_invalid_uuid(pool: PgPool) -> anyhow::Result));Ok(())}++const PG_BOT_OWNER: &str = "macro|[email protected]";++async fn insert_pg_bot_user(pool: &PgPool) -> anyhow::Result<()> {+ let macro_user_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, '[email protected]', $2)+ "#,+ macro_user_id,+ PG_BOT_OWNER,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ($1, '[email protected]', $2)+ "#,+ PG_BOT_OWNER,+ macro_user_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn insert_pg_bot_team(pool: &PgPool, team_id: Uuid) -> anyhow::Result<()> {+ insert_pg_bot_user(pool).await?;+ sqlx::query!(+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'PG Bot Team', $2)",+ team_id,+ PG_BOT_OWNER,+ )+ .execute(pool)+ .await?;+ Ok(())+}++async fn insert_pg_bot(+ pool: &PgPool,+ bot_id: BotId,+ owner_user_id: Option<&str>,+ team_id: Option<Uuid>,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO bots (id, kind, owner_user_id, team_id, name, handle)+ VALUES ($1, 'owned', $2, $3, 'PG Bot', $4)+ "#,+ bot_id.as_uuid(),+ owner_user_id,+ team_id,+ format!("pg-bot-{bot_id}"),+ )+ .execute(pool)+ .await?;+ Ok(())+}++async fn insert_pg_bot_channel(+ pool: &PgPool,+ channel_id: Uuid,+ channel_type: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO comms_channels (id, name, channel_type, owner_id)+ VALUES ($1, 'PG Bot Channel', $2::text::comms_channel_type, $3)+ "#,+ channel_id,+ channel_type,+ PG_BOT_OWNER,+ )+ .execute(pool)+ .await?;+ Ok(())+}++async fn insert_pg_bot_participant(+ pool: &PgPool,+ channel_id: Uuid,+ bot_id: BotId,+ role: &str,+) -> anyhow::Result<()> {+ let principal = bot_id.into_storage_id();+ sqlx::query!(+ r#"+ INSERT INTO comms_channel_participants (channel_id, role, user_id)+ VALUES ($1, $2::text::comms_participant_role, $3)+ "#,+ channel_id,+ role,+ principal.as_ref(),+ )+ .execute(pool)+ .await?;+ Ok(())+}++async fn insert_pg_bot_entity_access(+ pool: &PgPool,+ entity_id: Uuid,+ entity_type: &str,+ source_id: &str,+ source_type: &str,+ access_level: AccessLevel,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO entity_access (+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level+ )+ VALUES (+ $1,+ $2,+ $3,+ $4::text::entity_access_source_type,+ $5::text::"AccessLevel"+ )+ "#,+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level.to_string(),+ )+ .execute(pool)+ .await?;+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pg_bot_document_grant_through_active_channel(pool: PgPool) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let channel_id = Uuid::new_v4();+ let document_id = Uuid::new_v4();+ insert_pg_bot(&pool, bot_id, Some(PG_BOT_OWNER), None).await?;+ insert_pg_bot_channel(&pool, channel_id, "private").await?;+ insert_pg_bot_participant(&pool, channel_id, bot_id, "member").await?;+ insert_pg_bot_entity_access(+ &pool,+ document_id,+ "document",+ &channel_id.to_string(),+ "channel",+ AccessLevel::Edit,+ )+ .await?;++ let access = PgAccessRepository::new(pool)+ .get_bot_entity_access(bot_id, &document_id.to_string(), EntityType::Document)+ .await?;++ assert_eq!(access, Some(AccessLevel::Edit));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pg_bot_team_grant_is_available_only_to_team_scoped_bot(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::new_v4();+ let team_bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let user_bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let document_id = Uuid::new_v4();+ insert_pg_bot_team(&pool, team_id).await?;+ insert_pg_bot(&pool, team_bot_id, None, Some(team_id)).await?;+ insert_pg_bot(&pool, user_bot_id, Some(PG_BOT_OWNER), None).await?;+ insert_pg_bot_entity_access(+ &pool,+ document_id,+ "document",+ &team_id.to_string(),+ "team",+ AccessLevel::Comment,+ )+ .await?;+ let repo = PgAccessRepository::new(pool);++ let team_access = repo+ .get_bot_entity_access(team_bot_id, &document_id.to_string(), EntityType::Document)+ .await?;+ let user_access = repo+ .get_bot_entity_access(user_bot_id, &document_id.to_string(), EntityType::Document)+ .await?;++ assert_eq!(team_access, Some(AccessLevel::Comment));+ assert_eq!(user_access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pg_bot_ungranted_document_returns_none(pool: PgPool) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let document_id = Uuid::new_v4();+ insert_pg_bot(&pool, bot_id, Some(PG_BOT_OWNER), None).await?;++ let access = PgAccessRepository::new(pool)+ .get_bot_entity_access(bot_id, &document_id.to_string(), EntityType::Document)+ .await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pg_bot_email_thread_receives_view_from_containing_project(+ pool: PgPool,+) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let channel_id = Uuid::new_v4();+ let project_id = Uuid::new_v4();+ let link_id = Uuid::new_v4();+ let thread_id = Uuid::new_v4();+ insert_pg_bot_user(&pool).await?;+ insert_pg_bot(&pool, bot_id, Some(PG_BOT_OWNER), None).await?;+ insert_pg_bot_channel(&pool, channel_id, "private").await?;+ insert_pg_bot_participant(&pool, channel_id, bot_id, "member").await?;+ sqlx::query!(+ r#"INSERT INTO "Project" (id, name, "userId") VALUES ($1, 'PG Bot Project', $2)"#,+ project_id.to_string(),+ PG_BOT_OWNER,+ )+ .execute(&pool)+ .await?;+ sqlx::query!(+ r#"+ INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)+ VALUES ($1, $2, $2, '[email protected]', 'GMAIL')+ "#,+ link_id,+ PG_BOT_OWNER,+ )+ .execute(&pool)+ .await?;+ sqlx::query!(+ "INSERT INTO email_threads (id, link_id, project_id) VALUES ($1, $2, $3)",+ thread_id,+ link_id,+ project_id.to_string(),+ )+ .execute(&pool)+ .await?;+ insert_pg_bot_entity_access(+ &pool,+ project_id,+ "project",+ &channel_id.to_string(),+ "channel",+ AccessLevel::Owner,+ )+ .await?;++ let access = PgAccessRepository::new(pool)+ .get_bot_entity_access(bot_id, &thread_id.to_string(), EntityType::EmailThread)+ .await?;++ assert_eq!(access, Some(AccessLevel::View));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pg_bot_channel_role_requires_explicit_canonical_participation(+ pool: PgPool,+) -> anyhow::Result<()> {+ let participating_bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let other_bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let channel_id = Uuid::new_v4();+ insert_pg_bot(&pool, participating_bot_id, Some(PG_BOT_OWNER), None).await?;+ insert_pg_bot(&pool, other_bot_id, Some(PG_BOT_OWNER), None).await?;+ insert_pg_bot_channel(&pool, channel_id, "public").await?;+ insert_pg_bot_participant(&pool, channel_id, participating_bot_id, "admin").await?;+ let repo = PgAccessRepository::new(pool);++ let participating_role = repo+ .get_bot_channel_role(&channel_id, participating_bot_id)+ .await?;+ let non_participating_role = repo.get_bot_channel_role(&channel_id, other_bot_id).await?;++ assert_eq!(+ participating_role,+ ChannelRoleResult::Role(ParticipantRole::Admin)+ );+ assert_eq!(non_participating_role, ChannelRoleResult::NoAccess);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pg_bot_entity_access_rejects_malformed_uuid(pool: PgPool) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let error = PgAccessRepository::new(pool)+ .get_bot_entity_access(bot_id, "not-a-uuid", EntityType::Document)+ .await+ .expect_err("malformed entity ID should be rejected");++ assert!(matches!(+ error,+ AccessError::BadRequest("Invalid entity ID format")+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pg_bot_entity_access_rejects_unsupported_entity_type(pool: PgPool) -> anyhow::Result<()> {+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let error = PgAccessRepository::new(pool)+ .get_bot_entity_access(bot_id, &Uuid::new_v4().to_string(), EntityType::CrmCompany)+ .await+ .expect_err("unsupported bot entity type should be rejected");++ assert!(matches!(+ error,+ AccessError::BadRequest("Unsupported entity type for bot access")+ ));+ Ok(())+}diff --git a/crates/foreign_entity/src/inbound/axum_router/tests.rs b/crates/foreign_entity/src/inbound/axum_router/tests.rsindex f594657d5b..f7f124ba66 100644--- a/crates/foreign_entity/src/inbound/axum_router/tests.rs+++ b/crates/foreign_entity/src/inbound/axum_router/tests.rs@@ -10,8 +10,8 @@ use chrono::{DateTime, Utc};use entity_access::{domain::{models::{- AccessError, AccessLevel, CallChannelInfo, EntityAccessReceipt, EntityPermission,- EntityType, RequiredPermission, UserTeamInfo, ViewAccessLevel,+ AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt,+ EntityPermission, EntityType, RequiredPermission, UserTeamInfo, ViewAccessLevel,},ports::EntityAccessService,},@@ -153,6 +153,15 @@ impl EntityAccessService for NoopEntityAccessService {unreachable!("InternalUser extension should bypass real access receipt generation")}+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ unreachable!("InternalUser extension should bypass bot access receipt generation")+ }+async fn get_access_level(&self,_user_id: Option<&MacroUserId<Lowercase<'_>>>,diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rsindex 2b20641f38..60fdfc6c2d 100644--- a/crates/properties/src/domain/model.rs+++ b/crates/properties/src/domain/model.rs@@ -88,11 +88,13 @@ impl<T: RequiredPermission> PropertiesAccessReceipt<T> {}/// The authenticated user this receipt was minted for, if any- /// (`None` for internal and anonymous-public access).+ /// (`None` for bot, internal, and anonymous-public access).pub fn authenticated_user(&self) -> Option<&MacroUserIdStr<'static>> {match self.receipt.auth() {EntityAccessAuth::Authenticated(user) => Some(user),- EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => None,+ EntityAccessAuth::Bot(_)+ | EntityAccessAuth::Unauthenticated+ | EntityAccessAuth::Internal => None,}}diff --git a/crates/properties/src/domain/service_impl/helpers.rs b/crates/properties/src/domain/service_impl/helpers.rsindex 37b0c6bdff..01dbecd2c4 100644--- a/crates/properties/src/domain/service_impl/helpers.rs+++ b/crates/properties/src/domain/service_impl/helpers.rs@@ -16,6 +16,7 @@ fn tag_visible_to(owner: &PropertyOwner, auth: &EntityAccessAuth) -> bool {match owner {PropertyOwner::User { user_id } => match auth {EntityAccessAuth::Authenticated(caller) => user_id == caller.as_ref(),+ EntityAccessAuth::Bot(_) => false,EntityAccessAuth::Unauthenticated => false,EntityAccessAuth::Internal => true,},diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rsindex cae92a156e..1ceb3d9834 100644--- a/crates/properties/src/domain/test.rs+++ b/crates/properties/src/domain/test.rs@@ -7,6 +7,9 @@ use crate::domain::{service::PropertiesService,};use anyhow::anyhow;+use entity_access::domain::models::{+ BotId, EntityAccessAuth, EntityAccessReceipt, ViewAccessLevel,+};use macro_user_id::user_id::MacroUserIdStr;use models_properties::{EntityType,@@ -55,6 +58,22 @@ fn view_receipt(entity_id: &str, entity_type: EntityType) -> ViewReceipt {)}+#[test]+fn bot_receipt_has_no_authenticated_user_identity() {+ let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));+ let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_bot(+ bot_id.into_storage_id(),+ "document-1",+ entity_access::domain::models::EntityType::Document,+ );+ let access =+ PropertiesAccessReceipt::try_from_entity_access_receipt(receipt, EntityType::Document)+ .unwrap();++ assert!(access.authenticated_user().is_none());+ assert!(matches!(access.auth(), EntityAccessAuth::Bot(id) if id.bot_id() == bot_id));+}+/// Creates a mock permission service that mints edit receipts for any entity.fn create_mock_permission_service() -> MockPermissionService {let mut perm_checker = MockPermissionService::new();diff --git a/crates/soup/src/inbound/axum_router/tests.rs b/crates/soup/src/inbound/axum_router/tests.rsindex 8624f84bd0..206917fc60 100644--- a/crates/soup/src/inbound/axum_router/tests.rs+++ b/crates/soup/src/inbound/axum_router/tests.rs@@ -7,7 +7,7 @@ use email::domain::{models::{EmailErr, PreviewView, PreviewViewStandardLabel, UserProvider},ports::EmailService,};-use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};+use entity_access::domain::models::{BotId, EntityAccessReceipt, ViewAccessLevel};use http_body_util::BodyExt;use item_filters::EntityFilters;use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};@@ -293,6 +293,20 @@ impl entity_access::domain::ports::EntityAccessService for MockEntityAccess {unimplemented!()}+ async fn generate_bot_entity_access_receipt<+ T: entity_access::domain::models::RequiredPermission,+ >(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: entity_access::domain::models::EntityType,+ ) -> Result<+ entity_access::domain::models::EntityAccessReceipt<T>,+ entity_access::domain::models::AccessError,+ > {+ unimplemented!()+ }+async fn get_access_level(&self,_user_id: Option<diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex a75a8b2db4..3b89c662a6 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -21,7 +21,7 @@ use documents::domain::events::{DocumentUpdatedMetadata,};use entity_access::domain::models::{- AccessLevel, CallChannelInfo, EntityAccessReceipt, EntityPermission, RequiredPermission,+ AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission, RequiredPermission,UserTeamInfo,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};@@ -88,6 +88,15 @@ impl EntityAccessService for MockAccessService {unimplemented!("not used by webhook event ingestion")}+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ unimplemented!("not used by webhook event ingestion")+ }+async fn get_access_level(&self,_user_id: Option<&MacroUserId<Lowercase<'_>>>,