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.

fix(messages): send messages that mention items the sender cannot view (#9220)

Eric Hayesd67b8866b3d6
diff --git a/crates/channels/src/inbound/toolset/send_channel_message.rs b/crates/channels/src/inbound/toolset/send_channel_message.rs
index ad66f774fa..ee6a87b96c 100644
--- a/crates/channels/src/inbound/toolset/send_channel_message.rs
+++ b/crates/channels/src/inbound/toolset/send_channel_message.rs
@@ -102,8 +102,7 @@ fn send_error(err: MessageError) -> ToolCallError {
let description = match &err {
MessageError::Invalid(message) => (*message).to_string(),
MessageError::Forbidden => {
- "not allowed to send this message: it attaches or mentions an item the user cannot view"
- .to_string()
+ "not allowed to send this message: it attaches an item the user cannot view".to_string()
}
MessageError::NotFound => "thread not found in this channel".to_string(),
MessageError::Conflict | MessageError::Repository(_) => {
diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rs
index 061381e164..9e6e35e4c4 100644
--- a/crates/messages/src/domain/service.rs
+++ b/crates/messages/src/domain/service.rs
@@ -368,7 +368,8 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
{
return Err(MessageError::Invalid(error));
}
- self.validate_references(&access, &input.mentions, &input.attachments)
+ input.mentions = self
+ .validate_references(&access, input.mentions, &input.attachments)
.await?;
let canonical_root_id = match parent {
MessageParent::Call(call_id) => {
@@ -488,12 +489,13 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
"a message needs content or an attachment",
));
}
- self.validate_references(
- &access,
- &input.mentions,
- input.attachments.as_deref().unwrap_or_default(),
- )
- .await?;
+ input.mentions = self
+ .validate_references(
+ &access,
+ input.mentions,
+ input.attachments.as_deref().unwrap_or_default(),
+ )
+ .await?;
// Reconciliation may repeat a bot's final reply after a process died
// between patching it and recording success. Identical content must
// not produce another edit event or completion notification.
@@ -759,12 +761,16 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
Ok(resolved)
}
+ /// Rejects malformed references and attachments the sender cannot view, and
+ /// returns the mentions to record. A mention of something the sender cannot
+ /// view stays in the content but is not recorded, so it shares, notifies,
+ /// and triggers nothing.
async fn validate_references(
&self,
access: &EntityAccessReceipt<MessageWrite>,
- mentions: &[SimpleMention],
+ mentions: Vec<SimpleMention>,
attachments: &[NewAttachment],
- ) -> Result<(), MessageError> {
+ ) -> Result<Vec<SimpleMention>, MessageError> {
if attachments.len() > 10 || mentions.len() > 100 {
return Err(MessageError::Invalid("too many message references"));
}
@@ -775,7 +781,8 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
}
}
let mut checked = std::collections::HashSet::new();
- for (kind, id, mention) in mentions
+ let mut hidden = std::collections::HashSet::new();
+ for (raw_kind, id, mention) in mentions
.iter()
.map(|m| (m.entity_type.as_str(), m.entity_id.as_str(), true))
.chain(
@@ -784,13 +791,13 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
.map(|a| (a.entity_type.as_str(), a.entity_id.as_str(), false)),
)
{
- if !checked.insert((kind, id, mention)) {
+ if !checked.insert((raw_kind, id, mention)) {
continue;
}
// Editors also emit display-only chips (dates, contacts, colors) as
// mentions. They name nothing that can be authorized, so they are
// stored as written, exactly as the channel writer did before.
- let Some(kind) = MessageReferenceKind::parse(kind) else {
+ let Some(kind) = MessageReferenceKind::parse(raw_kind) else {
continue;
};
let entity_type = match kind {
@@ -848,10 +855,16 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
.can_view(access.auth(), entity_type, id)
.await?
{
- return Err(MessageError::Forbidden);
+ if !mention {
+ return Err(MessageError::Forbidden);
+ }
+ hidden.insert((raw_kind.to_owned(), id.to_owned()));
}
}
- Ok(())
+ Ok(mentions
+ .into_iter()
+ .filter(|m| !hidden.contains(&(m.entity_type.clone(), m.entity_id.clone())))
+ .collect())
}
async fn ensure_parent(&self, parent: &MessageParent) -> Result<(), MessageError> {
diff --git a/crates/messages/src/domain/service/test.rs b/crates/messages/src/domain/service/test.rs
index c0680cc01b..6fc3ae4cf3 100644
--- a/crates/messages/src/domain/service/test.rs
+++ b/crates/messages/src/domain/service/test.rs
@@ -698,7 +698,7 @@ async fn inaccessible_references_are_rejected_before_persistence() {
#[tokio::test]
async fn user_mentions_do_not_require_or_grant_parent_sharing() {
let service = MessageService::new(fixture(), Events::default());
- let mentions = [SimpleMention {
+ let mentions = vec![SimpleMention {
entity_type: "user".into(),
entity_id: "macro|[email protected]".into(),
}];
@@ -707,12 +707,12 @@ async fn user_mentions_do_not_require_or_grant_parent_sharing() {
service
.validate_references(
&access("macro|[email protected]", "doc", AccessLevel::Comment),
- &mentions,
+ mentions.clone(),
&[],
)
.await
.unwrap();
- let invalid = [SimpleMention {
+ let invalid = vec![SimpleMention {
entity_type: "user".into(),
entity_id: "arbitrary-string".into(),
}];
@@ -720,7 +720,7 @@ async fn user_mentions_do_not_require_or_grant_parent_sharing() {
service
.validate_references(
&access("macro|[email protected]", "doc", AccessLevel::Comment),
- &invalid,
+ invalid,
&[]
)
.await,
@@ -778,6 +778,7 @@ impl MessageReferenceAccess for ReferenceAccess {
#[tokio::test]
async fn editor_reference_tags_are_authorized_for_posts_and_edits() {
for (tag, entity_type) in [
+ ("channel", EntityType::Channel),
("form", EntityType::Form),
("thread", EntityType::EmailThread),
("email", EntityType::EmailThread),
@@ -792,7 +793,8 @@ async fn editor_reference_tags_are_authorized_for_posts_and_edits() {
allowed,
checked: Arc::default(),
};
- let service = MessageService::new(repo.clone(), Events::default())
+ let events = Events::default();
+ let service = MessageService::new(repo.clone(), events.clone())
.with_references(references.clone());
let mut input = post_input();
input.mentions = vec![SimpleMention {
@@ -812,18 +814,25 @@ async fn editor_reference_tags_are_authorized_for_posts_and_edits() {
)
.await;
for result in [posted, edited] {
+ let message = result.unwrap();
if allowed {
- let message = result.unwrap();
assert_eq!(message.mentions[0].entity_type, tag);
} else {
- assert!(
- matches!(result, Err(MessageError::Forbidden)),
- "{tag}: {result:?}"
- );
+ assert!(message.mentions.is_empty(), "{tag}: {message:?}");
}
}
- assert_eq!(repo.creates.lock().unwrap().len(), usize::from(allowed));
- assert_eq!(repo.edits.lock().unwrap().len(), usize::from(allowed));
+ // Delivery shares and notifies from the event's mentions, so an unviewable
+ // mention must never reach it.
+ for event in events.0.lock().unwrap().iter() {
+ let (MessageChange::Posted { mentions, .. }
+ | MessageChange::Edited { mentions, .. }) = &event.change
+ else {
+ panic!("expected post or edit");
+ };
+ assert_eq!(mentions.len(), usize::from(allowed), "{tag}");
+ }
+ assert_eq!(repo.creates.lock().unwrap().len(), 1);
+ assert_eq!(repo.edits.lock().unwrap().len(), 1);
assert_eq!(
*references.checked.lock().unwrap(),
vec![(entity_type, Uuid::from_u128(30).to_string()); 2]
@@ -903,10 +912,14 @@ async fn a_group_remains_one_authored_reference_and_resolves_current_recipients_
entity_type: "document".into(),
entity_id: "private".into(),
};
- assert!(matches!(
- service.post(channel_access(), input.clone()).await,
- Err(MessageError::Forbidden)
- ));
+ assert_eq!(
+ service
+ .post(channel_access(), input.clone())
+ .await
+ .unwrap()
+ .mentions,
+ input.mentions[..1]
+ );
input.mentions = vec![
SimpleMention {
entity_type: "user".into(),
@@ -918,7 +931,7 @@ async fn a_group_remains_one_authored_reference_and_resolves_current_recipients_
service.post(channel_access(), input).await,
Err(MessageError::Invalid("too many message references"))
));
- assert_eq!(repo.creates.lock().unwrap().len(), 1);
+ assert_eq!(repo.creates.lock().unwrap().len(), 2);
}
#[tokio::test]
@@ -1581,15 +1594,17 @@ async fn display_only_mention_kinds_are_stored_without_authorization() {
entity_type: "agent_session".into(),
entity_id: Uuid::from_u128(10).to_string(),
});
- assert!(matches!(
+ assert_eq!(
service
.post(
access("macro|[email protected]", "doc", AccessLevel::Comment),
- input,
+ input.clone(),
)
- .await,
- Err(MessageError::Forbidden)
- ));
+ .await
+ .unwrap()
+ .mentions,
+ input.mentions[..2]
+ );
assert_eq!(
*checks.checked.lock().unwrap(),
vec![(EntityType::AgentSession, Uuid::from_u128(10).to_string())]
diff --git a/crates/messages/src/domain/service/test/event_posts.rs b/crates/messages/src/domain/service/test/event_posts.rs
index 51efb78de8..10bbc3b869 100644
--- a/crates/messages/src/domain/service/test/event_posts.rs
+++ b/crates/messages/src/domain/service/test/event_posts.rs
@@ -137,9 +137,11 @@ async fn trusted_event_posts_still_validate_ids_content_and_references() {
let mut empty = post_input();
empty.content.clear();
let mut inaccessible = post_input();
- inaccessible.mentions = vec![SimpleMention {
+ inaccessible.attachments = vec![NewAttachment {
entity_type: "document".to_owned(),
entity_id: "private-document".to_owned(),
+ width: None,
+ height: None,
}];
for (id, input) in [
(Uuid::new_v4(), post_input()),