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(macro_authorization): MacroAuthorization enum (#5058)

Will Hutchinson47ac13b16873
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 0ddc1ffc31..a0ce954738 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -6,6 +6,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -299,6 +300,7 @@
],
"ai_usage": [
"crates/ai_usage",
+ "crates/bot_id",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -452,6 +454,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/authentication_service_client",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -1050,6 +1053,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
@@ -1099,6 +1103,7 @@
"crates/workspace-hack"
],
"contacts": [
+ "crates/bot_id",
"crates/contacts",
"crates/cowlike",
"crates/macro_auth",
@@ -1118,6 +1123,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/contacts",
"crates/cowlike",
"crates/database_env_vars",
@@ -1633,6 +1639,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_storage_service_client",
"crates/document_sub_type",
@@ -1664,6 +1671,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -2355,6 +2363,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -2630,6 +2639,7 @@
"crates/workspace-hack"
],
"graphql_common": [
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/filter_ast",
@@ -2707,6 +2717,7 @@
],
"graphql_notification": [
"crates/ai_toolset",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/filter_ast",
@@ -2881,6 +2892,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -2925,6 +2937,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
@@ -2947,6 +2960,7 @@
],
"invite_email": [
"crates/ai_toolset",
+ "crates/bot_id",
"crates/cowlike",
"crates/invite_email",
"crates/last_online_tracker",
@@ -3178,6 +3192,7 @@
"crates/workspace-hack"
],
"macro_authorization": [
+ "crates/bot_id",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -3225,6 +3240,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -3291,6 +3307,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -3344,6 +3361,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -3401,6 +3419,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -3646,6 +3665,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -3996,6 +4016,7 @@
],
"notification": [
"crates/ai_toolset",
+ "crates/bot_id",
"crates/cowlike",
"crates/last_online_tracker",
"crates/macro_auth",
@@ -4132,6 +4153,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
@@ -4447,6 +4469,7 @@
],
"referral": [
"crates/ai_toolset",
+ "crates/bot_id",
"crates/cowlike",
"crates/invite_email",
"crates/ip_extractor",
@@ -5273,6 +5296,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -5329,6 +5353,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -5353,6 +5378,7 @@
"crates/workspace-hack"
],
"sync_service_hex": [
+ "crates/bot_id",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -5668,6 +5694,7 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/bot_id",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
diff --git a/.sqlx/query-0770d1265be3dd87e6c4cba304688f970c66e77cb0e0ca33b67ddbe735bfeea7.json b/.sqlx/query-0770d1265be3dd87e6c4cba304688f970c66e77cb0e0ca33b67ddbe735bfeea7.json
new file mode 100644
index 0000000000..606383efb9
--- /dev/null
+++ b/.sqlx/query-0770d1265be3dd87e6c4cba304688f970c66e77cb0e0ca33b67ddbe735bfeea7.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id AS fusion_user_id,\n email,\n \"organizationId\" AS \"organization_id?\"\n FROM \"User\"\n WHERE email = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "fusion_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "organization_id?",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "0770d1265be3dd87e6c4cba304688f970c66e77cb0e0ca33b67ddbe735bfeea7"
+}
diff --git a/.sqlx/query-0dd8b8765c6b7e09bfd135aa09531a385936a23b16b948a1062e7dd79a500afd.json b/.sqlx/query-0dd8b8765c6b7e09bfd135aa09531a385936a23b16b948a1062e7dd79a500afd.json
new file mode 100644
index 0000000000..4713ffff2f
--- /dev/null
+++ b/.sqlx/query-0dd8b8765c6b7e09bfd135aa09531a385936a23b16b948a1062e7dd79a500afd.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id AS fusion_user_id,\n email,\n \"organizationId\" AS \"organization_id?\"\n FROM \"User\"\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "fusion_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "organization_id?",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "0dd8b8765c6b7e09bfd135aa09531a385936a23b16b948a1062e7dd79a500afd"
+}
diff --git a/.sqlx/query-b36c8af057dab26d2394ba92ea5ed1f83c702a50af77552512c8fa5e3440e317.json b/.sqlx/query-b36c8af057dab26d2394ba92ea5ed1f83c702a50af77552512c8fa5e3440e317.json
new file mode 100644
index 0000000000..dbbab0c9ca
--- /dev/null
+++ b/.sqlx/query-b36c8af057dab26d2394ba92ea5ed1f83c702a50af77552512c8fa5e3440e317.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_participants\n WHERE channel_id = $1\n AND user_id = $2\n AND left_at IS NULL\n ) AS \"is_active!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "is_active!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "b36c8af057dab26d2394ba92ea5ed1f83c702a50af77552512c8fa5e3440e317"
+}
diff --git a/.sqlx/query-eb3db180aff5d16f1eed86bfbddf2ffbe4cec0122e364242dec6fec10a98c1c8.json b/.sqlx/query-eb3db180aff5d16f1eed86bfbddf2ffbe4cec0122e364242dec6fec10a98c1c8.json
new file mode 100644
index 0000000000..07ddddb5f3
--- /dev/null
+++ b/.sqlx/query-eb3db180aff5d16f1eed86bfbddf2ffbe4cec0122e364242dec6fec10a98c1c8.json
@@ -0,0 +1,46 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n bt.id AS token_id,\n b.id AS bot_id,\n b.kind,\n b.owner_user_id,\n b.team_id\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n WHERE bt.token = $1\n AND bt.revoked_at IS NULL\n AND (bt.expires_at IS NULL OR bt.expires_at > now())\n AND b.deleted_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "token_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "bot_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "team_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "eb3db180aff5d16f1eed86bfbddf2ffbe4cec0122e364242dec6fec10a98c1c8"
+}
diff --git a/Cargo.lock b/Cargo.lock
index f4e2631542..13ab36dc3f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8236,11 +8236,13 @@ name = "macro_authorization"
version = "0.1.0"
dependencies = [
"axum",
+ "bot_id",
"constant_time_eq",
"cookie",
"http-body-util",
"jsonwebtoken 10.3.0",
"macro_auth",
+ "macro_db_migrator",
"macro_env_var",
"macro_user_id",
"model-error-response",
@@ -8249,11 +8251,13 @@ dependencies = [
"serde",
"serde_json",
"serde_urlencoded",
+ "sqlx",
"thiserror 2.0.18",
"tokio",
"tower 0.5.3",
"tracing",
"urlencoding",
+ "uuid",
"workspace-hack",
]
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index d1d8c6f095..ad810a900e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -2883,9 +2883,14 @@ export const postChannelBotWebhookParams = zod.object({
});
export const postChannelBotWebhookHeader = zod.object({
+ 'x-macro-bot-token': zod
+ .string()
+ .nullish()
+ .describe('Preferred bot authentication token'),
'x-macro-channel-bot-token': zod
.string()
- .describe('Bot authentication token'),
+ .nullish()
+ .describe('Legacy channel-scoped bot authentication token'),
});
export const postChannelBotWebhookBody = zod
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index f47e13393c..92d7ee7521 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -3882,13 +3882,23 @@
"format": "uuid"
}
},
+ {
+ "name": "x-macro-bot-token",
+ "in": "header",
+ "description": "Preferred bot authentication token",
+ "required": false,
+ "schema": {
+ "type": ["string", "null"]
+ }
+ },
{
"name": "x-macro-channel-bot-token",
"in": "header",
- "description": "Bot authentication token",
- "required": true,
+ "description": "Legacy channel-scoped bot authentication token",
+ "required": false,
+ "deprecated": true,
"schema": {
- "type": "string"
+ "type": ["string", "null"]
}
}
],
@@ -3933,6 +3943,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
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 ff2aa93269..b9ce03b0b5 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 macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use crate::domain::{
ai_projection_service::{AiProjectionService, requires_professional_features},
@@ -98,9 +98,11 @@ impl From<UserAiProjection> for ProjectionStateResponse {
#[tracing::instrument(skip_all, err)]
pub async fn handler<T: AiProjectionService, Auth: MacroAuthorizationService>(
State(state): State<AiProjectionRouterState<T, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<UpsertProjectionRequest>,
) -> Result<Json<ProjectionStateResponse>, UpsertProjectionError> {
+ let user = user.authorization.user;
+
// Free-tier models are available to everyone; anything else (including
// the default smart model when no model is named) is premium-only.
if requires_professional_features(req.model.as_deref())
diff --git a/crates/ai_usage/src/inbound/axum_router.rs b/crates/ai_usage/src/inbound/axum_router.rs
index b88537b811..9f87e3fb73 100644
--- a/crates/ai_usage/src/inbound/axum_router.rs
+++ b/crates/ai_usage/src/inbound/axum_router.rs
@@ -13,7 +13,7 @@ use axum::{
};
use chrono::{DateTime, Utc};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use serde::{Deserialize, Serialize};
@@ -101,8 +101,16 @@ where
}
/// Returns `Some(403)` unless the caller is a Macro admin.
-fn admin_rejection<Auth>(user: &MacroAuthorizationExtractor<Auth>) -> Option<Response> {
- if user.macro_user_id.email_str().ends_with(ADMIN_EMAIL_SUFFIX) {
+fn admin_rejection<Auth>(
+ user: &MacroAuthorizationExtractor<Auth, UserOrInternal>,
+) -> Option<Response> {
+ if user
+ .authorization
+ .user
+ .macro_user_id
+ .email_str()
+ .ends_with(ADMIN_EMAIL_SUFFIX)
+ {
None
} else {
Some(
@@ -140,10 +148,13 @@ fn internal_error(context: &str) -> Response {
),
tag = "ai_usage"
)]
-#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(
+ skip(service, user),
+ fields(actor = %user.acting_entity())
+)]
pub async fn get_usage_handler<T: UsageService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<UsageRequest>,
) -> Response {
if let Some(resp) = admin_rejection(&user) {
@@ -196,10 +207,13 @@ pub async fn get_usage_handler<T: UsageService, Auth: MacroAuthorizationService>
),
tag = "ai_usage"
)]
-#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(
+ skip(service, user),
+ fields(actor = %user.acting_entity())
+)]
pub async fn set_pricing_handler<T: UsageService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<SetPricingRequest>,
) -> Response {
if let Some(resp) = admin_rejection(&user) {
diff --git a/crates/bots/Cargo.toml b/crates/bots/Cargo.toml
index 5278a10216..152de16154 100644
--- a/crates/bots/Cargo.toml
+++ b/crates/bots/Cargo.toml
@@ -14,6 +14,7 @@ inbound = [
"entity_access/ports",
"dep:macro_authorization",
"dep:model-error-response",
+ "macro_authorization/axum",
"dep:serde_json",
"dep:utoipa",
"ports",
@@ -29,7 +30,7 @@ channels = { path = "../channels", optional = true, default-features = false, fe
chrono = { workspace = true }
entity_access = { path = "../entity_access", optional = true, default-features = false }
hex = { workspace = true }
-macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }
+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false }
macro_event_broker = { path = "../macro_event_broker", default-features = false }
macro_event_topics = { path = "../macro_event_topics" }
macro_user_id = { path = "../macro_user_id" }
diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rs
index b5f74b8ae3..8935b9b6ab 100644
--- a/crates/bots/src/domain/ports.rs
+++ b/crates/bots/src/domain/ports.rs
@@ -49,6 +49,13 @@ pub trait BotRepo: Clone + Send + Sync + 'static {
team_id: Uuid,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Check whether a bot is an active channel participant.
+ fn bot_active_in_channel(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
/// Patch an active bot.
fn patch_bot(
&self,
@@ -221,6 +228,13 @@ pub trait BotService: Clone + Send + Sync + 'static {
token_id: Uuid,
) -> impl Future<Output = Result<(), BotError>> + Send;
+ /// Ensure that a bot is an active participant in a channel.
+ fn ensure_bot_in_channel(
+ &self,
+ bot_id: BotId,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<(), BotError>> + Send;
+
/// Authenticate a raw bearer token.
fn authenticate_token(
&self,
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index a3e4e19521..678066dd75 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -52,6 +52,11 @@ fn token_candidate_is_valid(candidate: &BotTokenCandidate, now: &DateTime<Utc>)
.is_none_or(|expires_at| expires_at > now)
}
+struct ValidatedBotToken {
+ bot: AuthenticatedBot,
+ token_id: Uuid,
+}
+
impl<R, B> BotServiceImpl<R, B>
where
R: BotRepo,
@@ -123,7 +128,7 @@ where
async fn authenticate_candidate(
&self,
candidate: Option<BotTokenCandidate>,
- ) -> Result<AuthenticatedBot, BotError> {
+ ) -> Result<ValidatedBotToken, BotError> {
let Some(candidate) = candidate else {
return Err(BotError::Unauthorized);
};
@@ -133,13 +138,15 @@ where
return Err(BotError::Unauthorized);
}
- let token_id = candidate.token.id;
- let bot = candidate.bot;
+ let authenticated = ValidatedBotToken {
+ bot: candidate.bot,
+ token_id: candidate.token.id,
+ };
self.repo
- .mark_token_used(token_id)
+ .mark_token_used(authenticated.token_id)
.await
.map_err(|err| BotError::Repo(err.into()))?;
- Ok(bot)
+ Ok(authenticated)
}
}
@@ -393,13 +400,26 @@ where
}
}
+ async fn ensure_bot_in_channel(&self, bot_id: BotId, channel_id: Uuid) -> Result<(), BotError> {
+ if self
+ .repo
+ .bot_active_in_channel(channel_id, bot_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ {
+ Ok(())
+ } else {
+ Err(BotError::Unauthorized)
+ }
+ }
+
async fn authenticate_token(&self, token: &str) -> Result<AuthenticatedBot, BotError> {
let candidate = self
.repo
.token_candidate(token)
.await
.map_err(|err| BotError::Repo(err.into()))?;
- self.authenticate_candidate(candidate).await
+ Ok(self.authenticate_candidate(candidate).await?.bot)
}
async fn authenticate_channel_token(
@@ -412,6 +432,6 @@ where
.channel_token_candidate(channel_id, token)
.await
.map_err(|err| BotError::Repo(err.into()))?;
- self.authenticate_candidate(candidate).await
+ Ok(self.authenticate_candidate(candidate).await?.bot)
}
}
diff --git a/crates/bots/src/inbound/axum_router.rs b/crates/bots/src/inbound/axum_router.rs
index b0dee63a4a..0249cb8a79 100644
--- a/crates/bots/src/inbound/axum_router.rs
+++ b/crates/bots/src/inbound/axum_router.rs
@@ -25,7 +25,7 @@ use entity_access::{
inbound::axum_extractors::ChannelAccessLevelExtractor,
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
@@ -181,12 +181,12 @@ async fn create_bot_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<CreateBotRequest>,
) -> Result<(StatusCode, Json<Bot>), BotsHandlerErr> {
let bot = state
.service
- .create_bot(authorization.macro_user_id, req)
+ .create_bot(authorization.authorization.user.macro_user_id, req)
.await?;
Ok((StatusCode::CREATED, Json(bot)))
}
@@ -197,10 +197,13 @@ async fn list_bots_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<Vec<Bot>>, BotsHandlerErr> {
Ok(Json(
- state.service.list_bots(authorization.macro_user_id).await?,
+ state
+ .service
+ .list_bots(authorization.authorization.user.macro_user_id)
+ .await?,
))
}
@@ -210,13 +213,13 @@ async fn get_bot_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<BotPath>,
) -> Result<Json<Bot>, BotsHandlerErr> {
Ok(Json(
state
.service
- .get_bot(authorization.macro_user_id, path.bot_id)
+ .get_bot(authorization.authorization.user.macro_user_id, path.bot_id)
.await?,
))
}
@@ -227,14 +230,18 @@ async fn patch_bot_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<BotPath>,
Json(req): Json<PatchBotRequest>,
) -> Result<Json<Bot>, BotsHandlerErr> {
Ok(Json(
state
.service
- .patch_bot(authorization.macro_user_id, path.bot_id, req)
+ .patch_bot(
+ authorization.authorization.user.macro_user_id,
+ path.bot_id,
+ req,
+ )
.await?,
))
}
@@ -245,12 +252,12 @@ async fn delete_bot_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<BotPath>,
) -> Result<StatusCode, BotsHandlerErr> {
state
.service
- .delete_bot(authorization.macro_user_id, path.bot_id)
+ .delete_bot(authorization.authorization.user.macro_user_id, path.bot_id)
.await?;
Ok(StatusCode::NO_CONTENT)
}
@@ -261,13 +268,17 @@ async fn create_token_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<BotPath>,
Json(req): Json<CreateBotTokenRequest>,
) -> Result<(StatusCode, Json<CreateBotTokenResponse>), BotsHandlerErr> {
let token = state
.service
- .create_token(authorization.macro_user_id, path.bot_id, req)
+ .create_token(
+ authorization.authorization.user.macro_user_id,
+ path.bot_id,
+ req,
+ )
.await?;
Ok((StatusCode::CREATED, Json(token)))
}
@@ -278,13 +289,13 @@ async fn list_tokens_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<BotPath>,
) -> Result<Json<Vec<BotToken>>, BotsHandlerErr> {
Ok(Json(
state
.service
- .list_tokens(authorization.macro_user_id, path.bot_id)
+ .list_tokens(authorization.authorization.user.macro_user_id, path.bot_id)
.await?,
))
}
@@ -295,12 +306,16 @@ async fn revoke_token_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<BotTokenPath>,
) -> Result<StatusCode, BotsHandlerErr> {
state
.service
- .revoke_token(authorization.macro_user_id, path.bot_id, path.token_id)
+ .revoke_token(
+ authorization.authorization.user.macro_user_id,
+ path.bot_id,
+ path.token_id,
+ )
.await?;
Ok(StatusCode::NO_CONTENT)
}
@@ -327,13 +342,13 @@ pub async fn list_bot_channels_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<BotPath>,
) -> Result<Json<Vec<BotChannel>>, BotsHandlerErr> {
Ok(Json(
state
.service
- .list_bot_channels(authorization.macro_user_id, path.bot_id)
+ .list_bot_channels(authorization.authorization.user.macro_user_id, path.bot_id)
.await?,
))
}
@@ -361,12 +376,16 @@ pub async fn remove_bot_channel_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<BotChannelPath>,
) -> Result<StatusCode, BotsHandlerErr> {
state
.service
- .remove_bot_from_channel(authorization.macro_user_id, path.channel_id, path.bot_id)
+ .remove_bot_from_channel(
+ authorization.authorization.user.macro_user_id,
+ path.channel_id,
+ path.bot_id,
+ )
.await?;
Ok(StatusCode::NO_CONTENT)
}
diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rs
index 2b1506d24a..b83ebff213 100644
--- a/crates/bots/src/inbound/axum_router/tests.rs
+++ b/crates/bots/src/inbound/axum_router/tests.rs
@@ -18,7 +18,7 @@ use entity_access::domain::{
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use macro_authorization::{
InternalAuthConfig, JwtValidator, MacroAuthorizationError, MacroAuthorizationServiceImpl,
- MacroAuthorizationState, ValidatedIdentity,
+ MacroAuthorizationState, NoBotAuthorizer, ValidatedIdentity,
};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_event_broker::NoopMacroEventBroker;
@@ -179,6 +179,14 @@ impl BotService for TestBotService {
unimplemented!()
}
+ async fn ensure_bot_in_channel(
+ &self,
+ _bot_id: BotId,
+ _channel_id: Uuid,
+ ) -> Result<(), BotError> {
+ unimplemented!()
+ }
+
async fn authenticate_token(&self, _token: &str) -> Result<AuthenticatedBot, BotError> {
unimplemented!()
}
@@ -327,6 +335,7 @@ fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
api_key: "test-internal-key".to_string(),
default_user_id: None,
},
+ NoBotAuthorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
diff --git a/crates/bots/src/inbound/channel_webhook_router.rs b/crates/bots/src/inbound/channel_webhook_router.rs
index 7a854ed94a..f5e8749f74 100644
--- a/crates/bots/src/inbound/channel_webhook_router.rs
+++ b/crates/bots/src/inbound/channel_webhook_router.rs
@@ -13,8 +13,8 @@ use crate::domain::{
use axum::{
Json, Router,
body::Bytes,
- extract::{FromRef, Path, State},
- http::{HeaderMap, StatusCode, header::CONTENT_TYPE},
+ extract::{FromRef, FromRequestParts, Path, State},
+ http::{HeaderMap, StatusCode, header::CONTENT_TYPE, request::Parts},
response::IntoResponse,
routing::post,
};
@@ -29,10 +29,13 @@ use entity_access::{
},
inbound::axum_extractors::ChannelAccessLevelExtractor,
};
-use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
+use macro_authorization::{
+ BOT_TOKEN_HEADER, BotAuthentication, BotOnly, MacroAuthorizationRejection,
+ MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
-use std::{future::Future, sync::Arc};
+use std::{future::Future, marker::PhantomData, sync::Arc};
use uuid::Uuid;
/// Header used to authenticate channel bot webhook requests.
@@ -129,6 +132,40 @@ impl<BotSvc, ChannelPoster, AccessSvc, Auth>
}
}
+struct ChannelWebhookAuthorizationExtractor<Auth> {
+ authentication: Option<BotAuthentication>,
+ _service: PhantomData<fn() -> Auth>,
+}
+
+impl<S, Auth> FromRequestParts<S> for ChannelWebhookAuthorizationExtractor<Auth>
+where
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = MacroAuthorizationRejection;
+
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ if parts.headers.contains_key(BOT_TOKEN_HEADER)
+ && parts.headers.contains_key(CHANNEL_BOT_TOKEN_HEADER)
+ {
+ return Err(MacroAuthorizationRejection {
+ status: StatusCode::BAD_REQUEST,
+ message: "ambiguous credentials".into(),
+ });
+ }
+
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, BotOnly>::from_request_parts(parts, state)
+ .await?
+ .authorization;
+ Ok(Self {
+ authentication: authorization,
+ _service: PhantomData,
+ })
+ }
+}
+
/// Channel id path.
#[derive(Debug, serde::Deserialize)]
pub struct ChannelPath {
@@ -230,21 +267,40 @@ where
path = "/channels/{channel_id}/webhook",
params(
("channel_id" = Uuid, Path, description = "Channel ID"),
- ("x-macro-channel-bot-token" = String, Header, description = "Bot authentication token")
+ ("x-macro-bot-token" = Option<String>, Header, description = "Preferred bot authentication token"),
+ ("x-macro-channel-bot-token" = Option<String>, Header, deprecated, description = "Legacy channel-scoped bot authentication token")
),
request_body = ChannelWebhookRequest,
responses(
(status = 200, body = ChannelWebhookResponse),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
(status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(err, skip_all, fields(channel_id = tracing::field::Empty))]
+#[tracing::instrument(
+ err,
+ skip_all,
+ fields(
+ channel_id = tracing::field::Empty,
+ bot_id = tracing::field::Empty,
+ token_id = tracing::field::Empty,
+ acting_user_id = tracing::field::Empty,
+ )
+)]
+#[allow(
+ private_interfaces,
+ reason = "the public handler is referenced by DSS OpenAPI while its route-specific extractor stays private"
+)]
pub async fn post_channel_webhook_handler<BotSvc, ChannelPoster, AccessSvc, Auth>(
State(state): State<ChannelBotWebhookRouterState<BotSvc, ChannelPoster, AccessSvc, Auth>>,
Path(path): Path<ChannelPath>,
+ ChannelWebhookAuthorizationExtractor {
+ authentication: preferred_authentication,
+ ..
+ }: ChannelWebhookAuthorizationExtractor<Auth>,
headers: HeaderMap,
body: Bytes,
) -> Result<(StatusCode, Json<ChannelWebhookResponse>), ChannelBotWebhookHandlerErr>
@@ -257,16 +313,31 @@ where
tracing::Span::current().record("channel_id", tracing::field::display(path.channel_id));
let content = parse_webhook_content(&headers, body)?;
- let bot_auth_token = channel_bot_token(&headers)?;
- let authenticated = state
- .bot_service
- .authenticate_channel_token(path.channel_id, bot_auth_token)
- .await?;
+ let bot_id = match preferred_authentication {
+ Some(authentication) => {
+ record_preferred_bot(&authentication);
+ state
+ .bot_service
+ .ensure_bot_in_channel(authentication.bot_id, path.channel_id)
+ .await?;
+ authentication.bot_id
+ }
+ None => {
+ let bot_auth_token = channel_bot_token(&headers)?;
+ let authenticated = state
+ .bot_service
+ .authenticate_channel_token(path.channel_id, bot_auth_token)
+ .await?;
+ tracing::Span::current()
+ .record("bot_id", tracing::field::display(authenticated.bot_id));
+ authenticated.bot_id
+ }
+ };
let response = state
.channel_poster
.post_message(
- Sender::new_from_bot(authenticated.bot_id),
+ Sender::new_from_bot(bot_id),
path.channel_id,
PostMessageRequest {
content,
@@ -289,6 +360,18 @@ where
))
}
+fn record_preferred_bot(bot: &BotAuthentication) {
+ let span = tracing::Span::current();
+ span.record("bot_id", tracing::field::display(bot.bot_id));
+ span.record("token_id", tracing::field::display(bot.token_id));
+ if let Some(acting_user) = &bot.acting_user {
+ span.record(
+ "acting_user_id",
+ tracing::field::display(&acting_user.macro_user_id),
+ );
+ }
+}
+
fn channel_bot_token(headers: &HeaderMap) -> Result<&str, ChannelBotWebhookHandlerErr> {
let token = headers
.get(CHANNEL_BOT_TOKEN_HEADER)
@@ -364,11 +447,11 @@ impl IntoResponse for ChannelBotWebhookHandlerErr {
Self::BadRequest(_) | Self::Bot(BotError::BadRequest(_)) => StatusCode::BAD_REQUEST,
Self::Bot(BotError::Unauthorized)
| Self::Channel(ChannelMutationErr::Unauthorized(_)) => StatusCode::UNAUTHORIZED,
+ Self::Channel(ChannelMutationErr::Forbidden(_)) => StatusCode::FORBIDDEN,
Self::Bot(BotError::NotFound(_)) | Self::Channel(ChannelMutationErr::NotFound(_)) => {
StatusCode::NOT_FOUND
}
Self::Channel(ChannelMutationErr::BadRequest(_)) => StatusCode::BAD_REQUEST,
- Self::Channel(ChannelMutationErr::Forbidden(_)) => StatusCode::FORBIDDEN,
Self::Bot(BotError::Repo(_))
| Self::Channel(ChannelMutationErr::Repo(_))
| Self::Channel(ChannelMutationErr::Gateway(_))
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index dfd99a64dc..2ebce1c8db 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -17,8 +17,11 @@ use entity_access::domain::{
ports::EntityAccessService,
};
use macro_authorization::{
+ BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,
+ BOT_FOR_ORGANIZATION_ID_HEADER, BOT_TOKEN_HEADER,
+ BotActingUserClaims as AuthorizationBotActingUserClaims, BotAuthentication, BotAuthorizer,
InternalAuthConfig, JwtValidator, MacroAuthorizationError, MacroAuthorizationServiceImpl,
- MacroAuthorizationState, ValidatedIdentity,
+ MacroAuthorizationState, MacroUserAuthentication, ValidatedIdentity,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use rootcause::Report;
@@ -37,7 +40,7 @@ enum TestCreateMode {
}
#[derive(Clone)]
-enum TestAuthMode {
+enum TestLegacyAuthMode {
Ok {
expected_channel_id: Uuid,
expected_token: String,
@@ -46,6 +49,15 @@ enum TestAuthMode {
Unauthorized,
}
+#[derive(Clone)]
+enum TestMembershipMode {
+ Ok {
+ expected_channel_id: Uuid,
+ expected_bot_id: BotId,
+ },
+ Unauthorized,
+}
+
#[derive(Debug, Clone)]
struct CreateCall {
caller: MacroUserIdStr<'static>,
@@ -58,51 +70,80 @@ struct AuthCall {
token: String,
}
+#[derive(Debug, Clone, Copy, Eq, PartialEq)]
+struct MembershipCall {
+ channel_id: Uuid,
+ bot_id: BotId,
+}
+
#[derive(Clone)]
struct TestBotService {
create_mode: TestCreateMode,
- auth_mode: TestAuthMode,
+ legacy_auth_mode: TestLegacyAuthMode,
+ membership_mode: TestMembershipMode,
create_calls: Arc<AtomicUsize>,
auth_calls: Arc<AtomicUsize>,
+ membership_calls: Arc<AtomicUsize>,
last_create: Arc<Mutex<Option<CreateCall>>>,
last_auth: Arc<Mutex<Option<AuthCall>>>,
+ last_membership: Arc<Mutex<Option<MembershipCall>>>,
}
impl TestBotService {
fn for_create(response: CreateChannelScopedBotResponse) -> Self {
- Self {
- create_mode: TestCreateMode::Ok(response),
- auth_mode: TestAuthMode::Unauthorized,
- create_calls: Arc::new(AtomicUsize::new(0)),
- auth_calls: Arc::new(AtomicUsize::new(0)),
- last_create: Arc::new(Mutex::new(None)),
- last_auth: Arc::new(Mutex::new(None)),
- }
+ Self::new(
+ TestCreateMode::Ok(response),
+ TestLegacyAuthMode::Unauthorized,
+ TestMembershipMode::Unauthorized,
+ )
}
fn for_webhook(channel_id: Uuid, token: &str, bot_id: BotId) -> Self {
- Self {
- create_mode: TestCreateMode::Unauthorized,
- auth_mode: TestAuthMode::Ok {
+ Self::new(
+ TestCreateMode::Unauthorized,
+ TestLegacyAuthMode::Ok {
expected_channel_id: channel_id,
expected_token: token.to_string(),
bot_id,
},
- create_calls: Arc::new(AtomicUsize::new(0)),
- auth_calls: Arc::new(AtomicUsize::new(0)),
- last_create: Arc::new(Mutex::new(None)),
- last_auth: Arc::new(Mutex::new(None)),
- }
+ TestMembershipMode::Unauthorized,
+ )
+ }
+
+ fn for_preferred_webhook(channel_id: Uuid, bot_id: BotId) -> Self {
+ Self::new(
+ TestCreateMode::Unauthorized,
+ TestLegacyAuthMode::Unauthorized,
+ TestMembershipMode::Ok {
+ expected_channel_id: channel_id,
+ expected_bot_id: bot_id,
+ },
+ )
}
fn unauthorized_webhook() -> Self {
+ Self::new(
+ TestCreateMode::Unauthorized,
+ TestLegacyAuthMode::Unauthorized,
+ TestMembershipMode::Unauthorized,
+ )
+ }
+
+ fn new(
+ create_mode: TestCreateMode,
+ legacy_auth_mode: TestLegacyAuthMode,
+ membership_mode: TestMembershipMode,
+ ) -> Self {
Self {
- create_mode: TestCreateMode::Unauthorized,
- auth_mode: TestAuthMode::Unauthorized,
+ create_mode,
+ legacy_auth_mode,
+ membership_mode,
create_calls: Arc::new(AtomicUsize::new(0)),
auth_calls: Arc::new(AtomicUsize::new(0)),
+ membership_calls: Arc::new(AtomicUsize::new(0)),
last_create: Arc::new(Mutex::new(None)),
last_auth: Arc::new(Mutex::new(None)),
+ last_membership: Arc::new(Mutex::new(None)),
}
}
}
@@ -217,6 +258,24 @@ impl BotService for TestBotService {
unimplemented!()
}
+ async fn ensure_bot_in_channel(&self, bot_id: BotId, channel_id: Uuid) -> Result<(), BotError> {
+ self.membership_calls.fetch_add(1, Ordering::SeqCst);
+ *self
+ .last_membership
+ .lock()
+ .expect("membership call mutex poisoned") = Some(MembershipCall { channel_id, bot_id });
+
+ match self.membership_mode {
+ TestMembershipMode::Ok {
+ expected_channel_id,
+ expected_bot_id,
+ } if channel_id == expected_channel_id && bot_id == expected_bot_id => Ok(()),
+ TestMembershipMode::Ok { .. } | TestMembershipMode::Unauthorized => {
+ Err(BotError::Unauthorized)
+ }
+ }
+ }
+
async fn authenticate_token(&self, _token: &str) -> Result<AuthenticatedBot, BotError> {
unimplemented!()
}
@@ -232,8 +291,8 @@ impl BotService for TestBotService {
token: token.to_string(),
});
- match &self.auth_mode {
- TestAuthMode::Ok {
+ match &self.legacy_auth_mode {
+ TestLegacyAuthMode::Ok {
expected_channel_id,
expected_token,
bot_id,
@@ -412,6 +471,89 @@ impl ChannelMessagePoster for TestChannelPoster {
}
}
+#[derive(Clone)]
+enum TestBotAuthorizationMode {
+ Ok {
+ expected_token: String,
+ expected_claims: Option<AuthorizationBotActingUserClaims>,
+ authentication: Box<BotAuthentication>,
+ },
+ Reject(MacroAuthorizationError),
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+struct BotAuthorizationCall {
+ token: String,
+ claims: Option<AuthorizationBotActingUserClaims>,
+}
+
+#[derive(Clone)]
+struct TestBotAuthorizer {
+ mode: TestBotAuthorizationMode,
+ calls: Arc<Mutex<Vec<BotAuthorizationCall>>>,
+}
+
+impl TestBotAuthorizer {
+ fn authorized(
+ token: &str,
+ claims: Option<AuthorizationBotActingUserClaims>,
+ authentication: BotAuthentication,
+ ) -> Self {
+ Self {
+ mode: TestBotAuthorizationMode::Ok {
+ expected_token: token.to_string(),
+ expected_claims: claims,
+ authentication: Box::new(authentication),
+ },
+ calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn rejecting(error: MacroAuthorizationError) -> Self {
+ Self {
+ mode: TestBotAuthorizationMode::Reject(error),
+ calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn call_count(&self) -> usize {
+ self.calls
+ .lock()
+ .expect("bot authorization calls mutex poisoned")
+ .len()
+ }
+}
+
+impl BotAuthorizer for TestBotAuthorizer {
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ acting_user: Option<AuthorizationBotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ self.calls
+ .lock()
+ .expect("bot authorization calls mutex poisoned")
+ .push(BotAuthorizationCall {
+ token: bot_token.to_string(),
+ claims: acting_user.clone(),
+ });
+
+ match &self.mode {
+ TestBotAuthorizationMode::Ok {
+ expected_token,
+ expected_claims,
+ authentication,
+ } if bot_token == expected_token && acting_user == *expected_claims => {
+ Ok(authentication.as_ref().clone())
+ }
+ TestBotAuthorizationMode::Ok { .. } => {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+ TestBotAuthorizationMode::Reject(error) => Err(Report::new(*error)),
+ }
+ }
+}
+
#[derive(Clone, Default)]
struct FakeJwtValidator;
@@ -428,13 +570,16 @@ impl JwtValidator for FakeJwtValidator {
type TestAuthorizationService = MacroAuthorizationServiceImpl<FakeJwtValidator>;
-fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
+fn authorization_state(
+ bot_authorizer: TestBotAuthorizer,
+) -> MacroAuthorizationState<TestAuthorizationService> {
let service = MacroAuthorizationServiceImpl::new(
FakeJwtValidator,
InternalAuthConfig {
api_key: "test-internal-key".to_string(),
default_user_id: None,
},
+ bot_authorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
@@ -456,20 +601,60 @@ fn router(
service,
poster,
TestAccessService::new(role),
- authorization_state(),
+ authorization_state(TestBotAuthorizer::rejecting(
+ MacroAuthorizationError::InvalidCredentials,
+ )),
))
.layer(axum::middleware::map_request(attach_default_bearer))
}
fn webhook_router(service: TestBotService, poster: TestChannelPoster) -> Router {
+ webhook_router_with_authorizer(service, poster, rejecting_bot_authorizer())
+}
+
+fn webhook_router_with_authorizer(
+ service: TestBotService,
+ poster: TestChannelPoster,
+ bot_authorizer: TestBotAuthorizer,
+) -> Router {
channel_bot_webhook_router(ChannelBotWebhookRouterState::new(
service,
poster,
TestAccessService::new(EntityParticipantRole::Member),
- authorization_state(),
+ authorization_state(bot_authorizer),
))
}
+fn rejecting_bot_authorizer() -> TestBotAuthorizer {
+ TestBotAuthorizer::rejecting(MacroAuthorizationError::InvalidCredentials)
+}
+
+fn bot_authentication(bot_id: BotId) -> BotAuthentication {
+ BotAuthentication {
+ bot_id,
+ token_id: Uuid::new_v4(),
+ acting_user: None,
+ }
+}
+
+fn bot_authentication_with_acting_user(bot_id: BotId) -> BotAuthentication {
+ BotAuthentication {
+ bot_id,
+ token_id: Uuid::new_v4(),
+ acting_user: Some(MacroUserAuthentication {
+ macro_user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ user_context: Default::default(),
+ }),
+ }
+}
+
+fn webhook_request(channel_id: Uuid) -> axum::http::request::Builder {
+ Request::builder()
+ .method("POST")
+ .uri(format!("/channels/{channel_id}/webhook"))
+ .header("content-type", "application/json")
+}
+
fn scoped_bot_response(bot_id: BotId) -> CreateChannelScopedBotResponse {
let now = chrono::Utc::now();
let bot_token = "mbot_test_1234".to_string();
@@ -573,7 +758,327 @@ async fn channel_webhook_router_admin_can_create_scoped_bot() {
}
#[tokio::test]
-async fn channel_webhook_router_valid_json_posts_as_bot() {
+async fn channel_webhook_router_preferred_token_posts_as_bot() {
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let token = "mbot_test_preferred";
+ let service = TestBotService::for_preferred_webhook(channel_id, bot_id);
+ let poster = TestChannelPoster::new();
+ let authorizer = TestBotAuthorizer::authorized(token, None, bot_authentication(bot_id));
+ let request = webhook_request(channel_id)
+ .header(BOT_TOKEN_HEADER, token)
+ .body(Body::from(
+ serde_json::json!({ "content": "hello preferred" }).to_string(),
+ ))
+ .unwrap();
+
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(authorizer.call_count(), 1);
+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(service.membership_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ *service
+ .last_membership
+ .lock()
+ .expect("membership call mutex poisoned"),
+ Some(MembershipCall { channel_id, bot_id })
+ );
+
+ let calls = poster.calls.lock().expect("posted message mutex poisoned");
+ assert_eq!(calls.len(), 1);
+ let call = &calls[0];
+ assert_eq!(call.actor, Sender::new_from_bot(bot_id));
+ assert_eq!(call.channel_id, channel_id);
+ assert_eq!(call.req.content, "hello preferred");
+ assert!(call.req.triggered_by.is_none());
+}
+
+#[tokio::test]
+async fn channel_webhook_router_verified_acting_user_is_not_used_for_attribution() {
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let token = "mbot_test_acting_user";
+ let claims = AuthorizationBotActingUserClaims {
+ user_id: Some("macro|[email protected]".to_string()),
+ fusion_user_id: Some("fusion-acting-bot".to_string()),
+ organization_id: Some(42),
+ };
+ let service = TestBotService::for_preferred_webhook(channel_id, bot_id);
+ let poster = TestChannelPoster::new();
+ let authorizer = TestBotAuthorizer::authorized(
+ token,
+ Some(claims.clone()),
+ bot_authentication_with_acting_user(bot_id),
+ );
+ let request = webhook_request(channel_id)
+ .header(BOT_TOKEN_HEADER, token)
+ .header(
+ BOT_FOR_MACRO_USER_ID_HEADER,
+ claims.user_id.as_deref().unwrap(),
+ )
+ .header(
+ BOT_FOR_FUSIONAUTH_USER_ID_HEADER,
+ claims.fusion_user_id.as_deref().unwrap(),
+ )
+ .header(
+ BOT_FOR_ORGANIZATION_ID_HEADER,
+ claims.organization_id.unwrap(),
+ )
+ .body(Body::from(
+ serde_json::json!({ "content": "verified user" }).to_string(),
+ ))
+ .unwrap();
+
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ authorizer
+ .calls
+ .lock()
+ .expect("bot authorization calls mutex poisoned")
+ .as_slice(),
+ &[BotAuthorizationCall {
+ token: token.to_string(),
+ claims: Some(claims),
+ }]
+ );
+ assert_eq!(service.membership_calls.load(Ordering::SeqCst), 1);
+ let calls = poster.calls.lock().expect("posted message mutex poisoned");
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0].actor, Sender::new_from_bot(bot_id));
+ assert!(calls[0].req.triggered_by.is_none());
+}
+
+#[tokio::test]
+async fn channel_webhook_router_cookie_only_user_is_forbidden_without_posting() {
+ let channel_id = Uuid::new_v4();
+ let service = TestBotService::unauthorized_webhook();
+ let poster = TestChannelPoster::new();
+ let authorizer = rejecting_bot_authorizer();
+ let request = webhook_request(channel_id)
+ .header("cookie", "macro-access-token=macro|[email protected]")
+ .body(Body::from(
+ serde_json::json!({ "content": "user request" }).to_string(),
+ ))
+ .unwrap();
+
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let error: ErrorResponse = serde_json::from_slice(&body).unwrap();
+ assert_eq!(error.message, "forbidden");
+ assert_eq!(authorizer.call_count(), 0);
+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(service.membership_calls.load(Ordering::SeqCst), 0);
+ assert!(
+ poster
+ .calls
+ .lock()
+ .expect("posted message mutex poisoned")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn channel_webhook_router_bot_token_and_user_are_ambiguous_without_posting() {
+ let channel_id = Uuid::new_v4();
+ let service = TestBotService::unauthorized_webhook();
+ let poster = TestChannelPoster::new();
+ let authorizer = rejecting_bot_authorizer();
+ let request = webhook_request(channel_id)
+ .header(BOT_TOKEN_HEADER, "mbot_test_preferred")
+ .header(
+ header::AUTHORIZATION,
+ "Bearer macro|[email protected]",
+ )
+ .body(Body::from(
+ serde_json::json!({ "content": "ambiguous" }).to_string(),
+ ))
+ .unwrap();
+
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let error: ErrorResponse = serde_json::from_slice(&body).unwrap();
+ assert_eq!(error.message, "ambiguous credentials");
+ assert_eq!(authorizer.call_count(), 0);
+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(service.membership_calls.load(Ordering::SeqCst), 0);
+ assert!(
+ poster
+ .calls
+ .lock()
+ .expect("posted message mutex poisoned")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn channel_webhook_router_both_bot_headers_are_ambiguous_before_validation() {
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let legacy_token = "mbot_test_legacy";
+ let service = TestBotService::for_webhook(channel_id, legacy_token, bot_id);
+ let poster = TestChannelPoster::new();
+ let authorizer = rejecting_bot_authorizer();
+ let request = webhook_request(channel_id)
+ .header(BOT_TOKEN_HEADER, "mbot_test_invalid_preferred")
+ .header(CHANNEL_BOT_TOKEN_HEADER, legacy_token)
+ .body(Body::from(
+ serde_json::json!({ "content": "ambiguous" }).to_string(),
+ ))
+ .unwrap();
+
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let error: ErrorResponse = serde_json::from_slice(&body).unwrap();
+ assert_eq!(error.message, "ambiguous credentials");
+ assert_eq!(authorizer.call_count(), 0);
+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(service.membership_calls.load(Ordering::SeqCst), 0);
+ assert!(
+ poster
+ .calls
+ .lock()
+ .expect("posted message mutex poisoned")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn channel_webhook_router_invalid_preferred_token_does_not_fall_back_to_legacy() {
+ let channel_id = Uuid::new_v4();
+ let service = TestBotService::unauthorized_webhook();
+ let poster = TestChannelPoster::new();
+ let authorizer = rejecting_bot_authorizer();
+ let request = webhook_request(channel_id)
+ .header(BOT_TOKEN_HEADER, "mbot_test_invalid_preferred")
+ .body(Body::from(
+ serde_json::json!({ "content": "invalid preferred" }).to_string(),
+ ))
+ .unwrap();
+
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(authorizer.call_count(), 1);
+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(service.membership_calls.load(Ordering::SeqCst), 0);
+ assert!(
+ poster
+ .calls
+ .lock()
+ .expect("posted message mutex poisoned")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn channel_webhook_router_preferred_bot_outside_channel_is_unauthorized() {
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let token = "mbot_test_outside_channel";
+ let service = TestBotService::unauthorized_webhook();
+ let poster = TestChannelPoster::new();
+ let authorizer = TestBotAuthorizer::authorized(token, None, bot_authentication(bot_id));
+ let request = webhook_request(channel_id)
+ .header(BOT_TOKEN_HEADER, token)
+ .body(Body::from(
+ serde_json::json!({ "content": "outside channel" }).to_string(),
+ ))
+ .unwrap();
+
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(authorizer.call_count(), 1);
+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(service.membership_calls.load(Ordering::SeqCst), 1);
+ assert!(
+ poster
+ .calls
+ .lock()
+ .expect("posted message mutex poisoned")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn channel_webhook_router_rejected_acting_user_is_forbidden_without_posting() {
+ let channel_id = Uuid::new_v4();
+ let service = TestBotService::unauthorized_webhook();
+ let poster = TestChannelPoster::new();
+ let authorizer = TestBotAuthorizer::rejecting(MacroAuthorizationError::ActingUserNotAuthorized);
+ let request = webhook_request(channel_id)
+ .header(BOT_TOKEN_HEADER, "mbot_test_forbidden_claims")
+ .header(BOT_FOR_MACRO_USER_ID_HEADER, "macro|[email protected]")
+ .body(Body::from(
+ serde_json::json!({ "content": "forbidden" }).to_string(),
+ ))
+ .unwrap();
+
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert_eq!(authorizer.call_count(), 1);
+ assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(service.membership_calls.load(Ordering::SeqCst), 0);
+ assert!(
+ poster
+ .calls
+ .lock()
+ .expect("posted message mutex poisoned")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn channel_webhook_router_legacy_valid_json_posts_as_bot() {
let channel_id = Uuid::new_v4();
let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let token = "mbot_test_valid";
@@ -616,6 +1121,7 @@ async fn channel_webhook_router_valid_json_posts_as_bot() {
assert!(call.req.attachments.is_empty());
assert!(call.req.thread_id.is_none());
assert!(call.req.nonce.is_none());
+ assert!(call.req.triggered_by.is_none());
}
#[tokio::test]
@@ -687,21 +1193,21 @@ async fn channel_webhook_router_missing_token_header_returns_unauthorized_withou
let channel_id = Uuid::new_v4();
let service = TestBotService::unauthorized_webhook();
let poster = TestChannelPoster::new();
- let request = Request::builder()
- .method("POST")
- .uri(format!("/channels/{channel_id}/webhook"))
- .header("content-type", "application/json")
+ let authorizer = rejecting_bot_authorizer();
+ let request = webhook_request(channel_id)
.body(Body::from(
serde_json::json!({ "content": "hello" }).to_string(),
))
.unwrap();
- let response = webhook_router(service.clone(), poster.clone())
- .oneshot(request)
- .await
- .unwrap();
+ let response =
+ webhook_router_with_authorizer(service.clone(), poster.clone(), authorizer.clone())
+ .oneshot(request)
+ .await
+ .unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(authorizer.call_count(), 0);
assert_eq!(service.auth_calls.load(Ordering::SeqCst), 0);
assert!(
poster
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index 2c31117f7c..4f6bc36d40 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -419,6 +419,31 @@ impl BotRepo for PgBotsRepo {
Ok(has_team)
}
+ async fn bot_active_in_channel(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<bool, Self::Err> {
+ let is_active = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_channel_participants
+ WHERE channel_id = $1
+ AND user_id = $2
+ AND left_at IS NULL
+ ) AS "is_active!"
+ "#,
+ channel_id,
+ principal_id(bot_id),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to check bot channel membership")?;
+
+ Ok(is_active)
+ }
+
async fn patch_bot(
&self,
bot_id: BotId,
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index dff2f252be..fa924e94d8 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -17,7 +17,6 @@ const USER_OWNER: &str = "macro|[email protected]";
const USER_OTHER: &str = "macro|[email protected]";
const TEAM_MEMBER: &str = "macro|[email protected]";
const TEAM_OTHER: &str = "macro|[email protected]";
-
fn user_id(value: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")
}
@@ -260,6 +259,49 @@ async fn token_last_used_at(
Ok(last_used_at)
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn bot_active_in_channel_returns_true_for_active_membership(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ insert_channel(&pool, channel_id).await?;
+ let repo = PgBotsRepo::new(pool);
+ repo.add_bot_to_channel(channel_id, bot_id).await?;
+
+ assert!(repo.bot_active_in_channel(channel_id, bot_id).await?);
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn bot_active_in_channel_returns_false_for_non_member(pool: PgPool) -> anyhow::Result<()> {
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ insert_channel(&pool, channel_id).await?;
+ let repo = PgBotsRepo::new(pool);
+
+ assert!(!repo.bot_active_in_channel(channel_id, bot_id).await?);
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn bot_active_in_channel_returns_false_for_soft_deleted_membership(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ insert_channel(&pool, channel_id).await?;
+ let repo = PgBotsRepo::new(pool);
+ repo.add_bot_to_channel(channel_id, bot_id).await?;
+ assert!(repo.remove_bot_from_channel(channel_id, bot_id).await?);
+
+ assert!(!repo.bot_active_in_channel(channel_id, bot_id).await?);
+
+ Ok(())
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn create_user_owned_bot_records_user_owner(pool: PgPool) -> anyhow::Result<()> {
let service = service(&pool);
diff --git a/crates/call/src/inbound/axum_router.rs b/crates/call/src/inbound/axum_router.rs
index d8391f2d5a..10bed3c918 100644
--- a/crates/call/src/inbound/axum_router.rs
+++ b/crates/call/src/inbound/axum_router.rs
@@ -28,7 +28,7 @@ use entity_access::{
},
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use model_error_response::ErrorResponse;
use uuid::Uuid;
@@ -290,14 +290,14 @@ pub async fn get_or_create_call_handler<
>(
State(state): State<CallRouterState<S, Svc, Auth>>,
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<CallTokenResponse>, CallError> {
let channel_id = Uuid::parse_str(&access.entity_access_receipt.entity().entity_id)
.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid channel_id")))?;
let response = state
.service
- .get_or_create_call(&channel_id, user.macro_user_id)
+ .get_or_create_call(&channel_id, user.authorization.user.macro_user_id.clone())
.await?;
Ok(Json(response))
@@ -540,7 +540,7 @@ pub async fn get_batch_call_record_preview_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<CallRouterState<S, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<GetBatchCallRecordPreviewRequest>,
) -> Result<Json<GetBatchCallRecordPreviewResponse>, CallError> {
if request.call_ids.len() > MAX_BATCH_CALL_IDS {
@@ -551,7 +551,7 @@ pub async fn get_batch_call_record_preview_handler<
let response = state
.service
- .get_batch_call_record_previews(request, user.macro_user_id)
+ .get_batch_call_record_previews(request, user.authorization.user.macro_user_id.clone())
.await?;
Ok(Json(response))
}
@@ -579,13 +579,13 @@ pub async fn leave_or_end_call_handler<
>(
State(state): State<CallRouterState<S, Svc, Auth>>,
access: CallWithChannelIdAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<LeaveCallResponse>, CallError> {
let channel_id = access.channel_id;
let response = state
.service
- .leave_or_end_call(&channel_id, user.macro_user_id)
+ .leave_or_end_call(&channel_id, user.authorization.user.macro_user_id.clone())
.await?;
Ok(Json(response))
diff --git a/crates/channels/src/inbound/axum_router.rs b/crates/channels/src/inbound/axum_router.rs
index 86eab6e7c8..0b4784ffdf 100644
--- a/crates/channels/src/inbound/axum_router.rs
+++ b/crates/channels/src/inbound/axum_router.rs
@@ -43,7 +43,7 @@ use entity_access::{
inbound::axum_extractors::ChannelAccessLevelExtractor,
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
@@ -406,13 +406,14 @@ pub async fn create_channel_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<CreateChannelRequest>,
) -> Result<(StatusCode, Json<CreateChannelResponse>), ChannelsHandlerErr> {
+ let user = &user.authorization.user;
let res = state
.service
.create_channel(
- Sender::new_from_user(user.macro_user_id),
+ Sender::new_from_user(user.macro_user_id.clone()),
user.user_context.organization_id.map(i64::from),
req,
)
@@ -442,12 +443,13 @@ pub async fn get_or_create_dm_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<GetOrCreateDmRequest>,
) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
+ let user = &user.authorization.user;
let res = state
.service
- .get_or_create_dm(Sender::new_from_user(user.macro_user_id), req)
+ .get_or_create_dm(Sender::new_from_user(user.macro_user_id.clone()), req)
.await?;
Ok((StatusCode::OK, Json(res)))
}
@@ -474,12 +476,13 @@ pub async fn get_or_create_private_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<GetOrCreatePrivateRequest>,
) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
+ let user = &user.authorization.user;
let res = state
.service
- .get_or_create_private(Sender::new_from_user(user.macro_user_id), req)
+ .get_or_create_private(Sender::new_from_user(user.macro_user_id.clone()), req)
.await?;
Ok((StatusCode::OK, Json(res)))
}
@@ -871,11 +874,12 @@ pub async fn join_channel_by_code_handler<
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
Path(join_code): Path<Uuid>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<StatusCode, ChannelsHandlerErr> {
+ let user = &user.authorization.user;
state
.service
- .join_channel_by_code(Sender::new_from_user(user.macro_user_id), join_code)
+ .join_channel_by_code(Sender::new_from_user(user.macro_user_id.clone()), join_code)
.await?;
Ok(StatusCode::OK)
}
@@ -909,6 +913,7 @@ pub async fn join_channel_handler<
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
state.service.join_channel(actor, channel_id).await?;
+
Ok(StatusCode::OK)
}
@@ -1007,9 +1012,10 @@ pub async fn create_mention_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- macro_user: MacroAuthorizationExtractor<Auth>,
+ macro_user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<CreateEntityMentionRequest>,
) -> Result<(StatusCode, Json<CreateEntityMentionResponse>), ChannelsHandlerErr> {
+ let macro_user = &macro_user.authorization.user;
require_document_edit_access(
state.access_service.as_ref(),
&macro_user.macro_user_id,
@@ -1067,9 +1073,10 @@ pub async fn delete_mention_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- macro_user: MacroAuthorizationExtractor<Auth>,
+ macro_user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(mention_id): Path<Uuid>,
) -> Result<(StatusCode, Json<DeleteEntityMentionResponse>), ChannelsHandlerErr> {
+ let macro_user = &macro_user.authorization.user;
let mention = state
.service
.get_entity_mention(mention_id)
@@ -1620,17 +1627,14 @@ pub async fn get_batch_channel_preview_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id,
- user_context,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<GetBatchChannelPreviewRequest>,
) -> Result<Json<GetBatchChannelPreviewResponse>, ChannelsHandlerErr> {
- let org_id = user_context.organization_id.map(i64::from);
+ let user = &user.authorization.user;
+ let org_id = user.user_context.organization_id.map(i64::from);
let previews = state
.service
- .batch_get_channel_previews(macro_user_id, org_id, req.channel_ids)
+ .batch_get_channel_previews(user.macro_user_id.clone(), org_id, req.channel_ids)
.await?;
Ok(Json(GetBatchChannelPreviewResponse { previews }))
}
@@ -1665,9 +1669,10 @@ pub async fn get_attachment_references_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<AttachmentReferencesPath>,
) -> Result<Json<GetAttachmentReferencesResponse>, ChannelsHandlerErr> {
+ let user = &user.authorization.user;
let span = tracing::Span::current();
span.record("entity_type", tracing::field::display(&path.entity_type));
span.record("entity_id", tracing::field::display(&path.entity_id));
@@ -1709,8 +1714,9 @@ pub async fn get_activity_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<Vec<ApiActivity>>, ChannelsHandlerErr> {
+ let user = &user.authorization.user;
let activities = state
.service
.get_activities(user.macro_user_id.to_string())
@@ -1742,15 +1748,16 @@ pub async fn post_activity_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<PostActivityRequest>,
) -> Result<(StatusCode, Json<ApiActivity>), ChannelsHandlerErr> {
+ let user = &user.authorization.user;
let channel_id = Uuid::parse_str(&req.channel_id)
.map_err(|_| ChannelsHandlerErr::BadRequest("Invalid channel_id"))?;
let activity = state
.service
.post_activity(
- Sender::new_from_user(user.macro_user_id),
+ Sender::new_from_user(user.macro_user_id.clone()),
channel_id,
req.activity_type,
)
diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rs
index e8d621b3a7..cb89d8c35f 100644
--- a/crates/channels/src/inbound/axum_router/test.rs
+++ b/crates/channels/src/inbound/axum_router/test.rs
@@ -912,6 +912,7 @@ fn authorization_state_with_default(
api_key: VALID_INTERNAL_KEY.to_string(),
default_user_id: default_user_id.map(str::to_string),
},
+ macro_authorization::NoBotAuthorizer,
);
(MacroAuthorizationState::new(Arc::new(service)), validator)
}
diff --git a/crates/channels/src/inbound/list_router.rs b/crates/channels/src/inbound/list_router.rs
index 1f20e0a002..aa4b99e617 100644
--- a/crates/channels/src/inbound/list_router.rs
+++ b/crates/channels/src/inbound/list_router.rs
@@ -12,7 +12,7 @@ use axum::{
};
use frecency::domain::models::AggregateFrecency;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use serde::Serialize;
@@ -108,16 +108,17 @@ impl IntoResponse for ChannelListRouterErr {
)]
async fn get_channels_handler<S, Auth>(
State(service): State<ChannelListRouterState<S, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<Vec<ApiChannelWithLatest>>, ChannelListRouterErr>
where
S: ChannelListService,
Auth: MacroAuthorizationService,
{
+ let user = &authorization.authorization.user;
let res = service
.inner
.get_channels(GetChannelsRequest {
- macro_id: macro_user_id,
+ macro_id: user.macro_user_id.clone(),
limit: Some(DEFAULT_CHANNEL_LIST_LIMIT),
include_frecency: true,
query: models_pagination::Query::Sort(
@@ -135,7 +136,7 @@ where
))
}
-#[tracing::instrument(skip(service))]
+#[tracing::instrument(skip(service, authorization))]
#[utoipa::path(get,
tag = "activity",
operation_id = "get_activity",
@@ -148,15 +149,16 @@ where
/// Handle legacy channel activity list requests.
pub async fn get_activity_handler<S, Auth>(
State(service): State<ChannelListRouterState<S, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<Vec<ApiActivity>>, ChannelListRouterErr>
where
S: ChannelListService,
Auth: MacroAuthorizationService,
{
+ let user = &authorization.authorization.user;
let res = service
.inner
- .get_activities(macro_user_id)
+ .get_activities(user.macro_user_id.clone())
.await
.map_err(|_| ChannelListRouterErr::Internal)?;
diff --git a/crates/channels/src/inbound/list_router/test.rs b/crates/channels/src/inbound/list_router/test.rs
index 521cba6e84..15c61c8a38 100644
--- a/crates/channels/src/inbound/list_router/test.rs
+++ b/crates/channels/src/inbound/list_router/test.rs
@@ -113,6 +113,7 @@ fn test_router(default_user_id: Option<&str>) -> (Router, ServiceCallTracker) {
api_key: VALID_INTERNAL_KEY.to_string(),
default_user_id: default_user_id.map(str::to_owned),
},
+ macro_authorization::NoBotAuthorizer,
);
let state = ChannelListRouterState::new(
list_service,
diff --git a/crates/chat/src/inbound/http/extractors.rs b/crates/chat/src/inbound/http/extractors.rs
index 99989204ad..9d52ff37f0 100644
--- a/crates/chat/src/inbound/http/extractors.rs
+++ b/crates/chat/src/inbound/http/extractors.rs
@@ -12,7 +12,7 @@ use axum::http::request::Parts;
use axum::response::IntoResponse;
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationService,
- MacroAuthorizationState,
+ MacroAuthorizationState, UserOrInternal,
};
use roles_and_permissions::domain::model::PermissionId;
use roles_and_permissions::domain::port::UserRolesAndPermissionsService;
@@ -103,10 +103,11 @@ where
type Rejection = ChatModelAccessRejection;
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 user =
+ MacroAuthorizationExtractor::<Auth, UserOrInternal>::from_request_parts(parts, state)
+ .await
+ .map_err(ChatModelAccessRejection::Unauthorized)?;
+ let user = &user.authorization.user;
let UserPermissionsState(permissions_service) = UserPermissionsState::<P>::from_ref(state);
let permissions = permissions_service
.get_user_permissions(&user.macro_user_id)
diff --git a/crates/chat/src/inbound/http/router.rs b/crates/chat/src/inbound/http/router.rs
index 66189fb663..eddf3da1cb 100644
--- a/crates/chat/src/inbound/http/router.rs
+++ b/crates/chat/src/inbound/http/router.rs
@@ -13,7 +13,7 @@ use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAcces
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::ChatAccessLevelExtractor;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use model::response::StringIDResponse;
use models_permissions::share_permission::SharePermissionV2;
@@ -184,7 +184,11 @@ pub struct CreateChatRequest {
)
)]
/// Create a new chat.
-#[tracing::instrument(skip(state, user, _access, req), fields(user_id = %user.macro_user_id), err(Debug))]
+#[tracing::instrument(
+ skip(state, user, _access, req),
+ fields(actor = %user.acting_entity()),
+ err(Debug)
+)]
pub async fn create_chat_handler<
S: ChatService,
Svc: EntityAccessService,
@@ -192,15 +196,17 @@ pub async fn create_chat_handler<
P: UserRolesAndPermissionsService,
>(
State(state): State<ChatRouterState<S, Svc, Auth, P>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
// 402 on no perms
_access: ChatModelAccess<Auth, P>,
Json(req): Json<CreateChatRequest>,
) -> Result<Json<StringIDResponse>> {
+ let user = &user.authorization.user;
+
let id = state
.inner
.create(
- user.macro_user_id,
+ user.macro_user_id.clone(),
CreateChatArgs {
name: req.name.unwrap_or_else(|| "New Chat".to_string()),
project_id: req.project_id,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 71649b895c..3cf717c914 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -92,6 +92,7 @@ impl FromRef<SchemaOnlyState> for MacroAuthorizationState<SchemaOnlyAuthorizatio
api_key: String::new(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
diff --git a/crates/contacts/src/inbound/http.rs b/crates/contacts/src/inbound/http.rs
index 430139cf12..0baeeef49d 100644
--- a/crates/contacts/src/inbound/http.rs
+++ b/crates/contacts/src/inbound/http.rs
@@ -7,7 +7,7 @@ use axum::routing::get;
use axum::{RequestPartsExt, Router};
use axum_extra::extract::Cached;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use rate_limit::domain::models::RateLimitOk;
@@ -48,12 +48,17 @@ pub struct AddContactRequest {
(status = 404, body=String),
(status = 500, body=String)))
]
-#[instrument(skip(authorization, contacts), fields(user_id = authorization.macro_user_id.as_ref()))]
+#[instrument(
+ skip(authorization, contacts),
+ fields(actor = %authorization.acting_entity())
+)]
pub async fn handler<S: ContactsService, Auth: MacroAuthorizationService>(
State(contacts): State<Arc<S>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> impl IntoResponse {
- match contacts.query_contacts(authorization.macro_user_id).await {
+ let user = authorization.authorization.user;
+
+ match contacts.query_contacts(user.macro_user_id.clone()).await {
Ok(contacts) if !contacts.is_empty() => {
(StatusCode::OK, Json(Some(GetContactsResponse { contacts })))
}
@@ -73,15 +78,21 @@ pub async fn handler<S: ContactsService, Auth: MacroAuthorizationService>(
(status = 401, body=String),
(status = 500, body=String)))
]
-#[instrument(skip(service, authorization), fields(user_id = authorization.macro_user_id.as_ref()), err)]
+#[instrument(
+ skip(service, authorization),
+ fields(actor = %authorization.acting_entity()),
+ err
+)]
pub async fn add_contact_handler<S: ContactsService, Auth: MacroAuthorizationService>(
State(service): State<Arc<S>>,
- Cached(authorization): Cached<MacroAuthorizationExtractor<Auth>>,
+ Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>>,
Json(body): Json<AddContactRequest>,
) -> Result<StatusCode, StatusCode> {
+ let user = authorization.authorization.user;
+
service
.add_contact_nodes(ContactsNodes {
- users: HashSet::from([authorization.macro_user_id, body.user_id]),
+ users: HashSet::from([user.macro_user_id.clone(), body.user_id]),
})
.await
.map_err(|e| {
@@ -92,7 +103,7 @@ pub async fn add_contact_handler<S: ContactsService, Auth: MacroAuthorizationSer
}
/// Rate limit for adding contacts: 50 requests per user per hour.
-pub struct PerUserAddContactRateLimit<Auth>(MacroAuthorizationExtractor<Auth>);
+pub struct PerUserAddContactRateLimit<Auth>(MacroAuthorizationExtractor<Auth, UserOrInternal>);
impl<S, Auth> RateLimitExtractable<S> for PerUserAddContactRateLimit<Auth>
where
@@ -109,7 +120,7 @@ where
fn key(&self) -> RateLimitKey {
RateLimitKey::builder(&"per-user-add-contact")
- .append(&self.0.macro_user_id.as_ref())
+ .append(&self.0.authorization.user.macro_user_id.as_ref())
.finish()
}
}
@@ -126,7 +137,7 @@ where
parts: &mut axum::http::request::Parts,
state: &S,
) -> Result<Self, Self::Rejection> {
- let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth>> =
+ let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>> =
parts.extract_with_state(state).await?;
Ok(Self(authorization))
}
diff --git a/crates/contacts/src/inbound/http/test.rs b/crates/contacts/src/inbound/http/test.rs
index c04f500736..82167baafd 100644
--- a/crates/contacts/src/inbound/http/test.rs
+++ b/crates/contacts/src/inbound/http/test.rs
@@ -123,6 +123,7 @@ fn build_test_router(should_exceed: bool) -> (Router, FakeJwtValidator) {
api_key: VALID_INTERNAL_KEY.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
);
let state = ContactsRouterState {
contacts_service: Arc::new(MockService),
diff --git a/crates/crm/src/inbound/axum_extractors.rs b/crates/crm/src/inbound/axum_extractors.rs
index 20a2a91312..91494a1162 100644
--- a/crates/crm/src/inbound/axum_extractors.rs
+++ b/crates/crm/src/inbound/axum_extractors.rs
@@ -27,7 +27,7 @@ use entity_access::{
inbound::axum_extractors::ExtractorError,
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use uuid::Uuid;
@@ -82,10 +82,11 @@ where
.map_err(|_| ExtractorError::BadRequest("missing company_id path parameter"))?;
let company_id = extract_company_id(&path_params)?.to_string();
- let MacroAuthorizationExtractor { macro_user_id, .. } =
- MacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ MacroAuthorizationExtractor::<Auth, UserOrInternal>::from_request_parts(parts, state)
.await
.map_err(ExtractorError::from)?;
+ let macro_user_id = authorization.authorization.user.macro_user_id.clone();
let (permission, team_id) = service
.get_crm_entity_permission_with_team(
@@ -157,10 +158,11 @@ where
.map_err(|_| ExtractorError::BadRequest("missing contact_id path parameter"))?;
let contact_id = extract_contact_id(&path_params)?.to_string();
- let MacroAuthorizationExtractor { macro_user_id, .. } =
- MacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ MacroAuthorizationExtractor::<Auth, UserOrInternal>::from_request_parts(parts, state)
.await
.map_err(ExtractorError::from)?;
+ let macro_user_id = authorization.authorization.user.macro_user_id.clone();
let (permission, team_id) = service
.get_crm_entity_permission_with_team(
@@ -233,10 +235,11 @@ where
.map_err(|_| ExtractorError::BadRequest("missing comment_id path parameter"))?;
let comment_id = extract_comment_id(&path_params)?;
- let MacroAuthorizationExtractor { macro_user_id, .. } =
- MacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ MacroAuthorizationExtractor::<Auth, UserOrInternal>::from_request_parts(parts, state)
.await
.map_err(ExtractorError::from)?;
+ let macro_user_id = authorization.authorization.user.macro_user_id.clone();
let (crm_entity_type, entity_id) = crm_service
.get_comment_entity(&comment_id)
diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rs
index c1fc83e561..f593ac5d4a 100644
--- a/crates/crm/src/inbound/axum_extractors/test.rs
+++ b/crates/crm/src/inbound/axum_extractors/test.rs
@@ -487,6 +487,7 @@ fn test_router(
api_key: INTERNAL_KEY.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
);
let state: CrmRouterState<FakeCrmService, FakeEntityAccessService, TestAuthorizationService> =
CrmRouterState {
diff --git a/crates/documents/src/inbound/axum_router/copy_document.rs b/crates/documents/src/inbound/axum_router/copy_document.rs
index aa9e4f5e99..8a5cc86c45 100644
--- a/crates/documents/src/inbound/axum_router/copy_document.rs
+++ b/crates/documents/src/inbound/axum_router/copy_document.rs
@@ -6,7 +6,7 @@ use axum::{
};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model::document::{DocumentBasic, FileTypeExt};
use models_permissions::share_permission::access_level::ViewAccessLevel;
@@ -38,7 +38,7 @@ use crate::domain::ports::DocumentService;
(status = 500, body = model_error_response::ErrorResponse),
)
)]
-#[tracing::instrument(skip(state, access, user, document_context, req), fields(user_id=%user.macro_user_id, document_version_id=?params.version_id))]
+#[tracing::instrument(skip(state, access, user, document_context, req), fields(user_id=%user.authorization.user.macro_user_id, document_version_id=?params.version_id))]
pub async fn copy_document_handler<
T: DocumentService,
Svc: EntityAccessService,
@@ -46,7 +46,7 @@ pub async fn copy_document_handler<
>(
access: DocumentAccessExtractor<ViewAccessLevel, Svc, Auth>,
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
Query(params): Query<CopyDocumentQueryParams>,
@@ -61,7 +61,7 @@ pub async fn copy_document_handler<
.copy_document(
access.entity_access_receipt,
document_context.0,
- user.macro_user_id,
+ user.authorization.user.macro_user_id.clone(),
req.document_name,
params.version_id,
req.version_id,
diff --git a/crates/documents/src/inbound/axum_router/create_document.rs b/crates/documents/src/inbound/axum_router/create_document.rs
index a4e27aa153..1e7ef73aa3 100644
--- a/crates/documents/src/inbound/axum_router/create_document.rs
+++ b/crates/documents/src/inbound/axum_router/create_document.rs
@@ -5,7 +5,9 @@ use std::str::FromStr;
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal, UserOrInternalCaller,
+};
use model::document::response::CreateDocumentRequest;
use model::document::{FileType, FileTypeExt};
use models_permissions::share_permission::access_level::EditAccessLevel;
@@ -34,20 +36,22 @@ use crate::domain::response::CreateDocumentResponse;
(status = 500, body = model_error_response::ErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, project), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(state, user, project), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn create_document_handler<
T: DocumentService,
Svc: EntityAccessService,
Auth: MacroAuthorizationService,
>(
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateDocumentRequest, Svc, Auth>,
) -> Result<Json<CreateDocumentResponse>, DocumentError> {
let req = project.into_inner();
// Email linking is internal only
- if req.email_attachment_id.is_some() && !user.is_internal_access {
+ if req.email_attachment_id.is_some()
+ && user.authorization.caller != UserOrInternalCaller::Internal
+ {
return Err(DocumentError::Unauthorized);
}
@@ -88,7 +92,7 @@ pub async fn create_document_handler<
id: req.id,
sha: req.sha,
document_name,
- user_id: user.macro_user_id.clone(),
+ user_id: user.authorization.user.macro_user_id.clone(),
file_type,
project_id: req.project_id,
team_id,
@@ -102,7 +106,11 @@ pub async fn create_document_handler<
let response_data = state
.service
- .create_document(user.macro_user_id, args, req.job_id)
+ .create_document(
+ user.authorization.user.macro_user_id.clone(),
+ args,
+ req.job_id,
+ )
.await?;
Ok(Json(CreateDocumentResponse {
diff --git a/crates/documents/src/inbound/axum_router/create_markdown.rs b/crates/documents/src/inbound/axum_router/create_markdown.rs
index a9688250a2..89210357e6 100644
--- a/crates/documents/src/inbound/axum_router/create_markdown.rs
+++ b/crates/documents/src/inbound/axum_router/create_markdown.rs
@@ -3,7 +3,7 @@
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_permissions::share_permission::access_level::{AccessLevel, EditAccessLevel};
use super::DocumentRouterState;
@@ -29,14 +29,14 @@ use crate::domain::ports::create::DocumentCreationService;
(status = 500, body = model_error_response::ErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, project), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(state, user, project), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn create_markdown_handler<
T: DocumentService + DocumentCreationService,
Svc: EntityAccessService,
Auth: MacroAuthorizationService,
>(
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
project: ProjectBodyAccessLevelExtractorV2<
EditAccessLevel,
CreateMarkdownDocumentRequest,
@@ -57,7 +57,7 @@ pub async fn create_markdown_handler<
let created = state
.creator
.create_markdown_text(
- user.macro_user_id.clone(),
+ user.authorization.user.macro_user_id.clone(),
NewMarkdownTextDocument {
metadata: metadata.build(),
markdown: req.markdown.unwrap_or_default(),
@@ -75,7 +75,7 @@ pub async fn create_markdown_handler<
.clone();
let token = encode_permission_token(
- Some(user.macro_user_id.as_ref().to_string()),
+ Some(user.authorization.user.macro_user_id.as_ref().to_string()),
document_id.clone(),
AccessLevel::Edit,
&state.document_permission_jwt_secret,
diff --git a/crates/documents/src/inbound/axum_router/create_snippet.rs b/crates/documents/src/inbound/axum_router/create_snippet.rs
index e4e5608737..fc7477752a 100644
--- a/crates/documents/src/inbound/axum_router/create_snippet.rs
+++ b/crates/documents/src/inbound/axum_router/create_snippet.rs
@@ -3,7 +3,7 @@
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_permissions::share_permission::access_level::EditAccessLevel;
use super::DocumentRouterState;
@@ -27,14 +27,14 @@ use crate::domain::ports::create::DocumentCreationService;
(status = 500, body = model_error_response::ErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, project), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(state, user, project), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn create_snippet_handler<
T: DocumentService + DocumentCreationService,
Svc: EntityAccessService,
Auth: MacroAuthorizationService,
>(
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateSnippetRequest, Svc, Auth>,
) -> Result<Json<CreateSnippetResponse>, DocumentError> {
let req = project.into_inner();
@@ -47,7 +47,7 @@ pub async fn create_snippet_handler<
let created = state
.creator
.create_markdown_text(
- user.macro_user_id,
+ user.authorization.user.macro_user_id.clone(),
NewMarkdownTextDocument {
metadata: metadata.build(),
markdown: req.markdown.unwrap_or_default(),
diff --git a/crates/documents/src/inbound/axum_router/create_task.rs b/crates/documents/src/inbound/axum_router/create_task.rs
index 3a08885bf6..debe73c0f2 100644
--- a/crates/documents/src/inbound/axum_router/create_task.rs
+++ b/crates/documents/src/inbound/axum_router/create_task.rs
@@ -6,7 +6,7 @@ use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::{
OptionalMacroUserTeamExtractorV2, ProjectBodyAccessLevelExtractorV2,
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_permissions::share_permission::access_level::{AccessLevel, EditAccessLevel};
use super::DocumentRouterState;
@@ -33,21 +33,21 @@ use super::task_duplicates::spawn_task_duplicate_detection;
(status = 500, body = model_error_response::ErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, optional_team, project), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(state, user, optional_team, project), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn create_task_handler<
T: DocumentService + DocumentCreationService,
Svc: EntityAccessService,
Auth: MacroAuthorizationService,
>(
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
optional_team: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Svc, Auth>,
project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateTaskRequest, Svc, Auth>,
) -> Result<Json<CreateTaskResponse>, DocumentError> {
let req = project.into_inner();
let task_name = req.task_name.clone();
let markdown = req.markdown.clone().unwrap_or_default();
- let owner = user.macro_user_id.as_ref().to_string();
+ let owner = user.authorization.user.macro_user_id.as_ref().to_string();
let mut metadata = NewDocumentMetadata::builder(task_name.clone());
if let Some(project_id) = req.project_id {
@@ -65,7 +65,7 @@ pub async fn create_task_handler<
let created = state
.creator
.create_markdown_text(
- user.macro_user_id.clone(),
+ user.authorization.user.macro_user_id.clone(),
NewMarkdownTextDocument {
metadata: metadata.build(),
markdown,
@@ -95,7 +95,7 @@ pub async fn create_task_handler<
);
let token = encode_permission_token(
- Some(user.macro_user_id.as_ref().to_string()),
+ Some(user.authorization.user.macro_user_id.as_ref().to_string()),
document_id.clone(),
AccessLevel::Edit,
&state.document_permission_jwt_secret,
diff --git a/crates/documents/src/inbound/axum_router/get_document_by_team_slug.rs b/crates/documents/src/inbound/axum_router/get_document_by_team_slug.rs
index 5ee125fd11..fedeb89857 100644
--- a/crates/documents/src/inbound/axum_router/get_document_by_team_slug.rs
+++ b/crates/documents/src/inbound/axum_router/get_document_by_team_slug.rs
@@ -17,7 +17,7 @@ use entity_access::{
},
inbound::axum_extractors::{ExtractorError, MacroUserTeamExtractorV2},
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use serde::Deserialize;
use super::DocumentRouterState;
@@ -56,7 +56,7 @@ where
state: &DocumentRouterState<T, Svc, Auth>,
) -> Result<Self, Self::Rejection> {
let user = parts
- .extract_with_state::<MacroAuthorizationExtractor<Auth>, _>(state)
+ .extract_with_state::<MacroAuthorizationExtractor<Auth, UserOrInternal>, _>(state)
.await
.map_err(IntoResponse::into_response)?;
let team = parts
@@ -76,8 +76,12 @@ where
let entity_access_receipt = state
.access_service
.generate_entity_access_receipt::<Level>(
- &user.macro_user_id,
- user.user_context.organization_id.map(i64::from),
+ &user.authorization.user.macro_user_id,
+ user.authorization
+ .user
+ .user_context
+ .organization_id
+ .map(i64::from),
&document_id,
EntityType::Document,
)
diff --git a/crates/documents/src/inbound/axum_router/put_interaction.rs b/crates/documents/src/inbound/axum_router/put_interaction.rs
index 9d5837e3f3..6d9e36740a 100644
--- a/crates/documents/src/inbound/axum_router/put_interaction.rs
+++ b/crates/documents/src/inbound/axum_router/put_interaction.rs
@@ -7,7 +7,7 @@ use axum::{
response::IntoResponse,
};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{InternalMacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService};
use serde::Deserialize;
use super::{DocumentRouterState, Params};
@@ -28,7 +28,7 @@ pub async fn put_interaction_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- _internal_authorization: InternalMacroAuthorizationExtractor<Auth>,
+ _internal_authorization: MacroAuthorizationExtractor<Auth, InternalOnly>,
Path(Params { document_id }): Path<Params>,
Json(body): Json<InteractionRequest>,
) -> impl IntoResponse {
diff --git a/crates/documents/src/inbound/axum_router/put_snapshot.rs b/crates/documents/src/inbound/axum_router/put_snapshot.rs
index cd9bd6243c..a678065db5 100644
--- a/crates/documents/src/inbound/axum_router/put_snapshot.rs
+++ b/crates/documents/src/inbound/axum_router/put_snapshot.rs
@@ -7,7 +7,7 @@ use axum::{
response::IntoResponse,
};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{InternalMacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService};
use super::{DocumentRouterState, Params};
use crate::domain::ports::DocumentService;
@@ -20,7 +20,7 @@ pub async fn put_snapshot_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- _internal_authorization: InternalMacroAuthorizationExtractor<Auth>,
+ _internal_authorization: MacroAuthorizationExtractor<Auth, InternalOnly>,
Path(Params { document_id }): Path<Params>,
body: Bytes,
) -> impl IntoResponse {
diff --git a/crates/documents/src/inbound/axum_router/task_duplicates.rs b/crates/documents/src/inbound/axum_router/task_duplicates.rs
index 0cb0b83f14..4e0fc7d586 100644
--- a/crates/documents/src/inbound/axum_router/task_duplicates.rs
+++ b/crates/documents/src/inbound/axum_router/task_duplicates.rs
@@ -12,7 +12,7 @@ use entity_access::inbound::axum_extractors::{
DocumentAccessExtractor, OptionalMacroUserTeamExtractorV2,
};
use lexical_client::LexicalClient;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model::document::DocumentBasic;
use model::response::GenericSuccessResponse;
use models_permissions::share_permission::access_level::{OwnerAccessLevel, ViewAccessLevel};
@@ -104,14 +104,14 @@ pub async fn get_task_duplicates_handler<
(status = 500, body = model_error_response::ErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, optional_team, request), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(skip(state, user, optional_team, request), fields(user_id=?user.authorization.user.macro_user_id), err)]
pub async fn task_similarity_search_handler<
T: DocumentService,
Svc: EntityAccessService,
Auth: MacroAuthorizationService,
>(
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
optional_team: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Svc, Auth>,
Json(request): Json<TaskSimilaritySearchRequest>,
) -> Result<Json<TaskSimilaritySearchResponse>, DocumentError> {
@@ -129,7 +129,7 @@ pub async fn task_similarity_search_handler<
let results = state
.task_dedup_service
.similarity_search(
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
team_id,
&request.task_name,
&markdown,
@@ -149,7 +149,7 @@ pub async fn dismiss_task_duplicates_handler<
>(
_access: DocumentAccessExtractor<ViewAccessLevel, Svc, Auth>,
State(state): State<DocumentRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(Params { document_id }): Path<Params>,
Json(request): Json<DismissTaskDuplicatesRequest>,
) -> Result<Json<GenericSuccessResponse>, DocumentError> {
@@ -158,7 +158,7 @@ pub async fn dismiss_task_duplicates_handler<
.dismiss_matches(
&document_id,
&request.match_ids,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
)
.await
.map_err(task_dedup_error)?;
diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rs
index 871cc7f5a3..95ffc7b779 100644
--- a/crates/documents/src/inbound/axum_router/tests.rs
+++ b/crates/documents/src/inbound/axum_router/tests.rs
@@ -979,10 +979,13 @@ async fn snapshot_upload_requires_internal_api_key() {
.expect("request should build");
assert_eq!(
send_status(&router, jwt_request).await,
- StatusCode::UNAUTHORIZED
+ StatusCode::FORBIDDEN
);
assert!(document_service.upload_snapshot_calls().is_empty());
- assert!(authorization_service.calls().is_empty());
+ assert_eq!(
+ authorization_service.calls(),
+ [AuthorizationCall::Jwt(JWT_TOKEN.to_string())]
+ );
let internal_request = Request::put("/snapshot-document/snapshot")
.header(INTERNAL_API_KEY_HEADER, STANDARD_INTERNAL_KEY)
@@ -998,10 +1001,13 @@ async fn snapshot_upload_requires_internal_api_key() {
);
assert_eq!(
authorization_service.calls(),
- [AuthorizationCall::Internal {
- provided_key: STANDARD_INTERNAL_KEY.to_string(),
- claims: InternalIdentityClaims::default(),
- }]
+ [
+ AuthorizationCall::Jwt(JWT_TOKEN.to_string()),
+ AuthorizationCall::Internal {
+ provided_key: STANDARD_INTERNAL_KEY.to_string(),
+ claims: InternalIdentityClaims::default(),
+ }
+ ]
);
}
diff --git a/crates/email/src/inbound/axum/axum_impls.rs b/crates/email/src/inbound/axum/axum_impls.rs
index 8160344a50..399a02e347 100644
--- a/crates/email/src/inbound/axum/axum_impls.rs
+++ b/crates/email/src/inbound/axum/axum_impls.rs
@@ -14,7 +14,7 @@ use axum::{
use axum_extra::extract::Cached;
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationService,
- MacroAuthorizationState,
+ MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
@@ -167,10 +167,12 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let header_link_id = parse_link_id_header(parts)?;
- let Cached(MacroAuthorizationExtractor { macro_user_id, .. }) = parts
- .extract_with_state(state)
- .await
- .map_err(EmailLinkErr::Authorization)?;
+ let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>> =
+ parts
+ .extract_with_state(state)
+ .await
+ .map_err(EmailLinkErr::Authorization)?;
+ let macro_user_id = authorization.authorization.user.macro_user_id.clone();
let caller = macro_user_id.clone();
let links = <EmailRouterState<U>>::from_ref(state)
.inner
@@ -205,10 +207,12 @@ where
type Rejection = EmailLinkErr;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
- let Cached(MacroAuthorizationExtractor { macro_user_id, .. }) = parts
- .extract_with_state(state)
- .await
- .map_err(EmailLinkErr::Authorization)?;
+ let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>> =
+ parts
+ .extract_with_state(state)
+ .await
+ .map_err(EmailLinkErr::Authorization)?;
+ let macro_user_id = authorization.authorization.user.macro_user_id.clone();
let links = <EmailRouterState<U>>::from_ref(state)
.inner
.get_inboxes_for_macro_id(macro_user_id)
diff --git a/crates/email/src/inbound/axum/previews_router.rs b/crates/email/src/inbound/axum/previews_router.rs
index ce7721cd1f..3ea8ca5628 100644
--- a/crates/email/src/inbound/axum/previews_router.rs
+++ b/crates/email/src/inbound/axum/previews_router.rs
@@ -5,7 +5,7 @@ use axum::{
};
use axum_extra::extract::Cached;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use model_error_response::ErrorResponse;
use models_pagination::{
@@ -82,22 +82,35 @@ where
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(links, macro_user, service), fields(user_id=macro_user.macro_user_id.as_ref(), fusionauth_user_id=macro_user.user_context.fusion_user_id))]
+#[tracing::instrument(
+ skip(links, macro_user, service),
+ fields(
+ actor = %macro_user.acting_entity(),
+ fusionauth_user_id = tracing::field::Empty,
+ )
+)]
async fn cursor_handler<T: EmailService, Auth: MacroAuthorizationService>(
State(service): State<EmailRouterState<T>>,
- Cached(macro_user): Cached<MacroAuthorizationExtractor<Auth>>,
+ Cached(macro_user): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>>,
Cached(MultiEmailLinkExtractor(links, _)): Cached<MultiEmailLinkExtractor<T, Auth>>,
PreviewViewPathExtractor(preview_view): PreviewViewPathExtractor,
extract::Query(params): extract::Query<GetPreviewsCursorParams>,
cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, ()>>,
) -> Result<Json<ApiPaginatedThreadCursor>, GetPreviewsCursorError> {
+ let user = &macro_user.authorization.user;
+ let span = tracing::Span::current();
+ span.record(
+ "fusionauth_user_id",
+ tracing::field::display(&user.user_context.fusion_user_id),
+ );
+
Ok(Json(ApiPaginatedThreadCursor::new(
service
.inner
.get_email_thread_previews(GetEmailsRequest {
view: preview_view,
link_ids: links.iter().map(|link| link.id).collect(),
- macro_id: macro_user.macro_user_id,
+ macro_id: user.macro_user_id.clone(),
limit: params.limit,
query: cursor
.into_query(
diff --git a/crates/email/src/inbound/axum/thread_labels_router.rs b/crates/email/src/inbound/axum/thread_labels_router.rs
index bb3534bc24..2e9f5a7c36 100644
--- a/crates/email/src/inbound/axum/thread_labels_router.rs
+++ b/crates/email/src/inbound/axum/thread_labels_router.rs
@@ -7,7 +7,7 @@ use axum::{
};
use axum_extra::extract::Cached;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use model_error_response::ErrorResponse;
use thiserror::Error;
@@ -115,16 +115,17 @@ where
#[tracing::instrument(err, skip(state, macro_user, body))]
pub async fn update_thread_labels_handler<T: EmailService, Auth: MacroAuthorizationService>(
State(state): State<EmailRouterState<T>>,
- Cached(macro_user): Cached<MacroAuthorizationExtractor<Auth>>,
+ Cached(macro_user): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>>,
Path(thread_id): Path<Uuid>,
Json(body): Json<UpdateThreadLabelRequest>,
) -> Result<Json<UpdateThreadLabelsResponse>, UpdateThreadLabelError> {
// Resolve the inbox from the thread (scoped to the caller's own and delegated
// inboxes). No Gmail token is needed here — provider sync goes through the
// gmail_ops queue, which authenticates itself.
+ let user = &macro_user.authorization.user;
let link = state
.inner
- .get_owned_link_for_thread(macro_user.macro_user_id, thread_id)
+ .get_owned_link_for_thread(user.macro_user_id.clone(), thread_id)
.await?
.ok_or_else(|| UpdateThreadLabelError::NotFound("Thread not found".to_string()))?;
diff --git a/crates/entity_access/src/inbound/axum_extractors/call.rs b/crates/entity_access/src/inbound/axum_extractors/call.rs
index 4dfa195f71..5a9d2a0a6c 100644
--- a/crates/entity_access/src/inbound/axum_extractors/call.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/call.rs
@@ -16,6 +16,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use uuid::Uuid;
@@ -73,13 +74,21 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
let Path(CallAccessParams { call_id }) = parts
.extract::<Path<CallAccessParams>>()
@@ -179,14 +188,22 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- user_context,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let (macro_user_id, user_context) = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| (Some(user.macro_user_id.clone()), user.user_context.clone()))
+ .unwrap_or_default();
let Path(CallWithChannelIdAccessParams { channel_id }) = parts
.extract::<Path<CallWithChannelIdAccessParams>>()
diff --git a/crates/entity_access/src/inbound/axum_extractors/call/test.rs b/crates/entity_access/src/inbound/axum_extractors/call/test.rs
index ee58106373..da1fcf2686 100644
--- a/crates/entity_access/src/inbound/axum_extractors/call/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/call/test.rs
@@ -8,8 +8,9 @@ use axum::{
routing::get,
};
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
+ MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -22,9 +23,12 @@ use tower::ServiceExt;
use uuid::Uuid;
use super::*;
-use crate::domain::models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, MemberParticipantRole, OwnerParticipantRole,
- UserTeamInfo,
+use crate::{
+ domain::models::{
+ AccessError, AccessLevel, BotId, CallChannelInfo, MemberParticipantRole,
+ OwnerParticipantRole, UserTeamInfo,
+ },
+ inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const CALL_ID: &str = "9e8e56e7-97e8-4148-9618-a63dacabf104";
@@ -234,6 +238,18 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -371,6 +387,14 @@ fn request(path: String, token: Option<&str>) -> Request<Body> {
.expect("request should be valid")
}
+fn bot_request(path: String) -> Request<Body> {
+ Request::builder()
+ .uri(path)
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(Body::empty())
+ .expect("request should be valid")
+}
+
fn internal_request(path: String, user_id: Option<&str>) -> Request<Body> {
let mut request = Request::builder()
.uri(path)
@@ -479,6 +503,18 @@ async fn missing_and_expired_credentials_are_rejected_for_both_variants() {
}
}
+#[tokio::test]
+async fn bot_credentials_are_forbidden_for_both_variants_without_permission_lookup() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ let state = TestState::new(true, member_permission());
+ let (status, body) = send(&state, bot_request(variant.valid_path())).await;
+
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
+ assert!(state.entity_access.permission_calls().is_empty());
+ }
+}
+
#[tokio::test]
async fn malformed_ids_are_rejected_for_both_variants() {
for variant in [Variant::CallId, Variant::ChannelId] {
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel.rs b/crates/entity_access/src/inbound/axum_extractors/channel.rs
index 5f40d87c49..1f38ef45c9 100644
--- a/crates/entity_access/src/inbound/axum_extractors/channel.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/channel.rs
@@ -22,6 +22,7 @@ use crate::domain::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
#[derive(Debug, serde::Deserialize)]
struct ChannelAccessParams {
@@ -54,14 +55,22 @@ where
#[tracing::instrument(err, skip(state, parts))]
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- user_context,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let (macro_user_id, user_context) = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| (Some(user.macro_user_id.clone()), user.user_context.clone()))
+ .unwrap_or_default();
let Path(ChannelAccessParams { channel_id }) = parts
.extract::<Path<ChannelAccessParams>>()
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
index b58de79d51..e9d871a4b2 100644
--- a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
@@ -8,8 +8,9 @@ use axum::{
routing::get,
};
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
+ MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -21,9 +22,12 @@ use tower::ServiceExt;
use uuid::Uuid;
use super::*;
-use crate::domain::models::{
- AccessError, AccessLevel, AdminParticipantRole, BotId, CallChannelInfo, MemberParticipantRole,
- OwnerParticipantRole, UserTeamInfo, ViewOnly,
+use crate::{
+ domain::models::{
+ AccessError, AccessLevel, AdminParticipantRole, BotId, CallChannelInfo,
+ MemberParticipantRole, OwnerParticipantRole, UserTeamInfo, ViewOnly,
+ },
+ inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const CHANNEL_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
@@ -188,6 +192,18 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -446,6 +462,29 @@ async fn missing_credentials_are_rejected_without_acl_call() {
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn bot_credentials_are_forbidden_without_permission_lookup() {
+ let state = TestState::new(EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner,
+ });
+ let mut request = request(None);
+ request.headers_mut().insert(
+ BOT_TOKEN_HEADER,
+ VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
+ );
+ let response = app(state.clone(), member_handler)
+ .oneshot(request)
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn expired_token_preserves_exact_rejection() {
let state = TestState::new(EntityPermission::ChannelRole {
diff --git a/crates/entity_access/src/inbound/axum_extractors/chat.rs b/crates/entity_access/src/inbound/axum_extractors/chat.rs
index 2795439448..da40fc1f4f 100644
--- a/crates/entity_access/src/inbound/axum_extractors/chat.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/chat.rs
@@ -13,6 +13,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use super::{ExtractorError, RequiredPermission};
@@ -55,13 +56,21 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
let chat_context: Extension<ChatBasic> = parts
.extract()
diff --git a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
index a4bb5960e3..bc433bca0a 100644
--- a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
@@ -7,8 +7,9 @@ use axum::{
response::IntoResponse,
};
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
+ MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -20,9 +21,12 @@ use rootcause::Report;
use uuid::Uuid;
use super::*;
-use crate::domain::models::{
- AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
- ViewAccessLevel,
+use crate::{
+ domain::models::{
+ AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
+ ViewAccessLevel,
+ },
+ inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const CHAT_ID: &str = "chat-1";
@@ -186,6 +190,18 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -429,6 +445,27 @@ async fn invalid_internal_credentials_are_rejected_without_acl_lookup() {
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn bot_credentials_are_forbidden_without_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let mut request = request(None, chat(false));
+ request.headers_mut().insert(
+ BOT_TOKEN_HEADER,
+ VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
+ );
+ let error = extract::<ViewAccessLevel>(request, &state)
+ .await
+ .expect_err("bot credentials should be forbidden");
+ let response = error.into_response();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn expired_token_preserves_exact_unauthorized_json() {
let state = TestState::new(Some(AccessLevel::Owner));
diff --git a/crates/entity_access/src/inbound/axum_extractors/document.rs b/crates/entity_access/src/inbound/axum_extractors/document.rs
index 37afdb36f6..d1fcb1ddc7 100644
--- a/crates/entity_access/src/inbound/axum_extractors/document.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/document.rs
@@ -13,6 +13,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use super::{ExtractorError, RequiredPermission};
@@ -55,13 +56,21 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
let document_context: Extension<DocumentBasic> = parts
.extract()
diff --git a/crates/entity_access/src/inbound/axum_extractors/document/test.rs b/crates/entity_access/src/inbound/axum_extractors/document/test.rs
index 486dbaadf9..9045aca0ae 100644
--- a/crates/entity_access/src/inbound/axum_extractors/document/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/document/test.rs
@@ -7,8 +7,9 @@ use axum::{
response::IntoResponse,
};
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
+ MacroAuthorizationService, MacroAuthorizationState,
};
#[allow(deprecated)]
use macro_authorization::{
@@ -24,9 +25,12 @@ use rootcause::Report;
use uuid::Uuid;
use super::*;
-use crate::domain::models::{
- AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
- ViewAccessLevel,
+use crate::{
+ domain::models::{
+ AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
+ ViewAccessLevel,
+ },
+ inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const DOCUMENT_ID: &str = "document-1";
@@ -191,6 +195,18 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -485,6 +501,27 @@ async fn invalid_internal_credentials_are_rejected_without_acl_lookup() {
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn bot_credentials_are_forbidden_without_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let mut request = request(None, document(false));
+ request.headers_mut().insert(
+ BOT_TOKEN_HEADER,
+ VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
+ );
+ let error = extract::<ViewAccessLevel>(request, &state)
+ .await
+ .expect_err("bot credentials should be forbidden");
+ let response = error.into_response();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn expired_token_preserves_exact_unauthorized_json() {
let state = TestState::new(Some(AccessLevel::Owner));
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_body.rs b/crates/entity_access/src/inbound/axum_extractors/entity_body.rs
index 956148b0a4..9d83e2396b 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_body.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_body.rs
@@ -11,6 +11,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use serde::{Deserialize, de::DeserializeOwned};
@@ -55,11 +56,19 @@ where
#[tracing::instrument(err, skip(req, state))]
async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> {
- let OptionalMacroAuthorizationExtractor { macro_user_id, .. } = req
- .extract_parts_with_state::<OptionalMacroAuthorizationExtractor<Auth>, _>(state)
+ let authorization = req
+ .extract_parts_with_state::<
+ OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService>,
+ _,
+ >(state)
.await
.map_err(ExtractorError::from)?;
- let user = macro_user_id.ok_or(ExtractorError::Unauthorized)?;
+ let user = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone())
+ .ok_or(ExtractorError::Unauthorized)?;
let Json(json): Json<serde_json::Value> = req
.extract()
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs b/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
index aa8ffefd70..b0c7fa0a88 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
@@ -4,7 +4,9 @@ use axum::{
http::{Request, StatusCode, header, request::Builder},
routing::post,
};
-use macro_authorization::{INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER};
+use macro_authorization::{
+ BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+};
use serde::Deserialize;
use tower::ServiceExt;
@@ -13,7 +15,7 @@ use crate::{
domain::models::{AccessLevel, EditAccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel},
inbound::axum_extractors::test_support::{
AccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY, TestState,
- USER_ID,
+ USER_ID, VALID_BOT_TOKEN,
},
};
@@ -171,6 +173,24 @@ async fn identity_less_internal_access_is_rejected_before_body_and_acl_lookup()
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn bot_access_is_forbidden_before_body_and_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(body("document", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert_eq!(response_body(response).await, r#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn absent_access_is_rejected() {
let state = TestState::new(None);
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs b/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
index 3877a3f33e..61fd70f614 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
@@ -12,6 +12,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use super::ExtractorError;
@@ -55,14 +56,22 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- user_context,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let (macro_user_id, user_context) = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| (Some(user.macro_user_id.clone()), user.user_context.clone()))
+ .unwrap_or_default();
let Path(EntityPermissionParams {
entity_type,
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs b/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
index c056490e80..fc77040084 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
@@ -8,9 +8,9 @@ use axum::{
routing::get,
};
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
- InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
- MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -23,12 +23,15 @@ use tower::ServiceExt;
use uuid::Uuid;
use super::EntityPermissionExtractor;
-use crate::domain::{
- models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessAuth, EntityAccessReceipt,
- EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+use crate::{
+ domain::{
+ models::{
+ AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessAuth,
+ EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+ },
+ ports::EntityAccessService,
},
- ports::EntityAccessService,
+ inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const USER_ID: &str = "macro|[email protected]";
@@ -182,6 +185,7 @@ impl EntityAccessService for FakeEntityAccessService {
#[derive(Clone, Debug, Eq, PartialEq)]
enum AuthorizationCall {
Bearer(String),
+ Bot(String),
Internal {
provided_key: String,
claims: InternalIdentityClaims,
@@ -214,6 +218,23 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(AuthorizationCall::Bot(token.to_string()));
+
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -406,6 +427,24 @@ async fn invalid_and_expired_tokens_preserve_authorization_rejections() {
}
}
+#[tokio::test]
+async fn bot_credentials_are_forbidden_without_permission_lookup() {
+ let (router, entity_access, authorization) = test_router();
+ let request = empty_body(
+ request(&format!("/entity/document/{ENTITY_ID}")).header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
+ assert!(entity_access.calls().is_empty());
+ assert_eq!(
+ authorization.calls(),
+ [AuthorizationCall::Bot(VALID_BOT_TOKEN.to_string())]
+ );
+}
+
#[tokio::test]
async fn internal_request_with_acting_user_looks_up_the_users_permission() {
let (router, entity_access, authorization) = test_router();
diff --git a/crates/entity_access/src/inbound/axum_extractors/foreign_entity.rs b/crates/entity_access/src/inbound/axum_extractors/foreign_entity.rs
index c878916a04..53be6d4ec3 100644
--- a/crates/entity_access/src/inbound/axum_extractors/foreign_entity.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/foreign_entity.rs
@@ -1,5 +1,8 @@
//! Foreign entity access extractor.
+#[cfg(test)]
+mod test;
+
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;
@@ -11,6 +14,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use uuid::Uuid;
@@ -58,13 +62,21 @@ where
})?;
let foreign_entity_id = extract_foreign_entity_id(&path_params)?.to_string();
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
if macro_user_id.is_none() && is_internal_access {
return Self::from_permission(
diff --git a/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs b/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs
new file mode 100644
index 0000000000..02f342a28b
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs
@@ -0,0 +1,52 @@
+use axum::{
+ Router,
+ body::{Body, to_bytes},
+ http::{Request, StatusCode},
+ routing::get,
+};
+use macro_authorization::BOT_TOKEN_HEADER;
+use tower::ServiceExt;
+
+use super::*;
+use crate::{
+ domain::models::{AccessLevel, ViewAccessLevel},
+ inbound::axum_extractors::test_support::{
+ FakeAuthorizationService, FakeEntityAccessService, TestState, VALID_BOT_TOKEN,
+ },
+};
+
+const FOREIGN_ENTITY_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
+
+type ViewExtractor = ForeignEntityAccessLevelExtractor<
+ ViewAccessLevel,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
+
+async fn handler(_access: ViewExtractor) -> StatusCode {
+ StatusCode::OK
+}
+
+#[tokio::test]
+async fn bot_credentials_are_forbidden_without_permission_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let router = Router::new()
+ .route("/foreign/{foreign_entity_id}", get(handler))
+ .with_state(state.clone());
+ let request = Request::get(format!("/foreign/{FOREIGN_ENTITY_ID}"))
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(Body::empty())
+ .expect("request should be valid");
+
+ let response = router
+ .oneshot(request)
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/history.rs b/crates/entity_access/src/inbound/axum_extractors/history.rs
index c6f13a81f2..78c4324fcf 100644
--- a/crates/entity_access/src/inbound/axum_extractors/history.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/history.rs
@@ -12,6 +12,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use super::{ExtractorError, RequiredPermission};
@@ -57,13 +58,21 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
let Path(HistoryParams { item_id, item_type }) =
<Path<HistoryParams>>::from_request_parts(parts, state)
diff --git a/crates/entity_access/src/inbound/axum_extractors/history/test.rs b/crates/entity_access/src/inbound/axum_extractors/history/test.rs
index cea63849e7..0ad3bbbcd8 100644
--- a/crates/entity_access/src/inbound/axum_extractors/history/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/history/test.rs
@@ -4,7 +4,9 @@ use axum::{
http::{Request, StatusCode, header},
routing::post,
};
-use macro_authorization::{INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER};
+use macro_authorization::{
+ BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+};
use tower::ServiceExt;
use super::*;
@@ -12,7 +14,7 @@ use crate::{
domain::models::{AccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel},
inbound::axum_extractors::test_support::{
AccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY, TestState,
- USER_ID,
+ USER_ID, VALID_BOT_TOKEN,
},
};
@@ -107,6 +109,24 @@ async fn internal_history_act_as_identity_uses_acl() {
);
}
+#[tokio::test]
+async fn bot_history_access_is_forbidden_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert_eq!(response_body(response).await, r#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn expired_history_credentials_preserve_authorization_rejection() {
let state = TestState::new(Some(AccessLevel::Owner));
diff --git a/crates/entity_access/src/inbound/axum_extractors/pin.rs b/crates/entity_access/src/inbound/axum_extractors/pin.rs
index e70d8a15d9..b44181782e 100644
--- a/crates/entity_access/src/inbound/axum_extractors/pin.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/pin.rs
@@ -13,6 +13,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use super::{ExtractorError, RequiredPermission};
@@ -66,11 +67,19 @@ where
async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor { macro_user_id, .. } = req
- .extract_parts_with_state::<OptionalMacroAuthorizationExtractor<Auth>, _>(state)
+ let authorization = req
+ .extract_parts_with_state::<
+ OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService>,
+ _,
+ >(state)
.await
.map_err(ExtractorError::from)?;
- let macro_user_id = macro_user_id.ok_or(ExtractorError::Unauthorized)?;
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone())
+ .ok_or(ExtractorError::Unauthorized)?;
let Path(PinParams { pinned_item_id }) = req
.extract_parts_with_state(state)
diff --git a/crates/entity_access/src/inbound/axum_extractors/pin/test.rs b/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
index 2c4a173f83..31c0be80cb 100644
--- a/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
@@ -4,7 +4,9 @@ use axum::{
http::{Request, StatusCode, header},
routing::post,
};
-use macro_authorization::{INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER};
+use macro_authorization::{
+ BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+};
use serde::Deserialize;
use tower::ServiceExt;
@@ -13,7 +15,7 @@ use crate::{
domain::models::{AccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel},
inbound::axum_extractors::test_support::{
AccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY, TestState,
- USER_ID,
+ USER_ID, VALID_BOT_TOKEN,
},
};
@@ -150,6 +152,24 @@ async fn internal_pin_act_as_identity_uses_acl() {
);
}
+#[tokio::test]
+async fn bot_pin_access_is_forbidden_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(body())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert_eq!(response_body(response).await, r#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn expired_pin_credentials_preserve_authorization_rejection() {
let state = TestState::new(Some(AccessLevel::Owner));
diff --git a/crates/entity_access/src/inbound/axum_extractors/project.rs b/crates/entity_access/src/inbound/axum_extractors/project.rs
index a103ad6230..4e5bfdcae5 100644
--- a/crates/entity_access/src/inbound/axum_extractors/project.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/project.rs
@@ -13,6 +13,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use macro_user_id::user_id::MacroUserIdStr;
use serde::de::DeserializeOwned;
@@ -57,13 +58,21 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
let project_context: Extension<BasicProject> = parts
.extract()
@@ -267,14 +276,19 @@ where
async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- is_internal_access,
- ..
- } = req
+ let authorization: OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService> = req
.extract_parts_with_state(state)
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
let has_internal_owner_access = macro_user_id.is_none() && is_internal_access;
extract_project_body_access(req, service, macro_user_id, has_internal_owner_access)
diff --git a/crates/entity_access/src/inbound/axum_extractors/project/test.rs b/crates/entity_access/src/inbound/axum_extractors/project/test.rs
index 53e7e2671d..57adf6e2d8 100644
--- a/crates/entity_access/src/inbound/axum_extractors/project/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/project/test.rs
@@ -7,8 +7,9 @@ use axum::{
response::IntoResponse,
};
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
+ MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};
use model_user::UserContext;
@@ -16,9 +17,12 @@ use rootcause::Report;
use uuid::Uuid;
use super::*;
-use crate::domain::models::{
- AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
- ViewAccessLevel,
+use crate::{
+ domain::models::{
+ AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
+ ViewAccessLevel,
+ },
+ inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const PROJECT_ID: &str = "project-1";
@@ -182,6 +186,18 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -259,6 +275,14 @@ fn bearer_request(body: &str, token: &str) -> Request<Body> {
.expect("request should be valid")
}
+fn bot_request(body: &str) -> Request<Body> {
+ Request::post("/")
+ .header(header::CONTENT_TYPE, "application/json")
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(Body::from(body.to_string()))
+ .expect("request should be valid")
+}
+
fn internal_request(body: &str, user_id: Option<&str>) -> Request<Body> {
let mut request = Request::post("/")
.header(header::CONTENT_TYPE, "application/json")
@@ -351,6 +375,27 @@ async fn authenticated_project_owner_bypasses_access_lookup() {
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn bot_project_access_is_forbidden_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let mut request = project_request(None, project(false));
+ request.headers_mut().insert(
+ BOT_TOKEN_HEADER,
+ VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
+ );
+ let error = extract_project_access::<ViewAccessLevel>(request, &state)
+ .await
+ .expect_err("bot credentials should be forbidden");
+ let response = error.into_response();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn deleted_project_rejects_non_owner_before_access_lookup() {
let state = TestState::new(Some(AccessLevel::Owner));
@@ -455,6 +500,25 @@ async fn direct_project_id_with_sufficient_access_returns_receipt_and_body() {
);
}
+#[tokio::test]
+async fn bot_project_body_access_is_forbidden_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let error = EditExtractor::from_request(
+ bot_request(r#"{"name":"document","projectId":"project-1"}"#),
+ &state,
+ )
+ .await
+ .expect_err("bot credentials should be forbidden");
+ let response = error.into_response();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn parent_project_id_is_used_for_access_lookup() {
let state = TestState::new(Some(AccessLevel::Owner));
diff --git a/crates/entity_access/src/inbound/axum_extractors/team.rs b/crates/entity_access/src/inbound/axum_extractors/team.rs
index 8dc5482a0b..6043726b57 100644
--- a/crates/entity_access/src/inbound/axum_extractors/team.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/team.rs
@@ -22,7 +22,7 @@ use crate::domain::{
ports::EntityAccessService,
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
@@ -124,11 +124,15 @@ where
#[tracing::instrument(err, skip(state, parts))]
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroAuthorizationExtractor { macro_user_id, .. } = parts
+ let authorization: MacroAuthorizationExtractor<Auth, UserOrInternal> = parts
.extract_with_state(state)
.await
.map_err(ExtractorError::from)?;
- let outcome = team_access_outcome::<T, Svc>(service.as_ref(), macro_user_id).await?;
+ let outcome = team_access_outcome::<T, Svc>(
+ service.as_ref(),
+ authorization.authorization.user.macro_user_id,
+ )
+ .await?;
Ok(Self {
entity_access_receipt: outcome.into_optional_receipt(),
@@ -164,13 +168,16 @@ where
#[tracing::instrument(err, skip(state, parts))]
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroAuthorizationExtractor { macro_user_id, .. } = parts
+ let authorization: MacroAuthorizationExtractor<Auth, UserOrInternal> = parts
.extract_with_state(state)
.await
.map_err(ExtractorError::from)?;
- let entity_access_receipt = team_access_outcome::<T, Svc>(service.as_ref(), macro_user_id)
- .await?
- .into_required_receipt()?;
+ let entity_access_receipt = team_access_outcome::<T, Svc>(
+ service.as_ref(),
+ authorization.authorization.user.macro_user_id,
+ )
+ .await?
+ .into_required_receipt()?;
Ok(Self {
entity_access_receipt,
diff --git a/crates/entity_access/src/inbound/axum_extractors/team/test.rs b/crates/entity_access/src/inbound/axum_extractors/team/test.rs
index 0b54349577..31258d9ea6 100644
--- a/crates/entity_access/src/inbound/axum_extractors/team/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/team/test.rs
@@ -1,4 +1,7 @@
-use std::{collections::HashMap, sync::Arc};
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
use axum::{
body::{Body, to_bytes},
@@ -9,8 +12,9 @@ use axum::{
#[allow(deprecated)]
use macro_authorization::LEGACY_DSS_INTERNAL_API_KEY_HEADER;
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
+ MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -21,9 +25,12 @@ use rootcause::Report;
use uuid::Uuid;
use super::*;
-use crate::domain::models::{
- AccessError, AccessLevel, AdminTeamRole, BotId, CallChannelInfo, EntityAccessAuth,
- EntityPermission, TeamRole, UserTeamInfo,
+use crate::{
+ domain::models::{
+ AccessError, AccessLevel, AdminTeamRole, BotId, CallChannelInfo, EntityAccessAuth,
+ EntityPermission, TeamRole, UserTeamInfo,
+ },
+ inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const USER_ID: &str = "macro|[email protected]";
@@ -43,6 +50,7 @@ type RequiredV2Extractor =
#[derive(Clone, Debug, Default)]
struct FakeEntityAccessService {
memberships: Arc<HashMap<String, UserTeamInfo>>,
+ membership_lookups: Arc<Mutex<Vec<String>>>,
}
impl FakeEntityAccessService {
@@ -56,6 +64,13 @@ impl FakeEntityAccessService {
);
self
}
+
+ fn membership_lookups(&self) -> Vec<String> {
+ self.membership_lookups
+ .lock()
+ .expect("membership lookups lock poisoned")
+ .clone()
+ }
}
impl EntityAccessService for FakeEntityAccessService {
@@ -66,7 +81,7 @@ impl EntityAccessService for FakeEntityAccessService {
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- Err(AccessError::Internal)
+ panic!("unexpected generate_entity_access_receipt call")
}
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
@@ -75,7 +90,7 @@ impl EntityAccessService for FakeEntityAccessService {
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- Err(AccessError::Internal)
+ panic!("unexpected generate_bot_entity_access_receipt call")
}
async fn get_access_level(
@@ -151,6 +166,10 @@ impl EntityAccessService for FakeEntityAccessService {
&self,
user_id: &MacroUserId<Lowercase<'_>>,
) -> Result<Option<UserTeamInfo>, AccessError> {
+ self.membership_lookups
+ .lock()
+ .expect("membership lookups lock poisoned")
+ .push(user_id.as_ref().to_string());
Ok(self.memberships.get(user_id.as_ref()).copied())
}
}
@@ -177,6 +196,18 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -347,6 +378,47 @@ async fn required_v2_rejects_expired_credentials() {
assert_eq!(body, r#"{"message":"jwt expired"}"#);
}
+#[tokio::test]
+async fn team_extractors_forbid_bots_without_membership_lookup() {
+ let optional_state = state(
+ FakeEntityAccessService::default(),
+ FakeAuthorizationService::default(),
+ );
+ let optional_error = extract_v2(
+ Request::builder()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(Body::empty())
+ .expect("request should be valid"),
+ &optional_state,
+ )
+ .await
+ .expect_err("bot credentials should be forbidden");
+ let (status, body) = response_parts(optional_error.into_response()).await;
+
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, r#"{"message":"forbidden"}"#);
+ assert!(optional_state.entity_access.membership_lookups().is_empty());
+
+ let required_state = state(
+ FakeEntityAccessService::default(),
+ FakeAuthorizationService::default(),
+ );
+ let required_error = extract_required_v2(
+ Request::builder()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(Body::empty())
+ .expect("request should be valid"),
+ &required_state,
+ )
+ .await
+ .expect_err("bot credentials should be forbidden");
+ let (status, body) = response_parts(required_error.into_response()).await;
+
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, r#"{"message":"forbidden"}"#);
+ assert!(required_state.entity_access.membership_lookups().is_empty());
+}
+
#[tokio::test]
async fn required_v2_preserves_no_membership_error() {
let state = state(
diff --git a/crates/entity_access/src/inbound/axum_extractors/test_support.rs b/crates/entity_access/src/inbound/axum_extractors/test_support.rs
index 2b56feca56..81577948a9 100644
--- a/crates/entity_access/src/inbound/axum_extractors/test_support.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/test_support.rs
@@ -2,8 +2,8 @@ use std::sync::{Arc, Mutex};
use axum::extract::FromRef;
use macro_authorization::{
- InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
- MacroAuthorizationState,
+ BotActingUserClaims, BotAuthentication, InternalIdentityClaims, MacroAuthorizationError,
+ MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -24,6 +24,7 @@ use crate::domain::{
pub(super) const INTERNAL_KEY: &str = "valid-internal-key";
pub(super) const USER_ID: &str = "macro|[email protected]";
+pub(super) const VALID_BOT_TOKEN: &str = "valid-bot-token";
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct AccessCall {
@@ -169,6 +170,18 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -182,6 +195,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+pub(super) fn valid_bot_authentication() -> BotAuthentication {
+ BotAuthentication {
+ bot_id: BotId::new_from_uuid(Uuid::from_u128(1)),
+ token_id: Uuid::from_u128(2),
+ acting_user: None,
+ }
+}
+
fn user_context(user_id: &str) -> UserContext {
UserContext {
user_id: user_id.to_string(),
diff --git a/crates/entity_access/src/inbound/axum_extractors/thread.rs b/crates/entity_access/src/inbound/axum_extractors/thread.rs
index 868da91c97..8832a6c947 100644
--- a/crates/entity_access/src/inbound/axum_extractors/thread.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/thread.rs
@@ -14,6 +14,7 @@ use axum::{
};
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use super::{ExtractorError, RequiredPermission};
@@ -52,13 +53,21 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let OptionalMacroAuthorizationExtractor {
- macro_user_id,
- is_internal_access,
- ..
- } = OptionalMacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state)
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(ExtractorError::from)?;
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
let Path(path_params): Path<HashMap<String, String>> = parts
.extract()
diff --git a/crates/entity_access/src/inbound/axum_extractors/thread/test.rs b/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
index 82904166d5..326990f90a 100644
--- a/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
@@ -8,8 +8,9 @@ use axum::{
routing::get,
};
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
+ MacroAuthorizationService, MacroAuthorizationState,
};
use model_user::UserContext;
use rootcause::Report;
@@ -19,7 +20,8 @@ use super::*;
use crate::{
domain::models::{EditAccessLevel, EntityAccessAuth, ViewAccessLevel},
inbound::axum_extractors::test_support::{
- AccessCall, FakeEntityAccessService, INTERNAL_KEY, USER_ID,
+ AccessCall, FakeEntityAccessService, INTERNAL_KEY, USER_ID, VALID_BOT_TOKEN,
+ valid_bot_authentication,
},
};
@@ -54,6 +56,18 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(valid_bot_authentication())
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -294,6 +308,24 @@ async fn default_internal_user_uses_the_users_acl() {
);
}
+#[tokio::test]
+async fn bot_thread_access_is_forbidden_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = view_router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert_eq!(response_body(response).await, r#"{"message":"forbidden"}"#);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn invalid_internal_key_is_rejected_without_anonymous_fallback() {
let state = TestState::new(Some(AccessLevel::Owner));
diff --git a/crates/favorites/src/inbound/axum_router.rs b/crates/favorites/src/inbound/axum_router.rs
index 1185307b26..4c90d4ba87 100644
--- a/crates/favorites/src/inbound/axum_router.rs
+++ b/crates/favorites/src/inbound/axum_router.rs
@@ -14,7 +14,7 @@ use entity_access::{
inbound::axum_extractors::EntityBodyAccessLevelExtractor,
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use model_entity::EntityType;
use model_error_response::ErrorResponse;
@@ -165,14 +165,17 @@ pub struct ReorderFavoritesRequest {
#[tracing::instrument(err, skip_all)]
pub async fn list_favorites_handler<S, AccessSvc, Auth>(
State(state): State<FavoritesRouterState<S, AccessSvc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<FavoritesList>, FavoritesError>
where
S: FavoritesService,
AccessSvc: EntityAccessService,
Auth: MacroAuthorizationService,
{
- let favorites = state.service.list_favorites(&user.macro_user_id).await?;
+ let favorites = state
+ .service
+ .list_favorites(&user.authorization.user.macro_user_id)
+ .await?;
Ok(Json(FavoritesList { favorites }))
}
@@ -225,7 +228,7 @@ where
#[tracing::instrument(err, skip_all)]
pub async fn remove_favorite_by_entity_handler<S, AccessSvc, Auth>(
State(state): State<FavoritesRouterState<S, AccessSvc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(params): Path<RemoveFavoriteByEntityParams>,
) -> Result<Json<()>, FavoritesError>
where
@@ -236,7 +239,7 @@ where
let entity = params.entity_type.with_entity_str(&params.entity_id);
state
.service
- .remove_favorite_by_entity(&user.macro_user_id, &entity)
+ .remove_favorite_by_entity(&user.authorization.user.macro_user_id, &entity)
.await?;
Ok(Json(()))
}
@@ -258,7 +261,7 @@ where
#[tracing::instrument(err, skip_all)]
pub async fn reorder_favorites_handler<S, AccessSvc, Auth>(
State(state): State<FavoritesRouterState<S, AccessSvc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<ReorderFavoritesRequest>,
) -> Result<Json<()>, FavoritesError>
where
@@ -273,7 +276,7 @@ where
.collect();
state
.service
- .reorder_favorites(&user.macro_user_id, &ordered)
+ .reorder_favorites(&user.authorization.user.macro_user_id, &ordered)
.await?;
Ok(Json(()))
}
diff --git a/crates/graphql_common/src/authorization.rs b/crates/graphql_common/src/authorization.rs
index ec8a487184..4f2a6cdcd6 100644
--- a/crates/graphql_common/src/authorization.rs
+++ b/crates/graphql_common/src/authorization.rs
@@ -6,6 +6,7 @@ use axum::extract::FromRef;
use axum_extra::extract::Cached;
use macro_authorization::{
MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
use macro_user_id::user_id::MacroUserIdStr;
@@ -25,10 +26,16 @@ where
return Ok(user_id.clone());
}
- let Cached(authorization) =
- extract_part::<Cached<OptionalMacroAuthorizationExtractor<Auth>>, St>(ctx).await?;
+ let Cached(authorization) = extract_part::<
+ Cached<OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService>>,
+ St,
+ >(ctx)
+ .await?;
authorization
- .macro_user_id
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone())
.ok_or_else(|| async_graphql::Error::new("authentication required"))
}
diff --git a/crates/graphql_common/src/authorization/test.rs b/crates/graphql_common/src/authorization/test.rs
index acb7080c6c..ddaa8326b2 100644
--- a/crates/graphql_common/src/authorization/test.rs
+++ b/crates/graphql_common/src/authorization/test.rs
@@ -9,8 +9,8 @@ use axum::{
http::{Request as HttpRequest, header},
};
use macro_authorization::{
- InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
- MacroAuthorizationState,
+ BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use model_user::UserContext;
use rootcause::Report;
@@ -19,6 +19,7 @@ use super::*;
use crate::GraphqlRequestParts;
const VALID_USER_ID: &str = "macro|[email protected]";
+const VALID_BOT_TOKEN: &str = "valid-bot";
#[derive(Clone, Default)]
struct FakeAuthorizationService {
@@ -47,6 +48,26 @@ impl MacroAuthorizationService for FakeAuthorizationService {
})
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ _acting_user: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ self.authorization_calls.fetch_add(1, Ordering::SeqCst);
+
+ if token != VALID_BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(BotAuthentication {
+ bot_id: "00000000-0000-0000-0000-000000000001"
+ .parse()
+ .expect("valid bot ID"),
+ token_id: uuid::Uuid::from_u128(2),
+ acting_user: None,
+ })
+ }
+
async fn authorize_internal(
&self,
_provided_key: &str,
@@ -87,17 +108,27 @@ impl TestQuery {
}
}
+enum RequestCredentials<'a> {
+ Anonymous,
+ Bearer(&'a str),
+ Bot(&'a str),
+}
+
async fn execute(
service: &FakeAuthorizationService,
- bearer_token: Option<&str>,
+ credentials: RequestCredentials<'_>,
query: &str,
) -> async_graphql::Response {
- let request = match bearer_token {
- Some(token) => HttpRequest::builder()
+ let request = match credentials {
+ RequestCredentials::Anonymous => HttpRequest::new(()),
+ RequestCredentials::Bearer(token) => HttpRequest::builder()
.header(header::AUTHORIZATION, format!("Bearer {token}"))
.body(())
.unwrap(),
- None => HttpRequest::new(()),
+ RequestCredentials::Bot(token) => HttpRequest::builder()
+ .header(BOT_TOKEN_HEADER, token)
+ .body(())
+ .unwrap(),
};
let (parts, ()) = request.into_parts();
let state = TestState {
@@ -115,7 +146,7 @@ async fn execute(
async fn valid_bearer_returns_macro_user_id() {
let service = FakeAuthorizationService::default();
- let response = execute(&service, Some("valid"), "{ userId }").await;
+ let response = execute(&service, RequestCredentials::Bearer("valid"), "{ userId }").await;
assert!(response.errors.is_empty(), "{:?}", response.errors);
assert_eq!(
@@ -128,7 +159,7 @@ async fn valid_bearer_returns_macro_user_id() {
async fn missing_credentials_require_authentication() {
let service = FakeAuthorizationService::default();
- let response = execute(&service, None, "{ userId }").await;
+ let response = execute(&service, RequestCredentials::Anonymous, "{ userId }").await;
assert_eq!(response.errors.len(), 1);
assert_eq!(response.errors[0].message, "authentication required");
@@ -139,18 +170,44 @@ async fn missing_credentials_require_authentication() {
async fn invalid_credentials_preserve_safe_authorization_message() {
let service = FakeAuthorizationService::default();
- let response = execute(&service, Some("invalid"), "{ userId }").await;
+ let response = execute(
+ &service,
+ RequestCredentials::Bearer("invalid"),
+ "{ userId }",
+ )
+ .await;
assert_eq!(response.errors.len(), 1);
assert_eq!(response.errors[0].message, "unauthorized");
assert_eq!(service.authorization_calls(), 1);
}
+#[tokio::test]
+async fn valid_bot_credentials_return_safe_forbidden_message() {
+ let service = FakeAuthorizationService::default();
+
+ let response = execute(
+ &service,
+ RequestCredentials::Bot(VALID_BOT_TOKEN),
+ "{ userId }",
+ )
+ .await;
+
+ assert_eq!(response.errors.len(), 1);
+ assert_eq!(response.errors[0].message, "forbidden");
+ assert_eq!(service.authorization_calls(), 1);
+}
+
#[tokio::test]
async fn repeated_helper_calls_share_cached_authorization() {
let service = FakeAuthorizationService::default();
- let response = execute(&service, Some("valid"), "{ repeatedUserIds }").await;
+ let response = execute(
+ &service,
+ RequestCredentials::Bearer("valid"),
+ "{ repeatedUserIds }",
+ )
+ .await;
assert!(response.errors.is_empty(), "{:?}", response.errors);
assert_eq!(
diff --git a/crates/import/src/inbound/axum_router.rs b/crates/import/src/inbound/axum_router.rs
index c570a4bf71..658b529c5d 100644
--- a/crates/import/src/inbound/axum_router.rs
+++ b/crates/import/src/inbound/axum_router.rs
@@ -11,7 +11,7 @@ use axum::{
routing::{get, post},
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use serde::Deserialize;
use std::str::FromStr;
@@ -107,12 +107,12 @@ fn unknown_source_response(source: &str) -> Response {
),
tag = "import"
)]
-#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn get_state_handler<T: ImportService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Response {
- match service.state(user.macro_user_id).await {
+ match service.state(user.authorization.user.macro_user_id).await {
Ok(state) => Json(state).into_response(),
Err(e) => error_response(e),
}
@@ -129,14 +129,18 @@ pub async fn get_state_handler<T: ImportService, Auth: MacroAuthorizationService
),
tag = "import"
)]
-#[tracing::instrument(skip(service, user, body), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(skip(service, user, body), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn run_import_handler<T: ImportService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(body): Json<RunImportRequest>,
) -> Response {
match service
- .run_import(user.macro_user_id, body.import_ids, body.discard_ids)
+ .run_import(
+ user.authorization.user.macro_user_id,
+ body.import_ids,
+ body.discard_ids,
+ )
.await
{
Ok(outcome) => Json(outcome).into_response(),
@@ -156,16 +160,19 @@ pub async fn run_import_handler<T: ImportService, Auth: MacroAuthorizationServic
),
tag = "import"
)]
-#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn retry_gather_handler<T: ImportService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(source): Path<String>,
) -> Response {
let Ok(source) = ImportSource::from_str(&source) else {
return unknown_source_response(&source);
};
- match service.retry_gather(user.macro_user_id, source).await {
+ match service
+ .retry_gather(user.authorization.user.macro_user_id, source)
+ .await
+ {
Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(e),
}
@@ -183,16 +190,19 @@ pub async fn retry_gather_handler<T: ImportService, Auth: MacroAuthorizationServ
),
tag = "import"
)]
-#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn dismiss_run_handler<T: ImportService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(source): Path<String>,
) -> Response {
let Ok(source) = ImportSource::from_str(&source) else {
return unknown_source_response(&source);
};
- match service.dismiss_run(user.macro_user_id, source).await {
+ match service
+ .dismiss_run(user.authorization.user.macro_user_id, source)
+ .await
+ {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(e),
}
diff --git a/crates/macro_authorization/Cargo.toml b/crates/macro_authorization/Cargo.toml
index 70b1cc3f58..7063691b97 100644
--- a/crates/macro_authorization/Cargo.toml
+++ b/crates/macro_authorization/Cargo.toml
@@ -8,27 +8,29 @@ version = "0.1.0"
axum = [
"dep:axum",
"dep:macro_auth",
- "dep:macro_user_id",
"dep:model-error-response",
"dep:serde",
- "dep:tracing",
]
default = ["axum", "outbound"]
local_auth = ["dep:macro_env_var"]
-outbound = ["dep:macro_auth", "dep:tracing"]
+outbound = ["dep:macro_auth"]
+postgres = ["dep:sqlx"]
[dependencies]
axum = { workspace = true, optional = true }
+bot_id = { path = "../bot_id" }
constant_time_eq = { workspace = true }
macro_auth = { path = "../macro_auth", optional = true }
macro_env_var = { path = "../macro_env_var", optional = true }
-macro_user_id = { path = "../macro_user_id", optional = true }
+macro_user_id = { path = "../macro_user_id" }
model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user" }
rootcause = { workspace = true }
serde = { workspace = true, optional = true }
+sqlx = { workspace = true, optional = true }
thiserror = { workspace = true }
-tracing = { workspace = true, optional = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
@@ -36,6 +38,7 @@ cookie = { workspace = true }
http-body-util = { workspace = true }
jsonwebtoken = { workspace = true }
macro_auth = { path = "../macro_auth", features = ["testing"] }
+macro_db_migrator = { path = "../macro_db_migrator" }
serde_json = { workspace = true }
serde_urlencoded = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }
diff --git a/crates/macro_authorization/src/domain.rs b/crates/macro_authorization/src/domain.rs
index 940bb52324..16e799cd60 100644
--- a/crates/macro_authorization/src/domain.rs
+++ b/crates/macro_authorization/src/domain.rs
@@ -1,5 +1,7 @@
//! Authorization domain models, ports, and service implementation.
+/// Bot credential authorization policy.
+pub mod bot_authorizer;
/// Models produced and consumed by the authorization domain.
pub mod models;
/// Interfaces that connect the authorization domain to its adapters.
diff --git a/crates/macro_authorization/src/domain/bot_authorizer.rs b/crates/macro_authorization/src/domain/bot_authorizer.rs
new file mode 100644
index 0000000000..46c2670867
--- /dev/null
+++ b/crates/macro_authorization/src/domain/bot_authorizer.rs
@@ -0,0 +1,160 @@
+//! Bot credential authorization policy.
+
+#[cfg(test)]
+mod test;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::UserContext;
+use rootcause::Report;
+
+use super::{
+ models::{
+ BotActingUserClaims, BotAuthentication, BotAuthorizationOwner, BotTokenAuthorization,
+ MacroAuthorizationError, MacroUserAuthentication, ResolvedBotActingUser,
+ },
+ ports::{BotAuthorizationRepo, BotAuthorizer},
+};
+
+/// Bot authorizer backed by transport-independent authorization facts.
+#[derive(Clone, Debug)]
+pub struct BotAuthorizerService<R> {
+ repo: R,
+}
+
+impl<R> BotAuthorizerService<R> {
+ /// Create a bot authorizer backed by the supplied repository.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+}
+
+impl<R> BotAuthorizerService<R>
+where
+ R: BotAuthorizationRepo,
+{
+ async fn resolve_acting_user(
+ &self,
+ token: &BotTokenAuthorization,
+ claims: &BotActingUserClaims,
+ ) -> Result<ResolvedBotActingUser, Report<MacroAuthorizationError>> {
+ if claims.user_id.is_none() && claims.fusion_user_id.is_none() {
+ return Err(Report::new(
+ MacroAuthorizationError::ActingUserNotAuthorized,
+ ));
+ }
+
+ let claimed_macro_user_id = claims
+ .user_id
+ .as_deref()
+ .map(MacroUserIdStr::parse_from_str)
+ .transpose()
+ .map_err(|_| Report::new(MacroAuthorizationError::ActingUserNotAuthorized))?;
+
+ if token.owner == BotAuthorizationOwner::System {
+ return Err(Report::new(
+ MacroAuthorizationError::ActingUserNotAuthorized,
+ ));
+ }
+
+ let acting_user = self
+ .repo
+ .find_acting_user(claims)
+ .await
+ .map_err(|error| repository_error(error, "find acting user"))?
+ .ok_or_else(|| Report::new(MacroAuthorizationError::ActingUserNotAuthorized))?;
+
+ let macro_user_id_matches = claimed_macro_user_id
+ .as_ref()
+ .is_none_or(|claimed| claimed.as_ref() == acting_user.macro_user_id.as_ref());
+ let fusion_user_id_matches = claims
+ .fusion_user_id
+ .as_deref()
+ .is_none_or(|claimed| claimed == acting_user.fusion_user_id);
+ let organization_id_matches = claims
+ .organization_id
+ .is_none_or(|claimed| Some(claimed) == acting_user.organization_id);
+
+ if !macro_user_id_matches || !fusion_user_id_matches || !organization_id_matches {
+ return Err(Report::new(
+ MacroAuthorizationError::ActingUserNotAuthorized,
+ ));
+ }
+
+ let authorized = match &token.owner {
+ BotAuthorizationOwner::User { user_id } => {
+ user_id == acting_user.macro_user_id.as_ref()
+ }
+ BotAuthorizationOwner::Team { team_id } => self
+ .repo
+ .user_has_team(&acting_user.fusion_user_id, *team_id)
+ .await
+ .map_err(|error| repository_error(error, "check bot owner team membership"))?,
+ BotAuthorizationOwner::System => false,
+ };
+
+ if !authorized {
+ return Err(Report::new(
+ MacroAuthorizationError::ActingUserNotAuthorized,
+ ));
+ }
+
+ Ok(acting_user)
+ }
+}
+
+impl<R> BotAuthorizer for BotAuthorizerService<R>
+where
+ R: BotAuthorizationRepo,
+{
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ acting_user: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ let token = self
+ .repo
+ .find_valid_bot_token(bot_token)
+ .await
+ .map_err(|error| repository_error(error, "find valid bot token"))?
+ .ok_or_else(|| Report::new(MacroAuthorizationError::InvalidCredentials))?;
+
+ self.repo
+ .mark_token_used(token.token_id)
+ .await
+ .map_err(|error| repository_error(error, "mark bot token used"))?;
+
+ let acting_user = match acting_user {
+ Some(claims) => Some(user_authentication(
+ self.resolve_acting_user(&token, &claims).await?,
+ )),
+ None => None,
+ };
+
+ Ok(BotAuthentication {
+ bot_id: token.bot_id,
+ token_id: token.token_id,
+ acting_user,
+ })
+ }
+}
+
+fn user_authentication(acting_user: ResolvedBotActingUser) -> MacroUserAuthentication {
+ let user_id = acting_user.macro_user_id.as_ref().to_owned();
+ MacroUserAuthentication {
+ macro_user_id: acting_user.macro_user_id,
+ user_context: UserContext {
+ user_id,
+ fusion_user_id: acting_user.fusion_user_id,
+ permissions: None,
+ organization_id: acting_user.organization_id,
+ },
+ }
+}
+
+fn repository_error(
+ error: impl std::fmt::Debug,
+ operation: &'static str,
+) -> Report<MacroAuthorizationError> {
+ tracing::error!(error=?error, operation, "bot authorization repository failed");
+ Report::new(MacroAuthorizationError::Unavailable)
+}
diff --git a/crates/macro_authorization/src/domain/bot_authorizer/test.rs b/crates/macro_authorization/src/domain/bot_authorizer/test.rs
new file mode 100644
index 0000000000..d126fbb338
--- /dev/null
+++ b/crates/macro_authorization/src/domain/bot_authorizer/test.rs
@@ -0,0 +1,286 @@
+use std::sync::{Arc, Mutex};
+
+use bot_id::BotId;
+use uuid::Uuid;
+
+use super::*;
+use crate::domain::{
+ models::{BotAuthorizationOwner, BotTokenAuthorization},
+ ports::BotAuthorizationRepo,
+};
+
+const RAW_TOKEN: &str = "mbot_test_secret";
+const OWNER_ID: &str = "macro|[email protected]";
+const FUSION_USER_ID: &str = "fusion-owner";
+const ORGANIZATION_ID: i32 = 42;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum Failure {
+ FindToken,
+ MarkTokenUsed,
+ FindActingUser,
+ UserHasTeam,
+}
+
+#[derive(Debug, Default)]
+struct Calls {
+ tokens: Vec<String>,
+ marked_token_ids: Vec<Uuid>,
+ acting_user_claims: Vec<BotActingUserClaims>,
+ team_lookups: Vec<(String, Uuid)>,
+}
+
+#[derive(Clone)]
+struct FakeRepo {
+ token: Option<BotTokenAuthorization>,
+ acting_user: Option<ResolvedBotActingUser>,
+ user_has_team: bool,
+ failure: Option<Failure>,
+ calls: Arc<Mutex<Calls>>,
+}
+
+impl FakeRepo {
+ fn owned_by_user() -> Self {
+ Self {
+ token: Some(BotTokenAuthorization {
+ bot_id: BotId::new_from_uuid(Uuid::from_u128(1)),
+ token_id: Uuid::from_u128(2),
+ owner: BotAuthorizationOwner::User {
+ user_id: OWNER_ID.to_string(),
+ },
+ }),
+ acting_user: Some(resolved_user()),
+ user_has_team: true,
+ failure: None,
+ calls: Arc::new(Mutex::new(Calls::default())),
+ }
+ }
+
+ fn fail_at(mut self, failure: Failure) -> Self {
+ self.failure = Some(failure);
+ self
+ }
+}
+
+impl BotAuthorizationRepo for FakeRepo {
+ type Err = &'static str;
+
+ async fn find_valid_bot_token(
+ &self,
+ token: &str,
+ ) -> Result<Option<BotTokenAuthorization>, Self::Err> {
+ self.calls.lock().unwrap().tokens.push(token.to_string());
+ if self.failure == Some(Failure::FindToken) {
+ return Err("find token failed");
+ }
+ Ok(self.token.clone())
+ }
+
+ async fn mark_token_used(&self, token_id: Uuid) -> Result<(), Self::Err> {
+ self.calls.lock().unwrap().marked_token_ids.push(token_id);
+ if self.failure == Some(Failure::MarkTokenUsed) {
+ return Err("mark used failed");
+ }
+ Ok(())
+ }
+
+ async fn find_acting_user(
+ &self,
+ claims: &BotActingUserClaims,
+ ) -> Result<Option<ResolvedBotActingUser>, Self::Err> {
+ self.calls
+ .lock()
+ .unwrap()
+ .acting_user_claims
+ .push(claims.clone());
+ if self.failure == Some(Failure::FindActingUser) {
+ return Err("find user failed");
+ }
+ Ok(self.acting_user.clone())
+ }
+
+ async fn user_has_team(&self, fusion_user_id: &str, team_id: Uuid) -> Result<bool, Self::Err> {
+ self.calls
+ .lock()
+ .unwrap()
+ .team_lookups
+ .push((fusion_user_id.to_string(), team_id));
+ if self.failure == Some(Failure::UserHasTeam) {
+ return Err("team lookup failed");
+ }
+ Ok(self.user_has_team)
+ }
+}
+
+fn resolved_user() -> ResolvedBotActingUser {
+ ResolvedBotActingUser {
+ macro_user_id: MacroUserIdStr::try_from(OWNER_ID.to_string()).unwrap(),
+ fusion_user_id: FUSION_USER_ID.to_string(),
+ organization_id: Some(ORGANIZATION_ID),
+ }
+}
+
+fn claims() -> BotActingUserClaims {
+ BotActingUserClaims {
+ user_id: Some(OWNER_ID.to_string()),
+ fusion_user_id: Some(FUSION_USER_ID.to_string()),
+ organization_id: Some(ORGANIZATION_ID),
+ }
+}
+
+fn assert_error(
+ result: Result<BotAuthentication, Report<MacroAuthorizationError>>,
+ expected: MacroAuthorizationError,
+) {
+ assert_eq!(result.unwrap_err().current_context(), &expected);
+}
+
+#[tokio::test]
+async fn authorizes_bare_bot_and_marks_the_valid_token_used() {
+ let repo = FakeRepo::owned_by_user();
+ let authentication = BotAuthorizerService::new(repo.clone())
+ .authorize_bot(RAW_TOKEN, None)
+ .await
+ .unwrap();
+
+ let token = repo.token.as_ref().unwrap();
+ assert_eq!(authentication.bot_id, token.bot_id);
+ assert_eq!(authentication.token_id, token.token_id);
+ assert!(authentication.acting_user.is_none());
+
+ let calls = repo.calls.lock().unwrap();
+ assert_eq!(calls.tokens, [RAW_TOKEN]);
+ assert_eq!(calls.marked_token_ids, [token.token_id]);
+ assert!(calls.acting_user_claims.is_empty());
+}
+
+#[tokio::test]
+async fn authorizes_exact_user_owner_with_consistent_claims() {
+ let repo = FakeRepo::owned_by_user();
+ let authentication = BotAuthorizerService::new(repo.clone())
+ .authorize_bot(RAW_TOKEN, Some(claims()))
+ .await
+ .unwrap();
+
+ let acting_user = authentication.acting_user.unwrap();
+ assert_eq!(acting_user.macro_user_id.as_ref(), OWNER_ID);
+ assert_eq!(acting_user.user_context.user_id, OWNER_ID);
+ assert_eq!(acting_user.user_context.fusion_user_id, FUSION_USER_ID);
+ assert_eq!(
+ acting_user.user_context.organization_id,
+ Some(ORGANIZATION_ID)
+ );
+ assert_eq!(acting_user.user_context.permissions, None);
+ assert_eq!(repo.calls.lock().unwrap().acting_user_claims, [claims()]);
+}
+
+#[tokio::test]
+async fn authorizes_current_team_member_and_rejects_non_member() {
+ let team_id = Uuid::from_u128(3);
+ for (has_team, expected) in [
+ (true, None),
+ (
+ false,
+ Some(MacroAuthorizationError::ActingUserNotAuthorized),
+ ),
+ ] {
+ let mut repo = FakeRepo::owned_by_user();
+ repo.token.as_mut().unwrap().owner = BotAuthorizationOwner::Team { team_id };
+ repo.user_has_team = has_team;
+
+ let result = BotAuthorizerService::new(repo.clone())
+ .authorize_bot(RAW_TOKEN, Some(claims()))
+ .await;
+
+ if let Some(expected) = expected {
+ assert_error(result, expected);
+ } else {
+ result.unwrap();
+ }
+ assert_eq!(
+ repo.calls.lock().unwrap().team_lookups,
+ [(FUSION_USER_ID.to_string(), team_id)]
+ );
+ }
+}
+
+#[tokio::test]
+async fn rejects_system_bot_claims_before_user_lookups() {
+ let mut repo = FakeRepo::owned_by_user();
+ repo.token.as_mut().unwrap().owner = BotAuthorizationOwner::System;
+
+ let result = BotAuthorizerService::new(repo.clone())
+ .authorize_bot(RAW_TOKEN, Some(claims()))
+ .await;
+
+ assert_error(result, MacroAuthorizationError::ActingUserNotAuthorized);
+ assert!(repo.calls.lock().unwrap().acting_user_claims.is_empty());
+}
+
+#[tokio::test]
+async fn rejects_missing_malformed_or_inconsistent_acting_user_claims() {
+ let invalid_claims = [
+ BotActingUserClaims {
+ user_id: None,
+ fusion_user_id: None,
+ organization_id: Some(ORGANIZATION_ID),
+ },
+ BotActingUserClaims {
+ user_id: Some("not-a-macro-user-id".to_string()),
+ fusion_user_id: None,
+ organization_id: None,
+ },
+ BotActingUserClaims {
+ fusion_user_id: Some("different-fusion-user".to_string()),
+ ..claims()
+ },
+ BotActingUserClaims {
+ organization_id: Some(ORGANIZATION_ID + 1),
+ ..claims()
+ },
+ ];
+
+ for claims in invalid_claims {
+ let result = BotAuthorizerService::new(FakeRepo::owned_by_user())
+ .authorize_bot(RAW_TOKEN, Some(claims))
+ .await;
+ assert_error(result, MacroAuthorizationError::ActingUserNotAuthorized);
+ }
+}
+
+#[tokio::test]
+async fn rejects_unknown_token_without_marking_or_policy_lookups() {
+ let mut repo = FakeRepo::owned_by_user();
+ repo.token = None;
+
+ let result = BotAuthorizerService::new(repo.clone())
+ .authorize_bot(RAW_TOKEN, Some(claims()))
+ .await;
+
+ assert_error(result, MacroAuthorizationError::InvalidCredentials);
+ let calls = repo.calls.lock().unwrap();
+ assert!(calls.marked_token_ids.is_empty());
+ assert!(calls.acting_user_claims.is_empty());
+}
+
+#[tokio::test]
+async fn maps_repository_failures_to_unavailable() {
+ for failure in [
+ Failure::FindToken,
+ Failure::MarkTokenUsed,
+ Failure::FindActingUser,
+ ] {
+ let result = BotAuthorizerService::new(FakeRepo::owned_by_user().fail_at(failure))
+ .authorize_bot(RAW_TOKEN, Some(claims()))
+ .await;
+ assert_error(result, MacroAuthorizationError::Unavailable);
+ }
+
+ let team_id = Uuid::from_u128(3);
+ let mut repo = FakeRepo::owned_by_user().fail_at(Failure::UserHasTeam);
+ repo.token.as_mut().unwrap().owner = BotAuthorizationOwner::Team { team_id };
+ let result = BotAuthorizerService::new(repo)
+ .authorize_bot(RAW_TOKEN, Some(claims()))
+ .await;
+ assert_error(result, MacroAuthorizationError::Unavailable);
+}
diff --git a/crates/macro_authorization/src/domain/models.rs b/crates/macro_authorization/src/domain/models.rs
index 09c8247437..0c0353ed70 100644
--- a/crates/macro_authorization/src/domain/models.rs
+++ b/crates/macro_authorization/src/domain/models.rs
@@ -1,6 +1,124 @@
+#[cfg(test)]
+mod test;
+
use std::collections::HashSet;
+use bot_id::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::UserContext;
use thiserror::Error;
+use uuid::Uuid;
+
+/// A user identity that has been authenticated or verified for a bot.
+#[derive(Clone, Debug)]
+pub struct MacroUserAuthentication {
+ /// The user's parsed Macro identifier.
+ pub macro_user_id: MacroUserIdStr<'static>,
+ /// The authenticated user context.
+ pub user_context: UserContext,
+}
+
+/// A bot principal whose token has been validated.
+///
+/// The raw token is deliberately excluded so it cannot flow into handlers,
+/// tracing spans, or logs after authentication.
+#[derive(Clone, Debug)]
+pub struct BotAuthentication {
+ /// The validated bot.
+ pub bot_id: BotId,
+ /// The token row used to authenticate, for audit and telemetry.
+ pub token_id: Uuid,
+ /// The verified acting user, when one was requested and authorized.
+ pub acting_user: Option<MacroUserAuthentication>,
+}
+
+/// How the caller authenticated.
+///
+/// This enum is exhaustive so adding an authentication source requires every
+/// authorization decision to account for it explicitly.
+#[derive(Clone, Debug)]
+pub enum MacroAuthorization {
+ /// A caller authenticated directly with user credentials.
+ User(MacroUserAuthentication),
+ /// A caller authenticated with a bot token.
+ Bot(BotAuthentication),
+ /// An internally authenticated service, optionally acting for a user.
+ Internal(Option<MacroUserAuthentication>),
+}
+
+impl MacroAuthorization {
+ /// Return the authenticated or verified user the caller is acting for.
+ pub fn acting_user(&self) -> Option<&MacroUserAuthentication> {
+ match self {
+ Self::User(user) => Some(user),
+ Self::Bot(bot) => bot.acting_user.as_ref(),
+ Self::Internal(user) => user.as_ref(),
+ }
+ }
+
+ /// Return whether the caller authenticated as an internal service.
+ pub fn is_internal(&self) -> bool {
+ matches!(self, Self::Internal(_))
+ }
+
+ /// Return the authenticated bot principal, when the caller is a bot.
+ pub fn bot(&self) -> Option<&BotAuthentication> {
+ match self {
+ Self::Bot(bot) => Some(bot),
+ Self::User(_) | Self::Internal(_) => None,
+ }
+ }
+}
+
+/// Ownership facts for a bot whose token has been validated.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum BotAuthorizationOwner {
+ /// A bot owned by one Macro user.
+ User {
+ /// The owning Macro user identifier.
+ user_id: String,
+ },
+ /// A bot owned by a team.
+ Team {
+ /// The owning team identifier.
+ team_id: Uuid,
+ },
+ /// A first-party system bot with no user or team owner.
+ System,
+}
+
+/// Valid bot-token facts returned by the authorization repository.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct BotTokenAuthorization {
+ /// The authenticated bot.
+ pub bot_id: BotId,
+ /// The token row used to authenticate.
+ pub token_id: Uuid,
+ /// The bot owner used by acting-user policy.
+ pub owner: BotAuthorizationOwner,
+}
+
+/// Acting-user facts resolved from the user store.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct ResolvedBotActingUser {
+ /// The user's parsed Macro identifier.
+ pub macro_user_id: MacroUserIdStr<'static>,
+ /// The user's FusionAuth identifier.
+ pub fusion_user_id: String,
+ /// The user's organization, when present.
+ pub organization_id: Option<i32>,
+}
+
+/// Unverified acting-user claims presented by a bot.
+#[derive(Clone, Debug, Default, Eq, PartialEq)]
+pub struct BotActingUserClaims {
+ /// The claimed Macro user identifier.
+ pub user_id: Option<String>,
+ /// The claimed FusionAuth user identifier.
+ pub fusion_user_id: Option<String>,
+ /// The claimed organization identifier.
+ pub organization_id: Option<i32>,
+}
/// Identity claims presented by an internally authenticated caller.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
@@ -50,4 +168,10 @@ pub enum MacroAuthorizationError {
/// The supplied credential is otherwise invalid.
#[error("invalid credentials")]
InvalidCredentials,
+ /// The authenticated bot is not authorized to act for the claimed user.
+ #[error("acting user not authorized")]
+ ActingUserNotAuthorized,
+ /// Authorization could not be completed because a required service failed.
+ #[error("authorization unavailable")]
+ Unavailable,
}
diff --git a/crates/macro_authorization/src/domain/models/test.rs b/crates/macro_authorization/src/domain/models/test.rs
new file mode 100644
index 0000000000..574debd156
--- /dev/null
+++ b/crates/macro_authorization/src/domain/models/test.rs
@@ -0,0 +1,154 @@
+use bot_id::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::UserContext;
+use uuid::Uuid;
+
+use super::{
+ BotActingUserClaims, BotAuthentication, MacroAuthorization, MacroAuthorizationError,
+ MacroUserAuthentication,
+};
+
+const BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(1));
+const TOKEN_ID: Uuid = Uuid::from_u128(2);
+
+fn user_authentication() -> MacroUserAuthentication {
+ MacroUserAuthentication {
+ macro_user_id: MacroUserIdStr::try_from("macro|[email protected]".to_string())
+ .expect("valid Macro user id"),
+ user_context: UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "fusion-user-id".to_string(),
+ permissions: None,
+ organization_id: Some(42),
+ },
+ }
+}
+
+fn assert_acting_user(user: &MacroUserAuthentication) {
+ assert_eq!(user.macro_user_id.as_ref(), "macro|[email protected]");
+ assert_eq!(user.user_context.user_id, "macro|[email protected]");
+ assert_eq!(user.user_context.fusion_user_id, "fusion-user-id");
+ assert_eq!(user.user_context.organization_id, Some(42));
+}
+
+#[test]
+fn user_authorization_exposes_its_acting_user() {
+ let authorization = MacroAuthorization::User(user_authentication());
+
+ assert_acting_user(
+ authorization
+ .acting_user()
+ .expect("a user principal is its own acting user"),
+ );
+ assert!(!authorization.is_internal());
+ assert!(authorization.bot().is_none());
+
+ let MacroAuthorization::User(user) = authorization else {
+ panic!("expected user authorization");
+ };
+ assert_acting_user(&user);
+}
+
+#[test]
+fn bot_authorization_exposes_the_bot_and_verified_acting_user() {
+ let authorization = MacroAuthorization::Bot(BotAuthentication {
+ bot_id: BOT_ID,
+ token_id: TOKEN_ID,
+ acting_user: Some(user_authentication()),
+ });
+
+ assert_acting_user(
+ authorization
+ .acting_user()
+ .expect("bot has a verified acting user"),
+ );
+ assert!(!authorization.is_internal());
+
+ let bot = authorization.bot().expect("expected bot authorization");
+ assert_eq!(bot.bot_id, BOT_ID);
+ assert_eq!(bot.token_id, TOKEN_ID);
+ assert_acting_user(
+ bot.acting_user
+ .as_ref()
+ .expect("bot has a verified acting user"),
+ );
+
+ let BotAuthentication {
+ bot_id,
+ token_id,
+ acting_user,
+ } = bot.clone();
+ assert_eq!(bot_id, BOT_ID);
+ assert_eq!(token_id, TOKEN_ID);
+ assert!(acting_user.is_some());
+}
+
+#[test]
+fn bare_bot_authorization_has_no_acting_user() {
+ let authorization = MacroAuthorization::Bot(BotAuthentication {
+ bot_id: BOT_ID,
+ token_id: TOKEN_ID,
+ acting_user: None,
+ });
+
+ assert!(authorization.acting_user().is_none());
+ assert!(!authorization.is_internal());
+ assert!(authorization.bot().is_some());
+}
+
+#[test]
+fn internal_authorization_exposes_its_acting_user() {
+ let authorization = MacroAuthorization::Internal(Some(user_authentication()));
+
+ assert_acting_user(
+ authorization
+ .acting_user()
+ .expect("internal principal has an acting user"),
+ );
+ assert!(authorization.is_internal());
+ assert!(authorization.bot().is_none());
+
+ let MacroAuthorization::Internal(Some(user)) = authorization else {
+ panic!("expected internal authorization with an acting user");
+ };
+ assert_acting_user(&user);
+}
+
+#[test]
+fn internal_authorization_can_have_no_acting_user() {
+ let authorization = MacroAuthorization::Internal(None);
+
+ assert!(authorization.acting_user().is_none());
+ assert!(authorization.is_internal());
+ assert!(authorization.bot().is_none());
+}
+
+#[test]
+fn bot_acting_user_claims_carry_unverified_values() {
+ let claims = BotActingUserClaims {
+ user_id: Some("macro|[email protected]".to_string()),
+ fusion_user_id: Some("claimed-fusion-id".to_string()),
+ organization_id: Some(7),
+ };
+
+ assert_eq!(claims.user_id.as_deref(), Some("macro|[email protected]"));
+ assert_eq!(claims.fusion_user_id.as_deref(), Some("claimed-fusion-id"));
+ assert_eq!(claims.organization_id, Some(7));
+}
+
+#[test]
+fn authorization_errors_remain_clone_and_copy() {
+ fn assert_clone_and_copy<T: Clone + Copy>() {}
+
+ assert_clone_and_copy::<MacroAuthorizationError>();
+
+ let errors = [
+ MacroAuthorizationError::CredentialsExpired,
+ MacroAuthorizationError::InvalidCredentials,
+ MacroAuthorizationError::ActingUserNotAuthorized,
+ MacroAuthorizationError::Unavailable,
+ ];
+ let copied_errors = errors;
+
+ assert_eq!(errors, copied_errors);
+}
diff --git a/crates/macro_authorization/src/domain/ports.rs b/crates/macro_authorization/src/domain/ports.rs
index 21fdc290df..d82857fc9f 100644
--- a/crates/macro_authorization/src/domain/ports.rs
+++ b/crates/macro_authorization/src/domain/ports.rs
@@ -1,9 +1,66 @@
-use std::future::Future;
+use std::{fmt::Debug, future::Future};
use model_user::UserContext;
use rootcause::Report;
-use super::models::{InternalIdentityClaims, MacroAuthorizationError, ValidatedIdentity};
+use super::models::{
+ BotActingUserClaims, BotAuthentication, BotTokenAuthorization, InternalIdentityClaims,
+ MacroAuthorizationError, ResolvedBotActingUser, ValidatedIdentity,
+};
+use uuid::Uuid;
+
+/// Persistence facts required to authorize bot credentials.
+pub trait BotAuthorizationRepo: Clone + Send + Sync + 'static {
+ /// Repository error.
+ type Err: Debug + Send;
+
+ /// Find a currently valid token and its bot ownership facts.
+ fn find_valid_bot_token(
+ &self,
+ token: &str,
+ ) -> impl Future<Output = Result<Option<BotTokenAuthorization>, Self::Err>> + Send;
+
+ /// Mark a validated token as used.
+ fn mark_token_used(&self, token_id: Uuid)
+ -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Resolve acting-user claims to user-store facts.
+ fn find_acting_user(
+ &self,
+ claims: &BotActingUserClaims,
+ ) -> impl Future<Output = Result<Option<ResolvedBotActingUser>, Self::Err>> + Send;
+
+ /// Check whether a user is a current member of a team.
+ fn user_has_team(
+ &self,
+ fusion_user_id: &str,
+ team_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+}
+
+/// Validates bot credentials and resolves verified acting-user identities.
+pub trait BotAuthorizer: Clone + Send + Sync + 'static {
+ /// Authorize a bot token, verifying and resolving any acting-user claims.
+ fn authorize_bot(
+ &self,
+ bot_token: &str,
+ acting_user: Option<BotActingUserClaims>,
+ ) -> impl Future<Output = Result<BotAuthentication, Report<MacroAuthorizationError>>> + Send;
+}
+
+/// Bot authorizer used by services that do not support bot authentication.
+#[derive(Clone)]
+pub struct NoBotAuthorizer;
+
+impl BotAuthorizer for NoBotAuthorizer {
+ async fn authorize_bot(
+ &self,
+ _bot_token: &str,
+ _acting_user: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
/// Cryptographic credential validation used by the authorization domain.
///
@@ -25,6 +82,19 @@ pub trait MacroAuthorizationService: Clone + Send + Sync + 'static {
jwt: &str,
) -> impl Future<Output = Result<UserContext, Report<MacroAuthorizationError>>> + Send;
+ /// Authorize a bot token, verifying any acting-user claims.
+ ///
+ /// Services reject bot credentials unless they explicitly provide a bot
+ /// authorizer.
+ fn authorize_bot(
+ &self,
+ _bot_token: &str,
+ _acting_user: Option<BotActingUserClaims>,
+ ) -> impl Future<Output = Result<BotAuthentication, Report<MacroAuthorizationError>>> + Send
+ {
+ async { Err(Report::new(MacroAuthorizationError::InvalidCredentials)) }
+ }
+
/// Authorize an internal service-to-service caller.
///
/// Returns `Ok(None)` when the key is valid but no identity is established
diff --git a/crates/macro_authorization/src/domain/service.rs b/crates/macro_authorization/src/domain/service.rs
index 3c99f3efc8..9bc166d991 100644
--- a/crates/macro_authorization/src/domain/service.rs
+++ b/crates/macro_authorization/src/domain/service.rs
@@ -1,28 +1,66 @@
#[cfg(test)]
mod test;
+use std::{future::Future, pin::Pin, sync::Arc};
+
use constant_time_eq::constant_time_eq;
use model_user::UserContext;
use rootcause::Report;
use super::{
- models::{InternalAuthConfig, InternalIdentityClaims, MacroAuthorizationError},
- ports::{JwtValidator, MacroAuthorizationService},
+ models::{
+ BotActingUserClaims, BotAuthentication, InternalAuthConfig, InternalIdentityClaims,
+ MacroAuthorizationError,
+ },
+ ports::{BotAuthorizer, JwtValidator, MacroAuthorizationService},
};
+type BotAuthorizationFuture<'a> = Pin<
+ Box<
+ dyn Future<Output = Result<BotAuthentication, Report<MacroAuthorizationError>>> + Send + 'a,
+ >,
+>;
+
+trait DynBotAuthorizer: Send + Sync {
+ fn authorize_bot<'a>(
+ &'a self,
+ bot_token: &'a str,
+ acting_user: Option<BotActingUserClaims>,
+ ) -> BotAuthorizationFuture<'a>;
+}
+
+impl<B> DynBotAuthorizer for B
+where
+ B: BotAuthorizer,
+{
+ fn authorize_bot<'a>(
+ &'a self,
+ bot_token: &'a str,
+ acting_user: Option<BotActingUserClaims>,
+ ) -> BotAuthorizationFuture<'a> {
+ Box::pin(BotAuthorizer::authorize_bot(self, bot_token, acting_user))
+ }
+}
+
/// Default authorization service backed by a credential validator.
#[derive(Clone)]
pub struct MacroAuthorizationServiceImpl<V> {
validator: V,
internal_auth: InternalAuthConfig,
+ bot_authorizer: Arc<dyn DynBotAuthorizer>,
}
impl<V> MacroAuthorizationServiceImpl<V> {
- /// Create an authorization service using the supplied validator and required internal authorization configuration.
- pub fn new(validator: V, internal_auth: InternalAuthConfig) -> Self {
+ /// Create an authorization service with required user, internal, and bot authorization dependencies.
+ pub fn new(
+ validator: V,
+ internal_auth: InternalAuthConfig,
+ bot_authorizer: impl BotAuthorizer,
+ ) -> Self {
Self {
validator,
internal_auth,
+ bot_authorizer: Arc::new(bot_authorizer),
}
}
}
@@ -42,6 +80,38 @@ where
})
}
+ #[tracing::instrument(
+ err,
+ skip_all,
+ fields(
+ bot_id = tracing::field::Empty,
+ token_id = tracing::field::Empty,
+ acting_user_id = tracing::field::Empty,
+ )
+ )]
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ acting_user: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ let bot = self
+ .bot_authorizer
+ .authorize_bot(bot_token, acting_user)
+ .await?;
+
+ let span = tracing::Span::current();
+ span.record("bot_id", tracing::field::display(bot.bot_id));
+ span.record("token_id", tracing::field::display(bot.token_id));
+ if let Some(acting_user) = &bot.acting_user {
+ span.record(
+ "acting_user_id",
+ tracing::field::display(&acting_user.macro_user_id),
+ );
+ }
+
+ Ok(bot)
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
diff --git a/crates/macro_authorization/src/domain/service/test.rs b/crates/macro_authorization/src/domain/service/test.rs
index 5b043c1d8e..59b2c2923e 100644
--- a/crates/macro_authorization/src/domain/service/test.rs
+++ b/crates/macro_authorization/src/domain/service/test.rs
@@ -1,13 +1,21 @@
-use std::collections::HashSet;
+use std::{
+ collections::HashSet,
+ sync::{Arc, Mutex},
+};
+use bot_id::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::UserContext;
use rootcause::Report;
+use uuid::Uuid;
-use super::*;
+use super::MacroAuthorizationServiceImpl;
use crate::domain::{
models::{
- InternalAuthConfig, InternalIdentityClaims, MacroAuthorizationError, ValidatedIdentity,
+ BotActingUserClaims, BotAuthentication, InternalAuthConfig, InternalIdentityClaims,
+ MacroAuthorizationError, MacroUserAuthentication, ValidatedIdentity,
},
- ports::JwtValidator,
+ ports::{BotAuthorizer, JwtValidator, MacroAuthorizationService, NoBotAuthorizer},
};
#[derive(Clone)]
@@ -21,7 +29,69 @@ impl JwtValidator for FakeJwtValidator {
}
}
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct BotAuthorizationCall {
+ bot_token: String,
+ acting_user: Option<BotActingUserClaims>,
+}
+
+#[derive(Clone)]
+struct FakeBotAuthorizer {
+ calls: Arc<Mutex<Vec<BotAuthorizationCall>>>,
+ result: Result<BotAuthentication, MacroAuthorizationError>,
+}
+
+impl FakeBotAuthorizer {
+ fn new(result: Result<BotAuthentication, MacroAuthorizationError>) -> Self {
+ Self {
+ calls: Arc::new(Mutex::new(Vec::new())),
+ result,
+ }
+ }
+
+ fn calls(&self) -> Vec<BotAuthorizationCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+}
+
+impl BotAuthorizer for FakeBotAuthorizer {
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ acting_user: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(BotAuthorizationCall {
+ bot_token: bot_token.to_string(),
+ acting_user,
+ });
+
+ self.result.clone().map_err(Report::new)
+ }
+}
+
+#[derive(Clone)]
+struct DefaultRejectingAuthorizationService;
+
+impl MacroAuthorizationService for DefaultRejectingAuthorizationService {
+ async fn authorize(&self, _jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+
+ async fn authorize_internal(
+ &self,
+ _provided_key: &str,
+ _claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+
const INTERNAL_API_KEY: &str = "secret-key";
+const BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(1));
+const TOKEN_ID: Uuid = Uuid::from_u128(2);
fn internal_auth_config(default_user_id: Option<&str>) -> InternalAuthConfig {
InternalAuthConfig {
@@ -38,9 +108,146 @@ fn service_with_internal_auth(
result: Err(MacroAuthorizationError::InvalidCredentials),
},
internal_auth_config(default_user_id),
+ NoBotAuthorizer,
)
}
+fn bot_authentication() -> BotAuthentication {
+ BotAuthentication {
+ bot_id: BOT_ID,
+ token_id: TOKEN_ID,
+ acting_user: Some(MacroUserAuthentication {
+ macro_user_id: MacroUserIdStr::try_from("macro|[email protected]".to_string())
+ .expect("valid Macro user id"),
+ user_context: UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "fusion-acting-user".to_string(),
+ permissions: None,
+ organization_id: Some(42),
+ },
+ }),
+ }
+}
+
+fn assert_bot_authentication(bot: &BotAuthentication) {
+ assert_eq!(bot.bot_id, BOT_ID);
+ assert_eq!(bot.token_id, TOKEN_ID);
+
+ let acting_user = bot
+ .acting_user
+ .as_ref()
+ .expect("expected a verified acting user");
+ assert_eq!(
+ acting_user.macro_user_id.as_ref(),
+ );
+ assert_eq!(acting_user.user_context.user_id, "macro|[email protected]");
+ assert_eq!(
+ acting_user.user_context.fusion_user_id,
+ "fusion-acting-user"
+ );
+ assert_eq!(acting_user.user_context.organization_id, Some(42));
+ assert_eq!(acting_user.user_context.permissions, None);
+}
+
+#[tokio::test]
+async fn no_bot_authorizer_rejects_bot_credentials() {
+ let error = NoBotAuthorizer
+ .authorize_bot(
+ "bot-token",
+ Some(BotActingUserClaims {
+ user_id: Some("macro|[email protected]".to_string()),
+ fusion_user_id: None,
+ organization_id: None,
+ }),
+ )
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.current_context(),
+ &MacroAuthorizationError::InvalidCredentials
+ );
+}
+
+#[tokio::test]
+async fn authorization_service_trait_rejects_bots_by_default() {
+ let error = DefaultRejectingAuthorizationService
+ .authorize_bot("bot-token", None)
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.current_context(),
+ &MacroAuthorizationError::InvalidCredentials
+ );
+}
+
+#[tokio::test]
+async fn authorization_service_impl_rejects_bots_with_explicit_no_bot_authorizer() {
+ let error = service_with_internal_auth(None)
+ .authorize_bot("bot-token", None)
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.current_context(),
+ &MacroAuthorizationError::InvalidCredentials
+ );
+}
+
+#[tokio::test]
+async fn authorize_bot_delegates_token_and_exact_acting_user_claims() {
+ let claims = BotActingUserClaims {
+ user_id: Some("macro|[email protected]".to_string()),
+ fusion_user_id: Some("fusion-acting-user".to_string()),
+ organization_id: Some(42),
+ };
+ let authorizer = FakeBotAuthorizer::new(Ok(bot_authentication()));
+ let service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator {
+ result: Err(MacroAuthorizationError::InvalidCredentials),
+ },
+ internal_auth_config(None),
+ authorizer.clone(),
+ );
+
+ let bot = service
+ .authorize_bot("bot-token", Some(claims.clone()))
+ .await
+ .unwrap();
+
+ assert_bot_authentication(&bot);
+ assert_eq!(
+ authorizer.calls(),
+ vec![BotAuthorizationCall {
+ bot_token: "bot-token".to_string(),
+ acting_user: Some(claims),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn authorize_bot_passes_through_authorizer_errors() {
+ for expected in [
+ MacroAuthorizationError::InvalidCredentials,
+ MacroAuthorizationError::ActingUserNotAuthorized,
+ MacroAuthorizationError::Unavailable,
+ ] {
+ let service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator {
+ result: Err(MacroAuthorizationError::InvalidCredentials),
+ },
+ internal_auth_config(None),
+ FakeBotAuthorizer::new(Err(expected)),
+ );
+
+ let error = service.authorize_bot("bot-token", None).await.unwrap_err();
+
+ assert_eq!(error.current_context(), &expected);
+ }
+}
+
#[tokio::test]
async fn authorize_constructs_user_context_from_validated_identity() {
let permissions = HashSet::from(["documents:read".to_string(), "documents:write".to_string()]);
@@ -54,6 +261,7 @@ async fn authorize_constructs_user_context_from_validated_identity() {
}),
},
internal_auth_config(None),
+ NoBotAuthorizer,
);
let context = service.authorize("valid-jwt").await.unwrap();
@@ -137,6 +345,7 @@ async fn authorize_propagates_expired_credentials() {
result: Err(MacroAuthorizationError::CredentialsExpired),
},
internal_auth_config(None),
+ NoBotAuthorizer,
);
let error = service.authorize("expired-jwt").await.unwrap_err();
@@ -154,6 +363,7 @@ async fn authorize_propagates_invalid_credentials() {
result: Err(MacroAuthorizationError::InvalidCredentials),
},
internal_auth_config(None),
+ NoBotAuthorizer,
);
let error = service.authorize("invalid-jwt").await.unwrap_err();
diff --git a/crates/macro_authorization/src/inbound.rs b/crates/macro_authorization/src/inbound.rs
index 1d4637fcd7..a42c0c01a7 100644
--- a/crates/macro_authorization/src/inbound.rs
+++ b/crates/macro_authorization/src/inbound.rs
@@ -5,9 +5,14 @@ pub mod axum;
#[allow(deprecated)]
pub use axum::{
- INTERNAL_API_KEY_HEADER, INTERNAL_FUSIONAUTH_USER_ID_HEADER,
- INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
- InternalMacroAuthorizationExtractor, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
- LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationExtractor,
- MacroAuthorizationRejection, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ ActingEntity, ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy,
+ BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,
+ BOT_FOR_ORGANIZATION_ID_HEADER, BOT_TOKEN_HEADER, BotOnly, INTERNAL_API_KEY_HEADER,
+ INTERNAL_FUSIONAUTH_USER_ID_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization, InternalEntity, InternalOnly,
+ LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
+ MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor, UserOnly, UserOrInternal, UserOrInternalAuthorization,
+ UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,
+ UserOrInternalServiceAuthorization,
};
diff --git a/crates/macro_authorization/src/inbound/axum.rs b/crates/macro_authorization/src/inbound/axum.rs
index 855d9cffec..2476c75c6a 100644
--- a/crates/macro_authorization/src/inbound/axum.rs
+++ b/crates/macro_authorization/src/inbound/axum.rs
@@ -1,40 +1,80 @@
#[cfg(test)]
mod test;
-use std::{borrow::Cow, fmt, marker::PhantomData, sync::Arc};
+mod bot;
+mod internal;
+mod macro_authorization;
+mod optional;
+mod policy;
+mod user;
+
+use std::{borrow::Cow, fmt, sync::Arc};
use ::axum::{
Json,
- extract::{FromRef, FromRequestParts, Query},
- http::{HeaderMap, StatusCode, header, request::Parts},
+ http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_auth::headers::AccessTokenExtractor;
-#[cfg(feature = "local_auth")]
-use macro_env_var::maybe_env_vars;
+use bot_id::BotId;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model_error_response::ErrorResponse;
use model_user::UserContext;
-use rootcause::Report;
-use serde::Deserialize;
-use crate::{InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService};
+use crate::{MacroAuthorization, MacroUserAuthentication};
-/// Header carrying the shared key for standard internal service authorization.
-pub const INTERNAL_API_KEY_HEADER: &str = "x-internal-auth-key";
-/// Header carrying the acting Macro user ID for standard internal authorization.
-pub const INTERNAL_MACRO_USER_ID_HEADER: &str = "x-internal-macro-user-id";
-/// Header carrying the acting organization ID for standard internal authorization.
-pub const INTERNAL_MACRO_ORGANIZATION_ID_HEADER: &str = "x-internal-macro-organization-id";
-/// Header carrying the acting FusionAuth user ID for standard internal authorization.
-pub const INTERNAL_FUSIONAUTH_USER_ID_HEADER: &str = "x-internal-fusionauth-user-id";
+pub use bot::{
+ BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,
+ BOT_FOR_ORGANIZATION_ID_HEADER, BOT_TOKEN_HEADER,
+};
+#[allow(deprecated)]
+pub use internal::{
+ INTERNAL_API_KEY_HEADER, INTERNAL_FUSIONAUTH_USER_ID_HEADER,
+ INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
+};
+pub use macro_authorization::MacroAuthorizationExtractor;
+pub use optional::OptionalMacroAuthorizationExtractor;
+pub use policy::{
+ ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy, BotOnly,
+ InternalAuthorization, InternalEntity, InternalOnly, UserOnly, UserOrInternal,
+ UserOrInternalAuthorization, UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,
+ UserOrInternalServiceAuthorization,
+};
+
+/// The authenticated entity responsible for a request.
+///
+/// This intentionally identifies the authenticating principal rather than an
+/// acting user. A bot acting for a user is attributed to the bot, and an
+/// internal service acting for a user is attributed to the internal service.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ActingEntity<'a> {
+ /// A directly authenticated bot.
+ Bot(BotId),
+ /// A directly authenticated Macro user.
+ User(&'a str),
+ /// An authenticated internal service.
+ Internal,
+}
+
+impl<'a> From<&'a MacroAuthorization> for ActingEntity<'a> {
+ fn from(authorization: &'a MacroAuthorization) -> Self {
+ match authorization {
+ MacroAuthorization::User(user) => Self::User(user.macro_user_id.as_ref()),
+ MacroAuthorization::Bot(bot) => Self::Bot(bot.bot_id),
+ MacroAuthorization::Internal(_) => Self::Internal,
+ }
+ }
+}
-/// Legacy DSS header carrying the internal service authorization key.
-#[deprecated(note = "migrate callers to INTERNAL_API_KEY_HEADER")]
-pub const LEGACY_DSS_INTERNAL_API_KEY_HEADER: &str = "x-document-storage-service-auth-key";
-/// Legacy DSS header carrying the acting Macro user ID.
-#[deprecated(note = "migrate callers to INTERNAL_MACRO_USER_ID_HEADER")]
-pub const LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER: &str = "x-document-storage-service-user-id";
+impl fmt::Display for ActingEntity<'_> {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Bot(bot_id) => bot_id.fmt(formatter),
+ Self::User(user_id) => formatter.write_str(user_id.as_ref()),
+ Self::Internal => formatter.write_str("internal"),
+ }
+ }
+}
/// Rejection returned when request credentials cannot authorize a user.
#[derive(Clone, Debug)]
@@ -62,7 +102,7 @@ impl IntoResponse for MacroAuthorizationRejection {
/// Axum state containing the service used by authorization extractors.
pub struct MacroAuthorizationState<Svc> {
- service: Arc<Svc>,
+ pub(super) service: Arc<Svc>,
}
impl<Svc> MacroAuthorizationState<Svc> {
@@ -80,288 +120,9 @@ impl<Svc> Clone for MacroAuthorizationState<Svc> {
}
}
-#[cfg(feature = "local_auth")]
-maybe_env_vars! {
- struct LocalUserId;
- struct LocalFusionUserId;
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "kebab-case")]
-struct AuthorizationQuery {
- macro_api_token: Option<String>,
-}
-
-struct AuthorizedUser {
- macro_user_id: MacroUserIdStr<'static>,
+pub(super) fn authenticated_user(
user_context: UserContext,
-}
-
-struct AuthorizationOutcome {
- identity: Option<AuthorizedUser>,
- is_internal_access: bool,
-}
-
-struct InternalHeaderConvention {
- key_header: &'static str,
- user_id_header: &'static str,
- organization_id_header: Option<&'static str>,
- fusion_user_id_header: Option<&'static str>,
-}
-
-#[allow(deprecated)]
-static INTERNAL_HEADER_CONVENTIONS: [InternalHeaderConvention; 2] = [
- InternalHeaderConvention {
- key_header: INTERNAL_API_KEY_HEADER,
- user_id_header: INTERNAL_MACRO_USER_ID_HEADER,
- organization_id_header: Some(INTERNAL_MACRO_ORGANIZATION_ID_HEADER),
- fusion_user_id_header: Some(INTERNAL_FUSIONAUTH_USER_ID_HEADER),
- },
- InternalHeaderConvention {
- key_header: LEGACY_DSS_INTERNAL_API_KEY_HEADER,
- user_id_header: LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
- organization_id_header: None,
- fusion_user_id_header: None,
- },
-];
-
-/// Extracts and authorizes a required acting user.
-///
-/// This extractor automatically supports both direct user access and internal
-/// service access. Internal credentials are checked first and must resolve to
-/// an acting user through an identity header or the configured default user.
-/// User credentials are read from the `macro-api-token` query parameter,
-/// followed by a bearer header or access-token cookie. Use
-/// [`InternalMacroAuthorizationExtractor`] instead only when the endpoint must
-/// be exclusively internal and does not require an acting user. The
-/// authorization service is resolved from Axum state.
-#[non_exhaustive]
-pub struct MacroAuthorizationExtractor<Svc> {
- /// The validated Macro user identifier.
- pub macro_user_id: MacroUserIdStr<'static>,
- /// The complete context returned by the authorization service.
- pub user_context: UserContext,
- /// True when the request authenticated with an internal service key rather than user credentials.
- pub is_internal_access: bool,
- _service: PhantomData<fn() -> Svc>,
-}
-
-impl<Svc> Clone for MacroAuthorizationExtractor<Svc> {
- fn clone(&self) -> Self {
- Self {
- macro_user_id: self.macro_user_id.clone(),
- user_context: self.user_context.clone(),
- is_internal_access: self.is_internal_access,
- _service: PhantomData,
- }
- }
-}
-
-impl<S, Svc> FromRequestParts<S> for MacroAuthorizationExtractor<Svc>
-where
- MacroAuthorizationState<Svc>: FromRef<S>,
- Svc: MacroAuthorizationService,
- S: Send + Sync + 'static,
-{
- type Rejection = MacroAuthorizationRejection;
-
- async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
- let outcome = authorize_request::<S, Svc>(parts, state).await?;
- let Some(authorized_user) = outcome.identity else {
- return Err(rejection("unauthorized"));
- };
-
- Ok(Self {
- macro_user_id: authorized_user.macro_user_id,
- user_context: authorized_user.user_context,
- is_internal_access: outcome.is_internal_access,
- _service: PhantomData,
- })
- }
-}
-
-/// Authorizes an exclusively internal service endpoint using an internal API key.
-///
-/// Use this extractor only for endpoints that will never accept direct user
-/// access. Do not use it merely to support internal callers:
-/// [`MacroAuthorizationExtractor`] and [`OptionalMacroAuthorizationExtractor`]
-/// already accept internal credentials automatically. This extractor does not
-/// accept user credentials as a substitute and intentionally exposes no user
-/// identity.
-///
-/// Both the standard and legacy DSS internal API key headers are accepted.
-/// Acting-user identity headers are forwarded to the authorization service so
-/// it can validate any supplied identity, but only the internal API key is
-/// required.
-#[non_exhaustive]
-pub struct InternalMacroAuthorizationExtractor<Svc> {
- _service: PhantomData<fn() -> Svc>,
-}
-
-impl<Svc> Clone for InternalMacroAuthorizationExtractor<Svc> {
- fn clone(&self) -> Self {
- Self {
- _service: PhantomData,
- }
- }
-}
-
-impl<S, Svc> FromRequestParts<S> for InternalMacroAuthorizationExtractor<Svc>
-where
- MacroAuthorizationState<Svc>: FromRef<S>,
- Svc: MacroAuthorizationService,
- S: Send + Sync + 'static,
-{
- type Rejection = MacroAuthorizationRejection;
-
- async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
- let convention =
- internal_header_convention(&parts.headers).ok_or_else(|| rejection("unauthorized"))?;
-
- authorize_internal_request::<S, Svc>(parts, state, convention).await?;
-
- Ok(Self {
- _service: PhantomData,
- })
- }
-}
-
-/// Extracts and authorizes an optional acting user.
-///
-/// This extractor automatically supports anonymous callers, direct user
-/// credentials, and internal service credentials. Internal credentials are
-/// checked first and set `is_internal_access` even when they establish no user
-/// identity. Requests without credentials succeed with an empty
-/// [`UserContext`]. Any supplied credential must still pass authorization; an
-/// invalid credential is never treated as anonymous. Use
-/// [`InternalMacroAuthorizationExtractor`] instead only when the endpoint must
-/// be exclusively internal.
-#[non_exhaustive]
-pub struct OptionalMacroAuthorizationExtractor<Svc> {
- /// The validated Macro user identifier, or `None` for an anonymous request.
- pub macro_user_id: Option<MacroUserIdStr<'static>>,
- /// The authorized context, or the default context for an anonymous request.
- pub user_context: UserContext,
- /// True when the request authenticated with an internal service key rather than user credentials.
- pub is_internal_access: bool,
- _service: PhantomData<fn() -> Svc>,
-}
-
-impl<Svc> Clone for OptionalMacroAuthorizationExtractor<Svc> {
- fn clone(&self) -> Self {
- Self {
- macro_user_id: self.macro_user_id.clone(),
- user_context: self.user_context.clone(),
- is_internal_access: self.is_internal_access,
- _service: PhantomData,
- }
- }
-}
-
-impl<S, Svc> FromRequestParts<S> for OptionalMacroAuthorizationExtractor<Svc>
-where
- MacroAuthorizationState<Svc>: FromRef<S>,
- Svc: MacroAuthorizationService,
- S: Send + Sync + 'static,
-{
- type Rejection = MacroAuthorizationRejection;
-
- async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
- let outcome = authorize_request::<S, Svc>(parts, state).await?;
- let Some(authorized_user) = outcome.identity else {
- return Ok(Self {
- macro_user_id: None,
- user_context: UserContext::default(),
- is_internal_access: outcome.is_internal_access,
- _service: PhantomData,
- });
- };
-
- Ok(Self {
- macro_user_id: Some(authorized_user.macro_user_id),
- user_context: authorized_user.user_context,
- is_internal_access: outcome.is_internal_access,
- _service: PhantomData,
- })
- }
-}
-
-async fn authorize_request<S, Svc>(
- parts: &mut Parts,
- state: &S,
-) -> Result<AuthorizationOutcome, MacroAuthorizationRejection>
-where
- MacroAuthorizationState<Svc>: FromRef<S>,
- Svc: MacroAuthorizationService,
- S: Send + Sync + 'static,
-{
- if let Some(convention) = internal_header_convention(&parts.headers) {
- return authorize_internal_request::<S, Svc>(parts, state, convention).await;
- }
-
- #[cfg(feature = "local_auth")]
- if let Some(user_context) = local_user_context() {
- return authorization_outcome(Some(user_context), false);
- }
-
- let Some(token) = extract_token(parts, state).await? else {
- return Ok(AuthorizationOutcome {
- identity: None,
- is_internal_access: false,
- });
- };
-
- let authorization = MacroAuthorizationState::<Svc>::from_ref(state);
- let user_context = authorization
- .service
- .authorize(&token)
- .await
- .map_err(authorization_rejection)?;
-
- authorization_outcome(Some(user_context), false)
-}
-
-async fn authorize_internal_request<S, Svc>(
- parts: &Parts,
- state: &S,
- convention: &InternalHeaderConvention,
-) -> Result<AuthorizationOutcome, MacroAuthorizationRejection>
-where
- MacroAuthorizationState<Svc>: FromRef<S>,
- Svc: MacroAuthorizationService,
- S: Send + Sync + 'static,
-{
- let provided_key = parts
- .headers
- .get(convention.key_header)
- .and_then(|header| header.to_str().ok())
- .ok_or_else(|| rejection("unauthorized"))?;
- let claims = internal_identity_claims(&parts.headers, convention);
- let authorization = MacroAuthorizationState::<Svc>::from_ref(state);
- let user_context = authorization
- .service
- .authorize_internal(provided_key, claims)
- .await
- .map_err(internal_authorization_rejection)?;
-
- authorization_outcome(user_context, true)
-}
-
-fn authorization_outcome(
- user_context: Option<UserContext>,
- is_internal_access: bool,
-) -> Result<AuthorizationOutcome, MacroAuthorizationRejection> {
- let identity = user_context.map(authorized_user).transpose()?;
-
- Ok(AuthorizationOutcome {
- identity,
- is_internal_access,
- })
-}
-
-fn authorized_user(
- user_context: UserContext,
-) -> Result<AuthorizedUser, MacroAuthorizationRejection> {
+) -> Result<MacroUserAuthentication, MacroAuthorizationRejection> {
let macro_user_id = MacroUserIdStr::parse_from_str(&user_context.user_id)
.map(CowLike::into_owned)
.map_err(|error| {
@@ -369,92 +130,22 @@ fn authorized_user(
rejection("invalid user id")
})?;
- Ok(AuthorizedUser {
+ Ok(MacroUserAuthentication {
macro_user_id,
user_context,
})
}
-fn internal_header_convention(headers: &HeaderMap) -> Option<&InternalHeaderConvention> {
- INTERNAL_HEADER_CONVENTIONS
- .iter()
- .find(|convention| headers.contains_key(convention.key_header))
-}
-
-fn internal_identity_claims(
- headers: &HeaderMap,
- convention: &InternalHeaderConvention,
-) -> InternalIdentityClaims {
- InternalIdentityClaims {
- user_id: header_string(headers, Some(convention.user_id_header)),
- fusion_user_id: header_string(headers, convention.fusion_user_id_header),
- organization_id: header_string(headers, convention.organization_id_header)
- .and_then(|organization_id| organization_id.parse().ok()),
- }
-}
-
-fn header_string(headers: &HeaderMap, name: Option<&str>) -> Option<String> {
- name.and_then(|name| headers.get(name))
- .and_then(|header| header.to_str().ok())
- .map(str::to_owned)
-}
-
-#[cfg(feature = "local_auth")]
-fn local_user_context() -> Option<UserContext> {
- Some(UserContext {
- user_id: LocalUserId::new()?.to_string(),
- fusion_user_id: LocalFusionUserId::new()
- .map(|fusion_user_id| fusion_user_id.to_string())
- .unwrap_or_else(|| "set me!".to_string()),
- organization_id: Some(1),
- permissions: None,
- })
-}
-
-async fn extract_token<S>(
- parts: &mut Parts,
- state: &S,
-) -> Result<Option<String>, MacroAuthorizationRejection>
-where
- S: Send + Sync,
-{
- let query_token = Query::<AuthorizationQuery>::from_request_parts(parts, state)
- .await
- .ok()
- .and_then(|Query(query)| query.macro_api_token);
-
- if let Some(token) = query_token {
- return Ok(Some(token));
- }
-
- match AccessTokenExtractor::from_request_parts(parts, state).await {
- Ok(token) => Ok(Some(token.as_ref().to_owned())),
- Err(_) if parts.headers.contains_key(header::AUTHORIZATION) => {
- Err(rejection("unauthorized"))
- }
- Err(_) => Ok(None),
- }
-}
-
-fn authorization_rejection(error: Report<MacroAuthorizationError>) -> MacroAuthorizationRejection {
- let message = match error.current_context() {
- MacroAuthorizationError::CredentialsExpired => "jwt expired",
- MacroAuthorizationError::InvalidCredentials => "unauthorized",
- };
- tracing::error!(error=?error, "credential authorization failed");
- rejection(message)
+pub(super) fn rejection(message: &'static str) -> MacroAuthorizationRejection {
+ status_rejection(StatusCode::UNAUTHORIZED, message)
}
-fn internal_authorization_rejection(
- error: Report<MacroAuthorizationError>,
+pub(super) fn status_rejection(
+ status: StatusCode,
+ message: &'static str,
) -> MacroAuthorizationRejection {
- tracing::error!(error=?error.current_context(), "internal authorization failed");
- rejection("unauthorized")
-}
-
-fn rejection(message: &'static str) -> MacroAuthorizationRejection {
MacroAuthorizationRejection {
- status: StatusCode::UNAUTHORIZED,
+ status,
message: message.into(),
}
}
diff --git a/crates/macro_authorization/src/inbound/axum/bot.rs b/crates/macro_authorization/src/inbound/axum/bot.rs
new file mode 100644
index 0000000000..5b4d133588
--- /dev/null
+++ b/crates/macro_authorization/src/inbound/axum/bot.rs
@@ -0,0 +1,111 @@
+use ::axum::{
+ extract::FromRef,
+ http::{HeaderMap, StatusCode, request::Parts},
+};
+use rootcause::Report;
+
+use crate::{
+ BotActingUserClaims, BotAuthentication, MacroAuthorizationError, MacroAuthorizationService,
+};
+
+use super::{MacroAuthorizationRejection, MacroAuthorizationState, rejection, status_rejection};
+
+/// Header carrying a bot authentication token.
+pub const BOT_TOKEN_HEADER: &str = "x-macro-bot-token";
+/// Header carrying the Macro user ID a bot claims to act for.
+pub const BOT_FOR_MACRO_USER_ID_HEADER: &str = "x-macro-bot-for-macro-user-id";
+/// Header carrying the FusionAuth user ID a bot claims to act for.
+pub const BOT_FOR_FUSIONAUTH_USER_ID_HEADER: &str = "x-macro-bot-for-fusionauth-user-id";
+/// Header carrying the organization ID a bot claims to act for.
+pub const BOT_FOR_ORGANIZATION_ID_HEADER: &str = "x-macro-bot-for-organization-id";
+
+pub(super) async fn authorize_optional_bot_request<S, Svc>(
+ parts: &Parts,
+ state: &S,
+) -> Result<Option<BotAuthentication>, MacroAuthorizationRejection>
+where
+ MacroAuthorizationState<Svc>: FromRef<S>,
+ Svc: MacroAuthorizationService,
+{
+ let Some(token) = bot_token(&parts.headers)? else {
+ return Ok(None);
+ };
+ let claims = bot_acting_user_claims(&parts.headers)?;
+ let authorization = MacroAuthorizationState::<Svc>::from_ref(state);
+ let bot = authorization
+ .service
+ .authorize_bot(&token, claims)
+ .await
+ .map_err(bot_authorization_rejection)?;
+
+ Ok(Some(bot))
+}
+
+fn bot_token(headers: &HeaderMap) -> Result<Option<String>, MacroAuthorizationRejection> {
+ let Some(header) = headers.get(BOT_TOKEN_HEADER) else {
+ return Ok(None);
+ };
+ let token = header.to_str().map_err(|_| rejection("unauthorized"))?;
+ if token.trim().is_empty() {
+ return Err(rejection("unauthorized"));
+ }
+
+ Ok(Some(token.to_owned()))
+}
+
+fn bot_acting_user_claims(
+ headers: &HeaderMap,
+) -> Result<Option<BotActingUserClaims>, MacroAuthorizationRejection> {
+ let user_id = bot_claim_header(headers, BOT_FOR_MACRO_USER_ID_HEADER)?;
+ let fusion_user_id = bot_claim_header(headers, BOT_FOR_FUSIONAUTH_USER_ID_HEADER)?;
+ let organization_id = bot_claim_header(headers, BOT_FOR_ORGANIZATION_ID_HEADER)?
+ .map(|organization_id| organization_id.parse::<i32>())
+ .transpose()
+ .map_err(|_| invalid_bot_claims_rejection())?;
+
+ if user_id.is_none() && fusion_user_id.is_none() && organization_id.is_none() {
+ return Ok(None);
+ }
+
+ Ok(Some(BotActingUserClaims {
+ user_id,
+ fusion_user_id,
+ organization_id,
+ }))
+}
+
+fn bot_claim_header(
+ headers: &HeaderMap,
+ name: &'static str,
+) -> Result<Option<String>, MacroAuthorizationRejection> {
+ headers
+ .get(name)
+ .map(|header| {
+ header
+ .to_str()
+ .map(str::to_owned)
+ .map_err(|_| invalid_bot_claims_rejection())
+ })
+ .transpose()
+}
+
+fn invalid_bot_claims_rejection() -> MacroAuthorizationRejection {
+ status_rejection(StatusCode::BAD_REQUEST, "invalid bot claims")
+}
+
+fn bot_authorization_rejection(
+ error: Report<MacroAuthorizationError>,
+) -> MacroAuthorizationRejection {
+ let rejection = match error.current_context() {
+ MacroAuthorizationError::CredentialsExpired
+ | MacroAuthorizationError::InvalidCredentials => rejection("unauthorized"),
+ MacroAuthorizationError::ActingUserNotAuthorized => {
+ status_rejection(StatusCode::FORBIDDEN, "forbidden")
+ }
+ MacroAuthorizationError::Unavailable => {
+ status_rejection(StatusCode::INTERNAL_SERVER_ERROR, "internal server error")
+ }
+ };
+ tracing::error!(error=?error, "bot authorization failed");
+ rejection
+}
diff --git a/crates/macro_authorization/src/inbound/axum/internal.rs b/crates/macro_authorization/src/inbound/axum/internal.rs
new file mode 100644
index 0000000000..fef1a12d84
--- /dev/null
+++ b/crates/macro_authorization/src/inbound/axum/internal.rs
@@ -0,0 +1,108 @@
+use ::axum::{
+ extract::FromRef,
+ http::{HeaderMap, request::Parts},
+};
+use rootcause::Report;
+
+use crate::{
+ InternalIdentityClaims, MacroAuthorization, MacroAuthorizationError, MacroAuthorizationService,
+};
+
+use super::{MacroAuthorizationRejection, MacroAuthorizationState, authenticated_user, rejection};
+
+/// Header carrying the shared key for standard internal service authorization.
+pub const INTERNAL_API_KEY_HEADER: &str = "x-internal-auth-key";
+/// Header carrying the acting Macro user ID for standard internal authorization.
+pub const INTERNAL_MACRO_USER_ID_HEADER: &str = "x-internal-macro-user-id";
+/// Header carrying the acting organization ID for standard internal authorization.
+pub const INTERNAL_MACRO_ORGANIZATION_ID_HEADER: &str = "x-internal-macro-organization-id";
+/// Header carrying the acting FusionAuth user ID for standard internal authorization.
+pub const INTERNAL_FUSIONAUTH_USER_ID_HEADER: &str = "x-internal-fusionauth-user-id";
+
+/// Legacy DSS header carrying the internal service authorization key.
+#[deprecated(note = "migrate callers to INTERNAL_API_KEY_HEADER")]
+pub const LEGACY_DSS_INTERNAL_API_KEY_HEADER: &str = "x-document-storage-service-auth-key";
+/// Legacy DSS header carrying the acting Macro user ID.
+#[deprecated(note = "migrate callers to INTERNAL_MACRO_USER_ID_HEADER")]
+pub const LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER: &str = "x-document-storage-service-user-id";
+
+pub(super) struct InternalHeaderConvention {
+ key_header: &'static str,
+ user_id_header: &'static str,
+ organization_id_header: Option<&'static str>,
+ fusion_user_id_header: Option<&'static str>,
+}
+
+#[allow(deprecated)]
+static INTERNAL_HEADER_CONVENTIONS: [InternalHeaderConvention; 2] = [
+ InternalHeaderConvention {
+ key_header: INTERNAL_API_KEY_HEADER,
+ user_id_header: INTERNAL_MACRO_USER_ID_HEADER,
+ organization_id_header: Some(INTERNAL_MACRO_ORGANIZATION_ID_HEADER),
+ fusion_user_id_header: Some(INTERNAL_FUSIONAUTH_USER_ID_HEADER),
+ },
+ InternalHeaderConvention {
+ key_header: LEGACY_DSS_INTERNAL_API_KEY_HEADER,
+ user_id_header: LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
+ organization_id_header: None,
+ fusion_user_id_header: None,
+ },
+];
+
+pub(super) async fn authorize_internal_request<S, Svc>(
+ parts: &Parts,
+ state: &S,
+ convention: &InternalHeaderConvention,
+) -> Result<Option<MacroAuthorization>, MacroAuthorizationRejection>
+where
+ MacroAuthorizationState<Svc>: FromRef<S>,
+ Svc: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ let provided_key = parts
+ .headers
+ .get(convention.key_header)
+ .and_then(|header| header.to_str().ok())
+ .ok_or_else(|| rejection("unauthorized"))?;
+ let claims = internal_identity_claims(&parts.headers, convention);
+ let authorization = MacroAuthorizationState::<Svc>::from_ref(state);
+ let user_context = authorization
+ .service
+ .authorize_internal(provided_key, claims)
+ .await
+ .map_err(internal_authorization_rejection)?;
+ let acting_user = user_context.map(authenticated_user).transpose()?;
+
+ Ok(Some(MacroAuthorization::Internal(acting_user)))
+}
+
+pub(super) fn internal_header_convention(headers: &HeaderMap) -> Option<&InternalHeaderConvention> {
+ INTERNAL_HEADER_CONVENTIONS
+ .iter()
+ .find(|convention| headers.contains_key(convention.key_header))
+}
+
+fn internal_identity_claims(
+ headers: &HeaderMap,
+ convention: &InternalHeaderConvention,
+) -> InternalIdentityClaims {
+ InternalIdentityClaims {
+ user_id: header_string(headers, Some(convention.user_id_header)),
+ fusion_user_id: header_string(headers, convention.fusion_user_id_header),
+ organization_id: header_string(headers, convention.organization_id_header)
+ .and_then(|organization_id| organization_id.parse().ok()),
+ }
+}
+
+fn header_string(headers: &HeaderMap, name: Option<&str>) -> Option<String> {
+ name.and_then(|name| headers.get(name))
+ .and_then(|header| header.to_str().ok())
+ .map(str::to_owned)
+}
+
+fn internal_authorization_rejection(
+ error: Report<MacroAuthorizationError>,
+) -> MacroAuthorizationRejection {
+ tracing::error!(error=?error.current_context(), "internal authorization failed");
+ rejection("unauthorized")
+}
diff --git a/crates/macro_authorization/src/inbound/axum/macro_authorization.rs b/crates/macro_authorization/src/inbound/axum/macro_authorization.rs
new file mode 100644
index 0000000000..bcc7f6143d
--- /dev/null
+++ b/crates/macro_authorization/src/inbound/axum/macro_authorization.rs
@@ -0,0 +1,100 @@
+use std::marker::PhantomData;
+
+use ::axum::{
+ extract::{FromRef, FromRequestParts},
+ http::{StatusCode, request::Parts},
+};
+
+use crate::{MacroAuthorization, MacroAuthorizationService};
+
+use super::{
+ AuthorizationPolicy, MacroAuthorizationRejection, MacroAuthorizationState,
+ bot::{BOT_TOKEN_HEADER, authorize_optional_bot_request},
+ internal::{authorize_internal_request, internal_header_convention},
+ rejection, status_rejection,
+ user::{authorize_optional_user_request, explicit_user_credential_present},
+};
+
+/// Extracts and authorizes the request principal, then narrows it with `Policy`.
+#[non_exhaustive]
+pub struct MacroAuthorizationExtractor<Svc, Policy: AuthorizationPolicy> {
+ /// The policy-narrowed authorization established for the request.
+ pub authorization: Policy::Output,
+ _service: PhantomData<fn() -> Svc>,
+}
+
+impl<Svc, Policy: AuthorizationPolicy> MacroAuthorizationExtractor<Svc, Policy> {
+ /// Return the authenticated entity responsible for this request.
+ pub fn acting_entity(&self) -> Policy::ActingEntity<'_> {
+ Policy::acting_entity(&self.authorization)
+ }
+}
+
+impl<Svc, Policy: AuthorizationPolicy> Clone for MacroAuthorizationExtractor<Svc, Policy> {
+ fn clone(&self) -> Self {
+ Self {
+ authorization: self.authorization.clone(),
+ _service: PhantomData,
+ }
+ }
+}
+
+impl<S, Svc, Policy> FromRequestParts<S> for MacroAuthorizationExtractor<Svc, Policy>
+where
+ MacroAuthorizationState<Svc>: FromRef<S>,
+ Svc: MacroAuthorizationService,
+ Policy: AuthorizationPolicy,
+ S: Send + Sync + 'static,
+{
+ type Rejection = MacroAuthorizationRejection;
+
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let authorization = authorize_request::<S, Svc>(parts, state)
+ .await?
+ .ok_or_else(|| rejection("unauthorized"))?;
+
+ Ok(Self {
+ authorization: Policy::narrow(authorization)?,
+ _service: PhantomData,
+ })
+ }
+}
+
+pub(super) async fn authorize_request<S, Svc>(
+ parts: &mut Parts,
+ state: &S,
+) -> Result<Option<MacroAuthorization>, MacroAuthorizationRejection>
+where
+ MacroAuthorizationState<Svc>: FromRef<S>,
+ Svc: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ let internal_convention = internal_header_convention(&parts.headers);
+ let has_bot_token = parts.headers.contains_key(BOT_TOKEN_HEADER);
+ let has_explicit_user_credential = explicit_user_credential_present(parts);
+ let explicit_credential_count = usize::from(internal_convention.is_some())
+ + usize::from(has_bot_token)
+ + usize::from(has_explicit_user_credential);
+
+ if explicit_credential_count > 1 {
+ return Err(status_rejection(
+ StatusCode::BAD_REQUEST,
+ "ambiguous credentials",
+ ));
+ }
+
+ if let Some(convention) = internal_convention {
+ return authorize_internal_request::<S, Svc>(parts, state, convention).await;
+ }
+
+ if has_bot_token {
+ let bot = authorize_optional_bot_request::<S, Svc>(parts, state)
+ .await?
+ .expect("bot token presence was checked");
+ return Ok(Some(MacroAuthorization::Bot(bot)));
+ }
+
+ authorize_optional_user_request::<S, Svc>(parts, state)
+ .await
+ .map(|user| user.map(MacroAuthorization::User))
+}
diff --git a/crates/macro_authorization/src/inbound/axum/optional.rs b/crates/macro_authorization/src/inbound/axum/optional.rs
new file mode 100644
index 0000000000..ef1e32d767
--- /dev/null
+++ b/crates/macro_authorization/src/inbound/axum/optional.rs
@@ -0,0 +1,60 @@
+use std::marker::PhantomData;
+
+use ::axum::{
+ extract::{FromRef, FromRequestParts},
+ http::request::Parts,
+};
+
+use crate::MacroAuthorizationService;
+
+use super::{
+ AuthorizationPolicy, MacroAuthorizationRejection, MacroAuthorizationState,
+ macro_authorization::authorize_request,
+};
+
+/// Extracts an optional principal: anonymous requests succeed with `None`;
+/// any supplied credential must authenticate and satisfy `Policy`.
+#[non_exhaustive]
+pub struct OptionalMacroAuthorizationExtractor<Svc, Policy: AuthorizationPolicy> {
+ /// The narrowed authorization, or `None` for an anonymous request.
+ pub authorization: Option<Policy::Output>,
+ _service: PhantomData<fn() -> Svc>,
+}
+
+impl<Svc, Policy: AuthorizationPolicy> OptionalMacroAuthorizationExtractor<Svc, Policy> {
+ /// Return the authenticated entity responsible for this request, if any.
+ pub fn acting_entity(&self) -> Option<Policy::ActingEntity<'_>> {
+ self.authorization.as_ref().map(Policy::acting_entity)
+ }
+}
+
+impl<Svc, Policy: AuthorizationPolicy> Clone for OptionalMacroAuthorizationExtractor<Svc, Policy> {
+ fn clone(&self) -> Self {
+ Self {
+ authorization: self.authorization.clone(),
+ _service: PhantomData,
+ }
+ }
+}
+
+impl<S, Svc, Policy> FromRequestParts<S> for OptionalMacroAuthorizationExtractor<Svc, Policy>
+where
+ MacroAuthorizationState<Svc>: FromRef<S>,
+ Svc: MacroAuthorizationService,
+ Policy: AuthorizationPolicy,
+ S: Send + Sync + 'static,
+{
+ type Rejection = MacroAuthorizationRejection;
+
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let authorization = authorize_request::<S, Svc>(parts, state)
+ .await?
+ .map(Policy::narrow)
+ .transpose()?;
+
+ Ok(Self {
+ authorization,
+ _service: PhantomData,
+ })
+ }
+}
diff --git a/crates/macro_authorization/src/inbound/axum/policy.rs b/crates/macro_authorization/src/inbound/axum/policy.rs
new file mode 100644
index 0000000000..a5110e9af2
--- /dev/null
+++ b/crates/macro_authorization/src/inbound/axum/policy.rs
@@ -0,0 +1,310 @@
+use std::fmt;
+
+use ::axum::http::StatusCode;
+use bot_id::BotId;
+
+use crate::{BotAuthentication, MacroAuthorization, MacroUserAuthentication};
+
+use super::{ActingEntity, MacroAuthorizationRejection, rejection, status_rejection};
+
+/// An endpoint's authorization policy: which authenticated principals the
+/// endpoint admits and the narrowed authorization type its handler receives.
+///
+/// This trait is sealed because policies are security-relevant and are defined
+/// only in this crate.
+pub trait AuthorizationPolicy: sealed::Sealed + Send + Sync + 'static {
+ /// The narrowed authorization carried by the extractor.
+ type Output: Clone + Send + Sync + 'static;
+
+ /// The typed authenticated entity responsible for a request, borrowed from
+ /// [`Self::Output`].
+ type ActingEntity<'a>: Copy + fmt::Debug + fmt::Display;
+
+ /// Validate an authenticated principal against the policy and narrow it.
+ fn narrow(
+ authorization: MacroAuthorization,
+ ) -> Result<Self::Output, MacroAuthorizationRejection>;
+
+ /// Derive the authenticated entity from the narrowed authorization.
+ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_>;
+}
+
+/// Admits directly authenticated users and internal services acting for a user.
+pub struct UserOrInternal;
+
+/// Admits directly authenticated users and all internal services.
+pub struct UserOrInternalService;
+
+/// Admits any principal with a verified acting user.
+pub struct ActingUser;
+
+/// Admits only directly authenticated users.
+pub struct UserOnly;
+
+/// Admits only authenticated bots.
+pub struct BotOnly;
+
+/// Admits only authenticated internal services.
+pub struct InternalOnly;
+
+/// Admits every authenticated principal.
+pub struct AnyPrincipal;
+
+/// The credential kind that established a [`UserOrInternal`] acting user.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum UserOrInternalCaller {
+ /// The user authenticated directly.
+ User,
+ /// An internal service acted for the user.
+ Internal,
+}
+
+/// A guaranteed acting user, established by direct user or internal credentials.
+#[derive(Clone, Debug)]
+#[non_exhaustive]
+pub struct UserOrInternalAuthorization {
+ /// The verified acting user.
+ pub user: MacroUserAuthentication,
+ /// How the acting user was established.
+ pub caller: UserOrInternalCaller,
+}
+
+/// A user or internal service; internal callers need not act for a user.
+///
+/// This is the policy output for receipt-minting infrastructure that must keep
+/// supporting identityless internal callers and must itself decide what an
+/// absent user means.
+#[derive(Clone, Debug)]
+pub enum UserOrInternalServiceAuthorization {
+ /// A directly authenticated user.
+ User(MacroUserAuthentication),
+ /// An internal service, optionally acting for a user.
+ Internal(Option<MacroUserAuthentication>),
+}
+
+impl UserOrInternalServiceAuthorization {
+ /// Return the authenticated or verified user the caller acts for, if any.
+ pub fn acting_user(&self) -> Option<&MacroUserAuthentication> {
+ match self {
+ Self::User(user) => Some(user),
+ Self::Internal(user) => user.as_ref(),
+ }
+ }
+
+ /// Return whether the caller is an internal service.
+ pub fn is_internal(&self) -> bool {
+ matches!(self, Self::Internal(_))
+ }
+}
+
+/// Any principal narrowed to its verified acting user.
+#[derive(Clone, Debug)]
+#[non_exhaustive]
+pub struct ActingUserAuthorization {
+ /// The full authenticating principal.
+ pub principal: MacroAuthorization,
+ /// The verified acting user.
+ pub user: MacroUserAuthentication,
+}
+
+/// An internal service caller.
+#[derive(Clone, Debug)]
+#[non_exhaustive]
+pub struct InternalAuthorization {
+ /// The acting user verified from identity headers, if one was supplied or
+ /// configured as the internal default.
+ pub acting_user: Option<MacroUserAuthentication>,
+}
+
+/// Acting entity for policies that admit users and internal services.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum UserOrInternalEntity<'a> {
+ /// A directly authenticated Macro user.
+ User(&'a str),
+ /// An authenticated internal service.
+ Internal,
+}
+
+impl fmt::Display for UserOrInternalEntity<'_> {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::User(user_id) => formatter.write_str(user_id),
+ Self::Internal => formatter.write_str("internal"),
+ }
+ }
+}
+
+/// Acting entity for internal-only endpoints.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct InternalEntity;
+
+impl fmt::Display for InternalEntity {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("internal")
+ }
+}
+
+impl AuthorizationPolicy for UserOrInternal {
+ type Output = UserOrInternalAuthorization;
+ type ActingEntity<'a> = UserOrInternalEntity<'a>;
+
+ fn narrow(
+ authorization: MacroAuthorization,
+ ) -> Result<Self::Output, MacroAuthorizationRejection> {
+ match authorization {
+ MacroAuthorization::User(user) => Ok(UserOrInternalAuthorization {
+ user,
+ caller: UserOrInternalCaller::User,
+ }),
+ MacroAuthorization::Internal(Some(user)) => Ok(UserOrInternalAuthorization {
+ user,
+ caller: UserOrInternalCaller::Internal,
+ }),
+ MacroAuthorization::Internal(None) => Err(rejection("unauthorized")),
+ MacroAuthorization::Bot(_) => Err(forbidden()),
+ }
+ }
+
+ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_> {
+ match output.caller {
+ UserOrInternalCaller::User => {
+ UserOrInternalEntity::User(output.user.macro_user_id.as_ref())
+ }
+ UserOrInternalCaller::Internal => UserOrInternalEntity::Internal,
+ }
+ }
+}
+
+impl AuthorizationPolicy for UserOrInternalService {
+ type Output = UserOrInternalServiceAuthorization;
+ type ActingEntity<'a> = UserOrInternalEntity<'a>;
+
+ fn narrow(
+ authorization: MacroAuthorization,
+ ) -> Result<Self::Output, MacroAuthorizationRejection> {
+ match authorization {
+ MacroAuthorization::User(user) => Ok(UserOrInternalServiceAuthorization::User(user)),
+ MacroAuthorization::Internal(user) => {
+ Ok(UserOrInternalServiceAuthorization::Internal(user))
+ }
+ MacroAuthorization::Bot(_) => Err(forbidden()),
+ }
+ }
+
+ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_> {
+ match output {
+ UserOrInternalServiceAuthorization::User(user) => {
+ UserOrInternalEntity::User(user.macro_user_id.as_ref())
+ }
+ UserOrInternalServiceAuthorization::Internal(_) => UserOrInternalEntity::Internal,
+ }
+ }
+}
+
+impl AuthorizationPolicy for ActingUser {
+ type Output = ActingUserAuthorization;
+ type ActingEntity<'a> = ActingEntity<'a>;
+
+ fn narrow(
+ authorization: MacroAuthorization,
+ ) -> Result<Self::Output, MacroAuthorizationRejection> {
+ let user = authorization
+ .acting_user()
+ .cloned()
+ .ok_or_else(|| rejection("unauthorized"))?;
+
+ Ok(ActingUserAuthorization {
+ principal: authorization,
+ user,
+ })
+ }
+
+ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_> {
+ ActingEntity::from(&output.principal)
+ }
+}
+
+impl AuthorizationPolicy for UserOnly {
+ type Output = MacroUserAuthentication;
+ type ActingEntity<'a> = &'a str;
+
+ fn narrow(
+ authorization: MacroAuthorization,
+ ) -> Result<Self::Output, MacroAuthorizationRejection> {
+ match authorization {
+ MacroAuthorization::User(user) => Ok(user),
+ MacroAuthorization::Bot(_) | MacroAuthorization::Internal(_) => Err(forbidden()),
+ }
+ }
+
+ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_> {
+ output.macro_user_id.as_ref()
+ }
+}
+
+impl AuthorizationPolicy for BotOnly {
+ type Output = BotAuthentication;
+ type ActingEntity<'a> = BotId;
+
+ fn narrow(
+ authorization: MacroAuthorization,
+ ) -> Result<Self::Output, MacroAuthorizationRejection> {
+ match authorization {
+ MacroAuthorization::Bot(bot) => Ok(bot),
+ MacroAuthorization::User(_) | MacroAuthorization::Internal(_) => Err(forbidden()),
+ }
+ }
+
+ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_> {
+ output.bot_id
+ }
+}
+
+impl AuthorizationPolicy for InternalOnly {
+ type Output = InternalAuthorization;
+ type ActingEntity<'a> = InternalEntity;
+
+ fn narrow(
+ authorization: MacroAuthorization,
+ ) -> Result<Self::Output, MacroAuthorizationRejection> {
+ match authorization {
+ MacroAuthorization::Internal(acting_user) => Ok(InternalAuthorization { acting_user }),
+ MacroAuthorization::User(_) | MacroAuthorization::Bot(_) => Err(forbidden()),
+ }
+ }
+
+ fn acting_entity(_output: &Self::Output) -> Self::ActingEntity<'_> {
+ InternalEntity
+ }
+}
+
+impl AuthorizationPolicy for AnyPrincipal {
+ type Output = MacroAuthorization;
+ type ActingEntity<'a> = ActingEntity<'a>;
+
+ fn narrow(
+ authorization: MacroAuthorization,
+ ) -> Result<Self::Output, MacroAuthorizationRejection> {
+ Ok(authorization)
+ }
+
+ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_> {
+ ActingEntity::from(output)
+ }
+}
+
+fn forbidden() -> MacroAuthorizationRejection {
+ status_rejection(StatusCode::FORBIDDEN, "forbidden")
+}
+
+mod sealed {
+ pub trait Sealed {}
+
+ impl Sealed for super::UserOrInternal {}
+ impl Sealed for super::UserOrInternalService {}
+ impl Sealed for super::ActingUser {}
+ impl Sealed for super::UserOnly {}
+ impl Sealed for super::BotOnly {}
+ impl Sealed for super::InternalOnly {}
+ impl Sealed for super::AnyPrincipal {}
+}
diff --git a/crates/macro_authorization/src/inbound/axum/test.rs b/crates/macro_authorization/src/inbound/axum/test.rs
index 0ee6741b42..3dc5299fb9 100644
--- a/crates/macro_authorization/src/inbound/axum/test.rs
+++ b/crates/macro_authorization/src/inbound/axum/test.rs
@@ -11,13 +11,18 @@ use ::axum::{
response::IntoResponse,
routing::get,
};
+use bot_id::BotId;
use http_body_util::BodyExt;
use rootcause::Report;
use serde_json::{Value, json};
use tower::ServiceExt;
+use uuid::Uuid;
use super::*;
-use crate::InternalIdentityClaims;
+use crate::{
+ BotActingUserClaims, BotAuthentication, InternalIdentityClaims, MacroAuthorization,
+ MacroAuthorizationError, MacroAuthorizationService, MacroUserAuthentication,
+};
const VALID_USER_ID: &str = "macro|[email protected]";
const COOKIE_USER_ID: &str = "macro|[email protected]";
@@ -26,12 +31,19 @@ const BEARER_USER_ID: &str = "macro|[email protected]";
const OPTIONAL_USER_ID: &str = "macro|[email protected]";
const STANDARD_INTERNAL_USER_ID: &str = "macro|[email protected]";
const LEGACY_INTERNAL_USER_ID: &str = "macro|[email protected]";
+const BOT_ACTING_USER_ID: &str = "macro|[email protected]";
const VALID_INTERNAL_KEY: &str = "valid-internal-key";
+const BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(1));
+const BOT_TOKEN_ID: Uuid = Uuid::from_u128(2);
const ACCESS_TOKEN_COOKIE: &str = "macro-access-token";
#[derive(Clone, Debug, Eq, PartialEq)]
enum AuthorizationCall {
Jwt(String),
+ Bot {
+ token: String,
+ claims: Option<BotActingUserClaims>,
+ },
Internal {
provided_key: String,
claims: InternalIdentityClaims,
@@ -70,6 +82,31 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(AuthorizationCall::Bot {
+ token: token.to_owned(),
+ claims: claims.clone(),
+ });
+
+ match token {
+ "bot-bare" => Ok(bot_authentication(None)),
+ "bot-acting" => Ok(bot_authentication(Some(BOT_ACTING_USER_ID))),
+ "bot-expired" => Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
+ "bot-forbidden" => Err(Report::new(
+ MacroAuthorizationError::ActingUserNotAuthorized,
+ )),
+ "bot-unavailable" => Err(Report::new(MacroAuthorizationError::Unavailable)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
@@ -109,6 +146,18 @@ fn user_context(user_id: &str, organization_id: Option<i32>) -> UserContext {
}
}
+fn bot_authentication(acting_user_id: Option<&str>) -> BotAuthentication {
+ BotAuthentication {
+ bot_id: BOT_ID,
+ token_id: BOT_TOKEN_ID,
+ acting_user: acting_user_id.map(|user_id| MacroUserAuthentication {
+ macro_user_id: MacroUserIdStr::try_from(user_id.to_owned())
+ .expect("valid bot acting user id"),
+ user_context: user_context(user_id, Some(42)),
+ }),
+ }
+}
+
#[derive(Clone)]
struct TestState {
authorization: MacroAuthorizationState<FakeAuthorizationService>,
@@ -122,34 +171,146 @@ impl FromRef<TestState> for MacroAuthorizationState<FakeAuthorizationService> {
}
async fn required_handler(
- extractor: MacroAuthorizationExtractor<FakeAuthorizationService>,
+ extractor: MacroAuthorizationExtractor<FakeAuthorizationService, UserOrInternal>,
) -> Json<Value> {
let extractor = extractor.clone();
+ let acting_entity = extractor.acting_entity().to_string();
+ let authorization = &extractor.authorization;
+ let variant = match authorization.caller {
+ UserOrInternalCaller::User => "user",
+ UserOrInternalCaller::Internal => "internal",
+ };
Json(json!({
- "macro_user_id": extractor.macro_user_id.to_string(),
- "user_context": extractor.user_context,
- "is_internal_access": extractor.is_internal_access,
+ "authorization": {
+ "variant": variant,
+ "macro_user_id": authorization.user.macro_user_id.to_string(),
+ "user_context": authorization.user.user_context,
+ },
+ "acting_entity": acting_entity,
+ "macro_user_id": authorization.user.macro_user_id.to_string(),
+ "user_context": authorization.user.user_context,
+ "is_internal_access": authorization.caller == UserOrInternalCaller::Internal,
}))
}
async fn optional_handler(
- extractor: OptionalMacroAuthorizationExtractor<FakeAuthorizationService>,
+ extractor: OptionalMacroAuthorizationExtractor<FakeAuthorizationService, UserOrInternalService>,
+) -> Json<Value> {
+ let extractor = extractor.clone();
+ let acting_entity = extractor
+ .acting_entity()
+ .map(|acting_entity| acting_entity.to_string());
+ let authorization = extractor
+ .authorization
+ .as_ref()
+ .map(user_or_internal_service_json);
+ let acting_user = extractor
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user);
+
+ Json(json!({
+ "authorization": authorization,
+ "acting_entity": acting_entity,
+ "macro_user_id": acting_user.map(|user| user.macro_user_id.to_string()),
+ "user_context": acting_user.map(|user| user.user_context.clone()).unwrap_or_default(),
+ "is_internal_access": extractor
+ .authorization
+ .as_ref()
+ .is_some_and(UserOrInternalServiceAuthorization::is_internal),
+ }))
+}
+
+fn user_or_internal_service_json(authorization: &UserOrInternalServiceAuthorization) -> Value {
+ let variant = if authorization.is_internal() {
+ "internal"
+ } else {
+ "user"
+ };
+ let acting_user = authorization.acting_user();
+
+ json!({
+ "variant": variant,
+ "macro_user_id": acting_user.map(|user| user.macro_user_id.to_string()),
+ "user_context": acting_user.map(|user| &user.user_context),
+ })
+}
+
+async fn user_handler(
+ extractor: MacroAuthorizationExtractor<FakeAuthorizationService, UserOnly>,
) -> Json<Value> {
let extractor = extractor.clone();
+ let acting_entity = extractor.acting_entity().to_string();
Json(json!({
- "macro_user_id": extractor.macro_user_id.map(|id| id.to_string()),
- "user_context": extractor.user_context,
- "is_internal_access": extractor.is_internal_access,
+ "acting_entity": acting_entity,
+ "macro_user_id": extractor.authorization.macro_user_id.to_string(),
+ "user_context": extractor.authorization.user_context,
}))
}
async fn internal_handler(
- extractor: InternalMacroAuthorizationExtractor<FakeAuthorizationService>,
+ extractor: MacroAuthorizationExtractor<FakeAuthorizationService, InternalOnly>,
) -> Json<Value> {
- let _extractor = extractor.clone();
- Json(json!({ "authorized": true }))
+ let extractor = extractor.clone();
+ Json(json!({
+ "acting_entity": extractor.acting_entity().to_string(),
+ "authorized": true,
+ }))
+}
+
+async fn bot_handler(
+ extractor: MacroAuthorizationExtractor<FakeAuthorizationService, BotOnly>,
+) -> Json<Value> {
+ let extractor = extractor.clone();
+ let acting_entity = extractor.acting_entity().to_string();
+ Json(bot_json(&extractor.authorization, &acting_entity))
+}
+
+async fn optional_bot_handler(
+ extractor: OptionalMacroAuthorizationExtractor<FakeAuthorizationService, BotOnly>,
+) -> Json<Value> {
+ Json(
+ extractor
+ .authorization
+ .map(|bot| bot_json(&bot, &bot.bot_id.to_string()))
+ .unwrap_or(Value::Null),
+ )
+}
+
+async fn policy_handler<Policy>(
+ extractor: MacroAuthorizationExtractor<FakeAuthorizationService, Policy>,
+) -> Json<Value>
+where
+ Policy: AuthorizationPolicy,
+{
+ Json(json!({ "acting_entity": extractor.acting_entity().to_string() }))
+}
+
+async fn optional_policy_handler<Policy>(
+ extractor: OptionalMacroAuthorizationExtractor<FakeAuthorizationService, Policy>,
+) -> Json<Value>
+where
+ Policy: AuthorizationPolicy,
+{
+ Json(json!({
+ "acting_entity": extractor
+ .acting_entity()
+ .map(|acting_entity| acting_entity.to_string()),
+ }))
+}
+
+fn bot_json(bot: &BotAuthentication, acting_entity: &str) -> Value {
+ json!({
+ "acting_entity": acting_entity,
+ "bot_id": bot.bot_id.to_string(),
+ "token_id": bot.token_id.to_string(),
+ "acting_user_id": bot
+ .acting_user
+ .as_ref()
+ .map(|user| user.macro_user_id.to_string()),
+ })
}
fn test_router() -> (Router, FakeAuthorizationService) {
@@ -161,7 +322,57 @@ fn test_router() -> (Router, FakeAuthorizationService) {
let router = Router::new()
.route("/required", get(required_handler))
.route("/optional", get(optional_handler))
+ .route("/user", get(user_handler))
.route("/internal", get(internal_handler))
+ .route("/bot", get(bot_handler))
+ .route("/optional-bot", get(optional_bot_handler))
+ .route(
+ "/required/user-or-internal",
+ get(policy_handler::<UserOrInternal>),
+ )
+ .route(
+ "/required/user-or-internal-service",
+ get(policy_handler::<UserOrInternalService>),
+ )
+ .route("/required/acting-user", get(policy_handler::<ActingUser>))
+ .route("/required/user-only", get(policy_handler::<UserOnly>))
+ .route("/required/bot-only", get(policy_handler::<BotOnly>))
+ .route(
+ "/required/internal-only",
+ get(policy_handler::<InternalOnly>),
+ )
+ .route(
+ "/required/any-principal",
+ get(policy_handler::<AnyPrincipal>),
+ )
+ .route(
+ "/optional/user-or-internal",
+ get(optional_policy_handler::<UserOrInternal>),
+ )
+ .route(
+ "/optional/user-or-internal-service",
+ get(optional_policy_handler::<UserOrInternalService>),
+ )
+ .route(
+ "/optional/acting-user",
+ get(optional_policy_handler::<ActingUser>),
+ )
+ .route(
+ "/optional/user-only",
+ get(optional_policy_handler::<UserOnly>),
+ )
+ .route(
+ "/optional/bot-only",
+ get(optional_policy_handler::<BotOnly>),
+ )
+ .route(
+ "/optional/internal-only",
+ get(optional_policy_handler::<InternalOnly>),
+ )
+ .route(
+ "/optional/any-principal",
+ get(optional_policy_handler::<AnyPrincipal>),
+ )
.with_state(state);
(router, service)
@@ -235,9 +446,67 @@ fn state_and_extractors_are_clone_without_requiring_service_clone() {
struct NotClone;
assert_clone_without_service_clone::<MacroAuthorizationState<NotClone>>();
- assert_clone_without_service_clone::<InternalMacroAuthorizationExtractor<NotClone>>();
- assert_clone_without_service_clone::<MacroAuthorizationExtractor<NotClone>>();
- assert_clone_without_service_clone::<OptionalMacroAuthorizationExtractor<NotClone>>();
+ assert_clone_without_service_clone::<MacroAuthorizationExtractor<NotClone, AnyPrincipal>>();
+ assert_clone_without_service_clone::<OptionalMacroAuthorizationExtractor<NotClone, AnyPrincipal>>(
+ );
+}
+
+#[tokio::test]
+async fn extractors_report_the_authenticating_entity() {
+ let (router, _service) = test_router();
+ let requests = [
+ (
+ empty_body(request("/required").header("authorization", "Bearer valid")),
+ Some(VALID_USER_ID.to_string()),
+ ),
+ (
+ empty_body(request("/required/acting-user").header(BOT_TOKEN_HEADER, "bot-acting")),
+ Some(BOT_ID.to_string()),
+ ),
+ (
+ empty_body(
+ request("/required")
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header(INTERNAL_MACRO_USER_ID_HEADER, STANDARD_INTERNAL_USER_ID),
+ ),
+ Some("internal".to_string()),
+ ),
+ (
+ empty_body(request("/optional").header("authorization", "Bearer optional")),
+ Some(OPTIONAL_USER_ID.to_string()),
+ ),
+ (
+ empty_body(request("/optional/any-principal").header(BOT_TOKEN_HEADER, "bot-bare")),
+ Some(BOT_ID.to_string()),
+ ),
+ (
+ empty_body(request("/optional").header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)),
+ Some("internal".to_string()),
+ ),
+ (empty_body(request("/optional")), None),
+ (
+ empty_body(request("/user").header("authorization", "Bearer valid")),
+ Some(VALID_USER_ID.to_string()),
+ ),
+ (
+ empty_body(request("/bot").header(BOT_TOKEN_HEADER, "bot-bare")),
+ Some(BOT_ID.to_string()),
+ ),
+ (
+ empty_body(request("/internal").header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)),
+ Some("internal".to_string()),
+ ),
+ ];
+
+ for (request, expected) in requests {
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(
+ body["acting_entity"],
+ expected.map(Value::String).unwrap_or(Value::Null)
+ );
+ }
}
#[allow(deprecated)]
@@ -250,7 +519,10 @@ async fn internal_accepts_standard_and_legacy_api_keys_without_identity_headers(
let (status, body) = send(&router, request).await;
assert_eq!(status, StatusCode::OK);
- assert_eq!(body, json!({ "authorized": true }));
+ assert_eq!(
+ body,
+ json!({ "acting_entity": "internal", "authorized": true })
+ );
}
assert_eq!(
@@ -282,7 +554,10 @@ async fn internal_forwards_identity_headers_to_create_user_context() {
let (status, body) = send(&router, request).await;
assert_eq!(status, StatusCode::OK);
- assert_eq!(body, json!({ "authorized": true }));
+ assert_eq!(
+ body,
+ json!({ "acting_entity": "internal", "authorized": true })
+ );
assert_eq!(
service.calls(),
[AuthorizationCall::Internal {
@@ -297,20 +572,22 @@ async fn internal_forwards_identity_headers_to_create_user_context() {
}
#[tokio::test]
-async fn internal_rejects_missing_key_and_does_not_fall_back_to_jwt() {
+async fn internal_only_requires_credentials_and_forbids_valid_user_credentials() {
let (router, service) = test_router();
- for request in [
- empty_body(request("/internal")),
- empty_body(request("/internal").header("authorization", "Bearer valid")),
- ] {
- let (status, body) = send(&router, request).await;
+ let (status, body) = send(&router, empty_body(request("/internal"))).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
- assert_eq!(status, StatusCode::UNAUTHORIZED);
- assert_eq!(body, json!({ "message": "unauthorized" }));
- }
+ let user_request = empty_body(request("/internal").header("authorization", "Bearer valid"));
+ let (status, body) = send(&router, user_request).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
- assert!(service.calls().is_empty());
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::Jwt("valid".to_string())]
+ );
}
#[tokio::test]
@@ -354,6 +631,64 @@ async fn internal_standard_key_takes_precedence_over_legacy_key() {
);
}
+#[tokio::test]
+async fn user_accepts_query_bearer_and_cookie_credentials() {
+ let (router, service) = test_router();
+ let requests = [
+ (
+ empty_body(request("/user?macro-api-token=query")),
+ QUERY_USER_ID,
+ ),
+ (
+ empty_body(request("/user").header("authorization", "Bearer bearer")),
+ BEARER_USER_ID,
+ ),
+ (
+ empty_body(request("/user").header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie"))),
+ COOKIE_USER_ID,
+ ),
+ ];
+
+ for (request, expected_user_id) in requests {
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["macro_user_id"], expected_user_id);
+ assert_eq!(body["user_context"]["user_id"], expected_user_id);
+ }
+
+ assert_eq!(
+ service.calls(),
+ [
+ AuthorizationCall::Jwt("query".to_string()),
+ AuthorizationCall::Jwt("bearer".to_string()),
+ AuthorizationCall::Jwt("cookie".to_string()),
+ ]
+ );
+}
+
+#[tokio::test]
+async fn user_rejects_missing_and_invalid_user_credentials() {
+ let (router, service) = test_router();
+
+ let (status, body) = send(&router, empty_body(request("/user"))).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+
+ let (status, body) = send(
+ &router,
+ empty_body(request("/user").header("authorization", "Bearer expired")),
+ )
+ .await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "jwt expired" }));
+
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::Jwt("expired".to_string())]
+ );
+}
+
#[tokio::test]
async fn required_extracts_valid_bearer_and_preserves_organization() {
let (router, service) = test_router();
@@ -362,6 +697,12 @@ async fn required_extracts_valid_bearer_and_preserves_organization() {
let (status, body) = send(&router, request).await;
assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["authorization"]["variant"], "user");
+ assert_eq!(
+ body["authorization"]["macro_user_id"],
+ body["macro_user_id"]
+ );
+ assert_eq!(body["authorization"]["user_context"], body["user_context"]);
assert_eq!(body["macro_user_id"], VALID_USER_ID);
assert_eq!(body["user_context"]["organization_id"], 42);
assert_eq!(body["is_internal_access"], false);
@@ -427,7 +768,7 @@ async fn bearer_token_takes_precedence_over_cookie() {
}
#[tokio::test]
-async fn malformed_query_falls_back_to_other_or_absent_credentials() {
+async fn malformed_query_remains_an_explicit_user_credential() {
let (router, service) = test_router();
let malformed_query = "macro-api-token=query&macro-api-token=invalid";
@@ -443,24 +784,19 @@ async fn malformed_query_falls_back_to_other_or_absent_credentials() {
.header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
);
let (status, body) = send(&router, cookie_request).await;
- assert_eq!(status, StatusCode::OK);
- assert_eq!(body["macro_user_id"], COOKIE_USER_ID);
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
let (status, body) = send(
&router,
empty_body(request(&format!("/optional?{malformed_query}"))),
)
.await;
- assert_eq!(status, StatusCode::OK);
- assert_eq!(body["macro_user_id"], Value::Null);
- assert_eq!(body["user_context"]["user_id"], "");
- assert_eq!(body["is_internal_access"], false);
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
assert_eq!(
service.calls(),
- [
- AuthorizationCall::Jwt("bearer".to_string()),
- AuthorizationCall::Jwt("cookie".to_string()),
- ]
+ [AuthorizationCall::Jwt("bearer".to_string())]
);
}
@@ -482,6 +818,7 @@ async fn optional_returns_default_context_for_missing_credentials() {
let (status, body) = send(&router, empty_body(request("/optional"))).await;
assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["authorization"], Value::Null);
assert_eq!(body["macro_user_id"], Value::Null);
assert_eq!(body["user_context"]["user_id"], "");
assert_eq!(body["user_context"]["fusion_user_id"], "");
@@ -580,6 +917,12 @@ async fn optional_returns_authenticated_output() {
let (status, body) = send(&router, request).await;
assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["authorization"]["variant"], "user");
+ assert_eq!(
+ body["authorization"]["macro_user_id"],
+ body["macro_user_id"]
+ );
+ assert_eq!(body["authorization"]["user_context"], body["user_context"]);
assert_eq!(body["macro_user_id"], OPTIONAL_USER_ID);
assert_eq!(body["user_context"]["user_id"], OPTIONAL_USER_ID);
assert_eq!(body["user_context"]["fusion_user_id"], "fusion-user-id");
@@ -598,13 +941,18 @@ async fn standard_internal_headers_authorize_matching_claims() {
.header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
.header(INTERNAL_MACRO_USER_ID_HEADER, STANDARD_INTERNAL_USER_ID)
.header(INTERNAL_MACRO_ORGANIZATION_ID_HEADER, "42")
- .header(INTERNAL_FUSIONAUTH_USER_ID_HEADER, "standard-fusion-id")
- .header("authorization", "Bearer invalid"),
+ .header(INTERNAL_FUSIONAUTH_USER_ID_HEADER, "standard-fusion-id"),
);
let (status, body) = send(&router, request).await;
assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["authorization"]["variant"], "internal");
+ assert_eq!(
+ body["authorization"]["macro_user_id"],
+ body["macro_user_id"]
+ );
+ assert_eq!(body["authorization"]["user_context"], body["user_context"]);
assert_eq!(body["macro_user_id"], STANDARD_INTERNAL_USER_ID);
assert_eq!(body["user_context"]["fusion_user_id"], "standard-fusion-id");
assert_eq!(body["user_context"]["organization_id"], 42);
@@ -731,12 +1079,12 @@ async fn standard_convention_takes_precedence_when_both_keys_are_present() {
}
#[tokio::test]
-async fn invalid_internal_key_rejects_without_jwt_fallback() {
+async fn invalid_internal_key_rejects_without_cookie_fallback() {
let (router, service) = test_router();
let request = empty_body(
request("/required")
.header(INTERNAL_API_KEY_HEADER, "invalid-internal-key")
- .header("authorization", "Bearer valid"),
+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
);
let (status, body) = send(&router, request).await;
@@ -753,13 +1101,13 @@ async fn invalid_internal_key_rejects_without_jwt_fallback() {
}
#[tokio::test]
-async fn malformed_internal_key_rejects_without_jwt_fallback() {
+async fn malformed_internal_key_rejects_without_cookie_fallback() {
let (router, service) = test_router();
let malformed_key = HeaderValue::from_bytes(b"\xff").unwrap();
let request = empty_body(
request("/required")
.header(INTERNAL_API_KEY_HEADER, malformed_key)
- .header("authorization", "Bearer valid"),
+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
);
let (status, body) = send(&router, request).await;
@@ -797,6 +1145,9 @@ async fn identityless_internal_request_is_preserved_by_optional_extractor() {
let (status, body) = send(&router, request).await;
assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["authorization"]["variant"], "internal");
+ assert_eq!(body["authorization"]["macro_user_id"], Value::Null);
+ assert_eq!(body["authorization"]["user_context"], Value::Null);
assert_eq!(body["macro_user_id"], Value::Null);
assert_eq!(body["user_context"]["user_id"], "");
assert_eq!(body["user_context"]["fusion_user_id"], "");
@@ -839,3 +1190,675 @@ async fn malformed_internal_organization_is_ignored() {
}]
);
}
+
+#[test]
+fn bot_header_constants_use_the_resolved_names() {
+ assert_eq!(BOT_TOKEN_HEADER, "x-macro-bot-token");
+ assert_eq!(
+ BOT_FOR_MACRO_USER_ID_HEADER,
+ "x-macro-bot-for-macro-user-id"
+ );
+ assert_eq!(
+ BOT_FOR_FUSIONAUTH_USER_ID_HEADER,
+ "x-macro-bot-for-fusionauth-user-id"
+ );
+ assert_eq!(
+ BOT_FOR_ORGANIZATION_ID_HEADER,
+ "x-macro-bot-for-organization-id"
+ );
+}
+
+#[tokio::test]
+async fn acting_user_and_any_principal_accept_bot_with_verified_acting_user() {
+ let (router, service) = test_router();
+
+ for path in ["/required/acting-user", "/optional/any-principal"] {
+ let request = empty_body(
+ request(path)
+ .header(BOT_TOKEN_HEADER, "bot-acting")
+ .header(BOT_FOR_MACRO_USER_ID_HEADER, BOT_ACTING_USER_ID)
+ .header(BOT_FOR_FUSIONAUTH_USER_ID_HEADER, "fusion-claimed")
+ .header(BOT_FOR_ORGANIZATION_ID_HEADER, "42"),
+ );
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["acting_entity"], BOT_ID.to_string());
+ }
+
+ let claims = Some(BotActingUserClaims {
+ user_id: Some(BOT_ACTING_USER_ID.to_owned()),
+ fusion_user_id: Some("fusion-claimed".to_owned()),
+ organization_id: Some(42),
+ });
+ assert_eq!(
+ service.calls(),
+ [
+ AuthorizationCall::Bot {
+ token: "bot-acting".to_owned(),
+ claims: claims.clone(),
+ },
+ AuthorizationCall::Bot {
+ token: "bot-acting".to_owned(),
+ claims,
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn bare_bot_is_forbidden_by_no_bot_policies_and_accepted_by_bot_only() {
+ let (router, service) = test_router();
+
+ let (status, body) = send(
+ &router,
+ empty_body(request("/required").header(BOT_TOKEN_HEADER, "bot-bare")),
+ )
+ .await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
+
+ let (status, body) = send(
+ &router,
+ empty_body(request("/optional").header(BOT_TOKEN_HEADER, "bot-bare")),
+ )
+ .await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
+
+ for path in ["/bot", "/optional-bot"] {
+ let (status, body) = send(
+ &router,
+ empty_body(request(path).header(BOT_TOKEN_HEADER, "bot-bare")),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["bot_id"], BOT_ID.to_string());
+ assert_eq!(body["token_id"], BOT_TOKEN_ID.to_string());
+ assert_eq!(body["acting_user_id"], Value::Null);
+ }
+
+ assert_eq!(
+ service.calls(),
+ vec![
+ AuthorizationCall::Bot {
+ token: "bot-bare".to_owned(),
+ claims: None,
+ };
+ 4
+ ]
+ );
+}
+
+#[tokio::test]
+async fn missing_malformed_and_blank_bot_tokens_follow_required_and_optional_contracts() {
+ let (router, service) = test_router();
+
+ let (status, body) = send(&router, empty_body(request("/bot"))).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+
+ let (status, body) = send(&router, empty_body(request("/optional-bot"))).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body, Value::Null);
+
+ for path in ["/required", "/optional", "/bot", "/optional-bot"] {
+ let malformed_token = HeaderValue::from_bytes(b"\xff").unwrap();
+ let (status, body) = send(
+ &router,
+ empty_body(request(path).header(BOT_TOKEN_HEADER, malformed_token)),
+ )
+ .await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+
+ for blank_token in ["", " "] {
+ let (status, body) = send(
+ &router,
+ empty_body(request(path).header(BOT_TOKEN_HEADER, blank_token)),
+ )
+ .await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+ }
+ }
+
+ assert!(service.calls().is_empty());
+}
+
+#[tokio::test]
+async fn bot_authorization_errors_have_generic_status_specific_responses() {
+ let (router, service) = test_router();
+
+ for token in ["bot-invalid", "bot-expired", "bot-revoked"] {
+ for path in ["/required", "/optional", "/bot", "/optional-bot"] {
+ let (status, body) = send(
+ &router,
+ empty_body(request(path).header(BOT_TOKEN_HEADER, token)),
+ )
+ .await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+ }
+ }
+
+ for path in ["/required", "/optional", "/bot", "/optional-bot"] {
+ let (status, body) = send(
+ &router,
+ empty_body(request(path).header(BOT_TOKEN_HEADER, "bot-forbidden")),
+ )
+ .await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
+
+ let (status, body) = send(
+ &router,
+ empty_body(request(path).header(BOT_TOKEN_HEADER, "bot-unavailable")),
+ )
+ .await;
+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(body, json!({ "message": "internal server error" }));
+ }
+
+ assert_eq!(service.calls().len(), 20);
+ assert!(
+ service
+ .calls()
+ .iter()
+ .all(|call| matches!(call, AuthorizationCall::Bot { .. }))
+ );
+}
+
+#[tokio::test]
+async fn bot_claim_headers_are_strictly_parsed_before_authorization() {
+ let (router, service) = test_router();
+ let malformed_header = HeaderValue::from_bytes(b"\xff").unwrap();
+
+ for header in [
+ BOT_FOR_MACRO_USER_ID_HEADER,
+ BOT_FOR_FUSIONAUTH_USER_ID_HEADER,
+ BOT_FOR_ORGANIZATION_ID_HEADER,
+ ] {
+ let (status, body) = send(
+ &router,
+ empty_body(
+ request("/bot")
+ .header(BOT_TOKEN_HEADER, "bot-acting")
+ .header(header, malformed_header.clone()),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(body, json!({ "message": "invalid bot claims" }));
+ }
+
+ for organization_id in ["not-an-integer", "", "2147483648"] {
+ let (status, body) = send(
+ &router,
+ empty_body(
+ request("/bot")
+ .header(BOT_TOKEN_HEADER, "bot-acting")
+ .header(BOT_FOR_ORGANIZATION_ID_HEADER, organization_id),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(body, json!({ "message": "invalid bot claims" }));
+ }
+
+ assert!(service.calls().is_empty());
+}
+
+#[tokio::test]
+async fn bot_claims_without_a_user_identifier_reach_the_authorizer() {
+ let (router, service) = test_router();
+ let request = empty_body(
+ request("/bot")
+ .header(BOT_TOKEN_HEADER, "bot-forbidden")
+ .header(BOT_FOR_ORGANIZATION_ID_HEADER, "42"),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::Bot {
+ token: "bot-forbidden".to_owned(),
+ claims: Some(BotActingUserClaims {
+ user_id: None,
+ fusion_user_id: None,
+ organization_id: Some(42),
+ }),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn every_combination_of_multiple_explicit_credential_types_is_ambiguous() {
+ for path in [
+ "/required/user-or-internal",
+ "/required/user-or-internal-service",
+ "/required/acting-user",
+ "/required/user-only",
+ "/required/bot-only",
+ "/required/internal-only",
+ "/required/any-principal",
+ "/optional/user-or-internal",
+ "/optional/user-or-internal-service",
+ "/optional/acting-user",
+ "/optional/user-only",
+ "/optional/bot-only",
+ "/optional/internal-only",
+ "/optional/any-principal",
+ ] {
+ let (router, service) = test_router();
+ let path_with_query = format!("{path}?macro-api-token=query");
+ let requests = [
+ empty_body(
+ request(path)
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header("authorization", "Bearer valid"),
+ ),
+ empty_body(
+ request(path)
+ .header(BOT_TOKEN_HEADER, "bot-acting")
+ .header("authorization", "Bearer valid"),
+ ),
+ empty_body(
+ request(path)
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header(BOT_TOKEN_HEADER, "bot-acting"),
+ ),
+ empty_body(
+ request(path)
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header(BOT_TOKEN_HEADER, "bot-acting")
+ .header("authorization", "Bearer valid"),
+ ),
+ empty_body(
+ request(&path_with_query).header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY),
+ ),
+ empty_body(request(&path_with_query).header(BOT_TOKEN_HEADER, "bot-acting")),
+ ];
+
+ for request in requests {
+ let (status, body) = send(&router, request).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(body, json!({ "message": "ambiguous credentials" }));
+ }
+
+ assert!(service.calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn explicit_credentials_win_over_ambient_cookies_without_fallback() {
+ let (router, service) = test_router();
+
+ let valid_bot_request = empty_body(
+ request("/required")
+ .header(BOT_TOKEN_HEADER, "bot-acting")
+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
+ );
+ let (status, body) = send(&router, valid_bot_request).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
+
+ let invalid_bot_request = empty_body(
+ request("/required")
+ .header(BOT_TOKEN_HEADER, "bot-invalid")
+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
+ );
+ let (status, body) = send(&router, invalid_bot_request).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+
+ let malformed_user_request = empty_body(
+ request("/required")
+ .header("authorization", "Basic deliberate-but-malformed")
+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
+ );
+ let (status, body) = send(&router, malformed_user_request).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+
+ assert_eq!(
+ service.calls(),
+ [
+ AuthorizationCall::Bot {
+ token: "bot-acting".to_owned(),
+ claims: None,
+ },
+ AuthorizationCall::Bot {
+ token: "bot-invalid".to_owned(),
+ claims: None,
+ },
+ ]
+ );
+}
+
+#[derive(Clone, Copy, Debug)]
+enum PrincipalCredentials {
+ User,
+ BotWithActingUser,
+ BotWithoutActingUser,
+ InternalWithActingUser,
+ InternalWithoutActingUser,
+ Anonymous,
+}
+
+const PRINCIPAL_CREDENTIALS: [PrincipalCredentials; 6] = [
+ PrincipalCredentials::User,
+ PrincipalCredentials::BotWithActingUser,
+ PrincipalCredentials::BotWithoutActingUser,
+ PrincipalCredentials::InternalWithActingUser,
+ PrincipalCredentials::InternalWithoutActingUser,
+ PrincipalCredentials::Anonymous,
+];
+
+fn principal_request(path: &str, credentials: PrincipalCredentials) -> Request<Body> {
+ let request = match credentials {
+ PrincipalCredentials::User => request(path).header("authorization", "Bearer valid"),
+ PrincipalCredentials::BotWithActingUser => {
+ request(path).header(BOT_TOKEN_HEADER, "bot-acting")
+ }
+ PrincipalCredentials::BotWithoutActingUser => {
+ request(path).header(BOT_TOKEN_HEADER, "bot-bare")
+ }
+ PrincipalCredentials::InternalWithActingUser => request(path)
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header(INTERNAL_MACRO_USER_ID_HEADER, STANDARD_INTERNAL_USER_ID),
+ PrincipalCredentials::InternalWithoutActingUser => {
+ request(path).header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ }
+ PrincipalCredentials::Anonymous => request(path),
+ };
+
+ empty_body(request)
+}
+
+#[tokio::test]
+async fn required_policy_matrix_enforces_principal_and_acting_user_contracts() {
+ let policies = [
+ (
+ "/required/user-or-internal",
+ [
+ StatusCode::OK,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ StatusCode::UNAUTHORIZED,
+ ],
+ ),
+ (
+ "/required/user-or-internal-service",
+ [
+ StatusCode::OK,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ ],
+ ),
+ (
+ "/required/acting-user",
+ [
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ StatusCode::UNAUTHORIZED,
+ ],
+ ),
+ (
+ "/required/user-only",
+ [
+ StatusCode::OK,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::UNAUTHORIZED,
+ ],
+ ),
+ (
+ "/required/bot-only",
+ [
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::UNAUTHORIZED,
+ ],
+ ),
+ (
+ "/required/internal-only",
+ [
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ ],
+ ),
+ (
+ "/required/any-principal",
+ [
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ ],
+ ),
+ ];
+
+ assert_policy_matrix(policies).await;
+}
+
+#[tokio::test]
+async fn optional_policy_matrix_enforces_credentials_but_allows_anonymous_requests() {
+ let policies = [
+ (
+ "/optional/user-or-internal",
+ [
+ StatusCode::OK,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ StatusCode::OK,
+ ],
+ ),
+ (
+ "/optional/user-or-internal-service",
+ [
+ StatusCode::OK,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ ],
+ ),
+ (
+ "/optional/acting-user",
+ [
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ StatusCode::OK,
+ StatusCode::UNAUTHORIZED,
+ StatusCode::OK,
+ ],
+ ),
+ (
+ "/optional/user-only",
+ [
+ StatusCode::OK,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ ],
+ ),
+ (
+ "/optional/bot-only",
+ [
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ ],
+ ),
+ (
+ "/optional/internal-only",
+ [
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::FORBIDDEN,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ ],
+ ),
+ (
+ "/optional/any-principal",
+ [
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ StatusCode::OK,
+ ],
+ ),
+ ];
+
+ assert_policy_matrix(policies).await;
+}
+
+async fn assert_policy_matrix<const N: usize>(policies: [(&str, [StatusCode; 6]); N]) {
+ let (router, _service) = test_router();
+
+ for (path, expected_statuses) in policies {
+ for (credentials, expected_status) in
+ PRINCIPAL_CREDENTIALS.into_iter().zip(expected_statuses)
+ {
+ let (status, body) = send(&router, principal_request(path, credentials)).await;
+ assert_eq!(
+ status, expected_status,
+ "unexpected status for {path} with {credentials:?}: {body}"
+ );
+
+ match expected_status {
+ StatusCode::UNAUTHORIZED => {
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+ }
+ StatusCode::FORBIDDEN => {
+ assert_eq!(body, json!({ "message": "forbidden" }));
+ }
+ StatusCode::OK => {}
+ status => panic!("unexpected matrix status {status}"),
+ }
+ }
+ }
+}
+
+#[test]
+fn policies_report_typed_acting_entity_variants_with_display_parity() {
+ let user = macro_user_authentication(VALID_USER_ID);
+ let internal_user = macro_user_authentication(STANDARD_INTERNAL_USER_ID);
+ let bot = bot_authentication(Some(BOT_ACTING_USER_ID));
+
+ let direct_user = MacroAuthorization::User(user.clone());
+ let user_or_internal = UserOrInternal::narrow(direct_user.clone()).unwrap();
+ assert_eq!(
+ UserOrInternal::acting_entity(&user_or_internal),
+ UserOrInternalEntity::User(VALID_USER_ID)
+ );
+ assert_display_parity::<UserOrInternal>(direct_user);
+
+ let internal = MacroAuthorization::Internal(Some(internal_user.clone()));
+ let user_or_internal = UserOrInternal::narrow(internal.clone()).unwrap();
+ assert_eq!(
+ UserOrInternal::acting_entity(&user_or_internal),
+ UserOrInternalEntity::Internal
+ );
+ assert_display_parity::<UserOrInternal>(internal.clone());
+
+ let internal_service = UserOrInternalService::narrow(internal.clone()).unwrap();
+ assert!(internal_service.is_internal());
+ assert_eq!(
+ internal_service
+ .acting_user()
+ .map(|user| user.macro_user_id.as_ref()),
+ Some(STANDARD_INTERNAL_USER_ID)
+ );
+ assert_eq!(
+ UserOrInternalService::acting_entity(&internal_service),
+ UserOrInternalEntity::Internal
+ );
+ assert_display_parity::<UserOrInternalService>(internal.clone());
+
+ let bot_principal = MacroAuthorization::Bot(bot.clone());
+ let acting_user = ActingUser::narrow(bot_principal.clone()).unwrap();
+ assert!(matches!(acting_user.principal, MacroAuthorization::Bot(_)));
+ assert_eq!(acting_user.user.macro_user_id.as_ref(), BOT_ACTING_USER_ID);
+ assert_eq!(
+ ActingUser::acting_entity(&acting_user),
+ ActingEntity::Bot(BOT_ID)
+ );
+ assert_display_parity::<ActingUser>(bot_principal.clone());
+
+ let user_only = UserOnly::narrow(MacroAuthorization::User(user.clone())).unwrap();
+ assert_eq!(UserOnly::acting_entity(&user_only), VALID_USER_ID);
+ assert_display_parity::<UserOnly>(MacroAuthorization::User(user));
+
+ let bot_only = BotOnly::narrow(bot_principal.clone()).unwrap();
+ assert_eq!(BotOnly::acting_entity(&bot_only), BOT_ID);
+ assert_display_parity::<BotOnly>(bot_principal.clone());
+
+ let internal_only = InternalOnly::narrow(internal.clone()).unwrap();
+ assert_eq!(
+ internal_only
+ .acting_user
+ .as_ref()
+ .map(|user| user.macro_user_id.as_ref()),
+ Some(STANDARD_INTERNAL_USER_ID)
+ );
+ assert_eq!(InternalOnly::acting_entity(&internal_only), InternalEntity);
+ assert_display_parity::<InternalOnly>(internal.clone());
+
+ let any_principal = AnyPrincipal::narrow(bot_principal.clone()).unwrap();
+ assert_eq!(
+ AnyPrincipal::acting_entity(&any_principal),
+ ActingEntity::Bot(BOT_ID)
+ );
+ assert_display_parity::<AnyPrincipal>(bot_principal);
+}
+
+fn macro_user_authentication(user_id: &str) -> MacroUserAuthentication {
+ MacroUserAuthentication {
+ macro_user_id: MacroUserIdStr::try_from(user_id.to_owned()).expect("valid Macro user ID"),
+ user_context: user_context(user_id, None),
+ }
+}
+
+fn assert_display_parity<Policy: AuthorizationPolicy>(authorization: MacroAuthorization) {
+ let expected = ActingEntity::from(&authorization).to_string();
+ let output = Policy::narrow(authorization).expect("principal should satisfy policy");
+
+ assert_eq!(Policy::acting_entity(&output).to_string(), expected);
+}
diff --git a/crates/macro_authorization/src/inbound/axum/user.rs b/crates/macro_authorization/src/inbound/axum/user.rs
new file mode 100644
index 0000000000..82877ca810
--- /dev/null
+++ b/crates/macro_authorization/src/inbound/axum/user.rs
@@ -0,0 +1,153 @@
+use ::axum::{
+ extract::{FromRef, FromRequestParts, Query},
+ http::{header, request::Parts},
+};
+use macro_auth::headers::AccessTokenExtractor;
+#[cfg(feature = "local_auth")]
+use macro_env_var::maybe_env_vars;
+#[cfg(feature = "local_auth")]
+use model_user::UserContext;
+use rootcause::Report;
+use serde::Deserialize;
+
+use crate::{MacroAuthorizationError, MacroAuthorizationService, MacroUserAuthentication};
+
+use super::{MacroAuthorizationRejection, MacroAuthorizationState, authenticated_user, rejection};
+
+#[cfg(feature = "local_auth")]
+maybe_env_vars! {
+ struct LocalUserId;
+ struct LocalFusionUserId;
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "kebab-case")]
+struct AuthorizationQuery {
+ macro_api_token: Option<String>,
+}
+
+pub(super) fn explicit_user_credential_present(parts: &Parts) -> bool {
+ query_user_credential_present(parts) || parts.headers.contains_key(header::AUTHORIZATION)
+}
+
+pub(super) async fn authorize_optional_user_request<S, Svc>(
+ parts: &mut Parts,
+ state: &S,
+) -> Result<Option<MacroUserAuthentication>, MacroAuthorizationRejection>
+where
+ MacroAuthorizationState<Svc>: FromRef<S>,
+ Svc: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ let query_token = extract_query_token(parts, state).await;
+
+ if explicit_user_credential_present(parts) {
+ let token = extract_explicit_user_token(parts, state, query_token).await?;
+ return authorize_user_token::<S, Svc>(state, &token)
+ .await
+ .map(Some);
+ }
+
+ #[cfg(feature = "local_auth")]
+ if let Some(user_context) = local_user_context() {
+ return authenticated_user(user_context).map(Some);
+ }
+
+ let Some(token) = extract_ambient_user_token(parts, state).await else {
+ return Ok(None);
+ };
+
+ authorize_user_token::<S, Svc>(state, &token)
+ .await
+ .map(Some)
+}
+
+fn query_user_credential_present(parts: &Parts) -> bool {
+ parts.uri.query().is_some_and(|query| {
+ query.split('&').any(|parameter| {
+ parameter
+ .split_once('=')
+ .map_or(parameter, |(name, _value)| name)
+ == "macro-api-token"
+ })
+ })
+}
+
+async fn extract_query_token<S>(parts: &mut Parts, state: &S) -> Option<String>
+where
+ S: Send + Sync,
+{
+ Query::<AuthorizationQuery>::from_request_parts(parts, state)
+ .await
+ .ok()
+ .and_then(|Query(query)| query.macro_api_token)
+}
+
+async fn extract_explicit_user_token<S>(
+ parts: &mut Parts,
+ state: &S,
+ query_token: Option<String>,
+) -> Result<String, MacroAuthorizationRejection>
+where
+ S: Send + Sync,
+{
+ if let Some(token) = query_token {
+ return Ok(token);
+ }
+
+ match AccessTokenExtractor::from_request_parts(parts, state).await {
+ Ok(token @ AccessTokenExtractor::Header(_)) => Ok(token.as_ref().to_owned()),
+ Ok(AccessTokenExtractor::Cookie(_)) | Err(_) => Err(rejection("unauthorized")),
+ }
+}
+
+async fn extract_ambient_user_token<S>(parts: &mut Parts, state: &S) -> Option<String>
+where
+ S: Send + Sync,
+{
+ AccessTokenExtractor::from_request_parts(parts, state)
+ .await
+ .ok()
+ .map(|token| token.as_ref().to_owned())
+}
+
+#[cfg(feature = "local_auth")]
+fn local_user_context() -> Option<UserContext> {
+ Some(UserContext {
+ user_id: LocalUserId::new()?.to_string(),
+ fusion_user_id: LocalFusionUserId::new()
+ .map(|fusion_user_id| fusion_user_id.to_string())
+ .unwrap_or_else(|| "set me!".to_string()),
+ organization_id: Some(1),
+ permissions: None,
+ })
+}
+
+async fn authorize_user_token<S, Svc>(
+ state: &S,
+ token: &str,
+) -> Result<MacroUserAuthentication, MacroAuthorizationRejection>
+where
+ MacroAuthorizationState<Svc>: FromRef<S>,
+ Svc: MacroAuthorizationService,
+{
+ let authorization = MacroAuthorizationState::<Svc>::from_ref(state);
+ let user_context = authorization
+ .service
+ .authorize(token)
+ .await
+ .map_err(authorization_rejection)?;
+
+ authenticated_user(user_context)
+}
+
+fn authorization_rejection(error: Report<MacroAuthorizationError>) -> MacroAuthorizationRejection {
+ let message = match error.current_context() {
+ MacroAuthorizationError::CredentialsExpired => "jwt expired",
+ MacroAuthorizationError::InvalidCredentials
+ | MacroAuthorizationError::ActingUserNotAuthorized
+ | MacroAuthorizationError::Unavailable => "unauthorized",
+ };
+ tracing::error!(error=?error, "credential authorization failed");
+ rejection(message)
+}
diff --git a/crates/macro_authorization/src/lib.rs b/crates/macro_authorization/src/lib.rs
index dd5bcfb678..d95bd93a2e 100644
--- a/crates/macro_authorization/src/lib.rs
+++ b/crates/macro_authorization/src/lib.rs
@@ -1,31 +1,36 @@
#![deny(missing_docs)]
//! Transport-independent authorization services and optional transport adapters.
//!
-//! The domain layer validates credentials through a cryptographic validation
-//! port and returns the authenticated user's [`model_user::UserContext`].
+//! The domain layer validates user, bot, and internal service credentials and
+//! returns a typed principal with any authenticated or verified acting user.
+//! [`MacroAuthorizationServiceImpl::new`] requires bot authorization to be
+//! configured explicitly, just like internal authorization. Services backed by
+//! MacroDB should use `PgBotAuthorizer`; services that intentionally reject
+//! bot credentials must pass [`NoBotAuthorizer`].
//!
//! # Choosing an Axum extractor
//!
-//! The `axum` feature provides three request extractors:
+//! The `axum` feature provides a required [`MacroAuthorizationExtractor`] and
+//! an [`OptionalMacroAuthorizationExtractor`] for endpoints that permit
+//! anonymous requests. Both require an explicit [`AuthorizationPolicy`] type:
//!
-//! - [`MacroAuthorizationExtractor`] requires an acting user. It accepts either
-//! user credentials or internal service credentials automatically. An
-//! internal request must resolve to a user through its acting-user header or
-//! [`InternalAuthConfig::default_user_id`].
-//! - [`OptionalMacroAuthorizationExtractor`] supports anonymous, authenticated
-//! user, and internal service callers. Missing credentials succeed without a
-//! user identity, but supplied invalid or expired credentials are rejected.
-//! - [`InternalMacroAuthorizationExtractor`] is for endpoints that will only
-//! ever be called by trusted internal services. It requires an internal API
-//! key, does not accept user credentials as a substitute, and exposes no user
-//! identity.
+//! | Policy | Admitted principals | Narrowed output |
+//! |---|---|---|
+//! | [`UserOrInternal`] | User or internal service acting for a user | [`UserOrInternalAuthorization`] |
+//! | [`UserOrInternalService`] | User or internal service, with optional acting user | [`UserOrInternalServiceAuthorization`] |
+//! | [`ActingUser`] | Any principal with an acting user | [`ActingUserAuthorization`] |
+//! | [`UserOnly`] | Directly authenticated user | [`MacroUserAuthentication`] |
+//! | [`BotOnly`] | Bot, with optional acting user | [`BotAuthentication`] |
+//! | [`InternalOnly`] | Internal service, with optional acting user | [`InternalAuthorization`] |
+//! | [`AnyPrincipal`] | Any authenticated principal | [`MacroAuthorization`] |
//!
-//! [`MacroAuthorizationExtractor`] and [`OptionalMacroAuthorizationExtractor`]
-//! detect internal headers before user credentials, validate the internal key,
-//! and set `is_internal_access` to `true`. Do not add
-//! [`InternalMacroAuthorizationExtractor`] merely to let an internal service
-//! call an endpoint: use it only when being internal-only is part of the
-//! endpoint's security contract.
+//! Both extractors reject requests that combine explicit credential types
+//! (internal key, bot token, or user query/bearer) with `400 Bad Request` rather
+//! than choosing a principal. Query and bearer credentials are one user type,
+//! while access-token cookies are ambient; an explicit credential wins over a
+//! cookie. Local-auth fallback and cookies are considered only when no explicit
+//! credential is present. A valid principal not admitted by the selected policy
+//! is rejected with `403 Forbidden`.
//!
//! These extractors authenticate the caller; they do not decide whether that
//! caller may act on a particular entity. Entity authorization and business
@@ -36,27 +41,41 @@ pub mod domain;
/// Inbound transport adapters backed by the authorization service.
#[cfg(feature = "axum")]
pub mod inbound;
-/// Adapters for validating credentials with external authentication systems.
-#[cfg(feature = "outbound")]
+/// Adapters for validating credentials with external authentication systems and PostgreSQL.
+#[cfg(any(feature = "outbound", feature = "postgres"))]
pub mod outbound;
pub use domain::{
+ bot_authorizer::BotAuthorizerService,
models::{
- InternalAuthConfig, InternalIdentityClaims, MacroAuthorizationError, ValidatedIdentity,
+ BotActingUserClaims, BotAuthentication, BotAuthorizationOwner, BotTokenAuthorization,
+ InternalAuthConfig, InternalIdentityClaims, MacroAuthorization, MacroAuthorizationError,
+ MacroUserAuthentication, ResolvedBotActingUser, ValidatedIdentity,
+ },
+ ports::{
+ BotAuthorizationRepo, BotAuthorizer, JwtValidator, MacroAuthorizationService,
+ NoBotAuthorizer,
},
- ports::{JwtValidator, MacroAuthorizationService},
service::MacroAuthorizationServiceImpl,
};
/// Service-backed Axum authorization extractors, state, headers, and rejection type.
#[allow(deprecated)]
#[cfg(feature = "axum")]
pub use inbound::{
- INTERNAL_API_KEY_HEADER, INTERNAL_FUSIONAUTH_USER_ID_HEADER,
- INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
- InternalMacroAuthorizationExtractor, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
- LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationExtractor,
- MacroAuthorizationRejection, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ ActingEntity, ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy,
+ BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,
+ BOT_FOR_ORGANIZATION_ID_HEADER, BOT_TOKEN_HEADER, BotOnly, INTERNAL_API_KEY_HEADER,
+ INTERNAL_FUSIONAUTH_USER_ID_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization, InternalEntity, InternalOnly,
+ LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
+ MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor, UserOnly, UserOrInternal, UserOrInternalAuthorization,
+ UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,
+ UserOrInternalServiceAuthorization,
};
/// JWT validation adapters for user-authenticated and internal-only services.
#[cfg(feature = "outbound")]
pub use outbound::{MacroAuthJwtValidator, NoopMacroAuthJwtValidator};
+/// PostgreSQL bot authorization repository and concrete authorizer.
+#[cfg(feature = "postgres")]
+pub use outbound::{PgBotAuthorizationRepo, PgBotAuthorizer};
diff --git a/crates/macro_authorization/src/outbound.rs b/crates/macro_authorization/src/outbound.rs
index 35c7ad56f1..59ddf0e0ca 100644
--- a/crates/macro_authorization/src/outbound.rs
+++ b/crates/macro_authorization/src/outbound.rs
@@ -1,11 +1,21 @@
//! Outbound authorization adapters.
/// JWT validation backed by the shared `macro_auth` implementation.
+#[cfg(feature = "outbound")]
pub mod macro_auth;
/// JWT validation adapter for internal-only services.
+#[cfg(feature = "outbound")]
pub mod noop;
+/// PostgreSQL facts for bot authorization.
+#[cfg(feature = "postgres")]
+pub mod pg_bot_authorization;
/// JWT validator backed by the shared `macro_auth` implementation.
+#[cfg(feature = "outbound")]
pub use macro_auth::MacroAuthJwtValidator;
/// JWT validator for services that only support internal authorization.
+#[cfg(feature = "outbound")]
pub use noop::NoopMacroAuthJwtValidator;
+/// PostgreSQL bot authorization repository and concrete authorizer.
+#[cfg(feature = "postgres")]
+pub use pg_bot_authorization::{PgBotAuthorizationRepo, PgBotAuthorizer};
diff --git a/crates/macro_authorization/src/outbound/pg_bot_authorization.rs b/crates/macro_authorization/src/outbound/pg_bot_authorization.rs
new file mode 100644
index 0000000000..6b621ce4e3
--- /dev/null
+++ b/crates/macro_authorization/src/outbound/pg_bot_authorization.rs
@@ -0,0 +1,205 @@
+//! PostgreSQL bot authorization facts.
+
+#[cfg(test)]
+mod test;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use thiserror::Error;
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{
+ BotActingUserClaims, BotAuthorizationOwner, BotTokenAuthorization, ResolvedBotActingUser,
+ },
+ ports::BotAuthorizationRepo,
+};
+
+/// PostgreSQL facts required by bot authorization policy.
+#[derive(Clone, Debug)]
+pub struct PgBotAuthorizationRepo {
+ pool: PgPool,
+}
+
+impl PgBotAuthorizationRepo {
+ /// Create a PostgreSQL bot authorization repository.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+/// Bot authorizer backed by PostgreSQL.
+pub type PgBotAuthorizer =
+ crate::domain::bot_authorizer::BotAuthorizerService<PgBotAuthorizationRepo>;
+
+/// PostgreSQL bot authorization repository error.
+#[derive(Debug, Error)]
+pub enum PgBotAuthorizationRepoError {
+ /// A database operation failed.
+ #[error("bot authorization database operation failed")]
+ Database(#[from] sqlx::Error),
+ /// Persisted bot ownership data violated its schema invariant.
+ #[error("invalid persisted bot ownership data")]
+ InvalidBotOwner,
+ /// Persisted user data could not be represented as a Macro user identifier.
+ #[error("invalid persisted user email")]
+ InvalidUserEmail,
+}
+
+#[derive(Debug)]
+struct BotTokenAuthorizationRow {
+ token_id: Uuid,
+ bot_id: Uuid,
+ kind: String,
+ owner_user_id: Option<String>,
+ team_id: Option<Uuid>,
+}
+
+impl TryFrom<BotTokenAuthorizationRow> for BotTokenAuthorization {
+ type Error = PgBotAuthorizationRepoError;
+
+ fn try_from(row: BotTokenAuthorizationRow) -> Result<Self, Self::Error> {
+ let owner = match (row.kind.as_str(), row.owner_user_id, row.team_id) {
+ ("owned", Some(user_id), None) => BotAuthorizationOwner::User { user_id },
+ ("owned", None, Some(team_id)) => BotAuthorizationOwner::Team { team_id },
+ ("system", None, None) => BotAuthorizationOwner::System,
+ _ => return Err(PgBotAuthorizationRepoError::InvalidBotOwner),
+ };
+
+ Ok(Self {
+ bot_id: bot_id::BotId::new_from_uuid(row.bot_id),
+ token_id: row.token_id,
+ owner,
+ })
+ }
+}
+
+#[derive(Debug)]
+struct ActingUserRow {
+ fusion_user_id: String,
+ email: String,
+ organization_id: Option<i32>,
+}
+
+impl TryFrom<ActingUserRow> for ResolvedBotActingUser {
+ type Error = PgBotAuthorizationRepoError;
+
+ fn try_from(row: ActingUserRow) -> Result<Self, Self::Error> {
+ Ok(Self {
+ macro_user_id: MacroUserIdStr::try_from_email(&row.email)
+ .map_err(|_| PgBotAuthorizationRepoError::InvalidUserEmail)?,
+ fusion_user_id: row.fusion_user_id,
+ organization_id: row.organization_id,
+ })
+ }
+}
+
+impl BotAuthorizationRepo for PgBotAuthorizationRepo {
+ type Err = PgBotAuthorizationRepoError;
+
+ async fn find_valid_bot_token(
+ &self,
+ token: &str,
+ ) -> Result<Option<BotTokenAuthorization>, Self::Err> {
+ let row = sqlx::query_as!(
+ BotTokenAuthorizationRow,
+ r#"
+ SELECT
+ bt.id AS token_id,
+ b.id AS bot_id,
+ b.kind,
+ b.owner_user_id,
+ b.team_id
+ FROM bot_tokens bt
+ JOIN bots b ON b.id = bt.bot_id
+ WHERE bt.token = $1
+ AND bt.revoked_at IS NULL
+ AND (bt.expires_at IS NULL OR bt.expires_at > now())
+ AND b.deleted_at IS NULL
+ "#,
+ token,
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ row.map(BotTokenAuthorization::try_from).transpose()
+ }
+
+ async fn mark_token_used(&self, token_id: Uuid) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ UPDATE bot_tokens
+ SET last_used_at = now()
+ WHERE id = $1
+ "#,
+ token_id,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn find_acting_user(
+ &self,
+ claims: &BotActingUserClaims,
+ ) -> Result<Option<ResolvedBotActingUser>, Self::Err> {
+ let row = if let Some(macro_user_id) = claims.user_id.as_deref() {
+ let Ok(macro_user_id) = MacroUserIdStr::try_from(macro_user_id) else {
+ return Ok(None);
+ };
+
+ sqlx::query_as!(
+ ActingUserRow,
+ r#"
+ SELECT
+ id AS fusion_user_id,
+ email,
+ "organizationId" AS "organization_id?"
+ FROM "User"
+ WHERE email = $1
+ "#,
+ macro_user_id.email_str(),
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ } else if let Some(fusion_user_id) = claims.fusion_user_id.as_deref() {
+ sqlx::query_as!(
+ ActingUserRow,
+ r#"
+ SELECT
+ id AS fusion_user_id,
+ email,
+ "organizationId" AS "organization_id?"
+ FROM "User"
+ WHERE id = $1
+ "#,
+ fusion_user_id,
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ } else {
+ None
+ };
+
+ row.map(ResolvedBotActingUser::try_from).transpose()
+ }
+
+ async fn user_has_team(&self, fusion_user_id: &str, team_id: Uuid) -> Result<bool, Self::Err> {
+ let has_team = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM team_user
+ WHERE user_id = $1 AND team_id = $2
+ ) AS "has_team!"
+ "#,
+ fusion_user_id,
+ team_id,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+
+ Ok(has_team)
+ }
+}
diff --git a/crates/macro_authorization/src/outbound/pg_bot_authorization/test.rs b/crates/macro_authorization/src/outbound/pg_bot_authorization/test.rs
new file mode 100644
index 0000000000..1c5daba0f8
--- /dev/null
+++ b/crates/macro_authorization/src/outbound/pg_bot_authorization/test.rs
@@ -0,0 +1,191 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+
+use super::*;
+use crate::domain::ports::BotAuthorizationRepo as _;
+
+const TOKEN: &str = "mbot_authorization_test_secret";
+const USER_ID: &str = "macro|[email protected]";
+const USER_EMAIL: &str = "[email protected]";
+const FUSION_USER_ID: &str = "fusion-bot-authorization";
+
+async fn insert_bot_token(
+ pool: &PgPool,
+ owner_user_id: Option<&str>,
+ revoked: bool,
+) -> (Uuid, Uuid) {
+ let bot_id = Uuid::new_v4();
+ let token_id = Uuid::new_v4();
+ sqlx::query!(
+ r#"
+ INSERT INTO bots (id, kind, owner_user_id, name, handle)
+ VALUES ($1, 'owned', $2, 'Authorization bot', $3)
+ "#,
+ bot_id,
+ owner_user_id,
+ format!("authorization-{bot_id}"),
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"
+ INSERT INTO bot_tokens (id, bot_id, token, revoked_at)
+ VALUES ($1, $2, $3, CASE WHEN $4 THEN now() ELSE NULL END)
+ "#,
+ token_id,
+ bot_id,
+ TOKEN,
+ revoked,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ (bot_id, token_id)
+}
+
+async fn insert_user(pool: &PgPool) {
+ let macro_user_id = Uuid::new_v4();
+ sqlx::query!(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $2, $3)
+ "#,
+ macro_user_id,
+ USER_EMAIL,
+ format!("stripe_{macro_user_id}"),
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"
+ INSERT INTO "User" (id, email, macro_user_id)
+ VALUES ($1, $2, $3)
+ "#,
+ FUSION_USER_ID,
+ USER_EMAIL,
+ macro_user_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn finds_valid_token_owner_and_marks_usage(pool: PgPool) {
+ let (bot_id, token_id) = insert_bot_token(&pool, Some(USER_ID), false).await;
+ let repo = PgBotAuthorizationRepo::new(pool.clone());
+
+ let token = repo
+ .find_valid_bot_token(TOKEN)
+ .await
+ .unwrap()
+ .expect("valid token");
+ assert_eq!(token.bot_id.as_uuid(), bot_id);
+ assert_eq!(token.token_id, token_id);
+ assert_eq!(
+ token.owner,
+ BotAuthorizationOwner::User {
+ user_id: USER_ID.to_string()
+ }
+ );
+
+ repo.mark_token_used(token_id).await.unwrap();
+ let last_used_at = sqlx::query_scalar!(
+ r#"SELECT last_used_at FROM bot_tokens WHERE id = $1"#,
+ token_id,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(last_used_at.is_some());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn rejects_unknown_revoked_expired_and_deleted_bot_tokens(pool: PgPool) {
+ let repo = PgBotAuthorizationRepo::new(pool.clone());
+ assert!(
+ repo.find_valid_bot_token("unknown")
+ .await
+ .unwrap()
+ .is_none()
+ );
+
+ insert_bot_token(&pool, Some(USER_ID), true).await;
+ assert!(repo.find_valid_bot_token(TOKEN).await.unwrap().is_none());
+
+ sqlx::query!(
+ "UPDATE bot_tokens SET revoked_at = NULL, expires_at = now() - interval '1 minute'"
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(repo.find_valid_bot_token(TOKEN).await.unwrap().is_none());
+
+ sqlx::query!("UPDATE bot_tokens SET expires_at = NULL")
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!("UPDATE bots SET deleted_at = now()")
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(repo.find_valid_bot_token(TOKEN).await.unwrap().is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn resolves_acting_users_by_macro_or_fusion_identifier(pool: PgPool) {
+ insert_user(&pool).await;
+ let repo = PgBotAuthorizationRepo::new(pool);
+
+ for claims in [
+ BotActingUserClaims {
+ user_id: Some(USER_ID.to_string()),
+ fusion_user_id: Some("ignored-by-lookup".to_string()),
+ organization_id: None,
+ },
+ BotActingUserClaims {
+ user_id: None,
+ fusion_user_id: Some(FUSION_USER_ID.to_string()),
+ organization_id: None,
+ },
+ ] {
+ let user = repo
+ .find_acting_user(&claims)
+ .await
+ .unwrap()
+ .expect("acting user");
+ assert_eq!(user.macro_user_id.as_ref(), USER_ID);
+ assert_eq!(user.fusion_user_id, FUSION_USER_ID);
+ assert_eq!(user.organization_id, None);
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn checks_current_team_membership(pool: PgPool) {
+ insert_user(&pool).await;
+ let team_id = Uuid::new_v4();
+ sqlx::query!(
+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Authorization team', $2)"#,
+ team_id,
+ FUSION_USER_ID,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"
+ INSERT INTO team_user (user_id, team_id, team_role)
+ VALUES ($1, $2, 'member'::team_role)
+ "#,
+ FUSION_USER_ID,
+ team_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let repo = PgBotAuthorizationRepo::new(pool);
+ assert!(repo.user_has_team(FUSION_USER_ID, team_id).await.unwrap());
+}
diff --git a/crates/mcp_client/src/inbound/axum_router.rs b/crates/mcp_client/src/inbound/axum_router.rs
index 82d98d56ed..8561a0bcf3 100644
--- a/crates/mcp_client/src/inbound/axum_router.rs
+++ b/crates/mcp_client/src/inbound/axum_router.rs
@@ -10,7 +10,7 @@ use axum::{
routing::{delete, get, post, put},
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use model_error_response::ErrorResponse;
use serde::{Deserialize, Serialize};
@@ -244,7 +244,7 @@ impl IntoResponse for McpHandlerErr {
#[tracing::instrument(skip_all, err)]
pub async fn list_servers<S, O, Auth>(
State(state): State<McpRouterState<S, O, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<Vec<ServerResponse>>, McpHandlerErr>
where
S: McpServerStore,
@@ -252,9 +252,10 @@ where
Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
{
+ let user = &authorization.authorization.user;
let records = state
.store
- .list(&macro_user_id)
+ .list(&user.macro_user_id)
.await
.map_err(anyhow::Error::from)?;
@@ -279,7 +280,7 @@ where
#[tracing::instrument(skip_all, err)]
pub async fn add_server<S, O, Auth>(
State(state): State<McpRouterState<S, O, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(body): Json<AddServerRequest>,
) -> Result<(StatusCode, Json<ServerResponse>), McpHandlerErr>
where
@@ -288,8 +289,9 @@ where
Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
{
+ let user = &authorization.authorization.user;
let record = McpServerRecord {
- user_id: macro_user_id,
+ user_id: user.macro_user_id.clone(),
url: body.url,
server_name: body.server_name,
credentials: None,
@@ -325,7 +327,7 @@ where
#[tracing::instrument(skip_all, err)]
pub async fn update_server<S, O, Auth>(
State(state): State<McpRouterState<S, O, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(body): Json<UpdateServerRequest>,
) -> Result<Json<ServerResponse>, McpHandlerErr>
where
@@ -334,9 +336,10 @@ where
Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
{
+ let user = &authorization.authorization.user;
let mut record = state
.store
- .load(&macro_user_id, &body.url)
+ .load(&user.macro_user_id, &body.url)
.await
.map_err(anyhow::Error::from)?
.ok_or(McpHandlerErr::NotFound)?;
@@ -373,7 +376,7 @@ where
#[tracing::instrument(skip_all, err)]
pub async fn delete_server<S, O, Auth>(
State(state): State<McpRouterState<S, O, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Query(params): Query<DeleteServerParams>,
) -> Result<StatusCode, McpHandlerErr>
where
@@ -382,9 +385,10 @@ where
Auth: MacroAuthorizationService,
anyhow::Error: From<S::Err>,
{
+ let user = &authorization.authorization.user;
state
.store
- .delete(&macro_user_id, &params.url)
+ .delete(&user.macro_user_id, &params.url)
.await
.map_err(anyhow::Error::from)?;
@@ -407,7 +411,7 @@ where
#[tracing::instrument(skip_all, err)]
pub async fn start_auth<S, O, Auth>(
State(state): State<McpRouterState<S, O, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(body): Json<StartAuthRequest>,
) -> Result<Json<StartAuthResponse>, McpHandlerErr>
where
@@ -415,9 +419,10 @@ where
O: OAuthClient,
Auth: MacroAuthorizationService,
{
+ let user = &authorization.authorization.user;
let authorization_url = state
.oauth
- .start_authorization(&macro_user_id, &body.server_url, &body.server_name)
+ .start_authorization(&user.macro_user_id, &body.server_url, &body.server_name)
.await?;
Ok(Json(StartAuthResponse { authorization_url }))
diff --git a/crates/memory/src/inbound/axum_router.rs b/crates/memory/src/inbound/axum_router.rs
index f2f29476ce..5b1fee8d31 100644
--- a/crates/memory/src/inbound/axum_router.rs
+++ b/crates/memory/src/inbound/axum_router.rs
@@ -7,7 +7,7 @@ use axum::{
routing::get,
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use serde::Serialize;
use std::sync::Arc;
@@ -83,11 +83,16 @@ where
),
tag = "memory"
)]
-#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(
+ skip(service, user),
+ fields(actor = %user.acting_entity())
+)]
pub async fn get_memory_handler<T: MemoryService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Response {
+ let user = user.authorization.user;
+
match service.get_or_generate_memory(user.macro_user_id).await {
Ok(Some(memory)) => Json(MemoryResponse { memory }).into_response(),
Ok(None) => StatusCode::NOT_FOUND.into_response(),
diff --git a/crates/notification/src/inbound/http/device.rs b/crates/notification/src/inbound/http/device.rs
index 58852913a1..bd546db4ca 100644
--- a/crates/notification/src/inbound/http/device.rs
+++ b/crates/notification/src/inbound/http/device.rs
@@ -5,7 +5,7 @@ use axum::{
extract::State,
routing::{delete, post},
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model_error_response::ErrorResponse;
use reqwest::StatusCode;
@@ -28,12 +28,16 @@ where
#[tracing::instrument(skip(state, user, req))]
async fn register_device<S: NotificationReader, Auth: MacroAuthorizationService>(
State(state): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<DeviceRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
state
.inner
- .register_device(user.macro_user_id, &req.token, &req.device_type)
+ .register_device(
+ user.authorization.user.macro_user_id,
+ &req.token,
+ &req.device_type,
+ )
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to register device");
@@ -52,7 +56,7 @@ async fn register_device<S: NotificationReader, Auth: MacroAuthorizationService>
#[tracing::instrument(skip(state, _macro_user, req))]
async fn unregister_device<S: NotificationReader, Auth: MacroAuthorizationService>(
State(state): State<NotificationRouterState<S, Auth>>,
- _macro_user: MacroAuthorizationExtractor<Auth>,
+ _macro_user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<DeviceRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
state
diff --git a/crates/notification/src/inbound/http/mod.rs b/crates/notification/src/inbound/http/mod.rs
index 02132ef12a..7c5eb64463 100644
--- a/crates/notification/src/inbound/http/mod.rs
+++ b/crates/notification/src/inbound/http/mod.rs
@@ -13,7 +13,7 @@ use axum::{
};
use hmac::Hmac;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
@@ -223,7 +223,7 @@ pub async fn bulk_get_by_event_item_ids<
T: Serialize + DeserializeOwned + Send,
>(
State(service): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Query(Params { limit, done, seen }): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
Json(req): Json<BulkGetByEventItemIdsRequest>,
@@ -231,7 +231,7 @@ pub async fn bulk_get_by_event_item_ids<
let result = service
.inner
.get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {
- user_id: user.macro_user_id,
+ user_id: user.authorization.user.macro_user_id,
event_item_ids: &req.event_item_ids,
limit,
cursor: cursor.into_query(CreatedAt, ()),
@@ -282,10 +282,16 @@ pub struct NotificationBulkRequest {
)]
pub async fn bulk_mark_seen<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
- bulk_update(&service, user.macro_user_id, &req, NotificationStatus::Seen).await
+ bulk_update(
+ &service,
+ user.authorization.user.macro_user_id,
+ &req,
+ NotificationStatus::Seen,
+ )
+ .await
}
/// Mark notifications as done.
@@ -303,12 +309,12 @@ pub async fn bulk_mark_seen<S: NotificationReader, Auth: MacroAuthorizationServi
)]
pub async fn bulk_mark_done<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
bulk_update(
&service,
- user.macro_user_id,
+ user.authorization.user.macro_user_id,
&req,
NotificationStatus::Done(true),
)
@@ -330,12 +336,12 @@ pub async fn bulk_mark_done<S: NotificationReader, Auth: MacroAuthorizationServi
)]
pub async fn bulk_mark_undone<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
bulk_update(
&service,
- user.macro_user_id,
+ user.authorization.user.macro_user_id,
&req,
NotificationStatus::Done(false),
)
@@ -394,7 +400,7 @@ pub async fn get_by_event_item_id<
T: Serialize + DeserializeOwned + Send,
>(
State(service): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(EventItemIdPath { event_item_id }): Path<EventItemIdPath>,
Query(Params { limit, done, seen }): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
@@ -402,7 +408,7 @@ pub async fn get_by_event_item_id<
let result = service
.inner
.get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {
- user_id: user.macro_user_id,
+ user_id: user.authorization.user.macro_user_id,
event_item_ids: &[event_item_id],
limit,
cursor: cursor.into_query(CreatedAt, ()),
@@ -452,12 +458,12 @@ pub async fn get_notification_by_id<
T: Serialize + DeserializeOwned + Send,
>(
State(service): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,
) -> Result<Json<UserNotificationRow<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let result = service
.inner
- .get_user_notification_by_id::<T>(user.macro_user_id, notification_id)
+ .get_user_notification_by_id::<T>(user.authorization.user.macro_user_id, notification_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get user notification by id");
@@ -498,12 +504,12 @@ pub async fn get_notification_by_id<
)]
pub async fn delete_notification<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
- .delete_user_notification(user.macro_user_id, notification_id)
+ .delete_user_notification(user.authorization.user.macro_user_id, notification_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to delete user notification");
@@ -533,12 +539,15 @@ pub async fn delete_notification<S: NotificationReader, Auth: MacroAuthorization
)]
pub async fn bulk_delete_notifications<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
- .bulk_delete_user_notifications(user.macro_user_id, &req.notification_ids)
+ .bulk_delete_user_notifications(
+ user.authorization.user.macro_user_id,
+ &req.notification_ids,
+ )
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to delete user notifications");
diff --git a/crates/notification/src/inbound/http/preferences.rs b/crates/notification/src/inbound/http/preferences.rs
index 24af10000d..33cb21c501 100644
--- a/crates/notification/src/inbound/http/preferences.rs
+++ b/crates/notification/src/inbound/http/preferences.rs
@@ -6,8 +6,7 @@ use axum::{
http::{StatusCode, uri::PathAndQuery},
response::Html,
};
-use cowlike::CowLike;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use macro_service_urls::NotificationServiceUrl;
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
@@ -48,12 +47,12 @@ pub async fn get_notification_type_preferences<
Auth: MacroAuthorizationService,
>(
State(state): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<GetNotificationTypePreferencesResponse>, (StatusCode, Json<ErrorResponse<'static>>)>
{
let disabled = state
.inner
- .get_disabled_notification_types(user.macro_user_id)
+ .get_disabled_notification_types(user.authorization.user.macro_user_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get notification type preferences");
@@ -90,14 +89,14 @@ pub async fn get_notification_type_preferences<
)]
pub async fn disable_notification_type<S: NotificationReader, Auth: MacroAuthorizationService>(
State(state): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(NotificationEventTypePath {
notification_event_type,
}): Path<NotificationEventTypePath>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
disable_notification_type_inner(
&state,
- user.macro_user_id.copied(),
+ user.authorization.user.macro_user_id,
notification_event_type.as_str(),
)
.await
@@ -221,14 +220,17 @@ async fn disable_notification_type_inner<S: NotificationReader, Auth: MacroAutho
)]
pub async fn enable_notification_type<S: NotificationReader, Auth: MacroAuthorizationService>(
State(state): State<NotificationRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(NotificationEventTypePath {
notification_event_type,
}): Path<NotificationEventTypePath>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
state
.inner
- .enable_notification_type(user.macro_user_id, &notification_event_type)
+ .enable_notification_type(
+ user.authorization.user.macro_user_id,
+ &notification_event_type,
+ )
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to enable notification type");
diff --git a/crates/onboarding/src/inbound/axum_router.rs b/crates/onboarding/src/inbound/axum_router.rs
index cb8e0d5097..fc005aca02 100644
--- a/crates/onboarding/src/inbound/axum_router.rs
+++ b/crates/onboarding/src/inbound/axum_router.rs
@@ -11,7 +11,7 @@ use axum::{
routing::{get, post},
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use serde::Deserialize;
use std::sync::Arc;
@@ -87,12 +87,15 @@ fn error_response(e: OnboardingError) -> Response {
),
tag = "onboarding"
)]
-#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn get_state_handler<T: OnboardingService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Response {
- match service.get_state(user.macro_user_id).await {
+ match service
+ .get_state(user.authorization.user.macro_user_id)
+ .await
+ {
Ok(state) => Json(state).into_response(),
Err(e) => error_response(e),
}
@@ -110,13 +113,16 @@ pub async fn get_state_handler<T: OnboardingService, Auth: MacroAuthorizationSer
),
tag = "onboarding"
)]
-#[tracing::instrument(skip(service, user, body), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(skip(service, user, body), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn complete_handler<T: OnboardingService, Auth: MacroAuthorizationService>(
State(service): State<Arc<T>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(body): Json<CompleteOnboardingRequest>,
) -> Response {
- match service.complete(user.macro_user_id, body.skipped).await {
+ match service
+ .complete(user.authorization.user.macro_user_id, body.skipped)
+ .await
+ {
Ok(row) => Json(row).into_response(),
Err(e) => error_response(e),
}
diff --git a/crates/projects/src/inbound/axum_router/create_project.rs b/crates/projects/src/inbound/axum_router/create_project.rs
index 94c8ecd933..dca4c51d8b 100644
--- a/crates/projects/src/inbound/axum_router/create_project.rs
+++ b/crates/projects/src/inbound/axum_router/create_project.rs
@@ -5,7 +5,7 @@ use entity_access::{
domain::{models::EditAccessLevel, ports::EntityAccessService},
inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2,
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model::project::{request::CreateProjectRequest, response::CreateProjectResponse};
use super::ProjectRouterState;
@@ -23,10 +23,14 @@ use crate::domain::{models::ProjectError, ports::ProjectService};
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, project), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, project),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn create_project_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateProjectRequest, Svc, Auth>,
) -> Result<Json<CreateProjectResponse>, ProjectError>
where
@@ -36,7 +40,10 @@ where
{
let data = state
.service
- .create_project(user.macro_user_id, project.into_inner())
+ .create_project(
+ user.authorization.user.macro_user_id.clone(),
+ project.into_inner(),
+ )
.await?;
Ok(Json(CreateProjectResponse { error: false, data }))
diff --git a/crates/projects/src/inbound/axum_router/delete_project.rs b/crates/projects/src/inbound/axum_router/delete_project.rs
index 0048010526..8c51b34c96 100644
--- a/crates/projects/src/inbound/axum_router/delete_project.rs
+++ b/crates/projects/src/inbound/axum_router/delete_project.rs
@@ -5,7 +5,7 @@ use entity_access::{
domain::{models::OwnerAccessLevel, ports::EntityAccessService},
inbound::axum_extractors::ProjectAccessLevelExtractor,
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model::project::BasicProject;
use model::response::{GenericSuccessResponse, SuccessResponse, TypedSuccessResponse};
use serde::{Deserialize, Serialize};
@@ -40,10 +40,14 @@ pub type ProjectDeleteResponse = TypedSuccessResponse<ProjectDeleteResponseData>
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, access, project), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, access, project),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn delete_project_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
access: ProjectAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
project: Extension<BasicProject>,
) -> Result<Json<ProjectDeleteResponse>, ProjectError>
@@ -57,7 +61,7 @@ where
.soft_delete_project(
access.entity_access_receipt,
project.0,
- user.macro_user_id.to_string(),
+ user.authorization.user.macro_user_id.to_string(),
)
.await?;
@@ -85,10 +89,14 @@ where
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, access, project), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, access, project),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn permanently_delete_project_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
access: ProjectAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
Extension(project): Extension<BasicProject>,
) -> Result<Json<SuccessResponse>, ProjectError>
diff --git a/crates/projects/src/inbound/axum_router/edit_project.rs b/crates/projects/src/inbound/axum_router/edit_project.rs
index 585c1d0c51..e5d2e7313b 100644
--- a/crates/projects/src/inbound/axum_router/edit_project.rs
+++ b/crates/projects/src/inbound/axum_router/edit_project.rs
@@ -5,7 +5,7 @@ use entity_access::{
domain::{models::EditAccessLevel, ports::EntityAccessService},
inbound::axum_extractors::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractorV2},
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model::{
project::{BasicProject, request::PatchProjectRequestV2},
response::{GenericSuccessResponse, SuccessResponse},
@@ -28,10 +28,14 @@ use crate::domain::{models::ProjectError, ports::ProjectService};
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, access, project, body), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, access, project, body),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn edit_project_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
access: ProjectAccessLevelExtractor<EditAccessLevel, Svc, Auth>,
project: Extension<BasicProject>,
body: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, PatchProjectRequestV2, Svc, Auth>,
diff --git a/crates/projects/src/inbound/axum_router/get_batch_preview.rs b/crates/projects/src/inbound/axum_router/get_batch_preview.rs
index b154c288b3..75504fd110 100644
--- a/crates/projects/src/inbound/axum_router/get_batch_preview.rs
+++ b/crates/projects/src/inbound/axum_router/get_batch_preview.rs
@@ -2,7 +2,9 @@
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationService, OptionalMacroAuthorizationExtractor};
+use macro_authorization::{
+ MacroAuthorizationService, OptionalMacroAuthorizationExtractor, UserOrInternalService,
+};
use model::project::{
request::GetBatchProjectPreviewRequest, response::GetBatchProjectPreviewResponse,
};
@@ -22,10 +24,14 @@ use crate::domain::{models::ProjectError, ports::ProjectService};
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, request), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, request),
+ fields(actor = tracing::field::Empty),
+ err
+)]
pub async fn get_batch_preview_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: OptionalMacroAuthorizationExtractor<Auth>,
+ user: OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService>,
Json(request): Json<GetBatchProjectPreviewRequest>,
) -> Result<Json<GetBatchProjectPreviewResponse>, ProjectError>
where
@@ -33,9 +39,17 @@ where
Svc: EntityAccessService,
Auth: MacroAuthorizationService,
{
+ if let Some(actor) = user.acting_entity() {
+ tracing::Span::current().record("actor", tracing::field::display(actor));
+ }
+ let user_id = user
+ .authorization
+ .as_ref()
+ .and_then(|authorization| authorization.acting_user())
+ .map(|user| user.macro_user_id.clone());
let previews = state
.service
- .get_batch_preview(user.macro_user_id, request.project_ids)
+ .get_batch_preview(user_id, request.project_ids)
.await?;
Ok(Json(GetBatchProjectPreviewResponse { previews }))
}
diff --git a/crates/projects/src/inbound/axum_router/get_project.rs b/crates/projects/src/inbound/axum_router/get_project.rs
index 837daeed54..48b2f50ae0 100644
--- a/crates/projects/src/inbound/axum_router/get_project.rs
+++ b/crates/projects/src/inbound/axum_router/get_project.rs
@@ -5,7 +5,7 @@ use entity_access::{
domain::{models::ViewAccessLevel, ports::EntityAccessService},
inbound::axum_extractors::ProjectAccessLevelExtractor,
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model::project::response::{GetProjectContentResponse, GetProjectResponse};
use super::ProjectRouterState;
@@ -22,10 +22,14 @@ use crate::domain::{models::ProjectError, ports::ProjectService};
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, access), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, access),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn get_project_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
access: ProjectAccessLevelExtractor<ViewAccessLevel, Svc, Auth>,
) -> Result<Json<GetProjectResponse>, ProjectError>
where
@@ -52,10 +56,14 @@ where
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, access), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, access),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn get_project_content_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
access: ProjectAccessLevelExtractor<ViewAccessLevel, Svc, Auth>,
) -> Result<Json<GetProjectContentResponse>, ProjectError>
where
diff --git a/crates/projects/src/inbound/axum_router/get_projects.rs b/crates/projects/src/inbound/axum_router/get_projects.rs
index 3f4a9f4772..cdd3842f0e 100644
--- a/crates/projects/src/inbound/axum_router/get_projects.rs
+++ b/crates/projects/src/inbound/axum_router/get_projects.rs
@@ -2,7 +2,7 @@
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model::{project::response::GetProjectsResponse, response::TypedSuccessResponse};
use super::ProjectRouterState;
@@ -22,17 +22,24 @@ pub type PendingProjectsResponse = TypedSuccessResponse<Vec<model::project::Pend
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn get_projects_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<GetProjectsResponse>, ProjectError>
where
T: ProjectService,
Svc: EntityAccessService,
Auth: MacroAuthorizationService,
{
- let projects = state.service.list_projects(user.macro_user_id).await?;
+ let projects = state
+ .service
+ .list_projects(user.authorization.user.macro_user_id.clone())
+ .await?;
Ok(Json(GetProjectsResponse {
error: false,
data: projects,
@@ -50,10 +57,14 @@ where
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn get_pending_projects_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<PendingProjectsResponse>, ProjectError>
where
T: ProjectService,
@@ -62,7 +73,7 @@ where
{
let projects = state
.service
- .list_pending_projects(user.macro_user_id)
+ .list_pending_projects(user.authorization.user.macro_user_id.clone())
.await?;
Ok(Json(PendingProjectsResponse {
error: false,
diff --git a/crates/projects/src/inbound/axum_router/project_permission.rs b/crates/projects/src/inbound/axum_router/project_permission.rs
index 806d8b3929..4d4bf1a004 100644
--- a/crates/projects/src/inbound/axum_router/project_permission.rs
+++ b/crates/projects/src/inbound/axum_router/project_permission.rs
@@ -8,7 +8,7 @@ use entity_access::{
},
inbound::axum_extractors::ProjectAccessLevelExtractor,
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_permissions::share_permission::{SharePermissionV2, access_level::AccessLevel};
use super::ProjectRouterState;
@@ -27,10 +27,14 @@ use crate::domain::{models::ProjectError, ports::ProjectService};
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, access), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, access),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn get_project_permissions_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
access: ProjectAccessLevelExtractor<OwnerAccessLevel, Svc, Auth>,
) -> Result<Json<SharePermissionV2>, ProjectError>
where
@@ -59,10 +63,14 @@ where
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, access), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, access),
+ fields(user_id = ?user.authorization.user.macro_user_id),
+ err
+)]
pub async fn get_project_access_level_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
access: ProjectAccessLevelExtractor<ViewAccessLevel, Svc, Auth>,
) -> Result<Json<AccessLevel>, ProjectError>
where
diff --git a/crates/projects/src/inbound/axum_router/upload_folder.rs b/crates/projects/src/inbound/axum_router/upload_folder.rs
index f6976a4d8b..ced19f8726 100644
--- a/crates/projects/src/inbound/axum_router/upload_folder.rs
+++ b/crates/projects/src/inbound/axum_router/upload_folder.rs
@@ -5,7 +5,9 @@ use entity_access::domain::{
models::{EditAccessLevel, EntityType},
ports::EntityAccessService,
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal, UserOrInternalCaller,
+};
use model::{
folder::{UploadFolderRequest, UploadFolderResponseData},
response::TypedSuccessResponse,
@@ -35,10 +37,14 @@ pub type UploadExtractFolderResponse = TypedSuccessResponse<UploadExtractFolderR
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, request), fields(user_id=%user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, request),
+ fields(user_id = %user.authorization.user.macro_user_id),
+ err
+)]
pub async fn upload_folder_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<UploadFolderRequest>,
) -> Result<Json<UploadFolderResponse>, ProjectError>
where
@@ -49,7 +55,11 @@ where
ensure_parent_edit_access(&state, &user, request.parent_id.as_deref()).await?;
let data = state
.service
- .upload_folder(user.macro_user_id, user.is_internal_access, request)
+ .upload_folder(
+ user.authorization.user.macro_user_id.clone(),
+ user.authorization.caller == UserOrInternalCaller::Internal,
+ request,
+ )
.await?;
Ok(Json(UploadFolderResponse { error: false, data }))
@@ -67,10 +77,14 @@ where
(status = 500, body = model::response::GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, request), fields(user_id=%user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, request),
+ fields(user_id = %user.authorization.user.macro_user_id),
+ err
+)]
pub async fn upload_extract_folder_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<UploadExtractFolderRequest>,
) -> Result<Json<UploadExtractFolderResponse>, ProjectError>
where
@@ -81,7 +95,7 @@ where
ensure_parent_edit_access(&state, &user, request.parent_id.as_deref()).await?;
let data = state
.service
- .create_upload_extract_request(user.macro_user_id, request)
+ .create_upload_extract_request(user.authorization.user.macro_user_id.clone(), request)
.await?;
Ok(Json(UploadExtractFolderResponse { error: false, data }))
@@ -89,16 +103,20 @@ where
async fn ensure_parent_edit_access<T, Svc, Auth>(
state: &ProjectRouterState<T, Svc, Auth>,
- user: &MacroAuthorizationExtractor<Auth>,
+ user: &MacroAuthorizationExtractor<Auth, UserOrInternal>,
parent_id: Option<&str>,
) -> Result<(), ProjectError>
where
Svc: EntityAccessService,
{
- let Some(parent_id) = parent_id.filter(|_| !user.is_internal_access) else {
+ if user.authorization.caller == UserOrInternalCaller::Internal {
+ return Ok(());
+ }
+ let Some(parent_id) = parent_id else {
return Ok(());
};
+ let user = &user.authorization.user;
let _receipt = state
.access_service
.generate_entity_access_receipt::<EditAccessLevel>(
@@ -113,10 +131,14 @@ where
}
/// Mark a project tree as uploaded. This handler is mounted only on the internal router.
-#[tracing::instrument(skip(state, user, request), fields(user_id=%user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(state, user, request),
+ fields(user_id = %user.authorization.user.macro_user_id),
+ err
+)]
pub async fn mark_uploaded_handler<T, Svc, Auth>(
State(state): State<ProjectRouterState<T, Svc, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<MarkProjectUploadedRequest>,
) -> Result<Json<MarkProjectUploadedResponse>, ProjectError>
where
diff --git a/crates/properties/src/inbound/axum_router/definitions.rs b/crates/properties/src/inbound/axum_router/definitions.rs
index 15d3eb947c..07fa6b572d 100644
--- a/crates/properties/src/inbound/axum_router/definitions.rs
+++ b/crates/properties/src/inbound/axum_router/definitions.rs
@@ -7,7 +7,7 @@ use axum::{
response::{IntoResponse, Response},
};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_properties::EntityType;
use models_properties::api::CreatePropertyDefinitionRequest;
use models_properties::service::property_definition::PropertyDefinition;
@@ -105,12 +105,10 @@ pub async fn list_properties<
>(
Query(query): Query<ListPropertiesQuery>,
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
) -> Result<Json<Vec<PropertyDefinitionResponse>>, ListPropertiesErr> {
+ let user = user.authorization.user.macro_user_id;
let callers_team = team.entity_access_receipt.as_ref();
// Determine query parameters based on scope. The team receipt and user id are
@@ -207,13 +205,11 @@ pub async fn create_property_definition<
Auth: MacroAuthorizationService,
>(
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
Json(request): Json<CreatePropertyDefinitionRequest>,
) -> Result<(StatusCode, Json<PropertyDefinition>), CreatePropertyDefinitionErr> {
+ let user = user.authorization.user.macro_user_id;
tracing::info!(scope = ?request.scope, "creating property definition");
// The owner is derived in the service from the authenticated caller and
@@ -274,12 +270,10 @@ pub async fn delete_property_definition<
>(
Path(property_uuid): Path<Uuid>,
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
) -> Result<Response, DeletePropertyDefinitionError> {
+ let user = user.authorization.user.macro_user_id;
tracing::info!("deleting property definition");
state
diff --git a/crates/properties/src/inbound/axum_router/entities.rs b/crates/properties/src/inbound/axum_router/entities.rs
index 4fd85e9422..b6f0b62754 100644
--- a/crates/properties/src/inbound/axum_router/entities.rs
+++ b/crates/properties/src/inbound/axum_router/entities.rs
@@ -15,7 +15,7 @@ use axum::{
};
use entity_access::domain::models::EditAccessLevel;
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_properties::api::{PropertyTargetEntityType, PropertyTargetReference, SetPropertyValue};
use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;
use serde::{Deserialize, Serialize};
@@ -250,12 +250,10 @@ pub async fn get_bulk_entity_properties<
Auth: MacroAuthorizationService,
>(
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<BulkEntityPropertiesRequest>,
) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {
+ let user = user.authorization.user.macro_user_id;
// The public endpoint requires explicit property IDs. An empty property_ids
// means "no properties requested", so return early with empty result.
if request.entities.is_empty() || request.property_ids.is_empty() {
@@ -795,14 +793,12 @@ pub async fn bulk_update_entities_property_options<
Auth: MacroAuthorizationService,
>(
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<BulkUpdateEntitiesPropertyOptionsRequest>,
) -> Result<Json<BulkUpdateEntitiesPropertyOptionsResponse>, BulkUpdateEntitiesPropertyOptionsErr> {
tracing::info!("bulk updating property options across entities");
+ let user = user.authorization.user.macro_user_id;
validate_bulk_entities_option_request(&request)?;
let BulkUpdateEntitiesPropertyOptionsRequest {
@@ -937,11 +933,9 @@ pub async fn delete_entity_property<
>(
Path(entity_property_uuid): Path<Uuid>,
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<StatusCode, DeleteEntityPropertyErr> {
+ let user = user.authorization.user.macro_user_id;
tracing::info!("removing entity property");
// The entity this property is attached to is only known after a lookup, so
diff --git a/crates/properties/src/inbound/axum_router/extract.rs b/crates/properties/src/inbound/axum_router/extract.rs
index bafb1f5d40..58d68468a5 100644
--- a/crates/properties/src/inbound/axum_router/extract.rs
+++ b/crates/properties/src/inbound/axum_router/extract.rs
@@ -21,7 +21,7 @@ use entity_access::domain::models::{
use entity_access::domain::ports::EntityAccessService;
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationService,
- OptionalMacroAuthorizationExtractor,
+ OptionalMacroAuthorizationExtractor, UserOrInternal, UserOrInternalService,
};
use macro_user_id::user_id::MacroUserIdStr;
use models_properties::api::PropertyTargetEntityType;
@@ -177,13 +177,18 @@ where
) -> Result<Self, Self::Rejection> {
let params = entity_path_params(parts).await?;
- let OptionalMacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- } = parts
- .extract_with_state::<OptionalMacroAuthorizationExtractor<Auth>, _>(state)
+ let authorization = parts
+ .extract_with_state::<
+ OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService>,
+ _,
+ >(state)
.await
.map_err(ReceiptRejection::from)?;
+ let user = authorization
+ .authorization
+ .as_ref()
+ .and_then(|authorization| authorization.acting_user())
+ .map(|user| user.macro_user_id.clone());
let receipt = mint_view_receipt(
state.entity_access_service.as_ref(),
@@ -216,14 +221,12 @@ where
) -> Result<Self, Self::Rejection> {
let params = entity_path_params(parts).await?;
- let MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- } = parts
- .extract_with_state::<MacroAuthorizationExtractor<Auth>, _>(state)
+ let authorization = parts
+ .extract_with_state::<MacroAuthorizationExtractor<Auth, UserOrInternal>, _>(state)
.await
.map_err(ReceiptRejection::from)?;
+ let user = authorization.authorization.user.macro_user_id;
let receipt = mint_authenticated_receipt::<EditAccessLevel, A>(
state.entity_access_service.as_ref(),
&user,
diff --git a/crates/properties/src/inbound/axum_router/options.rs b/crates/properties/src/inbound/axum_router/options.rs
index 709f9c0932..ceded5f303 100644
--- a/crates/properties/src/inbound/axum_router/options.rs
+++ b/crates/properties/src/inbound/axum_router/options.rs
@@ -7,7 +7,7 @@ use axum::{
response::{IntoResponse, Response},
};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_properties::api::{AddPropertyOptionRequest, UpdatePropertyOptionRequest};
use models_properties::service::property_option::PropertyOption;
use thiserror::Error;
@@ -63,12 +63,10 @@ pub async fn get_property_options<
>(
Path(property_uuid): Path<Uuid>,
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
) -> Result<Json<Vec<PropertyOption>>, GetPropertyOptionsErr> {
+ let user = user.authorization.user.macro_user_id;
tracing::info!("retrieving property options");
let options = state
@@ -133,13 +131,11 @@ pub async fn add_property_option<
>(
Path(property_uuid): Path<Uuid>,
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
Json(request): Json<AddPropertyOptionRequest>,
) -> Result<(StatusCode, Json<PropertyOption>), AddPropertyOptionErr> {
+ let user = user.authorization.user.macro_user_id;
tracing::info!("adding property option");
let option = state
@@ -208,13 +204,11 @@ pub async fn update_property_option<
>(
Path((def_uuid, option_uuid)): Path<(Uuid, Uuid)>,
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
Json(request): Json<UpdatePropertyOptionRequest>,
) -> Result<(StatusCode, Json<PropertyOption>), UpdatePropertyOptionErr> {
+ let user = user.authorization.user.macro_user_id;
let updated = state
.properties_service
.update_property_option(
@@ -278,12 +272,10 @@ pub async fn delete_property_option<
>(
Path((def_uuid, option_uuid)): Path<(Uuid, Uuid)>,
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
) -> Result<StatusCode, DeletePropertyOptionErr> {
+ let user = user.authorization.user.macro_user_id;
tracing::info!("deleting property option");
state
diff --git a/crates/properties/src/inbound/axum_router/tags.rs b/crates/properties/src/inbound/axum_router/tags.rs
index 903ac52cbe..2860a0e56c 100644
--- a/crates/properties/src/inbound/axum_router/tags.rs
+++ b/crates/properties/src/inbound/axum_router/tags.rs
@@ -6,7 +6,7 @@ use axum::{
response::{IntoResponse, Response},
};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_properties::api::{PropertyDefinitionDetailResponse, PropertyOptionResponse};
use serde::{Deserialize, Serialize};
use thiserror::Error;
@@ -109,12 +109,10 @@ pub async fn list_tags<
Auth: MacroAuthorizationService,
>(
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
) -> Result<Json<Vec<TagSetResponse>>, TagsError> {
+ let user = user.authorization.user.macro_user_id;
let sets = state
.properties_service
.list_tag_sets(&user, team.entity_access_receipt.as_ref())
@@ -143,13 +141,11 @@ pub async fn ensure_tag_set<
Auth: MacroAuthorizationService,
>(
State(state): State<PropertiesRouterState<S, A, Auth>>,
- MacroAuthorizationExtractor {
- macro_user_id: user,
- ..
- }: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: PropertyTeamExtractor<A, Auth>,
Json(request): Json<EnsureTagSetRequest>,
) -> Result<Json<TagSetResponse>, TagsError> {
+ let user = user.authorization.user.macro_user_id;
let set = state
.properties_service
.ensure_tag_set(
diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rs
index d3d7b29afb..65914f5422 100644
--- a/crates/properties/src/inbound/axum_router/test.rs
+++ b/crates/properties/src/inbound/axum_router/test.rs
@@ -17,7 +17,7 @@ use entity_access::domain::{
use macro_authorization::{
INTERNAL_API_KEY_HEADER, InternalAuthConfig, JwtValidator, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
MacroAuthorizationError, MacroAuthorizationExtractor, MacroAuthorizationServiceImpl,
- MacroAuthorizationState, ValidatedIdentity,
+ MacroAuthorizationState, UserOrInternal, ValidatedIdentity,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -235,6 +235,7 @@ fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
api_key: INTERNAL_API_KEY.to_string(),
default_user_id: Some(DEFAULT_INTERNAL_USER_ID.to_string()),
},
+ macro_authorization::NoBotAuthorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
@@ -255,9 +256,9 @@ fn test_router(entity_access_service: FakeEntityAccessService) -> Router {
}
async fn required_auth_handler(
- authorization: MacroAuthorizationExtractor<TestAuthorizationService>,
+ authorization: MacroAuthorizationExtractor<TestAuthorizationService, UserOrInternal>,
) -> String {
- authorization.macro_user_id.to_string()
+ authorization.authorization.user.macro_user_id.to_string()
}
async fn team_handler(
diff --git a/crates/referral/src/inbound/axum_router/get_referral_code.rs b/crates/referral/src/inbound/axum_router/get_referral_code.rs
index aa19f6b81b..64139ab1db 100644
--- a/crates/referral/src/inbound/axum_router/get_referral_code.rs
+++ b/crates/referral/src/inbound/axum_router/get_referral_code.rs
@@ -1,7 +1,7 @@
//! Handler for `GET /code`.
use axum::{Json, extract::State};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use super::ReferralRouterState;
use crate::domain::models::{ReferralCode, ReferralError};
@@ -24,11 +24,12 @@ use crate::domain::ports::ReferralService;
#[tracing::instrument(skip(state, authorization), err)]
pub async fn get_referral_code_handler<T: ReferralService, R, Auth: MacroAuthorizationService>(
State(state): State<ReferralRouterState<T, R, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<ReferralCode>, ReferralError> {
+ let user = authorization.authorization.user;
let code = state
.service
- .get_referral_code_for_user(&authorization.macro_user_id)
+ .get_referral_code_for_user(&user.macro_user_id)
.await?;
Ok(Json(code))
diff --git a/crates/referral/src/inbound/axum_router/send_invite.rs b/crates/referral/src/inbound/axum_router/send_invite.rs
index d8ecc2f31d..bafa904ce4 100644
--- a/crates/referral/src/inbound/axum_router/send_invite.rs
+++ b/crates/referral/src/inbound/axum_router/send_invite.rs
@@ -8,7 +8,7 @@ use axum_extra::extract::Cached;
use ip_extractor::ClientIp;
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationService,
- MacroAuthorizationState,
+ MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::email::EmailStr;
use rate_limit::inbound::RateLimitExtractable;
@@ -49,19 +49,20 @@ pub async fn post_referral_invite_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ReferralRouterState<T, R, Auth>>,
- Cached(authorization): Cached<MacroAuthorizationExtractor<Auth>>,
+ Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>>,
Json(SendInviteBody { recipient }): Json<SendInviteBody>,
) -> Result<StatusCode, ReferralError> {
+ let user = authorization.authorization.user;
let () = state
.service
- .send_referral_invite(authorization.macro_user_id, recipient)
+ .send_referral_invite(user.macro_user_id.clone(), recipient)
.await?;
Ok(StatusCode::NO_CONTENT)
}
/// the rate limit definition for the per-user rate limit on referring new users
-pub struct PerUserReferralRateLimit<Auth>(MacroAuthorizationExtractor<Auth>);
+pub struct PerUserReferralRateLimit<Auth>(MacroAuthorizationExtractor<Auth, UserOrInternal>);
impl<S, Auth> RateLimitExtractable<S> for PerUserReferralRateLimit<Auth>
where
@@ -79,7 +80,7 @@ where
fn key(&self) -> rate_limit::RateLimitKey {
RateLimitKey::builder(&"per-user-referral")
- .append(&self.0.macro_user_id.as_ref())
+ .append(&self.0.authorization.user.macro_user_id.as_ref())
.finish()
}
}
@@ -96,7 +97,7 @@ where
parts: &mut axum::http::request::Parts,
state: &S,
) -> Result<Self, Self::Rejection> {
- let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth>> =
+ let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>> =
parts.extract_with_state(state).await?;
Ok(Self(authorization))
}
diff --git a/crates/search_service/src/api/search/channel.rs b/crates/search_service/src/api/search/channel.rs
index b1b2a563b2..67d4fece57 100644
--- a/crates/search_service/src/api/search/channel.rs
+++ b/crates/search_service/src/api/search/channel.rs
@@ -13,7 +13,7 @@ use axum::{
routing::post,
};
use channels::domain::models::ChannelHistoryInfo;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserId;
use models_search::MatchType;
use models_search::channel::{
@@ -301,13 +301,17 @@ pub fn router() -> Router<SearchHandlerState> {
/// Internal viewer-aware channel name search used by AI NameSearch.
pub async fn name_handler(
State(ctx): State<SearchHandlerState>,
- authorization: MacroAuthorizationExtractor<SearchAuthorizationService>,
+ authorization: MacroAuthorizationExtractor<SearchAuthorizationService, InternalOnly>,
extract::Query(query_params): extract::Query<SearchPaginationParams>,
extract::Json(req): extract::Json<ChannelNameSearchRequest>,
) -> Result<Json<ChannelNameSearchResponse>, SearchError> {
- if !authorization.is_internal_access {
- return Err(SearchError::InternalAccessRequired);
- }
+ let user_context = authorization
+ .authorization
+ .acting_user
+ .as_ref()
+ .ok_or(SearchError::NoUserId)?
+ .user_context
+ .clone();
let query = req.query.trim();
if query.len() < 3 {
@@ -318,14 +322,14 @@ pub async fn name_handler(
return Err(SearchError::InvalidPageSize);
}
- let user_id = MacroUserId::parse_from_str(&authorization.user_context.user_id)
- .map_err(|_| SearchError::InvalidUserId(authorization.user_context.user_id.clone()))?
+ let user_id = MacroUserId::parse_from_str(&user_context.user_id)
+ .map_err(|_| SearchError::InvalidUserId(user_context.user_id.clone()))?
.lowercase();
let filters = item_filters::ChannelFilters::default();
let channels = simple_channel::filter_channels(
&ctx,
user_id.as_ref(),
- authorization.user_context.organization_id,
+ user_context.organization_id,
&filters,
)
.await?;
@@ -375,11 +379,16 @@ pub async fn name_handler(
)]
pub async fn handler(
State(ctx): State<SearchHandlerState>,
- authorization: MacroAuthorizationExtractor<SearchAuthorizationService>,
+ authorization: MacroAuthorizationExtractor<SearchAuthorizationService, UserOrInternal>,
extract::Query(query_params): extract::Query<SearchPaginationParams>,
extract::Json(req): extract::Json<ChannelSearchRequest>,
) -> Result<Json<ChannelSearchResponse>, SearchError> {
- let user_id = authorization.user_context.user_id.clone();
+ let user_id = authorization
+ .authorization
+ .user
+ .user_context
+ .user_id
+ .clone();
if user_id.is_empty() {
return Err(SearchError::NoUserId);
}
@@ -428,7 +437,11 @@ pub async fn handler(
let channel_ids = simple_channel::filter_channels(
&ctx,
user_id.as_ref(),
- authorization.user_context.organization_id,
+ authorization
+ .authorization
+ .user
+ .user_context
+ .organization_id,
&filters,
)
.await?
diff --git a/crates/search_service/src/api/search/simple/simple_unified.rs b/crates/search_service/src/api/search/simple/simple_unified.rs
index 669ed3842e..7cb7b59a18 100644
--- a/crates/search_service/src/api/search/simple/simple_unified.rs
+++ b/crates/search_service/src/api/search/simple/simple_unified.rs
@@ -12,7 +12,7 @@ use axum::{
};
use crm::domain::auth::CrmTeamReceipt;
use entity_access::domain::models::MemberTeamRole;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserId;
use model::{response::ErrorResponse, user::UserContext};
use models_search::unified::SearchEntityFilters;
@@ -647,11 +647,11 @@ pub(in crate::api::search) async fn perform_unified_search(
)]
pub async fn handler(
State(ctx): State<SearchHandlerState>,
- authorization: MacroAuthorizationExtractor<SearchAuthorizationService>,
+ authorization: MacroAuthorizationExtractor<SearchAuthorizationService, UserOrInternal>,
extract::Query(query_params): extract::Query<SearchPaginationParams>,
extract::Json(req): extract::Json<UnifiedSearchRequest>,
) -> Result<Json<SimpleSearchResponse>, SearchError> {
- let user_context = &authorization.user_context;
+ let user_context = &authorization.authorization.user.user_context;
tracing::info!(
user_id = user_context.user_id,
diff --git a/crates/search_service/src/api/search/unified.rs b/crates/search_service/src/api/search/unified.rs
index 754bab270d..7beaaccd39 100644
--- a/crates/search_service/src/api/search/unified.rs
+++ b/crates/search_service/src/api/search/unified.rs
@@ -11,7 +11,7 @@ use axum::{
extract::{self, State},
response::Json,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use models_search::unified::{
UnifiedSearchRequest, UnifiedSearchResponse, UnifiedSearchResponseItem,
@@ -39,11 +39,11 @@ use std::cmp::Ordering;
)]
pub async fn handler(
State(ctx): State<SearchHandlerState>,
- authorization: MacroAuthorizationExtractor<SearchAuthorizationService>,
+ authorization: MacroAuthorizationExtractor<SearchAuthorizationService, UserOrInternal>,
extract::Query(query_params): extract::Query<SearchPaginationParams>,
extract::Json(req): extract::Json<UnifiedSearchRequest>,
) -> Result<Json<UnifiedSearchResponse>, SearchError> {
- let user_context = &authorization.user_context;
+ let user_context = &authorization.authorization.user.user_context;
tracing::info!(
user_id = user_context.user_id,
diff --git a/crates/soup/src/inbound/axum_router.rs b/crates/soup/src/inbound/axum_router.rs
index 97967e41de..ab56217cb0 100644
--- a/crates/soup/src/inbound/axum_router.rs
+++ b/crates/soup/src/inbound/axum_router.rs
@@ -46,7 +46,7 @@ use item_filters::{
},
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
@@ -775,7 +775,7 @@ where
)]
pub async fn get_soup_handler<T, U, EAS, Auth>(
State(service): State<SoupRouterState<T, U, EAS, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: OptionalMacroUserTeamExtractorV2<MemberTeamRole, EAS, Auth>,
Query(params): Query<Params>,
cursor: SoupCursor<EntityFilters>,
@@ -786,6 +786,7 @@ where
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
{
+ let macro_user_id = authorization.authorization.user.macro_user_id;
let link_ids = fetch_caller_link_ids(&service, macro_user_id.as_ref()).await?;
// Team receipt is plumbed through even for GET so that paginating a
// team-scoped query via a cursor (which carries the original filter)
@@ -847,7 +848,7 @@ type SoupCursor<R> = axum_extra::either::Either<
#[tracing::instrument(err, skip_all)]
pub async fn post_soup_handler<T, U, EAS, Auth>(
State(service): State<SoupRouterState<T, U, EAS, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: OptionalMacroUserTeamExtractorV2<MemberTeamRole, EAS, Auth>,
cursor: SoupCursor<EntityFilters>,
Json(PostSoupRequest {
@@ -862,6 +863,7 @@ where
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
{
+ let macro_user_id = authorization.authorization.user.macro_user_id;
let link_ids = fetch_caller_link_ids(&service, macro_user_id.as_ref()).await?;
// Pass the raw extractor receipt through — `handle` resolves the
// CRM-scope check against the *effective* filter (which may come from
@@ -913,7 +915,7 @@ pub struct PostSoupAstRequest {
#[tracing::instrument(err, skip_all)]
pub async fn post_soup_ast_handler<T, U, EAS, Auth>(
State(service): State<SoupRouterState<T, U, EAS, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
team: OptionalMacroUserTeamExtractorV2<MemberTeamRole, EAS, Auth>,
cursor: SoupCursor<ApiEntityFilterAst>,
Json(PostSoupAstRequest {
@@ -928,6 +930,7 @@ where
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
{
+ let macro_user_id = authorization.authorization.user.macro_user_id;
let link_ids = fetch_caller_link_ids(&service, macro_user_id.as_ref()).await?;
// Pass the raw extractor receipt through — `handle` resolves the
// CRM-scope check against the *effective* filter (which may come from
@@ -1004,7 +1007,7 @@ enum GroupedSoupRequestMode {
#[tracing::instrument(err, skip_all)]
pub async fn post_grouped_soup_ast_handler<T, U, EAS, Auth>(
State(service): State<SoupRouterState<T, U, EAS, Auth>>,
- MacroAuthorizationExtractor { macro_user_id, .. }: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, EntityFilterAst>>,
Json(request): Json<PostGroupedSoupAstRequest>,
) -> Result<Json<GroupedSoupPage>, SoupHandlerErr>
@@ -1014,6 +1017,7 @@ where
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
{
+ let macro_user_id = authorization.authorization.user.macro_user_id;
let (filters, params, mode) = match request {
PostGroupedSoupAstRequest::Initial(request) => (
request.filters,
diff --git a/crates/sync_service/src/inbound/axum_router.rs b/crates/sync_service/src/inbound/axum_router.rs
index 230a5f162c..f496e80bfd 100644
--- a/crates/sync_service/src/inbound/axum_router.rs
+++ b/crates/sync_service/src/inbound/axum_router.rs
@@ -9,7 +9,7 @@ use axum::{
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use crate::domain::{
@@ -61,7 +61,7 @@ where
)]
pub async fn bulk_wakeup_handler<Svc, Auth>(
State(state): State<SyncServiceRouterState<Svc, Auth>>,
- _user: MacroAuthorizationExtractor<Auth>,
+ _user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<BulkWakeupRequest>,
) -> Response
where
diff --git a/crates/teams/src/inbound/axum_router/create_team.rs b/crates/teams/src/inbound/axum_router/create_team.rs
index bf63550e01..3c4c634f53 100644
--- a/crates/teams/src/inbound/axum_router/create_team.rs
+++ b/crates/teams/src/inbound/axum_router/create_team.rs
@@ -1,6 +1,6 @@
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use crate::domain::{
model::{CreateTeamError, Team},
@@ -31,9 +31,10 @@ pub struct CreateTeamRequest {
#[tracing::instrument(skip_all, err)]
pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<TeamRouterState<T, Eas, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<CreateTeamRequest>,
) -> Result<Json<Team>, CreateTeamError> {
+ let user = &user.authorization.user;
// Teams are free up to FREE_TEAM_MAX_MEMBERS members - a subscription is
// linked when the owner has one, but is no longer required to create.
let subscription_id = state
diff --git a/crates/teams/src/inbound/axum_router/get_user_invites.rs b/crates/teams/src/inbound/axum_router/get_user_invites.rs
index cab99154cd..f079f7e4e6 100644
--- a/crates/teams/src/inbound/axum_router/get_user_invites.rs
+++ b/crates/teams/src/inbound/axum_router/get_user_invites.rs
@@ -1,6 +1,6 @@
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model_error_response::ErrorResponse;
use crate::domain::{
@@ -32,11 +32,11 @@ pub struct TeamInvitesResponse {
#[tracing::instrument(skip_all, err)]
pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<TeamRouterState<T, Eas, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<TeamInvitesResponse>, TeamError> {
let invites = state
.service
- .get_user_invites(&authorization.macro_user_id)
+ .get_user_invites(&authorization.authorization.user.macro_user_id)
.await?;
Ok(Json(TeamInvitesResponse { invites }))
}
diff --git a/crates/teams/src/inbound/axum_router/get_user_teams.rs b/crates/teams/src/inbound/axum_router/get_user_teams.rs
index 05710f76d6..a678c87fb9 100644
--- a/crates/teams/src/inbound/axum_router/get_user_teams.rs
+++ b/crates/teams/src/inbound/axum_router/get_user_teams.rs
@@ -1,6 +1,6 @@
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model_error_response::ErrorResponse;
use crate::domain::{
@@ -25,11 +25,11 @@ use super::TeamRouterState;
#[tracing::instrument(skip_all, err)]
pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<TeamRouterState<T, Eas, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<Vec<Team>>, TeamError> {
let teams = state
.service
- .get_user_teams(&authorization.macro_user_id)
+ .get_user_teams(&authorization.authorization.user.macro_user_id)
.await?;
Ok(Json(teams))
}
diff --git a/crates/teams/src/inbound/axum_router/join_team.rs b/crates/teams/src/inbound/axum_router/join_team.rs
index 18babbee87..3cd423c3a8 100644
--- a/crates/teams/src/inbound/axum_router/join_team.rs
+++ b/crates/teams/src/inbound/axum_router/join_team.rs
@@ -1,6 +1,6 @@
use axum::extract::{Path, State};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model_error_response::ErrorResponse;
use crate::domain::{model::JoinTeamError, team_repo::TeamService};
@@ -32,12 +32,15 @@ pub struct TeamInvitePathParam {
#[tracing::instrument(skip_all, err)]
pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<TeamRouterState<T, Eas, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(TeamInvitePathParam { team_invite_id }): Path<TeamInvitePathParam>,
) -> Result<(), JoinTeamError> {
state
.service
- .join_team(&team_invite_id, &authorization.macro_user_id)
+ .join_team(
+ &team_invite_id,
+ &authorization.authorization.user.macro_user_id,
+ )
.await?;
Ok(())
}
diff --git a/crates/teams/src/inbound/axum_router/premium_user.rs b/crates/teams/src/inbound/axum_router/premium_user.rs
index c41ee520b2..f8cea62f48 100644
--- a/crates/teams/src/inbound/axum_router/premium_user.rs
+++ b/crates/teams/src/inbound/axum_router/premium_user.rs
@@ -11,6 +11,7 @@ use axum::{
use entity_access::domain::ports::EntityAccessService;
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationService,
+ UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
@@ -84,15 +85,17 @@ where
parts: &mut Parts,
state: &TeamRouterState<T, Eas, Auth>,
) -> Result<Self, Self::Rejection> {
- let user = MacroAuthorizationExtractor::<Auth>::from_request_parts(parts, state).await?;
-
+ let authorization =
+ MacroAuthorizationExtractor::<Auth, UserOrInternal>::from_request_parts(parts, state)
+ .await?;
+ let user = &authorization.authorization.user;
let Some(subscription_id) = state.service.is_user_premium(&user.macro_user_id).await?
else {
return Err(PremiumUserRejection::NotPremium);
};
Ok(Self {
- macro_user_id: user.macro_user_id,
+ macro_user_id: user.macro_user_id.clone(),
subscription_id,
_authorization: PhantomData,
})
diff --git a/crates/teams/src/inbound/axum_router/reject_invitation.rs b/crates/teams/src/inbound/axum_router/reject_invitation.rs
index c6a6ff14cd..eed69be7d0 100644
--- a/crates/teams/src/inbound/axum_router/reject_invitation.rs
+++ b/crates/teams/src/inbound/axum_router/reject_invitation.rs
@@ -1,6 +1,6 @@
use axum::extract::{Path, State};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use model_error_response::ErrorResponse;
use crate::domain::{model::RemoveTeamInviteError, team_repo::TeamService};
@@ -32,12 +32,15 @@ pub struct TeamInvitePathParam {
#[tracing::instrument(skip_all, err)]
pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<TeamRouterState<T, Eas, Auth>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(TeamInvitePathParam { team_invite_id }): Path<TeamInvitePathParam>,
) -> Result<(), RemoveTeamInviteError> {
state
.service
- .reject_invitation(&authorization.macro_user_id, &team_invite_id)
+ .reject_invitation(
+ &authorization.authorization.user.macro_user_id,
+ &team_invite_id,
+ )
.await?;
Ok(())
}
diff --git a/crates/webhook/src/inbound/axum_router.rs b/crates/webhook/src/inbound/axum_router.rs
index c4a656fec9..023b3904d5 100644
--- a/crates/webhook/src/inbound/axum_router.rs
+++ b/crates/webhook/src/inbound/axum_router.rs
@@ -16,7 +16,7 @@ use axum::{
};
use axum_extra::extract::Cached;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use model_error_response::ErrorResponse;
use rate_limit::domain::models::RateLimitOk;
@@ -79,7 +79,7 @@ pub struct WebhookPath {
/// Per-user validation attempt rate limit.
pub struct PerUserValidateWebhookRateLimit<Auth> {
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
webhook_id: WebhookId,
}
@@ -98,7 +98,7 @@ where
fn key(&self) -> RateLimitKey {
RateLimitKey::builder(&"per-user-validate-webhook")
- .append(&self.authorization.macro_user_id.as_ref())
+ .append(&self.authorization.authorization.user.macro_user_id.as_ref())
.append(&self.webhook_id)
.finish()
}
@@ -116,10 +116,11 @@ where
parts: &mut axum::http::request::Parts,
state: &S,
) -> Result<Self, Self::Rejection> {
- let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth>> = parts
- .extract_with_state(state)
- .await
- .map_err(IntoResponse::into_response)?;
+ let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>> =
+ parts
+ .extract_with_state(state)
+ .await
+ .map_err(IntoResponse::into_response)?;
let Path(path): Path<WebhookPath> = parts
.extract_with_state(state)
.await
@@ -221,11 +222,11 @@ where
)]
pub async fn create_webhook<S: WebhookService, Auth: MacroAuthorizationService>(
State(service): State<Arc<S>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<CreateWebhookRequest>,
) -> Result<(StatusCode, Json<CreateWebhookResponse>), WebhookHandlerError> {
let webhook = service
- .create_webhook(authorization.macro_user_id, request)
+ .create_webhook(authorization.authorization.user.macro_user_id, request)
.await?;
Ok((StatusCode::CREATED, Json(webhook.into())))
}
@@ -247,13 +248,17 @@ pub async fn create_webhook<S: WebhookService, Auth: MacroAuthorizationService>(
)]
pub async fn patch_webhook<S: WebhookService, Auth: MacroAuthorizationService>(
State(service): State<Arc<S>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<WebhookPath>,
Json(request): Json<PatchWebhookRequest>,
) -> Result<Json<Webhook>, WebhookHandlerError> {
Ok(Json(
service
- .patch_webhook(authorization.macro_user_id, path.webhook_id, request)
+ .patch_webhook(
+ authorization.authorization.user.macro_user_id,
+ path.webhook_id,
+ request,
+ )
.await?,
))
}
@@ -273,11 +278,14 @@ pub async fn patch_webhook<S: WebhookService, Auth: MacroAuthorizationService>(
)]
pub async fn delete_webhook<S: WebhookService, Auth: MacroAuthorizationService>(
State(service): State<Arc<S>>,
- authorization: MacroAuthorizationExtractor<Auth>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(path): Path<WebhookPath>,
) -> Result<StatusCode, WebhookHandlerError> {
service
- .delete_webhook(authorization.macro_user_id, path.webhook_id)
+ .delete_webhook(
+ authorization.authorization.user.macro_user_id,
+ path.webhook_id,
+ )
.await?;
Ok(StatusCode::NO_CONTENT)
}
@@ -298,12 +306,15 @@ pub async fn delete_webhook<S: WebhookService, Auth: MacroAuthorizationService>(
)]
pub async fn validate_webhook<S: WebhookService, Auth: MacroAuthorizationService>(
State(service): State<Arc<S>>,
- Cached(authorization): Cached<MacroAuthorizationExtractor<Auth>>,
+ Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, UserOrInternal>>,
Path(path): Path<WebhookPath>,
) -> Result<Json<ValidateWebhookResponse>, WebhookHandlerError> {
Ok(Json(
service
- .validate_webhook(authorization.macro_user_id, path.webhook_id)
+ .validate_webhook(
+ authorization.authorization.user.macro_user_id,
+ path.webhook_id,
+ )
.await?,
))
}
diff --git a/services/authentication_service/src/api/email/generate_email_link.rs b/services/authentication_service/src/api/email/generate_email_link.rs
index 2e42af0e8c..95cd38f8dd 100644
--- a/services/authentication_service/src/api/email/generate_email_link.rs
+++ b/services/authentication_service/src/api/email/generate_email_link.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
use utoipa::ToSchema;
@@ -36,15 +36,15 @@ static VERIFY_EMAIL_TEMPLATE: &str = include_str!("./_verify_email_template.html
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, authorization, ip_context,req), fields(client_ip=%ip_context, email=%req.email, fusion_user_id=%authorization.user_context.fusion_user_id), err(Debug))]
+#[tracing::instrument(skip(ctx, authorization, ip_context,req), fields(client_ip=%ip_context, email=%req.email, fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
ip_context: ClientIp,
extract::Json(mut req): extract::Json<GenerateEmailLinkRequest>,
) -> Result<Response, Response> {
tracing::info!("generate_email_link");
- let user_context = &authorization.user_context;
+ let user_context = &authorization.authorization.user.user_context;
// normalize the email before linking
req.email = email_validator::normalize_email(&req.email)
.context("failed to normalize email")
diff --git a/services/authentication_service/src/api/github_pull_requests.rs b/services/authentication_service/src/api/github_pull_requests.rs
index 58964ecf78..1f05a2e41f 100644
--- a/services/authentication_service/src/api/github_pull_requests.rs
+++ b/services/authentication_service/src/api/github_pull_requests.rs
@@ -9,7 +9,7 @@ use github::domain::{
models::{EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, GithubError},
ports::GithubLinkService,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use crate::api::context::{ApiContext, AuthorizationService};
@@ -64,17 +64,20 @@ pub fn router() -> Router<ApiContext> {
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, request), fields(user_id = %authorization.macro_user_id), err)]
+#[tracing::instrument(skip(ctx, authorization, request), fields(user_id = %authorization.authorization.user.macro_user_id), err)]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(request): extract::Json<EnrichGithubPullRequestsProxyRequest>,
) -> Result<Json<EnrichGithubPullRequestsResponse>, EnrichGithubPullRequestsProxyError> {
tracing::info!("enrich_github_pull_requests");
let pull_requests = ctx
.github_link_service
- .enrich_pull_requests(&authorization.macro_user_id, request.pull_requests)
+ .enrich_pull_requests(
+ &authorization.authorization.user.macro_user_id,
+ request.pull_requests,
+ )
.await?;
Ok(Json(EnrichGithubPullRequestsResponse { pull_requests }))
diff --git a/services/authentication_service/src/api/internal/delete_inbox_grant_user.rs b/services/authentication_service/src/api/internal/delete_inbox_grant_user.rs
index d5d3f1d5f0..fe14f6ca8f 100644
--- a/services/authentication_service/src/api/internal/delete_inbox_grant_user.rs
+++ b/services/authentication_service/src/api/internal/delete_inbox_grant_user.rs
@@ -5,7 +5,7 @@ use axum::{
response::{IntoResponse, Response},
};
use fusionauth::error::FusionAuthClientError;
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::{EmptyResponse, ErrorResponse};
use crate::api::context::{ApiContext, AuthorizationService};
@@ -25,7 +25,7 @@ pub struct DeleteInboxGrantUserQueryParams {
#[tracing::instrument(skip(ctx, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Query(DeleteInboxGrantUserQueryParams { fusionauth_user_id }): extract::Query<
DeleteInboxGrantUserQueryParams,
>,
diff --git a/services/authentication_service/src/api/internal/google_access_token.rs b/services/authentication_service/src/api/internal/google_access_token.rs
index 473745a51b..a0f6768bd1 100644
--- a/services/authentication_service/src/api/internal/google_access_token.rs
+++ b/services/authentication_service/src/api/internal/google_access_token.rs
@@ -6,7 +6,7 @@ use axum::{
};
use fusionauth::FusionAuthClient;
use fusionauth::error::FusionAuthClientError;
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::authentication::google_token::GoogleAccessToken;
use model::response::ErrorResponse;
use std::sync::Arc;
@@ -26,7 +26,7 @@ pub struct GoogleAccessTokenParams {
#[tracing::instrument(skip(auth_client, _internal_authorization))]
pub async fn handler(
State(auth_client): State<Arc<FusionAuthClient>>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Query(params): extract::Query<GoogleAccessTokenParams>,
) -> Result<Response, Response> {
get_access_token(auth_client, &params, "google_gmail").await
diff --git a/services/authentication_service/src/api/internal/post_get_existing_users.rs b/services/authentication_service/src/api/internal/post_get_existing_users.rs
index 727cdb478c..f02f0811cf 100644
--- a/services/authentication_service/src/api/internal/post_get_existing_users.rs
+++ b/services/authentication_service/src/api/internal/post_get_existing_users.rs
@@ -6,7 +6,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use macro_user_id::{cowlike::CowLike, lowercased::Lowercase, user_id::MacroUserId};
use model::response::ErrorResponse;
use utoipa::ToSchema;
@@ -65,7 +65,7 @@ impl IntoResponse for GetExistingUsersError {
#[tracing::instrument(skip(ctx, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(GetExistingUsersRequest { user_ids }): extract::Json<GetExistingUsersRequest>,
) -> Result<Json<GetExistingUsersResponse>, GetExistingUsersError> {
tracing::info!("internal_get_existing_users");
diff --git a/services/authentication_service/src/api/internal/relocate_inbox_grant.rs b/services/authentication_service/src/api/internal/relocate_inbox_grant.rs
index 38da172906..e161b8d87b 100644
--- a/services/authentication_service/src/api/internal/relocate_inbox_grant.rs
+++ b/services/authentication_service/src/api/internal/relocate_inbox_grant.rs
@@ -8,7 +8,7 @@ use axum::{
response::{IntoResponse, Response},
};
use fusionauth::identity_provider::{IdentityProviderLink, LinkUserRequest};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::ErrorResponse;
use crate::api::context::{ApiContext, AuthorizationService};
@@ -50,7 +50,7 @@ pub struct RelocateInboxGrantResponse {
#[tracing::instrument(skip(ctx, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(RelocateInboxGrantRequest {
email,
owner_fusionauth_user_id,
diff --git a/services/authentication_service/src/api/internal/remove_link.rs b/services/authentication_service/src/api/internal/remove_link.rs
index f4ce8973a5..1d816315e6 100644
--- a/services/authentication_service/src/api/internal/remove_link.rs
+++ b/services/authentication_service/src/api/internal/remove_link.rs
@@ -8,7 +8,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::{EmptyResponse, ErrorResponse};
#[cfg(test)]
@@ -44,7 +44,7 @@ fn find_idp_link(links: Vec<Link>, linked_email: &str) -> Option<Link> {
#[tracing::instrument(skip(ctx, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Query(RemoveLinkQueryParams {
fusionauth_user_id,
linked_email,
diff --git a/services/authentication_service/src/api/jwt/macro_api_token.rs b/services/authentication_service/src/api/jwt/macro_api_token.rs
index 7cdf91d7cd..c8efac1a1c 100644
--- a/services/authentication_service/src/api/jwt/macro_api_token.rs
+++ b/services/authentication_service/src/api/jwt/macro_api_token.rs
@@ -6,7 +6,7 @@ use axum::{
response::{IntoResponse, Response},
};
use macro_auth::macro_api_token::EncodeMacroApiTokenArgs;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use sqlx::PgPool;
use utoipa::ToSchema;
@@ -44,10 +44,10 @@ pub struct MacroApiTokenQuery {
pub async fn handler(
State(db): State<PgPool>,
State(macro_api_token_context): State<MacroApiTokenContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Query(query): Query<MacroApiTokenQuery>,
) -> Result<Response, Response> {
- let user_context = &authorization.user_context;
+ let user_context = &authorization.authorization.user.user_context;
let email = if let Some(email) = query.email.clone() {
// TODO: figure out if email is url_encoded by default
let email = urlencoding::decode(email.as_ref()).map_err(|e| {
diff --git a/services/authentication_service/src/api/link/create_in_progress_link.rs b/services/authentication_service/src/api/link/create_in_progress_link.rs
index 5599e58596..088d168950 100644
--- a/services/authentication_service/src/api/link/create_in_progress_link.rs
+++ b/services/authentication_service/src/api/link/create_in_progress_link.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
use model::response::ErrorResponse;
@@ -29,18 +29,18 @@ pub struct CreateInProgressLinkResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.user_context.user_id, fusion_user_id=%authorization.user_context.fusion_user_id), err(Debug))]
+#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.authorization.user.user_context.user_id, fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
ip_context: ClientIp,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
tracing::info!("create_in_progress_link");
let count =
macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
)
.await
.map_err(|e| {
@@ -65,7 +65,7 @@ pub async fn handler(
let link_id = macro_db_client::in_progress_user_link::create_in_progress_user_link(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
)
.await
.map_err(|e| {
diff --git a/services/authentication_service/src/api/link/github.rs b/services/authentication_service/src/api/link/github.rs
index aae211bd64..2bff869505 100644
--- a/services/authentication_service/src/api/link/github.rs
+++ b/services/authentication_service/src/api/link/github.rs
@@ -5,7 +5,7 @@ use axum::{
response::{IntoResponse, Response},
};
use github::domain::{models::GithubError, ports::GithubLinkService};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
use model::response::{EmptyResponse, ErrorResponse};
use serde_utils::urlencode::UrlEncoded;
@@ -118,14 +118,14 @@ impl IntoResponse for GithubLinkStatusError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.macro_user_id), err)]
+#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.authorization.user.macro_user_id), err)]
pub async fn check_github_link_status_handler(
State(ctx): State<ApiContext>,
ip_context: ClientIp,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Json<GithubLinkStatusResponse>, GithubLinkStatusError> {
ctx.github_link_service
- .check_user_link_token(&authorization.macro_user_id)
+ .check_user_link_token(&authorization.authorization.user.macro_user_id)
.await?;
Ok(Json(GithubLinkStatusResponse {
@@ -156,12 +156,12 @@ pub(crate) struct InitGithubLinkQueryParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.user_context.user_id, fusion_user_id=%authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.authorization.user.user_context.user_id, fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn init_github_link_handler(
State(ctx): State<ApiContext>,
query: Query<InitGithubLinkQueryParams>,
ip_context: ClientIp,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Json<InitGithubLinkResponse>, InitGithubLinkError> {
let Query(InitGithubLinkQueryParams { original_url }) = query;
// TODO: this should probably be a middleware or extractor
@@ -169,7 +169,7 @@ pub async fn init_github_link_handler(
let count =
macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
)
.await?;
@@ -180,7 +180,7 @@ pub async fn init_github_link_handler(
// Create in-progress link
let link_id = macro_db_client::in_progress_user_link::create_in_progress_user_link(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
)
.await?;
@@ -254,14 +254,14 @@ impl IntoResponse for DeleteGithubLinkError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.macro_user_id), err)]
+#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.authorization.user.macro_user_id), err)]
pub async fn delete_github_link_handler(
State(ctx): State<ApiContext>,
ip_context: ClientIp,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Json<EmptyResponse>, DeleteGithubLinkError> {
ctx.github_link_service
- .delete_user_link(&authorization.macro_user_id)
+ .delete_user_link(&authorization.authorization.user.macro_user_id)
.await?;
Ok(Json(EmptyResponse::default()))
diff --git a/services/authentication_service/src/api/link/gmail.rs b/services/authentication_service/src/api/link/gmail.rs
index d18e5c18ae..6de5ea6993 100644
--- a/services/authentication_service/src/api/link/gmail.rs
+++ b/services/authentication_service/src/api/link/gmail.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
use macro_user_id::user_id::MacroUserIdStr;
use model::response::ErrorResponse;
@@ -98,7 +98,7 @@ pub(crate) struct InitGmailLinkQueryParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, db_permissions), fields(client_ip=%ip_context, user_id=%db_permissions.authorization.user_context.user_id, fusion_user_id=%db_permissions.authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, ip_context, db_permissions), fields(client_ip=%ip_context, user_id=%db_permissions.authorization.authorization.user.user_context.user_id, fusion_user_id=%db_permissions.authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn init_gmail_link_handler(
State(ctx): State<ApiContext>,
query: Query<InitGmailLinkQueryParams>,
@@ -112,14 +112,14 @@ pub async fn init_gmail_link_handler(
db_permissions
.permissions
.contains(&PermissionId::ReadProfessionalFeatures.to_string()),
- || count_accessible_email_inboxes(&ctx.db, &authorization.macro_user_id),
+ || count_accessible_email_inboxes(&ctx.db, &authorization.authorization.user.macro_user_id),
)
.await?;
let count =
macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
)
.await?;
@@ -129,7 +129,7 @@ pub async fn init_gmail_link_handler(
let link_id = macro_db_client::in_progress_user_link::create_in_progress_user_link(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
)
.await?;
@@ -244,20 +244,26 @@ impl IntoResponse for GmailLinkStatusError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.macro_user_id), err)]
+#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.authorization.user.macro_user_id), err)]
pub async fn check_gmail_link_status_handler(
State(ctx): State<ApiContext>,
ip_context: ClientIp,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Json<GmailLinkStatusResponse>, GmailLinkStatusError> {
// Check if the user has an email link in db
- if macro_db_client::email::check_user_email_link(&ctx.db, &authorization.macro_user_id)
- .await
- .map_err(GmailLinkStatusError::Internal)?
+ if macro_db_client::email::check_user_email_link(
+ &ctx.db,
+ &authorization.authorization.user.macro_user_id,
+ )
+ .await
+ .map_err(GmailLinkStatusError::Internal)?
{
let links = ctx
.auth_client
- .get_links(&authorization.user_context.fusion_user_id, None)
+ .get_links(
+ &authorization.authorization.user.user_context.fusion_user_id,
+ None,
+ )
.await
.map_err(|e| GmailLinkStatusError::Internal(e.into()))?;
diff --git a/services/authentication_service/src/api/logout.rs b/services/authentication_service/src/api/logout.rs
index 32a8be27fc..4e6eba6a24 100644
--- a/services/authentication_service/src/api/logout.rs
+++ b/services/authentication_service/src/api/logout.rs
@@ -10,7 +10,7 @@ use axum::{
response::{IntoResponse, Response},
routing::{get, post},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::EmptyResponse;
use tower_cookies::{CookieManagerLayer, Cookies};
@@ -30,10 +30,10 @@ pub fn router() -> Router<ApiContext> {
(status = 200, body= EmptyResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, jwt_session, cookies), fields(user_id=%authorization.user_context.user_id, organization_id=?authorization.user_context.organization_id))]
+#[tracing::instrument(skip(ctx, authorization, jwt_session, cookies), fields(user_id=%authorization.authorization.user.user_context.user_id, organization_id=?authorization.authorization.user.user_context.organization_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
JwtSessionContext(jwt_session): JwtSessionContext,
cookies: Cookies,
) -> Result<Response, Response> {
diff --git a/services/authentication_service/src/api/merge/create_merge_request.rs b/services/authentication_service/src/api/merge/create_merge_request.rs
index 5dbd2024ec..9e11fa0170 100644
--- a/services/authentication_service/src/api/merge/create_merge_request.rs
+++ b/services/authentication_service/src/api/merge/create_merge_request.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
use utoipa::ToSchema;
@@ -40,15 +40,15 @@ static MERGE_REQUEST_TEMPLATE: &str = include_str!("./_merge_request_template.ht
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, authorization, ip_context,req), fields(client_ip=%ip_context, email=%req.email, fusion_user_id=%authorization.user_context.fusion_user_id), err(Debug))]
+#[tracing::instrument(skip(ctx, authorization, ip_context,req), fields(client_ip=%ip_context, email=%req.email, fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
ip_context: ClientIp,
extract::Json(mut req): extract::Json<CreateAccountMergeRequest>,
) -> Result<Response, Response> {
tracing::info!("create_merge_request");
- let user_context = &authorization.user_context;
+ let user_context = &authorization.authorization.user.user_context;
// normalize the email
req.email = email_validator::normalize_email(&req.email)
diff --git a/services/authentication_service/src/api/merge/verify_merge_request.rs b/services/authentication_service/src/api/merge/verify_merge_request.rs
index a4e02e1e00..ffb5ff67e4 100644
--- a/services/authentication_service/src/api/merge/verify_merge_request.rs
+++ b/services/authentication_service/src/api/merge/verify_merge_request.rs
@@ -6,7 +6,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
use crate::api::context::{ApiContext, AuthorizationService};
@@ -33,15 +33,15 @@ pub struct Params {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, authorization, ip_context), fields(client_ip=%ip_context, fusion_user_id=%authorization.user_context.fusion_user_id), err(Debug))]
+#[tracing::instrument(skip(ctx, authorization, ip_context), fields(client_ip=%ip_context, fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
ip_context: ClientIp,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Path(Params { code }): extract::Path<Params>,
) -> Result<Response, Response> {
tracing::info!("verify_merge_request");
- let user_context = &authorization.user_context;
+ let user_context = &authorization.authorization.user.user_context;
let (account_merge_request_id, to_merge_macro_user_id) =
macro_db_client::account_merge_request::get_merge_request_info(
diff --git a/services/authentication_service/src/api/permissions/get_user_permissions.rs b/services/authentication_service/src/api/permissions/get_user_permissions.rs
index 13bef33dc1..9b67580447 100644
--- a/services/authentication_service/src/api/permissions/get_user_permissions.rs
+++ b/services/authentication_service/src/api/permissions/get_user_permissions.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use crate::api::context::{ApiContext, AuthorizationService};
@@ -19,14 +19,14 @@ use crate::api::context::{ApiContext, AuthorizationService};
(status = 500, body=String),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=%authorization.user_context.user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=%authorization.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
let permissions = macro_db_client::user::get_permissions::get_user_permissions(
&ctx.db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
)
.await
.map_err(|e| {
diff --git a/services/authentication_service/src/api/permissions_extractor.rs b/services/authentication_service/src/api/permissions_extractor.rs
index 7ba94e6193..aace496ac2 100644
--- a/services/authentication_service/src/api/permissions_extractor.rs
+++ b/services/authentication_service/src/api/permissions_extractor.rs
@@ -6,7 +6,7 @@ use axum::{
http::{StatusCode, request::Parts},
response::{IntoResponse, Response},
};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationState};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationState, UserOrInternal};
use model::response::ErrorResponse;
use sqlx::PgPool;
@@ -14,7 +14,7 @@ use crate::api::context::AuthorizationService;
/// An authorized user and their current database-backed permissions.
pub(crate) struct DbPermissionsExtractor {
- pub(crate) authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ pub(crate) authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
pub(crate) permissions: HashSet<String>,
}
@@ -28,19 +28,21 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let authorization =
- MacroAuthorizationExtractor::<AuthorizationService>::from_request_parts(parts, state)
+ MacroAuthorizationExtractor::<AuthorizationService, UserOrInternal>::from_request_parts(
+ parts, state,
+ )
.await
.map_err(IntoResponse::into_response)?;
let db = PgPool::from_ref(state);
let permissions = macro_db_client::user::get_permissions::get_user_permissions(
&db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
)
.await
.map_err(|error| {
tracing::error!(
error = ?error,
- user_id = %authorization.user_context.user_id,
+ user_id = %authorization.authorization.user.user_context.user_id,
"unable to get user permissions"
);
(
diff --git a/services/authentication_service/src/api/user/delete_user.rs b/services/authentication_service/src/api/user/delete_user.rs
index 65e3b9222d..a462897e52 100644
--- a/services/authentication_service/src/api/user/delete_user.rs
+++ b/services/authentication_service/src/api/user/delete_user.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use tower_cookies::Cookies;
use crate::api::{
@@ -26,14 +26,14 @@ use model::response::{ErrorResponse, GenericSuccessResponse};
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, jwt_session, cookies), fields(user_id=%authorization.user_context.user_id))]
+#[tracing::instrument(skip(ctx, authorization, jwt_session, cookies), fields(user_id=%authorization.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
JwtSessionContext(jwt_session): JwtSessionContext,
cookies: Cookies,
) -> Result<Response, Response> {
- let user_context = &authorization.user_context;
+ let user_context = &authorization.authorization.user.user_context;
let user_id = &*user_context.user_id;
// This may seem dumb, but if you delete this account it will delete my fusionauth account and
// we will then be locked out of fusionauth. So this is a way to prevent any accidental fuck
diff --git a/services/authentication_service/src/api/user/get_legacy_user_permissions.rs b/services/authentication_service/src/api/user/get_legacy_user_permissions.rs
index 262e433d0e..e990b94484 100644
--- a/services/authentication_service/src/api/user/get_legacy_user_permissions.rs
+++ b/services/authentication_service/src/api/user/get_legacy_user_permissions.rs
@@ -92,14 +92,21 @@ impl IntoResponse for GetLegacyUserPermissionsError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, db_permissions), err, fields(user_id=%db_permissions.authorization.user_context.user_id))]
+#[tracing::instrument(skip(ctx, db_permissions), err, fields(user_id=%db_permissions.authorization.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
db_permissions: DbPermissionsExtractor,
) -> Result<GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsError> {
- let user_id = MacroUserId::parse_from_str(&db_permissions.authorization.user_context.user_id)
- .map_err(|_| GetLegacyUserPermissionsError::InvalidMacroUserId)?
- .lowercase();
+ let user_id = MacroUserId::parse_from_str(
+ &db_permissions
+ .authorization
+ .authorization
+ .user
+ .user_context
+ .user_id,
+ )
+ .map_err(|_| GetLegacyUserPermissionsError::InvalidMacroUserId)?
+ .lowercase();
let email = user_id.email_part().lowercase();
diff --git a/services/authentication_service/src/api/user/get_name.rs b/services/authentication_service/src/api/user/get_name.rs
index ce609c828d..4d1cc40568 100644
--- a/services/authentication_service/src/api/user/get_name.rs
+++ b/services/authentication_service/src/api/user/get_name.rs
@@ -8,7 +8,7 @@ use macro_db_client::user::get_user_name::get_user_name;
use crate::api::context::{ApiContext, AuthorizationService};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use model::user::UserName;
@@ -26,12 +26,15 @@ use model::user::UserName;
#[tracing::instrument(skip(ctx, authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
- let user_name = get_user_name(&ctx.db, &authorization.user_context.fusion_user_id)
+ let user_name = get_user_name(
+ &ctx.db,
+ &authorization.authorization.user.user_context.fusion_user_id,
+ )
.await
.map_err(|e| {
- tracing::error!(error=?e, authorization.user_context.user_id, "failed to update user name");
+ tracing::error!(error=?e, user_id = %authorization.authorization.user.user_context.user_id, "failed to update user name");
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
})?;
Ok((StatusCode::OK, Json(user_name)).into_response())
diff --git a/services/authentication_service/src/api/user/get_user_info.rs b/services/authentication_service/src/api/user/get_user_info.rs
index 2892c70bd4..45de3e590f 100644
--- a/services/authentication_service/src/api/user/get_user_info.rs
+++ b/services/authentication_service/src/api/user/get_user_info.rs
@@ -7,7 +7,7 @@ use axum::{
use crate::api::context::{ApiContext, AuthorizationService};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::authentication::user::GetUserInfo;
use model::response::ErrorResponse;
@@ -22,14 +22,14 @@ use model::response::ErrorResponse;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=%authorization.macro_user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=%authorization.authorization.user.macro_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
let permissions = macro_db_client::user::get_permissions::get_user_permissions(
&ctx.db,
- authorization.macro_user_id.as_ref(),
+ authorization.authorization.user.macro_user_id.as_ref(),
)
.await
.map_err(|e| {
@@ -46,8 +46,12 @@ pub async fn handler(
Ok((
StatusCode::OK,
Json(GetUserInfo {
- user_id: authorization.macro_user_id.to_string(),
- organization_id: authorization.user_context.organization_id,
+ user_id: authorization.authorization.user.macro_user_id.to_string(),
+ organization_id: authorization
+ .authorization
+ .user
+ .user_context
+ .organization_id,
permissions: permissions.into_iter().collect(),
}),
)
diff --git a/services/authentication_service/src/api/user/get_user_link_exists.rs b/services/authentication_service/src/api/user/get_user_link_exists.rs
index 3ec66941de..87194ba812 100644
--- a/services/authentication_service/src/api/user/get_user_link_exists.rs
+++ b/services/authentication_service/src/api/user/get_user_link_exists.rs
@@ -8,7 +8,7 @@ use utoipa::ToSchema;
use crate::api::context::{ApiContext, AuthorizationService};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
#[derive(serde::Deserialize, serde::Serialize, Debug)]
@@ -39,10 +39,10 @@ pub struct UserLinkResponse {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id = authorization.user_context.user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id = authorization.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Query(params): extract::Query<Params>,
) -> Result<Response, Response> {
tracing::info!("get_user_link_exists");
@@ -76,10 +76,10 @@ pub async fn handler(
let links = ctx
.auth_client
- .get_links(&authorization.user_context.fusion_user_id, Some(idp_id.clone()))
+ .get_links(&authorization.authorization.user.user_context.fusion_user_id, Some(idp_id.clone()))
.await
.map_err(|e| {
- tracing::error!(error=?e, "error fetching links for userid {} and idp id {}", authorization.user_context.fusion_user_id, idp_id.as_str());
+ tracing::error!(error=?e, "error fetching links for userid {} and idp id {}", authorization.authorization.user.user_context.fusion_user_id, idp_id.as_str());
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
diff --git a/services/authentication_service/src/api/user/get_user_organization.rs b/services/authentication_service/src/api/user/get_user_organization.rs
index 5b8e19c41c..a5fb1d4329 100644
--- a/services/authentication_service/src/api/user/get_user_organization.rs
+++ b/services/authentication_service/src/api/user/get_user_organization.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
@@ -68,12 +68,14 @@ impl IntoResponse for GetUserOrganizationResponse {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=?user_context.user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=?user_context.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<GetUserOrganizationResponse, UserOrganizationError> {
- let organization_id = if let Some(organization_id) = user_context.user_context.organization_id {
+ let organization_id = if let Some(organization_id) =
+ user_context.authorization.user.user_context.organization_id
+ {
organization_id
} else {
return Ok(GetUserOrganizationResponse::NoOrganization);
diff --git a/services/authentication_service/src/api/user/get_user_quota.rs b/services/authentication_service/src/api/user/get_user_quota.rs
index 7e150b4525..f01fd4f700 100644
--- a/services/authentication_service/src/api/user/get_user_quota.rs
+++ b/services/authentication_service/src/api/user/get_user_quota.rs
@@ -25,12 +25,12 @@ use model::response::ErrorResponse;
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, db_permissions), fields(user_id=?db_permissions.authorization.user_context.user_id))]
+#[tracing::instrument(skip(ctx, db_permissions), fields(user_id=?db_permissions.authorization.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
db_permissions: DbPermissionsExtractor,
) -> Result<Response, Response> {
- let user_context = &db_permissions.authorization.user_context;
+ let user_context = &db_permissions.authorization.authorization.user.user_context;
// If the user is premium, return NO_CONTENT.
if db_permissions
diff --git a/services/authentication_service/src/api/user/patch_ai_consent.rs b/services/authentication_service/src/api/user/patch_ai_consent.rs
index 1a1772fb04..b667402270 100644
--- a/services/authentication_service/src/api/user/patch_ai_consent.rs
+++ b/services/authentication_service/src/api/user/patch_ai_consent.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserId;
use crate::api::context::{ApiContext, AuthorizationService};
@@ -67,15 +67,16 @@ impl IntoResponse for PatchAiConsentError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(req): extract::Json<PatchAiConsentRequest>,
) -> Result<Json<EmptyResponse>, PatchAiConsentError> {
- let user_id = MacroUserId::parse_from_str(&user_context.user_context.user_id)
- .map_err(|_| PatchAiConsentError::InvalidMacroUserId)?
- .lowercase();
+ let user_id =
+ MacroUserId::parse_from_str(&user_context.authorization.user.user_context.user_id)
+ .map_err(|_| PatchAiConsentError::InvalidMacroUserId)?
+ .lowercase();
macro_db_client::user::patch::patch_ai_consent(&ctx.db, &user_id, req.ai_data_consent)
.await
diff --git a/services/authentication_service/src/api/user/patch_tutorial.rs b/services/authentication_service/src/api/user/patch_tutorial.rs
index 78c66a75e4..068d0cd4e4 100644
--- a/services/authentication_service/src/api/user/patch_tutorial.rs
+++ b/services/authentication_service/src/api/user/patch_tutorial.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserId;
use crate::api::context::{ApiContext, AuthorizationService};
@@ -67,15 +67,16 @@ impl IntoResponse for PatchTutorialCompleteError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(req): extract::Json<PatchUserTutorialRequest>,
) -> Result<Json<EmptyResponse>, PatchTutorialCompleteError> {
- let user_id = MacroUserId::parse_from_str(&user_context.user_context.user_id)
- .map_err(|_| PatchTutorialCompleteError::InvalidMacroUserId)?
- .lowercase();
+ let user_id =
+ MacroUserId::parse_from_str(&user_context.authorization.user.user_context.user_id)
+ .map_err(|_| PatchTutorialCompleteError::InvalidMacroUserId)?
+ .lowercase();
macro_db_client::user::patch::patch_user_tutorial(&ctx.db, &user_id, req.tutorial_complete)
.await
diff --git a/services/authentication_service/src/api/user/patch_user_group.rs b/services/authentication_service/src/api/user/patch_user_group.rs
index ca7889307c..e0353294c6 100644
--- a/services/authentication_service/src/api/user/patch_user_group.rs
+++ b/services/authentication_service/src/api/user/patch_user_group.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserId;
use crate::api::context::{ApiContext, AuthorizationService};
@@ -66,15 +66,16 @@ impl IntoResponse for PatchUserGroupError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(req): extract::Json<PatchUserGroupRequest>,
) -> Result<Json<EmptyResponse>, PatchUserGroupError> {
- let user_id = MacroUserId::parse_from_str(&user_context.user_context.user_id)
- .map_err(|_| PatchUserGroupError::InvalidMacroUserId)?
- .lowercase();
+ let user_id =
+ MacroUserId::parse_from_str(&user_context.authorization.user.user_context.user_id)
+ .map_err(|_| PatchUserGroupError::InvalidMacroUserId)?
+ .lowercase();
macro_db_client::user::patch::patch_user_group(&ctx.db, &user_id, &req.group)
.await
diff --git a/services/authentication_service/src/api/user/patch_user_onboarding.rs b/services/authentication_service/src/api/user/patch_user_onboarding.rs
index 36d2a10e45..05378b7be9 100644
--- a/services/authentication_service/src/api/user/patch_user_onboarding.rs
+++ b/services/authentication_service/src/api/user/patch_user_onboarding.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserId;
use crate::api::context::{ApiContext, AuthorizationService};
@@ -73,15 +73,16 @@ impl IntoResponse for PatchUserOnboardingError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.authorization.user.user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(req): extract::Json<PatchUserOnboardingRequest>,
) -> Result<Json<EmptyResponse>, PatchUserOnboardingError> {
- let user_id = MacroUserId::parse_from_str(&user_context.user_context.user_id)
- .map_err(|_| PatchUserOnboardingError::InvalidMacroUserId)?
- .lowercase();
+ let user_id =
+ MacroUserId::parse_from_str(&user_context.authorization.user.user_context.user_id)
+ .map_err(|_| PatchUserOnboardingError::InvalidMacroUserId)?
+ .lowercase();
macro_db_client::user::patch::patch_user_onboarding(
&ctx.db,
diff --git a/services/authentication_service/src/api/user/post_get_names.rs b/services/authentication_service/src/api/user/post_get_names.rs
index 12d1cff3f4..22a5a9e1ac 100644
--- a/services/authentication_service/src/api/user/post_get_names.rs
+++ b/services/authentication_service/src/api/user/post_get_names.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::{InternalMacroAuthorizationExtractor, MacroAuthorizationExtractor};
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::user::get_user_name::get_user_names;
use crate::api::context::{ApiContext, AuthorizationService};
@@ -31,7 +31,7 @@ pub struct PostGetNamesRequestBody {
#[tracing::instrument(skip(ctx, _authorization))]
pub async fn handler_external(
State(ctx): State<ApiContext>,
- _authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ _authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(req): extract::Json<PostGetNamesRequestBody>,
) -> Result<Response, Response> {
lookup_names(&ctx, req).await
@@ -39,7 +39,7 @@ pub async fn handler_external(
pub async fn handler_internal(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<PostGetNamesRequestBody>,
) -> Result<Response, Response> {
lookup_names(&ctx, req).await
diff --git a/services/authentication_service/src/api/user/post_get_names_with_email.rs b/services/authentication_service/src/api/user/post_get_names_with_email.rs
index 66884a329a..c25edec313 100644
--- a/services/authentication_service/src/api/user/post_get_names_with_email.rs
+++ b/services/authentication_service/src/api/user/post_get_names_with_email.rs
@@ -4,7 +4,7 @@ use axum::{
extract::{self, State},
http::StatusCode,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::user::get_user_name::get_user_names_with_email;
use macro_user_id::user_id::MacroUserId;
use macro_user_id::{cowlike::CowLike, lowercased::Lowercase};
@@ -33,7 +33,7 @@ pub struct GetNamesWithEmailRequestBody {
#[tracing::instrument(skip(ctx, authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(req): extract::Json<GetNamesWithEmailRequestBody>,
) -> Result<Json<UserNames>, (StatusCode, String)> {
let user_profile_ids: NonEmpty<Vec<MacroUserId<Lowercase>>> = NonEmpty::new(
@@ -55,7 +55,7 @@ pub async fn handler(
let user_names = get_user_names_with_email(
&ctx.db,
- authorization.macro_user_id.as_ref(),
+ authorization.authorization.user.macro_user_id.as_ref(),
user_profile_ids,
)
.await
diff --git a/services/authentication_service/src/api/user/post_profile_pictures.rs b/services/authentication_service/src/api/user/post_profile_pictures.rs
index 8b5bfff203..ef5db81d70 100644
--- a/services/authentication_service/src/api/user/post_profile_pictures.rs
+++ b/services/authentication_service/src/api/user/post_profile_pictures.rs
@@ -7,7 +7,7 @@ use axum::{
use crate::api::context::{ApiContext, AuthorizationService};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::user::update_profile_picture::get_profile_pictures;
use model::response::ErrorResponse;
use model::user::ProfilePictures;
@@ -32,7 +32,7 @@ pub struct GetProfilePicturesRequestBody {
#[tracing::instrument(skip(ctx, _authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ _authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(req): extract::Json<GetProfilePicturesRequestBody>,
) -> Result<Response, Response> {
let user_id_list = req.user_id_list;
diff --git a/services/authentication_service/src/api/user/put_name.rs b/services/authentication_service/src/api/user/put_name.rs
index 03c73895be..f20f8f2c96 100644
--- a/services/authentication_service/src/api/user/put_name.rs
+++ b/services/authentication_service/src/api/user/put_name.rs
@@ -8,7 +8,7 @@ use macro_db_client::user::update_user_name::update_user_name;
use crate::api::context::{ApiContext, AuthorizationService};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::EmptyResponse;
use model::response::ErrorResponse;
use model::user::PutUserNameQueryParams;
@@ -25,17 +25,17 @@ use model::user::PutUserNameQueryParams;
),
params(PutUserNameQueryParams),
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id = authorization.user_context.user_id, macro_user_id = authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id = authorization.authorization.user.user_context.user_id, macro_user_id = authorization.authorization.user.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
Query(params): Query<PutUserNameQueryParams>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
tracing::info!("put_user_name");
update_user_name(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
params.first_name,
params.last_name,
)
diff --git a/services/authentication_service/src/api/user/put_profile_picture.rs b/services/authentication_service/src/api/user/put_profile_picture.rs
index 8159ee42ad..1cfdd94ad6 100644
--- a/services/authentication_service/src/api/user/put_profile_picture.rs
+++ b/services/authentication_service/src/api/user/put_profile_picture.rs
@@ -7,7 +7,7 @@ use axum::{
use crate::api::context::{ApiContext, AuthorizationService};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::user::update_profile_picture::update_profile_picture;
use model::response::{EmptyResponse, ErrorResponse};
use serde::Deserialize;
@@ -34,17 +34,17 @@ pub struct ProfilePictureQueryParams {
pub async fn handler(
State(ctx): State<ApiContext>,
Query(params): Query<ProfilePictureQueryParams>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
update_profile_picture(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
&params.url,
"000",
)
.await
.map_err(|e| {
- tracing::error!(error=?e, authorization.user_context.user_id, "failed to update user profile picture");
+ tracing::error!(error=?e, user_id = %authorization.authorization.user.user_context.user_id, "failed to update user profile picture");
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
})?;
Ok((StatusCode::OK, Json(EmptyResponse {})).into_response())
diff --git a/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs b/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
index 12af1af656..1a995f46ad 100644
--- a/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
+++ b/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
@@ -2,7 +2,7 @@ use axum::{Json, extract::State};
use entity_access::domain::models::OwnerTeamRole;
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractorV2;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use serde::Deserialize;
use utoipa::ToSchema;
@@ -51,18 +51,20 @@ pub struct CreateCheckoutSessionV2Request {
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, optional_team), err, fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, optional_team), err, fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn create_checkout_session<Eas: EntityAccessService>(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
optional_team: OptionalMacroUserTeamExtractorV2<OwnerTeamRole, Eas, AuthorizationService>,
Json(req): Json<CreateCheckoutSessionV2Request>,
) -> Result<Json<StripeSessionResponse>, StripeOperationError> {
// Get the stripe customer ID from the database
- let stripe_customer_id =
- macro_db_client::user::get::get_stripe_customer_id_by_user_id(&ctx.db, &user.macro_user_id)
- .await?
- .ok_or(StripeOperationError::MissingStripeId)?;
+ let stripe_customer_id = macro_db_client::user::get::get_stripe_customer_id_by_user_id(
+ &ctx.db,
+ &user.authorization.user.macro_user_id,
+ )
+ .await?
+ .ok_or(StripeOperationError::MissingStripeId)?;
let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;
@@ -116,7 +118,10 @@ pub async fn create_checkout_session<Eas: EntityAccessService>(
let team_id = team.entity().entity_id.clone();
metadata.insert("team_id".to_string(), team_id);
- metadata.insert("owner_id".to_string(), user.macro_user_id.to_string());
+ metadata.insert(
+ "owner_id".to_string(),
+ user.authorization.user.macro_user_id.to_string(),
+ );
}
if let Some(ga_client_id) = req.metadata.ga_client_id {
diff --git a/services/authentication_service/src/api/user/stripe/create_portal_session.rs b/services/authentication_service/src/api/user/stripe/create_portal_session.rs
index ce18aeed82..5fdb4ab3c9 100644
--- a/services/authentication_service/src/api/user/stripe/create_portal_session.rs
+++ b/services/authentication_service/src/api/user/stripe/create_portal_session.rs
@@ -1,5 +1,5 @@
use axum::{Json, extract::State};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use serde::Deserialize;
use utoipa::ToSchema;
@@ -27,16 +27,16 @@ pub struct CreatePortalSessionRequest {
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), err, fields(user_id = %authorization.macro_user_id))]
+#[tracing::instrument(skip(ctx, authorization), err, fields(user_id = %authorization.authorization.user.macro_user_id))]
pub async fn create_portal_session(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(req): Json<CreatePortalSessionRequest>,
) -> Result<Json<StripeSessionResponse>, StripeOperationError> {
// Get the stripe customer ID from the database
let stripe_customer_id = macro_db_client::user::get::get_stripe_customer_id_by_user_id(
&ctx.db,
- &authorization.macro_user_id,
+ &authorization.authorization.user.macro_user_id,
)
.await?
.ok_or(StripeOperationError::MissingStripeId)?;
diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
index 9781205a19..dcfc4e117b 100644
--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
@@ -8,7 +8,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use rand::Rng;
use crate::{
@@ -42,7 +42,7 @@ fn support_channel_name<T: AsRef<str>>(email: &Email<T>) -> String {
#[tracing::instrument(skip(ctx, req, _internal_authorization), fields(email=%req.event.user.email, fusionauth_user_id=%req.event.user.id, username=?req.event.user.username, event_type=%req.event.event_type, ip_address=%req.event.info.ip_address))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<FusionAuthUserWebhook>,
) -> Result<Response, Response> {
tracing::info!("create_user_webhook");
diff --git a/services/authentication_service/src/api/webhooks/user/delete_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
index ad6db2a165..944b9dd384 100644
--- a/services/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
@@ -7,7 +7,7 @@ use comms_db_client::{
channels::get_channels::get_org_channels,
participants::remove_participant::{RemoveParticipantOptions, remove_participant},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use macro_user_id::user_id::MacroUserIdStr;
use model::{authentication::webhooks::FusionAuthUserWebhook, user::UserInfoWithMacroUserId};
use notification::domain::ports::NotificationRepository;
@@ -23,7 +23,7 @@ use sqs_client::email::LinkManagerMessage;
#[tracing::instrument(skip(ctx, req, _internal_authorization), fields(event_id=req.event.id, email=req.event.user.email,fusionauth_user_id=req.event.user.id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<FusionAuthUserWebhook>,
) -> Result<Response, Response> {
tracing::info!("delete user webhook");
diff --git a/services/authentication_service/src/api/webhooks/user/populate_jwt.rs b/services/authentication_service/src/api/webhooks/user/populate_jwt.rs
index f896330952..a34a10a10a 100644
--- a/services/authentication_service/src/api/webhooks/user/populate_jwt.rs
+++ b/services/authentication_service/src/api/webhooks/user/populate_jwt.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::{
authentication::webhooks::populate_jwt::{PopulateJwtWebhook, PopulateJwtWebhookResponse},
user::UserInfoWithMacroUserId,
@@ -15,7 +15,7 @@ use model::{
#[tracing::instrument(skip(ctx, req, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<PopulateJwtWebhook>,
) -> Result<Response, Response> {
let email = req.email.to_lowercase();
diff --git a/services/authentication_service/src/api/webhooks/user/update_name.rs b/services/authentication_service/src/api/webhooks/user/update_name.rs
index 0c01674494..8fd75d3f08 100644
--- a/services/authentication_service/src/api/webhooks/user/update_name.rs
+++ b/services/authentication_service/src/api/webhooks/user/update_name.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use crate::api::context::{ApiContext, AuthorizationService};
@@ -36,7 +36,7 @@ async fn process(
#[tracing::instrument(skip(ctx, req, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<UpdateNameWebhook>,
) -> Result<Response, Response> {
let user_id = "macro|".to_string() + &req.email;
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index aa1493def7..af26bc5a16 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -212,6 +212,7 @@ async fn main() -> anyhow::Result<()> {
api_key: internal_api_key.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
)));
let redis_client = redis::Client::open(config.redis_uri.to_string().as_str())
diff --git a/services/connection_gateway/src/api/connection/mod.rs b/services/connection_gateway/src/api/connection/mod.rs
index 6311441bdc..8441f2b931 100644
--- a/services/connection_gateway/src/api/connection/mod.rs
+++ b/services/connection_gateway/src/api/connection/mod.rs
@@ -20,7 +20,7 @@ use futures::{
sink::SinkExt,
stream::{SplitSink, StreamExt},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserIdStr;
use messages::handle_websocket_stream;
use model::user::UserContext;
@@ -35,21 +35,21 @@ pub fn router() -> Router<AppState> {
}
/// Handle upgrading the https connection to a websocket connection
-#[tracing::instrument(skip(ws, authorization, ctx, config), fields(user_id=?authorization.macro_user_id))]
+#[tracing::instrument(
+ skip(ws, authorization, ctx, config),
+ fields(actor = %authorization.acting_entity())
+)]
pub async fn ws_handler(
ws: WebSocketUpgrade,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
State(ctx): State<ApiContext>,
State(config): State<Arc<Config>>,
) -> impl IntoResponse {
+ let macro_user_id = authorization.authorization.user.macro_user_id.clone();
+ let user_context = authorization.authorization.user.user_context.clone();
+
ws.on_upgrade(move |socket| {
- handle_websocket_connection(
- socket,
- ctx,
- config,
- authorization.macro_user_id,
- authorization.user_context,
- )
+ handle_websocket_connection(socket, ctx, config, macro_user_id, user_context)
})
}
diff --git a/services/connection_gateway/src/api/entities/mod.rs b/services/connection_gateway/src/api/entities/mod.rs
index 1d33899f51..3d3d1f3763 100644
--- a/services/connection_gateway/src/api/entities/mod.rs
+++ b/services/connection_gateway/src/api/entities/mod.rs
@@ -10,7 +10,7 @@ use axum::{
response::ErrorResponse,
routing::get,
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model_entity::Entity;
use utoipa::ToSchema;
@@ -46,7 +46,7 @@ pub struct QueryParams {
#[tracing::instrument(skip(_internal_authorization, ctx))]
#[axum::debug_handler(state = AppState)]
pub async fn get_entity_handler(
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
State(ctx): State<ApiContext>,
Path(entity): Path<Entity<'static>>,
Query(query_params): Query<QueryParams>,
diff --git a/services/connection_gateway/src/api/message/mod.rs b/services/connection_gateway/src/api/message/mod.rs
index 52563ccb7a..88abc2f12a 100644
--- a/services/connection_gateway/src/api/message/mod.rs
+++ b/services/connection_gateway/src/api/message/mod.rs
@@ -13,7 +13,7 @@ use connection_gateway_models::{
BatchSendMessageBody, BatchSendUniqueMessagesBody, SendMessageBody, SendMessageResponse,
};
use futures::future::try_join_all;
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model_entity::Entity;
use std::time::Instant;
@@ -52,7 +52,7 @@ where
#[tracing::instrument(skip(_internal_authorization, ctx))]
#[axum::debug_handler(state = AppState)]
pub async fn send_message_handler(
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
State(ctx): State<AppState>,
Path(entity): Path<Entity<'static>>,
Json(body): Json<SendMessageBody>,
@@ -95,7 +95,7 @@ pub async fn send_message_handler(
)]
#[tracing::instrument(skip(_internal_authorization, ctx))]
pub async fn batch_send_message_handler(
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
State(ctx): State<AppState>,
Json(body): Json<BatchSendMessageBody<'static>>,
) -> Result<(StatusCode, JsonResponse<SendMessageResponse>), (StatusCode, String)> {
@@ -147,7 +147,7 @@ pub async fn batch_send_message_handler(
#[tracing::instrument(skip(_internal_authorization, ctx))]
#[axum::debug_handler(state = AppState)]
pub async fn batch_send_unique_messages_handler(
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
State(ctx): State<AppState>,
Json(body): Json<BatchSendUniqueMessagesBody>,
) -> Result<(StatusCode, JsonResponse<SendMessageResponse>), (StatusCode, String)> {
diff --git a/services/connection_gateway/src/api/test.rs b/services/connection_gateway/src/api/test.rs
index 3bd000bcf9..ca25a02e78 100644
--- a/services/connection_gateway/src/api/test.rs
+++ b/services/connection_gateway/src/api/test.rs
@@ -12,8 +12,8 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
#[allow(deprecated)]
use macro_authorization::LEGACY_DSS_INTERNAL_API_KEY_HEADER;
use macro_authorization::{
- INTERNAL_API_KEY_HEADER, InternalAuthConfig, InternalMacroAuthorizationExtractor,
- MacroAuthJwtValidator, MacroAuthorizationServiceImpl, MacroAuthorizationState,
+ INTERNAL_API_KEY_HEADER, InternalAuthConfig, InternalOnly, MacroAuthJwtValidator,
+ MacroAuthorizationExtractor, MacroAuthorizationServiceImpl, MacroAuthorizationState,
};
use serde_json::{Value, json};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -60,7 +60,7 @@ impl FromRef<TestState> for Arc<Config> {
}
async fn internal_auth_probe(
- _authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
) -> Json<Value> {
Json(json!({ "authorized": true }))
}
@@ -72,6 +72,7 @@ fn test_state() -> TestState {
api_key: TEST_INTERNAL_API_KEY.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
);
TestState {
diff --git a/services/connection_gateway/src/main.rs b/services/connection_gateway/src/main.rs
index 74190673d4..6a35139c33 100644
--- a/services/connection_gateway/src/main.rs
+++ b/services/connection_gateway/src/main.rs
@@ -128,6 +128,7 @@ async fn main() -> Result<()> {
api_key: config.internal_api_key.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
)));
let app = router(AppState {
diff --git a/services/contacts_service/src/main.rs b/services/contacts_service/src/main.rs
index e6b3429071..f33f91dd00 100644
--- a/services/contacts_service/src/main.rs
+++ b/services/contacts_service/src/main.rs
@@ -115,6 +115,7 @@ async fn main() -> anyhow::Result<()> {
api_key: config.internal_api_key.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
);
let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));
diff --git a/services/convert_service/src/api/backfill/backfill_docx.rs b/services/convert_service/src/api/backfill/backfill_docx.rs
index d0dc34a061..89566dfc5d 100644
--- a/services/convert_service/src/api/backfill/backfill_docx.rs
+++ b/services/convert_service/src/api/backfill/backfill_docx.rs
@@ -11,7 +11,7 @@ use axum::{
response::{IntoResponse, Response},
};
use futures::StreamExt;
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::{
convert::ConvertQueueMessage,
document::{BomPart, BomPartWithContent, DocumentMetadata},
@@ -43,7 +43,7 @@ use crate::api::context::{ApiContext, AuthorizationService};
#[tracing::instrument(skip(ctx, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Query(pagination): extract::Query<PaginationQueryParams>,
) -> Result<Response, Response> {
let pagination = Pagination::from_query_params(pagination);
diff --git a/services/convert_service/src/api/convert.rs b/services/convert_service/src/api/convert.rs
index ee1b93f16a..b0d0d1b88b 100644
--- a/services/convert_service/src/api/convert.rs
+++ b/services/convert_service/src/api/convert.rs
@@ -8,7 +8,7 @@ use axum::{
response::{IntoResponse, Response},
routing::post,
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::{
convert::ConvertRequest,
document::FileType,
@@ -45,7 +45,7 @@ use super::context::{ApiContext, AuthorizationService};
#[tracing::instrument(skip(ctx, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<ConvertRequest>,
) -> Result<Response, Response> {
let job_id = macro_uuid::generate_uuid_v7().to_string();
diff --git a/services/convert_service/src/main.rs b/services/convert_service/src/main.rs
index ad7ced1bf1..de7ff38466 100644
--- a/services/convert_service/src/main.rs
+++ b/services/convert_service/src/main.rs
@@ -73,6 +73,7 @@ async fn main() -> anyhow::Result<()> {
api_key: config.internal_api_key.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
)));
let db = PgPoolOptions::new()
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 0b830e0f46..d73cd5e31f 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
@@ -7,7 +7,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::dcs::get_chats_for_attachment::{
get_latest_single_attachment_chat, get_multi_attachment_chat,
};
@@ -29,13 +29,13 @@ pub struct Params {
),
params( ("attachment_id" = String, Path, description = "id of the attachment"))
)]
-#[tracing::instrument(skip(db, user), fields(user_id=%user.macro_user_id))]
+#[tracing::instrument(skip(db, user), fields(user_id=%user.authorization.user.macro_user_id))]
pub async fn get_chats_for_attachment_handler(
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
Path(Params { attachment_id }): Path<Params>,
) -> Result<Response, Response> {
- let user_id = user.macro_user_id.as_ref();
+ let user_id = user.authorization.user.macro_user_id.as_ref();
let mut transaction = db.begin().await.map_err(|e| {
tracing::error!(error=?e, user_id=%user_id, attachment_id=%attachment_id, "failed to begin transaction");
StatusCode::INTERNAL_SERVER_ERROR.into_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 b7b12047d6..61c3552fdb 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
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
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,
@@ -26,13 +26,13 @@ use sqlx::PgPool;
(status = 500, body = String, description = "Internal server error")
)
)]
-#[tracing::instrument(skip(db, user, request), fields(user_id = %user.macro_user_id, message_count = request.message_ids.len()))]
+#[tracing::instrument(skip(db, user, request), fields(user_id = %user.authorization.user.macro_user_id, message_count = request.message_ids.len()))]
pub async fn get_chat_history_batch_messages_handler(
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
Json(request): Json<ChatHistoryBatchMessagesRequest>,
) -> Result<Json<ChatHistory>, Response> {
- let user_id = user.macro_user_id.as_ref();
+ let user_id = user.authorization.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)
diff --git a/services/document_cognition_service/src/api/chats/mod.rs b/services/document_cognition_service/src/api/chats/mod.rs
index 90f2159e6d..3d43de7be8 100644
--- a/services/document_cognition_service/src/api/chats/mod.rs
+++ b/services/document_cognition_service/src/api/chats/mod.rs
@@ -14,7 +14,7 @@ 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 macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use tower::ServiceBuilder;
/// Requires an authenticated acting user before the request proceeds.
@@ -25,7 +25,7 @@ use tower::ServiceBuilder;
/// 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>,
+ _user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
req: Request,
next: Next,
) -> Response {
diff --git a/services/document_cognition_service/src/api/citations/mod.rs b/services/document_cognition_service/src/api/citations/mod.rs
index 4e898ae9ff..d4576bbd3f 100644
--- a/services/document_cognition_service/src/api/citations/mod.rs
+++ b/services/document_cognition_service/src/api/citations/mod.rs
@@ -6,7 +6,9 @@ use axum::{
response::Json,
routing::get,
};
-use macro_authorization::OptionalMacroAuthorizationExtractor;
+use macro_authorization::{
+ OptionalMacroAuthorizationExtractor, UserOrInternalService, UserOrInternalServiceAuthorization,
+};
use macro_db_client::dcs::get_part_by_id::get_part_by_id;
use model::citations::DocumentTextPart;
use sqlx::PgPool;
@@ -32,12 +34,20 @@ pub struct Params {
(status = 500, body = String),
)
)]
-#[tracing::instrument(skip(db, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(db, user), fields(actor = tracing::field::Empty))]
pub async fn get_citation_handler(
State(db): State<PgPool>,
- user: OptionalMacroAuthorizationExtractor<DcsAuthorizationService>,
+ user: OptionalMacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternalService>,
Path(Params { id }): Path<Params>,
) -> Result<Json<DocumentTextPart>, (StatusCode, String)> {
+ if let Some(actor) = user.acting_entity() {
+ tracing::Span::current().record("actor", tracing::field::display(actor));
+ }
+ let user_id = user
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.as_ref());
match get_part_by_id(db, id.as_str()).await {
Ok(Some(part)) => Ok(Json(part)),
Ok(None) => Err((
@@ -45,7 +55,7 @@ pub async fn get_citation_handler(
"not found - possible hallucination".to_string(),
)),
Err(err) => {
- tracing::error!(user_id=?user.macro_user_id, citation_id=%id, error=%err, "failed to get citation");
+ tracing::error!(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 a75256161f..75e39e20b7 100644
--- a/services/document_cognition_service/src/api/completions.rs
+++ b/services/document_cognition_service/src/api/completions.rs
@@ -1,6 +1,6 @@
use crate::api::context::DcsAuthorizationService;
use axum::{extract, response::IntoResponse};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_env_var::maybe_env_vars;
const OPENAI_CHAT_COMPLETIONS_URL: &str = "https://api.openai.com/v1/chat/completions";
@@ -12,7 +12,7 @@ maybe_env_vars! {
/// A non-streaming proxy to the chatgpt api
#[tracing::instrument(err(Debug), skip(_user, body))]
pub async fn handler(
- _user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ _user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
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/test.rs b/services/document_cognition_service/src/api/context/test.rs
index b7ef72d8bc..218ac32ff2 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -446,6 +446,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
api_key: "testing".to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
)));
let user_permissions_service = Arc::new(
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 30d6bc3c4d..62374da8b0 100644
--- a/services/document_cognition_service/src/api/id_mapping/create.rs
+++ b/services/document_cognition_service/src/api/id_mapping/create.rs
@@ -7,7 +7,7 @@ use axum::{
extract::{Path, State},
http::StatusCode,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -49,7 +49,7 @@ pub struct CreateIdMappingResponse {
#[tracing::instrument(skip(db, _user))]
pub async fn create_id_mapping_handler(
State(db): State<PgPool>,
- _user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ _user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
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 18633f4455..7712f7500a 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
@@ -7,7 +7,7 @@ use axum::{
extract::{Path, State},
http::StatusCode,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -41,7 +41,7 @@ pub struct GetIdMappingResponse {
#[tracing::instrument(skip(db, _user))]
pub async fn get_id_mapping_handler(
State(db): State<PgPool>,
- _user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ _user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
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/preview/get_batch_preview.rs b/services/document_cognition_service/src/api/preview/get_batch_preview.rs
index 1b1df5375d..a98c786c74 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
@@ -2,7 +2,7 @@ use crate::api::context::DcsAuthorizationService;
use anyhow::Result;
use axum::extract::{Json, State};
use axum::{extract, http::StatusCode};
-use macro_authorization::OptionalMacroAuthorizationExtractor;
+use macro_authorization::{OptionalMacroAuthorizationExtractor, UserOrInternalService};
use model::chat::preview::{ChatPreview, ChatPreviewData, ChatPreviewV2, WithChatId};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -35,7 +35,7 @@ pub async fn handler(
// 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>,
+ _user: OptionalMacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternalService>,
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 0115bf94d7..4050609d25 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
@@ -25,7 +25,7 @@ use axum::response::IntoResponse;
use chat::domain::ports::MessageService;
use futures::StreamExt;
use macro_auth::headers::AccessTokenExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::dcs::create_chat;
use macro_user_id::user_id::MacroUserIdStr;
use mcp_client::domain::ports::McpServerStore;
@@ -135,18 +135,18 @@ impl IntoResponse for ChatMessageError {
(status = 403, description = "Forbidden"),
)
)]
-#[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)]
+#[tracing::instrument(skip(state, model_access, user, bearer, request), fields(chat_id=?request.chat_id, user_id = %user.authorization.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: DcsChatModelAccess,
- user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
Extension(bearer): Extension<BearerToken>,
Json(request): Json<HttpSendChatMessageRequest>,
) -> Result<Json<SendChatMessageResponse>, ChatMessageError> {
Box::pin(send_chat_message_inner(
state,
model_access,
- user.macro_user_id,
+ user.authorization.user.macro_user_id.clone(),
bearer,
request,
))
diff --git a/services/document_cognition_service/src/api/stream/stop.rs b/services/document_cognition_service/src/api/stream/stop.rs
index ae6f424650..ae6c65ccd0 100644
--- a/services/document_cognition_service/src/api/stream/stop.rs
+++ b/services/document_cognition_service/src/api/stream/stop.rs
@@ -11,7 +11,7 @@ use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
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), fields(chat_id = %request.chat_id, stream_id = %request.stream_id, user_id = %user.macro_user_id), err)]
+#[tracing::instrument(skip(state, user), fields(chat_id = %request.chat_id, stream_id = %request.stream_id, user_id = %user.authorization.user.macro_user_id), err)]
pub async fn stop_chat_stream(
State(state): State<ApiContext>,
- user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
Json(request): Json<StopChatStreamRequest>,
) -> Result<Json<StopChatStreamResponse>, StopChatStreamError> {
let access = chat_permissions::chat_access(
&state,
- &user.macro_user_id,
+ &user.authorization.user.macro_user_id,
&request.chat_id,
request.stream_id.clone(),
)
diff --git a/services/document_cognition_service/src/api/structured_completion.rs b/services/document_cognition_service/src/api/structured_completion.rs
index 4eb7832249..d79117a221 100644
--- a/services/document_cognition_service/src/api/structured_completion.rs
+++ b/services/document_cognition_service/src/api/structured_completion.rs
@@ -8,7 +8,7 @@ use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use futures::StreamExt;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use mcp_client::domain::ports::McpServerStore;
use serde::{Deserialize, Serialize};
use std::fmt;
@@ -62,17 +62,17 @@ impl IntoResponse for StructuredCompletionError {
(status = 500, description = "Internal error", body = StructuredCompletionError),
)
)]
-#[tracing::instrument(skip(state, model_access, user, request), fields(user_id = %user.macro_user_id), err)]
+#[tracing::instrument(skip(state, model_access, user, request), fields(user_id = %user.authorization.user.macro_user_id), err)]
pub async fn structured_completion(
State(state): State<ApiContext>,
model_access: DcsChatModelAccess,
- user: MacroAuthorizationExtractor<DcsAuthorizationService>,
+ user: MacroAuthorizationExtractor<DcsAuthorizationService, UserOrInternal>,
Json(request): Json<StructuredCompletionRequest>,
) -> Result<Json<StructuredCompletionResponse>, StructuredCompletionError> {
let ctx = Arc::new(state);
let model = model_access.best_model();
- let user_id = user.macro_user_id;
+ let user_id = user.authorization.user.macro_user_id.clone();
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 7908ede2c5..188c453df0 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -152,6 +152,7 @@ async fn main() -> anyhow::Result<()> {
api_key: internal_api_key.clone(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
)));
let lexical_client = Arc::new(lexical_client::LexicalClient::new(
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index 8651726f80..65b3737b1e 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -115,7 +115,7 @@ lazy_static = { workspace = true }
lexical_client = { path = "../../crates/lexical_client" }
lexical_mention_extractor = { path = "../../crates/lexical_mention_extractor" }
macro_auth = { path = "../../crates/macro_auth" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = ["postgres"] }
macro_aws_config = { path = "../../crates/macro_aws_config", features = ["s3"] }
macro_axum_utils = { path = "../../crates/macro_axum_utils" }
macro_config = { path = "../../crates/macro_config" }
diff --git a/services/document_storage_service/src/api/activity/get_recent_activity.rs b/services/document_storage_service/src/api/activity/get_recent_activity.rs
index 767e0e9a3e..a3cb65251e 100644
--- a/services/document_storage_service/src/api/activity/get_recent_activity.rs
+++ b/services/document_storage_service/src/api/activity/get_recent_activity.rs
@@ -12,7 +12,7 @@ use crate::{
api::context::{ApiContext, AuthorizationService},
model::response::activity::{GetActivitiesResponse, UserActivitiesResponse},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::{
request::pagination::{Pagination, PaginationQueryParams},
response::{GenericErrorResponse, GenericResponse},
@@ -33,11 +33,11 @@ use model::{
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, pagination_query), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, pagination_query), fields(user_id=?user.authorization.user.macro_user_id))]
#[deprecated]
pub async fn get_recent_activity_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Query(pagination_query): Query<PaginationQueryParams>,
) -> impl IntoResponse {
if let Some(limit) = pagination_query.limit
@@ -55,7 +55,7 @@ pub async fn get_recent_activity_handler(
let result = match macro_db_client::activity::get_recent_activities(
ctx.db.clone(),
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
pagination.limit,
pagination.offset,
)
diff --git a/services/document_storage_service/src/api/annotations/create_anchor.rs b/services/document_storage_service/src/api/annotations/create_anchor.rs
index d358aa39d1..d8b582c178 100644
--- a/services/document_storage_service/src/api/annotations/create_anchor.rs
+++ b/services/document_storage_service/src/api/annotations/create_anchor.rs
@@ -10,7 +10,7 @@ use axum::{
};
use connection_gateway_client::ConnectionGatewayClient;
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::annotations::create_anchor::create_unthreaded_anchor;
use model::{
annotations::{
@@ -51,7 +51,7 @@ pub async fn create_anchor_handler(
_access: DocumentAccessExtractor<CommentAccessLevel, EntityAccessService, AuthorizationService>,
State(db): State<PgPool>,
State(connection_gateway_client): State<Arc<ConnectionGatewayClient>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
Json(req): Json<CreateUnthreadedAnchorRequest>,
@@ -65,7 +65,7 @@ pub async fn create_anchor_handler(
)
.into_response());
}
- let user_id = user.macro_user_id.as_ref();
+ let user_id = user.authorization.user.macro_user_id.as_ref();
let document_id = document_id.as_str();
match create_unthreaded_anchor(&db, user_id, document_id, req).await {
Ok(res) => {
diff --git a/services/document_storage_service/src/api/annotations/create_comment.rs b/services/document_storage_service/src/api/annotations/create_comment.rs
index 2a15ab1734..28648850f3 100644
--- a/services/document_storage_service/src/api/annotations/create_comment.rs
+++ b/services/document_storage_service/src/api/annotations/create_comment.rs
@@ -13,7 +13,7 @@ use axum::{
};
use connection_gateway_client::ConnectionGatewayClient;
use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::annotations::create_comment::create_document_comment;
use macro_user_id::user_id::MacroUserIdStr;
use model::{
@@ -61,12 +61,12 @@ pub async fn create_comment_handler(
State(properties_service): State<Arc<crate::api::context::PropertiesService>>,
State(db): State<PgPool>,
State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
Json(req): Json<CreateCommentRequest>,
) -> Result<Response, Response> {
- let user_id = user.macro_user_id.to_string();
+ let user_id = user.authorization.user.macro_user_id.to_string();
if document_context.deleted_at.is_some() {
return Err((
StatusCode::BAD_REQUEST,
diff --git a/services/document_storage_service/src/api/annotations/delete_anchor.rs b/services/document_storage_service/src/api/annotations/delete_anchor.rs
index d830006702..6789a4fb96 100644
--- a/services/document_storage_service/src/api/annotations/delete_anchor.rs
+++ b/services/document_storage_service/src/api/annotations/delete_anchor.rs
@@ -9,7 +9,7 @@ use axum::{
response::{IntoResponse, Response},
};
use connection_gateway_client::ConnectionGatewayClient;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::annotations::delete_anchor::delete_document_anchor;
use model::{
annotations::{
@@ -39,10 +39,10 @@ use super::comment_error_response;
pub async fn delete_anchor_handler(
State(db): State<PgPool>,
State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(req): Json<DeleteUnthreadedAnchorRequest>,
) -> Result<Response, Response> {
- let user_id = user.macro_user_id.as_ref();
+ let user_id = user.authorization.user.macro_user_id.as_ref();
match delete_document_anchor(&db, user_id, req).await {
Ok(res) => {
let response: DeleteUnthreadedAnchorResponse = res;
diff --git a/services/document_storage_service/src/api/annotations/delete_comment.rs b/services/document_storage_service/src/api/annotations/delete_comment.rs
index ac2fe4b9f8..ddffdcef58 100644
--- a/services/document_storage_service/src/api/annotations/delete_comment.rs
+++ b/services/document_storage_service/src/api/annotations/delete_comment.rs
@@ -12,7 +12,7 @@ use axum::{
response::{IntoResponse, Response},
};
use connection_gateway_client::ConnectionGatewayClient;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::annotations::delete_comment::delete_document_comment;
use model::{
annotations::{
@@ -49,11 +49,11 @@ pub struct Params {
pub async fn delete_comment_handler(
State(db): State<PgPool>,
State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { comment_id }): Path<Params>,
Json(req): Json<DeleteCommentRequest>,
) -> Result<Response, Response> {
- let user_id = user.macro_user_id.as_ref();
+ let user_id = user.authorization.user.macro_user_id.as_ref();
match delete_document_comment(&db, comment_id, user_id, req).await {
Ok(res) => {
let response: DeleteCommentResponse = res;
diff --git a/services/document_storage_service/src/api/annotations/edit_anchor.rs b/services/document_storage_service/src/api/annotations/edit_anchor.rs
index 3ddf3df23a..75868d3cac 100644
--- a/services/document_storage_service/src/api/annotations/edit_anchor.rs
+++ b/services/document_storage_service/src/api/annotations/edit_anchor.rs
@@ -9,7 +9,7 @@ use axum::{
response::{IntoResponse, Response},
};
use connection_gateway_client::ConnectionGatewayClient;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::annotations::edit_anchor::edit_document_anchor;
use model::{
annotations::{
@@ -38,10 +38,10 @@ use super::comment_error_response;
pub async fn edit_anchor_handler(
State(db): State<PgPool>,
State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(req): Json<EditAnchorRequest>,
) -> Result<Response, Response> {
- let user_id = user.macro_user_id.as_ref();
+ let user_id = user.authorization.user.macro_user_id.as_ref();
match edit_document_anchor(&db, user_id, req).await {
Ok(res) => {
let response: EditAnchorResponse = res;
diff --git a/services/document_storage_service/src/api/annotations/edit_comment.rs b/services/document_storage_service/src/api/annotations/edit_comment.rs
index a12cf76b17..ffe73a9278 100644
--- a/services/document_storage_service/src/api/annotations/edit_comment.rs
+++ b/services/document_storage_service/src/api/annotations/edit_comment.rs
@@ -11,7 +11,7 @@ use axum::{
response::{IntoResponse, Response},
};
use connection_gateway_client::ConnectionGatewayClient;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::annotations::edit_comment::edit_document_comment;
use macro_user_id::user_id::MacroUserIdStr;
use model::{
@@ -51,11 +51,11 @@ pub async fn edit_comment_handler(
State(db): State<PgPool>,
State(notification_ingress_service): State<Arc<crate::api::context::NotificationIngressType>>,
State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { comment_id }): Path<Params>,
Json(req): Json<EditCommentRequest>,
) -> Result<Response, Response> {
- let user_id = user.macro_user_id.to_string();
+ let user_id = user.authorization.user.macro_user_id.to_string();
// TODO: check if the user has comment access to the document
match edit_document_comment(&db, comment_id, &user_id, &req).await {
Ok(res) => {
diff --git a/services/document_storage_service/src/api/documents/delete_document.rs b/services/document_storage_service/src/api/documents/delete_document.rs
index 861808eb34..f61c14b713 100644
--- a/services/document_storage_service/src/api/documents/delete_document.rs
+++ b/services/document_storage_service/src/api/documents/delete_document.rs
@@ -8,7 +8,7 @@ use axum::{Extension, extract::Path, http::StatusCode, response::IntoResponse};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
#[allow(unused_imports)]
use futures::stream::TryStreamExt;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document::DocumentBasic;
use model::response::{
ErrorResponse, GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse,
@@ -38,11 +38,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, _access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(state, user, _access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn permanently_delete_document_handler(
_access: DocumentAccessExtractor<OwnerAccessLevel, EntityAccessService, AuthorizationService>,
State(state): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
) -> Result<Response, Response> {
diff --git a/services/document_storage_service/src/api/documents/export_document.rs b/services/document_storage_service/src/api/documents/export_document.rs
index 3fe9befec1..e322ab0e59 100644
--- a/services/document_storage_service/src/api/documents/export_document.rs
+++ b/services/document_storage_service/src/api/documents/export_document.rs
@@ -13,7 +13,7 @@ use axum::{
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
use futures::StreamExt;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::{
document::{DocumentBasic, FileType, response::LocationResponseData},
response::{ErrorResponse, GenericErrorResponse},
@@ -61,12 +61,12 @@ pub struct ExportDocumentResponse {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, _access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(state, user, _access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
_access: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService, AuthorizationService>,
Path(Params { .. }): Path<Params>,
State(state): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
) -> Result<Response, Response> {
tracing::info!("export document");
diff --git a/services/document_storage_service/src/api/documents/get_batch_preview.rs b/services/document_storage_service/src/api/documents/get_batch_preview.rs
index a4faff1b2f..284c78c616 100644
--- a/services/document_storage_service/src/api/documents/get_batch_preview.rs
+++ b/services/document_storage_service/src/api/documents/get_batch_preview.rs
@@ -9,12 +9,15 @@ use anyhow::Result;
use axum::extract::Json;
use axum::extract::State;
use axum::response::{IntoResponse, Response};
-use macro_authorization::OptionalMacroAuthorizationExtractor;
+use macro_authorization::{OptionalMacroAuthorizationExtractor, UserOrInternalService};
use model::document::{DocumentPreview, DocumentPreviewV2, WithDocumentId};
use model::response::{GenericErrorResponse, GenericResponse};
use reqwest::StatusCode;
-#[tracing::instrument(skip(ctx, user, req), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(
+ skip(ctx, user, req),
+ fields(actor = tracing::field::Empty)
+)]
#[utoipa::path(
tag = "document",
post,
@@ -28,9 +31,13 @@ use reqwest::StatusCode;
)]
pub async fn get_batch_preview_handler(
State(ctx): State<ApiContext>,
- user: OptionalMacroAuthorizationExtractor<AuthorizationService>,
+ user: OptionalMacroAuthorizationExtractor<AuthorizationService, UserOrInternalService>,
Json(req): Json<GetBatchPreviewRequest>,
) -> Result<(StatusCode, Json<GetBatchPreviewResponse>), Response> {
+ if let Some(actor) = user.acting_entity() {
+ tracing::Span::current().record("actor", tracing::field::display(actor));
+ }
+
// Ensure the document ids are unique to prevent duplicate work
let unique_document_ids: HashSet<String> = req.document_ids.iter().cloned().collect();
let document_ids: Vec<String> = unique_document_ids.into_iter().collect();
diff --git a/services/document_storage_service/src/api/documents/get_document.rs b/services/document_storage_service/src/api/documents/get_document.rs
index 1441d79a42..2902040a58 100644
--- a/services/document_storage_service/src/api/documents/get_document.rs
+++ b/services/document_storage_service/src/api/documents/get_document.rs
@@ -1,6 +1,6 @@
use crate::api::context::AuthorizationService;
use axum::{Extension, Json, extract::Path, http::StatusCode, response::IntoResponse};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::document::DocumentBasic;
use model::response::GenericErrorResponse;
use serde::Deserialize;
@@ -28,7 +28,7 @@ pub struct Params {
)]
#[tracing::instrument(skip(document_basic, _auth))]
pub async fn get_document_basic_handler(
- _auth: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Extension(document_basic): Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
) -> impl IntoResponse {
diff --git a/services/document_storage_service/src/api/documents/get_document_access_level.rs b/services/document_storage_service/src/api/documents/get_document_access_level.rs
index fb2e24b7ab..3144a9e306 100644
--- a/services/document_storage_service/src/api/documents/get_document_access_level.rs
+++ b/services/document_storage_service/src/api/documents/get_document_access_level.rs
@@ -4,7 +4,7 @@ use axum::Json;
use axum::extract::State;
use axum::{extract::Path, http::StatusCode, response::IntoResponse};
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{GenericErrorResponse, GenericResponse};
use model_entity::EntityType;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -30,16 +30,16 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { document_id }): Path<Params>,
) -> impl IntoResponse {
let user_access_level: Option<AccessLevel> = match ctx
.entity_access_service
.get_access_level(
- Some(&user.macro_user_id),
+ Some(&user.authorization.user.macro_user_id),
&document_id,
EntityType::Document,
)
diff --git a/services/document_storage_service/src/api/documents/get_document_key.rs b/services/document_storage_service/src/api/documents/get_document_key.rs
index d79393e579..c93ed5a929 100644
--- a/services/document_storage_service/src/api/documents/get_document_key.rs
+++ b/services/document_storage_service/src/api/documents/get_document_key.rs
@@ -6,7 +6,7 @@ use crate::model::response::documents::get::{GetDocumentKeyResponse, GetDocument
use axum::extract::State;
use axum::{Extension, extract::Path, http::StatusCode, response::IntoResponse};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document::FileType;
use model::response::GenericErrorResponse;
use model::{document::DocumentBasic, response::GenericResponse};
@@ -34,11 +34,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, document_context, _access), fields(user_id=?user.macro_user_id, file_type=?document_context.file_type))]
+#[tracing::instrument(skip(state, user, document_context, _access), fields(user_id=?user.authorization.user.macro_user_id, file_type=?document_context.file_type))]
pub async fn get_document_key_handler(
_access: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService, AuthorizationService>,
State(state): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params {
document_id,
diff --git a/services/document_storage_service/src/api/documents/get_document_list.rs b/services/document_storage_service/src/api/documents/get_document_list.rs
index 7272042bfa..f356f2a0b9 100644
--- a/services/document_storage_service/src/api/documents/get_document_list.rs
+++ b/services/document_storage_service/src/api/documents/get_document_list.rs
@@ -4,7 +4,7 @@ use crate::{
};
use axum::extract::State;
use axum::{http::StatusCode, response::IntoResponse};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::{
document::response::GetDocumentListResult,
response::{GenericErrorResponse, GenericResponse},
@@ -22,21 +22,21 @@ use model::{
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn get_document_list_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> impl IntoResponse {
let document_search_response_date: Vec<GetDocumentListResult> =
match macro_db_client::document::get_document_list(
ctx.db.clone(),
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
)
.await
{
Ok(document_search_response_date) => document_search_response_date,
Err(e) => {
- tracing::error!(error=?e, user_id=?user.macro_user_id, "unable to get document search");
+ tracing::error!(error=?e, user_id=?user.authorization.user.macro_user_id, "unable to get document search");
return GenericResponse::builder()
.message("unable to get document search")
.is_error(true)
diff --git a/services/document_storage_service/src/api/documents/get_document_permissions.rs b/services/document_storage_service/src/api/documents/get_document_permissions.rs
index 7a9d96344c..f4899947cc 100644
--- a/services/document_storage_service/src/api/documents/get_document_permissions.rs
+++ b/services/document_storage_service/src/api/documents/get_document_permissions.rs
@@ -7,7 +7,7 @@ use axum::{
response::{IntoResponse, Json, Response},
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::GenericErrorResponse;
use model::version::ApiVersionEnum;
use models_permissions::share_permission::access_level::OwnerAccessLevel;
@@ -35,7 +35,7 @@ pub struct Params {
)]
#[allow(unused, reason = "used to generate OpenAPI documentation")]
pub(in crate::api) async fn get_document_permissions_handler_v2(
- _user: MacroAuthorizationExtractor<AuthorizationService>,
+ _user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
_api_version: Extension<ApiVersionEnum>,
Path(Params { document_id: _ }): Path<Params>,
) -> impl IntoResponse {
diff --git a/services/document_storage_service/src/api/documents/get_document_processing_result.rs b/services/document_storage_service/src/api/documents/get_document_processing_result.rs
index c630387966..f838ebaad5 100644
--- a/services/document_storage_service/src/api/documents/get_document_processing_result.rs
+++ b/services/document_storage_service/src/api/documents/get_document_processing_result.rs
@@ -5,7 +5,7 @@ use axum::{
response::IntoResponse,
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::GenericErrorResponse;
use model::response::GenericResponse;
use models_permissions::share_permission::access_level::ViewAccessLevel;
@@ -34,11 +34,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(db, user, _access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(db, user, _access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
_access: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService, AuthorizationService>,
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { document_id }): Path<Params>,
) -> impl IntoResponse {
let processing_result = match macro_db_client::document::get_document_process_content(
diff --git a/services/document_storage_service/src/api/documents/get_document_version.rs b/services/document_storage_service/src/api/documents/get_document_version.rs
index 823cd0e8d3..cf1eeb2e74 100644
--- a/services/document_storage_service/src/api/documents/get_document_version.rs
+++ b/services/document_storage_service/src/api/documents/get_document_version.rs
@@ -6,7 +6,7 @@ use axum::{
};
use entity_access::domain::models::EntityPermission;
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::document::get_document_version;
use macro_db_client::user_document_view_location::get::get_user_document_view_location;
use model::document::response::{GetDocumentResponse, GetDocumentResponseData};
@@ -38,11 +38,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(db, user, access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(db, user, access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
access: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService, AuthorizationService>,
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params {
document_id,
document_version_id,
@@ -66,18 +66,22 @@ pub async fn handler(
}
};
- let view_location =
- match get_user_document_view_location(&db, user.macro_user_id.as_ref(), &document_id).await
- {
- Ok(view_location) => view_location,
- Err(e) => {
- tracing::error!(error=?e, "error getting view location");
- return GenericResponse::builder()
- .message("error getting view location")
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR);
- }
- };
+ let view_location = match get_user_document_view_location(
+ &db,
+ user.authorization.user.macro_user_id.as_ref(),
+ &document_id,
+ )
+ .await
+ {
+ Ok(view_location) => view_location,
+ Err(e) => {
+ tracing::error!(error=?e, "error getting view location");
+ return GenericResponse::builder()
+ .message("error getting view location")
+ .is_error(true)
+ .send(StatusCode::INTERNAL_SERVER_ERROR);
+ }
+ };
let user_access_level = match access.entity_access_receipt.entity_permission() {
EntityPermission::AccessLevel { access_level } => *access_level,
diff --git a/services/document_storage_service/src/api/documents/get_document_views.rs b/services/document_storage_service/src/api/documents/get_document_views.rs
index e00ce80fc8..00505a271e 100644
--- a/services/document_storage_service/src/api/documents/get_document_views.rs
+++ b/services/document_storage_service/src/api/documents/get_document_views.rs
@@ -7,7 +7,7 @@ use axum::{
response::{IntoResponse, Response},
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::{document::DocumentBasic, response::GenericErrorResponse};
use models_permissions::share_permission::access_level::ViewAccessLevel;
@@ -34,12 +34,12 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(db, user, document_id, _access), fields(user_id=?user.macro_user_id, document_id=?document_context.document_id, original_document_id=?document_id))]
+#[tracing::instrument(skip(db, user, document_id, _access), fields(user_id=?user.authorization.user.macro_user_id, document_id=?document_context.document_id, original_document_id=?document_id))]
pub async fn get_document_views_handler(
_access: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService, AuthorizationService>,
Path(Params { document_id }): Path<Params>,
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
) -> Result<Response, Response> {
let users = macro_db_client::document::get_document_views(&db, &document_context.document_id)
diff --git a/services/document_storage_service/src/api/documents/get_documents_metadata.rs b/services/document_storage_service/src/api/documents/get_documents_metadata.rs
index 98f8c7348a..5491c32f69 100644
--- a/services/document_storage_service/src/api/documents/get_documents_metadata.rs
+++ b/services/document_storage_service/src/api/documents/get_documents_metadata.rs
@@ -3,7 +3,7 @@ use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use macro_db_client::notification::get_basic_cloud_storage_documents_metadata;
use model::document_storage_service_internal::{
DocumentMetadata, GetDocumentsMetadataRequest, GetDocumentsMetadataResponse,
@@ -13,7 +13,7 @@ use model::response::GenericResponse;
#[tracing::instrument(skip(ctx, _auth), fields(document_count = ?request.document_ids.len()))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _auth: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Json(request): Json<GetDocumentsMetadataRequest>,
) -> impl IntoResponse {
// Validate input
diff --git a/services/document_storage_service/src/api/documents/get_full_pdf_modification_data.rs b/services/document_storage_service/src/api/documents/get_full_pdf_modification_data.rs
index de41124eac..07c04e18e5 100644
--- a/services/document_storage_service/src/api/documents/get_full_pdf_modification_data.rs
+++ b/services/document_storage_service/src/api/documents/get_full_pdf_modification_data.rs
@@ -8,7 +8,7 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::document::build_pdf_modification_data::{
get_complete_pdf_modification_data, get_pdf_modification_data_for_document,
};
@@ -39,10 +39,10 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, document_context), fields(user_id=?user.macro_user_id, file_type=?document_context.file_type))]
+#[tracing::instrument(skip(ctx, user, document_context), fields(user_id=?user.authorization.user.macro_user_id, file_type=?document_context.file_type))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
) -> impl IntoResponse {
diff --git a/services/document_storage_service/src/api/documents/get_user_documents.rs b/services/document_storage_service/src/api/documents/get_user_documents.rs
index 12bbd7b0a2..15f49acca0 100644
--- a/services/document_storage_service/src/api/documents/get_user_documents.rs
+++ b/services/document_storage_service/src/api/documents/get_user_documents.rs
@@ -8,7 +8,7 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::document::get_user_documents;
use model::response::{GenericErrorResponse, GenericResponse};
use sqlx::PgPool;
@@ -30,11 +30,11 @@ use sqlx::PgPool;
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(db, user, params), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(db, user, params), fields(user_id=?user.authorization.user.macro_user_id))]
#[axum::debug_handler(state = crate::api::context::ApiContext)]
pub async fn get_user_documents_handler(
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Query(params): Query<GetUserDocumentsQueryParams>,
) -> impl IntoResponse {
if let Some(limit) = params.limit
@@ -54,7 +54,7 @@ pub async fn get_user_documents_handler(
let documents = match get_user_documents(
&db,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
query_params.limit,
query_params.offset,
query_params.file_type,
@@ -63,7 +63,7 @@ pub async fn get_user_documents_handler(
{
Ok(documents) => documents,
Err(e) => {
- tracing::error!(error=?e, user_id=?user.macro_user_id, "failed to get user documents");
+ tracing::error!(error=?e, user_id=?user.authorization.user.macro_user_id, "failed to get user documents");
return GenericResponse::builder()
.message("failed to get documents")
.is_error(true)
diff --git a/services/document_storage_service/src/api/documents/initialize_how_to_guide.rs b/services/document_storage_service/src/api/documents/initialize_how_to_guide.rs
index be5b4e724d..d28415ea19 100644
--- a/services/document_storage_service/src/api/documents/initialize_how_to_guide.rs
+++ b/services/document_storage_service/src/api/documents/initialize_how_to_guide.rs
@@ -8,7 +8,7 @@ use documents_hex::domain::create::{
};
use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
use favorites::domain::ports::FavoritesService;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{ErrorResponse, GenericSuccessResponse};
use model_entity::EntityType;
use reqwest::StatusCode;
@@ -19,10 +19,10 @@ const HOW_TO_GUIDE_TEMPLATE: &str = include_str!("./template/macro_how_to_guide.
/// Creates the "Macro how to guide" markdown document for the user and pins it
/// to their sidebar favorites. Called by the authentication service when a new
/// user signs up.
-#[tracing::instrument(skip(state, user_context), fields(user_id=?user_context.macro_user_id))]
+#[tracing::instrument(skip(state, user_context), fields(user_id=?user_context.authorization.user.macro_user_id))]
pub async fn handler(
State(state): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
tracing::info!("initialize how to guide");
@@ -30,7 +30,7 @@ pub async fn handler(
.documents_state
.creator
.create_markdown_text(
- user_context.macro_user_id.clone(),
+ user_context.authorization.user.macro_user_id.clone(),
NewMarkdownTextDocument {
metadata: NewDocumentMetadata::builder(HOW_TO_GUIDE_NAME).build(),
markdown: HOW_TO_GUIDE_TEMPLATE.to_string(),
@@ -52,8 +52,13 @@ pub async fn handler(
let receipt = state
.entity_access_service
.generate_entity_access_receipt::<ViewAccessLevel>(
- &user_context.macro_user_id,
- user_context.user_context.organization_id.map(i64::from),
+ &user_context.authorization.user.macro_user_id,
+ user_context
+ .authorization
+ .user
+ .user_context
+ .organization_id
+ .map(i64::from),
created.document_id(),
EntityType::Document,
)
diff --git a/services/document_storage_service/src/api/documents/initialize_user_documents.rs b/services/document_storage_service/src/api/documents/initialize_user_documents.rs
index 4c96baf7d1..74f7819804 100644
--- a/services/document_storage_service/src/api/documents/initialize_user_documents.rs
+++ b/services/document_storage_service/src/api/documents/initialize_user_documents.rs
@@ -4,7 +4,7 @@ use axum::{
response::{IntoResponse, Json, Response},
};
use futures::StreamExt;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::cowlike::CowLike;
use model::{
document::BasicDocument,
@@ -33,10 +33,10 @@ const CANVAS_TEMPLATE: &str = include_str!("./template/canvas_template.canvas");
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user_context), fields(user_id=?user_context.macro_user_id))]
+#[tracing::instrument(skip(state, user_context), fields(user_id=?user_context.authorization.user.macro_user_id))]
pub async fn handler(
State(state): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
tracing::info!("initialize user documents");
let start_time = std::time::Instant::now();
@@ -82,7 +82,7 @@ pub async fn handler(
let project =
macro_db_client::document::initialize_onboarding_documents::create_project_transaction(
&mut transaction,
- user_context.macro_user_id.copied(),
+ user_context.authorization.user.macro_user_id.copied(),
PROJECT_NAME,
None,
&share_permission,
@@ -105,7 +105,7 @@ pub async fn handler(
let db_documents =
macro_db_client::document::initialize_onboarding_documents::create_onboarding_documents(
&mut transaction,
- user_context.macro_user_id.clone(),
+ user_context.authorization.user.macro_user_id.clone(),
&project.id,
&share_permission,
documents,
@@ -160,7 +160,7 @@ pub async fn handler(
let s3_client = shared_s3_client.clone(); // Clone the client for parallel usage
let markdown_template = shared_markdown_template.clone();
let canvas_template = shared_canvas_template.clone();
- let user_id = user_context.macro_user_id.clone();
+ let user_id = user_context.authorization.user.macro_user_id.clone();
async move {
let uri_document_name = urlencoding::encode(document.document_name.as_str());
let deref_file_type = document.file_type.as_deref();
@@ -218,7 +218,7 @@ pub async fn handler(
// Set the onboarding status to true so we don't do this again
macro_db_client::user::onboarding_status::set_onboarding_status(
&mut transaction,
- user_context.macro_user_id.as_ref(),
+ user_context.authorization.user.macro_user_id.as_ref(),
)
.await
.map_err(|e| {
diff --git a/services/document_storage_service/src/api/documents/job_processing_result.rs b/services/document_storage_service/src/api/documents/job_processing_result.rs
index 532167a77d..aed4f735f8 100644
--- a/services/document_storage_service/src/api/documents/job_processing_result.rs
+++ b/services/document_storage_service/src/api/documents/job_processing_result.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
-use macro_authorization::OptionalMacroAuthorizationExtractor;
+use macro_authorization::{OptionalMacroAuthorizationExtractor, UserOrInternalService};
use macro_db_client::document::get_document_process_content_from_job_id;
use model::response::GenericErrorResponse;
use model::response::GenericResponse;
@@ -33,15 +33,19 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(db, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(db, user), fields(actor = tracing::field::Empty))]
pub async fn job_processing_result_handler(
State(db): State<PgPool>,
- user: OptionalMacroAuthorizationExtractor<AuthorizationService>,
+ user: OptionalMacroAuthorizationExtractor<AuthorizationService, UserOrInternalService>,
Path(Params {
document_id,
job_id,
}): Path<Params>,
) -> impl IntoResponse {
+ if let Some(actor) = user.acting_entity() {
+ tracing::Span::current().record("actor", tracing::field::display(actor));
+ }
+
let processing_result =
match get_document_process_content_from_job_id(&db, job_id.as_str(), document_id.as_str())
.await
diff --git a/services/document_storage_service/src/api/documents/list_documents_with_access.rs b/services/document_storage_service/src/api/documents/list_documents_with_access.rs
index 7e933c672b..b906927b04 100644
--- a/services/document_storage_service/src/api/documents/list_documents_with_access.rs
+++ b/services/document_storage_service/src/api/documents/list_documents_with_access.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document::list::{DocumentListFilters, ListDocumentsWithAccessResponse};
use model::response::GenericErrorResponse;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -45,10 +45,10 @@ pub struct ListDocumentsWithAccessQuery {
(status = 500, body = GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn list_documents_with_access_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Query(query): Query<ListDocumentsWithAccessQuery>,
) -> impl IntoResponse {
let page_size = if query.page_size <= 0 || query.page_size > MAX_PAGE_SIZE {
@@ -93,7 +93,7 @@ pub async fn list_documents_with_access_handler(
let documents = match macro_db_client::document::list_documents_with_access(
&ctx.db,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
&filters,
min_access_level,
offset,
@@ -105,7 +105,7 @@ pub async fn list_documents_with_access_handler(
Err(e) => {
tracing::error!(
error=?e,
- user_id=?user.macro_user_id,
+ user_id=?user.authorization.user.macro_user_id,
"unable to list documents with access"
);
return (
diff --git a/services/document_storage_service/src/api/documents/location.rs b/services/document_storage_service/src/api/documents/location.rs
index 49db4632e1..1865856c23 100644
--- a/services/document_storage_service/src/api/documents/location.rs
+++ b/services/document_storage_service/src/api/documents/location.rs
@@ -1,7 +1,7 @@
use crate::api::context::ApiContext;
use crate::api::context::{AuthorizationService, EntityAccessService};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use models_permissions::share_permission::access_level::ViewAccessLevel;
use rayon::prelude::*;
use std::{
@@ -49,7 +49,7 @@ static DOCUMENT_DOES_NOT_EXIST: &str = "document does not exist in s3";
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, document_context, _access_level), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(state, user, document_context, _access_level), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn get_location_handler(
_access_level: DocumentAccessExtractor<
ViewAccessLevel,
@@ -57,7 +57,7 @@ pub async fn get_location_handler(
AuthorizationService,
>,
State(state): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
params: Query<LocationQueryParams>,
diff --git a/services/document_storage_service/src/api/documents/permissions_token/create_permission_token.rs b/services/document_storage_service/src/api/documents/permissions_token/create_permission_token.rs
index 072f3f5217..3936f78f58 100644
--- a/services/document_storage_service/src/api/documents/permissions_token/create_permission_token.rs
+++ b/services/document_storage_service/src/api/documents/permissions_token/create_permission_token.rs
@@ -8,7 +8,9 @@ use axum::{
use documents_hex::domain::permission_token::encode_permission_token;
use entity_access::domain::models::EntityPermission;
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::OptionalMacroAuthorizationExtractor;
+use macro_authorization::{
+ OptionalMacroAuthorizationExtractor, UserOrInternalService, UserOrInternalServiceAuthorization,
+};
use model::response::ErrorResponse;
use models_permissions::share_permission::access_level::{AccessLevel, ViewAccessLevel};
use serde::Deserialize;
@@ -43,10 +45,13 @@ pub struct DocumentPermissionsTokenResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user, users_access_level), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(
+ skip(state, user, users_access_level),
+ fields(actor = tracing::field::Empty)
+)]
pub async fn handler(
State(state): State<ApiContext>,
- user: OptionalMacroAuthorizationExtractor<AuthorizationService>,
+ user: OptionalMacroAuthorizationExtractor<AuthorizationService, UserOrInternalService>,
users_access_level: DocumentAccessExtractor<
ViewAccessLevel,
EntityAccessService,
@@ -54,7 +59,14 @@ pub async fn handler(
>,
Path(Params { document_id }): Path<Params>,
) -> Result<Response, Response> {
- let user_id = user.macro_user_id.map(|user_id| user_id.to_string());
+ if let Some(actor) = user.acting_entity() {
+ tracing::Span::current().record("actor", tracing::field::display(actor));
+ }
+ let user_id = user
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.to_string());
let access_level = match users_access_level.entity_access_receipt.entity_permission() {
EntityPermission::AccessLevel { access_level } => *access_level,
diff --git a/services/document_storage_service/src/api/documents/permissions_token/validate_permissions_token.rs b/services/document_storage_service/src/api/documents/permissions_token/validate_permissions_token.rs
index 05d59a2b3c..4a358317e3 100644
--- a/services/document_storage_service/src/api/documents/permissions_token/validate_permissions_token.rs
+++ b/services/document_storage_service/src/api/documents/permissions_token/validate_permissions_token.rs
@@ -7,7 +7,9 @@ use axum::{
response::{IntoResponse, Response},
};
use jsonwebtoken::{Algorithm, DecodingKey, Validation};
-use macro_authorization::OptionalMacroAuthorizationExtractor;
+use macro_authorization::{
+ OptionalMacroAuthorizationExtractor, UserOrInternalService, UserOrInternalServiceAuthorization,
+};
use macro_sync_service_jwt::ISSUER;
use model::{document::DocumentPermissionsToken, response::ErrorResponse};
use utoipa::ToSchema;
@@ -34,10 +36,13 @@ pub struct DocumentPermissionsTokenRequest {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(config_context, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(
+ skip(config_context, user),
+ fields(actor = tracing::field::Empty)
+)]
pub async fn handler(
State(config_context): State<Arc<Config>>,
- user: OptionalMacroAuthorizationExtractor<AuthorizationService>,
+ user: OptionalMacroAuthorizationExtractor<AuthorizationService, UserOrInternalService>,
extract::Json(DocumentPermissionsTokenRequest { token }): extract::Json<
DocumentPermissionsTokenRequest,
>,
@@ -47,7 +52,14 @@ pub async fn handler(
validation.set_issuer(&[ISSUER]);
- let user_id = user.macro_user_id.map(|user_id| user_id.to_string());
+ if let Some(actor) = user.acting_entity() {
+ tracing::Span::current().record("actor", tracing::field::display(actor));
+ }
+ let user_id = user
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.to_string());
// Attempt to decode the token.
let decoded_jwt: DocumentPermissionsToken = match jsonwebtoken::decode::<DocumentPermissionsToken>(
diff --git a/services/document_storage_service/src/api/documents/pre_save.rs b/services/document_storage_service/src/api/documents/pre_save.rs
index 053baa3cbf..508d2776f9 100644
--- a/services/document_storage_service/src/api/documents/pre_save.rs
+++ b/services/document_storage_service/src/api/documents/pre_save.rs
@@ -18,7 +18,7 @@ use crate::api::context::{AuthorizationService, EntityAccessService};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
#[allow(unused_imports)]
use futures::stream::StreamExt;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::GenericErrorResponse;
use model::{
@@ -50,13 +50,13 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
),
)]
-#[tracing::instrument(skip(state, document_context, user, req, _access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(state, document_context, user, req, _access), fields(user_id=?user.authorization.user.macro_user_id))]
#[allow(deprecated, reason = "we just want deprecated to show up in utoipa")]
#[deprecated(note = "we no longer support editing docx files as they are now converted to pdf.")]
pub async fn presave_document_handler(
_access: DocumentAccessExtractor<EditAccessLevel, EntityAccessService, AuthorizationService>,
State(state): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
Json(req): Json<PreSaveDocumentRequest>,
diff --git a/services/document_storage_service/src/api/documents/put_document_update.rs b/services/document_storage_service/src/api/documents/put_document_update.rs
index 05c618495c..d951a487f1 100644
--- a/services/document_storage_service/src/api/documents/put_document_update.rs
+++ b/services/document_storage_service/src/api/documents/put_document_update.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::{EmptyResponse, GenericErrorResponse};
#[derive(serde::Deserialize)]
@@ -31,7 +31,7 @@ pub struct Params {
#[tracing::instrument(skip(ctx, _auth))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _auth: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(Params { document_id }): Path<Params>,
) -> impl IntoResponse {
let res = macro_db_client::document::update::update_document(&ctx.db, &document_id).await;
diff --git a/services/document_storage_service/src/api/documents/revert_delete_document.rs b/services/document_storage_service/src/api/documents/revert_delete_document.rs
index d37255868a..4be36b1033 100644
--- a/services/document_storage_service/src/api/documents/revert_delete_document.rs
+++ b/services/document_storage_service/src/api/documents/revert_delete_document.rs
@@ -4,7 +4,7 @@ use axum::{Extension, extract::Path, http::StatusCode, response::IntoResponse};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
#[allow(unused_imports)]
use futures::stream::TryStreamExt;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document::DocumentBasic;
use model::response::{
GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse,
@@ -34,11 +34,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(db, user, document_context, _access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(db, user, document_context, _access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
_access: DocumentAccessExtractor<OwnerAccessLevel, EntityAccessService, AuthorizationService>,
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
) -> impl IntoResponse {
diff --git a/services/document_storage_service/src/api/documents/save_document/save_document_handler.rs b/services/document_storage_service/src/api/documents/save_document/save_document_handler.rs
index 44dc448233..cd08298c84 100644
--- a/services/document_storage_service/src/api/documents/save_document/save_document_handler.rs
+++ b/services/document_storage_service/src/api/documents/save_document/save_document_handler.rs
@@ -16,7 +16,7 @@ use axum::{
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document::response::DocumentResponseMetadata;
use model::{
document::{DocumentBasic, FileType, FileTypeExt},
@@ -48,11 +48,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, document_context, _access, project), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, document_context, _access, project), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn save_document_handler(
_access: DocumentAccessExtractor<EditAccessLevel, EntityAccessService, AuthorizationService>,
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
project: ProjectBodyAccessLevelExtractorV2<
diff --git a/services/document_storage_service/src/api/documents/simple_save.rs b/services/document_storage_service/src/api/documents/simple_save.rs
index ff4ebb4c91..83723f657b 100644
--- a/services/document_storage_service/src/api/documents/simple_save.rs
+++ b/services/document_storage_service/src/api/documents/simple_save.rs
@@ -13,7 +13,7 @@ use axum::{
response::IntoResponse,
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document::response::DocumentResponseMetadata;
use model::{
document::{DocumentBasic, FileType, FileTypeExt},
@@ -46,11 +46,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(_access, state, user, document_context, multipart), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(_access, state, user, document_context, multipart), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
_access: DocumentAccessExtractor<EditAccessLevel, EntityAccessService, AuthorizationService>,
State(state): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
mut multipart: Multipart,
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index 1a7fa28da0..a32480051f 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -13,7 +13,9 @@ use axum::{
};
use axum_extra::extract::Cached;
use complete_graph::GraphqlRequestParts;
-use macro_authorization::OptionalMacroAuthorizationExtractor;
+use macro_authorization::{
+ OptionalMacroAuthorizationExtractor, UserOrInternalService, UserOrInternalServiceAuthorization,
+};
use macro_user_id::user_id::MacroUserIdStr;
const GRAPHQL_PATH: &str = "/soup/graphql";
@@ -36,11 +38,20 @@ async fn graphiql() -> Html<String> {
async fn graphql_handler(
State(state): State<ApiContext>,
- Cached(auth): Cached<OptionalMacroAuthorizationExtractor<AuthorizationService>>,
+ Cached(auth): Cached<
+ OptionalMacroAuthorizationExtractor<AuthorizationService, UserOrInternalService>,
+ >,
request_parts: Parts,
request: GraphQLRequest,
) -> GraphQLResponse {
- let request = graphql_query_context_data(request.into_inner(), &state, auth.macro_user_id);
+ let request = graphql_query_context_data(
+ request.into_inner(),
+ &state,
+ auth.authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone()),
+ );
state
.graphql_soup_schema
.execute(request.data(GraphqlRequestParts::new(request_parts)))
@@ -50,11 +61,18 @@ async fn graphql_handler(
async fn subscription_handler(
State(state): State<ApiContext>,
- Cached(auth): Cached<OptionalMacroAuthorizationExtractor<AuthorizationService>>,
+ Cached(auth): Cached<
+ OptionalMacroAuthorizationExtractor<AuthorizationService, UserOrInternalService>,
+ >,
protocol: GraphQLProtocol,
upgrade: WebSocketUpgrade,
) -> Response {
- let Some(macro_user_id) = auth.macro_user_id else {
+ let Some(macro_user_id) = auth
+ .authorization
+ .as_ref()
+ .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone())
+ else {
return (
StatusCode::UNAUTHORIZED,
"authentication required for GraphQL Soup subscriptions",
diff --git a/services/document_storage_service/src/api/history/delete_history.rs b/services/document_storage_service/src/api/history/delete_history.rs
index 19791ac835..9d8a2826a8 100644
--- a/services/document_storage_service/src/api/history/delete_history.rs
+++ b/services/document_storage_service/src/api/history/delete_history.rs
@@ -1,7 +1,7 @@
use crate::api::context::{ApiContext, AuthorizationService};
use axum::extract::State;
use axum::{extract::Path, http::StatusCode, response::IntoResponse};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{
GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse,
};
@@ -26,21 +26,21 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn delete_history_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { item_type, item_id }): Path<Params>,
) -> impl IntoResponse {
if let Err(e) = macro_db_client::history::delete_user_history(
&ctx.db,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
item_id.as_str(),
item_type.as_str(),
)
.await
{
- tracing::error!(error=?e, user_id=?user.macro_user_id, "unable to delete history");
+ tracing::error!(error=?e, user_id=?user.authorization.user.macro_user_id, "unable to delete history");
return GenericResponse::builder()
.message("unable to delete history")
.is_error(true)
diff --git a/services/document_storage_service/src/api/history/get_history.rs b/services/document_storage_service/src/api/history/get_history.rs
index 1690d879cf..73e21fc691 100644
--- a/services/document_storage_service/src/api/history/get_history.rs
+++ b/services/document_storage_service/src/api/history/get_history.rs
@@ -2,7 +2,7 @@ use crate::api::context::{ApiContext, AuthorizationService};
use crate::model::response::history::GetUserHistoryResponse;
use axum::extract::State;
use axum::{Extension, http::StatusCode, response::IntoResponse};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{GenericErrorResponse, GenericResponse};
use model::version::ApiVersionEnum;
@@ -16,23 +16,23 @@ use model::version::ApiVersionEnum;
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn get_history_handler(
State(ctx): State<ApiContext>,
api_version: Extension<ApiVersionEnum>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> impl IntoResponse {
tracing::info!("get_history_handler");
let history = match macro_db_client::history::get_user_history(
&ctx.db,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
)
.await
{
Ok(history) => history,
Err(e) => {
- tracing::error!(error=?e, user_id=?user.macro_user_id, "unable to get history");
+ tracing::error!(error=?e, user_id=?user.authorization.user.macro_user_id, "unable to get history");
return GenericResponse::builder()
.message("unable to get history")
.is_error(true)
diff --git a/services/document_storage_service/src/api/history/upsert_history.rs b/services/document_storage_service/src/api/history/upsert_history.rs
index 66029918e3..7e82c87bb8 100644
--- a/services/document_storage_service/src/api/history/upsert_history.rs
+++ b/services/document_storage_service/src/api/history/upsert_history.rs
@@ -4,7 +4,7 @@ use axum::extract::State;
use axum::{extract::Path, http::StatusCode, response::IntoResponse};
use entity_access::domain::models::EntityPermission;
use entity_access::inbound::axum_extractors::HistoryAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{
GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse,
};
@@ -32,7 +32,7 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, history_access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, history_access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn upsert_history_handler(
history_access: HistoryAccessExtractor<
ViewAccessLevel,
@@ -40,7 +40,7 @@ pub async fn upsert_history_handler(
AuthorizationService,
>,
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { item_type, item_id }): Path<Params>,
) -> impl IntoResponse {
let access_level = match history_access.entity_access_receipt.entity_permission() {
@@ -85,7 +85,7 @@ pub async fn upsert_history_handler(
if let Err(e) = macro_db_client::history::upsert_user_history(
&mut transaction,
- user.macro_user_id.clone(),
+ user.authorization.user.macro_user_id.clone(),
item_id.as_str(),
item_type.as_str(),
)
@@ -103,7 +103,7 @@ pub async fn upsert_history_handler(
&& let Err(e) = macro_db_client::document::track_document::track_document(
&mut transaction,
item_id.as_str(),
- Some(user.macro_user_id.as_ref()),
+ Some(user.authorization.user.macro_user_id.as_ref()),
)
.await
{
diff --git a/services/document_storage_service/src/api/instructions/create_instructions.rs b/services/document_storage_service/src/api/instructions/create_instructions.rs
index b123037fe8..631fb4be3a 100644
--- a/services/document_storage_service/src/api/instructions/create_instructions.rs
+++ b/services/document_storage_service/src/api/instructions/create_instructions.rs
@@ -6,7 +6,7 @@ use axum::{Json, extract::State};
use documents_hex::domain::create::{NewDocumentMetadata, NewMarkdownTextDocument};
use documents_hex::domain::models::DocumentError;
use documents_hex::domain::ports::create::DocumentCreationService as _;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::instructions::create::{
CreateInstructionsError, insert_instructions_document,
};
@@ -25,12 +25,12 @@ use models_dcs::constants::INSTRUCTIONS_FILE_NAME;
(status = 500, body = GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.macro_user_id))]
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.authorization.user.macro_user_id))]
pub async fn create_instructions_handler(
State(ctx): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Json<CreateInstructionsDocumentResponse>, DocumentError> {
- let user_id = user_context.macro_user_id;
+ let user_id = user_context.authorization.user.macro_user_id.clone();
if get_instructions_document(&ctx.db, user_id.clone())
.await
diff --git a/services/document_storage_service/src/api/instructions/get_instructions.rs b/services/document_storage_service/src/api/instructions/get_instructions.rs
index 6aa0b26a56..fa5d34c973 100644
--- a/services/document_storage_service/src/api/instructions/get_instructions.rs
+++ b/services/document_storage_service/src/api/instructions/get_instructions.rs
@@ -3,7 +3,7 @@ use crate::{
model::response::instructions::GetInstructionsDocumentResponse,
};
use axum::{Json, extract::State, http::StatusCode, response::IntoResponse};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::cowlike::CowLike;
use model::response::{GenericErrorResponse, GenericResponse};
@@ -18,14 +18,14 @@ use model::response::{GenericErrorResponse, GenericResponse};
(status = 500, body = GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.macro_user_id))]
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.authorization.user.macro_user_id))]
pub async fn get_instructions_handler(
State(ctx): State<ApiContext>,
- user_context: MacroAuthorizationExtractor<AuthorizationService>,
+ user_context: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> impl IntoResponse {
match macro_db_client::instructions::get::get_instructions_document(
&ctx.db,
- user_context.macro_user_id.copied(),
+ user_context.authorization.user.macro_user_id.copied(),
)
.await
{
@@ -38,7 +38,7 @@ pub async fn get_instructions_handler(
.is_error(true)
.send(StatusCode::NOT_FOUND),
Err(err) => {
- tracing::error!(error=?err, user_id=%user_context.macro_user_id, "failed to get instructions document");
+ tracing::error!(error=?err, user_id=%user_context.authorization.user.macro_user_id, "failed to get instructions document");
GenericResponse::builder()
.message("Failed to get instructions document")
.is_error(true)
diff --git a/services/document_storage_service/src/api/internal/associate_github_installations.rs b/services/document_storage_service/src/api/internal/associate_github_installations.rs
index be107fe23c..a3cc048110 100644
--- a/services/document_storage_service/src/api/internal/associate_github_installations.rs
+++ b/services/document_storage_service/src/api/internal/associate_github_installations.rs
@@ -5,7 +5,7 @@ use axum::{
response::{IntoResponse, Response},
};
use github::domain::ports::GithubSyncService;
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::{EmptyResponse, GenericErrorResponse};
#[derive(serde::Deserialize)]
@@ -33,7 +33,7 @@ pub struct Params {
#[tracing::instrument(skip(ctx, _auth), err(Debug))]
pub async fn associate_github_installations_handler(
State(ctx): State<ApiContext>,
- _auth: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(Params { github_user_id }): Path<Params>,
) -> Result<Response, Response> {
ctx.github_sync_service
diff --git a/services/document_storage_service/src/api/internal/mod.rs b/services/document_storage_service/src/api/internal/mod.rs
index e6bbfe4fcf..90078a0777 100644
--- a/services/document_storage_service/src/api/internal/mod.rs
+++ b/services/document_storage_service/src/api/internal/mod.rs
@@ -23,7 +23,7 @@ use axum::{
Router,
routing::{delete, get, post, put},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use macro_middleware::cloud_storage::{
document::ensure_document_exists, thread::ensure_thread_exists,
};
@@ -199,7 +199,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
}
async fn health_handler(
- _auth: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
) -> &'static str {
"healthy"
}
diff --git a/services/document_storage_service/src/api/items/get_item_ids.rs b/services/document_storage_service/src/api/items/get_item_ids.rs
index a9c65cc7d0..7ea71c447d 100644
--- a/services/document_storage_service/src/api/items/get_item_ids.rs
+++ b/services/document_storage_service/src/api/items/get_item_ids.rs
@@ -3,7 +3,7 @@ use crate::api::context::{ApiContext, AuthorizationService};
use axum::Json;
use axum::extract::{Query, State};
use axum::http::StatusCode;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document_storage_service_internal::GetItemIDsResponse;
#[derive(serde::Deserialize)]
@@ -13,10 +13,10 @@ pub struct Params {
}
/// Gets the ids of the items the user has access to
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn get_item_ids_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Query(Params {
item_type,
exclude_owned,
@@ -24,7 +24,7 @@ pub async fn get_item_ids_handler(
) -> Result<(StatusCode, Json<GetItemIDsResponse>), (StatusCode, String)> {
tracing::info!("get_item_ids");
- let user_id = user.user_context.user_id.clone();
+ let user_id = user.authorization.user.user_context.user_id.clone();
if matches!(user_id.as_str(), "" | MACRO_INTERNAL_USER_ID) {
return Err((
diff --git a/services/document_storage_service/src/api/items/validate_item_ids.rs b/services/document_storage_service/src/api/items/validate_item_ids.rs
index 1e4ce7173b..08285536cd 100644
--- a/services/document_storage_service/src/api/items/validate_item_ids.rs
+++ b/services/document_storage_service/src/api/items/validate_item_ids.rs
@@ -2,19 +2,19 @@ use crate::api::MACRO_INTERNAL_USER_ID;
use crate::api::context::{ApiContext, AuthorizationService};
use axum::extract::{Json, State};
use axum::http::StatusCode;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document_storage_service_internal::{ValidateItemIDsRequest, ValidateItemIDsResponse};
/// Validates the user has access to the provided list of item ids
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(req): Json<ValidateItemIDsRequest>,
) -> Result<(StatusCode, Json<ValidateItemIDsResponse>), (StatusCode, String)> {
tracing::info!("validate_item_ids");
- let user_id = user.user_context.user_id.clone();
+ let user_id = user.authorization.user.user_context.user_id.clone();
if matches!(user_id.as_str(), "" | MACRO_INTERNAL_USER_ID) {
return Err((
diff --git a/services/document_storage_service/src/api/middleware/ensure_user_is_onboarded.rs b/services/document_storage_service/src/api/middleware/ensure_user_is_onboarded.rs
index 11ad4c0432..b28550e182 100644
--- a/services/document_storage_service/src/api/middleware/ensure_user_is_onboarded.rs
+++ b/services/document_storage_service/src/api/middleware/ensure_user_is_onboarded.rs
@@ -5,17 +5,17 @@ use axum::{
middleware::Next,
response::Response,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::user::onboarding_status::get_onboarding_status;
use sqlx::PgPool;
pub async fn handler(
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
req: Request,
next: Next,
) -> Result<Response, (StatusCode, String)> {
- let is_onboarded = get_onboarding_status(&db, user.macro_user_id.as_ref())
+ let is_onboarded = get_onboarding_status(&db, user.authorization.user.macro_user_id.as_ref())
.await
.map_err(|e| {
(
diff --git a/services/document_storage_service/src/api/notification/get_document_notification_users.rs b/services/document_storage_service/src/api/notification/get_document_notification_users.rs
index 1b102bf1d4..bf06a3f37e 100644
--- a/services/document_storage_service/src/api/notification/get_document_notification_users.rs
+++ b/services/document_storage_service/src/api/notification/get_document_notification_users.rs
@@ -3,7 +3,7 @@ use axum::Json;
use axum::extract::State;
use axum::response::Response;
use axum::{extract::Path, http::StatusCode, response::IntoResponse};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::GenericErrorResponse;
use sqlx::PgPool;
@@ -30,7 +30,7 @@ pub struct Params {
#[tracing::instrument(skip(db, _auth))]
pub async fn handler(
State(db): State<PgPool>,
- _auth: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(Params { document_id }): Path<Params>,
) -> Result<Response, Response> {
let users =
diff --git a/services/document_storage_service/src/api/notification/get_project_notification_users.rs b/services/document_storage_service/src/api/notification/get_project_notification_users.rs
index 103fc58551..71de567e5d 100644
--- a/services/document_storage_service/src/api/notification/get_project_notification_users.rs
+++ b/services/document_storage_service/src/api/notification/get_project_notification_users.rs
@@ -3,7 +3,7 @@ use axum::Json;
use axum::extract::State;
use axum::response::Response;
use axum::{extract::Path, http::StatusCode, response::IntoResponse};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::GenericErrorResponse;
use sqlx::PgPool;
@@ -30,7 +30,7 @@ pub struct Params {
#[tracing::instrument(skip(db, _auth))]
pub async fn handler(
State(db): State<PgPool>,
- _auth: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(Params { project_id }): Path<Params>,
) -> Result<Response, Response> {
let users =
diff --git a/services/document_storage_service/src/api/pins/add_pin.rs b/services/document_storage_service/src/api/pins/add_pin.rs
index 85e81e5e7c..2392fecd59 100644
--- a/services/document_storage_service/src/api/pins/add_pin.rs
+++ b/services/document_storage_service/src/api/pins/add_pin.rs
@@ -9,7 +9,7 @@ use axum::{
};
use entity_access::inbound::axum_extractors::PinAccessLevelExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{
GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse,
};
@@ -36,11 +36,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, pin_type, inner), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, pin_type, inner), fields(user_id=?user.authorization.user.macro_user_id))]
#[axum::debug_handler(state = ApiContext)]
pub async fn add_pin_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { pinned_item_id }): Path<Params>,
PinAccessLevelExtractor {
pin_type, inner, ..
@@ -53,7 +53,7 @@ pub async fn add_pin_handler(
) -> impl IntoResponse {
match macro_db_client::pins::upsert_pin(
ctx.db.clone(),
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
pinned_item_id.as_str(),
pin_type.pin_type.as_str(),
inner.pin_index,
@@ -62,7 +62,7 @@ pub async fn add_pin_handler(
{
Ok(_) => (),
Err(err) => {
- tracing::error!(error=?err, user_id=?user.macro_user_id, "failed to add pin");
+ tracing::error!(error=?err, user_id=?user.authorization.user.macro_user_id, "failed to add pin");
return GenericResponse::builder()
.message("failed to add pin")
.is_error(true)
diff --git a/services/document_storage_service/src/api/pins/get_pins.rs b/services/document_storage_service/src/api/pins/get_pins.rs
index cf767e7488..722b60255f 100644
--- a/services/document_storage_service/src/api/pins/get_pins.rs
+++ b/services/document_storage_service/src/api/pins/get_pins.rs
@@ -5,7 +5,7 @@ use crate::{
};
use axum::extract::State;
use axum::{http::StatusCode, response::IntoResponse};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{GenericErrorResponse, GenericResponse};
/// Gets the users pinned items
@@ -18,17 +18,20 @@ use model::response::{GenericErrorResponse, GenericResponse};
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn get_pins_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> impl IntoResponse {
- let pins = match macro_db_client::pins::get_pins(ctx.db.clone(), user.macro_user_id.as_ref())
- .await
+ let pins = match macro_db_client::pins::get_pins(
+ ctx.db.clone(),
+ user.authorization.user.macro_user_id.as_ref(),
+ )
+ .await
{
Ok(pins) => pins,
Err(err) => {
- tracing::error!(error=?err, user_id=?user.macro_user_id, "failed to get users pinned items");
+ tracing::error!(error=?err, user_id=?user.authorization.user.macro_user_id, "failed to get users pinned items");
return GenericResponse::builder()
.message("failed to get pins")
.is_error(true)
diff --git a/services/document_storage_service/src/api/pins/remove_pin.rs b/services/document_storage_service/src/api/pins/remove_pin.rs
index bbc99c3721..2dc1d88cfa 100644
--- a/services/document_storage_service/src/api/pins/remove_pin.rs
+++ b/services/document_storage_service/src/api/pins/remove_pin.rs
@@ -7,7 +7,7 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{
GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse,
};
@@ -32,16 +32,16 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn remove_pin_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { pinned_item_id }): Path<Params>,
Json(req): Json<PinRequest>,
) -> impl IntoResponse {
match macro_db_client::pins::remove_pin(
ctx.db.clone(),
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
pinned_item_id.as_str(),
req.pin_type.as_str(),
)
@@ -49,7 +49,7 @@ pub async fn remove_pin_handler(
{
Ok(_) => (),
Err(err) => {
- tracing::error!(error=?err, user_id=?user.macro_user_id, "failed to add pin");
+ tracing::error!(error=?err, user_id=?user.authorization.user.macro_user_id, "failed to add pin");
return GenericResponse::builder()
.message("failed to add pin")
.is_error(true)
diff --git a/services/document_storage_service/src/api/pins/reorder_pins.rs b/services/document_storage_service/src/api/pins/reorder_pins.rs
index 284dcd3ae3..4dc88c888a 100644
--- a/services/document_storage_service/src/api/pins/reorder_pins.rs
+++ b/services/document_storage_service/src/api/pins/reorder_pins.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::{
pin::request::ReorderPinRequest,
response::{GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse},
@@ -21,18 +21,22 @@ use model::{
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, req), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, req), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn reorder_pins_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
extract::Json(req): extract::Json<Vec<ReorderPinRequest>>,
) -> impl IntoResponse {
- match macro_db_client::pins::reorder_pins(ctx.db.clone(), user.macro_user_id.as_ref(), req)
- .await
+ match macro_db_client::pins::reorder_pins(
+ ctx.db.clone(),
+ user.authorization.user.macro_user_id.as_ref(),
+ req,
+ )
+ .await
{
Ok(_) => (),
Err(err) => {
- tracing::error!(error=?err, user_id=?user.macro_user_id, "failed to reorder pins");
+ tracing::error!(error=?err, user_id=?user.authorization.user.macro_user_id, "failed to reorder pins");
return GenericResponse::builder()
.message("failed to reorder pins")
.is_error(true)
diff --git a/services/document_storage_service/src/api/recents/recently_deleted.rs b/services/document_storage_service/src/api/recents/recently_deleted.rs
index a015f10a2f..b0b7e6ed15 100644
--- a/services/document_storage_service/src/api/recents/recently_deleted.rs
+++ b/services/document_storage_service/src/api/recents/recently_deleted.rs
@@ -1,7 +1,7 @@
use crate::api::context::AuthorizationService;
use axum::extract::State;
use axum::{http::StatusCode, response::IntoResponse};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::item::Item;
use model::response::{GenericErrorResponse, GenericResponse, TypedSuccessResponse};
use sqlx::PgPool;
@@ -28,16 +28,16 @@ pub type RecentlyDeletedResponse = TypedSuccessResponse<RecentlyDeletedResponseD
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(db, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(db, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
State(db): State<PgPool>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> impl IntoResponse {
tracing::info!("recently_deleted");
let items = match macro_db_client::recents::deleted::get_recently_deleted(
&db,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
)
.await
{
diff --git a/services/document_storage_service/src/api/saved_views.rs b/services/document_storage_service/src/api/saved_views.rs
index d8c6ada854..e0dba33c1d 100644
--- a/services/document_storage_service/src/api/saved_views.rs
+++ b/services/document_storage_service/src/api/saved_views.rs
@@ -5,7 +5,7 @@ use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, patch, post};
use axum::{Router, routing::get};
-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationState};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationState, UserOrInternal};
use model::response::ErrorResponse;
use model::user::UserContext;
use saved_views::{ExcludedDefaultViewStorage, PgViewStorage, ViewStorage};
@@ -131,7 +131,7 @@ where
let db = PgPool::from_ref(state);
let user =
- MacroAuthorizationExtractor::<AuthorizationService>::from_request_parts(parts, state)
+ MacroAuthorizationExtractor::<AuthorizationService, UserOrInternal>::from_request_parts(parts, state)
.await
.map_err(|_| SavedViewErr::Unauthorized)?;
@@ -143,11 +143,11 @@ where
authorize_view_access(
&PgViewStorage::new(db),
saved_view_id,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
)
.await?;
- Ok(SavedViewOwner(user.user_context))
+ Ok(SavedViewOwner(user.authorization.user.user_context.clone()))
}
}
@@ -161,22 +161,22 @@ where
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id), err)]
async fn get_views_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<(StatusCode, Json<ViewsResponse>), SavedViewErr> {
let pg_view_storage = PgViewStorage::new(ctx.db.clone());
let (views, excluded_default_views) = try_join!(
async {
pg_view_storage
- .get_views_for_user(user.macro_user_id.as_ref())
+ .get_views_for_user(user.authorization.user.macro_user_id.as_ref())
.await
},
async {
pg_view_storage
- .get_excluded_default_views_for_user(user.macro_user_id.as_ref())
+ .get_excluded_default_views_for_user(user.authorization.user.macro_user_id.as_ref())
.await
}
)?;
@@ -202,13 +202,13 @@ async fn get_views_handler(
)]
async fn create_view_handler(
ctx: State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(create_view_request): Json<CreateViewRequest>,
) -> Result<(StatusCode, Json<View>), SavedViewErr> {
let pg_view_storage = PgViewStorage::new(ctx.db.clone());
let new_view = View::new(
- user.macro_user_id.to_string(),
+ user.authorization.user.macro_user_id.to_string(),
create_view_request.name,
create_view_request.config,
);
@@ -286,10 +286,10 @@ async fn patch_view_handler(
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id), err)]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id), err)]
pub async fn exclude_default_view_handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(ExcludeDefaultViewRequest {
default_view_id: id,
}): Json<ExcludeDefaultViewRequest>,
@@ -298,7 +298,7 @@ pub async fn exclude_default_view_handler(
pg_view_storage
.create_excluded_default_view(ExcludedDefaultView::new(
- user.macro_user_id.to_string(),
+ user.authorization.user.macro_user_id.to_string(),
id.to_string(),
))
.await?;
diff --git a/services/document_storage_service/src/api/threads/edit_thread.rs b/services/document_storage_service/src/api/threads/edit_thread.rs
index 3ec00af633..b8f02cff0f 100644
--- a/services/document_storage_service/src/api/threads/edit_thread.rs
+++ b/services/document_storage_service/src/api/threads/edit_thread.rs
@@ -7,7 +7,7 @@ use axum::{Extension, Json, extract};
use entity_access::domain::models::EntityPermission;
use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;
use entity_access::inbound::axum_extractors::ThreadAccessLevelExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::share_permission::edit::edit_thread_permission;
use model::response::{
ErrorResponse, GenericErrorResponse, GenericSuccessResponse, SuccessResponse,
@@ -48,7 +48,7 @@ pub struct PatchThreadRequestV2 {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, project, thread_access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, project, thread_access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn edit_thread_handler(
thread_access: ThreadAccessLevelExtractor<
OwnerAccessLevel,
@@ -56,7 +56,7 @@ pub async fn edit_thread_handler(
AuthorizationService,
>,
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
thread_context: Extension<EmailThreadPermission>,
extract::Path(ThreadParams { thread_id }): extract::Path<ThreadParams>,
project: ProjectBodyAccessLevelExtractorV2<
diff --git a/services/document_storage_service/src/api/threads/get_thread_access_level.rs b/services/document_storage_service/src/api/threads/get_thread_access_level.rs
index 16c5ae3487..c0742f182f 100644
--- a/services/document_storage_service/src/api/threads/get_thread_access_level.rs
+++ b/services/document_storage_service/src/api/threads/get_thread_access_level.rs
@@ -4,7 +4,7 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use entity_access::domain::ports::EntityAccessService;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::GenericResponse;
use model::thread::response::GetThreadUserAccessLevelResponse;
use model_entity::EntityType;
@@ -14,16 +14,16 @@ use models_permissions::share_permission::access_level::AccessLevel;
pub struct Params {
pub thread_id: String,
}
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { thread_id }): Path<Params>,
) -> impl IntoResponse {
let user_access_level: Option<AccessLevel> = match ctx
.entity_access_service
.get_access_level(
- Some(&user.macro_user_id),
+ Some(&user.authorization.user.macro_user_id),
&thread_id,
EntityType::EmailThread,
)
diff --git a/services/document_storage_service/src/api/user/delete_user_items.rs b/services/document_storage_service/src/api/user/delete_user_items.rs
index 5c853e3609..13260fce14 100644
--- a/services/document_storage_service/src/api/user/delete_user_items.rs
+++ b/services/document_storage_service/src/api/user/delete_user_items.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::{EmptyResponse, GenericErrorResponse};
#[derive(serde::Deserialize)]
@@ -29,7 +29,7 @@ pub struct Params {
#[tracing::instrument(skip(ctx, _auth))]
pub async fn delete_user_items_handler(
State(ctx): State<ApiContext>,
- _auth: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(Params { user_id }): Path<Params>,
) -> Result<Response, Response> {
tracing::info!("deleting user dss items");
diff --git a/services/document_storage_service/src/api/user/populate_items.rs b/services/document_storage_service/src/api/user/populate_items.rs
index 0995a0dcb9..14baa893d6 100644
--- a/services/document_storage_service/src/api/user/populate_items.rs
+++ b/services/document_storage_service/src/api/user/populate_items.rs
@@ -1,6 +1,6 @@
use crate::api::context::AuthorizationService;
use axum::{http::StatusCode, response::IntoResponse};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{GenericErrorResponse, GenericResponse, GenericSuccessResponse};
/// Populates the users items
@@ -18,9 +18,9 @@ use model::response::{GenericErrorResponse, GenericResponse, GenericSuccessRespo
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(user), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn populate_items_handler(
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> impl IntoResponse {
let response_data = GenericSuccessResponse { success: true };
diff --git a/services/document_storage_service/src/api/user_document_view_location/delete_user_document_view_location.rs b/services/document_storage_service/src/api/user_document_view_location/delete_user_document_view_location.rs
index 6e5d1819c1..8bf5b64d13 100644
--- a/services/document_storage_service/src/api/user_document_view_location/delete_user_document_view_location.rs
+++ b/services/document_storage_service/src/api/user_document_view_location/delete_user_document_view_location.rs
@@ -6,7 +6,7 @@ use axum::{
response::{IntoResponse, Json},
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, GenericErrorResponse, GenericResponse};
use models_permissions::share_permission::access_level::ViewAccessLevel;
@@ -28,16 +28,16 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, _document), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, _document), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
_document: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService, AuthorizationService>,
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { document_id }): Path<Params>,
) -> impl IntoResponse {
match macro_db_client::user_document_view_location::delete::delete_user_document_view_location(
&ctx.db,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
&document_id,
)
.await
diff --git a/services/document_storage_service/src/api/user_document_view_location/get_user_document_view_location.rs b/services/document_storage_service/src/api/user_document_view_location/get_user_document_view_location.rs
index 9c5c8bd9a4..aa0b984c80 100644
--- a/services/document_storage_service/src/api/user_document_view_location/get_user_document_view_location.rs
+++ b/services/document_storage_service/src/api/user_document_view_location/get_user_document_view_location.rs
@@ -7,7 +7,7 @@ use axum::{
response::{IntoResponse, Json},
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{GenericErrorResponse, GenericResponse};
use models_permissions::share_permission::access_level::ViewAccessLevel;
use serde::Deserialize;
@@ -32,16 +32,16 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, _access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, _access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
_access: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService, AuthorizationService>,
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { document_id }): Path<Params>,
) -> impl IntoResponse {
match macro_db_client::user_document_view_location::get::get_user_document_view_location(
&ctx.db,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
&document_id,
)
.await
diff --git a/services/document_storage_service/src/api/user_document_view_location/upsert_user_document_view_location.rs b/services/document_storage_service/src/api/user_document_view_location/upsert_user_document_view_location.rs
index e420a11f8b..a0413b306e 100644
--- a/services/document_storage_service/src/api/user_document_view_location/upsert_user_document_view_location.rs
+++ b/services/document_storage_service/src/api/user_document_view_location/upsert_user_document_view_location.rs
@@ -7,7 +7,7 @@ use axum::{
response::{IntoResponse, Json},
};
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, GenericErrorResponse, GenericResponse};
use models_permissions::share_permission::access_level::ViewAccessLevel;
@@ -30,18 +30,18 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user, req, _access), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user, req, _access), fields(user_id=?user.authorization.user.macro_user_id))]
pub async fn handler(
_access: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService, AuthorizationService>,
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { document_id }): Path<Params>,
extract::Json(req): extract::Json<UpsertUserDocumentViewLocationRequest>,
) -> impl IntoResponse {
if let Err(e) =
macro_db_client::user_document_view_location::upsert::upsert_user_document_view_location(
&ctx.db,
- user.macro_user_id.as_ref(),
+ user.authorization.user.macro_user_id.as_ref(),
&document_id,
&req.location,
)
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 03ad704c0a..9a2d4c2816 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -14,6 +14,7 @@ use crate::{
};
use analytics_client::{AnalyticsClient, AnalyticsClientConfig, MetaConfig};
use anyhow::Context;
+use bots::{domain::service::BotServiceImpl, outbound::pg_bots_repo::PgBotsRepo};
use cal::{
domain::service::{CalConfig, CalEventMeta, CalWebhookServiceImpl},
inbound::cal_webhook_router::CalWebhookRouterState,
@@ -77,7 +78,10 @@ use github::outbound::github_sync_client::GithubSyncClientImpl;
use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;
use lexical_client::LexicalClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState};
+use macro_authorization::{
+ InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
+ MacroAuthorizationState, PgBotAuthorizationRepo, PgBotAuthorizer,
+};
use macro_entrypoint::MacroEntrypoint;
use macro_env_var::maybe_env_vars;
use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
@@ -259,13 +263,23 @@ async fn main() -> anyhow::Result<()> {
let jwt_validation_args =
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await?;
- let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(
+
+ let macro_event_broker = MacroEventBrokerService::new(
+ KafkaEventPublisher::new(config.kafka_brokers.as_ref())
+ .context("failed to create kafka event publisher")?,
+ );
+ let bots_repo = PgBotsRepo::new(db.clone());
+ let bots_service = BotServiceImpl::new(bots_repo, macro_event_broker.clone());
+
+ let authorization_service: AuthorizationService = MacroAuthorizationServiceImpl::new(
MacroAuthJwtValidator::new(jwt_validation_args.clone()),
InternalAuthConfig {
api_key: dss_auth_key.as_ref().to_string(),
default_user_id: Some(MACRO_INTERNAL_USER_ID.to_string()),
},
- )));
+ PgBotAuthorizer::new(PgBotAuthorizationRepo::new(db.clone())),
+ );
+ let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));
// Initialize OpenSearch client
let opensearch_client = OpensearchClient::new(
@@ -424,11 +438,6 @@ async fn main() -> anyhow::Result<()> {
entity_access_management::outbound::PgRepository::new(db.clone()),
);
- let macro_event_broker = MacroEventBrokerService::new(
- KafkaEventPublisher::new(config.kafka_brokers.as_ref())
- .context("failed to create kafka event publisher")?,
- );
-
let project_service = Arc::new(ProjectServiceImpl::new(
PgProjectRepo::new(db.clone()),
S3ProjectUploadAdapter::new(
@@ -783,9 +792,6 @@ async fn main() -> anyhow::Result<()> {
Arc::new(PgTaskMatchRepo::new(db.clone())),
));
let channels_repo = PgChannelsRepo::new(db.clone());
- let bots_repo = bots::outbound::pg_bots_repo::PgBotsRepo::new(db.clone());
- let bots_service =
- bots::domain::service::BotServiceImpl::new(bots_repo.clone(), macro_event_broker.clone());
let (bot_trigger_sender, bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();
let channel_side_effects = ChannelSideEffectService::new(
diff --git a/services/email_service/src/api/email/attachments/get.rs b/services/email_service/src/api/email/attachments/get.rs
index fa11aaa14f..6601f2ccbe 100644
--- a/services/email_service/src/api/email/attachments/get.rs
+++ b/services/email_service/src/api/email/attachments/get.rs
@@ -5,7 +5,7 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use cloudfront_sign::{SignedOptions, get_signed_url};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use models_email::email::service::attachment;
use models_email::service;
@@ -36,18 +36,18 @@ pub struct GetAttachmentResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id
))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(attachment_id): Path<Uuid>,
) -> Result<Response, Response> {
// Resolve which of the caller's inboxes owns this attachment. Each inbox is a
// distinct Google account, so the owning link also determines the Gmail token.
let links = email_db_client::links::get::fetch_inboxes_for_macro_id(
&ctx.db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
)
.await
.map_err(|e| {
diff --git a/services/email_service/src/api/email/backfill/cancel.rs b/services/email_service/src/api/email/backfill/cancel.rs
index 3c4b8fd2ad..5e968935b5 100644
--- a/services/email_service/src/api/email/backfill/cancel.rs
+++ b/services/email_service/src/api/email/backfill/cancel.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use models_email::email::service::backfill::BackfillJobStatus;
use models_email::email::service::link::Link;
@@ -31,10 +31,10 @@ pub struct CancelBackfillParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, link), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization, link), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
link: Extension<Link>,
Json(req_body): Json<CancelBackfillParams>,
) -> Result<Response, Response> {
diff --git a/services/email_service/src/api/email/backfill/get.rs b/services/email_service/src/api/email/backfill/get.rs
index cdf230c9ba..e45a346e85 100644
--- a/services/email_service/src/api/email/backfill/get.rs
+++ b/services/email_service/src/api/email/backfill/get.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use models_email::email::service::backfill::BackfillJob;
use models_email::email::service::link::Link;
@@ -36,10 +36,10 @@ pub struct GetBackfillJobResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, link), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization, link), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
link: Extension<Link>,
Path(job_id): Path<Uuid>,
) -> Result<Response, Response> {
@@ -151,14 +151,14 @@ pub struct ListBackfillJobsResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn list_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, ListBackfillJobsError> {
let jobs = email_db_client::backfill::job::get::get_all_jobs_by_fusionauth_user_id(
&ctx.db,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
)
.await
.map_err(ListBackfillJobsError::QueryError)?;
diff --git a/services/email_service/src/api/email/contacts/list.rs b/services/email_service/src/api/email/contacts/list.rs
index cdc5082aa7..16bff3d16b 100644
--- a/services/email_service/src/api/email/contacts/list.rs
+++ b/services/email_service/src/api/email/contacts/list.rs
@@ -3,7 +3,7 @@ use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use models_email::email::service::address::ContactInfoWithInteraction;
use sqlx::types::Uuid;
@@ -29,14 +29,14 @@ pub struct ListContactsResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn list_contacts_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
let links = email_db_client::links::get::fetch_inboxes_for_macro_id(
&ctx.db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
)
.await
.map_err(|e| {
diff --git a/services/email_service/src/api/email/init.rs b/services/email_service/src/api/email/init.rs
index c891451e83..7983325de9 100644
--- a/services/email_service/src/api/email/init.rs
+++ b/services/email_service/src/api/email/init.rs
@@ -14,7 +14,7 @@ use email::domain::ports::EmailRepo;
use email::outbound::EmailPgRepo;
use email_service::pubsub::publish_email_event;
use email_utils::token_cache_key::TokenCacheKey;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::email::EmailStr;
use macro_user_id::user_id::MacroUserIdStr;
use model::response::ErrorResponse;
@@ -192,11 +192,11 @@ pub struct InitParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
query: Query<InitParams>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, InitError> {
// Init runs on every authentication, so its expected no-op outcomes (400s)
// must not error-log. The span skips the auto err event and the result is
@@ -221,10 +221,10 @@ async fn init_user(
link_id,
force_share,
}): Query<InitParams>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, InitError> {
- let macro_user_id = authorization.macro_user_id;
- let user_context = authorization.user_context;
+ let macro_user_id = authorization.authorization.user.macro_user_id.clone();
+ let user_context = authorization.authorization.user.user_context.clone();
tracing::info!(user_id = %user_context.user_id, ?link_id, "Init called");
let pg_repo = EmailPgRepo::new(ctx.db.clone());
diff --git a/services/email_service/src/api/email/labels/create.rs b/services/email_service/src/api/email/labels/create.rs
index 729216179c..3d8065c369 100644
--- a/services/email_service/src/api/email/labels/create.rs
+++ b/services/email_service/src/api/email/labels/create.rs
@@ -3,7 +3,7 @@ use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use models_email::service;
use models_email::service::link::Link;
@@ -36,10 +36,10 @@ pub struct CreateLabelResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, link, gmail_token), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization, link, gmail_token), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
link: Extension<Link>,
gmail_token: Extension<String>,
Json(request_body): Json<CreateLabelRequest>,
diff --git a/services/email_service/src/api/email/labels/delete.rs b/services/email_service/src/api/email/labels/delete.rs
index ab7a36bd2a..1d522573ed 100644
--- a/services/email_service/src/api/email/labels/delete.rs
+++ b/services/email_service/src/api/email/labels/delete.rs
@@ -3,7 +3,7 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use models_email::service::link::Link;
use uuid::Uuid;
@@ -25,10 +25,10 @@ use uuid::Uuid;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, link), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization, link), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
link: Extension<Link>,
Path(label_id): Path<Uuid>,
) -> Result<Response, Response> {
diff --git a/services/email_service/src/api/email/links/delete.rs b/services/email_service/src/api/email/links/delete.rs
index 8290282b01..861f64795a 100644
--- a/services/email_service/src/api/email/links/delete.rs
+++ b/services/email_service/src/api/email/links/delete.rs
@@ -4,7 +4,7 @@ use anyhow::Context;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use models_email::email::service::pubsub::{DeletionReason, LinkManagerMessage};
use uuid::Uuid;
@@ -30,13 +30,13 @@ use uuid::Uuid;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn delete_link_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(link_id): Path<Uuid>,
) -> Result<Response, InboxActionError> {
- let user_context = &authorization.user_context;
+ let user_context = &authorization.authorization.user.user_context;
let (link, access) = authorize_inbox_access(&ctx, &user_context.user_id, link_id).await?;
match access {
diff --git a/services/email_service/src/api/email/links/health_check.rs b/services/email_service/src/api/email/links/health_check.rs
index bf9f56a724..972ea0fd9c 100644
--- a/services/email_service/src/api/email/links/health_check.rs
+++ b/services/email_service/src/api/email/links/health_check.rs
@@ -5,7 +5,7 @@ use axum::response::{IntoResponse, Json, Response};
use email_service::util::gmail::auth::{
fetch_token_or_mark_reauth_no_cache, is_reauth_required_error,
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use models_email::email::service::pubsub::LinkManagerMessage;
use std::time::Duration;
@@ -55,14 +55,14 @@ impl IntoResponse for HealthCheckError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn health_check_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, HealthCheckError> {
let links = email_db_client::links::get::fetch_inboxes_for_macro_id(
&ctx.db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
)
.await
.map_err(HealthCheckError::DatabaseError)?;
diff --git a/services/email_service/src/api/email/links/list.rs b/services/email_service/src/api/email/links/list.rs
index 055bd24453..950452732d 100644
--- a/services/email_service/src/api/email/links/list.rs
+++ b/services/email_service/src/api/email/links/list.rs
@@ -3,7 +3,7 @@ use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use models_email::api;
use utoipa::ToSchema;
@@ -47,14 +47,14 @@ pub struct ListLinksResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn list_links_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, ListLinksError> {
let inboxes = email_db_client::links::get::fetch_inbox_details_for_macro_id(
&ctx.db,
- &authorization.macro_user_id,
+ &authorization.authorization.user.macro_user_id,
)
.await
.map_err(ListLinksError::DatabaseError)?;
diff --git a/services/email_service/src/api/email/links/resync.rs b/services/email_service/src/api/email/links/resync.rs
index fe788fe502..f2499d2b2a 100644
--- a/services/email_service/src/api/email/links/resync.rs
+++ b/services/email_service/src/api/email/links/resync.rs
@@ -3,7 +3,7 @@ use crate::api::email::links::access::{InboxActionError, authorize_inbox_access}
use anyhow::Context;
use axum::extract::{Path, State};
use axum::response::{IntoResponse, Json, Response};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use models_email::email::service::backfill::{
BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, InitPayload, JobScopedPayload,
@@ -41,14 +41,18 @@ pub struct ResyncResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn resync_link_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(link_id): Path<Uuid>,
) -> Result<Response, InboxActionError> {
- let (link, _access) =
- authorize_inbox_access(&ctx, &authorization.user_context.user_id, link_id).await?;
+ let (link, _access) = authorize_inbox_access(
+ &ctx,
+ &authorization.authorization.user.user_context.user_id,
+ link_id,
+ )
+ .await?;
if let Some(active) =
email_db_client::backfill::job::get::get_active_backfill_job(&ctx.db, link.id)
diff --git a/services/email_service/src/api/email/messages/get.rs b/services/email_service/src/api/email/messages/get.rs
index 0c4b1693c2..1059158c16 100644
--- a/services/email_service/src/api/email/messages/get.rs
+++ b/services/email_service/src/api/email/messages/get.rs
@@ -6,7 +6,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use sqlx::types::Uuid;
use std::collections::HashSet;
@@ -79,10 +79,10 @@ pub struct PathParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(PathParams { id }): Path<PathParams>,
) -> Result<Response, GetMessageError> {
let message = email_db_client::messages::get_parsed::get_parsed_message_by_id(&ctx.db, &id)
@@ -93,7 +93,8 @@ pub async fn handler(
return Err(GetMessageError::MessageNotFound);
};
- let link_ids = owned_link_ids(&ctx, &authorization.user_context.user_id).await?;
+ let link_ids =
+ owned_link_ids(&ctx, &authorization.authorization.user.user_context.user_id).await?;
if link_ids.contains(&message.link_id) {
Ok(Json(message).into_response())
} else {
@@ -115,10 +116,10 @@ pub async fn handler(
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn batch_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(ids): Json<Vec<Uuid>>,
) -> Result<Response, GetMessageError> {
let messages =
@@ -131,7 +132,8 @@ pub async fn batch_handler(
return Err(GetMessageError::MessageNotFound);
}
- let link_ids = owned_link_ids(&ctx, &authorization.user_context.user_id).await?;
+ let link_ids =
+ owned_link_ids(&ctx, &authorization.authorization.user.user_context.user_id).await?;
let accessible_messages = messages
.into_iter()
.filter(|msg| link_ids.contains(&msg.link_id))
diff --git a/services/email_service/src/api/email/messages/labels.rs b/services/email_service/src/api/email/messages/labels.rs
index c32d190bf1..19d6179e15 100644
--- a/services/email_service/src/api/email/messages/labels.rs
+++ b/services/email_service/src/api/email/messages/labels.rs
@@ -7,7 +7,7 @@ use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use email::domain::events::{EmailEventOrigin, EmailMacroEvent, LabelRef};
use email_service::pubsub::publish_email_event;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use models_email::service;
use sqlx::types::Uuid;
@@ -43,10 +43,10 @@ pub struct UpdateLabelBatchResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, body), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, authorization, body), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(body): Json<UpdateLabelBatchRequest>,
) -> Result<Response, Response> {
if body.message_ids.is_empty() || body.message_ids.len() > BATCH_UPDATE_MESSAGE_LIMIT {
@@ -66,7 +66,7 @@ pub async fn handler(
// delegated inboxes); a single label op targets messages in one inbox.
let link = email_db_client::links::get::fetch_owned_link_for_message(
&ctx.db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
body.message_ids[0],
)
.await
@@ -119,7 +119,7 @@ pub async fn handler(
let db_messages = email_db_client::messages::get_simple_messages::get_simple_messages_batch(
&ctx.db,
&body.message_ids,
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
)
.await
.map_err(|e| {
@@ -186,7 +186,7 @@ pub async fn handler(
email_db_client::messages::update::update_message_read_status_batch(
&mut *tx,
message_db_ids.clone(),
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
!is_adding,
)
.await
@@ -195,7 +195,7 @@ pub async fn handler(
email_db_client::messages::update::update_message_starred_status_batch(
&mut *tx,
message_db_ids.clone(),
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
is_adding,
)
.await
diff --git a/services/email_service/src/api/email/sync/disable.rs b/services/email_service/src/api/email/sync/disable.rs
index 4fc663dbb6..fc97a9a197 100644
--- a/services/email_service/src/api/email/sync/disable.rs
+++ b/services/email_service/src/api/email/sync/disable.rs
@@ -3,7 +3,7 @@ use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use models_email::email::service::link::Link;
use models_email::email::service::pubsub::LinkManagerMessage;
@@ -46,13 +46,13 @@ impl IntoResponse for DisableSyncError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, link), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, authorization, link), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn disable_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
link: Extension<Link>,
) -> Result<Response, DisableSyncError> {
- tracing::info!(user_id = %authorization.user_context.user_id, "Disable called");
+ tracing::info!(user_id = %authorization.authorization.user.user_context.user_id, "Disable called");
// Enqueue the delete operation to handle cleanup asynchronously
let message = LinkManagerMessage::DeleteLink {
diff --git a/services/email_service/src/api/email/threads/archived.rs b/services/email_service/src/api/email/threads/archived.rs
index ab5fd36aca..5097b94a33 100644
--- a/services/email_service/src/api/email/threads/archived.rs
+++ b/services/email_service/src/api/email/threads/archived.rs
@@ -7,7 +7,7 @@ use axum::response::{IntoResponse, Response};
use email::domain::events::{EmailEventOrigin, EmailMacroEvent, ThreadArchivedMetadata};
use email_db_client::threads::update::update_inbox_visible_status;
use email_service::pubsub::publish_email_event;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use models_email::service::label::system_labels;
use models_email::service::message::Message;
@@ -68,10 +68,10 @@ pub struct ArchiveThreadRequest {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, authorization, body), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, authorization, body), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn archived_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(thread_id): Path<Uuid>,
Json(body): Json<ArchiveThreadRequest>,
) -> Result<Response, ArchiveThreadError> {
@@ -81,7 +81,7 @@ pub async fn archived_handler(
// delegated inboxes.
let link = email_db_client::links::get::fetch_owned_link_for_thread(
&ctx.db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
thread_id,
)
.await?
diff --git a/services/email_service/src/api/email/threads/get.rs b/services/email_service/src/api/email/threads/get.rs
index 172f7a08af..5df72ad2b9 100644
--- a/services/email_service/src/api/email/threads/get.rs
+++ b/services/email_service/src/api/email/threads/get.rs
@@ -4,7 +4,7 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Json, extract};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use sqlx::types::Uuid;
use std::collections::HashSet;
@@ -89,10 +89,10 @@ const MESSAGE_MAX: i64 = 100;
(status = 500, description = "Internal Server Error", body = ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.user_context.user_id, fusionauth_user_id=authorization.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, authorization), fields(user_id=authorization.authorization.user.user_context.user_id, fusionauth_user_id=authorization.authorization.user.user_context.fusion_user_id), err)]
pub async fn get_thread_messages_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(PathParams { id }): Path<PathParams>,
extract::Query(query_params): extract::Query<GetThreadMessagesParams>,
) -> Result<Response, GetThreadError> {
@@ -100,7 +100,7 @@ pub async fn get_thread_messages_handler(
let link_ids: HashSet<Uuid> = email_db_client::links::get::fetch_inboxes_for_macro_id(
&ctx.db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
)
.await
.context("Failed to fetch links")?
diff --git a/services/email_service/src/api/email/threads/seen.rs b/services/email_service/src/api/email/threads/seen.rs
index 62126461eb..6c344bf46a 100644
--- a/services/email_service/src/api/email/threads/seen.rs
+++ b/services/email_service/src/api/email/threads/seen.rs
@@ -6,7 +6,7 @@ use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use email::domain::events::{EmailEventOrigin, EmailMacroEvent, ThreadReadMetadata};
use email_service::pubsub::publish_email_event;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use models_email::service::label::system_labels;
use models_email::service::message::Message;
@@ -71,14 +71,14 @@ pub struct PathParams {
#[tracing::instrument(skip(ctx, authorization), err)]
pub async fn seen_handler(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(PathParams { id: thread_id }): Path<PathParams>,
) -> Result<Response, SeenThreadError> {
// Resolve the inbox from the thread itself, scoped to the caller's own and
// delegated inboxes.
let link = email_db_client::links::get::fetch_owned_link_for_thread(
&ctx.db,
- &authorization.user_context.user_id,
+ &authorization.authorization.user.user_context.user_id,
thread_id,
)
.await
@@ -129,7 +129,7 @@ pub async fn seen_handler(
email_db_client::messages::update::update_message_read_status_batch(
&mut *tx,
message_db_ids.clone(),
- &authorization.user_context.fusion_user_id,
+ &authorization.authorization.user.user_context.fusion_user_id,
true,
)
.await
diff --git a/services/email_service/src/api/internal/delete_user.rs b/services/email_service/src/api/internal/delete_user.rs
index 0fb90ad6e9..6ec7eb5071 100644
--- a/services/email_service/src/api/internal/delete_user.rs
+++ b/services/email_service/src/api/internal/delete_user.rs
@@ -3,14 +3,14 @@ use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::ErrorResponse;
use models_email::email::service::pubsub::LinkManagerMessage;
#[tracing::instrument(skip(ctx))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(fusionauth_user_id): Path<String>,
) -> Result<Response, Response> {
tracing::info!(user_id = fusionauth_user_id, "Delete user called");
diff --git a/services/email_service/src/api/internal/get_message_by_id.rs b/services/email_service/src/api/internal/get_message_by_id.rs
index 2afd2cfe59..b1b656e0c3 100644
--- a/services/email_service/src/api/internal/get_message_by_id.rs
+++ b/services/email_service/src/api/internal/get_message_by_id.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::ErrorResponse;
use sqlx::types::Uuid;
@@ -17,7 +17,7 @@ pub struct PathParams {
#[tracing::instrument(skip(ctx))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(PathParams { id }): Path<PathParams>,
) -> Result<Response, Response> {
let message = email_db_client::messages::get_parsed::get_parsed_message_by_id(&ctx.db, &id)
@@ -49,7 +49,7 @@ pub async fn handler(
#[tracing::instrument(skip(ctx))]
pub async fn get_message_by_id_batch_handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Json(ids): Json<Vec<Uuid>>,
) -> Result<Response, Response> {
let messages =
diff --git a/services/email_service/src/api/internal/get_message_senders.rs b/services/email_service/src/api/internal/get_message_senders.rs
index 8ddc2e689c..e00ddea35c 100644
--- a/services/email_service/src/api/internal/get_message_senders.rs
+++ b/services/email_service/src/api/internal/get_message_senders.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use models_email::service::message::{MessageSendersRequest, MessageSendersResponse};
use strum_macros::AsRefStr;
use thiserror::Error;
@@ -42,7 +42,7 @@ impl IntoResponse for GetMessageSendersError {
#[tracing::instrument(skip_all)]
pub async fn handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Json(req_body): Json<MessageSendersRequest>,
) -> Result<Response, GetMessageSendersError> {
let link = email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, &req_body.user_id)
diff --git a/services/email_service/src/api/internal/get_messages_by_thread_id.rs b/services/email_service/src/api/internal/get_messages_by_thread_id.rs
index 797cca8899..e3ce4f20a0 100644
--- a/services/email_service/src/api/internal/get_messages_by_thread_id.rs
+++ b/services/email_service/src/api/internal/get_messages_by_thread_id.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::ErrorResponse;
use sqlx::types::Uuid;
@@ -52,7 +52,7 @@ pub struct PathParams {
#[tracing::instrument(skip(ctx))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Path(PathParams { id }): extract::Path<PathParams>,
extract::Query(query_params): extract::Query<ListThreadsParams>,
) -> Result<Response, Response> {
diff --git a/services/email_service/src/api/internal/get_thread_histories.rs b/services/email_service/src/api/internal/get_thread_histories.rs
index 87ba48ddc5..b63f79d02e 100644
--- a/services/email_service/src/api/internal/get_thread_histories.rs
+++ b/services/email_service/src/api/internal/get_thread_histories.rs
@@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use models_email::service::message::{ThreadHistoryRequest, ThreadHistoryResponse};
use strum_macros::AsRefStr;
use thiserror::Error;
@@ -42,7 +42,7 @@ impl IntoResponse for GetThreadHistoriesError {
#[tracing::instrument(skip_all)]
pub async fn handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Json(req_body): Json<ThreadHistoryRequest>,
) -> Result<Response, GetThreadHistoriesError> {
let link = email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, &req_body.user_id)
diff --git a/services/email_service/src/api/internal/get_thread_owner.rs b/services/email_service/src/api/internal/get_thread_owner.rs
index 5ea2001a6b..6bdb638d11 100644
--- a/services/email_service/src/api/internal/get_thread_owner.rs
+++ b/services/email_service/src/api/internal/get_thread_owner.rs
@@ -3,7 +3,7 @@ use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use model::response::ErrorResponse;
@@ -13,7 +13,7 @@ use uuid::Uuid;
#[tracing::instrument(skip(ctx))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(thread_id): Path<Uuid>,
) -> Result<Response, Response> {
let user_id = email_db_client::threads::get::get_macro_id_from_thread_id(&ctx.db, thread_id)
diff --git a/services/email_service/src/api/internal/gmail/cancel.rs b/services/email_service/src/api/internal/gmail/cancel.rs
index cee9fae178..a585ee3493 100644
--- a/services/email_service/src/api/internal/gmail/cancel.rs
+++ b/services/email_service/src/api/internal/gmail/cancel.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::ErrorResponse;
use models_email::email::service::backfill::BackfillJobStatus;
use sqlx::types::Uuid;
@@ -19,7 +19,7 @@ pub struct BackfillCancelParams {
#[tracing::instrument(skip(ctx))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Json(req_body): Json<BackfillCancelParams>,
) -> Result<Response, Response> {
let job = email_db_client::backfill::job::get::get_backfill_job(&ctx.db, req_body.job_id)
diff --git a/services/email_service/src/api/internal/gmail/create.rs b/services/email_service/src/api/internal/gmail/create.rs
index d6b5af00ae..63d7ed0961 100644
--- a/services/email_service/src/api/internal/gmail/create.rs
+++ b/services/email_service/src/api/internal/gmail/create.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::ErrorResponse;
use models_email::email::service::backfill::{
BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, InitPayload, JobScopedPayload,
@@ -33,7 +33,7 @@ pub struct LinkJobPair {
#[tracing::instrument(skip(ctx))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Json(req_body): Json<BackfillParams>,
) -> Result<Response, Response> {
let mut link_job_pairs: Vec<LinkJobPair> = Vec::new();
diff --git a/services/email_service/src/api/internal/gmail/get.rs b/services/email_service/src/api/internal/gmail/get.rs
index 72d603e2e0..3e64aff081 100644
--- a/services/email_service/src/api/internal/gmail/get.rs
+++ b/services/email_service/src/api/internal/gmail/get.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::response::ErrorResponse;
use models_email::email::service::backfill::BackfillJob;
use sqlx::PgPool;
@@ -20,7 +20,7 @@ pub struct GetBackfillJobResponse {
/// Get a backfill job.
pub async fn handler(
State(db): State<PgPool>,
- _: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(job_id): Path<Uuid>,
) -> Result<Response, Response> {
let job = email_db_client::backfill::job::get::get_backfill_job(&db, job_id)
diff --git a/services/email_service/src/api/middleware/gmail_token.rs b/services/email_service/src/api/middleware/gmail_token.rs
index 09f215785b..9c8fb3f6d0 100644
--- a/services/email_service/src/api/middleware/gmail_token.rs
+++ b/services/email_service/src/api/middleware/gmail_token.rs
@@ -1,18 +1,18 @@
use axum::extract::State;
use axum::{extract::Request, middleware::Next, response::Response};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use crate::api::context::{ApiContext, AuthorizationService};
use email_service::util::gmail::auth::fetch_gmail_token_usercontext_response;
pub(in crate::api) async fn attach_gmail_token(
State(ctx): State<ApiContext>,
- authorization: MacroAuthorizationExtractor<AuthorizationService>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
mut req: Request,
next: Next,
) -> Result<Response, Response> {
let gmail_token = fetch_gmail_token_usercontext_response(
- &authorization.user_context,
+ &authorization.authorization.user.user_context,
&ctx.redis_client,
&ctx.auth_service_client,
)
diff --git a/services/email_service/src/main.rs b/services/email_service/src/main.rs
index 4b0c3fed8d..0c22b357bc 100644
--- a/services/email_service/src/main.rs
+++ b/services/email_service/src/main.rs
@@ -131,6 +131,7 @@ async fn main() -> anyhow::Result<()> {
api_key: config.internal_api_key.to_string(),
default_user_id: Some("macro|[email protected]".to_string()),
},
+ macro_authorization::NoBotAuthorizer,
)));
let sqs_client = Arc::new(sqs_client);
diff --git a/services/image_proxy_service/src/api/proxy/mod.rs b/services/image_proxy_service/src/api/proxy/mod.rs
index 93deead657..f6b833f392 100644
--- a/services/image_proxy_service/src/api/proxy/mod.rs
+++ b/services/image_proxy_service/src/api/proxy/mod.rs
@@ -8,7 +8,7 @@ use axum::extract::{Query, State};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use futures::StreamExt;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
use model::response::ErrorResponse;
use reqwest::StatusCode;
@@ -163,10 +163,10 @@ pub struct ProxyParams {
#[tracing::instrument(
err(Debug),
skip(user, http_client),
- fields(user_id = ?user.macro_user_id)
+ fields(actor = %user.acting_entity())
)]
pub async fn proxy_request_handler(
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Query(params): Query<ProxyParams>,
State(http_client): State<reqwest::Client>,
_ip: ClientIp,
diff --git a/services/image_proxy_service/src/api/test.rs b/services/image_proxy_service/src/api/test.rs
index 35fc4b6f34..0e6cd29c8b 100644
--- a/services/image_proxy_service/src/api/test.rs
+++ b/services/image_proxy_service/src/api/test.rs
@@ -29,6 +29,7 @@ fn test_context() -> ApiContext {
api_key: TEST_INTERNAL_API_KEY.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
);
ApiContext {
diff --git a/services/image_proxy_service/src/main.rs b/services/image_proxy_service/src/main.rs
index a3c1b485a8..d024528810 100644
--- a/services/image_proxy_service/src/main.rs
+++ b/services/image_proxy_service/src/main.rs
@@ -34,6 +34,7 @@ async fn main() -> anyhow::Result<()> {
api_key: config.internal_api_key.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
);
let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));
diff --git a/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs b/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
index 6cc6e63ec5..1eda899745 100644
--- a/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
+++ b/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
use model_notifications::UserUnsubscribe;
@@ -24,11 +24,11 @@ use crate::api::context::{ApiContext, AuthorizationService};
#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
let unsubscribe_items = notification_db_client::unsubscribe::get::get_user_unsubscribes(
&ctx.db,
- &user.user_context.user_id,
+ &user.authorization.user.user_context.user_id,
)
.await
.map_err(|e| {
diff --git a/services/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs b/services/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs
index 9d3a5e6320..f5b298a0a4 100644
--- a/services/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs
+++ b/services/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use crate::api::context::{ApiContext, AuthorizationService};
@@ -24,11 +24,11 @@ use crate::api::context::{ApiContext, AuthorizationService};
#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
notification_db_client::user_mute_notification::remove_user_mute_notification(
&ctx.db,
- &user.user_context.user_id,
+ &user.authorization.user.user_context.user_id,
)
.await
.map_err(|e| {
diff --git a/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs b/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs
index 54c891f0db..c627313269 100644
--- a/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs
+++ b/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use crate::api::context::{ApiContext, AuthorizationService};
@@ -26,12 +26,12 @@ use super::unsubscribe_item::UnsubscribeItemPathParams;
#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(UnsubscribeItemPathParams { item_type, item_id }): Path<UnsubscribeItemPathParams>,
) -> Result<Response, Response> {
notification_db_client::unsubscribe::item::remove_unsubscribed_item_user(
&ctx.db,
- &user.user_context.user_id,
+ &user.authorization.user.user_context.user_id,
&item_id,
)
.await
diff --git a/services/notification_service/src/api/unsubscribe/unsubscribe_all.rs b/services/notification_service/src/api/unsubscribe/unsubscribe_all.rs
index 476a6ed246..1edf507209 100644
--- a/services/notification_service/src/api/unsubscribe/unsubscribe_all.rs
+++ b/services/notification_service/src/api/unsubscribe/unsubscribe_all.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use crate::api::context::{ApiContext, AuthorizationService};
@@ -23,11 +23,11 @@ use crate::api::context::{ApiContext, AuthorizationService};
#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
notification_db_client::user_mute_notification::upsert_user_mute_notification(
&ctx.db,
- &user.user_context.user_id,
+ &user.authorization.user.user_context.user_id,
)
.await
.map_err(|e| {
diff --git a/services/notification_service/src/api/unsubscribe/unsubscribe_email.rs b/services/notification_service/src/api/unsubscribe/unsubscribe_email.rs
index cc8fdde773..d4a2247b28 100644
--- a/services/notification_service/src/api/unsubscribe/unsubscribe_email.rs
+++ b/services/notification_service/src/api/unsubscribe/unsubscribe_email.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use crate::api::context::{ApiContext, AuthorizationService};
@@ -23,9 +23,14 @@ use crate::api::context::{ApiContext, AuthorizationService};
#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
- let email = user.user_context.user_id.replace("macro|", "");
+ let email = user
+ .authorization
+ .user
+ .user_context
+ .user_id
+ .replace("macro|", "");
notification_db_client::unsubscribe::email::upsert_email_unsubscribe(&ctx.db, &email)
.await
.map_err(|e| {
diff --git a/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs b/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs
index 6cb598875c..de2fae2018 100644
--- a/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs
+++ b/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
@@ -32,12 +32,12 @@ pub struct UnsubscribeItemPathParams {
#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(UnsubscribeItemPathParams { item_type, item_id }): Path<UnsubscribeItemPathParams>,
) -> Result<Response, Response> {
notification_db_client::unsubscribe::item::upsert_unsubscribed_item_user(
&ctx.db,
- &user.user_context.user_id,
+ &user.authorization.user.user_context.user_id,
&item_id,
&item_type,
)
diff --git a/services/notification_service/src/api/user_notification.rs b/services/notification_service/src/api/user_notification.rs
index ab9d67f7c8..5522bb31c6 100644
--- a/services/notification_service/src/api/user_notification.rs
+++ b/services/notification_service/src/api/user_notification.rs
@@ -5,7 +5,7 @@ use axum::extract::State;
use chrono::{DateTime, Utc};
use email_formatting::EmailDigestNotification;
use itertools::{Either, Itertools};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use model_error_response::ErrorResponse;
@@ -182,7 +182,7 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificati
State(state): State<
::notification::inbound::http::NotificationRouterState<S, AuthorizationService>,
>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
query: axum::extract::Query<::notification::inbound::http::Params>,
cursor: Option<
models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,
@@ -194,12 +194,13 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificati
axum::Json<model_error_response::ErrorResponse<'static>>,
),
> {
- let cleanup_user_id = user.macro_user_id.clone();
+ let user_id = user.authorization.user.macro_user_id.clone();
+ let cleanup_user_id = user_id.clone();
let axum::Json(response) = ::notification::inbound::http::list_user_notifications::<
S,
AuthorizationService,
serde_json::Value,
- >(&state, user.macro_user_id, query, cursor)
+ >(&state, user_id, query, cursor)
.await?;
let (notifs, failed): (Vec<_>, Vec<_>) = response
@@ -293,7 +294,7 @@ async fn bulk_get_typed_notifications_by_event_item_ids<
state: axum::extract::State<
::notification::inbound::http::NotificationRouterState<S, AuthorizationService>,
>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
query: axum::extract::Query<::notification::inbound::http::Params>,
cursor: Option<
models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,
@@ -351,7 +352,7 @@ async fn get_typed_by_event_item_id<S: ::notification::domain::service::Notifica
state: axum::extract::State<
::notification::inbound::http::NotificationRouterState<S, AuthorizationService>,
>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
path: axum::extract::Path<::notification::inbound::http::EventItemIdPath>,
query: axum::extract::Query<::notification::inbound::http::Params>,
cursor: Option<
@@ -408,7 +409,7 @@ async fn get_typed_notification_by_id<S: ::notification::domain::service::Notifi
state: axum::extract::State<
::notification::inbound::http::NotificationRouterState<S, AuthorizationService>,
>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
path: axum::extract::Path<::notification::inbound::http::NotificationIdPath>,
) -> Result<
axum::Json<ApiUserNotification>,
diff --git a/services/notification_service/src/main.rs b/services/notification_service/src/main.rs
index 31678e38b6..f1a3244bf8 100644
--- a/services/notification_service/src/main.rs
+++ b/services/notification_service/src/main.rs
@@ -136,6 +136,7 @@ pub async fn main() -> anyhow::Result<()> {
api_key: config.internal_api_key.as_ref().to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
)));
let notification_repository =
diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rs
index f35b4a4d3e..cc039558c5 100644
--- a/services/scheduled_action/src/bins/service.rs
+++ b/services/scheduled_action/src/bins/service.rs
@@ -106,6 +106,7 @@ async fn main() -> Result<()> {
api_key: config.internal_api_key.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
);
let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));
diff --git a/services/scheduled_action/src/inbound/axum_router.rs b/services/scheduled_action/src/inbound/axum_router.rs
index ca2a88b5b7..7056fb1cb0 100644
--- a/services/scheduled_action/src/inbound/axum_router.rs
+++ b/services/scheduled_action/src/inbound/axum_router.rs
@@ -7,7 +7,7 @@ use axum::routing::{get, post, put};
use axum::{Json, Router};
use chrono::Utc;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_uuid::Uuid;
use model::response::EmptyResponse;
@@ -96,7 +96,7 @@ pub async fn create_action<
Auth: MacroAuthorizationService,
>(
State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<CreateScheduledAction>,
) -> Result<impl IntoResponse, ScheduledActionApiError> {
let now = Utc::now();
@@ -106,7 +106,7 @@ pub async fn create_action<
.ok_or_else(|| anyhow::anyhow!("schedule has no future firings"))?;
let action = ScheduledAction {
id: None,
- owner: user.macro_user_id,
+ owner: user.authorization.user.macro_user_id.clone(),
name: req.name,
schedule: req.schedule,
kind: req.kind,
@@ -138,9 +138,12 @@ pub async fn list_actions<
Auth: MacroAuthorizationService,
>(
State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<impl IntoResponse, ScheduledActionApiError> {
- let actions = state.service.get_actions(user.macro_user_id).await?;
+ let actions = state
+ .service
+ .get_actions(user.authorization.user.macro_user_id.clone())
+ .await?;
Ok(Json(actions))
}
@@ -163,7 +166,7 @@ pub async fn update_action<
Auth: MacroAuthorizationService,
>(
State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(id): Path<Uuid>,
Json(req): Json<UpdateScheduledAction>,
) -> Result<impl IntoResponse, ScheduledActionApiError> {
@@ -174,7 +177,7 @@ pub async fn update_action<
.ok_or_else(|| anyhow::anyhow!("schedule has no future firings"))?;
let action = ScheduledAction {
id: Some(id),
- owner: user.macro_user_id.clone(),
+ owner: user.authorization.user.macro_user_id.clone(),
name: req.name,
schedule: req.schedule,
kind: req.kind,
@@ -188,7 +191,7 @@ pub async fn update_action<
};
let updated = state
.service
- .update_action(action, user.macro_user_id)
+ .update_action(action, user.authorization.user.macro_user_id.clone())
.await?;
Ok(Json(updated))
}
@@ -211,10 +214,13 @@ pub async fn delete_action<
Auth: MacroAuthorizationService,
>(
State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(id): Path<Uuid>,
) -> Result<impl IntoResponse, ScheduledActionApiError> {
- state.service.delete_action(&id, user.macro_user_id).await?;
+ state
+ .service
+ .delete_action(&id, user.authorization.user.macro_user_id.clone())
+ .await?;
Ok(StatusCode::NO_CONTENT)
}
@@ -237,12 +243,12 @@ pub async fn execute_action<
Auth: MacroAuthorizationService,
>(
State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(id): Path<Uuid>,
) -> Result<impl IntoResponse, ScheduledActionApiError> {
let execution = state
.service
- .execute_action_now(&id, user.macro_user_id)
+ .execute_action_now(&id, user.authorization.user.macro_user_id.clone())
.await?;
Ok(Json(execution))
}
@@ -265,12 +271,12 @@ pub async fn list_history<
Auth: MacroAuthorizationService,
>(
State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(id): Path<Uuid>,
) -> Result<impl IntoResponse, ScheduledActionApiError> {
let records = state
.service
- .get_execution_records(&id, user.macro_user_id)
+ .get_execution_records(&id, user.authorization.user.macro_user_id.clone())
.await?;
Ok(Json(records))
}
diff --git a/services/search_processing_service/src/api/internal/backfill.rs b/services/search_processing_service/src/api/internal/backfill.rs
index 1df8193937..a6cf72206b 100644
--- a/services/search_processing_service/src/api/internal/backfill.rs
+++ b/services/search_processing_service/src/api/internal/backfill.rs
@@ -21,7 +21,7 @@ use axum::{
response::{IntoResponse, Response},
routing::{get, post},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use serde::Serialize;
use crate::BackfillServiceImpl;
@@ -54,7 +54,7 @@ struct AcceptedReceipt {
async fn calls(
State(service): State<Arc<BackfillServiceImpl>>,
State(jobs): State<BackfillJobs>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<CallBackfillRequest>,
) -> Response {
spawn_backfill(
@@ -70,7 +70,7 @@ async fn calls(
async fn chats(
State(service): State<Arc<BackfillServiceImpl>>,
State(jobs): State<BackfillJobs>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<ChatBackfillRequest>,
) -> Response {
spawn_backfill(
@@ -86,7 +86,7 @@ async fn chats(
async fn channels(
State(service): State<Arc<BackfillServiceImpl>>,
State(jobs): State<BackfillJobs>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<ChannelBackfillRequest>,
) -> Response {
spawn_backfill(
@@ -104,7 +104,7 @@ async fn channels(
async fn documents(
State(service): State<Arc<BackfillServiceImpl>>,
State(jobs): State<BackfillJobs>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<DocumentBackfillRequest>,
) -> Response {
spawn_backfill(
@@ -122,7 +122,7 @@ async fn documents(
async fn emails(
State(service): State<Arc<BackfillServiceImpl>>,
State(jobs): State<BackfillJobs>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<EmailBackfillRequest>,
) -> Response {
spawn_backfill(
@@ -140,7 +140,7 @@ async fn emails(
async fn properties(
State(service): State<Arc<BackfillServiceImpl>>,
State(jobs): State<BackfillJobs>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<PropertiesBackfillRequest>,
) -> Response {
spawn_backfill(
@@ -158,7 +158,7 @@ async fn properties(
async fn projects(
State(service): State<Arc<BackfillServiceImpl>>,
State(jobs): State<BackfillJobs>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<ProjectBackfillRequest>,
) -> Response {
spawn_backfill(
@@ -175,7 +175,7 @@ async fn projects(
#[tracing::instrument(skip(jobs, _internal_authorization))]
async fn status(
State(jobs): State<BackfillJobs>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
Path(job_id): Path<String>,
) -> Response {
match jobs.snapshot(&JobId::from(job_id)).await {
diff --git a/services/search_processing_service/src/api/internal/delete_document.rs b/services/search_processing_service/src/api/internal/delete_document.rs
index 643e84b0eb..c4b2360589 100644
--- a/services/search_processing_service/src/api/internal/delete_document.rs
+++ b/services/search_processing_service/src/api/internal/delete_document.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
#[derive(serde::Deserialize)]
pub struct Params {
@@ -15,7 +15,7 @@ pub struct Params {
#[tracing::instrument(skip(ctx, _internal_authorization))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Path(Params { document_id }): extract::Path<Params>,
) -> Result<Response, Response> {
tracing::info!("delete document request initiated");
diff --git a/services/search_processing_service/src/api/internal/extract_sync.rs b/services/search_processing_service/src/api/internal/extract_sync.rs
index 949ca5a6cf..3ae6f7a95f 100644
--- a/services/search_processing_service/src/api/internal/extract_sync.rs
+++ b/services/search_processing_service/src/api/internal/extract_sync.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_authorization::InternalMacroAuthorizationExtractor;
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model::document::FileType;
use sqs_client::search::{SearchQueueMessage, document::SearchExtractorMessage};
use uuid::Uuid;
@@ -52,7 +52,7 @@ fn documents_to_messages(documents: Vec<SyncDocument>) -> Vec<SearchQueueMessage
#[tracing::instrument(skip(ctx, _internal_authorization, req))]
pub async fn handler(
State(ctx): State<ApiContext>,
- _internal_authorization: InternalMacroAuthorizationExtractor<AuthorizationService>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
extract::Json(req): extract::Json<ExtractSyncRequest>,
) -> Result<Response, Response> {
let document_ids: Vec<&str> = req
diff --git a/services/search_processing_service/src/main.rs b/services/search_processing_service/src/main.rs
index ea153f966c..66d4c5b1e2 100644
--- a/services/search_processing_service/src/main.rs
+++ b/services/search_processing_service/src/main.rs
@@ -76,6 +76,7 @@ async fn main() -> anyhow::Result<()> {
api_key: config.internal_api_key.to_string(),
default_user_id: None,
},
+ macro_authorization::NoBotAuthorizer,
)));
let aws_config = macro_aws_config::get_macro_aws_config().await;
diff --git a/services/static_file_service/src/api/file/bulk_delete_file.rs b/services/static_file_service/src/api/file/bulk_delete_file.rs
index edcbc29aa5..d8b6e560df 100644
--- a/services/static_file_service/src/api/file/bulk_delete_file.rs
+++ b/services/static_file_service/src/api/file/bulk_delete_file.rs
@@ -6,7 +6,7 @@ use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal, UserOrInternalCaller};
use model::response::ErrorResponse;
use std::sync::Arc;
use strum_macros::AsRefStr;
@@ -52,11 +52,15 @@ impl IntoResponse for BulkDeleteError {
)
)
]
-#[tracing::instrument(skip(metadata_client, storage_client, user), fields(user_id = ?user.macro_user_id), err)]
+#[tracing::instrument(
+ skip(metadata_client, storage_client, user),
+ fields(actor = %user.acting_entity()),
+ err
+)]
pub async fn handle_bulk_delete_file(
State(metadata_client): State<DynamodbClient>,
State(storage_client): State<Arc<S3Client>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(req): Json<BulkDeleteRequest>,
) -> Result<Json<BulkDeleteResponse>, BulkDeleteError> {
// Validate request
@@ -83,12 +87,16 @@ pub async fn handle_bulk_delete_file(
let mut s3_keys_to_delete = Vec::new();
let mut file_ids_to_delete = Vec::new();
+ let is_internal = user.authorization.caller == UserOrInternalCaller::Internal;
+
// Process each file
for file_id in &req.file_ids {
match metadata_results.get(file_id) {
Some(metadata) => {
// Skip owner check for internal requests
- if !user.is_internal_access && metadata.owner_id != user.macro_user_id.as_ref() {
+ if !is_internal
+ && metadata.owner_id != user.authorization.user.macro_user_id.as_ref()
+ {
tracing::warn!(file_id = file_id, "delete requested by non-owner");
results.push(DeleteResult {
file_id: file_id.clone(),
diff --git a/services/static_file_service/src/api/file/delete_file.rs b/services/static_file_service/src/api/file/delete_file.rs
index b8f31e5132..42f24936d1 100644
--- a/services/static_file_service/src/api/file/delete_file.rs
+++ b/services/static_file_service/src/api/file/delete_file.rs
@@ -6,7 +6,7 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::response::Response;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal, UserOrInternalCaller};
use std::sync::Arc;
#[derive(serde::Deserialize)]
@@ -28,11 +28,14 @@ pub struct Params {
)
)
]
-#[tracing::instrument(skip(metadata_client, storage_client, user), fields(user_id = ?user.macro_user_id))]
+#[tracing::instrument(
+ skip(metadata_client, storage_client, user),
+ fields(actor = %user.acting_entity())
+)]
pub async fn handle_delete_file(
State(metadata_client): State<DynamodbClient>,
State(storage_client): State<Arc<S3Client>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { file_id }): Path<Params>,
) -> Result<Response, Response> {
let metadata = metadata_client
@@ -45,7 +48,8 @@ pub async fn handle_delete_file(
.ok_or_else(|| (StatusCode::NOT_FOUND, "not found").into_response())?;
// Skip owner check for internal requests
- if !user.is_internal_access && metadata.owner_id != user.macro_user_id.as_ref() {
+ let is_internal = user.authorization.caller == UserOrInternalCaller::Internal;
+ if !is_internal && metadata.owner_id != user.authorization.user.macro_user_id.as_ref() {
tracing::warn!("delete requested by non-owner");
return Err((StatusCode::FORBIDDEN, "access denied").into_response());
}
diff --git a/services/static_file_service/src/api/file/get_file.rs b/services/static_file_service/src/api/file/get_file.rs
index f6134ef6b1..04389136e4 100644
--- a/services/static_file_service/src/api/file/get_file.rs
+++ b/services/static_file_service/src/api/file/get_file.rs
@@ -1,7 +1,7 @@
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use std::sync::Arc;
use crate::api::context::AuthorizationService;
@@ -26,11 +26,14 @@ pub struct Params {
(status = 500, body=String)
)
)]
-#[tracing::instrument(skip(metadata_client, storage_client, user), fields(user_id = ?user.macro_user_id))]
+#[tracing::instrument(
+ skip(metadata_client, storage_client, user),
+ fields(actor = %user.acting_entity())
+)]
pub async fn handle_get_presigned_url(
State(metadata_client): State<DynamodbClient>,
State(storage_client): State<Arc<S3Client>>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { file_id }): Path<Params>,
) -> Result<Response, Response> {
// First get metadata to ensure file exists and is uploaded
diff --git a/services/static_file_service/src/api/file/metadata.rs b/services/static_file_service/src/api/file/metadata.rs
index 298c07e6e0..ab260a7153 100644
--- a/services/static_file_service/src/api/file/metadata.rs
+++ b/services/static_file_service/src/api/file/metadata.rs
@@ -5,7 +5,7 @@ use axum::extract::{Json, Path, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::response::Response;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
#[derive(serde::Deserialize)]
pub struct Params {
@@ -25,10 +25,13 @@ pub struct Params {
(status = 500, body=String)
)
)]
-#[tracing::instrument(skip(metadata_client, user), fields(user_id = ?user.macro_user_id))]
+#[tracing::instrument(
+ skip(metadata_client, user),
+ fields(actor = %user.acting_entity())
+)]
pub async fn handle_get_metadata(
State(metadata_client): State<DynamodbClient>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(Params { file_id }): Path<Params>,
) -> Result<Response, Response> {
metadata_client
diff --git a/services/static_file_service/src/api/file/mod.rs b/services/static_file_service/src/api/file/mod.rs
index 11509e2885..a139743886 100644
--- a/services/static_file_service/src/api/file/mod.rs
+++ b/services/static_file_service/src/api/file/mod.rs
@@ -4,11 +4,10 @@ pub mod get_file;
pub mod metadata;
pub mod put_presigned_url;
+use crate::api::context::AppState;
use axum::Router;
use axum::routing::{delete, get, post, put};
-use crate::api::context::AppState;
-
pub fn router() -> Router<AppState> {
Router::new()
.route(
diff --git a/services/static_file_service/src/api/file/put_presigned_url.rs b/services/static_file_service/src/api/file/put_presigned_url.rs
index 16c0f6f8e1..987aee4669 100644
--- a/services/static_file_service/src/api/file/put_presigned_url.rs
+++ b/services/static_file_service/src/api/file/put_presigned_url.rs
@@ -8,7 +8,7 @@ use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::response::Response;
use chrono::Utc;
-use macro_authorization::MacroAuthorizationExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::document::FileType;
use uuid::Uuid;
@@ -22,10 +22,10 @@ use uuid::Uuid;
(status = 500, body=String),
),
)]
-#[tracing::instrument(skip(ctx, user), fields(user_id=?user.macro_user_id))]
+#[tracing::instrument(skip(ctx, user), fields(actor = %user.acting_entity()))]
pub async fn put_presigned_url(
State(ctx): State<AppState>,
- user: MacroAuthorizationExtractor<AuthorizationService>,
+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Json(request): Json<PutFileRequest>,
) -> Result<Response, Response> {
let content_type = if let Some(content_type) = request.content_type {
@@ -52,7 +52,7 @@ pub async fn put_presigned_url(
let s3_key = static_file_key.to_key();
let permalink = format!("{}/{}", ctx.config.static_file_service_url, s3_key);
- let owner_id = user.macro_user_id.as_ref().to_string();
+ let owner_id = user.authorization.user.macro_user_id.as_ref().to_string();
let metadata = MetadataObject {
file_id: id.clone(),
diff --git a/services/static_file_service/src/api/mod.rs b/services/static_file_service/src/api/mod.rs
index dd6f63fd27..8194c3c1ca 100644
--- a/services/static_file_service/src/api/mod.rs
+++ b/services/static_file_service/src/api/mod.rs
@@ -52,6 +52,7 @@ pub async fn setup_and_serve(
api_key: config.internal_api_key.as_ref().to_string(),
default_user_id: Some(MACRO_INTERNAL_USER_ID.to_string()),
},
+ macro_authorization::NoBotAuthorizer,
)));
let state = AppState {