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.

refactor(crm): gate CRM service methods with capability-token receipts (#3766)

Evan Hutnik139bc4a2b116
diff --git a/rust/cloud-storage/.sqlx/query-b507630afbc72830ecf99356f004253f29af4b7c35df0bcff830cfc9b6cb9ee4.json b/rust/cloud-storage/.sqlx/query-060ac46a89df4da317917f28ca8d95dc07b98f4a64effa9b76d58089fb0728b1.json
similarity index 60%
rename from rust/cloud-storage/.sqlx/query-b507630afbc72830ecf99356f004253f29af4b7c35df0bcff830cfc9b6cb9ee4.json
rename to rust/cloud-storage/.sqlx/query-060ac46a89df4da317917f28ca8d95dc07b98f4a64effa9b76d58089fb0728b1.json
index 7934632c48..d763e29e78 100644
--- a/rust/cloud-storage/.sqlx/query-b507630afbc72830ecf99356f004253f29af4b7c35df0bcff830cfc9b6cb9ee4.json
+++ b/rust/cloud-storage/.sqlx/query-060ac46a89df4da317917f28ca8d95dc07b98f4a64effa9b76d58089fb0728b1.json
@@ -1,6 +1,6 @@
{
"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 ",
+ "query": "\n SELECT\n c.hidden AS \"hidden!\",\n c.team_id AS \"team_id!\",\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": [
{
@@ -10,6 +10,11 @@
},
{
"ordinal": 1,
+ "name": "team_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
"name": "role!: TeamRole",
"type_info": {
"Custom": {
@@ -32,9 +37,10 @@
]
},
"nullable": [
+ false,
false,
false
]
},
- "hash": "b507630afbc72830ecf99356f004253f29af4b7c35df0bcff830cfc9b6cb9ee4"
+ "hash": "060ac46a89df4da317917f28ca8d95dc07b98f4a64effa9b76d58089fb0728b1"
}
diff --git a/rust/cloud-storage/.sqlx/query-4dcee20753a8996e6dfab48fc0dcb6ab0ea074976d13639ccc6d6932f79fae13.json b/rust/cloud-storage/.sqlx/query-4dcee20753a8996e6dfab48fc0dcb6ab0ea074976d13639ccc6d6932f79fae13.json
new file mode 100644
index 0000000000..c1dc3557e2
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-4dcee20753a8996e6dfab48fc0dcb6ab0ea074976d13639ccc6d6932f79fae13.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT c.owner\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 AND (\n EXISTS (\n SELECT 1 FROM crm_companies co\n WHERE co.id = t.company_id\n AND co.team_id = $2\n AND ($3 OR co.hidden = FALSE)\n )\n OR EXISTS (\n SELECT 1 FROM crm_contacts ct\n JOIN crm_companies co2 ON co2.id = ct.company_id\n WHERE ct.id = t.contact_id\n AND co2.team_id = $2\n AND ($3 OR (ct.hidden = FALSE AND co2.hidden = FALSE))\n )\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "4dcee20753a8996e6dfab48fc0dcb6ab0ea074976d13639ccc6d6932f79fae13"
+}
diff --git a/rust/cloud-storage/.sqlx/query-0643eed420f0f10eab30aa91b17d858d0f765ba260e5fa84edf3741df03f6566.json b/rust/cloud-storage/.sqlx/query-ae7424712141289a46985ef940f940ba795df321fe73b299eac464a0ef6a3081.json
similarity index 56%
rename from rust/cloud-storage/.sqlx/query-0643eed420f0f10eab30aa91b17d858d0f765ba260e5fa84edf3741df03f6566.json
rename to rust/cloud-storage/.sqlx/query-ae7424712141289a46985ef940f940ba795df321fe73b299eac464a0ef6a3081.json
index e706732669..910cee7485 100644
--- a/rust/cloud-storage/.sqlx/query-0643eed420f0f10eab30aa91b17d858d0f765ba260e5fa84edf3741df03f6566.json
+++ b/rust/cloud-storage/.sqlx/query-ae7424712141289a46985ef940f940ba795df321fe73b299eac464a0ef6a3081.json
@@ -1,6 +1,6 @@
{
"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 ",
+ "query": "\n SELECT\n (ct.hidden OR c.hidden) AS \"hidden!\",\n c.team_id AS \"team_id!\",\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": [
{
@@ -10,6 +10,11 @@
},
{
"ordinal": 1,
+ "name": "team_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
"name": "role!: TeamRole",
"type_info": {
"Custom": {
@@ -33,8 +38,9 @@
},
"nullable": [
null,
+ false,
false
]
},
- "hash": "0643eed420f0f10eab30aa91b17d858d0f765ba260e5fa84edf3741df03f6566"
+ "hash": "ae7424712141289a46985ef940f940ba795df321fe73b299eac464a0ef6a3081"
}
diff --git a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs
index d4214c0dfb..52f567e699 100644
--- a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs
@@ -207,6 +207,15 @@ impl EntityAccessService for TestAccessService {
Ok(EntityPermission::ChannelRole { role: self.role })
}
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<(EntityPermission, uuid::Uuid), AccessError> {
+ unimplemented!("bots test mock does not support CRM entity access")
+ }
+
async fn get_users_by_entity(
&self,
_entity_id: &str,
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index 3780f3d772..0266c2afb3 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -151,6 +151,15 @@ impl EntityAccessService for TestAccessService {
}
}
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<(EntityPermission, uuid::Uuid), AccessError> {
+ unimplemented!("channels test mock does not support CRM entity access")
+ }
+
async fn get_call_channel(
&self,
_call_id: &Uuid,
diff --git a/rust/cloud-storage/chat/src/inbound/test.rs b/rust/cloud-storage/chat/src/inbound/test.rs
index 9f7f252a43..79b147dd6d 100644
--- a/rust/cloud-storage/chat/src/inbound/test.rs
+++ b/rust/cloud-storage/chat/src/inbound/test.rs
@@ -400,6 +400,15 @@ impl EntityAccessService for MockAccessService {
})
}
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<(EntityPermission, uuid::Uuid), AccessError> {
+ unimplemented!("chat test mock does not support CRM entity access")
+ }
+
async fn get_users_by_entity(
&self,
_entity_id: &str,
diff --git a/rust/cloud-storage/crm/src/domain.rs b/rust/cloud-storage/crm/src/domain.rs
index 9931a67484..aec1f2a614 100644
--- a/rust/cloud-storage/crm/src/domain.rs
+++ b/rust/cloud-storage/crm/src/domain.rs
@@ -18,3 +18,7 @@ pub mod company_metadata_resolver;
/// The CRM service trait and implementation
#[cfg(feature = "ports")]
pub mod service;
+
+/// Capability-token receipt wrappers gating per-entity CRM service calls
+#[cfg(feature = "ports")]
+pub mod auth;
diff --git a/rust/cloud-storage/crm/src/domain/auth.rs b/rust/cloud-storage/crm/src/domain/auth.rs
new file mode 100644
index 0000000000..4f9317277d
--- /dev/null
+++ b/rust/cloud-storage/crm/src/domain/auth.rs
@@ -0,0 +1,285 @@
+//! Capability tokens for authorized CRM service calls.
+//!
+//! Each per-entity / per-team CRM service method takes one of these
+//! receipt wrappers instead of raw ids. A receipt bundles a verified
+//! [`EntityAccessReceipt`] — the capability, mintable only by the
+//! `entity_access` trusted seam — with the owning `team_id` the CRM
+//! repository scopes its queries by. Holding a receipt is a
+//! compile-time proof that the caller passed the access check for the
+//! entity it addresses; there is no way to call a per-entity CRM method
+//! with a bare UUID.
+//!
+//! The company / contact / comment receipts are minted by the CRM
+//! access extractors in [`crate::inbound::axum_extractors`] via
+//! crate-private constructors. [`CrmTeamReceipt::from_team_receipt`] is
+//! public because the team receipt it wraps is itself the capability
+//! (only `entity_access` can produce one) and the team id is derived
+//! from it — there is nothing to forge. The `dangerously_internal`
+//! constructors are test-only (`cfg(test)`, crate-private): no production
+//! caller can mint a receipt without passing an access check.
+
+use entity_access::domain::models::{
+ AccessLevel, EntityAccessReceipt, EntityType, RequiredPermission,
+};
+use uuid::Uuid;
+
+use crate::domain::{comment::CrmCommentEntityType, model::CrmError};
+
+#[cfg(test)]
+mod test;
+
+/// Capability token for a CRM service call addressing a single company.
+///
+/// `receipt`'s entity is the `CrmCompany`; `team_id` is the owning team,
+/// resolved at mint time.
+#[derive(Debug)]
+pub struct CrmCompanyReceipt<T: RequiredPermission> {
+ receipt: EntityAccessReceipt<T>,
+ team_id: Uuid,
+}
+
+impl<T: RequiredPermission> CrmCompanyReceipt<T> {
+ /// Mint a company receipt. Crate-private so only the CRM access
+ /// extractors can produce one off a verified access check. Unused
+ /// when the extractor seam (`axum`) isn't compiled (e.g. crm pulled
+ /// in for `ports` only).
+ #[cfg_attr(not(feature = "axum"), allow(dead_code))]
+ pub(crate) fn new(receipt: EntityAccessReceipt<T>, team_id: Uuid) -> Self {
+ Self { receipt, team_id }
+ }
+
+ /// The owning team the repository scopes its query by.
+ pub fn team_id(&self) -> Uuid {
+ self.team_id
+ }
+
+ /// The underlying verified access receipt.
+ pub fn receipt(&self) -> &EntityAccessReceipt<T> {
+ &self.receipt
+ }
+
+ /// The addressed company id. Errors if the receipt is not for a
+ /// `CrmCompany` (defensive — the type is only minted for company
+ /// receipts) or the id is malformed.
+ pub(crate) fn company_id(&self) -> Result<Uuid, CrmError> {
+ if self.receipt.entity().entity_type != EntityType::CrmCompany {
+ return Err(CrmError::InvalidRequest(
+ "receipt is not for a CrmCompany".into(),
+ ));
+ }
+ Uuid::parse_str(&self.receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidRequest("invalid company id".into()))
+ }
+
+ /// Whether the caller's role reveals hidden rows (Edit+).
+ pub(crate) fn include_hidden(&self) -> bool {
+ self.receipt
+ .entity_permission()
+ .allows_access_level(AccessLevel::Edit)
+ }
+
+ /// Test-only: mints an `Owner` receipt with no access check.
+ #[cfg(test)]
+ pub(crate) fn dangerously_internal(company_id: Uuid, team_id: Uuid) -> Self {
+ Self {
+ receipt: EntityAccessReceipt::dangerously_assert_internal_user(
+ &company_id.to_string(),
+ EntityType::CrmCompany,
+ ),
+ team_id,
+ }
+ }
+}
+
+/// Capability token for a CRM service call addressing a single contact.
+///
+/// `receipt`'s entity is the `CrmContact`; `team_id` is the team that
+/// owns the contact's parent company, resolved at mint time.
+#[derive(Debug)]
+pub struct CrmContactReceipt<T: RequiredPermission> {
+ receipt: EntityAccessReceipt<T>,
+ team_id: Uuid,
+}
+
+impl<T: RequiredPermission> CrmContactReceipt<T> {
+ /// Mint a contact receipt. Crate-private so only the CRM access
+ /// extractors can produce one off a verified access check. Unused
+ /// when the extractor seam (`axum`) isn't compiled.
+ #[cfg_attr(not(feature = "axum"), allow(dead_code))]
+ pub(crate) fn new(receipt: EntityAccessReceipt<T>, team_id: Uuid) -> Self {
+ Self { receipt, team_id }
+ }
+
+ /// The owning team the repository scopes its query by.
+ pub fn team_id(&self) -> Uuid {
+ self.team_id
+ }
+
+ /// The underlying verified access receipt.
+ pub fn receipt(&self) -> &EntityAccessReceipt<T> {
+ &self.receipt
+ }
+
+ /// The addressed contact id. Errors if the receipt is not for a
+ /// `CrmContact` (defensive) or the id is malformed.
+ pub(crate) fn contact_id(&self) -> Result<Uuid, CrmError> {
+ if self.receipt.entity().entity_type != EntityType::CrmContact {
+ return Err(CrmError::InvalidRequest(
+ "receipt is not for a CrmContact".into(),
+ ));
+ }
+ Uuid::parse_str(&self.receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidRequest("invalid contact id".into()))
+ }
+
+ /// Whether the caller's role reveals hidden rows (Edit+).
+ pub(crate) fn include_hidden(&self) -> bool {
+ self.receipt
+ .entity_permission()
+ .allows_access_level(AccessLevel::Edit)
+ }
+
+ /// Test-only: mints an `Owner` receipt with no access check.
+ #[cfg(test)]
+ #[allow(dead_code)]
+ pub(crate) fn dangerously_internal(contact_id: Uuid, team_id: Uuid) -> Self {
+ Self {
+ receipt: EntityAccessReceipt::dangerously_assert_internal_user(
+ &contact_id.to_string(),
+ EntityType::CrmContact,
+ ),
+ team_id,
+ }
+ }
+}
+
+/// Capability token for a team-level CRM service call (e.g. listing the
+/// team's companies for the soup feed) that isn't keyed on a single
+/// entity.
+///
+/// `receipt`'s entity is the `Team`; `team_id` equals its entity id.
+#[derive(Debug)]
+pub struct CrmTeamReceipt<T: RequiredPermission> {
+ receipt: EntityAccessReceipt<T>,
+ team_id: Uuid,
+}
+
+impl<T: RequiredPermission> CrmTeamReceipt<T> {
+ /// Mint from a verified team-scoped access receipt (e.g. one
+ /// produced by `MacroUserTeamExtractor`). Public because the receipt
+ /// is itself the capability and `team_id` is derived from its entity
+ /// id, so nothing can be forged. Errors if the receipt is not for a
+ /// `Team` or the id is malformed.
+ pub fn from_team_receipt(receipt: EntityAccessReceipt<T>) -> Result<Self, CrmError> {
+ if receipt.entity().entity_type != EntityType::Team {
+ return Err(CrmError::InvalidRequest("receipt is not for a Team".into()));
+ }
+ let team_id =
+ Uuid::parse_str(&receipt.entity().entity_id).map_err(|_| CrmError::InvalidTeamId)?;
+ Ok(Self { receipt, team_id })
+ }
+
+ /// The team whose records the call addresses.
+ pub fn team_id(&self) -> Uuid {
+ self.team_id
+ }
+
+ /// The underlying verified access receipt.
+ pub fn receipt(&self) -> &EntityAccessReceipt<T> {
+ &self.receipt
+ }
+
+ /// Test-only: mints an `Owner` receipt with no access check.
+ #[cfg(test)]
+ #[allow(dead_code)]
+ pub(crate) fn dangerously_internal(team_id: Uuid) -> Self {
+ Self {
+ receipt: EntityAccessReceipt::dangerously_assert_internal_user(
+ &team_id.to_string(),
+ EntityType::Team,
+ ),
+ team_id,
+ }
+ }
+}
+
+/// Capability token for a CRM comment service call. The `receipt`'s
+/// entity is the comment's owning CRM company or contact; `team_id` is
+/// the owning team, resolved at mint time.
+#[derive(Debug)]
+pub struct CrmCommentReceipt<T: RequiredPermission> {
+ receipt: EntityAccessReceipt<T>,
+ team_id: Uuid,
+}
+
+impl<T: RequiredPermission> CrmCommentReceipt<T> {
+ /// Mint a comment receipt off a verified access receipt for the
+ /// comment's owning entity. Crate-private. Errors if the receipt is
+ /// not for a CRM company or contact. Unused when the extractor seam
+ /// (`axum`) isn't compiled.
+ #[cfg_attr(not(feature = "axum"), allow(dead_code))]
+ pub(crate) fn new(receipt: EntityAccessReceipt<T>, team_id: Uuid) -> Result<Self, CrmError> {
+ match receipt.entity().entity_type {
+ EntityType::CrmCompany | EntityType::CrmContact => Ok(Self { receipt, team_id }),
+ _ => Err(CrmError::InvalidRequest(
+ "receipt is not for a CrmCompany or CrmContact".into(),
+ )),
+ }
+ }
+
+ /// The owning team the repository scopes its query by.
+ pub fn team_id(&self) -> Uuid {
+ self.team_id
+ }
+
+ /// The underlying verified access receipt.
+ pub fn receipt(&self) -> &EntityAccessReceipt<T> {
+ &self.receipt
+ }
+
+ /// Whether the caller's role reveals comments on hidden parents (Edit+).
+ pub(crate) fn include_hidden(&self) -> bool {
+ self.receipt
+ .entity_permission()
+ .allows_access_level(AccessLevel::Edit)
+ }
+
+ /// The CRM entity (type + id) the comment hangs off, derived from
+ /// the receipt. Used by create / list-threads, which key on the
+ /// owning entity rather than a comment id.
+ pub(crate) fn comment_entity(&self) -> Result<(CrmCommentEntityType, Uuid), CrmError> {
+ let entity_type = match self.receipt.entity().entity_type {
+ EntityType::CrmCompany => CrmCommentEntityType::CrmCompany,
+ EntityType::CrmContact => CrmCommentEntityType::CrmContact,
+ _ => {
+ return Err(CrmError::InvalidRequest(
+ "receipt is not for a CrmCompany or CrmContact".into(),
+ ));
+ }
+ };
+ let entity_id = Uuid::parse_str(&self.receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidRequest("invalid entity id".into()))?;
+ Ok((entity_type, entity_id))
+ }
+
+ /// Test-only: mints an `Owner` receipt with no access check.
+ #[cfg(test)]
+ #[allow(dead_code)]
+ pub(crate) fn dangerously_internal(
+ entity_type: CrmCommentEntityType,
+ entity_id: Uuid,
+ team_id: Uuid,
+ ) -> Self {
+ let et = match entity_type {
+ CrmCommentEntityType::CrmCompany => EntityType::CrmCompany,
+ CrmCommentEntityType::CrmContact => EntityType::CrmContact,
+ };
+ Self {
+ receipt: EntityAccessReceipt::dangerously_assert_internal_user(
+ &entity_id.to_string(),
+ et,
+ ),
+ team_id,
+ }
+ }
+}
diff --git a/rust/cloud-storage/crm/src/domain/auth/test.rs b/rust/cloud-storage/crm/src/domain/auth/test.rs
new file mode 100644
index 0000000000..54903e1321
--- /dev/null
+++ b/rust/cloud-storage/crm/src/domain/auth/test.rs
@@ -0,0 +1,117 @@
+use super::*;
+use entity_access::domain::models::{EntityAccessReceipt, EntityType, ViewAccessLevel};
+
+fn company_uuid() -> Uuid {
+ Uuid::from_u128(0x1111_1111_1111_1111_1111_1111_1111_1111)
+}
+
+fn team_uuid() -> Uuid {
+ Uuid::from_u128(0x2222_2222_2222_2222_2222_2222_2222_2222)
+}
+
+#[test]
+fn company_receipt_exposes_company_id_and_team() {
+ let company = company_uuid();
+ let team = team_uuid();
+ let access = CrmCompanyReceipt::<ViewAccessLevel>::new(
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &company.to_string(),
+ EntityType::CrmCompany,
+ ),
+ team,
+ );
+
+ assert_eq!(access.company_id().unwrap(), company);
+ assert_eq!(access.team_id(), team);
+ // dangerously_assert_internal_user grants Owner, which is Edit+.
+ assert!(access.include_hidden());
+}
+
+#[test]
+fn company_receipt_rejects_wrong_entity_type() {
+ let access = CrmCompanyReceipt::<ViewAccessLevel>::new(
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &company_uuid().to_string(),
+ EntityType::Team,
+ ),
+ team_uuid(),
+ );
+
+ assert!(matches!(
+ access.company_id(),
+ Err(CrmError::InvalidRequest(_))
+ ));
+}
+
+#[test]
+fn contact_receipt_exposes_contact_id() {
+ let contact = company_uuid();
+ let access = CrmContactReceipt::<ViewAccessLevel>::new(
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &contact.to_string(),
+ EntityType::CrmContact,
+ ),
+ team_uuid(),
+ );
+
+ assert_eq!(access.contact_id().unwrap(), contact);
+}
+
+#[test]
+fn team_receipt_from_team_receipt_validates_type_and_id() {
+ let team = team_uuid();
+ let ok = CrmTeamReceipt::<ViewAccessLevel>::from_team_receipt(
+ EntityAccessReceipt::dangerously_assert_internal_user(&team.to_string(), EntityType::Team),
+ )
+ .unwrap();
+ assert_eq!(ok.team_id(), team);
+
+ // Wrong entity type is rejected.
+ assert!(
+ CrmTeamReceipt::<ViewAccessLevel>::from_team_receipt(
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &team.to_string(),
+ EntityType::CrmCompany,
+ ),
+ )
+ .is_err()
+ );
+
+ // Malformed team id is rejected.
+ assert!(matches!(
+ CrmTeamReceipt::<ViewAccessLevel>::from_team_receipt(
+ EntityAccessReceipt::dangerously_assert_internal_user("not-a-uuid", EntityType::Team),
+ ),
+ Err(CrmError::InvalidTeamId)
+ ));
+}
+
+#[test]
+fn comment_receipt_derives_entity_and_rejects_non_crm() {
+ let entity = company_uuid();
+ let access = CrmCommentReceipt::<ViewAccessLevel>::new(
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &entity.to_string(),
+ EntityType::CrmContact,
+ ),
+ team_uuid(),
+ )
+ .unwrap();
+
+ assert_eq!(
+ access.comment_entity().unwrap(),
+ (CrmCommentEntityType::CrmContact, entity)
+ );
+
+ // A receipt for a non-CRM entity cannot mint a comment receipt.
+ assert!(
+ CrmCommentReceipt::<ViewAccessLevel>::new(
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &entity.to_string(),
+ EntityType::Team,
+ ),
+ team_uuid(),
+ )
+ .is_err()
+ );
+}
diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rs
index e9a1da402a..90ff74eb49 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -444,7 +444,9 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<CrmCommentThread>, CrmError>> + Send;
/// Edit a CRM comment's `text`, scoped to `team_id` via the comment's
- /// thread → entity → company. Returns the updated comment, or
+ /// thread → entity → company. Owner-only: returns
+ /// [`CrmError::CommentNotOwned`] when `requester` (the caller's macro
+ /// user id) is not the comment's author, or
/// [`CrmError::CommentNotFound`] when it doesn't exist or isn't owned by
/// the team. `include_hidden = false` (non-admin) additionally
/// returns `CommentNotFound` when the parent entity is hidden.
@@ -454,12 +456,15 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
comment_id: &uuid::Uuid,
text: &str,
include_hidden: bool,
+ requester: &str,
) -> impl Future<Output = Result<CrmComment, CrmError>> + Send;
/// Soft-delete a CRM comment (sets `deleted_at`), scoped to `team_id`.
/// When it was the thread's last live comment, the thread is
/// soft-deleted too (reported via
- /// [`DeleteCrmCommentResult::thread_deleted`]). Returns
+ /// [`DeleteCrmCommentResult::thread_deleted`]). Owner-only: returns
+ /// [`CrmError::CommentNotOwned`] when `requester` (the caller's macro
+ /// user id) is not the comment's author, or
/// [`CrmError::CommentNotFound`] when the comment doesn't exist, is
/// already deleted, or isn't owned by the team. `include_hidden =
/// false` (non-admin) additionally returns `CommentNotFound` when
@@ -469,6 +474,7 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
include_hidden: bool,
+ requester: &str,
) -> impl Future<Output = Result<DeleteCrmCommentResult, CrmError>> + Send;
/// Resolve a CRM comment to the entity its thread is attached to.
diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rs
index 1e3f6cebc8..482580fd5d 100644
--- a/rust/cloud-storage/crm/src/domain/model.rs
+++ b/rust/cloud-storage/crm/src/domain/model.rs
@@ -250,6 +250,10 @@ pub enum CrmError {
/// Comment id does not exist or does not belong to the team.
#[error("crm comment not found for team")]
CommentNotFound,
+ /// Comment exists and is visible to the caller, but they are not its
+ /// author — only the comment owner may edit or delete it.
+ #[error("crm comment not owned by caller")]
+ CommentNotOwned,
/// Request rejected for a client-side reason (e.g. blank comment text).
#[error("{0}")]
InvalidRequest(String),
diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rs
index abc51f576a..48558a100d 100644
--- a/rust/cloud-storage/crm/src/domain/service.rs
+++ b/rust/cloud-storage/crm/src/domain/service.rs
@@ -1,6 +1,7 @@
//! The CrmService trait and its default implementation.
use crate::domain::{
+ auth::{CrmCommentReceipt, CrmCompanyReceipt, CrmContactReceipt, CrmTeamReceipt},
comment::{CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult},
companies_repo::{CompaniesRepository, CrmCompanyListSort, CrmCompanySoupCursor},
company_metadata_resolver::CompanyMetadataResolver,
@@ -8,6 +9,7 @@ use crate::domain::{
model::{CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError, CrmScopePrecheck},
};
use chrono::{DateTime, Utc};
+use entity_access::domain::models::{EditAccessLevel, MemberTeamRole, ViewAccessLevel};
use serde_json::Value;
/// The CrmService exposes operations over CRM records (companies, their
@@ -127,41 +129,35 @@ pub trait CrmService: Clone + Send + Sync + 'static {
macro_id: &str,
) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;
- /// Toggle `email_sync` for `(company_id, team_id)`. Purely a
- /// visibility/permission flag — populate continues to write CRM
+ /// Toggle `email_sync` for the company addressed by `access`. Purely
+ /// a visibility/permission flag — populate continues to write CRM
/// rows regardless. See
/// [`crate::domain::companies_repo::CompaniesRepository::set_email_sync`].
- /// Authorization is the caller's responsibility.
fn set_email_sync(
&self,
- team_id: &uuid::Uuid,
- company_id: &uuid::Uuid,
+ access: &CrmCompanyReceipt<EditAccessLevel>,
email_sync: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
- /// Toggle the `hidden` flag on a CRM company for `(company_id,
- /// team_id)`. The company's contacts cascade with the flag — hide
- /// soft-hides every contact (`hidden = TRUE`), un-hide soft-restores
- /// them (`hidden = FALSE`). Contact rows and `crm_contact_sources`
- /// are preserved across the cycle. Hide additionally forces
- /// `email_sync = false`; un-hide leaves `email_sync` as-is. See
+ /// Toggle the `hidden` flag on the company addressed by `access`. The
+ /// company's contacts cascade with the flag — hide soft-hides every
+ /// contact (`hidden = TRUE`), un-hide soft-restores them (`hidden =
+ /// FALSE`). Contact rows and `crm_contact_sources` are preserved
+ /// across the cycle. Hide additionally forces `email_sync = false`;
+ /// un-hide leaves `email_sync` as-is. See
/// [`crate::domain::companies_repo::CompaniesRepository::set_company_hidden`].
- /// Authorization is the caller's responsibility.
fn set_company_hidden(
&self,
- team_id: &uuid::Uuid,
- company_id: &uuid::Uuid,
+ access: &CrmCompanyReceipt<EditAccessLevel>,
hidden: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
- /// Toggle the `hidden` flag on a CRM contact, scoped to `team_id`
- /// via the contact's company. Hiding is a display-only opt-out and
- /// does not affect populate/depopulate. Authorization is the
- /// caller's responsibility.
+ /// Toggle the `hidden` flag on the contact addressed by `access`.
+ /// Hiding is a display-only opt-out and does not affect
+ /// populate/depopulate.
fn set_contact_hidden(
&self,
- team_id: &uuid::Uuid,
- contact_id: &uuid::Uuid,
+ access: &CrmContactReceipt<EditAccessLevel>,
hidden: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
@@ -181,7 +177,7 @@ pub trait CrmService: Clone + Send + Sync + 'static {
#[allow(clippy::too_many_arguments)]
fn list_companies_for_soup(
&self,
- team_id: &uuid::Uuid,
+ access: &CrmTeamReceipt<MemberTeamRole>,
user_id: &str,
company_ids: &[uuid::Uuid],
hidden: Option<bool>,
@@ -190,102 +186,86 @@ pub trait CrmService: Clone + Send + Sync + 'static {
limit: i64,
) -> impl Future<Output = Result<Vec<CrmCompanyForSoup>, CrmError>> + Send;
- /// List a company's contacts, scoped to `team_id`. `include_hidden`
- /// reflects the caller's role: non-admin viewers pass `false`
- /// (hidden contacts filtered out, hidden parent companies 404);
- /// admin/owner pass `true` (every owned contact returned, hidden
- /// parent companies reachable). See
+ /// List the contacts of the company addressed by `access`. The
+ /// caller's role (encoded in the receipt) decides whether hidden
+ /// contacts and a hidden parent company are visible: members see
+ /// neither; admin/owner see both. See
/// [`CompaniesRepository::list_contacts_for_company`].
fn list_contacts_for_company(
&self,
- team_id: &uuid::Uuid,
- company_id: &uuid::Uuid,
- include_hidden: bool,
+ access: &CrmCompanyReceipt<ViewAccessLevel>,
) -> impl Future<Output = Result<Vec<CrmContact>, CrmError>> + Send;
- /// Fetch a single CRM contact by id, scoped to `team_id`.
- /// `include_hidden = false` hides contacts whose own `hidden` flag
- /// or whose parent company's `hidden` is set; `true` (admin/owner)
- /// reveals every owned contact. See
+ /// Fetch the contact addressed by `access`, scoped to its owning
+ /// team. The receipt's role decides whether a hidden contact (or one
+ /// under a hidden company) is revealed. See
/// [`CompaniesRepository::get_contact_for_team`].
fn get_contact_for_team(
&self,
- team_id: &uuid::Uuid,
- contact_id: &uuid::Uuid,
- include_hidden: bool,
+ access: &CrmContactReceipt<ViewAccessLevel>,
) -> impl Future<Output = Result<Option<CrmContact>, CrmError>> + Send;
- /// Fetch a single CRM company by id, scoped to `team_id`, hydrated
- /// with all domains, the primary domain's directory metadata, and
- /// the company's full contact list. `include_hidden = false` hides
- /// companies whose `hidden` flag is set and filters hidden contacts;
- /// `true` (admin/owner) reveals every owned company and contact.
- /// See [`CompaniesRepository::get_company_for_team`].
+ /// Fetch the company addressed by `access`, hydrated with all
+ /// domains, the primary domain's directory metadata, and the
+ /// company's full contact list. The receipt's role decides whether a
+ /// hidden company and hidden contacts are revealed. See
+ /// [`CompaniesRepository::get_company_for_team`].
fn get_company_for_team(
&self,
- team_id: &uuid::Uuid,
- company_id: &uuid::Uuid,
- include_hidden: bool,
+ access: &CrmCompanyReceipt<ViewAccessLevel>,
) -> impl Future<Output = Result<Option<CrmCompanyWithContacts>, CrmError>> + Send;
- /// Create a comment on a CRM company or contact, optionally as a reply
- /// to an existing thread. See
- /// [`CompaniesRepository::create_crm_comment`]. Authorization (team
- /// membership) is the caller's responsibility; the entity-ownership
- /// scoping is enforced in the repository. `include_hidden` mirrors
- /// the read side: non-admin callers can't comment on a hidden
- /// entity (`false`); admin/owner can (`true`).
+ /// Create a comment on the CRM entity addressed by `access`,
+ /// optionally as a reply to an existing thread. The owning entity
+ /// (company or contact) and `include_hidden` are derived from the
+ /// receipt; the entity-ownership scoping is enforced in the
+ /// repository. See [`CompaniesRepository::create_crm_comment`].
#[allow(clippy::too_many_arguments)]
fn create_crm_comment(
&self,
- team_id: &uuid::Uuid,
- entity_type: CrmCommentEntityType,
- entity_id: &uuid::Uuid,
+ access: &CrmCommentReceipt<ViewAccessLevel>,
owner: &str,
thread_id: Option<uuid::Uuid>,
thread_metadata: Option<Value>,
text: &str,
metadata: Option<Value>,
- include_hidden: bool,
) -> impl Future<Output = Result<CrmCommentThread, CrmError>> + Send;
- /// List a CRM entity's comment threads. `include_hidden` controls
- /// whether hidden parent entities 404 (non-admin) or are
- /// reachable (admin/owner). See
+ /// List the comment threads on the CRM entity addressed by `access`.
+ /// The receipt's role decides whether a hidden parent entity is
+ /// reachable (admin/owner) or 404s (member). See
/// [`CompaniesRepository::get_crm_comment_threads`].
fn get_crm_comment_threads(
&self,
- team_id: &uuid::Uuid,
- entity_type: CrmCommentEntityType,
- entity_id: &uuid::Uuid,
- include_hidden: bool,
+ access: &CrmCommentReceipt<ViewAccessLevel>,
) -> impl Future<Output = Result<Vec<CrmCommentThread>, CrmError>> + Send;
- /// Edit a CRM comment's text, scoped to `team_id`. `include_hidden
- /// = false` (non-admin) treats comments on hidden entities as not
- /// found. See [`CompaniesRepository::edit_crm_comment`].
+ /// Edit the text of `comment_id`, scoped to the team in `access`
+ /// (the receipt for the comment's owning entity). A member's receipt
+ /// treats comments on hidden entities as not found. See
+ /// [`CompaniesRepository::edit_crm_comment`].
fn edit_crm_comment(
&self,
- team_id: &uuid::Uuid,
+ access: &CrmCommentReceipt<ViewAccessLevel>,
comment_id: &uuid::Uuid,
text: &str,
- include_hidden: bool,
) -> impl Future<Output = Result<CrmComment, CrmError>> + Send;
- /// Soft-delete a CRM comment, scoped to `team_id`. `include_hidden
- /// = false` (non-admin) treats comments on hidden entities as not
- /// found. See [`CompaniesRepository::delete_crm_comment`].
+ /// Soft-delete `comment_id`, scoped to the team in `access`. A
+ /// member's receipt treats comments on hidden entities as not found.
+ /// See [`CompaniesRepository::delete_crm_comment`].
fn delete_crm_comment(
&self,
- team_id: &uuid::Uuid,
+ access: &CrmCommentReceipt<ViewAccessLevel>,
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`].
+ /// comment doesn't exist or is soft-deleted. Takes a raw
+ /// `comment_id` (not a receipt) because it is the minting primitive
+ /// the comment access extractor calls *before* a receipt exists, to
+ /// dispatch the access check to the right entity type. See
+ /// [`CompaniesRepository::get_comment_entity`].
fn get_comment_entity(
&self,
comment_id: &uuid::Uuid,
@@ -478,39 +458,42 @@ where
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
async fn set_email_sync(
&self,
- team_id: &uuid::Uuid,
- company_id: &uuid::Uuid,
+ access: &CrmCompanyReceipt<EditAccessLevel>,
email_sync: bool,
) -> Result<(), CrmError> {
+ let team_id = access.team_id();
+ let company_id = access.company_id()?;
self.companies_repository
- .set_email_sync(team_id, company_id, email_sync)
+ .set_email_sync(&team_id, &company_id, email_sync)
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
async fn set_company_hidden(
&self,
- team_id: &uuid::Uuid,
- company_id: &uuid::Uuid,
+ access: &CrmCompanyReceipt<EditAccessLevel>,
hidden: bool,
) -> Result<(), CrmError> {
+ let team_id = access.team_id();
+ let company_id = access.company_id()?;
self.companies_repository
- .set_company_hidden(team_id, company_id, hidden)
+ .set_company_hidden(&team_id, &company_id, hidden)
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
async fn set_contact_hidden(
&self,
- team_id: &uuid::Uuid,
- contact_id: &uuid::Uuid,
+ access: &CrmContactReceipt<EditAccessLevel>,
hidden: bool,
) -> Result<(), CrmError> {
+ let team_id = access.team_id();
+ let contact_id = access.contact_id()?;
self.companies_repository
- .set_contact_hidden(team_id, contact_id, hidden)
+ .set_contact_hidden(&team_id, &contact_id, hidden)
.await
}
@@ -526,11 +509,11 @@ where
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
#[allow(clippy::too_many_arguments)]
async fn list_companies_for_soup(
&self,
- team_id: &uuid::Uuid,
+ access: &CrmTeamReceipt<MemberTeamRole>,
user_id: &str,
company_ids: &[uuid::Uuid],
hidden: Option<bool>,
@@ -538,66 +521,70 @@ where
cursor: Option<CrmCompanySoupCursor>,
limit: i64,
) -> Result<Vec<CrmCompanyForSoup>, CrmError> {
+ let team_id = access.team_id();
self.companies_repository
- .list_companies_for_soup(team_id, user_id, company_ids, hidden, sort, cursor, limit)
+ .list_companies_for_soup(&team_id, user_id, company_ids, hidden, sort, cursor, limit)
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
async fn list_contacts_for_company(
&self,
- team_id: &uuid::Uuid,
- company_id: &uuid::Uuid,
- include_hidden: bool,
+ access: &CrmCompanyReceipt<ViewAccessLevel>,
) -> Result<Vec<CrmContact>, CrmError> {
+ let team_id = access.team_id();
+ let company_id = access.company_id()?;
+ let include_hidden = access.include_hidden();
self.companies_repository
- .list_contacts_for_company(team_id, company_id, include_hidden)
+ .list_contacts_for_company(&team_id, &company_id, include_hidden)
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
async fn get_contact_for_team(
&self,
- team_id: &uuid::Uuid,
- contact_id: &uuid::Uuid,
- include_hidden: bool,
+ access: &CrmContactReceipt<ViewAccessLevel>,
) -> Result<Option<CrmContact>, CrmError> {
+ let team_id = access.team_id();
+ let contact_id = access.contact_id()?;
+ let include_hidden = access.include_hidden();
self.companies_repository
- .get_contact_for_team(team_id, contact_id, include_hidden)
+ .get_contact_for_team(&team_id, &contact_id, include_hidden)
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
async fn get_company_for_team(
&self,
- team_id: &uuid::Uuid,
- company_id: &uuid::Uuid,
- include_hidden: bool,
+ access: &CrmCompanyReceipt<ViewAccessLevel>,
) -> Result<Option<CrmCompanyWithContacts>, CrmError> {
+ let team_id = access.team_id();
+ let company_id = access.company_id()?;
+ let include_hidden = access.include_hidden();
self.companies_repository
- .get_company_for_team(team_id, company_id, include_hidden)
+ .get_company_for_team(&team_id, &company_id, include_hidden)
.await
}
- #[tracing::instrument(skip(self, thread_metadata, text, metadata), err)]
+ #[tracing::instrument(skip(self, access, thread_metadata, text, metadata), err)]
#[allow(clippy::too_many_arguments)]
async fn create_crm_comment(
&self,
- team_id: &uuid::Uuid,
- entity_type: CrmCommentEntityType,
- entity_id: &uuid::Uuid,
+ access: &CrmCommentReceipt<ViewAccessLevel>,
owner: &str,
thread_id: Option<uuid::Uuid>,
thread_metadata: Option<Value>,
text: &str,
metadata: Option<Value>,
- include_hidden: bool,
) -> Result<CrmCommentThread, CrmError> {
+ let (entity_type, entity_id) = access.comment_entity()?;
+ let team_id = access.team_id();
+ let include_hidden = access.include_hidden();
self.companies_repository
.create_crm_comment(
- team_id,
+ &team_id,
entity_type,
- entity_id,
+ &entity_id,
owner,
thread_id,
thread_metadata,
@@ -608,41 +595,57 @@ where
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
async fn get_crm_comment_threads(
&self,
- team_id: &uuid::Uuid,
- entity_type: CrmCommentEntityType,
- entity_id: &uuid::Uuid,
- include_hidden: bool,
+ access: &CrmCommentReceipt<ViewAccessLevel>,
) -> Result<Vec<CrmCommentThread>, CrmError> {
+ let (entity_type, entity_id) = access.comment_entity()?;
+ let team_id = access.team_id();
+ let include_hidden = access.include_hidden();
self.companies_repository
- .get_crm_comment_threads(team_id, entity_type, entity_id, include_hidden)
+ .get_crm_comment_threads(&team_id, entity_type, &entity_id, include_hidden)
.await
}
- #[tracing::instrument(skip(self, text), err)]
+ #[tracing::instrument(skip(self, access, text), err)]
async fn edit_crm_comment(
&self,
- team_id: &uuid::Uuid,
+ access: &CrmCommentReceipt<ViewAccessLevel>,
comment_id: &uuid::Uuid,
text: &str,
- include_hidden: bool,
) -> Result<CrmComment, CrmError> {
+ let team_id = access.team_id();
+ let include_hidden = access.include_hidden();
+ let requester = access
+ .receipt()
+ .get_authenticated_user()
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
self.companies_repository
- .edit_crm_comment(team_id, comment_id, text, include_hidden)
+ .edit_crm_comment(
+ &team_id,
+ comment_id,
+ text,
+ include_hidden,
+ requester.as_ref(),
+ )
.await
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, access), err)]
async fn delete_crm_comment(
&self,
- team_id: &uuid::Uuid,
+ access: &CrmCommentReceipt<ViewAccessLevel>,
comment_id: &uuid::Uuid,
- include_hidden: bool,
) -> Result<DeleteCrmCommentResult, CrmError> {
+ let team_id = access.team_id();
+ let include_hidden = access.include_hidden();
+ let requester = access
+ .receipt()
+ .get_authenticated_user()
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
self.companies_repository
- .delete_crm_comment(team_id, comment_id, include_hidden)
+ .delete_crm_comment(&team_id, comment_id, include_hidden, requester.as_ref())
.await
}
@@ -702,8 +705,7 @@ impl CrmService for NoOpCrmService {
async fn set_email_sync(
&self,
- _team_id: &uuid::Uuid,
- _company_id: &uuid::Uuid,
+ _access: &CrmCompanyReceipt<EditAccessLevel>,
_email_sync: bool,
) -> Result<(), CrmError> {
unimplemented!("NoOpCrmService.set_email_sync")
@@ -711,8 +713,7 @@ impl CrmService for NoOpCrmService {
async fn set_company_hidden(
&self,
- _team_id: &uuid::Uuid,
- _company_id: &uuid::Uuid,
+ _access: &CrmCompanyReceipt<EditAccessLevel>,
_hidden: bool,
) -> Result<(), CrmError> {
unimplemented!("NoOpCrmService.set_company_hidden")
@@ -720,8 +721,7 @@ impl CrmService for NoOpCrmService {
async fn set_contact_hidden(
&self,
- _team_id: &uuid::Uuid,
- _contact_id: &uuid::Uuid,
+ _access: &CrmContactReceipt<EditAccessLevel>,
_hidden: bool,
) -> Result<(), CrmError> {
unimplemented!("NoOpCrmService.set_contact_hidden")
@@ -739,7 +739,7 @@ impl CrmService for NoOpCrmService {
#[allow(clippy::too_many_arguments)]
async fn list_companies_for_soup(
&self,
- _team_id: &uuid::Uuid,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
_user_id: &str,
_company_ids: &[uuid::Uuid],
_hidden: Option<bool>,
@@ -752,27 +752,21 @@ impl CrmService for NoOpCrmService {
async fn list_contacts_for_company(
&self,
- _team_id: &uuid::Uuid,
- _company_id: &uuid::Uuid,
- _include_hidden: bool,
+ _access: &CrmCompanyReceipt<ViewAccessLevel>,
) -> Result<Vec<CrmContact>, CrmError> {
Ok(Vec::new())
}
async fn get_contact_for_team(
&self,
- _team_id: &uuid::Uuid,
- _contact_id: &uuid::Uuid,
- _include_hidden: bool,
+ _access: &CrmContactReceipt<ViewAccessLevel>,
) -> Result<Option<CrmContact>, CrmError> {
Ok(None)
}
async fn get_company_for_team(
&self,
- _team_id: &uuid::Uuid,
- _company_id: &uuid::Uuid,
- _include_hidden: bool,
+ _access: &CrmCompanyReceipt<ViewAccessLevel>,
) -> Result<Option<CrmCompanyWithContacts>, CrmError> {
Ok(None)
}
@@ -780,44 +774,36 @@ impl CrmService for NoOpCrmService {
#[allow(clippy::too_many_arguments)]
async fn create_crm_comment(
&self,
- _team_id: &uuid::Uuid,
- _entity_type: CrmCommentEntityType,
- _entity_id: &uuid::Uuid,
+ _access: &CrmCommentReceipt<ViewAccessLevel>,
_owner: &str,
_thread_id: Option<uuid::Uuid>,
_thread_metadata: Option<Value>,
_text: &str,
_metadata: Option<Value>,
- _include_hidden: bool,
) -> Result<CrmCommentThread, CrmError> {
unimplemented!("NoOpCrmService.create_crm_comment")
}
async fn get_crm_comment_threads(
&self,
- _team_id: &uuid::Uuid,
- _entity_type: CrmCommentEntityType,
- _entity_id: &uuid::Uuid,
- _include_hidden: bool,
+ _access: &CrmCommentReceipt<ViewAccessLevel>,
) -> Result<Vec<CrmCommentThread>, CrmError> {
Ok(Vec::new())
}
async fn edit_crm_comment(
&self,
- _team_id: &uuid::Uuid,
+ _access: &CrmCommentReceipt<ViewAccessLevel>,
_comment_id: &uuid::Uuid,
_text: &str,
- _include_hidden: bool,
) -> Result<CrmComment, CrmError> {
unimplemented!("NoOpCrmService.edit_crm_comment")
}
async fn delete_crm_comment(
&self,
- _team_id: &uuid::Uuid,
+ _access: &CrmCommentReceipt<ViewAccessLevel>,
_comment_id: &uuid::Uuid,
- _include_hidden: bool,
) -> Result<DeleteCrmCommentResult, CrmError> {
unimplemented!("NoOpCrmService.delete_crm_comment")
}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_extractors.rs b/rust/cloud-storage/crm/src/inbound/axum_extractors.rs
index 96e05164e1..ec97c482c7 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_extractors.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_extractors.rs
@@ -1,9 +1,11 @@
//! 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.
+//! These live in the `crm` crate rather than `entity_access` because
+//! they mint CRM-domain capability tokens ([`crate::domain::auth`]) —
+//! and the comment extractor additionally crosses the [`CrmService`]
+//! boundary (comment → owning entity). `entity_access` deliberately
+//! knows nothing about CRM models, so the CRM-typed extractors and the
+//! receipts they produce are the trusted seam that lives here.
use std::collections::HashMap;
use std::marker::PhantomData;
@@ -25,27 +27,170 @@ use model_user::axum_extractor::MacroUserExtractor;
use uuid::Uuid;
use crate::{
- domain::{comment::CrmCommentEntityType, service::CrmService},
+ domain::{
+ auth::{CrmCommentReceipt, CrmCompanyReceipt, CrmContactReceipt},
+ comment::CrmCommentEntityType,
+ service::CrmService,
+ },
inbound::axum_router::CrmServiceRef,
};
+/// Validates that the user satisfies the required permission for a CRM
+/// company and mints a [`CrmCompanyReceipt`] 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 access check resolves the company's
+/// owning `team_id` from the same ownership row and bundles it into the
+/// receipt, so the service scopes its queries by the entity's team rather
+/// than the caller's default team.
+#[derive(Debug)]
+pub struct CrmCompanyAccessLevelExtractor<T: RequiredPermission, Svc> {
+ /// Capability token authorizing CRM company service calls.
+ pub receipt: CrmCompanyReceipt<T>,
+ _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, team_id) = service
+ .get_crm_entity_permission_with_team(
+ Some(&macro_user_id),
+ &company_id,
+ EntityType::CrmCompany,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ let receipt = EntityAccessReceipt::try_new_authenticated_user(
+ macro_user_id,
+ Entity {
+ entity_id: company_id,
+ entity_type: EntityType::CrmCompany,
+ },
+ permission,
+ )?;
+
+ Ok(Self {
+ receipt: CrmCompanyReceipt::new(receipt, team_id),
+ _marker: PhantomData,
+ })
+ }
+}
+
+/// Validates that the user satisfies the required permission for a CRM
+/// contact and mints a [`CrmContactReceipt`] 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
+/// [`CrmCompanyAccessLevelExtractor`]. Hidden contacts (or contacts whose
+/// parent company is hidden) are invisible to plain members.
+///
+/// Reads `contact_id` from the path. The access check resolves the contact's
+/// owning `team_id` (its parent company's team) from the same ownership row
+/// and bundles it into the receipt.
+#[derive(Debug)]
+pub struct CrmContactAccessLevelExtractor<T: RequiredPermission, Svc> {
+ /// Capability token authorizing CRM contact service calls.
+ pub receipt: CrmContactReceipt<T>,
+ _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, team_id) = service
+ .get_crm_entity_permission_with_team(
+ Some(&macro_user_id),
+ &contact_id,
+ EntityType::CrmContact,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ let receipt = EntityAccessReceipt::try_new_authenticated_user(
+ macro_user_id,
+ Entity {
+ entity_id: contact_id,
+ entity_type: EntityType::CrmContact,
+ },
+ permission,
+ )?;
+
+ Ok(Self {
+ receipt: CrmContactReceipt::new(receipt, team_id),
+ _marker: PhantomData,
+ })
+ }
+}
+
/// 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.
+/// entity (company or contact) a given comment belongs to and mints a
+/// [`CrmCommentReceipt`]. 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,
+ /// Capability token authorizing CRM comment service calls.
+ pub receipt: CrmCommentReceipt<T>,
_marker: PhantomData<(T, C, Eas)>,
}
@@ -89,11 +234,11 @@ where
// 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)
+ let (permission, team_id) = match access_service
+ .get_crm_entity_permission_with_team(Some(&macro_user_id), &entity_id_str, entity_type)
.await
{
- Ok(p) => p,
+ Ok(pair) => pair,
Err(AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_)) => {
return Err(ExtractorError::NotFound("CRM comment not found"));
}
@@ -104,29 +249,45 @@ where
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;
+ let receipt = EntityAccessReceipt::try_new_authenticated_user(
+ macro_user_id,
+ Entity {
+ entity_id: entity_id_str,
+ entity_type,
+ },
+ permission,
+ )?;
+
+ // entity_type is CrmCompany / CrmContact by construction, so this
+ // never errors; surface any future mismatch as Internal.
+ let receipt =
+ CrmCommentReceipt::new(receipt, team_id).map_err(|_| ExtractorError::Internal)?;
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,
+ receipt,
_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"))
+}
+
+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"))
+}
+
fn extract_comment_id(path_params: &HashMap<String, String>) -> Result<Uuid, ExtractorError> {
let raw_id = path_params
.get("comment_id")
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 ee99c25397..9ffab2495c 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
@@ -14,10 +14,7 @@ use axum::{
extract::{Path, State},
};
use entity_access::{
- domain::{
- models::{AccessLevel, ViewAccessLevel},
- ports::EntityAccessService,
- },
+ domain::{models::ViewAccessLevel, ports::EntityAccessService},
inbound::axum_extractors::EntityPermissionExtractor,
};
use model_error_response::ErrorResponse;
@@ -28,6 +25,7 @@ use uuid::Uuid;
use crate::{
domain::{
+ auth::CrmCommentReceipt,
comment::{CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult},
model::CrmError,
service::CrmService,
@@ -85,18 +83,12 @@ pub struct EditCrmCommentRequest {
pub async fn list_handler<C: CrmService, Eas: EntityAccessService>(
access: EntityPermissionExtractor<Eas>,
State(state): State<CrmRouterState<C, Eas>>,
- Path((entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
+ Path((_entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
) -> Result<Json<Vec<CrmCommentThread>>, CrmError> {
- let team_id = team_id_for_user(&state, &access).await?;
- let include_hidden = access
- .entity_access_receipt
- .entity_permission()
- .allows_access_level(AccessLevel::Edit);
+ let team_id = owning_team_for_entity(&state, &access).await?;
+ let receipt = CrmCommentReceipt::new(access.entity_access_receipt, team_id)?;
- let threads = state
- .service
- .get_crm_comment_threads(&team_id, entity_type, &entity_id, include_hidden)
- .await?;
+ let threads = state.service.get_crm_comment_threads(&receipt).await?;
Ok(Json(threads))
}
@@ -125,18 +117,10 @@ pub async fn list_handler<C: CrmService, Eas: EntityAccessService>(
pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
access: EntityPermissionExtractor<Eas>,
State(state): State<CrmRouterState<C, Eas>>,
- Path((entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
+ Path((_entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
Json(req): Json<CreateCrmCommentRequest>,
) -> Result<Json<CrmCommentThread>, CrmError> {
- let team_id = team_id_for_user(&state, &access).await?;
- let include_hidden = access
- .entity_access_receipt
- .entity_permission()
- .allows_access_level(AccessLevel::Edit);
- let owner = access
- .entity_access_receipt
- .get_authenticated_user()
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ let team_id = owning_team_for_entity(&state, &access).await?;
let text = req.text.trim();
if text.is_empty() {
@@ -145,18 +129,21 @@ pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
));
}
+ let receipt = CrmCommentReceipt::new(access.entity_access_receipt, team_id)?;
+ let owner = receipt
+ .receipt()
+ .get_authenticated_user()
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
let thread = state
.service
.create_crm_comment(
- &team_id,
- entity_type,
- &entity_id,
+ &receipt,
owner.as_ref(),
req.thread_id,
req.thread_metadata,
text,
req.metadata,
- include_hidden,
)
.await?;
@@ -187,11 +174,6 @@ pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
Path(comment_id): Path<Uuid>,
Json(req): Json<EditCrmCommentRequest>,
) -> Result<Json<CrmComment>, CrmError> {
- let include_hidden = access
- .entity_access_receipt
- .entity_permission()
- .allows_access_level(AccessLevel::Edit);
-
let text = req.text.trim();
if text.is_empty() {
return Err(CrmError::InvalidRequest(
@@ -201,7 +183,7 @@ pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
let comment = state
.service
- .edit_crm_comment(&access.team_id, &comment_id, text, include_hidden)
+ .edit_crm_comment(&access.receipt, &comment_id, text)
.await?;
Ok(Json(comment))
@@ -230,24 +212,20 @@ pub async fn delete_handler<C: CrmService, Eas: EntityAccessService>(
State(state): State<CrmRouterState<C, Eas>>,
Path(comment_id): Path<Uuid>,
) -> Result<Json<DeleteCrmCommentResult>, CrmError> {
- let include_hidden = access
- .entity_access_receipt
- .entity_permission()
- .allows_access_level(AccessLevel::Edit);
-
let result = state
.service
- .delete_crm_comment(&access.team_id, &comment_id, include_hidden)
+ .delete_crm_comment(&access.receipt, &comment_id)
.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>(
+/// Resolve the owning team of the entity the comment hangs off, derived from
+/// the same ownership lookup that grants access — not the caller's default
+/// team — so the bundled team can't drift from the authorized entity.
+/// `EntityPermissionExtractor` already validated access on that entity, so a
+/// failure here means corrupted state rather than a real authorization miss.
+async fn owning_team_for_entity<C: CrmService, Eas: EntityAccessService>(
state: &CrmRouterState<C, Eas>,
access: &EntityPermissionExtractor<Eas>,
) -> Result<Uuid, CrmError> {
@@ -255,11 +233,15 @@ async fn team_id_for_user<C: CrmService, Eas: EntityAccessService>(
.entity_access_receipt
.get_authenticated_user()
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- state
+ let entity = access.entity_access_receipt.entity();
+ let (_permission, team_id) = state
.entity_access_service
- .get_user_team(&user_id.0)
+ .get_crm_entity_permission_with_team(
+ Some(&user_id.0),
+ &entity.entity_id,
+ entity.entity_type,
+ )
.await
- .map_err(|e| CrmError::StorageLayerError(anyhow::Error::msg(e.to_string())))?
- .map(|t| t.team_id)
- .ok_or(CrmError::InvalidTeamId)
+ .map_err(|e| CrmError::StorageLayerError(anyhow::Error::msg(e.to_string())))?;
+ Ok(team_id)
}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/get_company.rs b/rust/cloud-storage/crm/src/inbound/axum_router/get_company.rs
index a6085b587d..069b74be40 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/get_company.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/get_company.rs
@@ -3,21 +3,18 @@ use axum::{
extract::{Path, State},
};
use chrono::{DateTime, Utc};
-use entity_access::{
- domain::{
- models::{AccessLevel, ViewAccessLevel},
- ports::EntityAccessService,
- },
- inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
-};
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
use model_error_response::ErrorResponse;
use serde::Serialize;
use utoipa::ToSchema;
use uuid::Uuid;
-use crate::domain::{
- model::{CrmCompanyWithContacts, CrmDomain, CrmError},
- service::CrmService,
+use crate::{
+ domain::{
+ model::{CrmCompanyWithContacts, CrmDomain, CrmError},
+ service::CrmService,
+ },
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
};
use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
@@ -133,14 +130,9 @@ pub async fn handler<C: CrmService, Eas: EntityAccessService>(
State(state): State<CrmRouterState<C, Eas>>,
Path(company_id): Path<Uuid>,
) -> Result<Json<CrmCompanyResponse>, CrmError> {
- let include_hidden = access
- .entity_access_receipt
- .entity_permission()
- .allows_access_level(AccessLevel::Edit);
-
let record = state
.service
- .get_company_for_team(&access.team_id, &company_id, include_hidden)
+ .get_company_for_team(&access.receipt)
.await?
.ok_or(CrmError::CompanyNotFoundForTeam)?;
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 41f3e8095b..b2f1b76b96 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
@@ -2,17 +2,14 @@ use axum::{
Json,
extract::{Path, State},
};
-use entity_access::{
- domain::{
- models::{AccessLevel, ViewAccessLevel},
- ports::EntityAccessService,
- },
- inbound::axum_extractors::CrmContactAccessLevelExtractor,
-};
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
use model_error_response::ErrorResponse;
use uuid::Uuid;
-use crate::domain::{model::CrmError, service::CrmService};
+use crate::{
+ domain::{model::CrmError, service::CrmService},
+ inbound::axum_extractors::CrmContactAccessLevelExtractor,
+};
use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
@@ -41,14 +38,9 @@ pub async fn handler<C: CrmService, Eas: EntityAccessService>(
State(state): State<CrmRouterState<C, Eas>>,
Path(contact_id): Path<Uuid>,
) -> Result<Json<CrmContactResponse>, CrmError> {
- let include_hidden = access
- .entity_access_receipt
- .entity_permission()
- .allows_access_level(AccessLevel::Edit);
-
let contact = state
.service
- .get_contact_for_team(&access.team_id, &contact_id, include_hidden)
+ .get_contact_for_team(&access.receipt)
.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 7d21191f44..c6fa83d729 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
@@ -3,21 +3,18 @@ use axum::{
extract::{Path, State},
};
use chrono::{DateTime, Utc};
-use entity_access::{
- domain::{
- models::{AccessLevel, ViewAccessLevel},
- ports::EntityAccessService,
- },
- inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
-};
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
use model_error_response::ErrorResponse;
use serde::Serialize;
use utoipa::ToSchema;
use uuid::Uuid;
-use crate::domain::{
- model::{CrmContact, CrmError},
- service::CrmService,
+use crate::{
+ domain::{
+ model::{CrmContact, CrmError},
+ service::CrmService,
+ },
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
};
use super::CrmRouterState;
@@ -90,14 +87,9 @@ pub async fn handler<C: CrmService, Eas: EntityAccessService>(
State(state): State<CrmRouterState<C, Eas>>,
Path(company_id): Path<Uuid>,
) -> Result<Json<Vec<CrmContactResponse>>, CrmError> {
- let include_hidden = access
- .entity_access_receipt
- .entity_permission()
- .allows_access_level(AccessLevel::Edit);
-
let contacts = state
.service
- .list_contacts_for_company(&access.team_id, &company_id, include_hidden)
+ .list_contacts_for_company(&access.receipt)
.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 6bb915de3b..172337638f 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
@@ -152,6 +152,12 @@ impl IntoResponse for CrmError {
message: "crm comment not found".into(),
}),
),
+ CrmError::CommentNotOwned => (
+ StatusCode::FORBIDDEN,
+ Json(ErrorResponse {
+ message: "you can only modify your own crm comments".into(),
+ }),
+ ),
CrmError::InvalidRequest(message) => (
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
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 1dd67879ed..d0c9d7b940 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
@@ -3,16 +3,16 @@ use axum::{
extract::{Path, State},
http::StatusCode,
};
-use entity_access::{
- domain::{models::EditAccessLevel, ports::EntityAccessService},
- inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
-};
+use entity_access::domain::{models::EditAccessLevel, ports::EntityAccessService};
use model_error_response::ErrorResponse;
use serde::Deserialize;
use utoipa::ToSchema;
use uuid::Uuid;
-use crate::domain::{model::CrmError, service::CrmService};
+use crate::{
+ domain::{model::CrmError, service::CrmService},
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
+};
use super::CrmRouterState;
@@ -59,7 +59,7 @@ pub async fn handler<C: CrmService, Eas: EntityAccessService>(
) -> Result<StatusCode, CrmError> {
state
.service
- .set_company_hidden(&access.team_id, &company_id, req.hidden)
+ .set_company_hidden(&access.receipt, 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 a8f83bfe70..b2bc3567d2 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
@@ -3,16 +3,16 @@ use axum::{
extract::{Path, State},
http::StatusCode,
};
-use entity_access::{
- domain::{models::EditAccessLevel, ports::EntityAccessService},
- inbound::axum_extractors::CrmContactAccessLevelExtractor,
-};
+use entity_access::domain::{models::EditAccessLevel, ports::EntityAccessService};
use model_error_response::ErrorResponse;
use serde::Deserialize;
use utoipa::ToSchema;
use uuid::Uuid;
-use crate::domain::{model::CrmError, service::CrmService};
+use crate::{
+ domain::{model::CrmError, service::CrmService},
+ inbound::axum_extractors::CrmContactAccessLevelExtractor,
+};
use super::CrmRouterState;
@@ -51,7 +51,7 @@ pub async fn handler<C: CrmService, Eas: EntityAccessService>(
) -> Result<StatusCode, CrmError> {
state
.service
- .set_contact_hidden(&access.team_id, &contact_id, req.hidden)
+ .set_contact_hidden(&access.receipt, 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 33e5116566..8615d06ad6 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
@@ -3,16 +3,16 @@ use axum::{
extract::{Path, State},
http::StatusCode,
};
-use entity_access::{
- domain::{models::EditAccessLevel, ports::EntityAccessService},
- inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
-};
+use entity_access::domain::{models::EditAccessLevel, ports::EntityAccessService};
use model_error_response::ErrorResponse;
use serde::Deserialize;
use utoipa::ToSchema;
use uuid::Uuid;
-use crate::domain::{model::CrmError, service::CrmService};
+use crate::{
+ domain::{model::CrmError, service::CrmService},
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
+};
use super::CrmRouterState;
@@ -56,7 +56,7 @@ pub async fn handler<C: CrmService, Eas: EntityAccessService>(
) -> Result<StatusCode, CrmError> {
state
.service
- .set_email_sync(&access.team_id, &company_id, req.email_sync)
+ .set_email_sync(&access.receipt, 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 fb808f11b9..166fbb7b6f 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -66,6 +66,48 @@ impl CompaniesRepositoryImpl {
Ok(())
}
+
+ /// Resolve a comment's author, but only when the comment resolves to a
+ /// team-owned parent the caller may see (`include_hidden` admits hidden
+ /// parents). `Ok(None)` means absent / cross-team / hidden-from-caller —
+ /// indistinguishable on purpose. Gates owner-only edit/delete.
+ async fn comment_owner_if_visible(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ include_hidden: bool,
+ ) -> Result<Option<String>, CrmError> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT c.owner
+ FROM crm_comment c
+ JOIN crm_thread t ON t.id = c.thread_id
+ WHERE c.id = $1
+ AND c.deleted_at IS NULL
+ AND (
+ EXISTS (
+ SELECT 1 FROM crm_companies co
+ WHERE co.id = t.company_id
+ AND co.team_id = $2
+ AND ($3 OR co.hidden = FALSE)
+ )
+ OR EXISTS (
+ SELECT 1 FROM crm_contacts ct
+ JOIN crm_companies co2 ON co2.id = ct.company_id
+ WHERE ct.id = t.contact_id
+ AND co2.team_id = $2
+ AND ($3 OR (ct.hidden = FALSE AND co2.hidden = FALSE))
+ )
+ )
+ "#,
+ comment_id,
+ team_id,
+ include_hidden,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))
+ }
}
impl CompaniesRepository for CompaniesRepositoryImpl {
@@ -1604,7 +1646,19 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
comment_id: &uuid::Uuid,
text: &str,
include_hidden: bool,
+ requester: &str,
) -> Result<CrmComment, CrmError> {
+ // Owner-only: a visible-but-unowned comment is `CommentNotOwned`,
+ // an absent/cross-team/hidden one is `CommentNotFound`.
+ match self
+ .comment_owner_if_visible(team_id, comment_id, include_hidden)
+ .await?
+ {
+ None => return Err(CrmError::CommentNotFound),
+ Some(owner) if owner != requester => return Err(CrmError::CommentNotOwned),
+ Some(_) => {}
+ }
+
// Update only when the comment's thread resolves to a company or
// contact owned by the team, so cross-team edits 404. For
// non-admins (`include_hidden = false`) the parent must also
@@ -1667,7 +1721,19 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
include_hidden: bool,
+ requester: &str,
) -> Result<DeleteCrmCommentResult, CrmError> {
+ // Owner-only: a visible-but-unowned comment is `CommentNotOwned`,
+ // an absent/cross-team/hidden one is `CommentNotFound`.
+ match self
+ .comment_owner_if_visible(team_id, comment_id, include_hidden)
+ .await?
+ {
+ None => return Err(CrmError::CommentNotFound),
+ Some(owner) if owner != requester => return Err(CrmError::CommentNotOwned),
+ Some(_) => {}
+ }
+
let mut tx = self
.pool
.begin()
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/comments.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/comments.rs
index 81b18a30a5..5d89dc4e3b 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test/comments.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/comments.rs
@@ -285,7 +285,7 @@ async fn edit_crm_comment_updates_text(pool: PgPool) -> anyhow::Result<()> {
let comment_id = ct.comments[0].comment_id;
let updated = repo
- .edit_crm_comment(&team_id, &comment_id, "after", false)
+ .edit_crm_comment(&team_id, &comment_id, "after", false, owner)
.await?;
assert_eq!(updated.text, "after");
@@ -325,7 +325,13 @@ async fn edit_crm_comment_cross_team_404(pool: PgPool) -> anyhow::Result<()> {
.await?;
let result = repo
- .edit_crm_comment(&team_b, &ct.comments[0].comment_id, "hacked", false)
+ .edit_crm_comment(
+ &team_b,
+ &ct.comments[0].comment_id,
+ "hacked",
+ false,
+ )
.await;
assert!(matches!(
result,
@@ -357,7 +363,7 @@ async fn delete_crm_comment_removes_empty_thread(pool: PgPool) -> anyhow::Result
.await?;
let result = repo
- .delete_crm_comment(&team_id, &ct.comments[0].comment_id, false)
+ .delete_crm_comment(&team_id, &ct.comments[0].comment_id, false, owner)
.await?;
assert!(result.thread_deleted);
assert_eq!(result.thread_id, ct.thread.thread_id);
@@ -411,7 +417,7 @@ async fn delete_crm_comment_keeps_thread_with_remaining(pool: PgPool) -> anyhow:
// Deleting the root leaves the thread alive with the reply.
let result = repo
- .delete_crm_comment(&team_id, &root.comments[0].comment_id, false)
+ .delete_crm_comment(&team_id, &root.comments[0].comment_id, false, owner)
.await?;
assert!(!result.thread_deleted);
@@ -453,7 +459,12 @@ async fn delete_crm_comment_cross_team_404(pool: PgPool) -> anyhow::Result<()> {
.await?;
let result = repo
- .delete_crm_comment(&team_b, &ct.comments[0].comment_id, false)
+ .delete_crm_comment(
+ &team_b,
+ &ct.comments[0].comment_id,
+ false,
+ )
.await;
assert!(matches!(
result,
@@ -635,21 +646,24 @@ async fn edit_delete_crm_comment_block_member_on_hidden_entity(pool: PgPool) ->
// Member: edit and delete both 404 because the parent is hidden.
assert!(matches!(
- repo.edit_crm_comment(&team_id, &comment_id, "edited", false)
+ repo.edit_crm_comment(&team_id, &comment_id, "edited", false, owner)
.await,
Err(crate::domain::model::CrmError::CommentNotFound)
));
assert!(matches!(
- repo.delete_crm_comment(&team_id, &comment_id, false).await,
+ repo.delete_crm_comment(&team_id, &comment_id, false, owner)
+ .await,
Err(crate::domain::model::CrmError::CommentNotFound)
));
- // Admin: edit succeeds, then delete succeeds.
+ // Author with admin visibility: edit then delete succeed even on a
+ // hidden parent (members 404 above; only the author may mutate).
let edited = repo
- .edit_crm_comment(&team_id, &comment_id, "edited by admin", true)
+ .edit_crm_comment(&team_id, &comment_id, "edited by admin", true, owner)
.await?;
assert_eq!(edited.text, "edited by admin");
- repo.delete_crm_comment(&team_id, &comment_id, true).await?;
+ repo.delete_crm_comment(&team_id, &comment_id, true, owner)
+ .await?;
Ok(())
}
@@ -726,17 +740,18 @@ async fn crm_comment_visibility_on_hidden_contact_with_visible_company(
));
assert!(matches!(
- repo.edit_crm_comment(&team_id, &comment_id, "edited", false)
+ repo.edit_crm_comment(&team_id, &comment_id, "edited", false, owner)
.await,
Err(crate::domain::model::CrmError::CommentNotFound)
));
assert!(matches!(
- repo.delete_crm_comment(&team_id, &comment_id, false).await,
+ repo.delete_crm_comment(&team_id, &comment_id, false, owner)
+ .await,
Err(crate::domain::model::CrmError::CommentNotFound)
));
- // Admin view: everything reachable. Thread + comment survive,
- // edit + delete succeed in sequence.
+ // Admin visibility reaches the hidden contact; the author (with that
+ // visibility) can edit + delete in sequence. Thread + comment survive.
let admin_threads = repo
.get_crm_comment_threads(
&team_id,
@@ -749,10 +764,109 @@ async fn crm_comment_visibility_on_hidden_contact_with_visible_company(
assert_eq!(admin_threads[0].comments.len(), 1);
let edited = repo
- .edit_crm_comment(&team_id, &comment_id, "edited by admin", true)
+ .edit_crm_comment(&team_id, &comment_id, "edited by admin", true, owner)
.await?;
assert_eq!(edited.text, "edited by admin");
- repo.delete_crm_comment(&team_id, &comment_id, true).await?;
+ repo.delete_crm_comment(&team_id, &comment_id, true, owner)
+ .await?;
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn edit_crm_comment_non_owner_forbidden(pool: PgPool) -> anyhow::Result<()> {
+ // A teammate who can see the comment still cannot edit it — only the
+ // author may. The parent is visible to the caller, so this is
+ // `CommentNotOwned` (403), not `CommentNotFound` (404).
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let ct = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "mine",
+ None,
+ false,
+ )
+ .await?;
+ let comment_id = ct.comments[0].comment_id;
+
+ let result = repo
+ .edit_crm_comment(
+ &team_id,
+ &comment_id,
+ "hijacked",
+ false,
+ )
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CommentNotOwned)
+ ));
+
+ // The original text is untouched.
+ let threads = repo
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ false,
+ )
+ .await?;
+ assert_eq!(threads[0].comments[0].text, "mine");
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn delete_crm_comment_non_owner_forbidden(pool: PgPool) -> anyhow::Result<()> {
+ // Same rule for delete: a non-author teammate gets `CommentNotOwned`
+ // and the comment survives.
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let ct = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "mine",
+ None,
+ false,
+ )
+ .await?;
+ let comment_id = ct.comments[0].comment_id;
+
+ let result = repo
+ .delete_crm_comment(&team_id, &comment_id, false, "macro|[email protected]")
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CommentNotOwned)
+ ));
+
+ let threads = repo
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ false,
+ )
+ .await?;
+ assert_eq!(threads[0].comments.len(), 1);
Ok(())
}
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_company_hidden.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_company_hidden.rs
index 0ad2877910..db4747a8a7 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_company_hidden.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_company_hidden.rs
@@ -1,8 +1,10 @@
use super::helpers::*;
+use crate::domain::auth::CrmCompanyReceipt;
use crate::domain::companies_repo::*;
use crate::domain::service::{CrmService, CrmServiceImpl};
use crate::outbound::companies_repo::*;
use crate::outbound::no_op_resolver::NoOpCompanyMetadataResolver;
+use entity_access::domain::models::EditAccessLevel;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::PgPool;
use uuid::Uuid;
@@ -81,9 +83,8 @@ async fn service_set_company_hidden_true_soft_hides_contacts_and_disables_email_
CompaniesRepositoryImpl::new(pool.clone()),
NoOpCompanyMetadataResolver,
);
- service
- .set_company_hidden(&team_id, &company_id, true)
- .await?;
+ let access = CrmCompanyReceipt::<EditAccessLevel>::dangerously_internal(company_id, team_id);
+ service.set_company_hidden(&access, true).await?;
assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));
assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));
@@ -146,9 +147,8 @@ async fn service_set_company_hidden_false_does_not_re_enable_email_sync(
CompaniesRepositoryImpl::new(pool.clone()),
NoOpCompanyMetadataResolver,
);
- service
- .set_company_hidden(&team_id, &company_id, false)
- .await?;
+ let access = CrmCompanyReceipt::<EditAccessLevel>::dangerously_internal(company_id, team_id);
+ service.set_company_hidden(&access, false).await?;
assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));
// Un-hiding leaves email_sync alone — caller must re-enable it explicitly.
diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rs
index 7a93fde911..b61b717dc6 100644
--- a/rust/cloud-storage/entity_access/src/domain/models.rs
+++ b/rust/cloud-storage/entity_access/src/domain/models.rs
@@ -12,6 +12,18 @@ pub use models_permissions::share_permission::access_level::{
CommentAccessLevel, EditAccessLevel, OwnerAccessLevel, ViewAccessLevel,
};
+/// A user's resolved access to a CRM entity (company or contact) paired with
+/// the entity's owning team — both produced by the same ownership lookup, so
+/// the team is guaranteed to be the one that granted access (not the user's
+/// default team).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CrmEntityAccess {
+ /// The access level the user holds on the entity.
+ pub access_level: AccessLevel,
+ /// The team that owns the entity.
+ pub team_id: Uuid,
+}
+
/// The role a user has within a channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
@@ -48,27 +60,27 @@ pub enum TeamRole {
}
/// Team member role.
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct MemberTeamRole;
/// Team administrator role.
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct AdminTeamRole;
/// Team owner role with full control.
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct OwnerTeamRole;
/// Channel owner role with full control
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct OwnerParticipantRole;
/// Channel Administrator
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct AdminParticipantRole;
/// Regular channel member.
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct MemberParticipantRole;
/// Trait implemented by marker types that encode a permission requirement.
diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rs
index 9f4982241d..90a6e9f25d 100644
--- a/rust/cloud-storage/entity_access/src/domain/ports.rs
+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs
@@ -4,8 +4,8 @@
use super::models::EntityType;
use crate::domain::models::{
- AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, EntityAccessReceipt,
- EntityPermission, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, CrmEntityAccess,
+ EntityAccessReceipt, EntityPermission, RequiredPermission, UserTeamInfo,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};
use std::future::Future;
@@ -61,19 +61,23 @@ 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.
+ /// Get the access level a user has for a CRM company, with the company's
+ /// owning `team_id`.
///
/// 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.
+ /// plain members (returns `None`) but reachable by admins and owners. The
+ /// returned `team_id` is the company's owning team, resolved from the same
+ /// row that grants access.
fn get_crm_company_access(
&self,
company_id: &str,
user_id: Option<&MacroUserId<Lowercase<'_>>>,
- ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+ ) -> impl Future<Output = Result<Option<CrmEntityAccess>, AccessError>> + Send;
- /// Get the access level a user has for a CRM contact.
+ /// Get the access level a user has for a CRM contact, with the contact's
+ /// owning `team_id` (its parent company's team).
///
/// 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
@@ -83,7 +87,7 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
&self,
contact_id: &str,
user_id: Option<&MacroUserId<Lowercase<'_>>>,
- ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+ ) -> impl Future<Output = Result<Option<CrmEntityAccess>, AccessError>> + Send;
/// Check if a user is a member of the specified channels.
///
@@ -212,6 +216,24 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {
user_org_id: Option<i64>,
) -> impl Future<Output = Result<EntityPermission, AccessError>> + Send;
+ /// Resolve a user's permission for a CRM company or contact **together
+ /// with the entity's owning `team_id`** — the team that owns the entity
+ /// and that the user belongs to, resolved from the same ownership lookup
+ /// that grants access. Mint team-scoped CRM receipts off this rather than
+ /// pairing [`Self::get_entity_permission`] with [`Self::get_user_team`],
+ /// so the bundled team can't drift from the authorized entity for a
+ /// multi-team user. Errors `AccessError::Unauthorized` when access fails.
+ ///
+ /// No default impl on purpose: implementors must derive the team from the
+ /// entity's ownership row (not the user's default team), so the invariant
+ /// can't be silently weakened by inheriting a fallback.
+ fn get_crm_entity_permission_with_team(
+ &self,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> impl Future<Output = Result<(EntityPermission, Uuid), AccessError>> + Send;
+
/// Get all user IDs that have access to a given entity.
///
/// For Document, Chat, Project, and EmailThread: returns user IDs with direct
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
index b2403691b5..02e8cc4062 100644
--- a/rust/cloud-storage/entity_access/src/domain/service.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -5,8 +5,9 @@ use std::str::FromStr;
use crate::domain::{
models::{
- AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, Entity, EntityAccessAuth,
- EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, CrmEntityAccess, Entity,
+ EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission,
+ UserTeamInfo,
},
ports::{AccessRepository, EntityAccessService},
};
@@ -94,21 +95,23 @@ where
}
}
- /// Get access level for a CRM company via the user's team membership.
+ /// Get access level + owning team 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> {
+ ) -> Result<Option<CrmEntityAccess>, 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.
+ /// Get access level + owning team 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> {
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
self.repo.get_crm_contact_access(entity_id, user_id).await
}
@@ -178,8 +181,14 @@ 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,
+ EntityType::CrmCompany => Ok(self
+ .get_crm_company_access(entity_id, user_id)
+ .await?
+ .map(|a| a.access_level)),
+ EntityType::CrmContact => Ok(self
+ .get_crm_contact_access(entity_id, user_id)
+ .await?
+ .map(|a| a.access_level)),
// 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.
@@ -257,8 +266,8 @@ where
EntityType::CrmCompany => {
let access = self.get_crm_company_access(entity_id, user_id).await?;
match access {
- Some(level) => Ok(EntityPermission::AccessLevel {
- access_level: level,
+ Some(access) => Ok(EntityPermission::AccessLevel {
+ access_level: access.access_level,
}),
None => Err(AccessError::Unauthorized),
}
@@ -266,8 +275,8 @@ where
EntityType::CrmContact => {
let access = self.get_crm_contact_access(entity_id, user_id).await?;
match access {
- Some(level) => Ok(EntityPermission::AccessLevel {
- access_level: level,
+ Some(access) => Ok(EntityPermission::AccessLevel {
+ access_level: access.access_level,
}),
None => Err(AccessError::Unauthorized),
}
@@ -286,6 +295,34 @@ where
}
}
+ #[tracing::instrument(err, skip(self))]
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<(EntityPermission, Uuid), AccessError> {
+ // Resolve permission and owning team from one ownership lookup, so the
+ // team is the entity's owner (and the user is a member of it) rather
+ // than the user's default team.
+ let access = match entity_type {
+ EntityType::CrmCompany => self.get_crm_company_access(entity_id, user_id).await?,
+ EntityType::CrmContact => self.get_crm_contact_access(entity_id, user_id).await?,
+ _ => {
+ return Err(AccessError::BadRequest(
+ "get_crm_entity_permission_with_team supports only CRM entities",
+ ));
+ }
+ };
+ let access = access.ok_or(AccessError::Unauthorized)?;
+ Ok((
+ EntityPermission::AccessLevel {
+ access_level: access.access_level,
+ },
+ access.team_id,
+ ))
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_users_by_entity(
&self,
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 0463e18be1..a0a7f74ef4 100644
--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs
@@ -200,16 +200,28 @@ impl AccessRepository for MockRepo {
&self,
_company_id: &str,
_user_id: Option<&MacroUserId<Lowercase<'_>>>,
- ) -> Result<Option<AccessLevel>, AccessError> {
- Ok(*self.crm_company_access.lock().await)
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
+ // Owning team is irrelevant to these access-level tests; pair with nil.
+ Ok(
+ (*self.crm_company_access.lock().await).map(|access_level| CrmEntityAccess {
+ access_level,
+ team_id: Uuid::nil(),
+ }),
+ )
}
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)
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
+ // Owning team is irrelevant to these access-level tests; pair with nil.
+ Ok(
+ (*self.crm_contact_access.lock().await).map(|access_level| CrmEntityAccess {
+ access_level,
+ team_id: Uuid::nil(),
+ }),
+ )
}
async fn get_entity_users(
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
deleted file mode 100644
index 6c0d5109eb..0000000000
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/crm_company.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-//! 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
deleted file mode 100644
index 67e7b39640..0000000000
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/crm_contact.rs
+++ /dev/null
@@ -1,109 +0,0 @@
-//! 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 d7afed5522..1a33c7e478 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,8 +6,6 @@
mod call;
mod channel;
mod chat;
-mod crm_company;
-mod crm_contact;
mod document;
mod entity_permission;
mod foreign_entity;
@@ -20,8 +18,6 @@ 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 3f8cf375d3..5911edf5de 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
@@ -7,7 +7,8 @@ mod test;
use crate::domain::{
models::{
- AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, EntityType, UserTeamInfo,
+ AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, CrmEntityAccess, EntityType,
+ UserTeamInfo,
},
ports::AccessRepository,
};
@@ -164,7 +165,7 @@ impl AccessRepository for PgAccessRepository {
&self,
company_id: &str,
user_id: Option<&MacroUserId<Lowercase<'_>>>,
- ) -> Result<Option<AccessLevel>, AccessError> {
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
let company_uuid = company_id
.parse::<Uuid>()
.map_err(|_| AccessError::BadRequest("Invalid CRM company ID format"))?;
@@ -182,7 +183,7 @@ impl AccessRepository for PgAccessRepository {
&self,
contact_id: &str,
user_id: Option<&MacroUserId<Lowercase<'_>>>,
- ) -> Result<Option<AccessLevel>, AccessError> {
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
let contact_uuid = contact_id
.parse::<Uuid>()
.map_err(|_| AccessError::BadRequest("Invalid CRM contact ID format"))?;
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
index 08f04dbe18..8364bfde20 100644
--- 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
@@ -1,25 +1,30 @@
//! Query for CRM company access level.
-use crate::domain::models::{AccessLevel, TeamRole};
+use crate::domain::models::{AccessLevel, CrmEntityAccess, 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.
+/// Resolve the access level a user has for a CRM company, together with the
+/// company's owning `team_id`.
///
/// 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.
+/// team, so the returned `team_id` is the team that owns the company *and*
+/// that the user belongs to — the caller can scope downstream queries by it
+/// without trusting the user's default 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> {
+) -> Result<Option<CrmEntityAccess>, sqlx::Error> {
let row = sqlx::query!(
r#"
SELECT
c.hidden AS "hidden!",
+ c.team_id AS "team_id!",
tu.team_role AS "role!: TeamRole"
FROM crm_companies c
JOIN team_user tu
@@ -33,7 +38,12 @@ pub async fn get_crm_company_access(
.fetch_optional(pool)
.await?;
- Ok(row.and_then(|r| team_role_to_access_level(r.role, r.hidden)))
+ Ok(row.and_then(|r| {
+ team_role_to_access_level(r.role, r.hidden).map(|access_level| CrmEntityAccess {
+ access_level,
+ team_id: r.team_id,
+ })
+ }))
}
/// Map a team role + hidden flag to an [`AccessLevel`].
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
index 7305af8fba..efc534e609 100644
--- 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
@@ -1,28 +1,31 @@
//! Query for CRM contact access level.
-use crate::domain::models::{AccessLevel, TeamRole};
+use crate::domain::models::{CrmEntityAccess, 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.
+/// Resolve the access level a user has for a CRM contact, together with the
+/// owning `team_id` (the contact's parent company's team).
///
/// 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.
+/// `team_user` membership on the owning team, so the returned `team_id` is
+/// the team that owns the contact *and* that the user belongs to. 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> {
+) -> Result<Option<CrmEntityAccess>, sqlx::Error> {
let row = sqlx::query!(
r#"
SELECT
(ct.hidden OR c.hidden) AS "hidden!",
+ c.team_id AS "team_id!",
tu.team_role AS "role!: TeamRole"
FROM crm_contacts ct
JOIN crm_companies c
@@ -38,5 +41,10 @@ pub async fn get_crm_contact_access(
.fetch_optional(pool)
.await?;
- Ok(row.and_then(|r| team_role_to_access_level(r.role, r.hidden)))
+ Ok(row.and_then(|r| {
+ team_role_to_access_level(r.role, r.hidden).map(|access_level| CrmEntityAccess {
+ access_level,
+ team_id: r.team_id,
+ })
+ }))
}
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 db05034db5..8d75fa9891 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,6 +1,6 @@
use super::PgAccessRepository;
use crate::domain::{
- models::{AccessError, AccessLevel},
+ models::{AccessError, AccessLevel, CrmEntityAccess},
ports::AccessRepository,
};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
@@ -216,10 +216,30 @@ async fn crm_company_access_maps_team_role_to_access_level(pool: PgPool) -> anyh
let company_id = insert_crm_company(&pool, TEAM_ALPHA, false).await?;
let repo = PgAccessRepository::new(pool);
+ // Each role resolves to its access level paired with the company's owning team.
+ let team_alpha = Uuid::parse_str(TEAM_ALPHA)?;
let cases = [
- (TEAM_MEMBER, Some(AccessLevel::View)),
- (TEAM_ADMIN, Some(AccessLevel::Edit)),
- (TEAM_OWNER, Some(AccessLevel::Owner)),
+ (
+ TEAM_MEMBER,
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::View,
+ team_id: team_alpha,
+ }),
+ ),
+ (
+ TEAM_ADMIN,
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::Edit,
+ team_id: team_alpha,
+ }),
+ ),
+ (
+ TEAM_OWNER,
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::Owner,
+ team_id: team_alpha,
+ }),
+ ),
];
for (uid, expected) in cases {
let actual = repo
@@ -237,6 +257,7 @@ async fn crm_company_access_maps_team_role_to_access_level(pool: PgPool) -> anyh
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);
+ let team_alpha = Uuid::parse_str(TEAM_ALPHA)?;
assert_eq!(
repo.get_crm_company_access(&company_id.to_string(), Some(&user_id(TEAM_MEMBER)))
@@ -246,12 +267,18 @@ async fn crm_company_access_hides_from_member_when_hidden(pool: PgPool) -> anyho
assert_eq!(
repo.get_crm_company_access(&company_id.to_string(), Some(&user_id(TEAM_ADMIN)))
.await?,
- Some(AccessLevel::Edit),
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::Edit,
+ team_id: team_alpha,
+ }),
);
assert_eq!(
repo.get_crm_company_access(&company_id.to_string(), Some(&user_id(TEAM_OWNER)))
.await?,
- Some(AccessLevel::Owner),
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::Owner,
+ team_id: team_alpha,
+ }),
);
Ok(())
}
@@ -313,10 +340,30 @@ async fn crm_contact_access_maps_team_role_to_access_level(pool: PgPool) -> anyh
let contact_id = insert_crm_contact(&pool, company_id, false).await?;
let repo = PgAccessRepository::new(pool);
+ // The owning team is the contact's parent company's team.
+ let team_alpha = Uuid::parse_str(TEAM_ALPHA)?;
let cases = [
- (TEAM_MEMBER, Some(AccessLevel::View)),
- (TEAM_ADMIN, Some(AccessLevel::Edit)),
- (TEAM_OWNER, Some(AccessLevel::Owner)),
+ (
+ TEAM_MEMBER,
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::View,
+ team_id: team_alpha,
+ }),
+ ),
+ (
+ TEAM_ADMIN,
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::Edit,
+ team_id: team_alpha,
+ }),
+ ),
+ (
+ TEAM_OWNER,
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::Owner,
+ team_id: team_alpha,
+ }),
+ ),
];
for (uid, expected) in cases {
let actual = repo
@@ -335,6 +382,7 @@ async fn crm_contact_access_hidden_contact_blocks_member(pool: PgPool) -> anyhow
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);
+ let team_alpha = Uuid::parse_str(TEAM_ALPHA)?;
assert_eq!(
repo.get_crm_contact_access(&contact_id.to_string(), Some(&user_id(TEAM_MEMBER)))
@@ -344,7 +392,10 @@ async fn crm_contact_access_hidden_contact_blocks_member(pool: PgPool) -> anyhow
assert_eq!(
repo.get_crm_contact_access(&contact_id.to_string(), Some(&user_id(TEAM_ADMIN)))
.await?,
- Some(AccessLevel::Edit),
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::Edit,
+ team_id: team_alpha,
+ }),
);
Ok(())
}
diff --git a/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs b/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs
index 453b7e0c3c..fe0d03909e 100644
--- a/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs
@@ -190,6 +190,15 @@ impl EntityAccessService for NoopEntityAccessService {
unreachable!("InternalUser extension should bypass real access checks")
}
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<(EntityPermission, uuid::Uuid), AccessError> {
+ unreachable!("InternalUser extension should bypass real access checks")
+ }
+
async fn get_users_by_entity(
&self,
_entity_id: &str,
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 3469a3bf3d..1b1b736494 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -7,6 +7,7 @@ pub use grouping::{
use call::domain::models::GetCallRecordsRequest;
use comms::domain::models::GetChannelsRequest;
+use crm::domain::auth::CrmTeamReceipt;
use crm::domain::companies_repo::{CrmCompanyListSort, CrmCompanySoupCursor};
use email::domain::models::{GetEmailsRequest, PreviewView};
use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};
@@ -365,11 +366,13 @@ impl SoupRequest<Option<EntityFilterAst>> {
team_receipt: &Option<EntityAccessReceipt<MemberTeamRole>>,
) -> Option<GetCrmCompaniesRequest> {
let receipt = team_receipt.as_ref()?;
- let team_id = Uuid::parse_str(&receipt.entity().entity_id)
+ // Re-wrap the verified team receipt as the CRM capability token the
+ // service now requires; a malformed receipt skips the sub-request.
+ let access = CrmTeamReceipt::from_team_receipt(receipt.clone())
.inspect_err(|e| {
tracing::warn!(
error=?e,
- "team_receipt entity_id is not a valid uuid; skipping crm_company sub-request"
+ "team_receipt is not a valid CRM team receipt; skipping crm_company sub-request"
);
})
.ok()?;
@@ -417,7 +420,7 @@ impl SoupRequest<Option<EntityFilterAst>> {
}
Some(GetCrmCompaniesRequest {
- team_id,
+ access,
user_id: self.user.clone(),
company_ids: extract.ids,
hidden: extract.hidden,
@@ -497,8 +500,9 @@ impl SoupRequest<Option<EntityFilterAst>> {
/// Parameters for fetching CRM companies to fold into the soup feed.
#[derive(Debug)]
pub struct GetCrmCompaniesRequest {
- /// Team whose CRM companies to list. Derived from the team receipt.
- pub team_id: Uuid,
+ /// Capability token for the team whose CRM companies to list. The
+ /// service derives the team id from it.
+ pub access: CrmTeamReceipt<MemberTeamRole>,
/// Requesting user — used to scope the per-user `UserHistory` join
/// behind the `Viewed*` sort variants. Always populated; the soup
/// request always has a user.
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index b3d4a4436e..1d0657336a 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -409,7 +409,7 @@ where
};
let GetCrmCompaniesRequest {
- team_id,
+ access,
user_id,
company_ids,
hidden,
@@ -421,7 +421,7 @@ where
Ok(Either::Right(
self.crm_service
.list_companies_for_soup(
- &team_id,
+ &access,
user_id.as_ref(),
&company_ids,
hidden,
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 5cd1f2f458..8ed8edbb24 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -338,6 +338,20 @@ impl entity_access::domain::ports::EntityAccessService for MockEntityAccess {
unimplemented!()
}
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<
+ &macro_user_id::user_id::MacroUserId<macro_user_id::lowercased::Lowercase<'_>>,
+ >,
+ _entity_id: &str,
+ _entity_type: entity_access::domain::models::EntityType,
+ ) -> Result<
+ (entity_access::domain::models::EntityPermission, uuid::Uuid),
+ entity_access::domain::models::AccessError,
+ > {
+ unimplemented!()
+ }
+
async fn get_users_by_entity(
&self,
_entity_id: &str,