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(channels): use macro authorization (#4962)

Will Hutchinson23be3b287a11
diff --git a/Cargo.lock b/Cargo.lock
index cb847efda5..1de3a1fec7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2591,6 +2591,7 @@ dependencies = [
"http-body-util",
"indexmap 2.14.0",
"item_filters",
+ "macro_authorization",
"macro_db_migrator",
"macro_env",
"macro_env_var",
@@ -2602,7 +2603,6 @@ dependencies = [
"model-entity",
"model-error-response",
"model_notifications",
- "model_user",
"models_pagination",
"models_permissions",
"non_empty",
diff --git a/crates/channels/Cargo.toml b/crates/channels/Cargo.toml
index b333b4de35..a5baf55dce 100644
--- a/crates/channels/Cargo.toml
+++ b/crates/channels/Cargo.toml
@@ -25,8 +25,8 @@ attachment = [
inbound = [
"dep:axum",
"dep:entity_access",
+ "dep:macro_authorization",
"dep:model-error-response",
- "dep:model_user",
"dep:utoipa",
"entity_access/inbound",
"models_pagination/axum",
@@ -83,6 +83,9 @@ frecency = { path = "../frecency", optional = true }
futures = { workspace = true, optional = true }
indexmap = { workspace = true, optional = true }
item_filters = { path = "../item_filters", optional = true }
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = [
+ "axum",
+] }
macro_event_broker = { path = "../macro_event_broker", default-features = false }
macro_event_topics = { path = "../macro_event_topics" }
macro_user_id = { path = "../macro_user_id" }
@@ -90,7 +93,6 @@ macro_uuid = { path = "../macro_uuid", optional = true }
model-entity = { path = "../model-entity", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
model_notifications = { path = "../model_notifications", optional = true }
-model_user = { path = "../model_user", optional = true, features = ["axum"] }
models_pagination = { path = "../models_pagination" }
models_permissions = { path = "../models_permissions", optional = true }
non_empty = { path = "../non_empty", optional = true }
@@ -125,6 +127,7 @@ macro_env_var = { path = "../macro_env_var" }
macro_event_broker = { path = "../macro_event_broker" }
mockall = { workspace = true }
rdkafka = { workspace = true }
+rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal"] }
tower = { workspace = true }
diff --git a/crates/channels/src/inbound/axum_router.rs b/crates/channels/src/inbound/axum_router.rs
index d6c1812ee5..34f565b838 100644
--- a/crates/channels/src/inbound/axum_router.rs
+++ b/crates/channels/src/inbound/axum_router.rs
@@ -40,11 +40,13 @@ use entity_access::{
},
ports::EntityAccessService,
},
- inbound::axum_extractors::ChannelAccessLevelExtractor,
+ inbound::axum_extractors::ChannelAccessLevelExtractorV2,
+};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
-use model_user::axum_extractor::MacroUserExtractor;
use models_pagination::{
Base64Str, BidirectionalCursor, CreatedAt, Cursor, CursorOptionExt, CursorVal,
CursorWithValAndFilter, PaginatedOpaqueCursor, Query as PaginationQuery, TypeEraseCursor,
@@ -54,26 +56,33 @@ use std::sync::Arc;
use uuid::Uuid;
/// State for the channels router.
-pub struct ChannelsRouterState<S, Svc> {
+pub struct ChannelsRouterState<S, Svc, Auth> {
service: Arc<S>,
access_service: Arc<Svc>,
+ authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S, Svc> Clone for ChannelsRouterState<S, Svc> {
+impl<S, Svc, Auth> Clone for ChannelsRouterState<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: ChannelService, Svc: EntityAccessService> ChannelsRouterState<S, Svc> {
- /// Create a router state wrapping the channel service and entity access service.
- pub fn new(service: S, access_service: Svc) -> Self {
+impl<S: ChannelService, Svc: EntityAccessService, Auth> ChannelsRouterState<S, Svc, Auth> {
+ /// Create a router state wrapping the channel service, entity access service, and authorization state.
+ pub fn new(
+ service: S,
+ access_service: Svc,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
Self {
service: Arc::new(service),
access_service: Arc::new(access_service),
+ authorization_state,
}
}
@@ -81,20 +90,31 @@ impl<S: ChannelService, Svc: EntityAccessService> ChannelsRouterState<S, Svc> {
///
/// Used when the channel service must also be shared with other components
/// (such as the bot trigger dispatcher) that post messages through it.
- pub fn from_arc(service: Arc<S>, access_service: Svc) -> Self {
+ pub fn from_arc(
+ service: Arc<S>,
+ access_service: Svc,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
Self {
service,
access_service: Arc::new(access_service),
+ authorization_state,
}
}
}
-impl<S, Svc> FromRef<ChannelsRouterState<S, Svc>> for Arc<Svc> {
- fn from_ref(state: &ChannelsRouterState<S, Svc>) -> Self {
+impl<S, Svc, Auth> FromRef<ChannelsRouterState<S, Svc, Auth>> for Arc<Svc> {
+ fn from_ref(state: &ChannelsRouterState<S, Svc, Auth>) -> Self {
state.access_service.clone()
}
}
+impl<S, Svc, Auth> FromRef<ChannelsRouterState<S, Svc, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &ChannelsRouterState<S, Svc, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
fn channel_id_from_receipt<T: RequiredPermission>(
receipt: &EntityAccessReceipt<T>,
) -> Result<Uuid, ChannelsHandlerErr> {
@@ -246,110 +266,127 @@ fn cursor_from_first_message(
}
/// Build the channel mutation router.
-pub fn channel_mutation_router<S, Svc>() -> Router<ChannelsRouterState<S, Svc>>
+pub fn channel_mutation_router<S, Svc, Auth>() -> Router<ChannelsRouterState<S, Svc, Auth>>
where
S: ChannelService,
Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
Router::new()
- .route("/", post(create_channel_handler::<S, Svc>))
+ .route("/", post(create_channel_handler::<S, Svc, Auth>))
.route(
"/get_or_create_dm",
- post(get_or_create_dm_handler::<S, Svc>),
+ post(get_or_create_dm_handler::<S, Svc, Auth>),
)
.route(
"/get_or_create_private",
- post(get_or_create_private_handler::<S, Svc>),
+ post(get_or_create_private_handler::<S, Svc, Auth>),
)
- .route("/mentions", post(create_mention_handler::<S, Svc>))
+ .route("/mentions", post(create_mention_handler::<S, Svc, Auth>))
.route(
"/mentions/{mention_id}",
- delete(delete_mention_handler::<S, Svc>),
+ delete(delete_mention_handler::<S, Svc, Auth>),
+ )
+ .route(
+ "/{channel_id}",
+ patch(patch_channel_handler::<S, Svc, Auth>),
+ )
+ .route(
+ "/{channel_id}",
+ delete(delete_channel_handler::<S, Svc, Auth>),
)
- .route("/{channel_id}", patch(patch_channel_handler::<S, Svc>))
- .route("/{channel_id}", delete(delete_channel_handler::<S, Svc>))
.route(
"/{channel_id}/message",
- post(post_message_handler::<S, Svc>),
+ post(post_message_handler::<S, Svc, Auth>),
+ )
+ .route(
+ "/{channel_id}/typing",
+ post(post_typing_handler::<S, Svc, Auth>),
)
- .route("/{channel_id}/typing", post(post_typing_handler::<S, Svc>))
.route(
"/{channel_id}/reaction",
- post(post_reaction_handler::<S, Svc>),
+ post(post_reaction_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/message/{message_id}",
- patch(patch_message_handler::<S, Svc>),
+ patch(patch_message_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/message/{message_id}",
- delete(delete_message_handler::<S, Svc>),
+ delete(delete_message_handler::<S, Svc, Auth>),
+ )
+ .route(
+ "/{channel_id}/join",
+ post(join_channel_handler::<S, Svc, Auth>),
)
- .route("/{channel_id}/join", post(join_channel_handler::<S, Svc>))
.route(
"/join/{join_code}",
- post(join_channel_by_code_handler::<S, Svc>),
+ post(join_channel_by_code_handler::<S, Svc, Auth>),
+ )
+ .route(
+ "/{channel_id}/leave",
+ post(leave_channel_handler::<S, Svc, Auth>),
)
- .route("/{channel_id}/leave", post(leave_channel_handler::<S, Svc>))
.route(
"/{channel_id}/participants",
- post(add_participants_handler::<S, Svc>),
+ post(add_participants_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/participants",
- delete(remove_participants_handler::<S, Svc>),
+ delete(remove_participants_handler::<S, Svc, Auth>),
)
}
/// Create the channels router.
-pub fn channels_router<S, Svc, T>(state: ChannelsRouterState<S, Svc>) -> Router<T>
+pub fn channels_router<S, Svc, Auth, T>(state: ChannelsRouterState<S, Svc, Auth>) -> Router<T>
where
S: ChannelService,
Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
T: Send + Sync,
{
- channel_mutation_router::<S, Svc>()
- .route("/{channel_id}", get(get_channel_handler::<S, Svc>))
+ channel_mutation_router::<S, Svc, Auth>()
+ .route("/{channel_id}", get(get_channel_handler::<S, Svc, Auth>))
.route(
"/{channel_id}/join-link",
- get(get_channel_join_link_handler::<S, Svc>),
+ get(get_channel_join_link_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/messages",
- get(get_channel_messages_handler::<S, Svc>)
- .post(post_channel_messages_handler::<S, Svc>),
+ get(get_channel_messages_handler::<S, Svc, Auth>)
+ .post(post_channel_messages_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/messages/{message_id}/replies",
- get(get_thread_replies_handler::<S, Svc>),
+ get(get_thread_replies_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/messages/{message_id}/context",
- get(get_message_with_context_handler::<S, Svc>),
+ get(get_message_with_context_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/messages/{message_id}/resolve",
- get(resolve_channel_message_handler::<S, Svc>),
+ get(resolve_channel_message_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/attachments",
- get(get_channel_attachments_handler::<S, Svc>),
+ get(get_channel_attachments_handler::<S, Svc, Auth>),
)
.route(
"/{channel_id}/participants",
- get(get_channel_participants_handler::<S, Svc>),
+ get(get_channel_participants_handler::<S, Svc, Auth>),
)
.route(
"/preview",
- post(get_batch_channel_preview_handler::<S, Svc>),
+ post(get_batch_channel_preview_handler::<S, Svc, Auth>),
)
.route(
"/attachments/{entity_type}/{entity_id}/references",
- get(get_attachment_references_handler::<S, Svc>),
+ get(get_attachment_references_handler::<S, Svc, Auth>),
)
.route(
"/activity",
- get(get_activity_handler::<S, Svc>).post(post_activity_handler::<S, Svc>),
+ get(get_activity_handler::<S, Svc, Auth>).post(post_activity_handler::<S, Svc, Auth>),
)
.with_state(state)
}
@@ -370,9 +407,13 @@ where
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn create_channel_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn create_channel_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<CreateChannelRequest>,
) -> Result<(StatusCode, Json<CreateChannelResponse>), ChannelsHandlerErr> {
let res = state
@@ -402,9 +443,13 @@ pub async fn create_channel_handler<S: ChannelService, Svc: EntityAccessService>
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_or_create_dm_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn get_or_create_dm_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<GetOrCreateDmRequest>,
) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
let res = state
@@ -430,9 +475,13 @@ pub async fn get_or_create_dm_handler<S: ChannelService, Svc: EntityAccessServic
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_or_create_private_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn get_or_create_private_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<GetOrCreatePrivateRequest>,
) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
let res = state
@@ -462,9 +511,13 @@ pub async fn get_or_create_private_handler<S: ChannelService, Svc: EntityAccessS
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn patch_channel_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,
+pub async fn patch_channel_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<AdminParticipantRole, Svc, Auth>,
Json(req): Json<PatchChannelRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -492,9 +545,13 @@ pub async fn patch_channel_handler<S: ChannelService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn delete_channel_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<OwnerParticipantRole, Svc>,
+pub async fn delete_channel_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<OwnerParticipantRole, Svc, Auth>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
@@ -522,9 +579,13 @@ pub async fn delete_channel_handler<S: ChannelService, Svc: EntityAccessService>
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn post_message_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn post_message_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Json(req): Json<PostMessageRequest>,
) -> Result<(StatusCode, Json<PostMessageResponse>), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -554,9 +615,13 @@ pub async fn post_message_handler<S: ChannelService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn patch_message_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn patch_message_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
Json(req): Json<PatchMessageRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
@@ -590,9 +655,13 @@ pub async fn patch_message_handler<S: ChannelService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn delete_message_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn delete_message_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
Query(query): Query<DeleteMessageQuery>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
@@ -625,9 +694,13 @@ pub async fn delete_message_handler<S: ChannelService, Svc: EntityAccessService>
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn post_reaction_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn post_reaction_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Json(req): Json<PostReactionRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -656,9 +729,13 @@ pub async fn post_reaction_handler<S: ChannelService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn post_typing_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn post_typing_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Json(req): Json<PostTypingRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -687,9 +764,13 @@ pub async fn post_typing_handler<S: ChannelService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn add_participants_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn add_participants_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Json(req): Json<AddParticipantsRequest>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -721,9 +802,13 @@ pub async fn add_participants_handler<S: ChannelService, Svc: EntityAccessServic
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn remove_participants_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn remove_participants_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Json(req): Json<RemoveParticipantsRequest>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -754,9 +839,13 @@ pub async fn remove_participants_handler<S: ChannelService, Svc: EntityAccessSer
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_channel_join_link_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn get_channel_join_link_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
) -> Result<Json<ChannelJoinCodeResponse>, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
let response = state.service.get_channel_join_code(channel_id).await?;
@@ -782,10 +871,14 @@ pub async fn get_channel_join_link_handler<S: ChannelService, Svc: EntityAccessS
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn join_channel_by_code_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
+pub async fn join_channel_by_code_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
Path(join_code): Path<Uuid>,
- user: MacroUserExtractor,
+ user: MacroAuthorizationExtractor<Auth>,
) -> Result<StatusCode, ChannelsHandlerErr> {
state
.service
@@ -812,10 +905,14 @@ pub async fn join_channel_by_code_handler<S: ChannelService, Svc: EntityAccessSe
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn join_channel_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
+pub async fn join_channel_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
Path(path): Path<ChannelPath>,
- user: MacroUserExtractor,
+ user: MacroAuthorizationExtractor<Auth>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = path.channel_id;
state
@@ -844,9 +941,13 @@ pub async fn join_channel_handler<S: ChannelService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn leave_channel_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn leave_channel_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
@@ -910,9 +1011,13 @@ fn map_access_error(err: AccessError) -> ChannelsHandlerErr {
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn create_mention_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- macro_user: MacroUserExtractor,
+pub async fn create_mention_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ macro_user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<CreateEntityMentionRequest>,
) -> Result<(StatusCode, Json<CreateEntityMentionResponse>), ChannelsHandlerErr> {
require_document_edit_access(
@@ -966,9 +1071,13 @@ pub async fn create_mention_handler<S: ChannelService, Svc: EntityAccessService>
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn delete_mention_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- macro_user: MacroUserExtractor,
+pub async fn delete_mention_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ macro_user: MacroAuthorizationExtractor<Auth>,
Path(mention_id): Path<Uuid>,
) -> Result<(StatusCode, Json<DeleteEntityMentionResponse>), ChannelsHandlerErr> {
let mention = state
@@ -1027,9 +1136,13 @@ pub async fn delete_mention_handler<S: ChannelService, Svc: EntityAccessService>
load_around_message_id = tracing::field::Empty
)
)]
-pub async fn get_channel_messages_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn get_channel_messages_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Query(params): Query<Params>,
cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {
@@ -1070,9 +1183,13 @@ pub async fn get_channel_messages_handler<S: ChannelService, Svc: EntityAccessSe
load_around_message_id = tracing::field::Empty
)
)]
-pub async fn post_channel_messages_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn post_channel_messages_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Query(params): Query<Params>,
cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
Json(filters): Json<ChannelMessageFilters>,
@@ -1094,8 +1211,8 @@ pub async fn post_channel_messages_handler<S: ChannelService, Svc: EntityAccessS
.await
}
-async fn channel_messages_response<S: ChannelService, Svc>(
- state: &ChannelsRouterState<S, Svc>,
+async fn channel_messages_response<S: ChannelService, Svc, Auth: MacroAuthorizationService>(
+ state: &ChannelsRouterState<S, Svc, Auth>,
params: Params,
cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
channel_id: Uuid,
@@ -1188,9 +1305,13 @@ async fn channel_messages_response<S: ChannelService, Svc>(
skip_all,
fields(channel_id = tracing::field::Empty, message_id = tracing::field::Empty)
)]
-pub async fn get_thread_replies_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- _access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn get_thread_replies_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ _access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
) -> Result<Json<Vec<ApiThreadReply>>, ChannelsHandlerErr> {
let channel_id = path.channel_id;
@@ -1237,9 +1358,13 @@ pub async fn get_thread_replies_handler<S: ChannelService, Svc: EntityAccessServ
after = tracing::field::Empty
)
)]
-pub async fn get_message_with_context_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- _access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn get_message_with_context_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ _access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
Query(params): Query<MessageContextParams>,
) -> Result<Json<GetMessageWithContextResponse>, ChannelsHandlerErr> {
@@ -1285,9 +1410,13 @@ pub async fn get_message_with_context_handler<S: ChannelService, Svc: EntityAcce
skip_all,
fields(channel_id = tracing::field::Empty, message_id = tracing::field::Empty)
)]
-pub async fn resolve_channel_message_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- _access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn resolve_channel_message_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ _access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
) -> Result<Json<ApiResolvedChannelMessage>, ChannelsHandlerErr> {
let channel_id = path.channel_id;
@@ -1332,9 +1461,13 @@ pub async fn resolve_channel_message_handler<S: ChannelService, Svc: EntityAcces
attachment_type = tracing::field::Empty
)
)]
-pub async fn get_channel_attachments_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn get_channel_attachments_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Query(params): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<PaginatedOpaqueCursor<ApiChannelAttachment>>, ChannelsHandlerErr> {
@@ -1394,9 +1527,13 @@ pub struct ApiChannelDetail {
)
)]
#[tracing::instrument(err, skip_all, fields(channel_id = tracing::field::Empty))]
-pub async fn get_channel_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn get_channel_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
Query(params): Query<Params>,
) -> Result<Json<ApiChannelDetail>, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -1452,9 +1589,13 @@ pub async fn get_channel_handler<S: ChannelService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all, fields(channel_id = tracing::field::Empty))]
-pub async fn get_channel_participants_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+pub async fn get_channel_participants_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
) -> Result<Json<Vec<ApiChannelParticipant>>, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
tracing::Span::current().record("channel_id", tracing::field::display(channel_id));
@@ -1483,13 +1624,17 @@ pub async fn get_channel_participants_handler<S: ChannelService, Svc: EntityAcce
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_batch_channel_preview_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- MacroUserExtractor {
+pub async fn get_batch_channel_preview_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id,
user_context,
..
- }: MacroUserExtractor,
+ }: MacroAuthorizationExtractor<Auth>,
Json(req): Json<GetBatchChannelPreviewRequest>,
) -> Result<Json<GetBatchChannelPreviewResponse>, ChannelsHandlerErr> {
let org_id = user_context.organization_id.map(i64::from);
@@ -1524,9 +1669,13 @@ pub async fn get_batch_channel_preview_handler<S: ChannelService, Svc: EntityAcc
entity_id = tracing::field::Empty,
)
)]
-pub async fn get_attachment_references_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn get_attachment_references_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Path(path): Path<AttachmentReferencesPath>,
) -> Result<Json<GetAttachmentReferencesResponse>, ChannelsHandlerErr> {
let span = tracing::Span::current();
@@ -1564,9 +1713,13 @@ pub async fn get_attachment_references_handler<S: ChannelService, Svc: EntityAcc
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_activity_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn get_activity_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
) -> Result<Json<Vec<ApiActivity>>, ChannelsHandlerErr> {
let activities = state
.service
@@ -1593,9 +1746,13 @@ pub async fn get_activity_handler<S: ChannelService, Svc: EntityAccessService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn post_activity_handler<S: ChannelService, Svc: EntityAccessService>(
- State(state): State<ChannelsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn post_activity_handler<
+ S: ChannelService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<PostActivityRequest>,
) -> Result<(StatusCode, Json<ApiActivity>), ChannelsHandlerErr> {
let channel_id = Uuid::parse_str(&req.channel_id)
diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rs
index 17d353851b..912505078a 100644
--- a/crates/channels/src/inbound/axum_router/test.rs
+++ b/crates/channels/src/inbound/axum_router/test.rs
@@ -11,8 +11,9 @@ use crate::domain::ports::{
ChannelService,
};
use axum::{
- Extension, Router,
- http::{Request, StatusCode},
+ Router,
+ body::Body,
+ http::{Request, StatusCode, header},
};
use entity_access::domain::{
models::{
@@ -23,14 +24,31 @@ use entity_access::domain::{
ports::EntityAccessService,
};
use http_body_util::BodyExt;
+#[allow(deprecated)]
+use macro_authorization::{
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ InternalAuthConfig, JwtValidator, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
+ LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationError,
+ MacroAuthorizationServiceImpl, MacroAuthorizationState, ValidatedIdentity,
+};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
-use model_user::UserContext;
use models_pagination::{Base64Str, CreatedAt, Cursor, CursorVal, PaginateOn, Query};
-use std::sync::{Arc, Mutex};
+use rootcause::Report;
+use std::sync::{
+ Arc, Mutex,
+ atomic::{AtomicUsize, Ordering},
+};
use tower::util::ServiceExt;
+const TEST_USER_ID: &str = "macro|[email protected]";
+const INTERNAL_USER_ID: &str = "macro|[email protected]";
+const VALID_BEARER_TOKEN: &str = "valid";
+const ORGANIZATION_BEARER_TOKEN: &str = "valid-with-organization";
+const VALID_INTERNAL_KEY: &str = "valid-internal-key";
+const TEST_ORGANIZATION_ID: i32 = 42;
+
// --- Access service implementations for tests ---
#[derive(Clone, Copy)]
@@ -40,30 +58,44 @@ enum AccessMode {
NotFound,
}
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct PermissionCall {
+ user_id: Option<String>,
+ entity_id: String,
+ entity_type: EntityType,
+ organization_id: Option<i64>,
+}
+
#[derive(Clone)]
struct TestAccessService {
mode: AccessMode,
+ permission_calls: Arc<Mutex<Vec<PermissionCall>>>,
}
impl TestAccessService {
- const fn allow() -> Self {
- Self {
- mode: AccessMode::Allow,
- }
+ fn allow() -> Self {
+ Self::new(AccessMode::Allow)
}
- const fn deny() -> Self {
- Self {
- mode: AccessMode::Deny,
- }
+ fn deny() -> Self {
+ Self::new(AccessMode::Deny)
}
- const fn not_found() -> Self {
+ fn not_found() -> Self {
+ Self::new(AccessMode::NotFound)
+ }
+
+ fn new(mode: AccessMode) -> Self {
Self {
- mode: AccessMode::NotFound,
+ mode,
+ permission_calls: Arc::default(),
}
}
+ fn permission_calls(&self) -> Vec<PermissionCall> {
+ self.permission_calls.lock().unwrap().clone()
+ }
+
fn access_err(&self) -> AccessError {
match self.mode {
AccessMode::Allow => AccessError::Internal,
@@ -142,11 +174,18 @@ impl EntityAccessService for TestAccessService {
async fn get_entity_permission(
&self,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _entity_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
entity_type: EntityType,
- _user_org_id: Option<i64>,
+ user_org_id: Option<i64>,
) -> Result<EntityPermission, AccessError> {
+ self.permission_calls.lock().unwrap().push(PermissionCall {
+ user_id: user_id.map(|user_id| user_id.as_ref().to_string()),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ organization_id: user_org_id,
+ });
+
match self.mode {
AccessMode::Allow => match entity_type {
EntityType::Channel => Ok(EntityPermission::ChannelRole {
@@ -812,45 +851,282 @@ impl ChannelService for RecordingMutationService {
}
}
-fn user_extension() -> Extension<UserContext> {
- Extension(UserContext {
- user_id: "macro|[email protected]".to_string(),
- fusion_user_id: "1234".to_string(),
- permissions: None,
- organization_id: None,
- })
+#[derive(Clone, Default)]
+struct FakeJwtValidator {
+ validation_count: Arc<AtomicUsize>,
+}
+
+impl FakeJwtValidator {
+ fn validation_count(&self) -> usize {
+ self.validation_count.load(Ordering::SeqCst)
+ }
+}
+
+impl JwtValidator for FakeJwtValidator {
+ fn validate(&self, jwt: &str) -> Result<ValidatedIdentity, Report<MacroAuthorizationError>> {
+ self.validation_count.fetch_add(1, Ordering::SeqCst);
+
+ let organization_id = match jwt {
+ VALID_BEARER_TOKEN => None,
+ ORGANIZATION_BEARER_TOKEN => Some(TEST_ORGANIZATION_ID),
+ "expired" => return Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
+ _ => return Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ };
+
+ Ok(ValidatedIdentity {
+ user_id: TEST_USER_ID.to_string(),
+ fusion_user_id: "test-fusion-user".to_string(),
+ organization_id,
+ permissions: None,
+ })
+ }
+}
+
+type TestAuthorizationService = MacroAuthorizationServiceImpl<FakeJwtValidator>;
+
+fn authorization_state_with_default(
+ default_user_id: Option<&str>,
+) -> (
+ MacroAuthorizationState<TestAuthorizationService>,
+ FakeJwtValidator,
+) {
+ let validator = FakeJwtValidator::default();
+ let service = MacroAuthorizationServiceImpl::new(
+ validator.clone(),
+ InternalAuthConfig {
+ api_key: VALID_INTERNAL_KEY.to_string(),
+ default_user_id: default_user_id.map(str::to_string),
+ },
+ );
+ (MacroAuthorizationState::new(Arc::new(service)), validator)
+}
+
+fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
+ authorization_state_with_default(None).0
+}
+
+async fn attach_bearer(mut request: Request<Body>) -> Request<Body> {
+ request.headers_mut().insert(
+ header::AUTHORIZATION,
+ format!("Bearer {VALID_BEARER_TOKEN}").parse().unwrap(),
+ );
+ request
}
fn mock_router() -> Router {
channels_router(ChannelsRouterState::new(
MockService,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension())
+ .layer(axum::middleware::map_request(attach_bearer))
}
fn error_router() -> Router {
channels_router(ChannelsRouterState::new(
ErrorService,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension())
+ .layer(axum::middleware::map_request(attach_bearer))
}
fn denied_router() -> Router {
channels_router(ChannelsRouterState::new(
MockService,
TestAccessService::deny(),
+ authorization_state(),
))
- .layer(user_extension())
+ .layer(axum::middleware::map_request(attach_bearer))
}
fn not_found_router() -> Router {
channels_router(ChannelsRouterState::new(
MockService,
TestAccessService::not_found(),
+ authorization_state(),
))
- .layer(user_extension())
+ .layer(axum::middleware::map_request(attach_bearer))
+}
+
+fn join_by_code_router(
+ default_user_id: Option<&str>,
+) -> (Router, Uuid, Arc<Mutex<Vec<Sender>>>, FakeJwtValidator) {
+ let join_code = Uuid::new_v4();
+ let service = JoinLinkService::new(Uuid::new_v4(), join_code, vec![]);
+ let joined_users = service.joined_users.clone();
+ let (authorization_state, validator) = authorization_state_with_default(default_user_id);
+ let router = channels_router(ChannelsRouterState::new(
+ service,
+ TestAccessService::deny(),
+ authorization_state,
+ ));
+ (router, join_code, joined_users, validator)
+}
+
+fn join_by_code_request(join_code: Uuid) -> axum::http::request::Builder {
+ Request::post(format!("/join/{join_code}"))
+}
+
+#[tokio::test]
+async fn valid_bearer_authenticates_user() {
+ let (router, join_code, joined_users, validator) = join_by_code_router(None);
+ let request = join_by_code_request(join_code)
+ .header(
+ header::AUTHORIZATION,
+ format!("Bearer {VALID_BEARER_TOKEN}"),
+ )
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(validator.validation_count(), 1);
+ let joined_users = joined_users.lock().unwrap();
+ assert_eq!(joined_users.len(), 1);
+ assert_eq!(joined_users[0].as_ref(), TEST_USER_ID);
+}
+
+#[tokio::test]
+async fn missing_credentials_are_rejected_before_service_invocation() {
+ let (router, join_code, joined_users, validator) = join_by_code_router(None);
+ let request = join_by_code_request(join_code).body(Body::empty()).unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(validator.validation_count(), 0);
+ assert!(joined_users.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn invalid_credentials_are_rejected_before_service_invocation() {
+ let (router, join_code, joined_users, validator) = join_by_code_router(None);
+ let request = join_by_code_request(join_code)
+ .header(header::AUTHORIZATION, "Bearer invalid")
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(validator.validation_count(), 1);
+ assert!(joined_users.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn expired_credentials_are_rejected_before_service_invocation() {
+ let (router, join_code, joined_users, validator) = join_by_code_router(None);
+ let request = join_by_code_request(join_code)
+ .header(header::AUTHORIZATION, "Bearer expired")
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(validator.validation_count(), 1);
+ assert!(joined_users.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn standard_internal_headers_propagate_organization_to_entity_access() {
+ let channel_id = Uuid::new_v4();
+ let access_service = TestAccessService::allow();
+ let router = channels_router(ChannelsRouterState::new(
+ MockService,
+ access_service.clone(),
+ authorization_state(),
+ ));
+ let request = Request::get(format!("/{channel_id}/messages"))
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header(INTERNAL_MACRO_USER_ID_HEADER, INTERNAL_USER_ID)
+ .header(INTERNAL_MACRO_ORGANIZATION_ID_HEADER, "73")
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ access_service.permission_calls(),
+ [PermissionCall {
+ user_id: Some(INTERNAL_USER_ID.to_string()),
+ entity_id: channel_id.to_string(),
+ entity_type: EntityType::Channel,
+ organization_id: Some(73),
+ }]
+ );
+}
+
+#[allow(deprecated)]
+#[tokio::test]
+async fn legacy_internal_headers_authenticate_acting_user() {
+ let (router, join_code, joined_users, validator) = join_by_code_router(None);
+ let request = join_by_code_request(join_code)
+ .header(LEGACY_DSS_INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header(LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, INTERNAL_USER_ID)
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(validator.validation_count(), 0);
+ let joined_users = joined_users.lock().unwrap();
+ assert_eq!(joined_users.len(), 1);
+ assert_eq!(joined_users[0].as_ref(), INTERNAL_USER_ID);
+}
+
+#[tokio::test]
+async fn internal_headers_use_dss_style_default_identity() {
+ let (router, join_code, joined_users, validator) = join_by_code_router(Some(TEST_USER_ID));
+ let request = join_by_code_request(join_code)
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(validator.validation_count(), 0);
+ let joined_users = joined_users.lock().unwrap();
+ assert_eq!(joined_users.len(), 1);
+ assert_eq!(joined_users[0].as_ref(), TEST_USER_ID);
+}
+
+#[tokio::test]
+async fn bearer_organization_is_propagated_to_entity_access() {
+ let channel_id = Uuid::new_v4();
+ let access_service = TestAccessService::allow();
+ let (authorization_state, validator) = authorization_state_with_default(None);
+ let router = channels_router(ChannelsRouterState::new(
+ MockService,
+ access_service.clone(),
+ authorization_state,
+ ));
+ let request = Request::get(format!("/{channel_id}/messages"))
+ .header(
+ header::AUTHORIZATION,
+ format!("Bearer {ORGANIZATION_BEARER_TOKEN}"),
+ )
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(validator.validation_count(), 1);
+ assert_eq!(
+ access_service.permission_calls(),
+ [PermissionCall {
+ user_id: Some(TEST_USER_ID.to_string()),
+ entity_id: channel_id.to_string(),
+ entity_type: EntityType::Channel,
+ organization_id: Some(i64::from(TEST_ORGANIZATION_ID)),
+ }]
+ );
}
#[tokio::test]
@@ -862,8 +1138,9 @@ async fn active_participant_can_get_persisted_channel_join_code() {
let router = channels_router(ChannelsRouterState::new(
service,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let response = router
.oneshot(
@@ -889,8 +1166,12 @@ async fn non_participant_cannot_get_channel_join_code() {
let channel_id = Uuid::new_v4();
let service = JoinLinkService::new(channel_id, Uuid::new_v4(), vec![]);
let requested_channel_ids = service.requested_channel_ids.clone();
- let router = channels_router(ChannelsRouterState::new(service, TestAccessService::deny()))
- .layer(user_extension());
+ let router = channels_router(ChannelsRouterState::new(
+ service,
+ TestAccessService::deny(),
+ authorization_state(),
+ ))
+ .layer(axum::middleware::map_request(attach_bearer));
let response = router
.oneshot(
@@ -921,8 +1202,9 @@ async fn non_private_channels_cannot_get_join_codes() {
let router = channels_router(ChannelsRouterState::new(
service,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
for (channel_type, channel_id) in non_private_channels {
let response = router
@@ -946,8 +1228,12 @@ async fn non_private_channels_cannot_get_join_codes() {
#[tokio::test]
async fn join_channel_by_code_handles_malformed_and_unknown_codes() {
let service = JoinLinkService::new(Uuid::new_v4(), Uuid::new_v4(), vec![]);
- let router = channels_router(ChannelsRouterState::new(service, TestAccessService::deny()))
- .layer(user_extension());
+ let router = channels_router(ChannelsRouterState::new(
+ service,
+ TestAccessService::deny(),
+ authorization_state(),
+ ))
+ .layer(axum::middleware::map_request(attach_bearer));
let malformed_response = router
.clone()
@@ -980,8 +1266,12 @@ async fn authenticated_user_can_join_by_code_without_channel_access() {
let join_code = Uuid::new_v4();
let service = JoinLinkService::new(Uuid::new_v4(), join_code, vec![]);
let joined_users = service.joined_users.clone();
- let router = channels_router(ChannelsRouterState::new(service, TestAccessService::deny()))
- .layer(user_extension());
+ let router = channels_router(ChannelsRouterState::new(
+ service,
+ TestAccessService::deny(),
+ authorization_state(),
+ ))
+ .layer(axum::middleware::map_request(attach_bearer));
let response = router
.oneshot(
@@ -1017,8 +1307,9 @@ async fn post_message_route_uses_entity_access_and_mutation_service() {
let router = channels_router(ChannelsRouterState::new(
mutation_service,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let request = Request::builder()
.method("POST")
@@ -1192,8 +1483,9 @@ async fn participants_returns_data_with_correct_shape() {
let router = channels_router(ChannelsRouterState::new(
ParticipantsService,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let request = Request::builder()
.uri(format!("/{channel_id}/participants"))
@@ -1427,8 +1719,9 @@ async fn messages_around_omits_previous_cursor_when_no_newer_page() {
has_more_newer: false,
},
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let message_id = Uuid::new_v4();
let request = Request::builder()
@@ -1454,8 +1747,9 @@ async fn messages_around_returns_previous_cursor_when_newer_page_exists() {
has_more_newer: true,
},
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let message_id = Uuid::new_v4();
let request = Request::builder()
@@ -1479,8 +1773,9 @@ async fn messages_around_returns_404_when_not_found() {
let router = channels_router(ChannelsRouterState::new(
NotFoundService,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let message_id = Uuid::new_v4();
let request = Request::builder()
@@ -1598,8 +1893,9 @@ async fn post_messages_empty_body_uses_default_filters() {
let router = channels_router(ChannelsRouterState::new(
svc.clone(),
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let request = Request::builder()
@@ -1625,8 +1921,9 @@ async fn post_messages_forwards_message_ids_filter() {
let router = channels_router(ChannelsRouterState::new(
svc.clone(),
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let id_a = Uuid::new_v4();
@@ -1653,8 +1950,9 @@ async fn post_messages_forwards_last_activity_filter() {
let router = channels_router(ChannelsRouterState::new(
svc.clone(),
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let body = serde_json::json!({ "last_activity": "2024-06-01T12:00:00Z" }).to_string();
@@ -1686,8 +1984,9 @@ async fn post_messages_forwards_notification_filter_for_authenticated_user() {
let router = channels_router(ChannelsRouterState::new(
svc.clone(),
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let body = serde_json::json!({
@@ -1725,8 +2024,9 @@ async fn post_messages_rejects_oversized_filter_list() {
let router = channels_router(ChannelsRouterState::new(
MockService,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let ids: Vec<Uuid> = (0..101).map(|_| Uuid::new_v4()).collect();
@@ -1770,8 +2070,9 @@ async fn thread_replies_returns_404_when_not_found() {
let router = channels_router(ChannelsRouterState::new(
NotFoundService,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let message_id = Uuid::new_v4();
let request = Request::builder()
@@ -2042,8 +2343,9 @@ async fn get_activity_returns_user_activities() {
let router = channels_router(ChannelsRouterState::new(
ActivityService::default(),
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let request = Request::builder()
.uri("/activity")
.body(axum::body::Body::empty())
@@ -2064,8 +2366,9 @@ async fn post_activity_records_and_returns_activity() {
let router = channels_router(ChannelsRouterState::new(
service,
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let channel_id = Uuid::new_v4();
let request = Request::builder()
.method("POST")
@@ -2098,8 +2401,9 @@ async fn post_activity_rejects_invalid_channel_id() {
let router = channels_router(ChannelsRouterState::new(
ActivityService::default(),
TestAccessService::allow(),
+ authorization_state(),
))
- .layer(user_extension());
+ .layer(axum::middleware::map_request(attach_bearer));
let request = Request::builder()
.method("POST")
.uri("/activity")
diff --git a/crates/channels/src/inbound/list_router.rs b/crates/channels/src/inbound/list_router.rs
index eea7b0bf52..af7a0fc8d2 100644
--- a/crates/channels/src/inbound/list_router.rs
+++ b/crates/channels/src/inbound/list_router.rs
@@ -1,9 +1,20 @@
+#[cfg(test)]
+mod test;
+
use std::sync::Arc;
-use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};
+use axum::{
+ Json, Router,
+ extract::{FromRef, State},
+ http::StatusCode,
+ response::IntoResponse,
+ routing::get,
+};
use frecency::domain::models::AggregateFrecency;
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
use macro_user_id::user_id::MacroUserIdStr;
-use model_user::axum_extractor::MacroUserExtractor;
use serde::Serialize;
use thiserror::Error;
use utoipa::ToSchema;
@@ -20,33 +31,48 @@ use crate::domain::{
const DEFAULT_CHANNEL_LIST_LIMIT: u32 = 100;
/// Router state for legacy channel-list endpoints.
-pub struct ChannelListRouterState<S> {
+pub struct ChannelListRouterState<S, Auth> {
/// Inner channel list service.
pub inner: Arc<S>,
+ /// State for request authorization.
+ pub authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S> Clone for ChannelListRouterState<S> {
+impl<S, Auth> Clone for ChannelListRouterState<S, Auth> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<S, Auth> ChannelListRouterState<S, Auth> {
+ /// Build router state from a channel list service and authorization state.
+ pub fn new(s: S, authorization_state: MacroAuthorizationState<Auth>) -> Self {
+ Self {
+ inner: Arc::new(s),
+ authorization_state,
}
}
}
-impl<S: ChannelListService> ChannelListRouterState<S> {
- /// Build router state from a channel list service.
- pub fn new(s: S) -> Self {
- Self { inner: Arc::new(s) }
+impl<S, Auth> FromRef<ChannelListRouterState<S, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &ChannelListRouterState<S, Auth>) -> Self {
+ state.authorization_state.clone()
}
}
/// Legacy `/channels` and `/activity` list routes.
-pub fn channel_list_router<S: ChannelListService, T: Send + Sync + 'static>(
- s: ChannelListRouterState<S>,
-) -> Router<T> {
+pub fn channel_list_router<S, Auth, T>(s: ChannelListRouterState<S, Auth>) -> Router<T>
+where
+ S: ChannelListService,
+ Auth: MacroAuthorizationService,
+ T: Send + Sync + 'static,
+{
Router::new()
- .route("/channels", get(get_channels_handler))
- .route("/activity", get(get_activity_handler))
+ .route("/channels", get(get_channels_handler::<S, Auth>))
+ .route("/activity", get(get_activity_handler::<S, Auth>))
.with_state(s)
}
@@ -80,10 +106,14 @@ impl IntoResponse for ChannelListRouterErr {
(status = 500, body=String),
)
)]
-async fn get_channels_handler<S: ChannelListService>(
- State(service): State<ChannelListRouterState<S>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
-) -> Result<Json<Vec<ApiChannelWithLatest>>, ChannelListRouterErr> {
+async fn get_channels_handler<S, Auth>(
+ State(service): State<ChannelListRouterState<S, Auth>>,
+ MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+) -> Result<Json<Vec<ApiChannelWithLatest>>, ChannelListRouterErr>
+where
+ S: ChannelListService,
+ Auth: MacroAuthorizationService,
+{
let res = service
.inner
.get_channels(GetChannelsRequest {
@@ -116,10 +146,14 @@ async fn get_channels_handler<S: ChannelListService>(
(status = 500, body=String),
))]
/// Handle legacy channel activity list requests.
-pub async fn get_activity_handler<S: ChannelListService>(
- State(service): State<ChannelListRouterState<S>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
-) -> Result<Json<Vec<ApiActivity>>, ChannelListRouterErr> {
+pub async fn get_activity_handler<S, Auth>(
+ State(service): State<ChannelListRouterState<S, Auth>>,
+ MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+) -> Result<Json<Vec<ApiActivity>>, ChannelListRouterErr>
+where
+ S: ChannelListService,
+ Auth: MacroAuthorizationService,
+{
let res = service
.inner
.get_activities(macro_user_id)
diff --git a/crates/channels/src/inbound/list_router/test.rs b/crates/channels/src/inbound/list_router/test.rs
new file mode 100644
index 0000000000..521cba6e84
--- /dev/null
+++ b/crates/channels/src/inbound/list_router/test.rs
@@ -0,0 +1,218 @@
+use std::{
+ collections::HashSet,
+ sync::{Arc, Mutex},
+};
+
+use axum::{
+ Router,
+ body::Body,
+ http::{Request, StatusCode, header},
+};
+use macro_authorization::{
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalAuthConfig, JwtValidator,
+ MacroAuthorizationError, MacroAuthorizationServiceImpl, MacroAuthorizationState,
+ ValidatedIdentity,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use tower::ServiceExt;
+
+use super::*;
+use crate::domain::models::{ChannelMessage, GetThreadReplyRowsRequest, UserName};
+
+const VALID_BEARER_TOKEN: &str = "valid-token";
+const INVALID_BEARER_TOKEN: &str = "invalid-token";
+const EXPIRED_BEARER_TOKEN: &str = "expired-token";
+const VALID_INTERNAL_KEY: &str = "valid-internal-key";
+const BEARER_USER_ID: &str = "macro|[email protected]";
+const ACTING_USER_ID: &str = "macro|[email protected]";
+const DEFAULT_USER_ID: &str = "macro|[email protected]";
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+enum ServiceCall {
+ GetChannels(String),
+ GetActivities(String),
+}
+
+#[derive(Clone, Default)]
+struct ServiceCallTracker {
+ calls: Arc<Mutex<Vec<ServiceCall>>>,
+}
+
+impl ServiceCallTracker {
+ fn record(&self, call: ServiceCall) {
+ self.calls.lock().unwrap().push(call);
+ }
+
+ fn calls(&self) -> Vec<ServiceCall> {
+ self.calls.lock().unwrap().clone()
+ }
+}
+
+struct FakeChannelListService {
+ tracker: ServiceCallTracker,
+}
+
+impl ChannelListService for FakeChannelListService {
+ async fn get_channels(
+ &self,
+ request: GetChannelsRequest,
+ ) -> Result<Vec<ChannelWithLatest>, Report> {
+ self.tracker
+ .record(ServiceCall::GetChannels(request.macro_id.to_string()));
+ Ok(Vec::new())
+ }
+
+ async fn get_activities(&self, user_id: MacroUserIdStr<'_>) -> Result<Vec<Activity>, Report> {
+ self.tracker
+ .record(ServiceCall::GetActivities(user_id.to_string()));
+ Ok(Vec::new())
+ }
+
+ async fn get_thread_messages(
+ &self,
+ _request: GetThreadReplyRowsRequest,
+ ) -> Result<Vec<ChannelMessage>, Report> {
+ Ok(Vec::new())
+ }
+
+ async fn get_names(
+ &self,
+ _names: HashSet<MacroUserIdStr<'_>>,
+ ) -> Result<Vec<UserName>, Report> {
+ Ok(Vec::new())
+ }
+}
+
+#[derive(Clone, Copy)]
+struct FakeJwtValidator;
+
+impl JwtValidator for FakeJwtValidator {
+ fn validate(&self, jwt: &str) -> Result<ValidatedIdentity, Report<MacroAuthorizationError>> {
+ match jwt {
+ VALID_BEARER_TOKEN => Ok(ValidatedIdentity {
+ user_id: BEARER_USER_ID.to_string(),
+ fusion_user_id: "fusion-user-id".to_string(),
+ organization_id: None,
+ permissions: None,
+ }),
+ EXPIRED_BEARER_TOKEN => Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+}
+
+fn test_router(default_user_id: Option<&str>) -> (Router, ServiceCallTracker) {
+ let tracker = ServiceCallTracker::default();
+ let list_service = FakeChannelListService {
+ tracker: tracker.clone(),
+ };
+ let authorization_service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator,
+ InternalAuthConfig {
+ api_key: VALID_INTERNAL_KEY.to_string(),
+ default_user_id: default_user_id.map(str::to_owned),
+ },
+ );
+ let state = ChannelListRouterState::new(
+ list_service,
+ MacroAuthorizationState::new(Arc::new(authorization_service)),
+ );
+
+ (channel_list_router::<_, _, ()>(state), tracker)
+}
+
+fn bearer_request(path: &str, token: &str) -> Request<Body> {
+ Request::get(path)
+ .header(header::AUTHORIZATION, format!("Bearer {token}"))
+ .body(Body::empty())
+ .unwrap()
+}
+
+#[tokio::test]
+async fn valid_bearer_credentials_pass_user_id_to_channel_list_service() {
+ let (router, tracker) = test_router(None);
+
+ let response = router
+ .oneshot(bearer_request("/channels", VALID_BEARER_TOKEN))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ tracker.calls(),
+ vec![ServiceCall::GetChannels(BEARER_USER_ID.to_string())]
+ );
+}
+
+#[tokio::test]
+async fn standard_internal_credentials_pass_acting_user_to_channel_list_service() {
+ let (router, tracker) = test_router(None);
+ let request = Request::get("/channels")
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header(INTERNAL_MACRO_USER_ID_HEADER, ACTING_USER_ID)
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ tracker.calls(),
+ vec![ServiceCall::GetChannels(ACTING_USER_ID.to_string())]
+ );
+}
+
+#[tokio::test]
+async fn standard_internal_credentials_use_default_user_for_activity_service() {
+ let (router, tracker) = test_router(Some(DEFAULT_USER_ID));
+ let request = Request::get("/activity")
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ tracker.calls(),
+ vec![ServiceCall::GetActivities(DEFAULT_USER_ID.to_string())]
+ );
+}
+
+#[tokio::test]
+async fn missing_credentials_are_rejected_without_invoking_list_service() {
+ let (router, tracker) = test_router(None);
+ let request = Request::get("/channels").body(Body::empty()).unwrap();
+
+ let response = router.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(tracker.calls().is_empty());
+}
+
+#[tokio::test]
+async fn invalid_credentials_are_rejected_without_invoking_list_service() {
+ let (router, tracker) = test_router(None);
+
+ let response = router
+ .oneshot(bearer_request("/activity", INVALID_BEARER_TOKEN))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(tracker.calls().is_empty());
+}
+
+#[tokio::test]
+async fn expired_credentials_are_rejected_without_invoking_list_service() {
+ let (router, tracker) = test_router(None);
+
+ let response = router
+ .oneshot(bearer_request("/channels", EXPIRED_BEARER_TOKEN))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(tracker.calls().is_empty());
+}
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 360669f346..35c63f6224 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -274,7 +274,8 @@ pub(crate) type DssChannelListService =
ChannelListServiceImpl<PgChannelsRepo, PgChannelsRepo, FrecencyPgStorage>;
/// Type alias for the legacy channel list router state.
-pub(crate) type DssChannelListState = ChannelListRouterState<DssChannelListService>;
+pub(crate) type DssChannelListState =
+ ChannelListRouterState<DssChannelListService, AuthorizationService>;
/// Type alias for the channels service wired into DSS.
pub(crate) type DssChannelService = ChannelServiceImpl<
@@ -294,7 +295,8 @@ pub(crate) type DssChannelService = ChannelServiceImpl<
>;
/// Type alias for the channels router state.
-pub(crate) type DssChannelsState = ChannelsRouterState<DssChannelService, EntityAccessService>;
+pub(crate) type DssChannelsState =
+ ChannelsRouterState<DssChannelService, EntityAccessService, AuthorizationService>;
/// Type alias for the bots service wired into DSS.
pub(crate) type DssBotService = BotServiceImpl<PgBotsRepo>;
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index d91eed718d..692c6af71f 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -364,11 +364,14 @@ async fn main() -> anyhow::Result<()> {
frecency_storage.clone(),
);
// Create the legacy channel list router state for routes mounted under /comms.
- let channel_list_state = ChannelListRouterState::new(ChannelListServiceImpl::new(
- PgChannelsRepo::new(db.clone()),
- PgChannelsRepo::new(db.clone()),
- frecency_storage.clone(),
- ));
+ let channel_list_state = ChannelListRouterState::new(
+ ChannelListServiceImpl::new(
+ PgChannelsRepo::new(db.clone()),
+ PgChannelsRepo::new(db.clone()),
+ frecency_storage.clone(),
+ ),
+ authorization_state.clone(),
+ );
let s3 = Arc::new(S3::new(
s3_client,
@@ -905,6 +908,7 @@ async fn main() -> anyhow::Result<()> {
channels_state: ChannelsRouterState::from_arc(
channels_service,
(*entity_access_service).clone(),
+ authorization_state.clone(),
),
bots_state: bots::inbound::axum_router::BotsRouterState::new(
bots_service.clone(),