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
add get_users_by_entity to entity access service (#1836)
Will Hutchinsonf9b30f74eacd
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rsindex 4efcf2717c..e1a3d21c6f 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs@@ -18,6 +18,7 @@ use entity_access::domain::{ports::EntityAccessService,};use http_body_util::BodyExt;+use macro_user_id::user_id::MacroUserIdStr;use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};use model_user::UserContext;use models_pagination::{Base64Str, CreatedAt, Cursor, CursorVal, PaginateOn, Query};@@ -66,6 +67,14 @@ impl TestAccessService {}impl EntityAccessService for TestAccessService {+ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ unimplemented!()+ }+async fn generate_entity_access_receipt<T: RequiredPermission>(&self,_user_id: &MacroUserId<Lowercase<'_>>,diff --git a/rust/cloud-storage/entity_access/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json b/rust/cloud-storage/entity_access/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.jsonnew file mode 100644index 0000000000..03a8dbf6bb--- /dev/null+++ b/rust/cloud-storage/entity_access/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b"+}diff --git a/rust/cloud-storage/entity_access/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json b/rust/cloud-storage/entity_access/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.jsonnew file mode 100644index 0000000000..2bde15938f--- /dev/null+++ b/rust/cloud-storage/entity_access/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT project_id FROM project_hierarchy\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6"+}diff --git a/rust/cloud-storage/entity_access/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json b/rust/cloud-storage/entity_access/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.jsonnew file mode 100644index 0000000000..e42c9f2009--- /dev/null+++ b/rust/cloud-storage/entity_access/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0"+}diff --git a/rust/cloud-storage/entity_access/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json b/rust/cloud-storage/entity_access/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.jsonnew file mode 100644index 0000000000..4c96ff0fd5--- /dev/null+++ b/rust/cloud-storage/entity_access/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE etp.\"threadId\" = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f"+}diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rsindex 5c58be045c..b8b5d95bcf 100644--- a/rust/cloud-storage/entity_access/src/domain/ports.rs+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs@@ -7,7 +7,7 @@ use crate::domain::models::{AccessError, AccessLevel, ChannelRoleResult, EntityAccessReceipt, EntityPermission,RequiredPermission,};-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};use std::future::Future;use uuid::Uuid;@@ -77,6 +77,38 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {user_id: Option<&MacroUserId<Lowercase<'_>>>,user_org_id: Option<i64>,) -> impl Future<Output = Result<ChannelRoleResult, AccessError>> + Send;++ /// Get all user IDs with access to a document via `UserItemAccess`.+ ///+ /// Includes users with direct access and users with access through the project hierarchy.+ fn get_document_users(+ &self,+ document_id: &str,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, AccessError>> + Send;++ /// Get all user IDs with access to a chat via `UserItemAccess`.+ ///+ /// Includes users with direct access and users with access through the project hierarchy.+ fn get_chat_users(+ &self,+ chat_id: &str,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, AccessError>> + Send;++ /// Get all user IDs with access to a project via `UserItemAccess`.+ ///+ /// Includes users with direct access and users with access through the project hierarchy.+ fn get_project_users(+ &self,+ project_id: &str,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, AccessError>> + Send;++ /// Get all user IDs with access to an email thread via `UserItemAccess`.+ ///+ /// Includes users with direct access and users with access through the project hierarchy.+ fn get_thread_users(+ &self,+ thread_id: &str,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, AccessError>> + Send;}/// Service for checking entity access levels.@@ -141,4 +173,18 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {entity_type: EntityType,user_org_id: Option<i64>,) -> impl Future<Output = Result<EntityPermission, AccessError>> + Send;++ /// Get all user IDs that have access to a given entity via `UserItemAccess`.+ ///+ /// Returns user IDs with direct access to the entity or inherited access+ /// through the project hierarchy. Only considers `UserItemAccess` grants,+ /// not public share permissions.+ ///+ /// Supported entity types: Document, Chat, Project, EmailThread.+ /// Returns `AccessError::BadRequest` for unsupported types (Channel, Team, User).+ fn get_users_by_entity(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, AccessError>> + Send;}diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rsindex 4125a17dc7..8f24a850ec 100644--- a/rust/cloud-storage/entity_access/src/domain/service.rs+++ b/rust/cloud-storage/entity_access/src/domain/service.rs@@ -10,7 +10,9 @@ use crate::domain::{},ports::{AccessRepository, EntityAccessService},};-use macro_user_id::{cowlike::CowLike, lowercased::Lowercase, user_id::MacroUserId};+use macro_user_id::{+ cowlike::CowLike, lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr,+};use uuid::Uuid;/// Implementation of the [`EntityAccessService`].@@ -200,6 +202,23 @@ where_ => Err(AccessError::BadRequest("Unsupported entity type")),}}++ #[tracing::instrument(err, skip(self))]+ async fn get_users_by_entity(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ match entity_type {+ EntityType::Document => self.repo.get_document_users(entity_id).await,+ EntityType::Chat => self.repo.get_chat_users(entity_id).await,+ EntityType::Project => self.repo.get_project_users(entity_id).await,+ EntityType::EmailThread => self.repo.get_thread_users(entity_id).await,+ _ => Err(AccessError::BadRequest(+ "get_users_by_entity only supports Document, Chat, Project, and EmailThread",+ )),+ }+ }}#[cfg(test)]diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rsindex 158f51ef27..42f84229b8 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,10 @@ struct MockRepo {thread_access: Arc<Mutex<Option<AccessLevel>>>,channel_membership: Arc<Mutex<Vec<Uuid>>>,channel_role: Arc<Mutex<ChannelRoleResult>>,+ document_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,+ chat_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,+ project_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,+ thread_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,}impl MockRepo {@@ -30,6 +34,10 @@ impl MockRepo {thread_access: Arc::new(Mutex::new(None)),channel_membership: Arc::new(Mutex::new(vec![])),channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),+ document_users: Arc::new(Mutex::new(vec![])),+ chat_users: Arc::new(Mutex::new(vec![])),+ project_users: Arc::new(Mutex::new(vec![])),+ thread_users: Arc::new(Mutex::new(vec![])),}}@@ -62,6 +70,26 @@ impl MockRepo {self.channel_role = Arc::new(Mutex::new(result));self}++ fn with_document_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {+ self.document_users = Arc::new(Mutex::new(users));+ self+ }++ fn with_chat_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {+ self.chat_users = Arc::new(Mutex::new(users));+ self+ }++ fn with_project_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {+ self.project_users = Arc::new(Mutex::new(users));+ self+ }++ fn with_thread_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {+ self.thread_users = Arc::new(Mutex::new(users));+ self+ }}impl AccessRepository for MockRepo {@@ -113,12 +141,44 @@ impl AccessRepository for MockRepo {) -> Result<ChannelRoleResult, AccessError> {Ok(*self.channel_role.lock().await)}++ async fn get_document_users(+ &self,+ _document_id: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Ok(self.document_users.lock().await.clone())+ }++ async fn get_chat_users(+ &self,+ _chat_id: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Ok(self.chat_users.lock().await.clone())+ }++ async fn get_project_users(+ &self,+ _project_id: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Ok(self.project_users.lock().await.clone())+ }++ async fn get_thread_users(+ &self,+ _thread_id: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Ok(self.thread_users.lock().await.clone())+ }}fn test_user_id() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()}+fn user_id(s: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(s.to_string()).unwrap()+}+#[tokio::test]async fn test_get_document_access_returns_level_from_repo() {let repo = MockRepo::new().with_document_access(AccessLevel::Edit);@@ -826,3 +886,201 @@ async fn test_generate_receipt_unsupported_type_returns_bad_request() {assert!(matches!(result, Err(AccessError::BadRequest(_))));}++// --- get_users_by_entity tests ---++#[tokio::test]+async fn test_get_users_by_entity_document_returns_users() {+ let users = vec![+ user_id("macro|[email protected]"),+ user_id("macro|[email protected]"),+ ];+ let repo = MockRepo::new().with_document_users(users.clone());+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("doc-1", EntityType::Document)+ .await+ .unwrap();++ assert_eq!(result.len(), 2);+ assert_eq!(result[0].to_string(), "macro|[email protected]");+ assert_eq!(result[1].to_string(), "macro|[email protected]");+}++#[tokio::test]+async fn test_get_users_by_entity_document_returns_empty_when_no_users() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("doc-1", EntityType::Document)+ .await+ .unwrap();++ assert!(result.is_empty());+}++#[tokio::test]+async fn test_get_users_by_entity_chat_returns_users() {+ let users = vec![user_id("macro|[email protected]")];+ let repo = MockRepo::new().with_chat_users(users.clone());+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("chat-1", EntityType::Chat)+ .await+ .unwrap();++ assert_eq!(result.len(), 1);+ assert_eq!(result[0].to_string(), "macro|[email protected]");+}++#[tokio::test]+async fn test_get_users_by_entity_chat_returns_empty_when_no_users() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("chat-1", EntityType::Chat)+ .await+ .unwrap();++ assert!(result.is_empty());+}++#[tokio::test]+async fn test_get_users_by_entity_project_returns_users() {+ let users = vec![+ user_id("macro|[email protected]"),+ user_id("macro|[email protected]"),+ user_id("macro|[email protected]"),+ ];+ let repo = MockRepo::new().with_project_users(users.clone());+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("proj-1", EntityType::Project)+ .await+ .unwrap();++ assert_eq!(result.len(), 3);+ assert_eq!(result[0].to_string(), "macro|[email protected]");+ assert_eq!(result[1].to_string(), "macro|[email protected]");+ assert_eq!(result[2].to_string(), "macro|[email protected]");+}++#[tokio::test]+async fn test_get_users_by_entity_project_returns_empty_when_no_users() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("proj-1", EntityType::Project)+ .await+ .unwrap();++ assert!(result.is_empty());+}++#[tokio::test]+async fn test_get_users_by_entity_thread_returns_users() {+ let users = vec![+ user_id("macro|[email protected]"),+ user_id("macro|[email protected]"),+ ];+ let repo = MockRepo::new().with_thread_users(users.clone());+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("thread-1", EntityType::EmailThread)+ .await+ .unwrap();++ assert_eq!(result.len(), 2);+ assert_eq!(result[0].to_string(), "macro|[email protected]");+ assert_eq!(result[1].to_string(), "macro|[email protected]");+}++#[tokio::test]+async fn test_get_users_by_entity_thread_returns_empty_when_no_users() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("thread-1", EntityType::EmailThread)+ .await+ .unwrap();++ assert!(result.is_empty());+}++#[tokio::test]+async fn test_get_users_by_entity_channel_returns_bad_request() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("11111111-1111-1111-1111-111111111111", EntityType::Channel)+ .await;++ assert!(matches!(result, Err(AccessError::BadRequest(_))));+}++#[tokio::test]+async fn test_get_users_by_entity_team_returns_bad_request() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("team-1", EntityType::Team)+ .await;++ assert!(matches!(result, Err(AccessError::BadRequest(_))));+}++#[tokio::test]+async fn test_get_users_by_entity_user_returns_bad_request() {+ let repo = MockRepo::new();+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("user-1", EntityType::User)+ .await;++ assert!(matches!(result, Err(AccessError::BadRequest(_))));+}++#[tokio::test]+async fn test_get_users_by_entity_document_with_single_user() {+ let users = vec![user_id("macro|[email protected]")];+ let repo = MockRepo::new().with_document_users(users.clone());+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("doc-1", EntityType::Document)+ .await+ .unwrap();++ assert_eq!(result.len(), 1);+ assert_eq!(result[0].to_string(), "macro|[email protected]");+}++#[tokio::test]+async fn test_get_users_by_entity_project_with_many_users() {+ let users: Vec<MacroUserIdStr<'static>> = (0..50)+ .map(|i| user_id(&format!("macro|user{}@test.com", i)))+ .collect();+ let repo = MockRepo::new().with_project_users(users.clone());+ let service = EntityAccessServiceImpl::new(repo);++ let result = service+ .get_users_by_entity("proj-1", EntityType::Project)+ .await+ .unwrap();++ assert_eq!(result.len(), 50);+ for (i, u) in result.iter().enumerate() {+ assert_eq!(u.to_string(), format!("macro|user{}@test.com", i));+ }+}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 379d2f9139..92f14f2f4c 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@@ -6,10 +6,20 @@ use crate::domain::{models::{AccessError, AccessLevel, ChannelRoleResult},ports::AccessRepository,};-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};use sqlx::PgPool;use uuid::Uuid;+/// Convert a list of user ID strings from the database into typed [`MacroUserIdStr`] values.+///+/// Invalid user IDs are silently filtered out to avoid failing the entire query+/// due to a single malformed row.+fn parse_user_ids(raw: Vec<String>) -> Vec<MacroUserIdStr<'static>> {+ raw.into_iter()+ .filter_map(|s| MacroUserIdStr::try_from(s).ok())+ .collect()+}+/// PostgreSQL-backed implementation of [`AccessRepository`].////// Contains all SQL queries directly - no external crate dependencies.@@ -91,4 +101,40 @@ impl AccessRepository for PgAccessRepository {).await?)}++ #[tracing::instrument(err, skip(self))]+ async fn get_document_users(+ &self,+ document_id: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ let raw = queries::document_users::get_document_users(&self.pool, document_id).await?;+ Ok(parse_user_ids(raw))+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_chat_users(+ &self,+ chat_id: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ let raw = queries::chat_users::get_chat_users(&self.pool, chat_id).await?;+ Ok(parse_user_ids(raw))+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_project_users(+ &self,+ project_id: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ let raw = queries::project_users::get_project_users(&self.pool, project_id).await?;+ Ok(parse_user_ids(raw))+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_thread_users(+ &self,+ thread_id: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ let raw = queries::thread_users::get_thread_users(&self.pool, thread_id).await?;+ Ok(parse_user_ids(raw))+ }}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_users.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_users.rsnew file mode 100644index 0000000000..343359121e--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_users.rs@@ -0,0 +1,38 @@+//! Query for users with access to a chat via UserItemAccess.++use sqlx::PgPool;++/// Get all user IDs that have access to a chat via `UserItemAccess`.+///+/// Includes users with direct access to the chat and users with access+/// to any parent project in the hierarchy.+#[tracing::instrument(err, skip(pool))]+pub async fn get_chat_users(pool: &PgPool, chat_id: &str) -> Result<Vec<String>, sqlx::Error> {+ let users: Vec<String> = sqlx::query_scalar!(+ r#"+ WITH RECURSIVE project_hierarchy AS (+ SELECT p.id as project_id+ FROM "Chat" c+ JOIN "Project" p ON c."projectId" = p.id AND p."deletedAt" IS NULL+ WHERE c.id = $1 AND c."deletedAt" IS NULL+ UNION ALL+ SELECT parent.id as project_id+ FROM project_hierarchy ph+ JOIN "Project" parent ON parent.id = (+ SELECT "parentId" FROM "Project" WHERE id = ph.project_id AND "parentId" IS NOT NULL AND "deletedAt" IS NULL+ )+ )+ SELECT DISTINCT user_id FROM "UserItemAccess"+ WHERE item_id IN (+ SELECT $1+ UNION+ SELECT project_id FROM project_hierarchy+ )+ "#,+ chat_id+ )+ .fetch_all(pool)+ .await?;++ Ok(users)+}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_users.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_users.rsnew file mode 100644index 0000000000..6658b9e99a--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_users.rs@@ -0,0 +1,41 @@+//! Query for users with access to a document via UserItemAccess.++use sqlx::PgPool;++/// Get all user IDs that have access to a document via `UserItemAccess`.+///+/// Includes users with direct access to the document and users with access+/// to any parent project in the hierarchy.+#[tracing::instrument(err, skip(pool))]+pub async fn get_document_users(+ pool: &PgPool,+ document_id: &str,+) -> Result<Vec<String>, sqlx::Error> {+ let users: Vec<String> = sqlx::query_scalar!(+ r#"+ WITH RECURSIVE project_hierarchy AS (+ SELECT p.id as project_id+ FROM "Document" d+ JOIN "Project" p ON d."projectId" = p.id AND p."deletedAt" IS NULL+ WHERE d.id = $1 AND d."deletedAt" IS NULL+ UNION ALL+ SELECT parent.id as project_id+ FROM project_hierarchy ph+ JOIN "Project" parent ON parent.id = (+ SELECT "parentId" FROM "Project" WHERE id = ph.project_id AND "parentId" IS NOT NULL AND "deletedAt" IS NULL+ )+ )+ SELECT DISTINCT user_id FROM "UserItemAccess"+ WHERE item_id IN (+ SELECT $1+ UNION+ SELECT project_id FROM project_hierarchy+ )+ "#,+ document_id+ )+ .fetch_all(pool)+ .await?;++ Ok(users)+}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 a3a087e361..28d4928f60 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@@ -5,6 +5,10 @@pub mod channel_membership;pub mod channel_role;pub mod chat_access;+pub mod chat_users;pub mod document_access;+pub mod document_users;pub mod project_access;+pub mod project_users;pub mod thread_access;+pub mod thread_users;diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_users.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_users.rsnew file mode 100644index 0000000000..aa7df82a3c--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_users.rs@@ -0,0 +1,38 @@+//! Query for users with access to a project via UserItemAccess.++use sqlx::PgPool;++/// Get all user IDs that have access to a project via `UserItemAccess`.+///+/// Includes users with direct access to the project and users with access+/// to any parent project in the hierarchy.+#[tracing::instrument(err, skip(pool))]+pub async fn get_project_users(+ pool: &PgPool,+ project_id: &str,+) -> Result<Vec<String>, sqlx::Error> {+ let users: Vec<String> = sqlx::query_scalar!(+ r#"+ WITH RECURSIVE project_hierarchy AS (+ SELECT id as project_id+ FROM "Project"+ WHERE id = $1 AND "deletedAt" IS NULL+ UNION ALL+ SELECT parent.id as project_id+ FROM project_hierarchy ph+ JOIN "Project" parent ON parent.id = (+ SELECT "parentId" FROM "Project" WHERE id = ph.project_id AND "parentId" IS NOT NULL AND "deletedAt" IS NULL+ )+ )+ SELECT DISTINCT user_id FROM "UserItemAccess"+ WHERE item_id IN (+ SELECT project_id FROM project_hierarchy+ )+ "#,+ project_id+ )+ .fetch_all(pool)+ .await?;++ Ok(users)+}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_users.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_users.rsnew file mode 100644index 0000000000..9c1d5c6767--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_users.rs@@ -0,0 +1,38 @@+//! Query for users with access to an email thread via UserItemAccess.++use sqlx::PgPool;++/// Get all user IDs that have access to an email thread via `UserItemAccess`.+///+/// Includes users with direct access to the thread and users with access+/// to any parent project in the hierarchy.+#[tracing::instrument(err, skip(pool))]+pub async fn get_thread_users(pool: &PgPool, thread_id: &str) -> Result<Vec<String>, sqlx::Error> {+ let users: Vec<String> = sqlx::query_scalar!(+ r#"+ WITH RECURSIVE project_hierarchy AS (+ SELECT p.id as project_id+ FROM "EmailThreadPermission" etp+ JOIN "Project" p ON etp."projectId" = p.id AND p."deletedAt" IS NULL+ WHERE etp."threadId" = $1+ UNION ALL+ SELECT parent.id as project_id+ FROM project_hierarchy ph+ JOIN "Project" parent ON parent.id = (+ SELECT "parentId" FROM "Project" WHERE id = ph.project_id AND "parentId" IS NOT NULL AND "deletedAt" IS NULL+ )+ )+ SELECT DISTINCT user_id FROM "UserItemAccess"+ WHERE item_id IN (+ SELECT $1+ UNION+ SELECT project_id FROM project_hierarchy+ )+ "#,+ thread_id+ )+ .fetch_all(pool)+ .await?;++ Ok(users)+}