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(favorites): macro authorization (#4973)

Will Hutchinsonac4f48a5c29d
diff --git a/Cargo.lock b/Cargo.lock
index 3e27171a02..8ac6a2ba0a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5353,12 +5353,12 @@ dependencies = [
"chrono",
"cowlike",
"entity_access",
+ "macro_authorization",
"macro_db_migrator",
"macro_user_id",
"mockall",
"model-entity",
"model-error-response",
- "model_user",
"serde",
"serde_json",
"sqlx",
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_body.rs b/crates/entity_access/src/inbound/axum_extractors/entity_body.rs
new file mode 100644
index 0000000000..956148b0a4
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_body.rs
@@ -0,0 +1,100 @@
+//! Entity access extractor for entities identified in a JSON request body.
+
+#[cfg(test)]
+mod test;
+
+use std::{marker::PhantomData, sync::Arc};
+
+use axum::{
+ Json, RequestExt,
+ extract::{FromRef, FromRequest, Request},
+};
+use macro_authorization::{
+ MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+};
+use serde::{Deserialize, de::DeserializeOwned};
+
+use super::{ExtractorError, RequiredPermission};
+use crate::domain::{
+ models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType},
+ ports::EntityAccessService,
+};
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct EntityBodyFields {
+ entity_type: EntityType,
+ entity_id: String,
+}
+
+/// Validates that an authenticated user has access to an entity identified in the request body.
+///
+/// Type parameter `T` specifies the required access level, `Svc` is the entity access service,
+/// `V` is the typed request body, and `Auth` is the authorization service. This extractor consumes
+/// the request body and must therefore be the final body-consuming extractor in a handler.
+#[derive(Debug)]
+pub struct EntityBodyAccessLevelExtractor<T: RequiredPermission, Svc, V, Auth> {
+ /// The receipt proving access to the entity from the request body.
+ pub entity_access_receipt: EntityAccessReceipt<T>,
+ /// The deserialized request body.
+ pub inner: V,
+ _marker: PhantomData<(T, Svc, Auth)>,
+}
+
+impl<T, S, Svc, V, Auth> FromRequest<S> for EntityBodyAccessLevelExtractor<T, Svc, V, Auth>
+where
+ T: RequiredPermission,
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
+ V: DeserializeOwned,
+ S: Send + Sync + 'static,
+{
+ type Rejection = ExtractorError;
+
+ #[tracing::instrument(err, skip(req, state))]
+ async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> {
+ let OptionalMacroAuthorizationExtractor { macro_user_id, .. } = req
+ .extract_parts_with_state::<OptionalMacroAuthorizationExtractor<Auth>, _>(state)
+ .await
+ .map_err(ExtractorError::from)?;
+ let user = macro_user_id.ok_or(ExtractorError::Unauthorized)?;
+
+ let Json(json): Json<serde_json::Value> = req
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::BadRequest("Invalid JSON body"))?;
+ let EntityBodyFields {
+ entity_type,
+ entity_id,
+ } = serde_json::from_value(json.clone())
+ .map_err(|_| ExtractorError::BadRequest("Invalid entity body"))?;
+
+ let service = Arc::<Svc>::from_ref(state);
+ let access_level = service
+ .get_access_level(Some(&user), &entity_id, entity_type)
+ .await
+ .map_err(ExtractorError::from)?
+ .ok_or(ExtractorError::Unauthorized)?;
+ let entity_permission = EntityPermission::AccessLevel { access_level };
+ if !entity_permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ auth: EntityAccessAuth::Authenticated(user),
+ entity: Entity {
+ entity_id,
+ entity_type,
+ },
+ entity_permission,
+ _marker: PhantomData,
+ },
+ inner: serde_json::from_value(json)
+ .map_err(|_| ExtractorError::BadRequest("Invalid request body"))?,
+ _marker: PhantomData,
+ })
+ }
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs b/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
new file mode 100644
index 0000000000..aa8ffefd70
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
@@ -0,0 +1,329 @@
+use axum::{
+ Router,
+ body::{Body, to_bytes},
+ http::{Request, StatusCode, header, request::Builder},
+ routing::post,
+};
+use macro_authorization::{INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER};
+use serde::Deserialize;
+use tower::ServiceExt;
+
+use super::*;
+use crate::{
+ domain::models::{AccessLevel, EditAccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel},
+ inbound::axum_extractors::test_support::{
+ AccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY, TestState,
+ USER_ID,
+ },
+};
+
+const ENTITY_ID: &str = "entity-1";
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TestBody {
+ entity_type: EntityType,
+ entity_id: String,
+ position: u32,
+}
+
+type ViewExtractor = EntityBodyAccessLevelExtractor<
+ ViewAccessLevel,
+ FakeEntityAccessService,
+ TestBody,
+ FakeAuthorizationService,
+>;
+type EditExtractor = EntityBodyAccessLevelExtractor<
+ EditAccessLevel,
+ FakeEntityAccessService,
+ TestBody,
+ FakeAuthorizationService,
+>;
+
+async fn view_handler(access: ViewExtractor) -> String {
+ let auth = match access.entity_access_receipt.auth() {
+ EntityAccessAuth::Authenticated(_) => "authenticated",
+ EntityAccessAuth::Bot(_) => "bot",
+ EntityAccessAuth::Unauthenticated => "unauthenticated",
+ EntityAccessAuth::Internal => "internal",
+ };
+ let entity = access.entity_access_receipt.entity();
+
+ format!(
+ "{auth}:{}:{}:{}:{}:{}",
+ entity.entity_type,
+ entity.entity_id,
+ access.inner.entity_type,
+ access.inner.entity_id,
+ access.inner.position
+ )
+}
+
+async fn edit_handler(_access: EditExtractor) {}
+
+fn router(state: TestState) -> Router {
+ Router::new()
+ .route("/view", post(view_handler))
+ .route("/edit", post(edit_handler))
+ .with_state(state)
+}
+
+fn request(path: &str) -> Builder {
+ Request::post(path).header(header::CONTENT_TYPE, "application/json")
+}
+
+fn body(entity_type: &str, entity_id: &str) -> Body {
+ Body::from(format!(
+ r#"{{"entityType":"{entity_type}","entityId":"{entity_id}","position":7}}"#
+ ))
+}
+
+async fn response_body(response: axum::response::Response) -> String {
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ String::from_utf8(body.to_vec()).expect("response body should be UTF-8")
+}
+
+#[tokio::test]
+async fn authenticated_access_uses_body_entity_and_preserves_typed_body() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(body("document", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ response_body(response).await,
+ "authenticated:document:entity-1:document:entity-1:7"
+ );
+ assert_eq!(
+ state.entity_access.calls(),
+ [AccessCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn acting_user_internal_access_uses_the_acting_users_acl() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
+ .header(INTERNAL_MACRO_USER_ID_HEADER, USER_ID)
+ .body(body("document", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ response_body(response).await,
+ "authenticated:document:entity-1:document:entity-1:7"
+ );
+ assert_eq!(
+ state.entity_access.calls(),
+ [AccessCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn missing_identity_is_rejected_before_body_and_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(request("/view").body(Body::from("{")).unwrap())
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn identity_less_internal_access_is_rejected_before_body_and_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn absent_access_is_rejected() {
+ let state = TestState::new(None);
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(body("document", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.calls().len(), 1);
+}
+
+#[tokio::test]
+async fn view_access_does_not_satisfy_edit_access() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/edit")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(body("document", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.calls().len(), 1);
+}
+
+#[tokio::test]
+async fn missing_and_malformed_json_are_rejected_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+
+ for invalid_body in [Body::empty(), Body::from("{")] {
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(invalid_body)
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ }
+
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn missing_entity_fields_are_rejected_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+
+ for invalid_body in [
+ Body::from(r#"{"entityId":"entity-1","position":7}"#),
+ Body::from(r#"{"entityType":"document","position":7}"#),
+ ] {
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(invalid_body)
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ }
+
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn unknown_entity_types_are_rejected_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(body("thread", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn typed_body_failure_is_rejected_after_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(Body::from(
+ r#"{"entityType":"document","entityId":"entity-1","position":"first"}"#,
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ state.entity_access.calls(),
+ [AccessCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn channels_and_static_files_keep_get_access_level_semantics() {
+ let state = TestState::new(Some(AccessLevel::View));
+
+ for (entity_type, entity_id) in [("channel", "channel-1"), ("static_file", "static-1")] {
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(body(entity_type, entity_id))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ }
+
+ assert_eq!(
+ state.entity_access.calls(),
+ [
+ AccessCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: "channel-1".to_string(),
+ entity_type: EntityType::Channel,
+ },
+ AccessCall {
+ user_id: Some(USER_ID.to_string()),
+ entity_id: "static-1".to_string(),
+ entity_type: EntityType::StaticFile,
+ },
+ ]
+ );
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/mod.rs b/crates/entity_access/src/inbound/axum_extractors/mod.rs
index 648511b33e..e0adc08878 100644
--- a/crates/entity_access/src/inbound/axum_extractors/mod.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/mod.rs
@@ -12,6 +12,7 @@ mod call;
mod channel;
mod chat;
mod document;
+mod entity_body;
mod entity_permission;
mod foreign_entity;
mod history;
@@ -24,6 +25,7 @@ pub use call::{CallAccessLevelExtractor, CallWithChannelIdAccessLevelExtractor};
pub use channel::ChannelAccessLevelExtractor;
pub use chat::ChatAccessLevelExtractor;
pub use document::DocumentAccessExtractor;
+pub use entity_body::EntityBodyAccessLevelExtractor;
pub use entity_permission::EntityPermissionExtractor;
pub use foreign_entity::ForeignEntityAccessLevelExtractor;
pub use history::HistoryAccessExtractor;
diff --git a/crates/favorites/Cargo.toml b/crates/favorites/Cargo.toml
index 0a60ede7de..787b6c443f 100644
--- a/crates/favorites/Cargo.toml
+++ b/crates/favorites/Cargo.toml
@@ -8,8 +8,8 @@ version = "0.1.0"
default = []
inbound = [
"dep:axum",
+ "dep:macro_authorization",
"dep:model-error-response",
- "dep:model_user",
"dep:utoipa",
"entity_access/inbound",
"ports",
@@ -25,11 +25,11 @@ axum = { workspace = true, optional = true }
chrono = { workspace = true, features = ["serde"] }
cowlike = { path = "../cowlike" }
entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }
macro_user_id = { path = "../macro_user_id" }
mockall = { workspace = true, optional = true }
model-entity = { path = "../model-entity" }
model-error-response = { path = "../model-error-response", optional = true }
-model_user = { path = "../model_user", optional = true, features = ["axum"] }
serde = { workspace = true }
sqlx = { workspace = true, optional = true }
thiserror = { workspace = true }
diff --git a/crates/favorites/src/domain/models.rs b/crates/favorites/src/domain/models.rs
index c4c7411f3a..7df060eda3 100644
--- a/crates/favorites/src/domain/models.rs
+++ b/crates/favorites/src/domain/models.rs
@@ -65,6 +65,9 @@ pub enum FavoritesError {
/// The request was invalid.
#[error("{0}")]
BadRequest(String),
+ /// The receipt does not belong to an authenticated user.
+ #[error("you do not have access to this entity")]
+ Unauthorized,
/// Any other internal error.
#[error(transparent)]
Internal(#[from] anyhow::Error),
diff --git a/crates/favorites/src/domain/ports.rs b/crates/favorites/src/domain/ports.rs
index 6eb92cacc3..967e59619c 100644
--- a/crates/favorites/src/domain/ports.rs
+++ b/crates/favorites/src/domain/ports.rs
@@ -2,6 +2,7 @@
use std::collections::HashSet;
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
@@ -66,8 +67,7 @@ pub trait FavoritesService: Send + Sync + 'static {
/// Add an entity to the user's favorites (idempotent).
fn add_favorite(
&self,
- user_id: &MacroUserIdStr<'_>,
- entity: &Entity<'_>,
+ receipt: &EntityAccessReceipt<ViewAccessLevel>,
) -> impl Future<Output = Result<Favorite, FavoritesError>> + Send;
/// List the user's favorites in manual order.
diff --git a/crates/favorites/src/domain/service.rs b/crates/favorites/src/domain/service.rs
index eb4e62c2aa..f9c9dea0d1 100644
--- a/crates/favorites/src/domain/service.rs
+++ b/crates/favorites/src/domain/service.rs
@@ -1,7 +1,11 @@
//! Favorites service implementation.
+#[cfg(test)]
+mod test;
+
use std::collections::HashSet;
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
@@ -46,10 +50,16 @@ where
#[tracing::instrument(err, skip(self))]
async fn add_favorite(
&self,
- user_id: &MacroUserIdStr<'_>,
- entity: &Entity<'_>,
+ receipt: &EntityAccessReceipt<ViewAccessLevel>,
) -> Result<Favorite, FavoritesError> {
- validate_entity(entity)?;
+ let user_id = receipt
+ .get_authenticated_user()
+ .map_err(|_| FavoritesError::Unauthorized)?;
+ let receipt_entity = receipt.entity();
+ let entity = receipt_entity
+ .entity_type
+ .with_entity_str(&receipt_entity.entity_id);
+ validate_entity(&entity)?;
// Cap the collection at add time. Enforcing it here (rather than only
// in `reorder_favorites`) keeps table growth bounded and guarantees a
// reorder payload can never exceed the limit and be rejected. Re-adding
@@ -67,7 +77,7 @@ where
}
Ok(self
.repo
- .add_favorite(user_id, entity)
+ .add_favorite(user_id, &entity)
.await
.map_err(anyhow::Error::from)?)
}
diff --git a/crates/favorites/src/domain/service/test.rs b/crates/favorites/src/domain/service/test.rs
new file mode 100644
index 0000000000..cbcef2024b
--- /dev/null
+++ b/crates/favorites/src/domain/service/test.rs
@@ -0,0 +1,247 @@
+use std::collections::HashSet;
+use std::sync::{Arc, Mutex};
+
+use chrono::Utc;
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+
+use super::{FavoritesServiceImpl, MAX_FAVORITES_PER_COLLECTION};
+use crate::domain::models::{Favorite, FavoritesError};
+use crate::domain::ports::{FavoritesRepo, FavoritesService};
+
+const USER_ID: &str = "macro|[email protected]";
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum RepoCall {
+ Count {
+ user_id: String,
+ },
+ Add {
+ user_id: String,
+ entity_type: EntityType,
+ entity_id: String,
+ },
+}
+
+#[derive(Clone)]
+struct FakeFavoritesRepo {
+ count: i64,
+ calls: Arc<Mutex<Vec<RepoCall>>>,
+}
+
+impl FakeFavoritesRepo {
+ fn new(count: i64) -> Self {
+ Self {
+ count,
+ calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn recorded_calls(&self) -> Vec<RepoCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+
+ fn record(&self, call: RepoCall) {
+ self.calls.lock().expect("calls lock poisoned").push(call);
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+#[error("fake favorites repository error")]
+struct FakeRepoError;
+
+impl FavoritesRepo for FakeFavoritesRepo {
+ type Err = FakeRepoError;
+
+ async fn add_favorite(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<Favorite, Self::Err> {
+ self.record(RepoCall::Add {
+ user_id: user_id.as_ref().to_string(),
+ entity_type: entity.entity_type,
+ entity_id: entity.entity_id.to_string(),
+ });
+
+ Ok(Favorite {
+ entity_type: entity.entity_type,
+ entity_id: entity.entity_id.to_string(),
+ sort_order: 0.0,
+ created_at: Utc::now(),
+ file_type: None,
+ document_sub_type: None,
+ channel_type: None,
+ channel_id: None,
+ })
+ }
+
+ async fn count_favorites(&self, user_id: &MacroUserIdStr<'_>) -> Result<i64, Self::Err> {
+ self.record(RepoCall::Count {
+ user_id: user_id.as_ref().to_string(),
+ });
+ Ok(self.count)
+ }
+
+ async fn list_favorites(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Vec<Favorite>, Self::Err> {
+ Ok(Vec::new())
+ }
+
+ async fn remove_favorite_by_entity(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ _entity: &Entity<'_>,
+ ) -> Result<bool, Self::Err> {
+ Ok(false)
+ }
+
+ async fn reorder_favorites(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ _ordered: &[Entity<'_>],
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn favorited_entities(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ _entities: &[Entity<'_>],
+ ) -> Result<HashSet<Entity<'static>>, Self::Err> {
+ Ok(HashSet::new())
+ }
+}
+
+fn user_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str(USER_ID).expect("valid user id")
+}
+
+fn authenticated_receipt(
+ entity_id: &str,
+ entity_type: EntityType,
+) -> EntityAccessReceipt<ViewAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(user_id(), entity_id, entity_type)
+}
+
+#[tokio::test]
+async fn add_favorite_forwards_authenticated_user_and_receipt_entity() {
+ let repo = FakeFavoritesRepo::new(0);
+ let service = FavoritesServiceImpl::new(repo.clone());
+ let receipt = authenticated_receipt("channel-123", EntityType::Channel);
+
+ let favorite = service
+ .add_favorite(&receipt)
+ .await
+ .expect("favorite should be added");
+
+ assert_eq!(favorite.entity_type, EntityType::Channel);
+ assert_eq!(favorite.entity_id, "channel-123");
+ assert_eq!(
+ repo.recorded_calls(),
+ vec![
+ RepoCall::Count {
+ user_id: USER_ID.to_string(),
+ },
+ RepoCall::Add {
+ user_id: USER_ID.to_string(),
+ entity_type: EntityType::Channel,
+ entity_id: "channel-123".to_string(),
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn add_favorite_rejects_internal_receipt_before_repository_calls() {
+ let repo = FakeFavoritesRepo::new(0);
+ let service = FavoritesServiceImpl::new(repo.clone());
+ let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_internal_user(
+ "doc-123",
+ EntityType::Document,
+ );
+
+ let error = service
+ .add_favorite(&receipt)
+ .await
+ .expect_err("internal receipt should be rejected");
+
+ assert!(matches!(error, FavoritesError::Unauthorized));
+ assert_eq!(error.to_string(), "you do not have access to this entity");
+ assert!(repo.recorded_calls().is_empty());
+}
+
+#[tokio::test]
+async fn add_favorite_rejects_empty_entity_id_before_repository_calls() {
+ let repo = FakeFavoritesRepo::new(0);
+ let service = FavoritesServiceImpl::new(repo.clone());
+ let receipt = authenticated_receipt(" ", EntityType::Document);
+
+ let error = service
+ .add_favorite(&receipt)
+ .await
+ .expect_err("empty entity id should be rejected");
+
+ assert!(
+ matches!(error, FavoritesError::BadRequest(message) if message == "entity_id must not be empty")
+ );
+ assert!(repo.recorded_calls().is_empty());
+}
+
+#[tokio::test]
+async fn add_favorite_rejects_collection_at_cap_before_add() {
+ let repo = FakeFavoritesRepo::new(MAX_FAVORITES_PER_COLLECTION as i64);
+ let service = FavoritesServiceImpl::new(repo.clone());
+ let receipt = authenticated_receipt("doc-123", EntityType::Document);
+
+ let error = service
+ .add_favorite(&receipt)
+ .await
+ .expect_err("full collection should reject add");
+
+ assert!(matches!(
+ error,
+ FavoritesError::BadRequest(message)
+ if message == format!(
+ "cannot have more than {MAX_FAVORITES_PER_COLLECTION} favorites"
+ )
+ ));
+ assert_eq!(
+ repo.recorded_calls(),
+ vec![RepoCall::Count {
+ user_id: USER_ID.to_string(),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn repeated_adds_are_delegated_to_repository_for_idempotency() {
+ let repo = FakeFavoritesRepo::new(0);
+ let service = FavoritesServiceImpl::new(repo.clone());
+ let receipt = authenticated_receipt("doc-123", EntityType::Document);
+
+ service
+ .add_favorite(&receipt)
+ .await
+ .expect("first add should succeed");
+ service
+ .add_favorite(&receipt)
+ .await
+ .expect("repeated add should succeed");
+
+ let count_call = RepoCall::Count {
+ user_id: USER_ID.to_string(),
+ };
+ let add_call = RepoCall::Add {
+ user_id: USER_ID.to_string(),
+ entity_type: EntityType::Document,
+ entity_id: "doc-123".to_string(),
+ };
+ assert_eq!(
+ repo.recorded_calls(),
+ vec![count_call.clone(), add_call.clone(), count_call, add_call]
+ );
+}
diff --git a/crates/favorites/src/inbound/axum_router.rs b/crates/favorites/src/inbound/axum_router.rs
index 4c505308bc..1185307b26 100644
--- a/crates/favorites/src/inbound/axum_router.rs
+++ b/crates/favorites/src/inbound/axum_router.rs
@@ -4,15 +4,20 @@ use std::sync::Arc;
use axum::{
Json, Router,
- extract::{Path, State},
+ extract::{FromRef, Path, State},
http::StatusCode,
response::IntoResponse,
routing::{delete, get, patch, post},
};
-use entity_access::domain::ports::EntityAccessService;
+use entity_access::{
+ domain::{models::ViewAccessLevel, ports::EntityAccessService},
+ inbound::axum_extractors::EntityBodyAccessLevelExtractor,
+};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
use model_entity::EntityType;
use model_error_response::ErrorResponse;
-use model_user::axum_extractor::MacroUserExtractor;
use serde::Deserialize;
use crate::domain::{
@@ -21,64 +26,52 @@ use crate::domain::{
};
/// Router state for favorites endpoints.
-pub struct FavoritesRouterState<S, AccessSvc> {
+pub struct FavoritesRouterState<S, AccessSvc, Auth> {
service: Arc<S>,
access_service: Arc<AccessSvc>,
+ authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S, AccessSvc> Clone for FavoritesRouterState<S, AccessSvc> {
+impl<S, AccessSvc, Auth> Clone for FavoritesRouterState<S, AccessSvc, Auth> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
access_service: self.access_service.clone(),
+ authorization_state: self.authorization_state.clone(),
}
}
}
-impl<S, AccessSvc> FavoritesRouterState<S, AccessSvc>
+impl<S, AccessSvc, Auth> FavoritesRouterState<S, AccessSvc, Auth>
where
S: FavoritesService,
AccessSvc: EntityAccessService,
{
- /// Create router state from shared service references.
- pub fn new(service: Arc<S>, access_service: Arc<AccessSvc>) -> Self {
+ /// Create router state from shared service references and authorization state.
+ pub fn new(
+ service: Arc<S>,
+ access_service: Arc<AccessSvc>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
Self {
service,
access_service,
+ authorization_state,
}
}
}
-/// Ensure the caller has at least view access to the entity they are trying
-/// to favorite.
-///
-/// Favorites hydrate display metadata (channel types, file types) on read,
-/// so without this check a caller could favorite an arbitrary id and use
-/// `GET /favorites` as an oracle for entities they cannot see. Entity types
-/// the access layer does not recognize (e.g. channel messages) resolve to
-/// "no access" and are rejected.
-async fn ensure_entity_access<AccessSvc>(
- access_service: &AccessSvc,
- user: &MacroUserExtractor,
- entity_type: EntityType,
- entity_id: &str,
-) -> Result<(), FavoritesApiError>
-where
- AccessSvc: EntityAccessService,
+impl<S, AccessSvc, Auth> FromRef<FavoritesRouterState<S, AccessSvc, Auth>> for Arc<AccessSvc> {
+ fn from_ref(state: &FavoritesRouterState<S, AccessSvc, Auth>) -> Self {
+ state.access_service.clone()
+ }
+}
+
+impl<S, AccessSvc, Auth> FromRef<FavoritesRouterState<S, AccessSvc, Auth>>
+ for MacroAuthorizationState<Auth>
{
- let access = access_service
- .get_access_level(Some(&user.macro_user_id), entity_id, entity_type)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "favorites: failed to check entity access");
- FavoritesApiError::Favorites(FavoritesError::Internal(anyhow::anyhow!(
- "failed to check entity access"
- )))
- })?;
- if access.is_some() {
- Ok(())
- } else {
- Err(FavoritesApiError::Forbidden)
+ fn from_ref(state: &FavoritesRouterState<S, AccessSvc, Auth>) -> Self {
+ state.authorization_state.clone()
}
}
@@ -89,20 +82,26 @@ where
/// - `POST /` — favorite an entity.
/// - `DELETE /{entity_type}/{entity_id}` — remove a favorite.
/// - `PATCH /reorder` — persist a manual order.
-pub fn favorites_router<S, AccessSvc, T>(state: FavoritesRouterState<S, AccessSvc>) -> Router<T>
+pub fn favorites_router<S, AccessSvc, Auth, T>(
+ state: FavoritesRouterState<S, AccessSvc, Auth>,
+) -> Router<T>
where
S: FavoritesService,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
T: Send + Sync + 'static,
{
Router::new()
- .route("/", get(list_favorites_handler::<S, AccessSvc>))
- .route("/", post(add_favorite_handler::<S, AccessSvc>))
+ .route("/", get(list_favorites_handler::<S, AccessSvc, Auth>))
+ .route("/", post(add_favorite_handler::<S, AccessSvc, Auth>))
.route(
"/{entity_type}/{entity_id}",
- delete(remove_favorite_by_entity_handler::<S, AccessSvc>),
+ delete(remove_favorite_by_entity_handler::<S, AccessSvc, Auth>),
+ )
+ .route(
+ "/reorder",
+ patch(reorder_favorites_handler::<S, AccessSvc, Auth>),
)
- .route("/reorder", patch(reorder_favorites_handler::<S, AccessSvc>))
.with_state(state)
}
@@ -164,13 +163,14 @@ pub struct ReorderFavoritesRequest {
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn list_favorites_handler<S, AccessSvc>(
- State(state): State<FavoritesRouterState<S, AccessSvc>>,
- user: MacroUserExtractor,
-) -> Result<Json<FavoritesList>, FavoritesApiError>
+pub async fn list_favorites_handler<S, AccessSvc, Auth>(
+ State(state): State<FavoritesRouterState<S, AccessSvc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
+) -> Result<Json<FavoritesList>, FavoritesError>
where
S: FavoritesService,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
let favorites = state.service.list_favorites(&user.macro_user_id).await?;
Ok(Json(FavoritesList { favorites }))
@@ -192,29 +192,18 @@ where
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn add_favorite_handler<S, AccessSvc>(
- State(state): State<FavoritesRouterState<S, AccessSvc>>,
- user: MacroUserExtractor,
- Json(req): Json<AddFavoriteRequest>,
-) -> Result<Json<Favorite>, FavoritesApiError>
+pub async fn add_favorite_handler<S, AccessSvc, Auth>(
+ State(state): State<FavoritesRouterState<S, AccessSvc, Auth>>,
+ access: EntityBodyAccessLevelExtractor<ViewAccessLevel, AccessSvc, AddFavoriteRequest, Auth>,
+) -> Result<Json<Favorite>, FavoritesError>
where
S: FavoritesService,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
- // Only let the caller favorite entities they can actually access, so a
- // favorite can't be used as an oracle for entity metadata (file type,
- // private-channel type) they were never allowed to see.
- ensure_entity_access(
- state.access_service.as_ref(),
- &user,
- req.entity_type,
- &req.entity_id,
- )
- .await?;
- let entity = req.entity_type.with_entity_str(&req.entity_id);
let favorite = state
.service
- .add_favorite(&user.macro_user_id, &entity)
+ .add_favorite(&access.entity_access_receipt)
.await?;
Ok(Json(favorite))
}
@@ -234,14 +223,15 @@ where
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn remove_favorite_by_entity_handler<S, AccessSvc>(
- State(state): State<FavoritesRouterState<S, AccessSvc>>,
- user: MacroUserExtractor,
+pub async fn remove_favorite_by_entity_handler<S, AccessSvc, Auth>(
+ State(state): State<FavoritesRouterState<S, AccessSvc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Path(params): Path<RemoveFavoriteByEntityParams>,
-) -> Result<Json<()>, FavoritesApiError>
+) -> Result<Json<()>, FavoritesError>
where
S: FavoritesService,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
let entity = params.entity_type.with_entity_str(&params.entity_id);
state
@@ -266,14 +256,15 @@ where
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn reorder_favorites_handler<S, AccessSvc>(
- State(state): State<FavoritesRouterState<S, AccessSvc>>,
- user: MacroUserExtractor,
+pub async fn reorder_favorites_handler<S, AccessSvc, Auth>(
+ State(state): State<FavoritesRouterState<S, AccessSvc, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<ReorderFavoritesRequest>,
-) -> Result<Json<()>, FavoritesApiError>
+) -> Result<Json<()>, FavoritesError>
where
S: FavoritesService,
AccessSvc: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
let ordered: Vec<_> = req
.favorites
@@ -287,34 +278,18 @@ where
Ok(Json(()))
}
-/// API-level error for favorites handlers.
-#[derive(Debug, thiserror::Error)]
-pub enum FavoritesApiError {
- /// The caller does not have access to the entity they tried to favorite.
- #[error("you do not have access to this entity")]
- Forbidden,
- /// Domain error.
- #[error(transparent)]
- Favorites(#[from] FavoritesError),
-}
-
-impl IntoResponse for FavoritesApiError {
+impl IntoResponse for FavoritesError {
fn into_response(self) -> axum::response::Response {
let status_code = match &self {
- FavoritesApiError::Forbidden => StatusCode::FORBIDDEN,
- FavoritesApiError::Favorites(FavoritesError::NotFound) => StatusCode::NOT_FOUND,
- FavoritesApiError::Favorites(FavoritesError::BadRequest(_)) => StatusCode::BAD_REQUEST,
- FavoritesApiError::Favorites(FavoritesError::Internal(_)) => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
+ FavoritesError::NotFound => StatusCode::NOT_FOUND,
+ FavoritesError::BadRequest(_) => StatusCode::BAD_REQUEST,
+ FavoritesError::Unauthorized => StatusCode::FORBIDDEN,
+ FavoritesError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
- if status_code.is_server_error() {
- tracing::error!(error=?self, "favorites internal server error");
- }
-
let message = match &self {
- FavoritesApiError::Favorites(FavoritesError::Internal(_)) => {
+ FavoritesError::Internal(_) => {
+ tracing::error!(error=?self, "favorites internal server error");
"internal server error".to_string()
}
error => error.to_string(),
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 0796e9e920..9628038f98 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -356,7 +356,8 @@ pub(crate) type DssCallInternalState = InternalCallRouterState<DssCallService>;
pub(crate) type FavoritesServiceType = FavoritesServiceImpl<PgFavoritesRepo>;
/// Type alias for the favorites router state.
-pub(crate) type DssFavoritesState = FavoritesRouterState<FavoritesServiceType, EntityAccessService>;
+pub(crate) type DssFavoritesState =
+ FavoritesRouterState<FavoritesServiceType, EntityAccessService, AuthorizationService>;
/// Type alias for the foreign entity service.
pub(crate) type ForeignEntityServiceType = ForeignEntityServiceImpl<PgForeignEntityRepo>;
diff --git a/services/document_storage_service/src/api/documents/initialize_how_to_guide.rs b/services/document_storage_service/src/api/documents/initialize_how_to_guide.rs
index fdc6643b15..be5b4e724d 100644
--- a/services/document_storage_service/src/api/documents/initialize_how_to_guide.rs
+++ b/services/document_storage_service/src/api/documents/initialize_how_to_guide.rs
@@ -6,6 +6,7 @@ use axum::{
use documents_hex::domain::create::{
MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument,
};
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
use favorites::domain::ports::FavoritesService;
use macro_authorization::MacroAuthorizationExtractor;
use model::response::{ErrorResponse, GenericSuccessResponse};
@@ -48,13 +49,30 @@ pub async fn handler(
.into_response()
})?;
- state
- .favorites_service
- .add_favorite(
+ let receipt = state
+ .entity_access_service
+ .generate_entity_access_receipt::<ViewAccessLevel>(
&user_context.macro_user_id,
- &EntityType::Document.with_entity_str(created.document_id()),
+ user_context.user_context.organization_id.map(i64::from),
+ created.document_id(),
+ EntityType::Document,
)
.await
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to authorize how to guide document favorite");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "failed to favorite how to guide document".into(),
+ }),
+ )
+ .into_response()
+ })?;
+
+ state
+ .favorites_service
+ .add_favorite(&receipt)
+ .await
.map_err(|e| {
tracing::error!(error=?e, "failed to favorite how to guide document");
(
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 8a69be4e97..6ece836b82 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -859,6 +859,7 @@ async fn main() -> anyhow::Result<()> {
favorites_state: FavoritesRouterState::new(
favorites_service.clone(),
entity_access_service.clone(),
+ authorization_state.clone(),
),
favorites_service,
#[cfg(feature = "graphql")]