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(soup): omit email threads when the CRM domain scope is rejected (#9606)

teod7cad3a091c2
diff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.md
index 7e139d2303..83d6326c25 100644
--- a/crates/soup/AGENTS.md
+++ b/crates/soup/AGENTS.md
@@ -84,6 +84,11 @@ rows, initiatives, ...) and get back a single unified, paginated result.
the caller's mailbox. Keep browser requests bounded; never expand every CRM
record into client-side filters or raise ingress limits to fit them.
+- A `crm_domains` (`ecd`) scope that email rejects as not found or not
+ permitted (archived company, email sync off) leaves email threads out of the
+ page instead of failing it; `handle_email_request` matches those two errors
+ only. Email's precheck is the only gate on the team-wide widening, so never
+ drop just the failing domains and keep the scope.
- Agent sessions named by id (an `Id` literal in `cursor_soup`, which GraphQL
`agentSession` and its log use, and `by_ids`) also accept a grant on the
document or call whose live thread the session runs in, matching
diff --git a/crates/soup/src/domain/service.rs b/crates/soup/src/domain/service.rs
index 7856f77985..9e542921f7 100644
--- a/crates/soup/src/domain/service.rs
+++ b/crates/soup/src/domain/service.rs
@@ -25,7 +25,7 @@ use crm::domain::{
};
use either::Either;
use email::domain::{
- models::{GetEmailsRequest, PreviewView, PreviewViewStandardLabel},
+ models::{EmailErr, GetEmailsRequest, PreviewView, PreviewViewStandardLabel},
ports::EmailPreviewServiceReadOnly,
};
use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};
@@ -1299,7 +1299,18 @@ where
return Ok(Either::Left(None.into_iter()));
};
- let email_response = self.email_service.get_email_thread_previews(req).await?;
+ let email_response = match self.email_service.get_email_thread_previews(req).await {
+ Ok(response) => response,
+ // An archived company, or one whose domains have left the team's
+ // CRM, still opens with its email list. Email authorizes only
+ // the team-wide widening, so its threads are left out of the page
+ // and every other source keeps its results.
+ Err(err @ (EmailErr::CrmDomainNotFound(_) | EmailErr::CrmDomainNotPermitted(_))) => {
+ tracing::warn!(error = %err, "CRM domain scope rejected; omitting email threads");
+ return Ok(Either::Left(None.into_iter()));
+ }
+ Err(err) => return Err(err.into()),
+ };
let mut frecency_scores: Vec<Option<AggregateFrecency>> =
Vec::with_capacity(email_response.items.len());
diff --git a/crates/soup/src/domain/service/tests.rs b/crates/soup/src/domain/service/tests.rs
index 53788c0d9e..dcc57a3b71 100644
--- a/crates/soup/src/domain/service/tests.rs
+++ b/crates/soup/src/domain/service/tests.rs
@@ -47,6 +47,7 @@ use super::*;
mod agent_metadata;
mod attention;
mod crm_association;
+mod crm_scope;
mod exclusions;
mod favorites;
diff --git a/crates/soup/src/domain/service/tests/crm_scope.rs b/crates/soup/src/domain/service/tests/crm_scope.rs
new file mode 100644
index 0000000000..63941ecba3
--- /dev/null
+++ b/crates/soup/src/domain/service/tests/crm_scope.rs
@@ -0,0 +1,153 @@
+//! CRM-scoped email (`crm_domains`) through the Soup service: which email
+//! authorization failures leave the email source out of the page and which
+//! still fail the request.
+use super::*;
+
+const USER: &str = "macro|[email protected]";
+const TEAM: Uuid = Uuid::from_u128(0x7e);
+const DOCUMENT: Uuid = Uuid::from_u128(0xd0c);
+
+/// Builds the error a stubbed email service fails with.
+type MakeEmailErr = fn() -> EmailErr;
+
+/// Fails every email preview request with the error `make` builds.
+struct FailingEmailPreviewService {
+ make: MakeEmailErr,
+ calls: Arc<Mutex<usize>>,
+}
+
+impl EmailPreviewServiceReadOnly for FailingEmailPreviewService {
+ async fn get_email_thread_previews(
+ &self,
+ req: email::domain::models::GetEmailsRequest,
+ ) -> Result<PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>, EmailErr>
+ {
+ assert!(req.crm_scope.is_some(), "the request carries the CRM scope");
+ *self.calls.lock().unwrap() += 1;
+ Err((self.make)())
+ }
+}
+
+async fn crm_domain_soup(make: MakeEmailErr) -> (Result<Vec<String>, SoupErr>, usize) {
+ let user = MacroUserIdStr::parse_from_str(USER).unwrap();
+ let mut soup_mock = MockSoupRepo::new();
+ soup_mock
+ .expect_unexpanded_generic_cursor_soup()
+ .returning(|_params| {
+ Box::pin(async move {
+ Ok(vec![SoupItem::Document(soup_document_uuid_with_updated(
+ DOCUMENT,
+ Default::default(),
+ ))])
+ })
+ });
+ let calls = Arc::new(Mutex::new(0));
+ let team_receipt = EntityAccessReceipt::<MemberTeamRole>::dangerously_assert_authenticated_user(
+ user.clone(),
+ &TEAM.to_string(),
+ EntityType::Team,
+ );
+
+ let result = SoupImpl::new(
+ soup_mock,
+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
+ FailingEmailPreviewService {
+ make,
+ calls: calls.clone(),
+ },
+ NoopCommsService,
+ NoopCallRecordQueryService,
+ NoOpCrmService,
+ NoopPullRequestListing,
+ )
+ .get_user_soup(
+ SoupRequest {
+ sort_direction: SoupSortDirection::default(),
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::All,
+ ),
+ link_ids: vec![Uuid::from_u128(0x11)],
+ soup_type: SoupType::UnExpanded,
+ limit: 20,
+ cursor: SoupQuery::new_sort_simple(
+ SimpleSortMethod::UpdatedAt,
+ EntityFilters {
+ email_filters: item_filters::EmailFilters {
+ crm_domains: vec!["example.com".to_string()],
+ ..item_filters::EmailFilters::default()
+ },
+ ..EntityFilters::default()
+ },
+ ),
+ user,
+ },
+ Some(team_receipt),
+ )
+ .await
+ .map(|output| {
+ output
+ .type_erase()
+ .items
+ .iter()
+ .map(|item| item.entity().entity_id.to_string())
+ .collect()
+ });
+ let calls = *calls.lock().unwrap();
+ (result, calls)
+}
+
+#[tokio::test]
+async fn unknown_crm_domain_omits_email_threads() {
+ let (result, calls) =
+ crm_domain_soup(|| EmailErr::CrmDomainNotFound("example.com".to_string())).await;
+
+ let ids = result.expect("an unknown CRM domain is not a server error");
+ assert_eq!(calls, 1);
+ assert_eq!(
+ ids,
+ vec![DOCUMENT.to_string()],
+ "other sources keep their items"
+ );
+}
+
+#[tokio::test]
+async fn not_permitted_crm_domain_omits_email_threads() {
+ let (result, calls) =
+ crm_domain_soup(|| EmailErr::CrmDomainNotPermitted("example.com".to_string())).await;
+
+ let ids = result.expect("an archived company's domain is not a server error");
+ assert_eq!(calls, 1);
+ assert_eq!(
+ ids,
+ vec![DOCUMENT.to_string()],
+ "other sources keep their items"
+ );
+}
+
+#[tokio::test]
+async fn other_email_errors_still_fail_the_request() {
+ let cases: [(MakeEmailErr, &str); 5] = [
+ (|| EmailErr::CrmDisabledForTeam, "CrmDisabledForTeam"),
+ (|| EmailErr::Unauthorized, "Unauthorized"),
+ (
+ || EmailErr::CrmAddressNotFound("[email protected]".to_string()),
+ "CrmAddressNotFound",
+ ),
+ (
+ || EmailErr::CrmAddressNotPermitted("[email protected]".to_string()),
+ "CrmAddressNotPermitted",
+ ),
+ (
+ || EmailErr::RepoErr(anyhow::anyhow!("database unavailable")),
+ "RepoErr",
+ ),
+ ];
+ for (make, name) in cases {
+ let (result, _) = crm_domain_soup(make).await;
+ let err = result.expect_err(name);
+ assert!(
+ matches!(err, SoupErr::EmailErr(_)),
+ "{name} should stay an email error, got {err:?}"
+ );
+ }
+}