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
fix(email): Attachment sharing (#1489)
Evan Hutnik57f5451a5622
diff --git a/js/app/packages/core/component/AI/signal/attachment.ts b/js/app/packages/core/component/AI/signal/attachment.tsindex 9d33254211..2a3b4573a6 100644--- a/js/app/packages/core/component/AI/signal/attachment.ts+++ b/js/app/packages/core/component/AI/signal/attachment.ts@@ -136,7 +136,7 @@ export const useGetChatAttachmentInfo = () => {return getDocumentAttachment(mention.itemId);} else if (mention.itemType === 'channel') {return getChannelAttachment(mention);- } else if (mention.itemType === 'email') {+ } else if (mention.itemType === 'thread') {return getEmailAttachment(mention);} else if (mention.itemType === 'project') {return getProjectAttachment(mention.itemId);diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex 182b7c62ec..533caf6a05 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -117,7 +117,7 @@ export type ItemMention = {| 'rss'| 'contact'| 'date'- | 'email'+ | 'thread'| 'unknown'| 'color'| 'group';@@ -172,7 +172,7 @@ export function $mentionItemFromNode(node: MentionNode): ItemMention {fileType = 'rss';} else if (blockName === 'email') {fileType = 'email';- itemType = 'email';+ itemType = 'thread';} else if (blockName === 'unknown') {fileType = 'unknown';}@@ -246,8 +246,9 @@ const getDocumentMentionItemType = (case 'chat':case 'channel':case 'project':- case 'email':return itemType;+ case 'email':+ return 'thread';default:console.error(`Invalid item type: ${itemType} for document mention node`);return 'document';@@ -679,7 +680,7 @@ function registerMentionsPlugin(fileType = 'unknown';}onCreateMention({- itemType: blockName === 'email' ? 'email' : itemType,+ itemType: blockName === 'email' ? 'thread' : itemType,itemId: node.getDocumentId(),fileType,documentName,diff --git a/rust/cloud-storage/document_storage_service/justfile b/rust/cloud-storage/document_storage_service/justfileindex 8663436991..d018e9a2db 100644--- a/rust/cloud-storage/document_storage_service/justfile+++ b/rust/cloud-storage/document_storage_service/justfile@@ -10,8 +10,5 @@ mod ci '../ci.just'deploy-dev:just ci::deploy-dev document-storage-service-run: ensure::ensure_dynamodb- cargo run -F local-check:SQLX_OFFLINE=true cargo checkdiff --git a/rust/cloud-storage/email_db_client/.sqlx/query-3c570d90cccdcc4d4546ecd377500c4882b1c7fb6c56e822cc4dfb8d4191dce4.json b/rust/cloud-storage/email_db_client/.sqlx/query-3c570d90cccdcc4d4546ecd377500c4882b1c7fb6c56e822cc4dfb8d4191dce4.jsonnew file mode 100644index 0000000000..c910776c50--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-3c570d90cccdcc4d4546ecd377500c4882b1c7fb6c56e822cc4dfb8d4191dce4.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT et.id as thread_id, et.link_id\n FROM email_attachments ea\n INNER JOIN email_messages em ON ea.message_id = em.id\n INNER JOIN email_threads et ON em.thread_id = et.id\n WHERE ea.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "link_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "3c570d90cccdcc4d4546ecd377500c4882b1c7fb6c56e822cc4dfb8d4191dce4"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-b3bb26f4b163d8bea13a5a3fb0ea3d89543ceaefae74f8962e4504196d0b76c2.json b/rust/cloud-storage/email_db_client/.sqlx/query-b3bb26f4b163d8bea13a5a3fb0ea3d89543ceaefae74f8962e4504196d0b76c2.jsonnew file mode 100644index 0000000000..3a0d508069--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-b3bb26f4b163d8bea13a5a3fb0ea3d89543ceaefae74f8962e4504196d0b76c2.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT document_id\n FROM document_email de\n INNER JOIN \"Document\" d on de.document_id = d.id\n INNER JOIN email_attachments ea on de.email_attachment_id = ea.id\n INNER JOIN email_messages em on ea.message_id = em.id\n WHERE email_attachment_id = $1 AND d.\"deletedAt\" IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b3bb26f4b163d8bea13a5a3fb0ea3d89543ceaefae74f8962e4504196d0b76c2"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-b3cccb591b27205ca6ed2b1575606e62d2f22b14691b9c428438b9452cae83da.json b/rust/cloud-storage/email_db_client/.sqlx/query-be835e7de49553e947e0d265f8f681321d099febed2ed002dac6d706bf4ec173.jsonsimilarity index 92%rename from rust/cloud-storage/email_db_client/.sqlx/query-b3cccb591b27205ca6ed2b1575606e62d2f22b14691b9c428438b9452cae83da.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-be835e7de49553e947e0d265f8f681321d099febed2ed002dac6d706bf4ec173.jsonindex f4e2b838a6..902514760f 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-b3cccb591b27205ca6ed2b1575606e62d2f22b14691b9c428438b9452cae83da.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-be835e7de49553e947e0d265f8f681321d099febed2ed002dac6d706bf4ec173.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n a.id AS attachment_db_id,\n m.provider_id as \"email_provider_id!\",\n a.provider_attachment_id as \"provider_attachment_id!\",\n a.filename as \"filename?\",\n a.mime_type as \"mime_type!\",\n m.internal_date_ts as \"internal_date_ts!\",\n m.id as message_db_id,\n m.thread_id as thread_db_id,\n from_contact.email_address as sender_email,\n m.subject as subject\n FROM email_attachments a\n JOIN email_messages m ON a.message_id = m.id\n JOIN email_contacts from_contact ON m.from_contact_id = from_contact.id\n JOIN email_threads t ON m.thread_id = t.id\n WHERE a.id = $1 AND t.link_id = $2\n ",+ "query": "\n SELECT\n a.id AS attachment_db_id,\n m.provider_id as \"email_provider_id!\",\n a.provider_attachment_id as \"provider_attachment_id!\",\n a.filename as \"filename?\",\n a.mime_type as \"mime_type!\",\n m.internal_date_ts as \"internal_date_ts!\",\n m.id as message_db_id,\n m.thread_id as thread_db_id,\n from_contact.email_address as sender_email,\n m.subject as subject\n FROM email_attachments a\n JOIN email_messages m ON a.message_id = m.id\n JOIN email_contacts from_contact ON m.from_contact_id = from_contact.id\n JOIN email_threads t ON m.thread_id = t.id\n WHERE a.id = $1\n ","describe": {"columns": [{@@ -56,7 +56,6 @@],"parameters": {"Left": [- "Uuid","Uuid"]},@@ -73,5 +72,5 @@true]},- "hash": "b3cccb591b27205ca6ed2b1575606e62d2f22b14691b9c428438b9452cae83da"+ "hash": "be835e7de49553e947e0d265f8f681321d099febed2ed002dac6d706bf4ec173"}diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rsindex 010c79e6b4..4cdc632778 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs@@ -335,7 +335,7 @@ pub async fn get_attachments_by_thread_ids(/// Get document_id for email attachment if record exists#[tracing::instrument(skip(db), err)]-pub async fn get_document_id_by_attachment_id(+pub async fn get_document_id_by_att_id_and_link(db: &Pool<Postgres>,link_id: Uuid,email_attachment_id: Uuid,@@ -357,3 +357,49 @@ pub async fn get_document_id_by_attachment_id(Ok(result.map(|record| record.document_id))}++/// Get document_id for email attachment if record exists+#[tracing::instrument(skip(db), err)]+pub async fn get_document_id_by_att_id(+ db: &Pool<Postgres>,+ email_attachment_id: Uuid,+) -> anyhow::Result<Option<String>> {+ let result = sqlx::query!(+ r#"+ SELECT document_id+ FROM document_email de+ INNER JOIN "Document" d on de.document_id = d.id+ INNER JOIN email_attachments ea on de.email_attachment_id = ea.id+ INNER JOIN email_messages em on ea.message_id = em.id+ WHERE email_attachment_id = $1 AND d."deletedAt" IS NULL+ "#,+ email_attachment_id,+ )+ .fetch_optional(db)+ .await?;++ Ok(result.map(|record| record.document_id))+}++/// Get thread_id and link_id for an email attachment+#[tracing::instrument(skip(db), err)]+pub async fn get_thread_id_for_attachment(+ db: &Pool<Postgres>,+ attachment_id: Uuid,+) -> anyhow::Result<Option<(Uuid, Uuid)>> {+ let result = sqlx::query!(+ r#"+ SELECT et.id as thread_id, et.link_id+ FROM email_attachments ea+ INNER JOIN email_messages em ON ea.message_id = em.id+ INNER JOIN email_threads et ON em.thread_id = et.id+ WHERE ea.id = $1+ "#,+ attachment_id,+ )+ .fetch_optional(db)+ .await+ .with_context(|| format!("Failed to fetch thread_id for attachment {}", attachment_id))?;++ Ok(result.map(|record| (record.thread_id, record.link_id)))+}diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rsindex 6b52fd331c..661517898e 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs@@ -472,7 +472,6 @@ pub async fn new_email_media_atts(pub async fn fetch_attachment_upload_metadata_by_id(db: &Pool<Postgres>,- link_id: Uuid,attachment_id: Uuid,) -> anyhow::Result<Option<AttachmentUploadMetadata>> {let row = sqlx::query_as!(@@ -493,10 +492,9 @@ pub async fn fetch_attachment_upload_metadata_by_id(JOIN email_messages m ON a.message_id = m.idJOIN email_contacts from_contact ON m.from_contact_id = from_contact.idJOIN email_threads t ON m.thread_id = t.id- WHERE a.id = $1 AND t.link_id = $2+ WHERE a.id = $1"#,- attachment_id,- link_id+ attachment_id).fetch_optional(db).await?;diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rsindex f635fd5ab4..434da606f9 100644--- a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs@@ -3,6 +3,7 @@ use axum::extract::{Path, State};use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::{Extension, Json};+use email_service::util::gmail::auth::fetch_gmail_access_token_from_link;use email_service::util::upload_attachment::{UploadAttachmentContext, UploadAttachmentError, upload_attachment,};@@ -10,6 +11,7 @@ use model::response::ErrorResponse;use models_email::db::address::EmailRecipientType;use models_email::email::service::link::Link;use models_email::service::attachment::{AttachmentUploadArgs, AttachmentUploadDestination};+use std::time::Duration;use strum_macros::AsRefStr;use thiserror::Error;use utoipa::ToSchema;@@ -20,6 +22,9 @@ pub enum GetAttachmentDocumentIdError {#[error("Attachment not found")]AttachmentNotFound,+ #[error("Access denied")]+ AccessDenied,+#[error("Database error occurred")]DatabaseError(anyhow::Error),@@ -31,6 +36,7 @@ impl IntoResponse for GetAttachmentDocumentIdError {fn into_response(self) -> Response {let status_code = match &self {GetAttachmentDocumentIdError::AttachmentNotFound => StatusCode::NOT_FOUND,+ GetAttachmentDocumentIdError::AccessDenied => StatusCode::FORBIDDEN,GetAttachmentDocumentIdError::DatabaseError(_)| GetAttachmentDocumentIdError::UploadError(_) => StatusCode::INTERNAL_SERVER_ERROR,};@@ -63,35 +69,121 @@ pub struct GetAttachmentDocumentIDResponse {(status = 500, body = ErrorResponse),))]-#[tracing::instrument(skip(ctx))]+#[tracing::instrument(skip(ctx), err)]pub async fn handler(State(ctx): State<ApiContext>,link: Extension<Link>,gmail_token: Extension<String>,Path(attachment_id): Path<Uuid>,) -> Result<Json<GetAttachmentDocumentIDResponse>, GetAttachmentDocumentIdError> {- // return ID if attachment already exists in Macro- let existing_document_id =- email_db_client::attachments::provider::get_document_id_by_attachment_id(- &ctx.db,- link.id,+ // Fast path: return ID if attachment already exists in Macro+ if let Some(document_id) =+ email_db_client::attachments::provider::get_document_id_by_att_id(&ctx.db, attachment_id)+ .await+ .map_err(GetAttachmentDocumentIdError::DatabaseError)?+ {+ return Ok(Json(GetAttachmentDocumentIDResponse {attachment_id,- )+ document_id,+ }));+ }++ // Acquire a distributed lock to prevent duplicate uploads of the same attachment+ let lock_key = format!("attachment_upload:{}", attachment_id);+ let _lock = ctx+ .redis_client+ .acquire_lock(&lock_key, Duration::from_secs(60), Duration::from_secs(30)).await- .map_err(GetAttachmentDocumentIdError::DatabaseError)?;+ .map_err(|e| GetAttachmentDocumentIdError::DatabaseError(e.into()))?;- if let Some(document_id) = existing_document_id {+ // Re-check after acquiring lock — another request may have completed the upload+ if let Some(document_id) =+ email_db_client::attachments::provider::get_document_id_by_att_id(&ctx.db, attachment_id)+ .await+ .map_err(GetAttachmentDocumentIdError::DatabaseError)?+ {return Ok(Json(GetAttachmentDocumentIDResponse {attachment_id,document_id,}));}- // upload attachment if it doesn't already exist+ // Verify access and get owner's link and token+ let (owner_link, access_token) =+ verify_access_and_get_owner(&ctx, &link, gmail_token.0, attachment_id).await?;++ // Prepare and execute upload to owner's macro account+ let upload_args = prepare_upload_args(&ctx, attachment_id).await?;+ let document_id =+ upload_and_get_document_id(&ctx, &owner_link, &access_token, &upload_args).await?;++ // _lock released on drop++ Ok(Json(GetAttachmentDocumentIDResponse {+ attachment_id,+ document_id,+ }))+}++/// Verifies access and returns the owner's link and Gmail access token.+/// If the user is the owner, returns their link and token. Otherwise, verifies shared access+/// and returns the owner's link and token.+async fn verify_access_and_get_owner(+ ctx: &ApiContext,+ link: &Link,+ user_token: String,+ attachment_id: Uuid,+) -> Result<(Link, String), GetAttachmentDocumentIdError> {+ let (thread_id, owner_link_id) =+ email_db_client::attachments::provider::get_thread_id_for_attachment(+ &ctx.db,+ attachment_id,+ )+ .await+ .map_err(GetAttachmentDocumentIdError::DatabaseError)?+ .ok_or(GetAttachmentDocumentIdError::AttachmentNotFound)?;++ // User is the owner, use their link and token directly+ if owner_link_id == link.id {+ return Ok((link.clone(), user_token));+ }++ // Verify shared access to the thread+ macro_middleware::cloud_storage::ensure_access::get_users_access_level_v2(+ &ctx.db,+ link.macro_id.as_ref(),+ thread_id.to_string().as_ref(),+ "thread",+ )+ .await+ .map_err(|(_, msg)| GetAttachmentDocumentIdError::DatabaseError(anyhow::anyhow!(msg)))?+ .ok_or(GetAttachmentDocumentIdError::AccessDenied)?;++ // Fetch owner's link and access token+ let owner_link = email_db_client::links::get::fetch_link_by_id(&ctx.db, owner_link_id)+ .await+ .map_err(GetAttachmentDocumentIdError::DatabaseError)?+ .ok_or(GetAttachmentDocumentIdError::AttachmentNotFound)?;++ let owner_token = fetch_gmail_access_token_from_link(+ &owner_link,+ &ctx.redis_client,+ &ctx.auth_service_client,+ )+ .await+ .map_err(GetAttachmentDocumentIdError::DatabaseError)?;++ Ok((owner_link, owner_token))+}++/// Prepares the upload arguments for an attachment.+async fn prepare_upload_args(+ ctx: &ApiContext,+ attachment_id: Uuid,+) -> Result<AttachmentUploadArgs, GetAttachmentDocumentIdError> {let attachment_metadata =email_db_client::attachments::provider::upload::fetch_attachment_upload_metadata_by_id(&ctx.db,- link.id,attachment_id,).await@@ -111,15 +203,23 @@ pub async fn handler(.filter_map(|(contact, _)| contact.email_address.clone()).collect();- let attachment_upload_args = AttachmentUploadArgs {+ Ok(AttachmentUploadArgs {attachment_metadata,recipient_emails,backfill: false,// Frontend will soon use SFS URLs for image/video attachments directly instead of DSS// Until this transition is complete, we continue uploading all attachments to DSSupload_destination: AttachmentUploadDestination::Dss,- };+ })+}+/// Uploads the attachment and returns the document ID.+async fn upload_and_get_document_id(+ ctx: &ApiContext,+ link: &Link,+ access_token: &str,+ upload_args: &AttachmentUploadArgs,+) -> Result<String, GetAttachmentDocumentIdError> {let ctx_upload = UploadAttachmentContext {db: &ctx.db,redis_client: &ctx.redis_client,@@ -127,16 +227,11 @@ pub async fn handler(dss_client: &ctx.dss_client,sfs_client: &ctx.sfs_client,system_properties_service: &ctx.system_properties_service,- access_token: &gmail_token,- link: &link,+ access_token,+ link,};- let document_id = upload_attachment(ctx_upload, &attachment_upload_args)+ upload_attachment(ctx_upload, upload_args).await- .map_err(GetAttachmentDocumentIdError::UploadError)?;-- Ok(Json(GetAttachmentDocumentIDResponse {- attachment_id,- document_id,- }))+ .map_err(GetAttachmentDocumentIdError::UploadError)}diff --git a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rsindex b55ea32c9e..633bd8f96b 100644--- a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs+++ b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs@@ -40,7 +40,7 @@ impl AttachmentProcessor {link_id: Uuid,attachment: &AttachmentUploadMetadata,) -> anyhow::Result<()> {- let exists = email_db_client::attachments::provider::get_document_id_by_attachment_id(+ let exists = email_db_client::attachments::provider::get_document_id_by_att_id_and_link(&self.db,link_id,attachment.attachment_db_id,diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rsindex b5c161a4ea..0370c55540 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs@@ -65,7 +65,7 @@ async fn attachment_document_exists(link_id: Uuid,attachment_db_id: Uuid,) -> Result<bool, ProcessingError> {- let document_id = email_db_client::attachments::provider::get_document_id_by_attachment_id(+ let document_id = email_db_client::attachments::provider::get_document_id_by_att_id_and_link(&ctx.db,link_id,attachment_db_id,diff --git a/rust/cloud-storage/email_service/src/util/redis/lock.rs b/rust/cloud-storage/email_service/src/util/redis/lock.rsnew file mode 100644index 0000000000..47dbaddcf5--- /dev/null+++ b/rust/cloud-storage/email_service/src/util/redis/lock.rs@@ -0,0 +1,145 @@+use crate::util::redis::RedisClient;+use std::time::Duration;+use uuid::Uuid;++/// A distributed lock backed by Redis using SET NX EX.+///+/// Prefer calling [`RedisLock::release`] explicitly for deterministic cleanup.+/// If not released explicitly, the lock is released on a best-effort basis via `Drop`+/// (spawns a tokio task). The Redis TTL acts as the ultimate safety net if both fail.+pub struct RedisLock {+ /// `None` after an explicit `release()` call, so `Drop` becomes a no-op.+ inner: Option<RedisLockInner>,+}++struct RedisLockInner {+ client: redis::Client,+ key: String,+ token: String,+}++impl RedisLockInner {+ /// Release the lock atomically: only delete if the token still matches.+ /// This prevents releasing a lock that was already expired and acquired by someone else.+ async fn release(&self) {+ let script = redis::Script::new(+ r#"+ if redis.call('GET', KEYS[1]) == ARGV[1] then+ return redis.call('DEL', KEYS[1])+ else+ return 0+ end+ "#,+ );++ let result: Result<(), _> = async {+ let mut con = self.client.get_multiplexed_async_connection().await?;+ script+ .key(&self.key)+ .arg(&self.token)+ .invoke_async(&mut con)+ .await+ }+ .await;++ if let Err(e) = result {+ tracing::warn!(key = %self.key, error = %e, "failed to release redis lock");+ }+ }+}++impl RedisLock {+ /// Explicitly release the lock. Preferred over relying on Drop.+ pub async fn release(mut self) {+ if let Some(inner) = self.inner.take() {+ inner.release().await;+ }+ }+}++impl Drop for RedisLock {+ fn drop(&mut self) {+ if let Some(inner) = self.inner.take() {+ // Best-effort: spawn a task to release. If the runtime is shutting down+ // or we're outside a runtime, the TTL will expire the lock.+ if let Ok(handle) = tokio::runtime::Handle::try_current() {+ handle.spawn(async move {+ inner.release().await;+ });+ } else {+ tracing::warn!(+ key = %inner.key,+ "redis lock dropped outside tokio runtime, will expire via TTL"+ );+ }+ }+ }+}++#[derive(Debug, thiserror::Error)]+pub enum LockError {+ #[error("failed to acquire lock: already held")]+ AlreadyHeld,++ #[error("redis error: {0}")]+ Redis(#[from] redis::RedisError),+}++impl RedisClient {+ /// Attempts to acquire a distributed lock with the given key and TTL.+ ///+ /// Uses `SET key token NX EX ttl` for atomic acquire. The returned `RedisLock`+ /// releases the lock on drop (or preferably via explicit `release()`).+ ///+ /// Returns `Err(LockError::AlreadyHeld)` if the lock is already held by another caller.+ pub async fn try_acquire_lock(&self, key: &str, ttl: Duration) -> Result<RedisLock, LockError> {+ let token = Uuid::new_v4().to_string();+ let mut con = self.inner.get_multiplexed_async_connection().await?;++ let result: Option<String> = redis::cmd("SET")+ .arg(key)+ .arg(&token)+ .arg("NX")+ .arg("EX")+ .arg(ttl.as_secs())+ .query_async(&mut con)+ .await?;++ match result {+ Some(_) => Ok(RedisLock {+ inner: Some(RedisLockInner {+ client: self.inner.clone(),+ key: key.to_string(),+ token,+ }),+ }),+ None => Err(LockError::AlreadyHeld),+ }+ }++ /// Acquires a distributed lock, retrying until the timeout is reached.+ ///+ /// - `ttl`: How long the lock lives in Redis. Must be longer than the expected work duration.+ /// If the lock expires before work completes, another caller can acquire it.+ /// - `timeout`: How long to wait for the lock to become available before giving up.+ ///+ /// Polls every 100ms. Returns `Err(LockError::AlreadyHeld)` if the lock cannot be+ /// acquired within `timeout`.+ pub async fn acquire_lock(+ &self,+ key: &str,+ ttl: Duration,+ timeout: Duration,+ ) -> Result<RedisLock, LockError> {+ let start = std::time::Instant::now();+ loop {+ match self.try_acquire_lock(key, ttl).await {+ Ok(lock) => return Ok(lock),+ Err(LockError::AlreadyHeld) if start.elapsed() < timeout => {+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ Err(e) => return Err(e),+ }+ }+ }+}diff --git a/rust/cloud-storage/email_service/src/util/redis/mod.rs b/rust/cloud-storage/email_service/src/util/redis/mod.rsindex 500e61c23c..2674d04191 100644--- a/rust/cloud-storage/email_service/src/util/redis/mod.rs+++ b/rust/cloud-storage/email_service/src/util/redis/mod.rs@@ -1,5 +1,6 @@pub mod access_token;pub mod backfill;+pub mod lock;pub mod rate_limit;#[derive(Clone)]diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.jsondeleted file mode 100644index d2b084cf10..0000000000--- a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json+++ /dev/null@@ -1,17 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "UuidArray",- "TextArray",- "UuidArray",- "JsonbArray"- ]- },- "nullable": []- },- "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"-}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-4eece2777920eb0f5c4d2746221fb5b8070dbb37abe0dda364ed27e46eae230e.json b/rust/cloud-storage/macro_db_client/.sqlx/query-4eece2777920eb0f5c4d2746221fb5b8070dbb37abe0dda364ed27e46eae230e.jsonnew file mode 100644index 0000000000..fde27e0e7f--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-4eece2777920eb0f5c4d2746221fb5b8070dbb37abe0dda364ed27e46eae230e.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT et.id::text as \"thread_id!\"\n FROM document_email de\n JOIN email_attachments ea ON de.email_attachment_id = ea.id\n JOIN email_messages em ON ea.message_id = em.id\n JOIN email_threads et ON em.thread_id = et.id\n WHERE de.document_id = $1\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "4eece2777920eb0f5c4d2746221fb5b8070dbb37abe0dda364ed27e46eae230e"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.jsondeleted file mode 100644index 6d97183829..0000000000--- a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "UuidArray",- "TextArray",- "UuidArray"- ]- },- "nullable": []- },- "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"-}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.jsondeleted file mode 100644index 9d717fa5f9..0000000000--- a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "property_definition_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "values",- "type_info": "Jsonb"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- true- ]- },- "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"-}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.jsondeleted file mode 100644index 182e0858ba..0000000000--- a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json+++ /dev/null@@ -1,18 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "UuidArray",- "TextArray",- "TextArray",- "UuidArray",- "JsonbArray"- ]- },- "nullable": []- },- "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"-}diff --git a/rust/cloud-storage/macro_db_client/fixtures/document_access_via_email_thread.sql b/rust/cloud-storage/macro_db_client/fixtures/document_access_via_email_thread.sqlnew file mode 100644index 0000000000..f671f3bedd--- /dev/null+++ b/rust/cloud-storage/macro_db_client/fixtures/document_access_via_email_thread.sql@@ -0,0 +1,74 @@+-- Fixture for testing document access inherited from email thread permissions.+-- Sets up documents that are email attachments linked to threads, with various+-- thread permission configurations.++TRUNCATE TABLE public."User", public."Project", public."Document", public."SharePermission",+ public."DocumentPermission", public."ProjectPermission", public."EmailThreadPermission",+ public."UserItemAccess", public.email_links, public.email_threads, public.email_messages,+ public.email_attachments, public.document_email RESTART IDENTITY CASCADE;++------------------------------------------------------------+-- Users+------------------------------------------------------------+INSERT INTO public."User" ("id", "email")+VALUES ('user-thread-access', '[email protected]'), -- Has thread access only+ ('user-no-access', '[email protected]'), -- Has no access at all+ ('user-both-access', '[email protected]'); -- Has both direct doc and thread access++------------------------------------------------------------+-- Email infrastructure: link, thread, message, attachment+------------------------------------------------------------+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES ('a0000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'a0000000-0000-0000-0000-000000000001',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('a0000000-0000-0000-0000-000000000010', 'a0000000-0000-0000-0000-000000000001', false, false, NOW(), NOW()),+ ('a0000000-0000-0000-0000-000000000020', 'a0000000-0000-0000-0000-000000000001', false, false, NOW(), NOW());++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, internal_date_ts,+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)+VALUES ('a0000000-0000-0000-0000-000000000100', 'a0000000-0000-0000-0000-000000000010',+ 'a0000000-0000-0000-0000-000000000001', 'provider-msg-1', false, NOW(), true, false, false, false, NOW(), NOW()),+ ('a0000000-0000-0000-0000-000000000200', 'a0000000-0000-0000-0000-000000000020',+ 'a0000000-0000-0000-0000-000000000001', 'provider-msg-2', false, NOW(), true, false, false, false, NOW(), NOW());++INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('a0000000-0000-0000-0000-000000001000', 'a0000000-0000-0000-0000-000000000100', 'prov-att-1', 'report.pdf', 'application/pdf', NOW()),+ ('a0000000-0000-0000-0000-000000002000', 'a0000000-0000-0000-0000-000000000200', 'prov-att-2', 'invoice.pdf', 'application/pdf', NOW());++------------------------------------------------------------+-- Documents (email attachments uploaded as documents)+------------------------------------------------------------+-- d-attachment: linked to thread 1 via email attachment, no direct permissions+-- d-attachment-with-direct: linked to thread 2 via email attachment, also has direct access+-- d-not-attachment: regular document, not linked to any email+INSERT INTO public."Document" ("id", "name", "owner")+VALUES ('d-attachment', 'Email Attachment Doc', 'user-thread-access'),+ ('d-attachment-with-direct', 'Email Attachment With Direct Access', 'user-both-access'),+ ('d-not-attachment', 'Regular Document', 'user-no-access');++-- Link documents to email attachments+INSERT INTO document_email (document_id, email_attachment_id)+VALUES ('d-attachment', 'a0000000-0000-0000-0000-000000001000'),+ ('d-attachment-with-direct', 'a0000000-0000-0000-0000-000000002000');++------------------------------------------------------------+-- Thread permissions (via EmailThreadPermission + SharePermission)+------------------------------------------------------------+INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")+VALUES ('sp-thread-1', false, NULL),+ ('sp-thread-2', false, NULL);++INSERT INTO public."EmailThreadPermission" ("threadId", "sharePermissionId", "userId")+VALUES ('a0000000-0000-0000-0000-000000000010', 'sp-thread-1', 'user-thread-access'),+ ('a0000000-0000-0000-0000-000000000020', 'sp-thread-2', 'user-both-access');++-- user-thread-access has view on thread 1 (so should get view on d-attachment)+-- user-both-access has edit on thread 2+INSERT INTO public."UserItemAccess" ("id", "user_id", "item_id", "item_type", "access_level")+VALUES+ ('b0000000-0000-0000-0000-000000000001', 'user-thread-access', 'a0000000-0000-0000-0000-000000000010', 'thread', 'view'),+ ('b0000000-0000-0000-0000-000000000002', 'user-both-access', 'a0000000-0000-0000-0000-000000000020', 'thread', 'edit'),+ -- user-both-access also has direct view on d-attachment-with-direct (thread gives edit, so edit should win)+ ('b0000000-0000-0000-0000-000000000003', 'user-both-access', 'd-attachment-with-direct', 'document', 'view');diff --git a/rust/cloud-storage/macro_db_client/src/document/mod.rs b/rust/cloud-storage/macro_db_client/src/document/mod.rsindex af547ecb45..1acab09f14 100644--- a/rust/cloud-storage/macro_db_client/src/document/mod.rs+++ b/rust/cloud-storage/macro_db_client/src/document/mod.rs@@ -20,7 +20,7 @@ pub use list_documents_with_access::*;pub use save_document::*;pub mod build_pdf_modification_data;pub mod create_blank_docx;-mod document_email;+pub mod document_email;pub mod document_shas;pub mod get_all_documents;pub mod get_document_history;diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat.rsindex 534c2408c0..6f46cfb418 100644--- a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat.rs+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat.rs@@ -82,7 +82,7 @@ pub async fn get_public_access_level_for_chat(/// - `Ok(Some(AccessLevel))` if the user has any level of access./// - `Ok(None)` if the user has no access at all./// - `Err(_)` if a database error occurs.-#[tracing::instrument(skip(db))]+#[tracing::instrument(skip(db), err)]pub async fn get_highest_access_level_for_chat(db: &sqlx::Pool<sqlx::Postgres>,chat_id: &str,@@ -157,7 +157,7 @@ pub async fn get_highest_access_level_for_chat(/// - Keys are chat IDs from the input/// - Values are `Some(AccessLevel)` if the user has access, `None` if no access/// - `Err(_)` if a database error occurs.-#[tracing::instrument(skip(db))]+#[tracing::instrument(skip(db), err)]pub async fn get_highest_access_level_for_chats(db: &sqlx::Pool<sqlx::Postgres>,chat_ids: &[String],@@ -268,246 +268,5 @@ pub async fn get_highest_access_level_for_chats(}#[cfg(test)]-mod tests {- use super::*;-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_highest_level_is_from_explicit_access(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-1' on 'd-child'.- // EXPLICIT ACCESS: view (direct), edit (parent), owner (grandparent). Max is 'owner'.- // PUBLIC ACCESS: view (parent), edit (grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level should be 'owner' from the explicit grant.-- let highest_level = get_highest_access_level_for_chat(&pool, "d-child", "user-1").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Owner),- "Expected highest level to be 'owner' from an explicit UserItemAccess record"- );-- // highest public access is edit via grandparent-- let highest_level =- get_highest_access_level_for_chat(&pool, "d-child", "user-public-access-only").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "Expected highest level to be 'edit' from a public SharePermission record"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_user_scoping_is_correct(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-2' on 'd-child'.- // EXPLICIT ACCESS: 'user-2' only has 'view' access.- // PUBLIC ACCESS: view (parent), edit (grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level is 'edit' (from public), not 'owner' (from user-1's grant).-- let highest_level = get_highest_access_level_for_chat(&pool, "d-child", "user-2").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "User-2's highest access should be 'edit' from public, not 'owner' from user-1's explicit grant"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_simple_uia_case(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {- // SCENARIO: User has edit UIA access on private chat- // EXPECTATION: The user should have edit access to chat-- let highest_level =- get_highest_access_level_for_chat(&pool, "d-standalone", "user-3").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "User-3's highest access should be 'edit' from explicit grant"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_no_permissions_returns_none(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get access for any user on 'd-private'.- // This chat has no project, no UserItemAccess, and no SharePermission records.- // EXPECTATION: The query should return an empty list, resulting in `None`.-- let highest_level = get_highest_access_level_for_chat(&pool, "d-private", "user-1").await?;-- assert_eq!(- highest_level, None,- "Expected None for a chat with no permissions"- );-- Ok(())- }-- // Tests for the batch function get_highest_access_level_for_chats-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_batch_multiple_chats_different_access_levels(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get access for 'user-1' on multiple chats with different access levels- let chat_ids = vec![- "d-child".to_string(),- "d-standalone".to_string(),- "d-private".to_string(),- ];-- let access_levels = get_highest_access_level_for_chats(&pool, &chat_ids, "user-1").await?;-- // d-child: user-1 has owner access (from explicit grants)- assert_eq!(- access_levels.get("d-child"),- Some(&Some(AccessLevel::Owner)),- "Expected 'owner' access for d-child"- );-- // d-standalone: Check what user-1 actually has (test shows Comment access)- // We'll verify consistency with individual function rather than hardcode expectation- let individual_access =- get_highest_access_level_for_chat(&pool, "d-standalone", "user-1").await?;- assert_eq!(- access_levels.get("d-standalone"),- Some(&individual_access),- "Expected batch result to match individual function result for d-standalone"- );-- // d-private: user-1 should have no access (private chat with no permissions)- assert_eq!(- access_levels.get("d-private"),- Some(&None),- "Expected no access for d-private"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_batch_public_access_user(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {- // SCENARIO: Get access for 'user-public-access-only' on multiple chats- // This user has no explicit grants but should get public access where available- let chat_ids = vec!["d-child".to_string(), "d-private".to_string()];-- let access_levels =- get_highest_access_level_for_chats(&pool, &chat_ids, "user-public-access-only").await?;-- // d-child: public access is edit via grandparent- assert_eq!(- access_levels.get("d-child"),- Some(&Some(AccessLevel::Edit)),- "Expected 'edit' access from public permissions"- );-- // d-private: no public or explicit access- assert_eq!(- access_levels.get("d-private"),- Some(&None),- "Expected no access for d-private"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_batch_user_with_mixed_access(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get access for 'user-2' who has limited explicit access but benefits from public access- let chat_ids = vec!["d-child".to_string()];-- let access_levels = get_highest_access_level_for_chats(&pool, &chat_ids, "user-2").await?;-- // user-2 has view explicit access, but public access is edit, so should get edit- assert_eq!(- access_levels.get("d-child"),- Some(&Some(AccessLevel::Edit)),- "Expected 'edit' access from higher public permissions"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_batch_empty_input(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {- // SCENARIO: Test with empty chat_ids vector- let chat_ids: Vec<String> = vec![];-- let access_levels = get_highest_access_level_for_chats(&pool, &chat_ids, "user-1").await?;-- assert!(- access_levels.is_empty(),- "Expected empty result for empty input"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_batch_nonexistent_chats(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {- // SCENARIO: Test with chat IDs that don't exist- let chat_ids = vec!["nonexistent-1".to_string(), "nonexistent-2".to_string()];-- let access_levels = get_highest_access_level_for_chats(&pool, &chat_ids, "user-1").await?;-- // Should return None for each nonexistent chat- assert_eq!(- access_levels.get("nonexistent-1"),- Some(&None),- "Expected no access for nonexistent chat"- );- assert_eq!(- access_levels.get("nonexistent-2"),- Some(&None),- "Expected no access for nonexistent chat"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]- async fn test_batch_consistency_with_single_function(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Ensure batch function returns same results as individual calls- let chat_ids = vec!["d-child".to_string(), "d-standalone".to_string()];- let user_id = "user-1";-- // Get results from batch function- let batch_results = get_highest_access_level_for_chats(&pool, &chat_ids, user_id).await?;-- // Get results from individual function calls- let individual_d_child =- get_highest_access_level_for_chat(&pool, "d-child", user_id).await?;- let individual_d_standalone =- get_highest_access_level_for_chat(&pool, "d-standalone", user_id).await?;-- // Compare results- assert_eq!(- batch_results.get("d-child"),- Some(&individual_d_child),- "Batch and individual results should match for d-child"- );- assert_eq!(- batch_results.get("d-standalone"),- Some(&individual_d_standalone),- "Batch and individual results should match for d-standalone"- );-- Ok(())- }-}+#[path = "chat_tests.rs"]+mod tests;diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat_tests.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat_tests.rsnew file mode 100644index 0000000000..3819846385--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/chat_tests.rs@@ -0,0 +1,235 @@+use super::*;++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_highest_level_is_from_explicit_access(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-1' on 'd-child'.+ // EXPLICIT ACCESS: view (direct), edit (parent), owner (grandparent). Max is 'owner'.+ // PUBLIC ACCESS: view (parent), edit (grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level should be 'owner' from the explicit grant.++ let highest_level = get_highest_access_level_for_chat(&pool, "d-child", "user-1").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Owner),+ "Expected highest level to be 'owner' from an explicit UserItemAccess record"+ );++ // highest public access is edit via grandparent++ let highest_level =+ get_highest_access_level_for_chat(&pool, "d-child", "user-public-access-only").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "Expected highest level to be 'edit' from a public SharePermission record"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_user_scoping_is_correct(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-2' on 'd-child'.+ // EXPLICIT ACCESS: 'user-2' only has 'view' access.+ // PUBLIC ACCESS: view (parent), edit (grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level is 'edit' (from public), not 'owner' (from user-1's grant).++ let highest_level = get_highest_access_level_for_chat(&pool, "d-child", "user-2").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "User-2's highest access should be 'edit' from public, not 'owner' from user-1's explicit grant"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_simple_uia_case(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: User has edit UIA access on private chat+ // EXPECTATION: The user should have edit access to chat++ let highest_level = get_highest_access_level_for_chat(&pool, "d-standalone", "user-3").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "User-3's highest access should be 'edit' from explicit grant"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_no_permissions_returns_none(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: Get access for any user on 'd-private'.+ // This chat has no project, no UserItemAccess, and no SharePermission records.+ // EXPECTATION: The query should return an empty list, resulting in `None`.++ let highest_level = get_highest_access_level_for_chat(&pool, "d-private", "user-1").await?;++ assert_eq!(+ highest_level, None,+ "Expected None for a chat with no permissions"+ );++ Ok(())+}++// Tests for the batch function get_highest_access_level_for_chats++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_batch_multiple_chats_different_access_levels(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get access for 'user-1' on multiple chats with different access levels+ let chat_ids = vec![+ "d-child".to_string(),+ "d-standalone".to_string(),+ "d-private".to_string(),+ ];++ let access_levels = get_highest_access_level_for_chats(&pool, &chat_ids, "user-1").await?;++ // d-child: user-1 has owner access (from explicit grants)+ assert_eq!(+ access_levels.get("d-child"),+ Some(&Some(AccessLevel::Owner)),+ "Expected 'owner' access for d-child"+ );++ // d-standalone: Check what user-1 actually has (test shows Comment access)+ // We'll verify consistency with individual function rather than hardcode expectation+ let individual_access =+ get_highest_access_level_for_chat(&pool, "d-standalone", "user-1").await?;+ assert_eq!(+ access_levels.get("d-standalone"),+ Some(&individual_access),+ "Expected batch result to match individual function result for d-standalone"+ );++ // d-private: user-1 should have no access (private chat with no permissions)+ assert_eq!(+ access_levels.get("d-private"),+ Some(&None),+ "Expected no access for d-private"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_batch_public_access_user(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: Get access for 'user-public-access-only' on multiple chats+ // This user has no explicit grants but should get public access where available+ let chat_ids = vec!["d-child".to_string(), "d-private".to_string()];++ let access_levels =+ get_highest_access_level_for_chats(&pool, &chat_ids, "user-public-access-only").await?;++ // d-child: public access is edit via grandparent+ assert_eq!(+ access_levels.get("d-child"),+ Some(&Some(AccessLevel::Edit)),+ "Expected 'edit' access from public permissions"+ );++ // d-private: no public or explicit access+ assert_eq!(+ access_levels.get("d-private"),+ Some(&None),+ "Expected no access for d-private"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_batch_user_with_mixed_access(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: Get access for 'user-2' who has limited explicit access but benefits from public access+ let chat_ids = vec!["d-child".to_string()];++ let access_levels = get_highest_access_level_for_chats(&pool, &chat_ids, "user-2").await?;++ // user-2 has view explicit access, but public access is edit, so should get edit+ assert_eq!(+ access_levels.get("d-child"),+ Some(&Some(AccessLevel::Edit)),+ "Expected 'edit' access from higher public permissions"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_batch_empty_input(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: Test with empty chat_ids vector+ let chat_ids: Vec<String> = vec![];++ let access_levels = get_highest_access_level_for_chats(&pool, &chat_ids, "user-1").await?;++ assert!(+ access_levels.is_empty(),+ "Expected empty result for empty input"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_batch_nonexistent_chats(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: Test with chat IDs that don't exist+ let chat_ids = vec!["nonexistent-1".to_string(), "nonexistent-2".to_string()];++ let access_levels = get_highest_access_level_for_chats(&pool, &chat_ids, "user-1").await?;++ // Should return None for each nonexistent chat+ assert_eq!(+ access_levels.get("nonexistent-1"),+ Some(&None),+ "Expected no access for nonexistent chat"+ );+ assert_eq!(+ access_levels.get("nonexistent-2"),+ Some(&None),+ "Expected no access for nonexistent chat"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_batch_consistency_with_single_function(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Ensure batch function returns same results as individual calls+ let chat_ids = vec!["d-child".to_string(), "d-standalone".to_string()];+ let user_id = "user-1";++ // Get results from batch function+ let batch_results = get_highest_access_level_for_chats(&pool, &chat_ids, user_id).await?;++ // Get results from individual function calls+ let individual_d_child = get_highest_access_level_for_chat(&pool, "d-child", user_id).await?;+ let individual_d_standalone =+ get_highest_access_level_for_chat(&pool, "d-standalone", user_id).await?;++ // Compare results+ assert_eq!(+ batch_results.get("d-child"),+ Some(&individual_d_child),+ "Batch and individual results should match for d-child"+ );+ assert_eq!(+ batch_results.get("d-standalone"),+ Some(&individual_d_standalone),+ "Batch and individual results should match for d-standalone"+ );++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document.rsindex 018157ffe9..3afcefd88e 100644--- a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document.rs+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document.rs@@ -62,11 +62,13 @@ pub async fn get_public_access_level_for_document(/// Calculates the highest effective access level a user has for a document.///-/// This function determines the best possible permission by considering two sources:+/// This function determines the best possible permission by considering three sources:/// 1. **Explicit Grants**: Any `UserItemAccess` records for the specified user, applied either/// directly to the document or inherited from its entire project hierarchy./// 2. **Public Access**: Any `SharePermission` records marked as `isPublic=true`, applied either/// directly to the document or inherited from its project hierarchy.+/// 3. **Email Thread Inheritance**: If the document is an email attachment, the user's access+/// to the parent email thread is also considered.////// It combines all possible access levels from these sources, sorts them from highest (`Owner`)/// to lowest (`View`), and returns the single highest level.@@ -81,11 +83,36 @@ pub async fn get_public_access_level_for_document(/// - `Ok(Some(AccessLevel))` if the user has any level of access./// - `Ok(None)` if the user has no access at all./// - `Err(_)` if a database error occurs.-#[tracing::instrument(skip(db))]+#[tracing::instrument(skip(db), err)]pub async fn get_highest_access_level_for_document(db: &sqlx::Pool<sqlx::Postgres>,document_id: &str,user_id: &str,+) -> anyhow::Result<Option<AccessLevel>> {+ // Run the document access query and the email thread lookup concurrently+ let (doc_access_result, thread_id_result) = tokio::join!(+ get_document_direct_access_level(db, document_id, user_id),+ get_parent_thread_id_for_document(db, document_id)+ );++ let mut highest_level = doc_access_result?;++ // If the document is an email attachment, also check the user's access to the parent thread+ if let Some(thread_id) = thread_id_result? {+ let thread_access =+ super::thread::get_highest_access_level_for_thread(db, &thread_id, user_id).await?;+ highest_level = std::cmp::max(highest_level, thread_access);+ }++ Ok(highest_level)+}++/// Gets the document's direct access level from UserItemAccess and public SharePermissions.+#[tracing::instrument(skip(db), err)]+async fn get_document_direct_access_level(+ db: &sqlx::Pool<sqlx::Postgres>,+ document_id: &str,+ user_id: &str,) -> anyhow::Result<Option<AccessLevel>> {// have to use strings because the SharePermission and UserItemAccess access_level rows use different sql typeslet all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(@@ -124,14 +151,12 @@ pub async fn get_highest_access_level_for_document(document_id,user_id)- .fetch_all(db)- .await?;+ .fetch_all(db)+ .await?;let highest_level = all_level_strings.iter().filter_map(|optional_string| {- // `optional_string` is &Option<String>.- // We use `and_then` to proceed only if it's Some.optional_string.as_ref().and_then(|s| AccessLevel::from_str(s).ok())@@ -141,107 +166,30 @@ pub async fn get_highest_access_level_for_document(Ok(highest_level)}-#[cfg(test)]-mod tests {- use super::*;-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_document")- ))]- async fn test_highest_level_is_from_explicit_access(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-1' on 'd-child'.- // EXPLICIT ACCESS: view (direct), edit (parent), owner (grandparent). Max is 'owner'.- // PUBLIC ACCESS: view (parent), edit (grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level should be 'owner' from the explicit grant.-- let highest_level =- get_highest_access_level_for_document(&pool, "d-child", "user-1").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Owner),- "Expected highest level to be 'owner' from an explicit UserItemAccess record"- );-- // highest public access is edit via grandparent-- let highest_level =- get_highest_access_level_for_document(&pool, "d-child", "user-public-access-only")- .await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "Expected highest level to be 'edit' from a public SharePermission record"- );-- Ok(())- }-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_document")- ))]- async fn test_user_scoping_is_correct(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-2' on 'd-child'.- // EXPLICIT ACCESS: 'user-2' only has 'view' access.- // PUBLIC ACCESS: view (parent), edit (grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level is 'edit' (from public), not 'owner' (from user-1's grant).-- let highest_level =- get_highest_access_level_for_document(&pool, "d-child", "user-2").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "User-2's highest access should be 'edit' from public, not 'owner' from user-1's explicit grant"- );-- Ok(())- }-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_document")- ))]- async fn test_simple_uia_case(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {- // SCENARIO: User has edit UIA access on private document- // EXPECTATION: The user should have edit access to document-- let highest_level =- get_highest_access_level_for_document(&pool, "d-standalone", "user-3").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "User-3's highest access should be 'edit' from explicit grant"- );-- Ok(())- }-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_document")- ))]- async fn test_no_permissions_returns_none(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get access for any user on 'd-private'.- // This document has no project, no UserItemAccess, and no SharePermission records.- // EXPECTATION: The query should return an empty list, resulting in `None`.-- let highest_level =- get_highest_access_level_for_document(&pool, "d-private", "user-1").await?;-- assert_eq!(- highest_level, None,- "Expected None for a document with no permissions"- );+/// If a document is an email attachment, returns the thread ID it belongs to.+#[tracing::instrument(skip(db), err)]+async fn get_parent_thread_id_for_document(+ db: &sqlx::Pool<sqlx::Postgres>,+ document_id: &str,+) -> anyhow::Result<Option<String>> {+ let result = sqlx::query_scalar!(+ r#"+ SELECT et.id::text as "thread_id!"+ FROM document_email de+ JOIN email_attachments ea ON de.email_attachment_id = ea.id+ JOIN email_messages em ON ea.message_id = em.id+ JOIN email_threads et ON em.thread_id = et.id+ WHERE de.document_id = $1+ LIMIT 1+ "#,+ document_id+ )+ .fetch_optional(db)+ .await?;- Ok(())- }+ Ok(result)}++#[cfg(test)]+#[path = "document_tests.rs"]+mod tests;diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document_tests.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document_tests.rsnew file mode 100644index 0000000000..f8e2bddb56--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/document_tests.rs@@ -0,0 +1,190 @@+use super::*;++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_document")+))]+async fn test_highest_level_is_from_explicit_access(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-1' on 'd-child'.+ // EXPLICIT ACCESS: view (direct), edit (parent), owner (grandparent). Max is 'owner'.+ // PUBLIC ACCESS: view (parent), edit (grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level should be 'owner' from the explicit grant.++ let highest_level = get_highest_access_level_for_document(&pool, "d-child", "user-1").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Owner),+ "Expected highest level to be 'owner' from an explicit UserItemAccess record"+ );++ // highest public access is edit via grandparent++ let highest_level =+ get_highest_access_level_for_document(&pool, "d-child", "user-public-access-only").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "Expected highest level to be 'edit' from a public SharePermission record"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_document")+))]+async fn test_user_scoping_is_correct(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-2' on 'd-child'.+ // EXPLICIT ACCESS: 'user-2' only has 'view' access.+ // PUBLIC ACCESS: view (parent), edit (grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level is 'edit' (from public), not 'owner' (from user-1's grant).++ let highest_level = get_highest_access_level_for_document(&pool, "d-child", "user-2").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "User-2's highest access should be 'edit' from public, not 'owner' from user-1's explicit grant"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_document")+))]+async fn test_simple_uia_case(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: User has edit UIA access on private document+ // EXPECTATION: The user should have edit access to document++ let highest_level =+ get_highest_access_level_for_document(&pool, "d-standalone", "user-3").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "User-3's highest access should be 'edit' from explicit grant"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_document")+))]+async fn test_no_permissions_returns_none(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ // SCENARIO: Get access for any user on 'd-private'.+ // This document has no project, no UserItemAccess, and no SharePermission records.+ // EXPECTATION: The query should return an empty list, resulting in `None`.++ let highest_level = get_highest_access_level_for_document(&pool, "d-private", "user-1").await?;++ assert_eq!(+ highest_level, None,+ "Expected None for a document with no permissions"+ );++ Ok(())+}++// --- Email thread inheritance tests ---++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("document_access_via_email_thread")+))]+async fn test_thread_access_grants_document_access(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: user-thread-access has 'view' on the email thread but no direct document access.+ // The document is an email attachment of that thread.+ // EXPECTATION: The user should get 'view' access to the document via thread inheritance.++ let highest_level =+ get_highest_access_level_for_document(&pool, "d-attachment", "user-thread-access").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::View),+ "User should get 'view' access to the attachment document via thread access"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("document_access_via_email_thread")+))]+async fn test_no_thread_access_means_no_document_access(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: user-no-access has no access to the thread or the document.+ // EXPECTATION: Should return None.++ let highest_level =+ get_highest_access_level_for_document(&pool, "d-attachment", "user-no-access").await?;++ assert_eq!(+ highest_level, None,+ "User with no thread access should have no access to the attachment document"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("document_access_via_email_thread")+))]+async fn test_thread_access_combined_with_direct_access(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: user-both-access has direct 'view' on the document AND 'edit' on the thread.+ // EXPECTATION: The highest level should be 'edit' from the thread, not 'view' from direct.++ let highest_level = get_highest_access_level_for_document(+ &pool,+ "d-attachment-with-direct",+ "user-both-access",+ )+ .await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "Thread access ('edit') should be higher than direct document access ('view')"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("document_access_via_email_thread")+))]+async fn test_non_attachment_document_unaffected(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: d-not-attachment is a regular document not linked to any email.+ // No user has any permissions on it.+ // EXPECTATION: Thread inheritance should not apply; result should be None.++ let highest_level =+ get_highest_access_level_for_document(&pool, "d-not-attachment", "user-thread-access")+ .await?;++ assert_eq!(+ highest_level, None,+ "Non-attachment documents should not get access from thread permissions"+ );++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project.rsindex 6ff75f3075..ba4c12a406 100644--- a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project.rs+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project.rs@@ -78,7 +78,7 @@ pub async fn get_public_access_level_for_project(/// - `Ok(Some(AccessLevel))` if the user has any level of access./// - `Ok(None)` if the user has no access at all./// - `Err(_)` if a database error occurs.-#[tracing::instrument(skip(db))]+#[tracing::instrument(skip(db), err)]pub async fn get_highest_access_level_for_project(db: &sqlx::Pool<sqlx::Postgres>,project_id: &str,@@ -141,131 +141,5 @@ pub async fn get_highest_access_level_for_project(}#[cfg(test)]-mod tests {- use super::*;-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_project")- ))]- async fn test_highest_level_is_from_explicit_access_on_project(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-1' on 'p-child'.- // EXPLICIT ACCESS: view (direct on p-child), owner (inherited from p-grandparent). Max is 'owner'.- // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level should be 'owner' from the explicit grant on the grandparent.-- let highest_level =- get_highest_access_level_for_project(&pool, "p-child", "user-1").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Owner),- "Expected highest level to be 'owner' from an inherited UserItemAccess record"- );-- Ok(())- }-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_project")- ))]- async fn test_highest_level_is_from_public_access_on_project(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-public-access-only' on 'p-child'.- // This user has no explicit access grants.- // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level must be 'edit' from a public SharePermission.-- let highest_level =- get_highest_access_level_for_project(&pool, "p-child", "user-public-access-only")- .await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "Expected highest level to be 'edit' from a public SharePermission record"- );-- Ok(())- }-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_project")- ))]- async fn test_user_scoping_is_correct_on_project(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-2' on 'p-child'.- // EXPLICIT ACCESS: 'user-2' has 'comment' access inherited from p-parent.- // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level is 'edit' (from public), which is higher than- // the user's explicit 'comment' grant.-- let highest_level =- get_highest_access_level_for_project(&pool, "p-child", "user-2").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "User-2's highest access should be 'edit' from public, which is higher than their explicit 'comment' grant"- );-- Ok(())- }-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_project")- ))]- async fn test_private_share_permissions_are_ignored_on_project(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: A private 'owner' SharePermission is attached directly to 'p-child'.- // Get access for a user who would otherwise only have public access.- // EXPECTATION: The private permission must be ignored.-- let highest_level =- get_highest_access_level_for_project(&pool, "p-child", "user-public-access-only")- .await?;-- assert_ne!(- highest_level,- Some(AccessLevel::Owner),- "A private SharePermission should not grant owner access"- );- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "The highest access should still come from the public grandparent permission"- );-- Ok(())- }-- #[sqlx::test(fixtures(- path = "../../../fixtures",- scripts("highest_access_level_for_project")- ))]- async fn test_no_permissions_returns_none_for_project(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get access for any user on 'p-isolated'.- // This project has no permissions of any kind for user-1 and no public access.- // EXPECTATION: The query should return an empty list, resulting in `None`.-- let highest_level =- get_highest_access_level_for_project(&pool, "p-isolated", "user-1").await?;-- assert_eq!(- highest_level, None,- "Expected None for a project with no permissions for the user"- );-- Ok(())- }-}+#[path = "project_tests.rs"]+mod tests;diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project_tests.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project_tests.rsnew file mode 100644index 0000000000..371f37d28c--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/project_tests.rs@@ -0,0 +1,121 @@+use super::*;++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_project")+))]+async fn test_highest_level_is_from_explicit_access_on_project(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-1' on 'p-child'.+ // EXPLICIT ACCESS: view (direct on p-child), owner (inherited from p-grandparent). Max is 'owner'.+ // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level should be 'owner' from the explicit grant on the grandparent.++ let highest_level = get_highest_access_level_for_project(&pool, "p-child", "user-1").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Owner),+ "Expected highest level to be 'owner' from an inherited UserItemAccess record"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_project")+))]+async fn test_highest_level_is_from_public_access_on_project(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-public-access-only' on 'p-child'.+ // This user has no explicit access grants.+ // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level must be 'edit' from a public SharePermission.++ let highest_level =+ get_highest_access_level_for_project(&pool, "p-child", "user-public-access-only").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "Expected highest level to be 'edit' from a public SharePermission record"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_project")+))]+async fn test_user_scoping_is_correct_on_project(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-2' on 'p-child'.+ // EXPLICIT ACCESS: 'user-2' has 'comment' access inherited from p-parent.+ // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level is 'edit' (from public), which is higher than+ // the user's explicit 'comment' grant.++ let highest_level = get_highest_access_level_for_project(&pool, "p-child", "user-2").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "User-2's highest access should be 'edit' from public, which is higher than their explicit 'comment' grant"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_project")+))]+async fn test_private_share_permissions_are_ignored_on_project(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: A private 'owner' SharePermission is attached directly to 'p-child'.+ // Get access for a user who would otherwise only have public access.+ // EXPECTATION: The private permission must be ignored.++ let highest_level =+ get_highest_access_level_for_project(&pool, "p-child", "user-public-access-only").await?;++ assert_ne!(+ highest_level,+ Some(AccessLevel::Owner),+ "A private SharePermission should not grant owner access"+ );+ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "The highest access should still come from the public grandparent permission"+ );++ Ok(())+}++#[sqlx::test(fixtures(+ path = "../../../fixtures",+ scripts("highest_access_level_for_project")+))]+async fn test_no_permissions_returns_none_for_project(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get access for any user on 'p-isolated'.+ // This project has no permissions of any kind for user-1 and no public access.+ // EXPECTATION: The query should return an empty list, resulting in `None`.++ let highest_level = get_highest_access_level_for_project(&pool, "p-isolated", "user-1").await?;++ assert_eq!(+ highest_level, None,+ "Expected None for a project with no permissions for the user"+ );++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread.rsindex c6c90d440f..ca364bb6ba 100644--- a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread.rs+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread.rs@@ -81,7 +81,7 @@ pub async fn get_public_access_level_for_thread(/// - `Ok(Some(AccessLevel))` if the user has any level of access./// - `Ok(None)` if the user has no access at all./// - `Err(_)` if a database error occurs.-#[tracing::instrument(skip(db))]+#[tracing::instrument(skip(db), err)]pub async fn get_highest_access_level_for_thread(db: &sqlx::Pool<sqlx::Postgres>,thread_id: &str,@@ -151,116 +151,5 @@ pub async fn get_highest_access_level_for_thread(}#[cfg(test)]-mod tests {- use super::*;-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]- async fn test_highest_level_is_from_explicit_access_on_thread(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-1' on 'thread-nested'.- // EXPLICIT ACCESS: view (direct), owner (inherited from p-grandparent). Max is 'owner'.- // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level should be 'owner' from the explicit grant.-- let highest_level =- get_highest_access_level_for_thread(&pool, "thread-nested", "user-1").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Owner),- "Expected highest level to be 'owner' from an inherited UserItemAccess record"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]- async fn test_highest_level_is_from_public_access_on_thread(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-public-access-only' on 'thread-nested'.- // This user has no explicit access grants.- // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level must be 'edit' from a public SharePermission.-- let highest_level =- get_highest_access_level_for_thread(&pool, "thread-nested", "user-public-access-only")- .await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "Expected highest level to be 'edit' from a public SharePermission record"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]- async fn test_user_scoping_is_correct_on_thread(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get highest access for 'user-2' on 'thread-nested'.- // EXPLICIT ACCESS: 'user-2' has 'comment' access inherited from p-parent.- // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.- // EXPECTATION: The overall highest level is 'edit' (from public), which is higher than- // the user's explicit 'comment' grant.-- let highest_level =- get_highest_access_level_for_thread(&pool, "thread-nested", "user-2").await?;-- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "User-2's highest access should be 'edit' from public, which is higher than their explicit 'comment' grant"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]- async fn test_private_share_permissions_are_ignored_on_thread(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: A private 'owner' SharePermission is attached directly to 'thread-nested'.- // Get access for a user who would otherwise only have public access.- // EXPECTATION: The private permission must be ignored.-- let highest_level =- get_highest_access_level_for_thread(&pool, "thread-nested", "user-public-access-only")- .await?;-- assert_ne!(- highest_level,- Some(AccessLevel::Owner),- "A private SharePermission should not grant owner access"- );- assert_eq!(- highest_level,- Some(AccessLevel::Edit),- "The highest access should still come from the public grandparent permission"- );-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]- async fn test_no_permissions_returns_none_for_thread(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- // SCENARIO: Get access for any user on 'thread-private'.- // This thread has no project and no other permissions attached.- // EXPECTATION: The query should return an empty list, resulting in `None`.-- let highest_level =- get_highest_access_level_for_thread(&pool, "thread-private", "user-1").await?;-- assert_eq!(- highest_level, None,- "Expected None for a thread with no permissions for the user"- );-- Ok(())- }-}+#[path = "thread_tests.rs"]+mod tests;diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread_tests.rs b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread_tests.rsnew file mode 100644index 0000000000..4e98c6e073--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/share_permission/access_level/thread_tests.rs@@ -0,0 +1,111 @@+use super::*;++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]+async fn test_highest_level_is_from_explicit_access_on_thread(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-1' on 'thread-nested'.+ // EXPLICIT ACCESS: view (direct), owner (inherited from p-grandparent). Max is 'owner'.+ // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level should be 'owner' from the explicit grant.++ let highest_level =+ get_highest_access_level_for_thread(&pool, "thread-nested", "user-1").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Owner),+ "Expected highest level to be 'owner' from an inherited UserItemAccess record"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]+async fn test_highest_level_is_from_public_access_on_thread(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-public-access-only' on 'thread-nested'.+ // This user has no explicit access grants.+ // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level must be 'edit' from a public SharePermission.++ let highest_level =+ get_highest_access_level_for_thread(&pool, "thread-nested", "user-public-access-only")+ .await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "Expected highest level to be 'edit' from a public SharePermission record"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]+async fn test_user_scoping_is_correct_on_thread(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get highest access for 'user-2' on 'thread-nested'.+ // EXPLICIT ACCESS: 'user-2' has 'comment' access inherited from p-parent.+ // PUBLIC ACCESS: view (from p-parent), edit (from p-grandparent). Max is 'edit'.+ // EXPECTATION: The overall highest level is 'edit' (from public), which is higher than+ // the user's explicit 'comment' grant.++ let highest_level =+ get_highest_access_level_for_thread(&pool, "thread-nested", "user-2").await?;++ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "User-2's highest access should be 'edit' from public, which is higher than their explicit 'comment' grant"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]+async fn test_private_share_permissions_are_ignored_on_thread(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: A private 'owner' SharePermission is attached directly to 'thread-nested'.+ // Get access for a user who would otherwise only have public access.+ // EXPECTATION: The private permission must be ignored.++ let highest_level =+ get_highest_access_level_for_thread(&pool, "thread-nested", "user-public-access-only")+ .await?;++ assert_ne!(+ highest_level,+ Some(AccessLevel::Owner),+ "A private SharePermission should not grant owner access"+ );+ assert_eq!(+ highest_level,+ Some(AccessLevel::Edit),+ "The highest access should still come from the public grandparent permission"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_thread")))]+async fn test_no_permissions_returns_none_for_thread(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ // SCENARIO: Get access for any user on 'thread-private'.+ // This thread has no project and no other permissions attached.+ // EXPECTATION: The query should return an empty list, resulting in `None`.++ let highest_level =+ get_highest_access_level_for_thread(&pool, "thread-private", "user-1").await?;++ assert_eq!(+ highest_level, None,+ "Expected None for a thread with no permissions for the user"+ );++ Ok(())+}