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(bots): macro authorization (#4966)

Will Hutchinson9fa65bf918f6
diff --git a/Cargo.lock b/Cargo.lock
index 1de3a1fec7..6238257418 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2135,12 +2135,13 @@ dependencies = [
"chrono",
"entity_access",
"hex",
+ "macro_authorization",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
"model-error-response",
- "model_user",
"rand 0.9.4",
+ "rootcause",
"serde",
"serde_json",
"sqlx",
diff --git a/crates/bots/Cargo.toml b/crates/bots/Cargo.toml
index 4dfd2c9ada..7aaf7bf73f 100644
--- a/crates/bots/Cargo.toml
+++ b/crates/bots/Cargo.toml
@@ -12,8 +12,8 @@ inbound = [
"dep:entity_access",
"entity_access/inbound",
"entity_access/ports",
+ "dep:macro_authorization",
"dep:model-error-response",
- "dep:model_user",
"dep:serde_json",
"dep:utoipa",
"ports",
@@ -29,10 +29,10 @@ channels = { path = "../channels", optional = true, default-features = false, fe
chrono = { workspace = true }
entity_access = { path = "../entity_access", optional = true, default-features = false }
hex = { workspace = true }
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
-model_user = { path = "../model_user", optional = true, features = ["axum"] }
rand = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, optional = true }
@@ -50,6 +50,7 @@ entity_access = { path = "../entity_access", default-features = false, features
"ports",
] }
macro_db_migrator = { path = "../macro_db_migrator" }
+rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
tower = { workspace = true }
diff --git a/crates/bots/src/inbound/axum_router.rs b/crates/bots/src/inbound/axum_router.rs
index 0893cad5d8..b0dee63a4a 100644
--- a/crates/bots/src/inbound/axum_router.rs
+++ b/crates/bots/src/inbound/axum_router.rs
@@ -24,43 +24,58 @@ use entity_access::{
},
inbound::axum_extractors::ChannelAccessLevelExtractor,
};
+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 std::sync::Arc;
use uuid::Uuid;
/// State for the bots router.
-pub struct BotsRouterState<S, Svc> {
+pub struct BotsRouterState<S, Svc, Auth> {
service: Arc<S>,
access_service: Arc<Svc>,
+ authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S, Svc> Clone for BotsRouterState<S, Svc> {
+impl<S, Svc, Auth> Clone for BotsRouterState<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: BotService, Svc: EntityAccessService> BotsRouterState<S, Svc> {
+impl<S: BotService, Svc: EntityAccessService, Auth> BotsRouterState<S, Svc, Auth> {
/// Create a router state.
- pub fn new(service: S, access_service: Svc) -> Self {
+ 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,
}
}
}
-impl<S, Svc> FromRef<BotsRouterState<S, Svc>> for Arc<Svc> {
- fn from_ref(state: &BotsRouterState<S, Svc>) -> Self {
+impl<S, Svc, Auth> FromRef<BotsRouterState<S, Svc, Auth>> for Arc<Svc> {
+ fn from_ref(state: &BotsRouterState<S, Svc, Auth>) -> Self {
state.access_service.clone()
}
}
+impl<S, Svc, Auth> FromRef<BotsRouterState<S, Svc, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &BotsRouterState<S, Svc, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
/// Bot path.
#[derive(Debug, serde::Deserialize)]
pub struct BotPath {
@@ -103,54 +118,54 @@ pub struct BotChannelPath {
}
/// Create a bots router.
-pub fn bots_router<S, Svc, T>(state: BotsRouterState<S, Svc>) -> Router<T>
+pub fn bots_router<S, Svc, Auth, T>(state: BotsRouterState<S, Svc, Auth>) -> Router<T>
where
S: BotService,
Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
T: Send + Sync,
{
Router::new()
- .route("/bots", get(list_bots_handler::<S, Svc>))
- .route("/bots", post(create_bot_handler::<S, Svc>))
- .route("/bots/{bot_id}", get(get_bot_handler::<S, Svc>))
- .route("/bots/{bot_id}", patch(patch_bot_handler::<S, Svc>))
- .route("/bots/{bot_id}", delete(delete_bot_handler::<S, Svc>))
+ .route("/bots", get(list_bots_handler::<S, Svc, Auth>))
+ .route("/bots", post(create_bot_handler::<S, Svc, Auth>))
+ .route("/bots/{bot_id}", get(get_bot_handler::<S, Svc, Auth>))
+ .route("/bots/{bot_id}", patch(patch_bot_handler::<S, Svc, Auth>))
+ .route("/bots/{bot_id}", delete(delete_bot_handler::<S, Svc, Auth>))
.route(
"/bots/{bot_id}/channels",
- get(list_bot_channels_handler::<S, Svc>),
+ get(list_bot_channels_handler::<S, Svc, Auth>),
)
.route(
"/bots/{bot_id}/channels/{channel_id}",
- delete(remove_bot_channel_handler::<S, Svc>),
+ delete(remove_bot_channel_handler::<S, Svc, Auth>),
+ )
+ .route(
+ "/bots/{bot_id}/tokens",
+ get(list_tokens_handler::<S, Svc, Auth>),
)
- .route("/bots/{bot_id}/tokens", get(list_tokens_handler::<S, Svc>))
.route(
"/bots/{bot_id}/tokens",
- post(create_token_handler::<S, Svc>),
+ post(create_token_handler::<S, Svc, Auth>),
)
.route(
"/bots/{bot_id}/tokens/{token_id}",
- delete(revoke_token_handler::<S, Svc>),
+ delete(revoke_token_handler::<S, Svc, Auth>),
)
.route(
"/channels/{channel_id}/bots",
- get(list_channel_bots_handler::<S, Svc>),
+ get(list_channel_bots_handler::<S, Svc, Auth>),
)
.route(
"/channels/{channel_id}/bots",
- post(add_channel_bot_handler::<S, Svc>),
+ post(add_channel_bot_handler::<S, Svc, Auth>),
)
.route(
"/channels/{channel_id}/bots/{bot_id}",
- delete(remove_channel_bot_handler::<S, Svc>),
+ delete(remove_channel_bot_handler::<S, Svc, Auth>),
)
.with_state(state)
}
-fn caller_from_user(user: MacroUserExtractor) -> MacroUserIdStr<'static> {
- user.macro_user_id
-}
-
fn caller_from_receipt(
receipt: &EntityAccessReceipt<AdminParticipantRole>,
) -> Result<MacroUserIdStr<'static>, BotsHandlerErr> {
@@ -160,98 +175,132 @@ fn caller_from_receipt(
.map_err(|_| BotsHandlerErr::BadRequest("authenticated user required"))
}
-async fn create_bot_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+async fn create_bot_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Json(req): Json<CreateBotRequest>,
) -> Result<(StatusCode, Json<Bot>), BotsHandlerErr> {
let bot = state
.service
- .create_bot(caller_from_user(user), req)
+ .create_bot(authorization.macro_user_id, req)
.await?;
Ok((StatusCode::CREATED, Json(bot)))
}
-async fn list_bots_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+async fn list_bots_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
) -> Result<Json<Vec<Bot>>, BotsHandlerErr> {
- Ok(Json(state.service.list_bots(caller_from_user(user)).await?))
+ Ok(Json(
+ state.service.list_bots(authorization.macro_user_id).await?,
+ ))
}
-async fn get_bot_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+async fn get_bot_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Path(path): Path<BotPath>,
) -> Result<Json<Bot>, BotsHandlerErr> {
Ok(Json(
state
.service
- .get_bot(caller_from_user(user), path.bot_id)
+ .get_bot(authorization.macro_user_id, path.bot_id)
.await?,
))
}
-async fn patch_bot_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+async fn patch_bot_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Path(path): Path<BotPath>,
Json(req): Json<PatchBotRequest>,
) -> Result<Json<Bot>, BotsHandlerErr> {
Ok(Json(
state
.service
- .patch_bot(caller_from_user(user), path.bot_id, req)
+ .patch_bot(authorization.macro_user_id, path.bot_id, req)
.await?,
))
}
-async fn delete_bot_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+async fn delete_bot_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Path(path): Path<BotPath>,
) -> Result<StatusCode, BotsHandlerErr> {
state
.service
- .delete_bot(caller_from_user(user), path.bot_id)
+ .delete_bot(authorization.macro_user_id, path.bot_id)
.await?;
Ok(StatusCode::NO_CONTENT)
}
-async fn create_token_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+async fn create_token_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Path(path): Path<BotPath>,
Json(req): Json<CreateBotTokenRequest>,
) -> Result<(StatusCode, Json<CreateBotTokenResponse>), BotsHandlerErr> {
let token = state
.service
- .create_token(caller_from_user(user), path.bot_id, req)
+ .create_token(authorization.macro_user_id, path.bot_id, req)
.await?;
Ok((StatusCode::CREATED, Json(token)))
}
-async fn list_tokens_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+async fn list_tokens_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Path(path): Path<BotPath>,
) -> Result<Json<Vec<BotToken>>, BotsHandlerErr> {
Ok(Json(
state
.service
- .list_tokens(caller_from_user(user), path.bot_id)
+ .list_tokens(authorization.macro_user_id, path.bot_id)
.await?,
))
}
-async fn revoke_token_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+async fn revoke_token_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Path(path): Path<BotTokenPath>,
) -> Result<StatusCode, BotsHandlerErr> {
state
.service
- .revoke_token(caller_from_user(user), path.bot_id, path.token_id)
+ .revoke_token(authorization.macro_user_id, path.bot_id, path.token_id)
.await?;
Ok(StatusCode::NO_CONTENT)
}
@@ -272,15 +321,19 @@ async fn revoke_token_handler<S: BotService, Svc: EntityAccessService>(
(status = 500, body = ErrorResponse),
)
)]
-pub async fn list_bot_channels_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn list_bot_channels_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Path(path): Path<BotPath>,
) -> Result<Json<Vec<BotChannel>>, BotsHandlerErr> {
Ok(Json(
state
.service
- .list_bot_channels(caller_from_user(user), path.bot_id)
+ .list_bot_channels(authorization.macro_user_id, path.bot_id)
.await?,
))
}
@@ -302,21 +355,29 @@ pub async fn list_bot_channels_handler<S: BotService, Svc: EntityAccessService>(
(status = 500, body = ErrorResponse),
)
)]
-pub async fn remove_bot_channel_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- user: MacroUserExtractor,
+pub async fn remove_bot_channel_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth>,
Path(path): Path<BotChannelPath>,
) -> Result<StatusCode, BotsHandlerErr> {
state
.service
- .remove_bot_from_channel(caller_from_user(user), path.channel_id, path.bot_id)
+ .remove_bot_from_channel(authorization.macro_user_id, path.channel_id, path.bot_id)
.await?;
Ok(StatusCode::NO_CONTENT)
}
-async fn list_channel_bots_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- _access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,
+async fn list_channel_bots_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ _access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc, Auth>,
Path(path): Path<ChannelPath>,
) -> Result<Json<Vec<Bot>>, BotsHandlerErr> {
Ok(Json(
@@ -324,9 +385,13 @@ async fn list_channel_bots_handler<S: BotService, Svc: EntityAccessService>(
))
}
-async fn add_channel_bot_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,
+async fn add_channel_bot_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc, Auth>,
Path(path): Path<ChannelPath>,
Json(req): Json<AddChannelBotRequest>,
) -> Result<StatusCode, BotsHandlerErr> {
@@ -338,9 +403,13 @@ async fn add_channel_bot_handler<S: BotService, Svc: EntityAccessService>(
Ok(StatusCode::NO_CONTENT)
}
-async fn remove_channel_bot_handler<S: BotService, Svc: EntityAccessService>(
- State(state): State<BotsRouterState<S, Svc>>,
- access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,
+async fn remove_channel_bot_handler<
+ S: BotService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<BotsRouterState<S, Svc, Auth>>,
+ access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc, Auth>,
Path(path): Path<ChannelBotPath>,
) -> Result<StatusCode, BotsHandlerErr> {
let caller = caller_from_receipt(&access.entity_access_receipt)?;
diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rs
index d92ed7f1a1..4b97bbd9bc 100644
--- a/crates/bots/src/inbound/axum_router/tests.rs
+++ b/crates/bots/src/inbound/axum_router/tests.rs
@@ -5,9 +5,8 @@ use crate::domain::models::{
};
use crate::{domain::service::BotServiceImpl, outbound::pg_bots_repo::PgBotsRepo};
use axum::{
- Extension,
body::Body,
- http::{Request, StatusCode},
+ http::{Request, StatusCode, header},
};
use entity_access::domain::{
models::{
@@ -17,9 +16,13 @@ use entity_access::domain::{
ports::EntityAccessService,
};
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use macro_authorization::{
+ InternalAuthConfig, JwtValidator, MacroAuthorizationError, MacroAuthorizationServiceImpl,
+ MacroAuthorizationState, ValidatedIdentity,
+};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
-use model_user::UserContext;
+use rootcause::Report;
use sqlx::{PgPool, Row};
use std::sync::{
Arc,
@@ -27,6 +30,9 @@ use std::sync::{
};
use tower::ServiceExt;
+const DEFAULT_BEARER_TOKEN: &str = "macro|[email protected]";
+const INVALID_BEARER_TOKEN: &str = "invalid";
+
#[derive(Clone, Copy)]
enum TestBotMode {
Ok,
@@ -293,32 +299,79 @@ impl EntityAccessService for TestAccessService {
}
}
-fn user_extension() -> Extension<UserContext> {
- Extension(UserContext {
- user_id: "macro|[email protected]".to_string(),
- fusion_user_id: "fusion-user".to_string(),
- permissions: None,
- organization_id: None,
- })
+#[derive(Clone, Default)]
+struct FakeJwtValidator;
+
+impl JwtValidator for FakeJwtValidator {
+ fn validate(&self, jwt: &str) -> Result<ValidatedIdentity, Report<MacroAuthorizationError>> {
+ if jwt == INVALID_BEARER_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(ValidatedIdentity {
+ user_id: jwt.to_string(),
+ fusion_user_id: "fusion-user".to_string(),
+ organization_id: None,
+ permissions: None,
+ })
+ }
}
-fn router(service: TestBotService, role: EntityParticipantRole) -> Router {
- bots_router(BotsRouterState::new(service, TestAccessService::new(role))).layer(user_extension())
+type TestAuthorizationService = MacroAuthorizationServiceImpl<FakeJwtValidator>;
+
+fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
+ let service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator,
+ InternalAuthConfig {
+ api_key: "test-internal-key".to_string(),
+ default_user_id: None,
+ },
+ );
+ MacroAuthorizationState::new(Arc::new(service))
}
-fn user_context(user_id: &str) -> Extension<UserContext> {
- Extension(UserContext {
- user_id: user_id.to_string(),
- fusion_user_id: "fusion-user".to_string(),
- permissions: None,
- organization_id: None,
- })
+async fn attach_default_bearer(mut request: Request<Body>) -> Request<Body> {
+ request.headers_mut().insert(
+ header::AUTHORIZATION,
+ format!("Bearer {DEFAULT_BEARER_TOKEN}").parse().unwrap(),
+ );
+ request
+}
+
+fn router_without_credentials(service: TestBotService, role: EntityParticipantRole) -> Router {
+ bots_router(BotsRouterState::new(
+ service,
+ TestAccessService::new(role),
+ authorization_state(),
+ ))
+}
+
+fn router(service: TestBotService, role: EntityParticipantRole) -> Router {
+ router_without_credentials(service, role)
+ .layer(axum::middleware::map_request(attach_default_bearer))
}
fn real_router(pool: PgPool, user_id: &str) -> Router {
let bot_service = BotServiceImpl::new(PgBotsRepo::new(pool.clone()));
let access_service = EntityAccessServiceImpl::new(PgAccessRepository::new(pool));
- bots_router(BotsRouterState::new(bot_service, access_service)).layer(user_context(user_id))
+ let bearer_token = user_id.to_string();
+ bots_router(BotsRouterState::new(
+ bot_service,
+ access_service,
+ authorization_state(),
+ ))
+ .layer(axum::middleware::from_fn(
+ move |mut request: Request<Body>, next: axum::middleware::Next| {
+ let bearer_token = bearer_token.clone();
+ async move {
+ request.headers_mut().insert(
+ header::AUTHORIZATION,
+ format!("Bearer {bearer_token}").parse().unwrap(),
+ );
+ next.run(request).await
+ }
+ },
+ ))
}
async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {
@@ -432,6 +485,25 @@ async fn bot_owner_can_list_bot_channels_via_http() {
assert_eq!(service.list_bot_channels_calls.load(Ordering::SeqCst), 1);
}
+#[tokio::test]
+async fn bot_route_requires_credentials_without_invoking_service() {
+ let service = TestBotService::new(TestBotMode::Ok);
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let request = Request::builder()
+ .method("GET")
+ .uri(format!("/bots/{bot_id}/channels"))
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router_without_credentials(service.clone(), EntityParticipantRole::Member)
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(service.list_bot_channels_calls.load(Ordering::SeqCst), 0);
+}
+
#[tokio::test]
async fn bot_listing_requires_bot_usability() {
let service = TestBotService::new(TestBotMode::Unauthorized);
diff --git a/crates/bots/src/inbound/channel_webhook_router.rs b/crates/bots/src/inbound/channel_webhook_router.rs
index a5b415543a..7a854ed94a 100644
--- a/crates/bots/src/inbound/channel_webhook_router.rs
+++ b/crates/bots/src/inbound/channel_webhook_router.rs
@@ -29,6 +29,7 @@ use entity_access::{
},
inbound::axum_extractors::ChannelAccessLevelExtractor,
};
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use std::{future::Future, sync::Arc};
@@ -63,26 +64,28 @@ where
}
/// State for the channel bot webhook router.
-pub struct ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc> {
+pub struct ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth> {
bot_service: Arc<BotSvc>,
channel_poster: Arc<ChannelPoster>,
access_service: Arc<AccessSvc>,
+ authorization_state: MacroAuthorizationState<Auth>,
}
-impl<BotSvc, ChannelPoster, AccessSvc> Clone
- for ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>
+impl<BotSvc, ChannelPoster, AccessSvc, Auth> Clone
+ for ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>
{
fn clone(&self) -> Self {
Self {
bot_service: self.bot_service.clone(),
channel_poster: self.channel_poster.clone(),
access_service: self.access_service.clone(),
+ authorization_state: self.authorization_state.clone(),
}
}
}
-impl<BotSvc, ChannelPoster, AccessSvc>
- ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>
+impl<BotSvc, ChannelPoster, AccessSvc, Auth>
+ ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>
where
BotSvc: BotService,
ChannelPoster: ChannelMessagePoster,
@@ -93,23 +96,39 @@ where
bot_service: BotSvc,
channel_poster: ChannelPoster,
access_service: AccessSvc,
+ authorization_state: MacroAuthorizationState<Auth>,
) -> Self {
Self {
bot_service: Arc::new(bot_service),
channel_poster: Arc::new(channel_poster),
access_service: Arc::new(access_service),
+ authorization_state,
}
}
}
-impl<BotSvc, ChannelPoster, AccessSvc>
- FromRef<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>> for Arc<AccessSvc>
+impl<BotSvc, ChannelPoster, AccessSvc, Auth>
+ FromRef<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>>
+ for Arc<AccessSvc>
{
- fn from_ref(state: &ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>) -> Self {
+ fn from_ref(
+ state: &ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>,
+ ) -> Self {
state.access_service.clone()
}
}
+impl<BotSvc, ChannelPoster, AccessSvc, Auth>
+ FromRef<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>>
+ for MacroAuthorizationState<Auth>
+{
+ fn from_ref(
+ state: &ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>,
+ ) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
/// Channel id path.
#[derive(Debug, serde::Deserialize)]
pub struct ChannelPath {
@@ -118,37 +137,39 @@ pub struct ChannelPath {
}
/// Create the authenticated channel-scoped bot creation router.
-pub fn channel_scoped_bot_router<BotSvc, ChannelPoster, AccessSvc, T>(
- state: ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>,
+pub fn channel_scoped_bot_router<BotSvc, ChannelPoster, AccessSvc, Auth, T>(
+ state: ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>,
) -> Router<T>
where
BotSvc: BotService,
ChannelPoster: ChannelMessagePoster,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
T: Send + Sync,
{
Router::new()
.route(
"/channels/{channel_id}/bots/scoped",
- post(create_channel_scoped_bot_handler::<BotSvc, ChannelPoster, AccessSvc>),
+ post(create_channel_scoped_bot_handler::<BotSvc, ChannelPoster, AccessSvc, Auth>),
)
.with_state(state)
}
/// Create the unauthenticated channel bot webhook router.
-pub fn channel_bot_webhook_router<BotSvc, ChannelPoster, AccessSvc, T>(
- state: ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>,
+pub fn channel_bot_webhook_router<BotSvc, ChannelPoster, AccessSvc, Auth, T>(
+ state: ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>,
) -> Router<T>
where
BotSvc: BotService,
ChannelPoster: ChannelMessagePoster,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
T: Send + Sync,
{
Router::new()
.route(
"/channels/{channel_id}/webhook",
- post(post_channel_webhook_handler::<BotSvc, ChannelPoster, AccessSvc>),
+ post(post_channel_webhook_handler::<BotSvc, ChannelPoster, AccessSvc, Auth>),
)
.with_state(state)
}
@@ -181,9 +202,9 @@ fn caller_from_receipt(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn create_channel_scoped_bot_handler<BotSvc, ChannelPoster, AccessSvc>(
- State(state): State<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>>,
- access: ChannelAccessLevelExtractor<AdminParticipantRole, AccessSvc>,
+pub async fn create_channel_scoped_bot_handler<BotSvc, ChannelPoster, AccessSvc, Auth>(
+ State(state): State<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>>,
+ access: ChannelAccessLevelExtractor<AdminParticipantRole, AccessSvc, Auth>,
Path(path): Path<ChannelPath>,
Json(req): Json<CreateChannelScopedBotRequest>,
) -> Result<(StatusCode, Json<CreateChannelScopedBotResponse>), ChannelBotWebhookHandlerErr>
@@ -191,6 +212,7 @@ where
BotSvc: BotService,
ChannelPoster: ChannelMessagePoster,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
let caller = caller_from_receipt(&access.entity_access_receipt)?;
let response = state
@@ -220,8 +242,8 @@ where
)
)]
#[tracing::instrument(err, skip_all, fields(channel_id = tracing::field::Empty))]
-pub async fn post_channel_webhook_handler<BotSvc, ChannelPoster, AccessSvc>(
- State(state): State<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc>>,
+pub async fn post_channel_webhook_handler<BotSvc, ChannelPoster, AccessSvc, Auth>(
+ State(state): State<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>>,
Path(path): Path<ChannelPath>,
headers: HeaderMap,
body: Bytes,
@@ -230,6 +252,7 @@ where
BotSvc: BotService,
ChannelPoster: ChannelMessagePoster,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
tracing::Span::current().record("channel_id", tracing::field::display(path.channel_id));
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index 3e398d8806..dfd99a64dc 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -4,9 +4,9 @@ use crate::domain::models::{
CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,
};
use axum::{
- Extension, Router,
+ Router,
body::Body,
- http::{Request, StatusCode},
+ http::{Request, StatusCode, header},
};
use channels::domain::models::PostMessageResponse;
use entity_access::domain::{
@@ -16,14 +16,20 @@ use entity_access::domain::{
},
ports::EntityAccessService,
};
+use macro_authorization::{
+ InternalAuthConfig, JwtValidator, MacroAuthorizationError, MacroAuthorizationServiceImpl,
+ MacroAuthorizationState, ValidatedIdentity,
+};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
-use model_user::UserContext;
+use rootcause::Report;
use std::sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering},
};
use tower::ServiceExt;
+const DEFAULT_BEARER_TOKEN: &str = "macro|[email protected]";
+
#[derive(Clone)]
enum TestCreateMode {
Ok(CreateChannelScopedBotResponse),
@@ -406,13 +412,39 @@ impl ChannelMessagePoster for TestChannelPoster {
}
}
-fn user_extension() -> Extension<UserContext> {
- Extension(UserContext {
- user_id: "macro|[email protected]".to_string(),
- fusion_user_id: "fusion-user".to_string(),
- permissions: None,
- organization_id: None,
- })
+#[derive(Clone, Default)]
+struct FakeJwtValidator;
+
+impl JwtValidator for FakeJwtValidator {
+ fn validate(&self, jwt: &str) -> Result<ValidatedIdentity, Report<MacroAuthorizationError>> {
+ Ok(ValidatedIdentity {
+ user_id: jwt.to_string(),
+ fusion_user_id: "fusion-user".to_string(),
+ organization_id: None,
+ permissions: None,
+ })
+ }
+}
+
+type TestAuthorizationService = MacroAuthorizationServiceImpl<FakeJwtValidator>;
+
+fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
+ let service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator,
+ InternalAuthConfig {
+ api_key: "test-internal-key".to_string(),
+ default_user_id: None,
+ },
+ );
+ MacroAuthorizationState::new(Arc::new(service))
+}
+
+async fn attach_default_bearer(mut request: Request<Body>) -> Request<Body> {
+ request.headers_mut().insert(
+ header::AUTHORIZATION,
+ format!("Bearer {DEFAULT_BEARER_TOKEN}").parse().unwrap(),
+ );
+ request
}
fn router(
@@ -424,8 +456,9 @@ fn router(
service,
poster,
TestAccessService::new(role),
+ authorization_state(),
))
- .layer(user_extension())
+ .layer(axum::middleware::map_request(attach_default_bearer))
}
fn webhook_router(service: TestBotService, poster: TestChannelPoster) -> Router {
@@ -433,6 +466,7 @@ fn webhook_router(service: TestBotService, poster: TestChannelPoster) -> Router
service,
poster,
TestAccessService::new(EntityParticipantRole::Member),
+ authorization_state(),
))
}
diff --git a/crates/call/src/inbound/axum_router.rs b/crates/call/src/inbound/axum_router.rs
index c547846d62..d8391f2d5a 100644
--- a/crates/call/src/inbound/axum_router.rs
+++ b/crates/call/src/inbound/axum_router.rs
@@ -24,7 +24,7 @@ use entity_access::{
},
inbound::axum_extractors::{
CallAccessLevelExtractor, CallWithChannelIdAccessLevelExtractor,
- ChannelAccessLevelExtractorV2,
+ ChannelAccessLevelExtractor,
},
};
use macro_authorization::{
@@ -289,7 +289,7 @@ pub async fn get_or_create_call_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<CallRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
user: MacroAuthorizationExtractor<Auth>,
) -> Result<Json<CallTokenResponse>, CallError> {
let channel_id = Uuid::parse_str(&access.entity_access_receipt.entity().entity_id)
@@ -327,7 +327,7 @@ pub async fn check_active_call_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<CallRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<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")))?;
diff --git a/crates/channels/src/inbound/axum_router.rs b/crates/channels/src/inbound/axum_router.rs
index 34f565b838..1a285ba7f1 100644
--- a/crates/channels/src/inbound/axum_router.rs
+++ b/crates/channels/src/inbound/axum_router.rs
@@ -40,7 +40,7 @@ use entity_access::{
},
ports::EntityAccessService,
},
- inbound::axum_extractors::ChannelAccessLevelExtractorV2,
+ inbound::axum_extractors::ChannelAccessLevelExtractor,
};
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
@@ -517,7 +517,7 @@ pub async fn patch_channel_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<AdminParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc, Auth>,
Json(req): Json<PatchChannelRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -551,7 +551,7 @@ pub async fn delete_channel_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<OwnerParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<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)?;
@@ -585,7 +585,7 @@ pub async fn post_message_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Json(req): Json<PostMessageRequest>,
) -> Result<(StatusCode, Json<PostMessageResponse>), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -621,7 +621,7 @@ pub async fn patch_message_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
Json(req): Json<PatchMessageRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
@@ -661,7 +661,7 @@ pub async fn delete_message_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
Query(query): Query<DeleteMessageQuery>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
@@ -700,7 +700,7 @@ pub async fn post_reaction_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Json(req): Json<PostReactionRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -735,7 +735,7 @@ pub async fn post_typing_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Json(req): Json<PostTypingRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -770,7 +770,7 @@ pub async fn add_participants_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Json(req): Json<AddParticipantsRequest>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -808,7 +808,7 @@ pub async fn remove_participants_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Json(req): Json<RemoveParticipantsRequest>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -845,7 +845,7 @@ pub async fn get_channel_join_link_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<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?;
@@ -947,7 +947,7 @@ pub async fn leave_channel_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<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)?;
@@ -1142,7 +1142,7 @@ pub async fn get_channel_messages_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Query(params): Query<Params>,
cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {
@@ -1189,7 +1189,7 @@ pub async fn post_channel_messages_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Query(params): Query<Params>,
cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
Json(filters): Json<ChannelMessageFilters>,
@@ -1311,7 +1311,7 @@ pub async fn get_thread_replies_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- _access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ _access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
) -> Result<Json<Vec<ApiThreadReply>>, ChannelsHandlerErr> {
let channel_id = path.channel_id;
@@ -1364,7 +1364,7 @@ pub async fn get_message_with_context_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- _access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ _access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
Query(params): Query<MessageContextParams>,
) -> Result<Json<GetMessageWithContextResponse>, ChannelsHandlerErr> {
@@ -1416,7 +1416,7 @@ pub async fn resolve_channel_message_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- _access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ _access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Path(path): Path<ThreadRepliesPath>,
) -> Result<Json<ApiResolvedChannelMessage>, ChannelsHandlerErr> {
let channel_id = path.channel_id;
@@ -1467,7 +1467,7 @@ pub async fn get_channel_attachments_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Query(params): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<PaginatedOpaqueCursor<ApiChannelAttachment>>, ChannelsHandlerErr> {
@@ -1533,7 +1533,7 @@ pub async fn get_channel_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Query(params): Query<Params>,
) -> Result<Json<ApiChannelDetail>, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
@@ -1595,7 +1595,7 @@ pub async fn get_channel_participants_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractorV2<MemberParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<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));
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel.rs b/crates/entity_access/src/inbound/axum_extractors/channel.rs
index fb3d4b7819..5f40d87c49 100644
--- a/crates/entity_access/src/inbound/axum_extractors/channel.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/channel.rs
@@ -7,12 +7,12 @@ use std::marker::PhantomData;
use std::sync::Arc;
use axum::{
- Extension, RequestPartsExt,
+ RequestPartsExt,
extract::{FromRef, FromRequestParts, Path},
http::request::Parts,
};
-use super::{ExtractorError, InternalUser};
+use super::ExtractorError;
use crate::domain::{
models::{
Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -23,125 +23,24 @@ use crate::domain::{
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
};
-use model_user::axum_extractor::OptionalMacroUserExtractor;
-
#[derive(Debug, serde::Deserialize)]
struct ChannelAccessParams {
channel_id: String,
}
-/// Validates that the user satisfies the required permission for a channel.
-///
-/// Type parameter `T` specifies the required permission marker.
-/// Type parameter `Svc` is the entity access service implementation.
-#[derive(Debug)]
-pub struct ChannelAccessLevelExtractor<T: RequiredPermission, Svc> {
- /// The entity access receipt
- pub entity_access_receipt: EntityAccessReceipt<T>,
- _marker: PhantomData<(T, Svc)>,
-}
-
-impl<T, S, Svc> FromRequestParts<S> for ChannelAccessLevelExtractor<T, Svc>
-where
- T: RequiredPermission,
- Arc<Svc>: FromRef<S>,
- Svc: EntityAccessService,
- S: Send + Sync + 'static,
-{
- type Rejection = ExtractorError;
-
- #[tracing::instrument(err, skip(state, parts))]
- async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
- let service = <Arc<Svc>>::from_ref(state);
-
- let OptionalMacroUserExtractor {
- macro_user_id,
- user_context,
- ..
- } = parts
- .extract()
- .await
- .map_err(|_| ExtractorError::Internal)?;
-
- let Path(ChannelAccessParams { channel_id }) = parts
- .extract::<Path<ChannelAccessParams>>()
- .await
- .map_err(|_| ExtractorError::BadRequest("missing channel_id path parameter"))?;
-
- 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() {
- 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 user_org_id = user_context.organization_id.map(i64::from);
-
- let permission = service
- .get_entity_permission(
- Some(&macro_user_id),
- &channel_id,
- EntityType::Channel,
- user_org_id,
- )
- .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,
- })
- }
-}
-
/// 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> {
+pub struct ChannelAccessLevelExtractor<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>
+impl<T, S, Svc, Auth> FromRequestParts<S> for ChannelAccessLevelExtractor<T, Svc, Auth>
where
T: RequiredPermission,
Arc<Svc>: FromRef<S>,
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
index 28448343e2..308337b3da 100644
--- a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
@@ -238,17 +238,17 @@ impl FromRef<TestState> for MacroAuthorizationState<FakeAuthorizationService> {
}
}
-type V2Member = ChannelAccessLevelExtractorV2<
+type MemberExtractor = ChannelAccessLevelExtractor<
MemberParticipantRole,
FakeEntityAccessService,
FakeAuthorizationService,
>;
-type V2Admin = ChannelAccessLevelExtractorV2<
+type AdminExtractor = ChannelAccessLevelExtractor<
AdminParticipantRole,
FakeEntityAccessService,
FakeAuthorizationService,
>;
-type V2Owner = ChannelAccessLevelExtractorV2<
+type OwnerExtractor = ChannelAccessLevelExtractor<
OwnerParticipantRole,
FakeEntityAccessService,
FakeAuthorizationService,
@@ -305,12 +305,12 @@ fn assert_member_receipt(receipt: &EntityAccessReceipt<MemberParticipantRole>) {
));
}
-async fn member_handler(extractor: V2Member) -> StatusCode {
+async fn member_handler(extractor: MemberExtractor) -> StatusCode {
assert_member_receipt(&extractor.entity_access_receipt);
StatusCode::OK
}
-async fn authenticated_member_handler(extractor: V2Member) -> StatusCode {
+async fn authenticated_member_handler(extractor: MemberExtractor) -> StatusCode {
let receipt = extractor.entity_access_receipt;
assert_member_receipt(&receipt);
assert!(matches!(
@@ -320,11 +320,11 @@ async fn authenticated_member_handler(extractor: V2Member) -> StatusCode {
StatusCode::OK
}
-async fn admin_handler(_extractor: V2Admin) -> StatusCode {
+async fn admin_handler(_extractor: AdminExtractor) -> StatusCode {
StatusCode::OK
}
-async fn owner_handler(extractor: V2Owner) -> StatusCode {
+async fn owner_handler(extractor: OwnerExtractor) -> StatusCode {
assert!(matches!(
extractor.entity_access_receipt.auth(),
EntityAccessAuth::Internal
@@ -465,37 +465,3 @@ async fn default_internal_identity_uses_ordinary_acl_evaluation() {
);
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 49c7d7c009..500e33ec19 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, ChannelAccessLevelExtractorV2};
+pub use channel::ChannelAccessLevelExtractor;
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 35c63f6224..72ce74bd9a 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -302,11 +302,16 @@ pub(crate) type DssChannelsState =
pub(crate) type DssBotService = BotServiceImpl<PgBotsRepo>;
/// Type alias for the bots router state.
-pub(crate) type DssBotsState = BotsRouterState<DssBotService, EntityAccessService>;
+pub(crate) type DssBotsState =
+ BotsRouterState<DssBotService, EntityAccessService, AuthorizationService>;
/// Type alias for the channel bot webhook router state.
-pub(crate) type DssChannelBotWebhookState =
- ChannelBotWebhookRouterState<DssBotService, Arc<DssChannelService>, EntityAccessService>;
+pub(crate) type DssChannelBotWebhookState = ChannelBotWebhookRouterState<
+ DssBotService,
+ Arc<DssChannelService>,
+ EntityAccessService,
+ AuthorizationService,
+>;
/// Type alias for the call connection service.
pub(crate) type CallConnectionService =
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 692c6af71f..2ad4dd06cd 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -830,6 +830,7 @@ async fn main() -> anyhow::Result<()> {
bots_service.clone(),
channels_service.clone(),
(*entity_access_service).clone(),
+ authorization_state.clone(),
);
let soup_service = Arc::new(SoupImpl::new(
@@ -913,6 +914,7 @@ async fn main() -> anyhow::Result<()> {
bots_state: bots::inbound::axum_router::BotsRouterState::new(
bots_service.clone(),
(*entity_access_service).clone(),
+ authorization_state.clone(),
),
channel_bot_webhook_state,
call_state,