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): make channels crate use entity access pattern (#1807)

teo6a970d6f2218
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index b66c0d6e21..99f4eb2297 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -646,6 +646,26 @@
}
}
},
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -736,6 +756,16 @@
}
}
},
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -800,6 +830,16 @@
}
}
},
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -854,6 +894,26 @@
}
}
},
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 2a2912daa2..a66bbf1227 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1762,8 +1762,10 @@ dependencies = [
"anyhow",
"axum",
"chrono",
+ "entity_access",
"http-body-util",
"macro_db_migrator",
+ "macro_user_id",
"mockall",
"model-error-response",
"model_user",
diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.toml
index 764ee4d13f..5c377cbf28 100644
--- a/rust/cloud-storage/channels/Cargo.toml
+++ b/rust/cloud-storage/channels/Cargo.toml
@@ -7,6 +7,7 @@ version = "0.1.0"
[features]
inbound = [
"dep:axum",
+ "dep:entity_access",
"dep:model-error-response",
"dep:model_user",
"dep:utoipa",
@@ -20,6 +21,7 @@ ports = ["dep:tokio"]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
chrono = { workspace = true }
+entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["inbound"] }
model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
models_pagination = { path = "../models_pagination" }
@@ -34,6 +36,7 @@ uuid = { workspace = true }
[dev-dependencies]
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
+macro_user_id = { path = "../macro_user_id" }
mockall = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index ea9aaff0e0..964a65f51c 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -123,16 +123,6 @@ pub trait ChannelMessagesService: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send;
}
-/// Access check for channel membership. Separated from the business logic service.
-pub trait ChannelAccessCheck: Send + Sync + 'static {
- /// Check whether a user is an active participant in a channel.
- fn is_channel_member(
- &self,
- channel_id: Uuid,
- user_id: &str,
- ) -> impl Future<Output = Result<bool, anyhow::Error>> + Send;
-}
-
/// A paginated page of channel messages.
pub type ChannelMessagesPage =
models_pagination::PaginatedCursor<super::models::ChannelMessage, Uuid, CreatedAt, ()>;
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index 686fa55b1c..0c02bd5b9b 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -6,125 +6,68 @@ use crate::domain::models::{
MessagePageDirection, ParticipantRole, ThreadInfo, ThreadReply,
};
use crate::domain::ports::{
- ChannelAccessCheck, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult,
- ChannelMessagesService,
+ ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult, ChannelMessagesService,
};
use axum::{
Json, Router,
- extract::{FromRequestParts, Path, Query, State},
- http::{StatusCode, request::Parts},
+ extract::{FromRef, Path, Query, State},
+ http::StatusCode,
response::IntoResponse,
routing::get,
};
use chrono::{DateTime, Utc};
+use entity_access::{
+ domain::{
+ models::{EntityAccessReceipt, MemberParticipantRole, RequiredPermission},
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::ChannelAccessLevelExtractor,
+};
use model_error_response::ErrorResponse;
-use model_user::axum_extractor::MacroUserExtractor;
use models_pagination::{
Base64Str, BidirectionalCursor, BidirectionalCursorExtractor, CreatedAt, Cursor,
CursorExtractor, CursorVal, PaginatedOpaqueCursor, Query as PaginationQuery, TypeEraseCursor,
};
use serde::{Deserialize, Serialize};
-use std::{collections::HashMap, sync::Arc};
+use std::sync::Arc;
use uuid::Uuid;
/// State for the channels router.
-pub struct ChannelsRouterState<S, A> {
+pub struct ChannelsRouterState<S, Svc> {
service: Arc<S>,
- access: Arc<A>,
+ access_service: Arc<Svc>,
}
-impl<S, A> Clone for ChannelsRouterState<S, A> {
+impl<S, Svc> Clone for ChannelsRouterState<S, Svc> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
- access: self.access.clone(),
+ access_service: self.access_service.clone(),
}
}
}
-impl<S: ChannelMessagesService, A: ChannelAccessCheck> ChannelsRouterState<S, A> {
- /// Create a new router state wrapping the service and access checker.
- pub fn new(service: S, access: A) -> Self {
+impl<S: ChannelMessagesService, Svc: EntityAccessService> ChannelsRouterState<S, Svc> {
+ /// Create a new router state wrapping the service and entity access service.
+ pub fn new(service: S, access_service: Svc) -> Self {
Self {
service: Arc::new(service),
- access: Arc::new(access),
+ access_service: Arc::new(access_service),
}
}
}
-/// Verified channel member. Rejects the request if the authenticated user is not an active
-/// participant in the channel identified by the `:channel_id` path parameter.
-pub struct ChannelMember {
- /// The channel id from the path.
- pub channel_id: Uuid,
-}
-
-/// Rejection returned by the [`ChannelMember`] extractor.
-#[derive(Debug)]
-pub enum ChannelMemberRejection {
- /// The user is not authenticated.
- Unauthenticated,
- /// The `:channel_id` path parameter is missing or invalid.
- InvalidPath,
- /// The user is not a member of the channel.
- Forbidden,
- /// A database or internal error occurred.
- Internal,
-}
-
-impl IntoResponse for ChannelMemberRejection {
- fn into_response(self) -> axum::response::Response {
- let (status, message) = match self {
- Self::Unauthenticated => (StatusCode::UNAUTHORIZED, "Unauthorized"),
- Self::InvalidPath => (StatusCode::BAD_REQUEST, "Invalid channel_id"),
- Self::Forbidden => (StatusCode::FORBIDDEN, "Not a channel member"),
- Self::Internal => (
- StatusCode::INTERNAL_SERVER_ERROR,
- "An internal server error occurred",
- ),
- };
- (status, Json(ErrorResponse { message })).into_response()
+impl<S, Svc> FromRef<ChannelsRouterState<S, Svc>> for Arc<Svc> {
+ fn from_ref(state: &ChannelsRouterState<S, Svc>) -> Self {
+ state.access_service.clone()
}
}
-#[axum::async_trait]
-impl<S, A> FromRequestParts<ChannelsRouterState<S, A>> for ChannelMember
-where
- S: ChannelMessagesService,
- A: ChannelAccessCheck,
-{
- type Rejection = ChannelMemberRejection;
-
- async fn from_request_parts(
- parts: &mut Parts,
- state: &ChannelsRouterState<S, A>,
- ) -> Result<Self, Self::Rejection> {
- let user = MacroUserExtractor::from_request_parts(parts, state)
- .await
- .map_err(|_| ChannelMemberRejection::Unauthenticated)?;
-
- let Path(path_params) = Path::<HashMap<String, String>>::from_request_parts(parts, state)
- .await
- .map_err(|_| ChannelMemberRejection::InvalidPath)?;
- let channel_id = path_params
- .get("channel_id")
- .ok_or(ChannelMemberRejection::InvalidPath)
- .and_then(|raw| {
- Uuid::parse_str(raw.as_str()).map_err(|_| ChannelMemberRejection::InvalidPath)
- })?;
-
- let is_member = state
- .access
- .is_channel_member(channel_id, &user.user_context.user_id)
- .await
- .map_err(|_| ChannelMemberRejection::Internal)?;
-
- if !is_member {
- return Err(ChannelMemberRejection::Forbidden);
- }
-
- Ok(ChannelMember { channel_id })
- }
+fn channel_id_from_receipt<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+) -> Result<Uuid, ChannelsHandlerErr> {
+ Uuid::parse_str(&receipt.entity().entity_id)
+ .map_err(|_| ChannelsHandlerErr::BadRequest("Invalid channel_id"))
}
/// Query parameters for the messages endpoint.
@@ -190,28 +133,28 @@ fn cursor_from_first_message(
}
/// Create the channels router.
-pub fn channels_router<S, A, T>(state: ChannelsRouterState<S, A>) -> Router<T>
+pub fn channels_router<S, Svc, T>(state: ChannelsRouterState<S, Svc>) -> Router<T>
where
S: ChannelMessagesService,
- A: ChannelAccessCheck,
+ Svc: EntityAccessService,
T: Send + Sync,
{
Router::new()
.route(
"/:channel_id/messages",
- get(get_channel_messages_handler::<S, A>),
+ get(get_channel_messages_handler::<S, Svc>),
)
.route(
"/:channel_id/messages/:message_id/replies",
- get(get_thread_replies_handler::<S, A>),
+ get(get_thread_replies_handler::<S, Svc>),
)
.route(
"/:channel_id/attachments",
- get(get_channel_attachments_handler::<S, A>),
+ get(get_channel_attachments_handler::<S, Svc>),
)
.route(
"/:channel_id/participants",
- get(get_channel_participants_handler::<S, A>),
+ get(get_channel_participants_handler::<S, Svc>),
)
.with_state(state)
}
@@ -230,26 +173,28 @@ where
),
responses(
(status = 200, body = ApiChannelMessagesPage),
+ (status = 401, body = ErrorResponse),
(status = 400, body = ErrorResponse),
(status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_channel_messages_handler<S: ChannelMessagesService, A: ChannelAccessCheck>(
- State(state): State<ChannelsRouterState<S, A>>,
- member: ChannelMember,
+pub async fn get_channel_messages_handler<S: ChannelMessagesService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Query(params): Query<Params>,
cursor: BidirectionalCursorExtractor<Uuid, CreatedAt, ()>,
) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {
let limit = params.limit.unwrap_or(50).clamp(1, 100);
let (query, direction, has_cursor) = parse_messages_query(cursor);
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
let (page, has_more_newer) = match params.load_around_message_id {
Some(message_id) => {
let page = state
.service
- .get_channel_messages_around(member.channel_id, message_id, limit)
+ .get_channel_messages_around(channel_id, message_id, limit)
.await?;
(page, false)
}
@@ -259,7 +204,7 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, A: ChannelA
has_more_newer,
} = state
.service
- .get_channel_messages(member.channel_id, query, direction, limit)
+ .get_channel_messages(channel_id, query, direction, limit)
.await?;
(page, has_more_newer)
}
@@ -301,14 +246,15 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, A: ChannelA
),
responses(
(status = 200, body = Vec<ApiThreadReply>),
+ (status = 401, body = ErrorResponse),
(status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_thread_replies_handler<S: ChannelMessagesService, A: ChannelAccessCheck>(
- State(state): State<ChannelsRouterState<S, A>>,
- _member: ChannelMember,
+pub async fn get_thread_replies_handler<S: ChannelMessagesService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ _access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Path(path): Path<ThreadRepliesPath>,
) -> Result<Json<Vec<ApiThreadReply>>, ChannelsHandlerErr> {
let channel_id = path.channel_id;
@@ -336,22 +282,28 @@ pub async fn get_thread_replies_handler<S: ChannelMessagesService, A: ChannelAcc
),
responses(
(status = 200, body = ApiChannelAttachmentsPage),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_channel_attachments_handler<S: ChannelMessagesService, A: ChannelAccessCheck>(
- State(state): State<ChannelsRouterState<S, A>>,
- member: ChannelMember,
+pub async fn get_channel_attachments_handler<
+ S: ChannelMessagesService,
+ Svc: EntityAccessService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Query(params): Query<Params>,
cursor: CursorExtractor<Uuid, CreatedAt, ()>,
) -> Result<Json<PaginatedOpaqueCursor<ApiChannelAttachment>>, ChannelsHandlerErr> {
let limit = params.limit.unwrap_or(50);
let query = cursor.into_query(CreatedAt, ());
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
let page = state
.service
- .get_channel_attachments(member.channel_id, query, limit)
+ .get_channel_attachments(channel_id, query, limit)
.await?;
Ok(Json(page.type_erase().map(ApiChannelAttachment::from)))
@@ -367,18 +319,21 @@ pub async fn get_channel_attachments_handler<S: ChannelMessagesService, A: Chann
),
responses(
(status = 200, body = Vec<ApiChannelParticipant>),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn get_channel_participants_handler<S: ChannelMessagesService, A: ChannelAccessCheck>(
- State(state): State<ChannelsRouterState<S, A>>,
- member: ChannelMember,
+pub async fn get_channel_participants_handler<
+ S: ChannelMessagesService,
+ Svc: EntityAccessService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
) -> Result<Json<Vec<ApiChannelParticipant>>, ChannelsHandlerErr> {
- let participants = state
- .service
- .get_channel_participants(member.channel_id)
- .await?;
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let participants = state.service.get_channel_participants(channel_id).await?;
Ok(Json(
participants
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index 4e3cafc928..4efcf2717c 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -3,41 +3,137 @@ use crate::domain::models::{
ChannelAttachment, ChannelMessage, ChannelParticipant, MessagePageDirection, ParticipantRole,
};
use crate::domain::ports::{
- ChannelAccessCheck, ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage,
- ChannelMessagesQueryResult, ChannelMessagesService,
+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult,
+ ChannelMessagesService,
};
use axum::{
Extension, Router,
http::{Request, StatusCode},
};
+use entity_access::domain::{
+ models::{
+ AccessError, AccessLevel, EntityAccessReceipt, EntityPermission, EntityType,
+ ParticipantRole as EntityParticipantRole, RequiredPermission,
+ },
+ ports::EntityAccessService,
+};
use http_body_util::BodyExt;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use model_user::UserContext;
use models_pagination::{Base64Str, CreatedAt, Cursor, CursorVal, PaginateOn, Query};
use tower::util::ServiceExt;
-// --- Access check implementations for tests ---
+// --- Access service implementations for tests ---
-struct AlwaysAllow;
+#[derive(Clone, Copy)]
+enum AccessMode {
+ Allow,
+ Deny,
+ NotFound,
+}
-impl ChannelAccessCheck for AlwaysAllow {
- async fn is_channel_member(
- &self,
- _channel_id: Uuid,
- _user_id: &str,
- ) -> Result<bool, anyhow::Error> {
- Ok(true)
+#[derive(Clone)]
+struct TestAccessService {
+ mode: AccessMode,
+}
+
+impl TestAccessService {
+ const fn allow() -> Self {
+ Self {
+ mode: AccessMode::Allow,
+ }
+ }
+
+ const fn deny() -> Self {
+ Self {
+ mode: AccessMode::Deny,
+ }
+ }
+
+ const fn not_found() -> Self {
+ Self {
+ mode: AccessMode::NotFound,
+ }
+ }
+
+ fn access_err(&self) -> AccessError {
+ match self.mode {
+ AccessMode::Allow => AccessError::Internal,
+ AccessMode::Deny => AccessError::Unauthorized,
+ AccessMode::NotFound => AccessError::NotFound("Channel not found"),
+ }
}
}
-struct AlwaysDeny;
+impl EntityAccessService for TestAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ Err(self.access_err())
+ }
-impl ChannelAccessCheck for AlwaysDeny {
- async fn is_channel_member(
+ async fn get_access_level(
&self,
- _channel_id: Uuid,
- _user_id: &str,
- ) -> Result<bool, anyhow::Error> {
- Ok(false)
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(match self.mode {
+ AccessMode::Allow => Some(AccessLevel::View),
+ AccessMode::Deny | AccessMode::NotFound => None,
+ })
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ match self.mode {
+ AccessMode::Allow => Ok(AccessLevel::View),
+ AccessMode::Deny => Err(AccessError::Unauthorized),
+ AccessMode::NotFound => Err(AccessError::NotFound("Channel not found")),
+ }
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ match self.mode {
+ AccessMode::Allow => Ok(AccessLevel::View),
+ AccessMode::Deny => Err(AccessError::Unauthorized),
+ AccessMode::NotFound => Err(AccessError::NotFound("Channel not found")),
+ }
+ }
+
+ async fn get_entity_permission(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ entity_type: EntityType,
+ _user_org_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ match self.mode {
+ AccessMode::Allow => match entity_type {
+ EntityType::Channel => Ok(EntityPermission::ChannelRole {
+ role: EntityParticipantRole::Member,
+ }),
+ _ => Ok(EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ }),
+ },
+ AccessMode::Deny => Err(AccessError::Unauthorized),
+ AccessMode::NotFound => Err(AccessError::NotFound("Channel not found")),
+ }
}
}
@@ -239,15 +335,35 @@ fn user_extension() -> Extension<UserContext> {
}
fn mock_router() -> Router {
- channels_router(ChannelsRouterState::new(MockService, AlwaysAllow)).layer(user_extension())
+ channels_router(ChannelsRouterState::new(
+ MockService,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension())
}
fn error_router() -> Router {
- channels_router(ChannelsRouterState::new(ErrorService, AlwaysAllow)).layer(user_extension())
+ channels_router(ChannelsRouterState::new(
+ ErrorService,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension())
}
fn denied_router() -> Router {
- channels_router(ChannelsRouterState::new(MockService, AlwaysDeny)).layer(user_extension())
+ channels_router(ChannelsRouterState::new(
+ MockService,
+ TestAccessService::deny(),
+ ))
+ .layer(user_extension())
+}
+
+fn not_found_router() -> Router {
+ channels_router(ChannelsRouterState::new(
+ MockService,
+ TestAccessService::not_found(),
+ ))
+ .layer(user_extension())
}
#[tokio::test]
@@ -390,8 +506,11 @@ async fn participants_returns_empty_list() {
#[tokio::test]
async fn participants_returns_data_with_correct_shape() {
- let router = channels_router(ChannelsRouterState::new(ParticipantsService, AlwaysAllow))
- .layer(user_extension());
+ let router = channels_router(ChannelsRouterState::new(
+ ParticipantsService,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
let channel_id = Uuid::new_v4();
let request = Request::builder()
.uri(format!("/{channel_id}/participants"))
@@ -589,8 +708,11 @@ async fn messages_around_returns_empty_page() {
#[tokio::test]
async fn messages_around_returns_previous_cursor_when_items_present() {
- let router = channels_router(ChannelsRouterState::new(AroundHasItemsService, AlwaysAllow))
- .layer(user_extension());
+ let router = channels_router(ChannelsRouterState::new(
+ AroundHasItemsService,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
let channel_id = Uuid::new_v4();
let message_id = Uuid::new_v4();
let request = Request::builder()
@@ -611,8 +733,11 @@ async fn messages_around_returns_previous_cursor_when_items_present() {
#[tokio::test]
async fn messages_around_returns_404_when_not_found() {
- let router = channels_router(ChannelsRouterState::new(NotFoundService, AlwaysAllow))
- .layer(user_extension());
+ let router = channels_router(ChannelsRouterState::new(
+ NotFoundService,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
let channel_id = Uuid::new_v4();
let message_id = Uuid::new_v4();
let request = Request::builder()
@@ -650,8 +775,11 @@ async fn thread_replies_returns_empty_list() {
#[tokio::test]
async fn thread_replies_returns_404_when_not_found() {
- let router = channels_router(ChannelsRouterState::new(NotFoundService, AlwaysAllow))
- .layer(user_extension());
+ let router = channels_router(ChannelsRouterState::new(
+ NotFoundService,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
let channel_id = Uuid::new_v4();
let message_id = Uuid::new_v4();
let request = Request::builder()
@@ -679,11 +807,14 @@ async fn non_member_cannot_access_messages() {
.unwrap();
let res = router.oneshot(request).await.unwrap();
- assert_eq!(res.status(), StatusCode::FORBIDDEN);
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
let bytes = res.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
- assert_eq!(json["message"], "Not a channel member");
+ assert_eq!(
+ json["message"],
+ "User does not have access to the requested resource"
+ );
}
#[tokio::test]
@@ -696,7 +827,7 @@ async fn non_member_cannot_access_attachments() {
.unwrap();
let res = router.oneshot(request).await.unwrap();
- assert_eq!(res.status(), StatusCode::FORBIDDEN);
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
@@ -709,7 +840,7 @@ async fn non_member_cannot_access_participants() {
.unwrap();
let res = router.oneshot(request).await.unwrap();
- assert_eq!(res.status(), StatusCode::FORBIDDEN);
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
@@ -723,5 +854,18 @@ async fn non_member_cannot_access_thread_replies() {
.unwrap();
let res = router.oneshot(request).await.unwrap();
- assert_eq!(res.status(), StatusCode::FORBIDDEN);
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn missing_channel_returns_404() {
+ let router = not_found_router();
+ let channel_id = Uuid::new_v4();
+ let request = Request::builder()
+ .uri(format!("/{channel_id}/messages"))
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let res = router.oneshot(request).await.unwrap();
+ assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
diff --git a/rust/cloud-storage/channels/src/outbound/mod.rs b/rust/cloud-storage/channels/src/outbound/mod.rs
index 0aaaa8fe2d..7e85e2b8a8 100644
--- a/rust/cloud-storage/channels/src/outbound/mod.rs
+++ b/rust/cloud-storage/channels/src/outbound/mod.rs
@@ -1,4 +1,2 @@
-/// Postgres-backed channel membership check.
-pub mod pg_access_check;
/// Postgres repository for channel messages.
pub mod pg_channels_repo;
diff --git a/rust/cloud-storage/channels/src/outbound/pg_access_check/mod.rs b/rust/cloud-storage/channels/src/outbound/pg_access_check/mod.rs
deleted file mode 100644
index 325d22654e..0000000000
--- a/rust/cloud-storage/channels/src/outbound/pg_access_check/mod.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-#[cfg(test)]
-mod test;
-
-use crate::domain::ports::ChannelAccessCheck;
-use sqlx::PgPool;
-use uuid::Uuid;
-
-/// Postgres-backed channel membership check.
-pub struct PgChannelAccessCheck {
- pool: PgPool,
-}
-
-impl PgChannelAccessCheck {
- /// Create a new access check with the given connection pool.
- pub fn new(pool: PgPool) -> Self {
- Self { pool }
- }
-}
-
-impl ChannelAccessCheck for PgChannelAccessCheck {
- #[tracing::instrument(err, skip(self))]
- async fn is_channel_member(
- &self,
- channel_id: Uuid,
- user_id: &str,
- ) -> Result<bool, anyhow::Error> {
- let row = sqlx::query(
- "SELECT 1 FROM comms_channel_participants \
- WHERE channel_id = $1 AND user_id = $2 AND left_at IS NULL \
- LIMIT 1",
- )
- .bind(channel_id)
- .bind(user_id)
- .fetch_optional(&self.pool)
- .await?;
-
- Ok(row.is_some())
- }
-}
diff --git a/rust/cloud-storage/channels/src/outbound/pg_access_check/test.rs b/rust/cloud-storage/channels/src/outbound/pg_access_check/test.rs
deleted file mode 100644
index 006d0c45d4..0000000000
--- a/rust/cloud-storage/channels/src/outbound/pg_access_check/test.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-use super::*;
-use macro_db_migrator::MACRO_DB_MIGRATIONS;
-use sqlx::{Pool, Postgres};
-
-const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);
-const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);
-
-fn access(pool: Pool<Postgres>) -> PgChannelAccessCheck {
- PgChannelAccessCheck::new(pool)
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("channels_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn active_member_is_allowed(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let check = access(pool);
- assert!(
- check
- .is_channel_member(CH1, "macro|[email protected]")
- .await?
- );
- assert!(
- check
- .is_channel_member(CH1, "macro|[email protected]")
- .await?
- );
- assert!(
- check
- .is_channel_member(CH1, "macro|[email protected]")
- .await?
- );
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("channels_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn left_user_is_denied(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let check = access(pool);
- assert!(
- !check
- .is_channel_member(CH1, "macro|[email protected]")
- .await?
- );
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("channels_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn non_participant_is_denied(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let check = access(pool);
- assert!(
- !check
- .is_channel_member(CH1, "macro|[email protected]")
- .await?
- );
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("channels_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn member_of_different_channel_is_denied(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let check = access(pool);
- // user-a is in CH1 but not in CH2
- assert!(
- !check
- .is_channel_member(CH2, "macro|[email protected]")
- .await?
- );
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("channels_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn nonexistent_channel_is_denied(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let check = access(pool);
- let fake_channel = Uuid::from_u128(0xdeadbeef);
- assert!(
- !check
- .is_channel_member(fake_channel, "macro|[email protected]")
- .await?
- );
- Ok(())
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index c152011c8d..70a78619ea 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -1,9 +1,8 @@
use crate::{config::Config, service::s3::S3};
use axum::extract::FromRef;
use channels::{
- domain::service::ChannelMessagesServiceImpl,
- inbound::axum_router::ChannelsRouterState,
- outbound::{pg_access_check::PgChannelAccessCheck, pg_channels_repo::PgChannelMessagesRepo},
+ domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,
+ outbound::pg_channels_repo::PgChannelMessagesRepo,
};
use comms::{
domain::service::ChannelServiceImpl,
@@ -137,7 +136,7 @@ pub(crate) type CommsState = CommsRouterState<CommsChannelService>;
/// Type alias for the channels router state.
pub(crate) type DssChannelsState =
- ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>, PgChannelAccessCheck>;
+ ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>, EntityAccessService>;
/// Type alias for the document service used by the github sync service.
pub(crate) type GithubDocumentService =
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 9c306f860f..8ecdf2584a 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -9,9 +9,8 @@ use crate::{
};
use anyhow::Context;
use channels::{
- domain::service::ChannelMessagesServiceImpl,
- inbound::axum_router::ChannelsRouterState,
- outbound::{pg_access_check::PgChannelAccessCheck, pg_channels_repo::PgChannelMessagesRepo},
+ domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,
+ outbound::pg_channels_repo::PgChannelMessagesRepo,
};
use comms::{
domain::service::ChannelServiceImpl,
@@ -375,12 +374,12 @@ async fn main() -> anyhow::Result<()> {
entity_access_service: entity_access_service.clone(),
documents_state: DocumentRouterState {
service: document_service,
- access_service: entity_access_service,
+ access_service: entity_access_service.clone(),
pool: db.clone(),
},
channels_state: ChannelsRouterState::new(
ChannelMessagesServiceImpl::new(PgChannelMessagesRepo::new(db.clone())),
- PgChannelAccessCheck::new(db.clone()),
+ (*entity_access_service).clone(),
),
};
diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rs
index f0152c57d9..2d1ded143c 100644
--- a/rust/cloud-storage/entity_access/src/domain/models.rs
+++ b/rust/cloud-storage/entity_access/src/domain/models.rs
@@ -11,39 +11,6 @@ pub use models_permissions::share_permission::access_level::{
CommentAccessLevel, EditAccessLevel, OwnerAccessLevel, ViewAccessLevel,
};
-/// Trait to convert a unit struct marker into an [`AccessLevel`].
-///
-/// This allows extractors and receipts to be parameterized by required access level.
-/// Implement this for marker types like `ViewAccessLevel`, `EditAccessLevel`, etc.
-pub trait RequiredAccessLevel: std::fmt::Debug + Send + Sync + 'static {
- /// Returns the access level this marker represents.
- fn required_level() -> AccessLevel;
-}
-
-impl RequiredAccessLevel for ViewAccessLevel {
- fn required_level() -> AccessLevel {
- AccessLevel::View
- }
-}
-
-impl RequiredAccessLevel for CommentAccessLevel {
- fn required_level() -> AccessLevel {
- AccessLevel::Comment
- }
-}
-
-impl RequiredAccessLevel for EditAccessLevel {
- fn required_level() -> AccessLevel {
- AccessLevel::Edit
- }
-}
-
-impl RequiredAccessLevel for OwnerAccessLevel {
- fn required_level() -> AccessLevel {
- AccessLevel::Owner
- }
-}
-
/// The role a user has within a channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
@@ -58,6 +25,24 @@ pub enum ParticipantRole {
Member,
}
+/// Channel owner role with full control
+#[derive(Debug)]
+pub struct OwnerParticipantRole;
+
+/// Channel Administrator
+#[derive(Debug)]
+pub struct AdminParticipantRole;
+
+/// Regular channel member.
+#[derive(Debug)]
+pub struct MemberParticipantRole;
+
+/// Trait implemented by marker types that encode a permission requirement.
+pub trait RequiredPermission: std::fmt::Debug + Send + Sync + 'static {
+ /// Returns whether the provided permission satisfies this requirement.
+ fn is_satisfied_by(permission: &EntityPermission) -> bool;
+}
+
/// A user's permission for an entity, discriminated by entity kind.
///
/// Items (documents, chats, projects, threads) use access levels.
@@ -78,6 +63,86 @@ pub enum EntityPermission {
},
}
+impl EntityPermission {
+ /// Returns whether this permission grants at least the requested access level.
+ pub fn allows_access_level(&self, required: AccessLevel) -> bool {
+ matches!(
+ self,
+ EntityPermission::AccessLevel { access_level } if *access_level >= required
+ )
+ }
+
+ /// Returns whether this permission grants at least the requested channel role.
+ pub fn allows_participant_role(&self, required: ParticipantRole) -> bool {
+ matches!(
+ (self, required),
+ (
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner,
+ },
+ ParticipantRole::Owner,
+ ) | (
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner | ParticipantRole::Admin,
+ },
+ ParticipantRole::Admin,
+ ) | (
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner | ParticipantRole::Admin | ParticipantRole::Member,
+ },
+ ParticipantRole::Member
+ )
+ )
+ }
+
+ /// Returns whether this permission satisfies the provided marker type.
+ pub fn satisfies<T: RequiredPermission>(&self) -> bool {
+ T::is_satisfied_by(self)
+ }
+}
+
+impl RequiredPermission for ViewAccessLevel {
+ fn is_satisfied_by(permission: &EntityPermission) -> bool {
+ permission.allows_access_level(AccessLevel::View)
+ }
+}
+
+impl RequiredPermission for CommentAccessLevel {
+ fn is_satisfied_by(permission: &EntityPermission) -> bool {
+ permission.allows_access_level(AccessLevel::Comment)
+ }
+}
+
+impl RequiredPermission for EditAccessLevel {
+ fn is_satisfied_by(permission: &EntityPermission) -> bool {
+ permission.allows_access_level(AccessLevel::Edit)
+ }
+}
+
+impl RequiredPermission for OwnerAccessLevel {
+ fn is_satisfied_by(permission: &EntityPermission) -> bool {
+ permission.allows_access_level(AccessLevel::Owner)
+ }
+}
+
+impl RequiredPermission for OwnerParticipantRole {
+ fn is_satisfied_by(permission: &EntityPermission) -> bool {
+ permission.allows_participant_role(ParticipantRole::Owner)
+ }
+}
+
+impl RequiredPermission for AdminParticipantRole {
+ fn is_satisfied_by(permission: &EntityPermission) -> bool {
+ permission.allows_participant_role(ParticipantRole::Admin)
+ }
+}
+
+impl RequiredPermission for MemberParticipantRole {
+ fn is_satisfied_by(permission: &EntityPermission) -> bool {
+ permission.allows_participant_role(ParticipantRole::Member)
+ }
+}
+
/// Result of resolving a user's role in a channel.
///
/// Distinguishes between "user has a role", "channel exists but user
@@ -114,10 +179,10 @@ pub enum EntityAccessAuth {
/// Represents that a given user has a given permission for the provided id.
///
-/// The type parameter `T` encodes the minimum access level that was verified
+/// The type parameter `T` encodes the minimum permission that was verified
/// when this receipt was created.
#[derive(Debug)]
-pub struct EntityAccessReceipt<T: RequiredAccessLevel> {
+pub struct EntityAccessReceipt<T: RequiredPermission> {
/// The entity access authentication method
pub(crate) auth: EntityAccessAuth,
/// The entity that was requested access
@@ -128,7 +193,7 @@ pub struct EntityAccessReceipt<T: RequiredAccessLevel> {
pub(crate) _marker: PhantomData<T>,
}
-impl<T: RequiredAccessLevel> EntityAccessReceipt<T> {
+impl<T: RequiredPermission> EntityAccessReceipt<T> {
/// Getter for auth
pub fn auth(&self) -> &EntityAccessAuth {
&self.auth
diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rs
index 2ad491ca98..5c58be045c 100644
--- a/rust/cloud-storage/entity_access/src/domain/ports.rs
+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs
@@ -5,7 +5,7 @@
use super::models::EntityType;
use crate::domain::models::{
AccessError, AccessLevel, ChannelRoleResult, EntityAccessReceipt, EntityPermission,
- RequiredAccessLevel,
+ RequiredPermission,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use std::future::Future;
@@ -85,9 +85,9 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
pub trait EntityAccessService: Clone + Send + Sync + 'static {
/// Generates an [`EntityAccessReceipt<T>`] for a given entity and user.
///
- /// The type parameter `T` specifies the minimum access level required.
- /// Returns an error if the user does not have at least that level.
- fn generate_entity_access_receipt<T: RequiredAccessLevel>(
+ /// The type parameter `T` specifies the minimum permission required.
+ /// Returns an error if the user does not satisfy that requirement.
+ fn generate_entity_access_receipt<T: RequiredPermission>(
&self,
user_id: &MacroUserId<Lowercase<'_>>,
user_org_id: Option<i64>,
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
index 5f14e48a06..4125a17dc7 100644
--- a/rust/cloud-storage/entity_access/src/domain/service.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -6,7 +6,7 @@ use std::str::FromStr;
use crate::domain::{
models::{
AccessError, AccessLevel, ChannelRoleResult, Entity, EntityAccessAuth, EntityAccessReceipt,
- EntityPermission, EntityType, RequiredAccessLevel,
+ EntityPermission, EntityType, RequiredPermission,
},
ports::{AccessRepository, EntityAccessService},
};
@@ -79,7 +79,7 @@ where
R: AccessRepository,
{
#[tracing::instrument(err, skip(self))]
- async fn generate_entity_access_receipt<T: RequiredAccessLevel>(
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
&self,
user_id: &MacroUserId<Lowercase<'_>>,
user_org_id: Option<i64>,
@@ -90,10 +90,7 @@ where
.get_entity_permission(Some(user_id), entity_id, entity_type, user_org_id)
.await?;
- // Verify the user meets the minimum required access level
- if let EntityPermission::AccessLevel { access_level } = &entity_permission
- && *access_level < T::required_level()
- {
+ if !entity_permission.satisfies::<T>() {
return Err(AccessError::Unauthorized);
}
diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rs
index 4cb67f6a26..158f51ef27 100644
--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs
@@ -2,7 +2,8 @@
use super::*;
use crate::domain::models::{
- CommentAccessLevel, EditAccessLevel, EntityAccessAuth, ParticipantRole, ViewAccessLevel,
+ AdminParticipantRole, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,
+ MemberParticipantRole, OwnerParticipantRole, ParticipantRole, ViewAccessLevel,
};
use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::access_level::OwnerAccessLevel;
@@ -708,7 +709,7 @@ async fn test_generate_receipt_channel_with_role() {
let user_id = test_user_id();
let receipt = service
- .generate_entity_access_receipt::<ViewAccessLevel>(
+ .generate_entity_access_receipt::<MemberParticipantRole>(
&user_id,
None,
"11111111-1111-1111-1111-111111111111",
@@ -730,6 +731,66 @@ async fn test_generate_receipt_channel_with_role() {
));
}
+#[tokio::test]
+async fn test_generate_receipt_channel_member_fails_edit_requirement() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Member));
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .generate_entity_access_receipt::<AdminParticipantRole>(
+ &user_id,
+ None,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_generate_receipt_channel_admin_satisfies_edit_requirement() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let receipt = service
+ .generate_entity_access_receipt::<AdminParticipantRole>(
+ &user_id,
+ None,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Admin
+ }
+ ));
+}
+
+#[tokio::test]
+async fn test_generate_receipt_channel_admin_fails_owner_requirement() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .generate_entity_access_receipt::<OwnerParticipantRole>(
+ &user_id,
+ None,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
#[tokio::test]
async fn test_generate_receipt_channel_not_found_returns_not_found() {
let repo = MockRepo::new().with_channel_role(ChannelRoleResult::NotFound);
@@ -737,7 +798,7 @@ async fn test_generate_receipt_channel_not_found_returns_not_found() {
let user_id = test_user_id();
let result = service
- .generate_entity_access_receipt::<ViewAccessLevel>(
+ .generate_entity_access_receipt::<MemberParticipantRole>(
&user_id,
None,
"11111111-1111-1111-1111-111111111111",
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/channel.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/channel.rs
new file mode 100644
index 0000000000..b95a8b208f
--- /dev/null
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/channel.rs
@@ -0,0 +1,125 @@
+//! Channel access extractor.
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ Extension, RequestPartsExt, async_trait,
+ extract::{FromRef, FromRequestParts, Path},
+ http::request::Parts,
+};
+
+use super::{ExtractorError, InternalUser};
+use crate::domain::{
+ models::{
+ Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
+ ParticipantRole, RequiredPermission,
+ },
+ ports::EntityAccessService,
+};
+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)>,
+}
+
+#[async_trait]
+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.0),
+ entity_permission: permission,
+ _marker: PhantomData,
+ },
+ _marker: PhantomData,
+ })
+ }
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs
index e19a96de9b..b5b28a5a65 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs
@@ -9,7 +9,7 @@ use axum::{
http::request::Parts,
};
-use super::{ExtractorError, InternalUser, RequiredAccessLevel};
+use super::{ExtractorError, InternalUser, RequiredPermission};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -28,7 +28,7 @@ use model_user::axum_extractor::OptionalMacroUserExtractor;
///
/// - Chat context must be loaded (ChatBasic in extensions)
#[derive(Debug)]
-pub struct ChatAccessLevelExtractor<T: RequiredAccessLevel, Svc> {
+pub struct ChatAccessLevelExtractor<T: RequiredPermission, Svc> {
/// The entity access receipt
pub entity_access_receipt: EntityAccessReceipt<T>,
_marker: PhantomData<(T, Svc)>,
@@ -37,7 +37,7 @@ pub struct ChatAccessLevelExtractor<T: RequiredAccessLevel, Svc> {
#[async_trait]
impl<T, S, Svc> FromRequestParts<S> for ChatAccessLevelExtractor<T, Svc>
where
- T: RequiredAccessLevel,
+ T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
S: Send + Sync + 'static,
@@ -111,22 +111,18 @@ where
));
}
- let required_level = T::required_level();
- // Check access based on auth state
- let access_level: AccessLevel = match macro_user_id.as_ref() {
- Some(macro_user_id) => service
- .check_access(
- Some(macro_user_id),
- &chat_context.id,
- EntityType::Chat,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?,
- None => service
- .check_public_access(&chat_context.id, EntityType::Chat, required_level)
- .await
- .map_err(ExtractorError::from)?,
+ let access_level = match service
+ .get_access_level(macro_user_id.as_deref(), &chat_context.id, EntityType::Chat)
+ .await
+ .map_err(ExtractorError::from)?
+ {
+ Some(access_level) => access_level,
+ None => return Err(ExtractorError::Unauthorized),
+ };
+
+ let permission = EntityPermission::AccessLevel { access_level };
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
};
Ok(Self {
@@ -138,7 +134,7 @@ where
auth: macro_user_id
.map(|m| EntityAccessAuth::Authenticated(m.0))
.unwrap_or(EntityAccessAuth::Unauthenticated),
- entity_permission: EntityPermission::AccessLevel { access_level },
+ entity_permission: permission,
_marker: PhantomData,
},
_marker: PhantomData,
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs
index 74b7fe1d2f..78d4d3c5a4 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs
@@ -9,7 +9,7 @@ use axum::{
http::request::Parts,
};
-use super::{ExtractorError, RequiredAccessLevel};
+use super::{ExtractorError, RequiredPermission};
use crate::{
domain::{
models::{
@@ -33,7 +33,7 @@ use model_user::axum_extractor::OptionalMacroUserExtractor;
/// - User must be authenticated (MacroUserExtractor in extensions)
/// - Document context must be loaded (DocumentBasic in extensions)
#[derive(Debug)]
-pub struct DocumentAccessExtractor<T: RequiredAccessLevel, Svc> {
+pub struct DocumentAccessExtractor<T: RequiredPermission, Svc> {
/// The entity access receipt
pub entity_access_receipt: EntityAccessReceipt<T>,
_marker: PhantomData<(T, Svc)>,
@@ -42,7 +42,7 @@ pub struct DocumentAccessExtractor<T: RequiredAccessLevel, Svc> {
#[async_trait]
impl<T, S, Svc> FromRequestParts<S> for DocumentAccessExtractor<T, Svc>
where
- T: RequiredAccessLevel,
+ T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
S: Send + Sync + 'static,
@@ -116,29 +116,22 @@ where
));
}
- let required_level = T::required_level();
- // Check access based on auth state
- let access_level: AccessLevel = match macro_user_id.as_ref() {
- Some(macro_user_id) => service
- .check_access(
- Some(macro_user_id),
- &document_context.document_id,
- EntityType::Document,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?,
- None => {
- // Unauthenticated user: check public access only
- service
- .check_public_access(
- &document_context.document_id,
- EntityType::Document,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?
- }
+ let access_level = match service
+ .get_access_level(
+ macro_user_id.as_deref(),
+ &document_context.document_id,
+ EntityType::Document,
+ )
+ .await
+ .map_err(ExtractorError::from)?
+ {
+ Some(access_level) => access_level,
+ None => return Err(ExtractorError::Unauthorized),
+ };
+
+ let permission = EntityPermission::AccessLevel { access_level };
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
};
Ok(Self {
@@ -150,7 +143,7 @@ where
auth: macro_user_id
.map(|m| EntityAccessAuth::Authenticated(m.0))
.unwrap_or(EntityAccessAuth::Unauthenticated),
- entity_permission: EntityPermission::AccessLevel { access_level },
+ entity_permission: permission,
_marker: PhantomData,
},
_marker: PhantomData,
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs
index 2eb65ddaf3..ac811002b9 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs
@@ -9,7 +9,7 @@ use axum::{
http::request::Parts,
};
-use super::{ExtractorError, InternalUser, RequiredAccessLevel};
+use super::{ExtractorError, InternalUser, RequiredPermission};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -31,7 +31,7 @@ pub struct HistoryParams {
///
/// Extracts both item_id and item_type from the path parameters.
#[derive(Debug)]
-pub struct HistoryAccessExtractor<T: RequiredAccessLevel, Svc> {
+pub struct HistoryAccessExtractor<T: RequiredPermission, Svc> {
/// The entity access receipt
pub entity_access_receipt: EntityAccessReceipt<T>,
_marker: PhantomData<(T, Svc)>,
@@ -40,7 +40,7 @@ pub struct HistoryAccessExtractor<T: RequiredAccessLevel, Svc> {
#[async_trait]
impl<T, S, Svc> FromRequestParts<S> for HistoryAccessExtractor<T, Svc>
where
- T: RequiredAccessLevel,
+ T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
S: Send + Sync + 'static,
@@ -92,17 +92,18 @@ where
});
}
- let required_level = T::required_level();
- // Check access based on auth state
- let access_level: AccessLevel = match macro_user_id.as_ref() {
- Some(macro_user_id) => service
- .check_access(Some(macro_user_id), &item_id, entity_type, required_level)
- .await
- .map_err(ExtractorError::from)?,
- None => service
- .check_public_access(&item_id, entity_type, required_level)
- .await
- .map_err(ExtractorError::from)?,
+ let access_level = match service
+ .get_access_level(macro_user_id.as_deref(), &item_id, entity_type)
+ .await
+ .map_err(ExtractorError::from)?
+ {
+ Some(access_level) => access_level,
+ None => return Err(ExtractorError::Unauthorized),
+ };
+
+ let permission = EntityPermission::AccessLevel { access_level };
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
};
Ok(Self {
@@ -114,7 +115,7 @@ where
auth: macro_user_id
.map(|m| EntityAccessAuth::Authenticated(m.0))
.unwrap_or(EntityAccessAuth::Unauthenticated),
- entity_permission: EntityPermission::AccessLevel { access_level },
+ entity_permission: permission,
_marker: PhantomData,
},
_marker: PhantomData,
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
index 60f2177261..3fd74ba91c 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
@@ -3,6 +3,7 @@
//! These extractors validate that the requesting user has sufficient
//! access to the entity being accessed.
+mod channel;
mod chat;
mod document;
mod entity_permission;
@@ -10,6 +11,7 @@ mod history;
mod project;
mod thread;
+pub use channel::ChannelAccessLevelExtractor;
pub use chat::ChatAccessLevelExtractor;
pub use document::DocumentAccessExtractor;
pub use entity_permission::EntityPermissionExtractor;
@@ -22,7 +24,7 @@ use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use model_error_response::ErrorResponse;
-pub use crate::domain::models::RequiredAccessLevel;
+pub use crate::domain::models::RequiredPermission;
/// Marker struct for internal service-to-service requests.
///
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs
index 582332adc5..83574a48ea 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs
@@ -10,7 +10,7 @@ use axum::{
};
use serde::de::DeserializeOwned;
-use super::{ExtractorError, InternalUser, RequiredAccessLevel};
+use super::{ExtractorError, InternalUser, RequiredPermission};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -29,7 +29,7 @@ use model_user::axum_extractor::OptionalMacroUserExtractor;
///
/// - Project context must be loaded (BasicProject in extensions)
#[derive(Debug)]
-pub struct ProjectAccessLevelExtractor<T: RequiredAccessLevel, Svc> {
+pub struct ProjectAccessLevelExtractor<T: RequiredPermission, Svc> {
/// The entity access receipt
pub entity_access_receipt: EntityAccessReceipt<T>,
_marker: PhantomData<(T, Svc)>,
@@ -38,7 +38,7 @@ pub struct ProjectAccessLevelExtractor<T: RequiredAccessLevel, Svc> {
#[async_trait]
impl<T, S, Svc> FromRequestParts<S> for ProjectAccessLevelExtractor<T, Svc>
where
- T: RequiredAccessLevel,
+ T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
S: Send + Sync + 'static,
@@ -112,22 +112,22 @@ where
));
}
- let required_level = T::required_level();
- // Check access based on auth state
- let access_level: AccessLevel = match macro_user_id.as_ref() {
- Some(macro_user_id) => service
- .check_access(
- Some(macro_user_id),
- &project_context.id,
- EntityType::Project,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?,
- None => service
- .check_public_access(&project_context.id, EntityType::Project, required_level)
- .await
- .map_err(ExtractorError::from)?,
+ let access_level = match service
+ .get_access_level(
+ macro_user_id.as_deref(),
+ &project_context.id,
+ EntityType::Project,
+ )
+ .await
+ .map_err(ExtractorError::from)?
+ {
+ Some(access_level) => access_level,
+ None => return Err(ExtractorError::Unauthorized),
+ };
+
+ let permission = EntityPermission::AccessLevel { access_level };
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
};
Ok(Self {
@@ -139,7 +139,7 @@ where
auth: macro_user_id
.map(|m| EntityAccessAuth::Authenticated(m.0))
.unwrap_or(EntityAccessAuth::Unauthenticated),
- entity_permission: EntityPermission::AccessLevel { access_level },
+ entity_permission: permission,
_marker: PhantomData,
},
_marker: PhantomData,
@@ -197,7 +197,7 @@ impl ProjectOrParentId {
///
/// Downstream consumers also use the body (which is an antipattern) so we need to keep the value around.
#[derive(Debug)]
-pub enum ProjectBodyAccessLevelExtractor<T: RequiredAccessLevel, V, Svc> {
+pub enum ProjectBodyAccessLevelExtractor<T: RequiredPermission, V, Svc> {
/// A project was found in the body and access was validated.
FoundProject {
/// The project ID that was found.
@@ -218,7 +218,7 @@ pub enum ProjectBodyAccessLevelExtractor<T: RequiredAccessLevel, V, Svc> {
},
}
-impl<T: RequiredAccessLevel, V, Svc> ProjectBodyAccessLevelExtractor<T, V, Svc> {
+impl<T: RequiredPermission, V, Svc> ProjectBodyAccessLevelExtractor<T, V, Svc> {
/// Extract the body from this extractor.
pub fn into_inner(self) -> V {
match self {
@@ -231,7 +231,7 @@ impl<T: RequiredAccessLevel, V, Svc> ProjectBodyAccessLevelExtractor<T, V, Svc>
#[async_trait]
impl<T, S, V, Svc> FromRequest<S> for ProjectBodyAccessLevelExtractor<T, V, Svc>
where
- T: RequiredAccessLevel,
+ T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
S: Send + Sync + 'static,
@@ -292,22 +292,18 @@ where
});
}
- let required_level = T::required_level();
- // Check access based on auth state
- let access_level: AccessLevel = match macro_user_id.as_ref() {
- Some(macro_user_id) => service
- .check_access(
- Some(macro_user_id),
- project.id(),
- EntityType::Project,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?,
- None => service
- .check_public_access(project.id(), EntityType::Project, required_level)
- .await
- .map_err(ExtractorError::from)?,
+ let access_level = match service
+ .get_access_level(macro_user_id.as_deref(), project.id(), EntityType::Project)
+ .await
+ .map_err(ExtractorError::from)?
+ {
+ Some(access_level) => access_level,
+ None => return Err(ExtractorError::Unauthorized),
+ };
+
+ let permission = EntityPermission::AccessLevel { access_level };
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
};
Ok(Self::FoundProject {
@@ -319,7 +315,7 @@ where
auth: macro_user_id
.map(|m| EntityAccessAuth::Authenticated(m.0))
.unwrap_or(EntityAccessAuth::Unauthenticated),
- entity_permission: EntityPermission::AccessLevel { access_level },
+ entity_permission: permission,
_marker: PhantomData,
},
project,
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
index ba3984d5ca..4d1e1ab818 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
@@ -10,7 +10,7 @@ use axum::{
http::request::Parts,
};
-use super::{ExtractorError, InternalUser, RequiredAccessLevel};
+use super::{ExtractorError, InternalUser, RequiredPermission};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -26,7 +26,7 @@ use model_user::axum_extractor::OptionalMacroUserExtractor;
///
/// Extracts the thread ID from the `thread_id` path parameter.
#[derive(Debug)]
-pub struct ThreadAccessLevelExtractor<T: RequiredAccessLevel, Svc> {
+pub struct ThreadAccessLevelExtractor<T: RequiredPermission, Svc> {
/// The entity access receipt
pub entity_access_receipt: EntityAccessReceipt<T>,
_marker: PhantomData<(T, Svc)>,
@@ -35,7 +35,7 @@ pub struct ThreadAccessLevelExtractor<T: RequiredAccessLevel, Svc> {
#[async_trait]
impl<T, S, Svc> FromRequestParts<S> for ThreadAccessLevelExtractor<T, Svc>
where
- T: RequiredAccessLevel,
+ T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
S: Send + Sync + 'static,
@@ -89,22 +89,22 @@ where
});
}
- let required_level = T::required_level();
- // Check access based on auth state
- let access_level: AccessLevel = match macro_user_id.as_ref() {
- Some(macro_user_id) => service
- .check_access(
- Some(macro_user_id),
- &thread_id,
- EntityType::EmailThread,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?,
- None => service
- .check_public_access(&thread_id, EntityType::EmailThread, required_level)
- .await
- .map_err(ExtractorError::from)?,
+ let access_level = match service
+ .get_access_level(
+ macro_user_id.as_deref(),
+ &thread_id,
+ EntityType::EmailThread,
+ )
+ .await
+ .map_err(ExtractorError::from)?
+ {
+ Some(access_level) => access_level,
+ None => return Err(ExtractorError::Unauthorized),
+ };
+
+ let permission = EntityPermission::AccessLevel { access_level };
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
};
Ok(Self {
@@ -116,7 +116,7 @@ where
auth: macro_user_id
.map(|m| EntityAccessAuth::Authenticated(m.0))
.unwrap_or(EntityAccessAuth::Unauthenticated),
- entity_permission: EntityPermission::AccessLevel { access_level },
+ entity_permission: permission,
_marker: PhantomData,
},
_marker: PhantomData,