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(crm): integrate CRM companies and contacts into entity_access (#3727)

Evan Hutnik38f3da5292be
diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.ts
index 8ba6d2b6df..45cb6b64e3 100644
--- a/js/app/packages/queries/notification/user-notifications.ts
+++ b/js/app/packages/queries/notification/user-notifications.ts
@@ -540,7 +540,14 @@ function notificationEntityTypeToSoupTag(
.with('email_thread', () => 'emailThread' as const)
.with('foreign_entity', () => 'foreignEntity' as const)
.with(
- P.union('user', 'team', 'call', 'static_file', 'crm_company'),
+ P.union(
+ 'user',
+ 'team',
+ 'call',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact'
+ ),
() => null
)
.exhaustive();
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts
index 806baedf2a..4cda84692d 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts
@@ -23,4 +23,5 @@ export const EntityType = {
foreign_entity: 'foreign_entity',
static_file: 'static_file',
crm_company: 'crm_company',
+ crm_contact: 'crm_contact',
} as const;
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index f4baf98e4a..3e09ab219d 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -2397,7 +2397,8 @@
"call",
"foreign_entity",
"static_file",
- "crm_company"
+ "crm_company",
+ "crm_contact"
]
},
"ErrorResponse": {
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts
index ba77b13a7e..062e212685 100644
--- a/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts
@@ -23,4 +23,5 @@ export const EntityType = {
foreign_entity: 'foreign_entity',
static_file: 'static_file',
crm_company: 'crm_company',
+ crm_contact: 'crm_contact',
} as const;
diff --git a/js/app/packages/service-clients/service-connection/openapi.json b/js/app/packages/service-clients/service-connection/openapi.json
index a2e6738914..effc0c0de0 100644
--- a/js/app/packages/service-clients/service-connection/openapi.json
+++ b/js/app/packages/service-clients/service-connection/openapi.json
@@ -240,7 +240,8 @@
"call",
"foreign_entity",
"static_file",
- "crm_company"
+ "crm_company",
+ "crm_contact"
]
},
"GenericErrorResponse": {
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts
index 2588cf4759..2a276be51a 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts
@@ -23,4 +23,5 @@ export const EntityType = {
foreign_entity: 'foreign_entity',
static_file: 'static_file',
crm_company: 'crm_company',
+ crm_contact: 'crm_contact',
} as const;
diff --git a/js/app/packages/service-clients/service-notification/generated/zod.ts b/js/app/packages/service-clients/service-notification/generated/zod.ts
index d0bb45c1fd..e6e5a39e36 100644
--- a/js/app/packages/service-clients/service-notification/generated/zod.ts
+++ b/js/app/packages/service-clients/service-notification/generated/zod.ts
@@ -121,6 +121,7 @@ export const listTypedNotificationsResponse = zod
'foreign_entity',
'static_file',
'crm_company',
+ 'crm_contact',
])
.describe('The type of an entity in Macro'),
})
@@ -743,6 +744,7 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
'foreign_entity',
'static_file',
'crm_company',
+ 'crm_contact',
])
.describe('The type of an entity in Macro'),
})
@@ -1359,6 +1361,7 @@ export const getTypedNotificationsByEventItemIdResponse = zod
'foreign_entity',
'static_file',
'crm_company',
+ 'crm_contact',
])
.describe('The type of an entity in Macro'),
})
@@ -1986,6 +1989,7 @@ export const getTypedNotificationByIdResponse = zod
'foreign_entity',
'static_file',
'crm_company',
+ 'crm_contact',
])
.describe('The type of an entity in Macro'),
})
diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.json
index d427237d2c..c9b580fbd5 100644
--- a/js/app/packages/service-clients/service-notification/openapi.json
+++ b/js/app/packages/service-clients/service-notification/openapi.json
@@ -1475,7 +1475,8 @@
"call",
"foreign_entity",
"static_file",
- "crm_company"
+ "crm_company",
+ "crm_contact"
]
},
"ErrorResponse": {
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 0b7f4651a2..753c14baf9 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -2688,9 +2688,11 @@ export const editCrmCommentResponse = zod
.describe('A single comment within a [`CrmThread`].');
/**
- * @summary List the comment threads on a CRM company or contact, scoped to the
-requesting user's team. Returns 404 when the entity isn't owned by the
-team; an owned entity with no threads returns `200 []`.
+ * @summary List the comment threads on a CRM company or contact. Access is
+enforced by [`EntityPermissionExtractor`] against the path's
+`crm_company`/`crm_contact` entity type — hidden parents are
+invisible to plain members. An accessible entity with no threads
+returns `200 []`.
*/
export const listCrmCommentsParams = zod.object({
entity_type: zod
@@ -2902,12 +2904,11 @@ export const createCrmCommentResponse = zod
);
/**
- * @summary List the contacts of a CRM company, scoped to the requesting user's
-team. Returns 404 when the company isn't owned by the team (so
-existence doesn't leak across teams). Non-admin viewers also 404 on
-hidden companies and see only non-hidden contacts; admin/owner
-viewers reach hidden companies and see every owned contact
-regardless of `hidden` so they can render the right unhide UI.
+ * @summary List the contacts of a CRM company. Access is enforced by
+[`CrmCompanyAccessLevelExtractor`]: the user must be on the team that
+owns the company. Hidden companies and hidden contacts are invisible
+to plain members; admin/owner callers see hidden rows so they can
+render the right unhide UI.
*/
export const listCompanyContactsParams = zod.object({
company_id: zod.uuid().describe('The CRM company whose contacts to list'),
@@ -2992,11 +2993,11 @@ export const setCompanyHiddenBody = zod
.describe('Request body for `PUT \/companies\/{company_id}\/hidden`.');
/**
- * @summary Fetch a single CRM contact by id, scoped to the requesting user's
-team. Returns 404 when the contact doesn't exist or isn't owned by
-the team. Non-admin viewers also 404 on hidden contacts or hidden
-parent companies (so existence doesn't leak); admin/owner viewers
-reach every owned contact regardless of `hidden`.
+ * @summary Fetch a single CRM contact by id. Access is enforced by
+[`CrmContactAccessLevelExtractor`]: the user must be on the team that
+owns the contact's parent company, and hidden contacts are invisible
+to plain members. Admin/owner callers see hidden contacts so they can
+render the right unhide UI.
*/
export const getContactParams = zod.object({
contact_id: zod.uuid().describe('The CRM contact to fetch'),
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 65f2d9e0aa..16c5689cb7 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -3585,7 +3585,7 @@
"/crm/comments/{entity_type}/{entity_id}": {
"get": {
"tags": ["crm::inbound::axum_router::comments"],
- "summary": "List the comment threads on a CRM company or contact, scoped to the\nrequesting user's team. Returns 404 when the entity isn't owned by the\nteam; an owned entity with no threads returns `200 []`.",
+ "summary": "List the comment threads on a CRM company or contact. Access is\nenforced by [`EntityPermissionExtractor`] against the path's\n`crm_company`/`crm_contact` entity type — hidden parents are\ninvisible to plain members. An accessible entity with no threads\nreturns `200 []`.",
"operationId": "list_crm_comments",
"parameters": [
{
@@ -3736,7 +3736,7 @@
"/crm/companies/{company_id}/contacts": {
"get": {
"tags": ["crm::inbound::axum_router::list_company_contacts"],
- "summary": "List the contacts of a CRM company, scoped to the requesting user's\nteam. Returns 404 when the company isn't owned by the team (so\nexistence doesn't leak across teams). Non-admin viewers also 404 on\nhidden companies and see only non-hidden contacts; admin/owner\nviewers reach hidden companies and see every owned contact\nregardless of `hidden` so they can render the right unhide UI.",
+ "summary": "List the contacts of a CRM company. Access is enforced by\n[`CrmCompanyAccessLevelExtractor`]: the user must be on the team that\nowns the company. Hidden companies and hidden contacts are invisible\nto plain members; admin/owner callers see hidden rows so they can\nrender the right unhide UI.",
"operationId": "list_company_contacts",
"parameters": [
{
@@ -3938,7 +3938,7 @@
"/crm/contacts/{contact_id}": {
"get": {
"tags": ["crm::inbound::axum_router::get_contact"],
- "summary": "Fetch a single CRM contact by id, scoped to the requesting user's\nteam. Returns 404 when the contact doesn't exist or isn't owned by\nthe team. Non-admin viewers also 404 on hidden contacts or hidden\nparent companies (so existence doesn't leak); admin/owner viewers\nreach every owned contact regardless of `hidden`.",
+ "summary": "Fetch a single CRM contact by id. Access is enforced by\n[`CrmContactAccessLevelExtractor`]: the user must be on the team that\nowns the contact's parent company, and hidden contacts are invisible\nto plain members. Admin/owner callers see hidden contacts so they can\nrender the right unhide UI.",
"operationId": "get_contact",
"parameters": [
{
diff --git a/rust/cloud-storage/.sqlx/query-0643eed420f0f10eab30aa91b17d858d0f765ba260e5fa84edf3741df03f6566.json b/rust/cloud-storage/.sqlx/query-0643eed420f0f10eab30aa91b17d858d0f765ba260e5fa84edf3741df03f6566.json
new file mode 100644
index 0000000000..e706732669
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-0643eed420f0f10eab30aa91b17d858d0f765ba260e5fa84edf3741df03f6566.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n (ct.hidden OR c.hidden) AS \"hidden!\",\n tu.team_role AS \"role!: TeamRole\"\n FROM crm_contacts ct\n JOIN crm_companies c\n ON c.id = ct.company_id\n JOIN team_user tu\n ON tu.team_id = c.team_id\n AND tu.user_id = $1\n WHERE ct.id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "hidden!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null,
+ false
+ ]
+ },
+ "hash": "0643eed420f0f10eab30aa91b17d858d0f765ba260e5fa84edf3741df03f6566"
+}
diff --git a/rust/cloud-storage/.sqlx/query-0fb8a1f0bcfee684fa393fa7465a17b7345b658528783903597574827fd61dd0.json b/rust/cloud-storage/.sqlx/query-0fb8a1f0bcfee684fa393fa7465a17b7345b658528783903597574827fd61dd0.json
new file mode 100644
index 0000000000..f92c09c1ed
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-0fb8a1f0bcfee684fa393fa7465a17b7345b658528783903597574827fd61dd0.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT t.company_id, t.contact_id\n FROM crm_comment c\n JOIN crm_thread t ON t.id = c.thread_id\n WHERE c.id = $1\n AND c.deleted_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "company_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "contact_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true
+ ]
+ },
+ "hash": "0fb8a1f0bcfee684fa393fa7465a17b7345b658528783903597574827fd61dd0"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b507630afbc72830ecf99356f004253f29af4b7c35df0bcff830cfc9b6cb9ee4.json b/rust/cloud-storage/.sqlx/query-b507630afbc72830ecf99356f004253f29af4b7c35df0bcff830cfc9b6cb9ee4.json
new file mode 100644
index 0000000000..7934632c48
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b507630afbc72830ecf99356f004253f29af4b7c35df0bcff830cfc9b6cb9ee4.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n c.hidden AS \"hidden!\",\n tu.team_role AS \"role!: TeamRole\"\n FROM crm_companies c\n JOIN team_user tu\n ON tu.team_id = c.team_id\n AND tu.user_id = $1\n WHERE c.id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "hidden!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "b507630afbc72830ecf99356f004253f29af4b7c35df0bcff830cfc9b6cb9ee4"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index c629fd14e2..b9474d39ee 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2687,6 +2687,7 @@ dependencies = [
"macro_db_migrator",
"macro_uuid",
"model-error-response",
+ "model_user",
"reqwest 0.13.3",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.toml
index 935c0d31fd..a07921c03f 100644
--- a/rust/cloud-storage/crm/Cargo.toml
+++ b/rust/cloud-storage/crm/Cargo.toml
@@ -9,6 +9,7 @@ axum = [
"dep:axum",
"dep:macro_uuid",
"dep:model-error-response",
+ "dep:model_user",
"dep:utoipa",
"entity_access/axum",
"entity_access/inbound",
@@ -34,6 +35,7 @@ entity_access = { path = "../entity_access", default-features = false }
axum = { workspace = true, optional = true }
macro_uuid = { path = "../macro_uuid", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
+model_user = { path = "../model_user", optional = true, features = ["axum"] }
utoipa = { workspace = true, optional = true }
# Outbound dependencies
diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rs
index a68f0360e7..03c463d4c5 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -440,4 +440,16 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
comment_id: &uuid::Uuid,
include_hidden: bool,
) -> impl Future<Output = Result<DeleteCrmCommentResult, CrmError>> + Send;
+
+ /// Resolve a CRM comment to the entity its thread is attached to.
+ /// Returns `Ok(None)` when the comment doesn't exist or is
+ /// soft-deleted. The schema's `crm_thread_one_parent` check
+ /// constraint guarantees exactly one of `company_id` / `contact_id`
+ /// is set on the parent thread, so the variant is unambiguous. This
+ /// is the lookup the comment access extractor uses to dispatch
+ /// access checks to the right entity type.
+ fn get_comment_entity(
+ &self,
+ comment_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Option<(CrmCommentEntityType, uuid::Uuid)>, CrmError>> + Send;
}
diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rs
index 9a639fc919..4cc9a4b49a 100644
--- a/rust/cloud-storage/crm/src/domain/service.rs
+++ b/rust/cloud-storage/crm/src/domain/service.rs
@@ -273,6 +273,15 @@ pub trait CrmService: Clone + Send + Sync + 'static {
comment_id: &uuid::Uuid,
include_hidden: bool,
) -> impl Future<Output = Result<DeleteCrmCommentResult, CrmError>> + Send;
+
+ /// Resolve a comment to its owning CRM entity. `None` when the
+ /// comment doesn't exist or is soft-deleted. Used by the comment
+ /// access extractor to dispatch the access check to the right
+ /// entity type. See [`CompaniesRepository::get_comment_entity`].
+ fn get_comment_entity(
+ &self,
+ comment_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Option<(CrmCommentEntityType, uuid::Uuid)>, CrmError>> + Send;
}
/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`]
@@ -625,6 +634,16 @@ where
.delete_crm_comment(team_id, comment_id, include_hidden)
.await
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_comment_entity(
+ &self,
+ comment_id: &uuid::Uuid,
+ ) -> Result<Option<(CrmCommentEntityType, uuid::Uuid)>, CrmError> {
+ self.companies_repository
+ .get_comment_entity(comment_id)
+ .await
+ }
}
/// No-op [`CrmService`] for binaries that need to satisfy the bound
@@ -788,4 +807,11 @@ impl CrmService for NoOpCrmService {
) -> Result<DeleteCrmCommentResult, CrmError> {
unimplemented!("NoOpCrmService.delete_crm_comment")
}
+
+ async fn get_comment_entity(
+ &self,
+ _comment_id: &uuid::Uuid,
+ ) -> Result<Option<(CrmCommentEntityType, uuid::Uuid)>, CrmError> {
+ Ok(None)
+ }
}
diff --git a/rust/cloud-storage/crm/src/inbound.rs b/rust/cloud-storage/crm/src/inbound.rs
index 068e431c1f..299b52147a 100644
--- a/rust/cloud-storage/crm/src/inbound.rs
+++ b/rust/cloud-storage/crm/src/inbound.rs
@@ -1,4 +1,6 @@
//! Inbound adapters for the CRM domain.
+#[cfg(feature = "axum")]
+pub mod axum_extractors;
#[cfg(feature = "axum")]
pub mod axum_router;
diff --git a/rust/cloud-storage/crm/src/inbound/axum_extractors.rs b/rust/cloud-storage/crm/src/inbound/axum_extractors.rs
new file mode 100644
index 0000000000..96e05164e1
--- /dev/null
+++ b/rust/cloud-storage/crm/src/inbound/axum_extractors.rs
@@ -0,0 +1,144 @@
+//! Axum extractors specific to the CRM domain.
+//!
+//! Lives in the `crm` crate rather than `entity_access` because the
+//! lookups it performs (e.g. comment → owning entity) cross the
+//! `CrmService` boundary, and `entity_access` deliberately knows nothing
+//! about CRM models.
+
+use std::collections::HashMap;
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ RequestPartsExt,
+ extract::{FromRef, FromRequestParts, Path},
+ http::request::Parts,
+};
+use entity_access::{
+ domain::{
+ models::{AccessError, Entity, EntityAccessReceipt, EntityType, RequiredPermission},
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::ExtractorError,
+};
+use model_user::axum_extractor::MacroUserExtractor;
+use uuid::Uuid;
+
+use crate::{
+ domain::{comment::CrmCommentEntityType, service::CrmService},
+ inbound::axum_router::CrmServiceRef,
+};
+
+/// Validates that the user satisfies the required permission for the CRM
+/// entity (company or contact) a given comment belongs to. Reads
+/// `comment_id` from the path and resolves the owning entity via
+/// `CrmService::get_comment_entity`. The same role-to-AccessLevel
+/// mapping as the company / contact extractors applies; hidden parents
+/// are invisible to plain members.
+///
+/// Returns `NotFound` when the comment doesn't exist or is soft-deleted,
+/// so cross-team callers can't probe for comment existence.
+#[derive(Debug)]
+pub struct CrmCommentAccessLevelExtractor<T: RequiredPermission, C, Eas> {
+ /// The entity access receipt for the comment's owning entity.
+ pub entity_access_receipt: EntityAccessReceipt<T>,
+ /// Which CRM entity kind the comment is attached to.
+ pub entity_type: CrmCommentEntityType,
+ /// The owning team id, looked up alongside the access check.
+ pub team_id: Uuid,
+ _marker: PhantomData<(T, C, Eas)>,
+}
+
+impl<T, S, C, Eas> FromRequestParts<S> for CrmCommentAccessLevelExtractor<T, C, Eas>
+where
+ T: RequiredPermission,
+ CrmServiceRef<C>: FromRef<S>,
+ Arc<Eas>: FromRef<S>,
+ C: CrmService,
+ Eas: EntityAccessService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = ExtractorError;
+
+ #[tracing::instrument(err, skip(state, parts))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let CrmServiceRef(crm_service) = <CrmServiceRef<C>>::from_ref(state);
+ let access_service = <Arc<Eas>>::from_ref(state);
+
+ let Path(path_params): Path<HashMap<String, String>> = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::BadRequest("missing comment_id path parameter"))?;
+ let comment_id = extract_comment_id(&path_params)?;
+
+ let MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Unauthorized)?;
+
+ let (crm_entity_type, entity_id) = crm_service
+ .get_comment_entity(&comment_id)
+ .await
+ .map_err(|_| ExtractorError::Internal)?
+ .ok_or(ExtractorError::NotFound("CRM comment not found"))?;
+
+ let entity_type = entity_type_for(crm_entity_type);
+ let entity_id_str = entity_id.to_string();
+
+ // Map an "access denied" outcome to NotFound so a cross-team caller
+ // can't tell apart "this comment doesn't exist" (404) from "this
+ // comment exists but isn't yours" (401) — comment ids would
+ // otherwise be a probable existence oracle.
+ let permission = match access_service
+ .get_entity_permission(Some(&macro_user_id), &entity_id_str, entity_type, None)
+ .await
+ {
+ Ok(p) => p,
+ Err(AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_)) => {
+ return Err(ExtractorError::NotFound("CRM comment not found"));
+ }
+ Err(e) => return Err(ExtractorError::from(e)),
+ };
+
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::NotFound("CRM comment not found"));
+ }
+
+ let team_id = access_service
+ .get_user_team(&macro_user_id)
+ .await
+ .map_err(ExtractorError::from)?
+ .ok_or(ExtractorError::Unauthorized)?
+ .team_id;
+
+ Ok(Self {
+ entity_access_receipt: EntityAccessReceipt::try_new_authenticated_user(
+ macro_user_id,
+ Entity {
+ entity_id: entity_id_str,
+ entity_type,
+ },
+ permission,
+ )?,
+ entity_type: crm_entity_type,
+ team_id,
+ _marker: PhantomData,
+ })
+ }
+}
+
+fn extract_comment_id(path_params: &HashMap<String, String>) -> Result<Uuid, ExtractorError> {
+ let raw_id = path_params
+ .get("comment_id")
+ .ok_or(ExtractorError::BadRequest(
+ "missing comment_id path parameter",
+ ))?;
+ Uuid::parse_str(raw_id).map_err(|_| ExtractorError::BadRequest("invalid comment ID format"))
+}
+
+fn entity_type_for(t: CrmCommentEntityType) -> EntityType {
+ match t {
+ CrmCommentEntityType::CrmCompany => EntityType::CrmCompany,
+ CrmCommentEntityType::CrmContact => EntityType::CrmContact,
+ }
+}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs b/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
index 10f27e2b2b..ee99c25397 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
@@ -2,8 +2,12 @@
//!
//! Threads and comments hang off a CRM company or contact and mirror the
//! document comment shape so the frontend reuses its thread assembly /
-//! rendering. All routes are team-scoped via [`MacroUserTeamExtractor`];
-//! entity ownership is enforced in the repository.
+//! rendering. List/create routes use [`EntityPermissionExtractor`] over
+//! the path's `crm_company`/`crm_contact` entity type. Edit/delete are
+//! keyed by `comment_id` only and use [`CrmCommentAccessLevelExtractor`],
+//! which resolves the comment's owning entity before checking access. In
+//! every case the extractor enforces the team-membership rule, so
+//! members can't reach hidden parents.
use axum::{
Json,
@@ -11,10 +15,10 @@ use axum::{
};
use entity_access::{
domain::{
- models::{MemberTeamRole, TeamRole},
+ models::{AccessLevel, ViewAccessLevel},
ports::EntityAccessService,
},
- inbound::axum_extractors::MacroUserTeamExtractor,
+ inbound::axum_extractors::EntityPermissionExtractor,
};
use model_error_response::ErrorResponse;
use serde::Deserialize;
@@ -22,10 +26,13 @@ use serde_json::Value;
use utoipa::ToSchema;
use uuid::Uuid;
-use crate::domain::{
- comment::{CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult},
- model::CrmError,
- service::CrmService,
+use crate::{
+ domain::{
+ comment::{CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult},
+ model::CrmError,
+ service::CrmService,
+ },
+ inbound::axum_extractors::CrmCommentAccessLevelExtractor,
};
use super::CrmRouterState;
@@ -54,9 +61,11 @@ pub struct EditCrmCommentRequest {
pub text: String,
}
-/// List the comment threads on a CRM company or contact, scoped to the
-/// requesting user's team. Returns 404 when the entity isn't owned by the
-/// team; an owned entity with no threads returns `200 []`.
+/// List the comment threads on a CRM company or contact. Access is
+/// enforced by [`EntityPermissionExtractor`] against the path's
+/// `crm_company`/`crm_contact` entity type — hidden parents are
+/// invisible to plain members. An accessible entity with no threads
+/// returns `200 []`.
#[utoipa::path(
get,
path = "/crm/comments/{entity_type}/{entity_id}",
@@ -74,16 +83,15 @@ pub struct EditCrmCommentRequest {
)]
#[tracing::instrument(skip_all, err, fields(entity_id = %entity_id))]
pub async fn list_handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ access: EntityPermissionExtractor<Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path((entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
) -> Result<Json<Vec<CrmCommentThread>>, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
+ let team_id = team_id_for_user(&state, &access).await?;
let include_hidden = access
.entity_access_receipt
.entity_permission()
- .allows_team_role(TeamRole::Admin);
+ .allows_access_level(AccessLevel::Edit);
let threads = state
.service
@@ -115,17 +123,16 @@ pub async fn list_handler<C: CrmService, Eas: EntityAccessService>(
)]
#[tracing::instrument(skip_all, err, fields(entity_id = %entity_id))]
pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ access: EntityPermissionExtractor<Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path((entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
Json(req): Json<CreateCrmCommentRequest>,
) -> Result<Json<CrmCommentThread>, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
+ let team_id = team_id_for_user(&state, &access).await?;
let include_hidden = access
.entity_access_receipt
.entity_permission()
- .allows_team_role(TeamRole::Admin);
+ .allows_access_level(AccessLevel::Edit);
let owner = access
.entity_access_receipt
.get_authenticated_user()
@@ -175,17 +182,15 @@ pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
)]
#[tracing::instrument(skip_all, err, fields(comment_id = %comment_id))]
pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ access: CrmCommentAccessLevelExtractor<ViewAccessLevel, C, Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path(comment_id): Path<Uuid>,
Json(req): Json<EditCrmCommentRequest>,
) -> Result<Json<CrmComment>, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
let include_hidden = access
.entity_access_receipt
.entity_permission()
- .allows_team_role(TeamRole::Admin);
+ .allows_access_level(AccessLevel::Edit);
let text = req.text.trim();
if text.is_empty() {
@@ -196,7 +201,7 @@ pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
let comment = state
.service
- .edit_crm_comment(&team_id, &comment_id, text, include_hidden)
+ .edit_crm_comment(&access.team_id, &comment_id, text, include_hidden)
.await?;
Ok(Json(comment))
@@ -221,21 +226,40 @@ pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
)]
#[tracing::instrument(skip_all, err, fields(comment_id = %comment_id))]
pub async fn delete_handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ access: CrmCommentAccessLevelExtractor<ViewAccessLevel, C, Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path(comment_id): Path<Uuid>,
) -> Result<Json<DeleteCrmCommentResult>, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
let include_hidden = access
.entity_access_receipt
.entity_permission()
- .allows_team_role(TeamRole::Admin);
+ .allows_access_level(AccessLevel::Edit);
let result = state
.service
- .delete_crm_comment(&team_id, &comment_id, include_hidden)
+ .delete_crm_comment(&access.team_id, &comment_id, include_hidden)
.await?;
Ok(Json(result))
}
+
+/// Resolve the requesting user's owning team via the entity access
+/// service. `EntityPermissionExtractor` already validated team-membership
+/// access on the target entity, so a missing team here is treated as
+/// `InvalidTeamId` (i.e. corrupted state) rather than `Unauthorized`.
+async fn team_id_for_user<C: CrmService, Eas: EntityAccessService>(
+ state: &CrmRouterState<C, Eas>,
+ access: &EntityPermissionExtractor<Eas>,
+) -> Result<Uuid, CrmError> {
+ let user_id = access
+ .entity_access_receipt
+ .get_authenticated_user()
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ state
+ .entity_access_service
+ .get_user_team(&user_id.0)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(anyhow::Error::msg(e.to_string())))?
+ .map(|t| t.team_id)
+ .ok_or(CrmError::InvalidTeamId)
+}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/get_contact.rs b/rust/cloud-storage/crm/src/inbound/axum_router/get_contact.rs
index b32efe8b1d..41f3e8095b 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/get_contact.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/get_contact.rs
@@ -4,10 +4,10 @@ use axum::{
};
use entity_access::{
domain::{
- models::{MemberTeamRole, TeamRole},
+ models::{AccessLevel, ViewAccessLevel},
ports::EntityAccessService,
},
- inbound::axum_extractors::MacroUserTeamExtractor,
+ inbound::axum_extractors::CrmContactAccessLevelExtractor,
};
use model_error_response::ErrorResponse;
use uuid::Uuid;
@@ -16,11 +16,11 @@ use crate::domain::{model::CrmError, service::CrmService};
use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
-/// Fetch a single CRM contact by id, scoped to the requesting user's
-/// team. Returns 404 when the contact doesn't exist or isn't owned by
-/// the team. Non-admin viewers also 404 on hidden contacts or hidden
-/// parent companies (so existence doesn't leak); admin/owner viewers
-/// reach every owned contact regardless of `hidden`.
+/// Fetch a single CRM contact by id. Access is enforced by
+/// [`CrmContactAccessLevelExtractor`]: the user must be on the team that
+/// owns the contact's parent company, and hidden contacts are invisible
+/// to plain members. Admin/owner callers see hidden contacts so they can
+/// render the right unhide UI.
#[utoipa::path(
get,
path = "/crm/contacts/{contact_id}",
@@ -37,20 +37,18 @@ use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
)]
#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id))]
pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ access: CrmContactAccessLevelExtractor<ViewAccessLevel, Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path(contact_id): Path<Uuid>,
) -> Result<Json<CrmContactResponse>, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
let include_hidden = access
.entity_access_receipt
.entity_permission()
- .allows_team_role(TeamRole::Admin);
+ .allows_access_level(AccessLevel::Edit);
let contact = state
.service
- .get_contact_for_team(&team_id, &contact_id, include_hidden)
+ .get_contact_for_team(&access.team_id, &contact_id, include_hidden)
.await?
.ok_or(CrmError::ContactNotFoundForTeam)?;
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/list_company_contacts.rs b/rust/cloud-storage/crm/src/inbound/axum_router/list_company_contacts.rs
index 631bda0d80..7d21191f44 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/list_company_contacts.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/list_company_contacts.rs
@@ -5,10 +5,10 @@ use axum::{
use chrono::{DateTime, Utc};
use entity_access::{
domain::{
- models::{MemberTeamRole, TeamRole},
+ models::{AccessLevel, ViewAccessLevel},
ports::EntityAccessService,
},
- inbound::axum_extractors::MacroUserTeamExtractor,
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
};
use model_error_response::ErrorResponse;
use serde::Serialize;
@@ -65,12 +65,11 @@ impl From<CrmContact> for CrmContactResponse {
}
}
-/// List the contacts of a CRM company, scoped to the requesting user's
-/// team. Returns 404 when the company isn't owned by the team (so
-/// existence doesn't leak across teams). Non-admin viewers also 404 on
-/// hidden companies and see only non-hidden contacts; admin/owner
-/// viewers reach hidden companies and see every owned contact
-/// regardless of `hidden` so they can render the right unhide UI.
+/// List the contacts of a CRM company. Access is enforced by
+/// [`CrmCompanyAccessLevelExtractor`]: the user must be on the team that
+/// owns the company. Hidden companies and hidden contacts are invisible
+/// to plain members; admin/owner callers see hidden rows so they can
+/// render the right unhide UI.
#[utoipa::path(
get,
path = "/crm/companies/{company_id}/contacts",
@@ -87,20 +86,18 @@ impl From<CrmContact> for CrmContactResponse {
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path(company_id): Path<Uuid>,
) -> Result<Json<Vec<CrmContactResponse>>, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
let include_hidden = access
.entity_access_receipt
.entity_permission()
- .allows_team_role(TeamRole::Admin);
+ .allows_access_level(AccessLevel::Edit);
let contacts = state
.service
- .list_contacts_for_company(&team_id, &company_id, include_hidden)
+ .list_contacts_for_company(&access.team_id, &company_id, include_hidden)
.await?;
Ok(Json(contacts.into_iter().map(Into::into).collect()))
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
index 4ad77188f4..c6b52f0643 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
@@ -46,6 +46,27 @@ impl<C, Eas> FromRef<CrmRouterState<C, Eas>> for Arc<Eas> {
}
}
+/// Newtype around `Arc<C>` so it can be pulled from
+/// [`CrmRouterState`] via `FromRef` without colliding with
+/// [`FromRef`] for [`Arc<Eas>`] in the (theoretical) case where
+/// `C == Eas`. Plain `Arc<C>` vs `Arc<Eas>` overlap as
+/// implementations when both type params resolve to the same type;
+/// wrapping one side fixes it without changing the state's storage.
+#[derive(Debug)]
+pub struct CrmServiceRef<C>(pub Arc<C>);
+
+impl<C> Clone for CrmServiceRef<C> {
+ fn clone(&self) -> Self {
+ Self(self.0.clone())
+ }
+}
+
+impl<C, Eas> FromRef<CrmRouterState<C, Eas>> for CrmServiceRef<C> {
+ fn from_ref(state: &CrmRouterState<C, Eas>) -> Self {
+ CrmServiceRef(state.service.clone())
+ }
+}
+
// Manual Clone so C, Eas don't need Clone.
impl<C, Eas> Clone for CrmRouterState<C, Eas> {
fn clone(&self) -> Self {
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs b/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs
index f706934804..1dd67879ed 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs
@@ -4,8 +4,8 @@ use axum::{
http::StatusCode,
};
use entity_access::{
- domain::{models::AdminTeamRole, ports::EntityAccessService},
- inbound::axum_extractors::MacroUserTeamExtractor,
+ domain::{models::EditAccessLevel, ports::EntityAccessService},
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
};
use model_error_response::ErrorResponse;
use serde::Deserialize;
@@ -52,17 +52,14 @@ pub struct SetCompanyHiddenRequest {
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id, hidden = req.hidden))]
pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<AdminTeamRole, Eas>,
+ access: CrmCompanyAccessLevelExtractor<EditAccessLevel, Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path(company_id): Path<Uuid>,
Json(req): Json<SetCompanyHiddenRequest>,
) -> Result<StatusCode, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
-
state
.service
- .set_company_hidden(&team_id, &company_id, req.hidden)
+ .set_company_hidden(&access.team_id, &company_id, req.hidden)
.await?;
Ok(StatusCode::NO_CONTENT)
}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/set_contact_hidden.rs b/rust/cloud-storage/crm/src/inbound/axum_router/set_contact_hidden.rs
index 8f10ff7cf1..a8f83bfe70 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/set_contact_hidden.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_contact_hidden.rs
@@ -4,8 +4,8 @@ use axum::{
http::StatusCode,
};
use entity_access::{
- domain::{models::AdminTeamRole, ports::EntityAccessService},
- inbound::axum_extractors::MacroUserTeamExtractor,
+ domain::{models::EditAccessLevel, ports::EntityAccessService},
+ inbound::axum_extractors::CrmContactAccessLevelExtractor,
};
use model_error_response::ErrorResponse;
use serde::Deserialize;
@@ -44,17 +44,14 @@ pub struct SetContactHiddenRequest {
)]
#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id, hidden = req.hidden))]
pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<AdminTeamRole, Eas>,
+ access: CrmContactAccessLevelExtractor<EditAccessLevel, Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path(contact_id): Path<Uuid>,
Json(req): Json<SetContactHiddenRequest>,
) -> Result<StatusCode, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
-
state
.service
- .set_contact_hidden(&team_id, &contact_id, req.hidden)
+ .set_contact_hidden(&access.team_id, &contact_id, req.hidden)
.await?;
Ok(StatusCode::NO_CONTENT)
}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs b/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs
index 98586a2dda..33e5116566 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs
@@ -4,8 +4,8 @@ use axum::{
http::StatusCode,
};
use entity_access::{
- domain::{models::AdminTeamRole, ports::EntityAccessService},
- inbound::axum_extractors::MacroUserTeamExtractor,
+ domain::{models::EditAccessLevel, ports::EntityAccessService},
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
};
use model_error_response::ErrorResponse;
use serde::Deserialize;
@@ -49,17 +49,14 @@ pub struct SetEmailSyncRequest {
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id, email_sync = req.email_sync))]
pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<AdminTeamRole, Eas>,
+ access: CrmCompanyAccessLevelExtractor<EditAccessLevel, Eas>,
State(state): State<CrmRouterState<C, Eas>>,
Path(company_id): Path<Uuid>,
Json(req): Json<SetEmailSyncRequest>,
) -> Result<StatusCode, CrmError> {
- let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
- .map_err(|_| CrmError::InvalidTeamId)?;
-
state
.service
- .set_email_sync(&team_id, &company_id, req.email_sync)
+ .set_email_sync(&access.team_id, &company_id, req.email_sync)
.await?;
Ok(StatusCode::NO_CONTENT)
}
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
index e166debcc0..bf35fecd58 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -1696,6 +1696,32 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
thread_deleted,
})
}
+
+ #[tracing::instrument(skip(self), err, fields(comment_id = %comment_id))]
+ async fn get_comment_entity(
+ &self,
+ comment_id: &uuid::Uuid,
+ ) -> Result<Option<(CrmCommentEntityType, uuid::Uuid)>, CrmError> {
+ let row = sqlx::query!(
+ r#"
+ SELECT t.company_id, t.contact_id
+ FROM crm_comment c
+ JOIN crm_thread t ON t.id = c.thread_id
+ WHERE c.id = $1
+ AND c.deleted_at IS NULL
+ "#,
+ comment_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ Ok(row.and_then(|r| match (r.contact_id, r.company_id) {
+ (Some(contact_id), _) => Some((CrmCommentEntityType::CrmContact, contact_id)),
+ (None, Some(company_id)) => Some((CrmCommentEntityType::CrmCompany, company_id)),
+ (None, None) => None,
+ }))
+ }
}
/// Maps a CRM entity type to the team-scoped not-found error used when the
diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rs
index 4f156ec8bf..9f4982241d 100644
--- a/rust/cloud-storage/entity_access/src/domain/ports.rs
+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs
@@ -61,6 +61,30 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> impl Future<Output = Result<bool, AccessError>> + Send;
+ /// Get the access level a user has for a CRM company.
+ ///
+ /// Access derives from the user's role on the team that owns the company:
+ /// `Owner` → [`AccessLevel::Owner`], `Admin` → [`AccessLevel::Edit`],
+ /// `Member` → [`AccessLevel::View`]. Hidden companies are invisible to
+ /// plain members (returns `None`) but reachable by admins and owners.
+ fn get_crm_company_access(
+ &self,
+ company_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
+ /// Get the access level a user has for a CRM contact.
+ ///
+ /// Access derives from the user's role on the team that owns the contact's
+ /// parent company, with the same role-to-level mapping as
+ /// [`Self::get_crm_company_access`]. Hidden contacts (or contacts whose
+ /// parent company is hidden) are invisible to plain members.
+ fn get_crm_contact_access(
+ &self,
+ contact_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
/// Check if a user is a member of the specified channels.
///
/// Returns the subset of channel_ids that the user is a participant of.
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
index 0d5bf8df50..b2403691b5 100644
--- a/rust/cloud-storage/entity_access/src/domain/service.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -94,6 +94,24 @@ where
}
}
+ /// Get access level for a CRM company via the user's team membership.
+ async fn get_crm_company_access(
+ &self,
+ entity_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ self.repo.get_crm_company_access(entity_id, user_id).await
+ }
+
+ /// Get access level for a CRM contact via its parent company's team.
+ async fn get_crm_contact_access(
+ &self,
+ entity_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ self.repo.get_crm_contact_access(entity_id, user_id).await
+ }
+
/// Resolve a call id string to the channel id that owns it.
///
/// Looks up both the active `calls` table and the archived `call_records`
@@ -160,12 +178,12 @@ where
}
EntityType::Channel => self.get_channel_access(entity_id, user_id).await,
EntityType::ForeignEntity => self.get_foreign_entity_access(entity_id, user_id).await,
+ EntityType::CrmCompany => self.get_crm_company_access(entity_id, user_id).await,
+ EntityType::CrmContact => self.get_crm_contact_access(entity_id, user_id).await,
// Static files are always viewable. This is wrong for owners
EntityType::StaticFile => Ok(Some(AccessLevel::View)),
// These entity types don't have access checks implemented yet.
EntityType::Team | EntityType::User => Ok(None),
- // CRM companies are gated by team membership, not entity_access.
- EntityType::CrmCompany => Ok(None),
}
}
@@ -236,6 +254,24 @@ where
None => Err(AccessError::Unauthorized),
}
}
+ EntityType::CrmCompany => {
+ let access = self.get_crm_company_access(entity_id, user_id).await?;
+ match access {
+ Some(level) => Ok(EntityPermission::AccessLevel {
+ access_level: level,
+ }),
+ None => Err(AccessError::Unauthorized),
+ }
+ }
+ EntityType::CrmContact => {
+ let access = self.get_crm_contact_access(entity_id, user_id).await?;
+ match access {
+ Some(level) => Ok(EntityPermission::AccessLevel {
+ access_level: level,
+ }),
+ None => Err(AccessError::Unauthorized),
+ }
+ }
EntityType::Channel => {
let channel_uuid = Uuid::from_str(entity_id)
.map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;
diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rs
index 9838752279..0463e18be1 100644
--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs
@@ -20,6 +20,8 @@ struct MockRepo {
thread_access: Arc<Mutex<Option<AccessLevel>>>,
call_access: Arc<Mutex<Option<AccessLevel>>>,
foreign_entity_access: Arc<Mutex<bool>>,
+ crm_company_access: Arc<Mutex<Option<AccessLevel>>>,
+ crm_contact_access: Arc<Mutex<Option<AccessLevel>>>,
channel_membership: Arc<Mutex<Vec<Uuid>>>,
channel_role: Arc<Mutex<ChannelRoleResult>>,
document_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
@@ -40,6 +42,8 @@ impl MockRepo {
thread_access: Arc::new(Mutex::new(None)),
call_access: Arc::new(Mutex::new(None)),
foreign_entity_access: Arc::new(Mutex::new(false)),
+ crm_company_access: Arc::new(Mutex::new(None)),
+ crm_contact_access: Arc::new(Mutex::new(None)),
channel_membership: Arc::new(Mutex::new(vec![])),
channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),
document_users: Arc::new(Mutex::new(vec![])),
@@ -83,6 +87,18 @@ impl MockRepo {
self
}
+ #[allow(dead_code)]
+ fn with_crm_company_access(mut self, level: AccessLevel) -> Self {
+ self.crm_company_access = Arc::new(Mutex::new(Some(level)));
+ self
+ }
+
+ #[allow(dead_code)]
+ fn with_crm_contact_access(mut self, level: AccessLevel) -> Self {
+ self.crm_contact_access = Arc::new(Mutex::new(Some(level)));
+ self
+ }
+
fn with_channel_membership(mut self, channels: Vec<Uuid>) -> Self {
self.channel_membership = Arc::new(Mutex::new(channels));
self
@@ -180,6 +196,22 @@ impl AccessRepository for MockRepo {
Ok(*self.foreign_entity_access.lock().await)
}
+ async fn get_crm_company_access(
+ &self,
+ _company_id: &str,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(*self.crm_company_access.lock().await)
+ }
+
+ async fn get_crm_contact_access(
+ &self,
+ _contact_id: &str,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(*self.crm_contact_access.lock().await)
+ }
+
async fn get_entity_users(
&self,
_entity_id: &uuid::Uuid,
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/crm_company.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/crm_company.rs
new file mode 100644
index 0000000000..6c0d5109eb
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/crm_company.rs
@@ -0,0 +1,111 @@
+//! CRM company access extractor.
+
+use std::collections::HashMap;
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ RequestPartsExt,
+ extract::{FromRef, FromRequestParts, Path},
+ http::request::Parts,
+};
+use uuid::Uuid;
+
+use super::{ExtractorError, RequiredPermission};
+use crate::domain::{
+ models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityType},
+ ports::EntityAccessService,
+};
+use model_user::axum_extractor::MacroUserExtractor;
+
+/// Validates that the user satisfies the required permission for a CRM
+/// company and exposes the owning `team_id` for downstream service calls.
+///
+/// Access derives from the caller's role on the owning team: team owners
+/// get `Owner`, admins get `Edit`, members get `View`. Hidden companies are
+/// invisible to plain members — the extractor returns `Unauthorized` rather
+/// than leak existence.
+///
+/// Reads `company_id` from the path. The owning `team_id` is resolved via
+/// the user's `team_user` membership so handlers can keep passing it to
+/// existing team-scoped service methods without a second query in the
+/// handler.
+#[derive(Debug)]
+pub struct CrmCompanyAccessLevelExtractor<T: RequiredPermission, Svc> {
+ /// The entity access receipt.
+ pub entity_access_receipt: EntityAccessReceipt<T>,
+ /// The id of the team that owns the company. Looked up alongside the
+ /// access check so handlers don't need to re-query.
+ pub team_id: Uuid,
+ _marker: PhantomData<(T, Svc)>,
+}
+
+impl<T, S, Svc> FromRequestParts<S> for CrmCompanyAccessLevelExtractor<T, Svc>
+where
+ T: RequiredPermission,
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = ExtractorError;
+
+ #[tracing::instrument(err, skip(state, parts))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let service = <Arc<Svc>>::from_ref(state);
+
+ let Path(path_params): Path<HashMap<String, String>> = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::BadRequest("missing company_id path parameter"))?;
+ let company_id = extract_company_id(&path_params)?.to_string();
+
+ let MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Unauthorized)?;
+
+ let permission = service
+ .get_entity_permission(
+ Some(&macro_user_id),
+ &company_id,
+ EntityType::CrmCompany,
+ None,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ let team_id = service
+ .get_user_team(&macro_user_id)
+ .await
+ .map_err(ExtractorError::from)?
+ .ok_or(ExtractorError::Unauthorized)?
+ .team_id;
+
+ Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: company_id,
+ entity_type: EntityType::CrmCompany,
+ },
+ auth: EntityAccessAuth::Authenticated(macro_user_id),
+ entity_permission: permission,
+ _marker: PhantomData,
+ },
+ team_id,
+ _marker: PhantomData,
+ })
+ }
+}
+
+fn extract_company_id(path_params: &HashMap<String, String>) -> Result<Uuid, ExtractorError> {
+ let raw_id = path_params
+ .get("company_id")
+ .ok_or(ExtractorError::BadRequest(
+ "missing company_id path parameter",
+ ))?;
+ Uuid::parse_str(raw_id).map_err(|_| ExtractorError::BadRequest("invalid CRM company ID format"))
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/crm_contact.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/crm_contact.rs
new file mode 100644
index 0000000000..67e7b39640
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/crm_contact.rs
@@ -0,0 +1,109 @@
+//! CRM contact access extractor.
+
+use std::collections::HashMap;
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ RequestPartsExt,
+ extract::{FromRef, FromRequestParts, Path},
+ http::request::Parts,
+};
+use uuid::Uuid;
+
+use super::{ExtractorError, RequiredPermission};
+use crate::domain::{
+ models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityType},
+ ports::EntityAccessService,
+};
+use model_user::axum_extractor::MacroUserExtractor;
+
+/// Validates that the user satisfies the required permission for a CRM
+/// contact and exposes the owning `team_id` for downstream service calls.
+///
+/// Access derives from the caller's role on the team that owns the
+/// contact's parent company, with the same role-to-level mapping as
+/// [`super::CrmCompanyAccessLevelExtractor`]. Hidden contacts (or
+/// contacts whose parent company is hidden) are invisible to plain
+/// members.
+///
+/// Reads `contact_id` from the path. The owning `team_id` is resolved via
+/// the user's `team_user` membership so handlers don't need to re-query.
+#[derive(Debug)]
+pub struct CrmContactAccessLevelExtractor<T: RequiredPermission, Svc> {
+ /// The entity access receipt.
+ pub entity_access_receipt: EntityAccessReceipt<T>,
+ /// The id of the team that owns the contact (via its parent company).
+ pub team_id: Uuid,
+ _marker: PhantomData<(T, Svc)>,
+}
+
+impl<T, S, Svc> FromRequestParts<S> for CrmContactAccessLevelExtractor<T, Svc>
+where
+ T: RequiredPermission,
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = ExtractorError;
+
+ #[tracing::instrument(err, skip(state, parts))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let service = <Arc<Svc>>::from_ref(state);
+
+ let Path(path_params): Path<HashMap<String, String>> = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::BadRequest("missing contact_id path parameter"))?;
+ let contact_id = extract_contact_id(&path_params)?.to_string();
+
+ let MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Unauthorized)?;
+
+ let permission = service
+ .get_entity_permission(
+ Some(&macro_user_id),
+ &contact_id,
+ EntityType::CrmContact,
+ None,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ let team_id = service
+ .get_user_team(&macro_user_id)
+ .await
+ .map_err(ExtractorError::from)?
+ .ok_or(ExtractorError::Unauthorized)?
+ .team_id;
+
+ Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: contact_id,
+ entity_type: EntityType::CrmContact,
+ },
+ auth: EntityAccessAuth::Authenticated(macro_user_id),
+ entity_permission: permission,
+ _marker: PhantomData,
+ },
+ team_id,
+ _marker: PhantomData,
+ })
+ }
+}
+
+fn extract_contact_id(path_params: &HashMap<String, String>) -> Result<Uuid, ExtractorError> {
+ let raw_id = path_params
+ .get("contact_id")
+ .ok_or(ExtractorError::BadRequest(
+ "missing contact_id path parameter",
+ ))?;
+ Uuid::parse_str(raw_id).map_err(|_| ExtractorError::BadRequest("invalid CRM contact ID format"))
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
index 1a33c7e478..d7afed5522 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
@@ -6,6 +6,8 @@
mod call;
mod channel;
mod chat;
+mod crm_company;
+mod crm_contact;
mod document;
mod entity_permission;
mod foreign_entity;
@@ -18,6 +20,8 @@ mod thread;
pub use call::{CallAccessLevelExtractor, CallWithChannelIdAccessLevelExtractor};
pub use channel::ChannelAccessLevelExtractor;
pub use chat::ChatAccessLevelExtractor;
+pub use crm_company::CrmCompanyAccessLevelExtractor;
+pub use crm_contact::CrmContactAccessLevelExtractor;
pub use document::DocumentAccessExtractor;
pub use entity_permission::EntityPermissionExtractor;
pub use foreign_entity::ForeignEntityAccessLevelExtractor;
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
index b40e107c89..3f8cf375d3 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
@@ -159,6 +159,42 @@ impl AccessRepository for PgAccessRepository {
.await?)
}
+ #[tracing::instrument(err, skip(self))]
+ async fn get_crm_company_access(
+ &self,
+ company_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ let company_uuid = company_id
+ .parse::<Uuid>()
+ .map_err(|_| AccessError::BadRequest("Invalid CRM company ID format"))?;
+ let Some(user_id) = user_id else {
+ return Ok(None);
+ };
+ Ok(
+ queries::crm_company_access::get_crm_company_access(&self.pool, &company_uuid, user_id)
+ .await?,
+ )
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_crm_contact_access(
+ &self,
+ contact_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ let contact_uuid = contact_id
+ .parse::<Uuid>()
+ .map_err(|_| AccessError::BadRequest("Invalid CRM contact ID format"))?;
+ let Some(user_id) = user_id else {
+ return Ok(None);
+ };
+ Ok(
+ queries::crm_contact_access::get_crm_contact_access(&self.pool, &contact_uuid, user_id)
+ .await?,
+ )
+ }
+
#[tracing::instrument(err, skip(self))]
async fn check_user_channel_membership(
&self,
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/crm_company_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/crm_company_access.rs
new file mode 100644
index 0000000000..08f04dbe18
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/crm_company_access.rs
@@ -0,0 +1,50 @@
+//! Query for CRM company access level.
+
+use crate::domain::models::{AccessLevel, TeamRole};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// Resolve the access level a user has for a CRM company.
+///
+/// Joins `crm_companies` against the user's `team_user` row on the owning
+/// team. Returns `None` when the user is not on that team, or when the
+/// company is hidden and the user is a plain member.
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_crm_company_access(
+ pool: &PgPool,
+ company_id: &Uuid,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ c.hidden AS "hidden!",
+ tu.team_role AS "role!: TeamRole"
+ FROM crm_companies c
+ JOIN team_user tu
+ ON tu.team_id = c.team_id
+ AND tu.user_id = $1
+ WHERE c.id = $2
+ "#,
+ user_id.as_ref(),
+ company_id,
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(row.and_then(|r| team_role_to_access_level(r.role, r.hidden)))
+}
+
+/// Map a team role + hidden flag to an [`AccessLevel`].
+///
+/// Hidden CRM rows are invisible to plain members; admins and owners keep
+/// their normal access.
+pub(super) fn team_role_to_access_level(role: TeamRole, hidden: bool) -> Option<AccessLevel> {
+ match (role, hidden) {
+ (TeamRole::Member, true) => None,
+ (TeamRole::Member, false) => Some(AccessLevel::View),
+ (TeamRole::Admin, _) => Some(AccessLevel::Edit),
+ (TeamRole::Owner, _) => Some(AccessLevel::Owner),
+ }
+}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access.rs
new file mode 100644
index 0000000000..7305af8fba
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access.rs
@@ -0,0 +1,42 @@
+//! Query for CRM contact access level.
+
+use crate::domain::models::{AccessLevel, TeamRole};
+use crate::outbound::pg_access_repo::queries::crm_company_access::team_role_to_access_level;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// Resolve the access level a user has for a CRM contact.
+///
+/// Joins `crm_contacts` through its parent `crm_companies` row to the user's
+/// `team_user` membership on the owning team. Returns `None` when the user
+/// is not on that team, or when the contact (or its parent company) is
+/// hidden and the user is a plain member — hiding a company cascades to
+/// its contacts, so either flag suppresses access.
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_crm_contact_access(
+ pool: &PgPool,
+ contact_id: &Uuid,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ (ct.hidden OR c.hidden) AS "hidden!",
+ tu.team_role AS "role!: TeamRole"
+ FROM crm_contacts ct
+ JOIN crm_companies c
+ ON c.id = ct.company_id
+ JOIN team_user tu
+ ON tu.team_id = c.team_id
+ AND tu.user_id = $1
+ WHERE ct.id = $2
+ "#,
+ user_id.as_ref(),
+ contact_id,
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(row.and_then(|r| team_role_to_access_level(r.role, r.hidden)))
+}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs
index 90532713a4..a2297bd213 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs
@@ -21,6 +21,8 @@ pub mod channel_membership;
pub mod channel_role;
pub mod channel_users;
pub mod chat_access;
+pub mod crm_company_access;
+pub mod crm_contact_access;
pub mod document_access;
pub mod foreign_entity_access;
pub mod project_access;
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/test.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/test.rs
index 56a4b6871b..db05034db5 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/test.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/test.rs
@@ -1,5 +1,8 @@
use super::PgAccessRepository;
-use crate::domain::{models::AccessError, ports::AccessRepository};
+use crate::domain::{
+ models::{AccessError, AccessLevel},
+ ports::AccessRepository,
+};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
@@ -8,7 +11,10 @@ use uuid::Uuid;
const TEAM_ALPHA: &str = "00000000-0000-0000-0000-0000000ea001";
const TEAM_BETA: &str = "00000000-0000-0000-0000-0000000ea002";
const TEAM_MEMBER: &str = "macro|[email protected]";
+const TEAM_ADMIN: &str = "macro|[email protected]";
+const TEAM_OWNER: &str = "macro|[email protected]";
const USER_WITHOUT_TEAM: &str = "macro|[email protected]";
+const TEAM_BETA_OWNER: &str = "macro|[email protected]";
fn user_id(value: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(value.to_string()).unwrap()
@@ -164,3 +170,231 @@ async fn rejects_invalid_uuid(pool: PgPool) -> anyhow::Result<()> {
));
Ok(())
}
+
+// --------------------------------------------------------------------------
+// CRM company + contact access
+// --------------------------------------------------------------------------
+
+async fn insert_crm_company(pool: &PgPool, team_id: &str, hidden: bool) -> anyhow::Result<Uuid> {
+ let id = Uuid::new_v4();
+ sqlx::query!(
+ r#"
+ INSERT INTO crm_companies (id, team_id, hidden, first_interaction, last_interaction)
+ VALUES ($1, $2, $3, now(), now())
+ "#,
+ id,
+ Uuid::parse_str(team_id)?,
+ hidden,
+ )
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn insert_crm_contact(pool: &PgPool, company_id: Uuid, hidden: bool) -> anyhow::Result<Uuid> {
+ let id = Uuid::new_v4();
+ sqlx::query!(
+ r#"
+ INSERT INTO crm_contacts (id, company_id, email, hidden, first_interaction, last_interaction)
+ VALUES ($1, $2, $3, $4, now(), now())
+ "#,
+ id,
+ company_id,
+ format!("contact-{id}@example.com"),
+ hidden,
+ )
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_company_access_maps_team_role_to_access_level(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = insert_crm_company(&pool, TEAM_ALPHA, false).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ let cases = [
+ (TEAM_MEMBER, Some(AccessLevel::View)),
+ (TEAM_ADMIN, Some(AccessLevel::Edit)),
+ (TEAM_OWNER, Some(AccessLevel::Owner)),
+ ];
+ for (uid, expected) in cases {
+ let actual = repo
+ .get_crm_company_access(&company_id.to_string(), Some(&user_id(uid)))
+ .await?;
+ assert_eq!(actual, expected, "user {uid}");
+ }
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_company_access_hides_from_member_when_hidden(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = insert_crm_company(&pool, TEAM_ALPHA, true).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ assert_eq!(
+ repo.get_crm_company_access(&company_id.to_string(), Some(&user_id(TEAM_MEMBER)))
+ .await?,
+ None,
+ );
+ assert_eq!(
+ repo.get_crm_company_access(&company_id.to_string(), Some(&user_id(TEAM_ADMIN)))
+ .await?,
+ Some(AccessLevel::Edit),
+ );
+ assert_eq!(
+ repo.get_crm_company_access(&company_id.to_string(), Some(&user_id(TEAM_OWNER)))
+ .await?,
+ Some(AccessLevel::Owner),
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_company_access_denies_other_team(pool: PgPool) -> anyhow::Result<()> {
+ let alpha_company = insert_crm_company(&pool, TEAM_ALPHA, false).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ // Beta's owner has no role on Alpha → no access to an Alpha company.
+ let actual = repo
+ .get_crm_company_access(&alpha_company.to_string(), Some(&user_id(TEAM_BETA_OWNER)))
+ .await?;
+ assert_eq!(actual, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_company_access_denies_anonymous(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = insert_crm_company(&pool, TEAM_ALPHA, false).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ let actual = repo
+ .get_crm_company_access(&company_id.to_string(), None)
+ .await?;
+ assert_eq!(actual, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_company_access_rejects_invalid_uuid(pool: PgPool) -> anyhow::Result<()> {
+ let repo = PgAccessRepository::new(pool);
+ let err = repo
+ .get_crm_company_access("not-a-uuid", Some(&user_id(TEAM_MEMBER)))
+ .await
+ .expect_err("invalid UUID should be rejected");
+ assert!(matches!(
+ err,
+ AccessError::BadRequest("Invalid CRM company ID format")
+ ));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_contact_access_maps_team_role_to_access_level(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = insert_crm_company(&pool, TEAM_ALPHA, false).await?;
+ let contact_id = insert_crm_contact(&pool, company_id, false).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ let cases = [
+ (TEAM_MEMBER, Some(AccessLevel::View)),
+ (TEAM_ADMIN, Some(AccessLevel::Edit)),
+ (TEAM_OWNER, Some(AccessLevel::Owner)),
+ ];
+ for (uid, expected) in cases {
+ let actual = repo
+ .get_crm_contact_access(&contact_id.to_string(), Some(&user_id(uid)))
+ .await?;
+ assert_eq!(actual, expected, "user {uid}");
+ }
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_contact_access_hidden_contact_blocks_member(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = insert_crm_company(&pool, TEAM_ALPHA, false).await?;
+ let contact_id = insert_crm_contact(&pool, company_id, true).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ assert_eq!(
+ repo.get_crm_contact_access(&contact_id.to_string(), Some(&user_id(TEAM_MEMBER)))
+ .await?,
+ None,
+ );
+ assert_eq!(
+ repo.get_crm_contact_access(&contact_id.to_string(), Some(&user_id(TEAM_ADMIN)))
+ .await?,
+ Some(AccessLevel::Edit),
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_contact_access_hidden_company_cascades_to_contact(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = insert_crm_company(&pool, TEAM_ALPHA, true).await?;
+ let contact_id = insert_crm_contact(&pool, company_id, false).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ assert_eq!(
+ repo.get_crm_contact_access(&contact_id.to_string(), Some(&user_id(TEAM_MEMBER)))
+ .await?,
+ None,
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_contact_access_denies_other_team(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = insert_crm_company(&pool, TEAM_ALPHA, false).await?;
+ let contact_id = insert_crm_contact(&pool, company_id, false).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ let actual = repo
+ .get_crm_contact_access(&contact_id.to_string(), Some(&user_id(TEAM_BETA_OWNER)))
+ .await?;
+ assert_eq!(actual, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn crm_contact_access_rejects_invalid_uuid(pool: PgPool) -> anyhow::Result<()> {
+ let repo = PgAccessRepository::new(pool);
+ let err = repo
+ .get_crm_contact_access("not-a-uuid", Some(&user_id(TEAM_MEMBER)))
+ .await
+ .expect_err("invalid UUID should be rejected");
+ assert!(matches!(
+ err,
+ AccessError::BadRequest("Invalid CRM contact ID format")
+ ));
+ Ok(())
+}
diff --git a/rust/cloud-storage/entity_access_db_utils/src/lib.rs b/rust/cloud-storage/entity_access_db_utils/src/lib.rs
index 24dd57c8eb..d28cd0d061 100644
--- a/rust/cloud-storage/entity_access_db_utils/src/lib.rs
+++ b/rust/cloud-storage/entity_access_db_utils/src/lib.rs
@@ -225,6 +225,7 @@ pub async fn update_entity_access_channel_share_permissions(
| EntityType::Channel
| EntityType::StaticFile
| EntityType::CrmCompany
+ | EntityType::CrmContact
| EntityType::ForeignEntity => unreachable!(),
EntityType::Project => {
// Get all items in project
@@ -283,6 +284,7 @@ pub async fn update_entity_access_channel_share_permissions(
| EntityType::Channel
| EntityType::StaticFile
| EntityType::CrmCompany
+ | EntityType::CrmContact
| EntityType::ForeignEntity => unreachable!(),
EntityType::Project => {
// (a) Direct grant on the project itself (granted_from_project_id IS NULL)
diff --git a/rust/cloud-storage/macro_db_client/src/item_access/delete.rs b/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
index ba43ce9f3e..307716debb 100644
--- a/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
+++ b/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
@@ -38,6 +38,7 @@ pub async fn delete_user_entity_access_bulk(
| EntityType::Channel
| EntityType::StaticFile
| EntityType::CrmCompany
+ | EntityType::CrmContact
| EntityType::ForeignEntity => {
anyhow::bail!("invalid entity type")
}
diff --git a/rust/cloud-storage/model-entity/src/lib.rs b/rust/cloud-storage/model-entity/src/lib.rs
index b1923b65ec..f0469701e8 100644
--- a/rust/cloud-storage/model-entity/src/lib.rs
+++ b/rust/cloud-storage/model-entity/src/lib.rs
@@ -54,6 +54,8 @@ pub enum EntityType {
StaticFile,
/// The entity is a CRM company tracked by a team
CrmCompany,
+ /// The entity is a CRM contact tracked by a team
+ CrmContact,
}
impl EntityType {
@@ -73,8 +75,10 @@ impl EntityType {
EntityType::Call => true,
EntityType::ForeignEntity => false,
EntityType::StaticFile => false,
- // CRM companies are gated by team membership, not entity_access.
+ // CRM companies/contacts derive access via team membership joins
+ // — they aren't rows in the `entity_access` table.
EntityType::CrmCompany => false,
+ EntityType::CrmContact => false,
}
}
/// provide an entity string slice to upgrade this type into an [Entity]