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.

feat(documents): add document to entity_access when you are mentioned in it (#3817)

Will Hutchinsonace7f87585fc
diff --git a/rust/cloud-storage/.sqlx/query-03126b7a70835aac508c3f236c9e5bcd98c0df2596f1d098c08cd4308583f307.json b/rust/cloud-storage/.sqlx/query-03126b7a70835aac508c3f236c9e5bcd98c0df2596f1d098c08cd4308583f307.json
new file mode 100644
index 0000000000..ee80650f37
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-03126b7a70835aac508c3f236c9e5bcd98c0df2596f1d098c08cd4308583f307.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM entity_access \n WHERE entity_id = $1 \n AND entity_type = $2 \n AND source_type = $3\n AND source_id != $4\n AND granted_from_project_id IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ {
+ "Custom": {
+ "name": "entity_access_source_type",
+ "kind": {
+ "Enum": [
+ "channel",
+ "team",
+ "user"
+ ]
+ }
+ }
+ },
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "03126b7a70835aac508c3f236c9e5bcd98c0df2596f1d098c08cd4308583f307"
+}
diff --git a/rust/cloud-storage/.sqlx/query-ab7417eb79789bfff9a6084c7881191a9b0ee849745041e1fecc7e4ba9b4fc5d.json b/rust/cloud-storage/.sqlx/query-ab7417eb79789bfff9a6084c7881191a9b0ee849745041e1fecc7e4ba9b4fc5d.json
new file mode 100644
index 0000000000..16c7afa6a3
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-ab7417eb79789bfff9a6084c7881191a9b0ee849745041e1fecc7e4ba9b4fc5d.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n SELECT dp.\"documentId\"::uuid, 'document', u.user_id, 'user', sp.\"publicAccessLevel\"::\"AccessLevel\"\n FROM \"DocumentPermission\" dp\n JOIN \"SharePermission\" sp ON sp.id = dp.\"sharePermissionId\"\n CROSS JOIN UNNEST($2::text[]) AS u(user_id)\n WHERE dp.\"documentId\" = $1\n AND sp.\"isPublic\" = true\n AND sp.\"publicAccessLevel\" IS NOT NULL\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ab7417eb79789bfff9a6084c7881191a9b0ee849745041e1fecc7e4ba9b4fc5d"
+}
diff --git a/rust/cloud-storage/.sqlx/query-eab276e5a26ac65dd643a67de93e82418e3a012a628f1b5cd3be1f490eeec9f1.json b/rust/cloud-storage/.sqlx/query-eab276e5a26ac65dd643a67de93e82418e3a012a628f1b5cd3be1f490eeec9f1.json
new file mode 100644
index 0000000000..f47afb182d
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-eab276e5a26ac65dd643a67de93e82418e3a012a628f1b5cd3be1f490eeec9f1.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT owner FROM \"Document\" WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "eab276e5a26ac65dd643a67de93e82418e3a012a628f1b5cd3be1f490eeec9f1"
+}
diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs
index 4e6a1f6277..1ca6084646 100644
--- a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs
@@ -150,6 +150,20 @@ pub async fn create_comment_handler(
if let Some(Mentions { mention_id, .. }) = &req.mentions
&& !recipients.mention_recipients.is_empty()
{
+ // If the document is public, grant the mentioned users access so
+ // the comment surfaces in their soup/inbox — a notification alone
+ // isn't enough for the document to appear there.
+ let mention_recipients: Vec<MacroUserIdStr<'_>> =
+ recipients.mention_recipients.iter().cloned().collect();
+
+ let _ = macro_db_client::share_on_mention::share_public_document_with_mentioned_users(
+ &db,
+ &document_id,
+ &mention_recipients,
+ )
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "unable to update entity access"));
+
let request = notif_ctx
.build_mention_notif(recipients.mention_recipients, mention_id)
.into_request()
diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs
index 36cffd64a6..53df6b3ed1 100644
--- a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs
@@ -82,11 +82,25 @@ pub async fn edit_comment_handler(
sender_profile_picture_url,
};
- let recipient_ids = users
+ let recipient_ids: std::collections::HashSet<MacroUserIdStr<'static>> = users
.iter()
.filter_map(|id| MacroUserIdStr::try_from(id.clone()).ok())
.collect();
+ // If the document is public, grant the mentioned users access so
+ // the comment surfaces in their soup/inbox — a notification alone
+ // isn't enough for the document to appear there.
+ let mention_recipients: Vec<MacroUserIdStr<'_>> =
+ recipient_ids.iter().cloned().collect();
+
+ let _ = macro_db_client::share_on_mention::share_public_document_with_mentioned_users(
+ &db,
+ &res.document_id,
+ &mention_recipients,
+ )
+ .await
+ .inspect_err(|e| tracing::error!(error =? e, "couldn't share public document with mentioned users"));
+
let request = notif_ctx
.build_mention_notif(recipient_ids, &mention_id)
.into_request()
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
index bae2993bb5..5c7c837e10 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
@@ -526,8 +526,33 @@ impl DocumentRepo for PgDocumentRepo {
.await?;
if let Some(ref share_permission) = args.share_permission {
+ let mut document_now_private = false;
+
+ if let Some(is_public) = share_permission.is_public
+ && !is_public
+ {
+ document_now_private = true;
+ }
+
edit::update_share_permission(&mut transaction, &args.document_id, share_permission)
.await?;
+
+ // The share permission changed, if the document became private we need to update
+ // entity_access
+ if document_now_private {
+ let owner = edit::get_document_owner(&mut transaction, &args.document_id).await?;
+
+ // SAFETY: this will not fail
+ let entity_id = macro_uuid::string_to_uuid(&args.document_id).unwrap();
+
+ entity_access_db_utils::remove_non_owner_user_entity_access(
+ &mut transaction,
+ &entity_id,
+ EntityType::Document,
+ &owner,
+ )
+ .await?;
+ }
}
transaction.commit().await?;
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/edit.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/edit.rs
index 514fc2fafd..949fb4d7cf 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/edit.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/edit.rs
@@ -5,6 +5,16 @@ use models_permissions::share_permission::UpdateSharePermissionRequestV2;
use models_permissions::share_permission::channel_share_permission::UpdateOperation;
use sqlx::{Postgres, Transaction};
+pub(super) async fn get_document_owner(
+ transaction: &mut Transaction<'_, Postgres>,
+ document_id: &str,
+) -> Result<String, sqlx::Error> {
+ sqlx::query!(r#"SELECT owner FROM "Document" WHERE id = $1"#, document_id)
+ .map(|r| r.owner)
+ .fetch_one(transaction.as_mut())
+ .await
+}
+
/// Update document metadata (name, projectId, fileType, updatedAt).
///
/// `file_type`: None = no change, Some(None) = set to NULL, Some(Some(ft)) = set to ft.
diff --git a/rust/cloud-storage/entity_access_db_utils/src/lib.rs b/rust/cloud-storage/entity_access_db_utils/src/lib.rs
index d28cd0d061..fbaa62fd6a 100644
--- a/rust/cloud-storage/entity_access_db_utils/src/lib.rs
+++ b/rust/cloud-storage/entity_access_db_utils/src/lib.rs
@@ -42,6 +42,36 @@ pub async fn insert_entity_access_row(
Ok(())
}
+/// Removes all user source level entity access rows for the provided entity aside from the owner
+/// one.
+/// This is used when an item goes from public to private.
+#[tracing::instrument(skip(transaction), err)]
+pub async fn remove_non_owner_user_entity_access(
+ transaction: &mut Transaction<'_, Postgres>,
+ entity_id: &macro_uuid::Uuid,
+ entity_type: EntityType,
+ owner_id: &str,
+) -> Result<(), sqlx::Error> {
+ sqlx::query!(
+ r#"
+ DELETE FROM entity_access
+ WHERE entity_id = $1
+ AND entity_type = $2
+ AND source_type = $3
+ AND source_id != $4
+ AND granted_from_project_id IS NULL
+ "#,
+ entity_id,
+ entity_type.as_ref(),
+ EntityAccessSourceType::User as _,
+ owner_id,
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ Ok(())
+}
+
/// Deletes all entity_access rows for a given (entity_id, entity_type).
/// *NOTE*: The transaction does not get committed automatically.
#[tracing::instrument(skip(transaction), err)]
diff --git a/rust/cloud-storage/entity_access_db_utils/src/test.rs b/rust/cloud-storage/entity_access_db_utils/src/test.rs
index c5e29371a8..09d3a1d8cd 100644
--- a/rust/cloud-storage/entity_access_db_utils/src/test.rs
+++ b/rust/cloud-storage/entity_access_db_utils/src/test.rs
@@ -6,7 +6,7 @@ use models_permissions::share_permission::channel_share_permission::{
UpdateChannelSharePermission, UpdateOperation,
};
use sqlx::Row as _;
-use sqlx::{Pool, Postgres};
+use sqlx::{Pool, Postgres, Transaction};
use super::*;
@@ -56,6 +56,81 @@ async fn fetch_channel_rows(pool: &Pool<Postgres>, channel_id: &str) -> Vec<Row>
.unwrap()
}
+#[derive(Debug)]
+struct EntityAccessRow {
+ source_id: String,
+ source_type: String,
+ access_level: AccessLevel,
+ granted_from_project_id: Option<String>,
+}
+
+async fn insert_entity_access_for_test(
+ transaction: &mut Transaction<'_, Postgres>,
+ entity_id: &Uuid,
+ entity_type: EntityType,
+ source_id: &str,
+ source_type: EntityAccessSourceType,
+ access_level: AccessLevel,
+ granted_from_project_id: Option<&str>,
+) {
+ // Runtime query (not the compile-time macro) so this test helper does not
+ // require a `.sqlx` cache entry to build.
+ sqlx::query(
+ r#"
+ INSERT INTO entity_access (
+ entity_id,
+ entity_type,
+ source_id,
+ source_type,
+ access_level,
+ granted_from_project_id
+ )
+ VALUES ($1, $2, $3, $4, $5, $6)
+ "#,
+ )
+ .bind(entity_id)
+ .bind(entity_type.as_ref())
+ .bind(source_id)
+ .bind(source_type)
+ .bind(access_level)
+ .bind(granted_from_project_id)
+ .execute(transaction.as_mut())
+ .await
+ .unwrap();
+}
+
+async fn fetch_entity_access_rows(
+ pool: &Pool<Postgres>,
+ entity_id: &Uuid,
+ entity_type: EntityType,
+) -> Vec<EntityAccessRow> {
+ // Runtime query (not the compile-time macro) so this test helper does not
+ // require a `.sqlx` cache entry to build.
+ sqlx::query(
+ r#"
+ SELECT
+ source_id,
+ source_type::text AS source_type,
+ access_level,
+ granted_from_project_id
+ FROM entity_access
+ WHERE entity_id = $1 AND entity_type = $2
+ ORDER BY source_type, source_id, granted_from_project_id NULLS FIRST
+ "#,
+ )
+ .bind(entity_id)
+ .bind(entity_type.as_ref())
+ .map(|r: sqlx::postgres::PgRow| EntityAccessRow {
+ source_id: r.get("source_id"),
+ source_type: r.get("source_type"),
+ access_level: r.get("access_level"),
+ granted_from_project_id: r.get("granted_from_project_id"),
+ })
+ .fetch_all(pool)
+ .await
+ .unwrap()
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../fixtures", scripts("upsert_test_data"))
@@ -354,3 +429,194 @@ async fn upsert_to_project_with_no_children_inserts_only_project_row(pool: Pool<
assert!(rows[0].granted_from_project_id.is_none());
assert_eq!(rows[0].access_level, AccessLevel::View);
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("upsert_test_data"))
+)]
+async fn remove_non_owner_user_entity_access_removes_direct_non_owner_users(pool: Pool<Postgres>) {
+ let owner_id = "macro|[email protected]";
+ let mut tx = pool.begin().await.unwrap();
+
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Document,
+ owner_id,
+ EntityAccessSourceType::User,
+ AccessLevel::Owner,
+ None,
+ )
+ .await;
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Document,
+ EntityAccessSourceType::User,
+ AccessLevel::View,
+ None,
+ )
+ .await;
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Document,
+ EntityAccessSourceType::User,
+ AccessLevel::Edit,
+ None,
+ )
+ .await;
+
+ remove_non_owner_user_entity_access(&mut tx, &DOC_ROOT_ID, EntityType::Document, owner_id)
+ .await
+ .unwrap();
+ tx.commit().await.unwrap();
+
+ let rows = fetch_entity_access_rows(&pool, &DOC_ROOT_ID, EntityType::Document).await;
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].source_type, "user");
+ assert_eq!(rows[0].source_id, owner_id);
+ assert_eq!(rows[0].access_level, AccessLevel::Owner);
+ assert!(rows[0].granted_from_project_id.is_none());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("upsert_test_data"))
+)]
+async fn remove_non_owner_user_entity_access_preserves_non_user_inherited_and_other_entities(
+ pool: Pool<Postgres>,
+) {
+ let owner_id = "macro|[email protected]";
+ let shared_user_id = "macro|[email protected]";
+ let root_project_id = ROOT_PROJECT_ID.to_string();
+ let mut tx = pool.begin().await.unwrap();
+
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Document,
+ owner_id,
+ EntityAccessSourceType::User,
+ AccessLevel::Owner,
+ None,
+ )
+ .await;
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Document,
+ shared_user_id,
+ EntityAccessSourceType::User,
+ AccessLevel::View,
+ None,
+ )
+ .await;
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Document,
+ shared_user_id,
+ EntityAccessSourceType::User,
+ AccessLevel::View,
+ Some(root_project_id.as_str()),
+ )
+ .await;
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Document,
+ "team-1",
+ EntityAccessSourceType::Team,
+ AccessLevel::Edit,
+ None,
+ )
+ .await;
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Document,
+ "channel-1",
+ EntityAccessSourceType::Channel,
+ AccessLevel::Comment,
+ None,
+ )
+ .await;
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_CHILD_ID,
+ EntityType::Document,
+ EntityAccessSourceType::User,
+ AccessLevel::View,
+ None,
+ )
+ .await;
+ insert_entity_access_for_test(
+ &mut tx,
+ &DOC_ROOT_ID,
+ EntityType::Chat,
+ EntityAccessSourceType::User,
+ AccessLevel::View,
+ None,
+ )
+ .await;
+
+ remove_non_owner_user_entity_access(&mut tx, &DOC_ROOT_ID, EntityType::Document, owner_id)
+ .await
+ .unwrap();
+ tx.commit().await.unwrap();
+
+ let target_rows = fetch_entity_access_rows(&pool, &DOC_ROOT_ID, EntityType::Document).await;
+ assert_eq!(target_rows.len(), 4);
+ assert!(target_rows.iter().any(|r| {
+ r.source_type == "user"
+ && r.source_id == owner_id
+ && r.access_level == AccessLevel::Owner
+ && r.granted_from_project_id.is_none()
+ }));
+ assert!(target_rows.iter().any(|r| {
+ r.source_type == "user"
+ && r.source_id == shared_user_id
+ && r.access_level == AccessLevel::View
+ && r.granted_from_project_id.as_deref() == Some(root_project_id.as_str())
+ }));
+ assert!(target_rows.iter().any(|r| {
+ r.source_type == "team"
+ && r.source_id == "team-1"
+ && r.access_level == AccessLevel::Edit
+ && r.granted_from_project_id.is_none()
+ }));
+ assert!(target_rows.iter().any(|r| {
+ r.source_type == "channel"
+ && r.source_id == "channel-1"
+ && r.access_level == AccessLevel::Comment
+ && r.granted_from_project_id.is_none()
+ }));
+ assert!(!target_rows.iter().any(|r| {
+ r.source_type == "user"
+ && r.source_id == shared_user_id
+ && r.granted_from_project_id.is_none()
+ }));
+
+ let other_entity_rows =
+ fetch_entity_access_rows(&pool, &DOC_CHILD_ID, EntityType::Document).await;
+ assert_eq!(other_entity_rows.len(), 1);
+ assert_eq!(other_entity_rows[0].source_type, "user");
+ assert_eq!(
+ other_entity_rows[0].source_id,
+ );
+ assert_eq!(other_entity_rows[0].access_level, AccessLevel::View);
+ assert!(other_entity_rows[0].granted_from_project_id.is_none());
+
+ let other_type_rows = fetch_entity_access_rows(&pool, &DOC_ROOT_ID, EntityType::Chat).await;
+ assert_eq!(other_type_rows.len(), 1);
+ assert_eq!(other_type_rows[0].source_type, "user");
+ assert_eq!(other_type_rows[0].source_id, "macro|[email protected]");
+ assert_eq!(other_type_rows[0].access_level, AccessLevel::View);
+ assert!(other_type_rows[0].granted_from_project_id.is_none());
+}
diff --git a/rust/cloud-storage/macro_db_client/fixtures/share_on_mention.sql b/rust/cloud-storage/macro_db_client/fixtures/share_on_mention.sql
new file mode 100644
index 0000000000..5131b13a90
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/fixtures/share_on_mention.sql
@@ -0,0 +1,52 @@
+-- Fixture for share_on_mention tests: a public document and a private document,
+-- each with a SharePermission/DocumentPermission link. Document ids are real
+-- UUIDs because entity_access.entity_id is a UUID column.
+
+INSERT INTO public."Organization" ("id", "name")
+VALUES (1, 'organization-one');
+
+INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id")
+VALUES ('a1111111-1111-1111-1111-111111111111', 'owner', '[email protected]', 'stripe_owner');
+
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")
+VALUES (
+ 'stripe_owner',
+ 1,
+ 'a1111111-1111-1111-1111-111111111111'
+);
+
+-- Public document (anyone can comment).
+INSERT INTO public."Document" ("id", "name", "fileType", "owner", "createdAt", "updatedAt")
+VALUES (
+ '11111111-1111-1111-1111-111111111111',
+ 'Public Doc',
+ 'pdf',
+ '2022-01-01 00:00:00',
+ '2022-01-01 00:00:00'
+);
+
+INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")
+VALUES ('sp-public', true, 'comment', '2022-01-01 00:00:00', '2022-01-01 00:00:00');
+
+INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")
+VALUES ('11111111-1111-1111-1111-111111111111', 'sp-public');
+
+-- Private document (not public).
+INSERT INTO public."Document" ("id", "name", "fileType", "owner", "createdAt", "updatedAt")
+VALUES (
+ '22222222-2222-2222-2222-222222222222',
+ 'Private Doc',
+ 'pdf',
+ '2022-01-01 00:00:00',
+ '2022-01-01 00:00:00'
+);
+
+INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")
+VALUES ('sp-private', false, NULL, '2022-01-01 00:00:00', '2022-01-01 00:00:00');
+
+INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")
+VALUES ('22222222-2222-2222-2222-222222222222', 'sp-private');
diff --git a/rust/cloud-storage/macro_db_client/src/lib.rs b/rust/cloud-storage/macro_db_client/src/lib.rs
index 834d0e173f..b2498f7ab7 100644
--- a/rust/cloud-storage/macro_db_client/src/lib.rs
+++ b/rust/cloud-storage/macro_db_client/src/lib.rs
@@ -32,6 +32,7 @@ pub mod organization;
pub mod pins;
pub mod projects;
pub mod recents;
+pub mod share_on_mention;
pub mod share_permission;
#[cfg(feature = "team")]
pub mod team;
diff --git a/rust/cloud-storage/macro_db_client/src/share_on_mention/mod.rs b/rust/cloud-storage/macro_db_client/src/share_on_mention/mod.rs
new file mode 100644
index 0000000000..228a3f0acc
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/src/share_on_mention/mod.rs
@@ -0,0 +1,67 @@
+//! Auto-share a public document with users mentioned in its comments.
+//!
+//! When a user is `@mentioned` in a document comment we notify them, but being
+//! notified isn't enough for the document to surface in their soup/inbox — that
+//! requires an explicit `entity_access` row. For **public** documents we grant
+//! the mentioned users access at the document's public access level so the
+//! mention is actionable from their inbox. Private documents are left untouched
+//! so a mention can't silently widen access beyond what was already public.
+
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::{Pool, Postgres};
+
+#[cfg(test)]
+mod test;
+
+/// Grants the mentioned users `entity_access` to the document when it is public,
+/// so the document appears in their soup.
+///
+/// No-op when the document isn't public or no users are supplied. Existing
+/// access rows are never downgraded (conflicts are ignored), and the owner row
+/// is left intact.
+#[tracing::instrument(
+ skip(db, mentioned_user_ids),
+ fields(document_id = %document_id, user_count = mentioned_user_ids.len()),
+ err
+)]
+pub async fn share_public_document_with_mentioned_users(
+ db: &Pool<Postgres>,
+ document_id: &str,
+ mentioned_user_ids: &[MacroUserIdStr<'_>],
+) -> anyhow::Result<()> {
+ if mentioned_user_ids.is_empty() {
+ return Ok(());
+ }
+
+ let user_ids: Vec<String> = mentioned_user_ids
+ .iter()
+ .map(|id| id.as_ref().to_string())
+ .collect();
+
+ // Insert one access row per mentioned user, but only when the document is
+ // public — the join against `SharePermission` yields no rows otherwise, so
+ // the whole statement becomes a no-op for private documents. We grant the
+ // same level the document is public at, and `DO NOTHING` ensures we never
+ // clobber a user's pre-existing (possibly higher) access.
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ SELECT dp."documentId"::uuid, 'document', u.user_id, 'user', sp."publicAccessLevel"::"AccessLevel"
+ FROM "DocumentPermission" dp
+ JOIN "SharePermission" sp ON sp.id = dp."sharePermissionId"
+ CROSS JOIN UNNEST($2::text[]) AS u(user_id)
+ WHERE dp."documentId" = $1
+ AND sp."isPublic" = true
+ AND sp."publicAccessLevel" IS NOT NULL
+ ON CONFLICT (entity_id, entity_type, source_id, source_type)
+ WHERE granted_from_project_id IS NULL
+ DO NOTHING
+ "#,
+ document_id,
+ user_ids.as_slice(),
+ )
+ .execute(db)
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/macro_db_client/src/share_on_mention/test.rs b/rust/cloud-storage/macro_db_client/src/share_on_mention/test.rs
new file mode 100644
index 0000000000..85dae35d50
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/src/share_on_mention/test.rs
@@ -0,0 +1,109 @@
+use super::*;
+
+const PUBLIC_DOC: &str = "11111111-1111-1111-1111-111111111111";
+const PRIVATE_DOC: &str = "22222222-2222-2222-2222-222222222222";
+
+async fn access_level_for(
+ pool: &Pool<Postgres>,
+ document_id: &str,
+ source_id: &str,
+) -> Option<String> {
+ let entity_id = macro_uuid::string_to_uuid(document_id).unwrap();
+ sqlx::query_scalar!(
+ r#"
+ SELECT access_level::text as "access_level!"
+ FROM entity_access
+ WHERE entity_id = $1
+ AND entity_type = 'document'
+ AND source_type = 'user'
+ AND source_id = $2
+ "#,
+ entity_id,
+ source_id,
+ )
+ .fetch_optional(pool)
+ .await
+ .unwrap()
+}
+
+#[sqlx::test(fixtures(path = "../../fixtures", scripts("share_on_mention")))]
+async fn shares_public_document_with_mentioned_users(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let mentioned = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+
+ share_public_document_with_mentioned_users(&pool, PUBLIC_DOC, std::slice::from_ref(&mentioned))
+ .await?;
+
+ // The mentioned user gets access at the document's public access level.
+ assert_eq!(
+ access_level_for(&pool, PUBLIC_DOC, mentioned.as_ref()).await,
+ Some("comment".to_string()),
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(fixtures(path = "../../fixtures", scripts("share_on_mention")))]
+async fn does_not_share_private_document(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let mentioned = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+
+ share_public_document_with_mentioned_users(
+ &pool,
+ PRIVATE_DOC,
+ std::slice::from_ref(&mentioned),
+ )
+ .await?;
+
+ // Private documents are left untouched — no access is granted.
+ assert_eq!(
+ access_level_for(&pool, PRIVATE_DOC, mentioned.as_ref()).await,
+ None,
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(fixtures(path = "../../fixtures", scripts("share_on_mention")))]
+async fn does_not_downgrade_existing_access(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let mentioned = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let entity_id = macro_uuid::string_to_uuid(PUBLIC_DOC).unwrap();
+
+ // The user already has edit access to the public document.
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, 'document', $2, 'user', 'edit')
+ "#,
+ entity_id,
+ mentioned.as_ref(),
+ )
+ .execute(&pool)
+ .await?;
+
+ share_public_document_with_mentioned_users(&pool, PUBLIC_DOC, std::slice::from_ref(&mentioned))
+ .await?;
+
+ // The pre-existing (higher) access level is preserved, not clobbered.
+ assert_eq!(
+ access_level_for(&pool, PUBLIC_DOC, mentioned.as_ref()).await,
+ Some("edit".to_string()),
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(fixtures(path = "../../fixtures", scripts("share_on_mention")))]
+async fn empty_recipients_is_a_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let entity_id = macro_uuid::string_to_uuid(PUBLIC_DOC).unwrap();
+ share_public_document_with_mentioned_users(&pool, PUBLIC_DOC, &[]).await?;
+
+ let count = sqlx::query_scalar!(
+ r#"SELECT COUNT(*) as "count!" FROM entity_access WHERE entity_id = $1"#,
+ entity_id,
+ )
+ .fetch_one(&pool)
+ .await?;
+
+ assert_eq!(count, 0);
+
+ Ok(())
+}