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(dcs): use macro_authorization (#4942)

Will Hutchinsonb5271ad6f87a
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 4fa44b2c39..2f221f72cd 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -7,14 +7,19 @@
"crates/ai_usage",
"crates/attachment",
"crates/cowlike",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
"crates/macro_uuid",
"crates/model-entity",
+ "crates/model-error-response",
"crates/model_file_type",
"crates/model_user",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/workspace-hack"
],
"ai_projections": [
@@ -295,9 +300,15 @@
"ai_usage": [
"crates/ai_usage",
"crates/cowlike",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
+ "crates/macro_env_var",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/model-error-response",
"crates/model_user",
+ "crates/remote_env_var",
"crates/workspace-hack"
],
"analytics_client": [
@@ -441,6 +452,9 @@
"crates/authentication_service_client",
"crates/cowlike",
"crates/document_sub_type",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -454,6 +468,7 @@
"crates/models_permissions",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/workspace-hack"
],
"bot_id": [
@@ -1606,6 +1621,9 @@
"crates/cowlike",
"crates/document_storage_service_client",
"crates/document_sub_type",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -1619,6 +1637,7 @@
"crates/models_permissions",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/workspace-hack"
],
"document_sub_type": [
@@ -1632,6 +1651,8 @@
"crates/attachment",
"crates/cowlike",
"crates/document_sub_type",
+ "crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_aws_config",
"crates/macro_entrypoint",
"crates/macro_env",
@@ -1648,6 +1669,7 @@
"crates/models_permissions",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/s3_key",
"crates/workspace-hack",
"services/document_text_extractor"
@@ -2333,6 +2355,8 @@
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
+ "crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_db_client",
"crates/macro_entrypoint",
"crates/macro_env",
@@ -2354,6 +2378,7 @@
"crates/models_team",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/system_properties",
"crates/user_quota",
"crates/workspace-hack",
@@ -3156,7 +3181,10 @@
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
+ "crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_db_client",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -3175,6 +3203,7 @@
"crates/models_team",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/system_properties",
"crates/user_quota",
"crates/workspace-hack"
@@ -3220,6 +3249,7 @@
"crates/entity_access_db_utils",
"crates/ip_extractor",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_db_client",
"crates/macro_env",
"crates/macro_env_var",
@@ -3328,6 +3358,9 @@
"crates/attachment",
"crates/cowlike",
"crates/document_sub_type",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_sha_count_client",
"crates/macro_user_id",
@@ -3342,6 +3375,7 @@
"crates/models_permissions",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/workspace-hack"
],
"macro_sync_service_jwt": [
@@ -3380,6 +3414,9 @@
"crates/ai_usage",
"crates/attachment",
"crates/cowlike",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -3390,6 +3427,7 @@
"crates/model_user",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/workspace-hack"
],
"mcp_service": [
@@ -3622,6 +3660,9 @@
"crates/attachment",
"crates/cowlike",
"crates/document_sub_type",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -3635,6 +3676,7 @@
"crates/models_permissions",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/workspace-hack"
],
"model-entity": [
@@ -3996,6 +4038,7 @@
"crates/ip_extractor",
"crates/last_online_tracker",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_aws_config",
"crates/macro_config",
"crates/macro_config_derive",
@@ -5065,6 +5108,9 @@
"crates/attachment",
"crates/cowlike",
"crates/document_sub_type",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -5078,6 +5124,7 @@
"crates/models_permissions",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/sync_service",
"crates/sync_service_client",
"crates/workspace-hack"
@@ -5392,6 +5439,8 @@
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
+ "crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_db_client",
"crates/macro_entrypoint",
"crates/macro_env",
@@ -5413,6 +5462,7 @@
"crates/models_team",
"crates/non_empty",
"crates/prompt",
+ "crates/remote_env_var",
"crates/system_properties",
"crates/user_quota",
"crates/workspace-hack",
diff --git a/Cargo.lock b/Cargo.lock
index da06935c85..1459d4c1da 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -117,12 +117,14 @@ dependencies = [
"connection_gateway_client",
"futures",
"http-body-util",
+ "macro_authorization",
"macro_db_migrator",
"macro_user_id",
"model-entity",
"model-error-response",
"model_user",
"models_ai_projection",
+ "rootcause",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -271,10 +273,10 @@ dependencies = [
"anyhow",
"axum",
"chrono",
+ "macro_authorization",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
- "model_user",
"serde",
"serde_json",
"sqlx",
@@ -2650,16 +2652,17 @@ dependencies = [
"entity_access_management",
"futures",
"http-body-util",
+ "macro_authorization",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
"model",
"model-entity",
- "model_user",
"models_entity_access_management",
"models_permissions",
"non_empty",
"roles_and_permissions",
+ "rootcause",
"schemars 1.2.1",
"serde",
"serde_json",
@@ -4119,6 +4122,7 @@ dependencies = [
"lexical_client",
"log",
"macro_auth",
+ "macro_authorization",
"macro_aws_config",
"macro_config",
"macro_cors",
@@ -8648,10 +8652,10 @@ dependencies = [
"axum",
"base64 0.22.1",
"futures",
+ "macro_authorization",
"macro_env_var",
"macro_user_id",
"model-error-response",
- "model_user",
"oauth2",
"redis",
"reqwest 0.13.4",
@@ -8778,6 +8782,7 @@ dependencies = [
"frecency",
"futures",
"lexical_client",
+ "macro_authorization",
"macro_aws_config",
"macro_db_migrator",
"macro_entrypoint",
@@ -8785,7 +8790,6 @@ dependencies = [
"macro_env_var",
"macro_user_id",
"macro_uuid",
- "model_user",
"notification",
"readonly_pool",
"search_service_client",
diff --git a/crates/ai_projections/Cargo.toml b/crates/ai_projections/Cargo.toml
index 9a4b62786d..af6e517507 100644
--- a/crates/ai_projections/Cargo.toml
+++ b/crates/ai_projections/Cargo.toml
@@ -7,8 +7,8 @@ version = "0.1.0"
[features]
axum = [
"dep:axum",
+ "dep:macro_authorization",
"dep:model-error-response",
- "dep:model_user",
"dep:utoipa",
]
default = ["axum", "inbound", "outbound", "ports", "worker"]
@@ -56,8 +56,10 @@ tokio = { workspace = true, optional = true }
# Axum dependencies (for inbound)
axum = { workspace = true, optional = true }
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = [
+ "axum",
+] }
model-error-response = { path = "../model-error-response", optional = true }
-model_user = { path = "../model_user", optional = true, features = ["axum"] }
utoipa = { workspace = true, optional = true }
# Outbound dependencies
@@ -82,6 +84,8 @@ futures = { workspace = true, optional = true }
[dev-dependencies]
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
+model_user = { path = "../model_user" }
+rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
diff --git a/crates/ai_projections/src/inbound/axum_router/mod.rs b/crates/ai_projections/src/inbound/axum_router/mod.rs
index a5bc664fd7..4e7bbbd5cd 100644
--- a/crates/ai_projections/src/inbound/axum_router/mod.rs
+++ b/crates/ai_projections/src/inbound/axum_router/mod.rs
@@ -10,10 +10,12 @@ use std::sync::Arc;
use axum::{
Json, Router,
+ extract::FromRef,
http::StatusCode,
response::{IntoResponse, Response},
routing::post,
};
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
use model_error_response::ErrorResponse;
use crate::domain::{
@@ -21,29 +23,43 @@ use crate::domain::{
model::{AiProjectionError, UpsertProjectionError},
};
-/// Router state containing the ai projection service.
-pub struct AiProjectionRouterState<T> {
+/// Router state containing the ai projection service and the authorization
+/// state used to authenticate callers.
+pub struct AiProjectionRouterState<T, Auth> {
/// The ai projection service implementation.
pub service: Arc<T>,
+ /// The authorization state used by the request extractors.
+ pub authorization_state: MacroAuthorizationState<Auth>,
}
// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).
-impl<T> Clone for AiProjectionRouterState<T> {
+impl<T, Auth> Clone for AiProjectionRouterState<T, Auth> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
+ authorization_state: self.authorization_state.clone(),
}
}
}
+impl<T, Auth> FromRef<AiProjectionRouterState<T, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &AiProjectionRouterState<T, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
/// Build the ai projections router with all endpoints.
-pub fn ai_projections_router<T, S>(state: AiProjectionRouterState<T>) -> Router<S>
+pub fn ai_projections_router<T, Auth, S>(state: AiProjectionRouterState<T, Auth>) -> Router<S>
where
T: AiProjectionService,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
Router::new()
- .route("/ai-projections", post(upsert_projection::handler::<T>))
+ .route(
+ "/ai-projections",
+ post(upsert_projection::handler::<T, Auth>),
+ )
.with_state(state)
}
diff --git a/crates/ai_projections/src/inbound/axum_router/test.rs b/crates/ai_projections/src/inbound/axum_router/test.rs
index 8b4c97c03d..dbe7c3715b 100644
--- a/crates/ai_projections/src/inbound/axum_router/test.rs
+++ b/crates/ai_projections/src/inbound/axum_router/test.rs
@@ -2,10 +2,18 @@
use std::sync::{Arc, Mutex};
-use axum::{Extension, http::StatusCode};
+use axum::{
+ body::Body,
+ http::{Request, StatusCode, header},
+};
use http_body_util::BodyExt;
+use macro_authorization::{
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+ MacroAuthorizationState,
+};
use macro_user_id::user_id::MacroUserIdStr;
use model_user::UserContext;
+use rootcause::Report;
use tower::ServiceExt;
use super::{AiProjectionRouterState, ai_projections_router};
@@ -17,6 +25,39 @@ use crate::domain::{
},
};
+/// Fake authorization service accepting the `valid` bearer token as the test
+/// user.
+#[derive(Clone)]
+struct FakeAuthorizationService;
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ if jwt != "valid" {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(test_user_context())
+ }
+
+ async fn authorize_internal(
+ &self,
+ _provided_key: &str,
+ _claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+
+/// Attaches the test user's bearer token to every request, mirroring the
+/// credentials a real client would send.
+async fn attach_bearer(mut req: Request<Body>) -> Request<Body> {
+ req.headers_mut().insert(
+ header::AUTHORIZATION,
+ "Bearer valid".parse().expect("header should be valid"),
+ );
+ req
+}
+
#[derive(Clone, Default)]
struct MockService {
has_permission: bool,
@@ -75,8 +116,11 @@ fn build_router(has_permission: bool) -> axum::Router {
}
fn build_router_with(service: Arc<MockService>) -> axum::Router {
- let state = AiProjectionRouterState { service };
- ai_projections_router(state).layer(Extension(test_user_context()))
+ let state = AiProjectionRouterState {
+ service,
+ authorization_state: MacroAuthorizationState::new(Arc::new(FakeAuthorizationService)),
+ };
+ ai_projections_router(state).layer(axum::middleware::map_request(attach_bearer))
}
fn post_request() -> axum::http::Request<axum::body::Body> {
diff --git a/crates/ai_projections/src/inbound/axum_router/upsert_projection.rs b/crates/ai_projections/src/inbound/axum_router/upsert_projection.rs
index 354c9645ec..ff2aa93269 100644
--- a/crates/ai_projections/src/inbound/axum_router/upsert_projection.rs
+++ b/crates/ai_projections/src/inbound/axum_router/upsert_projection.rs
@@ -3,7 +3,7 @@
use axum::{Json, extract::State};
use chrono::{DateTime, Utc};
-use model_user::axum_extractor::MacroUserExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
use crate::domain::{
ai_projection_service::{AiProjectionService, requires_professional_features},
@@ -96,9 +96,9 @@ impl From<UserAiProjection> for ProjectionStateResponse {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: AiProjectionService>(
- State(state): State<AiProjectionRouterState<T>>,
- user: MacroUserExtractor,
+pub async fn handler<T: AiProjectionService, Auth: MacroAuthorizationService>(
+ State(state): State<AiProjectionRouterState<T, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<UpsertProjectionRequest>,
) -> Result<Json<ProjectionStateResponse>, UpsertProjectionError> {
// Free-tier models are available to everyone; anything else (including
diff --git a/crates/ai_usage/Cargo.toml b/crates/ai_usage/Cargo.toml
index bb92e90c12..786cea672d 100644
--- a/crates/ai_usage/Cargo.toml
+++ b/crates/ai_usage/Cargo.toml
@@ -8,9 +8,11 @@ version = "0.1.0"
anyhow = { workspace = true }
axum = { workspace = true }
chrono = { workspace = true }
+macro_authorization = { path = "../macro_authorization", default-features = false, features = [
+ "axum",
+] }
macro_user_id = { path = "../macro_user_id", features = ["schema"] }
macro_uuid = { path = "../macro_uuid" }
-model_user = { path = "../model_user", features = ["axum"] }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/crates/ai_usage/src/inbound.rs b/crates/ai_usage/src/inbound.rs
index caa1157629..0b0cc8e0f4 100644
--- a/crates/ai_usage/src/inbound.rs
+++ b/crates/ai_usage/src/inbound.rs
@@ -2,4 +2,4 @@
pub mod axum_router;
-pub use axum_router::ai_usage_router;
+pub use axum_router::{AiUsageRouterState, ai_usage_router};
diff --git a/crates/ai_usage/src/inbound/axum_router.rs b/crates/ai_usage/src/inbound/axum_router.rs
index cb27ca6d20..b88537b811 100644
--- a/crates/ai_usage/src/inbound/axum_router.rs
+++ b/crates/ai_usage/src/inbound/axum_router.rs
@@ -6,14 +6,16 @@
use crate::domain::{AiFeature, UsageApiParams, UsageService, UsageSummary};
use axum::{
Json, Router,
- extract::State,
+ extract::{FromRef, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::post,
};
use chrono::{DateTime, Utc};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
use macro_user_id::user_id::MacroUserIdStr;
-use model_user::axum_extractor::MacroUserExtractor;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use utoipa::ToSchema;
@@ -54,20 +56,52 @@ pub struct ErrorBody {
pub error: String,
}
+/// Router state containing the usage service and the authorization state used
+/// to authenticate callers.
+pub struct AiUsageRouterState<T, Auth> {
+ /// The usage service implementation.
+ pub service: Arc<T>,
+ /// The authorization state used by the request extractors.
+ pub authorization_state: MacroAuthorizationState<Auth>,
+}
+
+// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).
+impl<T, Auth> Clone for AiUsageRouterState<T, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<T, Auth> FromRef<AiUsageRouterState<T, Auth>> for Arc<T> {
+ fn from_ref(state: &AiUsageRouterState<T, Auth>) -> Self {
+ state.service.clone()
+ }
+}
+
+impl<T, Auth> FromRef<AiUsageRouterState<T, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &AiUsageRouterState<T, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
/// Build the admin AI-cost router.
-pub fn ai_usage_router<T, S>(service: Arc<T>) -> Router<S>
+pub fn ai_usage_router<T, Auth, S>(state: AiUsageRouterState<T, Auth>) -> Router<S>
where
T: UsageService,
+ Auth: MacroAuthorizationService,
S: Send + Sync + Clone + 'static,
{
Router::new()
- .route("/ai-cost/usage", post(get_usage_handler::<T>))
- .route("/ai-cost/pricing", post(set_pricing_handler::<T>))
- .with_state(service)
+ .route("/ai-cost/usage", post(get_usage_handler::<T, Auth>))
+ .route("/ai-cost/pricing", post(set_pricing_handler::<T, Auth>))
+ .with_state(state)
}
/// Returns `Some(403)` unless the caller is a Macro admin.
-fn admin_rejection(user: &MacroUserExtractor) -> Option<Response> {
+fn admin_rejection<Auth>(user: &MacroAuthorizationExtractor<Auth>) -> Option<Response> {
if user.macro_user_id.email_str().ends_with(ADMIN_EMAIL_SUFFIX) {
None
} else {
@@ -107,9 +141,9 @@ fn internal_error(context: &str) -> Response {
tag = "ai_usage"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
-pub async fn get_usage_handler<T: UsageService>(
+pub async fn get_usage_handler<T: UsageService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroUserExtractor,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<UsageRequest>,
) -> Response {
if let Some(resp) = admin_rejection(&user) {
@@ -163,9 +197,9 @@ pub async fn get_usage_handler<T: UsageService>(
tag = "ai_usage"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
-pub async fn set_pricing_handler<T: UsageService>(
+pub async fn set_pricing_handler<T: UsageService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroUserExtractor,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<SetPricingRequest>,
) -> Response {
if let Some(resp) = admin_rejection(&user) {
diff --git a/crates/chat/Cargo.toml b/crates/chat/Cargo.toml
index aab96af1c0..0470705f29 100644
--- a/crates/chat/Cargo.toml
+++ b/crates/chat/Cargo.toml
@@ -13,7 +13,7 @@ attachment = [
]
inbound = [
"dep:axum",
- "dep:model_user",
+ "dep:macro_authorization",
"dep:roles_and_permissions",
"entity_access/inbound",
"ports",
@@ -56,8 +56,12 @@ schemars = { workspace = true, optional = true }
# Inbound (HTTP handlers)
axum = { workspace = true, optional = true }
-model_user = { path = "../model_user", optional = true }
-roles_and_permissions = { path = "../roles_and_permissions", optional = true, default-features = false }
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = [
+ "axum",
+] }
+roles_and_permissions = { path = "../roles_and_permissions", optional = true, default-features = false, features = [
+ "ports",
+] }
utoipa = { workspace = true }
# Outbound (database adapters)
@@ -69,6 +73,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
+rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
diff --git a/crates/chat/src/inbound/http/extractors.rs b/crates/chat/src/inbound/http/extractors.rs
index 17b61986a4..99989204ad 100644
--- a/crates/chat/src/inbound/http/extractors.rs
+++ b/crates/chat/src/inbound/http/extractors.rs
@@ -1,25 +1,53 @@
//! Axum extractors for chat inbound handlers.
+use std::collections::HashSet;
+use std::marker::PhantomData;
+use std::sync::Arc;
+
use crate::domain::ports::ModelAccessService;
use crate::domain::service::ModelAccessServiceImpl;
-use axum::extract::FromRequestParts;
+use axum::extract::{FromRef, FromRequestParts};
use axum::http::StatusCode;
use axum::http::request::Parts;
use axum::response::IntoResponse;
-use model::user::UserContext;
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationService,
+ MacroAuthorizationState,
+};
use roles_and_permissions::domain::model::PermissionId;
+use roles_and_permissions::domain::port::UserRolesAndPermissionsService;
+
+/// Axum sub-state carrying the roles-and-permissions service used by
+/// [`ChatModelAccess`].
+///
+/// A newtype (rather than a bare `Arc<P>` bound) so router states can expose
+/// it via `FromRef` without colliding with other `Arc`-typed sub-states.
+pub struct UserPermissionsState<P>(pub Arc<P>);
+
+impl<P> Clone for UserPermissionsState<P> {
+ fn clone(&self) -> Self {
+ Self(Arc::clone(&self.0))
+ }
+}
/// Axum extractor resolving the requesting user's model entitlement from their
/// permissions.
///
/// Free users may use only [`FREE_MODEL`] (Haiku); professional (paid) users
/// may use every chat model. Backed by [`ModelAccessServiceImpl`].
+///
+/// Type parameter `Auth` is the authorization service implementation and `P`
+/// is the roles-and-permissions service used to look up the caller's
+/// permissions.
+///
+/// [`FREE_MODEL`]: crate::domain::models::FREE_MODEL
#[derive(Debug, Clone, Copy)]
-pub struct ChatModelAccess {
+pub struct ChatModelAccess<Auth, P> {
professional: bool,
+ _marker: PhantomData<fn() -> (Auth, P)>,
}
-impl ChatModelAccess {
+impl<Auth, P> ChatModelAccess<Auth, P> {
/// Whether the user holds the professional (paid) entitlement.
pub fn professional(&self) -> bool {
self.professional
@@ -39,39 +67,58 @@ impl ChatModelAccess {
/// Whether the user holds the professional (paid) entitlement, derived from the
/// existing roles-and-permissions access API.
-fn is_professional(user: &UserContext) -> bool {
- user.permissions
- .as_ref()
- .is_some_and(|perms| perms.contains(&PermissionId::ReadProfessionalFeatures.to_string()))
+fn is_professional(permissions: &HashSet<PermissionId>) -> bool {
+ permissions.contains(&PermissionId::ReadProfessionalFeatures)
}
/// Error returned when [`ChatModelAccess`] cannot be extracted.
pub enum ChatModelAccessRejection {
- /// The `UserContext` extension was missing (middleware not applied).
- MissingUserContext,
+ /// The caller's credentials were rejected by the authorization service.
+ Unauthorized(MacroAuthorizationRejection),
+ /// The caller's permissions could not be loaded.
+ PermissionsLookup,
}
impl IntoResponse for ChatModelAccessRejection {
fn into_response(self) -> axum::response::Response {
match self {
- Self::MissingUserContext => {
- (StatusCode::INTERNAL_SERVER_ERROR, "missing user context").into_response()
- }
+ Self::Unauthorized(rejection) => rejection.into_response(),
+ Self::PermissionsLookup => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "unable to load user permissions",
+ )
+ .into_response(),
}
}
}
-impl<S: Send + Sync> FromRequestParts<S> for ChatModelAccess {
+impl<S, Auth, P> FromRequestParts<S> for ChatModelAccess<Auth, P>
+where
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
+ UserPermissionsState<P>: FromRef<S>,
+ P: UserRolesAndPermissionsService,
+ S: Send + Sync + 'static,
+{
type Rejection = ChatModelAccessRejection;
- async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
- let user_context = parts
- .extensions
- .get::<UserContext>()
- .ok_or(ChatModelAccessRejection::MissingUserContext)?;
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let user = MacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ .await
+ .map_err(ChatModelAccessRejection::Unauthorized)?;
+
+ let UserPermissionsState(permissions_service) = UserPermissionsState::<P>::from_ref(state);
+ let permissions = permissions_service
+ .get_user_permissions(&user.macro_user_id)
+ .await
+ .map_err(|error| {
+ tracing::error!(error=?error, user_id = %user.macro_user_id, "unable to load user permissions");
+ ChatModelAccessRejection::PermissionsLookup
+ })?;
Ok(ChatModelAccess {
- professional: is_professional(user_context),
+ professional: is_professional(&permissions),
+ _marker: PhantomData,
})
}
}
@@ -81,27 +128,27 @@ mod test {
use super::*;
use crate::domain::models::FREE_MODEL;
- fn access(permissions: &[PermissionId]) -> ChatModelAccess {
+ fn access(permissions: &[PermissionId]) -> ChatModelAccess<(), ()> {
let professional = permissions.contains(&PermissionId::ReadProfessionalFeatures);
- ChatModelAccess { professional }
+ ChatModelAccess {
+ professional,
+ _marker: PhantomData,
+ }
}
- fn user(permissions: &[PermissionId]) -> UserContext {
- UserContext {
- permissions: Some(permissions.iter().map(ToString::to_string).collect()),
- ..Default::default()
- }
+ fn permissions(permissions: &[PermissionId]) -> HashSet<PermissionId> {
+ permissions.iter().cloned().collect()
}
#[test]
fn no_permissions_is_free() {
- assert!(!is_professional(&UserContext::default()));
- assert!(!is_professional(&user(&[])));
+ assert!(!is_professional(&HashSet::new()));
+ assert!(!is_professional(&permissions(&[])));
}
#[test]
fn professional_permission_is_professional() {
- assert!(is_professional(&user(&[
+ assert!(is_professional(&permissions(&[
PermissionId::ReadProfessionalFeatures
])));
}
diff --git a/crates/chat/src/inbound/http/router.rs b/crates/chat/src/inbound/http/router.rs
index 7e87d98569..66189fb663 100644
--- a/crates/chat/src/inbound/http/router.rs
+++ b/crates/chat/src/inbound/http/router.rs
@@ -12,44 +12,79 @@ use axum::{
use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::ChatAccessLevelExtractor;
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
use model::response::StringIDResponse;
-use model_user::axum_extractor::MacroUserExtractor;
use models_permissions::share_permission::SharePermissionV2;
+use roles_and_permissions::domain::port::UserRolesAndPermissionsService;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::domain::models::{CreateChatArgs, GetChatResponse, PatchChatArgs, Result};
use crate::domain::ports::ChatService;
-use crate::inbound::http::extractors::ChatModelAccess;
+use crate::inbound::http::extractors::{ChatModelAccess, UserPermissionsState};
-/// Shared state for the chat router, wrapping a [`ChatService`] implementation
-/// and an [`EntityAccessService`] for authorization.
-pub struct ChatRouterState<S, Svc> {
+/// Shared state for the chat router, wrapping a [`ChatService`] implementation,
+/// an [`EntityAccessService`] for entity authorization, a
+/// [`MacroAuthorizationService`] for caller authentication, and a
+/// [`UserRolesAndPermissionsService`] for model-entitlement lookups.
+pub struct ChatRouterState<S, Svc, Auth, P> {
inner: Arc<S>,
access_service: Arc<Svc>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ permissions_state: UserPermissionsState<P>,
}
-impl<S, Svc> Clone for ChatRouterState<S, Svc> {
+impl<S, Svc, Auth, P> Clone for ChatRouterState<S, Svc, Auth, P> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
access_service: Arc::clone(&self.access_service),
+ authorization_state: self.authorization_state.clone(),
+ permissions_state: self.permissions_state.clone(),
}
}
}
-impl<S, Svc> FromRef<ChatRouterState<S, Svc>> for Arc<Svc> {
- fn from_ref(state: &ChatRouterState<S, Svc>) -> Self {
+impl<S, Svc, Auth, P> FromRef<ChatRouterState<S, Svc, Auth, P>> for Arc<Svc> {
+ fn from_ref(state: &ChatRouterState<S, Svc, Auth, P>) -> Self {
state.access_service.clone()
}
}
-impl<S: ChatService, Svc: EntityAccessService> ChatRouterState<S, Svc> {
- /// Create a new [`ChatRouterState`] from a service and access service.
- pub fn new(service: S, access_service: Svc) -> Self {
+impl<S, Svc, Auth, P> FromRef<ChatRouterState<S, Svc, Auth, P>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &ChatRouterState<S, Svc, Auth, P>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+impl<S, Svc, Auth, P> FromRef<ChatRouterState<S, Svc, Auth, P>> for UserPermissionsState<P> {
+ fn from_ref(state: &ChatRouterState<S, Svc, Auth, P>) -> Self {
+ state.permissions_state.clone()
+ }
+}
+
+impl<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+> ChatRouterState<S, Svc, Auth, P>
+{
+ /// Create a new [`ChatRouterState`] from a service, access service,
+ /// authorization state, and roles-and-permissions service.
+ pub fn new(
+ service: S,
+ access_service: Svc,
+ authorization_state: MacroAuthorizationState<Auth>,
+ permissions_service: Arc<P>,
+ ) -> Self {
Self {
inner: Arc::new(service),
access_service: Arc::new(access_service),
+ authorization_state,
+ permissions_state: UserPermissionsState(permissions_service),
}
}
}
@@ -57,12 +92,18 @@ impl<S: ChatService, Svc: EntityAccessService> ChatRouterState<S, Svc> {
/// Build the router for the `POST /` create-chat route.
///
/// This is separated so that DCS can apply different middleware
-/// (e.g. `ensure_user_exists` + quota checks) without `ensure_chat_exists`.
-pub fn chat_create_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync + 'static>(
- state: ChatRouterState<S, Svc>,
+/// (e.g. quota checks) without `ensure_chat_exists`.
+pub fn chat_create_router<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+ T: Send + Sync + 'static,
+>(
+ state: ChatRouterState<S, Svc, Auth, P>,
) -> Router<T> {
Router::new()
- .route("/", post(create_chat_handler::<S, Svc>))
+ .route("/", post(create_chat_handler::<S, Svc, Auth, P>))
.with_state(state)
}
@@ -70,41 +111,53 @@ pub fn chat_create_router<S: ChatService, Svc: EntityAccessService, T: Send + Sy
///
/// These routes require `ensure_chat_exists` middleware to populate
/// `ChatBasic` in extensions before the [`ChatAccessLevelExtractor`] runs.
-pub fn chat_id_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync + 'static>(
- state: ChatRouterState<S, Svc>,
+pub fn chat_id_router<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+ T: Send + Sync + 'static,
+>(
+ state: ChatRouterState<S, Svc, Auth, P>,
) -> Router<T> {
Router::new()
.route(
"/{chat_id}",
- get(get_chat_handler::<S, Svc>)
- .delete(delete_chat_handler::<S, Svc>)
- .patch(patch_chat_handler::<S, Svc>),
+ get(get_chat_handler::<S, Svc, Auth, P>)
+ .delete(delete_chat_handler::<S, Svc, Auth, P>)
+ .patch(patch_chat_handler::<S, Svc, Auth, P>),
)
.route(
"/{chat_id}/permanent",
- delete(permanently_delete_chat_handler::<S, Svc>),
+ delete(permanently_delete_chat_handler::<S, Svc, Auth, P>),
+ )
+ .route(
+ "/{chat_id}/copy",
+ post(copy_chat_handler::<S, Svc, Auth, P>),
)
- .route("/{chat_id}/copy", post(copy_chat_handler::<S, Svc>))
.route(
"/{chat_id}/revert_delete",
- put(revert_delete_handler::<S, Svc>),
+ put(revert_delete_handler::<S, Svc, Auth, P>),
)
.route(
"/{chat_id}/permissions",
- get(get_chat_permissions_handler::<S, Svc>),
+ get(get_chat_permissions_handler::<S, Svc, Auth, P>),
)
.route(
"/{chat_id}/tool/update",
- post(update_tool_call_handler::<S, Svc>),
+ post(update_tool_call_handler::<S, Svc, Auth, P>),
)
.route(
"/{chat_id}/tool/response/update",
- post(update_tool_response_handler::<S, Svc>),
+ post(update_tool_response_handler::<S, Svc, Auth, P>),
+ )
+ .route(
+ "/{chat_id}/tool/call",
+ post(call_tool_handler::<S, Svc, Auth, P>),
)
- .route("/{chat_id}/tool/call", post(call_tool_handler::<S, Svc>))
.route(
"/{chat_id}/tool/reject",
- post(reject_tool_call_handler::<S, Svc>),
+ post(reject_tool_call_handler::<S, Svc, Auth, P>),
)
.with_state(state)
}
@@ -131,12 +184,17 @@ pub struct CreateChatRequest {
)
)]
/// Create a new chat.
-#[tracing::instrument(skip(state, user, req), fields(user_id = %user.macro_user_id), err(Debug))]
-pub async fn create_chat_handler<S: ChatService, Svc: EntityAccessService>(
- State(state): State<ChatRouterState<S, Svc>>,
- user: MacroUserExtractor,
+#[tracing::instrument(skip(state, user, _access, req), fields(user_id = %user.macro_user_id), err(Debug))]
+pub async fn create_chat_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
+ user: MacroAuthorizationExtractor<Auth>,
// 402 on no perms
- _model_access: ChatModelAccess,
+ _access: ChatModelAccess<Auth, P>,
Json(req): Json<CreateChatRequest>,
) -> Result<Json<StringIDResponse>> {
let id = state
@@ -168,9 +226,14 @@ pub async fn create_chat_handler<S: ChatService, Svc: EntityAccessService>(
)]
/// Get a chat by ID with messages and web citations.
#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
-pub async fn get_chat_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn get_chat_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<ViewAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
) -> Result<Json<GetChatResponse>> {
let response = state.inner.get_chat(access.entity_access_receipt).await?;
@@ -192,9 +255,14 @@ pub async fn get_chat_handler<S: ChatService, Svc: EntityAccessService>(
)]
/// Soft-delete a chat.
#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
-pub async fn delete_chat_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn delete_chat_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
) -> Result<StatusCode> {
state.inner.delete(access.entity_access_receipt).await?;
@@ -215,9 +283,14 @@ pub async fn delete_chat_handler<S: ChatService, Svc: EntityAccessService>(
)]
/// Permanently delete a chat and all associated data.
#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
-pub async fn permanently_delete_chat_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn permanently_delete_chat_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
) -> Result<StatusCode> {
state
@@ -254,9 +327,14 @@ pub struct PatchChatRequest {
)]
/// Patch a chat's name, project, or share permissions.
#[tracing::instrument(skip(state, access, req), fields(chat_id = %chat_id), err(Debug))]
-pub async fn patch_chat_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn patch_chat_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
Json(req): Json<PatchChatRequest>,
) -> Result<StatusCode> {
@@ -290,9 +368,14 @@ pub async fn patch_chat_handler<S: ChatService, Svc: EntityAccessService>(
)]
/// Copy a chat and its messages into a new chat.
#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
-pub async fn copy_chat_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn copy_chat_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<ViewAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
) -> Result<Json<StringIDResponse>> {
let id = state.inner.copy_chat(access.entity_access_receipt).await?;
@@ -313,9 +396,14 @@ pub async fn copy_chat_handler<S: ChatService, Svc: EntityAccessService>(
)]
/// Revert a soft-deleted chat.
#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
-pub async fn revert_delete_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn revert_delete_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
) -> Result<StatusCode> {
state
@@ -347,9 +435,14 @@ pub struct GetChatPermissionsResponse {
)]
/// Get the share permissions for a chat.
#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
-pub async fn get_chat_permissions_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<EditAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn get_chat_permissions_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<EditAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
) -> Result<Json<GetChatPermissionsResponse>> {
let permissions = state
@@ -434,9 +527,14 @@ pub struct RejectToolCallRequest {
fields(chat_id = %chat_id, message_id = %req.message_id, tool_call_id = %req.tool_call_id),
err(Debug)
)]
-pub async fn update_tool_call_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn update_tool_call_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
Json(req): Json<UpdateToolCallRequest>,
) -> Result<StatusCode> {
@@ -471,9 +569,14 @@ pub async fn update_tool_call_handler<S: ChatService, Svc: EntityAccessService>(
fields(chat_id = %chat_id, message_id = %req.message_id, tool_call_id = %req.tool_call_id),
err(Debug)
)]
-pub async fn update_tool_response_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn update_tool_response_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
Json(req): Json<UpdateToolResponseRequest>,
) -> Result<StatusCode> {
@@ -509,9 +612,14 @@ pub async fn update_tool_response_handler<S: ChatService, Svc: EntityAccessServi
fields(chat_id = %chat_id, message_id = %req.message_id, tool_call_id = %req.tool_call_id),
err(Debug)
)]
-pub async fn call_tool_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn call_tool_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
Json(req): Json<CallToolRequest>,
) -> Result<Json<CallToolResponse>> {
@@ -546,9 +654,14 @@ pub async fn call_tool_handler<S: ChatService, Svc: EntityAccessService>(
fields(chat_id = %chat_id, message_id = %req.message_id, tool_call_id = %req.tool_call_id),
err(Debug)
)]
-pub async fn reject_tool_call_handler<S: ChatService, Svc: EntityAccessService>(
- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
- State(state): State<ChatRouterState<S, Svc>>,
+pub async fn reject_tool_call_handler<
+ S: ChatService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ P: UserRolesAndPermissionsService,
+>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
+ State(state): State<ChatRouterState<S, Svc, Auth, P>>,
Path(chat_id): Path<String>,
Json(req): Json<RejectToolCallRequest>,
) -> Result<StatusCode> {
diff --git a/crates/chat/src/inbound/test.rs b/crates/chat/src/inbound/test.rs
index f8d44c0cf0..284455f83e 100644
--- a/crates/chat/src/inbound/test.rs
+++ b/crates/chat/src/inbound/test.rs
@@ -1,19 +1,25 @@
use axum::Extension;
use axum::Router;
use axum::body::Body;
-use axum::http::{Request, StatusCode};
+use axum::http::{Request, StatusCode, header};
use http_body_util::BodyExt;
+use macro_authorization::{
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+ MacroAuthorizationState,
+};
use macro_user_id::user_id::MacroUserIdStr;
use model::chat::ChatBasic;
use model::response::StringIDResponse;
-use model_user::UserContext;
+use model::user::UserContext;
+use rootcause::Report;
+use std::sync::Arc;
use tower::util::ServiceExt;
use crate::domain::models::{
ChatErr, ChatResponse, CreateChatArgs, GetChatResponse, PatchChatArgs, Result,
};
use crate::domain::ports::ChatService;
-use crate::inbound::http::router::{ChatRouterState, chat_id_router};
+use crate::inbound::http::router::{ChatRouterState, chat_create_router, chat_id_router};
use ai_toolset::tool_object::UserToolResponse;
use entity_access::domain::models::{
AccessError, AccessLevel, BotId, EditAccessLevel, EntityAccessReceipt, EntityPermission,
@@ -453,13 +459,109 @@ impl EntityAccessService for MockAccessService {
}
}
-fn user_extension() -> Extension<UserContext> {
- Extension(UserContext {
- user_id: "macro|[email protected]".to_string(),
- fusion_user_id: "1234".to_string(),
- permissions: None,
- organization_id: None,
- })
+/// Fake authorization service accepting the `valid` bearer token as the test
+/// user.
+#[derive(Clone)]
+struct FakeAuthorizationService;
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(
+ &self,
+ jwt: &str,
+ ) -> std::result::Result<UserContext, Report<MacroAuthorizationError>> {
+ if jwt != "valid" {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "1234".to_string(),
+ permissions: None,
+ organization_id: None,
+ })
+ }
+
+ async fn authorize_internal(
+ &self,
+ _provided_key: &str,
+ _claims: InternalIdentityClaims,
+ ) -> std::result::Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+
+fn authorization_state() -> MacroAuthorizationState<FakeAuthorizationService> {
+ MacroAuthorizationState::new(Arc::new(FakeAuthorizationService))
+}
+
+/// Fake roles-and-permissions service granting no permissions (free tier).
+#[derive(Clone)]
+struct FakeUserPermissionsService;
+
+impl roles_and_permissions::domain::port::UserRolesAndPermissionsService
+ for FakeUserPermissionsService
+{
+ async fn get_user_roles(
+ &self,
+ _user_id: &macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> std::result::Result<
+ std::collections::HashSet<roles_and_permissions::domain::model::RoleId>,
+ roles_and_permissions::domain::model::UserRolesAndPermissionsError,
+ > {
+ Ok(std::collections::HashSet::new())
+ }
+
+ async fn get_user_permissions(
+ &self,
+ _user_id: &macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> std::result::Result<
+ std::collections::HashSet<roles_and_permissions::domain::model::PermissionId>,
+ roles_and_permissions::domain::model::UserRolesAndPermissionsError,
+ > {
+ Ok(std::collections::HashSet::new())
+ }
+
+ async fn update_user_roles_and_permissions_for_subscription(
+ &self,
+ _email: macro_user_id::email::Email<macro_user_id::lowercased::Lowercase<'_>>,
+ _subscription_status: roles_and_permissions::domain::model::SubscriptionStatus,
+ _product_tier: roles_and_permissions::domain::model::ProductTier,
+ ) -> std::result::Result<(), roles_and_permissions::domain::model::UserRolesAndPermissionsError>
+ {
+ unimplemented!("not used by chat handlers")
+ }
+
+ async fn dangerous_upsert_roles_for_user(
+ &self,
+ _user_id: &macro_user_id::user_id::MacroUserIdStr<'_>,
+ _role_ids: non_empty::NonEmpty<&[roles_and_permissions::domain::model::RoleId]>,
+ ) -> std::result::Result<(), roles_and_permissions::domain::model::UserRolesAndPermissionsError>
+ {
+ unimplemented!("not used by chat handlers")
+ }
+
+ async fn dangerous_remove_roles_from_user(
+ &self,
+ _user_id: &macro_user_id::user_id::MacroUserIdStr<'_>,
+ _role_ids: &non_empty::NonEmpty<&[roles_and_permissions::domain::model::RoleId]>,
+ ) -> std::result::Result<(), roles_and_permissions::domain::model::UserRolesAndPermissionsError>
+ {
+ unimplemented!("not used by chat handlers")
+ }
+}
+
+fn permissions_service() -> Arc<FakeUserPermissionsService> {
+ Arc::new(FakeUserPermissionsService)
+}
+
+/// Attaches the test user's bearer token to every request, mirroring the
+/// credentials a real client would send.
+async fn attach_bearer(mut req: Request<Body>) -> Request<Body> {
+ req.headers_mut().insert(
+ header::AUTHORIZATION,
+ "Bearer valid".parse().expect("header should be valid"),
+ );
+ req
}
fn chat_basic_extension() -> Extension<ChatBasic> {
@@ -476,21 +578,65 @@ fn chat_basic_extension() -> Extension<ChatBasic> {
}
fn mock_id_router() -> Router {
- chat_id_router(ChatRouterState::new(MockService, MockAccessService))
- .layer(chat_basic_extension())
- .layer(user_extension())
+ chat_id_router(ChatRouterState::new(
+ MockService,
+ MockAccessService,
+ authorization_state(),
+ permissions_service(),
+ ))
+ .layer(chat_basic_extension())
+ .layer(axum::middleware::map_request(attach_bearer))
}
fn error_id_router() -> Router {
- chat_id_router(ChatRouterState::new(ErrorService, MockAccessService))
- .layer(chat_basic_extension())
- .layer(user_extension())
+ chat_id_router(ChatRouterState::new(
+ ErrorService,
+ MockAccessService,
+ authorization_state(),
+ permissions_service(),
+ ))
+ .layer(chat_basic_extension())
+ .layer(axum::middleware::map_request(attach_bearer))
}
fn not_found_id_router() -> Router {
- chat_id_router(ChatRouterState::new(NotFoundService, MockAccessService))
- .layer(chat_basic_extension())
- .layer(user_extension())
+ chat_id_router(ChatRouterState::new(
+ NotFoundService,
+ MockAccessService,
+ authorization_state(),
+ permissions_service(),
+ ))
+ .layer(chat_basic_extension())
+ .layer(axum::middleware::map_request(attach_bearer))
+}
+
+fn mock_create_router() -> Router {
+ chat_create_router(ChatRouterState::new(
+ MockService,
+ MockAccessService,
+ authorization_state(),
+ permissions_service(),
+ ))
+ .layer(axum::middleware::map_request(attach_bearer))
+}
+
+// -- create_chat tests --
+
+#[tokio::test]
+async fn create_chat_returns_id() {
+ let req = Request::builder()
+ .method("POST")
+ .uri("/")
+ .header("content-type", "application/json")
+ .body(Body::from(r#"{"name": "My Chat"}"#))
+ .unwrap();
+
+ let res = mock_create_router().oneshot(req).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body = res.into_body().collect().await.unwrap().to_bytes();
+ let response: StringIDResponse = serde_json::from_slice(&body).unwrap();
+ assert_eq!(response.id, "test-chat-id");
}
// -- get_chat tests --
diff --git a/crates/entity_access/src/inbound/axum_extractors/chat.rs b/crates/entity_access/src/inbound/axum_extractors/chat.rs
index 6154c070e5..2795439448 100644
--- a/crates/entity_access/src/inbound/axum_extractors/chat.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/chat.rs
@@ -1,5 +1,8 @@
//! Chat access extractor.
+#[cfg(test)]
+mod test;
+
use std::marker::PhantomData;
use std::sync::Arc;
@@ -8,8 +11,11 @@ use axum::{
extract::{FromRef, FromRequestParts},
http::request::Parts,
};
+use macro_authorization::{
+ MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+};
-use super::{ExtractorError, InternalUser, RequiredPermission};
+use super::{ExtractorError, RequiredPermission};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -17,28 +23,30 @@ use crate::domain::{
ports::EntityAccessService,
};
use model::chat::ChatBasic;
-use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Validates that the user has at least the required access level to a chat.
///
/// Type parameter `T` specifies the required access level.
/// Type parameter `Svc` is the entity access service implementation.
+/// Type parameter `Auth` is the authorization service implementation.
///
/// # Prerequisites
///
-/// - Chat context must be loaded (ChatBasic in extensions)
+/// - Chat context must be loaded (`ChatBasic` in extensions)
#[derive(Debug)]
-pub struct ChatAccessLevelExtractor<T: RequiredPermission, Svc> {
+pub struct ChatAccessLevelExtractor<T: RequiredPermission, Svc, Auth> {
/// The entity access receipt
pub entity_access_receipt: EntityAccessReceipt<T>,
- _marker: PhantomData<(T, Svc)>,
+ _marker: PhantomData<(T, Svc, Auth)>,
}
-impl<T, S, Svc> FromRequestParts<S> for ChatAccessLevelExtractor<T, Svc>
+impl<T, S, Svc, Auth> FromRequestParts<S> for ChatAccessLevelExtractor<T, Svc, Auth>
where
T: RequiredPermission,
Arc<Svc>: FromRef<S>,
Svc: EntityAccessService,
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
type Rejection = ExtractorError;
@@ -47,26 +55,20 @@ where
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, .. } = parts
- .extract()
+ let OptionalMacroAuthorizationExtractor {
+ macro_user_id,
+ is_internal_access,
+ ..
+ } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
.await
- .map_err(|_| ExtractorError::Internal)?;
+ .map_err(ExtractorError::from)?;
let chat_context: Extension<ChatBasic> = parts
.extract()
.await
.map_err(|_| ExtractorError::Internal)?;
- 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() {
+ if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
entity: Entity {
diff --git a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
new file mode 100644
index 0000000000..a4bb5960e3
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
@@ -0,0 +1,446 @@
+use std::sync::{Arc, Mutex};
+
+use axum::{
+ body::{Body, to_bytes},
+ extract::{FromRef, FromRequestParts},
+ http::{Request, StatusCode, header},
+ response::IntoResponse,
+};
+use macro_authorization::{
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+};
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+use model::chat::ChatBasic;
+use model_user::UserContext;
+use rootcause::Report;
+use uuid::Uuid;
+
+use super::*;
+use crate::domain::models::{
+ AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
+ ViewAccessLevel,
+};
+
+const CHAT_ID: &str = "chat-1";
+const OWNER_ID: &str = "macro|[email protected]";
+const USER_ID: &str = "macro|[email protected]";
+const ACT_AS_ID: &str = "macro|[email protected]";
+const DEFAULT_INTERNAL_ID: &str = "macro|[email protected]";
+const INTERNAL_KEY: &str = "valid-internal-key";
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct AccessCall {
+ user_id: Option<String>,
+ entity_id: String,
+ entity_type: EntityType,
+}
+
+#[derive(Clone, Debug)]
+struct FakeEntityAccessService {
+ access_level: Option<AccessLevel>,
+ calls: Arc<Mutex<Vec<AccessCall>>>,
+}
+
+impl FakeEntityAccessService {
+ fn new(access_level: Option<AccessLevel>) -> Self {
+ Self {
+ access_level,
+ calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn calls(&self) -> Vec<AccessCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+}
+
+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> {
+ panic!("unexpected generate_entity_access_receipt call")
+ }
+
+ 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 generate_bot_entity_access_receipt call")
+ }
+
+ async fn get_access_level(
+ &self,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(AccessCall {
+ user_id: user_id.map(|id| id.as_ref().to_string()),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+ Ok(self.access_level)
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_access call")
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_public_access call")
+ }
+
+ 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 get_entity_permission call")
+ }
+
+ 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 get_crm_entity_permission_with_team call")
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ panic!("unexpected get_users_by_entity call")
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel call")
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel_by_channel_id call")
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ panic!("unexpected get_user_team call")
+ }
+}
+
+#[derive(Clone, Debug, Default)]
+struct FakeAuthorizationService {
+ default_internal_user_id: Option<String>,
+}
+
+impl FakeAuthorizationService {
+ fn with_default_internal_user() -> Self {
+ Self {
+ default_internal_user_id: Some(DEFAULT_INTERNAL_ID.to_string()),
+ }
+ }
+}
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ match jwt {
+ "owner" => Ok(user_context(OWNER_ID)),
+ "valid" => Ok(user_context(USER_ID)),
+ "expired" => Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+
+ async fn authorize_internal(
+ &self,
+ provided_key: &str,
+ claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ if provided_key != INTERNAL_KEY {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(claims
+ .user_id
+ .or_else(|| self.default_internal_user_id.clone())
+ .map(|user_id| user_context(&user_id)))
+ }
+}
+
+struct TestState {
+ entity_access: Arc<FakeEntityAccessService>,
+ authorization: MacroAuthorizationState<FakeAuthorizationService>,
+}
+
+impl TestState {
+ fn new(access_level: Option<AccessLevel>) -> Self {
+ Self::with_authorization(access_level, FakeAuthorizationService::default())
+ }
+
+ fn with_authorization(
+ access_level: Option<AccessLevel>,
+ authorization: FakeAuthorizationService,
+ ) -> Self {
+ Self {
+ entity_access: Arc::new(FakeEntityAccessService::new(access_level)),
+ authorization: MacroAuthorizationState::new(Arc::new(authorization)),
+ }
+ }
+}
+
+impl FromRef<TestState> for Arc<FakeEntityAccessService> {
+ fn from_ref(state: &TestState) -> Self {
+ state.entity_access.clone()
+ }
+}
+
+impl FromRef<TestState> for MacroAuthorizationState<FakeAuthorizationService> {
+ fn from_ref(state: &TestState) -> Self {
+ state.authorization.clone()
+ }
+}
+
+fn user_context(user_id: &str) -> UserContext {
+ UserContext {
+ user_id: user_id.to_string(),
+ fusion_user_id: "fusion-user-id".to_string(),
+ organization_id: None,
+ permissions: None,
+ }
+}
+
+fn chat(deleted: bool) -> ChatBasic {
+ ChatBasic {
+ id: CHAT_ID.to_string(),
+ name: "Test chat".to_string(),
+ user_id: MacroUserIdStr::parse_from_str(OWNER_ID).expect("owner id should be valid"),
+ project_id: None,
+ deleted_at: deleted.then(|| {
+ "2026-01-01T00:00:00Z"
+ .parse()
+ .expect("deleted timestamp should be valid")
+ }),
+ }
+}
+
+fn request(token: Option<&str>, chat: ChatBasic) -> Request<Body> {
+ let mut request = Request::new(Body::empty());
+ request.extensions_mut().insert(chat);
+ if let Some(token) = token {
+ request.headers_mut().insert(
+ header::AUTHORIZATION,
+ format!("Bearer {token}")
+ .parse()
+ .expect("header should be valid"),
+ );
+ }
+ request
+}
+
+fn internal_request(user_id: Option<&str>, chat: ChatBasic) -> Request<Body> {
+ let mut request = request(None, chat);
+ request.headers_mut().insert(
+ INTERNAL_API_KEY_HEADER,
+ INTERNAL_KEY.parse().expect("key should be valid"),
+ );
+ if let Some(user_id) = user_id {
+ request.headers_mut().insert(
+ INTERNAL_MACRO_USER_ID_HEADER,
+ user_id.parse().expect("user id should be valid"),
+ );
+ }
+ request
+}
+
+async fn extract<T: RequiredPermission>(
+ request: Request<Body>,
+ state: &TestState,
+) -> Result<
+ ChatAccessLevelExtractor<T, FakeEntityAccessService, FakeAuthorizationService>,
+ ExtractorError,
+> {
+ let (mut parts, _) = request.into_parts();
+ ChatAccessLevelExtractor::from_request_parts(&mut parts, state).await
+}
+
+#[tokio::test]
+async fn anonymous_link_share_access_returns_unauthenticated_receipt() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let extracted = extract::<ViewAccessLevel>(request(None, chat(false)), &state)
+ .await
+ .expect("public link access should be allowed");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.auth(),
+ EntityAccessAuth::Unauthenticated
+ ));
+ assert_eq!(state.entity_access.calls()[0].user_id, None);
+}
+
+#[tokio::test]
+async fn authenticated_owner_bypasses_access_lookup() {
+ let state = TestState::new(None);
+ let extracted = extract::<EditAccessLevel>(request(Some("owner"), chat(false)), &state)
+ .await
+ .expect("the owner should be allowed");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ ));
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn insufficient_access_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let result = extract::<EditAccessLevel>(request(Some("valid"), chat(false)), &state).await;
+
+ assert!(matches!(result, Err(ExtractorError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn deleted_chat_allows_owner_but_rejects_non_owner() {
+ let owner_state = TestState::new(None);
+ extract::<EditAccessLevel>(request(Some("owner"), chat(true)), &owner_state)
+ .await
+ .expect("the owner should access a deleted chat");
+
+ let non_owner_state = TestState::new(Some(AccessLevel::Owner));
+ let result =
+ extract::<ViewAccessLevel>(request(Some("valid"), chat(true)), &non_owner_state).await;
+ assert!(matches!(
+ result,
+ Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource"
+ ))
+ ));
+ assert!(non_owner_state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn internal_act_as_uses_ordinary_acl_evaluation() {
+ let state = TestState::new(Some(AccessLevel::Edit));
+ let extracted =
+ extract::<EditAccessLevel>(internal_request(Some(ACT_AS_ID), chat(false)), &state)
+ .await
+ .expect("internal act-as identity should use its ACL");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.auth(),
+ EntityAccessAuth::Authenticated(actual) if actual.as_ref() == ACT_AS_ID
+ ));
+ assert_eq!(
+ state.entity_access.calls()[0].user_id.as_deref(),
+ Some(ACT_AS_ID)
+ );
+}
+
+#[tokio::test]
+async fn default_internal_identity_uses_ordinary_acl_evaluation() {
+ let state = TestState::with_authorization(
+ Some(AccessLevel::View),
+ FakeAuthorizationService::with_default_internal_user(),
+ );
+ let extracted = extract::<ViewAccessLevel>(internal_request(None, chat(false)), &state)
+ .await
+ .expect("default internal identity should use its ACL");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.auth(),
+ EntityAccessAuth::Authenticated(actual) if actual.as_ref() == DEFAULT_INTERNAL_ID
+ ));
+ assert_eq!(
+ state.entity_access.calls()[0].user_id.as_deref(),
+ Some(DEFAULT_INTERNAL_ID)
+ );
+}
+
+#[tokio::test]
+async fn identity_less_internal_request_receives_owner_without_acl_lookup() {
+ let state = TestState::new(None);
+ let extracted = extract::<EditAccessLevel>(internal_request(None, chat(false)), &state)
+ .await
+ .expect("identity-less internal access should be allowed");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.auth(),
+ EntityAccessAuth::Internal
+ ));
+ assert!(matches!(
+ extracted.entity_access_receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ ));
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn invalid_internal_credentials_are_rejected_without_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let mut request = internal_request(None, chat(false));
+ request
+ .headers_mut()
+ .insert(INTERNAL_API_KEY_HEADER, "invalid".parse().unwrap());
+ let error = extract::<ViewAccessLevel>(request, &state)
+ .await
+ .expect_err("invalid credentials should be rejected");
+ let response = error.into_response();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn expired_token_preserves_exact_unauthorized_json() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let error = extract::<ViewAccessLevel>(request(Some("expired"), chat(false)), &state)
+ .await
+ .expect_err("expired credentials should be rejected");
+ let response = error.into_response();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ assert_eq!(body.as_ref(), br#"{"message":"jwt expired"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
diff --git a/crates/mcp_client/Cargo.toml b/crates/mcp_client/Cargo.toml
index d461906138..6f1918637a 100644
--- a/crates/mcp_client/Cargo.toml
+++ b/crates/mcp_client/Cargo.toml
@@ -18,10 +18,12 @@ base64.workspace = true
async-openai.workspace = true
axum.workspace = true
futures.workspace = true
+macro_authorization = { path = "../macro_authorization", default-features = false, features = [
+ "axum",
+] }
macro_env_var = { path = "../macro_env_var", optional = true }
macro_user_id = { path = "../macro_user_id" }
model-error-response = { path = "../model-error-response" }
-model_user = { path = "../model_user", features = ["axum"] }
redis = { workspace = true, features = ["aio", "tokio-comp"] }
reqwest.workspace = true
rmcp = { workspace = true, features = ["auth", "client", "transport-streamable-http-client-reqwest"] }
diff --git a/crates/mcp_client/src/inbound/axum_router.rs b/crates/mcp_client/src/inbound/axum_router.rs
index 0bfe42696e..f6fd4d7dec 100644
--- a/crates/mcp_client/src/inbound/axum_router.rs
+++ b/crates/mcp_client/src/inbound/axum_router.rs
@@ -4,42 +4,55 @@ use crate::domain::{
};
use axum::{
Json, Router,
- extract::{Query, State},
+ extract::{FromRef, Query, State},
http::StatusCode,
response::IntoResponse,
routing::{delete, get, post, put},
};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
use model_error_response::ErrorResponse;
-use model_user::axum_extractor::MacroUserExtractor;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use utoipa::{IntoParams, ToSchema};
/// Shared state for the MCP router.
-pub struct McpRouterState<S, O> {
+pub struct McpRouterState<S, O, Auth> {
store: Arc<S>,
oauth: Arc<O>,
+ authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S, O> Clone for McpRouterState<S, O> {
+impl<S, O, Auth> Clone for McpRouterState<S, O, Auth> {
fn clone(&self) -> Self {
Self {
store: self.store.clone(),
oauth: self.oauth.clone(),
+ authorization_state: self.authorization_state.clone(),
}
}
}
-impl<S, O> McpRouterState<S, O>
+impl<S, O, Auth> FromRef<McpRouterState<S, O, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &McpRouterState<S, O, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+impl<S, O, Auth> McpRouterState<S, O, Auth>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
{
- /// Create a new router state from a server store and OAuth client.
- pub fn new(store: S, oauth: O) -> Self {
+ /// Create a new router state from a server store, OAuth client, and
+ /// authorization state.
+ pub fn new(store: S, oauth: O, authorization_state: MacroAuthorizationState<Auth>) -> Self {
Self {
store: Arc::new(store),
oauth: Arc::new(oauth),
+ authorization_state,
}
}
@@ -50,32 +63,39 @@ where
}
/// Authenticated MCP routes (CRUD + start auth).
-pub fn mcp_router<S, O, Global>(state: McpRouterState<S, O>) -> Router<Global>
+pub fn mcp_router<S, O, Auth, Global>(state: McpRouterState<S, O, Auth>) -> Router<Global>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
Global: Send + Sync,
{
Router::new()
- .route("/mcp/servers", get(list_servers::<S, O>))
- .route("/mcp/servers", post(add_server::<S, O>))
- .route("/mcp/servers", put(update_server::<S, O>))
- .route("/mcp/servers", delete(delete_server::<S, O>))
- .route("/mcp/servers/auth/start", post(start_auth::<S, O>))
+ .route("/mcp/servers", get(list_servers::<S, O, Auth>))
+ .route("/mcp/servers", post(add_server::<S, O, Auth>))
+ .route("/mcp/servers", put(update_server::<S, O, Auth>))
+ .route("/mcp/servers", delete(delete_server::<S, O, Auth>))
+ .route("/mcp/servers/auth/start", post(start_auth::<S, O, Auth>))
.with_state(state)
}
/// Unauthenticated OAuth callback route.
-pub fn mcp_oauth_callback_router<S, O, Global>(state: McpRouterState<S, O>) -> Router<Global>
+pub fn mcp_oauth_callback_router<S, O, Auth, Global>(
+ state: McpRouterState<S, O, Auth>,
+) -> Router<Global>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
Global: Send + Sync,
{
Router::new()
- .route("/mcp/servers/auth/callback", get(auth_callback::<S, O>))
+ .route(
+ "/mcp/servers/auth/callback",
+ get(auth_callback::<S, O, Auth>),
+ )
.with_state(state)
}
@@ -205,13 +225,14 @@ impl IntoResponse for McpHandlerErr {
)]
/// List all MCP servers configured for the authenticated user.
#[tracing::instrument(skip_all, err)]
-pub async fn list_servers<S, O>(
- State(state): State<McpRouterState<S, O>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+pub async fn list_servers<S, O, Auth>(
+ State(state): State<McpRouterState<S, O, Auth>>,
+ MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
) -> Result<Json<Vec<ServerResponse>>, McpHandlerErr>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
{
let records = state
@@ -239,14 +260,15 @@ where
)]
/// Add a new MCP server for the authenticated user.
#[tracing::instrument(skip_all, err)]
-pub async fn add_server<S, O>(
- State(state): State<McpRouterState<S, O>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+pub async fn add_server<S, O, Auth>(
+ State(state): State<McpRouterState<S, O, Auth>>,
+ MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
Json(body): Json<AddServerRequest>,
) -> Result<(StatusCode, Json<ServerResponse>), McpHandlerErr>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
{
let record = McpServerRecord {
@@ -284,14 +306,15 @@ where
)]
/// Update an existing MCP server's name or enabled status.
#[tracing::instrument(skip_all, err)]
-pub async fn update_server<S, O>(
- State(state): State<McpRouterState<S, O>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+pub async fn update_server<S, O, Auth>(
+ State(state): State<McpRouterState<S, O, Auth>>,
+ MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
Json(body): Json<UpdateServerRequest>,
) -> Result<Json<ServerResponse>, McpHandlerErr>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
{
let mut record = state
@@ -331,14 +354,15 @@ where
)]
/// Delete an MCP server by URL.
#[tracing::instrument(skip_all, err)]
-pub async fn delete_server<S, O>(
- State(state): State<McpRouterState<S, O>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+pub async fn delete_server<S, O, Auth>(
+ State(state): State<McpRouterState<S, O, Auth>>,
+ MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
Query(params): Query<DeleteServerParams>,
) -> Result<StatusCode, McpHandlerErr>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
{
state
@@ -364,14 +388,15 @@ where
)]
/// Start the OAuth authorization flow for an MCP server.
#[tracing::instrument(skip_all, err)]
-pub async fn start_auth<S, O>(
- State(state): State<McpRouterState<S, O>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+pub async fn start_auth<S, O, Auth>(
+ State(state): State<McpRouterState<S, O, Auth>>,
+ MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
Json(body): Json<StartAuthRequest>,
) -> Result<Json<StartAuthResponse>, McpHandlerErr>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
{
let authorization_url = state
.oauth
@@ -394,13 +419,14 @@ where
)]
/// OAuth callback endpoint — receives code and state from the authorization server.
#[tracing::instrument(skip_all, err)]
-pub async fn auth_callback<S, O>(
- State(state): State<McpRouterState<S, O>>,
+pub async fn auth_callback<S, O, Auth>(
+ State(state): State<McpRouterState<S, O, Auth>>,
Query(params): Query<AuthCallbackParams>,
) -> Result<String, McpHandlerErr>
where
S: McpServerStore,
O: OAuthClient,
+ Auth: MacroAuthorizationService,
{
state
.oauth
diff --git a/crates/memory/Cargo.toml b/crates/memory/Cargo.toml
index 56f0b25a5e..2ba8738e4e 100644
--- a/crates/memory/Cargo.toml
+++ b/crates/memory/Cargo.toml
@@ -18,9 +18,11 @@ futures = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
macro_env_var = { path = "../macro_env_var" }
+macro_authorization = { path = "../macro_authorization", default-features = false, features = [
+ "axum",
+] }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
-model_user = { path = "../model_user", features = ["axum"] }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/crates/memory/src/inbound/axum_router.rs b/crates/memory/src/inbound/axum_router.rs
index 50398e9d26..f2f29476ce 100644
--- a/crates/memory/src/inbound/axum_router.rs
+++ b/crates/memory/src/inbound/axum_router.rs
@@ -1,12 +1,14 @@
use crate::domain::MemoryService;
use axum::{
Json, Router,
- extract::State,
+ extract::{FromRef, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
};
-use model_user::axum_extractor::MacroUserExtractor;
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
use serde::Serialize;
use std::sync::Arc;
use utoipa::ToSchema;
@@ -24,14 +26,46 @@ pub struct MemoryErrorBody {
pub error: String,
}
-pub fn memory_router<T, S>(service: Arc<T>) -> Router<S>
+/// Router state containing the memory service and the authorization state
+/// used to authenticate callers.
+pub struct MemoryRouterState<T, Auth> {
+ /// The memory service implementation.
+ pub service: Arc<T>,
+ /// The authorization state used by the request extractors.
+ pub authorization_state: MacroAuthorizationState<Auth>,
+}
+
+// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).
+impl<T, Auth> Clone for MemoryRouterState<T, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<T, Auth> FromRef<MemoryRouterState<T, Auth>> for Arc<T> {
+ fn from_ref(state: &MemoryRouterState<T, Auth>) -> Self {
+ state.service.clone()
+ }
+}
+
+impl<T, Auth> FromRef<MemoryRouterState<T, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &MemoryRouterState<T, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+pub fn memory_router<T, Auth, S>(state: MemoryRouterState<T, Auth>) -> Router<S>
where
T: MemoryService + Send + Sync + 'static,
+ Auth: MacroAuthorizationService,
S: Send + Sync + Clone + 'static,
{
Router::new()
- .route("/memory", get(get_memory_handler::<T>))
- .with_state(service)
+ .route("/memory", get(get_memory_handler::<T, Auth>))
+ .with_state(state)
}
/// Get the authenticated user's latest memory.
@@ -50,9 +84,9 @@ where
tag = "memory"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
-pub async fn get_memory_handler<T: MemoryService>(
+pub async fn get_memory_handler<T: MemoryService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroUserExtractor,
+ user: MacroAuthorizationExtractor<Auth>,
) -> Response {
match service.get_or_generate_memory(user.macro_user_id).await {
Ok(Some(memory)) => Json(MemoryResponse { memory }).into_response(),
diff --git a/services/document_cognition_service/Cargo.toml b/services/document_cognition_service/Cargo.toml
index d1ee0971c1..d099cad08c 100644
--- a/services/document_cognition_service/Cargo.toml
+++ b/services/document_cognition_service/Cargo.toml
@@ -19,7 +19,7 @@ path = "src/doppler_config.rs"
[features]
local = []
-local_auth = ["macro_middleware/local_auth"]
+local_auth = ["macro_authorization/local_auth"]
local_queue = []
@@ -76,10 +76,9 @@ macro_env = { path = "../../crates/macro_env" }
macro_env_var = { path = "../../crates/macro_env_var" }
macro_event_broker = { path = "../../crates/macro_event_broker" }
macro_queues = { path = "../../crates/macro_queues" }
+macro_authorization = { path = "../../crates/macro_authorization" }
macro_middleware = { path = "../../crates/macro_middleware", default-features = false, features = [
- "auth",
"cloud_storage",
- "user_permissions",
] }
macro_user_id = { path = "../../crates/macro_user_id" }
macro_uuid = { path = "../../crates/macro_uuid" }
@@ -103,7 +102,9 @@ redis = { workspace = true, features = [
] }
regex = { workspace = true }
reqwest.workspace = true
-roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false }
+roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = [
+ "outbound",
+] }
schemars = { workspace = true }
search_service_client = { path = "../../crates/search_service_client" }
secretsmanager_client = { path = "../../crates/secretsmanager_client" }
diff --git a/services/document_cognition_service/src/api/attachments/get_chats_for_attachment.rs b/services/document_cognition_service/src/api/attachments/get_chats_for_attachment.rs
index de2f74e2ce..0b830e0f46 100644
--- a/services/document_cognition_service/src/api/attachments/get_chats_for_attachment.rs
+++ b/services/document_cognition_service/src/api/attachments/get_chats_for_attachment.rs
@@ -1,15 +1,16 @@
+use crate::api::context::DcsAuthorizationService;
use crate::model::response::attachments::GetChatsForAttachmentResponse;
use anyhow::Result;
use axum::{
- Extension, Json,
+ Json,
extract::{Path, State},
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_authorization::MacroAuthorizationExtractor;
use macro_db_client::dcs::get_chats_for_attachment::{
get_latest_single_attachment_chat, get_multi_attachment_chat,
};
-use model::user::UserContext;
use sqlx::PgPool;
#[derive(serde::Deserialize)]
@@ -28,38 +29,31 @@ pub struct Params {
),
params( ("attachment_id" = String, Path, description = "id of the attachment"))
)]
-#[tracing::instrument(skip(db, user_context), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(db, user), fields(user_id=%user.macro_user_id))]
pub async fn get_chats_for_attachment_handler(
State(db): State<PgPool>,
- user_context: Extension<UserContext>,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService>,
Path(Params { attachment_id }): Path<Params>,
) -> Result<Response, Response> {
+ let user_id = user.macro_user_id.as_ref();
let mut transaction = db.begin().await.map_err(|e| {
- tracing::error!(error=?e, user_id=%user_context.user_id, attachment_id=%attachment_id, "failed to begin transaction");
+ tracing::error!(error=?e, user_id=%user_id, attachment_id=%attachment_id, "failed to begin transaction");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
})?;
- let recent = get_latest_single_attachment_chat(
- &mut transaction,
- &attachment_id,
- user_context.user_id.as_str(),
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, user_id=%user_context.user_id, attachment_id=%attachment_id, "failed to get latest single attachment chat");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- })?;
+ let recent = get_latest_single_attachment_chat(&mut transaction, &attachment_id, user_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, user_id=%user_id, attachment_id=%attachment_id, "failed to get latest single attachment chat");
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ })?;
- let multi = get_multi_attachment_chat(
- &mut transaction,
- &attachment_id,
- user_context.user_id.as_str(),
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, user_id=%user_context.user_id, attachment_id=%attachment_id, "failed to get multi attachment chat");
- StatusCode::INTERNAL_SERVER_ERROR.into_response()
- })?;
+ let multi = get_multi_attachment_chat(&mut transaction, &attachment_id, user_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, user_id=%user_id, attachment_id=%attachment_id, "failed to get multi attachment chat");
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ })?;
let res = GetChatsForAttachmentResponse {
recent_chat: recent,
diff --git a/services/document_cognition_service/src/api/attachments/mod.rs b/services/document_cognition_service/src/api/attachments/mod.rs
index 11e20b7047..870e4cd71b 100644
--- a/services/document_cognition_service/src/api/attachments/mod.rs
+++ b/services/document_cognition_service/src/api/attachments/mod.rs
@@ -1,17 +1,12 @@
pub mod get_chats_for_attachment;
use axum::{Router, routing::get};
-use tower::ServiceBuilder;
use crate::api::context::ApiContext;
pub fn router() -> Router<ApiContext> {
Router::new().route(
"/{attachment_id}/chats",
- get(get_chats_for_attachment::get_chats_for_attachment_handler).layer(
- ServiceBuilder::new().layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- )),
- ),
+ get(get_chats_for_attachment::get_chats_for_attachment_handler),
)
}
diff --git a/services/document_cognition_service/src/api/chats/chat_history.rs b/services/document_cognition_service/src/api/chats/chat_history.rs
index a7e96fcfef..910f3c6f0f 100644
--- a/services/document_cognition_service/src/api/chats/chat_history.rs
+++ b/services/document_cognition_service/src/api/chats/chat_history.rs
@@ -1,5 +1,5 @@
-use crate::api::context::DcsEntityAccessService;
-use axum::extract::{Extension, Path, State};
+use crate::api::context::{DcsAuthorizationService, DcsEntityAccessService};
+use axum::extract::{Path, State};
use axum::{
Json,
http::StatusCode,
@@ -8,7 +8,6 @@ use axum::{
use entity_access::inbound::axum_extractors::ChatAccessLevelExtractor;
use macro_db_client::chat_history::get_chat_history;
use model::chat::ChatHistory;
-use model::user::UserContext;
use models_permissions::share_permission::access_level::ViewAccessLevel;
use sqlx::PgPool;
@@ -25,10 +24,13 @@ use sqlx::PgPool;
(status = 500, body = String, description = "Internal server error")
)
)]
-#[tracing::instrument(skip(db, user_context, _access), fields(chat_id = %chat_id, user_id = %user_context.user_id))]
+#[tracing::instrument(skip(db, _access), fields(chat_id = %chat_id))]
pub async fn get_chat_history_handler(
- _access: ChatAccessLevelExtractor<ViewAccessLevel, DcsEntityAccessService>,
- Extension(user_context): Extension<UserContext>,
+ _access: ChatAccessLevelExtractor<
+ ViewAccessLevel,
+ DcsEntityAccessService,
+ DcsAuthorizationService,
+ >,
State(db): State<PgPool>,
Path(chat_id): Path<String>,
) -> Result<Json<ChatHistory>, Response> {
diff --git a/services/document_cognition_service/src/api/chats/chat_history_batch_messages.rs b/services/document_cognition_service/src/api/chats/chat_history_batch_messages.rs
index 62fefbc836..b7b12047d6 100644
--- a/services/document_cognition_service/src/api/chats/chat_history_batch_messages.rs
+++ b/services/document_cognition_service/src/api/chats/chat_history_batch_messages.rs
@@ -1,15 +1,16 @@
-use axum::extract::{Extension, State};
+use crate::api::context::DcsAuthorizationService;
+use axum::extract::State;
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_authorization::MacroAuthorizationExtractor;
use macro_db_client::{
chat::get_chat_ids_for_messages, chat_history::get_chat_history_for_messages,
share_permission::access_level::chat::get_highest_access_level_for_chats,
};
use model::chat::ChatHistory;
-use model::user::UserContext;
use models_dcs::api::ChatHistoryBatchMessagesRequest;
use sqlx::PgPool;
@@ -25,19 +26,21 @@ use sqlx::PgPool;
(status = 500, body = String, description = "Internal server error")
)
)]
-#[tracing::instrument(skip(db, user_context, request), fields(user_id = %user_context.user_id, message_count = request.message_ids.len()))]
+#[tracing::instrument(skip(db, user, request), fields(user_id = %user.macro_user_id, message_count = request.message_ids.len()))]
pub async fn get_chat_history_batch_messages_handler(
State(db): State<PgPool>,
- Extension(user_context): Extension<UserContext>,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService>,
Json(request): Json<ChatHistoryBatchMessagesRequest>,
) -> Result<Json<ChatHistory>, Response> {
+ let user_id = user.macro_user_id.as_ref();
+
// Get all unique chat IDs and check access to each
let chat_ids = get_chat_ids_for_messages(&db, &request.message_ids)
.await
.map_err(|err| {
tracing::error!(
error = %err,
- user_id = %user_context.user_id,
+ user_id = %user_id,
message_count = request.message_ids.len(),
"Failed to get chat IDs for messages"
);
@@ -55,24 +58,23 @@ pub async fn get_chat_history_batch_messages_handler(
// Check access to all chats in a single database query
let chat_ids_vec: Vec<String> = chat_ids.into_iter().collect();
- let access_levels =
- get_highest_access_level_for_chats(&db, &chat_ids_vec, &user_context.user_id)
- .await
- .map_err(|err| {
- tracing::error!(
- error = %err,
- user_id = %user_context.user_id,
- chat_count = chat_ids_vec.len(),
- "Failed to check chat access for batch"
- );
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(serde_json::json!({
- "error": "Failed to check chat access"
- })),
- )
- .into_response()
- })?;
+ let access_levels = get_highest_access_level_for_chats(&db, &chat_ids_vec, user_id)
+ .await
+ .map_err(|err| {
+ tracing::error!(
+ error = %err,
+ user_id = %user_id,
+ chat_count = chat_ids_vec.len(),
+ "Failed to check chat access for batch"
+ );
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({
+ "error": "Failed to check chat access"
+ })),
+ )
+ .into_response()
+ })?;
// Check that user has access to all chats
for chat_id in &chat_ids_vec {
@@ -81,7 +83,7 @@ pub async fn get_chat_history_batch_messages_handler(
// Require at least View access to read messages from this chat
if access_level.is_none() {
tracing::warn!(
- user_id = %user_context.user_id,
+ user_id = %user_id,
chat_id = %chat_id,
"User does not have access to chat containing requested messages"
);
@@ -100,7 +102,7 @@ pub async fn get_chat_history_batch_messages_handler(
.map_err(|err| {
tracing::error!(
error = %err,
- user_id = %user_context.user_id,
+ user_id = %user_id,
message_count = request.message_ids.len(),
"Failed to get chat history for messages"
);
diff --git a/services/document_cognition_service/src/api/chats/mod.rs b/services/document_cognition_service/src/api/chats/mod.rs
index 8d3268f2b0..90f2159e6d 100644
--- a/services/document_cognition_service/src/api/chats/mod.rs
+++ b/services/document_cognition_service/src/api/chats/mod.rs
@@ -1,9 +1,12 @@
pub mod chat_history;
pub mod chat_history_batch_messages;
-use super::context::ApiContext;
+use super::context::{ApiContext, DcsAuthorizationService};
use axum::{
Router,
+ extract::Request,
+ middleware::Next,
+ response::Response,
routing::{get, post},
};
use chat::domain::service::ChatServiceImpl;
@@ -11,8 +14,24 @@ use chat::inbound::http::router::{ChatRouterState, chat_create_router, chat_id_r
use chat::outbound::postgres::PgChatRepo;
use entity_access::domain::service::EntityAccessServiceImpl;
use entity_access::outbound::PgAccessRepository;
+use macro_authorization::MacroAuthorizationExtractor;
use tower::ServiceBuilder;
+/// Requires an authenticated acting user before the request proceeds.
+///
+/// Chats are created with a public-view share permission by default, so
+/// without this gate the `/{chat_id}` routes would serve any chat to fully
+/// anonymous callers via the extractor's link-share path. It also keeps the
+/// pre-existing ordering where missing/invalid credentials get a 401 before
+/// `ensure_chat_exists` performs its lookup (and 404s).
+async fn require_authenticated_user(
+ _user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ req: Request,
+ next: Next,
+) -> Response {
+ next.run(req).await
+}
+
pub fn router(state: ApiContext) -> Router<ApiContext> {
let access_repo = PgAccessRepository::new(state.db.clone());
let access_service = EntityAccessServiceImpl::new(access_repo);
@@ -26,37 +45,32 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
entity_access_management::outbound::PgRepository::new(state.db.clone()),
),
);
- let chat_state = ChatRouterState::new(chat_service, access_service);
+ let chat_state = ChatRouterState::new(
+ chat_service,
+ access_service,
+ state.authorization_state.clone(),
+ state.user_permissions_service.clone(),
+ );
let ensure_chat_exists = axum::middleware::from_fn_with_state(
state.clone(),
macro_middleware::cloud_storage::chat::ensure_chat_exists::handler,
);
+ let require_user =
+ axum::middleware::from_fn_with_state(state.clone(), require_authenticated_user);
Router::new()
- // Create route — needs ensure_user_exists, no ensure_chat_exists.
+ // Create route — no ensure_chat_exists; the handler's authorization
+ // extractor enforces authentication.
// Note: free users are intentionally no longer capped by chat/document count,
// so no quota-enforcement middleware is applied here.
- .merge(
- chat_create_router(chat_state.clone()).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- macro_middleware::auth::ensure_user_exists::handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- macro_middleware::user_permissions::attach_user_permissions::handler,
- )),
- ),
- )
- // All /{chat_id} routes — need ensure_chat_exists for ChatAccessLevelExtractor
+ .merge(chat_create_router(chat_state.clone()))
+ // All /{chat_id} routes — require an authenticated user, then
+ // ensure_chat_exists for ChatAccessLevelExtractor
.merge(
chat_id_router(chat_state).layer(
ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- ))
+ .layer(require_user.clone())
.layer(ensure_chat_exists.clone()),
),
)
@@ -65,18 +79,12 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/history/{chat_id}",
get(chat_history::get_chat_history_handler).layer(
ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- ))
+ .layer(require_user)
.layer(ensure_chat_exists),
),
)
.route(
"/history_batch_messages",
- post(chat_history_batch_messages::get_chat_history_batch_messages_handler).layer(
- ServiceBuilder::new().layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- )),
- ),
+ post(chat_history_batch_messages::get_chat_history_batch_messages_handler),
)
}
diff --git a/services/document_cognition_service/src/api/citations/mod.rs b/services/document_cognition_service/src/api/citations/mod.rs
index 7125ab5d3d..4e898ae9ff 100644
--- a/services/document_cognition_service/src/api/citations/mod.rs
+++ b/services/document_cognition_service/src/api/citations/mod.rs
@@ -1,13 +1,14 @@
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, DcsAuthorizationService};
use axum::{
Router,
- extract::{Extension, Path, State},
+ extract::{Path, State},
http::StatusCode,
response::Json,
routing::get,
};
+use macro_authorization::OptionalMacroAuthorizationExtractor;
use macro_db_client::dcs::get_part_by_id::get_part_by_id;
-use model::{citations::DocumentTextPart, user::UserContext};
+use model::citations::DocumentTextPart;
use sqlx::PgPool;
pub fn router() -> Router<ApiContext> {
@@ -31,10 +32,10 @@ pub struct Params {
(status = 500, body = String),
)
)]
-#[tracing::instrument(skip(db, user_context), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(db, user), fields(user_id=?user.macro_user_id))]
pub async fn get_citation_handler(
State(db): State<PgPool>,
- user_context: Extension<UserContext>,
+ user: OptionalMacroAuthorizationExtractor<DcsAuthorizationService>,
Path(Params { id }): Path<Params>,
) -> Result<Json<DocumentTextPart>, (StatusCode, String)> {
match get_part_by_id(db, id.as_str()).await {
@@ -44,7 +45,7 @@ pub async fn get_citation_handler(
"not found - possible hallucination".to_string(),
)),
Err(err) => {
- tracing::error!(user_id=?user_context.user_id, citation_id=%id, error=%err, "failed to get citation");
+ tracing::error!(user_id=?user.macro_user_id, citation_id=%id, error=%err, "failed to get citation");
Err((
StatusCode::INTERNAL_SERVER_ERROR,
"unable to get citation".to_string(),
diff --git a/services/document_cognition_service/src/api/completions.rs b/services/document_cognition_service/src/api/completions.rs
index b2f91861a9..a75256161f 100644
--- a/services/document_cognition_service/src/api/completions.rs
+++ b/services/document_cognition_service/src/api/completions.rs
@@ -1,4 +1,6 @@
+use crate::api::context::DcsAuthorizationService;
use axum::{extract, response::IntoResponse};
+use macro_authorization::MacroAuthorizationExtractor;
use macro_env_var::maybe_env_vars;
const OPENAI_CHAT_COMPLETIONS_URL: &str = "https://api.openai.com/v1/chat/completions";
@@ -8,8 +10,9 @@ maybe_env_vars! {
}
/// A non-streaming proxy to the chatgpt api
-#[tracing::instrument(err(Debug), skip(body))]
+#[tracing::instrument(err(Debug), skip(_user, body))]
pub async fn handler(
+ _user: MacroAuthorizationExtractor<DcsAuthorizationService>,
extract::Json(mut body): extract::Json<serde_json::Value>,
) -> impl IntoResponse {
if let Some(obj) = body.as_object_mut() {
diff --git a/services/document_cognition_service/src/api/context/mod.rs b/services/document_cognition_service/src/api/context/mod.rs
index 16a84c31fc..b5eb7708d6 100644
--- a/services/document_cognition_service/src/api/context/mod.rs
+++ b/services/document_cognition_service/src/api/context/mod.rs
@@ -17,7 +17,10 @@ use document_storage_service_client::DocumentStorageServiceClient;
use documents::inbound::attachment::DocumentAttachmentService;
use email::inbound::attachment::EmailAttachmentService;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
-use macro_auth::{InternalApiKey, middleware::decode_jwt::JwtValidationArgs};
+use macro_auth::InternalApiKey;
+use macro_authorization::{
+ MacroAuthJwtValidator, MacroAuthorizationServiceImpl, MacroAuthorizationState,
+};
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
use notification::outbound::websocket::ConnectionGatewayClient;
@@ -31,6 +34,22 @@ use stream::domain::StreamRepo;
/// Type alias for the entity access service.
pub type DcsEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
+/// Type alias for the authorization service.
+pub type DcsAuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
+
+/// Type alias for the roles-and-permissions service backed by MacroDB.
+pub type DcsUserPermissionsService =
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl<
+ roles_and_permissions::outbound::pgpool::MacroDB,
+ roles_and_permissions::outbound::pgpool::MacroDB,
+ >;
+
+/// Type alias for the chat model entitlement extractor wired to DCS services.
+pub type DcsChatModelAccess = chat::inbound::http::extractors::ChatModelAccess<
+ DcsAuthorizationService,
+ DcsUserPermissionsService,
+>;
+
/// Type alias for the attachment provider wired to concrete DCS services.
pub type DcsAttachmentProvider = AttachmentProvider<
DocumentAttachmentService<ToolDocumentService, ToolEntityAccessService>,
@@ -73,6 +92,7 @@ pub type DcsMcpRouterState = mcp_client::inbound::McpRouterState<
mcp_client::outbound::pg_server_repo::PgServerRepo,
mcp_client::outbound::redis_state_store::RedisOAuthStateStore,
>,
+ DcsAuthorizationService,
>;
#[derive(Clone, FromRef)]
@@ -82,7 +102,8 @@ pub struct ApiContext {
pub document_storage_client: Arc<DocumentStorageServiceClient>,
pub search_service_client: Arc<SearchServiceClient>,
pub email_service_client_external: Arc<email_service_client::EmailServiceClientExternal>,
- pub jwt_args: JwtValidationArgs,
+ pub authorization_state: MacroAuthorizationState<DcsAuthorizationService>,
+ pub user_permissions_service: Arc<DcsUserPermissionsService>,
pub config: Arc<Config>,
pub internal_api_key: InternalApiKey,
pub notification_ingress_service: Arc<NotificationIngressType>,
@@ -107,4 +128,14 @@ pub struct ApiContext {
pub mcp_state: DcsMcpRouterState,
}
+impl FromRef<ApiContext>
+ for chat::inbound::http::extractors::UserPermissionsState<DcsUserPermissionsService>
+{
+ fn from_ref(state: &ApiContext) -> Self {
+ chat::inbound::http::extractors::UserPermissionsState(
+ state.user_permissions_service.clone(),
+ )
+ }
+}
+
pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 9d16bc0264..cbc9511cec 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -404,13 +404,32 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
),
);
+ let authorization_state =
+ MacroAuthorizationState::new(Arc::new(MacroAuthorizationServiceImpl::new(
+ MacroAuthJwtValidator::new(
+ macro_auth::middleware::decode_jwt::JwtValidationArgs::new_testing(),
+ ),
+ macro_authorization::InternalAuthConfig {
+ api_key: "testing".to_string(),
+ default_user_id: None,
+ },
+ )));
+
+ let user_permissions_service = Arc::new(
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
+ ),
+ );
+
let api_context = ApiContext {
db: pool.clone(),
sqs_client: Arc::new(sqs_client),
document_storage_client,
search_service_client,
email_service_client_external,
- jwt_args: JwtValidationArgs::new_testing(),
+ authorization_state: authorization_state.clone(),
+ user_permissions_service,
config: Arc::new(Config::new_empty_for_test()),
internal_api_key: InternalApiKey::Comptime("testing"),
notification_ingress_service,
@@ -480,7 +499,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
"http://localhost/mcp/servers/auth/callback".to_string(),
mcp_client::domain::provider_registry::PreRegisteredProviders::empty(),
);
- mcp_client::inbound::McpRouterState::new(mcp_repo, mcp_oauth)
+ mcp_client::inbound::McpRouterState::new(mcp_repo, mcp_oauth, authorization_state)
},
};
Arc::new(api_context)
diff --git a/services/document_cognition_service/src/api/id_mapping/create.rs b/services/document_cognition_service/src/api/id_mapping/create.rs
index 58e74019c2..30d6bc3c4d 100644
--- a/services/document_cognition_service/src/api/id_mapping/create.rs
+++ b/services/document_cognition_service/src/api/id_mapping/create.rs
@@ -1,11 +1,13 @@
//! Handler for creating ID mappings.
+use crate::api::context::DcsAuthorizationService;
use crate::service::id_mapping::create_id_mapping;
use axum::{
Json,
extract::{Path, State},
http::StatusCode,
};
+use macro_authorization::MacroAuthorizationExtractor;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -44,9 +46,10 @@ pub struct CreateIdMappingResponse {
(status = 500, body = String),
)
)]
-#[tracing::instrument(skip(db))]
+#[tracing::instrument(skip(db, _user))]
pub async fn create_id_mapping_handler(
State(db): State<PgPool>,
+ _user: MacroAuthorizationExtractor<DcsAuthorizationService>,
Path(Params { source_id }): Path<Params>,
Json(req): Json<CreateIdMappingRequest>,
) -> Result<(StatusCode, Json<CreateIdMappingResponse>), (StatusCode, String)> {
diff --git a/services/document_cognition_service/src/api/id_mapping/get_mapping.rs b/services/document_cognition_service/src/api/id_mapping/get_mapping.rs
index 1d4459f06a..18633f4455 100644
--- a/services/document_cognition_service/src/api/id_mapping/get_mapping.rs
+++ b/services/document_cognition_service/src/api/id_mapping/get_mapping.rs
@@ -1,11 +1,13 @@
//! Handler for retrieving ID mappings.
+use crate::api::context::DcsAuthorizationService;
use crate::service::id_mapping::get_id_mapping;
use axum::{
Json,
extract::{Path, State},
http::StatusCode,
};
+use macro_authorization::MacroAuthorizationExtractor;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -36,9 +38,10 @@ pub struct GetIdMappingResponse {
(status = 500, body = String),
)
)]
-#[tracing::instrument(skip(db))]
+#[tracing::instrument(skip(db, _user))]
pub async fn get_id_mapping_handler(
State(db): State<PgPool>,
+ _user: MacroAuthorizationExtractor<DcsAuthorizationService>,
Path(Params { source_id }): Path<Params>,
) -> Result<Json<GetIdMappingResponse>, (StatusCode, String)> {
let target_id = get_id_mapping(&db, &source_id).await.map_err(|e| {
diff --git a/services/document_cognition_service/src/api/id_mapping/mod.rs b/services/document_cognition_service/src/api/id_mapping/mod.rs
index 0cb8b3695b..62813b2067 100644
--- a/services/document_cognition_service/src/api/id_mapping/mod.rs
+++ b/services/document_cognition_service/src/api/id_mapping/mod.rs
@@ -6,7 +6,6 @@ use axum::{
Router,
routing::{get, post},
};
-use tower::ServiceBuilder;
use crate::api::context::ApiContext;
@@ -16,16 +15,6 @@ mod get_mapping;
/// Creates the router for id_mapping endpoints.
pub fn router() -> Router<ApiContext> {
Router::new()
- .route(
- "/{source_id}",
- post(create::create_id_mapping_handler).layer(ServiceBuilder::new().layer(
- axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler),
- )),
- )
- .route(
- "/{source_id}",
- get(get_mapping::get_id_mapping_handler).layer(ServiceBuilder::new().layer(
- axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler),
- )),
- )
+ .route("/{source_id}", post(create::create_id_mapping_handler))
+ .route("/{source_id}", get(get_mapping::get_id_mapping_handler))
}
diff --git a/services/document_cognition_service/src/api/mod.rs b/services/document_cognition_service/src/api/mod.rs
index 5816644349..97951b58a6 100644
--- a/services/document_cognition_service/src/api/mod.rs
+++ b/services/document_cognition_service/src/api/mod.rs
@@ -73,54 +73,42 @@ fn api_router(api_context: ApiContext) -> Router {
let memory_service = api_context.memory_service.clone();
let usage_service = api_context.usage_service.clone();
let ai_projections_service = api_context.ai_projections_service.clone();
+ let authorization_state = api_context.authorization_state.clone();
let mcp_state = api_context.mcp_state.clone();
let internal_router = Router::new()
.nest("/chats", chats::router(api_context.clone()))
- .nest("/stream", stream::router(api_context.clone()))
+ .nest("/stream", stream::router())
.route(
"/structured-completion",
- post(structured_completion::structured_completion).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- api_context.clone(),
- macro_middleware::user_permissions::attach_user_permissions::handler,
- )),
- ),
+ post(structured_completion::structured_completion),
)
+ .route("/chat/completions", post(completions::handler))
.nest("/attachments", attachments::router())
.nest("/citations", citations::router())
.nest("/preview", preview::router())
.nest("/id_mapping", id_mapping::router())
- .merge(memory::inbound::axum_router::memory_router(memory_service))
- .merge(ai_usage::inbound::ai_usage_router(usage_service))
+ .merge(memory::inbound::axum_router::memory_router(
+ memory::inbound::axum_router::MemoryRouterState {
+ service: memory_service,
+ authorization_state: authorization_state.clone(),
+ },
+ ))
+ .merge(ai_usage::inbound::ai_usage_router(
+ ai_usage::inbound::AiUsageRouterState {
+ service: usage_service,
+ authorization_state: authorization_state.clone(),
+ },
+ ))
.merge(ai_projections::inbound::axum_router::ai_projections_router(
ai_projections::inbound::axum_router::AiProjectionRouterState {
service: ai_projections_service,
+ authorization_state,
},
))
.merge(mcp_client::inbound::mcp_router(mcp_state.clone()))
- .with_state(api_context.clone())
- .route(
- "/chat/completions",
- post(completions::handler).layer(ServiceBuilder::new().layer(
- axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler),
- )),
- )
- .layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::auth::initialize_user_context::handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- api_context.jwt_args.clone(),
- macro_middleware::auth::attach_user::handler,
- )),
- );
+ .with_state(api_context.clone());
Router::new()
.nest("/{version}", internal_router.clone())
diff --git a/services/document_cognition_service/src/api/preview/get_batch_preview.rs b/services/document_cognition_service/src/api/preview/get_batch_preview.rs
index 1b239c969c..1b1df5375d 100644
--- a/services/document_cognition_service/src/api/preview/get_batch_preview.rs
+++ b/services/document_cognition_service/src/api/preview/get_batch_preview.rs
@@ -1,6 +1,8 @@
+use crate::api::context::DcsAuthorizationService;
use anyhow::Result;
use axum::extract::{Json, State};
use axum::{extract, http::StatusCode};
+use macro_authorization::OptionalMacroAuthorizationExtractor;
use model::chat::preview::{ChatPreview, ChatPreviewData, ChatPreviewV2, WithChatId};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -27,9 +29,13 @@ pub struct GetBatchPreviewResponse {
(status = 500, body=String),
)
)]
-#[tracing::instrument(skip(db))]
+#[tracing::instrument(skip(db, _user))]
pub async fn handler(
State(db): State<PgPool>,
+ // Anonymous access is allowed, but supplied invalid/expired credentials
+ // are still rejected with a 401 (matches the pre-migration behavior of
+ // the router-wide auth layer).
+ _user: OptionalMacroAuthorizationExtractor<DcsAuthorizationService>,
req: extract::Json<GetBatchPreviewRequest>,
) -> Result<(StatusCode, Json<GetBatchPreviewResponse>), (StatusCode, String)> {
// Ensure the document ids are unique to prevent duplicate work
diff --git a/services/document_cognition_service/src/api/stream/chat_message/mod.rs b/services/document_cognition_service/src/api/stream/chat_message/mod.rs
index 520276b83f..288e74eadd 100644
--- a/services/document_cognition_service/src/api/stream/chat_message/mod.rs
+++ b/services/document_cognition_service/src/api/stream/chat_message/mod.rs
@@ -3,7 +3,7 @@ use super::util::chat_message::ai_request::build_chat_messages;
use super::util::chat_message::toolset::choose_tools_prompt;
use super::util::chat_message::{store_conversation_messages, store_incoming_message};
use super::util::chat_permissions;
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, DcsAuthorizationService, DcsChatModelAccess};
use crate::api::utils::log;
use crate::core::constants::DEFAULT_CHAT_NAME;
use crate::model::stream::{
@@ -23,14 +23,13 @@ use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::IntoResponse;
use chat::domain::ports::MessageService;
-use chat::inbound::http::extractors::ChatModelAccess;
use futures::StreamExt;
use macro_auth::headers::AccessTokenExtractor;
+use macro_authorization::MacroAuthorizationExtractor;
use macro_db_client::dcs::create_chat;
use macro_user_id::user_id::MacroUserIdStr;
use mcp_client::domain::ports::McpServerStore;
use memory::domain::MemoryService;
-use model::user::UserContext;
use model_entity::{Entity, EntityType};
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -136,18 +135,18 @@ impl IntoResponse for ChatMessageError {
(status = 403, description = "Forbidden"),
)
)]
-#[tracing::instrument(skip(state, model_access, user_context, bearer, request), fields(chat_id=?request.chat_id, user_id = %user_context.user_id, attachment_ids=?request.attachments.as_ref().map(|a| a.iter().map(|att| att.entity_id.as_ref()).collect::<Vec<_>>()).unwrap_or_default()), ret, err)]
+#[tracing::instrument(skip(state, model_access, user, bearer, request), fields(chat_id=?request.chat_id, user_id = %user.macro_user_id, attachment_ids=?request.attachments.as_ref().map(|a| a.iter().map(|att| att.entity_id.as_ref()).collect::<Vec<_>>()).unwrap_or_default()), ret, err)]
pub async fn send_chat_message(
State(state): State<ApiContext>,
- model_access: ChatModelAccess,
- Extension(user_context): Extension<UserContext>,
+ model_access: DcsChatModelAccess,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService>,
Extension(bearer): Extension<BearerToken>,
Json(request): Json<HttpSendChatMessageRequest>,
) -> Result<Json<SendChatMessageResponse>, ChatMessageError> {
Box::pin(send_chat_message_inner(
state,
model_access,
- user_context,
+ user.macro_user_id,
bearer,
request,
))
@@ -156,8 +155,8 @@ pub async fn send_chat_message(
async fn send_chat_message_inner(
state: ApiContext,
- model_access: ChatModelAccess,
- user_context: UserContext,
+ model_access: DcsChatModelAccess,
+ user_id: MacroUserIdStr<'static>,
bearer: BearerToken,
request: HttpSendChatMessageRequest,
) -> Result<Json<SendChatMessageResponse>, ChatMessageError> {
@@ -169,13 +168,6 @@ async fn send_chat_message_inner(
let message_id = uuid::Uuid::new_v4().to_string();
let stream_id = message_id.clone();
- // Validate user ID
- let user_id =
- MacroUserIdStr::try_from(user_context.user_id.clone()).map_err(|_| ChatMessageError {
- error: "Invalid user ID".to_string(),
- stream_id: Some(stream_id.clone()),
- status: None,
- })?;
let user_id = Arc::new(user_id);
// Determine chat_id - use provided or we'll create a new chat
@@ -203,7 +195,7 @@ async fn send_chat_message_inner(
// Chat exists - check permissions
match chat_permissions::chat_access(
&ctx,
- &user_context,
+ &user_id,
&requested_chat_id,
stream_id.clone(),
)
diff --git a/services/document_cognition_service/src/api/stream/mod.rs b/services/document_cognition_service/src/api/stream/mod.rs
index e554d98952..8611e2d134 100644
--- a/services/document_cognition_service/src/api/stream/mod.rs
+++ b/services/document_cognition_service/src/api/stream/mod.rs
@@ -8,24 +8,13 @@ pub mod stop;
mod util;
use axum::{Router, routing::post};
-use tower::ServiceBuilder;
use crate::api::context::ApiContext;
/// Create the stream API router
-pub fn router(state: ApiContext) -> Router<ApiContext> {
+pub fn router() -> Router<ApiContext> {
Router::new()
.route("/chat/message", post(chat_message::send_chat_message))
.route("/chat/message/stop", post(stop::stop_chat_stream))
- .layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state,
- macro_middleware::user_permissions::attach_user_permissions::handler,
- ))
- .layer(axum::middleware::from_fn(chat_message::attach_bearer_token)),
- )
+ .layer(axum::middleware::from_fn(chat_message::attach_bearer_token))
}
diff --git a/services/document_cognition_service/src/api/stream/stop.rs b/services/document_cognition_service/src/api/stream/stop.rs
index c7452975e3..ae6f424650 100644
--- a/services/document_cognition_service/src/api/stream/stop.rs
+++ b/services/document_cognition_service/src/api/stream/stop.rs
@@ -5,13 +5,13 @@
//! whatever the user has already seen, and emits `StreamEnd` over the
//! durable stream.
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, DcsAuthorizationService};
use crate::api::stream::util::chat_permissions;
use axum::Json;
-use axum::extract::{Extension, State};
+use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
-use model::user::UserContext;
+use macro_authorization::MacroAuthorizationExtractor;
use models_permissions::share_permission::access_level::AccessLevel;
use serde::{Deserialize, Serialize};
use std::fmt;
@@ -68,15 +68,15 @@ impl IntoResponse for StopChatStreamError {
(status = 403, description = "Forbidden", body = StopChatStreamError),
)
)]
-#[tracing::instrument(skip(state, user_context), fields(chat_id = %request.chat_id, stream_id = %request.stream_id, user_id = %user_context.user_id), err)]
+#[tracing::instrument(skip(state, user), fields(chat_id = %request.chat_id, stream_id = %request.stream_id, user_id = %user.macro_user_id), err)]
pub async fn stop_chat_stream(
State(state): State<ApiContext>,
- Extension(user_context): Extension<UserContext>,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService>,
Json(request): Json<StopChatStreamRequest>,
) -> Result<Json<StopChatStreamResponse>, StopChatStreamError> {
let access = chat_permissions::chat_access(
&state,
- &user_context,
+ &user.macro_user_id,
&request.chat_id,
request.stream_id.clone(),
)
diff --git a/services/document_cognition_service/src/api/stream/util/chat_permissions.rs b/services/document_cognition_service/src/api/stream/util/chat_permissions.rs
index c7efb23b4d..3948097789 100644
--- a/services/document_cognition_service/src/api/stream/util/chat_permissions.rs
+++ b/services/document_cognition_service/src/api/stream/util/chat_permissions.rs
@@ -2,7 +2,6 @@ use crate::api::context::ApiContext;
use anyhow::Result;
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
-use model::user::UserContext;
use model_entity::EntityType;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -10,21 +9,19 @@ use models_permissions::share_permission::access_level::AccessLevel;
err,
skip(ctx),
fields(
- user_id = %user_ctx.user_id,
+ user_id = %user_id,
chat_id = %chat_id,
stream_id = %stream_id,
)
)]
pub async fn chat_access(
ctx: &ApiContext,
- user_ctx: &UserContext,
+ user_id: &MacroUserIdStr<'_>,
chat_id: &str,
stream_id: String,
) -> Result<AccessLevel> {
- let user_id = MacroUserIdStr::parse_from_str(&user_ctx.user_id)
- .map_err(|e| anyhow::anyhow!("Failed to parse user_id: {e}"))?;
ctx.entity_access_service
- .get_access_level(Some(&user_id), chat_id, EntityType::Chat)
+ .get_access_level(Some(user_id), chat_id, EntityType::Chat)
.await
.map_err(|e| anyhow::anyhow!(e))
.and_then(|access| match access {
diff --git a/services/document_cognition_service/src/api/structured_completion.rs b/services/document_cognition_service/src/api/structured_completion.rs
index b2e2c32d1f..3725d32818 100644
--- a/services/document_cognition_service/src/api/structured_completion.rs
+++ b/services/document_cognition_service/src/api/structured_completion.rs
@@ -1,17 +1,15 @@
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, DcsAuthorizationService, DcsChatModelAccess};
use crate::model::stream::ToolSet;
use agent::structured_output::DynamicSchema;
use agent::types::{ChatMessage, ChatMessageContent, Role};
use agent::{AgentLoop, StreamAccumulator};
use axum::Json;
-use axum::extract::{Extension, State};
+use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
-use chat::inbound::http::extractors::ChatModelAccess;
use futures::StreamExt;
-use macro_user_id::user_id::MacroUserIdStr;
+use macro_authorization::MacroAuthorizationExtractor;
use mcp_client::domain::ports::McpServerStore;
-use model::user::UserContext;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::Arc;
@@ -64,22 +62,17 @@ impl IntoResponse for StructuredCompletionError {
(status = 500, description = "Internal error", body = StructuredCompletionError),
)
)]
-#[tracing::instrument(skip(state, model_access, user_context, request), fields(user_id = %user_context.user_id), err)]
+#[tracing::instrument(skip(state, model_access, user, request), fields(user_id = %user.macro_user_id), err)]
pub async fn structured_completion(
State(state): State<ApiContext>,
- model_access: ChatModelAccess,
- Extension(user_context): Extension<UserContext>,
+ model_access: DcsChatModelAccess,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService>,
Json(request): Json<StructuredCompletionRequest>,
) -> Result<Json<StructuredCompletionResponse>, StructuredCompletionError> {
let ctx = Arc::new(state);
let model = model_access.best_model();
- let user_id = MacroUserIdStr::try_from(user_context.user_id.clone()).map_err(|_| {
- StructuredCompletionError {
- error: "Invalid user ID".to_string(),
- status: StatusCode::BAD_REQUEST,
- }
- })?;
+ let user_id = user.macro_user_id;
let tools_prompt: &(dyn std::fmt::Display + Sync) = match request.toolset {
ToolSet::All => &ctx.all_tools_prompt,
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index 7c1a2e0f0d..63b28a4ea2 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -28,6 +28,10 @@ use foreign_entity::{
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+use macro_authorization::{
+ InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
+ MacroAuthorizationState,
+};
use macro_entrypoint::MacroEntrypoint;
use macro_service_urls::{
ConnectionGatewayUrl, DocumentCognitionServiceUrl, DocumentStorageServiceUrl, EmailServiceUrl,
@@ -141,6 +145,15 @@ async fn main() -> anyhow::Result<()> {
.await
.context("failed to create jwt validation args")?;
+ let authorization_state =
+ MacroAuthorizationState::new(Arc::new(MacroAuthorizationServiceImpl::new(
+ MacroAuthJwtValidator::new(jwt_args),
+ InternalAuthConfig {
+ api_key: internal_api_key.clone(),
+ default_user_id: None,
+ },
+ )));
+
let lexical_client = Arc::new(lexical_client::LexicalClient::new(
internal_api_key.clone(),
LexicalServiceUrl::new()?.to_string(),
@@ -515,7 +528,18 @@ async fn main() -> anyhow::Result<()> {
mcp_redirect_uri,
mcp_pre_registered,
);
- let mcp_state = mcp_client::inbound::McpRouterState::new(mcp_server_repo, mcp_oauth);
+ let mcp_state = mcp_client::inbound::McpRouterState::new(
+ mcp_server_repo,
+ mcp_oauth,
+ authorization_state.clone(),
+ );
+
+ let user_permissions_service = Arc::new(
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
+ roles_and_permissions::outbound::pgpool::MacroDB::new(db.clone()),
+ roles_and_permissions::outbound::pgpool::MacroDB::new(db.clone()),
+ ),
+ );
api::setup_and_serve(ApiContext {
db: db.clone(),
@@ -523,7 +547,8 @@ async fn main() -> anyhow::Result<()> {
sqs_client: Arc::new(sqs_client),
document_storage_client: Arc::new(document_storage_client),
search_service_client,
- jwt_args,
+ authorization_state,
+ user_permissions_service,
internal_api_key: config.internal_api_key.clone(),
config: Arc::new(config),
notification_ingress_service,