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(calls): migrate calls macro authorization (#4914)

Will Hutchinson53d1e6dddfaa
diff --git a/Cargo.lock b/Cargo.lock
index 6249f1db7c..f851cf2e6c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2376,6 +2376,7 @@ dependencies = [
"item_filters",
"livekit-api",
"livekit-protocol",
+ "macro_authorization",
"macro_aws_config",
"macro_db_migrator",
"macro_user_id",
@@ -2383,7 +2384,6 @@ dependencies = [
"mockall",
"model-entity",
"model-error-response",
- "model_user",
"models_pagination",
"models_permissions",
"notification",
diff --git a/crates/call/Cargo.toml b/crates/call/Cargo.toml
index 3c55928e34..9fb560181d 100644
--- a/crates/call/Cargo.toml
+++ b/crates/call/Cargo.toml
@@ -9,8 +9,8 @@ ai_tools = ["dep:ai_toolset", "dep:async-trait", "dep:schemars", "ports"]
default = ["ai_tools", "inbound", "outbound", "ports"]
inbound = [
"dep:axum",
+ "dep:macro_authorization",
"dep:model-error-response",
- "dep:model_user",
"dep:utoipa",
"entity_access/inbound",
"item_filters/schema",
@@ -57,6 +57,9 @@ futures = { workspace = true, optional = true }
item_filters = { path = "../item_filters" }
livekit-api = { workspace = true, optional = true }
livekit-protocol = { workspace = true, optional = true }
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = [
+ "axum",
+] }
macro_aws_config = { path = "../macro_aws_config", optional = true, features = [
"s3",
] }
@@ -64,7 +67,6 @@ macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model-entity = { path = "../model-entity" }
model-error-response = { path = "../model-error-response", optional = true }
-model_user = { path = "../model_user", optional = true, features = ["axum"] }
models_pagination = { path = "../models_pagination" }
models_permissions = { path = "../models_permissions" }
notification = { path = "../notification" }
diff --git a/crates/call/src/inbound/axum_router.rs b/crates/call/src/inbound/axum_router.rs
index 199bc7b7c7..c547846d62 100644
--- a/crates/call/src/inbound/axum_router.rs
+++ b/crates/call/src/inbound/axum_router.rs
@@ -24,11 +24,13 @@ use entity_access::{
},
inbound::axum_extractors::{
CallAccessLevelExtractor, CallWithChannelIdAccessLevelExtractor,
- ChannelAccessLevelExtractor,
+ ChannelAccessLevelExtractorV2,
},
};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
use model_error_response::ErrorResponse;
-use model_user::axum_extractor::MacroUserExtractor;
use uuid::Uuid;
use crate::domain::models::{
@@ -43,36 +45,49 @@ use crate::domain::ports::CallService;
// ---------------------------------------------------------------------------
/// Router state for authenticated call operations.
-pub struct CallRouterState<S, Svc> {
+pub struct CallRouterState<S, Svc, Auth> {
service: Arc<S>,
access_service: Arc<Svc>,
+ authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S, Svc> Clone for CallRouterState<S, Svc> {
+impl<S, Svc, Auth> Clone for CallRouterState<S, Svc, Auth> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
access_service: self.access_service.clone(),
+ authorization_state: self.authorization_state.clone(),
}
}
}
-impl<S: CallService, Svc: EntityAccessService> CallRouterState<S, Svc> {
+impl<S: CallService, Svc: EntityAccessService, Auth> CallRouterState<S, Svc, Auth> {
/// Create a new router state from shared service references.
- pub fn new(service: Arc<S>, access_service: Arc<Svc>) -> Self {
+ pub fn new(
+ service: Arc<S>,
+ access_service: Arc<Svc>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
Self {
service,
access_service,
+ authorization_state,
}
}
}
-impl<S, Svc> FromRef<CallRouterState<S, Svc>> for Arc<Svc> {
- fn from_ref(state: &CallRouterState<S, Svc>) -> Self {
+impl<S, Svc, Auth> FromRef<CallRouterState<S, Svc, Auth>> for Arc<Svc> {
+ fn from_ref(state: &CallRouterState<S, Svc, Auth>) -> Self {
state.access_service.clone()
}
}
+impl<S, Svc, Auth> FromRef<CallRouterState<S, Svc, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &CallRouterState<S, Svc, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
/// Authenticated call router.
///
/// Routes:
@@ -85,38 +100,40 @@ impl<S, Svc> FromRef<CallRouterState<S, Svc>> for Arc<Svc> {
/// - `DELETE /record/{call_id}` — delete a call record
/// - `POST /record/{call_id}/share-with-team/toggle` — flip the call's share_with_team flag
/// - `POST /record/preview` — batch-fetch lightweight previews for many call ids
-pub fn call_router<S, Svc, T>(state: CallRouterState<S, Svc>) -> Router<T>
+pub fn call_router<S, Svc, Auth, T>(state: CallRouterState<S, Svc, Auth>) -> Router<T>
where
S: CallService,
Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
T: Send + Sync,
{
Router::new()
.route(
"/{channel_id}",
- get(get_or_create_call_handler::<S, Svc>).delete(leave_or_end_call_handler::<S, Svc>),
+ get(get_or_create_call_handler::<S, Svc, Auth>)
+ .delete(leave_or_end_call_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/active",
- get(check_active_call_handler::<S, Svc>),
+ get(check_active_call_handler::<S, Svc, Auth>),
)
.route(
"/record/preview",
- post(get_batch_call_record_preview_handler::<S, Svc>),
+ post(get_batch_call_record_preview_handler::<S, Svc, Auth>),
)
.route(
"/record/{call_id}",
- get(get_call_record_handler::<S, Svc>)
- .patch(edit_call_record_handler::<S, Svc>)
- .delete(delete_call_record_handler::<S, Svc>),
+ get(get_call_record_handler::<S, Svc, Auth>)
+ .patch(edit_call_record_handler::<S, Svc, Auth>)
+ .delete(delete_call_record_handler::<S, Svc, Auth>),
)
.route(
"/record/{call_id}/transcript",
- patch(edit_call_transcript_handler::<S, Svc>),
+ patch(edit_call_transcript_handler::<S, Svc, Auth>),
)
.route(
"/record/{call_id}/share-with-team/toggle",
- post(toggle_share_with_team_handler::<S, Svc>),
+ post(toggle_share_with_team_handler::<S, Svc, Auth>),
)
.with_state(state)
}
@@ -266,10 +283,14 @@ where
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_or_create_call_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
- user: MacroUserExtractor,
+pub async fn get_or_create_call_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ user: MacroAuthorizationExtractor<Auth>,
) -> Result<Json<CallTokenResponse>, CallError> {
let channel_id = Uuid::parse_str(&access.entity_access_receipt.entity().entity_id)
.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid channel_id")))?;
@@ -300,9 +321,13 @@ pub async fn get_or_create_call_handler<S: CallService, Svc: EntityAccessService
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn check_active_call_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn check_active_call_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
) -> Result<axum::response::Response, CallError> {
let channel_id = Uuid::parse_str(&access.entity_access_receipt.entity().entity_id)
.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid channel_id")))?;
@@ -333,9 +358,13 @@ pub async fn check_active_call_handler<S: CallService, Svc: EntityAccessService>
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_call_record_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: CallAccessLevelExtractor<ViewAccessLevel, Svc>,
+pub async fn get_call_record_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ access: CallAccessLevelExtractor<ViewAccessLevel, Svc, Auth>,
) -> Result<Json<CallRecord>, CallError> {
let record = state
.service
@@ -363,9 +392,13 @@ pub async fn get_call_record_handler<S: CallService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn delete_call_record_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: CallAccessLevelExtractor<EditAccessLevel, Svc>,
+pub async fn delete_call_record_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ access: CallAccessLevelExtractor<EditAccessLevel, Svc, Auth>,
) -> Result<StatusCode, CallError> {
state
.service
@@ -394,9 +427,13 @@ pub async fn delete_call_record_handler<S: CallService, Svc: EntityAccessService
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn edit_call_record_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: CallAccessLevelExtractor<EditAccessLevel, Svc>,
+pub async fn edit_call_record_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ access: CallAccessLevelExtractor<EditAccessLevel, Svc, Auth>,
Json(request): Json<EditCallRecordRequest>,
) -> Result<StatusCode, CallError> {
state
@@ -428,9 +465,13 @@ pub async fn edit_call_record_handler<S: CallService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn edit_call_transcript_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: CallAccessLevelExtractor<EditAccessLevel, Svc>,
+pub async fn edit_call_transcript_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ access: CallAccessLevelExtractor<EditAccessLevel, Svc, Auth>,
Json(request): Json<EditCallTranscriptRequest>,
) -> Result<StatusCode, CallError> {
state
@@ -459,9 +500,13 @@ pub async fn edit_call_transcript_handler<S: CallService, Svc: EntityAccessServi
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn toggle_share_with_team_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: CallAccessLevelExtractor<EditAccessLevel, Svc>,
+pub async fn toggle_share_with_team_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ access: CallAccessLevelExtractor<EditAccessLevel, Svc, Auth>,
) -> Result<Json<bool>, CallError> {
let new_value = state
.service
@@ -489,9 +534,13 @@ pub async fn toggle_share_with_team_handler<S: CallService, Svc: EntityAccessSer
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_batch_call_record_preview_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn get_batch_call_record_preview_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(request): Json<GetBatchCallRecordPreviewRequest>,
) -> Result<Json<GetBatchCallRecordPreviewResponse>, CallError> {
if request.call_ids.len() > MAX_BATCH_CALL_IDS {
@@ -523,10 +572,14 @@ pub async fn get_batch_call_record_preview_handler<S: CallService, Svc: EntityAc
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn leave_or_end_call_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: CallWithChannelIdAccessLevelExtractor<MemberParticipantRole, Svc>,
- user: MacroUserExtractor,
+pub async fn leave_or_end_call_handler<
+ S: CallService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CallRouterState<S, Svc, Auth>>,
+ access: CallWithChannelIdAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
+ user: MacroAuthorizationExtractor<Auth>,
) -> Result<Json<LeaveCallResponse>, CallError> {
let channel_id = access.channel_id;
diff --git a/crates/entity_access/src/inbound/axum_extractors/call.rs b/crates/entity_access/src/inbound/axum_extractors/call.rs
index bf91b340e3..4dfa195f71 100644
--- a/crates/entity_access/src/inbound/axum_extractors/call.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/call.rs
@@ -3,17 +3,23 @@
//! Resolves a call (from both `calls` and `call_records` tables), checks channel
//! membership, and exposes the call's `share_permission_id` for downstream handlers.
+#[cfg(test)]
+mod test;
+
use std::marker::PhantomData;
use std::sync::Arc;
use axum::{
- Extension, RequestPartsExt,
+ RequestPartsExt,
extract::{FromRef, FromRequestParts, Path},
http::request::Parts,
};
+use macro_authorization::{
+ MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+};
use uuid::Uuid;
-use super::{ExtractorError, InternalUser};
+use super::ExtractorError;
use crate::domain::{
models::{
Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -21,7 +27,6 @@ use crate::domain::{
},
ports::EntityAccessService,
};
-use model_user::axum_extractor::OptionalMacroUserExtractor;
#[derive(Debug, serde::Deserialize)]
struct CallAccessParams {
@@ -41,22 +46,25 @@ struct CallWithChannelIdAccessParams {
///
/// Type parameter `T` specifies the required permission marker.
/// Type parameter `Svc` is the entity access service implementation.
+/// Type parameter `Auth` is the authorization service implementation.
#[derive(Debug)]
-pub struct CallAccessLevelExtractor<T: RequiredPermission, Svc> {
- /// The entity access receipt (entity is the channel the call belongs to).
+pub struct CallAccessLevelExtractor<T: RequiredPermission, Svc, Auth> {
+ /// The entity access receipt for the call.
pub entity_access_receipt: EntityAccessReceipt<T>,
/// The call's share permission ID.
pub share_permission_id: String,
/// The channel ID the call belongs to.
pub channel_id: Uuid,
- _marker: PhantomData<(T, Svc)>,
+ _marker: PhantomData<(T, Svc, Auth)>,
}
-impl<T, S, Svc> FromRequestParts<S> for CallAccessLevelExtractor<T, Svc>
+impl<T, S, Svc, Auth> FromRequestParts<S> for CallAccessLevelExtractor<T, Svc, Auth>
where
T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
type Rejection = ExtractorError;
@@ -65,10 +73,13 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroUserExtractor { macro_user_id, .. } = parts
- .extract()
+ let OptionalMacroAuthorizationExtractor {
+ macro_user_id,
+ is_internal_access,
+ ..
+ } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
.await
- .map_err(|_| ExtractorError::Internal)?;
+ .map_err(ExtractorError::from)?;
let Path(CallAccessParams { call_id }) = parts
.extract::<Path<CallAccessParams>>()
@@ -84,16 +95,7 @@ where
.map_err(ExtractorError::from)?
.ok_or(ExtractorError::NotFound("call not found"))?;
- let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
- parts
- .extract()
- .await
- .map_err(|_| ExtractorError::Internal)?
- } else {
- None
- };
-
- if internal_user.is_some() {
+ if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
entity: Entity {
@@ -150,22 +152,25 @@ where
///
/// Type parameter `T` specifies the required permission marker.
/// Type parameter `Svc` is the entity access service implementation.
+/// Type parameter `Auth` is the authorization service implementation.
#[derive(Debug)]
-pub struct CallWithChannelIdAccessLevelExtractor<T: RequiredPermission, Svc> {
+pub struct CallWithChannelIdAccessLevelExtractor<T: RequiredPermission, Svc, Auth> {
/// The entity access receipt (entity is the channel the call belongs to).
pub entity_access_receipt: EntityAccessReceipt<T>,
/// The call's share permission ID.
pub share_permission_id: String,
/// The channel ID.
pub channel_id: Uuid,
- _marker: PhantomData<(T, Svc)>,
+ _marker: PhantomData<(T, Svc, Auth)>,
}
-impl<T, S, Svc> FromRequestParts<S> for CallWithChannelIdAccessLevelExtractor<T, Svc>
+impl<T, S, Svc, Auth> FromRequestParts<S> for CallWithChannelIdAccessLevelExtractor<T, Svc, Auth>
where
T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
type Rejection = ExtractorError;
@@ -174,14 +179,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(CallWithChannelIdAccessParams { channel_id }) = parts
.extract::<Path<CallWithChannelIdAccessParams>>()
@@ -197,16 +202,7 @@ where
.map_err(ExtractorError::from)?
.ok_or(ExtractorError::NotFound("call not found for channel"))?;
- let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
- parts
- .extract()
- .await
- .map_err(|_| ExtractorError::Internal)?
- } else {
- None
- };
-
- if internal_user.is_some() {
+ if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
entity: Entity {
diff --git a/crates/entity_access/src/inbound/axum_extractors/call/test.rs b/crates/entity_access/src/inbound/axum_extractors/call/test.rs
new file mode 100644
index 0000000000..ee58106373
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/call/test.rs
@@ -0,0 +1,560 @@
+use std::sync::{Arc, Mutex};
+
+use axum::{
+ Json, Router,
+ body::{Body, to_bytes},
+ extract::{FromRef, State},
+ http::{Request, StatusCode, header},
+ routing::get,
+};
+use macro_authorization::{
+ INTERNAL_API_KEY_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::*;
+use crate::domain::models::{
+ AccessError, AccessLevel, BotId, CallChannelInfo, MemberParticipantRole, OwnerParticipantRole,
+ UserTeamInfo,
+};
+
+const CALL_ID: &str = "9e8e56e7-97e8-4148-9618-a63dacabf104";
+const CHANNEL_ID: &str = "a1240db2-43c2-4974-92ad-70534f5f2ae8";
+const SHARE_PERMISSION_ID: &str = "share-permission-1";
+const USER_ID: &str = "macro|[email protected]";
+const ACT_AS_ID: &str = "macro|[email protected]";
+const DEFAULT_INTERNAL_ID: &str = "macro|[email protected]";
+const INTERNAL_KEY: &str = "valid-internal-key";
+const ORGANIZATION_ID: i64 = 42;
+
+#[derive(Clone, Copy)]
+enum Variant {
+ CallId,
+ ChannelId,
+}
+
+impl Variant {
+ fn path(self, id: &str) -> String {
+ match self {
+ Self::CallId => format!("/call/{id}"),
+ Self::ChannelId => format!("/channel/{id}"),
+ }
+ }
+
+ fn valid_path(self) -> String {
+ match self {
+ Self::CallId => self.path(CALL_ID),
+ Self::ChannelId => self.path(CHANNEL_ID),
+ }
+ }
+
+ fn entity_type(self) -> EntityType {
+ match self {
+ Self::CallId => EntityType::Call,
+ Self::ChannelId => EntityType::Channel,
+ }
+ }
+
+ fn entity_id(self) -> &'static str {
+ match self {
+ Self::CallId => CALL_ID,
+ Self::ChannelId => CHANNEL_ID,
+ }
+ }
+
+ fn expected_organization_id(self) -> Option<i64> {
+ match self {
+ Self::CallId => None,
+ Self::ChannelId => Some(ORGANIZATION_ID),
+ }
+ }
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct PermissionCall {
+ user_id: Option<String>,
+ entity_id: String,
+ entity_type: EntityType,
+ organization_id: Option<i64>,
+}
+
+#[derive(Clone, Debug)]
+struct FakeEntityAccessService {
+ call_info: Option<CallChannelInfo>,
+ permission: EntityPermission,
+ permission_calls: Arc<Mutex<Vec<PermissionCall>>>,
+}
+
+impl FakeEntityAccessService {
+ fn new(call_exists: bool, permission: EntityPermission) -> Self {
+ Self {
+ call_info: call_exists.then(|| CallChannelInfo {
+ channel_id: Uuid::parse_str(CHANNEL_ID).expect("channel id should be valid"),
+ share_permission_id: SHARE_PERMISSION_ID.to_string(),
+ }),
+ permission,
+ permission_calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn permission_calls(&self) -> Vec<PermissionCall> {
+ self.permission_calls
+ .lock()
+ .expect("permission 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> {
+ self.permission_calls
+ .lock()
+ .expect("permission calls lock poisoned")
+ .push(PermissionCall {
+ user_id: user_id.map(|id| id.as_ref().to_string()),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ organization_id,
+ });
+ Ok(self.permission)
+ }
+
+ 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> {
+ Ok(self.call_info.clone())
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ Ok(self.call_info.clone())
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ panic!("unexpected get_user_team call")
+ }
+}
+
+#[derive(Clone, Debug, Default)]
+struct FakeAuthorizationService {
+ default_internal_user_id: Option<String>,
+}
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ match jwt {
+ "valid" => Ok(user_context(USER_ID)),
+ "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>> {
+ if provided_key != INTERNAL_KEY {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(claims
+ .user_id
+ .or_else(|| self.default_internal_user_id.clone())
+ .map(|user_id| user_context(&user_id)))
+ }
+}
+
+#[derive(Clone)]
+struct TestState {
+ entity_access: Arc<FakeEntityAccessService>,
+ authorization: MacroAuthorizationState<FakeAuthorizationService>,
+}
+
+impl TestState {
+ fn new(call_exists: bool, permission: EntityPermission) -> Self {
+ Self::with_authorization(call_exists, permission, FakeAuthorizationService::default())
+ }
+
+ fn with_authorization(
+ call_exists: bool,
+ permission: EntityPermission,
+ authorization: FakeAuthorizationService,
+ ) -> Self {
+ Self {
+ entity_access: Arc::new(FakeEntityAccessService::new(call_exists, permission)),
+ authorization: MacroAuthorizationState::new(Arc::new(authorization)),
+ }
+ }
+}
+
+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()
+ }
+}
+
+fn user_context(user_id: &str) -> UserContext {
+ UserContext {
+ user_id: user_id.to_string(),
+ fusion_user_id: "fusion-user-id".to_string(),
+ organization_id: Some(
+ ORGANIZATION_ID
+ .try_into()
+ .expect("organization id should fit"),
+ ),
+ permissions: None,
+ }
+}
+
+async fn call_handler(
+ State(_state): State<TestState>,
+ extracted: CallAccessLevelExtractor<
+ MemberParticipantRole,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+ >,
+) -> Json<Value> {
+ Json(receipt_json(
+ &extracted.entity_access_receipt,
+ &extracted.share_permission_id,
+ extracted.channel_id,
+ ))
+}
+
+async fn channel_handler(
+ State(_state): State<TestState>,
+ extracted: CallWithChannelIdAccessLevelExtractor<
+ MemberParticipantRole,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+ >,
+) -> Json<Value> {
+ Json(receipt_json(
+ &extracted.entity_access_receipt,
+ &extracted.share_permission_id,
+ extracted.channel_id,
+ ))
+}
+
+fn receipt_json<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+ share_permission_id: &str,
+ channel_id: Uuid,
+) -> Value {
+ let (auth, user_id) = match receipt.auth() {
+ EntityAccessAuth::Authenticated(user_id) => ("authenticated", Some(user_id.as_ref())),
+ EntityAccessAuth::Internal => ("internal", None),
+ _ => ("unexpected", None),
+ };
+ let role = match receipt.entity_permission() {
+ EntityPermission::ChannelRole { role } => format!("{role:?}"),
+ permission => format!("unexpected: {permission:?}"),
+ };
+
+ json!({
+ "entity_id": receipt.entity().entity_id,
+ "entity_type": receipt.entity().entity_type,
+ "auth": auth,
+ "user_id": user_id,
+ "role": role,
+ "share_permission_id": share_permission_id,
+ "channel_id": channel_id,
+ })
+}
+
+fn router(state: TestState) -> Router {
+ Router::new()
+ .route("/call/{call_id}", get(call_handler))
+ .route("/channel/{channel_id}", get(channel_handler))
+ .with_state(state)
+}
+
+fn request(path: String, token: Option<&str>) -> Request<Body> {
+ let mut request = Request::builder().uri(path);
+ if let Some(token) = token {
+ request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
+ }
+ request
+ .body(Body::empty())
+ .expect("request should be valid")
+}
+
+fn internal_request(path: String, user_id: Option<&str>) -> Request<Body> {
+ let mut request = Request::builder()
+ .uri(path)
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY);
+ if let Some(user_id) = user_id {
+ request = request.header(INTERNAL_MACRO_USER_ID_HEADER, user_id);
+ }
+ request
+ .body(Body::empty())
+ .expect("request should be valid")
+}
+
+async fn send(state: &TestState, request: Request<Body>) -> (StatusCode, Value) {
+ let response = router(state.clone())
+ .oneshot(request)
+ .await
+ .expect("router should respond");
+ let status = response.status();
+ let bytes = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ let body = serde_json::from_slice(&bytes).expect("response should contain JSON");
+ (status, body)
+}
+
+fn member_permission() -> EntityPermission {
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ }
+}
+
+#[tokio::test]
+async fn authenticated_receipts_include_call_metadata_and_expected_acl_context() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ let state = TestState::new(true, member_permission());
+ let (status, body) = send(&state, request(variant.valid_path(), Some("valid"))).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["entity_id"], variant.entity_id());
+ assert_eq!(body["entity_type"], json!(variant.entity_type()));
+ assert_eq!(body["auth"], "authenticated");
+ assert_eq!(body["user_id"], USER_ID);
+ assert_eq!(body["role"], "Member");
+ assert_eq!(body["share_permission_id"], SHARE_PERMISSION_ID);
+ assert_eq!(body["channel_id"], CHANNEL_ID);
+ assert_eq!(
+ state.entity_access.permission_calls(),
+ [PermissionCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: variant.entity_id().to_string(),
+ entity_type: variant.entity_type(),
+ organization_id: variant.expected_organization_id(),
+ }]
+ );
+ }
+}
+
+#[tokio::test]
+async fn insufficient_permission_is_rejected_for_both_variants() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ let state = TestState::new(true, member_permission());
+ let app = Router::new()
+ .route(
+ "/call/{call_id}",
+ get(
+ |_: CallAccessLevelExtractor<
+ OwnerParticipantRole,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+ >| async {},
+ ),
+ )
+ .route(
+ "/channel/{channel_id}",
+ get(
+ |_: CallWithChannelIdAccessLevelExtractor<
+ OwnerParticipantRole,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+ >| async {},
+ ),
+ )
+ .with_state(state.clone());
+ let response = app
+ .oneshot(request(variant.valid_path(), Some("valid")))
+ .await
+ .expect("router should respond");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.permission_calls().len(), 1);
+ }
+}
+
+#[tokio::test]
+async fn missing_and_expired_credentials_are_rejected_for_both_variants() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ let state = TestState::new(true, member_permission());
+ let (status, _) = send(&state, request(variant.valid_path(), None)).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert!(state.entity_access.permission_calls().is_empty());
+
+ let (status, body) = send(&state, request(variant.valid_path(), Some("expired"))).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "jwt expired" }));
+ assert!(state.entity_access.permission_calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn malformed_ids_are_rejected_for_both_variants() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ let state = TestState::new(true, member_permission());
+ let (status, _) = send(&state, request(variant.path("not-a-uuid"), Some("valid"))).await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(state.entity_access.permission_calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn missing_call_information_is_rejected_including_for_internal_requests() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ for request in [
+ request(variant.valid_path(), Some("valid")),
+ internal_request(variant.valid_path(), None),
+ ] {
+ let state = TestState::new(false, member_permission());
+ let (status, _) = send(&state, request).await;
+
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ assert!(state.entity_access.permission_calls().is_empty());
+ }
+ }
+}
+
+#[tokio::test]
+async fn identity_less_internal_requests_receive_owner_receipts_without_acl_calls() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ let state = TestState::new(true, member_permission());
+ let (status, body) = send(&state, internal_request(variant.valid_path(), None)).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["entity_id"], variant.entity_id());
+ assert_eq!(body["entity_type"], json!(variant.entity_type()));
+ assert_eq!(body["auth"], "internal");
+ assert_eq!(body["role"], "Owner");
+ assert_eq!(body["share_permission_id"], SHARE_PERMISSION_ID);
+ assert_eq!(body["channel_id"], CHANNEL_ID);
+ assert!(state.entity_access.permission_calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn internal_act_as_and_default_users_use_ordinary_acl_evaluation() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ for (authorization, request, expected_user_id) in [
+ (
+ FakeAuthorizationService::default(),
+ internal_request(variant.valid_path(), Some(ACT_AS_ID)),
+ ACT_AS_ID,
+ ),
+ (
+ FakeAuthorizationService {
+ default_internal_user_id: Some(DEFAULT_INTERNAL_ID.to_string()),
+ },
+ internal_request(variant.valid_path(), None),
+ DEFAULT_INTERNAL_ID,
+ ),
+ ] {
+ let state = TestState::with_authorization(true, member_permission(), authorization);
+ let (status, body) = send(&state, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["auth"], "authenticated");
+ assert_eq!(body["user_id"], expected_user_id);
+ assert_eq!(
+ state.entity_access.permission_calls(),
+ [PermissionCall {
+ user_id: Some(expected_user_id.to_string()),
+ entity_id: variant.entity_id().to_string(),
+ entity_type: variant.entity_type(),
+ organization_id: variant.expected_organization_id(),
+ }]
+ );
+ }
+ }
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel.rs b/crates/entity_access/src/inbound/axum_extractors/channel.rs
index 6710e9d15e..fb3d4b7819 100644
--- a/crates/entity_access/src/inbound/axum_extractors/channel.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/channel.rs
@@ -1,5 +1,8 @@
//! Channel access extractor.
+#[cfg(test)]
+mod test;
+
use std::marker::PhantomData;
use std::sync::Arc;
@@ -17,6 +20,9 @@ use crate::domain::{
},
ports::EntityAccessService,
};
+use macro_authorization::{
+ MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+};
use model_user::axum_extractor::OptionalMacroUserExtractor;
#[derive(Debug, serde::Deserialize)]
@@ -122,3 +128,93 @@ where
})
}
}
+
+/// Authorizes a request and validates that its identity satisfies the required channel permission.
+///
+/// Type parameter `T` specifies the required permission marker.
+/// Type parameter `Svc` is the entity access service implementation.
+/// Type parameter `Auth` is the authorization service implementation.
+#[derive(Debug)]
+pub struct ChannelAccessLevelExtractorV2<T: RequiredPermission, Svc, Auth> {
+ /// The entity access receipt.
+ pub entity_access_receipt: EntityAccessReceipt<T>,
+ _marker: PhantomData<(T, Svc, Auth)>,
+}
+
+impl<T, S, Svc, Auth> FromRequestParts<S> for ChannelAccessLevelExtractorV2<T, Svc, Auth>
+where
+ T: RequiredPermission,
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
+ 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 OptionalMacroAuthorizationExtractor {
+ macro_user_id,
+ user_context,
+ is_internal_access,
+ ..
+ } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ .await
+ .map_err(ExtractorError::from)?;
+
+ let Path(ChannelAccessParams { channel_id }) = parts
+ .extract::<Path<ChannelAccessParams>>()
+ .await
+ .map_err(|_| ExtractorError::BadRequest("missing channel_id path parameter"))?;
+
+ if macro_user_id.is_none() && is_internal_access {
+ return Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: channel_id,
+ entity_type: EntityType::Channel,
+ },
+ auth: EntityAccessAuth::Internal,
+ entity_permission: EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner,
+ },
+ _marker: PhantomData,
+ },
+ _marker: PhantomData,
+ });
+ }
+
+ let Some(macro_user_id) = macro_user_id else {
+ return Err(ExtractorError::Unauthorized);
+ };
+
+ let permission = service
+ .get_entity_permission(
+ Some(&macro_user_id),
+ &channel_id,
+ EntityType::Channel,
+ user_context.organization_id.map(i64::from),
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: channel_id,
+ entity_type: EntityType::Channel,
+ },
+ auth: EntityAccessAuth::Authenticated(macro_user_id),
+ entity_permission: permission,
+ _marker: PhantomData,
+ },
+ _marker: PhantomData,
+ })
+ }
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
new file mode 100644
index 0000000000..28448343e2
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
@@ -0,0 +1,501 @@
+use std::sync::{Arc, Mutex};
+
+use axum::{
+ Router,
+ body::{Body, to_bytes},
+ extract::FromRef,
+ http::{Request, StatusCode, header},
+ routing::get,
+};
+use macro_authorization::{
+ INTERNAL_API_KEY_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 tower::ServiceExt;
+use uuid::Uuid;
+
+use super::*;
+use crate::domain::models::{
+ AccessError, AccessLevel, AdminParticipantRole, BotId, CallChannelInfo, MemberParticipantRole,
+ OwnerParticipantRole, UserTeamInfo,
+};
+
+const CHANNEL_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
+const USER_ID: &str = "macro|[email protected]";
+const ACT_AS_ID: &str = "macro|[email protected]";
+const DEFAULT_INTERNAL_ID: &str = "macro|[email protected]";
+const INTERNAL_KEY: &str = "valid-internal-key";
+const ORGANIZATION_ID: i32 = 42;
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct PermissionCall {
+ user_id: Option<String>,
+ entity_id: String,
+ entity_type: EntityType,
+ organization_id: Option<i64>,
+}
+
+#[derive(Clone)]
+struct FakeEntityAccessService {
+ permission: EntityPermission,
+ calls: Arc<Mutex<Vec<PermissionCall>>>,
+}
+
+impl FakeEntityAccessService {
+ fn new(permission: EntityPermission) -> Self {
+ Self {
+ permission,
+ calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn calls(&self) -> Vec<PermissionCall> {
+ 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> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(PermissionCall {
+ user_id: user_id.map(|id| id.as_ref().to_string()),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ organization_id,
+ });
+ Ok(self.permission)
+ }
+
+ 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, Default)]
+struct FakeAuthorizationService {
+ default_internal_user_id: Option<String>,
+}
+
+impl FakeAuthorizationService {
+ fn with_default_internal_user() -> Self {
+ Self {
+ default_internal_user_id: Some(DEFAULT_INTERNAL_ID.to_string()),
+ }
+ }
+}
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ match jwt {
+ "valid" => Ok(user_context(USER_ID, Some(ORGANIZATION_ID))),
+ "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>> {
+ if provided_key != INTERNAL_KEY {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(claims
+ .user_id
+ .or_else(|| self.default_internal_user_id.clone())
+ .map(|user_id| user_context(&user_id, claims.organization_id)))
+ }
+}
+
+#[derive(Clone)]
+struct TestState {
+ entity_access: Arc<FakeEntityAccessService>,
+ authorization: MacroAuthorizationState<FakeAuthorizationService>,
+}
+
+impl TestState {
+ fn new(permission: EntityPermission) -> Self {
+ Self::with_authorization(permission, FakeAuthorizationService::default())
+ }
+
+ fn with_authorization(
+ permission: EntityPermission,
+ authorization: FakeAuthorizationService,
+ ) -> Self {
+ Self {
+ entity_access: Arc::new(FakeEntityAccessService::new(permission)),
+ authorization: MacroAuthorizationState::new(Arc::new(authorization)),
+ }
+ }
+}
+
+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()
+ }
+}
+
+type V2Member = ChannelAccessLevelExtractorV2<
+ MemberParticipantRole,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
+type V2Admin = ChannelAccessLevelExtractorV2<
+ AdminParticipantRole,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
+type V2Owner = ChannelAccessLevelExtractorV2<
+ OwnerParticipantRole,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
+
+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,
+ }
+}
+
+fn request(token: Option<&str>) -> Request<Body> {
+ let mut request = Request::builder()
+ .uri(format!("/{CHANNEL_ID}"))
+ .body(Body::empty())
+ .expect("request should be valid");
+ if let Some(token) = token {
+ request.headers_mut().insert(
+ header::AUTHORIZATION,
+ format!("Bearer {token}")
+ .parse()
+ .expect("authorization header should be valid"),
+ );
+ }
+ request
+}
+
+fn internal_request(user_id: Option<&str>) -> Request<Body> {
+ let mut request = request(None);
+ request.headers_mut().insert(
+ INTERNAL_API_KEY_HEADER,
+ INTERNAL_KEY.parse().expect("internal key should be valid"),
+ );
+ if let Some(user_id) = user_id {
+ request.headers_mut().insert(
+ INTERNAL_MACRO_USER_ID_HEADER,
+ user_id.parse().expect("user id should be valid"),
+ );
+ }
+ request
+}
+
+fn assert_member_receipt(receipt: &EntityAccessReceipt<MemberParticipantRole>) {
+ assert_eq!(receipt.entity().entity_id, CHANNEL_ID);
+ assert!(matches!(receipt.entity().entity_type, EntityType::Channel));
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Member
+ }
+ ));
+}
+
+async fn member_handler(extractor: V2Member) -> StatusCode {
+ assert_member_receipt(&extractor.entity_access_receipt);
+ StatusCode::OK
+}
+
+async fn authenticated_member_handler(extractor: V2Member) -> StatusCode {
+ let receipt = extractor.entity_access_receipt;
+ assert_member_receipt(&receipt);
+ assert!(matches!(
+ receipt.auth(),
+ EntityAccessAuth::Authenticated(user_id) if user_id.as_ref() == USER_ID
+ ));
+ StatusCode::OK
+}
+
+async fn admin_handler(_extractor: V2Admin) -> StatusCode {
+ StatusCode::OK
+}
+
+async fn owner_handler(extractor: V2Owner) -> StatusCode {
+ assert!(matches!(
+ extractor.entity_access_receipt.auth(),
+ EntityAccessAuth::Internal
+ ));
+ assert!(matches!(
+ extractor.entity_access_receipt.entity_permission(),
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner
+ }
+ ));
+ StatusCode::OK
+}
+
+fn app<H, T>(state: TestState, handler: H) -> Router
+where
+ H: axum::handler::Handler<T, TestState>,
+ T: 'static,
+{
+ Router::new()
+ .route("/{channel_id}", get(handler))
+ .with_state(state)
+}
+
+#[tokio::test]
+async fn authenticated_access_forwards_organization_and_mints_receipt() {
+ let state = TestState::new(EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ });
+ let response = app(state.clone(), authenticated_member_handler)
+ .oneshot(request(Some("valid")))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ state.entity_access.calls(),
+ vec![PermissionCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: CHANNEL_ID.to_string(),
+ entity_type: EntityType::Channel,
+ organization_id: Some(i64::from(ORGANIZATION_ID)),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn insufficient_permission_is_rejected() {
+ let state = TestState::new(EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ });
+ let response = app(state.clone(), admin_handler)
+ .oneshot(request(Some("valid")))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.calls().len(), 1);
+}
+
+#[tokio::test]
+async fn missing_credentials_are_rejected_without_acl_call() {
+ let state = TestState::new(EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner,
+ });
+ let response = app(state.clone(), member_handler)
+ .oneshot(request(None))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn expired_token_preserves_exact_rejection() {
+ let state = TestState::new(EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner,
+ });
+ let response = app(state.clone(), member_handler)
+ .oneshot(request(Some("expired")))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ assert_eq!(body.as_ref(), br#"{"message":"jwt expired"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn identity_less_internal_access_receives_owner_without_acl_call() {
+ let state = TestState::new(EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ });
+ let response = app(state.clone(), owner_handler)
+ .oneshot(internal_request(None))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+async fn assert_internal_identity_uses_acl(
+ state: TestState,
+ request: Request<Body>,
+ user_id: &str,
+) {
+ let response = app(state.clone(), member_handler)
+ .oneshot(request)
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ state.entity_access.calls()[0].user_id.as_deref(),
+ Some(user_id)
+ );
+}
+
+#[tokio::test]
+async fn internal_act_as_identity_uses_ordinary_acl_evaluation() {
+ let state = TestState::new(EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ });
+ assert_internal_identity_uses_acl(state, internal_request(Some(ACT_AS_ID)), ACT_AS_ID).await;
+}
+
+#[tokio::test]
+async fn default_internal_identity_uses_ordinary_acl_evaluation() {
+ let state = TestState::with_authorization(
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ },
+ FakeAuthorizationService::with_default_internal_user(),
+ );
+ assert_internal_identity_uses_acl(state, internal_request(None), DEFAULT_INTERNAL_ID).await;
+}
+
+async fn v1_handler(
+ _extractor: crate::inbound::axum_extractors::ChannelAccessLevelExtractor<
+ MemberParticipantRole,
+ FakeEntityAccessService,
+ >,
+) -> StatusCode {
+ StatusCode::OK
+}
+
+#[tokio::test]
+async fn v1_remains_exported_and_uses_middleware_user_context() {
+ let state = TestState::new(EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ });
+ let mut request = request(None);
+ request
+ .extensions_mut()
+ .insert(user_context(USER_ID, Some(ORGANIZATION_ID)));
+ let response = app(state.clone(), v1_handler)
+ .oneshot(request)
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ state.entity_access.calls()[0].user_id.as_deref(),
+ Some(USER_ID)
+ );
+ assert_eq!(
+ state.entity_access.calls()[0].organization_id,
+ Some(i64::from(ORGANIZATION_ID))
+ );
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/mod.rs b/crates/entity_access/src/inbound/axum_extractors/mod.rs
index 500e33ec19..49c7d7c009 100644
--- a/crates/entity_access/src/inbound/axum_extractors/mod.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/mod.rs
@@ -21,7 +21,7 @@ mod team;
mod thread;
pub use call::{CallAccessLevelExtractor, CallWithChannelIdAccessLevelExtractor};
-pub use channel::ChannelAccessLevelExtractor;
+pub use channel::{ChannelAccessLevelExtractor, ChannelAccessLevelExtractorV2};
pub use chat::ChatAccessLevelExtractor;
pub use document::DocumentAccessExtractor;
pub use entity_permission::EntityPermissionExtractor;
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 9db816a56e..1d66b13f71 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -321,7 +321,8 @@ pub(crate) type DssCallService = CallServiceImpl<
>;
/// Type alias for the call router state.
-pub(crate) type DssCallState = CallRouterState<DssCallService, EntityAccessService>;
+pub(crate) type DssCallState =
+ CallRouterState<DssCallService, EntityAccessService, AuthorizationService>;
/// Type alias for the call webhook router state.
pub(crate) type DssCallWebhookState = WebhookRouterState<DssCallService>;
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index edf7725630..b2bdd93fb7 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -618,7 +618,11 @@ async fn main() -> anyhow::Result<()> {
.with_voice_repo(PgVoiceRepo::new(db.clone())),
);
- let call_state = CallRouterState::new(call_service.clone(), entity_access_service.clone());
+ let call_state = CallRouterState::new(
+ call_service.clone(),
+ entity_access_service.clone(),
+ authorization_state.clone(),
+ );
let call_webhook_state = WebhookRouterState::new(call_service.clone());
let webhook_repository = webhook::outbound::PgRepository::new(db.clone());