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(notification): update inbound to use macroauthorizationextractor (#5021)

Will Hutchinson48d68caa26c8
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 1200823c68..f4cde2c200 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -135,7 +135,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -491,7 +490,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -583,7 +581,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -766,7 +763,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -864,7 +860,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -931,7 +926,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -1232,7 +1226,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1312,7 +1305,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -1863,7 +1855,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -1941,7 +1932,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -2002,11 +1992,11 @@
"crates/bot_id",
"crates/channel_sender",
"crates/cowlike",
- "crates/decode_jwt",
"crates/email_formatting",
"crates/invite_email",
"crates/last_online_tracker",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_service_urls",
@@ -2033,7 +2023,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -2095,7 +2084,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -2239,7 +2227,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -2295,7 +2282,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -2664,7 +2650,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -2713,7 +2698,6 @@
"graphql_notification": [
"crates/ai_toolset",
"crates/cowlike",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/filter_ast",
"crates/graphql_common",
@@ -2747,7 +2731,6 @@
"crates/bot_id",
"crates/channel_sender",
"crates/cowlike",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2801,7 +2784,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -2915,10 +2897,10 @@
"invite_email": [
"crates/ai_toolset",
"crates/cowlike",
- "crates/decode_jwt",
"crates/invite_email",
"crates/last_online_tracker",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_service_urls",
@@ -2973,7 +2955,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -3047,7 +3028,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -3646,10 +3626,10 @@
"crates/bot_id",
"crates/channel_sender",
"crates/cowlike",
- "crates/decode_jwt",
"crates/invite_email",
"crates/last_online_tracker",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_service_urls",
@@ -3736,7 +3716,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -3817,7 +3796,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -3899,9 +3877,9 @@
"notification": [
"crates/ai_toolset",
"crates/cowlike",
- "crates/decode_jwt",
"crates/last_online_tracker",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_service_urls",
@@ -3921,10 +3899,10 @@
"crates/bot_id",
"crates/channel_sender",
"crates/cowlike",
- "crates/decode_jwt",
"crates/invite_email",
"crates/last_online_tracker",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_service_urls",
@@ -3947,11 +3925,11 @@
"crates/bot_id",
"crates/channel_sender",
"crates/cowlike",
- "crates/decode_jwt",
"crates/email_formatting",
"crates/invite_email",
"crates/last_online_tracker",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_aws_config",
"crates/macro_env",
"crates/macro_env_var",
@@ -4051,7 +4029,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -4113,7 +4090,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -4175,7 +4151,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/dynamodb_client",
"crates/email",
@@ -4239,7 +4214,6 @@
"crates/bot_id",
"crates/channel_sender",
"crates/cowlike",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4281,7 +4255,6 @@
"crates/bot_id",
"crates/channel_sender",
"crates/cowlike",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4327,7 +4300,6 @@
"referral": [
"crates/ai_toolset",
"crates/cowlike",
- "crates/decode_jwt",
"crates/invite_email",
"crates/ip_extractor",
"crates/last_online_tracker",
@@ -4671,7 +4643,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -4739,7 +4710,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/email",
@@ -4814,7 +4784,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -4922,7 +4891,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -4988,7 +4956,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -5243,7 +5210,6 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -5322,7 +5288,6 @@
"crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/dynamodb_client",
@@ -5385,7 +5350,6 @@
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
- "crates/decode_jwt",
"crates/document_sub_type",
"crates/dynamodb_client",
"crates/email",
diff --git a/Cargo.lock b/Cargo.lock
index 9b1fb358ee..f4bb569ece 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -9522,7 +9522,6 @@ dependencies = [
"axum",
"chrono",
"cowlike",
- "decode_jwt",
"either",
"futures",
"hex",
@@ -9530,7 +9529,7 @@ dependencies = [
"http-body-util",
"itertools 0.14.0",
"last_online_tracker",
- "macro_auth",
+ "macro_authorization",
"macro_db_migrator",
"macro_env",
"macro_service_urls",
@@ -9624,13 +9623,13 @@ dependencies = [
"axum",
"chrono",
"database_env_vars",
- "decode_jwt",
"email_formatting",
"hmac 0.12.1",
"http-body-util",
"itertools 0.14.0",
"last_online_tracker",
"macro_auth",
+ "macro_authorization",
"macro_aws_config",
"macro_config",
"macro_cors",
diff --git a/crates/notification/Cargo.toml b/crates/notification/Cargo.toml
index 88defdb9be..eb52dc90db 100644
--- a/crates/notification/Cargo.toml
+++ b/crates/notification/Cargo.toml
@@ -9,6 +9,7 @@ version = "0.1.0"
ai_tool = ["dep:ai_toolset", "dep:anyhow", "dep:async-trait", "dep:schemars"]
axum = [
"dep:axum",
+ "dep:macro_authorization",
"dep:model-error-response",
"dep:model_user",
"models_pagination/axum",
@@ -29,14 +30,13 @@ aws-sdk-sqs = { workspace = true }
axum = { workspace = true, optional = true }
chrono = { workspace = true }
cowlike = { path = "../cowlike" }
-decode_jwt = { path = "../decode_jwt" }
either = { workspace = true }
futures = { workspace = true }
hex = { workspace = true }
hmac = { workspace = true }
itertools = { workspace = true }
last_online_tracker = { path = "../last_online_tracker" }
-macro_auth = { path = "../macro_auth" }
+macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"], optional = true }
macro_env = { path = "../macro_env" }
macro_service_urls = { path = "../macro_service_urls" }
macro_user_id = { path = "../macro_user_id" }
@@ -69,7 +69,6 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
http-body-util = { workspace = true }
-macro_auth = { path = "../macro_auth", features = ["testing"] }
macro_db_migrator = { path = "../macro_db_migrator" }
rate_limit = { path = "../rate_limit", features = ["testing"] }
tokio = { workspace = true, features = ["macros", "rt", "test-util"] }
diff --git a/crates/notification/src/inbound/http/device.rs b/crates/notification/src/inbound/http/device.rs
index 87000983f5..58852913a1 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 decode_jwt::DecodedJwt;
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
use model_error_response::ErrorResponse;
use reqwest::StatusCode;
@@ -14,22 +14,26 @@ use crate::domain::service::NotificationReader;
use crate::inbound::http::NotificationRouterState;
/// Construct the device registration router.
-pub fn device_router<S: NotificationReader>() -> Router<NotificationRouterState<S>> {
+pub fn device_router<S, Auth>() -> Router<NotificationRouterState<S, Auth>>
+where
+ S: NotificationReader,
+ Auth: MacroAuthorizationService,
+{
Router::new()
- .route("/register", post(register_device::<S>))
- .route("/unregister", delete(unregister_device::<S>))
+ .route("/register", post(register_device::<S, Auth>))
+ .route("/unregister", delete(unregister_device::<S, Auth>))
}
/// Register a device for push notifications.
-#[tracing::instrument(skip(state, macro_user_id, req))]
-async fn register_device<S: NotificationReader>(
- State(state): State<NotificationRouterState<S>>,
- DecodedJwt { macro_user_id, .. }: DecodedJwt,
+#[tracing::instrument(skip(state, user, req))]
+async fn register_device<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(state): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<DeviceRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
state
.inner
- .register_device(macro_user_id, &req.token, &req.device_type)
+ .register_device(user.macro_user_id, &req.token, &req.device_type)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to register device");
@@ -46,9 +50,9 @@ async fn register_device<S: NotificationReader>(
/// Unregister a device from push notifications.
#[tracing::instrument(skip(state, _macro_user, req))]
-async fn unregister_device<S: NotificationReader>(
- State(state): State<NotificationRouterState<S>>,
- _macro_user: DecodedJwt,
+async fn unregister_device<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(state): State<NotificationRouterState<S, Auth>>,
+ _macro_user: MacroAuthorizationExtractor<Auth>,
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 fbe62ba3c2..02132ef12a 100644
--- a/crates/notification/src/inbound/http/mod.rs
+++ b/crates/notification/src/inbound/http/mod.rs
@@ -11,9 +11,11 @@ use axum::{
extract::{FromRef, Path, Query, State},
routing::{delete, get, patch, put},
};
-use decode_jwt::DecodedJwt;
use hmac::Hmac;
-use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
+use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use models_pagination::{CreatedAt, CursorOptionExt, CursorWithValAndFilter};
use reqwest::StatusCode;
@@ -49,75 +51,80 @@ pub struct NotificationIdPath {
}
/// the router state for a notification router
-pub struct NotificationRouterState<S> {
+pub struct NotificationRouterState<S, Auth> {
/// the inner S wrapped in an [Arc]
pub inner: Arc<S>,
/// the statically known list of notification typenames which can be blocked by the user
pub blockable_notification_typenames: &'static HashSet<&'static str>,
/// The value which is used to verify the presigned url requests
pub hmac_signing_key: Hmac<Sha256>,
- /// the args used to validate jwts
- pub jwt_args: JwtValidationArgs,
+ /// State used to authorize requests.
+ pub authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S> FromRef<NotificationRouterState<S>> for JwtValidationArgs {
- fn from_ref(input: &NotificationRouterState<S>) -> Self {
- input.jwt_args.clone()
+impl<S, Auth> FromRef<NotificationRouterState<S, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(input: &NotificationRouterState<S, Auth>) -> Self {
+ input.authorization_state.clone()
}
}
-impl<S> Clone for NotificationRouterState<S> {
+// Manual implementation so `Auth` does not need to implement `Clone`.
+impl<S, Auth> Clone for NotificationRouterState<S, Auth> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
blockable_notification_typenames: self.blockable_notification_typenames,
hmac_signing_key: self.hmac_signing_key.clone(),
- jwt_args: self.jwt_args.clone(),
+ authorization_state: self.authorization_state.clone(),
}
}
}
-impl<S: NotificationReader> NotificationRouterState<S> {
+impl<S: NotificationReader, Auth> NotificationRouterState<S, Auth> {
/// create a new instance of self
pub fn new(
val: S,
blockable_notification_typenames: &'static HashSet<&'static str>,
hmac_signing_key: Hmac<Sha256>,
- jwt_args: JwtValidationArgs,
+ authorization_state: MacroAuthorizationState<Auth>,
) -> Self {
NotificationRouterState {
inner: Arc::new(val),
blockable_notification_typenames,
hmac_signing_key,
- jwt_args,
+ authorization_state,
}
}
}
/// construct the router
-pub fn router<S: NotificationReader, T: Serialize + DeserializeOwned + Send + 'static>()
--> Router<NotificationRouterState<S>> {
+pub fn router<S, Auth, T>() -> Router<NotificationRouterState<S, Auth>>
+where
+ S: NotificationReader,
+ Auth: MacroAuthorizationService,
+ T: Serialize + DeserializeOwned + Send + 'static,
+{
Router::new()
.nest(
"/bulk",
Router::new()
- .route("/", delete(bulk_delete_notifications))
- .route("/seen", patch(bulk_mark_seen))
- .route("/done", patch(bulk_mark_done))
- .route("/undone", patch(bulk_mark_undone)),
+ .route("/", delete(bulk_delete_notifications::<S, Auth>))
+ .route("/seen", patch(bulk_mark_seen::<S, Auth>))
+ .route("/done", patch(bulk_mark_done::<S, Auth>))
+ .route("/undone", patch(bulk_mark_undone::<S, Auth>)),
)
.route(
"/preferences",
- get(preferences::get_notification_type_preferences),
+ get(preferences::get_notification_type_preferences::<S, Auth>),
)
.route(
"/preferences/{notification_event_type}/disable",
- put(preferences::disable_notification_type)
- .get(preferences::presigned_disable_notification_type),
+ put(preferences::disable_notification_type::<S, Auth>)
+ .get(preferences::presigned_disable_notification_type::<S, Auth>),
)
.route(
"/preferences/{notification_event_type}/enable",
- put(preferences::enable_notification_type),
+ put(preferences::enable_notification_type::<S, Auth>),
)
}
@@ -144,10 +151,11 @@ pub struct GetAllUserNotificationsResponse<T> {
/// List user notifications with generic metadata type `T`.
pub async fn list_user_notifications<
S: NotificationReader,
+ Auth: MacroAuthorizationService,
T: Serialize + DeserializeOwned + Send,
>(
- service: &NotificationRouterState<S>,
- decoded_jwt: DecodedJwt,
+ service: &NotificationRouterState<S, Auth>,
+ user_id: MacroUserIdStr<'static>,
Query(Params { limit, done, seen }): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
@@ -155,7 +163,7 @@ pub async fn list_user_notifications<
let result = service
.inner
.get_user_notifications::<T>(
- decoded_jwt.macro_user_id,
+ user_id,
limit,
query,
NotificationListFilters {
@@ -211,10 +219,11 @@ pub struct BulkGetByEventItemIdsRequest {
)]
pub async fn bulk_get_by_event_item_ids<
S: NotificationReader,
+ Auth: MacroAuthorizationService,
T: Serialize + DeserializeOwned + Send,
>(
- State(service): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+ State(service): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Query(Params { limit, done, seen }): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
Json(req): Json<BulkGetByEventItemIdsRequest>,
@@ -222,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: decoded_jwt.macro_user_id,
+ user_id: user.macro_user_id,
event_item_ids: &req.event_item_ids,
limit,
cursor: cursor.into_query(CreatedAt, ()),
@@ -271,12 +280,12 @@ pub struct NotificationBulkRequest {
(status = 500, body = ErrorResponse),
)
)]
-pub async fn bulk_mark_seen<S: NotificationReader>(
- State(service): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn bulk_mark_seen<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(service): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
- bulk_update(&service, &decoded_jwt, &req, NotificationStatus::Seen).await
+ bulk_update(&service, user.macro_user_id, &req, NotificationStatus::Seen).await
}
/// Mark notifications as done.
@@ -292,12 +301,18 @@ pub async fn bulk_mark_seen<S: NotificationReader>(
(status = 500, body = ErrorResponse),
)
)]
-pub async fn bulk_mark_done<S: NotificationReader>(
- State(service): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn bulk_mark_done<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(service): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
- bulk_update(&service, &decoded_jwt, &req, NotificationStatus::Done(true)).await
+ bulk_update(
+ &service,
+ user.macro_user_id,
+ &req,
+ NotificationStatus::Done(true),
+ )
+ .await
}
/// Mark notifications as not done.
@@ -313,30 +328,30 @@ pub async fn bulk_mark_done<S: NotificationReader>(
(status = 500, body = ErrorResponse),
)
)]
-pub async fn bulk_mark_undone<S: NotificationReader>(
- State(service): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn bulk_mark_undone<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(service): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
bulk_update(
&service,
- &decoded_jwt,
+ user.macro_user_id,
&req,
NotificationStatus::Done(false),
)
.await
}
-async fn bulk_update<S: NotificationReader>(
- service: &NotificationRouterState<S>,
- decoded_jwt: &DecodedJwt,
+async fn bulk_update<S: NotificationReader, Auth: MacroAuthorizationService>(
+ service: &NotificationRouterState<S, Auth>,
+ user_id: MacroUserIdStr<'static>,
req: &NotificationBulkRequest,
status: NotificationStatus,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
.update_notifications(UpdateNotificationsRequest {
- user_id: decoded_jwt.macro_user_id.clone(),
+ user_id,
notification_ids: &req.notification_ids,
status,
})
@@ -373,9 +388,13 @@ async fn bulk_update<S: NotificationReader>(
(status = 500, body = ErrorResponse),
)
)]
-pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + DeserializeOwned + Send>(
- State(service): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn get_by_event_item_id<
+ S: NotificationReader,
+ Auth: MacroAuthorizationService,
+ T: Serialize + DeserializeOwned + Send,
+>(
+ State(service): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Path(EventItemIdPath { event_item_id }): Path<EventItemIdPath>,
Query(Params { limit, done, seen }): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
@@ -383,7 +402,7 @@ pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + Deserial
let result = service
.inner
.get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {
- user_id: decoded_jwt.macro_user_id,
+ user_id: user.macro_user_id,
event_item_ids: &[event_item_id],
limit,
cursor: cursor.into_query(CreatedAt, ()),
@@ -429,15 +448,16 @@ pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + Deserial
)]
pub async fn get_notification_by_id<
S: NotificationReader,
+ Auth: MacroAuthorizationService,
T: Serialize + DeserializeOwned + Send,
>(
- State(service): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+ State(service): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,
) -> Result<Json<UserNotificationRow<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let result = service
.inner
- .get_user_notification_by_id::<T>(decoded_jwt.macro_user_id, notification_id)
+ .get_user_notification_by_id::<T>(user.macro_user_id, notification_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get user notification by id");
@@ -476,14 +496,14 @@ pub async fn get_notification_by_id<
(status = 500, body = ErrorResponse),
)
)]
-pub async fn delete_notification<S: NotificationReader>(
- State(service): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn delete_notification<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(service): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
- .delete_user_notification(decoded_jwt.macro_user_id, notification_id)
+ .delete_user_notification(user.macro_user_id, notification_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to delete user notification");
@@ -511,14 +531,14 @@ pub async fn delete_notification<S: NotificationReader>(
(status = 500, body = ErrorResponse),
)
)]
-pub async fn bulk_delete_notifications<S: NotificationReader>(
- State(service): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn bulk_delete_notifications<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(service): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
- .bulk_delete_user_notifications(decoded_jwt.macro_user_id, &req.notification_ids)
+ .bulk_delete_user_notifications(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 7cd02d64d5..24af10000d 100644
--- a/crates/notification/src/inbound/http/preferences.rs
+++ b/crates/notification/src/inbound/http/preferences.rs
@@ -7,7 +7,7 @@ use axum::{
response::Html,
};
use cowlike::CowLike;
-use decode_jwt::DecodedJwt;
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
use macro_service_urls::NotificationServiceUrl;
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
@@ -43,14 +43,17 @@ pub struct GetNotificationTypePreferencesResponse {
(status = 500, body = ErrorResponse),
)
)]
-pub async fn get_notification_type_preferences<S: NotificationReader>(
- State(state): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn get_notification_type_preferences<
+ S: NotificationReader,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
) -> Result<Json<GetNotificationTypePreferencesResponse>, (StatusCode, Json<ErrorResponse<'static>>)>
{
let disabled = state
.inner
- .get_disabled_notification_types(decoded_jwt.macro_user_id)
+ .get_disabled_notification_types(user.macro_user_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get notification type preferences");
@@ -85,16 +88,16 @@ pub async fn get_notification_type_preferences<S: NotificationReader>(
(status = 500, body = ErrorResponse),
)
)]
-pub async fn disable_notification_type<S: NotificationReader>(
- State(state): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn disable_notification_type<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(state): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Path(NotificationEventTypePath {
notification_event_type,
}): Path<NotificationEventTypePath>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
disable_notification_type_inner(
&state,
- decoded_jwt.macro_user_id.copied(),
+ user.macro_user_id.copied(),
notification_event_type.as_str(),
)
.await
@@ -109,8 +112,11 @@ pub struct PresignedQueryParams {
/// Disable a notification type for the authenticated user via a GET request with a presigned url.
/// This guarantees the signed url was produced in a trusted environment
-pub async fn presigned_disable_notification_type<S: NotificationReader>(
- State(state): State<NotificationRouterState<S>>,
+pub async fn presigned_disable_notification_type<
+ S: NotificationReader,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<NotificationRouterState<S, Auth>>,
Path(NotificationEventTypePath {
notification_event_type,
}): Path<NotificationEventTypePath>,
@@ -160,8 +166,8 @@ pub async fn presigned_disable_notification_type<S: NotificationReader>(
}
/// internal implementation of the GET/PUT methods to DRY up the code
-async fn disable_notification_type_inner<S: NotificationReader>(
- state: &NotificationRouterState<S>,
+async fn disable_notification_type_inner<S: NotificationReader, Auth: MacroAuthorizationService>(
+ state: &NotificationRouterState<S, Auth>,
calling_user: MacroUserIdStr<'_>,
notification_event_type: &str,
) -> Result<(), (StatusCode, Json<ErrorResponse<'static>>)> {
@@ -213,16 +219,16 @@ async fn disable_notification_type_inner<S: NotificationReader>(
(status = 500, body = ErrorResponse),
)
)]
-pub async fn enable_notification_type<S: NotificationReader>(
- State(state): State<NotificationRouterState<S>>,
- decoded_jwt: DecodedJwt,
+pub async fn enable_notification_type<S: NotificationReader, Auth: MacroAuthorizationService>(
+ State(state): State<NotificationRouterState<S, Auth>>,
+ user: MacroAuthorizationExtractor<Auth>,
Path(NotificationEventTypePath {
notification_event_type,
}): Path<NotificationEventTypePath>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
state
.inner
- .enable_notification_type(decoded_jwt.macro_user_id, &notification_event_type)
+ .enable_notification_type(user.macro_user_id, &notification_event_type)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to enable notification type");
diff --git a/crates/notification/src/inbound/http/test.rs b/crates/notification/src/inbound/http/test.rs
index 11064a0dbe..8a6483b130 100644
--- a/crates/notification/src/inbound/http/test.rs
+++ b/crates/notification/src/inbound/http/test.rs
@@ -1,10 +1,17 @@
-use std::collections::{HashMap, HashSet};
+use std::{
+ collections::{HashMap, HashSet},
+ sync::Arc,
+};
use axum::{Router, http::Request};
use hmac::{Hmac, Mac};
use http_body_util::BodyExt;
-use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+use macro_authorization::{
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+};
use macro_user_id::user_id::MacroUserIdStr;
+use model_user::UserContext;
use models_pagination::{CreatedAt, Paginated, Query};
use reqwest::StatusCode;
use rootcause::Report;
@@ -28,11 +35,55 @@ use crate::domain::{
use super::NotificationRouterState;
-/// A mock `NotificationReader` that panics on all methods.
-/// Tests that reject at the extractor level will never reach these methods.
-struct UnreachableService;
+const VALID_BEARER_TOKEN: &str = "valid-token";
+const VALID_AUTHORIZATION_HEADER: &str = "Bearer valid-token";
+const VALID_INTERNAL_KEY: &str = "valid-internal-key";
+const VALID_USER_ID: &str = "macro|[email protected]";
+
+#[derive(Clone)]
+struct FakeAuthorizationService;
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(&self, token: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ if token != VALID_BEARER_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ Ok(UserContext {
+ user_id: VALID_USER_ID.to_string(),
+ fusion_user_id: "fusion-user-id".to_string(),
+ organization_id: None,
+ permissions: None,
+ })
+ }
+
+ async fn authorize_internal(
+ &self,
+ provided_key: &str,
+ claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ if provided_key != VALID_INTERNAL_KEY {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+
+ let Some(user_id) = claims.user_id else {
+ return Ok(None);
+ };
+
+ Ok(Some(UserContext {
+ user_id,
+ fusion_user_id: claims.fusion_user_id.unwrap_or_default(),
+ organization_id: claims.organization_id,
+ permissions: None,
+ }))
+ }
+}
-impl NotificationReader for UnreachableService {
+/// A mock `NotificationReader` that only permits reading preferences for the test user.
+/// Tests that reject at the extractor level will not reach any methods.
+struct AuthenticationTestService;
+
+impl NotificationReader for AuthenticationTestService {
fn update_notifications(
&self,
_req: UpdateNotificationsRequest,
@@ -115,9 +166,12 @@ impl NotificationReader for UnreachableService {
fn get_disabled_notification_types(
&self,
- _user_id: MacroUserIdStr<'_>,
+ user_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Vec<DisabledNotificationType>, Report>> + Send {
- async { unreachable!("should not be called") }
+ async move {
+ assert_eq!(user_id.to_string(), VALID_USER_ID);
+ Ok(Vec::new())
+ }
}
fn disable_notification_type(
@@ -142,18 +196,21 @@ static BLOCKABLE: std::sync::LazyLock<HashSet<&'static str>> =
fn test_router() -> Router {
let hmac_key = Hmac::<Sha256>::new_from_slice(b"test-key").unwrap();
+ let authorization_state = MacroAuthorizationState::new(Arc::new(FakeAuthorizationService));
let state = NotificationRouterState::new(
- UnreachableService,
+ AuthenticationTestService,
&BLOCKABLE,
hmac_key,
- JwtValidationArgs::new_testing(),
+ authorization_state,
);
- let device_router = super::device::device_router::<UnreachableService>();
+ let device_router =
+ super::device::device_router::<AuthenticationTestService, FakeAuthorizationService>();
Router::new()
.nest(
"/user_notifications",
- super::router::<UnreachableService, serde_json::Value>(),
+ super::router::<AuthenticationTestService, FakeAuthorizationService, serde_json::Value>(
+ ),
)
.nest("/device", device_router)
.with_state(state)
@@ -161,12 +218,24 @@ fn test_router() -> Router {
/// Send a request to the router and return the status code.
async fn status(router: &Router, method: &str, uri: &str, body: Option<&str>) -> StatusCode {
- let builder = Request::builder().uri(uri).method(method);
- let builder = if body.is_some() {
- builder.header("content-type", "application/json")
- } else {
- builder
- };
+ status_with_headers(router, method, uri, body, &[]).await
+}
+
+/// Send a request with headers to the router and return the status code.
+async fn status_with_headers(
+ router: &Router,
+ method: &str,
+ uri: &str,
+ body: Option<&str>,
+ headers: &[(&'static str, &'static str)],
+) -> StatusCode {
+ let mut builder = Request::builder().uri(uri).method(method);
+ for &(name, value) in headers {
+ builder = builder.header(name, value);
+ }
+ if body.is_some() {
+ builder = builder.header("content-type", "application/json");
+ }
let req = builder
.body(axum::body::Body::from(body.unwrap_or_default().to_string()))
.unwrap();
@@ -180,19 +249,14 @@ async fn status_with_bad_token(
uri: &str,
body: Option<&str>,
) -> StatusCode {
- let builder = Request::builder()
- .uri(uri)
- .method(method)
- .header("authorization", "Bearer invalid.jwt.token");
- let builder = if body.is_some() {
- builder.header("content-type", "application/json")
- } else {
- builder
- };
- let req = builder
- .body(axum::body::Body::from(body.unwrap_or_default().to_string()))
- .unwrap();
- router.clone().oneshot(req).await.unwrap().status()
+ status_with_headers(
+ router,
+ method,
+ uri,
+ body,
+ &[("authorization", "Bearer invalid.jwt.token")],
+ )
+ .await
}
// -- No token tests ---------------------------------------------------------
@@ -433,6 +497,59 @@ async fn invalid_token_unregister_device() {
);
}
+// -- Valid authorization tests ----------------------------------------------
+
+#[tokio::test]
+async fn valid_bearer_token_reaches_per_user_handler() {
+ let router = test_router();
+ assert_eq!(
+ status_with_headers(
+ &router,
+ "GET",
+ "/user_notifications/preferences",
+ None,
+ &[("authorization", VALID_AUTHORIZATION_HEADER)],
+ )
+ .await,
+ StatusCode::OK
+ );
+}
+
+#[tokio::test]
+async fn valid_internal_key_and_acting_user_reach_per_user_handler() {
+ let router = test_router();
+ assert_eq!(
+ status_with_headers(
+ &router,
+ "GET",
+ "/user_notifications/preferences",
+ None,
+ &[
+ (INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY),
+ (INTERNAL_MACRO_USER_ID_HEADER, VALID_USER_ID),
+ ],
+ )
+ .await,
+ StatusCode::OK
+ );
+}
+
+#[tokio::test]
+async fn internal_request_without_acting_user_is_unauthorized() {
+ let router = test_router();
+ assert_eq!(
+ status_with_headers(
+ &router,
+ "GET",
+ "/user_notifications/preferences",
+ None,
+ &[(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)],
+ )
+ .await,
+ StatusCode::UNAUTHORIZED
+ );
+}
+
// -- Presigned disable preference tests -------------------------------------
/// A mock `NotificationReader` that returns `Ok(())` for `disable_notification_type`
@@ -551,17 +668,18 @@ const NOTIFICATION_BASE_URL: &str = "https://notifications.macro.com";
fn presigned_router() -> Router {
let hmac_key = Hmac::<Sha256>::new_from_slice(HMAC_KEY).unwrap();
+ let authorization_state = MacroAuthorizationState::new(Arc::new(FakeAuthorizationService));
let state = NotificationRouterState::new(
PresignedTestService,
&BLOCKABLE,
hmac_key,
- JwtValidationArgs::new_testing(),
+ authorization_state,
);
Router::new()
.nest(
"/user_notifications",
- super::router::<PresignedTestService, serde_json::Value>(),
+ super::router::<PresignedTestService, FakeAuthorizationService, serde_json::Value>(),
)
.with_state(state)
}
diff --git a/services/notification_service/Cargo.toml b/services/notification_service/Cargo.toml
index 3162c15252..36abf762f9 100644
--- a/services/notification_service/Cargo.toml
+++ b/services/notification_service/Cargo.toml
@@ -27,13 +27,13 @@ aws-sdk-sqs = { workspace = true }
axum = { workspace = true }
chrono = { workspace = true }
database_env_vars = { path = "../../crates/database_env_vars" }
-decode_jwt = { path = "../../crates/decode_jwt" }
email_formatting = { path = "../../crates/email_formatting" }
hmac = { workspace = true }
http-body-util = { workspace = true }
itertools = { workspace = true }
last_online_tracker = { path = "../../crates/last_online_tracker" }
macro_auth = { path = "../../crates/macro_auth" }
+macro_authorization = { path = "../../crates/macro_authorization" }
macro_aws_config = { path = "../../crates/macro_aws_config" }
macro_config = { path = "../../crates/macro_config" }
macro_cors = { path = "../../crates/macro_cors" }
diff --git a/services/notification_service/src/api/context.rs b/services/notification_service/src/api/context.rs
index a5f9d72cd7..8b77912ed1 100644
--- a/services/notification_service/src/api/context.rs
+++ b/services/notification_service/src/api/context.rs
@@ -1,14 +1,19 @@
use crate::config::Config;
use axum::extract::FromRef;
-use macro_auth::{InternalApiKey, middleware::decode_jwt::JwtValidationArgs};
+use macro_auth::InternalApiKey;
+use macro_authorization::{
+ MacroAuthJwtValidator, MacroAuthorizationServiceImpl, MacroAuthorizationState,
+};
use sqlx::PgPool;
use std::sync::Arc;
+pub(crate) type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
+
#[derive(Clone, FromRef)]
pub struct ApiContext {
pub db: PgPool,
pub sns_client: Arc<sns_client::SNS>,
pub config: Arc<Config>,
- pub jwt_args: JwtValidationArgs,
+ pub authorization_state: MacroAuthorizationState<AuthorizationService>,
pub internal_api_key: InternalApiKey,
}
diff --git a/services/notification_service/src/api/mod.rs b/services/notification_service/src/api/mod.rs
index 9d3991f16b..9ae492c4f5 100644
--- a/services/notification_service/src/api/mod.rs
+++ b/services/notification_service/src/api/mod.rs
@@ -1,4 +1,4 @@
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
use ::notification::inbound::http::NotificationRouterState;
use anyhow::Context;
use axum::Router;
@@ -22,7 +22,7 @@ pub(crate) mod swagger;
pub async fn setup_and_serve<S: ::notification::domain::service::NotificationReader>(
state: ApiContext,
- ingress_state: NotificationRouterState<S>,
+ ingress_state: NotificationRouterState<S, AuthorizationService>,
) -> anyhow::Result<()> {
let port = state.config.port;
let env = state.config.environment;
@@ -59,7 +59,7 @@ pub async fn setup_and_serve<S: ::notification::domain::service::NotificationRea
fn api_router<S: ::notification::domain::service::NotificationReader>(
_state: ApiContext,
- ingress_state: NotificationRouterState<S>,
+ ingress_state: NotificationRouterState<S, AuthorizationService>,
) -> Router<ApiContext> {
let middleware = {
ServiceBuilder::new().layer(axum::middleware::from_fn(
@@ -70,7 +70,7 @@ fn api_router<S: ::notification::domain::service::NotificationReader>(
let internal_router = Router::new()
.nest(
"/device",
- ::notification::inbound::http::device::device_router(),
+ ::notification::inbound::http::device::device_router::<S, AuthorizationService>(),
)
.nest("/user_notifications", user_notification::router())
.with_state(ingress_state)
diff --git a/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs b/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
index 64bb5b7959..6cc6e63ec5 100644
--- a/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
+++ b/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
@@ -4,11 +4,11 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use decode_jwt::DecodedJwt;
+use macro_authorization::MacroAuthorizationExtractor;
use model::response::ErrorResponse;
use model_notifications::UserUnsubscribe;
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
/// Gets the users unsubscribe items.
#[utoipa::path(
@@ -21,14 +21,14 @@ use crate::api::context::ApiContext;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, decoded_jwt))]
+#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- decoded_jwt: DecodedJwt,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
) -> Result<Response, Response> {
let unsubscribe_items = notification_db_client::unsubscribe::get::get_user_unsubscribes(
&ctx.db,
- &decoded_jwt.user_context.user_id,
+ &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 7ddf584082..9d3a5e6320 100644
--- a/services/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs
+++ b/services/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs
@@ -4,10 +4,10 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use decode_jwt::DecodedJwt;
+use macro_authorization::MacroAuthorizationExtractor;
use model::response::{EmptyResponse, ErrorResponse};
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
/// Unmutes all notifications.
/// Existing notifications that were muted manually will remain muted.
@@ -21,14 +21,14 @@ use crate::api::context::ApiContext;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, decoded_jwt))]
+#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- decoded_jwt: DecodedJwt,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
) -> Result<Response, Response> {
notification_db_client::user_mute_notification::remove_user_mute_notification(
&ctx.db,
- &decoded_jwt.user_context.user_id,
+ &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 6308a9a2cb..54c891f0db 100644
--- a/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs
+++ b/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs
@@ -4,10 +4,10 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use decode_jwt::DecodedJwt;
+use macro_authorization::MacroAuthorizationExtractor;
use model::response::{EmptyResponse, ErrorResponse};
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
use super::unsubscribe_item::UnsubscribeItemPathParams;
@@ -23,15 +23,15 @@ use super::unsubscribe_item::UnsubscribeItemPathParams;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, decoded_jwt))]
+#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- decoded_jwt: DecodedJwt,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
Path(UnsubscribeItemPathParams { item_type, item_id }): Path<UnsubscribeItemPathParams>,
) -> Result<Response, Response> {
notification_db_client::unsubscribe::item::remove_unsubscribed_item_user(
&ctx.db,
- &decoded_jwt.user_context.user_id,
+ &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 cc81046e5b..476a6ed246 100644
--- a/services/notification_service/src/api/unsubscribe/unsubscribe_all.rs
+++ b/services/notification_service/src/api/unsubscribe/unsubscribe_all.rs
@@ -4,10 +4,10 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use decode_jwt::DecodedJwt;
+use macro_authorization::MacroAuthorizationExtractor;
use model::response::{EmptyResponse, ErrorResponse};
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
/// Unsubscribes user from all notifications.
#[utoipa::path(
@@ -20,14 +20,14 @@ use crate::api::context::ApiContext;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, decoded_jwt))]
+#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- decoded_jwt: DecodedJwt,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
) -> Result<Response, Response> {
notification_db_client::user_mute_notification::upsert_user_mute_notification(
&ctx.db,
- &decoded_jwt.user_context.user_id,
+ &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 9c1048a0a9..cc8fdde773 100644
--- a/services/notification_service/src/api/unsubscribe/unsubscribe_email.rs
+++ b/services/notification_service/src/api/unsubscribe/unsubscribe_email.rs
@@ -4,10 +4,10 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use decode_jwt::DecodedJwt;
+use macro_authorization::MacroAuthorizationExtractor;
use model::response::{EmptyResponse, ErrorResponse};
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
/// Unsubscribes a user from receiving emails
#[utoipa::path(
@@ -20,12 +20,12 @@ use crate::api::context::ApiContext;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, decoded_jwt))]
+#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- decoded_jwt: DecodedJwt,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
) -> Result<Response, Response> {
- let email = decoded_jwt.user_context.user_id.replace("macro|", "");
+ let email = 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 b4a1a9cca6..6cb598875c 100644
--- a/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs
+++ b/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs
@@ -4,12 +4,12 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use decode_jwt::DecodedJwt;
+use macro_authorization::MacroAuthorizationExtractor;
use model::response::{EmptyResponse, ErrorResponse};
use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
#[derive(Deserialize, Serialize, ToSchema, IntoParams)]
pub struct UnsubscribeItemPathParams {
@@ -29,15 +29,15 @@ pub struct UnsubscribeItemPathParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, decoded_jwt))]
+#[tracing::instrument(skip(ctx, user))]
pub async fn handler(
State(ctx): State<ApiContext>,
- decoded_jwt: DecodedJwt,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
Path(UnsubscribeItemPathParams { item_type, item_id }): Path<UnsubscribeItemPathParams>,
) -> Result<Response, Response> {
notification_db_client::unsubscribe::item::upsert_unsubscribed_item_user(
&ctx.db,
- &decoded_jwt.user_context.user_id,
+ &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 f703740858..ab9d67f7c8 100644
--- a/services/notification_service/src/api/user_notification.rs
+++ b/services/notification_service/src/api/user_notification.rs
@@ -5,6 +5,7 @@ use axum::extract::State;
use chrono::{DateTime, Utc};
use email_formatting::EmailDigestNotification;
use itertools::{Either, Itertools};
+use macro_authorization::MacroAuthorizationExtractor;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use model_error_response::ErrorResponse;
@@ -23,6 +24,8 @@ use serde::Serialize;
use utoipa::ToSchema;
use uuid::Uuid;
+use crate::api::context::AuthorizationService;
+
/// The types of notifications that are blockable
pub(crate) static BLOCKABLE_NOTIFICATIONS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
HashSet::from([
@@ -137,8 +140,8 @@ pub fn to_typed_row(
/// Instantiates the notification crate's generic router, then overwrites the
/// GET `/` route with a wrapper that deserializes each row into [`NotifEvent`].
pub fn router<S: ::notification::domain::service::NotificationReader>()
--> axum::Router<NotificationRouterState<S>> {
- ::notification::inbound::http::router::<S, serde_json::Value>()
+-> axum::Router<NotificationRouterState<S, AuthorizationService>> {
+ ::notification::inbound::http::router::<S, AuthorizationService, serde_json::Value>()
.route("/", axum::routing::get(list_typed_notifications::<S>))
.route(
"/item/bulk",
@@ -150,8 +153,9 @@ pub fn router<S: ::notification::domain::service::NotificationReader>()
)
.route(
"/{notification_id}",
- axum::routing::get(get_typed_notification_by_id::<S>)
- .delete(::notification::inbound::http::delete_notification::<S>),
+ axum::routing::get(get_typed_notification_by_id::<S>).delete(
+ ::notification::inbound::http::delete_notification::<S, AuthorizationService>,
+ ),
)
}
@@ -175,8 +179,10 @@ pub fn router<S: ::notification::domain::service::NotificationReader>()
)
)]
async fn list_typed_notifications<S: ::notification::domain::service::NotificationReader>(
- State(state): State<::notification::inbound::http::NotificationRouterState<S>>,
- decoded_jwt: decode_jwt::DecodedJwt,
+ State(state): State<
+ ::notification::inbound::http::NotificationRouterState<S, AuthorizationService>,
+ >,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
query: axum::extract::Query<::notification::inbound::http::Params>,
cursor: Option<
models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,
@@ -188,11 +194,12 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificati
axum::Json<model_error_response::ErrorResponse<'static>>,
),
> {
- let user = decoded_jwt.macro_user_id.clone();
+ let cleanup_user_id = user.macro_user_id.clone();
let axum::Json(response) = ::notification::inbound::http::list_user_notifications::<
S,
+ AuthorizationService,
serde_json::Value,
- >(&state, decoded_jwt, query, cursor)
+ >(&state, user.macro_user_id, query, cursor)
.await?;
let (notifs, failed): (Vec<_>, Vec<_>) = response
@@ -208,7 +215,7 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificati
tokio::task::spawn(
CleanUpNotificationsTask {
service: state,
- user,
+ user: cleanup_user_id,
failed_notifs: failed,
}
.delete_failures(),
@@ -225,7 +232,7 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificati
}
struct CleanUpNotificationsTask<S> {
- service: NotificationRouterState<S>,
+ service: NotificationRouterState<S, AuthorizationService>,
user: MacroUserIdStr<'static>,
failed_notifs: Vec<(Uuid, serde_json::Error)>,
}
@@ -283,8 +290,10 @@ where
async fn bulk_get_typed_notifications_by_event_item_ids<
S: ::notification::domain::service::NotificationReader,
>(
- state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,
- decoded_jwt: decode_jwt::DecodedJwt,
+ state: axum::extract::State<
+ ::notification::inbound::http::NotificationRouterState<S, AuthorizationService>,
+ >,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
query: axum::extract::Query<::notification::inbound::http::Params>,
cursor: Option<
models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,
@@ -299,8 +308,9 @@ async fn bulk_get_typed_notifications_by_event_item_ids<
> {
let axum::Json(response) = ::notification::inbound::http::bulk_get_by_event_item_ids::<
S,
+ AuthorizationService,
serde_json::Value,
- >(state, decoded_jwt, query, cursor, body)
+ >(state, user, query, cursor, body)
.await?;
let items = response
@@ -338,8 +348,10 @@ async fn bulk_get_typed_notifications_by_event_item_ids<
)
)]
async fn get_typed_by_event_item_id<S: ::notification::domain::service::NotificationReader>(
- state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,
- decoded_jwt: decode_jwt::DecodedJwt,
+ state: axum::extract::State<
+ ::notification::inbound::http::NotificationRouterState<S, AuthorizationService>,
+ >,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
path: axum::extract::Path<::notification::inbound::http::EventItemIdPath>,
query: axum::extract::Query<::notification::inbound::http::Params>,
cursor: Option<
@@ -354,8 +366,9 @@ async fn get_typed_by_event_item_id<S: ::notification::domain::service::Notifica
> {
let axum::Json(response) = ::notification::inbound::http::get_by_event_item_id::<
S,
+ AuthorizationService,
serde_json::Value,
- >(state, decoded_jwt, path, query, cursor)
+ >(state, user, path, query, cursor)
.await?;
let items = response
@@ -392,8 +405,10 @@ async fn get_typed_by_event_item_id<S: ::notification::domain::service::Notifica
)
)]
async fn get_typed_notification_by_id<S: ::notification::domain::service::NotificationReader>(
- state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,
- decoded_jwt: decode_jwt::DecodedJwt,
+ state: axum::extract::State<
+ ::notification::inbound::http::NotificationRouterState<S, AuthorizationService>,
+ >,
+ user: MacroAuthorizationExtractor<AuthorizationService>,
path: axum::extract::Path<::notification::inbound::http::NotificationIdPath>,
) -> Result<
axum::Json<ApiUserNotification>,
@@ -404,8 +419,9 @@ async fn get_typed_notification_by_id<S: ::notification::domain::service::Notifi
> {
let axum::Json(row) = ::notification::inbound::http::get_notification_by_id::<
S,
+ AuthorizationService,
serde_json::Value,
- >(state, decoded_jwt, path)
+ >(state, user, path)
.await?;
let typed = to_typed_row(row).map_err(|e| {
diff --git a/services/notification_service/src/main.rs b/services/notification_service/src/main.rs
index cfc4d3c66e..31678e38b6 100644
--- a/services/notification_service/src/main.rs
+++ b/services/notification_service/src/main.rs
@@ -1,5 +1,5 @@
#![recursion_limit = "256"]
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService};
use crate::api::user_notification::BLOCKABLE_NOTIFICATIONS;
use ::notification::domain::models::email_notification_digest::ports::DigestBatch;
use ::notification::domain::service::NotificationEgressService;
@@ -16,6 +16,7 @@ use config::Config;
use email_formatting::EmailDigestNotification;
use hmac::{Hmac, Mac};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState};
use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
use macro_service_urls::ConnectionGatewayUrl;
@@ -129,6 +130,13 @@ pub async fn main() -> anyhow::Result<()> {
let jwt_args =
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await?;
+ let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(
+ MacroAuthJwtValidator::new(jwt_args),
+ InternalAuthConfig {
+ api_key: config.internal_api_key.as_ref().to_string(),
+ default_user_id: None,
+ },
+ )));
let notification_repository =
::notification::outbound::repository::DbNotificationRepository::new(db.clone());
@@ -176,7 +184,7 @@ pub async fn main() -> anyhow::Result<()> {
reader_service,
&BLOCKABLE_NOTIFICATIONS,
hmac_key.clone(),
- jwt_args.clone(),
+ authorization_state.clone(),
);
// Set up egress worker for delivering notifications from the queue
@@ -316,7 +324,7 @@ pub async fn main() -> anyhow::Result<()> {
db,
sns_client: Arc::new(sns_client),
config: Arc::new(config),
- jwt_args,
+ authorization_state,
},
ingress_state,
)