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(properties): macro authorization (#4969)

Will Hutchinson2d7fe9f4881f
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 3b84e25820..98bfa88c46 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -4278,14 +4278,11 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/invite_email",
- "crates/ip_extractor",
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
- "crates/macro_db_client",
"crates/macro_env",
"crates/macro_env_var",
- "crates/macro_middleware",
"crates/macro_service_urls",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -4297,13 +4294,10 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_dcs",
"crates/models_entity_access_management",
- "crates/models_opensearch",
"crates/models_pagination",
"crates/models_permissions",
"crates/models_properties",
- "crates/models_team",
"crates/non_empty",
"crates/notification",
"crates/prompt",
@@ -4312,7 +4306,6 @@
"crates/rate_limit",
"crates/remote_env_var",
"crates/system_properties",
- "crates/user_quota",
"crates/workspace-hack"
],
"rate_limit": [
diff --git a/Cargo.lock b/Cargo.lock
index 55e87b00cb..d9cebbe69b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11067,17 +11067,17 @@ dependencies = [
"entity_access",
"entity_access_db_utils",
"futures",
+ "macro_authorization",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
"mockall",
- "model",
"model-entity",
"model_notifications",
- "model_user",
"models_permissions",
"models_properties",
"notification",
+ "rootcause",
"schemars 1.2.1",
"serde",
"serde_json",
@@ -11098,7 +11098,7 @@ version = "0.1.0"
dependencies = [
"axum",
"entity_access",
- "macro_middleware",
+ "macro_authorization",
"models_properties",
"notification",
"properties",
diff --git a/crates/entity_access/src/inbound/axum_extractors/team.rs b/crates/entity_access/src/inbound/axum_extractors/team.rs
index d0633df845..dbf833aba2 100644
--- a/crates/entity_access/src/inbound/axum_extractors/team.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/team.rs
@@ -137,7 +137,6 @@ where
/// invalid, and identity-less internal credentials are rejected. A qualifying
/// team role produces a receipt; no membership or an insufficient role produces
/// `None`.
-#[allow(dead_code)]
#[derive(Debug)]
pub struct OptionalMacroUserTeamExtractorV2<T: RequiredPermission, Svc, Auth> {
/// The entity access receipt, if the authorized user has a qualifying team membership.
diff --git a/crates/properties/Cargo.toml b/crates/properties/Cargo.toml
index 94bb1dd593..c13bba9b3a 100644
--- a/crates/properties/Cargo.toml
+++ b/crates/properties/Cargo.toml
@@ -16,11 +16,10 @@ ai_tools = [
default = ["ai_tools", "inbound", "outbound", "ports"]
inbound = [
"dep:axum",
- "dep:model",
+ "dep:macro_authorization",
"dep:serde",
"dep:serde_json",
"dep:tokio",
- "dep:tower",
"dep:utoipa",
"entity_access/inbound",
"ports",
@@ -51,12 +50,13 @@ entity_access = { path = "../entity_access", default-features = false, features
] }
entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }
futures = { workspace = true, optional = true }
+macro_authorization = { path = "../macro_authorization", default-features = false, features = [
+ "axum",
+], optional = true }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid", optional = true }
-model = { path = "../model", optional = true }
model-entity = { path = "../model-entity", optional = true }
model_notifications = { path = "../model_notifications", optional = true }
-model_user = { path = "../model_user", features = ["axum"] }
models_permissions = { path = "../models_permissions", optional = true }
models_properties = { path = "../models_properties" }
notification = { path = "../notification", optional = true }
@@ -67,7 +67,6 @@ sqlx = { workspace = true, optional = true }
system_properties = { path = "../system_properties" }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["macros"], optional = true }
-tower = { workspace = true, optional = true }
tracing = { workspace = true }
utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
@@ -78,8 +77,10 @@ ai_toolset = { path = "../ai_toolset" }
chrono = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
+rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tower = { workspace = true }
[package.metadata.sqlx]
offline = true
diff --git a/crates/properties/src/inbound/axum_router.rs b/crates/properties/src/inbound/axum_router.rs
index 29bae5cc9a..9dbdd8bc80 100644
--- a/crates/properties/src/inbound/axum_router.rs
+++ b/crates/properties/src/inbound/axum_router.rs
@@ -4,9 +4,11 @@
//! as a [`Router`] generic over the [`PropertiesService`] implementation and
//! the entity access service (used for team-membership extraction).
//!
-//! The composition root supplies the concrete services via
-//! [`PropertiesRouterState`] plus the authentication middleware layer applied
-//! to the routes that require an authenticated user.
+//! The composition root supplies the concrete services and request
+//! authorization state via [`PropertiesRouterState`].
+
+#[cfg(test)]
+mod test;
pub mod definitions;
pub mod entities;
@@ -14,60 +16,72 @@ pub mod extract;
pub mod options;
pub mod tags;
-use std::convert::Infallible;
use std::sync::Arc;
use axum::{
Router,
- extract::{FromRef, Request},
+ extract::FromRef,
http::StatusCode,
- response::IntoResponse,
- routing::{Route, delete, get, post, put},
+ routing::{delete, get, post, put},
};
use entity_access::domain::models::MemberTeamRole;
use entity_access::domain::ports::EntityAccessService;
-use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractor;
-use tower::{Layer, Service};
+use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractorV2;
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
use crate::domain::error::PropertiesErr;
use crate::domain::service::PropertiesService;
/// State for the properties router.
-pub struct PropertiesRouterState<S, A> {
+pub struct PropertiesRouterState<S, A, Auth> {
properties_service: Arc<S>,
entity_access_service: Arc<A>,
+ authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S, A> Clone for PropertiesRouterState<S, A> {
+impl<S, A, Auth> Clone for PropertiesRouterState<S, A, Auth> {
fn clone(&self) -> Self {
Self {
properties_service: self.properties_service.clone(),
entity_access_service: self.entity_access_service.clone(),
+ authorization_state: self.authorization_state.clone(),
}
}
}
-impl<S: PropertiesService, A: EntityAccessService> PropertiesRouterState<S, A> {
- /// Create a router state wrapping the properties service and entity access service.
- pub fn new(properties_service: Arc<S>, entity_access_service: Arc<A>) -> Self {
+impl<S: PropertiesService, A: EntityAccessService, Auth> PropertiesRouterState<S, A, Auth> {
+ /// Create router state wrapping the properties, entity access, and authorization services.
+ pub fn new(
+ properties_service: Arc<S>,
+ entity_access_service: Arc<A>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
Self {
properties_service,
entity_access_service,
+ authorization_state,
}
}
}
/// Lets the entity access extractors pull the access service out of the state.
-impl<S, A> FromRef<PropertiesRouterState<S, A>> for Arc<A> {
- fn from_ref(state: &PropertiesRouterState<S, A>) -> Self {
+impl<S, A, Auth> FromRef<PropertiesRouterState<S, A, Auth>> for Arc<A> {
+ fn from_ref(state: &PropertiesRouterState<S, A, Auth>) -> Self {
state.entity_access_service.clone()
}
}
+/// Lets request extractors pull the authorization service out of the state.
+impl<S, A, Auth> FromRef<PropertiesRouterState<S, A, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &PropertiesRouterState<S, A, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
/// Team extractor used by property definition endpoints. Resolves the caller's team
/// membership without failing when they have no team. Member role is required, matching
/// the model where anyone on a team can manage that team's properties.
-pub type PropertyTeamExtractor<A> = OptionalMacroUserTeamExtractor<MemberTeamRole, A>;
+pub type PropertyTeamExtractor<A, Auth> = OptionalMacroUserTeamExtractorV2<MemberTeamRole, A, Auth>;
/// Map a domain [`PropertiesErr`] to the HTTP status code it represents.
pub fn properties_err_status(e: &PropertiesErr) -> StatusCode {
@@ -88,77 +102,62 @@ pub fn properties_err_status(e: &PropertiesErr) -> StatusCode {
}
/// Creates the properties router.
-///
-/// `ensure_user_exists` is the authentication middleware layer applied to every
-/// route that requires an authenticated user (all except the anonymous-capable
-/// entity property GET and the internal endpoints).
-pub fn router<S, A, L>(ensure_user_exists: L) -> Router<PropertiesRouterState<S, A>>
+pub fn router<S, A, Auth>() -> Router<PropertiesRouterState<S, A, Auth>>
where
S: PropertiesService,
A: EntityAccessService,
- L: Layer<Route> + Clone + Send + Sync + 'static,
- L::Service: Service<Request> + Clone + Send + Sync + 'static,
- <L::Service as Service<Request>>::Response: IntoResponse + 'static,
- <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
- <L::Service as Service<Request>>::Future: Send + 'static,
+ Auth: MacroAuthorizationService,
{
Router::new()
// Property Definition Management - requires authentication
.route(
"/definitions",
- get(definitions::list_properties::<S, A>)
- .post(definitions::create_property_definition::<S, A>)
- .layer(ensure_user_exists.clone()),
+ get(definitions::list_properties::<S, A, Auth>)
+ .post(definitions::create_property_definition::<S, A, Auth>),
)
.route(
"/definitions/{definition_id}",
- delete(definitions::delete_property_definition::<S, A>)
- .layer(ensure_user_exists.clone()),
+ delete(definitions::delete_property_definition::<S, A, Auth>),
)
// Property Options Management - requires authentication
.route(
"/definitions/{definition_id}/options",
- get(options::get_property_options::<S, A>)
- .post(options::add_property_option::<S, A>)
- .layer(ensure_user_exists.clone()),
+ get(options::get_property_options::<S, A, Auth>)
+ .post(options::add_property_option::<S, A, Auth>),
)
.route(
"/definitions/{definition_id}/options/{option_id}",
- delete(options::delete_property_option::<S, A>)
- .patch(options::update_property_option::<S, A>)
- .layer(ensure_user_exists.clone()),
+ delete(options::delete_property_option::<S, A, Auth>)
+ .patch(options::update_property_option::<S, A, Auth>),
)
.route(
"/tags",
- get(tags::list_tags::<S, A>)
- .post(tags::ensure_tag_set::<S, A>)
- .layer(ensure_user_exists.clone()),
+ get(tags::list_tags::<S, A, Auth>).post(tags::ensure_tag_set::<S, A, Auth>),
)
// Entity Property Operations
// GET allows anonymous access for public entities
.route(
"/entities/{entity_type}/{entity_id}",
- get(entities::get_entity_properties::<S, A>),
+ get(entities::get_entity_properties::<S, A, Auth>),
)
// Bulk entity properties - requires authentication
.route(
"/entities/bulk",
- post(entities::get_bulk_entity_properties::<S, A>).layer(ensure_user_exists.clone()),
+ post(entities::get_bulk_entity_properties::<S, A, Auth>),
)
// PUT/DELETE require authentication
.route(
"/entities/{entity_type}/{entity_id}/{property_id}",
- put(entities::set_entity_property::<S, A>).layer(ensure_user_exists.clone()),
+ put(entities::set_entity_property::<S, A, Auth>),
)
// Atomic single-option delta on a multi-select value (merges concurrent edits)
.route(
"/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",
- post(entities::add_entity_property_option::<S, A>)
- .delete(entities::remove_entity_property_option::<S, A>)
- .layer(ensure_user_exists.clone()),
+ post(entities::add_entity_property_option::<S, A, Auth>)
+ .delete(entities::remove_entity_property_option::<S, A, Auth>),
)
.route(
"/entity_properties/{entity_property_id}",
- delete(entities::delete_entity_property::<S, A>).layer(ensure_user_exists),
+ delete(entities::delete_entity_property::<S, A, Auth>),
)
}
diff --git a/crates/properties/src/inbound/axum_router/definitions.rs b/crates/properties/src/inbound/axum_router/definitions.rs
index 5c3ffc646f..15d3eb947c 100644
--- a/crates/properties/src/inbound/axum_router/definitions.rs
+++ b/crates/properties/src/inbound/axum_router/definitions.rs
@@ -7,7 +7,7 @@ use axum::{
response::{IntoResponse, Response},
};
use entity_access::domain::ports::EntityAccessService;
-use model::user::axum_extractor::MacroUserExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
use models_properties::EntityType;
use models_properties::api::CreatePropertyDefinitionRequest;
use models_properties::service::property_definition::PropertyDefinition;
@@ -98,14 +98,18 @@ pub enum PropertyDefinitionResponse {
tag = "Properties"
)]
#[tracing::instrument(skip(state, user, team), err)]
-pub async fn list_properties<S: PropertiesService, A: EntityAccessService>(
+pub async fn list_properties<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Query(query): Query<ListPropertiesQuery>,
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
) -> Result<Json<Vec<PropertyDefinitionResponse>>, ListPropertiesErr> {
let callers_team = team.entity_access_receipt.as_ref();
@@ -197,13 +201,17 @@ impl IntoResponse for CreatePropertyDefinitionErr {
tags = ["Properties"]
)]
#[tracing::instrument(skip(state, user, team), err)]
-pub async fn create_property_definition<S: PropertiesService, A: EntityAccessService>(
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+pub async fn create_property_definition<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
Json(request): Json<CreatePropertyDefinitionRequest>,
) -> Result<(StatusCode, Json<PropertyDefinition>), CreatePropertyDefinitionErr> {
tracing::info!(scope = ?request.scope, "creating property definition");
@@ -259,14 +267,18 @@ impl IntoResponse for DeletePropertyDefinitionError {
tag = "Properties"
)]
#[tracing::instrument(skip(state, user, team), err)]
-pub async fn delete_property_definition<S: PropertiesService, A: EntityAccessService>(
+pub async fn delete_property_definition<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path(property_uuid): Path<Uuid>,
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
) -> Result<Response, DeletePropertyDefinitionError> {
tracing::info!("deleting property definition");
diff --git a/crates/properties/src/inbound/axum_router/entities.rs b/crates/properties/src/inbound/axum_router/entities.rs
index 4ec1d94db8..6a222bffeb 100644
--- a/crates/properties/src/inbound/axum_router/entities.rs
+++ b/crates/properties/src/inbound/axum_router/entities.rs
@@ -15,7 +15,7 @@ use axum::{
};
use entity_access::domain::models::EditAccessLevel;
use entity_access::domain::ports::EntityAccessService;
-use model::user::axum_extractor::MacroUserExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
use models_properties::api::{PropertyTargetEntityType, PropertyTargetReference, SetPropertyValue};
use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;
use serde::{Deserialize, Serialize};
@@ -111,9 +111,13 @@ impl IntoResponse for GetEntityPropertiesErr {
tag = "Properties"
)]
#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), entity_type = ?access.0.entity_type(), include_metadata = query.include_metadata), err)]
-pub async fn get_entity_properties<S: PropertiesService, A: EntityAccessService>(
+pub async fn get_entity_properties<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Query(query): Query<EntityQueryParams>,
- State(state): State<PropertiesRouterState<S, A>>,
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
// Anonymous access is allowed for publicly shared entities; the extractor
// minted a view receipt either way.
access: ViewReceiptExtractor,
@@ -236,12 +240,16 @@ fn validate_bulk_request_size(
tag = "Properties"
)]
#[tracing::instrument(skip(state, request, user), fields(entity_count = request.entities.len()), err)]
-pub async fn get_bulk_entity_properties<S: PropertiesService, A: EntityAccessService>(
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+pub async fn get_bulk_entity_properties<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
+ }: MacroAuthorizationExtractor<Auth>,
Json(request): Json<BulkEntityPropertiesRequest>,
) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {
// The public endpoint requires explicit property IDs. An empty property_ids
@@ -352,9 +360,13 @@ impl IntoResponse for SetEntityPropertyErr {
tags = ["Properties"]
)]
#[tracing::instrument(skip(state, access, request), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, entity_type = ?access.0.entity_type(), has_value = request.value.is_some()), err)]
-pub async fn set_entity_property<S: PropertiesService, A: EntityAccessService>(
+pub async fn set_entity_property<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path((_entity_type, _entity_id, property_uuid)): Path<(PropertyTargetEntityType, String, Uuid)>,
- State(state): State<PropertiesRouterState<S, A>>,
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
access: EditReceiptExtractor,
Json(request): Json<SetEntityPropertyRequest>,
) -> Result<StatusCode, SetEntityPropertyErr> {
@@ -418,14 +430,18 @@ impl IntoResponse for EntityPropertyOptionErr {
tags = ["Properties"]
)]
#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, option_id = %option_uuid, entity_type = ?access.0.entity_type()), err)]
-pub async fn add_entity_property_option<S: PropertiesService, A: EntityAccessService>(
+pub async fn add_entity_property_option<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path((_entity_type, _entity_id, property_uuid, option_uuid)): Path<(
PropertyTargetEntityType,
String,
Uuid,
Uuid,
)>,
- State(state): State<PropertiesRouterState<S, A>>,
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
access: EditReceiptExtractor,
) -> Result<StatusCode, EntityPropertyOptionErr> {
tracing::info!("adding entity property option");
@@ -460,14 +476,18 @@ pub async fn add_entity_property_option<S: PropertiesService, A: EntityAccessSer
tags = ["Properties"]
)]
#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, option_id = %option_uuid, entity_type = ?access.0.entity_type()), err)]
-pub async fn remove_entity_property_option<S: PropertiesService, A: EntityAccessService>(
+pub async fn remove_entity_property_option<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path((_entity_type, _entity_id, property_uuid, option_uuid)): Path<(
PropertyTargetEntityType,
String,
Uuid,
Uuid,
)>,
- State(state): State<PropertiesRouterState<S, A>>,
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
access: EditReceiptExtractor,
) -> Result<StatusCode, EntityPropertyOptionErr> {
tracing::info!("removing entity property option");
@@ -520,13 +540,17 @@ impl IntoResponse for DeleteEntityPropertyErr {
tag = "Properties"
)]
#[tracing::instrument(skip(state, user), fields(entity_property_id = %entity_property_uuid), err)]
-pub async fn delete_entity_property<S: PropertiesService, A: EntityAccessService>(
+pub async fn delete_entity_property<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path(entity_property_uuid): Path<Uuid>,
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
+ }: MacroAuthorizationExtractor<Auth>,
) -> Result<StatusCode, DeleteEntityPropertyErr> {
tracing::info!("removing entity property");
diff --git a/crates/properties/src/inbound/axum_router/extract.rs b/crates/properties/src/inbound/axum_router/extract.rs
index 733c4f6af2..1bd4ec039b 100644
--- a/crates/properties/src/inbound/axum_router/extract.rs
+++ b/crates/properties/src/inbound/axum_router/extract.rs
@@ -5,6 +5,8 @@
//! passes the minted receipt into the domain service, whose entity-scoped
//! methods only accept receipts.
+use std::borrow::Cow;
+
use axum::{
RequestPartsExt,
extract::{FromRequestParts, Path},
@@ -17,8 +19,11 @@ use entity_access::domain::models::{
EntityType as AccessEntityType, RequiredPermission, ViewAccessLevel,
};
use entity_access::domain::ports::EntityAccessService;
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationService,
+ OptionalMacroAuthorizationExtractor,
+};
use macro_user_id::user_id::MacroUserIdStr;
-use model::user::axum_extractor::{MacroUserExtractor, OptionalMacroUserExtractor};
use models_properties::api::PropertyTargetEntityType;
use super::{PropertiesRouterState, properties_err_status};
@@ -36,9 +41,14 @@ struct EntityPathParams {
/// Rejection for the receipt extractors.
#[derive(Debug, thiserror::Error)]
pub enum ReceiptRejection {
- /// The route requires an authenticated user.
- #[error("Authentication required")]
- Unauthorized,
+ /// Request authorization failed.
+ #[error("{message}")]
+ Authorization {
+ /// HTTP status returned by the authorization extractor.
+ status: StatusCode,
+ /// Error message returned by the authorization extractor.
+ message: Cow<'static, str>,
+ },
/// The path is missing or has invalid entity parameters.
#[error("{0}")]
BadRequest(&'static str),
@@ -47,10 +57,19 @@ pub enum ReceiptRejection {
Properties(#[from] PropertiesErr),
}
+impl From<MacroAuthorizationRejection> for ReceiptRejection {
+ fn from((status, rejection): MacroAuthorizationRejection) -> Self {
+ Self::Authorization {
+ status,
+ message: rejection.0.message,
+ }
+ }
+}
+
impl IntoResponse for ReceiptRejection {
fn into_response(self) -> Response {
let status_code = match &self {
- ReceiptRejection::Unauthorized => StatusCode::UNAUTHORIZED,
+ ReceiptRejection::Authorization { status, .. } => *status,
ReceiptRejection::BadRequest(_) => StatusCode::BAD_REQUEST,
ReceiptRejection::Properties(e) => properties_err_status(e),
};
@@ -146,27 +165,28 @@ async fn entity_path_params(parts: &mut Parts) -> Result<EntityPathParams, Recei
/// Allows anonymous callers, for publicly shared entities.
pub struct ViewReceiptExtractor(pub ViewReceipt);
-impl<S, A> FromRequestParts<PropertiesRouterState<S, A>> for ViewReceiptExtractor
+impl<S, A, Auth> FromRequestParts<PropertiesRouterState<S, A, Auth>> for ViewReceiptExtractor
where
S: PropertiesService,
A: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
type Rejection = ReceiptRejection;
#[tracing::instrument(err, skip(parts, state))]
async fn from_request_parts(
parts: &mut Parts,
- state: &PropertiesRouterState<S, A>,
+ state: &PropertiesRouterState<S, A, Auth>,
) -> Result<Self, Self::Rejection> {
let params = entity_path_params(parts).await?;
- let OptionalMacroUserExtractor {
+ let OptionalMacroAuthorizationExtractor {
macro_user_id: user,
..
} = parts
- .extract()
+ .extract_with_state::<OptionalMacroAuthorizationExtractor<Auth>, _>(state)
.await
- .map_err(|_| ReceiptRejection::Unauthorized)?;
+ .map_err(ReceiptRejection::from)?;
let receipt = mint_view_receipt(
state.entity_access_service.as_ref(),
@@ -184,27 +204,28 @@ where
/// Requires an authenticated user.
pub struct EditReceiptExtractor(pub EditReceipt);
-impl<S, A> FromRequestParts<PropertiesRouterState<S, A>> for EditReceiptExtractor
+impl<S, A, Auth> FromRequestParts<PropertiesRouterState<S, A, Auth>> for EditReceiptExtractor
where
S: PropertiesService,
A: EntityAccessService,
+ Auth: MacroAuthorizationService,
{
type Rejection = ReceiptRejection;
#[tracing::instrument(err, skip(parts, state))]
async fn from_request_parts(
parts: &mut Parts,
- state: &PropertiesRouterState<S, A>,
+ state: &PropertiesRouterState<S, A, Auth>,
) -> Result<Self, Self::Rejection> {
let params = entity_path_params(parts).await?;
- let MacroUserExtractor {
+ let MacroAuthorizationExtractor {
macro_user_id: user,
..
} = parts
- .extract()
+ .extract_with_state::<MacroAuthorizationExtractor<Auth>, _>(state)
.await
- .map_err(|_| ReceiptRejection::Unauthorized)?;
+ .map_err(ReceiptRejection::from)?;
let receipt = mint_authenticated_receipt::<EditAccessLevel, A>(
state.entity_access_service.as_ref(),
diff --git a/crates/properties/src/inbound/axum_router/options.rs b/crates/properties/src/inbound/axum_router/options.rs
index 9316500b83..709f9c0932 100644
--- a/crates/properties/src/inbound/axum_router/options.rs
+++ b/crates/properties/src/inbound/axum_router/options.rs
@@ -7,7 +7,7 @@ use axum::{
response::{IntoResponse, Response},
};
use entity_access::domain::ports::EntityAccessService;
-use model::user::axum_extractor::MacroUserExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
use models_properties::api::{AddPropertyOptionRequest, UpdatePropertyOptionRequest};
use models_properties::service::property_option::PropertyOption;
use thiserror::Error;
@@ -56,14 +56,18 @@ impl IntoResponse for GetPropertyOptionsErr {
tag = "Properties"
)]
#[tracing::instrument(skip(state, user, team), fields(property_id = %property_uuid), err)]
-pub async fn get_property_options<S: PropertiesService, A: EntityAccessService>(
+pub async fn get_property_options<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path(property_uuid): Path<Uuid>,
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
) -> Result<Json<Vec<PropertyOption>>, GetPropertyOptionsErr> {
tracing::info!("retrieving property options");
@@ -122,14 +126,18 @@ impl IntoResponse for AddPropertyOptionErr {
tags = ["Properties"]
)]
#[tracing::instrument(skip(state, user, team), fields(property_id = %property_uuid, request = ?request), err)]
-pub async fn add_property_option<S: PropertiesService, A: EntityAccessService>(
+pub async fn add_property_option<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path(property_uuid): Path<Uuid>,
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
Json(request): Json<AddPropertyOptionRequest>,
) -> Result<(StatusCode, Json<PropertyOption>), AddPropertyOptionErr> {
tracing::info!("adding property option");
@@ -193,14 +201,18 @@ impl IntoResponse for UpdatePropertyOptionErr {
tags = ["Properties"]
)]
#[tracing::instrument(skip(state, user, team), fields(property_id = %def_uuid, option_id = %option_uuid, request = ?request), err)]
-pub async fn update_property_option<S: PropertiesService, A: EntityAccessService>(
+pub async fn update_property_option<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path((def_uuid, option_uuid)): Path<(Uuid, Uuid)>,
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
Json(request): Json<UpdatePropertyOptionRequest>,
) -> Result<(StatusCode, Json<PropertyOption>), UpdatePropertyOptionErr> {
let updated = state
@@ -259,14 +271,18 @@ impl IntoResponse for DeletePropertyOptionErr {
tag = "Properties"
)]
#[tracing::instrument(skip(state, user, team), err)]
-pub async fn delete_property_option<S: PropertiesService, A: EntityAccessService>(
+pub async fn delete_property_option<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
Path((def_uuid, option_uuid)): Path<(Uuid, Uuid)>,
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
) -> Result<StatusCode, DeletePropertyOptionErr> {
tracing::info!("deleting property option");
diff --git a/crates/properties/src/inbound/axum_router/tags.rs b/crates/properties/src/inbound/axum_router/tags.rs
index 2dca32f49d..903ac52cbe 100644
--- a/crates/properties/src/inbound/axum_router/tags.rs
+++ b/crates/properties/src/inbound/axum_router/tags.rs
@@ -6,7 +6,7 @@ use axum::{
response::{IntoResponse, Response},
};
use entity_access::domain::ports::EntityAccessService;
-use model::user::axum_extractor::MacroUserExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
use models_properties::api::{PropertyDefinitionDetailResponse, PropertyOptionResponse};
use serde::{Deserialize, Serialize};
use thiserror::Error;
@@ -103,13 +103,17 @@ impl IntoResponse for TagsError {
tag = "Properties"
)]
#[tracing::instrument(skip(state, user, team), err)]
-pub async fn list_tags<S: PropertiesService, A: EntityAccessService>(
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+pub async fn list_tags<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
) -> Result<Json<Vec<TagSetResponse>>, TagsError> {
let sets = state
.properties_service
@@ -133,13 +137,17 @@ pub async fn list_tags<S: PropertiesService, A: EntityAccessService>(
tag = "Properties"
)]
#[tracing::instrument(skip(state, user, team), fields(scope = ?request.scope), err)]
-pub async fn ensure_tag_set<S: PropertiesService, A: EntityAccessService>(
- State(state): State<PropertiesRouterState<S, A>>,
- MacroUserExtractor {
+pub async fn ensure_tag_set<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
macro_user_id: user,
..
- }: MacroUserExtractor,
- team: PropertyTeamExtractor<A>,
+ }: MacroAuthorizationExtractor<Auth>,
+ team: PropertyTeamExtractor<A, Auth>,
Json(request): Json<EnsureTagSetRequest>,
) -> Result<Json<TagSetResponse>, TagsError> {
let set = state
diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rs
new file mode 100644
index 0000000000..e3d4be148b
--- /dev/null
+++ b/crates/properties/src/inbound/axum_router/test.rs
@@ -0,0 +1,461 @@
+use std::sync::{Arc, Mutex};
+
+use axum::{
+ Router,
+ body::{Body, to_bytes},
+ http::{Request, StatusCode, header},
+ routing::get,
+};
+use entity_access::domain::{
+ models::{
+ AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessAuth, EntityAccessReceipt,
+ EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+ },
+ ports::EntityAccessService,
+};
+#[allow(deprecated)]
+use macro_authorization::{
+ INTERNAL_API_KEY_HEADER, InternalAuthConfig, JwtValidator, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
+ MacroAuthorizationError, MacroAuthorizationExtractor, MacroAuthorizationServiceImpl,
+ MacroAuthorizationState, ValidatedIdentity,
+};
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+use rootcause::Report;
+use tower::ServiceExt;
+use uuid::Uuid;
+
+use super::{
+ PropertiesRouterState, PropertyTeamExtractor,
+ extract::{EditReceiptExtractor, ViewReceiptExtractor},
+};
+use crate::{
+ PropertiesServiceImpl,
+ domain::ports::{MockNotificationService, MockPermissionService, MockPropertiesRepo},
+};
+
+const DEFAULT_INTERNAL_USER_ID: &str = "macro|[email protected]";
+const INTERNAL_API_KEY: &str = "test-internal-key";
+const ORGANIZATION_ID: i32 = 42;
+const VALID_USER_ID: &str = "macro|[email protected]";
+
+type TestPropertiesService =
+ PropertiesServiceImpl<MockPropertiesRepo, MockPermissionService, MockNotificationService>;
+type TestAuthorizationService = MacroAuthorizationServiceImpl<FakeJwtValidator>;
+
+#[derive(Clone, Debug, PartialEq)]
+enum AccessCall {
+ GenerateReceipt {
+ user_id: String,
+ organization_id: Option<i64>,
+ entity_id: String,
+ entity_type: EntityType,
+ },
+ PublicAccess {
+ entity_id: String,
+ entity_type: EntityType,
+ required_level: AccessLevel,
+ },
+ UserTeam {
+ user_id: String,
+ },
+}
+
+#[derive(Clone, Debug, Default)]
+struct FakeEntityAccessService {
+ calls: Arc<Mutex<Vec<AccessCall>>>,
+}
+
+impl FakeEntityAccessService {
+ fn calls(&self) -> Vec<AccessCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+
+ fn record(&self, call: AccessCall) {
+ self.calls.lock().expect("calls lock poisoned").push(call);
+ }
+}
+
+impl EntityAccessService for FakeEntityAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ user_org_id: Option<i64>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ self.record(AccessCall::GenerateReceipt {
+ user_id: user_id.as_ref().to_string(),
+ organization_id: user_org_id,
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+
+ let user_id = MacroUserIdStr::try_from(user_id.as_ref().to_string())
+ .expect("authorized test user id should be valid");
+ Ok(EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user_id,
+ entity_id,
+ entity_type,
+ ))
+ }
+
+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _bot_id: BotId,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ panic!("unexpected bot receipt request")
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ panic!("unexpected access-level request")
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected authenticated access check")
+ }
+
+ async fn check_public_access(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ self.record(AccessCall::PublicAccess {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ required_level,
+ });
+ Ok(AccessLevel::View)
+ }
+
+ 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> {
+ panic!("unexpected entity-permission request")
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<(EntityPermission, Uuid), AccessError> {
+ panic!("unexpected CRM permission request")
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ panic!("unexpected entity-users request")
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected call-channel request")
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected channel-call request")
+ }
+
+ async fn get_user_team(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ self.record(AccessCall::UserTeam {
+ user_id: user_id.as_ref().to_string(),
+ });
+ Ok(None)
+ }
+}
+
+#[derive(Clone, Copy)]
+struct FakeJwtValidator;
+
+impl JwtValidator for FakeJwtValidator {
+ fn validate(&self, jwt: &str) -> Result<ValidatedIdentity, Report<MacroAuthorizationError>> {
+ match jwt {
+ "valid" => Ok(ValidatedIdentity {
+ user_id: VALID_USER_ID.to_string(),
+ fusion_user_id: "fusion-valid-user".to_string(),
+ organization_id: Some(ORGANIZATION_ID),
+ permissions: None,
+ }),
+ "expired" => Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+}
+
+fn no_op_properties_service() -> TestPropertiesService {
+ PropertiesServiceImpl::new(
+ MockPropertiesRepo::new(),
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ )
+}
+
+fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
+ let service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator,
+ InternalAuthConfig {
+ api_key: INTERNAL_API_KEY.to_string(),
+ default_user_id: Some(DEFAULT_INTERNAL_USER_ID.to_string()),
+ },
+ );
+ MacroAuthorizationState::new(Arc::new(service))
+}
+
+fn test_router(entity_access_service: FakeEntityAccessService) -> Router {
+ let state = PropertiesRouterState::new(
+ Arc::new(no_op_properties_service()),
+ Arc::new(entity_access_service),
+ authorization_state(),
+ );
+
+ Router::new()
+ .route("/required", get(required_auth_handler))
+ .route("/team", get(team_handler))
+ .route("/view/{entity_type}/{entity_id}", get(view_handler))
+ .route("/edit/{entity_type}/{entity_id}", get(edit_handler))
+ .with_state(state)
+}
+
+async fn required_auth_handler(
+ authorization: MacroAuthorizationExtractor<TestAuthorizationService>,
+) -> String {
+ authorization.macro_user_id.to_string()
+}
+
+async fn team_handler(
+ team: PropertyTeamExtractor<FakeEntityAccessService, TestAuthorizationService>,
+) -> &'static str {
+ if team.entity_access_receipt.is_some() {
+ "team"
+ } else {
+ "no-team"
+ }
+}
+
+async fn view_handler(ViewReceiptExtractor(receipt): ViewReceiptExtractor) -> &'static str {
+ match receipt.auth() {
+ EntityAccessAuth::Authenticated(_) => "authenticated",
+ EntityAccessAuth::Unauthenticated => "unauthenticated",
+ EntityAccessAuth::Bot(_) => "bot",
+ EntityAccessAuth::Internal => "internal",
+ }
+}
+
+async fn edit_handler(EditReceiptExtractor(_receipt): EditReceiptExtractor) -> StatusCode {
+ StatusCode::OK
+}
+
+fn request(uri: &str) -> Request<Body> {
+ Request::builder()
+ .uri(uri)
+ .body(Body::empty())
+ .expect("request should be valid")
+}
+
+fn bearer_request(uri: &str, token: &str) -> Request<Body> {
+ Request::builder()
+ .uri(uri)
+ .header(header::AUTHORIZATION, format!("Bearer {token}"))
+ .body(Body::empty())
+ .expect("request should be valid")
+}
+
+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 required_auth_rejects_bad_credentials_and_accepts_valid_bearer() {
+ let router = test_router(FakeEntityAccessService::default());
+
+ let response = router
+ .clone()
+ .oneshot(request("/required"))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"unauthorized"}"#
+ );
+
+ let response = router
+ .clone()
+ .oneshot(bearer_request("/required", "invalid"))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"unauthorized"}"#
+ );
+
+ let response = router
+ .clone()
+ .oneshot(bearer_request("/required", "expired"))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"jwt expired"}"#
+ );
+
+ let response = router
+ .oneshot(bearer_request("/required", "valid"))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, VALID_USER_ID);
+}
+
+#[tokio::test]
+async fn property_team_extractor_uses_authorized_user() {
+ let entity_access_service = FakeEntityAccessService::default();
+ let response = test_router(entity_access_service.clone())
+ .oneshot(bearer_request("/team", "valid"))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "no-team");
+ assert_eq!(
+ entity_access_service.calls(),
+ [AccessCall::UserTeam {
+ user_id: VALID_USER_ID.to_string(),
+ }]
+ );
+}
+
+#[allow(deprecated)]
+#[tokio::test]
+async fn standard_and_legacy_internal_headers_use_the_default_user() {
+ for key_header in [INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_API_KEY_HEADER] {
+ let request = Request::builder()
+ .uri("/required")
+ .header(key_header, INTERNAL_API_KEY)
+ .body(Body::empty())
+ .expect("request should be valid");
+ let response = test_router(FakeEntityAccessService::default())
+ .oneshot(request)
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, DEFAULT_INTERNAL_USER_ID);
+ }
+}
+
+#[tokio::test]
+async fn anonymous_view_mints_public_receipt_but_invalid_token_is_rejected() {
+ let entity_access_service = FakeEntityAccessService::default();
+ let router = test_router(entity_access_service.clone());
+
+ let response = router
+ .clone()
+ .oneshot(request("/view/DOCUMENT/public-document"))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "unauthenticated");
+ assert_eq!(
+ entity_access_service.calls(),
+ [AccessCall::PublicAccess {
+ entity_id: "public-document".to_string(),
+ entity_type: EntityType::Document,
+ required_level: AccessLevel::View,
+ }]
+ );
+
+ let response = router
+ .oneshot(bearer_request("/view/DOCUMENT/public-document", "invalid"))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(response_body(response).await, "unauthorized");
+ assert_eq!(
+ entity_access_service.calls().len(),
+ 1,
+ "invalid credentials must not fall back to public authorization"
+ );
+}
+
+#[tokio::test]
+async fn edit_receipt_omits_organization_from_access_check() {
+ let entity_access_service = FakeEntityAccessService::default();
+ let response = test_router(entity_access_service.clone())
+ .oneshot(bearer_request("/edit/DOCUMENT/document-id", "valid"))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ entity_access_service.calls(),
+ [AccessCall::GenerateReceipt {
+ user_id: VALID_USER_ID.to_string(),
+ organization_id: None,
+ entity_id: "document-id".to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn receipt_rejection_preserves_expired_token_message() {
+ let response = test_router(FakeEntityAccessService::default())
+ .oneshot(bearer_request("/edit/DOCUMENT/document-id", "expired"))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(response_body(response).await, "jwt expired");
+}
+
+#[tokio::test]
+async fn malformed_typed_path_is_rejected_before_missing_authentication() {
+ let response = test_router(FakeEntityAccessService::default())
+ .oneshot(request("/edit/not-an-entity/document-id"))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ response_body(response).await,
+ "Missing or invalid entity_type / entity_id in path"
+ );
+}
diff --git a/crates/properties_service/Cargo.toml b/crates/properties_service/Cargo.toml
index 01e81bb417..aa7684a23c 100644
--- a/crates/properties_service/Cargo.toml
+++ b/crates/properties_service/Cargo.toml
@@ -15,10 +15,7 @@ path = "src/openapi.rs"
[dependencies]
axum = { workspace = true, features = ["tower-log", "ws"] }
entity_access = { path = "../entity_access" }
-macro_middleware = { path = "../macro_middleware", default-features = false, features = [
- "auth",
- "cloud_storage",
-] }
+macro_authorization = { path = "../macro_authorization" }
models_properties = { path = "../models_properties" }
notification = { path = "../notification" }
properties = { path = "../properties" }
diff --git a/crates/properties_service/src/api/context.rs b/crates/properties_service/src/api/context.rs
index 4b4c46d6e6..ce836453af 100644
--- a/crates/properties_service/src/api/context.rs
+++ b/crates/properties_service/src/api/context.rs
@@ -1,4 +1,5 @@
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use macro_authorization::{MacroAuthJwtValidator, MacroAuthorizationServiceImpl};
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
@@ -11,6 +12,9 @@ type NotificationIngressType = SqsNotificationIngress<SqsQueue>;
/// Type alias for the entity access service.
pub type EntityAccessServiceType = EntityAccessServiceImpl<PgAccessRepository>;
+/// Type alias for the request authorization service.
+pub type AuthorizationServiceType = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
+
/// Type alias for the properties service implementation used throughout the service.
pub type PropertiesService = PropertiesServiceImpl<
properties::PropertiesPgRepo,
@@ -19,4 +23,5 @@ pub type PropertiesService = PropertiesServiceImpl<
>;
/// Minimal state required by properties handlers.
-pub type PropertiesHandlerState = PropertiesRouterState<PropertiesService, EntityAccessServiceType>;
+pub type PropertiesHandlerState =
+ PropertiesRouterState<PropertiesService, EntityAccessServiceType, AuthorizationServiceType>;
diff --git a/crates/properties_service/src/api/mod.rs b/crates/properties_service/src/api/mod.rs
index 55e5108816..7bafbea7e7 100644
--- a/crates/properties_service/src/api/mod.rs
+++ b/crates/properties_service/src/api/mod.rs
@@ -5,10 +5,7 @@ use axum::Router;
use crate::api::context::PropertiesHandlerState;
-/// Creates the properties router with the service's authentication middleware
-/// applied to every route that requires an authenticated user.
+/// Creates the properties router backed by the request authorization service.
pub fn router() -> Router<PropertiesHandlerState> {
- properties::inbound::axum_router::router(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- ))
+ properties::inbound::axum_router::router()
}
diff --git a/crates/properties_service/src/lib.rs b/crates/properties_service/src/lib.rs
index 0314d3162e..604e5558ba 100644
--- a/crates/properties_service/src/lib.rs
+++ b/crates/properties_service/src/lib.rs
@@ -1,12 +1,13 @@
//! Properties Service Library - exposes API routes for integration into other services
//!
//! The routes themselves live in `properties::inbound::axum_router`; this crate
-//! is the composition shim binding them to the concrete service types and the
-//! service's authentication middleware.
+//! is the composition shim binding them to the concrete domain and request
+//! authorization service types.
pub mod api;
// Re-exports for consumers
+pub use api::context::AuthorizationServiceType;
pub use api::context::EntityAccessServiceType;
pub use api::context::PropertiesHandlerState;
pub use api::context::PropertiesService;
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index de8ecd5437..541123336a 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -449,6 +449,7 @@ impl From<&ApiContext> for PropertiesHandlerState {
PropertiesHandlerState::new(
ctx.properties_service.clone(),
ctx.entity_access_service.clone(),
+ ctx.authorization_state.clone(),
)
}
}