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
Seanaye/feat/lazy extraction (#4672)
Sean Aye410421937af6
diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.tsindex 99ae429381..5eddef1d24 100644--- a/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.ts+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.ts@@ -16,6 +16,7 @@ include all of the team's visible CRM companies. *//** Optional `crm_companies.hidden` filter. `None` = visible only(default for back-compat with non-admin callers). `Some(false)` =visible only (explicit). `Some(true)` = hidden only — requires-admin/owner team role; enforced upstream in soup's axum router. */+admin/owner team role; enforced by the CRM service from the+caller's team receipt. */hidden?: CrmCompanyFiltersHidden;}diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanyFiltersHidden.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFiltersHidden.tsindex a8d81bb3f3..db57fa1c7b 100644--- a/js/app/packages/service-clients/service-search/generated/models/crmCompanyFiltersHidden.ts+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFiltersHidden.ts@@ -9,6 +9,7 @@* Optional `crm_companies.hidden` filter. `None` = visible only(default for back-compat with non-admin callers). `Some(false)` =visible only (explicit). `Some(true)` = hidden only — requires-admin/owner team role; enforced upstream in soup's axum router.+admin/owner team role; enforced by the CRM service from the+caller's team receipt.*/export type CrmCompanyFiltersHidden = boolean | null;diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex c5b8b8a702..a5ddb45e34 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -893,7 +893,7 @@},"hidden": {"type": ["boolean", "null"],- "description": "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin/owner team role; enforced upstream in soup's axum router."+ "description": "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin/owner team role; enforced by the CRM service from the\ncaller's team receipt."}}},diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.tsindex 07a4b3e2f1..26f49eec25 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.ts@@ -16,6 +16,7 @@ include all of the team's visible CRM companies. *//** Optional `crm_companies.hidden` filter. `None` = visible only(default for back-compat with non-admin callers). `Some(false)` =visible only (explicit). `Some(true)` = hidden only — requires-admin/owner team role; enforced upstream in soup's axum router. */+admin/owner team role; enforced by the CRM service from the+caller's team receipt. */hidden?: CrmCompanyFiltersHidden;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFiltersHidden.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFiltersHidden.tsindex 5baf4a0229..d841a8a699 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFiltersHidden.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFiltersHidden.ts@@ -9,6 +9,7 @@* Optional `crm_companies.hidden` filter. `None` = visible only(default for back-compat with non-admin callers). `Some(false)` =visible only (explicit). `Some(true)` = hidden only — requires-admin/owner team role; enforced upstream in soup's axum router.+admin/owner team role; enforced by the CRM service from the+caller's team receipt.*/export type CrmCompanyFiltersHidden = boolean | null;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex d932075b01..0a6beb532a 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -8876,7 +8876,7 @@ export const postItemsSoupBody = zod.boolean().nullish().describe(- "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin\/owner team role; enforced upstream in soup's axum router."+ "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin\/owner team role; enforced by the CRM service from the\ncaller's team receipt."),}).optional()diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 79b3edbdaf..383173f32f 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -12749,7 +12749,7 @@},"hidden": {"type": ["boolean", "null"],- "description": "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin/owner team role; enforced upstream in soup's axum router."+ "description": "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin/owner team role; enforced by the CRM service from the\ncaller's team receipt."}}},diff --git a/nix/js-app.nix b/nix/js-app.nixindex 3d0a8d19e6..bebc1ec961 100644--- a/nix/js-app.nix+++ b/nix/js-app.nix@@ -77,6 +77,8 @@cargo-tauricargo-infocargo-udeps+ cmake+ nasmpulumipulumiPackages.pulumi-nodejspulumiPackages.pulumi-aws-native@@ -123,6 +125,14 @@];jsLibraries = if isDarwin then jsDarwinLibraries else jsLinuxLibraries;+ jsPkgConfigPath = pkgs.lib.makeSearchPath "lib/pkgconfig" [+ jsPkgs.openssl.dev+ ];+ jsCmakeFixEnv = {+ # Match the default dev shell's aws-lc-sys path. Its default cc builder+ # can reject wrapped cross compilers; the CMake builder needs cmake+nasm.+ AWS_LC_SYS_CMAKE_BUILDER = "1";+ };jsLinuxShellHook = ''export LD_LIBRARY_PATH="${pkgs.lib.makeLibraryPath jsLibraries}''${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"export XDG_DATA_DIRS="${jsPkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${jsPkgs.gsettings-desktop-schemas.name}:${jsPkgs.gtk3}/share/gsettings-schemas/${jsPkgs.gtk3.name}''${XDG_DATA_DIRS:+:$XDG_DATA_DIRS}"@@ -133,8 +143,9 @@js-app = jsPkgs.mkShell ({buildInputs = jsPackages ++ jsLibraries;- PKG_CONFIG_PATH = "${jsPkgs.openssl.dev}/lib/pkgconfig";+ PKG_CONFIG_PATH = jsPkgConfigPath;}+ // jsCmakeFixEnv// pkgs.lib.optionalAttrs isLinux {shellHook = jsLinuxShellHook;GIO_MODULE_DIR = "${jsPkgs.glib-networking}/lib/gio/modules/";@@ -142,15 +153,15 @@);}// pkgs.lib.optionalAttrs isLinux {- js-app-android = jsPkgs.mkShell {+ js-app-android = jsPkgs.mkShell ({buildInputs = jsAndroidPackages ++ jsLibraries;- PKG_CONFIG_PATH = "${jsPkgs.openssl.dev}/lib/pkgconfig";+ PKG_CONFIG_PATH = jsPkgConfigPath;shellHook = jsLinuxShellHook;ANDROID_HOME = "${android_sdk}/libexec/android-sdk";NDK_HOME = "${android_sdk}/libexec/android-sdk/ndk/26.3.11579264";GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${android_sdk}/libexec/android-sdk/build-tools/35.0.0/aapt2";GIO_MODULE_DIR = "${jsPkgs.glib-networking}/lib/gio/modules/";- };+ } // jsCmakeFixEnv);};};}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 252f64bfdd..85edbd113c 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5807,15 +5807,19 @@ dependencies = ["anyhow","async-graphql","async-trait",+ "axum",+ "axum-extra","chrono","document_sub_type","either",+ "email","entity_access","filter_ast","item_filters","macro_user_id","model-entity","model_file_type",+ "model_user","models_pagination","models_properties","models_soup",diff --git a/rust/cloud-storage/crm/src/domain/auth.rs b/rust/cloud-storage/crm/src/domain/auth.rsindex 4f9317277d..d95dc0fd06 100644--- a/rust/cloud-storage/crm/src/domain/auth.rs+++ b/rust/cloud-storage/crm/src/domain/auth.rs@@ -189,6 +189,15 @@ impl<T: RequiredPermission> CrmTeamReceipt<T> {&self.receipt}+ /// Whether the caller's team role reveals hidden rows (admin/owner).+ /// Derived from the receipt's actual team role, so the service — not+ /// the caller — enforces the hidden gate.+ pub(crate) fn include_hidden(&self) -> bool {+ self.receipt+ .entity_permission()+ .allows_team_role(entity_access::domain::models::TeamRole::Admin)+ }+/// Test-only: mints an `Owner` receipt with no access check.#[cfg(test)]#[allow(dead_code)]diff --git a/rust/cloud-storage/crm/src/domain/auth/test.rs b/rust/cloud-storage/crm/src/domain/auth/test.rsindex 54903e1321..d3f246c97a 100644--- a/rust/cloud-storage/crm/src/domain/auth/test.rs+++ b/rust/cloud-storage/crm/src/domain/auth/test.rs@@ -115,3 +115,32 @@ fn comment_receipt_derives_entity_and_rejects_non_crm() {.is_err());}++#[test]+fn team_receipt_hidden_gate_derives_from_team_role() {+ use entity_access::domain::models::{Entity, EntityPermission, MemberTeamRole, TeamRole};+ use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};++ let team = team_uuid();+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ let receipt_with_role = |role: TeamRole| {+ CrmTeamReceipt::from_team_receipt(+ EntityAccessReceipt::<MemberTeamRole>::try_new_authenticated_user(+ user.clone(),+ Entity {+ entity_id: team.to_string(),+ entity_type: EntityType::Team,+ },+ EntityPermission::TeamRole { role },+ )+ .unwrap(),+ )+ .unwrap()+ };++ assert!(!receipt_with_role(TeamRole::Member).include_hidden());+ assert!(receipt_with_role(TeamRole::Admin).include_hidden());+ assert!(receipt_with_role(TeamRole::Owner).include_hidden());+}diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rsindex 15a6aaa2c8..8b3d17011e 100644--- a/rust/cloud-storage/crm/src/domain/model.rs+++ b/rust/cloud-storage/crm/src/domain/model.rs@@ -266,6 +266,10 @@ pub enum CrmError {/// Request rejected for a client-side reason (e.g. blank comment text).#[error("{0}")]InvalidRequest(String),+ /// The request asks for hidden CRM rows but the caller's team role is+ /// below admin/owner.+ #[error("Querying hidden CRM companies requires admin/owner team role")]+ AdminRoleRequired,/// Tried to mutate a CRM company in a way that contradicts its/// `hidden = true` state — currently raised when attempting to/// re-enable `email_sync` on a hidden company.diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rsindex 48558a100d..c5d946053c 100644--- a/rust/cloud-storage/crm/src/domain/service.rs+++ b/rust/cloud-storage/crm/src/domain/service.rs@@ -174,6 +174,10 @@ pub trait CrmService: Clone + Send + Sync + 'static {/// required by the `Viewed*` sort variants (per-user/// `UserHistory` join); see/// [`CompaniesRepository::list_companies_for_soup`].+ ///+ /// `hidden = Some(true)` requires an admin/owner role on the+ /// receipt; the service returns [`CrmError::AdminRoleRequired`]+ /// otherwise.#[allow(clippy::too_many_arguments)]fn list_companies_for_soup(&self,@@ -521,6 +525,9 @@ wherecursor: Option<CrmCompanySoupCursor>,limit: i64,) -> Result<Vec<CrmCompanyForSoup>, CrmError> {+ if hidden == Some(true) && !access.include_hidden() {+ return Err(CrmError::AdminRoleRequired);+ }let team_id = access.team_id();self.companies_repository.list_companies_for_soup(&team_id, user_id, company_ids, hidden, sort, cursor, limit)diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rsindex 172337638f..0c50bba474 100644--- a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs+++ b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs@@ -164,6 +164,12 @@ impl IntoResponse for CrmError {message: message.into(),}),),+ CrmError::AdminRoleRequired => (+ StatusCode::FORBIDDEN,+ Json(ErrorResponse {+ message: "querying hidden crm entities requires admin/owner team role".into(),+ }),+ ),CrmError::CompanyHidden => (StatusCode::CONFLICT,Json(ErrorResponse {diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex ec1f81073e..f12df2c624 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -106,7 +106,7 @@ pub(crate) type DssCrmService = crm::domain::service::CrmServiceImpl<crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,>;-type DssEmailService = EmailServiceImpl<+pub(crate) type DssEmailService = EmailServiceImpl<EmailPgRepo,FrecencyQueryServiceImpl<FrecencyPgStorage>,email::domain::ports::NoOpEnqueuer,@@ -130,6 +130,17 @@ pub(crate) type DssSoupService = SoupImpl<type DssSoupState = SoupRouterState<DssSoupService, DssEmailService, EntityAccessService>;+/// GraphQL Soup schema wired to the DSS services; the `ApiContext` state+/// parameter lets GraphQL resolvers run the same axum extractors as the REST+/// routes, lazily, against the stored request parts.+#[cfg(feature = "graphql")]+pub(crate) type DssGraphqlSoupSchema = graphql_soup::SharedSoupSchema<+ DssSoupService,+ DssEmailService,+ EntityAccessService,+ ApiContext,+>;+type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;pub(crate) type PropertiesService = PropertiesServiceImpl<@@ -340,7 +351,7 @@ pub(crate) struct ApiContext {pub dynamo_db: aws_sdk_dynamodb::Client,pub soup_router_state: DssSoupState,#[cfg(feature = "graphql")]- pub graphql_soup_schema: graphql_soup::SharedSoupSchema<DssSoupService>,+ pub graphql_soup_schema: DssGraphqlSoupSchema,#[cfg(feature = "graphql")]pub graphql_notification_reader: Arc<dyn graphql_soup::SoupNotificationEdgeReader>,pub favorites_state: DssFavoritesState,@@ -410,3 +421,14 @@ impl FromRef<ApiContext> for SearchHandlerState {SearchHandlerState::from(ctx)}}++/// `#[derive(FromRef)]` only exposes direct field types, so hand the email+/// router state out of the nested soup router state for extractors like+/// `MultiEmailLinkExtractor` that key off `EmailRouterState`.+impl FromRef<ApiContext>+ for email::inbound::axum::previews_router::EmailRouterState<DssEmailService>+{+ fn from_ref(ctx: &ApiContext) -> Self {+ FromRef::from_ref(&ctx.soup_router_state)+ }+}diff --git a/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs b/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rsindex 469c4ba99b..845be79ada 100644--- a/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs+++ b/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs@@ -1,19 +1,14 @@use crate::api::context::ApiContext;-use async_graphql::{Response, ServerError, http::GraphiQLSource};+use async_graphql::{ServerError, http::GraphiQLSource};use async_graphql_axum::{GraphQLRequest, GraphQLResponse};use axum::{Router,- extract::{OriginalUri, State},- response::Html,+ extract::{FromRequest, FromRequestParts, OriginalUri, Request, State},+ response::{Html, IntoResponse, Response},routing::get,};use axum_extra::extract::Cached;-use email::domain::ports::EmailService;-use entity_access::domain::{- models::{Entity, EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole},- ports::EntityAccessService as _,-};-use graphql_soup::GraphqlSoupRequestContext;+use graphql_soup::GraphqlSoupRequestParts;use model_user::axum_extractor::OptionalMacroUserExtractor;pub(crate) fn router() -> Router<ApiContext> {@@ -24,59 +19,46 @@ async fn graphiql(OriginalUri(uri): OriginalUri) -> Html<String> {Html(GraphiQLSource::build().endpoint(uri.path()).finish())}-async fn handler(- State(state): State<ApiContext>,- Cached(OptionalMacroUserExtractor { macro_user_id, .. }): Cached<OptionalMacroUserExtractor>,- request: GraphQLRequest,-) -> GraphQLResponse {- let request = request.into_inner();+async fn handler(State(state): State<ApiContext>, req: Request) -> Response {+ let (mut parts, body) = req.into_parts();- let Some(macro_user_id) = macro_user_id else {- if is_introspection_query(&request.query) {- return state.graphql_soup_schema.execute(request).await.into();- }- return Response::from_errors(vec![ServerError::new(- "authentication required for GraphQL Soup queries",- None,- )])- .into();- };+ // Authentication stays eager: it gates execution for non-introspection+ // queries and primes the `Cached` entry that resolvers extract lazily.+ let auth =+ match Cached::<OptionalMacroUserExtractor>::from_request_parts(&mut parts, &state).await {+ Ok(Cached(auth)) => auth,+ Err(err) => return err.into_response(),+ };- let link_ids = match state- .soup_router_state- .email_service()- .get_inboxes_for_macro_id(macro_user_id.clone())- .await- {- Ok(links) => links.into_iter().map(|link| link.id).collect(),- Err(err) => {- return Response::from_errors(vec![ServerError::new(- format!("failed to load caller inboxes: {err}"),- None,- )])- .into();- }+ // `GraphQLRequest` consumes a whole request, but the original parts (with+ // the middleware-populated extensions) must survive for the resolvers, so+ // parse the body from a shallow copy of method/uri/headers.+ let mut synthetic = Request::new(body);+ *synthetic.method_mut() = parts.method.clone();+ *synthetic.uri_mut() = parts.uri.clone();+ *synthetic.headers_mut() = parts.headers.clone();++ let request = match <GraphQLRequest as FromRequest<()>>::from_request(synthetic, &()).await {+ Ok(request) => request.into_inner(),+ Err(rejection) => return rejection.into_response(),};- let team_receipt = match load_team_receipt(&state, ¯o_user_id).await {- Ok(team_receipt) => team_receipt,- Err(err) => {- return Response::from_errors(vec![ServerError::new(- format!("failed to load caller team: {err:?}"),- None,- )])- .into();+ let Some(macro_user_id) = auth.macro_user_id else {+ if is_introspection_query(&request.query) {+ return GraphQLResponse::from(state.graphql_soup_schema.execute(request).await)+ .into_response();}+ return GraphQLResponse::from(async_graphql::Response::from_errors(vec![+ ServerError::new("authentication required for GraphQL Soup queries", None),+ ]))+ .into_response();};let property_reader: std::sync::Arc<dyn graphql_soup::SoupPropertyEdgeReader> =state.properties_service.clone();let request = request- .data(GraphqlSoupRequestContext {- macro_user_id: macro_user_id.clone(),- link_ids,- team_receipt,- })+ .data(GraphqlSoupRequestParts::new(parts))+ .data(state.clone()).data(graphql_soup::entity_properties_loader(macro_user_id.clone(),property_reader,@@ -86,42 +68,9 @@ async fn handler(state.graphql_notification_reader.clone(),));- state.graphql_soup_schema.execute(request).await.into()+ GraphQLResponse::from(state.graphql_soup_schema.execute(request).await).into_response()}fn is_introspection_query(query: &str) -> bool {query.contains("__schema") || query.contains("__type")}--async fn load_team_receipt(- state: &ApiContext,- macro_user_id: ¯o_user_id::user_id::MacroUserIdStr<'static>,-) -> async_graphql::Result<Option<EntityAccessReceipt<MemberTeamRole>>> {- let Some(team_info) = state- .entity_access_service- .get_user_team(macro_user_id)- .await- .map_err(|err| async_graphql::Error::new(err.to_string()))?- else {- return Ok(None);- };-- let permission = EntityPermission::TeamRole {- role: team_info.role,- };-- if !permission.satisfies::<MemberTeamRole>() {- return Ok(None);- }-- EntityAccessReceipt::try_new_authenticated_user(- macro_user_id.clone(),- Entity {- entity_id: team_info.team_id.to_string(),- entity_type: EntityType::Team,- },- permission,- )- .map(Some)- .map_err(|err| async_graphql::Error::new(err.to_string()))-}diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rsindex fc5d2c4e5c..bb4c58b9ed 100644--- a/rust/cloud-storage/email/src/domain/ports.rs+++ b/rust/cloud-storage/email/src/domain/ports.rs@@ -532,6 +532,131 @@ impl EmailMessageEnqueuer for NoOpEnqueuer {}}+/// No-op [`EmailService`] for binaries that need to satisfy the bound but+/// never call email — e.g. schema-only GraphQL SDL export. Every method+/// errors; swap for a real implementation if you actually need email.+#[derive(Clone, Copy, Debug, Default)]+pub struct NoOpEmailService;++fn no_op_email_err() -> EmailErr {+ EmailErr::RepoErr(anyhow::anyhow!("no-op email service"))+}++impl EmailService for NoOpEmailService {+ async fn get_email_thread_previews(+ &self,+ _req: GetEmailsRequest,+ ) -> Result<PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>, EmailErr>+ {+ Err(no_op_email_err())+ }++ async fn get_link_by_auth_id_and_macro_id(+ &self,+ _auth_id: &str,+ _macro_id: MacroUserIdStr<'_>,+ ) -> Result<Option<Link>, EmailErr> {+ Err(no_op_email_err())+ }++ async fn get_link_by_macro_id(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ ) -> Result<Option<Link>, EmailErr> {+ Err(no_op_email_err())+ }++ async fn get_inboxes_for_macro_id(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ ) -> Result<Vec<Link>, EmailErr> {+ Err(no_op_email_err())+ }++ async fn get_owned_link_for_thread(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ _thread_id: Uuid,+ ) -> Result<Option<Link>, EmailErr> {+ Err(no_op_email_err())+ }++ async fn get_thread_with_messages(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ _offset: i64,+ _limit: i64,+ ) -> Result<Option<Thread>, EmailErr> {+ Err(no_op_email_err())+ }++ async fn get_thread_parsed(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ _offset: i64,+ _limit: i64,+ ) -> Result<Option<ParsedThread>, EmailErr> {+ Err(no_op_email_err())+ }++ async fn create_draft(+ &self,+ _link: &Link,+ _accessible_inboxes: &[Link],+ _input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ Err(no_op_email_err())+ }++ async fn send_message(+ &self,+ _link: &Link,+ _accessible_inboxes: &[Link],+ _input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ Err(no_op_email_err())+ }++ async fn list_labels(&self, _link: &Link) -> Result<Vec<LinkLabel>, EmailErr> {+ Err(no_op_email_err())+ }++ async fn update_thread_labels(+ &self,+ _access_token: &str,+ _link: &Link,+ _thread_id: Uuid,+ _label_id: Uuid,+ _add: bool,+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {+ Err(no_op_email_err())+ }++ async fn update_thread_project(+ &self,+ _thread_receipt: EntityAccessReceipt<EditAccessLevel>,+ _project_receipt: Option<EntityAccessReceipt<EditAccessLevel>>,+ ) -> Result<Option<String>, EmailErr> {+ Err(no_op_email_err())+ }++ async fn upsert_email_filter(+ &self,+ _link: &Link,+ _input: UpsertEmailFilterInput,+ ) -> Result<EmailFilter, EmailErr> {+ Err(no_op_email_err())+ }++ async fn delete_email_filter(&self, _link: &Link, _filter_id: Uuid) -> Result<bool, EmailErr> {+ Err(no_op_email_err())+ }++ async fn list_email_filters(&self, _link: &Link) -> Result<Vec<EmailFilter>, EmailErr> {+ Err(no_op_email_err())+ }+}+/// Outcome of a first-inbox provisioning attempt.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum FirstInboxProvisionOutcome {diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rsindex 90a6e9f25d..728240b11f 100644--- a/rust/cloud-storage/entity_access/src/domain/ports.rs+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs@@ -270,3 +270,97 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {user_id: &MacroUserId<Lowercase<'_>>,) -> impl Future<Output = Result<Option<UserTeamInfo>, AccessError>> + Send;}++/// No-op [`EntityAccessService`] for binaries that need to satisfy the+/// bound but never check access — e.g. schema-only GraphQL SDL export.+/// `get_user_team` reports no membership; every other method errors.+#[derive(Clone, Copy, Debug, Default)]+pub struct NoOpEntityAccessService;++impl EntityAccessService for NoOpEntityAccessService {+ async fn generate_entity_access_receipt<T: RequiredPermission>(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_access_level(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn check_access(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::Internal)+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_crm_entity_permission_with_team(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<(EntityPermission, Uuid), AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ Ok(None)+ }+}diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rsindex f061acfc8f..2dd4e1efde 100644--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs@@ -36,6 +36,18 @@ pub struct OptionalMacroUserTeamExtractor<T: RequiredPermission, Svc> {_marker: PhantomData<(T, Svc)>,}+impl<T: RequiredPermission, Svc> Clone for OptionalMacroUserTeamExtractor<T, Svc>+where+ EntityAccessReceipt<T>: Clone,+{+ fn clone(&self) -> Self {+ Self {+ entity_access_receipt: self.entity_access_receipt.clone(),+ _marker: PhantomData,+ }+ }+}+impl<T, S, Svc> FromRequestParts<S> for OptionalMacroUserTeamExtractor<T, Svc>whereT: RequiredPermission,diff --git a/rust/cloud-storage/graphql_soup/Cargo.toml b/rust/cloud-storage/graphql_soup/Cargo.tomlindex 406f53c513..f4e66dd03f 100644--- a/rust/cloud-storage/graphql_soup/Cargo.toml+++ b/rust/cloud-storage/graphql_soup/Cargo.toml@@ -8,14 +8,24 @@ publish = falseanyhow = { workspace = true }async-graphql = { workspace = true, features = ["dataloader"] }async-trait = { workspace = true }+axum = { workspace = true }+axum-extra = { workspace = true }chrono = { workspace = true }document_sub_type = { path = "../document_sub_type" }either = { workspace = true }-entity_access = { path = "../entity_access", default-features = false }+email = { path = "../email", default-features = false, features = [+ "axum",+ "inbound",+ "ports",+] }+entity_access = { path = "../entity_access", default-features = false, features = [+ "inbound",+] }filter_ast = { path = "../filter_ast" }item_filters = { path = "../item_filters" }macro_user_id = { path = "../macro_user_id" }model_file_type = { path = "../model_file_type" }+model_user = { path = "../model_user", features = ["axum"] }model-entity = { path = "../model-entity" }models_pagination = { path = "../models_pagination" }models_properties = { path = "../models_properties" }diff --git a/rust/cloud-storage/graphql_soup/src/auth.rs b/rust/cloud-storage/graphql_soup/src/auth.rsdeleted file mode 100644index b4e2ae2feb..0000000000--- a/rust/cloud-storage/graphql_soup/src/auth.rs+++ /dev/null@@ -1,58 +0,0 @@-use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};-use filter_ast::Expr;-use item_filters::ast::{EntityFilterAst, crm_company::CrmCompanyLiteral};--pub(crate) fn resolve_crm_team_receipt(- crm_scope_requested: bool,- receipt: Option<EntityAccessReceipt<MemberTeamRole>>,-) -> async_graphql::Result<Option<EntityAccessReceipt<MemberTeamRole>>> {- if crm_scope_requested && receipt.is_none() {- return Err(async_graphql::Error::new(- "CRM-scoped queries require team membership",- ));- }- Ok(receipt)-}--pub(crate) fn require_crm_admin_role(- admin_requested: bool,- receipt: &Option<EntityAccessReceipt<MemberTeamRole>>,-) -> async_graphql::Result<()> {- if !admin_requested {- return Ok(());- }- let Some(receipt) = receipt else {- return Err(async_graphql::Error::new(- "Querying hidden CRM companies requires admin/owner team role",- ));- };- if !receipt- .entity_permission()- .satisfies::<entity_access::domain::models::AdminTeamRole>()- {- return Err(async_graphql::Error::new(- "Querying hidden CRM companies requires admin/owner team role",- ));- }- Ok(())-}--pub(crate) fn requests_crm_scope(filter: &EntityFilterAst) -> bool {- filter.email_filter.crm_scope.is_some()-}--pub(crate) fn requests_crm_admin(filter: &EntityFilterAst) -> bool {- filter- .crm_company_filter- .as_deref()- .is_some_and(ast_requests_crm_admin)-}--fn ast_requests_crm_admin(expr: &Expr<CrmCompanyLiteral>) -> bool {- match expr {- Expr::Literal(CrmCompanyLiteral::Hidden(_)) => true,- Expr::And(a, b) | Expr::Or(a, b) => ast_requests_crm_admin(a) || ast_requests_crm_admin(b),- Expr::Not(a) => ast_requests_crm_admin(a),- _ => false,- }-}diff --git a/rust/cloud-storage/graphql_soup/src/inputs.rs b/rust/cloud-storage/graphql_soup/src/inputs.rsindex 690222915b..d475e4cbc8 100644--- a/rust/cloud-storage/graphql_soup/src/inputs.rs+++ b/rust/cloud-storage/graphql_soup/src/inputs.rs@@ -26,8 +26,6 @@ use models_pagination::{Base64Str, CursorWithValAndFilter, SimpleSortMethod};use soup::domain::models::{SoupQuery, SoupRequest, SoupType};use uuid::Uuid;-use crate::request_context::GraphqlSoupRequestContext;-/// Input for `Query.soup`.#[derive(async_graphql::InputObject)]pub struct SoupInput {@@ -49,7 +47,8 @@ pub struct SoupInput {impl SoupInput {pub(crate) fn into_request(self,- request_context: &GraphqlSoupRequestContext,+ macro_user_id: MacroUserIdStr<'static>,+ link_ids: Vec<Uuid>,) -> async_graphql::Result<SoupRequest<EntityFilterAst>> {let filter = self.filters@@ -80,14 +79,14 @@ impl SoupInput {},limit: self.limit.unwrap_or(20).min(500),cursor,- user: request_context.macro_user_id.clone(),+ user: macro_user_id,email_preview_view: self.email_view.map(GraphqlEmailView::as_preview_view_str).unwrap_or("inbox").parse().map_err(async_graphql::Error::new)?,- link_ids: request_context.link_ids.clone(),+ link_ids,})}}diff --git a/rust/cloud-storage/graphql_soup/src/inputs/tests.rs b/rust/cloud-storage/graphql_soup/src/inputs/tests.rsindex c68b93d7f1..316d739238 100644--- a/rust/cloud-storage/graphql_soup/src/inputs/tests.rs+++ b/rust/cloud-storage/graphql_soup/src/inputs/tests.rs@@ -5,14 +5,10 @@ use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use super::*;-fn test_request_context() -> GraphqlSoupRequestContext {- GraphqlSoupRequestContext {- macro_user_id: MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- link_ids: vec![],- team_receipt: None,- }+fn test_macro_user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned()}#[test]@@ -25,7 +21,7 @@ fn maps_email_view_to_soup_request() {email_view: Some(GraphqlEmailView::Sent),filters: None,}- .into_request(&test_request_context())+ .into_request(test_macro_user_id(), vec![]).unwrap();assert_eq!(request.email_preview_view.to_string(), "sent");@@ -41,7 +37,7 @@ fn defaults_email_view_to_inbox() {email_view: None,filters: None,}- .into_request(&test_request_context())+ .into_request(test_macro_user_id(), vec![]).unwrap();assert_eq!(request.email_preview_view.to_string(), "inbox");diff --git a/rust/cloud-storage/graphql_soup/src/lib.rs b/rust/cloud-storage/graphql_soup/src/lib.rsindex b0d6b39b2d..5ed245d12d 100644--- a/rust/cloud-storage/graphql_soup/src/lib.rs+++ b/rust/cloud-storage/graphql_soup/src/lib.rs@@ -4,7 +4,6 @@//! existing `soup` domain service without changing the existing REST API.#![deny(missing_docs)]-mod auth;mod inputs;mod loaders;mod objects;@@ -24,8 +23,8 @@ pub use objects::{GraphqlSoupNotification, GraphqlSoupProject, GraphqlSoupProperty,GraphqlSoupPropertyEntityReference, GraphqlSoupPropertyValue, SoupPage,};-pub use request_context::GraphqlSoupRequestContext;+pub use request_context::GraphqlSoupRequestParts;pub use schema::{- SchemaOnlySoupSchema, SchemaOnlySoupService, SharedSoupSchema, SharedSoupService,- SoupQueryRoot, SoupSchema, build_schema, build_schema_from_arc, build_schema_with_service,+ SchemaOnlySoupSchema, SchemaOnlyState, SharedSoupSchema, SharedSoupService, SoupQueryRoot,+ SoupSchema, build_schema, build_schema_from_arc, build_schema_with_service,};diff --git a/rust/cloud-storage/graphql_soup/src/request_context.rs b/rust/cloud-storage/graphql_soup/src/request_context.rsindex f97d206123..a35bf0404c 100644--- a/rust/cloud-storage/graphql_soup/src/request_context.rs+++ b/rust/cloud-storage/graphql_soup/src/request_context.rs@@ -1,18 +1,34 @@-use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};-use macro_user_id::user_id::MacroUserIdStr;-use uuid::Uuid;+use axum::{extract::FromRequestParts, http::request::Parts};-/// Request-scoped data required to execute a Soup GraphQL query.+/// Request-scoped HTTP request parts for a Soup GraphQL query.///-/// The embedding Axum/service layer remains responsible for authentication and-/// for resolving inbox link IDs. This keeps `graphql_soup` independent from the-/// existing REST extractors.-#[derive(Clone)]-pub struct GraphqlSoupRequestContext {- /// Authenticated Macro user executing the request.- pub macro_user_id: MacroUserIdStr<'static>,- /// Link IDs available to the request.- pub link_ids: Vec<Uuid>,- /// Optional team access receipt used for CRM-scoped queries.- pub team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+/// Resolvers run axum `FromRequestParts` extractors against these parts on+/// demand instead of the embedding service loading everything upfront. This+/// keeps per-request work lazy: a query that never touches email links or+/// CRM scope never pays for resolving them.+///+/// Extraction results that should be computed once per request should be+/// wrapped in `axum_extra::extract::Cached`, which memoizes inside the parts'+/// extensions exactly like the REST routes do.+pub struct GraphqlSoupRequestParts {+ parts: tokio::sync::Mutex<Parts>,+}++impl GraphqlSoupRequestParts {+ /// Wrap the parts of the incoming HTTP request.+ pub fn new(parts: Parts) -> Self {+ Self {+ parts: tokio::sync::Mutex::new(parts),+ }+ }++ /// Run an axum extractor against the stored request parts.+ pub async fn extract_with_state<T, St>(&self, state: &St) -> Result<T, T::Rejection>+ where+ T: FromRequestParts<St>,+ St: Send + Sync,+ {+ let mut parts = self.parts.lock().await;+ T::from_request_parts(&mut parts, state).await+ }}diff --git a/rust/cloud-storage/graphql_soup/src/schema.rs b/rust/cloud-storage/graphql_soup/src/schema.rsindex 32351592b4..3cdbb0318c 100644--- a/rust/cloud-storage/graphql_soup/src/schema.rs+++ b/rust/cloud-storage/graphql_soup/src/schema.rs@@ -1,60 +1,60 @@-use std::sync::Arc;+#[cfg(test)]+mod test;-use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema};-use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};-use models_pagination::TypeEraseCursor;-use soup::domain::{models::SoupRequest, ports::SoupService};+use std::{marker::PhantomData, sync::Arc};-use crate::{- auth::{- requests_crm_admin, requests_crm_scope, require_crm_admin_role, resolve_crm_team_receipt,+use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema};+use axum::extract::{FromRef, FromRequestParts};+use axum_extra::extract::Cached;+use email::{+ domain::ports::{EmailService, NoOpEmailService},+ inbound::axum::{axum_impls::MultiEmailLinkExtractor, previews_router::EmailRouterState},+};+use entity_access::{+ domain::{+ models::{EntityAccessReceipt, MemberTeamRole},+ ports::{EntityAccessService, NoOpEntityAccessService},},- inputs::SoupInput,- objects::SoupPage,- request_context::GraphqlSoupRequestContext,+ inbound::axum_extractors::OptionalMacroUserTeamExtractor,+};+use model_user::axum_extractor::MacroUserExtractor;+use models_pagination::TypeEraseCursor;+use soup::domain::{+ models::SoupRequest,+ ports::{NoOpSoupService, SoupService},};+use crate::{inputs::SoupInput, objects::SoupPage, request_context::GraphqlSoupRequestParts};+/// GraphQL Soup schema type.-pub type SoupSchema<S> = Schema<SoupQueryRoot<S>, EmptyMutation, EmptySubscription>;+///+/// `S` is the soup service, `E` the email service, `EAS` the entity access+/// service, and `St` the embedding axum router state that can hand out the+/// email router state and entity access service for the lazy extractors.+pub type SoupSchema<S, E, EAS, St> =+ Schema<SoupQueryRoot<S, E, EAS, St>, EmptyMutation, EmptySubscription>;/// GraphQL Soup schema type backed by a shared soup service.-pub type SharedSoupSchema<S> = SoupSchema<SharedSoupService<S>>;+pub type SharedSoupSchema<S, E, EAS, St> = SoupSchema<SharedSoupService<S>, E, EAS, St>;-/// GraphQL Soup schema type backed by the schema-only service.-pub type SchemaOnlySoupSchema = SoupSchema<SchemaOnlySoupService>;+/// GraphQL Soup schema type backed by the no-op services, used only for+/// SDL export or introspection.+pub type SchemaOnlySoupSchema =+ SoupSchema<NoOpSoupService, NoOpEmailService, NoOpEntityAccessService, SchemaOnlyState>;-/// Soup service used only to construct the GraphQL schema for SDL export.+/// Axum-style state used only to construct the GraphQL schema for SDL export.#[derive(Clone, Copy, Debug, Default)]-pub struct SchemaOnlySoupService;--impl SoupService for SchemaOnlySoupService {- async fn get_user_soup<T>(- &self,- _req: SoupRequest<T>,- _team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,- ) -> Result<soup::domain::ports::SoupOutput<T>, soup::domain::models::SoupErr>- where- SoupRequest<T>: soup::domain::models::IntoSoupReqAst,- T: Clone + serde::Serialize + Send,- {- Err(soup::domain::models::SoupErr::CommsErr)- }+pub struct SchemaOnlyState;- async fn get_user_soup_grouped(- &self,- _req: soup::domain::models::GroupedSortRequest<'_>,- ) -> Result<Vec<soup::domain::models::GroupedSoupItem>, soup::domain::models::SoupErr> {- Err(soup::domain::models::SoupErr::CommsErr)+impl FromRef<SchemaOnlyState> for EmailRouterState<NoOpEmailService> {+ fn from_ref(_state: &SchemaOnlyState) -> Self {+ EmailRouterState::new(NoOpEmailService)}+}- async fn caller_tag_sets<'a>(- &self,- _user_id: macro_user_id::user_id::MacroUserIdStr<'a>,- ) -> Result<- Vec<models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions>,- soup::domain::models::SoupErr,- >{- Err(soup::domain::models::SoupErr::CommsErr)+impl FromRef<SchemaOnlyState> for Arc<NoOpEntityAccessService> {+ fn from_ref(_state: &SchemaOnlyState) -> Self {+ Arc::new(NoOpEntityAccessService)}}@@ -108,34 +108,48 @@ where}}+/// Zero-sized marker tying the query objects to the email/entity-access/state+/// generics without requiring values of those types.+type ServicesMarker<E, EAS, St> = PhantomData<fn() -> (E, EAS, St)>;+/// Root GraphQL query object for Soup.-pub struct SoupQueryRoot<S> {+pub struct SoupQueryRoot<S, E, EAS, St> {service: S,+ _marker: ServicesMarker<E, EAS, St>,}-impl<S> SoupQueryRoot<S> {+impl<S, E, EAS, St> SoupQueryRoot<S, E, EAS, St> {/// Create a root GraphQL query object.pub fn new(service: S) -> Self {- Self { service }+ Self {+ service,+ _marker: PhantomData,+ }}}/// The authenticated user (viewer). All user-scoped data hangs off this/// object so clients (and their normalized caches) observe data ownership/// structurally rather than implicitly through the session.-pub struct GraphqlUser<S> {+pub struct GraphqlUser<S, E, EAS, St> {service: S,+ _marker: ServicesMarker<E, EAS, St>,}/// Build a GraphQL schema for Soup suitable for SDL export or introspection.pub fn build_schema() -> SchemaOnlySoupSchema {- build_schema_with_service(SchemaOnlySoupService)+ build_schema_with_service(NoOpSoupService)}/// Build a GraphQL schema for Soup backed by the provided service.-pub fn build_schema_with_service<S>(service: S) -> SoupSchema<S>+pub fn build_schema_with_service<S, E, EAS, St>(service: S) -> SoupSchema<S, E, EAS, St>whereS: SoupService + Clone,+ E: EmailService,+ EAS: EntityAccessService,+ St: Clone + Send + Sync + 'static,+ EmailRouterState<E>: FromRef<St>,+ Arc<EAS>: FromRef<St>,{Schema::build(SoupQueryRoot::new(service),@@ -146,48 +160,96 @@ where}/// Build a GraphQL schema for Soup backed by an `Arc`-shared service.-pub fn build_schema_from_arc<S>(service: Arc<S>) -> SharedSoupSchema<S>+pub fn build_schema_from_arc<S, E, EAS, St>(service: Arc<S>) -> SharedSoupSchema<S, E, EAS, St>whereS: SoupService,+ E: EmailService,+ EAS: EntityAccessService,+ St: Clone + Send + Sync + 'static,+ EmailRouterState<E>: FromRef<St>,+ Arc<EAS>: FromRef<St>,{build_schema_with_service(SharedSoupService::new(service))}+/// Run an axum extractor against the request parts stored in the GraphQL+/// context, using the embedding router state `St` also stored there.+async fn extract_part<T, St>(ctx: &Context<'_>) -> async_graphql::Result<T>+where+ T: FromRequestParts<St>,+ T::Rejection: std::fmt::Display,+ St: Clone + Send + Sync + 'static,+{+ let parts = ctx.data::<GraphqlSoupRequestParts>()?;+ let state = ctx.data::<St>()?;+ parts+ .extract_with_state::<T, St>(state)+ .await+ .map_err(|err| async_graphql::Error::new(err.to_string()))+}+#[Object]-impl<S> SoupQueryRoot<S>+impl<S, E, EAS, St> SoupQueryRoot<S, E, EAS, St>whereS: SoupService + Clone,+ E: EmailService,+ EAS: EntityAccessService,+ St: Clone + Send + Sync + 'static,+ EmailRouterState<E>: FromRef<St>,+ Arc<EAS>: FromRef<St>,{/// The authenticated user.- async fn user(&self) -> GraphqlUser<S> {+ async fn user(&self) -> GraphqlUser<S, E, EAS, St> {GraphqlUser {service: self.service.clone(),+ _marker: PhantomData,}}}#[Object(name = "GraphqlUser")]-impl<S> GraphqlUser<S>+impl<S, E, EAS, St> GraphqlUser<S, E, EAS, St>whereS: SoupService,+ E: EmailService,+ EAS: EntityAccessService,+ St: Clone + Send + Sync + 'static,+ EmailRouterState<E>: FromRef<St>,+ Arc<EAS>: FromRef<St>,{/// Stable id of the authenticated user.async fn id(&self, ctx: &Context<'_>) -> async_graphql::Result<async_graphql::ID> {- let request_context = ctx.data::<GraphqlSoupRequestContext>()?;- Ok(async_graphql::ID(request_context.macro_user_id.to_string()))+ let Cached(MacroUserExtractor { macro_user_id, .. }) =+ extract_part::<Cached<MacroUserExtractor>, St>(ctx).await?;+ Ok(async_graphql::ID(macro_user_id.to_string()))}/// Fetch a page of Soup items using the existing Soup filter AST format.async fn soup(&self, ctx: &Context<'_>, input: SoupInput) -> async_graphql::Result<SoupPage> {- let request_context = ctx.data::<GraphqlSoupRequestContext>()?;- let request = input.into_request(request_context)?;+ let Cached(MacroUserExtractor { macro_user_id, .. }) =+ extract_part::<Cached<MacroUserExtractor>, St>(ctx).await?;+ let Cached(MultiEmailLinkExtractor(links, _)) =+ extract_part::<Cached<MultiEmailLinkExtractor<E>>, St>(ctx).await?;+ let link_ids = links.into_iter().map(|link| link.id).collect();+ let request = input.into_request(macro_user_id, link_ids)?;+ // Team membership is only resolved when the query actually asks for+ // CRM-scoped data; everything else skips the lookup entirely. The+ // authorization itself (membership + admin role for hidden+ // companies) is enforced by the soup domain and CRM service from+ // the receipt.let effective_filter = request.cursor.filter();- let team_receipt = resolve_crm_team_receipt(- requests_crm_scope(effective_filter),- request_context.team_receipt.clone(),- )?;- require_crm_admin_role(requests_crm_admin(effective_filter), &team_receipt)?;+ let team_receipt =+ if effective_filter.requests_crm_scope() || effective_filter.requests_crm_admin() {+ let Cached(team) = extract_part::<+ Cached<OptionalMacroUserTeamExtractor<MemberTeamRole, EAS>>,+ St,+ >(ctx)+ .await?;+ team.entity_access_receipt+ } else {+ None+ };let page = self.service.get_user_soup(request, team_receipt).await?;Ok(SoupPage::from(page.type_erase()))diff --git a/rust/cloud-storage/graphql_soup/src/schema/test.rs b/rust/cloud-storage/graphql_soup/src/schema/test.rsnew file mode 100644index 0000000000..ebe256df2f--- /dev/null+++ b/rust/cloud-storage/graphql_soup/src/schema/test.rs@@ -0,0 +1,365 @@+use std::sync::atomic::{AtomicUsize, Ordering};++use email::domain::models::{+ CreateDraftInput, CreatedDraft, EmailErr, EmailFilter, EnrichedEmailThreadPreview,+ GetEmailsRequest, Link, LinkLabel, ParsedThread, Thread, UpdateThreadLabelsResult,+ UpsertEmailFilterInput,+};+use entity_access::domain::models::{+ AccessError, AccessLevel, CallChannelInfo, EditAccessLevel, EntityPermission, EntityType,+ RequiredPermission, UserTeamInfo, ViewAccessLevel,+};+use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+};+use model_user::UserContext;+use models_pagination::{PaginatedCursor, SimpleSortMethod};+use uuid::Uuid;++use super::*;++/// Email service whose inbox lookups are counted, so tests can assert when+/// the lazy extraction actually runs.+#[derive(Clone, Default)]+struct CountingEmailService {+ inbox_calls: Arc<AtomicUsize>,+}++fn test_email_err() -> EmailErr {+ EmailErr::RepoErr(anyhow::anyhow!("counting email service"))+}++impl EmailService for CountingEmailService {+ async fn get_email_thread_previews(+ &self,+ _req: GetEmailsRequest,+ ) -> Result<PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>, EmailErr>+ {+ Err(test_email_err())+ }++ async fn get_link_by_auth_id_and_macro_id(+ &self,+ _auth_id: &str,+ _macro_id: MacroUserIdStr<'_>,+ ) -> Result<Option<Link>, EmailErr> {+ Err(test_email_err())+ }++ async fn get_link_by_macro_id(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ ) -> Result<Option<Link>, EmailErr> {+ Err(test_email_err())+ }++ async fn get_inboxes_for_macro_id(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ ) -> Result<Vec<Link>, EmailErr> {+ self.inbox_calls.fetch_add(1, Ordering::SeqCst);+ Ok(Vec::new())+ }++ async fn get_owned_link_for_thread(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ _thread_id: Uuid,+ ) -> Result<Option<Link>, EmailErr> {+ Err(test_email_err())+ }++ async fn get_thread_with_messages(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ _offset: i64,+ _limit: i64,+ ) -> Result<Option<Thread>, EmailErr> {+ Err(test_email_err())+ }++ async fn get_thread_parsed(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ _offset: i64,+ _limit: i64,+ ) -> Result<Option<ParsedThread>, EmailErr> {+ Err(test_email_err())+ }++ async fn create_draft(+ &self,+ _link: &Link,+ _accessible_inboxes: &[Link],+ _input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ Err(test_email_err())+ }++ async fn send_message(+ &self,+ _link: &Link,+ _accessible_inboxes: &[Link],+ _input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ Err(test_email_err())+ }++ async fn list_labels(&self, _link: &Link) -> Result<Vec<LinkLabel>, EmailErr> {+ Err(test_email_err())+ }++ async fn update_thread_labels(+ &self,+ _access_token: &str,+ _link: &Link,+ _thread_id: Uuid,+ _label_id: Uuid,+ _add: bool,+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {+ Err(test_email_err())+ }++ async fn update_thread_project(+ &self,+ _thread_receipt: EntityAccessReceipt<EditAccessLevel>,+ _project_receipt: Option<EntityAccessReceipt<EditAccessLevel>>,+ ) -> Result<Option<String>, EmailErr> {+ Err(test_email_err())+ }++ async fn upsert_email_filter(+ &self,+ _link: &Link,+ _input: UpsertEmailFilterInput,+ ) -> Result<EmailFilter, EmailErr> {+ Err(test_email_err())+ }++ async fn delete_email_filter(&self, _link: &Link, _filter_id: Uuid) -> Result<bool, EmailErr> {+ Err(test_email_err())+ }++ async fn list_email_filters(&self, _link: &Link) -> Result<Vec<EmailFilter>, EmailErr> {+ Err(test_email_err())+ }+}++/// Entity access service whose team lookups are counted. The user has no+/// team, so CRM-scoped queries are rejected after the (counted) lookup.+#[derive(Clone, Default)]+struct CountingEntityAccessService {+ team_calls: Arc<AtomicUsize>,+}++impl EntityAccessService for CountingEntityAccessService {+ async fn generate_entity_access_receipt<T: RequiredPermission>(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_access_level(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn check_access(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::Internal)+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_crm_entity_permission_with_team(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<(EntityPermission, Uuid), AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ self.team_calls.fetch_add(1, Ordering::SeqCst);+ Ok(None)+ }+}++#[derive(Clone)]+struct TestState {+ email: EmailRouterState<CountingEmailService>,+ entity_access: Arc<CountingEntityAccessService>,+}++impl FromRef<TestState> for EmailRouterState<CountingEmailService> {+ fn from_ref(state: &TestState) -> Self {+ state.email.clone()+ }+}++impl FromRef<TestState> for Arc<CountingEntityAccessService> {+ fn from_ref(state: &TestState) -> Self {+ state.entity_access.clone()+ }+}++struct TestHarness {+ schema:+ SoupSchema<NoOpSoupService, CountingEmailService, CountingEntityAccessService, TestState>,+ state: TestState,+ inbox_calls: Arc<AtomicUsize>,+ team_calls: Arc<AtomicUsize>,+}++fn harness() -> TestHarness {+ let email = CountingEmailService::default();+ let entity_access = CountingEntityAccessService::default();+ let inbox_calls = Arc::clone(&email.inbox_calls);+ let team_calls = Arc::clone(&entity_access.team_calls);+ TestHarness {+ schema: build_schema_with_service(NoOpSoupService),+ state: TestState {+ email: EmailRouterState::new(email),+ entity_access: Arc::new(entity_access),+ },+ inbox_calls,+ team_calls,+ }+}++fn authenticated_parts() -> axum::http::request::Parts {+ let (mut parts, ()) = axum::http::Request::new(()).into_parts();+ parts.extensions.insert(UserContext {+ user_id: "macro|[email protected]".to_owned(),+ fusion_user_id: String::new(),+ permissions: None,+ organization_id: None,+ });+ parts+}++impl TestHarness {+ async fn execute(&self, query: &str) -> async_graphql::Response {+ let request = async_graphql::Request::new(query)+ .data(GraphqlSoupRequestParts::new(authenticated_parts()))+ .data(self.state.clone());+ self.schema.execute(request).await+ }+}++#[tokio::test]+async fn user_id_resolves_without_touching_services() {+ let harness = harness();++ let response = harness.execute("{ user { id } }").await;++ assert!(response.errors.is_empty(), "{:?}", response.errors);+ assert_eq!(+ response.data.to_string(),+ r#"{user: {id: "macro|[email protected]"}}"#+ );+ assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 0);+ assert_eq!(harness.team_calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn soup_resolves_inboxes_but_skips_team_lookup_without_crm_scope() {+ let harness = harness();++ // The schema-only soup service errors, but the laziness assertions below+ // are about which lookups ran before the service call.+ let _response = harness+ .execute("{ user { soup(input: {}) { hasMore } } }")+ .await;++ assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 1);+ assert_eq!(harness.team_calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn crm_scoped_soup_resolves_team_membership_lazily() {+ let harness = harness();++ // The membership/role authorization itself lives in the soup domain+ // and CRM service (covered by their tests); this asserts the GraphQL+ // layer resolves the team receipt only for CRM-scoped input.+ let response = harness+ .execute(+ r#"{ user { soup(input: {filters: {emailFilter: {crmScope: {domains: ["example.com"]}}}}) { hasMore } } }"#,+ )+ .await;++ assert_eq!(harness.team_calls.load(Ordering::SeqCst), 1);+ assert!(!response.errors.is_empty());+}++#[tokio::test]+async fn unauthenticated_request_fails_at_the_resolver() {+ let harness = harness();+ let (parts, ()) = axum::http::Request::new(()).into_parts();++ let request = async_graphql::Request::new("{ user { id } }")+ .data(GraphqlSoupRequestParts::new(parts))+ .data(harness.state.clone());+ let response = harness.schema.execute(request).await;++ assert!(!response.errors.is_empty());+ assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 0);+}diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rsindex 8f64627a39..903c60e7a1 100644--- a/rust/cloud-storage/item_filters/src/ast.rs+++ b/rust/cloud-storage/item_filters/src/ast.rs@@ -262,6 +262,24 @@ impl EntityFilterAst {}))}+ /// True when this filter asks the query to expand visibility across+ /// the requesting user's team via a CRM-scoped email attribute+ /// (`crm_domains` / `crm_addresses`). Queries carrying it require a+ /// team receipt.+ pub fn requests_crm_scope(&self) -> bool {+ self.email_filter.crm_scope.is_some()+ }++ /// True when this filter asks for data only admin/owner team members+ /// may see — currently a `Hidden(true)` CRM-company literal anywhere+ /// in the tree (including under `Not`, so `Not(Hidden(true))` is+ /// conservatively treated as admin-requesting).+ pub fn requests_crm_admin(&self) -> bool {+ self.crm_company_filter+ .as_deref()+ .is_some_and(crm_company_requests_admin)+ }+/// mock function to create the an empty ast#[cfg(feature = "mock")]pub fn mock_empty() -> Self {@@ -280,6 +298,21 @@ impl EntityFilterAst {}}+/// Walks a `CrmCompanyLiteral` tree checking for any `Hidden(true)`+/// literal. `And`/`Or`/`Not` all recurse: the role gate must stay+/// conservative, so any path reaching a `Hidden(true)` literal counts as+/// admin-requesting regardless of surrounding negation.+fn crm_company_requests_admin(expr: &Expr<CrmCompanyLiteral>) -> bool {+ match expr {+ Expr::Literal(CrmCompanyLiteral::Hidden(true)) => true,+ Expr::Literal(_) => false,+ Expr::And(a, b) | Expr::Or(a, b) => {+ crm_company_requests_admin(a) || crm_company_requests_admin(b)+ }+ Expr::Not(a) => crm_company_requests_admin(a),+ }+}+impl IsEmpty for EntityFilterAst {fn is_empty(&self) -> bool {let EntityFilterAst {diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rsindex cc753fa4db..8727dada66 100644--- a/rust/cloud-storage/item_filters/src/ast/tests.rs+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs@@ -1530,3 +1530,38 @@ fn properties_filter_matches_propertyless_evaluates_literals_as_false() {Expr::is_not(lit()))));}++#[test]+fn requests_crm_admin_finds_hidden_true_anywhere_in_tree() {+ let ast_with = |tree: Expr<CrmCompanyLiteral>| EntityFilterAst {+ crm_company_filter: Some(Arc::new(tree)),+ ..EntityFilterAst::default()+ };++ // Bare literal.+ assert!(ast_with(Expr::val(CrmCompanyLiteral::Hidden(true))).requests_crm_admin());+ // Hidden(false) is visible-only — no admin needed.+ assert!(!ast_with(Expr::val(CrmCompanyLiteral::Hidden(false))).requests_crm_admin());+ // Nested under And with an id filter.+ assert!(+ ast_with(Expr::and(+ Expr::val(CrmCompanyLiteral::Id(Uuid::from_u128(1))),+ Expr::val(CrmCompanyLiteral::Hidden(true)),+ ))+ .requests_crm_admin()+ );+ // Conservative under Not.+ assert!(+ ast_with(Expr::is_not(Expr::val(CrmCompanyLiteral::Hidden(true)))).requests_crm_admin()+ );+ // No crm_company_filter at all.+ assert!(!EntityFilterAst::default().requests_crm_admin());+}++#[test]+fn requests_crm_scope_reflects_email_crm_scope_tag() {+ let mut ast = EntityFilterAst::default();+ assert!(!ast.requests_crm_scope());+ ast.email_filter.crm_scope = Some(CrmScope::Domains(vec!["example.com".into()]));+ assert!(ast.requests_crm_scope());+}diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex 6661bed564..cb6b8b5371 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -551,7 +551,8 @@ pub struct CrmCompanyFilters {/// Optional `crm_companies.hidden` filter. `None` = visible only/// (default for back-compat with non-admin callers). `Some(false)` =/// visible only (explicit). `Some(true)` = hidden only — requires- /// admin/owner team role; enforced upstream in soup's axum router.+ /// admin/owner team role; enforced by the CRM service from the+ /// caller's team receipt.#[serde(default, skip_serializing_if = "Option::is_none")]pub hidden: Option<bool>,}diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rsindex 33167f18d4..285fce91e9 100644--- a/rust/cloud-storage/soup/src/domain/models.rs+++ b/rust/cloud-storage/soup/src/domain/models.rs@@ -369,7 +369,7 @@ impl SoupRequest<Option<EntityFilterAst>> {}/// The request's entity filter ast, regardless of cursor position.- fn entity_ast(&self) -> Option<&EntityFilterAst> {+ pub(crate) fn entity_ast(&self) -> Option<&EntityFilterAst> {match &self.cursor {SoupQuery::Simple(SimpleQueryInner(Query::Sort(_, f))) => f.as_ref(),SoupQuery::Simple(SimpleQueryInner(Query::Cursor(CursorWithValAndFilter {@@ -640,8 +640,8 @@ pub struct GetCrmCompaniesRequest {pub company_ids: Vec<Uuid>,/// Optional `crm_companies.hidden` filter. `None` = visible only/// (default); `Some(false)` = visible only (explicit); `Some(true)`- /// = hidden only. The admin/owner role check is enforced upstream- /// in soup's axum router before reaching this request.+ /// = hidden only. The admin/owner role check is enforced by the CRM+ /// service from `access` when this request is executed.pub hidden: Option<bool>,/// Which timestamp column to sort by.pub sort: CrmCompanyListSort,@@ -794,6 +794,14 @@ pub enum SoupErr {/// CRM lookup failed.#[error("A CRM error has occurred, see logs for more details")]CrmErr,+ /// The filter requested CRM-scoped data but the caller has no+ /// qualifying team membership.+ #[error("CRM-scoped queries require team membership")]+ CrmTeamRequired,+ /// The filter requested hidden CRM companies but the caller's team+ /// role is below admin/owner.+ #[error("Querying hidden CRM companies requires admin/owner team role")]+ CrmAdminRequired,/// Foreign entity lookup failed.#[error(transparent)]ForeignEntityErr(#[from] ForeignEntityError),diff --git a/rust/cloud-storage/soup/src/domain/ports.rs b/rust/cloud-storage/soup/src/domain/ports.rsindex 81f515ccce..5d550fa7c8 100644--- a/rust/cloud-storage/soup/src/domain/ports.rs+++ b/rust/cloud-storage/soup/src/domain/ports.rs@@ -102,3 +102,41 @@ pub trait SoupService: Send + Sync + 'static {user_id: MacroUserIdStr<'a>,) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, SoupErr>> + Send;}++/// No-op [`SoupService`] for binaries that need to satisfy the bound but+/// never serve soup queries — e.g. schema-only GraphQL SDL export. Every+/// method errors; swap for a real implementation if you actually need soup.+#[derive(Clone, Copy, Debug, Default)]+pub struct NoOpSoupService;++fn no_op_soup_err() -> SoupErr {+ SoupErr::SoupDbErr(anyhow::anyhow!("no-op soup service"))+}++impl SoupService for NoOpSoupService {+ async fn get_user_soup<T>(+ &self,+ _req: SoupRequest<T>,+ _team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+ ) -> Result<SoupOutput<T>, SoupErr>+ where+ SoupRequest<T>: IntoSoupReqAst,+ T: Clone + Serialize + Send,+ {+ Err(no_op_soup_err())+ }++ async fn get_user_soup_grouped(+ &self,+ _req: GroupedSortRequest<'_>,+ ) -> Result<Vec<GroupedSoupItem>, SoupErr> {+ Err(no_op_soup_err())+ }++ async fn caller_tag_sets<'a>(+ &self,+ _user_id: MacroUserIdStr<'a>,+ ) -> Result<Vec<PropertyDefinitionWithOptions>, SoupErr> {+ Err(no_op_soup_err())+ }+}diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex d0e3c3190f..a5b7cae8e2 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -460,7 +460,10 @@ wherelimit,).await- .map_err(|_| SoupErr::CrmErr)?+ .map_err(|err| match err {+ crm::domain::model::CrmError::AdminRoleRequired => SoupErr::CrmAdminRequired,+ _ => SoupErr::CrmErr,+ })?.into_iter().map(|company| SoupItem::CrmCompany(SoupCrmCompany::from(company))).collect();@@ -560,6 +563,19 @@ wherelet req = req.into_ast()?;let limit = req.limit.clamp(20, 500);+ // CRM-scoped visibility (team-wide email scope or hidden CRM+ // companies) requires a team receipt. Without this check the CRM+ // sub-request would silently skip for no-team callers, disguising+ // "no access" as "no data". The admin/owner role gate for hidden+ // companies lives one layer down in the CRM service, derived from+ // the receipt itself.+ if let Some(ast) = req.entity_ast()+ && (ast.requests_crm_scope() || ast.requests_crm_admin())+ && team_receipt.is_none()+ {+ return Err(SoupErr::CrmTeamRequired);+ }+// Borrow before email's builder consumes team_receipt.let crm_company_request = req.build_crm_company_request(&team_receipt);let foreign_entity_source_ids = req.build_foreign_entity_source_ids(team_receipt.as_ref());diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 0426962ed9..85eaeb4470 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -836,6 +836,55 @@ async fn team_receipt_contributes_team_foreign_entity_source_id() {assert_eq!(calls[0].requesting_user, Some(user.to_string()));}+#[tokio::test]+async fn crm_filters_without_team_receipt_are_rejected() {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let hidden_companies_filter = EntityFilters {+ crm_company_filters: item_filters::CrmCompanyFilters {+ company_ids: vec![],+ hidden: Some(true),+ },+ ..EntityFilters::default()+ };+ let crm_scope_filter = EntityFilters {+ email_filters: item_filters::EmailFilters {+ crm_domains: vec!["example.com".to_string()],+ ..item_filters::EmailFilters::default()+ },+ ..EntityFilters::default()+ };++ for filters in [hidden_companies_filter, crm_scope_filter] {+ let err = SoupImpl::new(+ MockSoupRepo::new(),+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),+ NoopEmailPreviewService,+ NoopCommsService,+ NoopCallRecordQueryService,+ NoOpCrmService,+ RecordingForeignEntityService::new(Vec::new()),+ )+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_ids: vec![],+ soup_type: SoupType::UnExpanded,+ limit: 20,+ cursor: SoupQuery::new_sort_simple(SimpleSortMethod::UpdatedAt, filters),+ user: user.clone(),+ },+ None,+ )+ .await+ .unwrap_err();++ assert!(matches!(err, SoupErr::CrmTeamRequired), "{err:?}");+ }+}+#[tokio::test]async fn foreign_entity_filter_suppresses_non_matching_foreign_entities() {let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rsindex 60b0f924c3..acbefd9959 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs@@ -23,7 +23,7 @@ use email::{};use entity_access::{domain::{- models::{AdminTeamRole, EntityAccessReceipt, MemberTeamRole},+ models::{EntityAccessReceipt, MemberTeamRole},ports::EntityAccessService,},inbound::axum_extractors::OptionalMacroUserTeamExtractor,@@ -465,7 +465,7 @@ where) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>whereSoupRequest<R>: IntoSoupReqAst,- R: Clone + Serialize + Send + RequestsCrmScope + RequestsCrmAdmin,+ R: Clone + Serialize + Send,{let user_for_favorites = macro_user_id.copied().into_owned();let create_fallback = move || -> SoupQuery<R> {@@ -490,15 +490,10 @@ where.unwrap_or_else(create_fallback),};- // Derive CRM-scope authorization from the *effective* filter (the- // one embedded in the resolved SoupQuery), not the raw request body.- // For cursor-paginated requests the body's filters may be empty and- // the real filter lives inside the cursor — checking the body would- // miss CRM scope on follow-up pages.- let team_receipt =- resolve_crm_team_receipt(cursor.filter().requests_crm_scope(), team_receipt_option)?;- require_crm_admin_role(cursor.filter().requests_crm_admin(), &team_receipt)?;-+ // CRM authorization (team membership for CRM scope, admin/owner+ // role for hidden companies) is enforced by the soup domain and+ // CRM service from the receipt itself; the router just forwards+ // whatever membership the extractor resolved.let res = self.service.get_user_soup(@@ -513,7 +508,7 @@ whereemail_preview_view: email_view,link_ids,},- team_receipt,+ team_receipt_option,).await?;@@ -585,69 +580,6 @@ where}}-/// Probe applied to whichever filter type a soup endpoint accepts-/// (`EntityFilters` for the typed POST, `ApiEntityFilterAst` for the AST-/// endpoint). Lets `handle` inspect the *materialized* SoupQuery's filter-/// — which may have come from the request body or from the cursor — and-/// decide whether CRM scope is in play.-pub trait RequestsCrmScope {- /// True when this filter asks the query to expand visibility across- /// the requesting user's team via a CRM-scoped attribute- /// (`crm_domains` or `crm_addresses`).- fn requests_crm_scope(&self) -> bool;-}--impl RequestsCrmScope for EntityFilters {- fn requests_crm_scope(&self) -> bool {- !self.email_filters.crm_domains.is_empty() || !self.email_filters.crm_addresses.is_empty()- }-}--impl RequestsCrmScope for ApiEntityFilterAst {- fn requests_crm_scope(&self) -> bool {- !self.email_crm_domains.is_empty() || !self.email_crm_addresses.is_empty()- }-}--/// Filter bodies that may opt into admin-only CRM data (currently:-/// hidden CRM companies) implement this so the soup handler can gate-/// the request on an admin/owner team role.-pub trait RequestsCrmAdmin {- /// True when this filter asks for data only admin/owner team- /// members may see — e.g. `crm_company_filters.hidden = Some(true)`.- fn requests_crm_admin(&self) -> bool;-}--impl RequestsCrmAdmin for EntityFilters {- fn requests_crm_admin(&self) -> bool {- matches!(self.crm_company_filters.hidden, Some(true))- }-}--impl RequestsCrmAdmin for ApiEntityFilterAst {- fn requests_crm_admin(&self) -> bool {- self.crm_company_filter- .as_deref()- .is_some_and(ast_requests_crm_admin)- }-}--/// Walks a `CrmCompanyLiteral` AST checking for any `Hidden(true)`-/// literal. Mirrors the conservative shape the request-time extractor-/// in `models::extract_crm_company_filter` allows: `And`/`Or` recurse;-/// `Not` would invert and fail closed downstream, but for the *role-/// gate* we still must inspect under `Not` to avoid a `Not(Hidden(false))`-/// sneaking past — treat any path reaching a `Hidden(true)` literal as-/// admin-required.-fn ast_requests_crm_admin(expr: &Expr<CrmCompanyLiteral>) -> bool {- match expr {- Expr::Literal(CrmCompanyLiteral::Hidden(true)) => true,- Expr::Literal(_) => false,- Expr::And(a, b) | Expr::Or(a, b) => ast_requests_crm_admin(a) || ast_requests_crm_admin(b),- Expr::Not(a) => ast_requests_crm_admin(a),- }-}-/// Builds the Axum router for soup HTTP endpoints.pub fn soup_router<T, U, EAS, S>(state: SoupRouterState<T, U, EAS>) -> Router<S>where@@ -745,6 +677,8 @@ impl From<SoupErr> for SoupHandlerErr {fn from(value: SoupErr) -> Self {match value {SoupErr::AstErr(expand_err) => SoupHandlerErr::ExpandErr(expand_err),+ SoupErr::CrmTeamRequired => SoupHandlerErr::CrmScopeForbidden,+ SoupErr::CrmAdminRequired => SoupHandlerErr::CrmAdminRequired,err => SoupHandlerErr::Internal(err),}}@@ -1081,43 +1015,6 @@ where}))}-/// Returns the team receipt to use when CRM-scoped visibility is required.-/// `crm_scope_requested` is true when the request body carries a-/// `crm_domains` / `crm_addresses` attribute. Returns-/// `Err(CrmScopeForbidden)` when CRM scope was requested but the user has-/// no qualifying team membership.-fn resolve_crm_team_receipt(- crm_scope_requested: bool,- receipt: Option<EntityAccessReceipt<MemberTeamRole>>,-) -> Result<Option<EntityAccessReceipt<MemberTeamRole>>, SoupHandlerErr> {- if crm_scope_requested && receipt.is_none() {- return Err(SoupHandlerErr::CrmScopeForbidden);- }- Ok(receipt)-}--/// Companion to [`resolve_crm_team_receipt`] for the admin-only CRM-/// data path (currently: hidden CRM companies). `admin_requested` is-/// the result of [`RequestsCrmAdmin::requests_crm_admin`] on the-/// effective filter. Returns `Err(CrmAdminRequired)` when the request-/// asks for admin-only data but the receipt is missing or the user's-/// actual team role doesn't satisfy [`AdminTeamRole`].-fn require_crm_admin_role(- admin_requested: bool,- receipt: &Option<EntityAccessReceipt<MemberTeamRole>>,-) -> Result<(), SoupHandlerErr> {- if !admin_requested {- return Ok(());- }- let Some(receipt) = receipt else {- return Err(SoupHandlerErr::CrmAdminRequired);- };- if !receipt.entity_permission().satisfies::<AdminTeamRole>() {- return Err(SoupHandlerErr::CrmAdminRequired);- }- Ok(())-}-/// Wire-format entity filter AST accepted by soup AST endpoints.#[derive(Debug, Default, Serialize, Deserialize, Clone, ToSchema)]pub struct ApiEntityFilterAst {