Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(notif): add signed unsubscribe url to digest (#2371)
Sean Ayef515103b8546
diff --git a/.env-local.enc b/.env-local.encindex 831e606c97..667103bc03 100644--- a/.env-local.enc+++ b/.env-local.enc@@ -128,6 +128,7 @@ LIVEKIT_API_KEY=ENC[AES256_GCM,data:qhLZaV4ww9UxE03tj91qx2Y=,iv:QJVCtekxlAe0fZLHLIVEKIT_API_SECRET=ENC[AES256_GCM,data:GLdp8wpK4kpbGPmR5aaWzZ4ns8jzTkRuFfroG8PUeG8ChFJONtoCFx1VjlxUfQ==,iv:YcaFnOZG8lA9kMxM8C4WD+DXqHRhprburLqIzDWI7Zc=,tag:Ro55kVfVytCWdfCT/GERCA==,type:str]LIVEKIT_TRANSCRIPTION_AGENT_NAME=ENC[AES256_GCM,data:RgXJ+WNruFiyg1Pjjzo++SDOLg==,iv:r7XZRhIJg+4qiEBBG6Pbvj+maiUh/jrO5lnwNkUXgxM=,tag:yVVoGBzz1Bl0lY1KqH4G3Q==,type:str]INTERNAL_CALL_SECRET=ENC[AES256_GCM,data:66UR3BO7Ddg5bQ0xmLNeY5EGb65L4tiXcsDNpTE=,iv:ovuMlw/k257Oh1CkosXjOXDWycQ4AoA9s+hhfHpeOvs=,tag:qXXYEFhSaM0Q4ffRdGtMRg==,type:str]+UNSUBSCRIBE_HMAC_SECRET=ENC[AES256_GCM,data:N5twF18QdQpAcMb7RxFR6l2DQ6t8c3bjl2FxMoJT3AkHkLZNSmCibhsfoMx12w==,iv:nbo2PYRG9AxWC2JwTEIk84M7KhO27tyMtH1BaqIPDT8=,tag:BCDWa/lataRL33lAw2HPCQ==,type:str]sops_age__list_0__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IEUzMVUyZyBBM1lmcDc3\nUENpRVorSGVGa3R2NFlrdkx1Mm43aEcyR1ZtbEswL2RnWHlqMwpVMnY4ck5makNC\nZzVZc3JrZ3NKV2x3RTY0TFovRXJtVzEyeFZOZWRheHBNCi0tLSBobjhCbHpJa25s\nZDhyQjhCaEYrOWNiWHZkRWpnRlkwTnNEbjMwYzdxcTUwCqxxxmXy3mFUAbAy29y8\n2DFYDATdVvmplHpDTvgrNyY+lAL/3Jp9vtIs5DGXW/r73Nv3AhISmuCid18qhpAY\nUqE=\n-----END AGE ENCRYPTED FILE-----\nsops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxvsops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93@@ -138,7 +139,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:07Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wFUqf7u/HEfCUGv7j69Mb6YAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMpcJQR1XeIAFFE7ebAgEQgDvYRYIWelwN8TuwA+6fZVaB34yKo9EQ5xPLr/3BU+ro1Mn2eBPCg3q8ie2LuE/3voim1X35P/cdtDqTZg==-sops_lastmodified=2026-04-06T18:22:08Z-sops_mac=ENC[AES256_GCM,data:L+DfQz4nS3vCOGqOh5Mun6Vt2oTKMIhF2FG//tmihJifBNobcd0UrwE9nRekaysT9yH3iIHYhOHq2MIp+To06v4kH48VGoHd2LarJTEh5xYATCEXR99MFU3S9BXMKPY/g3OZedf+jhc/0rDUoPtDYUXL7jaVBwj5Vw+1veWo/G0=,iv:j06rIjEB1dIzhcyBAdCBWB4Efqk/370GoPHwFMvvaUg=,tag:B+lDWzdjaNZzRbOWLFUtqg==,type:str]+sops_lastmodified=2026-04-06T21:16:16Z+sops_mac=ENC[AES256_GCM,data:I6LHAjz+DXfvYxsRl8IsqFDPf/Uap3WC+zvV1Wp47SqsUx3QDwKMJELT9NEE8Jmf3mZTQucZSBgXvFiLRSrGY5Ult/300WWaUjsyHyf1hdT9vvzIis0r7iSFEl2xCg0eVUcIWJ1DLKGLDKg+S/YziggOx0rsniXewAdYdIqofeQ=,iv:cM+kjTmNku5r9ia6gy52D+SfauJgNINeM1+ocfLhLY0=,tag:ENXb7WC1x7Nwqld+6nN+jQ==,type:str]sops_unencrypted_suffix=_unencrypted-sops_version=3.12.1+sops_version=3.12.2diff --git a/.env-localdev.enc b/.env-localdev.encindex 8a2e9c66a3..bf5185b105 100644--- a/.env-localdev.enc+++ b/.env-localdev.enc@@ -134,6 +134,7 @@ LIVEKIT_API_KEY=ENC[AES256_GCM,data:aKkhucWrN/FNaYmbloWdxm0=,iv:RmykULpzwZ9lftkFLIVEKIT_API_SECRET=ENC[AES256_GCM,data:VrLzVGpQG7ML+TZcopCsEkyj/mXiTm+9BsqWE3nGdIozRf6PIyUwHlyErGoFCQ==,iv:na9JIyCdt94SFnPLh9l+33c8lZRW+uR8WYw+Ju8zdYw=,tag:cLL0wJz4jzpAIRysbt4tSQ==,type:str]LIVEKIT_TRANSCRIPTION_AGENT_NAME=ENC[AES256_GCM,data:kPe4llQDxy8gkYjNH6bIe3W6Sg==,iv:8j7ryXT1MTiSoGz14jifVSH/FYlHRRY1DwCqdIqwenw=,tag:3GCNvV7rL2uIKj2sPw0LxQ==,type:str]INTERNAL_CALL_SECRET=ENC[AES256_GCM,data:ZRHFdPR0Rrq01RiNYDECflGVdG+xdHr0qrpR9xY=,iv:DNGhICcPs2zKFpxqSAdgezeT9F8L/r/JO0hT3tJN2Rg=,tag:Rg3YlrSIhtpwI70ifErOTw==,type:str]+UNSUBSCRIBE_HMAC_SECRET=ENC[AES256_GCM,data:qY1UwSmYGhkB0fi7k7FUia9Cfbyi4THRAvyB9VnmuZel4gqRACXcRI08OBfEbg==,iv:WdBWZC+yzLlJGqmMxeQzZBZA8zsLNuH3y0OfbOxGp4o=,tag:muNfHVbAQwMcqonfZk7Clg==,type:str]sops_age__list_0__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IEUzMVUyZyBBNDlKWUVt\nbUpscDEzSE9IZTNvdkd6VUFpWWhQM1ZWcndzL0srVXE4SW5GUQpHR2xNR3lIUnBV\nY3BqbmRadVVPMUdkeUluR0RycDJsWWt1V2Z0T1hqbG1JCi0tLSA5cVZQSGtNNmgr\nVXdyWGZsLzg2N0lyakxuVDZuNEFDUlUrNXJIMHE3UmRRClCd0JD9Q51ZLVKv73Px\nebG4SM/4o73tU3IHJu4tyQUrFM+we+JEDvsYKHBuUgTGC+2yQRPmHV+HObTqqRnu\nzGg=\n-----END AGE ENCRYPTED FILE-----\nsops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxvsops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93@@ -144,7 +145,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:17Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wHtcTS4UVhM79Eansn1/OmrAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMRrFwSp99ZM2mPtJzAgEQgDvsIaiNifNz0/18C9OH77AG/LQLpmDiXiJYV46yLDv9vdyPL3PaLMvkAqgL3Xb2F4RcZOIUxkTS3u92xQ==-sops_lastmodified=2026-04-06T18:21:59Z-sops_mac=ENC[AES256_GCM,data:bVn78dLiiNDtGJSQp2V+g7Vlvpy/IEdXpK1R5lkv83BlqWCxjlTU11Dz3HfAuLU44m3NbH/h8Goa7DvLI+e5nQPKTtEhCTgDkK6yjZ8SxhyqyQEu7Y3l+sLM+xhAE4oco+mjRI2PS+0KraA2/6NHs8VX9exl1I+5nn1SaQ9cqes=,iv:44pMBXAZEPcu2MaxJTbggI86ONUIFBToZH9nHzIDTZo=,tag:hNME/wS3YRgUTt4V2mdLHg==,type:str]+sops_lastmodified=2026-04-06T21:15:53Z+sops_mac=ENC[AES256_GCM,data:00qJ9YQlQvu/nDwMJFup2PUf4CceElV9cepklC7Mn7L1Z93KTIpsq1Hg9erI7cePxHD+Fbd8mhlZNZpL5IYb5wVRNlPQ6qlCgdCdkAsvJyEiR4xiio4HVNXm7JDYVjpoZgjma+CooDrZwoEVFIfG1mTjVSdrNvvxpJ0xju1cYwE=,iv:G7rSoIcJFJS4zxaFcJlPkO3TqoteizUliNKpyHDgyeo=,tag:++pji9aEIz/BPjsxmdKJqw==,type:str]sops_unencrypted_suffix=_unencrypted-sops_version=3.12.1+sops_version=3.12.2diff --git a/infra/stacks/notification-service/index.ts b/infra/stacks/notification-service/index.tsindex d1189e957e..60f2b95984 100644--- a/infra/stacks/notification-service/index.ts+++ b/infra/stacks/notification-service/index.ts@@ -47,6 +47,11 @@ const APNS_KEY_ID = aws.secretsmanager.apply((secret) => secret.secretString);const APNS_PRIVATE_KEY = config.requireSecret(`apns_private_key`);+const UNSUBSCRIBE_HMAC_SECRET_KEY = `url-signing-hmac-${stack}`;+const unsubscribeHmacSecretArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: UNSUBSCRIBE_HMAC_SECRET_KEY })+ .apply((secret) => secret.arn);+const FCM_SECRET_KEY = config.require(`fcm_secret_key`);const fcmCredentials: pulumi.Output<string> = aws.secretsmanager.getSecretVersionOutput({ secretId: FCM_SECRET_KEY })@@ -158,6 +163,7 @@ const notificationService = new NotificationService('notification-service', {internalApiKeyArn,MACRO_API_TOKENS.macroApiTokenPublicKeyArn,authenticationServiceInternalApiKeyArn,+ unsubscribeHmacSecretArn,],queueArns: [pushNotificationEventHandlerQueueArn,@@ -270,6 +276,10 @@ const notificationService = new NotificationService('notification-service', {name: 'AUTHENTICATION_SERVICE_SECRET_KEY',value: pulumi.interpolate`${AUTHENTICATION_SERVICE_INTERNAL_API_KEY}`,},+ {+ name: 'URL_SIGNING_HMAC',+ value: UNSUBSCRIBE_HMAC_SECRET_KEY,+ },// OpenTelemetry / Datadog tracing configuration{name: 'DD_SERVICE',diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex 80f41a1427..95496da5a7 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -535,7 +535,7 @@},"/v1/user_notifications/preferences": {"get": {- "tags": ["user_notification"],+ "tags": ["notification_crate::inbound::http::preferences"],"summary": "Get the notification types that the user has disabled.","operationId": "get_notification_type_preferences","responses": {@@ -574,7 +574,7 @@},"/v1/user_notifications/preferences/{notification_event_type}/disable": {"put": {- "tags": ["user_notification"],+ "tags": ["notification_crate::inbound::http::preferences"],"summary": "Disable a notification type for the authenticated user.","operationId": "disable_notification_type","parameters": [@@ -627,7 +627,7 @@},"/v1/user_notifications/preferences/{notification_event_type}/enable": {"put": {- "tags": ["user_notification"],+ "tags": ["notification_crate::inbound::http::preferences"],"summary": "Re-enable a notification type for the authenticated user.","operationId": "enable_notification_type","parameters": [diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex d337e4ec25..0554411826 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1383,7 +1383,9 @@ dependencies = ["axum","axum-core","bytes",+ "cookie","futures-util",+ "headers","http 1.3.1","http-body 1.0.1","http-body-util",@@ -2753,6 +2755,29 @@ dependencies = ["regex",]+[[package]]+name = "decode_jwt"+version = "0.1.0"+dependencies = [+ "axum",+ "axum-extra",+ "cookie",+ "http-body-util",+ "jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)",+ "macro_auth",+ "macro_user_id",+ "model-error-response",+ "model_user",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "tokio",+ "tower 0.5.2",+ "tracing",+ "url",+ "urlencoding",+]+[[package]]name = "deflate64"version = "0.1.9"@@ -3567,11 +3592,15 @@ version = "0.1.0"dependencies = ["askama","chrono",+ "hmac",+ "macro_env",+ "macro_service_urls","macro_user_id","model_notifications","notification","rootcause","serde",+ "sha2","tracing",]@@ -4570,6 +4599,30 @@ dependencies = ["hashbrown 0.15.2",]+[[package]]+name = "headers"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "headers-core",+ "http 1.3.1",+ "httpdate",+ "mime",+ "sha1",+]++[[package]]+name = "headers-core"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4"+dependencies = [+ "http 1.3.1",+]+[[package]]name = "heck"version = "0.4.1"@@ -5841,6 +5894,7 @@ version = "0.1.0"dependencies = ["anyhow","axum",+ "axum-extra","cookie","jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)","macro_env",@@ -5989,6 +6043,8 @@ version = "0.1.0"dependencies = ["anyhow","axum",+ "axum-extra",+ "decode_jwt","http-body-util","ip_extractor","macro_auth",@@ -6006,12 +6062,14 @@ dependencies = ["remote_env_var","serde","serde_json",+ "serde_urlencoded","sqlx","thiserror 2.0.17","tokio","tower 0.5.2","tracing","url",+ "urlencoding","user_quota","uuid",]@@ -6043,6 +6101,14 @@ dependencies = ["anyhow",]+[[package]]+name = "macro_service_urls"+version = "0.1.0"+dependencies = [+ "macro_env",+ "url",+]+[[package]]name = "macro_sha_count_client"version = "0.1.0"@@ -6882,12 +6948,18 @@ dependencies = ["axum","chrono","cowlike",+ "decode_jwt","either","futures","hex",+ "hmac",+ "http-body-util","itertools 0.14.0","last_online_tracker",+ "macro_auth","macro_db_migrator",+ "macro_env",+ "macro_service_urls","macro_user_id","macro_uuid","model-entity",@@ -6906,7 +6978,9 @@ dependencies = ["strum","thiserror 2.0.17","tokio",+ "tower 0.5.2","tracing",+ "url","utoipa","uuid",]@@ -6940,8 +7014,10 @@ dependencies = ["chrono","either","email_formatting",+ "hmac","inquire","macro_aws_config",+ "macro_env","macro_user_id","model-entity","model_notifications",@@ -6952,6 +7028,7 @@ dependencies = ["rootcause","serde","serde_json",+ "sha2","sqlx","tokio","tracing",@@ -6970,8 +7047,10 @@ dependencies = ["aws-sdk-sqs","axum","chrono",+ "decode_jwt","email_formatting","email_validator",+ "hmac","http-body-util","itertools 0.14.0","last_online_tracker",@@ -7004,6 +7083,7 @@ dependencies = ["serde","serde_json","ses_client",+ "sha2","sns_client","sqlx","thiserror 2.0.17",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 76d2aeba2b..4f38cd39fc 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -23,6 +23,7 @@ members = ["contacts_service","convert_service","cowlike",+ "decode_jwt","dataloss_prevention_handler","delete_chat_handler","deleted_item_poller",@@ -52,6 +53,7 @@ members = ["gmail_client","image_proxy_service","integration_tests/*",+ "invite_email","lambda_client","lexical_client","macro_auth",@@ -69,6 +71,7 @@ members = ["macro_sha_count_client","macro_share_permissions","macro_uuid",+ "memory","mention_utils","model","model_notifications",@@ -101,7 +104,6 @@ members = ["rate_limit","readonly_pool","referral",- "invite_email","roles_and_permissions","rpc/axum_rpc","rpc/axum_rpc_emit",@@ -131,7 +133,7 @@ members = ["upload_extractor_lambda_trigger","user_link_cleanup_handler","user_quota",- "worker_trigger", "memory",+ "worker_trigger",][workspace.dependencies]@@ -166,6 +168,7 @@ ego-tree = "0.6.2"either = "1"futures = "0.3.31"hex = "0.4.3"+hmac = "0.12.1"http = "1"http-body-util = "0.1.2"inquire = "0.7"diff --git a/rust/cloud-storage/authentication_service/src/api/middleware/extract_tokens.rs b/rust/cloud-storage/authentication_service/src/api/middleware/extract_tokens.rsindex c9a0a96daa..596c5225f7 100644--- a/rust/cloud-storage/authentication_service/src/api/middleware/extract_tokens.rs+++ b/rust/cloud-storage/authentication_service/src/api/middleware/extract_tokens.rs@@ -5,41 +5,27 @@ use axum::{middleware::Next,response::{IntoResponse, Response},};-use macro_auth::error::MacroAuthError;+use macro_auth::headers::{AccessTokenExtractor, RefreshTokenExtractor};/// Extracts the access token and refresh token and inserts into TokenContext-pub(in crate::api) async fn handler(mut req: Request, next: Next) -> Result<Response, Response> {- let headers = req.headers();- let access_token = match macro_auth::headers::extract_access_token_from_request_headers(headers)- {- Ok(access_token) => access_token,- Err(e) => match e {- MacroAuthError::NoAccessTokenProvided => {- return Err((StatusCode::BAD_REQUEST, "no access token to refresh").into_response());- }- _ => {- tracing::error!(error=?e, "unable to extract access token from request headers");- return Err((StatusCode::INTERNAL_SERVER_ERROR).into_response());- }- },+pub(in crate::api) async fn handler(+ access_token: Result<AccessTokenExtractor, StatusCode>,+ refresh_token: Result<RefreshTokenExtractor, StatusCode>,+ mut req: Request,+ next: Next,+) -> Result<Response, Response> {+ let access_token = match access_token {+ Ok(access_token) => access_token.as_ref().to_string(),+ Err(_e) => {+ return Err((StatusCode::BAD_REQUEST, "no access token to refresh").into_response());+ }};- let refresh_token = match macro_auth::headers::extract_refresh_token_from_request_headers(- headers,- ) {- Ok(refresh_token) => refresh_token,- Err(e) => match e {- MacroAuthError::NoRefreshTokenProvided => {- tracing::error!(error=?e, "missing refresh token");- return Err(- (StatusCode::BAD_REQUEST, "no refresh token to refresh").into_response()- );- }- _ => {- tracing::error!(error=?e, "unable to extract refresh token from request headers");- return Err((StatusCode::INTERNAL_SERVER_ERROR).into_response());- }- },+ let refresh_token = match refresh_token {+ Ok(refresh_token) => refresh_token.as_ref().to_string(),+ Err(_e) => {+ return Err((StatusCode::BAD_REQUEST, "no refresh token to refresh").into_response());+ }};req.extensions_mut().insert(TokenContext {diff --git a/rust/cloud-storage/decode_jwt/Cargo.toml b/rust/cloud-storage/decode_jwt/Cargo.tomlnew file mode 100644index 0000000000..33a82863c3--- /dev/null+++ b/rust/cloud-storage/decode_jwt/Cargo.toml@@ -0,0 +1,30 @@+[package]+edition = "2024"+name = "decode_jwt"+publish = false+version = "0.1.0"++[features]+local_auth = []++[dependencies]+axum = { workspace = true }+axum-extra = { workspace = true }+macro_auth = { path = "../macro_auth" }+macro_user_id = { path = "../macro_user_id" }+model-error-response = { path = "../model-error-response" }+model_user = { path = "../model_user" }+serde = { workspace = true }+tracing = { workspace = true }++[dev-dependencies]+cookie = { workspace = true }+http-body-util = { workspace = true }+jsonwebtoken = { workspace = true }+macro_auth = { path = "../macro_auth", features = ["testing"] }+serde_json = { workspace = true }+serde_urlencoded = "0.7"+tokio = { workspace = true, features = ["macros", "rt"] }+tower = { workspace = true }+url = { workspace = true }+urlencoding = { workspace = true }diff --git a/rust/cloud-storage/decode_jwt/src/lib.rs b/rust/cloud-storage/decode_jwt/src/lib.rsnew file mode 100644index 0000000000..1711385ce2--- /dev/null+++ b/rust/cloud-storage/decode_jwt/src/lib.rs@@ -0,0 +1,233 @@+#![deny(missing_docs)]+//! JWT decoding and validation for axum-based services.+//!+//! Provides an axum extractor ([`DecodedJwt`]) and middleware ([`handler`])+//! that decode a JWT from either the `Authorization` header or a+//! `macro-api-token` query parameter.++#[cfg(test)]+mod test;++use axum::{+ Json, RequestPartsExt,+ extract::{FromRef, FromRequestParts, Query},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use axum_extra::either::Either;+use macro_auth::{+ error::MacroAuthError,+ headers::AccessTokenExtractor,+ middleware::decode_jwt::{JwtToken, JwtValidationArgs},+};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_error_response::ErrorResponse;+use model_user::UserContext;+use serde::Deserialize;++/// Stores information about the JWT, this is used for the logout in particular call+#[derive(Clone)]+pub struct JwtContext {+ /// Macro access token The audience of the token+ pub audience: String,+ /// Macro access token The tenant id of the token+ pub tid: String,+}++/// the struct we use to extract api token from query parms+#[derive(Deserialize)]+#[serde(rename_all = "kebab-case")]+pub struct Params {+ macro_api_token: Option<String>,+}++/// The result of successfully decoding a JWT from a request.+pub struct DecodedJwt {+ /// The user context extracted from the token.+ pub user_context: UserContext,+ /// Present only when the token is a macro-access-token.+ pub jwt_context: Option<JwtContext>,++ /// the parsed macro user id of the user+ pub macro_user_id: MacroUserIdStr<'static>,+}++impl<S> FromRequestParts<S> for DecodedJwt+where+ S: Send + Sync,+ JwtValidationArgs: FromRef<S>,+{+ type Rejection = Either<DecodeJwtError, StatusCode>;++ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ state: &S,+ ) -> Result<Self, Self::Rejection> {+ let args = JwtValidationArgs::from_ref(state);+ let (access_token, Query(params)): (+ Result<AccessTokenExtractor, StatusCode>,+ Query<Params>,+ ) = parts+ .extract()+ .await+ .map_err(|_| Either::E2(StatusCode::INTERNAL_SERVER_ERROR))?;++ Self::new(access_token, params, &args).map_err(Either::E1)+ }+}++impl DecodedJwt {+ /// Extract and decode a JWT from query params or headers.+ ///+ /// This is the core logic separated from the middleware so it can be called+ /// independently (e.g. from a non-middleware handler).+ pub fn new(+ access_token_header: Result<AccessTokenExtractor, StatusCode>,+ query_params: Params,+ jwt_validation_args: &JwtValidationArgs,+ ) -> Result<DecodedJwt, DecodeJwtError> {+ if cfg!(feature = "local_auth") && std::env::var("LOCAL_USER_ID").is_ok() {+ let user_id =+ std::env::var("LOCAL_USER_ID").unwrap_or("macro|[email protected]".to_string());+ let Ok(macro_user_id) =+ MacroUserIdStr::parse_from_str(&user_id).map(CowLike::into_owned)+ else {+ return Err(DecodeJwtError::InvalidUserId(user_id));+ };+ let org_id: i32 = std::env::var("LOCAL_ORG_ID")+ .unwrap_or("1".to_string())+ .parse()+ .map_err(|_| {+ DecodeJwtError::InvalidUserId("LOCAL_ORG_ID is not a valid i32".to_string())+ })?;+ return Ok(DecodedJwt {+ user_context: UserContext {+ user_id,+ fusion_user_id: std::env::var("LOCAL_FUSION_USER_ID")+ .unwrap_or("set me!".to_string()),+ organization_id: Some(org_id),+ permissions: None,+ },+ jwt_context: None,+ macro_user_id,+ });+ }++ let access_token = if let Params {+ macro_api_token: Some(macro_api_token),+ } = query_params+ {+ tracing::trace!("macro-api-token found in query params");+ macro_api_token+ } else {+ match access_token_header {+ Ok(extractor) => extractor.as_ref().to_string(),+ Err(e) => {+ tracing::trace!(error=?e, "unable to get macro access token");+ return Err(DecodeJwtError::NoToken);+ }+ }+ };++ let jwt = macro_auth::middleware::decode_jwt::handler(jwt_validation_args, &access_token)+ .map_err(|e| match e {+ MacroAuthError::JwtExpired => DecodeJwtError::Expired,+ other => DecodeJwtError::Invalid(other),+ })?;++ let (user_id, fusion_user_id, organization_id) = match &jwt {+ JwtToken::MacroAccessToken(token) => (+ token.macro_user_id.clone(),+ token+ .root_macro_id+ .clone()+ .unwrap_or_else(|| token.fusion_user_id.clone()),+ token.macro_organization_id,+ ),+ JwtToken::MacroApiToken(token) => (+ token.macro_user_id.clone(),+ token.fusion_user_id.clone(),+ token.macro_organization_id,+ ),+ };++ let jwt_context = if let JwtToken::MacroAccessToken(token) = jwt {+ Some(JwtContext {+ audience: token.aud,+ tid: token.tid,+ })+ } else {+ None+ };++ let Ok(macro_user_id) = MacroUserIdStr::parse_from_str(&user_id).map(CowLike::into_owned)+ else {+ return Err(DecodeJwtError::InvalidUserId(user_id));+ };++ Ok(DecodedJwt {+ user_context: UserContext {+ user_id,+ fusion_user_id,+ organization_id,+ permissions: None,+ },+ jwt_context,+ macro_user_id,+ })+ }+}++/// Errors that can occur when decoding a JWT from a request.+#[derive(Debug)]+pub enum DecodeJwtError {+ /// No token was found in query params or headers.+ NoToken,+ /// The token was present but expired.+ Expired,+ /// The token was present but validation failed.+ Invalid(MacroAuthError),+ /// The macro user id could not be parsed+ InvalidUserId(String),+}++impl IntoResponse for DecodeJwtError {+ fn into_response(self) -> Response {+ match self {+ DecodeJwtError::NoToken => (+ StatusCode::UNAUTHORIZED,+ Json(ErrorResponse {+ message: "unauthorized".into(),+ }),+ )+ .into_response(),+ DecodeJwtError::Expired => (+ StatusCode::UNAUTHORIZED,+ Json(ErrorResponse {+ message: "jwt expired".into(),+ }),+ )+ .into_response(),+ DecodeJwtError::Invalid(e) => {+ tracing::error!(error=?e, "unable to decode jwt");+ (+ StatusCode::UNAUTHORIZED,+ Json(ErrorResponse {+ message: "unauthorized".into(),+ }),+ )+ .into_response()+ }+ DecodeJwtError::InvalidUserId(id) => {+ tracing::error!(error=%id, "invalid macro user id");+ (+ StatusCode::UNAUTHORIZED,+ Json(ErrorResponse {+ message: "invalid user id".into(),+ }),+ )+ .into_response()+ }+ }+ }+}diff --git a/rust/cloud-storage/decode_jwt/src/test.rs b/rust/cloud-storage/decode_jwt/src/test.rsnew file mode 100644index 0000000000..fac8072519--- /dev/null+++ b/rust/cloud-storage/decode_jwt/src/test.rs@@ -0,0 +1,485 @@+use std::collections::HashMap;+use std::time::{SystemTime, UNIX_EPOCH};++use axum::Router;+use axum::extract::FromRef;+use axum::http::Request;+use axum::http::StatusCode;+use axum::routing::get;+use http_body_util::BodyExt;+use macro_auth::headers::{AccessTokenCookieExtractor, AccessTokenExtractor};+use macro_auth::middleware::decode_jwt::JwtValidationArgs;+use tower::util::ServiceExt;++use super::*;++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++// These must match the empty values from JwtValidationArgs::new_testing()+const TEST_SECRET: &str = "";+const TEST_AUDIENCE: &str = "";+const TEST_ISSUER: &str = "";++fn test_args() -> JwtValidationArgs {+ JwtValidationArgs::new_testing()+}++fn create_access_token(+ audience: &str,+ issuer: &str,+ email: &str,+ secret: &str,+ exp: usize,+) -> String {+ let claims = serde_json::json!({+ "aud": audience,+ "exp": exp,+ "iss": issuer,+ "tid": "tenant_id",+ "email": email,+ "fusion_user_id": "fusion_testing",+ "macro_user_id": format!("macro|{email}"),+ "macro_organization_id": 1,+ });++ let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256);+ header.kid = Some("fromFusionauth".to_string());+ jsonwebtoken::encode(+ &header,+ &claims,+ &jsonwebtoken::EncodingKey::from_secret(secret.as_ref()),+ )+ .unwrap()+}++fn valid_token() -> String {+ let exp = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_secs() as usize+ + 3600;+ create_access_token(+ TEST_AUDIENCE,+ TEST_ISSUER,+ "[email protected]",+ TEST_SECRET,+ exp,+ )+}++fn expired_token() -> String {+ create_access_token(+ TEST_AUDIENCE,+ TEST_ISSUER,+ "[email protected]",+ TEST_SECRET,+ 1000,+ )+}++fn no_params() -> Params {+ Params {+ macro_api_token: None,+ }+}++/// Wrap a raw token string in an AccessTokenExtractor via the Cookie variant.+fn extractor_from_token(token: &str) -> Result<AccessTokenExtractor, StatusCode> {+ Ok(AccessTokenExtractor::Cookie(AccessTokenCookieExtractor(+ cookie::Cookie::new("token", token.to_string()),+ )))+}++fn no_extractor() -> Result<AccessTokenExtractor, StatusCode> {+ Err(StatusCode::UNAUTHORIZED)+}++/// Confirm that axum's `Query<Params>` (which uses `serde_urlencoded`) decodes+/// percent-encoded values the same way the old `url::form_urlencoded::parse` did.+#[test]+fn query_extractor_decodes_percent_encoded_token() {+ let token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abc";+ let encoded = format!("macro-api-token={}", urlencoding::encode(token));++ let params: Params = serde_urlencoded::from_str(&encoded).unwrap();+ assert_eq!(params.macro_api_token.as_deref(), Some(token));+}++/// The old code collected into a `HashMap<String, String>` via+/// `url::form_urlencoded::parse`. Confirm `serde_urlencoded` produces the same+/// result for a realistic JWT value that contains dots (which are not special in+/// percent-encoding but are worth checking).+#[test]+fn query_extractor_matches_form_urlencoded_parse() {+ let token = "header.payload.signature";+ let query = format!("macro-api-token={token}&other=value");++ // Old approach+ let old: HashMap<String, String> = url::form_urlencoded::parse(query.as_bytes())+ .into_owned()+ .collect();++ // New approach+ let new: Params = serde_urlencoded::from_str(&query).unwrap();++ assert_eq!(+ old.get("macro-api-token").unwrap(),+ new.macro_api_token.as_ref().unwrap()+ );+}++/// Percent-encoded special characters (e.g. `%2B` for `+`) must be decoded.+#[test]+fn query_extractor_decodes_special_characters() {+ let query = "macro-api-token=a%2Bb%3Dc";++ let old: HashMap<String, String> = url::form_urlencoded::parse(query.as_bytes())+ .into_owned()+ .collect();++ let new: Params = serde_urlencoded::from_str(query).unwrap();++ assert_eq!(old.get("macro-api-token").unwrap(), "a+b=c");+ assert_eq!(new.macro_api_token.as_deref(), Some("a+b=c"));+}++// ---------------------------------------------------------------------------+// DecodedJwt::new tests+// ---------------------------------------------------------------------------++#[test]+fn no_token_and_no_query_param_returns_no_token() {+ let args = test_args();+ let result = DecodedJwt::new(no_extractor(), no_params(), &args);+ assert!(matches!(result, Err(DecodeJwtError::NoToken)));+}++#[test]+fn invalid_token_in_header_returns_invalid() {+ let args = test_args();+ let result = DecodedJwt::new(extractor_from_token("not.a.valid.jwt"), no_params(), &args);+ assert!(matches!(result, Err(DecodeJwtError::Invalid(_))));+}++#[test]+fn expired_token_returns_expired() {+ let args = test_args();+ let token = expired_token();+ let result = DecodedJwt::new(extractor_from_token(&token), no_params(), &args);+ assert!(matches!(result, Err(DecodeJwtError::Expired)));+}++#[test]+fn valid_token_in_header_returns_decoded_jwt() {+ let args = test_args();+ let token = valid_token();+ let jwt = DecodedJwt::new(extractor_from_token(&token), no_params(), &args).unwrap();++ assert_eq!(jwt.user_context.user_id, "macro|[email protected]");+ assert_eq!(jwt.user_context.organization_id, Some(1));+ assert!(jwt.jwt_context.is_some());+ assert_eq!(jwt.jwt_context.unwrap().audience, TEST_AUDIENCE);+ assert_eq!(jwt.macro_user_id.as_ref(), "macro|[email protected]");+}++#[test]+fn valid_token_via_query_param_returns_decoded_jwt() {+ let args = test_args();+ let token = valid_token();+ let params = Params {+ macro_api_token: Some(token),+ };+ // Even with no header extractor, query param should work+ let jwt = DecodedJwt::new(no_extractor(), params, &args).unwrap();++ assert_eq!(jwt.user_context.user_id, "macro|[email protected]");+}++#[test]+fn query_param_takes_precedence_over_header() {+ let args = test_args();+ let good_token = valid_token();+ let params = Params {+ macro_api_token: Some(good_token),+ };+ // Header has garbage, but query param has a valid token — query wins+ let jwt = DecodedJwt::new(extractor_from_token("garbage"), params, &args).unwrap();++ assert_eq!(jwt.user_context.user_id, "macro|[email protected]");+}++#[test]+fn wrong_secret_returns_invalid() {+ let args = test_args();+ let exp = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_secs() as usize+ + 3600;+ let token = create_access_token(+ TEST_AUDIENCE,+ TEST_ISSUER,+ "[email protected]",+ "wrong_key",+ exp,+ );+ let result = DecodedJwt::new(extractor_from_token(&token), no_params(), &args);+ assert!(matches!(result, Err(DecodeJwtError::Invalid(_))));+}++#[test]+fn wrong_audience_returns_invalid() {+ let args = test_args();+ let exp = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_secs() as usize+ + 3600;+ let token = create_access_token(+ "wrong_audience",+ TEST_ISSUER,+ "[email protected]",+ TEST_SECRET,+ exp,+ );+ let result = DecodedJwt::new(extractor_from_token(&token), no_params(), &args);+ assert!(matches!(result, Err(DecodeJwtError::Invalid(_))));+}++#[test]+fn wrong_issuer_returns_invalid() {+ let args = test_args();+ let exp = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_secs() as usize+ + 3600;+ let token = create_access_token(+ TEST_AUDIENCE,+ "wrong.issuer.com",+ "[email protected]",+ TEST_SECRET,+ exp,+ );+ let result = DecodedJwt::new(extractor_from_token(&token), no_params(), &args);+ assert!(matches!(result, Err(DecodeJwtError::Invalid(_))));+}++#[test]+fn invalid_macro_user_id_in_token_returns_invalid_user_id() {+ let exp = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_secs() as usize+ + 3600;++ // Build a token whose macro_user_id lacks the required "macro|" prefix+ let claims = serde_json::json!({+ "aud": TEST_AUDIENCE,+ "exp": exp,+ "iss": TEST_ISSUER,+ "tid": "tenant_id",+ "email": "[email protected]",+ "fusion_user_id": "fusion_testing",+ "macro_user_id": "no_pipe_prefix",+ });++ let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256);+ header.kid = Some("fromFusionauth".to_string());+ let token = jsonwebtoken::encode(+ &header,+ &claims,+ &jsonwebtoken::EncodingKey::from_secret(TEST_SECRET.as_ref()),+ )+ .unwrap();++ let args = test_args();+ let result = DecodedJwt::new(extractor_from_token(&token), no_params(), &args);+ assert!(matches!(result, Err(DecodeJwtError::InvalidUserId(_))));+}++// ---------------------------------------------------------------------------+// Router integration tests — exercises FromRequestParts via real HTTP+// ---------------------------------------------------------------------------++/// State that satisfies `JwtValidationArgs: FromRef<S>` for the DecodedJwt extractor.+#[derive(Clone)]+struct TestState {+ jwt_args: JwtValidationArgs,+}++impl FromRef<TestState> for JwtValidationArgs {+ fn from_ref(state: &TestState) -> Self {+ state.jwt_args.clone()+ }+}++/// A handler that requires DecodedJwt and returns the extracted user id.+async fn echo_user(jwt: DecodedJwt) -> String {+ jwt.user_context.user_id+}++fn test_router() -> Router {+ let state = TestState {+ jwt_args: test_args(),+ };+ Router::new()+ .route("/protected", get(echo_user))+ .with_state(state)+}++async fn response_status(router: &Router, req: Request<axum::body::Body>) -> StatusCode {+ router.clone().oneshot(req).await.unwrap().status()+}++async fn response_body(router: &Router, req: Request<axum::body::Body>) -> String {+ let resp = router.clone().oneshot(req).await.unwrap();+ let body = resp.into_body().collect().await.unwrap().to_bytes();+ String::from_utf8_lossy(&body).to_string()+}++/// The access token cookie name used in Production environment (the default).+const ACCESS_TOKEN_COOKIE: &str = "macro-access-token";++#[tokio::test]+async fn router_no_token_returns_401() {+ let router = test_router();+ let req = Request::get("/protected")+ .body(axum::body::Body::empty())+ .unwrap();+ assert_eq!(+ response_status(&router, req).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn router_invalid_bearer_returns_401() {+ let router = test_router();+ let req = Request::get("/protected")+ .header("authorization", "Bearer not.a.valid.jwt")+ .body(axum::body::Body::empty())+ .unwrap();+ assert_eq!(+ response_status(&router, req).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn router_expired_bearer_returns_401() {+ let router = test_router();+ let token = expired_token();+ let req = Request::get("/protected")+ .header("authorization", format!("Bearer {token}"))+ .body(axum::body::Body::empty())+ .unwrap();+ assert_eq!(+ response_status(&router, req).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn router_valid_bearer_returns_200() {+ let router = test_router();+ let token = valid_token();+ let req = Request::get("/protected")+ .header("authorization", format!("Bearer {token}"))+ .body(axum::body::Body::empty())+ .unwrap();+ let body = response_body(&router, req).await;+ assert_eq!(body, "macro|[email protected]");+}++#[tokio::test]+async fn router_valid_cookie_returns_200() {+ let router = test_router();+ let token = valid_token();+ let req = Request::get("/protected")+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}={token}"))+ .body(axum::body::Body::empty())+ .unwrap();+ let body = response_body(&router, req).await;+ assert_eq!(body, "macro|[email protected]");+}++#[tokio::test]+async fn router_invalid_cookie_returns_401() {+ let router = test_router();+ let req = Request::get("/protected")+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}=garbage.token"))+ .body(axum::body::Body::empty())+ .unwrap();+ assert_eq!(+ response_status(&router, req).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn router_valid_query_param_returns_200() {+ let router = test_router();+ let token = valid_token();+ let uri = format!("/protected?macro-api-token={token}");+ let req = Request::get(&uri).body(axum::body::Body::empty()).unwrap();+ let body = response_body(&router, req).await;+ assert_eq!(body, "macro|[email protected]");+}++#[tokio::test]+async fn router_invalid_query_param_returns_401() {+ let router = test_router();+ let req = Request::get("/protected?macro-api-token=garbage")+ .body(axum::body::Body::empty())+ .unwrap();+ assert_eq!(+ response_status(&router, req).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn router_query_param_takes_precedence_over_bearer() {+ let router = test_router();+ let good_token = valid_token();+ let uri = format!("/protected?macro-api-token={good_token}");+ // Bearer header is garbage, but query param is valid — query wins+ let req = Request::get(&uri)+ .header("authorization", "Bearer garbage.token")+ .body(axum::body::Body::empty())+ .unwrap();+ let body = response_body(&router, req).await;+ assert_eq!(body, "macro|[email protected]");+}++#[tokio::test]+async fn router_bearer_takes_precedence_over_cookie() {+ let router = test_router();+ let token = valid_token();+ // Both Bearer header and cookie present — Bearer wins (Either::E1 in AccessTokenExtractor)+ let req = Request::get("/protected")+ .header("authorization", format!("Bearer {token}"))+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}=garbage"))+ .body(axum::body::Body::empty())+ .unwrap();+ let body = response_body(&router, req).await;+ assert_eq!(body, "macro|[email protected]");+}++#[tokio::test]+async fn router_wrong_cookie_name_returns_401() {+ let router = test_router();+ let token = valid_token();+ // Cookie name doesn't match the expected access token cookie+ let req = Request::get("/protected")+ .header("cookie", format!("wrong-cookie-name={token}"))+ .body(axum::body::Body::empty())+ .unwrap();+ assert_eq!(+ response_status(&router, req).await,+ StatusCode::UNAUTHORIZED+ );+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rsindex 9748affba6..8a3c49e3e8 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs@@ -21,6 +21,7 @@ use axum::middleware::Next;use axum::response::IntoResponse;use chat::inbound::ChatModelAccess;use futures::StreamExt;+use macro_auth::headers::AccessTokenExtractor;use macro_db_client::dcs::create_chat;use macro_user_id::user_id::MacroUserIdStr;use memory::domain::MemoryService;@@ -42,20 +43,22 @@ pub(crate) struct BearerToken(pub String);/// Middleware that extracts the raw access token from request headers or cookies/// and inserts it into request extensions.pub(crate) async fn attach_bearer_token(+ access_token: Result<AccessTokenExtractor, StatusCode>,mut req: Request,next: Next,) -> Result<axum::response::Response, StatusCode> {if cfg!(feature = "local_auth") {- let token = macro_auth::headers::extract_access_token_from_request_headers(req.headers())+ let token = access_token+ .map(|t| t.as_ref().to_string()).unwrap_or_default();req.extensions_mut().insert(BearerToken(token));return Ok(next.run(req).await);}- let token = macro_auth::headers::extract_access_token_from_request_headers(req.headers())- .map_err(|_| StatusCode::UNAUTHORIZED)?;+ let token = access_token.map_err(|_| StatusCode::UNAUTHORIZED)?;- req.extensions_mut().insert(BearerToken(token));+ req.extensions_mut()+ .insert(BearerToken(token.as_ref().to_string()));Ok(next.run(req).await)}diff --git a/rust/cloud-storage/email_formatting/Cargo.toml b/rust/cloud-storage/email_formatting/Cargo.tomlindex b1c82e4d49..ee6407cb15 100644--- a/rust/cloud-storage/email_formatting/Cargo.toml+++ b/rust/cloud-storage/email_formatting/Cargo.toml@@ -7,9 +7,13 @@ version = "0.1.0"[dependencies]askama = { workspace = true }chrono = { workspace = true }+hmac = { workspace = true }+macro_env = { path = "../macro_env" }+macro_service_urls = { path = "../macro_service_urls" }macro_user_id = { path = "../macro_user_id" }model_notifications = { path = "../model_notifications" }notification = { path = "../notification" }rootcause = { workspace = true }serde = { workspace = true, features = ["derive"] }+sha2 = { workspace = true }tracing = { workspace = true }diff --git a/rust/cloud-storage/email_formatting/src/lib.rs b/rust/cloud-storage/email_formatting/src/lib.rsindex 99cc64d1ec..f5eafcc097 100644--- a/rust/cloud-storage/email_formatting/src/lib.rs+++ b/rust/cloud-storage/email_formatting/src/lib.rs@@ -1,13 +1,17 @@use askama::Template;use chrono::{DateTime, Utc};+use hmac::Hmac;+use macro_env::Environment;+use macro_service_urls::EnvExtMacroServiceUrls;use macro_user_id::cowlike::CowLike;use model_notifications::{NotifEvent, NotificationTitle};use notification::domain::models::{Notification, NotificationExtEmail, RateLimitConfig, RateLimitKey, UserNotificationRow,- email_notification_digest::ports::DigestBatch, queue_message::EmailContent,+ email_notification_digest::ports::DigestBatch, queue_message::EmailContent, signing::SignedUrl,};use rootcause::Report;use serde::{Deserialize, Serialize};+use sha2::Sha256;use std::time::Duration;#[derive(Template)]@@ -16,6 +20,8 @@ struct DigestTemplate {notifs: Vec<NotifPreview>,num_truncated: usize,total_count: usize,+ /// the signed url which allows a client to unsubscribe from the email in an unauthenticated context+ unsubscribe_url: SignedUrl,}struct NotifPreview {@@ -50,7 +56,11 @@ pub struct EmailDigestNotification {}impl EmailDigestNotification {- pub fn new_from_digest_batch(digest: DigestBatch) -> Result<Self, Report> {+ pub fn new_from_digest_batch(+ digest: DigestBatch,+ env: Environment,+ sha: Hmac<Sha256>,+ ) -> Result<Self, Report> {let DigestBatch {user_id: _,notifications,@@ -75,10 +85,22 @@ impl EmailDigestNotification {let preview_len = notifs.len();let num_truncated = input_len - preview_len;+ let mut unsubscribe_url = env.notification_service();+ unsubscribe_url.set_path(&format!(+ "/user_notifications/preferences/{}/disable",+ Self::TYPE_NAME+ ));+ unsubscribe_url+ .query_pairs_mut()+ .append_pair("id", digest.user_id.as_ref())+ .finish();+ let unsubscribe_url = SignedUrl::new(unsubscribe_url, sha);+let inner_html_string = DigestTemplate {notifs,num_truncated,total_count: input_len,+ unsubscribe_url,}.render()?;diff --git a/rust/cloud-storage/email_formatting/templates/digest.html b/rust/cloud-storage/email_formatting/templates/digest.htmlindex 49ce750da3..b127010d6b 100644--- a/rust/cloud-storage/email_formatting/templates/digest.html+++ b/rust/cloud-storage/email_formatting/templates/digest.html@@ -259,6 +259,23 @@</tr></tbody></table>++ <div+ style="+ text-align: center;+ padding-top: 16px;+ font-family: "Inter", sans-serif;+ font-size: 12px;+ "+ >+ <a+ style="color: #636363; text-decoration: underline"+ href="{{ unsubscribe_url.as_ref() }}"+ target="_blank"+ >+ Unsubscribe from digest emails+ </a>+ </div></div></div></div>diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.tomlindex 83d886b83a..ec9c53e8c2 100644--- a/rust/cloud-storage/github/Cargo.toml+++ b/rust/cloud-storage/github/Cargo.toml@@ -31,7 +31,7 @@ entity_access = { path = "../entity_access", default-features = false, features"ports",], optional = true }hex = { workspace = true }-hmac = "0.12.1"+hmac = { workspace = true }jsonwebtoken = { workspace = true }macro_env = { path = "../macro_env", features = ["frontend_url"] }regex = { workspace = true }diff --git a/rust/cloud-storage/macro_auth/Cargo.toml b/rust/cloud-storage/macro_auth/Cargo.tomlindex 1ee3fa6d60..eaf4012282 100644--- a/rust/cloud-storage/macro_auth/Cargo.toml+++ b/rust/cloud-storage/macro_auth/Cargo.toml@@ -11,6 +11,7 @@ testing = [][dependencies]anyhow = { workspace = true }axum = { workspace = true }+axum-extra = { workspace = true, features = ["cookie", "typed-header"] }cookie = { workspace = true }jsonwebtoken = { workspace = true }macro_env = { path = "../macro_env" }diff --git a/rust/cloud-storage/macro_auth/src/headers.rs b/rust/cloud-storage/macro_auth/src/headers.rsindex fe44aaac52..a13a45853e 100644--- a/rust/cloud-storage/macro_auth/src/headers.rs+++ b/rust/cloud-storage/macro_auth/src/headers.rs@@ -1,101 +1,170 @@+use std::sync::LazyLock;++use axum::{RequestPartsExt, extract::FromRequestParts, http::StatusCode};+use axum_extra::{+ TypedHeader,+ either::Either,+ extract::CookieJar,+ headers::{Authorization, authorization::Bearer},+};use cookie::Cookie;use macro_env::Environment;-use crate::{- constant::{MACRO_ACCESS_TOKEN_COOKIE, MACRO_REFRESH_TOKEN_COOKIE, MACRO_REFRESH_TOKEN_HEADER},- error::MacroAuthError,+use crate::constant::{+ MACRO_ACCESS_TOKEN_COOKIE, MACRO_REFRESH_TOKEN_COOKIE, MACRO_REFRESH_TOKEN_HEADER,};-/// Extracts the access token from request headers-pub fn extract_access_token_from_request_headers(- headers: &axum::http::HeaderMap,-) -> Result<String, MacroAuthError> {- let auth_token_header = headers- .get(axum::http::header::AUTHORIZATION)- .and_then(|header| header.to_str().ok());-- let jwt = if let Some(auth_token) = auth_token_header {- let auth_token_parts = auth_token.split("Bearer ").collect::<Vec<&str>>();- if auth_token_parts.len() != 2 {- return Err(MacroAuthError::InvalidAuthorizationHeaderFormat);+/// Extracts the access token from a cookie. Returns `UNAUTHORIZED` if the cookie is missing.+pub struct AccessTokenCookieExtractor(pub Cookie<'static>);++impl<S> FromRequestParts<S> for AccessTokenCookieExtractor+where+ S: Send + Sync,+{+ type Rejection = StatusCode;++ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ _state: &S,+ ) -> Result<Self, Self::Rejection> {+ let jar: CookieJar = parts.extract().await.expect("This extractor is infallible");+ static ACCESS_COOKIE_NAME: LazyLock<String> =+ LazyLock::new(|| match Environment::new_or_prod() {+ Environment::Production => MACRO_ACCESS_TOKEN_COOKIE.to_string(),+ Environment::Develop => format!("dev-{MACRO_ACCESS_TOKEN_COOKIE}"),+ Environment::Local => format!("local-{MACRO_ACCESS_TOKEN_COOKIE}"),+ });++ match jar.get(&ACCESS_COOKIE_NAME) {+ Some(c) => Ok(Self(c.clone())),+ None => Err(StatusCode::UNAUTHORIZED),}- tracing::trace!("Authorization header provided");- Some(auth_token_parts[1].to_string())- } else {- // Check for cookie- tracing::trace!("no Authorization header provided. checking for cookie");- let cookie_header = headers- .get(axum::http::header::COOKIE)- .and_then(|header| header.to_str().ok());- let cookie_jwt = if let Some(header) = cookie_header {- header.split(';').find_map(|cookie| {- let cookie = Cookie::parse(cookie).ok()?;- // If the environment is prod, we want to use the base name for the cookie- // Otherwise, we want to prefix the cookie name with dev-- let access_token_cookie_name = match Environment::new_or_prod() {- Environment::Production => MACRO_ACCESS_TOKEN_COOKIE,- Environment::Develop => &format!("dev-{MACRO_ACCESS_TOKEN_COOKIE}"),- Environment::Local => &format!("local-{MACRO_ACCESS_TOKEN_COOKIE}"),- };-- if cookie.name() == access_token_cookie_name {- Some(cookie.value().to_owned())- } else {- None- }- })- } else {- None- };- cookie_jwt.clone()- };+ }+}+/// Extracts the refresh token from a cookie. Returns `UNAUTHORIZED` if the cookie is missing.+pub struct RefreshTokenCookieExtractor(pub Cookie<'static>);++impl<S> FromRequestParts<S> for RefreshTokenCookieExtractor+where+ S: Send + Sync,+{+ type Rejection = StatusCode;++ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ _state: &S,+ ) -> Result<Self, Self::Rejection> {+ let jar: CookieJar = parts.extract().await.expect("This extractor is infallible");+ static REFRESH_COOKIE_NAME: LazyLock<String> =+ LazyLock::new(|| match Environment::new_or_prod() {+ Environment::Production => MACRO_REFRESH_TOKEN_COOKIE.to_string(),+ Environment::Develop => format!("dev-{MACRO_REFRESH_TOKEN_COOKIE}"),+ Environment::Local => format!("local-{MACRO_REFRESH_TOKEN_COOKIE}"),+ });++ match jar.get(&REFRESH_COOKIE_NAME) {+ Some(c) => Ok(Self(c.clone())),+ None => Err(StatusCode::UNAUTHORIZED),+ }+ }+}++/// Extracts the access token from either the `Authorization: Bearer` header or a cookie.+/// Returns `UNAUTHORIZED` if neither source provides a token.+pub enum AccessTokenExtractor {+ Header(TypedHeader<Authorization<Bearer>>),+ Cookie(AccessTokenCookieExtractor),+}- if let Some(jwt) = jwt {- return Ok(jwt);+impl AsRef<str> for AccessTokenExtractor {+ fn as_ref(&self) -> &str {+ match self {+ AccessTokenExtractor::Header(typed_header) => typed_header.token(),+ AccessTokenExtractor::Cookie(access_token_cookie_extractor) => {+ access_token_cookie_extractor.0.value_trimmed()+ }+ }}+}++impl<S> FromRequestParts<S> for AccessTokenExtractor+where+ S: Send + Sync,+{+ type Rejection = StatusCode;- Err(MacroAuthError::NoAccessTokenProvided)+ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ _state: &S,+ ) -> Result<Self, Self::Rejection> {+ let either: Either<TypedHeader<Authorization<Bearer>>, AccessTokenCookieExtractor> =+ parts.extract().await?;+ Ok(match either {+ Either::E1(l) => Self::Header(l),+ Either::E2(r) => Self::Cookie(r),+ })+ }}-/// Extracts refresh token from request headers-pub fn extract_refresh_token_from_request_headers(- headers: &axum::http::HeaderMap,-) -> Result<String, MacroAuthError> {- let token_header = headers- .get(MACRO_REFRESH_TOKEN_HEADER)- .and_then(|header| header.to_str().ok());-- let token: Option<String> = if let Some(token) = token_header {- Some(token.to_string())- } else {- // Check for cookie- tracing::trace!("no x-macro-refresh-token header provided. checking for cookie");- let cookie_header = headers- .get(axum::http::header::COOKIE)- .and_then(|header| header.to_str().ok());- let cookie_jwt = if let Some(header) = cookie_header {- header.split(';').find_map(|cookie| {- let cookie = Cookie::parse(cookie).ok()?;- let refresh_token_cookie_name = match Environment::new_or_prod() {- Environment::Production => MACRO_REFRESH_TOKEN_COOKIE,- Environment::Develop => &format!("dev-{MACRO_REFRESH_TOKEN_COOKIE}"),- Environment::Local => &format!("local-{MACRO_REFRESH_TOKEN_COOKIE}"),- };- if cookie.name() == refresh_token_cookie_name {- Some(cookie.value().to_owned())- } else {- None- }- })- } else {- None+/// Extracts the refresh token from a custom header. Returns `BAD_REQUEST` if the header is missing.+pub struct RefreshTokenHeaderExtractor(pub String);++impl<S> FromRequestParts<S> for RefreshTokenHeaderExtractor+where+ S: Send + Sync,+{+ type Rejection = StatusCode;++ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ _state: &S,+ ) -> Result<Self, Self::Rejection> {+ let Some(header) = parts+ .headers+ .get(MACRO_REFRESH_TOKEN_HEADER)+ .and_then(|h| h.to_str().ok())+ else {+ return Err(StatusCode::BAD_REQUEST);};- cookie_jwt.clone()- };+ Ok(Self(header.to_string()))+ }+}++/// Extracts the refresh token from either a custom header or a cookie.+/// Returns `UNAUTHORIZED` if neither source provides a token.+pub enum RefreshTokenExtractor {+ Header(RefreshTokenHeaderExtractor),+ Cookie(RefreshTokenCookieExtractor),+}- if let Some(token) = token {- return Ok(token);+impl AsRef<str> for RefreshTokenExtractor {+ fn as_ref(&self) -> &str {+ match self {+ RefreshTokenExtractor::Header(refresh_token_header_extractor) => {+ &refresh_token_header_extractor.0+ }+ RefreshTokenExtractor::Cookie(refresh_token_cookie_extractor) => {+ refresh_token_cookie_extractor.0.value_trimmed()+ }+ }}+}++impl<S> FromRequestParts<S> for RefreshTokenExtractor+where+ S: Send + Sync,+{+ type Rejection = StatusCode;- Err(MacroAuthError::NoRefreshTokenProvided)+ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ _state: &S,+ ) -> Result<Self, Self::Rejection> {+ let either: Either<RefreshTokenHeaderExtractor, RefreshTokenCookieExtractor> =+ parts.extract().await?;+ Ok(match either {+ Either::E1(l) => Self::Header(l),+ Either::E2(r) => Self::Cookie(r),+ })+ }}diff --git a/rust/cloud-storage/macro_middleware/Cargo.toml b/rust/cloud-storage/macro_middleware/Cargo.tomlindex a5390e4092..ddc5b156ff 100644--- a/rust/cloud-storage/macro_middleware/Cargo.toml+++ b/rust/cloud-storage/macro_middleware/Cargo.toml@@ -6,7 +6,7 @@ version = "0.1.0"[features]all = ["auth", "cloud_storage", "tracking", "user_permissions"]-auth = ["dep:macro_auth", "dep:url"]+auth = ["dep:decode_jwt", "dep:macro_auth", "dep:url"]cloud_storage = ["dep:macro_share_permissions","dep:macro_user_id",@@ -15,7 +15,7 @@ cloud_storage = ["macro_db_client",]default = ["all"]-local_auth = []+local_auth = ["decode_jwt/local_auth"]macro_db_client = ["dep:macro_db_client", "dep:sqlx"]tracking = ["dep:ip_extractor"]user_permissions = ["dep:macro_user_id", "dep:user_quota", "macro_db_client"]@@ -23,12 +23,14 @@ user_permissions = ["dep:macro_user_id", "dep:user_quota", "macro_db_client"][dependencies]anyhow = { workspace = true }axum = { workspace = true, features = ["macros"] }+axum-extra = { workspace = true }+decode_jwt = { path = "../decode_jwt", optional = true }http-body-util = { workspace = true }ip_extractor = { path = "../ip_extractor", optional = true }macro_auth = { path = "../macro_auth", optional = true }macro_db_client = { path = "../macro_db_client", optional = true }-macro_env_var = { path = "../macro_env_var" }macro_env = { path = "../macro_env" }+macro_env_var = { path = "../macro_env_var" }macro_share_permissions = { path = "../macro_share_permissions", optional = true }macro_user_id = { path = "../macro_user_id", optional = true }macro_uuid = { path = "../macro_uuid" }@@ -48,3 +50,7 @@ tracing = { workspace = true }url = { workspace = true, optional = true }user_quota = { path = "../user_quota", optional = true }uuid = { workspace = true }++[dev-dependencies]+serde_urlencoded = "0.7"+urlencoding = { workspace = true }diff --git a/rust/cloud-storage/macro_middleware/src/auth/attach_user.rs b/rust/cloud-storage/macro_middleware/src/auth/attach_user.rsindex f1cc8ae05f..cac337421e 100644--- a/rust/cloud-storage/macro_middleware/src/auth/attach_user.rs+++ b/rust/cloud-storage/macro_middleware/src/auth/attach_user.rs@@ -9,6 +9,7 @@ use axum::{};use macro_auth::{error::MacroAuthError,+ headers::AccessTokenExtractor,middleware::decode_jwt::{JwtToken, JwtValidationArgs},};@@ -17,6 +18,7 @@ use model::{response::ErrorResponse, user::UserContext};/// Attempts to decode the JWT and attach user to the request context/// If there is no JWT to decode, the user context remains emptypub async fn handler(+ access_token: Result<AccessTokenExtractor, StatusCode>,State(jwt_validation_args): State<JwtValidationArgs>, // used for macro-access-token validationmut req: Request,next: Next,@@ -46,10 +48,8 @@ pub async fn handler(tracing::trace!("macro-api-token found in query params");macro_api_token.to_string()} else {- let headers = req.headers();-- match macro_auth::headers::extract_access_token_from_request_headers(headers) {- Ok(access_token) => access_token,+ match access_token {+ Ok(access_token) => access_token.as_ref().to_string(),Err(e) => {tracing::trace!(error=?e, "unable to get macro access token");return Ok(next.run(req).await);diff --git a/rust/cloud-storage/macro_middleware/src/auth/decode_jwt.rs b/rust/cloud-storage/macro_middleware/src/auth/decode_jwt.rsindex 7a57a88c50..f9834d8e24 100644--- a/rust/cloud-storage/macro_middleware/src/auth/decode_jwt.rs+++ b/rust/cloud-storage/macro_middleware/src/auth/decode_jwt.rs@@ -1,129 +1,28 @@use axum::{- Json,- extract::{Request, State},+ extract::{Query, Request, State},http::StatusCode,middleware::Next,- response::{IntoResponse, Response},+ response::Response,};-use macro_auth::{- error::MacroAuthError,- middleware::decode_jwt::{JwtToken, JwtValidationArgs},-};-use model::{response::ErrorResponse, user::UserContext};-use std::collections::HashMap;--/// Stores information about the JWT, this is used for the logout in particular call-#[derive(Clone)]-pub struct JwtContext {- /// Macro access token The audience of the token- pub audience: String,- /// Macro access token The tenant id of the token- pub tid: String,-}+pub use decode_jwt::*;+use macro_auth::{headers::AccessTokenExtractor, middleware::decode_jwt::JwtValidationArgs};-/// Decodes the JWT and updates the UserContext with the user_id, fusion_user_id and organization_id.+/// Axum middleware that decodes the JWT and attaches the user context to the request.+////// If in your request the user requires to be authenticated for all use cases, you can use this-/// middleware.-/// Otherwise, you should be using the `attach_user` middleware.+/// middleware. Otherwise, you should be using the `attach_user` middleware.pub async fn handler(- jwt_validation_args: State<JwtValidationArgs>, // used for macro-access-token validation+ access_token: Result<AccessTokenExtractor, StatusCode>,+ jwt_validation_args: State<JwtValidationArgs>,+ Query(params): Query<Params>,mut req: Request,next: Next,-) -> Result<Response, Response> {- if cfg!(feature = "local_auth") {- req.extensions_mut().insert(UserContext {- user_id: std::env::var("LOCAL_USER_ID").unwrap_or("macro|[email protected]".to_string()),- fusion_user_id: std::env::var("LOCAL_FUSION_USER_ID").unwrap_or("set me!".to_string()),- organization_id: Some(- std::env::var("LOCAL_ORG_ID")- .unwrap_or("1".to_string())- .parse()- .unwrap(),- ),- permissions: None,- });- return Ok(next.run(req).await);- }-- let query_params: HashMap<String, String> = req- .uri()- .query()- .map(|q| {- url::form_urlencoded::parse(q.as_bytes())- .into_owned()- .collect()- })- .unwrap_or_default();-- let access_token = if let Some(macro_api_token) = query_params.get("macro-api-token") {- tracing::trace!("macro-api-token found in query params");- macro_api_token.to_string()- } else {- let headers = req.headers();-- match macro_auth::headers::extract_access_token_from_request_headers(headers) {- Ok(access_token) => access_token,- Err(e) => {- tracing::trace!(error=?e, "unable to get macro access token");- return Err((- StatusCode::UNAUTHORIZED,- Json(ErrorResponse {- message: "unauthorized".into(),- }),- )- .into_response());- }- }- };-- let jwt = macro_auth::middleware::decode_jwt::handler(&jwt_validation_args, &access_token)- .map_err(|e| match e {- MacroAuthError::JwtExpired => (- StatusCode::UNAUTHORIZED,- Json(ErrorResponse {- message: "jwt expired".into(),- }),- )- .into_response(),- _ => {- tracing::error!(error=?e, "unable to decode jwt");- (- StatusCode::UNAUTHORIZED,- Json(ErrorResponse {- message: "unauthorized".into(),- }),- )- .into_response()- }- })?;-- let (user_id, fusion_user_id, organization_id) = match jwt.clone() {- JwtToken::MacroAccessToken(token) => (- token.macro_user_id,- token.root_macro_id.unwrap_or(token.fusion_user_id),- token.macro_organization_id,- ),- JwtToken::MacroApiToken(token) => (- token.macro_user_id,- token.fusion_user_id,- token.macro_organization_id,- ),- };-- // Attach user to the UserContext and to the request- req.extensions_mut().insert(UserContext {- user_id,- fusion_user_id,- organization_id,- permissions: None,- });+) -> Result<Response, DecodeJwtError> {+ let decoded = DecodedJwt::new(access_token, params, &jwt_validation_args)?;- // We can only attach the jwt context if the token is a macro-access-token- if let JwtToken::MacroAccessToken(token) = jwt {- req.extensions_mut().insert(JwtContext {- audience: token.aud,- tid: token.tid,- });+ req.extensions_mut().insert(decoded.user_context);+ if let Some(jwt_context) = decoded.jwt_context {+ req.extensions_mut().insert(jwt_context);}Ok(next.run(req).await)diff --git a/rust/cloud-storage/macro_service_urls/Cargo.toml b/rust/cloud-storage/macro_service_urls/Cargo.tomlnew file mode 100644index 0000000000..6e44d65565--- /dev/null+++ b/rust/cloud-storage/macro_service_urls/Cargo.toml@@ -0,0 +1,9 @@+[package]+edition = "2024"+name = "macro_service_urls"+publish = false+version = "0.1.0"++[dependencies]+macro_env = { path = "../macro_env" }+url = { workspace = true }diff --git a/rust/cloud-storage/macro_service_urls/src/lib.rs b/rust/cloud-storage/macro_service_urls/src/lib.rsnew file mode 100644index 0000000000..b97590789e--- /dev/null+++ b/rust/cloud-storage/macro_service_urls/src/lib.rs@@ -0,0 +1,150 @@+#![deny(missing_docs)]+//! Service URL resolution based on the current environment.++use macro_env::Environment;+use url::Url;++#[cfg(test)]+mod test;++/// Extension trait that provides service URLs based on the current environment.+pub trait EnvExtMacroServiceUrls {+ /// The main app URL.+ fn app(&self) -> Url;+ /// Authentication service URL.+ fn auth_service(&self) -> Url;+ /// PDF rendering service URL.+ fn pdf_service(&self) -> Url;+ /// Document storage service URL.+ fn document_storage_service(&self) -> Url;+ /// WebSocket service URL.+ fn websocket_service(&self) -> Url;+ /// Document cognition service URL.+ fn cognition_service(&self) -> Url;+ /// WebSocket connection gateway URL.+ fn connection_gateway(&self) -> Url;+ /// Notification service URL.+ fn notification_service(&self) -> Url;+ /// Static file service URL.+ fn static_file_service(&self) -> Url;+ /// Link unfurl service URL.+ fn unfurl_service(&self) -> Url;+ /// Contacts service URL.+ fn contacts_service(&self) -> Url;+ /// Email service URL.+ fn email_service(&self) -> Url;+ /// Image proxy service URL.+ fn image_proxy_service(&self) -> Url;+}++/// Helper to parse a static URL string. All URLs here are compile-time constants+/// so parsing can never fail.+fn url(s: &str) -> Url {+ Url::parse(s).unwrap()+}++impl EnvExtMacroServiceUrls for Environment {+ fn app(&self) -> Url {+ match self {+ Environment::Production => url("https://macro.com"),+ Environment::Develop => url("https://dev.macro.com"),+ Environment::Local => url("http://localhost:3000"),+ }+ }++ fn auth_service(&self) -> Url {+ match self {+ Environment::Production => url("https://auth-service.macro.com"),+ Environment::Develop => url("https://auth-service-dev.macro.com"),+ Environment::Local => url("http://localhost:8080"),+ }+ }++ fn pdf_service(&self) -> Url {+ match self {+ Environment::Production => url("https://pdf-service.macro.com"),+ Environment::Develop => url("https://pdf-service-dev.macro.com"),+ Environment::Local => url("http://localhost:4567"),+ }+ }++ fn document_storage_service(&self) -> Url {+ match self {+ Environment::Production => url("https://cloud-storage.macro.com"),+ Environment::Develop => url("https://cloud-storage-dev.macro.com"),+ Environment::Local => url("http://localhost:8086"),+ }+ }++ fn websocket_service(&self) -> Url {+ match self {+ Environment::Production => url("wss://services.macro.com"),+ Environment::Develop => url("wss://services-dev.macro.com"),+ Environment::Local => url("ws://localhost:6969"),+ }+ }++ fn cognition_service(&self) -> Url {+ match self {+ Environment::Production => url("https://document-cognition.macro.com"),+ Environment::Develop => url("https://document-cognition-dev.macro.com"),+ Environment::Local => url("http://localhost:8085"),+ }+ }++ fn connection_gateway(&self) -> Url {+ match self {+ Environment::Production => url("wss://connection-gateway.macro.com"),+ Environment::Develop => url("wss://connection-gateway-dev.macro.com"),+ Environment::Local => url("ws://localhost:8082"),+ }+ }++ fn notification_service(&self) -> Url {+ match self {+ Environment::Production => url("https://notifications.macro.com"),+ Environment::Develop => url("https://notifications-dev.macro.com"),+ Environment::Local => url("http://localhost:8089"),+ }+ }++ fn static_file_service(&self) -> Url {+ match self {+ Environment::Production => url("https://static-file-service.macro.com"),+ Environment::Develop => url("https://static-file-service-dev.macro.com"),+ Environment::Local => url("http://localhost:8100"),+ }+ }++ fn unfurl_service(&self) -> Url {+ match self {+ Environment::Production => url("https://unfurl-service.macro.com"),+ Environment::Develop => url("https://unfurl-service-dev.macro.com"),+ Environment::Local => url("http://localhost:8095"),+ }+ }++ fn contacts_service(&self) -> Url {+ match self {+ Environment::Production => url("https://contacts.macro.com"),+ Environment::Develop => url("https://contacts-dev.macro.com"),+ Environment::Local => url("http://localhost:8083"),+ }+ }++ fn email_service(&self) -> Url {+ match self {+ Environment::Production => url("https://email-service.macro.com"),+ Environment::Develop => url("https://email-service-dev.macro.com"),+ Environment::Local => url("http://localhost:8087"),+ }+ }++ fn image_proxy_service(&self) -> Url {+ match self {+ Environment::Production => url("https://image-proxy.macro.com"),+ Environment::Develop => url("https://image-proxy-dev.macro.com"),+ Environment::Local => url("http://localhost:8097"),+ }+ }+}diff --git a/rust/cloud-storage/macro_service_urls/src/test.rs b/rust/cloud-storage/macro_service_urls/src/test.rsnew file mode 100644index 0000000000..7d28195788--- /dev/null+++ b/rust/cloud-storage/macro_service_urls/src/test.rs@@ -0,0 +1,98 @@+use super::*;++const ENVS: [Environment; 3] = [+ Environment::Production,+ Environment::Develop,+ Environment::Local,+];++#[test]+fn app_parses() {+ for env in ENVS {+ let _ = env.app();+ }+}++#[test]+fn auth_service_parses() {+ for env in ENVS {+ let _ = env.auth_service();+ }+}++#[test]+fn pdf_service_parses() {+ for env in ENVS {+ let _ = env.pdf_service();+ }+}++#[test]+fn document_storage_service_parses() {+ for env in ENVS {+ let _ = env.document_storage_service();+ }+}++#[test]+fn websocket_service_parses() {+ for env in ENVS {+ let _ = env.websocket_service();+ }+}++#[test]+fn cognition_service_parses() {+ for env in ENVS {+ let _ = env.cognition_service();+ }+}++#[test]+fn connection_gateway_parses() {+ for env in ENVS {+ let _ = env.connection_gateway();+ }+}++#[test]+fn notification_service_parses() {+ for env in ENVS {+ let _ = env.notification_service();+ }+}++#[test]+fn static_file_service_parses() {+ for env in ENVS {+ let _ = env.static_file_service();+ }+}++#[test]+fn unfurl_service_parses() {+ for env in ENVS {+ let _ = env.unfurl_service();+ }+}++#[test]+fn contacts_service_parses() {+ for env in ENVS {+ let _ = env.contacts_service();+ }+}++#[test]+fn email_service_parses() {+ for env in ENVS {+ let _ = env.email_service();+ }+}++#[test]+fn image_proxy_service_parses() {+ for env in ENVS {+ let _ = env.image_proxy_service();+ }+}diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.tomlindex 0aabf9bce2..c0e77ab5c3 100644--- a/rust/cloud-storage/notification/Cargo.toml+++ b/rust/cloud-storage/notification/Cargo.toml@@ -29,11 +29,16 @@ 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_env = { path = "../macro_env" }+macro_service_urls = { path = "../macro_service_urls" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }model-entity = { path = "../model-entity" }@@ -57,10 +62,14 @@ strum = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true, features = ["time"] }tracing = { workspace = true }+url = { workspace = true }utoipa = { workspace = true, optional = true }uuid = { workspace = true }[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"] }+tower = { workspace = true }diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rsindex ac2782f299..6819fdad87 100644--- a/rust/cloud-storage/notification/src/domain/models.rs+++ b/rust/cloud-storage/notification/src/domain/models.rs@@ -10,6 +10,8 @@ pub mod queue_message;pub mod rate_limit;pub mod recipient;pub mod request;+/// Cryptographic URL signing and verification.+pub mod signing;use crate::domain::models::{apple::APNSPushNotification, queue_message::EmailContent};use chrono::{DateTime, Utc};diff --git a/rust/cloud-storage/notification/src/domain/models/signing.rs b/rust/cloud-storage/notification/src/domain/models/signing.rsnew file mode 100644index 0000000000..970ea2d9b2--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/models/signing.rs@@ -0,0 +1,79 @@+use hmac::{Hmac, Mac};+use sha2::Sha256;+use std::borrow::Cow;+use url::Url;++#[cfg(test)]+mod test;++/// The query parameter name used to store the HMAC signature.+const SIG_PARAM: &str = "sig";++/// A wrapper over url which is guaranteed to be a cryptographically signed url.+/// The signature exists as a query param under "sig".+pub struct SignedUrl(Url);++impl SignedUrl {+ /// Create a signed URL by computing an HMAC-SHA256 over the canonicalized+ /// URL string and appending the hex-encoded signature as the `sig` query parameter.+ pub fn new(u: Url, mac: Hmac<Sha256>) -> Self {+ let canonical = Self::canonicalize(&u);+ let sig = hex::encode(Self::compute_mac(&canonical, mac).into_bytes());+ let mut signed = canonical;+ signed.query_pairs_mut().append_pair(SIG_PARAM, &sig);+ Self(signed)+ }++ /// Canonicalize a URL by re-serializing its query pairs through+ /// `query_pairs()`/`extend_pairs()` so that both `new()` and `verify()`+ /// MAC the same byte representation.+ fn canonicalize(u: &Url) -> Url {+ let pairs: Vec<(Cow<'_, str>, Cow<'_, str>)> = u.query_pairs().collect();+ let mut canonical = u.clone();+ canonical+ .query_pairs_mut()+ .clear()+ .extend_pairs(pairs)+ .finish();+ canonical+ }++ fn compute_mac(u: &Url, mut mac: Hmac<Sha256>) -> hmac::digest::CtOutput<Hmac<Sha256>> {+ mac.update(u.as_str().as_bytes());+ mac.finalize()+ }++ /// Verify a URL that is expected to contain a `sig` query parameter.+ /// Returns `Some(SignedUrl)` if the signature is valid, `None` otherwise.+ pub fn verify(u: Url, mac: Hmac<Sha256>) -> Option<Self> {+ let (sig, others) = u+ .query_pairs()+ .partition::<Vec<(Cow<'_, str>, Cow<'_, str>)>, _>(|(k, _v)| k == SIG_PARAM);++ let [(_key, expected)] = sig.as_slice() else {+ return None;+ };++ // Reconstruct the URL without the sig param to compute the expected HMAC.+ let mut unsigned = u.clone();+ unsigned+ .query_pairs_mut()+ .clear()+ .extend_pairs(others)+ .finish();++ let expected_bytes = hex::decode(expected.as_ref()).ok()?;+ let mut verifier = mac;+ verifier.update(unsigned.as_str().as_bytes());+ verifier+ .verify_slice(&expected_bytes)+ .ok()+ .map(|()| Self(u))+ }+}++impl AsRef<Url> for SignedUrl {+ fn as_ref(&self) -> &Url {+ &self.0+ }+}diff --git a/rust/cloud-storage/notification/src/domain/models/signing/test.rs b/rust/cloud-storage/notification/src/domain/models/signing/test.rsnew file mode 100644index 0000000000..8323a0a517--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/models/signing/test.rs@@ -0,0 +1,47 @@+use super::*;+use hmac::{Hmac, Mac};+use sha2::Sha256;+use url::Url;++fn make_secret(key: &[u8]) -> Hmac<Sha256> {+ Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts any key size")+}++#[test]+fn sign_and_verify_roundtrip() {+ let secret = make_secret(b"test-secret");+ let url = Url::parse("https://example.com/path?foo=bar").unwrap();+ let signed = SignedUrl::new(url, secret.clone());++ let signed_url: &Url = signed.as_ref();+ assert!(signed_url.as_str().contains("sig="));+ assert!(SignedUrl::verify(signed_url.clone(), secret).is_some());+}++#[test]+fn verify_rejects_tampered_sig() {+ let secret = make_secret(b"test-secret");+ let url = Url::parse("https://example.com/path").unwrap();+ let signed = SignedUrl::new(url, secret.clone());++ let mut tampered: Url = signed.as_ref().clone();+ tampered.set_query(Some("sig=deadbeef"));+ assert!(SignedUrl::verify(tampered, secret).is_none());+}++#[test]+fn verify_rejects_wrong_secret() {+ let secret = make_secret(b"test-secret");+ let wrong = make_secret(b"wrong-secret");+ let url = Url::parse("https://example.com/path").unwrap();+ let signed = SignedUrl::new(url, secret);++ assert!(SignedUrl::verify(signed.as_ref().clone(), wrong).is_none());+}++#[test]+fn verify_returns_none_when_no_sig_param() {+ let secret = make_secret(b"test-secret");+ let url = Url::parse("https://example.com/path").unwrap();+ assert!(SignedUrl::verify(url, secret).is_none());+}diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex 595de4b186..e81e2329e6 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -295,9 +295,13 @@ pub trait NotificationEgress: Send + Sync + 'static {-> impl Future<Output = Vec<Result<DeliverySuccess, Report>>> + Send;/// Poll for ready digest batches, template them as emails, and send.- fn poll_email_digests<'a, T: NotificationExtEmail>(+ fn poll_email_digests<+ 'a,+ T: NotificationExtEmail,+ F: Fn(DigestBatch) -> Result<T, Report> + Send + Sync + 'static,+ >(&'a self,- f: fn(DigestBatch) -> Result<T, Report>,+ f: &'a F,) -> impl Future<Output = Result<ClaimResult<()>, Report>> + Send + 'a;}diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rsindex 0467e687e2..fb42cc0901 100644--- a/rust/cloud-storage/notification/src/domain/service/egress.rs+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs@@ -339,9 +339,13 @@ where}// #[tracing::instrument(err, skip(self))]- async fn poll_email_digests<T: NotificationExtEmail>(- &self,- f: fn(DigestBatch) -> Result<T, Report>,+ async fn poll_email_digests<+ 'a,+ T: NotificationExtEmail,+ F: Fn(DigestBatch) -> Result<T, Report> + Send + Sync + 'static,+ >(+ &'a self,+ f: &'a F,) -> Result<ClaimResult<()>, Report> {let batch =match tokio::time::timeout(DELIVERY_TIMEOUT, self.digest_batcher.claim_ready_digest())diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex 609e917f0f..a1f05daaec 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -1858,7 +1858,7 @@ async fn test_poll_email_digests_sends_email_for_ready_batch() {})}- service.poll_email_digests(digest_to_notif).await.unwrap();+ service.poll_email_digests(&digest_to_notif).await.unwrap();let published = queue.get_published();assert_eq!(published.len(), 1);@@ -1918,7 +1918,7 @@ async fn it_fails_to_send_to_non_macro_users() {}service- .poll_email_digests(digest_to_notif)+ .poll_email_digests(&digest_to_notif).await.unwrap_err();}@@ -1932,7 +1932,7 @@ async fn test_poll_email_digests_noop_when_empty() {}// MockDigestBatcher always returns Empty- service.poll_email_digests(digest_to_notif).await.unwrap();+ service.poll_email_digests(&digest_to_notif).await.unwrap();}// ============================================================================diff --git a/rust/cloud-storage/notification/src/inbound/http/device.rs b/rust/cloud-storage/notification/src/inbound/http/device.rsindex ee3372e30e..87000983f5 100644--- a/rust/cloud-storage/notification/src/inbound/http/device.rs+++ b/rust/cloud-storage/notification/src/inbound/http/device.rs@@ -5,8 +5,8 @@ use axum::{extract::State,routing::{delete, post},};+use decode_jwt::DecodedJwt;use model_error_response::ErrorResponse;-use model_user::axum_extractor::MacroUserExtractor;use reqwest::StatusCode;use crate::domain::models::device::DeviceRequest;@@ -21,15 +21,15 @@ pub fn device_router<S: NotificationReader>() -> Router<NotificationRouterState<}/// Register a device for push notifications.-#[tracing::instrument(skip(state, macro_user, req), fields(user_id=?macro_user.macro_user_id))]+#[tracing::instrument(skip(state, macro_user_id, req))]async fn register_device<S: NotificationReader>(State(state): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ DecodedJwt { macro_user_id, .. }: DecodedJwt,Json(req): Json<DeviceRequest>,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {state.inner- .register_device(macro_user.macro_user_id, &req.token, &req.device_type)+ .register_device(macro_user_id, &req.token, &req.device_type).await.map_err(|e| {tracing::error!(error=?e, "failed to register device");@@ -48,7 +48,7 @@ async fn register_device<S: NotificationReader>(#[tracing::instrument(skip(state, _macro_user, req))]async fn unregister_device<S: NotificationReader>(State(state): State<NotificationRouterState<S>>,- _macro_user: MacroUserExtractor,+ _macro_user: DecodedJwt,Json(req): Json<DeviceRequest>,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {statediff --git a/rust/cloud-storage/notification/src/inbound/http/mod.rs b/rust/cloud-storage/notification/src/inbound/http/mod.rsindex fe6099124b..6bd4816b08 100644--- a/rust/cloud-storage/notification/src/inbound/http/mod.rs+++ b/rust/cloud-storage/notification/src/inbound/http/mod.rs@@ -1,18 +1,25 @@//! This module exposes the http adapter for inbound http requests via an axum router+#[cfg(test)]+mod test;+pub mod device;+pub mod preferences;use axum::{Json, Router,- extract::{Path, Query, State},- routing::{delete, patch},+ 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 model_error_response::ErrorResponse;-use model_user::axum_extractor::MacroUserExtractor;use models_pagination::{CreatedAt, CursorOptionExt, CursorWithValAndFilter};use reqwest::StatusCode;use serde::{Deserialize, Serialize, de::DeserializeOwned};-use std::sync::Arc;+use sha2::Sha256;+use std::{collections::HashSet, sync::Arc};use utoipa::ToSchema;use uuid::Uuid;@@ -44,21 +51,44 @@ pub struct NotificationIdPath {pub struct NotificationRouterState<S> {/// 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,+}++impl<S> FromRef<NotificationRouterState<S>> for JwtValidationArgs {+ fn from_ref(input: &NotificationRouterState<S>) -> Self {+ input.jwt_args.clone()+ }}impl<S> Clone for NotificationRouterState<S> {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(),}}}impl<S: NotificationReader> NotificationRouterState<S> {/// create a new instance of self- pub fn new(val: S) -> Self {+ pub fn new(+ val: S,+ blockable_notification_typenames: &'static HashSet<&'static str>,+ hmac_signing_key: Hmac<Sha256>,+ jwt_args: JwtValidationArgs,+ ) -> Self {NotificationRouterState {inner: Arc::new(val),+ blockable_notification_typenames,+ hmac_signing_key,+ jwt_args,}}}@@ -66,14 +96,28 @@ impl<S: NotificationReader> NotificationRouterState<S> {/// construct the routerpub fn router<S: NotificationReader, T: Serialize + DeserializeOwned + Send + 'static>()-> Router<NotificationRouterState<S>> {- 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)),- )+ 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(+ "/preferences",+ get(preferences::get_notification_type_preferences),+ )+ .route(+ "/preferences/{notification_event_type}/disable",+ put(preferences::disable_notification_type)+ .get(preferences::presigned_disable_notification_type),+ )+ .route(+ "/preferences/{notification_event_type}/enable",+ put(preferences::enable_notification_type),+ )}/// the params for pagination@@ -98,14 +142,14 @@ pub async fn list_user_notifications<T: Serialize + DeserializeOwned + Send,>(service: &NotificationRouterState<S>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Query(Params { limit }): Query<Params>,cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {let query = cursor.into_query(CreatedAt, ());let result = service.inner- .get_user_notifications::<T>(macro_user.macro_user_id, limit, query)+ .get_user_notifications::<T>(decoded_jwt.macro_user_id, limit, query).await.map_err(|e| {tracing::error!(error=?e, "failed to get user notifications");@@ -153,7 +197,7 @@ pub async fn bulk_get_by_event_item_ids<T: Serialize + DeserializeOwned + Send,>(State(service): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Query(Params { limit }): Query<Params>,cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,Json(req): Json<BulkGetByEventItemIdsRequest>,@@ -161,7 +205,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: macro_user.macro_user_id,+ user_id: decoded_jwt.macro_user_id,event_item_ids: &req.event_item_ids,limit,cursor: cursor.into_query(CreatedAt, ()),@@ -206,10 +250,10 @@ pub struct NotificationBulkRequest {)]pub async fn bulk_mark_seen<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Json(req): Json<NotificationBulkRequest>,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {- bulk_update(&service, ¯o_user, &req, NotificationStatus::Seen).await+ bulk_update(&service, &decoded_jwt, &req, NotificationStatus::Seen).await}/// Mark notifications as done.@@ -227,10 +271,10 @@ pub async fn bulk_mark_seen<S: NotificationReader>()]pub async fn bulk_mark_done<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Json(req): Json<NotificationBulkRequest>,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {- bulk_update(&service, ¯o_user, &req, NotificationStatus::Done(true)).await+ bulk_update(&service, &decoded_jwt, &req, NotificationStatus::Done(true)).await}/// Mark notifications as not done.@@ -248,22 +292,28 @@ pub async fn bulk_mark_done<S: NotificationReader>()]pub async fn bulk_mark_undone<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Json(req): Json<NotificationBulkRequest>,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {- bulk_update(&service, ¯o_user, &req, NotificationStatus::Done(false)).await+ bulk_update(+ &service,+ &decoded_jwt,+ &req,+ NotificationStatus::Done(false),+ )+ .await}async fn bulk_update<S: NotificationReader>(service: &NotificationRouterState<S>,- macro_user: &MacroUserExtractor,+ decoded_jwt: &DecodedJwt,req: &NotificationBulkRequest,status: NotificationStatus,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {service.inner.update_notifications(UpdateNotificationsRequest {- user_id: macro_user.macro_user_id.clone(),+ user_id: decoded_jwt.macro_user_id.clone(),notification_ids: &req.notification_ids,status,})@@ -300,7 +350,7 @@ async fn bulk_update<S: NotificationReader>()]pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + DeserializeOwned + Send>(State(service): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Path(EventItemIdPath { event_item_id }): Path<EventItemIdPath>,Query(Params { limit }): Query<Params>,cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,@@ -308,7 +358,7 @@ pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + Deseriallet result = service.inner.get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {- user_id: macro_user.macro_user_id,+ user_id: decoded_jwt.macro_user_id,event_item_ids: &[event_item_id],limit,cursor: cursor.into_query(CreatedAt, ()),@@ -351,12 +401,12 @@ pub async fn get_notification_by_id<T: Serialize + DeserializeOwned + Send,>(State(service): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,) -> Result<Json<UserNotificationRow<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {let result = service.inner- .get_user_notification_by_id::<T>(macro_user.macro_user_id, notification_id)+ .get_user_notification_by_id::<T>(decoded_jwt.macro_user_id, notification_id).await.map_err(|e| {tracing::error!(error=?e, "failed to get user notification by id");@@ -397,12 +447,12 @@ pub async fn get_notification_by_id<)]pub async fn delete_notification<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {service.inner- .delete_user_notification(macro_user.macro_user_id, notification_id)+ .delete_user_notification(decoded_jwt.macro_user_id, notification_id).await.map_err(|e| {tracing::error!(error=?e, "failed to delete user notification");@@ -432,12 +482,12 @@ pub async fn delete_notification<S: NotificationReader>()]pub async fn bulk_delete_notifications<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,- macro_user: MacroUserExtractor,+ decoded_jwt: DecodedJwt,Json(req): Json<NotificationBulkRequest>,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {service.inner- .bulk_delete_user_notifications(macro_user.macro_user_id, &req.notification_ids)+ .bulk_delete_user_notifications(decoded_jwt.macro_user_id, &req.notification_ids).await.map_err(|e| {tracing::error!(error=?e, "failed to delete user notifications");diff --git a/rust/cloud-storage/notification/src/inbound/http/preferences.rs b/rust/cloud-storage/notification/src/inbound/http/preferences.rsnew file mode 100644index 0000000000..80b9706133--- /dev/null+++ b/rust/cloud-storage/notification/src/inbound/http/preferences.rs@@ -0,0 +1,227 @@+//! HTTP handlers for notification type preferences (enable/disable).++use axum::{+ Json,+ extract::{OriginalUri, Path, Query, State},+ http::{StatusCode, uri::PathAndQuery},+ response::Html,+};+use cowlike::CowLike;+use decode_jwt::DecodedJwt;+use macro_env::Environment;+use macro_service_urls::EnvExtMacroServiceUrls;+use macro_user_id::user_id::MacroUserIdStr;+use model_error_response::ErrorResponse;+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++use crate::domain::{models::signing::SignedUrl, service::NotificationReader};++use super::NotificationRouterState;++/// Path parameter for a notification event type.+#[derive(Deserialize)]+pub struct NotificationEventTypePath {+ /// The notification event type (e.g. "channel_message_send").+ pub notification_event_type: String,+}++/// Response for listing disabled notification types.+#[derive(Debug, Serialize, ToSchema)]+pub struct GetNotificationTypePreferencesResponse {+ /// The notification types that the user has disabled.+ pub disabled_types: Vec<String>,+}++/// Get the notification types that the user has disabled.+#[utoipa::path(+ get,+ operation_id = "get_notification_type_preferences",+ path = "/v1/user_notifications/preferences",+ responses(+ (status = 200, body = GetNotificationTypePreferencesResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn get_notification_type_preferences<S: NotificationReader>(+ State(state): State<NotificationRouterState<S>>,+ decoded_jwt: DecodedJwt,+) -> Result<Json<GetNotificationTypePreferencesResponse>, (StatusCode, Json<ErrorResponse<'static>>)>+{+ let disabled = state+ .inner+ .get_disabled_notification_types(decoded_jwt.macro_user_id)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to get notification type preferences");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to get notification type preferences".into(),+ }),+ )+ })?;++ Ok(Json(GetNotificationTypePreferencesResponse {+ disabled_types: disabled+ .into_iter()+ .map(|d| d.notification_event_type)+ .collect(),+ }))+}++/// Disable a notification type for the authenticated user.+#[utoipa::path(+ put,+ operation_id = "disable_notification_type",+ path = "/v1/user_notifications/preferences/{notification_event_type}/disable",+ params(+ ("notification_event_type" = String, Path, description = "The notification event type to disable"),+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn disable_notification_type<S: NotificationReader>(+ State(state): State<NotificationRouterState<S>>,+ decoded_jwt: DecodedJwt,+ Path(NotificationEventTypePath {+ notification_event_type,+ }): Path<NotificationEventTypePath>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ disable_notification_type_inner(+ &state,+ decoded_jwt.macro_user_id.copied(),+ notification_event_type.as_str(),+ )+ .await+ .map(Json)+}++/// The query param value to extract the macro user id+#[derive(Deserialize)]+pub struct PresignedQueryParams {+ id: MacroUserIdStr<'static>,+}++/// 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>>,+ Path(NotificationEventTypePath {+ notification_event_type,+ }): Path<NotificationEventTypePath>,+ Query(params): Query<PresignedQueryParams>,+ original_uri: OriginalUri,+) -> Result<Html<String>, (StatusCode, Html<String>)> {+ let env = Environment::new_or_prod();+ let notification_service_url = env.notification_service();+ let to_verify = notification_service_url.join(+ original_uri+ .path_and_query()+ .map(PathAndQuery::as_str)+ .unwrap_or("/"),+ );++ let Ok(to_verify) = to_verify else {+ return Err((StatusCode::BAD_REQUEST, Html("Invalid link".to_string())));+ };++ let Some(_verified) = SignedUrl::verify(to_verify, state.hmac_signing_key.clone()) else {+ return Err((+ StatusCode::BAD_REQUEST,+ Html("Invalid signature".to_string()),+ ));+ };++ disable_notification_type_inner(&state, params.id, notification_event_type.as_str())+ .await+ .map(|()| {+ Html(format!(+ "You have been unsubscribed from {notification_event_type}"+ ))+ })+ .map_err(|(status, Json(ErrorResponse { message }))| (status, Html(message.to_string())))+}++/// internal implementation of the GET/PUT methods to DRY up the code+async fn disable_notification_type_inner<S: NotificationReader>(+ state: &NotificationRouterState<S>,+ calling_user: MacroUserIdStr<'_>,+ notification_event_type: &str,+) -> Result<(), (StatusCode, Json<ErrorResponse<'static>>)> {+ // make sure the notification to block is one that matches the list+ let true = state+ .blockable_notification_typenames+ .contains(notification_event_type)+ else {+ return Err((+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: format!(+ "Cannot block notification type {notification_event_type}. Expected one of {:?}",+ state.blockable_notification_typenames+ )+ .into(),+ }),+ ));+ };++ state+ .inner+ .disable_notification_type(calling_user, notification_event_type)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to disable notification type");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to disable notification type".into(),+ }),+ )+ })?;++ Ok(())+}++/// Re-enable a notification type for the authenticated user.+#[utoipa::path(+ put,+ operation_id = "enable_notification_type",+ path = "/v1/user_notifications/preferences/{notification_event_type}/enable",+ params(+ ("notification_event_type" = String, Path, description = "The notification event type to enable"),+ ),+ responses(+ (status = 200),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn enable_notification_type<S: NotificationReader>(+ State(state): State<NotificationRouterState<S>>,+ decoded_jwt: DecodedJwt,+ Path(NotificationEventTypePath {+ notification_event_type,+ }): Path<NotificationEventTypePath>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ state+ .inner+ .enable_notification_type(decoded_jwt.macro_user_id, ¬ification_event_type)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to enable notification type");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to enable notification type".into(),+ }),+ )+ })?;++ Ok(Json(()))+}diff --git a/rust/cloud-storage/notification/src/inbound/http/test.rs b/rust/cloud-storage/notification/src/inbound/http/test.rsnew file mode 100644index 0000000000..2879637b24--- /dev/null+++ b/rust/cloud-storage/notification/src/inbound/http/test.rs@@ -0,0 +1,622 @@+use std::collections::HashSet;++use axum::{Router, http::Request};+use hmac::{Hmac, Mac};+use http_body_util::BodyExt;+use macro_auth::middleware::decode_jwt::JwtValidationArgs;+use macro_user_id::user_id::MacroUserIdStr;+use models_pagination::{CreatedAt, Paginated, Query};+use reqwest::StatusCode;+use rootcause::Report;+use serde::de::DeserializeOwned;+use sha2::Sha256;+use tower::util::ServiceExt;+use uuid::Uuid;++use crate::domain::{+ models::{+ DisabledNotificationType, UserNotificationRow,+ device::DeviceType,+ request::{GetNotificationsByEventItemIdsRequest, UpdateNotificationsRequest},+ signing::SignedUrl,+ },+ service::NotificationReader,+};++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;++impl NotificationReader for UnreachableService {+ fn update_notifications(+ &self,+ _req: UpdateNotificationsRequest,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!("should not be called") }+ }++ fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _limit: Option<u32>,+ _cursor: Query<Uuid, CreatedAt, ()>,+ ) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send+ {+ async { unreachable!("should not be called") }+ }++ fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ _req: GetNotificationsByEventItemIdsRequest<'_>,+ ) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send+ {+ async { unreachable!("should not be called") }+ }++ fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _notification_id: Uuid,+ ) -> impl Future<Output = Result<Option<UserNotificationRow<T>>, Report>> + Send {+ async { unreachable!("should not be called") }+ }++ fn delete_user_notification(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _notification_id: Uuid,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!("should not be called") }+ }++ fn bulk_delete_user_notifications(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _notification_ids: &[Uuid],+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!("should not be called") }+ }++ fn register_device(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _device_token: &str,+ _device_type: &DeviceType,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!("should not be called") }+ }++ fn unregister_device(+ &self,+ _device_token: &str,+ _device_type: &DeviceType,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!("should not be called") }+ }++ fn get_disabled_notification_types(+ &self,+ _user_id: MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<DisabledNotificationType>, Report>> + Send {+ async { unreachable!("should not be called") }+ }++ fn disable_notification_type(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _type_name: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!("should not be called") }+ }++ fn enable_notification_type(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _type_name: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!("should not be called") }+ }+}++static BLOCKABLE: std::sync::LazyLock<HashSet<&'static str>> =+ std::sync::LazyLock::new(|| HashSet::from(["test_type"]));++fn test_router() -> Router {+ let hmac_key = Hmac::<Sha256>::new_from_slice(b"test-key").unwrap();+ let state = NotificationRouterState::new(+ UnreachableService,+ &BLOCKABLE,+ hmac_key,+ JwtValidationArgs::new_testing(),+ );++ let device_router = super::device::device_router::<UnreachableService>();+ Router::new()+ .nest(+ "/user_notifications",+ super::router::<UnreachableService, serde_json::Value>(),+ )+ .nest("/device", device_router)+ .with_state(state)+}++/// 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+ };+ let req = builder+ .body(axum::body::Body::from(body.unwrap_or_default().to_string()))+ .unwrap();+ router.clone().oneshot(req).await.unwrap().status()+}++/// Send a request with an invalid bearer token and return the status code.+async fn status_with_bad_token(+ router: &Router,+ method: &str,+ 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()+}++// -- No token tests ---------------------------------------------------------++#[tokio::test]+async fn no_token_bulk_mark_seen() {+ let router = test_router();+ let body = r#"{"notification_ids":[]}"#;+ assert_eq!(+ status(+ &router,+ "PATCH",+ "/user_notifications/bulk/seen",+ Some(body)+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn no_token_bulk_mark_done() {+ let router = test_router();+ let body = r#"{"notification_ids":[]}"#;+ assert_eq!(+ status(+ &router,+ "PATCH",+ "/user_notifications/bulk/done",+ Some(body)+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn no_token_bulk_mark_undone() {+ let router = test_router();+ let body = r#"{"notification_ids":[]}"#;+ assert_eq!(+ status(+ &router,+ "PATCH",+ "/user_notifications/bulk/undone",+ Some(body)+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn no_token_bulk_delete() {+ let router = test_router();+ let body = r#"{"notification_ids":[]}"#;+ assert_eq!(+ status(&router, "DELETE", "/user_notifications/bulk", Some(body)).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn no_token_get_preferences() {+ let router = test_router();+ assert_eq!(+ status(&router, "GET", "/user_notifications/preferences", None).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn no_token_disable_preference() {+ let router = test_router();+ assert_eq!(+ status(+ &router,+ "PUT",+ "/user_notifications/preferences/test_type/disable",+ None+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn no_token_enable_preference() {+ let router = test_router();+ assert_eq!(+ status(+ &router,+ "PUT",+ "/user_notifications/preferences/test_type/enable",+ None+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn no_token_register_device() {+ let router = test_router();+ let body = r#"{"token":"tok","device_type":"Ios"}"#;+ assert_eq!(+ status(&router, "POST", "/device/register", Some(body)).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn no_token_unregister_device() {+ let router = test_router();+ let body = r#"{"token":"tok","device_type":"Ios"}"#;+ assert_eq!(+ status(&router, "DELETE", "/device/unregister", Some(body)).await,+ StatusCode::UNAUTHORIZED+ );+}++// -- Invalid token tests ----------------------------------------------------++#[tokio::test]+async fn invalid_token_bulk_mark_seen() {+ let router = test_router();+ let body = r#"{"notification_ids":[]}"#;+ assert_eq!(+ status_with_bad_token(+ &router,+ "PATCH",+ "/user_notifications/bulk/seen",+ Some(body)+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn invalid_token_bulk_mark_done() {+ let router = test_router();+ let body = r#"{"notification_ids":[]}"#;+ assert_eq!(+ status_with_bad_token(+ &router,+ "PATCH",+ "/user_notifications/bulk/done",+ Some(body)+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn invalid_token_bulk_mark_undone() {+ let router = test_router();+ let body = r#"{"notification_ids":[]}"#;+ assert_eq!(+ status_with_bad_token(+ &router,+ "PATCH",+ "/user_notifications/bulk/undone",+ Some(body)+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn invalid_token_bulk_delete() {+ let router = test_router();+ let body = r#"{"notification_ids":[]}"#;+ assert_eq!(+ status_with_bad_token(&router, "DELETE", "/user_notifications/bulk", Some(body)).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn invalid_token_get_preferences() {+ let router = test_router();+ assert_eq!(+ status_with_bad_token(&router, "GET", "/user_notifications/preferences", None).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn invalid_token_disable_preference() {+ let router = test_router();+ assert_eq!(+ status_with_bad_token(+ &router,+ "PUT",+ "/user_notifications/preferences/test_type/disable",+ None+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn invalid_token_enable_preference() {+ let router = test_router();+ assert_eq!(+ status_with_bad_token(+ &router,+ "PUT",+ "/user_notifications/preferences/test_type/enable",+ None+ )+ .await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn invalid_token_register_device() {+ let router = test_router();+ let body = r#"{"token":"tok","device_type":"Ios"}"#;+ assert_eq!(+ status_with_bad_token(&router, "POST", "/device/register", Some(body)).await,+ StatusCode::UNAUTHORIZED+ );+}++#[tokio::test]+async fn invalid_token_unregister_device() {+ let router = test_router();+ let body = r#"{"token":"tok","device_type":"Ios"}"#;+ assert_eq!(+ status_with_bad_token(&router, "DELETE", "/device/unregister", Some(body)).await,+ StatusCode::UNAUTHORIZED+ );+}++// -- Presigned disable preference tests -------------------------------------++/// A mock `NotificationReader` that returns `Ok(())` for `disable_notification_type`+/// and panics on everything else.+struct PresignedTestService;++impl NotificationReader for PresignedTestService {+ fn update_notifications(+ &self,+ _req: UpdateNotificationsRequest,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!() }+ }++ fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _limit: Option<u32>,+ _cursor: Query<Uuid, CreatedAt, ()>,+ ) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send+ {+ async { unreachable!() }+ }++ fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ _req: GetNotificationsByEventItemIdsRequest<'_>,+ ) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send+ {+ async { unreachable!() }+ }++ fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _notification_id: Uuid,+ ) -> impl Future<Output = Result<Option<UserNotificationRow<T>>, Report>> + Send {+ async { unreachable!() }+ }++ fn delete_user_notification(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _notification_id: Uuid,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!() }+ }++ fn bulk_delete_user_notifications(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _notification_ids: &[Uuid],+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!() }+ }++ fn register_device(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _device_token: &str,+ _device_type: &DeviceType,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!() }+ }++ fn unregister_device(+ &self,+ _device_token: &str,+ _device_type: &DeviceType,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!() }+ }++ fn get_disabled_notification_types(+ &self,+ _user_id: MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<DisabledNotificationType>, Report>> + Send {+ async { unreachable!() }+ }++ fn disable_notification_type(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _type_name: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { Ok(()) }+ }++ fn enable_notification_type(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _type_name: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ async { unreachable!() }+ }+}++const HMAC_KEY: &[u8] = b"test-key";++/// The base URL that `Environment::new_or_prod()` (Production) resolves to.+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 state = NotificationRouterState::new(+ PresignedTestService,+ &BLOCKABLE,+ hmac_key,+ JwtValidationArgs::new_testing(),+ );++ Router::new()+ .nest(+ "/user_notifications",+ super::router::<PresignedTestService, serde_json::Value>(),+ )+ .with_state(state)+}++/// Build a presigned disable URL path+query for use as a request URI.+///+/// Signs the full absolute URL (`https://notifications.macro.com/...`) and+/// returns only the path+query portion (e.g. `/user_notifications/preferences/...?id=...&sig=...`).+fn signed_disable_uri(notification_type: &str, user_id: &str) -> String {+ let hmac_key = Hmac::<Sha256>::new_from_slice(HMAC_KEY).unwrap();+ let mut unsigned = url::Url::parse(&format!(+ "{NOTIFICATION_BASE_URL}/user_notifications/preferences/{notification_type}/disable"+ ))+ .unwrap();+ // Use query_pairs_mut so the encoding matches what SignedUrl::verify expects+ // (application/x-www-form-urlencoded round-trip).+ unsigned.query_pairs_mut().append_pair("id", user_id);+ let signed = SignedUrl::new(unsigned, hmac_key);+ let signed_url = signed.as_ref();+ // Return path + query for use as request URI+ format!("{}?{}", signed_url.path(), signed_url.query().unwrap())+}++#[tokio::test]+async fn presigned_disable_succeeds_without_jwt() {+ let router = presigned_router();+ let uri = signed_disable_uri("test_type", "macro|[email protected]");++ let req = Request::builder()+ .uri(&uri)+ .method("GET")+ .body(axum::body::Body::empty())+ .unwrap();+ let resp = router.oneshot(req).await.unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+ let body = resp.into_body().collect().await.unwrap().to_bytes();+ let text = String::from_utf8_lossy(&body);+ assert!(+ text.contains("unsubscribed"),+ "expected success HTML, got: {text}"+ );+}++#[tokio::test]+async fn presigned_disable_succeeds_with_valid_hmac() {+ let router = presigned_router();+ let uri = signed_disable_uri("test_type", "macro|[email protected]");++ let resp = router+ .oneshot(+ Request::builder()+ .uri(&uri)+ .method("GET")+ .body(axum::body::Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+}++#[tokio::test]+async fn presigned_disable_fails_with_invalid_hmac() {+ let router = presigned_router();+ // Construct a URI with a bogus signature+ let uri = "/user_notifications/preferences/test_type/disable\+ ?id=macro|[email protected]&sig=0000000000000000000000000000000000000000000000000000000000000000";++ let resp = router+ .oneshot(+ Request::builder()+ .uri(uri)+ .method("GET")+ .body(axum::body::Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ let body = resp.into_body().collect().await.unwrap().to_bytes();+ let text = String::from_utf8_lossy(&body);+ assert!(+ text.contains("Invalid signature"),+ "expected rejection HTML, got: {text}"+ );+}diff --git a/rust/cloud-storage/notification/src/inbound/worker.rs b/rust/cloud-storage/notification/src/inbound/worker.rsindex 9163a0dee9..013fb8034e 100644--- a/rust/cloud-storage/notification/src/inbound/worker.rs+++ b/rust/cloud-storage/notification/src/inbound/worker.rs@@ -71,12 +71,15 @@ where/// runs the digest worker forever which will pick digest batch messages out of redis/// template them into emails via the templater fn f/// then place the formatted messages into the queue to be delievered- pub async fn run_digests<T: NotificationExtEmail>(+ pub async fn run_digests<+ T: NotificationExtEmail,+ F: Fn(DigestBatch) -> Result<T, Report> + Send + Sync + 'static,+ >(&self,- f: fn(DigestBatch) -> Result<T, Report>,+ f: F,) -> ! {loop {- let sleep_duration = match self.service.poll_email_digests(f).await {+ let sleep_duration = match self.service.poll_email_digests(&f).await {Ok(ClaimResult::Empty) => Duration::from_secs(5),Ok(ClaimResult::Wait(duration)) => duration,Ok(ClaimResult::Ready(())) => Duration::default(),diff --git a/rust/cloud-storage/notification_sandbox/Cargo.toml b/rust/cloud-storage/notification_sandbox/Cargo.tomlindex 725e07357f..7af85d0a83 100644--- a/rust/cloud-storage/notification_sandbox/Cargo.toml+++ b/rust/cloud-storage/notification_sandbox/Cargo.toml@@ -10,8 +10,10 @@ aws-sdk-sns = { workspace = true }chrono = { workspace = true }either = { workspace = true }email_formatting = { path = "../email_formatting" }+hmac = { workspace = true }inquire = { workspace = true }macro_aws_config = { path = "../macro_aws_config" }+macro_env = { path = "../macro_env" }macro_user_id = { path = "../macro_user_id" }model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }@@ -26,6 +28,7 @@ redis = { workspace = true, features = [rootcause = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }+sha2 = { workspace = true }sqlx = { workspace = true }tokio = { workspace = true, features = ["macros",diff --git a/rust/cloud-storage/notification_sandbox/src/main.rs b/rust/cloud-storage/notification_sandbox/src/main.rsindex 8f644a50c4..72b90a0fcb 100644--- a/rust/cloud-storage/notification_sandbox/src/main.rs+++ b/rust/cloud-storage/notification_sandbox/src/main.rs@@ -7,6 +7,8 @@ use std::sync::{Arc, Mutex};use std::time::Duration;use email_formatting::EmailDigestNotification;+use hmac::{Hmac, Mac};+use macro_env::Environment;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;@@ -371,12 +373,20 @@ async fn poll_email_digests(egress: &impl NotificationEgress) -> Result<(), Repofn digest_to_sandbox(batch: notification::domain::models::email_notification_digest::ports::DigestBatch,) -> Result<SandboxNotification, Report> {+ let secret = std::env::var("URL_SIGNING_HMAC")+ .unwrap_or_else(|_| "sandbox-default-hmac-secret".to_string());+ let hmac_key = Hmac::<sha2::Sha256>::new_from_slice(secret.as_bytes())+ .expect("HMAC accepts any key size");Ok(SandboxNotification {- inner: EmailDigestNotification::new_from_digest_batch(batch)?,+ inner: EmailDigestNotification::new_from_digest_batch(+ batch,+ Environment::Local,+ hmac_key,+ )?,})}- let res = egress.poll_email_digests(digest_to_sandbox).await?;+ let res = egress.poll_email_digests(&digest_to_sandbox).await?;println!("{res:?}");Ok(())}diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.tomlindex f7bf1170ed..8655daf8ea 100644--- a/rust/cloud-storage/notification_service/Cargo.toml+++ b/rust/cloud-storage/notification_service/Cargo.toml@@ -26,10 +26,13 @@ aws-sdk-sns = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true }chrono = { workspace = true }+decode_jwt = { path = "../decode_jwt" }email_formatting = { path = "../email_formatting" }email_validator = { path = "../email_validator" }+hmac = { workspace = true }http-body-util = { workspace = true }itertools = { workspace = true }+last_online_tracker = { path = "../last_online_tracker" }macro_auth = { path = "../macro_auth" }macro_aws_config = { path = "../macro_aws_config" }macro_cors = { path = "../macro_cors" }@@ -47,21 +50,21 @@ model = { path = "../model" }model-entity = { path = "../model-entity" }model-error-response = { path = "../model-error-response" }model_file_type = { path = "../model_file_type" }-last_online_tracker = { path = "../last_online_tracker" }model_notifications = { path = "../model_notifications" }model_user = { path = "../model_user", features = ["axum"] }models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination", features = ["axum"] }notification = { path = "../notification", features = ["axum"] }-rate_limit = { path = "../rate_limit" }notification_db_client = { path = "../notification_db_client" }paste = { workspace = true }+rate_limit = { path = "../rate_limit" }redis = { workspace = true }regex = { workspace = true }secretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }serde_json = { workspace = true }ses_client = { path = "../ses_client" }+sha2 = { workspace = true }sns_client = { path = "../sns_client" }sqlx = { workspace = true }thiserror = { workspace = true }diff --git a/rust/cloud-storage/notification_service/src/api/mod.rs b/rust/cloud-storage/notification_service/src/api/mod.rsindex 41d981f688..9d3991f16b 100644--- a/rust/cloud-storage/notification_service/src/api/mod.rs+++ b/rust/cloud-storage/notification_service/src/api/mod.rs@@ -58,18 +58,13 @@ pub async fn setup_and_serve<S: ::notification::domain::service::NotificationRea}fn api_router<S: ::notification::domain::service::NotificationReader>(- state: ApiContext,+ _state: ApiContext,ingress_state: NotificationRouterState<S>,) -> Router<ApiContext> {let middleware = {- ServiceBuilder::new()- .layer(axum::middleware::from_fn_with_state(- state.jwt_args.clone(),- macro_middleware::auth::decode_jwt::handler,- ))- .layer(axum::middleware::from_fn(- macro_middleware::connection_drop_prevention_handler,- ))+ ServiceBuilder::new().layer(axum::middleware::from_fn(+ macro_middleware::connection_drop_prevention_handler,+ ))};let internal_router = Router::new()diff --git a/rust/cloud-storage/notification_service/src/api/swagger.rs b/rust/cloud-storage/notification_service/src/api/swagger.rsindex 67f2436de1..a75af79d36 100644--- a/rust/cloud-storage/notification_service/src/api/swagger.rs+++ b/rust/cloud-storage/notification_service/src/api/swagger.rs@@ -44,9 +44,9 @@ use crate::{notification_crate::inbound::http::bulk_mark_undone,/// /user_notifications/preferences- user_notification::get_notification_type_preferences,- user_notification::disable_notification_type,- user_notification::enable_notification_type,+ notification_crate::inbound::http::preferences::get_notification_type_preferences,+ notification_crate::inbound::http::preferences::disable_notification_type,+ notification_crate::inbound::http::preferences::enable_notification_type,/// /unsubscribeunsubscribe::get_unsubscribes::handler,@@ -87,7 +87,7 @@ use crate::{user_notification::ApiUserNotification,user_notification::GetAllUserNotificationsResponse,notification_crate::inbound::http::BulkGetByEventItemIdsRequest,- user_notification::GetNotificationTypePreferencesResponse,+ notification_crate::inbound::http::preferences::GetNotificationTypePreferencesResponse,),),tags(diff --git a/rust/cloud-storage/notification_service/src/api/unsubscribe/get_unsubscribes.rs b/rust/cloud-storage/notification_service/src/api/unsubscribe/get_unsubscribes.rsindex 8bb41566d3..64bb5b7959 100644--- a/rust/cloud-storage/notification_service/src/api/unsubscribe/get_unsubscribes.rs+++ b/rust/cloud-storage/notification_service/src/api/unsubscribe/get_unsubscribes.rs@@ -1,14 +1,14 @@use axum::{- Extension, Json,+ Json,extract::State,http::StatusCode,response::{IntoResponse, Response},};+use decode_jwt::DecodedJwt;use model::response::ErrorResponse;use model_notifications::UserUnsubscribe;use crate::api::context::ApiContext;-use model::user::UserContext;/// Gets the users unsubscribe items.#[utoipa::path(@@ -21,14 +21,14 @@ use model::user::UserContext;(status = 500, body=ErrorResponse),))]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]+#[tracing::instrument(skip(ctx, decoded_jwt))]pub async fn handler(State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,+ decoded_jwt: DecodedJwt,) -> Result<Response, Response> {let unsubscribe_items = notification_db_client::unsubscribe::get::get_user_unsubscribes(&ctx.db,- &user_context.user_id,+ &decoded_jwt.user_context.user_id,).await.map_err(|e| {diff --git a/rust/cloud-storage/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs b/rust/cloud-storage/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rsindex a97ea0e223..7ddf584082 100644--- a/rust/cloud-storage/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs+++ b/rust/cloud-storage/notification_service/src/api/unsubscribe/remove_unsubscribe_all.rs@@ -1,15 +1,14 @@use axum::{- Extension, Json,+ Json,extract::State,http::StatusCode,response::{IntoResponse, Response},};+use decode_jwt::DecodedJwt;use model::response::{EmptyResponse, ErrorResponse};use crate::api::context::ApiContext;-use model::user::UserContext;-/// Unmutes all notifications./// Existing notifications that were muted manually will remain muted.#[utoipa::path(@@ -22,14 +21,14 @@ use model::user::UserContext;(status = 500, body=ErrorResponse),))]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]+#[tracing::instrument(skip(ctx, decoded_jwt))]pub async fn handler(State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,+ decoded_jwt: DecodedJwt,) -> Result<Response, Response> {notification_db_client::user_mute_notification::remove_user_mute_notification(&ctx.db,- &user_context.user_id,+ &decoded_jwt.user_context.user_id,).await.map_err(|e| {diff --git a/rust/cloud-storage/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs b/rust/cloud-storage/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rsindex 9d905e609f..6308a9a2cb 100644--- a/rust/cloud-storage/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs+++ b/rust/cloud-storage/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs@@ -1,13 +1,13 @@use axum::{- Extension, Json,+ Json,extract::{Path, State},http::StatusCode,response::{IntoResponse, Response},};+use decode_jwt::DecodedJwt;use model::response::{EmptyResponse, ErrorResponse};use crate::api::context::ApiContext;-use model::user::UserContext;use super::unsubscribe_item::UnsubscribeItemPathParams;@@ -23,15 +23,15 @@ use super::unsubscribe_item::UnsubscribeItemPathParams;(status = 500, body=ErrorResponse),))]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]+#[tracing::instrument(skip(ctx, decoded_jwt))]pub async fn handler(State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,+ decoded_jwt: DecodedJwt,Path(UnsubscribeItemPathParams { item_type, item_id }): Path<UnsubscribeItemPathParams>,) -> Result<Response, Response> {notification_db_client::unsubscribe::item::remove_unsubscribed_item_user(&ctx.db,- &user_context.user_id,+ &decoded_jwt.user_context.user_id,&item_id,).awaitdiff --git a/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_all.rs b/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_all.rsindex b31f9d9e79..cc81046e5b 100644--- a/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_all.rs+++ b/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_all.rs@@ -1,15 +1,14 @@use axum::{- Extension, Json,+ Json,extract::State,http::StatusCode,response::{IntoResponse, Response},};+use decode_jwt::DecodedJwt;use model::response::{EmptyResponse, ErrorResponse};use crate::api::context::ApiContext;-use model::user::UserContext;-/// Unsubscribes user from all notifications.#[utoipa::path(post,@@ -21,14 +20,14 @@ use model::user::UserContext;(status = 500, body=ErrorResponse),))]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]+#[tracing::instrument(skip(ctx, decoded_jwt))]pub async fn handler(State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,+ decoded_jwt: DecodedJwt,) -> Result<Response, Response> {notification_db_client::user_mute_notification::upsert_user_mute_notification(&ctx.db,- &user_context.user_id,+ &decoded_jwt.user_context.user_id,).await.map_err(|e| {diff --git a/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_email.rs b/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_email.rsindex d658d4464b..9c1048a0a9 100644--- a/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_email.rs+++ b/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_email.rs@@ -1,13 +1,11 @@use axum::{- Extension, Json,+ Json,extract::State,http::StatusCode,response::{IntoResponse, Response},};-use model::{- response::{EmptyResponse, ErrorResponse},- user::UserContext,-};+use decode_jwt::DecodedJwt;+use model::response::{EmptyResponse, ErrorResponse};use crate::api::context::ApiContext;@@ -22,12 +20,12 @@ use crate::api::context::ApiContext;(status = 500, body=ErrorResponse),))]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]+#[tracing::instrument(skip(ctx, decoded_jwt))]pub async fn handler(State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,+ decoded_jwt: DecodedJwt,) -> Result<Response, Response> {- let email = user_context.user_id.replace("macro|", "");+ let email = decoded_jwt.user_context.user_id.replace("macro|", "");notification_db_client::unsubscribe::email::upsert_email_unsubscribe(&ctx.db, &email).await.map_err(|e| {diff --git a/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_item.rs b/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_item.rsindex 8788784795..b4a1a9cca6 100644--- a/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_item.rs+++ b/rust/cloud-storage/notification_service/src/api/unsubscribe/unsubscribe_item.rs@@ -1,17 +1,16 @@use axum::{- Extension, Json,+ Json,extract::{Path, State},http::StatusCode,response::{IntoResponse, Response},};+use decode_jwt::DecodedJwt;use model::response::{EmptyResponse, ErrorResponse};use serde::{Deserialize, Serialize};use utoipa::{IntoParams, ToSchema};use crate::api::context::ApiContext;-use model::user::UserContext;-#[derive(Deserialize, Serialize, ToSchema, IntoParams)]pub struct UnsubscribeItemPathParams {pub item_type: String,@@ -30,15 +29,15 @@ pub struct UnsubscribeItemPathParams {(status = 500, body=ErrorResponse),))]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]+#[tracing::instrument(skip(ctx, decoded_jwt))]pub async fn handler(State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,+ decoded_jwt: DecodedJwt,Path(UnsubscribeItemPathParams { item_type, item_id }): Path<UnsubscribeItemPathParams>,) -> Result<Response, Response> {notification_db_client::unsubscribe::item::upsert_unsubscribed_item_user(&ctx.db,- &user_context.user_id,+ &decoded_jwt.user_context.user_id,&item_id,&item_type,)diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rsindex 8815512ca9..8d84c0c3c7 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs@@ -1,11 +1,7 @@use std::{collections::HashSet, sync::LazyLock};use ::notification::domain::models::UserNotificationRow;-use axum::{- Json,- extract::{Path, State},- http::StatusCode,-};+use axum::extract::State;use chrono::{DateTime, Utc};use email_formatting::EmailDigestNotification;use itertools::{Either, Itertools};@@ -21,10 +17,27 @@ use notification::{domain::{models::Notification, service::NotificationReader},inbound::http::NotificationRouterState,};-use serde::{Deserialize, Serialize};+use serde::Serialize;use utoipa::ToSchema;use uuid::Uuid;+/// The types of notifications that are blockable+pub(crate) static BLOCKABLE_NOTIFICATIONS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {+ HashSet::from([+ EmailDigestNotification::TYPE_NAME,+ NewEmailMetadata::TYPE_NAME,+ AiResponseMetadata::TYPE_NAME,+ ChannelMessageSendMetadata::TYPE_NAME,+ ChannelMentionMetadata::TYPE_NAME,+ ChannelReplyMetadata::TYPE_NAME,+ DocumentMentionMetadata::TYPE_NAME,+ TaskAssignedMetadata::TYPE_NAME,+ MentionedInDocumentCommentMetadata::TYPE_NAME,+ RepliedToDocumentCommentThreadMetadata::TYPE_NAME,+ CommentedOnDocumentMetadata::TYPE_NAME,+ ])+});+#[cfg(test)]mod test;@@ -133,18 +146,6 @@ pub fn router<S: ::notification::domain::service::NotificationReader>()axum::routing::get(get_typed_notification_by_id::<S>).delete(::notification::inbound::http::delete_notification::<S>),)- .route(- "/preferences",- axum::routing::get(get_notification_type_preferences::<S>),- )- .route(- "/preferences/{notification_event_type}/disable",- axum::routing::put(disable_notification_type::<S>),- )- .route(- "/preferences/{notification_event_type}/enable",- axum::routing::put(enable_notification_type::<S>),- )}/// Wrapper handler that calls the inner generic list handler with `serde_json::Value`,@@ -168,7 +169,7 @@ 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>>,- macro_user: model_user::axum_extractor::MacroUserExtractor,+ decoded_jwt: decode_jwt::DecodedJwt,query: axum::extract::Query<::notification::inbound::http::Params>,cursor: Option<models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,@@ -180,11 +181,11 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificatiaxum::Json<model_error_response::ErrorResponse<'static>>,),> {- let user = macro_user.macro_user_id.clone();+ let user = decoded_jwt.macro_user_id.clone();let axum::Json(response) = ::notification::inbound::http::list_user_notifications::<S,serde_json::Value,- >(&state, macro_user, query, cursor)+ >(&state, decoded_jwt, query, cursor).await?;let (notifs, failed): (Vec<_>, Vec<_>) = response@@ -276,7 +277,7 @@ async fn bulk_get_typed_notifications_by_event_item_ids<S: ::notification::domain::service::NotificationReader,>(state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,- macro_user: model_user::axum_extractor::MacroUserExtractor,+ decoded_jwt: decode_jwt::DecodedJwt,query: axum::extract::Query<::notification::inbound::http::Params>,cursor: Option<models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,@@ -292,7 +293,7 @@ async fn bulk_get_typed_notifications_by_event_item_ids<let axum::Json(response) = ::notification::inbound::http::bulk_get_by_event_item_ids::<S,serde_json::Value,- >(state, macro_user, query, cursor, body)+ >(state, decoded_jwt, query, cursor, body).await?;let items = response@@ -331,7 +332,7 @@ 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>>,- macro_user: model_user::axum_extractor::MacroUserExtractor,+ decoded_jwt: decode_jwt::DecodedJwt,path: axum::extract::Path<::notification::inbound::http::EventItemIdPath>,query: axum::extract::Query<::notification::inbound::http::Params>,cursor: Option<@@ -347,7 +348,7 @@ async fn get_typed_by_event_item_id<S: ::notification::domain::service::Notificalet axum::Json(response) = ::notification::inbound::http::get_by_event_item_id::<S,serde_json::Value,- >(state, macro_user, path, query, cursor)+ >(state, decoded_jwt, path, query, cursor).await?;let items = response@@ -385,7 +386,7 @@ 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>>,- macro_user: model_user::axum_extractor::MacroUserExtractor,+ decoded_jwt: decode_jwt::DecodedJwt,path: axum::extract::Path<::notification::inbound::http::NotificationIdPath>,) -> Result<axum::Json<ApiUserNotification>,@@ -397,7 +398,7 @@ async fn get_typed_notification_by_id<S: ::notification::domain::service::Notifilet axum::Json(row) = ::notification::inbound::http::get_notification_by_id::<S,serde_json::Value,- >(state, macro_user, path)+ >(state, decoded_jwt, path).await?;let typed = to_typed_row(row).map_err(|e| {@@ -412,164 +413,3 @@ async fn get_typed_notification_by_id<S: ::notification::domain::service::NotifiOk(axum::Json(ApiUserNotification::from_notification(typed)))}--/// Path parameter for a notification event type.-#[derive(Deserialize)]-pub struct NotificationEventTypePath {- /// The notification event type (e.g. "channel_message_send").- pub notification_event_type: String,-}--/// Response for listing disabled notification types.-#[derive(Debug, Serialize, ToSchema)]-pub struct GetNotificationTypePreferencesResponse {- /// The notification types that the user has disabled.- pub disabled_types: Vec<String>,-}--/// Get the notification types that the user has disabled.-#[utoipa::path(- get,- operation_id = "get_notification_type_preferences",- path = "/v1/user_notifications/preferences",- responses(- (status = 200, body = GetNotificationTypePreferencesResponse),- (status = 401, body = ErrorResponse),- (status = 500, body = ErrorResponse),- )-)]-pub async fn get_notification_type_preferences<S: NotificationReader>(- State(state): State<NotificationRouterState<S>>,- macro_user: model_user::axum_extractor::MacroUserExtractor,-) -> Result<- axum::Json<GetNotificationTypePreferencesResponse>,- (axum::http::StatusCode, axum::Json<ErrorResponse<'static>>),-> {- let disabled = state- .inner- .get_disabled_notification_types(macro_user.macro_user_id)- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to get notification type preferences");- (- axum::http::StatusCode::INTERNAL_SERVER_ERROR,- axum::Json(ErrorResponse {- message: "failed to get notification type preferences".into(),- }),- )- })?;-- Ok(axum::Json(GetNotificationTypePreferencesResponse {- disabled_types: disabled- .into_iter()- .map(|d| d.notification_event_type)- .collect(),- }))-}--/// The types of notifications that are blockable-static BLOCKABLE_NOTIFICATIONS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {- HashSet::from([- EmailDigestNotification::TYPE_NAME,- NewEmailMetadata::TYPE_NAME,- AiResponseMetadata::TYPE_NAME,- ChannelMessageSendMetadata::TYPE_NAME,- ChannelMentionMetadata::TYPE_NAME,- ChannelReplyMetadata::TYPE_NAME,- DocumentMentionMetadata::TYPE_NAME,- TaskAssignedMetadata::TYPE_NAME,- MentionedInDocumentCommentMetadata::TYPE_NAME,- RepliedToDocumentCommentThreadMetadata::TYPE_NAME,- CommentedOnDocumentMetadata::TYPE_NAME,- ])-});--/// Disable a notification type for the authenticated user.-#[utoipa::path(- put,- operation_id = "disable_notification_type",- path = "/v1/user_notifications/preferences/{notification_event_type}/disable",- params(- ("notification_event_type" = String, Path, description = "The notification event type to disable"),- ),- responses(- (status = 200),- (status = 400, body = ErrorResponse),- (status = 401, body = ErrorResponse),- (status = 500, body = ErrorResponse),- )-)]-pub async fn disable_notification_type<S: NotificationReader>(- State(state): State<NotificationRouterState<S>>,- macro_user: model_user::axum_extractor::MacroUserExtractor,- Path(NotificationEventTypePath {- notification_event_type,- }): Path<NotificationEventTypePath>,-) -> Result<axum::Json<()>, (axum::http::StatusCode, axum::Json<ErrorResponse<'static>>)> {- // make sure the notification to block is one that matches the list- let true = BLOCKABLE_NOTIFICATIONS.contains(notification_event_type.as_str()) else {- return Err((- StatusCode::BAD_REQUEST,- Json(ErrorResponse {- message: format!(- "Cannot block notification type {notification_event_type}. Expected one of {:?}",- &*BLOCKABLE_NOTIFICATIONS- ).into(),- }),- ));- };-- state- .inner- .disable_notification_type(macro_user.macro_user_id, ¬ification_event_type)- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to disable notification type");- (- axum::http::StatusCode::INTERNAL_SERVER_ERROR,- axum::Json(ErrorResponse {- message: "failed to disable notification type".into(),- }),- )- })?;-- Ok(axum::Json(()))-}--/// Re-enable a notification type for the authenticated user.-#[utoipa::path(- put,- operation_id = "enable_notification_type",- path = "/v1/user_notifications/preferences/{notification_event_type}/enable",- params(- ("notification_event_type" = String, Path, description = "The notification event type to enable"),- ),- responses(- (status = 200),- (status = 401, body = ErrorResponse),- (status = 500, body = ErrorResponse),- )-)]-pub async fn enable_notification_type<S: NotificationReader>(- State(state): State<NotificationRouterState<S>>,- macro_user: model_user::axum_extractor::MacroUserExtractor,- Path(NotificationEventTypePath {- notification_event_type,- }): Path<NotificationEventTypePath>,-) -> Result<axum::Json<()>, (axum::http::StatusCode, axum::Json<ErrorResponse<'static>>)> {- state- .inner- .enable_notification_type(macro_user.macro_user_id, ¬ification_event_type)- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to enable notification type");- (- axum::http::StatusCode::INTERNAL_SERVER_ERROR,- axum::Json(ErrorResponse {- message: "failed to enable notification type".into(),- }),- )- })?;-- Ok(axum::Json(()))-}diff --git a/rust/cloud-storage/notification_service/src/config.rs b/rust/cloud-storage/notification_service/src/config.rsindex 81be840f71..233c355504 100644--- a/rust/cloud-storage/notification_service/src/config.rs+++ b/rust/cloud-storage/notification_service/src/config.rs@@ -16,6 +16,11 @@ env_var!(});+env_var!(+ #[derive(Clone)]+ pub(crate) struct UrlSigningHmac;+);+#[derive(Debug)]pub struct Config {/// The services base url including the scheme.diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rsindex 8e9526f6d2..487ae3425e 100644--- a/rust/cloud-storage/notification_service/src/main.rs+++ b/rust/cloud-storage/notification_service/src/main.rs@@ -1,5 +1,7 @@#![recursion_limit = "256"]use crate::api::context::ApiContext;+use crate::api::user_notification::BLOCKABLE_NOTIFICATIONS;+use ::notification::domain::models::email_notification_digest::ports::DigestBatch;use ::notification::domain::service::NotificationEgressService;use ::notification::inbound::worker::NotificationWorker;use ::notification::outbound::email::EmailAdapter;@@ -10,22 +12,21 @@ use ::rate_limit::RateLimitServiceImpl;use anyhow::Context;use config::Config;use email_formatting::EmailDigestNotification;+use hmac::{Hmac, Mac};use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_entrypoint::MacroEntrypoint;use macro_env::Environment;use macro_middleware::auth::internal_access::InternalApiSecretKey;use secretsmanager_client::SecretManager;+use sha2::Sha256;use sqlx::postgres::PgPoolOptions;use std::sync::Arc;mod api;mod config;-#[allow(dead_code)]mod env;mod model;mod notification;-#[allow(dead_code)]-mod templates;#[tokio::main]pub async fn main() -> anyhow::Result<()> {@@ -65,7 +66,15 @@ pub async fn main() -> anyhow::Result<()> {.get_maybe_secret_value(config.environment, InternalApiSecretKey::new()?).await?;+ let unsubscribe_hmac_secret = secretsmanager_client+ .get_maybe_secret_value(config.environment, config::UrlSigningHmac::new()?)+ .await?;+let vars = config::Vars::new()?;++ let hmac_key = Hmac::<Sha256>::new_from_slice(unsubscribe_hmac_secret.as_ref().as_bytes())+ .expect("HMAC accepts any key size");+let redis_client =redis::Client::open(vars.redis_uri.as_ref()).expect("failed to create redis client");@@ -144,7 +153,12 @@ pub async fn main() -> anyhow::Result<()> {sns_endpoint_manager,platform_config,);- let ingress_state = ::notification::inbound::http::NotificationRouterState::new(reader_service);+ let ingress_state = ::notification::inbound::http::NotificationRouterState::new(+ reader_service,+ &BLOCKABLE_NOTIFICATIONS,+ hmac_key.clone(),+ jwt_args.clone(),+ );// Set up egress worker for delivering notifications from the queuelet egress_repository =@@ -206,11 +220,15 @@ pub async fn main() -> anyhow::Result<()> {tracing::info!("starting notification egress worker");worker_clone.run_notifications().await});++ let env = config.environment;+ let digest_batch_to_email = move |batch: DigestBatch| {+ EmailDigestNotification::new_from_digest_batch(batch, env, hmac_key.clone())+ };+tokio::spawn(async move {tracing::info!("starting digest worker");- worker- .run_digests(EmailDigestNotification::new_from_digest_batch)- .await+ worker.run_digests(digest_batch_to_email).await});// Set up ingress worker for processing notification requests from the ingress queuediff --git a/rust/cloud-storage/notification_service/src/openapi.rs b/rust/cloud-storage/notification_service/src/openapi.rsindex 4f713cb65e..35b4628bcc 100644--- a/rust/cloud-storage/notification_service/src/openapi.rs+++ b/rust/cloud-storage/notification_service/src/openapi.rs@@ -5,7 +5,6 @@ mod config;mod env;mod model;mod notification;-mod templates;use utoipa::OpenApi;diff --git a/rust/cloud-storage/notification_service/src/templates/channel_invite/_channel_invite_basic_template.html b/rust/cloud-storage/notification_service/src/templates/channel_invite/_channel_invite_basic_template.htmldeleted file mode 100644index 0a7f7e2f0e..0000000000--- a/rust/cloud-storage/notification_service/src/templates/channel_invite/_channel_invite_basic_template.html+++ /dev/null@@ -1,230 +0,0 @@-<!DOCTYPE html>-<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml">--<head>- <meta charset="utf-8" />- <meta name="x-apple-disable-message-reformatting" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="format-detection" content="telephone=no, date=no, address=no, email=no" />- <meta name="color-scheme" content="light dark" />- <meta name="supported-color-schemes" content="light dark" />- <!--[if mso]>- <noscript>- <xml>- <o:OfficeDocumentSettings- xmlns:o="urn:schemas-microsoft-com:office:office"- >- <o:PixelsPerInch>96</o:PixelsPerInch>- </o:OfficeDocumentSettings>- </xml>- </noscript>- <style>- td,- th,- p,- a,- h1,- h2,- h3,- h4,- h5,- h6 {- font-family: "Segoe UI", sans-serif;- mso-line-height-rule: exactly;- }- </style>- <![endif]-->- <title>Macro Channel Invite</title>- <style>- /* Base styles */- body {- margin: 0;- padding: 0;- width: 100%;- background-color: #f8f9fa;- }-- /* Text styles */- .title {- font-size: 24px;- font-weight: 400;- color: #202124;- margin: 0;- padding: 0;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- .message {- font-size: 16px;- color: #202124;- line-height: 1.5;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Button styles */- .button {- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: "Google Sans", Roboto, Arial, sans-serif;- display: inline-block;- }-- /* Item name styles */- .item-name {- font-weight: 500;- color: #202124;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Footer styles */- .footer-text {- font-size: 12px;- color: #5f6368;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Email action link styles */- .email-link {- color: #1a73e8;- text-decoration: none;- }-- /* Logo styles */- .logo {- height: 32px;- }- </style>-</head>--<body style="- word-break: break-word;- -webkit-font-smoothing: antialiased;- margin: 0;- width: 100%;- background-color: #f8f9fa;- padding: 0;- ">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td align="center" style="padding: 24px 0">- <!-- Main Container -->- <table width="100%" style="max-width: 640px" cellpadding="0" cellspacing="0" border="0" role="presentation">- <!-- Header with Logo -->- <tr>- <td align="center" style="padding: 16px 0">- <img src="https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/logos/logo.png" alt="Macro"- class="logo" height="32" />- </td>- </tr>- <!-- Main Content Card -->- <tr>- <td style="padding: 0 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="- background-color: #ffffff;- border-radius: 8px;- border: 1px solid #dadce0;- " role="presentation">- <!-- Title -->- <tr>- <td style="padding: 5px"></td>- </tr>-- <!-- Message -->- <tr>- <td style="padding: 24px 24px 16px 24px">- <p class="message" style="- font-size: 16px;- color: #202124;- line-height: 1.5;- margin: 0;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- <strong style="text-decoration: none">{{INVITED_BY}}</strong>- {{INVITE_MESSAGE}}- </p>- </td>- </tr>-- <!-- Button -->- <tr>- <td style="padding: 0 24px 24px 24px; text-align: left">- <table cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td style="- background-color: #1a73e8;- border-radius: 24px;- ">- <a href="{{CHANNEL_URL}}" class="button" style="- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: 'Google Sans', Roboto, Arial,- sans-serif;- display: inline-block;- ">- Open- </a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Footer -->- <tr>- <td style="padding: 24px 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- Macro, Inc.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- You have received this email because {{INVITED_BY}} has- invited you to a channel in Macro.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- Questions? Email us at- <a href="mailto:[email protected]" class="email-link"- style="color: #1a73e8; text-decoration: none">[email protected]</a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>- </table>-</body>--</html>diff --git a/rust/cloud-storage/notification_service/src/templates/channel_invite/_channel_invite_message_template.html b/rust/cloud-storage/notification_service/src/templates/channel_invite/_channel_invite_message_template.htmldeleted file mode 100644index ed268eb839..0000000000--- a/rust/cloud-storage/notification_service/src/templates/channel_invite/_channel_invite_message_template.html+++ /dev/null@@ -1,258 +0,0 @@-<!DOCTYPE html>-<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml">--<head>- <meta charset="utf-8" />- <meta name="x-apple-disable-message-reformatting" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="format-detection" content="telephone=no, date=no, address=no, email=no" />- <meta name="color-scheme" content="light dark" />- <meta name="supported-color-schemes" content="light dark" />- <!--[if mso]>- <noscript>- <xml>- <o:OfficeDocumentSettings- xmlns:o="urn:schemas-microsoft-com:office:office"- >- <o:PixelsPerInch>96</o:PixelsPerInch>- </o:OfficeDocumentSettings>- </xml>- </noscript>- <style>- td,- th,- p,- a,- h1,- h2,- h3,- h4,- h5,- h6 {- font-family: "Segoe UI", sans-serif;- mso-line-height-rule: exactly;- }- </style>- <![endif]-->- <title>Macro Channel Invite</title>- <style>- /* Base styles */- body {- margin: 0;- padding: 0;- width: 100%;- background-color: #f8f9fa;- }-- /* Text styles */- .title {- font-size: 24px;- font-weight: 400;- color: #202124;- margin: 0;- padding: 0;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- .message {- font-size: 16px;- color: #202124;- line-height: 1.5;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Button styles */- .button {- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: "Google Sans", Roboto, Arial, sans-serif;- display: inline-block;- }-- /* Item name styles */- .item-name {- font-weight: 500;- color: #202124;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Footer styles */- .footer-text {- font-size: 12px;- color: #5f6368;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Email action link styles */- .email-link {- color: #1a73e8;- text-decoration: none;- }-- /* Logo styles */- .logo {- height: 32px;- }- </style>-</head>--<body style="- word-break: break-word;- -webkit-font-smoothing: antialiased;- margin: 0;- width: 100%;- background-color: #f8f9fa;- padding: 0;- ">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td align="center" style="padding: 24px 0">- <!-- Main Container -->- <table width="100%" style="max-width: 640px" cellpadding="0" cellspacing="0" border="0" role="presentation">- <!-- Header with Logo -->- <tr>- <td align="center" style="padding: 16px 0">- <img src="https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/logos/logo.png" alt="Macro"- class="logo" height="32" />- </td>- </tr>- <!-- Main Content Card -->- <tr>- <td style="padding: 0 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="- background-color: #ffffff;- border-radius: 8px;- border: 1px solid #dadce0;- " role="presentation">- <!-- Title -->- <tr>- <td style="padding: 5px"></td>- </tr>-- <!-- Message -->- <tr>- <td style="padding: 24px 24px 16px 24px">- <p class="message" style="- font-size: 16px;- color: #202124;- line-height: 1.5;- margin: 0;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- <strong style="text-decoration: none">{{INVITED_BY}}</strong>- {{INVITE_MESSAGE}}- </p>- </td>- </tr>-- <!-- Item -->- <tr>- <td style="padding: 0 24px 16px 24px">- <table width="100%" cellpadding="0" cellspacing="0" border="0"- style="background-color: #f8f9fa; border-radius: 4px" role="presentation">- <tr>- <td style="padding: 12px">- <table cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <!-- Item Name -->- <td style="vertical-align: middle">- <span class="item-name" style="- font-weight: 500;- color: #202124;- font-family: 'Google Sans', Roboto, Arial,- sans-serif;- ">- {{CHANNEL_MESSAGE}}- </span>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Button -->- <tr>- <td style="padding: 0 24px 24px 24px; text-align: left">- <table cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td style="- background-color: #1a73e8;- border-radius: 24px;- ">- <a href="{{CHANNEL_URL}}" class="button" style="- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: 'Google Sans', Roboto, Arial,- sans-serif;- display: inline-block;- ">- Open- </a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Footer -->- <tr>- <td style="padding: 24px 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- Macro, Inc.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- You have received this email because {{INVITED_BY}} has- invited you to a channel in Macro.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- Questions? Email us at- <a href="mailto:[email protected]" class="email-link"- style="color: #1a73e8; text-decoration: none">[email protected]</a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>- </table>-</body>--</html>diff --git a/rust/cloud-storage/notification_service/src/templates/channel_invite/mod.rs b/rust/cloud-storage/notification_service/src/templates/channel_invite/mod.rsdeleted file mode 100644index 4a2ad1f866..0000000000--- a/rust/cloud-storage/notification_service/src/templates/channel_invite/mod.rs+++ /dev/null@@ -1,64 +0,0 @@-use model_notifications::ChannelInviteMetadata;-use url::Url;--use crate::templates::add_skip_offboarding_query_param;--static BASIC_TEMPLATE: &str = include_str!("./_channel_invite_basic_template.html");--static SUBJECT: &str = "Macro Channel Invite";--fn transform_channel_type(channel_type: &str) -> String {- match channel_type {- "private" => "group channel",- "public" => "public channel",- "direct_message" => "direct message",- "organization" => "organization channel",- _ => "",- }- .to_string()-}--fn create_invite_message(channel_name: Option<&str>, channel_type: &str) -> String {- if let Some(channel_name) = channel_name {- format!("invited you to #{}.", channel_name)- } else {- format!("invited you to a {}.", transform_channel_type(channel_type))- }-}--fn fill_channel_invite_basic_template(- channel_url: &Url,- invited_by: &str,- channel_name: Option<&str>,- channel_type: &str,-) -> String {- let invite_message = create_invite_message(channel_name, channel_type);-- BASIC_TEMPLATE- .replace("{{INVITED_BY}}", invited_by)- .replace("{{INVITE_MESSAGE}}", &invite_message)- .replace("{{CHANNEL_URL}}", channel_url.as_str())-}--pub fn fill_channel_invite_template(- channel_url: &Url,- channel_metadata: &ChannelInviteMetadata,-) -> anyhow::Result<(String, String)> {- let subject = SUBJECT;-- let mut channel_url = channel_url.clone();- channel_url = add_skip_offboarding_query_param(channel_url);-- let content = fill_channel_invite_basic_template(- &channel_url,- &channel_metadata.invited_by.to_string(),- Some(&channel_metadata.common.channel_name),- &channel_metadata- .common- .channel_type- .to_model_comms()- .to_string(),- );-- Ok((content, subject.to_string()))-}diff --git a/rust/cloud-storage/notification_service/src/templates/channel_message/_channel_message_basic_template.html b/rust/cloud-storage/notification_service/src/templates/channel_message/_channel_message_basic_template.htmldeleted file mode 100644index b850fbc741..0000000000--- a/rust/cloud-storage/notification_service/src/templates/channel_message/_channel_message_basic_template.html+++ /dev/null@@ -1,228 +0,0 @@-<!DOCTYPE html>-<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml">--<head>- <meta charset="utf-8" />- <meta name="x-apple-disable-message-reformatting" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="format-detection" content="telephone=no, date=no, address=no, email=no" />- <meta name="color-scheme" content="light dark" />- <meta name="supported-color-schemes" content="light dark" />- <!--[if mso]>- <noscript>- <xml>- <o:OfficeDocumentSettings- xmlns:o="urn:schemas-microsoft-com:office:office"- >- <o:PixelsPerInch>96</o:PixelsPerInch>- </o:OfficeDocumentSettings>- </xml>- </noscript>- <style>- td,- th,- p,- a,- h1,- h2,- h3,- h4,- h5,- h6 {- font-family: "Segoe UI", sans-serif;- mso-line-height-rule: exactly;- }- </style>- <![endif]-->- <title>Macro Channel Invite</title>- <style>- /* Base styles */- body {- margin: 0;- padding: 0;- width: 100%;- background-color: #f8f9fa;- }-- /* Text styles */- .title {- font-size: 24px;- font-weight: 400;- color: #202124;- margin: 0;- padding: 0;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- .message {- font-size: 16px;- color: #202124;- line-height: 1.5;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Button styles */- .button {- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: "Google Sans", Roboto, Arial, sans-serif;- display: inline-block;- }-- /* Item name styles */- .item-name {- font-weight: 500;- color: #202124;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Footer styles */- .footer-text {- font-size: 12px;- color: #5f6368;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Email action link styles */- .email-link {- color: #1a73e8;- text-decoration: none;- }-- /* Logo styles */- .logo {- height: 32px;- }- </style>-</head>--<body style="- word-break: break-word;- -webkit-font-smoothing: antialiased;- margin: 0;- width: 100%;- background-color: #f8f9fa;- padding: 0;- ">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td align="center" style="padding: 24px 0">- <!-- Main Container -->- <table width="100%" style="max-width: 640px" cellpadding="0" cellspacing="0" border="0" role="presentation">- <!-- Header with Logo -->- <tr>- <td align="center" style="padding: 16px 0">- <img src="https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/logos/logo.png" alt="Macro"- class="logo" height="32" />- </td>- </tr>- <!-- Main Content Card -->- <tr>- <td style="padding: 0 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="- background-color: #ffffff;- border-radius: 8px;- border: 1px solid #dadce0;- " role="presentation">- <!-- Title -->- <tr>- <td style="padding: 5px"></td>- </tr>-- <!-- Message -->- <tr>- <td style="padding: 24px 24px 16px 24px">- <p class="message" style="- font-size: 16px;- color: #202124;- line-height: 1.5;- margin: 0;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- You have unread message(s) in a {{CHANNEL_TYPE}}- </p>- </td>- </tr>-- <!-- Button -->- <tr>- <td style="padding: 0 24px 24px 24px; text-align: left">- <table cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td style="- background-color: #1a73e8;- border-radius: 24px;- ">- <a href="{{CHANNEL_URL}}" class="button" style="- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: 'Google Sans', Roboto, Arial,- sans-serif;- display: inline-block;- ">- Open- </a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Footer -->- <tr>- <td style="padding: 24px 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- Macro, Inc.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- You have received this email because you have unread message(s) in Macro.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- Questions? Email us at- <a href="mailto:[email protected]" class="email-link"- style="color: #1a73e8; text-decoration: none">[email protected]</a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>- </table>-</body>--</html>diff --git a/rust/cloud-storage/notification_service/src/templates/channel_message/_channel_message_named_template.html b/rust/cloud-storage/notification_service/src/templates/channel_message/_channel_message_named_template.htmldeleted file mode 100644index 7964ed43da..0000000000--- a/rust/cloud-storage/notification_service/src/templates/channel_message/_channel_message_named_template.html+++ /dev/null@@ -1,264 +0,0 @@-<!DOCTYPE html>-<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml">--<head>- <meta charset="utf-8" />- <meta name="x-apple-disable-message-reformatting" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="format-detection" content="telephone=no, date=no, address=no, email=no" />- <meta name="color-scheme" content="light dark" />- <meta name="supported-color-schemes" content="light dark" />- <!--[if mso]>- <noscript>- <xml>- <o:OfficeDocumentSettings- xmlns:o="urn:schemas-microsoft-com:office:office"- >- <o:PixelsPerInch>96</o:PixelsPerInch>- </o:OfficeDocumentSettings>- </xml>- </noscript>- <style>- td,- th,- p,- a,- h1,- h2,- h3,- h4,- h5,- h6 {- font-family: "Segoe UI", sans-serif;- mso-line-height-rule: exactly;- }- </style>- <![endif]-->- <title>Macro Channel Invite</title>- <style>- /* Base styles */- body {- margin: 0;- padding: 0;- width: 100%;- background-color: #f8f9fa;- }-- /* Text styles */- .title {- font-size: 24px;- font-weight: 400;- color: #202124;- margin: 0;- padding: 0;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- .message {- font-size: 16px;- color: #202124;- line-height: 1.5;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Button styles */- .button {- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: "Google Sans", Roboto, Arial, sans-serif;- display: inline-block;- }-- /* Item name styles */- .item-name {- font-weight: 500;- color: #202124;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Footer styles */- .footer-text {- font-size: 12px;- color: #5f6368;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Email action link styles */- .email-link {- color: #1a73e8;- text-decoration: none;- }-- /* Logo styles */- .logo {- height: 32px;- }- </style>-</head>--<body style="- word-break: break-word;- -webkit-font-smoothing: antialiased;- margin: 0;- width: 100%;- background-color: #f8f9fa;- padding: 0;- ">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td align="center" style="padding: 24px 0">- <!-- Main Container -->- <table width="100%" style="max-width: 640px" cellpadding="0" cellspacing="0" border="0" role="presentation">- <!-- Header with Logo -->- <tr>- <td align="center" style="padding: 16px 0">- <img src="https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/logos/logo.png" alt="Macro"- class="logo" height="32" />- </td>- </tr>- <!-- Main Content Card -->- <tr>- <td style="padding: 0 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="- background-color: #ffffff;- border-radius: 8px;- border: 1px solid #dadce0;- " role="presentation">- <!-- Title -->- <tr>- <td style="padding: 5px"></td>- </tr>-- <!-- Message -->- <tr>- <td style="padding: 24px 24px 16px 24px">- <p class="message" style="- font-size: 16px;- color: #202124;- line-height: 1.5;- margin: 0;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- You have unread message(s) in the channel- </p>- </td>- </tr>-- <!-- Item -->- <tr>- <td style="padding: 0 24px 16px 24px">- <table width="100%" cellpadding="0" cellspacing="0" border="0"- style="background-color: #f8f9fa; border-radius: 4px" role="presentation">- <tr>- <td style="padding: 12px">- <table cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <!-- Icon -->- <td style="- padding-right: 12px;- vertical-align: middle;- ">- <img src="{{ITEM_SHARE_ICON}}" width="24" height="24" alt="icon"- style="display: block; border: 0" />- </td>- <!-- Item Name -->- <td style="vertical-align: middle">- <span class="item-name" style="- font-weight: 500;- color: #202124;- font-family: 'Google Sans', Roboto, Arial,- sans-serif;- ">- {{CHANNEL_NAME}}- </span>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Button -->- <tr>- <td style="padding: 0 24px 24px 24px; text-align: left">- <table cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td style="- background-color: #1a73e8;- border-radius: 24px;- ">- <a href="{{CHANNEL_URL}}" class="button" style="- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: 'Google Sans', Roboto, Arial,- sans-serif;- display: inline-block;- ">- Open- </a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Footer -->- <tr>- <td style="padding: 24px 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- Macro, Inc.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- You have received this email because you have unread message(s) in Macro.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- Questions? Email us at- <a href="mailto:[email protected]" class="email-link"- style="color: #1a73e8; text-decoration: none">[email protected]</a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>- </table>-</body>--</html>diff --git a/rust/cloud-storage/notification_service/src/templates/channel_message/mod.rs b/rust/cloud-storage/notification_service/src/templates/channel_message/mod.rsdeleted file mode 100644index c93cf26008..0000000000--- a/rust/cloud-storage/notification_service/src/templates/channel_message/mod.rs+++ /dev/null@@ -1,22 +0,0 @@-use url::Url;--static NAMED_TEMPLATE: &str = include_str!("./_channel_message_named_template.html");--static SUBJECT: &str = "Macro Unread Message";--static CHANNEL_INVITE_ICON: &str = "https://coparse-release-artifact-storage-bucket.s3.us-east-1.amazonaws.com/item_share_icons/user.png";--fn fill_channel_message_named_template(channel_url: &Url, channel_name: &str) -> String {- NAMED_TEMPLATE- .replace("{{ITEM_SHARE_ICON}}", CHANNEL_INVITE_ICON)- .replace("{{CHANNEL_NAME}}", channel_name)- .replace("{{CHANNEL_URL}}", channel_url.as_str())-}--pub fn fill_channel_message_template(channel_url: &Url, channel_name: &str) -> (String, String) {- let subject = SUBJECT;-- let content = fill_channel_message_named_template(channel_url, channel_name);-- (content, subject.to_string())-}diff --git a/rust/cloud-storage/notification_service/src/templates/item_share/_item_share_template.html b/rust/cloud-storage/notification_service/src/templates/item_share/_item_share_template.htmldeleted file mode 100644index c57ba0be42..0000000000--- a/rust/cloud-storage/notification_service/src/templates/item_share/_item_share_template.html+++ /dev/null@@ -1,214 +0,0 @@-<!DOCTYPE html>-<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml">--<head>- <meta charset="utf-8" />- <meta name="x-apple-disable-message-reformatting" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="format-detection" content="telephone=no, date=no, address=no, email=no" />- <meta name="color-scheme" content="light dark" />- <meta name="supported-color-schemes" content="light dark" />- <!--[if mso]>- <noscript>- <xml>- <o:OfficeDocumentSettings xmlns:o="urn:schemas-microsoft-com:office:office">- <o:PixelsPerInch>96</o:PixelsPerInch>- </o:OfficeDocumentSettings>- </xml>- </noscript>- <style>- td, th, p, a, h1, h2, h3, h4, h5, h6 {- font-family: 'Segoe UI', sans-serif;- mso-line-height-rule: exactly;- }- </style>- <![endif]-->- <title>Macro Share</title>- <style>- /* Base styles */- body {- margin: 0;- padding: 0;- width: 100%;- background-color: #f8f9fa;- }-- /* Text styles */- .title {- font-size: 24px;- font-weight: 400;- color: #202124;- margin: 0;- padding: 0;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- }-- .message {- font-size: 16px;- color: #202124;- line-height: 1.5;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- }-- /* Button styles */- .button {- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- display: inline-block;- }-- /* Item name styles */- .item-name {- font-weight: 500;- color: #202124;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- }-- /* Footer styles */- .footer-text {- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- }-- /* Email action link styles */- .email-link {- color: #1a73e8;- text-decoration: none;- }-- /* Logo styles */- .logo {- height: 32px;- }- </style>-</head>--<body- style="word-break: break-word; -webkit-font-smoothing: antialiased; margin: 0; width: 100%; background-color: #f8f9fa; padding: 0;">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td align="center" style="padding: 24px 0;">- <!-- Main Container -->- <table width="100%" style="max-width: 640px;" cellpadding="0" cellspacing="0" border="0" role="presentation">- <!-- Header with Logo -->- <tr>- <td align="center" style="padding: 16px 0;">- <img src="https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/logos/logo.png" alt="Macro"- class="logo" height="32" />- </td>- </tr>- <!-- Main Content Card -->- <tr>- <td style="padding: 0 16px;">- <table width="100%" cellpadding="0" cellspacing="0" border="0"- style="background-color: #ffffff; border-radius: 8px; border: 1px solid #dadce0;" role="presentation">- <!-- Title -->- <tr>- <td style="padding: 5px;">- <!-- <h1 class="title" -->- <!-- style="font-size: 24px; font-weight: 400; color: #202124; margin: 0; padding: 0; font-family: 'Google Sans', Roboto, Arial, sans-serif;"> -->- <!-- {{ITEM_OWNER}} shared a {{ITEM_TYPE}} -->- <!-- </h1> -->- </td>- </tr>-- <!-- Message -->- <tr>- <td style="padding: 24px 24px 16px 24px;">- <p class="message"- style="font-size: 16px; color: #202124; line-height: 1.5; margin: 0; font-family: 'Google Sans', Roboto, Arial, sans-serif;">- <strong style="text-decoration: none;">{{ITEM_OWNER}}</strong> has given you access to the- following {{ITEM_TYPE}}:- </p>- </td>- </tr>-- <!-- Item -->- <tr>- <td style="padding: 0 24px 16px 24px;">- <table width="100%" cellpadding="0" cellspacing="0" border="0"- style="background-color: #f8f9fa; border-radius: 4px;" role="presentation">- <tr>- <td style="padding: 12px;">- <table cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <!-- Icon -->- <td style="padding-right: 12px; vertical-align: middle;">- <img src="{{ITEM_SHARE_ICON_URL}}" width="24" height="24" alt="icon"- style="display: block; border: 0;" />- </td>- <!-- Item Name -->- <td style="vertical-align: middle;">- <span class="item-name"- style="font-weight: 500; color: #202124; font-family: 'Google Sans', Roboto, Arial, sans-serif;">- {{ITEM_NAME}}- </span>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Button -->- <tr>- <td style="padding: 0 24px 24px 24px; text-align: left;">- <table cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td style="background-color: #1a73e8; border-radius: 24px;">- <a href="{{ITEM_URL}}" class="button"- style="background-color: #1a73e8; color: white; text-decoration: none; padding: 8px 24px; border-radius: 24px; font-weight: 500; font-size: 14px; font-family: 'Google Sans', Roboto, Arial, sans-serif; display: inline-block;">- Open- </a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Footer -->- <tr>- <td style="padding: 24px 16px;">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td class="footer-text"- style="font-size: 12px; color: #5f6368; font-family: 'Google Sans', Roboto, Arial, sans-serif; padding-bottom: 8px;">- Macro, Inc.- </td>- </tr>- <tr>- <td class="footer-text"- style="font-size: 12px; color: #5f6368; font-family: 'Google Sans', Roboto, Arial, sans-serif; padding-bottom: 8px;">- You have received this email because {{ITEM_OWNER}} shared a {{ITEM_TYPE}} with you from Macro.- </td>- </tr>- <tr>- <td class="footer-text"- style="font-size: 12px; color: #5f6368; font-family: 'Google Sans', Roboto, Arial, sans-serif;">- Questions? Email us at- <a href="mailto:[email protected]" class="email-link"- style="color: #1a73e8; text-decoration: none;">[email protected]</a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>- </table>-</body>--</html>diff --git a/rust/cloud-storage/notification_service/src/templates/item_share/mod.rs b/rust/cloud-storage/notification_service/src/templates/item_share/mod.rsdeleted file mode 100644index a8355da1c6..0000000000--- a/rust/cloud-storage/notification_service/src/templates/item_share/mod.rs+++ /dev/null@@ -1,66 +0,0 @@-use url::Url;--static ITEM_SHARE_TEMPLATE: &str = include_str!("./_item_share_template.html");--static ITEM_SHARE_SUBJECT: &str = "Macro {{ITEM_TYPE}} Share";--pub static DOCUMNET_ITEM_SHARE_ICON: &str =- "https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/item_share_icons/doc.png";--pub static CHAT_ITEM_SHARE_ICON: &str =- "https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/item_share_icons/chat.png";--pub static PROJECT_ITEM_SHARE_ICON: &str =- "https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/item_share_icons/folder.png";--fn get_item_share_icon(item_type: &str) -> &str {- match item_type {- "document" => DOCUMNET_ITEM_SHARE_ICON,- "chat" => CHAT_ITEM_SHARE_ICON,- "project" => PROJECT_ITEM_SHARE_ICON,- _ => "",- }-}--pub fn fill_item_share_template(- item_url: &Url,- item_owner: &str,- item_name: &str,- item_type: &str,-) -> (String, String) {- let item_share_icon = get_item_share_icon(item_type);-- let first_letter_uppercase = item_type.chars().next().unwrap().to_uppercase().to_string();- let item_type = format!("{}{}", first_letter_uppercase, &item_type[1..]);-- let subject = ITEM_SHARE_SUBJECT.replace("{{ITEM_TYPE}}", &item_type);-- let content = ITEM_SHARE_TEMPLATE- .replace("{{ITEM_OWNER}}", item_owner)- .replace("{{ITEM_NAME}}", item_name)- .replace("{{ITEM_TYPE}}", &item_type)- .replace("{{ITEM_SHARE_ICON_URL}}", item_share_icon)- .replace("{{ITEM_URL}}", item_url.as_str());-- (content, subject)-}--#[cfg(test)]-mod tests {- #[test]- fn test_uppercase_first_letter() {- let word = "document";- let first_letter_uppercase = word.chars().next().unwrap().to_uppercase().to_string();- assert_eq!(first_letter_uppercase, "D");-- let updated_word = format!("{}{}", first_letter_uppercase, &word[1..]);- assert_eq!(updated_word, "Document");-- let word = "chat";- let first_letter_uppercase = word.chars().next().unwrap().to_uppercase().to_string();- assert_eq!(first_letter_uppercase, "C");-- let updated_word = format!("{}{}", first_letter_uppercase, &word[1..]);- assert_eq!(updated_word, "Chat");- }-}diff --git a/rust/cloud-storage/notification_service/src/templates/mod.rs b/rust/cloud-storage/notification_service/src/templates/mod.rsdeleted file mode 100644index 1e4f7a2e60..0000000000--- a/rust/cloud-storage/notification_service/src/templates/mod.rs+++ /dev/null@@ -1,16 +0,0 @@-use url::Url;--pub mod channel_invite;-pub mod channel_message;-pub mod item_share;--/// Adds a query param to the URL to skip offboarding.-pub fn add_skip_offboarding_query_param(mut url: Url) -> Url {- url.query_pairs_mut()- .append_pair("skip_offboarding", "true");-- url-}--#[cfg(test)]-mod test;diff --git a/rust/cloud-storage/notification_service/src/templates/test.rs b/rust/cloud-storage/notification_service/src/templates/test.rsdeleted file mode 100644index 5521121dee..0000000000--- a/rust/cloud-storage/notification_service/src/templates/test.rs+++ /dev/null@@ -1,21 +0,0 @@-use super::*;--#[test]-fn test_add_skip_offboarding_query_param() -> anyhow::Result<()> {- // URL without query param- let url = "https://example.com";- let result = add_skip_offboarding_query_param(url.try_into()?);- assert_eq!(- result.to_string(),- "https://example.com/?skip_offboarding=true"- );- // URL with existing query param- let url = "https://example.com?foo=bar";- let result = add_skip_offboarding_query_param(url.try_into()?);- assert_eq!(- result.to_string(),- "https://example.com/?foo=bar&skip_offboarding=true"- );-- Ok(())-}diff --git a/rust/cloud-storage/notification_service/src/templates/unread_message/_unread_message_template.html b/rust/cloud-storage/notification_service/src/templates/unread_message/_unread_message_template.htmldeleted file mode 100644index b18c6f176c..0000000000--- a/rust/cloud-storage/notification_service/src/templates/unread_message/_unread_message_template.html+++ /dev/null@@ -1,229 +0,0 @@-<!DOCTYPE html>-<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml">--<head>- <meta charset="utf-8" />- <meta name="x-apple-disable-message-reformatting" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="format-detection" content="telephone=no, date=no, address=no, email=no" />- <meta name="color-scheme" content="light dark" />- <meta name="supported-color-schemes" content="light dark" />- <!--[if mso]>- <noscript>- <xml>- <o:OfficeDocumentSettings- xmlns:o="urn:schemas-microsoft-com:office:office"- >- <o:PixelsPerInch>96</o:PixelsPerInch>- </o:OfficeDocumentSettings>- </xml>- </noscript>- <style>- td,- th,- p,- a,- h1,- h2,- h3,- h4,- h5,- h6 {- font-family: "Segoe UI", sans-serif;- mso-line-height-rule: exactly;- }- </style>- <![endif]-->- <title>Macro Unread Notifications</title>- <style>- /* Base styles */- body {- margin: 0;- padding: 0;- width: 100%;- background-color: #f8f9fa;- }-- /* Text styles */- .title {- font-size: 24px;- font-weight: 400;- color: #202124;- margin: 0;- padding: 0;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- .message {- font-size: 16px;- color: #202124;- line-height: 1.5;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Button styles */- .button {- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: "Google Sans", Roboto, Arial, sans-serif;- display: inline-block;- }-- /* Item name styles */- .item-name {- font-weight: 500;- color: #202124;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Footer styles */- .footer-text {- font-size: 12px;- color: #5f6368;- font-family: "Google Sans", Roboto, Arial, sans-serif;- }-- /* Email action link styles */- .email-link {- color: #1a73e8;- text-decoration: none;- }-- /* Logo styles */- .logo {- height: 32px;- }- </style>-</head>--<body style="- word-break: break-word;- -webkit-font-smoothing: antialiased;- margin: 0;- width: 100%;- background-color: #f8f9fa;- padding: 0;- ">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td align="center" style="padding: 24px 0">- <!-- Main Container -->- <table width="100%" style="max-width: 640px" cellpadding="0" cellspacing="0" border="0" role="presentation">- <!-- Header with Logo -->- <tr>- <td align="center" style="padding: 16px 0">- <img src="https://coparse-release-artifact-storage-bucket.s3.amazonaws.com/logos/logo.png" alt="Macro"- class="logo" height="32" />- </td>- </tr>- <!-- Main Content Card -->- <tr>- <td style="padding: 0 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" style="- background-color: #ffffff;- border-radius: 8px;- border: 1px solid #dadce0;- " role="presentation">- <!-- Title -->- <tr>- <td style="padding: 5px"></td>- </tr>-- <!-- Message -->- <tr>- <td style="padding: 24px 24px 16px 24px; text-align: center;">- <p class="message" style="- font-size: 16px;- color: #202124;- line-height: 1.5;- margin: 0;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- text-align: center;- ">- You have unread message(s) in Macro. Login to view them.- </p>- </td>- </tr>-- <!-- Button -->- <tr>- <td style="padding: 0 24px 24px 24px; text-align: center">- <table cellpadding="0" cellspacing="0" border="0" role="presentation" style="margin: 0 auto;">- <tr>- <td style="- background-color: #1a73e8;- border-radius: 24px;- ">- <a href="{{MACRO_URL}}" class="button" style="- background-color: #1a73e8;- color: white;- text-decoration: none;- padding: 8px 24px;- border-radius: 24px;- font-weight: 500;- font-size: 14px;- font-family: 'Google Sans', Roboto, Arial,- sans-serif;- display: inline-block;- ">- Open Macro- </a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-- <!-- Footer -->- <tr>- <td style="padding: 24px 16px">- <table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- Macro, Inc.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- padding-bottom: 8px;- ">- You have received this email because you have unread message(s) in Macro.- </td>- </tr>- <tr>- <td class="footer-text" style="- font-size: 12px;- color: #5f6368;- font-family: 'Google Sans', Roboto, Arial, sans-serif;- ">- Questions? Email us at- <a href="mailto:[email protected]" class="email-link"- style="color: #1a73e8; text-decoration: none">[email protected]</a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>- </table>-</body>--</html>