Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(crm): macro authorization (#4972)

Will Hutchinson8e08bee64152
diff --git a/Cargo.lock b/Cargo.lock
index 6238257418..55e87b00cb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3354,14 +3354,15 @@ dependencies = [
"axum",
"chrono",
"entity_access",
+ "macro_authorization",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
"model-error-response",
- "model_user",
"models_properties",
"properties",
"reqwest 0.13.4",
+ "rootcause",
"schemars 1.2.1",
"serde",
"serde_json",
@@ -3369,6 +3370,7 @@ dependencies = [
"system_properties",
"thiserror 2.0.18",
"tokio",
+ "tower 0.5.3",
"tracing",
"unfurl",
"utoipa",
diff --git a/crates/crm/Cargo.toml b/crates/crm/Cargo.toml
index d0b62312d0..b110875b3f 100644
--- a/crates/crm/Cargo.toml
+++ b/crates/crm/Cargo.toml
@@ -18,13 +18,14 @@ ai_tools = [
]
axum = [
"dep:axum",
+ "dep:macro_authorization",
"dep:macro_uuid",
"dep:model-error-response",
- "dep:model_user",
"dep:utoipa",
"entity_access/axum",
"entity_access/inbound",
"entity_access/ports",
+ "ports",
]
default = ["ai_tools", "inbound", "outbound", "ports"]
inbound = ["axum", "ports"]
@@ -58,9 +59,9 @@ system_properties = { path = "../system_properties", optional = true }
# Axum / inbound dependencies
axum = { workspace = true, optional = true }
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }
macro_uuid = { path = "../macro_uuid", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
-model_user = { path = "../model_user", optional = true, features = ["axum"] }
utoipa = { workspace = true, optional = true }
# Outbound dependencies
@@ -71,4 +72,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
+macro_user_id = { path = "../macro_user_id" }
+rootcause = { workspace = true }
tokio = { workspace = true, features = ["macros"] }
+tower = { workspace = true }
diff --git a/crates/crm/src/inbound/axum_extractors.rs b/crates/crm/src/inbound/axum_extractors.rs
index ec97c482c7..20a2a91312 100644
--- a/crates/crm/src/inbound/axum_extractors.rs
+++ b/crates/crm/src/inbound/axum_extractors.rs
@@ -7,6 +7,9 @@
//! knows nothing about CRM models, so the CRM-typed extractors and the
//! receipts they produce are the trusted seam that lives here.
+#[cfg(test)]
+mod test;
+
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;
@@ -23,7 +26,9 @@ use entity_access::{
},
inbound::axum_extractors::ExtractorError,
};
-use model_user::axum_extractor::MacroUserExtractor;
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
use uuid::Uuid;
use crate::{
@@ -37,6 +42,8 @@ use crate::{
/// Validates that the user satisfies the required permission for a CRM
/// company and mints a [`CrmCompanyReceipt`] for downstream service calls.
+/// The acting user is authenticated through the authorization service in
+/// router state, supporting direct credentials and internal service callers.
///
/// Access derives from the caller's role on the owning team: team owners
/// get `Owner`, admins get `Edit`, members get `View`. Hidden companies are
@@ -48,17 +55,19 @@ use crate::{
/// 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> {
+pub struct CrmCompanyAccessLevelExtractor<T: RequiredPermission, Svc, Auth> {
/// Capability token authorizing CRM company service calls.
pub receipt: CrmCompanyReceipt<T>,
- _marker: PhantomData<(T, Svc)>,
+ _marker: PhantomData<(T, Svc, Auth)>,
}
-impl<T, S, Svc> FromRequestParts<S> for CrmCompanyAccessLevelExtractor<T, Svc>
+impl<T, S, Svc, Auth> FromRequestParts<S> for CrmCompanyAccessLevelExtractor<T, Svc, Auth>
where
T: RequiredPermission,
Arc<Svc>: FromRef<S>,
+ MacroAuthorizationState<Auth>: FromRef<S>,
Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
type Rejection = ExtractorError;
@@ -73,10 +82,10 @@ where
.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 MacroAuthorizationExtractor { macro_user_id, .. } =
+ MacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ .await
+ .map_err(ExtractorError::from)?;
let (permission, team_id) = service
.get_crm_entity_permission_with_team(
@@ -109,6 +118,8 @@ where
/// Validates that the user satisfies the required permission for a CRM
/// contact and mints a [`CrmContactReceipt`] for downstream service calls.
+/// The acting user is authenticated through the authorization service in
+/// router state, supporting direct credentials and internal service callers.
///
/// 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
@@ -119,17 +130,19 @@ where
/// 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> {
+pub struct CrmContactAccessLevelExtractor<T: RequiredPermission, Svc, Auth> {
/// Capability token authorizing CRM contact service calls.
pub receipt: CrmContactReceipt<T>,
- _marker: PhantomData<(T, Svc)>,
+ _marker: PhantomData<(T, Svc, Auth)>,
}
-impl<T, S, Svc> FromRequestParts<S> for CrmContactAccessLevelExtractor<T, Svc>
+impl<T, S, Svc, Auth> FromRequestParts<S> for CrmContactAccessLevelExtractor<T, Svc, Auth>
where
T: RequiredPermission,
Arc<Svc>: FromRef<S>,
+ MacroAuthorizationState<Auth>: FromRef<S>,
Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
type Rejection = ExtractorError;
@@ -144,10 +157,10 @@ where
.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 MacroAuthorizationExtractor { macro_user_id, .. } =
+ MacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ .await
+ .map_err(ExtractorError::from)?;
let (permission, team_id) = service
.get_crm_entity_permission_with_team(
@@ -181,26 +194,30 @@ where
/// Validates that the user satisfies the required permission for the CRM
/// 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.
+/// the owning entity via `CrmService::get_comment_entity`. The acting user
+/// is authenticated through the authorization service in router state for
+/// both direct credentials and internal service access. 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> {
+pub struct CrmCommentAccessLevelExtractor<T: RequiredPermission, C, Eas, Auth> {
/// Capability token authorizing CRM comment service calls.
pub receipt: CrmCommentReceipt<T>,
- _marker: PhantomData<(T, C, Eas)>,
+ _marker: PhantomData<(T, C, Eas, Auth)>,
}
-impl<T, S, C, Eas> FromRequestParts<S> for CrmCommentAccessLevelExtractor<T, C, Eas>
+impl<T, S, C, Eas, Auth> FromRequestParts<S> for CrmCommentAccessLevelExtractor<T, C, Eas, Auth>
where
T: RequiredPermission,
CrmServiceRef<C>: FromRef<S>,
Arc<Eas>: FromRef<S>,
+ MacroAuthorizationState<Auth>: FromRef<S>,
C: CrmService,
Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
type Rejection = ExtractorError;
@@ -216,10 +233,10 @@ where
.map_err(|_| ExtractorError::BadRequest("missing comment_id path parameter"))?;
let comment_id = extract_comment_id(&path_params)?;
- let MacroUserExtractor { macro_user_id, .. } = parts
- .extract()
- .await
- .map_err(|_| ExtractorError::Unauthorized)?;
+ let MacroAuthorizationExtractor { macro_user_id, .. } =
+ MacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ .await
+ .map_err(ExtractorError::from)?;
let (crm_entity_type, entity_id) = crm_service
.get_comment_entity(&comment_id)
diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rs
new file mode 100644
index 0000000000..10727bd907
--- /dev/null
+++ b/crates/crm/src/inbound/axum_extractors/test.rs
@@ -0,0 +1,741 @@
+use std::sync::{Arc, Mutex};
+
+use axum::{
+ Json, Router,
+ body::{Body, to_bytes},
+ http::{Request, StatusCode, header},
+ routing::get,
+};
+use chrono::{DateTime, Utc};
+use entity_access::domain::{
+ models::{
+ AccessError, AccessLevel, BotId, CallChannelInfo, EditAccessLevel, EntityAccessReceipt,
+ EntityPermission, EntityType, MemberTeamRole, RequiredPermission, UserTeamInfo,
+ ViewAccessLevel,
+ },
+ ports::EntityAccessService,
+};
+use macro_authorization::{
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalAuthConfig, JwtValidator,
+ MacroAuthorizationError, MacroAuthorizationServiceImpl, MacroAuthorizationState,
+ ValidatedIdentity,
+};
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+use rootcause::Report;
+use serde_json::{Value, json};
+use tower::ServiceExt;
+use uuid::Uuid;
+
+use super::{
+ CrmCommentAccessLevelExtractor, CrmCompanyAccessLevelExtractor, CrmContactAccessLevelExtractor,
+};
+use crate::{
+ domain::{
+ auth::{CrmCommentReceipt, CrmCompanyReceipt, CrmContactReceipt, CrmTeamReceipt},
+ comment::{CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult},
+ companies_repo::{CrmCompanyListSort, CrmCompanySoupCursor},
+ model::{
+ CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError, CrmScopePrecheck,
+ },
+ service::CrmService,
+ },
+ inbound::axum_router::CrmRouterState,
+};
+
+const USER_ID: &str = "macro|[email protected]";
+const INTERNAL_USER_ID: &str = "macro|[email protected]";
+const VALID_TOKEN: &str = "valid";
+const INTERNAL_KEY: &str = "valid-internal-key";
+const COMPANY_ID: &str = "11111111-1111-4111-8111-111111111111";
+const CONTACT_ID: &str = "22222222-2222-4222-8222-222222222222";
+const COMMENT_ID: &str = "33333333-3333-4333-8333-333333333333";
+const PARENT_ID: &str = "44444444-4444-4444-8444-444444444444";
+const TEAM_ID: &str = "55555555-5555-4555-8555-555555555555";
+
+#[derive(Clone, Default)]
+struct FakeJwtValidator;
+
+impl JwtValidator for FakeJwtValidator {
+ fn validate(&self, jwt: &str) -> Result<ValidatedIdentity, Report<MacroAuthorizationError>> {
+ match jwt {
+ VALID_TOKEN => Ok(ValidatedIdentity {
+ user_id: USER_ID.to_string(),
+ fusion_user_id: "test-fusion-user".to_string(),
+ organization_id: None,
+ permissions: None,
+ }),
+ "expired" => Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+}
+
+type TestAuthorizationService = MacroAuthorizationServiceImpl<FakeJwtValidator>;
+
+#[derive(Clone, Copy)]
+enum PermissionResult {
+ Allowed(EntityPermission),
+ Unauthorized,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct EntityAccessCall {
+ user_id: Option<String>,
+ entity_id: String,
+ entity_type: EntityType,
+}
+
+#[derive(Clone)]
+struct FakeEntityAccessService {
+ result: PermissionResult,
+ calls: Arc<Mutex<Vec<EntityAccessCall>>>,
+}
+
+impl FakeEntityAccessService {
+ fn with_access_level(access_level: AccessLevel) -> Self {
+ Self {
+ result: PermissionResult::Allowed(EntityPermission::AccessLevel { access_level }),
+ calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn unauthorized() -> Self {
+ Self {
+ result: PermissionResult::Unauthorized,
+ calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn calls(&self) -> Vec<EntityAccessCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+}
+
+impl EntityAccessService for FakeEntityAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ panic!("unexpected generate_entity_access_receipt call")
+ }
+
+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _bot_id: BotId,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ panic!("unexpected generate_bot_entity_access_receipt call")
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ panic!("unexpected get_access_level call")
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_access call")
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_public_access call")
+ }
+
+ async fn get_entity_permission(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _organization_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ panic!("unexpected get_entity_permission call")
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<(EntityPermission, Uuid), AccessError> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(EntityAccessCall {
+ user_id: user_id.map(|user_id| user_id.as_ref().to_string()),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+
+ match self.result {
+ PermissionResult::Allowed(permission) => Ok((permission, uuid(TEAM_ID))),
+ PermissionResult::Unauthorized => Err(AccessError::Unauthorized),
+ }
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ panic!("unexpected get_users_by_entity call")
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel call")
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel_by_channel_id call")
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ panic!("unexpected get_user_team call")
+ }
+}
+
+#[derive(Clone)]
+struct FakeCrmService {
+ comment_entity: Option<(CrmCommentEntityType, Uuid)>,
+ comment_calls: Arc<Mutex<Vec<Uuid>>>,
+}
+
+impl FakeCrmService {
+ fn new(comment_entity: Option<(CrmCommentEntityType, Uuid)>) -> Self {
+ Self {
+ comment_entity,
+ comment_calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn comment_calls(&self) -> Vec<Uuid> {
+ self.comment_calls
+ .lock()
+ .expect("comment calls lock poisoned")
+ .clone()
+ }
+}
+
+impl CrmService for FakeCrmService {
+ async fn populate_contact(
+ &self,
+ _team_id: &Uuid,
+ _link_id: &Uuid,
+ _user_email: &str,
+ _email: &str,
+ _name: Option<&str>,
+ _first_at: DateTime<Utc>,
+ _last_at: DateTime<Utc>,
+ _is_sent: bool,
+ ) -> Result<(), CrmError> {
+ panic!("unexpected populate_contact call")
+ }
+
+ async fn depopulate_contact(
+ &self,
+ _team_id: &Uuid,
+ _link_id: &Uuid,
+ _email: &str,
+ ) -> Result<(), CrmError> {
+ panic!("unexpected depopulate_contact call")
+ }
+
+ async fn depopulate_link_in_team(
+ &self,
+ _team_id: &Uuid,
+ _link_id: &Uuid,
+ ) -> Result<(), CrmError> {
+ panic!("unexpected depopulate_link_in_team call")
+ }
+
+ async fn get_team_id_for_user(&self, _macro_id: &str) -> Result<Option<Uuid>, CrmError> {
+ panic!("unexpected get_team_id_for_user call")
+ }
+
+ async fn set_email_sync(
+ &self,
+ _access: &CrmCompanyReceipt<EditAccessLevel>,
+ _email_sync: bool,
+ ) -> Result<(), CrmError> {
+ panic!("unexpected set_email_sync call")
+ }
+
+ async fn set_company_hidden(
+ &self,
+ _access: &CrmCompanyReceipt<EditAccessLevel>,
+ _hidden: bool,
+ ) -> Result<(), CrmError> {
+ panic!("unexpected set_company_hidden call")
+ }
+
+ async fn set_contact_hidden(
+ &self,
+ _access: &CrmContactReceipt<EditAccessLevel>,
+ _hidden: bool,
+ ) -> Result<(), CrmError> {
+ panic!("unexpected set_contact_hidden call")
+ }
+
+ async fn crm_scope_precheck(
+ &self,
+ _team_id: &Uuid,
+ _domains: &[String],
+ _addresses: &[String],
+ ) -> Result<CrmScopePrecheck, CrmError> {
+ panic!("unexpected crm_scope_precheck call")
+ }
+
+ async fn list_companies_for_soup(
+ &self,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
+ _user_id: &str,
+ _company_ids: &[Uuid],
+ _hidden: Option<bool>,
+ _sort: CrmCompanyListSort,
+ _cursor: Option<CrmCompanySoupCursor>,
+ _limit: i64,
+ ) -> Result<Vec<CrmCompanyForSoup>, CrmError> {
+ panic!("unexpected list_companies_for_soup call")
+ }
+
+ async fn list_contacts_for_company(
+ &self,
+ _access: &CrmCompanyReceipt<ViewAccessLevel>,
+ ) -> Result<Vec<CrmContact>, CrmError> {
+ panic!("unexpected list_contacts_for_company call")
+ }
+
+ async fn get_contact_for_team(
+ &self,
+ _access: &CrmContactReceipt<ViewAccessLevel>,
+ ) -> Result<Option<CrmContact>, CrmError> {
+ panic!("unexpected get_contact_for_team call")
+ }
+
+ async fn get_company_for_team(
+ &self,
+ _access: &CrmCompanyReceipt<ViewAccessLevel>,
+ ) -> Result<Option<CrmCompanyWithContacts>, CrmError> {
+ panic!("unexpected get_company_for_team call")
+ }
+
+ async fn create_crm_comment(
+ &self,
+ _access: &CrmCommentReceipt<ViewAccessLevel>,
+ _owner: &str,
+ _thread_id: Option<Uuid>,
+ _thread_metadata: Option<Value>,
+ _text: &str,
+ _metadata: Option<Value>,
+ ) -> Result<CrmCommentThread, CrmError> {
+ panic!("unexpected create_crm_comment call")
+ }
+
+ async fn get_crm_comment_threads(
+ &self,
+ _access: &CrmCommentReceipt<ViewAccessLevel>,
+ ) -> Result<Vec<CrmCommentThread>, CrmError> {
+ panic!("unexpected get_crm_comment_threads call")
+ }
+
+ async fn edit_crm_comment(
+ &self,
+ _access: &CrmCommentReceipt<ViewAccessLevel>,
+ _comment_id: &Uuid,
+ _text: &str,
+ ) -> Result<CrmComment, CrmError> {
+ panic!("unexpected edit_crm_comment call")
+ }
+
+ async fn delete_crm_comment(
+ &self,
+ _access: &CrmCommentReceipt<ViewAccessLevel>,
+ _comment_id: &Uuid,
+ ) -> Result<DeleteCrmCommentResult, CrmError> {
+ panic!("unexpected delete_crm_comment call")
+ }
+
+ async fn get_comment_entity(
+ &self,
+ comment_id: &Uuid,
+ ) -> Result<Option<(CrmCommentEntityType, Uuid)>, CrmError> {
+ self.comment_calls
+ .lock()
+ .expect("comment calls lock poisoned")
+ .push(*comment_id);
+ Ok(self.comment_entity)
+ }
+}
+
+async fn company_handler(
+ extractor: CrmCompanyAccessLevelExtractor<
+ EditAccessLevel,
+ FakeEntityAccessService,
+ TestAuthorizationService,
+ >,
+) -> Json<Value> {
+ receipt_response(extractor.receipt.receipt(), extractor.receipt.team_id())
+}
+
+async fn contact_handler(
+ extractor: CrmContactAccessLevelExtractor<
+ EditAccessLevel,
+ FakeEntityAccessService,
+ TestAuthorizationService,
+ >,
+) -> Json<Value> {
+ receipt_response(extractor.receipt.receipt(), extractor.receipt.team_id())
+}
+
+async fn comment_handler(
+ extractor: CrmCommentAccessLevelExtractor<
+ EditAccessLevel,
+ FakeCrmService,
+ FakeEntityAccessService,
+ TestAuthorizationService,
+ >,
+) -> Json<Value> {
+ receipt_response(extractor.receipt.receipt(), extractor.receipt.team_id())
+}
+
+fn receipt_response<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+ team_id: Uuid,
+) -> Json<Value> {
+ Json(json!({
+ "user_id": receipt
+ .get_authenticated_user()
+ .expect("CRM extractors require an authenticated user")
+ .to_string(),
+ "entity_id": receipt.entity().entity_id,
+ "entity_type": receipt.entity().entity_type.to_string(),
+ "permission": receipt.entity_permission(),
+ "team_id": team_id,
+ }))
+}
+
+fn test_router(
+ entity_access: FakeEntityAccessService,
+ comment_entity: Option<(CrmCommentEntityType, Uuid)>,
+) -> (Router, FakeEntityAccessService, FakeCrmService) {
+ let crm_service = FakeCrmService::new(comment_entity);
+ let authorization_service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator,
+ InternalAuthConfig {
+ api_key: INTERNAL_KEY.to_string(),
+ default_user_id: None,
+ },
+ );
+ let state: CrmRouterState<FakeCrmService, FakeEntityAccessService, TestAuthorizationService> =
+ CrmRouterState {
+ service: Arc::new(crm_service.clone()),
+ entity_access_service: Arc::new(entity_access.clone()),
+ authorization_state: MacroAuthorizationState::new(Arc::new(authorization_service)),
+ };
+ let router = Router::new()
+ .route("/companies/{company_id}", get(company_handler))
+ .route("/company-without-id/{other_id}", get(company_handler))
+ .route("/contacts/{contact_id}", get(contact_handler))
+ .route("/contact-without-id/{other_id}", get(contact_handler))
+ .route("/comments/{comment_id}", get(comment_handler))
+ .with_state(state);
+
+ (router, entity_access, crm_service)
+}
+
+fn uuid(value: &str) -> Uuid {
+ Uuid::parse_str(value).expect("test UUID should be valid")
+}
+
+fn bearer_request(path: &str, token: &str) -> Request<Body> {
+ Request::get(path)
+ .header(header::AUTHORIZATION, format!("Bearer {token}"))
+ .body(Body::empty())
+ .unwrap()
+}
+
+fn internal_request(path: &str, acting_user: Option<&str>) -> Request<Body> {
+ let mut request = Request::get(path).header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY);
+ if let Some(acting_user) = acting_user {
+ request = request.header(INTERNAL_MACRO_USER_ID_HEADER, acting_user);
+ }
+ request.body(Body::empty()).unwrap()
+}
+
+async fn send(router: &Router, request: Request<Body>) -> (StatusCode, Value) {
+ let response = router.clone().oneshot(request).await.unwrap();
+ let status = response.status();
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let body = serde_json::from_slice(&body).expect("response should contain JSON");
+ (status, body)
+}
+
+#[tokio::test]
+async fn valid_company_and_contact_receipts_contain_the_entity_and_owning_team() {
+ let access = FakeEntityAccessService::with_access_level(AccessLevel::Edit);
+ let (router, access, _crm) = test_router(access, None);
+
+ for (path, expected_id, expected_type) in [
+ (
+ format!("/companies/{COMPANY_ID}"),
+ COMPANY_ID,
+ EntityType::CrmCompany,
+ ),
+ (
+ format!("/contacts/{CONTACT_ID}"),
+ CONTACT_ID,
+ EntityType::CrmContact,
+ ),
+ ] {
+ let (status, body) = send(&router, bearer_request(&path, VALID_TOKEN)).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["user_id"], USER_ID);
+ assert_eq!(body["entity_id"], expected_id);
+ assert_eq!(body["entity_type"], expected_type.to_string());
+ assert_eq!(body["permission"]["access_level"], "edit");
+ assert_eq!(body["team_id"], TEAM_ID);
+ }
+
+ assert_eq!(
+ access.calls(),
+ [
+ EntityAccessCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: COMPANY_ID.to_string(),
+ entity_type: EntityType::CrmCompany,
+ },
+ EntityAccessCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: CONTACT_ID.to_string(),
+ entity_type: EntityType::CrmContact,
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn insufficient_company_and_contact_permissions_return_unauthorized() {
+ let access = FakeEntityAccessService::with_access_level(AccessLevel::View);
+ let (router, access, _crm) = test_router(access, None);
+
+ for path in [
+ format!("/companies/{COMPANY_ID}"),
+ format!("/contacts/{CONTACT_ID}"),
+ ] {
+ let (status, _body) = send(&router, bearer_request(&path, VALID_TOKEN)).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ }
+
+ assert_eq!(access.calls().len(), 2);
+}
+
+#[tokio::test]
+async fn malformed_and_missing_company_and_contact_ids_return_bad_request() {
+ let access = FakeEntityAccessService::with_access_level(AccessLevel::Edit);
+ let (router, access, _crm) = test_router(access, None);
+ let cases = [
+ (
+ "/companies/not-a-uuid",
+ "Bad request: invalid CRM company ID format",
+ ),
+ (
+ "/company-without-id/value",
+ "Bad request: missing company_id path parameter",
+ ),
+ (
+ "/contacts/not-a-uuid",
+ "Bad request: invalid CRM contact ID format",
+ ),
+ (
+ "/contact-without-id/value",
+ "Bad request: missing contact_id path parameter",
+ ),
+ ];
+
+ for (path, expected_message) in cases {
+ let request = Request::get(path).body(Body::empty()).unwrap();
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(body, json!({ "message": expected_message }));
+ }
+
+ assert!(access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn internal_company_and_contact_requests_check_access_as_the_acting_user() {
+ let access = FakeEntityAccessService::with_access_level(AccessLevel::Edit);
+ let (router, access, _crm) = test_router(access, None);
+
+ for path in [
+ format!("/companies/{COMPANY_ID}"),
+ format!("/contacts/{CONTACT_ID}"),
+ ] {
+ let (status, body) = send(&router, internal_request(&path, Some(INTERNAL_USER_ID))).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["user_id"], INTERNAL_USER_ID);
+ }
+
+ assert_eq!(
+ access.calls(),
+ [
+ EntityAccessCall {
+ user_id: Some(INTERNAL_USER_ID.to_string()),
+ entity_id: COMPANY_ID.to_string(),
+ entity_type: EntityType::CrmCompany,
+ },
+ EntityAccessCall {
+ user_id: Some(INTERNAL_USER_ID.to_string()),
+ entity_id: CONTACT_ID.to_string(),
+ entity_type: EntityType::CrmContact,
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn credential_failures_happen_before_permission_lookup() {
+ enum Credentials {
+ Missing,
+ Bearer(&'static str),
+ IdentityLessInternal,
+ }
+
+ let cases = [
+ (Credentials::Missing, "unauthorized"),
+ (Credentials::Bearer("invalid"), "unauthorized"),
+ (Credentials::Bearer("expired"), "jwt expired"),
+ (Credentials::IdentityLessInternal, "unauthorized"),
+ ];
+
+ for (credentials, expected_message) in cases {
+ let access = FakeEntityAccessService::with_access_level(AccessLevel::Edit);
+ let (router, access, _crm) = test_router(access, None);
+ let path = format!("/companies/{COMPANY_ID}");
+ let request = match credentials {
+ Credentials::Missing => Request::get(path).body(Body::empty()).unwrap(),
+ Credentials::Bearer(token) => bearer_request(&path, token),
+ Credentials::IdentityLessInternal => internal_request(&path, None),
+ };
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": expected_message }));
+ assert!(access.calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn comment_receipt_resolves_its_parent_entity_and_team() {
+ let access = FakeEntityAccessService::with_access_level(AccessLevel::Edit);
+ let comment_entity = Some((CrmCommentEntityType::CrmContact, uuid(PARENT_ID)));
+ let (router, access, crm) = test_router(access, comment_entity);
+
+ let (status, body) = send(
+ &router,
+ bearer_request(&format!("/comments/{COMMENT_ID}"), VALID_TOKEN),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["entity_id"], PARENT_ID);
+ assert_eq!(body["entity_type"], EntityType::CrmContact.to_string());
+ assert_eq!(body["team_id"], TEAM_ID);
+ assert_eq!(crm.comment_calls(), [uuid(COMMENT_ID)]);
+ assert_eq!(
+ access.calls(),
+ [EntityAccessCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: PARENT_ID.to_string(),
+ entity_type: EntityType::CrmContact,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn missing_comment_preserves_not_found_anti_oracle_response() {
+ let access = FakeEntityAccessService::with_access_level(AccessLevel::Edit);
+ let (router, access, crm) = test_router(access, None);
+
+ let (status, body) = send(
+ &router,
+ bearer_request(&format!("/comments/{COMMENT_ID}"), VALID_TOKEN),
+ )
+ .await;
+
+ assert_comment_not_found(status, body);
+ assert_eq!(crm.comment_calls(), [uuid(COMMENT_ID)]);
+ assert!(access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn denied_comment_parent_access_preserves_not_found_anti_oracle_response() {
+ let access = FakeEntityAccessService::unauthorized();
+ let comment_entity = Some((CrmCommentEntityType::CrmCompany, uuid(PARENT_ID)));
+ let (router, access, _crm) = test_router(access, comment_entity);
+
+ let (status, body) = send(
+ &router,
+ bearer_request(&format!("/comments/{COMMENT_ID}"), VALID_TOKEN),
+ )
+ .await;
+
+ assert_comment_not_found(status, body);
+ assert_eq!(access.calls().len(), 1);
+}
+
+#[tokio::test]
+async fn insufficient_comment_permission_preserves_not_found_anti_oracle_response() {
+ let access = FakeEntityAccessService::with_access_level(AccessLevel::View);
+ let comment_entity = Some((CrmCommentEntityType::CrmCompany, uuid(PARENT_ID)));
+ let (router, access, _crm) = test_router(access, comment_entity);
+
+ let (status, body) = send(
+ &router,
+ bearer_request(&format!("/comments/{COMMENT_ID}"), VALID_TOKEN),
+ )
+ .await;
+
+ assert_comment_not_found(status, body);
+ assert_eq!(access.calls().len(), 1);
+}
+
+fn assert_comment_not_found(status: StatusCode, body: Value) {
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ assert_eq!(
+ body,
+ json!({ "message": "Not found: CRM comment not found" })
+ );
+}
diff --git a/crates/crm/src/inbound/axum_router/comments.rs b/crates/crm/src/inbound/axum_router/comments.rs
index 9ffab2495c..f68bd1a722 100644
--- a/crates/crm/src/inbound/axum_router/comments.rs
+++ b/crates/crm/src/inbound/axum_router/comments.rs
@@ -17,6 +17,7 @@ use entity_access::{
domain::{models::ViewAccessLevel, ports::EntityAccessService},
inbound::axum_extractors::EntityPermissionExtractor,
};
+use macro_authorization::MacroAuthorizationService;
use model_error_response::ErrorResponse;
use serde::Deserialize;
use serde_json::Value;
@@ -80,9 +81,13 @@ pub struct EditCrmCommentRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(entity_id = %entity_id))]
-pub async fn list_handler<C: CrmService, Eas: EntityAccessService>(
- access: EntityPermissionExtractor<Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn list_handler<
+ C: CrmService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: EntityPermissionExtractor<Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path((_entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
) -> Result<Json<Vec<CrmCommentThread>>, CrmError> {
let team_id = owning_team_for_entity(&state, &access).await?;
@@ -114,9 +119,13 @@ pub async fn list_handler<C: CrmService, Eas: EntityAccessService>(
),
)]
#[tracing::instrument(skip_all, err, fields(entity_id = %entity_id))]
-pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
- access: EntityPermissionExtractor<Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn create_handler<
+ C: CrmService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: EntityPermissionExtractor<Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path((_entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
Json(req): Json<CreateCrmCommentRequest>,
) -> Result<Json<CrmCommentThread>, CrmError> {
@@ -168,9 +177,13 @@ pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
),
)]
#[tracing::instrument(skip_all, err, fields(comment_id = %comment_id))]
-pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
- access: CrmCommentAccessLevelExtractor<ViewAccessLevel, C, Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn edit_handler<
+ C: CrmService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: CrmCommentAccessLevelExtractor<ViewAccessLevel, C, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path(comment_id): Path<Uuid>,
Json(req): Json<EditCrmCommentRequest>,
) -> Result<Json<CrmComment>, CrmError> {
@@ -207,9 +220,13 @@ pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
),
)]
#[tracing::instrument(skip_all, err, fields(comment_id = %comment_id))]
-pub async fn delete_handler<C: CrmService, Eas: EntityAccessService>(
- access: CrmCommentAccessLevelExtractor<ViewAccessLevel, C, Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn delete_handler<
+ C: CrmService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: CrmCommentAccessLevelExtractor<ViewAccessLevel, C, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path(comment_id): Path<Uuid>,
) -> Result<Json<DeleteCrmCommentResult>, CrmError> {
let result = state
@@ -225,9 +242,13 @@ pub async fn delete_handler<C: CrmService, Eas: EntityAccessService>(
/// 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>,
+async fn owning_team_for_entity<
+ C: CrmService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ state: &CrmRouterState<C, Eas, Auth>,
+ access: &EntityPermissionExtractor<Eas, Auth>,
) -> Result<Uuid, CrmError> {
let user_id = access
.entity_access_receipt
diff --git a/crates/crm/src/inbound/axum_router/get_company.rs b/crates/crm/src/inbound/axum_router/get_company.rs
index 069b74be40..e03b637753 100644
--- a/crates/crm/src/inbound/axum_router/get_company.rs
+++ b/crates/crm/src/inbound/axum_router/get_company.rs
@@ -4,6 +4,7 @@ use axum::{
};
use chrono::{DateTime, Utc};
use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
use model_error_response::ErrorResponse;
use serde::Serialize;
use utoipa::ToSchema;
@@ -125,9 +126,9 @@ impl From<CrmCompanyWithContacts> for CrmCompanyResponse {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path(company_id): Path<Uuid>,
) -> Result<Json<CrmCompanyResponse>, CrmError> {
let record = state
diff --git a/crates/crm/src/inbound/axum_router/get_contact.rs b/crates/crm/src/inbound/axum_router/get_contact.rs
index b2f1b76b96..6a77ebd06c 100644
--- a/crates/crm/src/inbound/axum_router/get_contact.rs
+++ b/crates/crm/src/inbound/axum_router/get_contact.rs
@@ -3,6 +3,7 @@ use axum::{
extract::{Path, State},
};
use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
use model_error_response::ErrorResponse;
use uuid::Uuid;
@@ -33,9 +34,9 @@ use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
),
)]
#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: CrmContactAccessLevelExtractor<ViewAccessLevel, Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: CrmContactAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path(contact_id): Path<Uuid>,
) -> Result<Json<CrmContactResponse>, CrmError> {
let contact = state
diff --git a/crates/crm/src/inbound/axum_router/list_company_contacts.rs b/crates/crm/src/inbound/axum_router/list_company_contacts.rs
index c6fa83d729..af8b48eaa7 100644
--- a/crates/crm/src/inbound/axum_router/list_company_contacts.rs
+++ b/crates/crm/src/inbound/axum_router/list_company_contacts.rs
@@ -4,6 +4,7 @@ use axum::{
};
use chrono::{DateTime, Utc};
use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
use model_error_response::ErrorResponse;
use serde::Serialize;
use utoipa::ToSchema;
@@ -82,9 +83,9 @@ impl From<CrmContact> for CrmContactResponse {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path(company_id): Path<Uuid>,
) -> Result<Json<Vec<CrmContactResponse>>, CrmError> {
let contacts = state
diff --git a/crates/crm/src/inbound/axum_router/mod.rs b/crates/crm/src/inbound/axum_router/mod.rs
index 0c50bba474..588f72f186 100644
--- a/crates/crm/src/inbound/axum_router/mod.rs
+++ b/crates/crm/src/inbound/axum_router/mod.rs
@@ -33,24 +33,34 @@ use axum::{
routing::{get, patch, put},
};
use entity_access::domain::ports::EntityAccessService;
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
use model_error_response::ErrorResponse;
use crate::domain::{model::CrmError, service::CrmService};
-/// Router state for the CRM endpoints.
-pub struct CrmRouterState<C, Eas> {
+/// Router state for the CRM endpoints, including service-backed authorization
+/// for direct user credentials and internal service access.
+pub struct CrmRouterState<C, Eas, Auth> {
/// CRM service.
pub service: Arc<C>,
/// Entity access service used by the team-scoped extractors.
pub entity_access_service: Arc<Eas>,
+ /// State used to authorize direct users and internal service callers.
+ pub authorization_state: MacroAuthorizationState<Auth>,
}
-impl<C, Eas> FromRef<CrmRouterState<C, Eas>> for Arc<Eas> {
- fn from_ref(state: &CrmRouterState<C, Eas>) -> Self {
+impl<C, Eas, Auth> FromRef<CrmRouterState<C, Eas, Auth>> for Arc<Eas> {
+ fn from_ref(state: &CrmRouterState<C, Eas, Auth>) -> Self {
state.entity_access_service.clone()
}
}
+impl<C, Eas, Auth> FromRef<CrmRouterState<C, Eas, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &CrmRouterState<C, Eas, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
/// Newtype around `Arc<C>` so it can be pulled from
/// [`CrmRouterState`] via `FromRef` without colliding with
/// [`FromRef`] for [`Arc<Eas>`] in the (theoretical) case where
@@ -66,61 +76,65 @@ impl<C> Clone for CrmServiceRef<C> {
}
}
-impl<C, Eas> FromRef<CrmRouterState<C, Eas>> for CrmServiceRef<C> {
- fn from_ref(state: &CrmRouterState<C, Eas>) -> Self {
+impl<C, Eas, Auth> FromRef<CrmRouterState<C, Eas, Auth>> for CrmServiceRef<C> {
+ fn from_ref(state: &CrmRouterState<C, Eas, Auth>) -> Self {
CrmServiceRef(state.service.clone())
}
}
-// Manual Clone so C, Eas don't need Clone.
-impl<C, Eas> Clone for CrmRouterState<C, Eas> {
+// Manual Clone so C, Eas, and Auth don't need Clone.
+impl<C, Eas, Auth> Clone for CrmRouterState<C, Eas, Auth> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
entity_access_service: self.entity_access_service.clone(),
+ authorization_state: self.authorization_state.clone(),
}
}
}
/// Build the CRM router with all endpoints.
-pub fn crm_router<C, Eas, S>(state: CrmRouterState<C, Eas>) -> Router<S>
+pub fn crm_router<C, Eas, Auth, S>(state: CrmRouterState<C, Eas, Auth>) -> Router<S>
where
C: CrmService,
Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
Router::new()
.route(
"/companies/{company_id}/email-sync",
- put(set_email_sync::handler::<C, Eas>),
+ put(set_email_sync::handler::<C, Eas, Auth>),
)
.route(
"/companies/{company_id}/hidden",
- put(set_company_hidden::handler::<C, Eas>),
+ put(set_company_hidden::handler::<C, Eas, Auth>),
)
.route(
"/companies/{company_id}",
- get(get_company::handler::<C, Eas>),
+ get(get_company::handler::<C, Eas, Auth>),
)
.route(
"/companies/{company_id}/contacts",
- get(list_company_contacts::handler::<C, Eas>),
+ get(list_company_contacts::handler::<C, Eas, Auth>),
)
.route(
"/contacts/{contact_id}",
- get(get_contact::handler::<C, Eas>),
+ get(get_contact::handler::<C, Eas, Auth>),
)
.route(
"/contacts/{contact_id}/hidden",
- put(set_contact_hidden::handler::<C, Eas>),
+ put(set_contact_hidden::handler::<C, Eas, Auth>),
)
.route(
"/comments/{entity_type}/{entity_id}",
- get(comments::list_handler::<C, Eas>).post(comments::create_handler::<C, Eas>),
+ get(comments::list_handler::<C, Eas, Auth>)
+ .post(comments::create_handler::<C, Eas, Auth>),
)
.route(
"/comment/{comment_id}",
- patch(comments::edit_handler::<C, Eas>).delete(comments::delete_handler::<C, Eas>),
+ patch(comments::edit_handler::<C, Eas, Auth>)
+ .delete(comments::delete_handler::<C, Eas, Auth>),
)
.with_state(state)
}
diff --git a/crates/crm/src/inbound/axum_router/set_company_hidden.rs b/crates/crm/src/inbound/axum_router/set_company_hidden.rs
index d0c9d7b940..a63c9a1886 100644
--- a/crates/crm/src/inbound/axum_router/set_company_hidden.rs
+++ b/crates/crm/src/inbound/axum_router/set_company_hidden.rs
@@ -4,6 +4,7 @@ use axum::{
http::StatusCode,
};
use entity_access::domain::{models::EditAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
use model_error_response::ErrorResponse;
use serde::Deserialize;
use utoipa::ToSchema;
@@ -51,9 +52,9 @@ pub struct SetCompanyHiddenRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id, hidden = req.hidden))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: CrmCompanyAccessLevelExtractor<EditAccessLevel, Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: CrmCompanyAccessLevelExtractor<EditAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path(company_id): Path<Uuid>,
Json(req): Json<SetCompanyHiddenRequest>,
) -> Result<StatusCode, CrmError> {
diff --git a/crates/crm/src/inbound/axum_router/set_contact_hidden.rs b/crates/crm/src/inbound/axum_router/set_contact_hidden.rs
index b2bc3567d2..545bb076de 100644
--- a/crates/crm/src/inbound/axum_router/set_contact_hidden.rs
+++ b/crates/crm/src/inbound/axum_router/set_contact_hidden.rs
@@ -4,6 +4,7 @@ use axum::{
http::StatusCode,
};
use entity_access::domain::{models::EditAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
use model_error_response::ErrorResponse;
use serde::Deserialize;
use utoipa::ToSchema;
@@ -43,9 +44,9 @@ pub struct SetContactHiddenRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id, hidden = req.hidden))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: CrmContactAccessLevelExtractor<EditAccessLevel, Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: CrmContactAccessLevelExtractor<EditAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path(contact_id): Path<Uuid>,
Json(req): Json<SetContactHiddenRequest>,
) -> Result<StatusCode, CrmError> {
diff --git a/crates/crm/src/inbound/axum_router/set_email_sync.rs b/crates/crm/src/inbound/axum_router/set_email_sync.rs
index 8615d06ad6..24cbc90c01 100644
--- a/crates/crm/src/inbound/axum_router/set_email_sync.rs
+++ b/crates/crm/src/inbound/axum_router/set_email_sync.rs
@@ -4,6 +4,7 @@ use axum::{
http::StatusCode,
};
use entity_access::domain::{models::EditAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
use model_error_response::ErrorResponse;
use serde::Deserialize;
use utoipa::ToSchema;
@@ -48,9 +49,9 @@ pub struct SetEmailSyncRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id, email_sync = req.email_sync))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService>(
- access: CrmCompanyAccessLevelExtractor<EditAccessLevel, Eas>,
- State(state): State<CrmRouterState<C, Eas>>,
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: CrmCompanyAccessLevelExtractor<EditAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
Path(company_id): Path<Uuid>,
Json(req): Json<SetEmailSyncRequest>,
) -> Result<StatusCode, CrmError> {
diff --git a/crates/crm/src/lib.rs b/crates/crm/src/lib.rs
index acbba244d1..9fd2b5d497 100644
--- a/crates/crm/src/lib.rs
+++ b/crates/crm/src/lib.rs
@@ -14,7 +14,7 @@
pub mod domain;
/// The inbound module contains the inbound adapters for CRM
-#[cfg(any(feature = "inbound", feature = "ai_tools"))]
+#[cfg(any(feature = "inbound", feature = "ai_tools", all(test, feature = "axum")))]
pub mod inbound;
/// The outbound module contains the outbound adapters for CRM
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs b/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
index 0d0c9a8ccd..3877a3f33e 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
@@ -1,15 +1,20 @@
//! Generic entity permission extractor.
+#[cfg(test)]
+mod test;
+
use std::marker::PhantomData;
use std::sync::Arc;
use axum::{
- Extension, RequestPartsExt,
extract::{FromRef, FromRequestParts, Path},
http::request::Parts,
};
+use macro_authorization::{
+ MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+};
-use super::{ExtractorError, InternalUser};
+use super::ExtractorError;
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -17,7 +22,6 @@ use crate::domain::{
},
ports::EntityAccessService,
};
-use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Path parameters for entity permission routes.
#[derive(serde::Deserialize)]
@@ -31,16 +35,18 @@ struct EntityPermissionParams {
/// Reads `{entity_type}` and `{entity_id}` from path parameters and resolves
/// the user's permission via `EntityAccessService::get_entity_permission`.
#[derive(Debug)]
-pub struct EntityPermissionExtractor<Svc> {
+pub struct EntityPermissionExtractor<Svc, Auth> {
/// The entity access receipt
pub entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
- _marker: PhantomData<Svc>,
+ _marker: PhantomData<(Svc, Auth)>,
}
-impl<S, Svc> FromRequestParts<S> for EntityPermissionExtractor<Svc>
+impl<S, Svc, Auth> FromRequestParts<S> for EntityPermissionExtractor<Svc, Auth>
where
Arc<Svc>: FromRef<S>,
+ MacroAuthorizationState<Auth>: FromRef<S>,
Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
type Rejection = ExtractorError;
@@ -49,14 +55,14 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroUserExtractor {
+ let OptionalMacroAuthorizationExtractor {
macro_user_id,
user_context,
+ is_internal_access,
..
- } = parts
- .extract()
+ } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
.await
- .map_err(|_| ExtractorError::Internal)?;
+ .map_err(ExtractorError::from)?;
let Path(EntityPermissionParams {
entity_type,
@@ -67,17 +73,7 @@ where
let parsed_type = parse_entity_type(&entity_type)?;
- let internal_user: Option<Extension<InternalUser>> =
- if macro_user_id.is_none() || parsed_type == EntityType::ForeignEntity {
- parts
- .extract()
- .await
- .map_err(|_| ExtractorError::Internal)?
- } else {
- None
- };
-
- if internal_user.is_some() {
+ if is_internal_access && macro_user_id.is_none() {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
entity: Entity {
@@ -104,11 +100,7 @@ where
None => {
// For unauthenticated users, check public access at View level
let access_level = service
- .check_public_access(
- &entity_id,
- parsed_type,
- crate::domain::models::AccessLevel::View,
- )
+ .check_public_access(&entity_id, parsed_type, AccessLevel::View)
.await
.map_err(ExtractorError::from)?;
EntityPermission::AccessLevel { access_level }
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs b/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
new file mode 100644
index 0000000000..c056490e80
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
@@ -0,0 +1,522 @@
+use std::sync::{Arc, Mutex};
+
+use axum::{
+ Json, Router,
+ body::{Body, to_bytes},
+ extract::FromRef,
+ http::{Request, StatusCode, header},
+ routing::get,
+};
+use macro_authorization::{
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+ MacroAuthorizationState,
+};
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+use model_user::UserContext;
+use rootcause::Report;
+use serde_json::{Value, json};
+use tower::ServiceExt;
+use uuid::Uuid;
+
+use super::EntityPermissionExtractor;
+use crate::domain::{
+ models::{
+ AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessAuth, EntityAccessReceipt,
+ EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+ },
+ ports::EntityAccessService,
+};
+
+const USER_ID: &str = "macro|[email protected]";
+const INTERNAL_USER_ID: &str = "macro|[email protected]";
+const INTERNAL_KEY: &str = "valid-internal-key";
+const ENTITY_ID: &str = "entity-id";
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+enum EntityAccessCall {
+ GetEntityPermission {
+ user_id: Option<String>,
+ entity_id: String,
+ entity_type: EntityType,
+ organization_id: Option<i64>,
+ },
+ CheckPublicAccess {
+ entity_id: String,
+ entity_type: EntityType,
+ required_level: AccessLevel,
+ },
+}
+
+#[derive(Clone, Default)]
+struct FakeEntityAccessService {
+ calls: Arc<Mutex<Vec<EntityAccessCall>>>,
+}
+
+impl FakeEntityAccessService {
+ fn calls(&self) -> Vec<EntityAccessCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+}
+
+impl EntityAccessService for FakeEntityAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ panic!("unexpected generate_entity_access_receipt call")
+ }
+
+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _bot_id: BotId,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ panic!("unexpected generate_bot_entity_access_receipt call")
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ panic!("unexpected get_access_level call")
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_access call")
+ }
+
+ async fn check_public_access(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(EntityAccessCall::CheckPublicAccess {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ required_level,
+ });
+
+ Ok(AccessLevel::View)
+ }
+
+ async fn get_entity_permission(
+ &self,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ organization_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ self.calls.lock().expect("calls lock poisoned").push(
+ EntityAccessCall::GetEntityPermission {
+ user_id: user_id.map(|user_id| user_id.as_ref().to_string()),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ organization_id,
+ },
+ );
+
+ Ok(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ })
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<(EntityPermission, Uuid), AccessError> {
+ panic!("unexpected get_crm_entity_permission_with_team call")
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ panic!("unexpected get_users_by_entity call")
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel call")
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel_by_channel_id call")
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ panic!("unexpected get_user_team call")
+ }
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+enum AuthorizationCall {
+ Bearer(String),
+ Internal {
+ provided_key: String,
+ claims: InternalIdentityClaims,
+ },
+}
+
+#[derive(Clone, Default)]
+struct FakeAuthorizationService {
+ calls: Arc<Mutex<Vec<AuthorizationCall>>>,
+}
+
+impl FakeAuthorizationService {
+ fn calls(&self) -> Vec<AuthorizationCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+}
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(AuthorizationCall::Bearer(jwt.to_string()));
+
+ match jwt {
+ "valid" => Ok(user_context(USER_ID, None)),
+ "organization" => Ok(user_context(USER_ID, Some(42))),
+ "expired" => Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+
+ async fn authorize_internal(
+ &self,
+ provided_key: &str,
+ claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(AuthorizationCall::Internal {
+ provided_key: provided_key.to_string(),
+ claims: claims.clone(),
+ });
+
+ if provided_key != INTERNAL_KEY {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(claims
+ .user_id
+ .as_deref()
+ .map(|user_id| user_context(user_id, claims.organization_id)))
+ }
+}
+
+fn user_context(user_id: &str, organization_id: Option<i32>) -> UserContext {
+ UserContext {
+ user_id: user_id.to_string(),
+ fusion_user_id: "fusion-user-id".to_string(),
+ organization_id,
+ permissions: None,
+ }
+}
+
+#[derive(Clone)]
+struct TestState {
+ entity_access: Arc<FakeEntityAccessService>,
+ authorization: MacroAuthorizationState<FakeAuthorizationService>,
+}
+
+impl FromRef<TestState> for Arc<FakeEntityAccessService> {
+ fn from_ref(state: &TestState) -> Self {
+ state.entity_access.clone()
+ }
+}
+
+impl FromRef<TestState> for MacroAuthorizationState<FakeAuthorizationService> {
+ fn from_ref(state: &TestState) -> Self {
+ state.authorization.clone()
+ }
+}
+
+async fn handler(
+ extractor: EntityPermissionExtractor<FakeEntityAccessService, FakeAuthorizationService>,
+) -> Json<Value> {
+ let receipt = extractor.entity_access_receipt;
+ let auth = match receipt.auth {
+ EntityAccessAuth::Authenticated(user_id) => json!({ "authenticated": user_id.to_string() }),
+ EntityAccessAuth::Bot(bot_id) => json!({ "bot": bot_id.to_string() }),
+ EntityAccessAuth::Unauthenticated => json!("unauthenticated"),
+ EntityAccessAuth::Internal => json!("internal"),
+ };
+
+ Json(json!({
+ "auth": auth,
+ "entity_id": receipt.entity.entity_id,
+ "entity_type": receipt.entity.entity_type.to_string(),
+ "permission": receipt.entity_permission,
+ }))
+}
+
+fn test_router() -> (Router, FakeEntityAccessService, FakeAuthorizationService) {
+ let entity_access = FakeEntityAccessService::default();
+ let authorization = FakeAuthorizationService::default();
+ let state = TestState {
+ entity_access: Arc::new(entity_access.clone()),
+ authorization: MacroAuthorizationState::new(Arc::new(authorization.clone())),
+ };
+ let router = Router::new()
+ .route("/entity/{entity_type}/{entity_id}", get(handler))
+ .with_state(state);
+
+ (router, entity_access, authorization)
+}
+
+async fn send(router: &Router, request: Request<Body>) -> (StatusCode, Value) {
+ let response = router.clone().oneshot(request).await.unwrap();
+ let status = response.status();
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let body = serde_json::from_slice(&body).expect("response should contain JSON");
+
+ (status, body)
+}
+
+fn request(path: &str) -> axum::http::request::Builder {
+ Request::get(path)
+}
+
+fn empty_body(request: axum::http::request::Builder) -> Request<Body> {
+ request.body(Body::empty()).unwrap()
+}
+
+#[tokio::test]
+async fn bearer_authentication_looks_up_the_users_permission() {
+ let (router, entity_access, authorization) = test_router();
+ let request = empty_body(
+ request(&format!("/entity/document/{ENTITY_ID}"))
+ .header(header::AUTHORIZATION, "Bearer valid"),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["auth"], json!({ "authenticated": USER_ID }));
+ assert_eq!(body["permission"]["access_level"], "edit");
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::GetEntityPermission {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ organization_id: None,
+ }]
+ );
+ assert_eq!(
+ authorization.calls(),
+ [AuthorizationCall::Bearer("valid".to_string())]
+ );
+}
+
+#[tokio::test]
+async fn organization_id_is_forwarded_to_the_permission_lookup() {
+ let (router, entity_access, _authorization) = test_router();
+ let request = empty_body(
+ request(&format!("/entity/document/{ENTITY_ID}"))
+ .header(header::AUTHORIZATION, "Bearer organization"),
+ );
+
+ let (status, _body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::GetEntityPermission {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ organization_id: Some(42),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn anonymous_requests_check_public_view_access() {
+ let (router, entity_access, authorization) = test_router();
+
+ let (status, body) = send(
+ &router,
+ empty_body(request(&format!("/entity/project/{ENTITY_ID}"))),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["auth"], "unauthenticated");
+ assert_eq!(body["permission"]["access_level"], "view");
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::CheckPublicAccess {
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Project,
+ required_level: AccessLevel::View,
+ }]
+ );
+ assert!(authorization.calls().is_empty());
+}
+
+#[tokio::test]
+async fn invalid_and_expired_tokens_preserve_authorization_rejections() {
+ for (token, expected_message) in [("invalid", "unauthorized"), ("expired", "jwt expired")] {
+ let (router, entity_access, _authorization) = test_router();
+ let request = empty_body(
+ request(&format!("/entity/document/{ENTITY_ID}"))
+ .header(header::AUTHORIZATION, format!("Bearer {token}")),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": expected_message }));
+ assert!(entity_access.calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn internal_request_with_acting_user_looks_up_the_users_permission() {
+ let (router, entity_access, authorization) = test_router();
+ let request = empty_body(
+ request(&format!("/entity/document/{ENTITY_ID}"))
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
+ .header(INTERNAL_MACRO_USER_ID_HEADER, INTERNAL_USER_ID)
+ .header(INTERNAL_MACRO_ORGANIZATION_ID_HEADER, "84"),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["auth"], json!({ "authenticated": INTERNAL_USER_ID }));
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::GetEntityPermission {
+ user_id: Some(INTERNAL_USER_ID.to_string()),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ organization_id: Some(84),
+ }]
+ );
+ assert_eq!(
+ authorization.calls(),
+ [AuthorizationCall::Internal {
+ provided_key: INTERNAL_KEY.to_string(),
+ claims: InternalIdentityClaims {
+ user_id: Some(INTERNAL_USER_ID.to_string()),
+ fusion_user_id: None,
+ organization_id: Some(84),
+ },
+ }]
+ );
+}
+
+#[tokio::test]
+async fn identity_less_internal_requests_receive_typed_internal_permissions() {
+ let (router, entity_access, authorization) = test_router();
+
+ for (entity_type, expected_level) in [
+ ("document", AccessLevel::Owner),
+ ("foreign_entity", AccessLevel::View),
+ ] {
+ let request = empty_body(
+ request(&format!("/entity/{entity_type}/{ENTITY_ID}"))
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY),
+ );
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["auth"], "internal");
+ assert_eq!(
+ body["permission"]["access_level"],
+ serde_json::to_value(expected_level).unwrap()
+ );
+ }
+
+ assert!(entity_access.calls().is_empty());
+ assert_eq!(
+ authorization.calls(),
+ [
+ AuthorizationCall::Internal {
+ provided_key: INTERNAL_KEY.to_string(),
+ claims: InternalIdentityClaims::default(),
+ },
+ AuthorizationCall::Internal {
+ provided_key: INTERNAL_KEY.to_string(),
+ claims: InternalIdentityClaims::default(),
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn invalid_entity_types_return_bad_request_without_access_lookup() {
+ let (router, entity_access, _authorization) = test_router();
+
+ let (status, body) = send(
+ &router,
+ empty_body(request(&format!("/entity/not-an-entity/{ENTITY_ID}"))),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(
+ body,
+ json!({ "message": "Bad request: Invalid entity type" })
+ );
+ assert!(entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn thread_path_alias_maps_to_email_thread() {
+ let (router, entity_access, _authorization) = test_router();
+ let request = empty_body(
+ request(&format!("/entity/thread/{ENTITY_ID}"))
+ .header(header::AUTHORIZATION, "Bearer valid"),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["entity_type"], "email_thread");
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::GetEntityPermission {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::EmailThread,
+ organization_id: None,
+ }]
+ );
+}
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 72ce74bd9a..de8ecd5437 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -126,8 +126,11 @@ pub(crate) type DssEmailService = EmailServiceImpl<
>;
/// CRM router state.
-pub(crate) type DssCrmState =
- crm::inbound::axum_router::CrmRouterState<DssCrmService, EntityAccessService>;
+pub(crate) type DssCrmState = crm::inbound::axum_router::CrmRouterState<
+ DssCrmService,
+ EntityAccessService,
+ AuthorizationService,
+>;
pub(crate) type DssSoupService = SoupImpl<
PgSoupRepo,
diff --git a/services/document_storage_service/src/api/entity/get_entity_permission.rs b/services/document_storage_service/src/api/entity/get_entity_permission.rs
index 5cd174dcce..d55bbc1470 100644
--- a/services/document_storage_service/src/api/entity/get_entity_permission.rs
+++ b/services/document_storage_service/src/api/entity/get_entity_permission.rs
@@ -1,4 +1,4 @@
-use crate::api::context::EntityAccessService;
+use crate::api::context::{AuthorizationService, EntityAccessService};
use axum::{Json, http::StatusCode, response::IntoResponse};
use entity_access::{
domain::models::EntityPermission,
@@ -32,7 +32,10 @@ pub enum EntityPermissionResponse {
)
)]
pub async fn handler(
- result: Result<EntityPermissionExtractor<EntityAccessService>, ExtractorError>,
+ result: Result<
+ EntityPermissionExtractor<EntityAccessService, AuthorizationService>,
+ ExtractorError,
+ >,
) -> impl IntoResponse {
match result {
Ok(ext) => (
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 2ad4dd06cd..fe7fe69acc 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -926,6 +926,7 @@ async fn main() -> anyhow::Result<()> {
crm_state: crm::inbound::axum_router::CrmRouterState {
service: Arc::new(crm_service),
entity_access_service: entity_access_service.clone(),
+ authorization_state: authorization_state.clone(),
},
};