Skip to content

armgit / macro

Public Imported from GitHub
0

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

chore: hexify entity_access (#1001)

Eric Hayes6e40ea56d601
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 999d365cc1..d7e9163d84 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3285,6 +3285,30 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "entity_access"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "axum-extra",
+ "cool_asserts",
+ "macro_user_id",
+ "mockall",
+ "model",
+ "model-entity",
+ "model-error-response",
+ "model_user",
+ "models_permissions",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "equator"
version = "0.4.2"
@@ -8338,6 +8362,7 @@ dependencies = [
"native-tls",
"once_cell",
"percent-encoding",
+ "rustls 0.23.36",
"serde",
"serde_json",
"sha2",
@@ -8348,6 +8373,7 @@ dependencies = [
"tracing",
"url",
"uuid",
+ "webpki-roots 0.26.11",
]
[[package]]
@@ -9817,6 +9843,24 @@ dependencies = [
"libwebp-sys",
]
+[[package]]
+name = "webpki-roots"
+version = "0.26.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
+dependencies = [
+ "webpki-roots 1.0.5",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12bed680863276c63889429bfd6cab3b99943659923822de1c8a39c49e4d722c"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "weezl"
version = "0.1.12"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 00b43911b2..11e9ad1b49 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -36,6 +36,7 @@ members = [
"email_suppression_handler",
"email_utils",
"email_validator",
+ "entity_access",
"experiment_service",
"frecency",
"gmail_client",
diff --git a/rust/cloud-storage/entity_access/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json b/rust/cloud-storage/entity_access/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
new file mode 100644
index 0000000000..60bfee0647
--- /dev/null
+++ b/rust/cloud-storage/entity_access/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
@@ -0,0 +1,23 @@
+{
+ "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 access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95"
+}
diff --git a/rust/cloud-storage/entity_access/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json b/rust/cloud-storage/entity_access/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
new file mode 100644
index 0000000000..58618b2697
--- /dev/null
+++ b/rust/cloud-storage/entity_access/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n -- CTE to recursively find all parent projects, starting from the given project.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project ID provided.\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\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 -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n -- The hierarchy CTE includes the starting project, so this is all we need.\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n -- We only need to check ProjectPermission for the items in the hierarchy.\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b"
+}
diff --git a/rust/cloud-storage/entity_access/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json b/rust/cloud-storage/entity_access/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
new file mode 100644
index 0000000000..524cc25ec7
--- /dev/null
+++ b/rust/cloud-storage/entity_access/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
@@ -0,0 +1,23 @@
+{
+ "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 access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The chat itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be"
+}
diff --git a/rust/cloud-storage/entity_access/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json b/rust/cloud-storage/entity_access/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
new file mode 100644
index 0000000000..655495fb29
--- /dev/null
+++ b/rust/cloud-storage/entity_access/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT c.id\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a"
+}
diff --git a/rust/cloud-storage/entity_access/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json b/rust/cloud-storage/entity_access/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json
new file mode 100644
index 0000000000..2b67c5606d
--- /dev/null
+++ b/rust/cloud-storage/entity_access/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n -- CTE to recursively find all parent projects for the given email thread.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project directly associated with the thread.\n SELECT\n p.id as project_id\n FROM\n \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE\n etp.\"threadId\" = $1\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT\n parent.id as project_id\n FROM\n 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 -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The thread ID itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0"
+}
diff --git a/rust/cloud-storage/entity_access/Cargo.toml b/rust/cloud-storage/entity_access/Cargo.toml
new file mode 100644
index 0000000000..e905175d51
--- /dev/null
+++ b/rust/cloud-storage/entity_access/Cargo.toml
@@ -0,0 +1,51 @@
+[package]
+name = "entity_access"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[features]
+default = ["ports", "inbound", "outbound", "axum"]
+ports = ["dep:tokio"]
+inbound = ["axum", "ports"]
+outbound = ["ports"]
+axum = [
+ "dep:axum",
+ "dep:axum-extra",
+ "dep:model",
+ "dep:model_user",
+ "dep:model-error-response",
+]
+
+[dependencies]
+# Core
+anyhow = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+
+# Domain models (always included)
+models_permissions = { path = "../models_permissions" }
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity"}
+
+# Async runtime (for ports)
+tokio = { workspace = true, optional = true }
+
+# Axum dependencies (for inbound)
+axum = { workspace = true, optional = true }
+axum-extra = { workspace = true, optional = true }
+model = { path = "../model", optional = true }
+model_user = { path = "../model_user", optional = true, features = ["axum"] }
+model-error-response = { path = "../model-error-response", optional = true }
+
+# Database
+sqlx = { workspace = true }
+
+[dev-dependencies]
+mockall = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+cool_asserts = "2"
+sqlx = { workspace = true, features = ["runtime-tokio-rustls", "postgres"] }
diff --git a/rust/cloud-storage/entity_access/src/domain.rs b/rust/cloud-storage/entity_access/src/domain.rs
new file mode 100644
index 0000000000..732527f23b
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/domain.rs
@@ -0,0 +1,11 @@
+//! Domain layer for entity access.
+//!
+//! Contains models, ports (traits), and the service implementation.
+
+pub mod models;
+
+#[cfg(feature = "ports")]
+pub mod ports;
+
+#[cfg(feature = "ports")]
+pub mod service;
diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rs
new file mode 100644
index 0000000000..dfb11ccc3f
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/domain/models.rs
@@ -0,0 +1,28 @@
+//! Domain models for entity access.
+
+pub use model_entity::EntityType;
+pub use models_permissions::share_permission::access_level::AccessLevel;
+
+/// Errors that can occur during access checking.
+#[derive(Debug, thiserror::Error)]
+pub enum AccessError {
+ /// User does not have access to the requested resource.
+ #[error("User does not have access to the requested resource")]
+ Unauthorized,
+
+ /// User does not have access with a specific message.
+ #[error("{0}")]
+ UnauthorizedWithMessage(&'static str),
+
+ /// Database error during access check.
+ #[error("Database error: {0}")]
+ DatabaseError(#[from] sqlx::Error),
+
+ /// Bad request parameters.
+ #[error("Bad request: {0}")]
+ BadRequest(&'static str),
+
+ /// Internal server error.
+ #[error("Internal error")]
+ Internal,
+}
diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rs
new file mode 100644
index 0000000000..e137dffadb
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs
@@ -0,0 +1,91 @@
+//! Port definitions for entity access.
+//!
+//! These traits define the contracts that adapters must implement.
+
+use super::models::EntityType;
+use crate::domain::models::{AccessError, AccessLevel};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use std::future::Future;
+use uuid::Uuid;
+
+/// Repository for accessing entity permissions from the database.
+///
+/// This trait abstracts database operations for checking user access to entities.
+/// All methods query the database directly - no HTTP calls to external services.
+pub trait AccessRepository: Clone + Send + Sync + 'static {
+ /// Get the highest access level a user has for a document.
+ ///
+ /// Considers both explicit grants (UserItemAccess) and public access
+ /// (SharePermission) inherited through the project hierarchy.
+ fn get_document_access(
+ &self,
+ document_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
+ /// Get the highest access level a user has for a chat.
+ ///
+ /// Considers both explicit grants (UserItemAccess) and public access
+ /// (SharePermission) inherited through the project hierarchy.
+ fn get_chat_access(
+ &self,
+ chat_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
+ /// Get the highest access level a user has for a project.
+ ///
+ /// Considers both explicit grants (UserItemAccess) and public access
+ /// (SharePermission) inherited through the project hierarchy.
+ fn get_project_access(
+ &self,
+ project_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
+ /// Get the highest access level a user has for an email thread.
+ ///
+ /// Considers both explicit grants (UserItemAccess) and public access
+ /// (SharePermission) inherited through the project hierarchy.
+ fn get_thread_access(
+ &self,
+ thread_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, 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.
+ fn check_user_channel_membership(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ channel_ids: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<Uuid>, AccessError>> + Send;
+}
+
+/// Service for checking entity access levels.
+///
+/// This service orchestrates access checks using the repository.
+pub trait EntityAccessService: Clone + Send + Sync + 'static {
+ /// Get the access level a user has for an entity.
+ ///
+ /// Returns `None` if the user has no access to the entity.
+ fn get_access_level(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
+ /// Check if a user has at least the required access level for an entity.
+ ///
+ /// Returns the actual access level if access is granted.
+ /// Returns an error if the user does not have sufficient access.
+ fn check_access(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ required_level: AccessLevel,
+ ) -> impl Future<Output = Result<AccessLevel, AccessError>> + Send;
+}
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
new file mode 100644
index 0000000000..2a7669a93d
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -0,0 +1,118 @@
+//! Entity access service implementation.
+
+use crate::domain::{
+ models::{AccessError, AccessLevel, EntityType},
+ ports::{AccessRepository, EntityAccessService},
+};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use std::str::FromStr;
+use uuid::Uuid;
+
+/// Implementation of the [`EntityAccessService`].
+///
+/// This service orchestrates access checks by:
+/// 1. Delegating to [`AccessRepository`] for database queries
+/// 2. Applying business rules (owner always has access, etc.)
+#[derive(Clone)]
+pub struct EntityAccessServiceImpl<R> {
+ repo: R,
+}
+
+impl<R> EntityAccessServiceImpl<R>
+where
+ R: AccessRepository,
+{
+ /// Create a new entity access service.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+
+ /// Get access level for optimized entity types (document, chat, project, thread).
+ ///
+ /// These use the UserItemAccess table for efficient lookups.
+ async fn get_optimized_access(
+ &self,
+ entity_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ match entity_type {
+ EntityType::Document => self.repo.get_document_access(entity_id, user_id).await,
+ EntityType::Chat => self.repo.get_chat_access(entity_id, user_id).await,
+ EntityType::Project => self.repo.get_project_access(entity_id, user_id).await,
+ EntityType::EmailThread => self.repo.get_thread_access(entity_id, user_id).await,
+ _ => unreachable!("Only optimized types should call this method"),
+ }
+ }
+
+ /// Get access level for a channel.
+ ///
+ /// Channel access is binary - members get View access, non-members get None.
+ async fn get_channel_access(
+ &self,
+ channel_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ let channel_uuid = Uuid::from_str(channel_id)
+ .map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;
+
+ let user_channels = self
+ .repo
+ .check_user_channel_membership(user_id, &[channel_uuid])
+ .await?;
+
+ if user_channels.contains(&channel_uuid) {
+ Ok(Some(AccessLevel::View))
+ } else {
+ Ok(None)
+ }
+ }
+}
+
+impl<R> EntityAccessService for EntityAccessServiceImpl<R>
+where
+ R: AccessRepository,
+{
+ #[tracing::instrument(err, skip(self))]
+ async fn get_access_level(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ match entity_type {
+ EntityType::Document
+ | EntityType::Chat
+ | EntityType::Project
+ | EntityType::EmailThread => {
+ self.get_optimized_access(entity_id, user_id, entity_type)
+ .await
+ }
+ EntityType::Channel => self.get_channel_access(entity_id, user_id).await,
+ // These entity types don't have access checks implemented yet
+ EntityType::Email | EntityType::Team | EntityType::User => Ok(None),
+ }
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn check_access(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ let access_level = self
+ .get_access_level(user_id, entity_id, entity_type)
+ .await?;
+
+ match access_level {
+ Some(level) if level >= required_level => Ok(level),
+ Some(_) => Err(AccessError::Unauthorized),
+ None => Err(AccessError::Unauthorized),
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rs
new file mode 100644
index 0000000000..a65c984d63
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs
@@ -0,0 +1,261 @@
+//! Unit tests for the EntityAccessService.
+
+use super::*;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::Arc;
+use tokio::sync::Mutex;
+
+/// Mock repository for testing.
+#[derive(Clone)]
+struct MockRepo {
+ document_access: Arc<Mutex<Option<AccessLevel>>>,
+ chat_access: Arc<Mutex<Option<AccessLevel>>>,
+ project_access: Arc<Mutex<Option<AccessLevel>>>,
+ thread_access: Arc<Mutex<Option<AccessLevel>>>,
+ channel_membership: Arc<Mutex<Vec<Uuid>>>,
+}
+
+impl MockRepo {
+ fn new() -> Self {
+ Self {
+ document_access: Arc::new(Mutex::new(None)),
+ chat_access: Arc::new(Mutex::new(None)),
+ project_access: Arc::new(Mutex::new(None)),
+ thread_access: Arc::new(Mutex::new(None)),
+ channel_membership: Arc::new(Mutex::new(vec![])),
+ }
+ }
+
+ fn with_document_access(mut self, level: AccessLevel) -> Self {
+ self.document_access = Arc::new(Mutex::new(Some(level)));
+ self
+ }
+
+ fn with_chat_access(mut self, level: AccessLevel) -> Self {
+ self.chat_access = Arc::new(Mutex::new(Some(level)));
+ self
+ }
+
+ fn with_project_access(mut self, level: AccessLevel) -> Self {
+ self.project_access = Arc::new(Mutex::new(Some(level)));
+ self
+ }
+
+ fn with_thread_access(mut self, level: AccessLevel) -> Self {
+ self.thread_access = Arc::new(Mutex::new(Some(level)));
+ self
+ }
+
+ fn with_channel_membership(mut self, channels: Vec<Uuid>) -> Self {
+ self.channel_membership = Arc::new(Mutex::new(channels));
+ self
+ }
+}
+
+impl AccessRepository for MockRepo {
+ async fn get_document_access(
+ &self,
+ _document_id: &str,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(*self.document_access.lock().await)
+ }
+
+ async fn get_chat_access(
+ &self,
+ _chat_id: &str,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(*self.chat_access.lock().await)
+ }
+
+ async fn get_project_access(
+ &self,
+ _project_id: &str,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(*self.project_access.lock().await)
+ }
+
+ async fn get_thread_access(
+ &self,
+ _thread_id: &str,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(*self.thread_access.lock().await)
+ }
+
+ async fn check_user_channel_membership(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _channel_ids: &[Uuid],
+ ) -> Result<Vec<Uuid>, AccessError> {
+ Ok(self.channel_membership.lock().await.clone())
+ }
+}
+
+fn test_user_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()
+}
+
+#[tokio::test]
+async fn test_get_document_access_returns_level_from_repo() {
+ let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_access_level(&user_id, "doc-1", EntityType::Document)
+ .await;
+
+ assert_eq!(result.unwrap(), Some(AccessLevel::Edit));
+}
+
+#[tokio::test]
+async fn test_get_chat_access_returns_level_from_repo() {
+ let repo = MockRepo::new().with_chat_access(AccessLevel::View);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_access_level(&user_id, "chat-1", EntityType::Chat)
+ .await;
+
+ assert_eq!(result.unwrap(), Some(AccessLevel::View));
+}
+
+#[tokio::test]
+async fn test_get_project_access_returns_level_from_repo() {
+ let repo = MockRepo::new().with_project_access(AccessLevel::Owner);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_access_level(&user_id, "proj-1", EntityType::Project)
+ .await;
+
+ assert_eq!(result.unwrap(), Some(AccessLevel::Owner));
+}
+
+#[tokio::test]
+async fn test_get_thread_access_returns_level_from_repo() {
+ let repo = MockRepo::new().with_thread_access(AccessLevel::Comment);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_access_level(&user_id, "thread-1", EntityType::EmailThread)
+ .await;
+
+ assert_eq!(result.unwrap(), Some(AccessLevel::Comment));
+}
+
+#[tokio::test]
+async fn test_get_channel_access_for_member_returns_view() {
+ let channel_uuid: Uuid = "11111111-1111-1111-1111-111111111111".parse().unwrap();
+ let repo = MockRepo::new().with_channel_membership(vec![channel_uuid]);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_access_level(
+ &user_id,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await;
+
+ assert_eq!(result.unwrap(), Some(AccessLevel::View));
+}
+
+#[tokio::test]
+async fn test_get_channel_access_for_non_member_returns_none() {
+ let repo = MockRepo::new().with_channel_membership(vec![]);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_access_level(
+ &user_id,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await;
+
+ assert_eq!(result.unwrap(), None);
+}
+
+#[tokio::test]
+async fn test_get_channel_access_with_invalid_uuid_returns_error() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_access_level(&user_id, "not-a-uuid", EntityType::Channel)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::BadRequest(_))));
+}
+
+#[tokio::test]
+async fn test_check_access_sufficient_level_returns_actual_level() {
+ let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .check_access(&user_id, "doc-1", EntityType::Document, AccessLevel::View)
+ .await;
+
+ assert_eq!(result.unwrap(), AccessLevel::Edit);
+}
+
+#[tokio::test]
+async fn test_check_access_insufficient_level_returns_unauthorized() {
+ let repo = MockRepo::new().with_document_access(AccessLevel::View);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .check_access(&user_id, "doc-1", EntityType::Document, AccessLevel::Edit)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_check_access_no_access_returns_unauthorized() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .check_access(&user_id, "doc-1", EntityType::Document, AccessLevel::View)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_unsupported_entity_type_returns_none() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ // Email, Team, and User entity types don't have access checks implemented
+ let result = service
+ .get_access_level(&user_id, "email-1", EntityType::Email)
+ .await;
+ assert_eq!(result.unwrap(), None);
+
+ let result = service
+ .get_access_level(&user_id, "team-1", EntityType::Team)
+ .await;
+ assert_eq!(result.unwrap(), None);
+
+ let result = service
+ .get_access_level(&user_id, "user-1", EntityType::User)
+ .await;
+ assert_eq!(result.unwrap(), None);
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound.rs b/rust/cloud-storage/entity_access/src/inbound.rs
new file mode 100644
index 0000000000..eb8f744339
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound.rs
@@ -0,0 +1,6 @@
+//! Inbound adapters for entity access.
+//!
+//! These modules contain adapters for incoming requests, such as Axum extractors.
+
+#[cfg(feature = "axum")]
+pub mod axum_extractors;
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs
new file mode 100644
index 0000000000..535f9a8554
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs
@@ -0,0 +1,90 @@
+//! Chat access extractor.
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ Extension, RequestPartsExt, async_trait,
+ extract::{FromRef, FromRequestParts},
+ http::request::Parts,
+};
+
+use super::{ExtractorError, RequiredAccessLevel};
+use crate::domain::{
+ models::{AccessLevel, EntityType},
+ ports::EntityAccessService,
+};
+use model::chat::ChatBasic;
+use model_user::axum_extractor::MacroUserExtractor;
+
+/// Validates that the user has at least the required access level to a chat.
+///
+/// Type parameter `T` specifies the required access level.
+/// Type parameter `Svc` is the entity access service implementation.
+///
+/// # Prerequisites
+///
+/// - User must be authenticated (MacroUserExtractor in extensions)
+/// - Chat context must be loaded (ChatBasic in extensions)
+#[derive(Debug)]
+pub struct ChatAccessLevelExtractor<T, Svc> {
+ /// The actual access level the user has.
+ pub access_level: AccessLevel,
+ _marker: PhantomData<(T, Svc)>,
+}
+
+#[async_trait]
+impl<T, S, Svc> FromRequestParts<S> for ChatAccessLevelExtractor<T, Svc>
+where
+ T: RequiredAccessLevel,
+ 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 MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ let chat_context: Extension<ChatBasic> = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ // Owner always has full access
+ if chat_context.user_id == macro_user_id {
+ return Ok(Self {
+ access_level: AccessLevel::Owner,
+ _marker: PhantomData,
+ });
+ }
+
+ // Deleted items are only accessible by owner
+ if chat_context.deleted_at.is_some() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ // Check access via service
+ let required_level = T::required_level();
+ let access_level = service
+ .check_access(
+ &macro_user_id,
+ &chat_context.id,
+ EntityType::Chat,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ Ok(Self {
+ access_level,
+ _marker: PhantomData,
+ })
+ }
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs
new file mode 100644
index 0000000000..a2566aa326
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs
@@ -0,0 +1,92 @@
+//! Document access extractor.
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ Extension, RequestPartsExt, async_trait,
+ extract::{FromRef, FromRequestParts},
+ http::request::Parts,
+};
+
+use super::{ExtractorError, RequiredAccessLevel};
+use crate::domain::{
+ models::{AccessLevel, EntityType},
+ ports::EntityAccessService,
+};
+use model::document::DocumentBasic;
+use model_user::axum_extractor::MacroUserExtractor;
+
+/// Validates that the user has at least the required access level to a document.
+///
+/// Type parameter `T` specifies the required access level (ViewAccessLevel, EditAccessLevel, etc.)
+/// Type parameter `Svc` is the entity access service implementation.
+///
+/// # Prerequisites
+///
+/// - User must be authenticated (MacroUserExtractor in extensions)
+/// - Document context must be loaded (DocumentBasic in extensions)
+#[derive(Debug)]
+pub struct DocumentAccessExtractor<T, Svc> {
+ /// The actual access level the user has.
+ pub access_level: AccessLevel,
+ _marker: PhantomData<(T, Svc)>,
+}
+
+#[async_trait]
+impl<T, S, Svc> FromRequestParts<S> for DocumentAccessExtractor<T, Svc>
+where
+ T: RequiredAccessLevel,
+ 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 MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Unauthorized)?;
+
+ let document_context: Extension<DocumentBasic> = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ // Owner always has full access
+ if document_context.owner == macro_user_id {
+ return Ok(Self {
+ access_level: AccessLevel::Owner,
+ _marker: PhantomData,
+ });
+ }
+
+ // Deleted items are only accessible by owner
+ if document_context.deleted_at.is_some() {
+ return Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource",
+ ));
+ }
+
+ // Check access via service
+ let required_level = T::required_level();
+ let access_level = service
+ .check_access(
+ &macro_user_id,
+ &document_context.document_id,
+ EntityType::Document,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ Ok(Self {
+ access_level,
+ _marker: PhantomData,
+ })
+ }
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs
new file mode 100644
index 0000000000..bab468267c
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs
@@ -0,0 +1,79 @@
+//! History access extractor.
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ RequestPartsExt, async_trait,
+ extract::{FromRef, FromRequestParts, Path},
+ http::request::Parts,
+};
+
+use super::{ExtractorError, RequiredAccessLevel};
+use crate::domain::{
+ models::{AccessLevel, EntityType},
+ ports::EntityAccessService,
+};
+use model_user::axum_extractor::MacroUserExtractor;
+
+/// Path parameters for history routes.
+#[derive(serde::Deserialize)]
+pub struct HistoryParams {
+ /// The ID of the item.
+ pub item_id: String,
+ /// The type of item (e.g., "document", "chat").
+ pub item_type: String,
+}
+
+/// Validates the user has access to view the history of a particular item.
+///
+/// Extracts both item_id and item_type from the path parameters.
+#[derive(Clone, Debug)]
+pub struct HistoryAccessExtractor<T, Svc> {
+ /// The actual access level the user has.
+ pub access_level: AccessLevel,
+ _marker: PhantomData<(T, Svc)>,
+}
+
+#[async_trait]
+impl<T, S, Svc> FromRequestParts<S> for HistoryAccessExtractor<T, Svc>
+where
+ T: RequiredAccessLevel,
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = ExtractorError;
+
+ #[tracing::instrument(err, skip(parts, state))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let service = <Arc<Svc>>::from_ref(state);
+
+ let MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ let Path(HistoryParams { item_id, item_type }) =
+ <Path<HistoryParams>>::from_request_parts(parts, state)
+ .await
+ .map_err(|_| ExtractorError::BadRequest("Missing item_id or item_type in path"))?;
+
+ // Parse the item_type string into EntityType
+ let entity_type: EntityType = item_type
+ .parse()
+ .map_err(|_| ExtractorError::BadRequest("Invalid item_type"))?;
+
+ // Check access via service
+ let required_level = T::required_level();
+ let access_level = service
+ .check_access(&macro_user_id, &item_id, entity_type, required_level)
+ .await
+ .map_err(ExtractorError::from)?;
+
+ Ok(Self {
+ access_level,
+ _marker: PhantomData,
+ })
+ }
+}
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.rs
new file mode 100644
index 0000000000..f2ce993bc5
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
@@ -0,0 +1,112 @@
+//! Axum extractors for entity access control.
+//!
+//! These extractors validate that the requesting user has sufficient
+//! access to the entity being accessed.
+
+mod chat;
+mod document;
+mod history;
+mod project;
+mod thread;
+
+pub use chat::ChatAccessLevelExtractor;
+pub use document::DocumentAccessExtractor;
+pub use history::HistoryAccessExtractor;
+pub use project::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractor};
+pub use thread::ThreadAccessLevelExtractor;
+
+use crate::domain::models::{AccessError, AccessLevel};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use model_error_response::ErrorResponse;
+
+/// Trait to convert a unit struct marker into an [`AccessLevel`].
+///
+/// This allows extractors to be parameterized by required access level.
+/// Implement this for marker types like `ViewAccessLevel`, `EditAccessLevel`, etc.
+pub trait RequiredAccessLevel: std::fmt::Debug + Send + Sync + 'static {
+ /// Returns the access level this marker represents.
+ fn required_level() -> AccessLevel;
+}
+
+impl RequiredAccessLevel for models_permissions::share_permission::access_level::ViewAccessLevel {
+ fn required_level() -> AccessLevel {
+ AccessLevel::View
+ }
+}
+
+impl RequiredAccessLevel
+ for models_permissions::share_permission::access_level::CommentAccessLevel
+{
+ fn required_level() -> AccessLevel {
+ AccessLevel::Comment
+ }
+}
+
+impl RequiredAccessLevel for models_permissions::share_permission::access_level::EditAccessLevel {
+ fn required_level() -> AccessLevel {
+ AccessLevel::Edit
+ }
+}
+
+impl RequiredAccessLevel for models_permissions::share_permission::access_level::OwnerAccessLevel {
+ fn required_level() -> AccessLevel {
+ AccessLevel::Owner
+ }
+}
+
+/// Error type for access extractors that can be returned as HTTP responses.
+#[derive(Debug, thiserror::Error)]
+pub enum ExtractorError {
+ /// User does not have access to the requested resource.
+ #[error("User does not have access to the requested resource")]
+ Unauthorized,
+
+ /// User does not have access with a specific message.
+ #[error("{0}")]
+ UnauthorizedWithMessage(&'static str),
+
+ /// Bad request parameters.
+ #[error("Bad request: {0}")]
+ BadRequest(&'static str),
+
+ /// Internal server error.
+ #[error("Internal server error")]
+ Internal,
+
+ /// Database error.
+ #[error("Database error")]
+ Database,
+}
+
+impl From<AccessError> for ExtractorError {
+ fn from(err: AccessError) -> Self {
+ match err {
+ AccessError::Unauthorized => ExtractorError::Unauthorized,
+ AccessError::UnauthorizedWithMessage(msg) => {
+ ExtractorError::UnauthorizedWithMessage(msg)
+ }
+ AccessError::BadRequest(msg) => ExtractorError::BadRequest(msg),
+ AccessError::DatabaseError(_) => ExtractorError::Database,
+ AccessError::Internal => ExtractorError::Internal,
+ }
+ }
+}
+
+impl IntoResponse for ExtractorError {
+ fn into_response(self) -> Response {
+ let (status, message) = match &self {
+ ExtractorError::Unauthorized => (StatusCode::UNAUTHORIZED, self.to_string()),
+ ExtractorError::UnauthorizedWithMessage(_) => {
+ (StatusCode::UNAUTHORIZED, self.to_string())
+ }
+ ExtractorError::BadRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
+ ExtractorError::Internal | ExtractorError::Database => {
+ (StatusCode::INTERNAL_SERVER_ERROR, self.to_string())
+ }
+ };
+
+ let error_response = ErrorResponse { message: &message };
+ (status, axum::Json(error_response)).into_response()
+ }
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs
new file mode 100644
index 0000000000..dba83f7fc0
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs
@@ -0,0 +1,231 @@
+//! Project access extractors.
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ Extension, Json, RequestExt, RequestPartsExt, async_trait,
+ extract::{FromRef, FromRequest, FromRequestParts, Request},
+ http::request::Parts,
+};
+use serde::de::DeserializeOwned;
+
+use super::{ExtractorError, RequiredAccessLevel};
+use crate::domain::{
+ models::{AccessLevel, EntityType},
+ ports::EntityAccessService,
+};
+use model::project::BasicProject;
+use model_user::axum_extractor::MacroUserExtractor;
+
+/// Validates that the user has at least the required access level to a project.
+///
+/// Type parameter `T` specifies the required access level.
+/// Type parameter `Svc` is the entity access service implementation.
+///
+/// # Prerequisites
+///
+/// - User must be authenticated (MacroUserExtractor in extensions)
+/// - Project context must be loaded (BasicProject in extensions)
+#[derive(Debug)]
+pub struct ProjectAccessLevelExtractor<T, Svc> {
+ /// The actual access level the user has.
+ pub access_level: AccessLevel,
+ _marker: PhantomData<(T, Svc)>,
+}
+
+#[async_trait]
+impl<T, S, Svc> FromRequestParts<S> for ProjectAccessLevelExtractor<T, Svc>
+where
+ T: RequiredAccessLevel,
+ 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 MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ let project_context: Extension<BasicProject> = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ // Owner always has full access
+ if project_context.user_id == macro_user_id {
+ return Ok(Self {
+ access_level: AccessLevel::Owner,
+ _marker: PhantomData,
+ });
+ }
+
+ // Deleted items are only accessible by owner
+ if project_context.deleted_at.is_some() {
+ return Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource",
+ ));
+ }
+
+ // Check access via service
+ let required_level = T::required_level();
+ let access_level = service
+ .check_access(
+ &macro_user_id,
+ &project_context.id,
+ EntityType::Project,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ Ok(Self {
+ access_level,
+ _marker: PhantomData,
+ })
+ }
+}
+
+#[derive(Debug, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ProjectId {
+ project_id: String,
+}
+
+#[derive(Debug, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ProjectParentId {
+ project_parent_id: String,
+}
+
+/// Represents either a projectId or projectParentId from a request body.
+#[derive(Debug, serde::Deserialize)]
+#[serde(untagged)]
+pub enum ProjectOrParentId {
+ /// A direct project ID.
+ ProjectId(ProjectId),
+ /// A parent project ID.
+ Parent(ProjectParentId),
+}
+
+impl From<ProjectId> for ProjectOrParentId {
+ fn from(p: ProjectId) -> Self {
+ ProjectOrParentId::ProjectId(p)
+ }
+}
+
+impl From<ProjectParentId> for ProjectOrParentId {
+ fn from(p: ProjectParentId) -> Self {
+ ProjectOrParentId::Parent(p)
+ }
+}
+
+impl ProjectOrParentId {
+ /// Get the project ID string.
+ pub fn id(&self) -> &str {
+ match self {
+ ProjectOrParentId::ProjectId(project_id) => project_id.project_id.as_str(),
+ ProjectOrParentId::Parent(project_parent_id) => {
+ project_parent_id.project_parent_id.as_str()
+ }
+ }
+ }
+}
+
+/// Extractor which checks the body for a project and validates the access level if it exists.
+///
+/// Downstream consumers also use the body (which is an antipattern) so we need to keep the value around.
+#[derive(Debug)]
+pub enum ProjectBodyAccessLevelExtractor<T, V, Svc> {
+ /// A project was found in the body and access was validated.
+ FoundProject {
+ /// The project ID that was found.
+ project: ProjectOrParentId,
+ /// Marker for the desired access level.
+ desired: PhantomData<(T, Svc)>,
+ /// The actual access level the user has.
+ access_level: AccessLevel,
+ /// The parsed body.
+ body: V,
+ },
+ /// No project was found in the body.
+ ProjectNotInBody {
+ /// The parsed body.
+ body: V,
+ /// Marker for type parameters.
+ _marker: PhantomData<(T, Svc)>,
+ },
+}
+
+impl<T, V, Svc> ProjectBodyAccessLevelExtractor<T, V, Svc> {
+ /// Extract the body from this extractor.
+ pub fn into_inner(self) -> V {
+ match self {
+ ProjectBodyAccessLevelExtractor::FoundProject { body, .. } => body,
+ ProjectBodyAccessLevelExtractor::ProjectNotInBody { body, .. } => body,
+ }
+ }
+}
+
+#[async_trait]
+impl<T, S, V, Svc> FromRequest<S> for ProjectBodyAccessLevelExtractor<T, V, Svc>
+where
+ T: RequiredAccessLevel,
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ S: Send + Sync + 'static,
+ V: DeserializeOwned,
+{
+ type Rejection = ExtractorError;
+
+ async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> {
+ let service = <Arc<Svc>>::from_ref(state);
+
+ let MacroUserExtractor { macro_user_id, .. } = req
+ .extract_parts()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ let Json(json) = req
+ .extract::<Json<serde_json::Value>, _>()
+ .await
+ .map_err(|_| ExtractorError::BadRequest("Invalid JSON body"))?;
+
+ let json_clone = json.clone();
+ let cb = move || {
+ serde_json::from_value::<V>(json_clone)
+ .map_err(|_| ExtractorError::BadRequest("Invalid request body"))
+ };
+
+ let Ok(Some(project)) = serde_json::from_value::<Option<ProjectOrParentId>>(json) else {
+ return Ok(Self::ProjectNotInBody {
+ body: cb()?,
+ _marker: PhantomData,
+ });
+ };
+
+ let required_level = T::required_level();
+ let access_level = service
+ .check_access(
+ &macro_user_id,
+ project.id(),
+ EntityType::Project,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ Ok(Self::FoundProject {
+ access_level,
+ project,
+ desired: PhantomData,
+ body: cb()?,
+ })
+ }
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
new file mode 100644
index 0000000000..97b1ef3467
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
@@ -0,0 +1,77 @@
+//! Thread (email thread) access extractor.
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ Extension, RequestPartsExt, async_trait,
+ extract::{FromRef, FromRequestParts},
+ http::request::Parts,
+};
+
+use super::{ExtractorError, RequiredAccessLevel};
+use crate::domain::{
+ models::{AccessLevel, EntityType},
+ ports::EntityAccessService,
+};
+use model::thread::EmailThreadPermission;
+use model_user::axum_extractor::MacroUserExtractor;
+
+/// Validates that the user has at least the required access level to an email thread.
+///
+/// Type parameter `T` specifies the required access level.
+/// Type parameter `Svc` is the entity access service implementation.
+///
+/// # Prerequisites
+///
+/// - User context must be available (UserContext in extensions)
+/// - Thread context must be loaded (EmailThreadPermission in extensions)
+#[derive(Debug)]
+pub struct ThreadAccessLevelExtractor<T, Svc> {
+ /// The actual access level the user has.
+ pub access_level: AccessLevel,
+ _marker: PhantomData<(T, Svc)>,
+}
+
+#[async_trait]
+impl<T, S, Svc> FromRequestParts<S> for ThreadAccessLevelExtractor<T, Svc>
+where
+ T: RequiredAccessLevel,
+ 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 MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ let thread_context: Extension<EmailThreadPermission> = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ // Check access via service
+ let required_level = T::required_level();
+ let access_level = service
+ .check_access(
+ &macro_user_id,
+ &thread_context.thread_id,
+ EntityType::EmailThread,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ Ok(Self {
+ access_level,
+ _marker: PhantomData,
+ })
+ }
+}
diff --git a/rust/cloud-storage/entity_access/src/lib.rs b/rust/cloud-storage/entity_access/src/lib.rs
new file mode 100644
index 0000000000..4c4ba56c6a
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/lib.rs
@@ -0,0 +1,36 @@
+//! Entity access control for cloud storage.
+//!
+//! This crate provides a hexagonal architecture implementation for checking
+//! user access levels to various entities (documents, chats, projects, etc.).
+//!
+//! # Architecture
+//!
+//! - **domain**: Contains domain models, ports (traits), and the service implementation
+//! - **outbound**: Contains adapters for external dependencies (PostgreSQL)
+//! - **inbound**: Contains adapters for incoming requests (Axum extractors)
+//!
+//! # Usage
+//!
+//! ```ignore
+//! use entity_access::{
+//! domain::{ports::EntityAccessService, service::EntityAccessServiceImpl},
+//! outbound::PgAccessRepository,
+//! };
+//!
+//! let pool: sqlx::PgPool = /* ... */;
+//! let repo = PgAccessRepository::new(pool);
+//! let service = EntityAccessServiceImpl::new(repo);
+//!
+//! // Check access
+//! let access = service.get_access_level("user-id", "doc-id", EntityType::Document).await?;
+//! ```
+
+#![deny(missing_docs)]
+
+pub mod domain;
+
+#[cfg(feature = "inbound")]
+pub mod inbound;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/entity_access/src/outbound.rs b/rust/cloud-storage/entity_access/src/outbound.rs
new file mode 100644
index 0000000000..0e7bd3cfbf
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound.rs
@@ -0,0 +1,7 @@
+//! Outbound adapters for entity access.
+//!
+//! These modules contain concrete implementations of the domain ports.
+
+mod pg_access_repo;
+
+pub use pg_access_repo::PgAccessRepository;
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
new file mode 100644
index 0000000000..bf0b901872
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
@@ -0,0 +1,78 @@
+//! PostgreSQL implementation of the AccessRepository trait.
+
+mod queries;
+
+use crate::domain::{
+ models::{AccessError, AccessLevel},
+ ports::AccessRepository,
+};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// PostgreSQL-backed implementation of [`AccessRepository`].
+///
+/// Contains all SQL queries directly - no external crate dependencies.
+#[derive(Clone)]
+pub struct PgAccessRepository {
+ pool: PgPool,
+}
+
+impl PgAccessRepository {
+ /// Create a new PostgreSQL access repository.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl AccessRepository for PgAccessRepository {
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document_access(
+ &self,
+ document_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(queries::document_access::get_document_access(&self.pool, document_id, user_id).await?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_chat_access(
+ &self,
+ chat_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(queries::chat_access::get_chat_access(&self.pool, chat_id, user_id).await?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_project_access(
+ &self,
+ project_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(queries::project_access::get_project_access(&self.pool, project_id, user_id).await?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_thread_access(
+ &self,
+ thread_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(queries::thread_access::get_thread_access(&self.pool, thread_id, user_id).await?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn check_user_channel_membership(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ channel_ids: &[Uuid],
+ ) -> Result<Vec<Uuid>, AccessError> {
+ Ok(queries::channel_membership::check_user_channel_membership(
+ &self.pool,
+ user_id,
+ channel_ids,
+ )
+ .await?)
+ }
+}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_membership.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_membership.rs
new file mode 100644
index 0000000000..e7b9593010
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_membership.rs
@@ -0,0 +1,32 @@
+//! Query for channel membership check.
+
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// Check if a user is a member of the specified channels.
+///
+/// Returns the subset of channel_ids that the user is a participant of.
+#[tracing::instrument(err, skip(pool))]
+pub async fn check_user_channel_membership(
+ pool: &PgPool,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ channel_ids: &[Uuid],
+) -> Result<Vec<Uuid>, sqlx::Error> {
+ let user_id = user_id.as_ref();
+ let channels = sqlx::query_scalar!(
+ r#"
+ SELECT c.id
+ FROM comms_channels c
+ INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id
+ WHERE cp.user_id = $1 AND cp.left_at IS NULL
+ AND c.id = ANY($2::uuid[])
+ "#,
+ user_id,
+ channel_ids
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(channels)
+}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs
new file mode 100644
index 0000000000..938f31177b
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs
@@ -0,0 +1,64 @@
+//! Query for chat access level.
+
+use crate::domain::models::AccessLevel;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use std::str::FromStr;
+
+/// Get the highest access level a user has for a chat.
+///
+/// Considers both explicit grants (UserItemAccess) and public access
+/// (SharePermission) inherited through the project hierarchy.
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_chat_access(
+ pool: &PgPool,
+ chat_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ let user_id = user_id.as_ref();
+ let all_level_strings: Vec<Option<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 access_level FROM (
+ -- Source 1: Cast the AccessLevel enum to text.
+ SELECT access_level::text FROM "UserItemAccess"
+ WHERE user_id = $2 AND item_id IN (
+ SELECT $1 -- The chat itself
+ UNION
+ SELECT project_id FROM project_hierarchy -- All parent projects
+ )
+ UNION ALL
+ -- Source 2: Select the publicAccessLevel (which is already text).
+ SELECT "publicAccessLevel" as access_level
+ FROM "SharePermission"
+ WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (
+ SELECT "sharePermissionId" FROM "ChatPermission" WHERE "chatId" = $1
+ UNION
+ SELECT "sharePermissionId" FROM "ProjectPermission" WHERE "projectId" IN (SELECT project_id FROM project_hierarchy)
+ )
+ ) as all_levels
+ "#,
+ chat_id,
+ user_id
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let highest_level = all_level_strings
+ .iter()
+ .filter_map(|opt| opt.as_ref().and_then(|s| AccessLevel::from_str(s).ok()))
+ .max();
+
+ Ok(highest_level)
+}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
new file mode 100644
index 0000000000..9089ddc830
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
@@ -0,0 +1,64 @@
+//! Query for document access level.
+
+use crate::domain::models::AccessLevel;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use std::str::FromStr;
+
+/// Get the highest access level a user has for a document.
+///
+/// Considers both explicit grants (UserItemAccess) and public access
+/// (SharePermission) inherited through the project hierarchy.
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_document_access(
+ pool: &PgPool,
+ document_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ let user_id = user_id.as_ref();
+ let all_level_strings: Vec<Option<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 access_level FROM (
+ -- Source 1: Cast the AccessLevel enum to text.
+ SELECT access_level::text FROM "UserItemAccess"
+ WHERE user_id = $2 AND item_id IN (
+ SELECT $1
+ UNION
+ SELECT project_id FROM project_hierarchy
+ )
+ UNION ALL
+ -- Source 2: Select the publicAccessLevel (which is already text).
+ SELECT "publicAccessLevel" as access_level
+ FROM "SharePermission"
+ WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (
+ SELECT "sharePermissionId" FROM "DocumentPermission" WHERE "documentId" = $1
+ UNION
+ SELECT "sharePermissionId" FROM "ProjectPermission" WHERE "projectId" IN (SELECT project_id FROM project_hierarchy)
+ )
+ ) as all_levels
+ "#,
+ document_id,
+ user_id
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let highest_level = all_level_strings
+ .iter()
+ .filter_map(|opt| opt.as_ref().and_then(|s| AccessLevel::from_str(s).ok()))
+ .max();
+
+ Ok(highest_level)
+}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs
new file mode 100644
index 0000000000..0e27fa840a
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs
@@ -0,0 +1,9 @@
+//! SQL query functions for entity access checks.
+//!
+//! Each module contains a single query function for checking access to a specific entity type.
+
+pub mod channel_membership;
+pub mod chat_access;
+pub mod document_access;
+pub mod project_access;
+pub mod thread_access;
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_access.rs
new file mode 100644
index 0000000000..54d7d43711
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_access.rs
@@ -0,0 +1,66 @@
+//! Query for project access level.
+
+use crate::domain::models::AccessLevel;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use std::str::FromStr;
+
+/// Get the highest access level a user has for a project.
+///
+/// Considers both explicit grants (UserItemAccess) and public access
+/// (SharePermission) inherited through the project hierarchy.
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_project_access(
+ pool: &PgPool,
+ project_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ let user_id = user_id.as_ref();
+ let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(
+ r#"
+ -- CTE to recursively find all parent projects, starting from the given project.
+ WITH RECURSIVE project_hierarchy AS (
+ -- Base case: Start with the project ID provided.
+ SELECT id as project_id
+ FROM "Project"
+ WHERE id = $1 AND "deletedAt" IS NULL
+ UNION ALL
+ -- Recursive case: Find the parent of the project from the previous step.
+ 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
+ )
+ )
+ -- The subquery now gathers all levels as plain text.
+ SELECT access_level FROM (
+ -- Source 1: Cast the AccessLevel enum to text.
+ SELECT access_level::text FROM "UserItemAccess"
+ WHERE user_id = $2 AND item_id IN (
+ -- The hierarchy CTE includes the starting project, so this is all we need.
+ SELECT project_id FROM project_hierarchy
+ )
+ UNION ALL
+ -- Source 2: Select the publicAccessLevel (which is already text).
+ SELECT "publicAccessLevel" as access_level
+ FROM "SharePermission"
+ WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (
+ -- We only need to check ProjectPermission for the items in the hierarchy.
+ SELECT "sharePermissionId" FROM "ProjectPermission"
+ WHERE "projectId" IN (SELECT project_id FROM project_hierarchy)
+ )
+ ) as all_levels
+ "#,
+ project_id,
+ user_id
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let highest_level = all_level_strings
+ .iter()
+ .filter_map(|opt| opt.as_ref().and_then(|s| AccessLevel::from_str(s).ok()))
+ .max();
+
+ Ok(highest_level)
+}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
new file mode 100644
index 0000000000..a1f4eabeb6
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
@@ -0,0 +1,73 @@
+//! Query for email thread access level.
+
+use crate::domain::models::AccessLevel;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use std::str::FromStr;
+
+/// Get the highest access level a user has for an email thread.
+///
+/// Considers both explicit grants (UserItemAccess) and public access
+/// (SharePermission) inherited through the project hierarchy.
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_thread_access(
+ pool: &PgPool,
+ thread_id: &str,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ let user_id = user_id.as_ref();
+ let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(
+ r#"
+ -- CTE to recursively find all parent projects for the given email thread.
+ WITH RECURSIVE project_hierarchy AS (
+ -- Base case: Start with the project directly associated with the thread.
+ 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
+ -- Recursive case: Find the parent of the project from the previous step.
+ 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
+ )
+ )
+ -- The subquery now gathers all levels as plain text.
+ SELECT access_level FROM (
+ -- Source 1: Cast the AccessLevel enum to text.
+ SELECT access_level::text FROM "UserItemAccess"
+ WHERE user_id = $2 AND item_id IN (
+ SELECT $1 -- The thread ID itself
+ UNION
+ SELECT project_id FROM project_hierarchy -- All parent projects
+ )
+ UNION ALL
+ -- Source 2: Select the publicAccessLevel (which is already text).
+ SELECT "publicAccessLevel" as access_level
+ FROM "SharePermission"
+ WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (
+ SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $1
+ UNION
+ SELECT "sharePermissionId" FROM "ProjectPermission" WHERE "projectId" IN (SELECT project_id FROM project_hierarchy)
+ )
+ ) as all_levels
+ "#,
+ thread_id,
+ user_id
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let highest_level = all_level_strings
+ .iter()
+ .filter_map(|opt| opt.as_ref().and_then(|s| AccessLevel::from_str(s).ok()))
+ .max();
+
+ Ok(highest_level)
+}
diff --git a/rust/cloud-storage/models_properties/src/shared/entity_type.rs b/rust/cloud-storage/models_properties/src/shared/entity_type.rs
index e946410e6e..3f01a88780 100644
--- a/rust/cloud-storage/models_properties/src/shared/entity_type.rs
+++ b/rust/cloud-storage/models_properties/src/shared/entity_type.rs
@@ -1,7 +1,7 @@
//! Entity type shared across database, service, and API layers.
use serde::{Deserialize, Serialize};
-use std::fmt;
+use std::{fmt, str::FromStr};
use utoipa::ToSchema;
/// Type of entity that can be referenced by entity properties.
@@ -36,3 +36,24 @@ impl fmt::Display for EntityType {
}
}
}
+
+#[derive(Debug, Clone, thiserror::Error)]
+#[error("No conversion from {0}")]
+pub struct NoConversion(pub String);
+
+impl FromStr for EntityType {
+ type Err = NoConversion;
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.to_lowercase().as_str() {
+ "channel" => Ok(Self::Channel),
+ "chat" => Ok(Self::Chat),
+ "company" => Ok(Self::Company),
+ "document" => Ok(Self::Document),
+ "project" => Ok(Self::Project),
+ "task" => Ok(Self::Task),
+ "thread" => Ok(Self::Thread),
+ "user" => Ok(Self::User),
+ other => Err(NoConversion(other.to_owned())),
+ }
+ }
+}