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(entity_access): update entity access to support foreign entities (#3644)
Will Hutchinson301ab8749356
diff --git a/rust/cloud-storage/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.json b/rust/cloud-storage/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.jsondeleted file mode 100644index ee321949b6..0000000000--- a/rust/cloud-storage/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT COUNT(*) as \"persisted_count!\"\n FROM foreign_entity\n WHERE id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "persisted_count!",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- null- ]- },- "hash": "1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1"-}diff --git a/rust/cloud-storage/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.json b/rust/cloud-storage/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.jsondeleted file mode 100644index ba7824ec45..0000000000--- a/rust/cloud-storage/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE foreign_entity\n SET created_at = $2, updated_at = $3\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Timestamptz",- "Timestamptz"- ]- },- "nullable": []- },- "hash": "280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f"-}diff --git a/rust/cloud-storage/.sqlx/query-308c21dbdc26bcddf5343fb06b4903989ff52fa3ac924017c0bd5a50e0640134.json b/rust/cloud-storage/.sqlx/query-308c21dbdc26bcddf5343fb06b4903989ff52fa3ac924017c0bd5a50e0640134.jsondeleted file mode 100644index d110de19dc..0000000000--- a/rust/cloud-storage/.sqlx/query-308c21dbdc26bcddf5343fb06b4903989ff52fa3ac924017c0bd5a50e0640134.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT id FROM in_progress_user_link WHERE id = $1",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false- ]- },- "hash": "308c21dbdc26bcddf5343fb06b4903989ff52fa3ac924017c0bd5a50e0640134"-}diff --git a/rust/cloud-storage/.sqlx/query-31d2504654072ca22b3fc69edcfda0a7c112bb86527c7200c38326cd920f94e8.json b/rust/cloud-storage/.sqlx/query-31d2504654072ca22b3fc69edcfda0a7c112bb86527c7200c38326cd920f94e8.jsonnew file mode 100644index 0000000000..018d07b559--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-31d2504654072ca22b3fc69edcfda0a7c112bb86527c7200c38326cd920f94e8.json@@ -0,0 +1,24 @@+{+ "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 EXISTS (\n SELECT 1\n FROM foreign_entity fe\n WHERE fe.id = $1\n AND EXISTS (\n SELECT 1\n FROM source_pairs s\n WHERE s.stored_for_id = fe.stored_for_id\n AND s.stored_for_auth_entity = fe.stored_for_auth_entity\n )\n ) AS \"has_access!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "has_access!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "31d2504654072ca22b3fc69edcfda0a7c112bb86527c7200c38326cd920f94e8"+}diff --git a/rust/cloud-storage/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.json b/rust/cloud-storage/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.jsondeleted file mode 100644index ecd353f8c0..0000000000--- a/rust/cloud-storage/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE foreign_entity\n SET updated_at = NOW() - INTERVAL '1 hour'\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e"-}diff --git a/rust/cloud-storage/.sqlx/query-a070af6b64aa1575ea0583b7c47d0a31db822d1ae1b471387b335f416f8ee095.json b/rust/cloud-storage/.sqlx/query-a070af6b64aa1575ea0583b7c47d0a31db822d1ae1b471387b335f416f8ee095.jsondeleted file mode 100644index 9ee6143607..0000000000--- a/rust/cloud-storage/.sqlx/query-a070af6b64aa1575ea0583b7c47d0a31db822d1ae1b471387b335f416f8ee095.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT id FROM github_links WHERE id = $1",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false- ]- },- "hash": "a070af6b64aa1575ea0583b7c47d0a31db822d1ae1b471387b335f416f8ee095"-}diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rsindex 79b0f6496e..4f156ec8bf 100644--- a/rust/cloud-storage/entity_access/src/domain/ports.rs+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs@@ -51,6 +51,16 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {user_id: Option<&MacroUserId<Lowercase<'_>>>,) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;+ /// Check whether a user has access to a foreign entity.+ ///+ /// Foreign entity access is boolean because it only maps to [`AccessLevel::View`]+ /// at the service layer.+ fn has_foreign_entity_access(+ &self,+ foreign_entity_id: &str,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ ) -> impl Future<Output = Result<bool, AccessError>> + Send;+/// Check if a user is a member of the specified channels.////// Returns the subset of channel_ids that the user is a participant of.diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rsindex e0cc0b7e37..4574a65c81 100644--- a/rust/cloud-storage/entity_access/src/domain/service.rs+++ b/rust/cloud-storage/entity_access/src/domain/service.rs@@ -74,6 +74,26 @@ where}}+ /// Get access level for a foreign entity.+ ///+ /// Foreign entity access is binary and always maps to View access.+ async fn get_foreign_entity_access(+ &self,+ entity_id: &str,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ ) -> Result<Option<AccessLevel>, AccessError> {+ let has_access = self+ .repo+ .has_foreign_entity_access(entity_id, user_id)+ .await?;++ if has_access {+ Ok(Some(AccessLevel::View))+ } else {+ Ok(None)+ }+ }+/// Resolve a call id string to the channel id that owns it.////// Looks up both the active `calls` table and the archived `call_records`@@ -139,10 +159,11 @@ where.await}EntityType::Channel => self.get_channel_access(entity_id, user_id).await,+ EntityType::ForeignEntity => self.get_foreign_entity_access(entity_id, user_id).await,// Static files are always viewable. This is wrong for ownersEntityType::StaticFile => Ok(Some(AccessLevel::View)),// These entity types don't have access checks implemented yet.- EntityType::ForeignEntity | EntityType::Team | EntityType::User => Ok(None),+ EntityType::Team | EntityType::User => Ok(None),}}@@ -204,6 +225,15 @@ whereNone => Err(AccessError::Unauthorized),}}+ EntityType::ForeignEntity => {+ let access = self.get_foreign_entity_access(entity_id, user_id).await?;+ match access {+ Some(level) => Ok(EntityPermission::AccessLevel {+ access_level: level,+ }),+ None => Err(AccessError::Unauthorized),+ }+ }EntityType::Channel => {let channel_uuid = Uuid::from_str(entity_id).map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rsindex 9fc541bb32..9838752279 100644--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs@@ -19,6 +19,7 @@ struct MockRepo {project_access: Arc<Mutex<Option<AccessLevel>>>,thread_access: Arc<Mutex<Option<AccessLevel>>>,call_access: Arc<Mutex<Option<AccessLevel>>>,+ foreign_entity_access: Arc<Mutex<bool>>,channel_membership: Arc<Mutex<Vec<Uuid>>>,channel_role: Arc<Mutex<ChannelRoleResult>>,document_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,@@ -38,6 +39,7 @@ impl MockRepo {project_access: Arc::new(Mutex::new(None)),thread_access: Arc::new(Mutex::new(None)),call_access: Arc::new(Mutex::new(None)),+ foreign_entity_access: Arc::new(Mutex::new(false)),channel_membership: Arc::new(Mutex::new(vec![])),channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),document_users: Arc::new(Mutex::new(vec![])),@@ -76,6 +78,11 @@ impl MockRepo {self}+ fn with_foreign_entity_access(mut self, has_access: bool) -> Self {+ self.foreign_entity_access = Arc::new(Mutex::new(has_access));+ self+ }+fn with_channel_membership(mut self, channels: Vec<Uuid>) -> Self {self.channel_membership = Arc::new(Mutex::new(channels));self@@ -165,6 +172,14 @@ impl AccessRepository for MockRepo {Ok(*self.call_access.lock().await)}+ async fn has_foreign_entity_access(+ &self,+ _foreign_entity_id: &str,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ ) -> Result<bool, AccessError> {+ Ok(*self.foreign_entity_access.lock().await)+ }+async fn get_entity_users(&self,_entity_id: &uuid::Uuid,@@ -216,6 +231,8 @@ fn user_id(s: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from(s.to_string()).unwrap()}+const FOREIGN_ENTITY_ID: &str = "22222222-2222-2222-2222-222222222222";+#[tokio::test]async fn test_get_document_access_returns_level_from_repo() {let repo = MockRepo::new().with_document_access(AccessLevel::Edit);@@ -316,6 +333,32 @@ async fn test_get_channel_access_with_invalid_uuid_returns_error() {assert!(matches!(result, Err(AccessError::BadRequest(_))));}+#[tokio::test]+async fn test_get_foreign_entity_access_returns_view_when_repo_grants_access() {+ let repo = MockRepo::new().with_foreign_entity_access(true);+ let service = EntityAccessServiceImpl::new(repo);+ let user_id = test_user_id();++ let result = service+ .get_access_level(Some(&user_id), FOREIGN_ENTITY_ID, EntityType::ForeignEntity)+ .await;++ assert_eq!(result.unwrap(), Some(AccessLevel::View));+}++#[tokio::test]+async fn test_get_foreign_entity_access_returns_none_when_repo_denies_access() {+ let repo = MockRepo::new().with_foreign_entity_access(false);+ let service = EntityAccessServiceImpl::new(repo);+ let user_id = test_user_id();++ let result = service+ .get_access_level(Some(&user_id), FOREIGN_ENTITY_ID, EntityType::ForeignEntity)+ .await;++ assert_eq!(result.unwrap(), None);+}+#[tokio::test]async fn test_check_access_sufficient_level_returns_actual_level() {let repo = MockRepo::new().with_document_access(AccessLevel::Edit);@@ -422,6 +465,30 @@ async fn test_get_entity_permission_document_no_access_returns_unauthorized() {assert!(matches!(result, Err(AccessError::Unauthorized)));}+#[tokio::test]+async fn test_get_entity_permission_foreign_entity_returns_view_access_level() {+ let repo = MockRepo::new().with_foreign_entity_access(true);+ let service = EntityAccessServiceImpl::new(repo);+ let user_id = test_user_id();++ let result = service+ .get_entity_permission(+ Some(&user_id),+ FOREIGN_ENTITY_ID,+ EntityType::ForeignEntity,+ None,+ )+ .await+ .unwrap();++ assert!(matches!(+ result,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View+ }+ ));+}+#[tokio::test]async fn test_get_entity_permission_channel_returns_role() {let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));@@ -629,6 +696,49 @@ async fn test_generate_receipt_document_no_access_returns_unauthorized() {assert!(matches!(result, Err(AccessError::Unauthorized)));}+#[tokio::test]+async fn test_generate_receipt_foreign_entity_view_requirement_succeeds() {+ let repo = MockRepo::new().with_foreign_entity_access(true);+ let service = EntityAccessServiceImpl::new(repo);+ let user_id = test_user_id();++ let receipt = service+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &user_id,+ None,+ FOREIGN_ENTITY_ID,+ EntityType::ForeignEntity,+ )+ .await+ .unwrap();++ assert_eq!(receipt.entity().entity_id, FOREIGN_ENTITY_ID);+ assert!(matches!(+ receipt.entity_permission(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View+ }+ ));+}++#[tokio::test]+async fn test_generate_receipt_foreign_entity_view_access_fails_comment_requirement() {+ let repo = MockRepo::new().with_foreign_entity_access(true);+ let service = EntityAccessServiceImpl::new(repo);+ let user_id = test_user_id();++ let result = service+ .generate_entity_access_receipt::<CommentAccessLevel>(+ &user_id,+ None,+ FOREIGN_ENTITY_ID,+ EntityType::ForeignEntity,+ )+ .await;++ assert!(matches!(result, Err(AccessError::Unauthorized)));+}+// --- minimum access level enforcement tests ---#[tokio::test]diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rsindex a52bff0ddf..0d0c9a8ccd 100644--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs@@ -67,14 +67,15 @@ wherelet parsed_type = parse_entity_type(&entity_type)?;- let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {- parts- .extract()- .await- .map_err(|_| ExtractorError::Internal)?- } else {- None- };+ let internal_user: Option<Extension<InternalUser>> =+ if macro_user_id.is_none() || parsed_type == EntityType::ForeignEntity {+ parts+ .extract()+ .await+ .map_err(|_| ExtractorError::Internal)?+ } else {+ None+ };if internal_user.is_some() {return Ok(Self {@@ -85,7 +86,7 @@ where},auth: EntityAccessAuth::Internal,entity_permission: EntityPermission::AccessLevel {- access_level: AccessLevel::Owner,+ access_level: internal_access_level(parsed_type),},_marker: PhantomData,},@@ -131,6 +132,13 @@ where}}+fn internal_access_level(entity_type: EntityType) -> AccessLevel {+ match entity_type {+ EntityType::ForeignEntity => AccessLevel::View,+ _ => AccessLevel::Owner,+ }+}+/// Parse entity type string to [`EntityType`], handling the "email_thread" → "thread" alias.fn parse_entity_type(s: &str) -> Result<EntityType, ExtractorError> {// "thread" in the API maps to EmailThreaddiff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/foreign_entity.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/foreign_entity.rsnew file mode 100644index 0000000000..738d44ba22--- /dev/null+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/foreign_entity.rs@@ -0,0 +1,132 @@+//! Foreign entity access extractor.++use std::collections::HashMap;+use std::marker::PhantomData;+use std::sync::Arc;++use axum::{+ Extension, RequestPartsExt,+ extract::{FromRef, FromRequestParts, Path},+ http::request::Parts,+};+use uuid::Uuid;++use super::{ExtractorError, InternalUser, RequiredPermission};+use crate::domain::{+ models::{+ AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,+ },+ ports::EntityAccessService,+};+use model_user::axum_extractor::MacroUserExtractor;++/// Validates that the user satisfies the required permission for a foreign entity.+///+/// Foreign entities grant View access only. The extractor reads either+/// `foreign_entity_id` or `id` from the route path parameters.+#[derive(Debug)]+pub struct ForeignEntityAccessLevelExtractor<T: RequiredPermission, Svc> {+ /// The entity access receipt.+ pub entity_access_receipt: EntityAccessReceipt<T>,+ _marker: PhantomData<(T, Svc)>,+}++impl<T, S, Svc> FromRequestParts<S> for ForeignEntityAccessLevelExtractor<T, Svc>+where+ T: RequiredPermission,+ Arc<Svc>: FromRef<S>,+ Svc: EntityAccessService,+ S: Send + Sync + 'static,+{+ type Rejection = ExtractorError;++ #[tracing::instrument(err, skip(state, parts))]+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {+ let service = <Arc<Svc>>::from_ref(state);++ let Path(path_params): Path<HashMap<String, String>> =+ parts.extract().await.map_err(|_| {+ ExtractorError::BadRequest("missing foreign_entity_id or id path parameter")+ })?;+ let foreign_entity_id = extract_foreign_entity_id(&path_params)?.to_string();++ let internal_user: Option<Extension<InternalUser>> = parts+ .extract()+ .await+ .map_err(|_| ExtractorError::Internal)?;++ if internal_user.is_some() {+ return Self::from_permission(+ foreign_entity_id,+ EntityAccessAuth::Internal,+ view_permission(),+ );+ }++ let MacroUserExtractor { macro_user_id, .. } = parts+ .extract()+ .await+ .map_err(|_| ExtractorError::Unauthorized)?;++ let permission = service+ .get_entity_permission(+ Some(¯o_user_id),+ &foreign_entity_id,+ EntityType::ForeignEntity,+ None,+ )+ .await+ .map_err(ExtractorError::from)?;++ Self::from_permission(+ foreign_entity_id,+ EntityAccessAuth::Authenticated(macro_user_id),+ permission,+ )+ }+}++impl<T: RequiredPermission, Svc> ForeignEntityAccessLevelExtractor<T, Svc> {+ fn from_permission(+ foreign_entity_id: String,+ auth: EntityAccessAuth,+ entity_permission: EntityPermission,+ ) -> Result<Self, ExtractorError> {+ if !entity_permission.satisfies::<T>() {+ return Err(ExtractorError::Unauthorized);+ }++ Ok(Self {+ entity_access_receipt: EntityAccessReceipt {+ entity: Entity {+ entity_id: foreign_entity_id,+ entity_type: EntityType::ForeignEntity,+ },+ auth,+ entity_permission,+ _marker: PhantomData,+ },+ _marker: PhantomData,+ })+ }+}++fn extract_foreign_entity_id(+ path_params: &HashMap<String, String>,+) -> Result<Uuid, ExtractorError> {+ let raw_id = path_params+ .get("foreign_entity_id")+ .or_else(|| path_params.get("id"))+ .ok_or(ExtractorError::BadRequest(+ "missing foreign_entity_id or id path parameter",+ ))?;++ Uuid::parse_str(raw_id)+ .map_err(|_| ExtractorError::BadRequest("invalid foreign entity ID format"))+}++fn view_permission() -> EntityPermission {+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ }+}diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rsindex b7395a7046..1a33c7e478 100644--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs@@ -8,6 +8,7 @@ mod channel;mod chat;mod document;mod entity_permission;+mod foreign_entity;mod history;mod pin;mod project;@@ -19,6 +20,7 @@ pub use channel::ChannelAccessLevelExtractor;pub use chat::ChatAccessLevelExtractor;pub use document::DocumentAccessExtractor;pub use entity_permission::EntityPermissionExtractor;+pub use foreign_entity::ForeignEntityAccessLevelExtractor;pub use history::HistoryAccessExtractor;pub use pin::PinAccessLevelExtractor;pub use project::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractor};diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rsindex 9bb0ecf3dd..b40e107c89 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs@@ -2,6 +2,9 @@mod queries;+#[cfg(test)]+mod test;+use crate::domain::{models::{AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, EntityType, UserTeamInfo,@@ -27,6 +30,21 @@ impl PgAccessRepository {}}+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!["user".to_string()];++ if let Some(user_team) = user_team {+ source_ids.push(user_team.team_id.to_string());+ source_auth_entities.push("team".to_string());+ }++ (source_ids, source_auth_entities)+}+impl AccessRepository for PgAccessRepository {#[tracing::instrument(err, skip(self))]async fn get_document_access(@@ -115,6 +133,32 @@ 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 has_foreign_entity_access(+ &self,+ foreign_entity_id: &str,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ ) -> Result<bool, AccessError> {+ let foreign_entity_uuid = foreign_entity_id+ .parse::<Uuid>()+ .map_err(|_| AccessError::BadRequest("Invalid foreign entity ID format"))?;++ let Some(user_id) = user_id else {+ return Ok(false);+ };++ 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::has_foreign_entity_access(+ &self.pool,+ &foreign_entity_uuid,+ &source_ids,+ &source_auth_entities,+ )+ .await?)+ }+#[tracing::instrument(err, skip(self))]async fn check_user_channel_membership(&self,diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/foreign_entity_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/foreign_entity_access.rsnew file mode 100644index 0000000000..ec595157e6--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/foreign_entity_access.rs@@ -0,0 +1,46 @@+//! Query for foreign entity access.++use sqlx::PgPool;+use uuid::Uuid;++/// 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(+ pool: &PgPool,+ foreign_entity_id: &Uuid,+ source_ids: &[String],+ source_auth_entities: &[String],+) -> Result<bool, sqlx::Error> {+ if source_ids.is_empty()+ || source_auth_entities.is_empty()+ || source_ids.len() != source_auth_entities.len()+ {+ return Ok(false);+ }++ sqlx::query_scalar!(+ 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 EXISTS (+ SELECT 1+ FROM foreign_entity fe+ WHERE fe.id = $1+ AND EXISTS (+ SELECT 1+ FROM source_pairs s+ WHERE s.stored_for_id = fe.stored_for_id+ AND s.stored_for_auth_entity = fe.stored_for_auth_entity+ )+ ) AS "has_access!"+ "#,+ foreign_entity_id,+ source_ids,+ source_auth_entities,+ )+ .fetch_one(pool)+ .await+}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rsindex c7b9bfab63..cd8a6cb782 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs@@ -22,6 +22,7 @@ pub mod channel_role;pub mod channel_users;pub mod chat_access;pub mod document_access;+pub mod foreign_entity_access;pub mod project_access;pub mod team_access;pub mod thread_access;diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/test.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/test.rsnew file mode 100644index 0000000000..56a4b6871b--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/test.rs@@ -0,0 +1,166 @@+use super::PgAccessRepository;+use crate::domain::{models::AccessError, ports::AccessRepository};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;+use uuid::Uuid;++const TEAM_ALPHA: &str = "00000000-0000-0000-0000-0000000ea001";+const TEAM_BETA: &str = "00000000-0000-0000-0000-0000000ea002";+const TEAM_MEMBER: &str = "macro|[email protected]";+const USER_WITHOUT_TEAM: &str = "macro|[email protected]";++fn user_id(value: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(value.to_string()).unwrap()+}++async fn insert_foreign_entity(+ pool: &PgPool,+ id: Uuid,+ stored_for_id: &str,+ stored_for_auth_entity: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO foreign_entity (+ id,+ foreign_entity_id,+ foreign_entity_source,+ metadata,+ stored_for_id,+ stored_for_auth_entity+ )+ VALUES ($1, $2, $3, '{}'::jsonb, $4, $5)+ "#,+ id,+ format!("external-{id}"),+ "test-source",+ stored_for_id,+ stored_for_auth_entity,+ )+ .execute(pool)+ .await?;++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_team"))+)]+async fn grants_direct_user_access(pool: PgPool) -> anyhow::Result<()> {+ let foreign_entity_id = Uuid::new_v4();+ insert_foreign_entity(&pool, foreign_entity_id, USER_WITHOUT_TEAM, "user").await?;++ let repo = PgAccessRepository::new(pool);+ let user_id = user_id(USER_WITHOUT_TEAM);++ let has_access = repo+ .has_foreign_entity_access(&foreign_entity_id.to_string(), Some(&user_id))+ .await?;++ assert!(has_access);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_team"))+)]+async fn grants_team_access(pool: PgPool) -> anyhow::Result<()> {+ let foreign_entity_id = Uuid::new_v4();+ insert_foreign_entity(&pool, foreign_entity_id, TEAM_ALPHA, "team").await?;++ let repo = PgAccessRepository::new(pool);+ let user_id = user_id(TEAM_MEMBER);++ let has_access = repo+ .has_foreign_entity_access(&foreign_entity_id.to_string(), Some(&user_id))+ .await?;++ assert!(has_access);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_team"))+)]+async fn denies_unrelated_user_and_team_access(pool: PgPool) -> anyhow::Result<()> {+ let unrelated_user_entity_id = Uuid::new_v4();+ insert_foreign_entity(&pool, unrelated_user_entity_id, USER_WITHOUT_TEAM, "user").await?;++ let unrelated_team_entity_id = Uuid::new_v4();+ insert_foreign_entity(&pool, unrelated_team_entity_id, TEAM_BETA, "team").await?;++ let repo = PgAccessRepository::new(pool);+ let user_id = user_id(TEAM_MEMBER);++ let user_access = repo+ .has_foreign_entity_access(&unrelated_user_entity_id.to_string(), Some(&user_id))+ .await?;+ let team_access = repo+ .has_foreign_entity_access(&unrelated_team_entity_id.to_string(), Some(&user_id))+ .await?;++ assert!(!user_access);+ assert!(!team_access);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_team"))+)]+async fn denies_unauthenticated_access(pool: PgPool) -> anyhow::Result<()> {+ let foreign_entity_id = Uuid::new_v4();+ insert_foreign_entity(&pool, foreign_entity_id, USER_WITHOUT_TEAM, "user").await?;++ let repo = PgAccessRepository::new(pool);++ let has_access = repo+ .has_foreign_entity_access(&foreign_entity_id.to_string(), None)+ .await?;++ assert!(!has_access);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_team"))+)]+async fn denies_auth_namespace_mismatch(pool: PgPool) -> anyhow::Result<()> {+ let foreign_entity_id = Uuid::new_v4();+ insert_foreign_entity(&pool, foreign_entity_id, USER_WITHOUT_TEAM, "team").await?;++ let repo = PgAccessRepository::new(pool);+ let user_id = user_id(USER_WITHOUT_TEAM);++ let has_access = repo+ .has_foreign_entity_access(&foreign_entity_id.to_string(), Some(&user_id))+ .await?;++ assert!(!has_access);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_team"))+)]+async fn rejects_invalid_uuid(pool: PgPool) -> anyhow::Result<()> {+ let repo = PgAccessRepository::new(pool);+ let user_id = user_id(USER_WITHOUT_TEAM);++ let error = repo+ .has_foreign_entity_access("not-a-uuid", Some(&user_id))+ .await+ .expect_err("invalid UUID should be rejected");++ assert!(matches!(+ error,+ AccessError::BadRequest("Invalid foreign entity ID format")+ ));+ Ok(())+}