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(soup): bundle email_filter+crm_scope, extend /ast endpoint, optimize precheck (#3516)

Evan Hutnik253dde4497e7
diff --git a/js/app/packages/queries/soup/items.ts b/js/app/packages/queries/soup/items.ts
index fe0335c8d5..917a990883 100644
--- a/js/app/packages/queries/soup/items.ts
+++ b/js/app/packages/queries/soup/items.ts
@@ -12,7 +12,7 @@ import { mapSoupPageToEntityList } from '@queries/soup/transform-utils';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import { storageServiceClient } from '@service-storage/client';
import type { SoupApiItem } from '@service-storage/generated/schemas';
-import type { EntityFilterAst } from '@service-storage/generated/schemas/entityFilterAst';
+import type { ApiEntityFilterAst } from '@service-storage/generated/schemas/apiEntityFilterAst';
import type { EntityFilters } from '@service-storage/generated/schemas/entityFilters';
import type { Params } from '@service-storage/generated/schemas/params';
import type { PostSoupAstRequestAllOf } from '@service-storage/generated/schemas/postSoupAstRequestAllOf';
@@ -33,7 +33,7 @@ export type SoupItemsQueryArgs = {
export type SoupAstParams = Params;
-export type SoupAstBody = EntityFilterAst & PostSoupAstRequestAllOf;
+export type SoupAstBody = ApiEntityFilterAst & PostSoupAstRequestAllOf;
export type SoupAstItemsQueryArgs = {
params: SoupAstParams;
diff --git a/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts b/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts
index aa35d6c5fe..34002101e0 100644
--- a/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts
@@ -21,6 +21,20 @@ type). `Some(false)` and `None` apply no constraint. */
calendar_only?: EmailFiltersCalendarOnly;
/** Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC. */
cc?: string[];
+ /** CRM-scoped address filter. When non-empty, expands visibility to every
+teammate's mailbox and restricts to threads involving any of these
+fully-qualified addresses. Each address is authorized against
+`crm_contacts` + `crm_companies` (contact must not be hidden, company
+must not be hidden, `email_sync` must be true).
+Mutually exclusive with `crm_domains`. */
+ crm_addresses?: string[];
+ /** CRM-scoped domain filter. When non-empty, expands visibility to every
+teammate's mailbox and restricts to threads involving any of these
+domains (in any of sender/cc/bcc/recipient). Each domain is authorized
+against `crm_domains` + `crm_companies` (must exist for the caller's
+team, company must not be hidden, `email_sync` must be true).
+Mutually exclusive with `crm_addresses`. */
+ crm_domains?: string[];
/** Email thread IDs to filter by. Examples: ['thread-uuid-1']. Empty to search all threads. */
email_thread_ids?: string[];
/** Exclude emails that have any of these labels. Supports both Gmail system labels (e.g. "CATEGORY_PROMOTIONS") and user-created labels. Empty to not exclude any labels.
@@ -44,10 +58,4 @@ Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never ap
/** Controls whether shared email threads are included in results.
Defaults to "exclude" (only the user's own threads). */
shared?: SharedEmailFilter;
- /** When true, expand visibility to every teammate's mailbox: results may
-include emails the requesting user is not a participant on, as long as
-at least one of their teammates is. Requires every sender/cc/bcc/recipient
-value to be a fully-qualified email address or a domain (no partial
-substring matches). */
- team_scope?: boolean;
}
diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.json
index 2bb077b613..a69779b6a2 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -1112,6 +1112,20 @@
},
"description": "Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC."
},
+ "crm_addresses": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "CRM-scoped address filter. When non-empty, expands visibility to every\nteammate's mailbox and restricts to threads involving any of these\nfully-qualified addresses. Each address is authorized against\n`crm_contacts` + `crm_companies` (contact must not be hidden, company\nmust not be hidden, `email_sync` must be true).\nMutually exclusive with `crm_domains`."
+ },
+ "crm_domains": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "CRM-scoped domain filter. When non-empty, expands visibility to every\nteammate's mailbox and restricts to threads involving any of these\ndomains (in any of sender/cc/bcc/recipient). Each domain is authorized\nagainst `crm_domains` + `crm_companies` (must exist for the caller's\nteam, company must not be hidden, `email_sync` must be true).\nMutually exclusive with `crm_addresses`."
+ },
"email_thread_ids": {
"type": "array",
"items": {
@@ -1165,10 +1179,6 @@
"shared": {
"$ref": "#/components/schemas/SharedEmailFilter",
"description": "Controls whether shared email threads are included in results.\nDefaults to \"exclude\" (only the user's own threads)."
- },
- "team_scope": {
- "type": "boolean",
- "description": "When true, expand visibility to every teammate's mailbox: results may\ninclude emails the requesting user is not a participant on, as long as\nat least one of their teammates is. Requires every sender/cc/bcc/recipient\nvalue to be a fully-qualified email address or a domain (no partial\nsubstring matches)."
}
}
},
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts
new file mode 100644
index 0000000000..9064b5ed23
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts
@@ -0,0 +1,36 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface ApiEntityFilterAst {
+ /** the filters that should be applied to the call entity */
+ callf?: unknown;
+ /** the filters that should be applied to the chat entity */
+ cf?: unknown;
+ /** the filters that should be applied to the channel entity */
+ chanf?: unknown;
+ /** the filters that should be applied to the document entity */
+ df?: unknown;
+ /** CRM-scoped address filter (wire key: `eca`). Symmetric counterpart
+to `ecd` for fully-qualified email addresses. */
+ eca?: string[];
+ /** CRM-scoped domain filter (wire key: `ecd`). Parallel to the
+freeform `ef` AST. Expanded by the router into an any-direction
+OR sub-tree AND-merged into `ef`, plus a `CrmScope` tag stamped
+on the resulting [`item_filters::ast::EmailFilterAst::crm_scope`].
+Drives the per-team CRM authorization pre-check and candidate-set
+widening downstream. Mutually exclusive with `eca`. */
+ ecd?: string[];
+ /** the filters that should be applied to the email entity (raw AST
+tree only; CRM scope is carried by the `ecd` / `eca` sibling
+fields). On this endpoint the email filter stays a bare tree,
+unlike the materialized [`EntityFilterAst`] used for cursors. */
+ ef?: unknown;
+ /** the filters that should be applied to the project entity */
+ pf?: unknown;
+ /** the filters that should be applied based on entity properties */
+ propf?: unknown;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts
index 7a5ac1419e..b2bfadfcee 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts
@@ -21,6 +21,20 @@ type). `Some(false)` and `None` apply no constraint. */
calendar_only?: EmailFiltersCalendarOnly;
/** Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC. */
cc?: string[];
+ /** CRM-scoped address filter. When non-empty, expands visibility to every
+teammate's mailbox and restricts to threads involving any of these
+fully-qualified addresses. Each address is authorized against
+`crm_contacts` + `crm_companies` (contact must not be hidden, company
+must not be hidden, `email_sync` must be true).
+Mutually exclusive with `crm_domains`. */
+ crm_addresses?: string[];
+ /** CRM-scoped domain filter. When non-empty, expands visibility to every
+teammate's mailbox and restricts to threads involving any of these
+domains (in any of sender/cc/bcc/recipient). Each domain is authorized
+against `crm_domains` + `crm_companies` (must exist for the caller's
+team, company must not be hidden, `email_sync` must be true).
+Mutually exclusive with `crm_addresses`. */
+ crm_domains?: string[];
/** Email thread IDs to filter by. Examples: ['thread-uuid-1']. Empty to search all threads. */
email_thread_ids?: string[];
/** Exclude emails that have any of these labels. Supports both Gmail system labels (e.g. "CATEGORY_PROMOTIONS") and user-created labels. Empty to not exclude any labels.
@@ -44,10 +58,4 @@ Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never ap
/** Controls whether shared email threads are included in results.
Defaults to "exclude" (only the user's own threads). */
shared?: SharedEmailFilter;
- /** When true, expand visibility to every teammate's mailbox: results may
-include emails the requesting user is not a participant on, as long as
-at least one of their teammates is. Requires every sender/cc/bcc/recipient
-value to be a fully-qualified email address or a domain (no partial
-substring matches). */
- team_scope?: boolean;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilterAst.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilterAst.ts
deleted file mode 100644
index 0c43448267..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilterAst.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Describes a bundle of filters that should be applied across different entity types
- */
-export interface EntityFilterAst {
- /** the filters that should be applied to the call entity */
- callf?: unknown;
- /** the filters that should be applied to the chat entity */
- cf?: unknown;
- /** the filters that should be applied to the channel entity */
- chanf?: unknown;
- /** the filters that should be applied to the document entity */
- df?: unknown;
- /** the filters that should be applied to the email entity */
- ef?: unknown;
- /** the filters that should be applied to the project entity */
- pf?: unknown;
- /** the filters that should be applied based on entity properties */
- propf?: unknown;
-}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index c9410499e0..1f91fd7097 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -53,6 +53,7 @@ export * from './apiChannelMessagesPageNextCursor';
export * from './apiChannelMessagesPagePreviousCursor';
export * from './apiChannelParticipant';
export * from './apiCountedReaction';
+export * from './apiEntityFilterAst';
export * from './apiMessageAttachment';
export * from './apiMessageAttachmentHeight';
export * from './apiMessageAttachmentWidth';
@@ -353,7 +354,6 @@ export * from './emailFilters';
export * from './emailFiltersCalendarOnly';
export * from './emailFiltersImportance';
export * from './emptyResponse';
-export * from './entityFilterAst';
export * from './entityFilters';
export * from './entityPermission';
export * from './entityPermissionOneOf';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequest.ts
index dad8c4e0b6..9a69d3a1a2 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequest.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequest.ts
@@ -4,10 +4,10 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { EntityFilterAst } from './entityFilterAst';
+import type { ApiEntityFilterAst } from './apiEntityFilterAst';
import type { Params } from './params';
import type { PostSoupAstRequestAllOf } from './postSoupAstRequestAllOf';
-export type PostSoupAstRequest = EntityFilterAst &
+export type PostSoupAstRequest = ApiEntityFilterAst &
Params &
PostSoupAstRequestAllOf;
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 819a6c8b4b..e2f148c14b 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -5967,6 +5967,18 @@ export const postItemsSoupBody = zod
.describe(
"Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC."
),
+ crm_addresses: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "CRM-scoped address filter. When non-empty, expands visibility to every\nteammate's mailbox and restricts to threads involving any of these\nfully-qualified addresses. Each address is authorized against\n`crm_contacts` + `crm_companies` (contact must not be hidden, company\nmust not be hidden, `email_sync` must be true).\nMutually exclusive with `crm_domains`."
+ ),
+ crm_domains: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "CRM-scoped domain filter. When non-empty, expands visibility to every\nteammate's mailbox and restricts to threads involving any of these\ndomains (in any of sender\/cc\/bcc\/recipient). Each domain is authorized\nagainst `crm_domains` + `crm_companies` (must exist for the caller's\nteam, company must not be hidden, `email_sync` must be true).\nMutually exclusive with `crm_addresses`."
+ ),
email_thread_ids: zod
.array(zod.string())
.optional()
@@ -6032,12 +6044,6 @@ export const postItemsSoupBody = zod
.describe(
'Controls whether shared email threads are included in results.'
),
- team_scope: zod
- .boolean()
- .optional()
- .describe(
- "When true, expand visibility to every teammate's mailbox: results may\ninclude emails the requesting user is not a participant on, as long as\nat least one of their teammates is. Requires every sender\/cc\/bcc\/recipient\nvalue to be a fully-qualified email address or a domain (no partial\nsubstring matches)."
- ),
})
.optional()
.describe(
@@ -7428,10 +7434,24 @@ export const postItemsSoupAstBody = zod
.unknown()
.optional()
.describe('the filters that should be applied to the document entity'),
+ eca: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'CRM-scoped address filter (wire key: `eca`). Symmetric counterpart\nto `ecd` for fully-qualified email addresses.'
+ ),
+ ecd: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'CRM-scoped domain filter (wire key: `ecd`). Parallel to the\nfreeform `ef` AST. Expanded by the router into an any-direction\nOR sub-tree AND-merged into `ef`, plus a `CrmScope` tag stamped\non the resulting [`item_filters::ast::EmailFilterAst::crm_scope`].\nDrives the per-team CRM authorization pre-check and candidate-set\nwidening downstream. Mutually exclusive with `eca`.'
+ ),
ef: zod
.unknown()
.optional()
- .describe('the filters that should be applied to the email entity'),
+ .describe(
+ 'the filters that should be applied to the email entity (raw AST\ntree only; CRM scope is carried by the `ecd` \/ `eca` sibling\nfields). On this endpoint the email filter stays a bare tree,\nunlike the materialized [`EntityFilterAst`] used for cursors.'
+ ),
pf: zod
.unknown()
.optional()
@@ -7443,9 +7463,6 @@ export const postItemsSoupAstBody = zod
'the filters that should be applied based on entity properties'
),
})
- .describe(
- 'Describes a bundle of filters that should be applied across different entity types'
- )
.and(
zod.object({
expand: zod
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index d076785733..efbd56a08e 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -6564,6 +6564,46 @@
}
}
},
+ "ApiEntityFilterAst": {
+ "type": "object",
+ "properties": {
+ "callf": {
+ "description": "the filters that should be applied to the call entity"
+ },
+ "cf": {
+ "description": "the filters that should be applied to the chat entity"
+ },
+ "chanf": {
+ "description": "the filters that should be applied to the channel entity"
+ },
+ "df": {
+ "description": "the filters that should be applied to the document entity"
+ },
+ "eca": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "CRM-scoped address filter (wire key: `eca`). Symmetric counterpart\nto `ecd` for fully-qualified email addresses."
+ },
+ "ecd": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "CRM-scoped domain filter (wire key: `ecd`). Parallel to the\nfreeform `ef` AST. Expanded by the router into an any-direction\nOR sub-tree AND-merged into `ef`, plus a `CrmScope` tag stamped\non the resulting [`item_filters::ast::EmailFilterAst::crm_scope`].\nDrives the per-team CRM authorization pre-check and candidate-set\nwidening downstream. Mutually exclusive with `eca`."
+ },
+ "ef": {
+ "description": "the filters that should be applied to the email entity (raw AST\ntree only; CRM scope is carried by the `ecd` / `eca` sibling\nfields). On this endpoint the email filter stays a bare tree,\nunlike the materialized [`EntityFilterAst`] used for cursors."
+ },
+ "pf": {
+ "description": "the filters that should be applied to the project entity"
+ },
+ "propf": {
+ "description": "the filters that should be applied based on entity properties"
+ }
+ }
+ },
"ApiMessageAttachment": {
"type": "object",
"description": "An attachment on a message.",
@@ -9035,6 +9075,20 @@
},
"description": "Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC."
},
+ "crm_addresses": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "CRM-scoped address filter. When non-empty, expands visibility to every\nteammate's mailbox and restricts to threads involving any of these\nfully-qualified addresses. Each address is authorized against\n`crm_contacts` + `crm_companies` (contact must not be hidden, company\nmust not be hidden, `email_sync` must be true).\nMutually exclusive with `crm_domains`."
+ },
+ "crm_domains": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "CRM-scoped domain filter. When non-empty, expands visibility to every\nteammate's mailbox and restricts to threads involving any of these\ndomains (in any of sender/cc/bcc/recipient). Each domain is authorized\nagainst `crm_domains` + `crm_companies` (must exist for the caller's\nteam, company must not be hidden, `email_sync` must be true).\nMutually exclusive with `crm_addresses`."
+ },
"email_thread_ids": {
"type": "array",
"items": {
@@ -9088,10 +9142,6 @@
"shared": {
"$ref": "#/components/schemas/SharedEmailFilter",
"description": "Controls whether shared email threads are included in results.\nDefaults to \"exclude\" (only the user's own threads)."
- },
- "team_scope": {
- "type": "boolean",
- "description": "When true, expand visibility to every teammate's mailbox: results may\ninclude emails the requesting user is not a participant on, as long as\nat least one of their teammates is. Requires every sender/cc/bcc/recipient\nvalue to be a fully-qualified email address or a domain (no partial\nsubstring matches)."
}
}
},
@@ -9099,33 +9149,6 @@
"type": "object",
"description": "Empty response is required due to custom fetch forcing `response.json()`"
},
- "EntityFilterAst": {
- "type": "object",
- "description": "Describes a bundle of filters that should be applied across different entity types",
- "properties": {
- "callf": {
- "description": "the filters that should be applied to the call entity"
- },
- "cf": {
- "description": "the filters that should be applied to the chat entity"
- },
- "chanf": {
- "description": "the filters that should be applied to the channel entity"
- },
- "df": {
- "description": "the filters that should be applied to the document entity"
- },
- "ef": {
- "description": "the filters that should be applied to the email entity"
- },
- "pf": {
- "description": "the filters that should be applied to the project entity"
- },
- "propf": {
- "description": "the filters that should be applied based on entity properties"
- }
- }
- },
"EntityFilters": {
"type": "object",
"description": "a bundle of all of the filters for each entity type",
@@ -11163,7 +11186,7 @@
"PostSoupAstRequest": {
"allOf": [
{
- "$ref": "#/components/schemas/EntityFilterAst"
+ "$ref": "#/components/schemas/ApiEntityFilterAst"
},
{
"$ref": "#/components/schemas/Params"
diff --git a/rust/cloud-storage/.sqlx/query-59ed63c0cb97189af71b12a68e7a516b7122cb0462db7ecc569b2e55a6e5057f.json b/rust/cloud-storage/.sqlx/query-59ed63c0cb97189af71b12a68e7a516b7122cb0462db7ecc569b2e55a6e5057f.json
new file mode 100644
index 0000000000..9a379e32b6
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-59ed63c0cb97189af71b12a68e7a516b7122cb0462db7ecc569b2e55a6e5057f.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n input.domain AS \"domain!\",\n (d.id IS NOT NULL) AS \"exists!\",\n COALESCE(c.hidden, FALSE) AS \"company_hidden!\",\n COALESCE(c.email_sync, FALSE) AS \"email_sync!\"\n FROM UNNEST($2::text[]) WITH ORDINALITY AS input(domain, ord)\n LEFT JOIN crm_domains d\n ON d.team_id = $1 AND LOWER(d.domain) = input.domain\n LEFT JOIN crm_companies c\n ON c.id = d.company_id\n ORDER BY input.ord\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "domain!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "exists!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "company_hidden!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_sync!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "59ed63c0cb97189af71b12a68e7a516b7122cb0462db7ecc569b2e55a6e5057f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b845e01904b9e9f8d1f322e788b7cf6555ee13b3de24bbe50bbc801a2730e446.json b/rust/cloud-storage/.sqlx/query-b845e01904b9e9f8d1f322e788b7cf6555ee13b3de24bbe50bbc801a2730e446.json
new file mode 100644
index 0000000000..45964bff36
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b845e01904b9e9f8d1f322e788b7cf6555ee13b3de24bbe50bbc801a2730e446.json
@@ -0,0 +1,47 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n input.address AS \"address!\",\n (m.email IS NOT NULL) AS \"exists!\",\n COALESCE(m.contact_hidden, FALSE) AS \"contact_hidden!\",\n COALESCE(m.company_hidden, FALSE) AS \"company_hidden!\",\n COALESCE(m.email_sync, FALSE) AS \"email_sync!\"\n FROM UNNEST($2::text[]) WITH ORDINALITY AS input(address, ord)\n LEFT JOIN (\n SELECT\n ct.email AS email,\n ct.hidden AS contact_hidden,\n c.hidden AS company_hidden,\n c.email_sync AS email_sync\n FROM crm_contacts ct\n JOIN crm_companies c ON c.id = ct.company_id\n WHERE c.team_id = $1\n ) m ON m.email = input.address\n ORDER BY input.ord\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "address!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "exists!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "contact_hidden!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "company_hidden!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "email_sync!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "b845e01904b9e9f8d1f322e788b7cf6555ee13b3de24bbe50bbc801a2730e446"
+}
diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rs
index 12f76cf71b..68ebfeb3f2 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -1,6 +1,6 @@
//! Port for persistence operations on CRM companies.
-use crate::domain::model::{CrmCompany, CrmError, DomainMetadata};
+use crate::domain::model::{CrmCompany, CrmError, CrmScopePrecheck, DomainMetadata};
/// The CompaniesRepository defines persistence operations for CRM
/// companies and their associated domains.
@@ -212,4 +212,23 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
contact_id: &uuid::Uuid,
hidden: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
+
+ /// Batched authorization probe for a CRM-scoped email query. Returns
+ /// per-input status the email service maps into typed `EmailErr`
+ /// variants (`CrmDomainNotFound`, `CrmDomainNotPermitted`,
+ /// `CrmAddressNotFound`, `CrmAddressNotPermitted`,
+ /// `CrmDisabledForTeam`).
+ ///
+ /// `domains` and `addresses` are expected to be lowercased by the
+ /// caller. Either may be empty; both may be non-empty but the
+ /// service-layer caller enforces mutual exclusivity.
+ ///
+ /// Read-only and not transactional — the dynamic query that follows
+ /// re-checks the team-level killswitch via JOIN to close the race.
+ fn crm_scope_precheck(
+ &self,
+ team_id: &uuid::Uuid,
+ domains: &[String],
+ addresses: &[String],
+ ) -> impl Future<Output = Result<CrmScopePrecheck, CrmError>> + Send;
}
diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rs
index d235a8e2df..4ae6f16419 100644
--- a/rust/cloud-storage/crm/src/domain/model.rs
+++ b/rust/cloud-storage/crm/src/domain/model.rs
@@ -62,6 +62,61 @@ pub struct CrmDomain {
pub created_at: DateTime<Utc>,
}
+/// Result of [`crate::domain::companies_repo::CompaniesRepository::crm_scope_precheck`].
+///
+/// Carries the per-input authorization status the caller (`EmailService`)
+/// needs to either accept or reject a CRM-scoped query before it runs.
+#[derive(Debug, Clone)]
+pub struct CrmScopePrecheck {
+ /// `team_crm_settings.crm_enabled` for the requesting team. `false`
+ /// when the team's row exists with `crm_enabled = false`, *or* when no
+ /// row exists at all (older teams predating `team_crm_settings`).
+ pub crm_enabled: bool,
+ /// One row per requested domain, in the same order as the input list.
+ /// **Exception:** when `crm_enabled = false`, this vec is empty —
+ /// the email service short-circuits on the killswitch before
+ /// consulting per-input rows, so the per-domain probes are skipped
+ /// and callers must not assume length parity with the input list
+ /// without first checking `crm_enabled`.
+ pub domains: Vec<CrmDomainStatus>,
+ /// One row per requested address, in the same order as the input
+ /// list. Same `crm_enabled = false` exception as [`Self::domains`].
+ pub addresses: Vec<CrmAddressStatus>,
+}
+
+/// Per-domain authorization status. See [`CrmScopePrecheck`].
+#[derive(Debug, Clone)]
+pub struct CrmDomainStatus {
+ /// The domain as supplied (lowercased).
+ pub domain: String,
+ /// Whether a `crm_domains` row exists for this `(team_id, domain)`.
+ pub exists: bool,
+ /// `crm_companies.hidden` for the company owning the matched
+ /// `crm_domains` row. `false` when `!exists`.
+ pub company_hidden: bool,
+ /// `crm_companies.email_sync` for the company owning the matched
+ /// `crm_domains` row. `false` when `!exists`.
+ pub email_sync: bool,
+}
+
+/// Per-address authorization status. See [`CrmScopePrecheck`].
+#[derive(Debug, Clone)]
+pub struct CrmAddressStatus {
+ /// The address as supplied (lowercased).
+ pub address: String,
+ /// Whether a `crm_contacts` row exists whose company belongs to the
+ /// requesting team. Cross-team contacts (same email under a different
+ /// team's company) are reported as `exists = false` so existence
+ /// doesn't leak across teams.
+ pub exists: bool,
+ /// `crm_contacts.hidden` for the matched contact. `false` when `!exists`.
+ pub contact_hidden: bool,
+ /// `crm_companies.hidden` for the matched contact's company. `false` when `!exists`.
+ pub company_hidden: bool,
+ /// `crm_companies.email_sync` for the matched contact's company. `false` when `!exists`.
+ pub email_sync: bool,
+}
+
/// Errors that can occur in the CRM domain.
#[derive(Debug, thiserror::Error)]
pub enum CrmError {
diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rs
index 816678166c..0b34e7cdae 100644
--- a/rust/cloud-storage/crm/src/domain/service.rs
+++ b/rust/cloud-storage/crm/src/domain/service.rs
@@ -4,7 +4,7 @@ use crate::domain::{
companies_repo::CompaniesRepository,
company_metadata_resolver::CompanyMetadataResolver,
generic_email_domains::is_generic_email_domain,
- model::{CrmCompany, CrmError},
+ model::{CrmCompany, CrmError, CrmScopePrecheck},
};
/// The CrmService exposes operations over CRM records (companies, their
@@ -140,6 +140,15 @@ pub trait CrmService: Clone + Send + Sync + 'static {
contact_id: &uuid::Uuid,
hidden: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
+
+ /// Batched authorization probe for a CRM-scoped email query. See
+ /// [`CompaniesRepository::crm_scope_precheck`].
+ fn crm_scope_precheck(
+ &self,
+ team_id: &uuid::Uuid,
+ domains: &[String],
+ addresses: &[String],
+ ) -> impl Future<Output = Result<CrmScopePrecheck, CrmError>> + Send;
}
/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`]
@@ -360,4 +369,16 @@ where
.set_contact_hidden(team_id, contact_id, hidden)
.await
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn crm_scope_precheck(
+ &self,
+ team_id: &uuid::Uuid,
+ domains: &[String],
+ addresses: &[String],
+ ) -> Result<CrmScopePrecheck, CrmError> {
+ self.companies_repository
+ .crm_scope_precheck(team_id, domains, addresses)
+ .await
+ }
}
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
index fd4af6d1e7..2ab7eb8513 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -5,7 +5,10 @@ mod test;
use crate::domain::{
companies_repo::CompaniesRepository,
- model::{CrmCompany, CrmDomain, CrmError, DomainMetadata},
+ model::{
+ CrmAddressStatus, CrmCompany, CrmDomain, CrmDomainStatus, CrmError, CrmScopePrecheck,
+ DomainMetadata,
+ },
};
use sqlx::PgPool;
@@ -836,4 +839,126 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn crm_scope_precheck(
+ &self,
+ team_id: &uuid::Uuid,
+ domains: &[String],
+ addresses: &[String],
+ ) -> Result<CrmScopePrecheck, CrmError> {
+ // Killswitch read: a missing row is treated as `crm_enabled = false`.
+ let crm_enabled: bool = sqlx::query_scalar!(
+ r#"SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1"#,
+ team_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?
+ .unwrap_or(false);
+
+ // When the team killswitch is off, the email service will reject the
+ // request with `CrmDisabledForTeam` before looking at per-input
+ // statuses — so skip the probes entirely.
+ if !crm_enabled {
+ return Ok(CrmScopePrecheck {
+ crm_enabled: false,
+ domains: Vec::new(),
+ addresses: Vec::new(),
+ });
+ }
+
+ let domain_statuses: Vec<CrmDomainStatus> = if domains.is_empty() {
+ Vec::new()
+ } else {
+ // `WITH ORDINALITY` + `ORDER BY input.ord` guarantees output
+ // row order matches the input list — `CrmScopePrecheck.domains`
+ // documents that contract.
+ sqlx::query!(
+ r#"
+ SELECT
+ input.domain AS "domain!",
+ (d.id IS NOT NULL) AS "exists!",
+ COALESCE(c.hidden, FALSE) AS "company_hidden!",
+ COALESCE(c.email_sync, FALSE) AS "email_sync!"
+ FROM UNNEST($2::text[]) WITH ORDINALITY AS input(domain, ord)
+ LEFT JOIN crm_domains d
+ ON d.team_id = $1 AND LOWER(d.domain) = input.domain
+ LEFT JOIN crm_companies c
+ ON c.id = d.company_id
+ ORDER BY input.ord
+ "#,
+ team_id,
+ domains,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?
+ .into_iter()
+ .map(|r| CrmDomainStatus {
+ domain: r.domain,
+ exists: r.exists,
+ company_hidden: r.company_hidden,
+ email_sync: r.email_sync,
+ })
+ .collect()
+ };
+
+ let address_statuses: Vec<CrmAddressStatus> = if addresses.is_empty() {
+ Vec::new()
+ } else {
+ // Pre-materialize the team's contact rows in a derived table,
+ // then hash-join against the input array. Avoids LATERAL's
+ // per-outer-row execution. Safe to assume at most one row per
+ // (team, email) thanks to crm_contacts_company_id_email_key
+ // UNIQUE (company_id, email) plus the populate-path invariant
+ // that an email's domain uniquely identifies its company
+ // within a team (via crm_domains_team_id_lower_domain_unique).
+ // `WITH ORDINALITY` + `ORDER BY input.ord` guarantees output
+ // row order matches the input list — `CrmScopePrecheck.addresses`
+ // documents that contract.
+ sqlx::query!(
+ r#"
+ SELECT
+ input.address AS "address!",
+ (m.email IS NOT NULL) AS "exists!",
+ COALESCE(m.contact_hidden, FALSE) AS "contact_hidden!",
+ COALESCE(m.company_hidden, FALSE) AS "company_hidden!",
+ COALESCE(m.email_sync, FALSE) AS "email_sync!"
+ FROM UNNEST($2::text[]) WITH ORDINALITY AS input(address, ord)
+ LEFT JOIN (
+ SELECT
+ ct.email AS email,
+ ct.hidden AS contact_hidden,
+ c.hidden AS company_hidden,
+ c.email_sync AS email_sync
+ FROM crm_contacts ct
+ JOIN crm_companies c ON c.id = ct.company_id
+ WHERE c.team_id = $1
+ ) m ON m.email = input.address
+ ORDER BY input.ord
+ "#,
+ team_id,
+ addresses,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?
+ .into_iter()
+ .map(|r| CrmAddressStatus {
+ address: r.address,
+ exists: r.exists,
+ contact_hidden: r.contact_hidden,
+ company_hidden: r.company_hidden,
+ email_sync: r.email_sync,
+ })
+ .collect()
+ };
+
+ Ok(CrmScopePrecheck {
+ crm_enabled,
+ domains: domain_statuses,
+ addresses: address_statuses,
+ })
+ }
}
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
index 347fb1c4d4..85a2721cc6 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
@@ -674,3 +674,146 @@ async fn service_populate_contact_writes_when_domain_differs(pool: PgPool) -> an
);
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn precheck_reports_killswitch_off_when_settings_missing(pool: PgPool) -> anyhow::Result<()> {
+ let team = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team, owner).await?;
+ // intentionally no team_crm_settings row
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .crm_scope_precheck(&team, &["acme.com".to_string()], &[])
+ .await?;
+ // Killswitch off short-circuits: the email service rejects with
+ // CrmDisabledForTeam regardless of per-input state, so the probes
+ // are skipped and per-input rows come back empty.
+ assert!(!result.crm_enabled);
+ assert!(result.domains.is_empty());
+ assert!(result.addresses.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn precheck_resolves_domain_with_company_state(pool: PgPool) -> anyhow::Result<()> {
+ let team = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team, owner).await?;
+ enable_crm_for_team(&pool, team).await?;
+ insert_company(&pool, team, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .crm_scope_precheck(
+ &team,
+ &["acme.com".to_string(), "missing.com".to_string()],
+ &[],
+ )
+ .await?;
+ assert!(result.crm_enabled);
+ assert_eq!(result.domains.len(), 2);
+
+ let acme = result
+ .domains
+ .iter()
+ .find(|d| d.domain == "acme.com")
+ .unwrap();
+ assert!(acme.exists);
+ assert!(!acme.company_hidden);
+ assert!(acme.email_sync);
+
+ let missing = result
+ .domains
+ .iter()
+ .find(|d| d.domain == "missing.com")
+ .unwrap();
+ assert!(!missing.exists);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn precheck_reports_hidden_and_email_sync_disabled_companies(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team, owner).await?;
+ enable_crm_for_team(&pool, team).await?;
+ let hidden_co = insert_company(&pool, team, false, &["hidden.com"]).await?;
+ sqlx::query("UPDATE crm_companies SET hidden = TRUE WHERE id = $1")
+ .bind(hidden_co)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .crm_scope_precheck(&team, &["hidden.com".to_string()], &[])
+ .await?;
+ let d = &result.domains[0];
+ assert!(d.exists);
+ assert!(d.company_hidden);
+ assert!(!d.email_sync);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn precheck_address_resolves_contact_within_team(pool: PgPool) -> anyhow::Result<()> {
+ let team = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team, owner).await?;
+ enable_crm_for_team(&pool, team).await?;
+ let company = insert_company(&pool, team, true, &["acme.com"]).await?;
+ let link = insert_email_link(&pool, owner, "[email protected]").await?;
+ insert_contact_with_source(&pool, company, "[email protected]", link).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .crm_scope_precheck(
+ &team,
+ &[],
+ &["[email protected]".to_string(), "[email protected]".to_string()],
+ )
+ .await?;
+
+ let alice = result
+ .addresses
+ .iter()
+ .find(|a| a.address == "[email protected]")
+ .unwrap();
+ assert!(alice.exists);
+ assert!(!alice.contact_hidden);
+ assert!(!alice.company_hidden);
+ assert!(alice.email_sync);
+
+ let bob = result
+ .addresses
+ .iter()
+ .find(|a| a.address == "[email protected]")
+ .unwrap();
+ assert!(!bob.exists);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn precheck_address_does_not_leak_other_team_contacts(pool: PgPool) -> anyhow::Result<()> {
+ let team_a = Uuid::now_v7();
+ let team_b = Uuid::now_v7();
+ let owner_a = "macro|[email protected]";
+ let owner_b = "macro|[email protected]";
+ seed_team(&pool, team_a, owner_a).await?;
+ seed_team(&pool, team_b, owner_b).await?;
+ enable_crm_for_team(&pool, team_b).await?;
+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;
+ let link_a = insert_email_link(&pool, owner_a, "[email protected]").await?;
+ insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;
+
+ // team_b asks about an address that only exists under team_a — must
+ // report as non-existent, not leak team_a's contact state.
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .crm_scope_precheck(&team_b, &[], &["[email protected]".to_string()])
+ .await?;
+ assert!(!result.addresses[0].exists);
+ Ok(())
+}
diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_team_scope.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_scope.sql
similarity index 96%
rename from rust/cloud-storage/email/fixtures/email_dynamic_query_team_scope.sql
rename to rust/cloud-storage/email/fixtures/email_dynamic_query_crm_scope.sql
index adbe03107a..7bae48a214 100644
--- a/rust/cloud-storage/email/fixtures/email_dynamic_query_team_scope.sql
+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_crm_scope.sql
@@ -1,4 +1,4 @@
--- Fixture for testing team_scope dynamic queries.
+-- Fixture for testing CRM-scoped dynamic queries.
--
-- Sets up:
-- • Team Alpha with two members (Alice, Bob).
@@ -37,6 +37,14 @@ VALUES
('e0000001-0000-0000-0000-000000000001', 'macro|[email protected]', 'member');
-- Carol is intentionally NOT a member.
+-- Team-level CRM killswitch ON. The candidate-source SQL joins
+-- team_crm_settings (crm_enabled = TRUE), so this row must be present
+-- for any CRM-scoped query to return rows. Tests that exercise the
+-- killswitch-off behavior flip this in their own fixture script.
+INSERT INTO team_crm_settings (team_id, crm_enabled)
+VALUES
+ ('e0000001-0000-0000-0000-000000000001', TRUE);
+
-- == Email links (one per user) ==
INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
VALUES
diff --git a/rust/cloud-storage/email/src/domain/models/error.rs b/rust/cloud-storage/email/src/domain/models/error.rs
index 7bfee8eddb..2c99dcc07f 100644
--- a/rust/cloud-storage/email/src/domain/models/error.rs
+++ b/rust/cloud-storage/email/src/domain/models/error.rs
@@ -50,12 +50,24 @@ pub enum EmailErr {
/// Invalid email filter input.
#[error("{0}")]
InvalidEmailFilter(String),
- /// A team-scoped query referenced an email domain that is either not
- /// tracked as a CRM organization for the team, or whose organization
- /// has `email_sync` disabled. Without email_sync, the team has not
- /// opted into sharing emails for that organization across members.
- #[error(
- "Domain {0} is not authorized for team-scoped email queries (no matching CRM organization, or organization has email_sync disabled)"
- )]
- DomainNotPermittedForTeamScope(String),
+ /// The caller's team has `team_crm_settings.crm_enabled = false` (or no
+ /// row at all), so no CRM-scoped query is allowed.
+ #[error("CRM is disabled for this team")]
+ CrmDisabledForTeam,
+ /// A CRM-scoped query referenced a domain that does not have a matching
+ /// `crm_domains` row for the caller's team.
+ #[error("CRM domain {0} not found for this team")]
+ CrmDomainNotFound(String),
+ /// A CRM-scoped query referenced a domain whose company is hidden or
+ /// has `email_sync = false`.
+ #[error("CRM domain {0} is not permitted for CRM-scoped queries")]
+ CrmDomainNotPermitted(String),
+ /// A CRM-scoped query referenced an address with no matching
+ /// `crm_contacts` row for the caller's team.
+ #[error("CRM address {0} not found for this CRM scope")]
+ CrmAddressNotFound(String),
+ /// A CRM-scoped query referenced an address whose contact or company
+ /// is hidden, or whose company has `email_sync = false`.
+ #[error("CRM address {0} is not permitted for CRM-scoped queries")]
+ CrmAddressNotPermitted(String),
}
diff --git a/rust/cloud-storage/email/src/domain/models/preview.rs b/rust/cloud-storage/email/src/domain/models/preview.rs
index cf0d71a143..21a2a79c7d 100644
--- a/rust/cloud-storage/email/src/domain/models/preview.rs
+++ b/rust/cloud-storage/email/src/domain/models/preview.rs
@@ -1,7 +1,7 @@
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};
use frecency::domain::models::AggregateFrecency;
-use item_filters::ast::{LiteralTree, email::EmailLiteral};
+use item_filters::ast::{CrmScope, LiteralTree, email::EmailLiteral};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Identify, Query, SimpleSortMethod, SortOn};
use serde_with::{DeserializeFromStr, SerializeDisplay};
@@ -22,7 +22,7 @@ pub struct PreviewCursorQuery {
/// When `Some(team_id)`, the dynamic query path expands the candidate
/// thread set from "only this `link_id`" to "every `link_id` owned by
/// any user on this team." Populated by the service after a successful
- /// team_scope validation (see `validate_team_scope`).
+ /// CRM-scope validation (see `validate_crm_scope`).
pub team_id: Option<Uuid>,
}
@@ -141,9 +141,14 @@ pub struct GetEmailsRequest {
pub macro_id: MacroUserIdStr<'static>,
pub limit: Option<u32>,
pub query: Query<Uuid, SimpleSortMethod, LiteralTree<EmailLiteral>>,
- /// Proof that the caller belongs to a team, when the query contains an
- /// `EmailLiteral::TeamScope` literal. The receipt's `entity()` is the
- /// team's UUID, which the query layer can use to expand visibility to
- /// teammate mailboxes.
+ /// Proof that the caller belongs to a team. Forwarded by the soup
+ /// router unconditionally (when the user is on a team); the email
+ /// service uses it only when `crm_scope` is `Some` to authorize the
+ /// CRM-scoped widening of the candidate set.
pub team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,
+ /// CRM scope tag extracted from `EntityFilterAst::email_crm_scope`.
+ /// When `Some`, the email service runs the per-team CRM pre-check
+ /// and (on success) widens the candidate set to every team
+ /// member's mailbox.
+ pub crm_scope: Option<CrmScope>,
}
diff --git a/rust/cloud-storage/email/src/domain/service/previews.rs b/rust/cloud-storage/email/src/domain/service/previews.rs
index 440af171a6..accb947354 100644
--- a/rust/cloud-storage/email/src/domain/service/previews.rs
+++ b/rust/cloud-storage/email/src/domain/service/previews.rs
@@ -1,7 +1,5 @@
use entity_access::domain::models::EntityAccessReceipt;
use entity_access::domain::models::MemberTeamRole;
-use filter_ast::Expr;
-use item_filters::ast::email::{Email, EmailLiteral};
use crate::domain::{
models::{
@@ -13,12 +11,10 @@ use frecency::domain::{
models::{AggregateId, FrecencyByIdsRequest, FrecencyData},
ports::FrecencyQueryService,
};
-use item_filters::ast::LiteralTree;
use macro_user_id::cowlike::CowLike;
-use macro_user_id::email::ReadEmailParts;
use model_entity::EntityType;
use models_pagination::{CollectBy, PaginateOn, PaginatedCursor, SimpleSortMethod};
-use std::collections::{HashMap, HashSet};
+use std::collections::HashMap;
use uuid::Uuid;
use super::EmailServiceImpl;
@@ -44,10 +40,11 @@ where
limit,
query,
team_receipt,
+ crm_scope,
} = req;
let team_id = self
- .validate_team_scope(team_receipt.as_ref(), query.filter())
+ .validate_crm_scope(team_receipt.as_ref(), crm_scope.as_ref())
.await?;
let sort_method = *query.sort_method();
@@ -141,155 +138,68 @@ where
.map_err(anyhow::Error::from)?)
}
- /// Verify that a query is allowed to run team-scoped behavior.
+ /// CRM-scope validation for the new `crm_domains` / `crm_addresses`
+ /// filter attributes. Returns `Ok(Some(team_id))` when the scope is
+ /// present and every requested domain/address passes the per-team CRM
+ /// pre-check; `Ok(None)` when no scope was requested.
///
- /// Three layered checks, in order:
- /// 1. Did the query actually request `EmailLiteral::TeamScope`? If not,
- /// this is a normal per-mailbox query — no further checks apply.
- /// 2. Is a team-membership receipt present? If not, the caller asked
- /// for team-wide visibility without proof of team membership —
- /// reject as `Unauthorized`. (This shouldn't happen via the soup
- /// handler, which 403s upstream, but the email service is the
- /// resource boundary and validates defensively.)
- /// 3. For each `Email::Domain(_)` literal in the AST, the team must
- /// have a CRM organization tracking that domain with
- /// `email_sync = true`. Otherwise the team has not opted into
- /// sharing emails for that domain — reject the query.
- ///
- /// Returns `Some(team_id)` when team_scope was requested AND the receipt
- /// passed all checks (membership, domain authorization). `None` when
- /// team_scope wasn't requested — the caller should run the normal
- /// per-link query path.
- async fn validate_team_scope(
+ /// Errors:
+ /// * `Unauthorized` — caller has no qualifying team membership but
+ /// the filter requested CRM scope.
+ /// * `CrmDisabledForTeam` — `team_crm_settings.crm_enabled = false`.
+ /// * `CrmDomainNotFound` / `CrmDomainNotPermitted` —
+ /// per-domain failure (no row / hidden company / email_sync off).
+ /// * `CrmAddressNotFound` / `CrmAddressNotPermitted` —
+ /// per-address failure (no row / hidden contact / hidden company / email_sync off).
+ async fn validate_crm_scope(
&self,
team_receipt: Option<&EntityAccessReceipt<MemberTeamRole>>,
- filter: &LiteralTree<EmailLiteral>,
+ crm_scope: Option<&item_filters::ast::CrmScope>,
) -> Result<Option<Uuid>, EmailErr> {
- if !filter_requests_team_scope(filter) {
+ let Some(scope) = crm_scope else {
return Ok(None);
- }
-
- // Reject any `Email::Partial(_)` address under team_scope. The typed
- // POST endpoint catches this at AST expansion via
- // `ExpandErr::TeamScopeRequiresQualifiedEmail`, but the raw AST
- // endpoint bypasses that path — a `Partial` would otherwise become
- // a team-wide `ILIKE` substring search across teammate mailboxes,
- // skipping the qualified-address rule and the CRM domain-consent
- // gate. Reject here defensively.
- if filter_contains_partial_address(filter) {
- return Err(EmailErr::Unauthorized);
- }
+ };
let receipt = team_receipt.ok_or(EmailErr::Unauthorized)?;
-
let team_id = Uuid::parse_str(&receipt.entity().entity_id).map_err(|e| {
EmailErr::RepoErr(anyhow::anyhow!(
"team_receipt entity_id is not a valid uuid: {e}"
))
})?;
- let domains = collect_domain_literals(filter);
- if domains.is_empty() {
- return Ok(Some(team_id));
- }
+ let (domains, addresses): (&[String], &[String]) = match scope {
+ item_filters::ast::CrmScope::Domains(d) => (d.as_slice(), &[]),
+ item_filters::ast::CrmScope::Addresses(a) => (&[], a.as_slice()),
+ };
- for domain in domains {
- let company = self
- .crm_service
- .get_company_by_domain(&team_id, &domain)
- .await
- .map_err(|e| EmailErr::RepoErr(anyhow::anyhow!("crm lookup failed: {e}")))?;
+ let precheck = self
+ .crm_service
+ .crm_scope_precheck(&team_id, domains, addresses)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::anyhow!("crm precheck failed: {e}")))?;
- match company {
- Some(company) if company.email_sync => {}
- _ => return Err(EmailErr::DomainNotPermittedForTeamScope(domain)),
- }
+ if !precheck.crm_enabled {
+ return Err(EmailErr::CrmDisabledForTeam);
}
- Ok(Some(team_id))
- }
-}
-
-/// Walks an email-filter AST and returns the deduped set of domains that
-/// require CRM `email_sync` authorization under team_scope.
-///
-/// Sources:
-/// - `Email::Domain(d)` → `d` directly. The literal IS a domain.
-/// - `Email::Complete(addr)` → `addr.domain_part()`. The team_scope rule
-/// is "the address's company must have email_sync enabled", so an exact
-/// address like `[email protected]` is governed by acme.com's CRM company,
-/// not by whether alice is individually in `crm_contacts`.
-/// - `Email::Partial(_)` → not handled here. `validate_team_scope` rejects
-/// Partial+team_scope upfront via `filter_contains_partial_address`, so
-/// this walker only sees Domain/Complete by the time it runs.
-fn collect_domain_literals(filter: &LiteralTree<EmailLiteral>) -> HashSet<String> {
- fn walk(expr: &Expr<EmailLiteral>, out: &mut HashSet<String>) {
- match expr {
- Expr::And(a, b) | Expr::Or(a, b) => {
- walk(a, out);
- walk(b, out);
+ for status in &precheck.domains {
+ if !status.exists {
+ return Err(EmailErr::CrmDomainNotFound(status.domain.clone()));
+ }
+ if status.company_hidden || !status.email_sync {
+ return Err(EmailErr::CrmDomainNotPermitted(status.domain.clone()));
}
- Expr::Not(a) => walk(a, out),
- Expr::Literal(
- EmailLiteral::Sender(email)
- | EmailLiteral::Cc(email)
- | EmailLiteral::Bcc(email)
- | EmailLiteral::Recipient(email),
- ) => match email {
- Email::Domain(d) => {
- out.insert(d.to_ascii_lowercase());
- }
- Email::Complete(addr) => {
- out.insert(addr.0.domain_part().to_ascii_lowercase());
- }
- Email::Partial(_) => {}
- },
- Expr::Literal(_) => {}
}
- }
- let mut out = HashSet::new();
- if let Some(expr) = filter.as_ref() {
- walk(expr, &mut out);
- }
- out
-}
-/// Walks an email-filter AST and returns true if any node is the
-/// `EmailLiteral::TeamScope` literal. Used to gate team-scope-specific
-/// validation/expansion: without this literal the caller is not asking for
-/// team-wide visibility, so checks like CRM domain authorization don't apply.
-fn filter_requests_team_scope(filter: &LiteralTree<EmailLiteral>) -> bool {
- fn walk(expr: &Expr<EmailLiteral>) -> bool {
- match expr {
- Expr::And(a, b) | Expr::Or(a, b) => walk(a) || walk(b),
- Expr::Not(a) => walk(a),
- Expr::Literal(EmailLiteral::TeamScope) => true,
- Expr::Literal(_) => false,
+ for status in &precheck.addresses {
+ if !status.exists {
+ return Err(EmailErr::CrmAddressNotFound(status.address.clone()));
+ }
+ if status.contact_hidden || status.company_hidden || !status.email_sync {
+ return Err(EmailErr::CrmAddressNotPermitted(status.address.clone()));
+ }
}
- }
- filter.as_ref().map(|e| walk(e)).unwrap_or(false)
-}
-/// Walks an email-filter AST and returns true if any Sender/Cc/Bcc/Recipient
-/// literal carries an `Email::Partial(_)`. Partial is a substring fragment
-/// (the trigram-indexed ILIKE path) and must not appear under team_scope —
-/// the typed POST endpoint already rejects this combination at AST
-/// expansion (`ExpandErr::TeamScopeRequiresQualifiedEmail`), but the raw
-/// AST endpoint bypasses that path, so this is the defensive check at the
-/// email-service boundary.
-fn filter_contains_partial_address(filter: &LiteralTree<EmailLiteral>) -> bool {
- fn walk(expr: &Expr<EmailLiteral>) -> bool {
- match expr {
- Expr::And(a, b) | Expr::Or(a, b) => walk(a) || walk(b),
- Expr::Not(a) => walk(a),
- Expr::Literal(
- EmailLiteral::Sender(Email::Partial(_))
- | EmailLiteral::Cc(Email::Partial(_))
- | EmailLiteral::Bcc(Email::Partial(_))
- | EmailLiteral::Recipient(Email::Partial(_)),
- ) => true,
- Expr::Literal(_) => false,
- }
+ Ok(Some(team_id))
}
- filter.as_ref().map(|e| walk(e)).unwrap_or(false)
}
diff --git a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
index a6925ba6d9..831d5a0903 100644
--- a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
@@ -106,6 +106,7 @@ async fn cursor_handler<T: EmailService>(
)
.map_filter(|_| None),
team_receipt: None,
+ crm_scope: None,
})
.await?
.type_erase(),
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
index 31d5781c5e..deb8122a94 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
@@ -316,7 +316,6 @@ pub(super) fn build_message_email_filter(
SqlFragment::raw("TRUE")
}
filter_ast::ExprFrame::Literal(EmailLiteral::Shared(_)) => SqlFragment::raw("TRUE"),
- filter_ast::ExprFrame::Literal(EmailLiteral::TeamScope) => SqlFragment::raw("TRUE"),
filter_ast::ExprFrame::Literal(EmailLiteral::CalendarOnly(_)) => SqlFragment::raw("TRUE"),
filter_ast::ExprFrame::Literal(EmailLiteral::CreatedAt(_)) => SqlFragment::raw("TRUE"),
filter_ast::ExprFrame::Literal(EmailLiteral::UpdatedAt(_)) => SqlFragment::raw("TRUE"),
@@ -703,8 +702,7 @@ pub(super) fn build_thread_email_filter(
| EmailLiteral::Importance(_)
| EmailLiteral::NotificationDone(_)
| EmailLiteral::NotificationSeen(_)
- | EmailLiteral::Shared(_)
- | EmailLiteral::TeamScope,
+ | EmailLiteral::Shared(_),
) => SqlFragment::raw("TRUE"),
});
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
index d7daf0ad68..04ad2d9ee1 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
@@ -24,7 +24,7 @@ struct QueryParams {
resolved: ResolvedFilters,
/// When `Some(team_id)`, the "Owned" candidate source expands from
/// `t.link_id = $link_id` to `t.link_id IN (links of every member of
- /// $team_id)`. Set only after team_scope has been validated upstream.
+ /// $team_id)`. Set only after CRM scope has been validated upstream.
team_id: Option<Uuid>,
}
@@ -120,7 +120,7 @@ fn push_thread_candidate_select(
builder.push("t.link_id = ");
builder.push_bind(params.link_id);
}
- // Team-scoped query: expand to every email_link owned by any
+ // CRM-scoped query: expand to every email_link owned by any
// member of the team. The receipt has already been validated
// upstream, so the team_id is trusted here.
Some(team_id) => {
@@ -140,6 +140,22 @@ fn push_thread_candidate_select(
}
}
+ // Belt-and-suspenders killswitch check that covers both the Owned and
+ // Shared branches. Without this, a CRM-scoped request with
+ // `SharedEmailFilter::Include`/`Only` could still return rows after
+ // `team_crm_settings.crm_enabled` flips false between the pre-check
+ // and query execution. EXISTS short-circuits and Postgres planner
+ // treats it as a constant once evaluated per query.
+ if let Some(team_id) = params.team_id {
+ builder.push(
+ r#" AND EXISTS (
+ SELECT 1 FROM team_crm_settings tcs
+ WHERE tcs.team_id = "#,
+ );
+ builder.push_bind(team_id);
+ builder.push(" AND tcs.crm_enabled)");
+ }
+
let view_thread_filter = build_view_thread_filter(view);
if !view_thread_filter.is_empty() {
view_thread_filter.push_into(builder);
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/team_scope_dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs
similarity index 84%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/test/team_scope_dynamic_query.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs
index 3c403d5678..e0eb292a08 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/team_scope_dynamic_query.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/crm_scope_dynamic_query.rs
@@ -1,7 +1,8 @@
-//! DB-backed tests for team-scoped dynamic email queries.
+//! DB-backed tests for CRM-scoped dynamic email queries.
//!
-//! These exercise the changes that wire `team_id: Option<Uuid>` from the
-//! soup/email service down through `resolve_filters` and into the SQL
+//! These exercise the candidate-set widening that fires when `team_id`
+//! is `Some(_)` (the resolved CRM scope), plumbed from the soup/email
+//! service down through `resolve_filters` and into the SQL
//! candidate-thread selection:
//!
//! • `dynamic/query.rs::push_thread_candidate_select` — `Owned` source's
@@ -14,7 +15,7 @@
//! mailbox match when the same address resolves to multiple contact
//! UUIDs (one per link).
//!
-//! Fixture: `email/fixtures/email_dynamic_query_team_scope.sql`. Two team
+//! Fixture: `email/fixtures/email_dynamic_query_crm_scope.sql`. Two team
//! members (Alice, Bob) and one non-member (Carol). Each link has its own
//! `email_contacts` row for `[email protected]` and its own TRASH label
//! UUID — both of which the new ANY-based resolution must cover.
@@ -66,17 +67,17 @@ async fn run_and_collect_ids(
}
// =====================================================================
-// 1. Regression check: team_scope OFF still only returns the caller's link.
+// 1. Regression check: CRM scope OFF still only returns the caller's link.
// =====================================================================
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_off_returns_only_callers_link(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn crm_scope_off_returns_only_callers_link(pool: Pool<Postgres>) -> anyhow::Result<()> {
// Broad partial filter that matches both "[email protected]" and
// "[email protected]" (their email_address strings contain "com").
let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
@@ -101,7 +102,7 @@ async fn team_scope_off_returns_only_callers_link(pool: Pool<Postgres>) -> anyho
);
assert!(
!ids.contains(TB1_BOB_INBOX_ACME),
- "bob's thread must not appear without team_scope"
+ "bob's thread must not appear without CRM scope"
);
assert!(
!ids.contains(TC1_CAROL_INBOX_ACME),
@@ -113,17 +114,17 @@ async fn team_scope_off_returns_only_callers_link(pool: Pool<Postgres>) -> anyho
}
// =====================================================================
-// 2. team_scope expands `Owned` to every team-member link.
+// 2. CRM scope expands `Owned` to every team-member link.
// =====================================================================
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_returns_all_team_member_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn crm_scope_returns_all_team_member_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
// Broad partial match — should hit every acme/elsewhere thread on team
// links (alice + bob), TRASH excluded, carol excluded.
@@ -160,17 +161,17 @@ async fn team_scope_returns_all_team_member_threads(pool: Pool<Postgres>) -> any
}
// =====================================================================
-// 3. team_scope + `Sender(Domain(...))` filters across team links.
+// 3. CRM scope + `Sender(Domain(...))` filters across team links.
// =====================================================================
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_with_domain_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn crm_scope_with_domain_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Domain(
"acme.com".to_string(),
@@ -194,7 +195,7 @@ async fn team_scope_with_domain_filter(pool: Pool<Postgres>) -> anyhow::Result<(
}
// =====================================================================
-// 4. team_scope + `Sender(Complete(...))` resolves the address to ALL
+// 4. CRM scope + `Sender(Complete(...))` resolves the address to ALL
// matching contact_ids across team links, not just the caller's link.
//
// This is the headline fix from option 2 — the same address has a
@@ -206,10 +207,10 @@ async fn team_scope_with_domain_filter(pool: Pool<Postgres>) -> anyhow::Result<(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_with_complete_sender_resolves_across_links(
+async fn crm_scope_with_complete_sender_resolves_across_links(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
@@ -245,7 +246,7 @@ async fn team_scope_with_complete_sender_resolves_across_links(
}
// =====================================================================
-// 5. team_scope's TRASH exclusion covers every team link's TRASH label.
+// 5. CRM scope's TRASH exclusion covers every team link's TRASH label.
// Each link has a different TRASH label UUID; the multi-id ANY probe
// must exclude trashed threads in every link, not just the caller's.
// =====================================================================
@@ -254,10 +255,10 @@ async fn team_scope_with_complete_sender_resolves_across_links(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_excludes_trash_in_every_team_link(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn crm_scope_excludes_trash_in_every_team_link(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
// Match all acme threads across team links.
let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Domain(
@@ -286,7 +287,7 @@ async fn team_scope_excludes_trash_in_every_team_link(pool: Pool<Postgres>) -> a
}
// =====================================================================
-// 6. team_scope short-circuits when the Complete address has no matching
+// 6. CRM scope short-circuits when the Complete address has no matching
// contact in any team link (no rows in `contact_ids` map).
// =====================================================================
@@ -294,10 +295,10 @@ async fn team_scope_excludes_trash_in_every_team_link(pool: Pool<Postgres>) -> a
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_with_unknown_complete_sender_short_circuits(
+async fn crm_scope_with_unknown_complete_sender_short_circuits(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
@@ -332,12 +333,10 @@ async fn team_scope_with_unknown_complete_sender_short_circuits(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_uses_team_mailboxes_not_caller_link(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
+async fn crm_scope_uses_team_mailboxes_not_caller_link(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
let carol_link = Uuid::parse_str("a0000003-0000-0000-0000-000000000003")?;
let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
@@ -376,7 +375,7 @@ async fn team_scope_uses_team_mailboxes_not_caller_link(
}
// =====================================================================
-// 8. Recipient (TO) under team_scope resolves across team links. The same
+// 8. Recipient (TO) under CRM scope resolves across team links. The same
// address has one `email_contacts` row per link (different UUIDs); the
// `mr.contact_id = ANY($ids)` predicate must match the recipient row
// that points at the per-link contact row.
@@ -386,10 +385,10 @@ async fn team_scope_uses_team_mailboxes_not_caller_link(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_with_complete_recipient_resolves_across_links(
+async fn crm_scope_with_complete_recipient_resolves_across_links(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
@@ -421,10 +420,10 @@ async fn team_scope_with_complete_recipient_resolves_across_links(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_with_complete_cc_resolves_across_links(
+async fn crm_scope_with_complete_cc_resolves_across_links(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
@@ -449,10 +448,10 @@ async fn team_scope_with_complete_cc_resolves_across_links(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_with_complete_bcc_resolves_across_links(
+async fn crm_scope_with_complete_bcc_resolves_across_links(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
@@ -470,7 +469,7 @@ async fn team_scope_with_complete_bcc_resolves_across_links(
}
// =====================================================================
-// 11. NOT operator under team_scope with an unresolved Complete sender.
+// 11. NOT operator under CRM scope with an unresolved Complete sender.
// `fold_unresolved` reduces the inner literal to `Some(false)`, then
// `Not(Some(false)) -> Some(true)` — which is *not* a `Some(false)`
// constant, so `can_short_circuit` returns false and the query runs.
@@ -481,10 +480,10 @@ async fn team_scope_with_complete_bcc_resolves_across_links(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_not_unresolved_sender_does_not_short_circuit(
+async fn crm_scope_not_unresolved_sender_does_not_short_circuit(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
@@ -525,10 +524,10 @@ async fn team_scope_not_unresolved_sender_does_not_short_circuit(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_with_asymmetric_complete_sender(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn crm_scope_with_asymmetric_complete_sender(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(complete(
@@ -551,17 +550,17 @@ async fn team_scope_with_asymmetric_complete_sender(pool: Pool<Postgres>) -> any
// 13. OR of one known and one unknown Complete sender. The unknown branch
// folds to FALSE via `fold_unresolved`; the OR collapses to just the
// known branch's results. Verifies short-circuit + multi-id ANY
-// resolution compose correctly under team_scope.
+// resolution compose correctly under CRM scope.
// =====================================================================
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_or_of_known_and_unknown_complete_senders(
+async fn crm_scope_or_of_known_and_unknown_complete_senders(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
@@ -589,17 +588,17 @@ async fn team_scope_or_of_known_and_unknown_complete_senders(
// 14. Composed AND of two address kinds (Domain sender + Domain
// recipient). Threads must satisfy BOTH constraints. Exercises the
// intersection of the candidate-thread CTE pushdown across address
-// kinds under team_scope.
+// kinds under CRM scope.
// =====================================================================
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_composed_and_sender_domain_and_recipient_domain(
+async fn crm_scope_composed_and_sender_domain_and_recipient_domain(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
@@ -626,7 +625,7 @@ async fn team_scope_composed_and_sender_domain_and_recipient_domain(
}
// =====================================================================
-// 15. Cursor-based pagination under team_scope: result set spans multiple
+// 15. Cursor-based pagination under CRM scope: result set spans multiple
// team links. Page 1 + Page 2 must cover all 4 team-member inbox
// threads with no overlap and no missing rows.
// =====================================================================
@@ -635,10 +634,10 @@ async fn team_scope_composed_and_sender_domain_and_recipient_domain(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../../fixtures",
- scripts("email_dynamic_query_team_scope")
+ scripts("email_dynamic_query_crm_scope")
)
)]
-async fn team_scope_pagination_across_team_links(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn crm_scope_pagination_across_team_links(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
let link_id = Uuid::parse_str(ALICE_LINK_ID)?;
let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
@@ -719,3 +718,39 @@ async fn team_scope_pagination_across_team_links(pool: Pool<Postgres>) -> anyhow
Ok(())
}
+
+// 16. Killswitch race: if team_crm_settings.crm_enabled flips to FALSE
+// between the pre-check and the dynamic query, the candidate-source
+// JOIN drops every team link out of the candidate set. This is the
+// belt-and-suspenders gate; the typical entry point (validate_crm_scope)
+// would already reject the request with CrmDisabledForTeam, but this
+// test exercises the JOIN-level guard directly by calling the dynamic
+// query with team_id = Some after flipping the flag.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query_crm_scope")
+ )
+)]
+async fn crm_scope_collapses_to_empty_when_killswitch_off(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;
+ // Flip the killswitch off after the fixture (which sets it ON).
+ sqlx::query("UPDATE team_crm_settings SET crm_enabled = FALSE WHERE team_id = $1")
+ .bind(team_id)
+ .execute(&pool)
+ .await?;
+
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Domain(
+ "acme.com".to_string(),
+ ))));
+ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;
+ assert!(
+ ids.is_empty(),
+ "candidate set must be empty when crm_enabled = FALSE, got: {:?}",
+ ids
+ );
+ Ok(())
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
index 661bed560c..57f4de7609 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
@@ -1,10 +1,10 @@
+mod crm_scope_dynamic_query;
mod draft;
mod dynamic_query;
mod labels;
mod link;
mod message;
mod preview;
-mod team_scope_dynamic_query;
mod thread;
mod thread_labels;
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
index bd7c07b207..8a908e0a60 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
@@ -956,7 +956,7 @@ async fn test_dynamic_filter_document_date_created_at_gt(pool: PgPool) {
)))),
project_filter: None,
chat_filter: None,
- email_filter: None,
+ email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
properties_filter: None,
@@ -1047,7 +1047,7 @@ async fn test_dynamic_filter_document_date_created_at_lt(pool: PgPool) {
)))),
project_filter: None,
chat_filter: None,
- email_filter: None,
+ email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
properties_filter: None,
@@ -1134,7 +1134,7 @@ async fn test_dynamic_filter_document_date_updated_at_gt(pool: PgPool) {
)))),
project_filter: None,
chat_filter: None,
- email_filter: None,
+ email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
properties_filter: None,
@@ -1226,7 +1226,7 @@ async fn test_dynamic_filter_document_date_updated_at_lt(pool: PgPool) {
)))),
project_filter: None,
chat_filter: None,
- email_filter: None,
+ email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
properties_filter: None,
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 7fb1037849..ad4679a99d 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -79,18 +79,94 @@ pub enum ExpandErr {
/// invalid API AST expansion
#[error("invalid API AST expansion: {0}")]
ApiAst(String),
- /// team_scope requires fully-qualified email addresses or domains
- #[error(
- "team_scope=true requires all sender/recipient/cc/bcc values to be a complete email address or domain; partial matches are not allowed"
- )]
- TeamScopeRequiresQualifiedEmail,
+ /// crm_domains and crm_addresses cannot both be populated in the same request
+ #[error("crm_domains and crm_addresses cannot both be populated in the same request")]
+ CrmDomainsAndAddressesMutuallyExclusive,
+ /// a value in crm_domains does not look like a bare domain
+ #[error("invalid crm_domains value (must be a bare domain like 'acme.com'): {0}")]
+ InvalidCrmDomain(String),
+ /// a value in crm_addresses does not parse as a fully-qualified email address
+ #[error("invalid crm_addresses value (must be a fully-qualified email): {0}")]
+ InvalidCrmAddress(String),
+}
+
+/// CRM-scoped query authorization tag produced by [`EmailFilters`] expansion.
+///
+/// Carried alongside the email AST through [`EntityFilterAst`] and into the
+/// email service, where it drives:
+/// 1. authorization (each domain/address must pass a CRM pre-check), and
+/// 2. candidate-set widening (the dynamic query expands from the caller's
+/// single `link_id` to every team member's `link_id`).
+///
+/// Mutually exclusive: at most one variant carries values, and the inner
+/// `Vec<String>` is guaranteed non-empty. The custom [`Deserialize`] impl
+/// below rejects forged payloads with empty vectors, since an empty
+/// scope tag would desynchronize downstream auth/widening behavior from
+/// AST intent.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub enum CrmScope {
+ /// caller is asking for team-visible threads involving any of these domains
+ Domains(Vec<String>),
+ /// caller is asking for team-visible threads involving any of these addresses
+ Addresses(Vec<String>),
+}
+
+impl<'de> Deserialize<'de> for CrmScope {
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ // Mirror the auto-derived shape, then validate non-empty.
+ #[derive(Deserialize)]
+ enum Raw {
+ Domains(Vec<String>),
+ Addresses(Vec<String>),
+ }
+ let raw = Raw::deserialize(d)?;
+ match raw {
+ Raw::Domains(v) if v.is_empty() => Err(serde::de::Error::custom(
+ "CrmScope::Domains requires at least one domain",
+ )),
+ Raw::Addresses(v) if v.is_empty() => Err(serde::de::Error::custom(
+ "CrmScope::Addresses requires at least one address",
+ )),
+ Raw::Domains(v) => Ok(CrmScope::Domains(v)),
+ Raw::Addresses(v) => Ok(CrmScope::Addresses(v)),
+ }
+ }
}
/// type alias for a maybe empty, cheaply cloneable ast literal tree
pub type LiteralTree<T> = Option<Arc<Expr<T>>>;
+/// Email-entity filter bundle: the literal AST tree plus any CRM scope
+/// tag that came from typed-filter expansion.
+///
+/// Bundled (rather than two parallel fields on [`EntityFilterAst`])
+/// because the tag is logically a property of the email filter — it
+/// directs which mailboxes to search and which authorization checks to
+/// apply, both governed by the same email-entity machinery downstream.
+#[derive(Debug, Default, Serialize, Deserialize, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct EmailFilterAst {
+ /// The literal AST tree.
+ #[serde(default, rename = "t", skip_serializing_if = "Option::is_none")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
+ pub tree: LiteralTree<EmailLiteral>,
+ /// CRM-scope tag set by [`crate::EmailFilters`] expansion when the
+ /// request carries `crm_domains` or `crm_addresses`. Drives
+ /// authorization and candidate-set widening in the email service.
+ #[serde(default, rename = "cs", skip_serializing_if = "Option::is_none")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
+ pub crm_scope: Option<CrmScope>,
+}
+
+impl IsEmpty for EmailFilterAst {
+ fn is_empty(&self) -> bool {
+ self.tree.is_none() && self.crm_scope.is_none()
+ }
+}
+
/// Describes a bundle of filters that should be applied across different entity types
-#[derive(Debug, Serialize, Deserialize, Clone)]
+#[derive(Debug, Default, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct EntityFilterAst {
/// the filters that should be applied to the document entity
@@ -105,10 +181,10 @@ pub struct EntityFilterAst {
#[serde(default, rename = "cf")]
#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub chat_filter: LiteralTree<ChatLiteral>,
- /// the filters that should be applied to the email entity
+ /// the filters that should be applied to the email entity — bundles
+ /// the literal AST tree and any CRM scope tag (see [`EmailFilterAst`])
#[serde(default, rename = "ef")]
- #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
- pub email_filter: LiteralTree<EmailLiteral>,
+ pub email_filter: EmailFilterAst,
/// the filters that should be applied to the channel entity
#[serde(default, rename = "chanf")]
#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
@@ -129,13 +205,26 @@ impl EntityFilterAst {
if entity_filter.is_empty() {
return Ok(None);
}
+ // The crm_* lists are processed twice: once here to extract the
+ // tag, and once inside EmailFilters::expand_ast for the AST tree.
+ // Both call the same `expand_crm_scope` helper, so validation is
+ // deterministic and identical.
+ let crm_scope = email::expand_crm_scope(
+ entity_filter.email_filters.crm_domains.clone(),
+ entity_filter.email_filters.crm_addresses.clone(),
+ )?
+ .map(|(_, scope)| scope);
+ let email_tree = EmailFilters::expand_ast(entity_filter.email_filters)?.map(Arc::new);
Ok(Some(EntityFilterAst {
document_filter: DocumentFilters::expand_ast(entity_filter.document_filters)?
.map(Arc::new),
project_filter: ProjectFilters::expand_ast(entity_filter.project_filters)?
.map(Arc::new),
chat_filter: ChatFilters::expand_ast(entity_filter.chat_filters)?.map(Arc::new),
- email_filter: EmailFilters::expand_ast(entity_filter.email_filters)?.map(Arc::new),
+ email_filter: EmailFilterAst {
+ tree: email_tree,
+ crm_scope,
+ },
channel_filter: ChannelFilters::expand_ast(entity_filter.channel_filters)?
.map(Arc::new),
call_filter: CallFilters::expand_ast(entity_filter.call_filters)?.map(Arc::new),
@@ -151,7 +240,7 @@ impl EntityFilterAst {
document_filter: None,
project_filter: None,
chat_filter: None,
- email_filter: None,
+ email_filter: EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
properties_filter: None,
@@ -173,7 +262,7 @@ impl IsEmpty for EntityFilterAst {
document_filter.is_none()
&& project_filter.is_none()
&& chat_filter.is_none()
- && email_filter.is_none()
+ && email_filter.is_empty()
&& channel_filter.is_none()
&& call_filter.is_none()
&& properties_filter.is_none()
diff --git a/rust/cloud-storage/item_filters/src/ast/email.rs b/rust/cloud-storage/item_filters/src/ast/email.rs
index 852f4ac7ba..3a29c9e56c 100644
--- a/rust/cloud-storage/item_filters/src/ast/email.rs
+++ b/rust/cloud-storage/item_filters/src/ast/email.rs
@@ -54,10 +54,6 @@ pub enum EmailLiteral {
NotificationSeen(bool),
/// Controls whether shared email threads are included in results.
Shared(SharedEmailFilter),
- /// Expand visibility to every teammate's mailbox. Results may include
- /// emails the requesting user is not a participant on, as long as at
- /// least one teammate is.
- TeamScope,
/// When true, only include threads that have at least one message with an
/// `.ics` calendar attachment (filename or `application/ics` mime type).
/// When false, no constraint is applied.
@@ -85,10 +81,18 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {
include_labels: _,
exclude_labels: _,
shared,
- team_scope,
+ crm_domains,
+ crm_addresses,
calendar_only,
} = input;
+ // Expand crm_domains / crm_addresses via the shared helper so the
+ // raw AST endpoint and the typed POST stay byte-identical. We
+ // discard the scope tag here — the tag is stamped onto
+ // [`crate::ast::EmailFilterAst`] by the caller
+ // ([`crate::ast::EntityFilterAst::new_from_filters`]).
+ let crm_node = expand_crm_scope(crm_domains, crm_addresses)?.map(|(tree, _)| tree);
+
fn map_email(s: String) -> Email {
if let Ok(e) = EmailStr::parse_from_str(&s) {
return Email::Complete(e.into_owned());
@@ -104,17 +108,6 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {
let mapped_bcc: Vec<Email> = bcc.into_iter().map(map_email).collect();
let mapped_recipients: Vec<Email> = recipients.into_iter().map(map_email).collect();
- if team_scope
- && mapped_senders
- .iter()
- .chain(&mapped_cc)
- .chain(&mapped_bcc)
- .chain(&mapped_recipients)
- .any(|e| matches!(e, Email::Partial(_)))
- {
- return Err(ExpandErr::TeamScopeRequiresQualifiedEmail);
- }
-
let sender_nodes = mapped_senders
.into_iter()
.expand(EmailLiteral::Sender, Expr::or);
@@ -145,7 +138,6 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {
} else {
Some(Expr::Literal(EmailLiteral::Shared(shared)))
};
- let team_scope_node = team_scope.then_some(Expr::Literal(EmailLiteral::TeamScope));
let calendar_only_node = calendar_only
.filter(|v| *v)
.map(|v| Expr::Literal(EmailLiteral::CalendarOnly(v)));
@@ -161,10 +153,89 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {
notification_done_node,
notification_seen_node,
shared_node,
- team_scope_node,
+ crm_node,
calendar_only_node,
]
.into_iter()
.fold_with(Expr::and))
}
}
+
+/// Builds an OR-tree over all four address directions for a single [`Email`].
+/// Used by `crm_domains` / `crm_addresses` expansion so a single CRM literal
+/// matches a thread regardless of which header field the participant appears in.
+fn any_direction(e: Email) -> Expr<EmailLiteral> {
+ Expr::or(
+ Expr::or(
+ Expr::Literal(EmailLiteral::Sender(e.clone())),
+ Expr::Literal(EmailLiteral::Cc(e.clone())),
+ ),
+ Expr::or(
+ Expr::Literal(EmailLiteral::Bcc(e.clone())),
+ Expr::Literal(EmailLiteral::Recipient(e)),
+ ),
+ )
+}
+
+/// Expand the typed `crm_domains` / `crm_addresses` lists into:
+/// 1. an AST subtree of any-direction OR literals to AND into the
+/// email filter, and
+/// 2. the [`crate::ast::CrmScope`] tag that downstream consumers
+/// ([`crate::ast::EmailFilterAst::crm_scope`]) use for
+/// authorization + candidate-set widening.
+///
+/// Returns `Ok(None)` when both lists are empty. Returns
+/// [`ExpandErr::CrmDomainsAndAddressesMutuallyExclusive`] when both are
+/// non-empty. Each value is validated:
+/// * domains — must pass [`looks_like_domain`].
+/// * addresses — must parse as a fully-qualified [`EmailStr`].
+///
+/// Used by both [`EmailFilters::expand_ast`] (typed POST path, scope
+/// discarded — see [`crate::ast::EntityFilterAst::new_from_filters`])
+/// and the raw AST endpoint's `into_entity_ast` (typed fields alongside
+/// the freeform AST).
+pub fn expand_crm_scope(
+ crm_domains: Vec<String>,
+ crm_addresses: Vec<String>,
+) -> Result<Option<(Expr<EmailLiteral>, crate::ast::CrmScope)>, ExpandErr> {
+ if !crm_domains.is_empty() && !crm_addresses.is_empty() {
+ return Err(ExpandErr::CrmDomainsAndAddressesMutuallyExclusive);
+ }
+
+ if !crm_domains.is_empty() {
+ let lowercased: Vec<String> = crm_domains.into_iter().map(|s| s.to_lowercase()).collect();
+ let tree = lowercased
+ .iter()
+ .map(|d| -> Result<Expr<EmailLiteral>, ExpandErr> {
+ if !looks_like_domain(d) {
+ return Err(ExpandErr::InvalidCrmDomain(d.clone()));
+ }
+ Ok(any_direction(Email::Domain(d.clone())))
+ })
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .reduce(Expr::or)
+ .expect("non-empty list yields some node");
+ Ok(Some((tree, crate::ast::CrmScope::Domains(lowercased))))
+ } else if !crm_addresses.is_empty() {
+ let lowercased: Vec<String> = crm_addresses
+ .into_iter()
+ .map(|s| s.to_lowercase())
+ .collect();
+ let tree = lowercased
+ .iter()
+ .map(|s| -> Result<Expr<EmailLiteral>, ExpandErr> {
+ let parsed = EmailStr::parse_from_str(s)
+ .map_err(|_| ExpandErr::InvalidCrmAddress(s.clone()))?
+ .into_owned();
+ Ok(any_direction(Email::Complete(parsed)))
+ })
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .reduce(Expr::or)
+ .expect("non-empty list yields some node");
+ Ok(Some((tree, crate::ast::CrmScope::Addresses(lowercased))))
+ } else {
+ Ok(None)
+ }
+}
diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rs
index 3f6c302b66..bcdbf34cfd 100644
--- a/rust/cloud-storage/item_filters/src/ast/tests.rs
+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs
@@ -214,6 +214,7 @@ fn it_expands_email_thread_ids() {
.unwrap()
.unwrap()
.email_filter
+ .tree
.unwrap(),
)
.unwrap();
@@ -245,6 +246,7 @@ fn it_expands_email_thread_ids_with_sender() {
.unwrap()
.unwrap()
.email_filter
+ .tree
.unwrap(),
)
.unwrap();
@@ -863,3 +865,253 @@ fn it_expands_call_filter_without_attended_is_none_when_empty() {
let ast = CallFilters::expand_ast(f).unwrap();
assert!(ast.is_none(), "empty filter should expand to None");
}
+
+#[test]
+fn crm_domains_expand_to_any_direction_or() {
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_domains: vec!["acme.com".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let ast = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let scope = ast.email_filter.crm_scope.expect("crm scope should be set");
+ assert_matches!(scope, CrmScope::Domains(ref ds) if ds == &vec!["acme.com".to_string()]);
+
+ let tree = Arc::into_inner(ast.email_filter.tree.expect("email filter tree set")).unwrap();
+ let json = serde_json::to_value(tree).unwrap();
+ // OR of Sender/Cc/Bcc/Recipient Domain literals — exact tree shape isn't
+ // load-bearing; we just want to confirm any-direction expansion happened.
+ let s = json.to_string();
+ assert!(s.contains("Sender"));
+ assert!(s.contains("Cc"));
+ assert!(s.contains("Bcc"));
+ assert!(s.contains("Recipient"));
+ assert!(s.contains("acme.com"));
+}
+
+#[test]
+fn crm_addresses_expand_to_any_direction_or() {
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_addresses: vec!["[email protected]".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let ast = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let scope = ast.email_filter.crm_scope.expect("crm scope should be set");
+ assert_matches!(scope, CrmScope::Addresses(ref a) if a == &vec!["[email protected]".to_string()]);
+
+ let tree = Arc::into_inner(ast.email_filter.tree.expect("email filter tree set")).unwrap();
+ let json = serde_json::to_value(tree).unwrap();
+ let s = json.to_string();
+ assert!(s.contains("Sender"));
+ assert!(s.contains("Recipient"));
+ assert!(s.contains("[email protected]"));
+}
+
+#[test]
+fn crm_domains_and_addresses_together_is_rejected() {
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_domains: vec!["acme.com".to_string()],
+ crm_addresses: vec!["[email protected]".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let err = EntityFilterAst::new_from_filters(f).unwrap_err();
+ assert_matches!(err, ExpandErr::CrmDomainsAndAddressesMutuallyExclusive);
+}
+
+#[test]
+fn crm_domains_rejects_non_domain_string() {
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_domains: vec!["not a domain".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let err = EntityFilterAst::new_from_filters(f).unwrap_err();
+ assert_matches!(err, ExpandErr::InvalidCrmDomain(_));
+}
+
+#[test]
+fn crm_addresses_rejects_unparseable_email() {
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_addresses: vec!["not an email".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let err = EntityFilterAst::new_from_filters(f).unwrap_err();
+ assert_matches!(err, ExpandErr::InvalidCrmAddress(_));
+}
+
+#[test]
+fn empty_crm_lists_produce_no_scope_tag() {
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ senders: vec!["[email protected]".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ast = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ assert!(ast.email_filter.crm_scope.is_none());
+}
+
+#[test]
+fn crm_domains_are_lowercased_in_scope_tag() {
+ // Mixed-case input must land in the scope as lowercase, otherwise the
+ // CRM pre-check (which uses LOWER(domain) on the SQL side) could miss
+ // matches and reject valid requests.
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_domains: vec!["ACME.com".to_string(), "Widgets.IO".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ast = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let scope = ast.email_filter.crm_scope.expect("scope");
+ match scope {
+ CrmScope::Domains(d) => {
+ assert_eq!(d, vec!["acme.com".to_string(), "widgets.io".to_string()])
+ }
+ CrmScope::Addresses(_) => panic!("expected Domains variant"),
+ }
+}
+
+#[test]
+fn crm_addresses_are_lowercased_in_scope_tag() {
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_addresses: vec!["[email protected]".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ast = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let scope = ast.email_filter.crm_scope.expect("scope");
+ match scope {
+ CrmScope::Addresses(a) => assert_eq!(a, vec!["[email protected]".to_string()]),
+ CrmScope::Domains(_) => panic!("expected Addresses variant"),
+ }
+}
+
+#[test]
+fn multiple_crm_domains_or_together_in_tree() {
+ // Each domain expands to an any-direction OR of 4 literals. Multiple
+ // domains OR with each other at the top of the CRM sub-tree, so the
+ // final shape is OR-of-(OR-of-4) for each domain. We don't pin the
+ // exact tree shape — just confirm both domains appear in all 4
+ // direction literals.
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_domains: vec!["acme.com".to_string(), "widgets.io".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ast = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let tree = ast.email_filter.tree.as_ref().expect("tree set").as_ref();
+ let mut literals: Vec<String> = Vec::new();
+ collect_literals(tree, &mut literals);
+ // We expect 4 directions × 2 domains = 8 literal occurrences.
+ let acme_count = literals.iter().filter(|s| s.contains("acme.com")).count();
+ let widgets_count = literals.iter().filter(|s| s.contains("widgets.io")).count();
+ assert_eq!(
+ acme_count, 4,
+ "acme.com should appear in all 4 direction literals"
+ );
+ assert_eq!(
+ widgets_count, 4,
+ "widgets.io should appear in all 4 direction literals"
+ );
+ // And each direction must appear for both:
+ for direction in ["Sender", "Cc", "Bcc", "Recipient"] {
+ let count = literals.iter().filter(|s| s.contains(direction)).count();
+ assert_eq!(
+ count, 2,
+ "{} should appear once per domain (acme + widgets) = 2",
+ direction
+ );
+ }
+}
+
+#[test]
+fn crm_scope_ands_with_per_direction_senders() {
+ // When a request carries BOTH crm_domains (CRM scope) AND a regular
+ // per-direction sender filter, both must appear in the final AST
+ // ANDed together. The CRM scope widens visibility; the per-direction
+ // filter narrows within that widened scope.
+ let f = EntityFilters {
+ email_filters: crate::EmailFilters {
+ crm_domains: vec!["acme.com".to_string()],
+ senders: vec!["[email protected]".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ast = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let tree = ast.email_filter.tree.as_ref().expect("tree set").as_ref();
+ let mut literals: Vec<String> = Vec::new();
+ collect_literals(tree, &mut literals);
+ // The per-direction sender must be in the tree.
+ assert!(
+ literals.iter().any(|s| s.contains("[email protected]")),
+ "explicit sender filter must survive into the tree"
+ );
+ // The CRM domain must also be in the tree, on all four directions.
+ let acme_count = literals.iter().filter(|s| s.contains("acme.com")).count();
+ assert_eq!(acme_count, 4, "CRM domain expanded in all 4 directions");
+}
+
+/// Walks the Expr tree and pushes each Literal's JSON string into `out`.
+fn collect_literals(expr: &filter_ast::Expr<EmailLiteral>, out: &mut Vec<String>) {
+ match expr {
+ filter_ast::Expr::And(a, b) | filter_ast::Expr::Or(a, b) => {
+ collect_literals(a, out);
+ collect_literals(b, out);
+ }
+ filter_ast::Expr::Not(a) => collect_literals(a, out),
+ filter_ast::Expr::Literal(lit) => {
+ out.push(serde_json::to_string(lit).unwrap());
+ }
+ }
+}
+
+#[test]
+fn crm_scope_rejects_empty_domains_on_deserialize() {
+ // Forged payload — an "empty CRM scope" would bypass downstream auth /
+ // widening intent. CrmScope's custom Deserialize impl must reject it.
+ let err = serde_json::from_str::<CrmScope>(r#"{"Domains":[]}"#).unwrap_err();
+ assert!(
+ err.to_string().contains("at least one domain"),
+ "unexpected error: {err}"
+ );
+}
+
+#[test]
+fn crm_scope_rejects_empty_addresses_on_deserialize() {
+ let err = serde_json::from_str::<CrmScope>(r#"{"Addresses":[]}"#).unwrap_err();
+ assert!(
+ err.to_string().contains("at least one address"),
+ "unexpected error: {err}"
+ );
+}
+
+#[test]
+fn crm_scope_accepts_non_empty_variants_on_deserialize() {
+ let domains: CrmScope = serde_json::from_str(r#"{"Domains":["acme.com"]}"#).unwrap();
+ assert!(matches!(domains, CrmScope::Domains(d) if d == vec!["acme.com".to_string()]));
+ let addresses: CrmScope = serde_json::from_str(r#"{"Addresses":["[email protected]"]}"#).unwrap();
+ assert!(matches!(addresses, CrmScope::Addresses(a) if a == vec!["[email protected]".to_string()]));
+}
diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rs
index 4ab5b8e258..ccaf8069b4 100644
--- a/rust/cloud-storage/item_filters/src/lib.rs
+++ b/rust/cloud-storage/item_filters/src/lib.rs
@@ -247,13 +247,23 @@ pub struct EmailFilters {
#[serde(default, skip_serializing_if = "SharedEmailFilter::is_default")]
pub shared: SharedEmailFilter,
- /// When true, expand visibility to every teammate's mailbox: results may
- /// include emails the requesting user is not a participant on, as long as
- /// at least one of their teammates is. Requires every sender/cc/bcc/recipient
- /// value to be a fully-qualified email address or a domain (no partial
- /// substring matches).
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub team_scope: bool,
+ /// CRM-scoped domain filter. When non-empty, expands visibility to every
+ /// teammate's mailbox and restricts to threads involving any of these
+ /// domains (in any of sender/cc/bcc/recipient). Each domain is authorized
+ /// against `crm_domains` + `crm_companies` (must exist for the caller's
+ /// team, company must not be hidden, `email_sync` must be true).
+ /// Mutually exclusive with `crm_addresses`.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub crm_domains: Vec<String>,
+
+ /// CRM-scoped address filter. When non-empty, expands visibility to every
+ /// teammate's mailbox and restricts to threads involving any of these
+ /// fully-qualified addresses. Each address is authorized against
+ /// `crm_contacts` + `crm_companies` (contact must not be hidden, company
+ /// must not be hidden, `email_sync` must be true).
+ /// Mutually exclusive with `crm_domains`.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub crm_addresses: Vec<String>,
/// When `Some(true)`, only include threads that have at least one message
/// with an iCalendar attachment (`.ics` filename or `application/ics` mime
@@ -276,7 +286,8 @@ impl IsEmpty for EmailFilters {
include_labels,
exclude_labels,
shared,
- team_scope,
+ crm_domains,
+ crm_addresses,
calendar_only,
} = self;
senders.is_empty()
@@ -290,7 +301,8 @@ impl IsEmpty for EmailFilters {
&& include_labels.is_empty()
&& exclude_labels.is_empty()
&& shared.is_default()
- && !team_scope
+ && crm_domains.is_empty()
+ && crm_addresses.is_empty()
&& !calendar_only.unwrap_or(false)
}
}
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 70078d5ca0..0507fd55ec 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -273,13 +273,23 @@ impl SoupRequest<Option<EntityFilterAst>> {
/// take the parts of the [SoupRequest] that are only relevant to email
/// and move them into a [GetEmailsRequest] if it is possible to create one.
///
- /// `team_receipt` is forwarded onto the email request so the query layer
- /// can verify and use it when the email AST contains
- /// `EmailLiteral::TeamScope`.
+ /// `team_receipt` is forwarded onto the email request so the query
+ /// layer can verify and use it when the email filter carries a CRM
+ /// scope tag (`EntityFilterAst::email_filter::crm_scope`).
pub(crate) fn build_email_request(
&self,
team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,
) -> Option<GetEmailsRequest> {
+ let entity_ast: Option<&EntityFilterAst> = match &self.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(_, f))) => f.as_ref(),
+ SoupQuery::Simple(SimpleQueryInner(Query::Cursor(CursorWithValAndFilter {
+ filter,
+ ..
+ }))) => filter.as_ref(),
+ SoupQuery::Frecency(_) => None,
+ };
+ let crm_scope = entity_ast.and_then(|a| a.email_filter.crm_scope.clone());
+
Some(GetEmailsRequest {
view: self.email_preview_view.clone(),
link_id: self.link_id?,
@@ -288,7 +298,7 @@ impl SoupRequest<Option<EntityFilterAst>> {
query: match &self.cursor {
SoupQuery::Simple(SimpleQueryInner(Query::Sort(t, f))) => Some(Query::Sort(
*t,
- f.as_ref().and_then(|f| f.email_filter.clone()),
+ f.as_ref().and_then(|f| f.email_filter.tree.clone()),
)),
SoupQuery::Simple(SimpleQueryInner(Query::Cursor(CursorWithValAndFilter {
id,
@@ -299,12 +309,13 @@ impl SoupRequest<Option<EntityFilterAst>> {
id: *id,
limit: *limit,
val: val.clone(),
- filter: filter.as_ref().and_then(|f| f.email_filter.clone()),
+ filter: filter.as_ref().and_then(|f| f.email_filter.tree.clone()),
})),
// we don't yet have sort by frecency implemented for emails yet
SoupQuery::Frecency(_) => None,
}?,
team_receipt,
+ crm_scope,
})
}
diff --git a/rust/cloud-storage/soup/src/domain/ports.rs b/rust/cloud-storage/soup/src/domain/ports.rs
index 161becea70..35bd27b19a 100644
--- a/rust/cloud-storage/soup/src/domain/ports.rs
+++ b/rust/cloud-storage/soup/src/domain/ports.rs
@@ -60,8 +60,8 @@ pub trait SoupService: Send + Sync + 'static {
///
/// `team_receipt` proves the user belongs to a team and may be used by
/// filters that broaden visibility beyond the user's own mailboxes (e.g.
- /// `EmailLiteral::TeamScope`). Pass `None` when no team-scoped filter is
- /// active.
+ /// `EmailFilters::crm_domains` / `crm_addresses`). Pass `None` when
+ /// no CRM-scoped filter is active.
fn get_user_soup<T>(
&self,
req: SoupRequest<T>,
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index 24a5d6080c..5a00c4c318 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -322,7 +322,7 @@ where
) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>
where
SoupRequest<R>: IntoSoupReqAst,
- R: Clone + Serialize + Send + RequestsTeamScope,
+ R: Clone + Serialize + Send + RequestsCrmScope,
{
let create_fallback = move || -> SoupQuery<R> {
let params_sort = params
@@ -346,13 +346,13 @@ where
.unwrap_or_else(create_fallback),
};
- // Derive team_scope authorization from the *effective* filter (the
+ // 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 team_scope on follow-up pages.
+ // miss CRM scope on follow-up pages.
let team_receipt =
- resolve_team_receipt(cursor.filter().requests_team_scope(), team_receipt_option)?;
+ resolve_crm_team_receipt(cursor.filter().requests_crm_scope(), team_receipt_option)?;
let res = self
.service
@@ -442,22 +442,23 @@ where
/// (`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 team_scope is in play.
-pub trait RequestsTeamScope {
+/// 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.
- fn requests_team_scope(&self) -> bool;
+ /// the requesting user's team via a CRM-scoped attribute
+ /// (`crm_domains` or `crm_addresses`).
+ fn requests_crm_scope(&self) -> bool;
}
-impl RequestsTeamScope for EntityFilters {
- fn requests_team_scope(&self) -> bool {
- self.email_filters.team_scope
+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 RequestsTeamScope for ApiEntityFilterAst {
- fn requests_team_scope(&self) -> bool {
- email_filter_contains_team_scope(&self.email_filter)
+impl RequestsCrmScope for ApiEntityFilterAst {
+ fn requests_crm_scope(&self) -> bool {
+ !self.email_crm_domains.is_empty() || !self.email_crm_addresses.is_empty()
}
}
@@ -508,8 +509,8 @@ pub enum SoupHandlerErr {
ExpandErr(ExpandErr),
#[error("Invalid compound filter could not be expanded")]
Expand,
- #[error("team_scope requires team membership")]
- TeamScopeForbidden,
+ #[error("CRM-scoped queries require team membership")]
+ CrmScopeForbidden,
}
impl From<SoupErr> for SoupHandlerErr {
@@ -525,7 +526,7 @@ impl IntoResponse for SoupHandlerErr {
fn into_response(self) -> axum::response::Response {
let status_code = match &self {
SoupHandlerErr::ExpandErr(_) | SoupHandlerErr::Expand => StatusCode::BAD_REQUEST,
- SoupHandlerErr::TeamScopeForbidden => StatusCode::FORBIDDEN,
+ SoupHandlerErr::CrmScopeForbidden => StatusCode::FORBIDDEN,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
@@ -649,7 +650,7 @@ where
Err(e) => Err(e)?,
};
// Pass the raw extractor receipt through — `handle` resolves the
- // team_scope check against the *effective* filter (which may come from
+ // CRM-scope check against the *effective* filter (which may come from
// the cursor on follow-up pages), not the request body.
service
.handle(
@@ -670,7 +671,6 @@ where
#[serde(rename_all = "camelCase")]
pub struct PostSoupAstRequest {
#[serde(default, flatten)]
- #[schema(value_type = EntityFilterAst)]
filters: ApiEntityFilterAst,
#[serde(default, flatten)]
params: Params,
@@ -718,7 +718,7 @@ where
Err(e) => Err(e)?,
};
// Pass the raw extractor receipt through — `handle` resolves the
- // team_scope check against the *effective* filter (which may come from
+ // CRM-scope check against the *effective* filter (which may come from
// the cursor on follow-up pages), not the request body.
service
.handle(
@@ -741,7 +741,6 @@ where
pub struct PostGroupedSoupAstRequest {
/// Filters to apply (AST format)
#[serde(default, flatten)]
- #[schema(value_type = EntityFilterAst)]
filters: ApiEntityFilterAst,
/// Grouping parameters (required)
#[serde(flatten)]
@@ -803,58 +802,66 @@ where
.await
}
-/// Returns the team receipt to use when team-scoped visibility is required.
-/// `team_scope_requested` is true when the request body asks for team_scope
-/// (via the typed flag on POST or the `EmailLiteral::TeamScope` literal on
-/// the AST endpoint). Returns `Err(TeamScopeForbidden)` when team_scope was
-/// requested but the user has no qualifying team membership.
-fn resolve_team_receipt(
- team_scope_requested: bool,
+/// 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 team_scope_requested && receipt.is_none() {
- return Err(SoupHandlerErr::TeamScopeForbidden);
+ if crm_scope_requested && receipt.is_none() {
+ return Err(SoupHandlerErr::CrmScopeForbidden);
}
Ok(receipt)
}
-/// Walks an AST email filter tree and returns true if any node is the
-/// `TeamScope` literal.
-fn email_filter_contains_team_scope(filter: &LiteralTree<EmailLiteral>) -> bool {
- fn walk(expr: &Expr<EmailLiteral>) -> bool {
- match expr {
- Expr::And(a, b) | Expr::Or(a, b) => walk(a) || walk(b),
- Expr::Not(a) => walk(a),
- Expr::Literal(EmailLiteral::TeamScope) => true,
- Expr::Literal(_) => false,
- }
- }
- filter.as_ref().map(|e| walk(e)).unwrap_or(false)
-}
-
-#[derive(Debug, Default, Serialize, Deserialize, Clone)]
+#[derive(Debug, Default, Serialize, Deserialize, Clone, ToSchema)]
pub struct ApiEntityFilterAst {
/// the filters that should be applied to the document entity
#[serde(default, rename = "df")]
+ #[schema(value_type = serde_json::Value)]
pub document_filter: LiteralTree<ApiDocumentLiteral>,
/// the filters that should be applied to the project entity
#[serde(default, rename = "pf")]
+ #[schema(value_type = serde_json::Value)]
pub project_filter: LiteralTree<ProjectLiteral>,
/// the filters that should be applied to the chat entity
#[serde(default, rename = "cf")]
+ #[schema(value_type = serde_json::Value)]
pub chat_filter: LiteralTree<ChatLiteral>,
- /// the filters that should be applied to the email entity
+ /// the filters that should be applied to the email entity (raw AST
+ /// tree only; CRM scope is carried by the `ecd` / `eca` sibling
+ /// fields). On this endpoint the email filter stays a bare tree,
+ /// unlike the materialized [`EntityFilterAst`] used for cursors.
#[serde(default, rename = "ef")]
+ #[schema(value_type = serde_json::Value)]
pub email_filter: LiteralTree<EmailLiteral>,
/// the filters that should be applied to the channel entity
#[serde(default, rename = "chanf")]
+ #[schema(value_type = serde_json::Value)]
pub channel_filter: LiteralTree<ChannelLiteral>,
/// the filters that should be applied to the call entity
#[serde(default, rename = "callf")]
+ #[schema(value_type = serde_json::Value)]
pub call_filter: LiteralTree<CallLiteral>,
/// the filters that should be applied based on entity properties
#[serde(default, rename = "propf")]
+ #[schema(value_type = serde_json::Value)]
pub properties_filter: LiteralTree<PropertiesLiteral>,
+ /// CRM-scoped domain filter (wire key: `ecd`). Parallel to the
+ /// freeform `ef` AST. Expanded by the router into an any-direction
+ /// OR sub-tree AND-merged into `ef`, plus a `CrmScope` tag stamped
+ /// on the resulting [`item_filters::ast::EmailFilterAst::crm_scope`].
+ /// Drives the per-team CRM authorization pre-check and candidate-set
+ /// widening downstream. Mutually exclusive with `eca`.
+ #[serde(default, rename = "ecd", skip_serializing_if = "Vec::is_empty")]
+ pub email_crm_domains: Vec<String>,
+ /// CRM-scoped address filter (wire key: `eca`). Symmetric counterpart
+ /// to `ecd` for fully-qualified email addresses.
+ #[serde(default, rename = "eca", skip_serializing_if = "Vec::is_empty")]
+ pub email_crm_addresses: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
@@ -921,6 +928,8 @@ impl ApiEntityFilterAst {
channel_filter,
call_filter,
properties_filter,
+ email_crm_domains,
+ email_crm_addresses,
} = self;
let document_filter = document_filter
@@ -947,11 +956,39 @@ impl ApiEntityFilterAst {
.transpose()?
.map(Arc::new);
+ // Build the CRM sub-tree and tag from the typed lists. Mutual
+ // exclusivity and per-value validation happen here. We then
+ // AND-merge the sub-tree into the freeform `email_filter` AST so
+ // the matching SQL works identically to the typed POST path.
+ let crm =
+ item_filters::ast::email::expand_crm_scope(email_crm_domains, email_crm_addresses)
+ .map_err(|e| report!("{e}"))?;
+
+ let (email_tree, crm_scope) = match (email_filter, crm) {
+ (Some(existing), Some((crm_tree, scope))) => {
+ // The Arc was freshly constructed by serde when this
+ // request body deserialized, and has not been cloned
+ // since — refcount is 1, so `try_unwrap` always succeeds.
+ let existing_owned = Arc::try_unwrap(existing)
+ .map_err(|_| report!("internal: email_filter Arc was unexpectedly shared"))?;
+ (
+ Some(Arc::new(Expr::and(existing_owned, crm_tree))),
+ Some(scope),
+ )
+ }
+ (Some(existing), None) => (Some(existing), None),
+ (None, Some((crm_tree, scope))) => (Some(Arc::new(crm_tree)), Some(scope)),
+ (None, None) => (None, None),
+ };
+
Ok(EntityFilterAst {
document_filter,
project_filter,
chat_filter,
- email_filter,
+ email_filter: item_filters::ast::EmailFilterAst {
+ tree: email_tree,
+ crm_scope,
+ },
channel_filter,
call_filter,
properties_filter,
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index 03ef9a3ed8..8a27dc761d 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -1431,3 +1431,201 @@ async fn it_can_expand_assoc_ast() {
.expect("SoupService::handle should have been called with next cursor");
assert!(matches!(req.cursor_kind, MockCursorKind::SimpleCursor));
}
+
+// ============================================================================
+// /soup/ast CRM scope extension
+// ============================================================================
+
+use item_filters::ast::CrmScope;
+
+#[test]
+fn ast_endpoint_email_crm_domains_stamps_scope_and_ands_into_tree() {
+ let js = json!({
+ "ecd": ["acme.com"],
+ });
+ let api: ApiEntityFilterAst = serde_json::from_value(js).unwrap();
+ let req = SoupRequest {
+ soup_type: SoupType::Expanded,
+ limit: 20,
+ cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
+ SimpleSortMethod::ViewedAt,
+ api,
+ ))),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ email_preview_view: PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox),
+ link_id: None,
+ };
+ let req: SoupRequest<Option<EntityFilterAst>> = req.into_ast().unwrap();
+ let ast = match &req.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(_, f))) => f.as_ref().unwrap(),
+ _ => panic!("expected simple sort"),
+ };
+ let scope = ast.email_filter.crm_scope.as_ref().expect("scope set");
+ assert!(matches!(scope, CrmScope::Domains(d) if d == &vec!["acme.com".to_string()]));
+ // Sub-tree of any-direction OR literals stamped on the email AST.
+ assert!(ast.email_filter.tree.is_some());
+}
+
+#[test]
+fn ast_endpoint_email_crm_addresses_stamps_scope() {
+ let js = json!({
+ "eca": ["[email protected]"],
+ });
+ let api: ApiEntityFilterAst = serde_json::from_value(js).unwrap();
+ let req = SoupRequest {
+ soup_type: SoupType::Expanded,
+ limit: 20,
+ cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
+ SimpleSortMethod::ViewedAt,
+ api,
+ ))),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ email_preview_view: PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox),
+ link_id: None,
+ };
+ let req: SoupRequest<Option<EntityFilterAst>> = req.into_ast().unwrap();
+ let ast = match &req.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(_, f))) => f.as_ref().unwrap(),
+ _ => panic!("expected simple sort"),
+ };
+ let scope = ast.email_filter.crm_scope.as_ref().expect("scope set");
+ assert!(matches!(scope, CrmScope::Addresses(a) if a == &vec!["[email protected]".to_string()]));
+ assert!(ast.email_filter.tree.is_some());
+}
+
+#[test]
+fn ast_endpoint_email_crm_both_lists_rejected() {
+ let js = json!({
+ "ecd": ["acme.com"],
+ "eca": ["[email protected]"],
+ });
+ let api: ApiEntityFilterAst = serde_json::from_value(js).unwrap();
+ let req = SoupRequest {
+ soup_type: SoupType::Expanded,
+ limit: 20,
+ cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
+ SimpleSortMethod::ViewedAt,
+ api,
+ ))),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ email_preview_view: PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox),
+ link_id: None,
+ };
+ let res = req.into_ast();
+ assert!(res.is_err(), "mutual exclusivity must reject both lists");
+}
+
+#[test]
+fn ast_endpoint_empty_crm_lists_leaves_scope_none() {
+ let js = json!({
+ "ef": null,
+ });
+ let api: ApiEntityFilterAst = serde_json::from_value(js).unwrap();
+ let req = SoupRequest {
+ soup_type: SoupType::Expanded,
+ limit: 20,
+ cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
+ SimpleSortMethod::ViewedAt,
+ api,
+ ))),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ email_preview_view: PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox),
+ link_id: None,
+ };
+ let req: SoupRequest<Option<EntityFilterAst>> = req.into_ast().unwrap();
+ // ast.is_none() because the whole filter is empty.
+ let ast = match &req.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(_, f))) => f.as_ref(),
+ _ => panic!("expected simple sort"),
+ };
+ assert!(ast.is_none(), "fully-empty filter should collapse to None");
+}
+
+#[test]
+fn ast_endpoint_crm_ands_with_existing_freeform_ef() {
+ // The AND-merge between the freeform `ef` AST and the CRM-expanded
+ // sub-tree is the most consequential bit of `into_entity_ast`. This
+ // test pins the root shape:
+ // Expr::And(
+ // <original ef literal>, // unchanged
+ // <any-direction OR over the CRM domain>
+ // )
+ let js = json!({
+ "ef": { "l": { "Sender": { "Complete": "[email protected]" } } },
+ "ecd": ["acme.com"],
+ });
+ let api: ApiEntityFilterAst = serde_json::from_value(js).unwrap();
+ let req = SoupRequest {
+ soup_type: SoupType::Expanded,
+ limit: 20,
+ cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
+ SimpleSortMethod::ViewedAt,
+ api,
+ ))),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ email_preview_view: PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox),
+ link_id: None,
+ };
+ let req: SoupRequest<Option<EntityFilterAst>> = req.into_ast().unwrap();
+ let ast = match &req.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(_, f))) => f.as_ref().unwrap(),
+ _ => panic!("expected simple sort"),
+ };
+
+ let tree = ast.email_filter.tree.as_ref().expect("tree set");
+ match tree.as_ref() {
+ filter_ast::Expr::And(left, right) => {
+ // Left = the original ef literal, untouched.
+ let left_json = serde_json::to_value(left.as_ref()).unwrap();
+ assert_eq!(
+ left_json,
+ serde_json::json!({ "l": { "Sender": { "Complete": "[email protected]" } } }),
+ "left side of AND must be the original ef literal verbatim"
+ );
+ // Right = the any-direction CRM sub-tree. All four direction
+ // literals must appear in the right subtree carrying acme.com.
+ let right_json = serde_json::to_string(right.as_ref()).unwrap();
+ for direction in ["Sender", "Cc", "Bcc", "Recipient"] {
+ assert!(
+ right_json.contains(direction),
+ "right side must contain {} direction literal",
+ direction
+ );
+ }
+ assert!(right_json.contains("acme.com"));
+ }
+ other => panic!(
+ "expected And at root after CRM AND-merge, got: {}",
+ serde_json::to_string(other).unwrap()
+ ),
+ }
+}
+
+#[test]
+fn ast_endpoint_crm_domains_are_lowercased_in_scope() {
+ // Mixed-case input must land in the scope as lowercase — the CRM
+ // pre-check uses LOWER(domain) on the SQL side and would otherwise
+ // miss legitimate matches.
+ let js = json!({
+ "ecd": ["ACME.com"],
+ });
+ let api: ApiEntityFilterAst = serde_json::from_value(js).unwrap();
+ let req = SoupRequest {
+ soup_type: SoupType::Expanded,
+ limit: 20,
+ cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
+ SimpleSortMethod::ViewedAt,
+ api,
+ ))),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ email_preview_view: PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox),
+ link_id: None,
+ };
+ let req: SoupRequest<Option<EntityFilterAst>> = req.into_ast().unwrap();
+ let ast = match &req.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(_, f))) => f.as_ref().unwrap(),
+ _ => panic!("expected simple sort"),
+ };
+ let scope = ast.email_filter.crm_scope.as_ref().expect("scope set");
+ assert!(matches!(scope, CrmScope::Domains(d) if d == &vec!["acme.com".to_string()]));
+}
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
index b0f28b0cd6..b7a9529094 100644
--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
@@ -224,9 +224,14 @@ impl ListEntities {
document_filter: self.document_filter.clone(),
project_filter: self.project_filter.clone(),
chat_filter: self.chat_filter.clone(),
- email_filter: match self.email_preset {
- Some(preset) => Some(Arc::new(preset.filter())),
- None => self.email_filter.clone(),
+ // Toolset doesn't (yet) expose CRM scope; the tool surface stays
+ // per-link unless we add explicit fields for it.
+ email_filter: item_filters::ast::EmailFilterAst {
+ tree: match self.email_preset {
+ Some(preset) => Some(Arc::new(preset.filter())),
+ None => self.email_filter.clone(),
+ },
+ crm_scope: None,
},
channel_filter: self.channel_filter.clone(),
call_filter: self.call_filter.clone(),
@@ -263,7 +268,10 @@ impl ListEntities {
email_filter: if include_types.contains(&ItemType::Email) {
ast.email_filter
} else {
- Some(Arc::new(Expr::val(EmailLiteral::ThreadId(Uuid::nil()))))
+ item_filters::ast::EmailFilterAst {
+ tree: Some(Arc::new(Expr::val(EmailLiteral::ThreadId(Uuid::nil())))),
+ crm_scope: None,
+ }
},
channel_filter: if include_types.contains(&ItemType::Channel) {
ast.channel_filter
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/test.rs b/rust/cloud-storage/soup/src/inbound/toolset/test.rs
index a03d87ccea..45e5800b2d 100644
--- a/rust/cloud-storage/soup/src/inbound/toolset/test.rs
+++ b/rust/cloud-storage/soup/src/inbound/toolset/test.rs
@@ -66,7 +66,7 @@ fn test_email_preset_defaults_to_email_results() {
.unwrap();
let ast = list.entity_filter_ast();
- assert!(ast.email_filter.is_some());
+ assert!(ast.email_filter.tree.is_some());
assert!(ast.document_filter.is_some());
assert!(ast.project_filter.is_some());
assert!(ast.chat_filter.is_some());
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
index e3191c024e..ed92717ecb 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
@@ -5454,7 +5454,7 @@ fn mock_empty_ast() -> EntityFilterAst {
document_filter: None,
project_filter: None,
chat_filter: None,
- email_filter: None,
+ email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
properties_filter: None,