Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Add IP-based rate limiting for referral invites (#2106)

Sean Ayec531eab9ec78
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index f2c7c1b033..8bfa688a63 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5230,6 +5230,15 @@ dependencies = [
"syn 2.0.98",
]
+[[package]]
+name = "ip_extractor"
+version = "0.1.0"
+dependencies = [
+ "axum",
+ "thiserror 2.0.17",
+ "tokio",
+]
+
[[package]]
name = "ipconfig"
version = "0.3.2"
@@ -5797,6 +5806,7 @@ dependencies = [
"anyhow",
"axum",
"http-body-util",
+ "ip_extractor",
"macro_auth",
"macro_db_client",
"macro_env",
@@ -7879,6 +7889,8 @@ dependencies = [
name = "rate_limit"
version = "0.1.0"
dependencies = [
+ "axum",
+ "axum-extra",
"hex",
"redis",
"rootcause",
@@ -8034,6 +8046,7 @@ dependencies = [
"axum-extra",
"chrono",
"http-body-util",
+ "ip_extractor",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index 49b80a9f21..3395fa10f0 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -38,10 +38,11 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
NotificationIngressType,
>;
+type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;
+
pub(crate) type ReferralServiceType = ReferralServiceImpl<
PgReferralRepo,
StripeDiscountClient,
- RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>,
Arc<SqsNotificationIngress<SqsIngressQueue>>,
>;
@@ -71,6 +72,7 @@ pub(crate) struct ApiContext {
pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,
pub analytics_client: Arc<AnalyticsClient>,
pub referral_service: Arc<ReferralServiceType>,
+ pub rate_limit_service: RateLimiter,
/// The stripe price ids
pub stripe_price_ids: StripePriceIds,
}
diff --git a/rust/cloud-storage/authentication_service/src/api/email/generate_email_link.rs b/rust/cloud-storage/authentication_service/src/api/email/generate_email_link.rs
index 256b5630de..0a2fe00a25 100644
--- a/rust/cloud-storage/authentication_service/src/api/email/generate_email_link.rs
+++ b/rust/cloud-storage/authentication_service/src/api/email/generate_email_link.rs
@@ -5,13 +5,13 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_middleware::tracking::ClientIp;
use utoipa::ToSchema;
use crate::{api::context::ApiContext, config::BASE_URL, rate_limit_config::RATE_LIMIT_CONFIG};
use model::{
response::{EmptyResponse, ErrorResponse},
- tracking::IPContext,
user::UserContext,
};
@@ -34,11 +34,11 @@ static VERIFY_EMAIL_TEMPLATE: &str = include_str!("./_verify_email_template.html
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, user_context, ip_context,req), fields(client_ip=%ip_context.client_ip, email=%req.email, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, user_context, ip_context,req), fields(client_ip=%ip_context, email=%req.email, fusion_user_id=%user_context.fusion_user_id), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
extract::Json(mut req): extract::Json<GenerateEmailLinkRequest>,
) -> Result<Response, Response> {
tracing::info!("generate_email_link");
diff --git a/rust/cloud-storage/authentication_service/src/api/email/resend_fusionauth_verify_user_email.rs b/rust/cloud-storage/authentication_service/src/api/email/resend_fusionauth_verify_user_email.rs
index 81c47f73f9..c1fcfffdad 100644
--- a/rust/cloud-storage/authentication_service/src/api/email/resend_fusionauth_verify_user_email.rs
+++ b/rust/cloud-storage/authentication_service/src/api/email/resend_fusionauth_verify_user_email.rs
@@ -4,14 +4,12 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_middleware::tracking::ClientIp;
use utoipa::ToSchema;
use crate::{api::context::ApiContext, rate_limit_config::RATE_LIMIT_CONFIG};
-use model::{
- response::{EmptyResponse, ErrorResponse},
- tracking::IPContext,
-};
+use model::response::{EmptyResponse, ErrorResponse};
#[derive(serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ResendFusionauthVerifyUserEmailRequest {
@@ -29,10 +27,10 @@ pub struct ResendFusionauthVerifyUserEmailRequest {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, ip_context,req), fields(client_ip=%ip_context.client_ip, email=%req.email))]
+#[tracing::instrument(skip(ctx, ip_context,req), fields(client_ip=%ip_context, email=%req.email), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
extract::Json(req): extract::Json<ResendFusionauthVerifyUserEmailRequest>,
) -> Result<Response, Response> {
tracing::info!("resend_fusionauth_verify_user_email");
diff --git a/rust/cloud-storage/authentication_service/src/api/email/verify_email_link.rs b/rust/cloud-storage/authentication_service/src/api/email/verify_email_link.rs
index d87d177983..84417da6ed 100644
--- a/rust/cloud-storage/authentication_service/src/api/email/verify_email_link.rs
+++ b/rust/cloud-storage/authentication_service/src/api/email/verify_email_link.rs
@@ -4,14 +4,12 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Redirect, Response},
};
+use macro_middleware::tracking::ClientIp;
use crate::api::{context::ApiContext, utils::default_redirect_url};
use authentication_service::service::user::create_user::create_user_profile;
-use model::{
- response::{EmptyResponse, ErrorResponse},
- tracking::IPContext,
-};
+use model::response::{EmptyResponse, ErrorResponse};
#[derive(serde::Deserialize)]
pub struct Params {
@@ -31,10 +29,10 @@ pub struct Params {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, ip_context), fields(client_ip=%ip_context.client_ip))]
+#[tracing::instrument(skip(ctx, ip_context), fields(client_ip=%ip_context), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
extract::Path(Params { verification_id }): extract::Path<Params>,
) -> Result<Response, Response> {
tracing::info!("verify_email_link");
diff --git a/rust/cloud-storage/authentication_service/src/api/email/verify_fusionauth_user_email.rs b/rust/cloud-storage/authentication_service/src/api/email/verify_fusionauth_user_email.rs
index f1447025e3..00077cffed 100644
--- a/rust/cloud-storage/authentication_service/src/api/email/verify_fusionauth_user_email.rs
+++ b/rust/cloud-storage/authentication_service/src/api/email/verify_fusionauth_user_email.rs
@@ -1,16 +1,12 @@
+use crate::api::{context::ApiContext, utils::default_redirect_url};
use axum::{
Extension,
extract::{self, State},
http::StatusCode,
response::{IntoResponse, Redirect, Response},
};
-
-use crate::api::{context::ApiContext, utils::default_redirect_url};
-
-use model::{
- response::{EmptyResponse, ErrorResponse},
- tracking::IPContext,
-};
+use macro_middleware::tracking::ClientIp;
+use model::response::{EmptyResponse, ErrorResponse};
#[derive(serde::Deserialize)]
pub struct Params {
@@ -30,10 +26,10 @@ pub struct Params {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, ip_context), fields(client_ip=%ip_context.client_ip))]
+#[tracing::instrument(skip(ctx, ip_context), fields(client_ip=%ip_context), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
extract::Path(Params { verification_id }): extract::Path<Params>,
) -> Result<Response, Response> {
tracing::info!("verify_fusionauth_user_email");
@@ -42,7 +38,7 @@ pub async fn handler(
// This will trigger the user.email.verify event in FusionAuth to call our webhook to update
// macro_user_email_verification table
ctx.auth_client
- .verify_email(&verification_id, &ip_context.client_ip)
+ .verify_email(&verification_id, ip_context.origin_ip())
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to verify email");
diff --git a/rust/cloud-storage/authentication_service/src/api/link/create_in_progress_link.rs b/rust/cloud-storage/authentication_service/src/api/link/create_in_progress_link.rs
index 3d173a1ddd..f94261b6ce 100644
--- a/rust/cloud-storage/authentication_service/src/api/link/create_in_progress_link.rs
+++ b/rust/cloud-storage/authentication_service/src/api/link/create_in_progress_link.rs
@@ -4,10 +4,11 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_middleware::tracking::ClientIp;
use crate::api::context::ApiContext;
-use model::{response::ErrorResponse, tracking::IPContext, user::UserContext};
+use model::{response::ErrorResponse, user::UserContext};
#[derive(serde::Deserialize, serde::Serialize, Debug, utoipa::ToSchema)]
pub struct CreateInProgressLinkResponse {
@@ -28,10 +29,10 @@ pub struct CreateInProgressLinkResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
user_context: Extension<UserContext>,
) -> Result<Response, Response> {
tracing::info!("create_in_progress_link");
diff --git a/rust/cloud-storage/authentication_service/src/api/link/github.rs b/rust/cloud-storage/authentication_service/src/api/link/github.rs
index b50f316fd5..a3d623c9c1 100644
--- a/rust/cloud-storage/authentication_service/src/api/link/github.rs
+++ b/rust/cloud-storage/authentication_service/src/api/link/github.rs
@@ -5,10 +5,11 @@ use axum::{
response::{IntoResponse, Response},
};
use github::domain::{models::GithubError, ports::GithubLinkService};
+use macro_middleware::tracking::ClientIp;
use crate::api::{context::ApiContext, oauth2::OAuthState};
-use model::{response::ErrorResponse, tracking::IPContext, user::UserContext};
+use model::{response::ErrorResponse, user::UserContext};
#[derive(serde::Deserialize, serde::Serialize, Debug, utoipa::ToSchema)]
pub struct InitGithubLinkResponse {
@@ -66,10 +67,10 @@ impl IntoResponse for InitGithubLinkError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id), err)]
pub async fn init_github_link_handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
user_context: Extension<UserContext>,
) -> Result<Json<InitGithubLinkResponse>, InitGithubLinkError> {
// TODO: this should probably be a middleware or extractor
diff --git a/rust/cloud-storage/authentication_service/src/api/link/mod.rs b/rust/cloud-storage/authentication_service/src/api/link/mod.rs
index bd01418ffd..29a9bb3f61 100644
--- a/rust/cloud-storage/authentication_service/src/api/link/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/link/mod.rs
@@ -4,7 +4,6 @@ pub(in crate::api) mod create_in_progress_link;
pub(in crate::api) mod github;
/// The link router
-/// All routes have IPContext attached via the `macro_middleware::tracking::attach_ip_context_handler`.
/// We ensure the user is logged in with the `macro_middleware::auth::decode_jwt::handler`.
pub fn router(_state: ApiContext) -> Router<ApiContext> {
Router::new()
diff --git a/rust/cloud-storage/authentication_service/src/api/login/mod.rs b/rust/cloud-storage/authentication_service/src/api/login/mod.rs
index 37caa3859e..82721bdd47 100644
--- a/rust/cloud-storage/authentication_service/src/api/login/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/login/mod.rs
@@ -19,26 +19,16 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
.route(
"/passwordless",
- post(passwordless::handler).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::tracking::attach_ip_context_handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- middleware::rate_limit::passwordless::handler,
- )),
- ),
+ post(passwordless::handler).layer(ServiceBuilder::new().layer(
+ axum::middleware::from_fn_with_state(
+ state.clone(),
+ middleware::rate_limit::passwordless::handler,
+ ),
+ )),
)
.route(
"/password",
- post(password::handler).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::tracking::attach_ip_context_handler,
- ))
- .layer(CookieManagerLayer::new()),
- ),
+ post(password::handler).layer(ServiceBuilder::new().layer(CookieManagerLayer::new())),
)
.route(
"/apple",
diff --git a/rust/cloud-storage/authentication_service/src/api/login/password.rs b/rust/cloud-storage/authentication_service/src/api/login/password.rs
index 315173a776..ce573aa04d 100644
--- a/rust/cloud-storage/authentication_service/src/api/login/password.rs
+++ b/rust/cloud-storage/authentication_service/src/api/login/password.rs
@@ -3,16 +3,16 @@ use crate::api::{
utils::{create_access_token_cookie, create_refresh_token_cookie},
};
use axum::{
- Extension, Json,
+ Json,
extract::{self, State},
http::StatusCode,
response::{IntoResponse, Response},
};
use fusionauth::error::FusionAuthClientError;
+use macro_middleware::tracking::ClientIp;
use model::{
authentication::login::request::PasswordRequest,
response::{ErrorResponse, UserTokensResponse},
- tracking::IPContext,
};
use tower_cookies::Cookies;
@@ -28,10 +28,10 @@ use tower_cookies::Cookies;
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, req, ip_context), fields(email=%req.email, client_ip=%ip_context.client_ip))]
+#[tracing::instrument(skip(ctx, req, ip_context), fields(email=%req.email, client_ip=%ip_context), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
cookies: Cookies,
extract::Json(req): extract::Json<PasswordRequest>,
) -> Result<Response, Response> {
diff --git a/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs b/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs
index 9cf391fda3..b82a1a6996 100644
--- a/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs
+++ b/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs
@@ -1,9 +1,10 @@
use axum::{
- Extension, Json,
+ Json,
extract::{self, State},
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_middleware::tracking::ClientIp;
use std::borrow::Cow;
@@ -13,7 +14,6 @@ use macro_user_id::user_id::MacroUserId;
use model::{
authentication::login::{request::PasswordlessRequest, response::SsoRequiredResponse},
response::{EmptyResponse, ErrorResponse},
- tracking::IPContext,
};
use referral::domain::{models::ReferralCode, ports::ReferralService};
@@ -30,10 +30,10 @@ use referral::domain::{models::ReferralCode, ports::ReferralService};
(status = 500, body=String),
)
)]
-#[tracing::instrument(skip(ctx, req, ip_context), fields(email=%req.email, client_ip=%ip_context.client_ip))]
+#[tracing::instrument(skip(ctx, req, ip_context), fields(email=%req.email, client_ip=%ip_context), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
extract::Json(req): extract::Json<PasswordlessRequest>,
) -> Result<Response, Response> {
tracing::info!("passwordless_login_request");
@@ -102,7 +102,7 @@ pub async fn handler(
email: (&lowercase_email).into(),
password: generate_random_password().into(),
username: None,
- }, true, &ip_context.client_ip)
+ }, true, ip_context.origin_ip())
.await
.map_err(|e| {
tracing::error!(error=?e, email=%lowercase_email, "unable to create user");
diff --git a/rust/cloud-storage/authentication_service/src/api/merge/create_merge_request.rs b/rust/cloud-storage/authentication_service/src/api/merge/create_merge_request.rs
index 1efa55544b..06251c0d34 100644
--- a/rust/cloud-storage/authentication_service/src/api/merge/create_merge_request.rs
+++ b/rust/cloud-storage/authentication_service/src/api/merge/create_merge_request.rs
@@ -5,13 +5,13 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_middleware::tracking::ClientIp;
use utoipa::ToSchema;
use crate::{api::context::ApiContext, rate_limit_config::RATE_LIMIT_CONFIG};
use model::{
response::{EmptyResponse, ErrorResponse},
- tracking::IPContext,
user::UserContext,
};
@@ -39,11 +39,11 @@ static MERGE_REQUEST_TEMPLATE: &str = include_str!("./_merge_request_template.ht
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, user_context, ip_context,req), fields(client_ip=%ip_context.client_ip, email=%req.email, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, user_context, ip_context,req), fields(client_ip=%ip_context, email=%req.email, fusion_user_id=%user_context.fusion_user_id), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
extract::Json(mut req): extract::Json<CreateAccountMergeRequest>,
) -> Result<Response, Response> {
tracing::info!("create_merge_request");
diff --git a/rust/cloud-storage/authentication_service/src/api/merge/verify_merge_request.rs b/rust/cloud-storage/authentication_service/src/api/merge/verify_merge_request.rs
index 5bed1200c8..a66d7bdbd5 100644
--- a/rust/cloud-storage/authentication_service/src/api/merge/verify_merge_request.rs
+++ b/rust/cloud-storage/authentication_service/src/api/merge/verify_merge_request.rs
@@ -6,13 +6,13 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_middleware::tracking::ClientIp;
use crate::api::context::ApiContext;
use fusionauth::identity_provider::{IdentityProviderLink, LinkUserRequest};
use model::{
response::{EmptyResponse, ErrorResponse},
- tracking::IPContext,
user::UserContext,
};
@@ -35,10 +35,10 @@ pub struct Params {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, user_context, ip_context), fields(client_ip=%ip_context.client_ip, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, user_context, ip_context), fields(client_ip=%ip_context, fusion_user_id=%user_context.fusion_user_id), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
user_context: Extension<UserContext>,
extract::Path(Params { code }): extract::Path<Params>,
) -> Result<Response, Response> {
diff --git a/rust/cloud-storage/authentication_service/src/api/middleware/rate_limit/login_code.rs b/rust/cloud-storage/authentication_service/src/api/middleware/rate_limit/login_code.rs
index 8512657387..7e4b0f0fc6 100644
--- a/rust/cloud-storage/authentication_service/src/api/middleware/rate_limit/login_code.rs
+++ b/rust/cloud-storage/authentication_service/src/api/middleware/rate_limit/login_code.rs
@@ -2,7 +2,6 @@ use std::borrow::Cow;
use crate::{api::context::ApiContext, rate_limit_config::RATE_LIMIT_CONFIG};
use axum::{
- Extension,
body::Body,
extract::{Query, Request, State},
http::StatusCode,
@@ -10,13 +9,13 @@ use axum::{
response::{IntoResponse, Response},
};
use http_body_util::BodyExt;
-use model::tracking::IPContext;
+use macro_middleware::tracking::ClientIp;
/// Rate limit for validating passwordless login code
-#[tracing::instrument(skip(ctx, req, next, ip_context), fields(client_ip=%ip_context.client_ip))]
+#[tracing::instrument(skip(ctx, req, next, ip_context), fields(client_ip=%ip_context), err(Debug))]
pub(in crate::api) async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
req: Request,
next: Next,
) -> Result<Response, Response> {
diff --git a/rust/cloud-storage/authentication_service/src/api/middleware/rate_limit/passwordless.rs b/rust/cloud-storage/authentication_service/src/api/middleware/rate_limit/passwordless.rs
index dc93c728e2..bb739b9852 100644
--- a/rust/cloud-storage/authentication_service/src/api/middleware/rate_limit/passwordless.rs
+++ b/rust/cloud-storage/authentication_service/src/api/middleware/rate_limit/passwordless.rs
@@ -1,8 +1,5 @@
-use std::borrow::Cow;
-
use crate::{api::context::ApiContext, rate_limit_config::RATE_LIMIT_CONFIG};
use axum::{
- Extension,
body::Body,
extract::{Request, State},
http::StatusCode,
@@ -10,7 +7,8 @@ use axum::{
response::{IntoResponse, Response},
};
use http_body_util::BodyExt;
-use model::tracking::IPContext;
+use macro_middleware::tracking::ClientIp;
+use std::borrow::Cow;
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct RequestWithEmail {
@@ -20,10 +18,10 @@ pub struct RequestWithEmail {
/// Rate limit for passwordless logins
/// For rate limiting, we use the key `rtl_passwordless:${email}`
-#[tracing::instrument(skip(ctx, req, next, ip_context), fields(client_ip=%ip_context.client_ip))]
+#[tracing::instrument(skip(ctx, req, next, ip_context), fields(client_ip=%ip_context), err(Debug))]
pub(in crate::api) async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
req: Request,
next: Next,
) -> Result<Response, Response> {
diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rs
index f2a1f3e3b6..5dd8780243 100644
--- a/rust/cloud-storage/authentication_service/src/api/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs
@@ -5,6 +5,7 @@ use axum::http::HeaderName;
use macro_auth::constant::MACRO_REFRESH_TOKEN_HEADER;
use macro_tower_layers::MacroRequestIdAndTracingLayer;
use native_app_service::inbound::RouterState;
+use std::net::SocketAddr;
use std::time::Duration;
use tower::ServiceBuilder;
use utoipa::OpenApi;
@@ -60,9 +61,12 @@ pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<(
&env,
&port
);
- axum::serve(listener, app.into_make_service())
- .await
- .context("error starting service")
+ axum::serve(
+ listener,
+ app.into_make_service_with_connect_info::<SocketAddr>(),
+ )
+ .await
+ .context("error starting service")
}
fn api_router(state: ApiContext) -> Router<ApiContext> {
@@ -81,16 +85,12 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
.nest("/user", user::router(state.clone(), state.jwt_args.clone()))
.nest(
"/link",
- link::router(state.clone()).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::tracking::attach_ip_context_handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.jwt_args.clone(),
- macro_middleware::auth::decode_jwt::handler,
- )),
- ),
+ link::router(state.clone()).layer(ServiceBuilder::new().layer(
+ axum::middleware::from_fn_with_state(
+ state.jwt_args.clone(),
+ macro_middleware::auth::decode_jwt::handler,
+ ),
+ )),
)
.nest(
"/team",
@@ -100,14 +100,10 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
},
)
.layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::tracking::attach_ip_context_handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.jwt_args.clone(),
- macro_middleware::auth::decode_jwt::handler,
- )),
+ ServiceBuilder::new().layer(axum::middleware::from_fn_with_state(
+ state.jwt_args.clone(),
+ macro_middleware::auth::decode_jwt::handler,
+ )),
),
)
.nest(
@@ -115,17 +111,14 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
referral::inbound::axum_router::referral_router(
referral::inbound::axum_router::ReferralRouterState {
service: state.referral_service.clone(),
+ rate_limiter: state.rate_limit_service.clone(),
},
)
.layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::tracking::attach_ip_context_handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.jwt_args.clone(),
- macro_middleware::auth::decode_jwt::handler,
- )),
+ ServiceBuilder::new().layer(axum::middleware::from_fn_with_state(
+ state.jwt_args.clone(),
+ macro_middleware::auth::decode_jwt::handler,
+ )),
),
)
.nest("/jwt", jwt::router(state.jwt_args.clone()))
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth/mod.rs b/rust/cloud-storage/authentication_service/src/api/oauth/mod.rs
index ee12e4cb42..114fbe3742 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth/mod.rs
@@ -17,9 +17,6 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
get(passwordless_callback::handler).layer(
ServiceBuilder::new()
.layer(CookieManagerLayer::new())
- .layer(axum::middleware::from_fn(
- macro_middleware::tracking::attach_ip_context_handler,
- ))
.layer(axum::middleware::from_fn_with_state(
state.clone(),
middleware::rate_limit::login_code::handler,
diff --git a/rust/cloud-storage/authentication_service/src/api/user/create_user.rs b/rust/cloud-storage/authentication_service/src/api/user/create_user.rs
index 630916d8e2..2e733eb4f6 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/create_user.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/create_user.rs
@@ -1,16 +1,14 @@
use axum::{
- Extension, Json,
+ Json,
extract::{self, State},
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_middleware::tracking::ClientIp;
use crate::api::context::ApiContext;
-use model::{
- response::{EmptyResponse, ErrorResponse},
- tracking::IPContext,
-};
+use model::response::{EmptyResponse, ErrorResponse};
/// The request body to create a new user in fusionauth
/// NOTE: Never derive debug here as we don't want to accidentally log the password
@@ -37,10 +35,10 @@ pub struct CreateUserRequest {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, ip_context, req), fields(client_ip=%ip_context.client_ip))]
+#[tracing::instrument(skip(ctx, ip_context, req), fields(client_ip=%ip_context), err(Debug))]
pub async fn handler(
State(ctx): State<ApiContext>,
- ip_context: Extension<IPContext>,
+ ip_context: ClientIp,
extract::Json(req): extract::Json<CreateUserRequest>,
) -> Result<Response, Response> {
tracing::info!("create_user");
@@ -89,7 +87,7 @@ pub async fn handler(
username: Some(req.username.into()),
},
false,
- &ip_context.client_ip,
+ ip_context.origin_ip(),
)
.await
.map_err(|e| {
diff --git a/rust/cloud-storage/authentication_service/src/api/user/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/mod.rs
index df88f3b691..0c359411ea 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/mod.rs
@@ -31,9 +31,6 @@ pub(in crate::api) mod stripe;
pub fn router(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<ApiContext> {
Router::new()
.route("/", post(create_user::handler))
- .layer(ServiceBuilder::new().layer(axum::middleware::from_fn(
- macro_middleware::tracking::attach_ip_context_handler, // attach ip context to all requests
- )))
.merge(router_with_auth(state, jwt_args))
}
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 3a31a6ae62..6f3518056d 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -247,17 +247,17 @@ async fn main() -> anyhow::Result<()> {
},
);
+ let rate_limit = RateLimitServiceImpl {
+ repo: RedisRateLimitAdapter {
+ redis: redis_client,
+ },
+ };
let referral_service = ReferralServiceImpl {
repo: PgReferralRepo::new(db.clone()),
discount_client: StripeDiscountClient::new(
stripe_client.clone(),
10000, /*100$ credit, in cents*/
),
- rate_limit: RateLimitServiceImpl {
- repo: RedisRateLimitAdapter {
- redis: redis_client,
- },
- },
notification_ingress: notification_ingress_service.clone(),
};
@@ -273,6 +273,7 @@ async fn main() -> anyhow::Result<()> {
notification_ingress_service,
sqs_client: Arc::new(sqs_client),
environment: config.environment,
+ rate_limit_service: rate_limit,
jwt_args,
token_context: MacroApiTokenContext {
issuer: MacroApiTokenIssuer::new()?,
diff --git a/rust/cloud-storage/fusionauth/src/user/create.rs b/rust/cloud-storage/fusionauth/src/user/create.rs
index c7adbd8731..1ebb6090b0 100644
--- a/rust/cloud-storage/fusionauth/src/user/create.rs
+++ b/rust/cloud-storage/fusionauth/src/user/create.rs
@@ -1,4 +1,4 @@
-use std::borrow::Cow;
+use std::{borrow::Cow, net::IpAddr};
use crate::{
AuthedClient, Result,
@@ -56,12 +56,12 @@ pub(crate) async fn create_user(
client: &AuthedClient,
base_url: &str,
request: CreateUserRequest<'_>,
- client_ip: &str,
+ client_ip: IpAddr,
) -> Result<String> {
let res = client
.client()
.post(format!("{base_url}/api/user"))
- .header("X-Forwarded-For", client_ip)
+ .header("X-Forwarded-For", &client_ip.to_string())
.json(&request)
.send()
.await
diff --git a/rust/cloud-storage/fusionauth/src/user/mod.rs b/rust/cloud-storage/fusionauth/src/user/mod.rs
index 7dbef44b79..f30149a1fe 100644
--- a/rust/cloud-storage/fusionauth/src/user/mod.rs
+++ b/rust/cloud-storage/fusionauth/src/user/mod.rs
@@ -1,4 +1,4 @@
-use std::borrow::Cow;
+use std::{borrow::Cow, net::IpAddr};
use crate::{FusionAuthClient, Result};
@@ -24,7 +24,7 @@ impl FusionAuthClient {
&self,
user: create::User<'_>,
skip_verification: bool,
- client_ip: &str,
+ client_ip: IpAddr,
) -> Result<String> {
create::create_user(
&self.auth_client,
@@ -84,7 +84,7 @@ impl FusionAuthClient {
/// Verifies a user's email with the given verification ID.
#[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
- pub async fn verify_email(&self, verification_id: &str, client_ip: &str) -> Result<()> {
+ pub async fn verify_email(&self, verification_id: &str, client_ip: IpAddr) -> Result<()> {
verify::verify_email(
&self.auth_client,
&self.fusion_auth_base_url,
diff --git a/rust/cloud-storage/fusionauth/src/user/verify.rs b/rust/cloud-storage/fusionauth/src/user/verify.rs
index da35650671..f822aafa5d 100644
--- a/rust/cloud-storage/fusionauth/src/user/verify.rs
+++ b/rust/cloud-storage/fusionauth/src/user/verify.rs
@@ -1,4 +1,4 @@
-use std::borrow::Cow;
+use std::{borrow::Cow, net::IpAddr};
use crate::{
AuthedClient, Result,
@@ -19,12 +19,12 @@ pub(crate) async fn verify_email<'a>(
client: &AuthedClient,
base_url: &str,
verify_email_request: VerifyEmailRequest<'a>,
- client_ip: &str,
+ client_ip: IpAddr,
) -> Result<()> {
let res = client
.client()
.post(format!("{base_url}/api/user/verify-email"))
- .header("X-Forwarded-For", client_ip)
+ .header("X-Forwarded-For", &client_ip.to_string())
.json(&verify_email_request)
.send()
.await
diff --git a/rust/cloud-storage/image_proxy_service/src/api/mod.rs b/rust/cloud-storage/image_proxy_service/src/api/mod.rs
index 50f723eddc..823cd1de9f 100644
--- a/rust/cloud-storage/image_proxy_service/src/api/mod.rs
+++ b/rust/cloud-storage/image_proxy_service/src/api/mod.rs
@@ -41,14 +41,10 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
Router::new().nest(
"/proxy",
proxy::router().layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::tracking::attach_ip_context_handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.jwt_args.clone(),
- macro_middleware::auth::decode_jwt::handler,
- )),
+ ServiceBuilder::new().layer(axum::middleware::from_fn_with_state(
+ state.jwt_args.clone(),
+ macro_middleware::auth::decode_jwt::handler,
+ )),
),
)
}
diff --git a/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs b/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs
index ac4a669fdc..bdb35f731a 100644
--- a/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs
+++ b/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs
@@ -4,6 +4,7 @@ use axum::extract::{Query, State};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use futures::StreamExt;
+use macro_middleware::tracking::ClientIp;
use reqwest::StatusCode;
use serde::Deserialize;
use std::error::Error;
@@ -98,6 +99,7 @@ pub struct ProxyParams {
pub async fn proxy_request_handler(
Query(params): Query<ProxyParams>,
State(http_client): State<reqwest::Client>,
+ _ip: ClientIp,
) -> Result<Response, ProxyError> {
let validated_url = validate_url(&params.url)?;
assert_not_internal(&validated_url).await?;
diff --git a/rust/cloud-storage/ip_extractor/Cargo.toml b/rust/cloud-storage/ip_extractor/Cargo.toml
new file mode 100644
index 0000000000..666b9cef5c
--- /dev/null
+++ b/rust/cloud-storage/ip_extractor/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+edition = "2024"
+name = "ip_extractor"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+axum = { workspace = true }
+thiserror = { workspace = true }
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/rust/cloud-storage/ip_extractor/src/lib.rs b/rust/cloud-storage/ip_extractor/src/lib.rs
new file mode 100644
index 0000000000..3392def2e8
--- /dev/null
+++ b/rust/cloud-storage/ip_extractor/src/lib.rs
@@ -0,0 +1,122 @@
+#![deny(missing_docs)]
+//! Axum middleware for extracting client IP from requests.
+//!
+//! Extraction priority:
+//! 1. `X-Forwarded-For` — uses the last (rightmost) IP in the chain,
+//! which is the one added by the closest trusted proxy.
+//! 2. `ConnectInfo<SocketAddr>` — direct TCP peer address.
+
+#[cfg(test)]
+mod test;
+
+use axum::{
+ RequestPartsExt,
+ extract::{ConnectInfo, FromRequestParts, rejection::ExtensionRejection},
+ http::{HeaderName, HeaderValue, StatusCode},
+ response::{IntoResponse, Response},
+};
+use std::{
+ net::{AddrParseError, IpAddr, SocketAddr},
+ str::{FromStr, Utf8Error},
+};
+use thiserror::Error;
+
+/// The best guess at what the originating IP of a client request is.
+///
+/// Uses the last IP from the `X-Forwarded-For` header when present.
+/// Falls back to the direct connection IP for environments without
+/// a reverse proxy (e.g. local development).
+#[derive(Debug)]
+pub enum ClientIp {
+ /// IP from the X-Forwarded-For header
+ ForwardedFor(IpAddr),
+ /// the direct ip of the client
+ DirectIp(ConnectInfo<SocketAddr>),
+}
+
+impl std::fmt::Display for ClientIp {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ ClientIp::ForwardedFor(ip_addr) => write!(f, "{ip_addr}"),
+ ClientIp::DirectIp(connect_info) => {
+ write!(f, "{}:{}", connect_info.ip(), connect_info.port())
+ }
+ }
+ }
+}
+
+impl ClientIp {
+ /// get the [IpAddr] of the client
+ pub fn origin_ip(&self) -> IpAddr {
+ match self {
+ ClientIp::ForwardedFor(ip) => *ip,
+ ClientIp::DirectIp(connect_info) => connect_info.ip(),
+ }
+ }
+}
+
+/// The errors that can occur while extracting a [ClientIp]
+#[derive(Debug, Error)]
+pub enum ClientIpError {
+ /// the header contained an invalid ip address (v4/v6) value
+ #[error("invalid ip address {0:?}")]
+ ParseErr(#[from] AddrParseError),
+ /// the header contained non-ascii chars
+ #[error("invalid ascii {0:?}")]
+ InvalidAscii(#[from] Utf8Error),
+ /// the axum server did not call into_make_service_with_conn_info
+ #[error("Internal server err")]
+ ExtensionErr(#[from] ExtensionRejection),
+}
+
+impl IntoResponse for ClientIpError {
+ fn into_response(self) -> Response {
+ let code = match &self {
+ ClientIpError::ParseErr(_addr_parse_error) => StatusCode::BAD_REQUEST,
+ ClientIpError::InvalidAscii(_utf8_error) => StatusCode::BAD_REQUEST,
+ ClientIpError::ExtensionErr(_extension_rejection) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ (code, self.to_string()).into_response()
+ }
+}
+
+const X_FORWARDED_FOR_HEADER: HeaderName = HeaderName::from_static("x-forwarded-for");
+
+impl<S> FromRequestParts<S> for ClientIp
+where
+ S: Send + Sync,
+{
+ type Rejection = ClientIpError;
+
+ async fn from_request_parts(
+ parts: &mut axum::http::request::Parts,
+ _state: &S,
+ ) -> Result<Self, Self::Rejection> {
+ match parts.headers.get(X_FORWARDED_FOR_HEADER).map(parse_header) {
+ Some(Ok(ip)) => Ok(ClientIp::ForwardedFor(ip)),
+ Some(Err(e)) => Err(e),
+ None => {
+ let conn: ConnectInfo<SocketAddr> = parts.extract().await?;
+ Ok(ClientIp::DirectIp(conn))
+ }
+ }
+ }
+}
+
+fn parse_header(header: &HeaderValue) -> Result<IpAddr, ClientIpError> {
+ let bytes = header.as_bytes();
+
+ let start = bytes
+ .iter()
+ .enumerate()
+ .rev()
+ .find_map(|(idx, item)| match item {
+ b',' => Some(idx + 1),
+ _ => None,
+ })
+ .unwrap_or_default();
+
+ let s = str::from_utf8(&bytes[start..])?.trim();
+
+ Ok(IpAddr::from_str(s)?)
+}
diff --git a/rust/cloud-storage/ip_extractor/src/test.rs b/rust/cloud-storage/ip_extractor/src/test.rs
new file mode 100644
index 0000000000..8810cf05fe
--- /dev/null
+++ b/rust/cloud-storage/ip_extractor/src/test.rs
@@ -0,0 +1,230 @@
+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
+
+use axum::{
+ extract::{ConnectInfo, FromRequestParts},
+ http::{HeaderValue, Request, StatusCode},
+ response::IntoResponse,
+};
+
+use super::*;
+
+// -- parse_header tests --
+
+#[test]
+fn parse_single_ipv4() {
+ let header = HeaderValue::from_static("203.0.113.50");
+ let ip = parse_header(&header).unwrap();
+ assert_eq!(ip, IpAddr::V4(Ipv4Addr::new(203, 0, 113, 50)));
+}
+
+#[test]
+fn parse_single_ipv6() {
+ let header = HeaderValue::from_static("2001:db8::1");
+ let ip = parse_header(&header).unwrap();
+ assert_eq!(
+ ip,
+ IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1))
+ );
+}
+
+#[test]
+fn parse_takes_last_ip_in_chain() {
+ let header = HeaderValue::from_static("203.0.113.50, 10.0.0.1, 192.168.1.1");
+ let ip = parse_header(&header).unwrap();
+ assert_eq!(ip, IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));
+}
+
+#[test]
+fn parse_two_ips_takes_last() {
+ let header = HeaderValue::from_static("203.0.113.50, 10.0.0.1");
+ let ip = parse_header(&header).unwrap();
+ assert_eq!(ip, IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)));
+}
+
+#[test]
+fn parse_with_whitespace() {
+ let header = HeaderValue::from_static(" 203.0.113.50 ");
+ let ip = parse_header(&header).unwrap();
+ assert_eq!(ip, IpAddr::V4(Ipv4Addr::new(203, 0, 113, 50)));
+}
+
+#[test]
+fn parse_invalid_returns_error() {
+ let header = HeaderValue::from_static("not-an-ip");
+ let err = parse_header(&header).unwrap_err();
+ assert!(matches!(err, ClientIpError::ParseErr(_)));
+}
+
+#[test]
+fn parse_loopback() {
+ let header = HeaderValue::from_static("127.0.0.1");
+ let ip = parse_header(&header).unwrap();
+ assert_eq!(ip, IpAddr::V4(Ipv4Addr::LOCALHOST));
+}
+
+// -- ClientIp::origin_ip tests --
+
+#[test]
+fn origin_ip_forwarded_for() {
+ let ip = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 50));
+ let client_ip = ClientIp::ForwardedFor(ip);
+ assert_eq!(client_ip.origin_ip(), ip);
+}
+
+#[test]
+fn origin_ip_direct_ip() {
+ let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)), 12345);
+ let client_ip = ClientIp::DirectIp(ConnectInfo(addr));
+ assert_eq!(
+ client_ip.origin_ip(),
+ IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))
+ );
+}
+
+#[test]
+fn origin_ip_direct_ip_v6() {
+ let addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 443);
+ let client_ip = ClientIp::DirectIp(ConnectInfo(addr));
+ assert_eq!(client_ip.origin_ip(), IpAddr::V6(Ipv6Addr::LOCALHOST));
+}
+
+// -- Display tests --
+
+#[test]
+fn display_forwarded_for() {
+ let ip = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 50));
+ let client_ip = ClientIp::ForwardedFor(ip);
+ assert_eq!(client_ip.to_string(), "203.0.113.50");
+}
+
+#[test]
+fn display_direct_ip() {
+ let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)), 8080);
+ let client_ip = ClientIp::DirectIp(ConnectInfo(addr));
+ assert_eq!(client_ip.to_string(), "192.168.1.1:8080");
+}
+
+// -- FromRequestParts tests --
+
+#[tokio::test]
+async fn prefers_x_forwarded_for() {
+ let (mut parts, _body) = Request::builder()
+ .header("x-forwarded-for", "203.0.113.50")
+ .body(())
+ .unwrap()
+ .into_parts();
+
+ let client_ip = ClientIp::from_request_parts(&mut parts, &()).await.unwrap();
+
+ assert!(matches!(client_ip, ClientIp::ForwardedFor(_)));
+ assert_eq!(
+ client_ip.origin_ip(),
+ IpAddr::V4(Ipv4Addr::new(203, 0, 113, 50))
+ );
+}
+
+#[tokio::test]
+async fn x_forwarded_for_ipv6() {
+ let (mut parts, _body) = Request::builder()
+ .header("x-forwarded-for", "2001:db8::1")
+ .body(())
+ .unwrap()
+ .into_parts();
+
+ let client_ip = ClientIp::from_request_parts(&mut parts, &()).await.unwrap();
+
+ assert_eq!(
+ client_ip.origin_ip(),
+ IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1))
+ );
+}
+
+#[tokio::test]
+async fn x_forwarded_for_takes_last_ip() {
+ let (mut parts, _body) = Request::builder()
+ .header("x-forwarded-for", "203.0.113.50, 10.0.0.1, 192.168.1.1")
+ .body(())
+ .unwrap()
+ .into_parts();
+
+ let client_ip = ClientIp::from_request_parts(&mut parts, &()).await.unwrap();
+
+ assert_eq!(
+ client_ip.origin_ip(),
+ IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))
+ );
+}
+
+#[tokio::test]
+async fn falls_back_to_connect_info_when_no_forwarded_header() {
+ let (mut parts, _body) = Request::builder().body(()).unwrap().into_parts();
+ let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)), 9000);
+ parts.extensions.insert(ConnectInfo(addr));
+
+ let client_ip = ClientIp::from_request_parts(&mut parts, &()).await.unwrap();
+
+ assert!(matches!(client_ip, ClientIp::DirectIp(_)));
+ assert_eq!(
+ client_ip.origin_ip(),
+ IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100))
+ );
+}
+
+#[tokio::test]
+async fn forwarded_header_preferred_over_connect_info() {
+ let (mut parts, _body) = Request::builder()
+ .header("x-forwarded-for", "203.0.113.50")
+ .body(())
+ .unwrap()
+ .into_parts();
+ let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)), 9000);
+ parts.extensions.insert(ConnectInfo(addr));
+
+ let client_ip = ClientIp::from_request_parts(&mut parts, &()).await.unwrap();
+
+ assert!(matches!(client_ip, ClientIp::ForwardedFor(_)));
+ assert_eq!(
+ client_ip.origin_ip(),
+ IpAddr::V4(Ipv4Addr::new(203, 0, 113, 50))
+ );
+}
+
+#[tokio::test]
+async fn no_header_no_connect_info_returns_error() {
+ let (mut parts, _body) = Request::builder().body(()).unwrap().into_parts();
+
+ let err = ClientIp::from_request_parts(&mut parts, &())
+ .await
+ .unwrap_err();
+ assert!(matches!(err, ClientIpError::ExtensionErr(_)));
+}
+
+#[tokio::test]
+async fn invalid_forwarded_address_returns_error() {
+ let (mut parts, _body) = Request::builder()
+ .header("x-forwarded-for", "not-an-ip")
+ .body(())
+ .unwrap()
+ .into_parts();
+
+ let err = ClientIp::from_request_parts(&mut parts, &())
+ .await
+ .unwrap_err();
+ assert!(matches!(err, ClientIpError::ParseErr(_)));
+}
+
+// -- ClientIpError::into_response tests --
+
+#[test]
+fn error_response_parse_err_is_400() {
+ let err: ClientIpError = "not-an-ip".parse::<IpAddr>().unwrap_err().into();
+ let response = err.into_response();
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+}
+
+#[test]
+fn error_response_invalid_ascii_is_400() {
+ let err = ClientIpError::InvalidAscii(std::str::from_utf8(b"\xff").unwrap_err());
+ let response = err.into_response();
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+}
diff --git a/rust/cloud-storage/macro_middleware/Cargo.toml b/rust/cloud-storage/macro_middleware/Cargo.toml
index ef89af8a6a..a5390e4092 100644
--- a/rust/cloud-storage/macro_middleware/Cargo.toml
+++ b/rust/cloud-storage/macro_middleware/Cargo.toml
@@ -17,13 +17,14 @@ cloud_storage = [
default = ["all"]
local_auth = []
macro_db_client = ["dep:macro_db_client", "dep:sqlx"]
-tracking = []
+tracking = ["dep:ip_extractor"]
user_permissions = ["dep:macro_user_id", "dep:user_quota", "macro_db_client"]
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, features = ["macros"] }
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" }
diff --git a/rust/cloud-storage/macro_middleware/src/tracking/mod.rs b/rust/cloud-storage/macro_middleware/src/tracking/mod.rs
index 2a1879b511..de9df2d7df 100644
--- a/rust/cloud-storage/macro_middleware/src/tracking/mod.rs
+++ b/rust/cloud-storage/macro_middleware/src/tracking/mod.rs
@@ -1,57 +1 @@
-use anyhow::Context;
-use axum::{
- Json,
- extract::Request,
- http::{HeaderMap, StatusCode},
- middleware::Next,
- response::{IntoResponse, Response},
-};
-
-use macro_env::Environment;
-use model::{response::ErrorResponse, tracking::IPContext};
-
-/// Attempts to decode the JWT and attach user to the request context
-/// If there is no JWT to decode, the user context remains empty
-pub async fn attach_ip_context_handler(mut req: Request, next: Next) -> Result<Response, Response> {
- // If running locally we automatically attach the ip context for you
- if let Environment::Local = Environment::new_or_prod() {
- req.extensions_mut().insert(IPContext {
- client_ip: std::env::var("LOCAL_IP").unwrap_or("127.0.0.1".to_string()),
- });
- return Ok(next.run(req).await);
- }
-
- let headers = req.headers();
- let client_ip = get_ip_from_x_forwarded_for(headers)
- .context("no ip provided")
- .map_err(|_| {
- (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "no ip provided",
- }),
- )
- .into_response()
- })?;
-
- // Attach user to the UserContext and to the request
- req.extensions_mut().insert(IPContext { client_ip });
-
- Ok(next.run(req).await)
-}
-
-fn get_ip_from_x_forwarded_for(headers: &HeaderMap) -> Option<String> {
- let x_forwarded_for = headers
- .get("x-forwarded-for")
- .and_then(|header| header.to_str().ok());
-
- if let Some(x_forwarded_for) = x_forwarded_for {
- let ip = x_forwarded_for
- .split(',')
- .next()
- .map(|ip| ip.trim().to_string());
- return ip;
- }
-
- None
-}
+pub use ip_extractor::*;
diff --git a/rust/cloud-storage/model/src/lib.rs b/rust/cloud-storage/model/src/lib.rs
index d17ae9467a..1faa7dc76b 100644
--- a/rust/cloud-storage/model/src/lib.rs
+++ b/rust/cloud-storage/model/src/lib.rs
@@ -19,7 +19,6 @@ pub mod request;
pub mod response;
pub mod sync_service;
pub mod thread;
-pub mod tracking;
pub mod user;
pub mod user_document_view_location;
pub mod version;
diff --git a/rust/cloud-storage/model/src/tracking.rs b/rust/cloud-storage/model/src/tracking.rs
deleted file mode 100644
index 32fcd1430d..0000000000
--- a/rust/cloud-storage/model/src/tracking.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-#[derive(serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, Debug)]
-pub struct IPContext {
- /// The client ip address
- pub client_ip: String,
-}
diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.toml
index 342faf1757..0aabf9bce2 100644
--- a/rust/cloud-storage/notification/Cargo.toml
+++ b/rust/cloud-storage/notification/Cargo.toml
@@ -62,4 +62,5 @@ uuid = { workspace = true }
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
+rate_limit = { path = "../rate_limit", features = ["testing"] }
tokio = { workspace = true, features = ["macros", "rt", "test-util"] }
diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rs
index ba9162e811..0467e687e2 100644
--- a/rust/cloud-storage/notification/src/domain/service/egress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs
@@ -212,20 +212,20 @@ where
.await
.context(DeliveryFailure::Other)?;
- match &*ticket {
- RateLimitResult::Exceeded(exceeded) => {
+ let ticket_ok = match ticket {
+ RateLimitResult::Err(exceeded) => {
return Err(report!(
- "Rate limit key: {} was exceeded. Current count is {} but max count is {}",
- exceeded.key,
+ "Rate limit key was exceeded. Current count is {} but max count is {}",
exceeded.current_count,
exceeded.max_count
)
- .context(DeliveryFailure::RateLimit(exceeded.clone())));
+ .context(DeliveryFailure::RateLimit(exceeded)));
}
- RateLimitResult::Allowed { .. } => {}
- }
+ RateLimitResult::Ok(ticket) => ticket,
+ };
- self.email
+ if let Err(e) = self
+ .email
.send_email(recipient.clone(), &content)
.await
.inspect_err(|e| {
@@ -236,12 +236,16 @@ where
"Email delivery failed"
);
})
- .context(DeliveryFailure::Other)?;
-
- self.rate_limiter
- .increment_ticket(ticket)
- .await
- .context(DeliveryFailure::Other)?;
+ {
+ let _ = self
+ .rate_limiter
+ .rollback_ticket(ticket_ok)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "Failed to rollback rate limit after email failure");
+ });
+ return Err(e.context(DeliveryFailure::Other));
+ }
Ok(DeliverySuccess::Email)
}
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index 2bdb451c73..430ef0ea8e 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -27,6 +27,7 @@ use crate::domain::service::{
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
+use rate_limit::domain::models::RateLimitOk;
use rootcause::{Report, report};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@@ -1057,27 +1058,24 @@ struct MockRateLimitPort {
impl rate_limit::RateLimitPort for MockRateLimitPort {
async fn check(
&self,
- _key: &RateLimitKey,
- config: &RateLimitConfig,
+ key: RateLimitKey,
+ config: RateLimitConfig,
) -> Result<RateLimitResult, Report> {
if self.should_exceed {
- Ok(RateLimitResult::Exceeded(RateLimitExceeded {
- key: "test_key".to_string(),
+ Ok(RateLimitResult::Err(RateLimitExceeded {
current_count: config.max_count.saturating_add(1),
max_count: config.max_count,
retry_after: config.window,
}))
} else {
- Ok(RateLimitResult::Allowed { current_count: 1 })
+ Ok(RateLimitResult::Ok(RateLimitOk::new_testing_value(
+ 1, key, config,
+ )))
}
}
- async fn increment(
- &self,
- _key: &RateLimitKey,
- _config: &RateLimitConfig,
- ) -> Result<u64, Report> {
- Ok(1)
+ async fn decrement(&self, _key: &RateLimitKey) -> Result<(), Report> {
+ Ok(())
}
}
diff --git a/rust/cloud-storage/notification_sandbox/Cargo.toml b/rust/cloud-storage/notification_sandbox/Cargo.toml
index a7dcdb0493..725e07357f 100644
--- a/rust/cloud-storage/notification_sandbox/Cargo.toml
+++ b/rust/cloud-storage/notification_sandbox/Cargo.toml
@@ -17,7 +17,7 @@ model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
models_pagination = { path = "../models_pagination" }
notification = { path = "../notification" }
-rate_limit = { path = "../rate_limit" }
+rate_limit = { path = "../rate_limit", features = ["testing"] }
redis = { workspace = true, features = [
"aio",
"tokio-comp",
diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rs b/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rs
index 264c170ee2..efc68916f5 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rs
@@ -1,4 +1,6 @@
-use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitPort, RateLimitResult};
+use rate_limit::{
+ RateLimitConfig, RateLimitKey, RateLimitPort, RateLimitResult, domain::models::RateLimitOk,
+};
use rootcause::Report;
/// Rate limit port that always allows (no-op for sandbox).
@@ -7,17 +9,15 @@ pub struct NoOpRateLimitPort;
impl RateLimitPort for NoOpRateLimitPort {
async fn check(
&self,
- _key: &RateLimitKey,
- _config: &RateLimitConfig,
+ key: RateLimitKey,
+ config: RateLimitConfig,
) -> Result<RateLimitResult, Report> {
- Ok(RateLimitResult::Allowed { current_count: 0 })
+ Ok(RateLimitResult::Ok(RateLimitOk::new_testing_value(
+ 0, key, config,
+ )))
}
- async fn increment(
- &self,
- _key: &RateLimitKey,
- _config: &RateLimitConfig,
- ) -> Result<u64, Report> {
- Ok(0)
+ async fn decrement(&self, _key: &RateLimitKey) -> Result<(), Report> {
+ Ok(())
}
}
diff --git a/rust/cloud-storage/rate_limit/Cargo.toml b/rust/cloud-storage/rate_limit/Cargo.toml
index 2bf4c13236..a268c9b804 100644
--- a/rust/cloud-storage/rate_limit/Cargo.toml
+++ b/rust/cloud-storage/rate_limit/Cargo.toml
@@ -4,7 +4,13 @@ name = "rate_limit"
publish = false
version = "0.1.0"
+[features]
+axum = ["dep:axum", "dep:axum-extra"]
+testing = []
+
[dependencies]
+axum = { workspace = true, optional = true }
+axum-extra = { workspace = true, optional = true }
hex = { workspace = true }
redis = { workspace = true, features = [
"aio",
@@ -14,6 +20,7 @@ redis = { workspace = true, features = [
rootcause = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
+
tracing = { workspace = true }
twox-hash = { version = "2" }
diff --git a/rust/cloud-storage/rate_limit/src/domain/models.rs b/rust/cloud-storage/rate_limit/src/domain/models.rs
index 137071eecc..c254d9c6dc 100644
--- a/rust/cloud-storage/rate_limit/src/domain/models.rs
+++ b/rust/cloud-storage/rate_limit/src/domain/models.rs
@@ -56,42 +56,45 @@ impl RateLimitKey {
}
}
-/// Result of a rate limit check.
-#[derive(Debug)]
-pub enum RateLimitResult {
- /// The action is allowed. Contains the current count after increment.
- Allowed {
- /// The current count after increment.
- current_count: u64,
- },
- /// The rate limit has been exceeded.
- Exceeded(RateLimitExceeded),
-}
+/// The result of checking the rate limit
+pub type RateLimitResult = Result<RateLimitOk, RateLimitExceeded>;
-/// The return value from the rate limit service
+/// The Ok value for passing the rate limit
#[derive(Debug)]
-pub struct RateLimitTicket {
- pub(crate) result: RateLimitResult,
+pub struct RateLimitOk {
+ /// the current count of the rate limit key
+ #[allow(dead_code)]
+ pub(crate) current_count: u64,
+ /// the key that was used to create this value
pub(crate) key: RateLimitKey,
+ /// the config that was used to create this value
+ #[expect(dead_code)]
pub(crate) config: RateLimitConfig,
}
-impl std::ops::Deref for RateLimitTicket {
- type Target = RateLimitResult;
-
- fn deref(&self) -> &Self::Target {
- &self.result
+#[cfg(feature = "testing")]
+impl RateLimitOk {
+ /// function which should only be used in downstream tests
+ /// constructs the value from raw parts
+ pub fn new_testing_value(
+ current_count: u64,
+ key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> Self {
+ RateLimitOk {
+ current_count,
+ key,
+ config,
+ }
}
}
/// Error returned when a rate limit is exceeded.
-#[derive(Debug, Error, Clone)]
+#[derive(Debug, Error, Clone, Copy)]
#[error(
- "Rate limit key: {key} was exceeded. Current count is {current_count} but max count is {max_count}"
+ "Rate limit key was exceeded. Current count is {current_count} but max count is {max_count}"
)]
pub struct RateLimitExceeded {
- /// The key that is exceeded.
- pub key: String,
/// The current count.
pub current_count: u64,
/// The maximum allowed count.
diff --git a/rust/cloud-storage/rate_limit/src/domain/ports.rs b/rust/cloud-storage/rate_limit/src/domain/ports.rs
index 401a56b0a4..59b1f119dd 100644
--- a/rust/cloud-storage/rate_limit/src/domain/ports.rs
+++ b/rust/cloud-storage/rate_limit/src/domain/ports.rs
@@ -4,42 +4,45 @@ use std::future::Future;
use rootcause::Report;
-use crate::domain::models::{RateLimitConfig, RateLimitKey, RateLimitResult, RateLimitTicket};
+use crate::domain::models::{RateLimitConfig, RateLimitKey, RateLimitOk, RateLimitResult};
/// Port for rate limiting operations.
pub trait RateLimitPort: Send + Sync + 'static {
- /// Check if the action is allowed without incrementing the counter.
+ /// Atomically check and increment the rate limit counter.
+ ///
+ /// If the current count is below the limit, the counter is incremented and
+ /// `Ok(RateLimitOk)` is returned. If the limit is already reached,
+ /// `Err(RateLimitExceeded)` is returned without incrementing.
///
/// The `RateLimitKey` is a hashed value - callers control what gets rate
/// limited by constructing the key from relevant data.
fn check(
&self,
- key: &RateLimitKey,
- config: &RateLimitConfig,
+ key: RateLimitKey,
+ config: RateLimitConfig,
) -> impl Future<Output = Result<RateLimitResult, Report>> + Send;
- /// Increment the rate limit counter for a key.
+ /// Decrement the rate limit counter for a key.
///
- /// Should only be called after a successful action.
- fn increment(
- &self,
- key: &RateLimitKey,
- config: &RateLimitConfig,
- ) -> impl Future<Output = Result<u64, Report>> + Send;
+ /// Used to roll back a previously counted request when the action fails.
+ fn decrement(&self, key: &RateLimitKey) -> impl Future<Output = Result<(), Report>> + Send;
}
-/// the external facing service interface, this signature enforces that users are incrementing at most 1 time per ticket read
+/// The external facing service interface.
+///
+/// `check_rate_limit` atomically checks and increments the counter.
+/// If the downstream action fails, call `rollback_ticket` to decrement.
pub trait RateLimitService: Send + Sync + 'static {
- /// check the rate limit, returning a ticket which can be used to increment the counter
+ /// Atomically check and increment the rate limit, returning a ticket on success.
fn check_rate_limit(
&self,
key: RateLimitKey,
config: RateLimitConfig,
- ) -> impl Future<Output = Result<RateLimitTicket, Report>> + Send;
+ ) -> impl Future<Output = Result<RateLimitResult, Report>> + Send;
- /// increment the counter for a given ticket
- fn increment_ticket(
+ /// Roll back a previously counted request when the action fails.
+ fn rollback_ticket(
&self,
- ticket: RateLimitTicket,
+ ticket: RateLimitOk,
) -> impl Future<Output = Result<(), Report>> + Send;
}
diff --git a/rust/cloud-storage/rate_limit/src/domain/service.rs b/rust/cloud-storage/rate_limit/src/domain/service.rs
index 77318a57a9..f43c7cea3b 100644
--- a/rust/cloud-storage/rate_limit/src/domain/service.rs
+++ b/rust/cloud-storage/rate_limit/src/domain/service.rs
@@ -1,11 +1,12 @@
use rootcause::Report;
use crate::{
- RateLimitConfig, RateLimitKey, RateLimitPort,
- domain::{models::RateLimitTicket, ports::RateLimitService},
+ RateLimitConfig, RateLimitKey, RateLimitPort, RateLimitResult,
+ domain::{models::RateLimitOk, ports::RateLimitService},
};
/// a concrete struct which implements [RateLimitService]
+#[derive(Clone)]
pub struct RateLimitServiceImpl<R> {
/// the inner impl of [RateLimitPort]
pub repo: R,
@@ -19,18 +20,13 @@ where
&self,
key: RateLimitKey,
config: RateLimitConfig,
- ) -> Result<RateLimitTicket, Report> {
- let result = self.repo.check(&key, &config).await?;
- Ok(RateLimitTicket {
- result,
- key,
- config,
- })
+ ) -> Result<RateLimitResult, Report> {
+ let result = self.repo.check(key, config).await?;
+ Ok(result)
}
#[tracing::instrument(err, skip(self))]
- async fn increment_ticket(&self, ticket: RateLimitTicket) -> Result<(), Report> {
- self.repo.increment(&ticket.key, &ticket.config).await?;
- Ok(())
+ async fn rollback_ticket(&self, ticket: RateLimitOk) -> Result<(), Report> {
+ self.repo.decrement(&ticket.key).await
}
}
diff --git a/rust/cloud-storage/rate_limit/src/inbound.rs b/rust/cloud-storage/rate_limit/src/inbound.rs
new file mode 100644
index 0000000000..76f3beac12
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/inbound.rs
@@ -0,0 +1,97 @@
+//! Defines axum integrations for the RateLimitService
+use std::marker::PhantomData;
+
+use crate::{
+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitService, domain::models::RateLimitOk,
+};
+use axum::{
+ RequestPartsExt,
+ extract::{FromRef, FromRequestParts, Request, State},
+ http::StatusCode,
+ middleware::Next,
+ response::{IntoResponse, Response},
+};
+use axum_extra::either::Either3;
+
+/// trait which allows a caller to define rate limit key via the hash impl and a config
+pub trait RateLimitExtractable<S>: FromRequestParts<S> + Send + 'static {
+ /// return the configuration for this rate limit that the key will be compared against
+ fn config() -> RateLimitConfig;
+ /// the return the rate limit key for this value
+ fn key(&self) -> RateLimitKey;
+}
+
+/// An extractor for some rate limit key, where K: Hash + FromRequestParts
+pub struct RateLimitExtractor<K, Svc> {
+ key_phantom: PhantomData<K>,
+ service_phantom: PhantomData<Svc>,
+ /// the [RateLimitOk] value which is returned, guaranteeing the rate limit is valid
+ pub rate_limit_success: RateLimitOk,
+}
+
+impl IntoResponse for RateLimitExceeded {
+ fn into_response(self) -> axum::response::Response {
+ StatusCode::TOO_MANY_REQUESTS.into_response()
+ }
+}
+
+type RateLimitErr<Rej> = Either3<Rej, RateLimitExceeded, StatusCode>;
+
+impl<K, S, Svc> FromRequestParts<S> for RateLimitExtractor<K, Svc>
+where
+ K: RateLimitExtractable<S>,
+ S: Send + Sync,
+ Svc: FromRef<S>,
+ Svc: RateLimitService,
+{
+ type Rejection = RateLimitErr<K::Rejection>;
+
+ async fn from_request_parts(
+ parts: &mut axum::http::request::Parts,
+ state: &S,
+ ) -> Result<Self, Self::Rejection> {
+ let service: Svc = FromRef::from_ref(state);
+ let key: K = parts.extract_with_state(state).await.map_err(Either3::E1)?;
+ let rate_limit_key = key.key();
+ let config = K::config();
+ let res = service
+ .check_rate_limit(rate_limit_key, config)
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "rate limit check failed"))
+ .map_err(|_| Either3::E3(StatusCode::INTERNAL_SERVER_ERROR))?;
+ match res {
+ Ok(ok) => Ok(RateLimitExtractor {
+ key_phantom: PhantomData,
+ service_phantom: PhantomData,
+ rate_limit_success: ok,
+ }),
+ Err(exceeded) => Err(Either3::E2(exceeded)),
+ }
+ }
+}
+
+/// Rate limit middleware which leverages [RateLimitExtractor] to check and asser the limit before the inner handler runs.
+/// If the response status code from the handler is 2xx, then the counter will be incremented for the rate limit.
+pub async fn rate_limit_middleware<S, K, Svc>(
+ extractable: RateLimitExtractor<K, Svc>,
+ State(service): State<Svc>,
+ req: Request,
+ next: Next,
+) -> Response
+where
+ K: RateLimitExtractable<S>,
+ S: Send + Sync,
+ Svc: FromRef<S>,
+ Svc: RateLimitService,
+{
+ let response = next.run(req).await;
+ if !response.status().is_success() {
+ let _ = service
+ .rollback_ticket(extractable.rate_limit_success)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "Failed to rollback rate limit counter in middleware")
+ });
+ }
+ response
+}
diff --git a/rust/cloud-storage/rate_limit/src/lib.rs b/rust/cloud-storage/rate_limit/src/lib.rs
index 5c17ded118..0943623f2f 100644
--- a/rust/cloud-storage/rate_limit/src/lib.rs
+++ b/rust/cloud-storage/rate_limit/src/lib.rs
@@ -5,12 +5,13 @@
//! adapter following hexagonal architecture.
pub mod domain;
+#[cfg(feature = "axum")]
+pub mod inbound;
pub mod outbound;
// Re-export key types at crate root for convenience.
pub use domain::models::{
RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitKeyBuilder, RateLimitResult,
- RateLimitTicket,
};
pub use domain::ports::{RateLimitPort, RateLimitService};
pub use domain::service::RateLimitServiceImpl;
diff --git a/rust/cloud-storage/rate_limit/src/outbound/redis.rs b/rust/cloud-storage/rate_limit/src/outbound/redis.rs
index 555ab5902a..5d2c69ec7b 100644
--- a/rust/cloud-storage/rate_limit/src/outbound/redis.rs
+++ b/rust/cloud-storage/rate_limit/src/outbound/redis.rs
@@ -3,17 +3,27 @@
#[cfg(test)]
mod test;
-use redis::AsyncCommands;
use rootcause::Report;
-use crate::domain::models::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult};
+use crate::domain::models::{
+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitOk, RateLimitResult,
+};
use crate::domain::ports::RateLimitPort;
+/// Redis key prefix for rate limit counters.
+const KEY_PREFIX: &str = "rtl";
+
+/// Format a [`RateLimitKey`] into the Redis key string used for storage.
+fn redis_key(key: &RateLimitKey) -> String {
+ format!("{KEY_PREFIX}:{}", key.to_hex_string())
+}
+
/// Redis-based implementation of the rate limit port.
///
/// This adapter uses Redis to store and check rate limit counters.
/// The key is provided by the caller (already hashed), and this adapter
/// handles the Redis operations.
+#[derive(Clone)]
pub struct RedisRateLimitAdapter<R> {
/// the inner redis client
pub redis: R,
@@ -23,87 +33,113 @@ pub struct RedisRateLimitAdapter<R> {
///
/// This allows the adapter to work with different Redis client implementations.
pub trait RedisRateLimitOps {
- /// Get the current count for a key.
- fn get_count(
+ /// Atomically check the rate limit and increment if allowed.
+ ///
+ /// Uses a Lua script to avoid TOCTOU races between reading the count and
+ /// incrementing. Returns `(allowed, current_count, ttl_seconds_if_denied)`.
+ fn check_and_increment(
&self,
key: &str,
- ) -> impl std::future::Future<Output = Result<Option<u64>, Report>> + Send;
+ max_count: u64,
+ expiry_seconds: u64,
+ ) -> impl std::future::Future<Output = Result<(bool, u64, Option<u64>), Report>> + Send;
- /// Get the remaining TTL in seconds for a key. Returns `None` if the key
- /// does not exist or has no expiry.
- fn get_ttl(
- &self,
- key: &str,
- ) -> impl std::future::Future<Output = Result<Option<u64>, Report>> + Send;
+ /// Decrement the counter for a key, flooring at zero.
+ fn decrement(&self, key: &str) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+}
- /// Increment a key and set expiry if it's new.
- fn increment_with_expiry(
+impl RedisRateLimitOps for redis::Client {
+ async fn check_and_increment(
&self,
key: &str,
+ max_count: u64,
expiry_seconds: u64,
- ) -> impl std::future::Future<Output = Result<u64, Report>> + Send;
-}
-
-impl RedisRateLimitOps for redis::Client {
- async fn get_count(&self, key: &str) -> Result<Option<u64>, Report> {
+ ) -> Result<(bool, u64, Option<u64>), Report> {
let mut conn = self.get_multiplexed_async_connection().await?;
- let count: Option<u64> = conn.get(key).await?;
- Ok(count)
- }
- async fn get_ttl(&self, key: &str) -> Result<Option<u64>, Report> {
- let mut conn = self.get_multiplexed_async_connection().await?;
- let ttl: i64 = conn.ttl(key).await?;
- // Redis returns -2 if key doesn't exist, -1 if no expiry
- Ok(if ttl > 0 { Some(ttl as u64) } else { None })
+ let script = redis::Script::new(
+ r"
+ local key = KEYS[1]
+ local max_count = tonumber(ARGV[1])
+ local window = tonumber(ARGV[2])
+ local current = tonumber(redis.call('GET', key) or '0')
+ if current >= max_count then
+ local ttl = redis.call('TTL', key)
+ if ttl < 0 then ttl = 0 end
+ return {0, current, ttl}
+ end
+ local new_count = redis.call('INCR', key)
+ if new_count == 1 then
+ redis.call('EXPIRE', key, window)
+ end
+ return {1, new_count, 0}
+ ",
+ );
+
+ let (allowed, count, ttl): (i64, i64, i64) = script
+ .key(key)
+ .arg(max_count)
+ .arg(expiry_seconds)
+ .invoke_async(&mut conn)
+ .await?;
+
+ let ttl = if ttl > 0 { Some(ttl as u64) } else { None };
+ Ok((allowed == 1, count as u64, ttl))
}
- async fn increment_with_expiry(&self, key: &str, expiry_seconds: u64) -> Result<u64, Report> {
+ async fn decrement(&self, key: &str) -> Result<(), Report> {
let mut conn = self.get_multiplexed_async_connection().await?;
- // Use atomic pipeline: INCR + EXPIRE
- let (new_count,): (u64,) = redis::pipe()
- .atomic()
- .incr(key, 1u64)
- .expire(key, expiry_seconds as i64)
- .ignore()
- .query_async(&mut conn)
- .await?;
-
- Ok(new_count)
+ // DECR but floor at 0 to avoid negative counts
+ let script = redis::Script::new(
+ r"
+ local key = KEYS[1]
+ local current = tonumber(redis.call('GET', key) or '0')
+ if current > 0 then
+ redis.call('DECR', key)
+ end
+ return 0
+ ",
+ );
+
+ script.key(key).invoke_async::<i64>(&mut conn).await?;
+
+ Ok(())
}
}
impl<R: RedisRateLimitOps + Send + Sync + 'static> RateLimitPort for RedisRateLimitAdapter<R> {
async fn check(
&self,
- key: &RateLimitKey,
- config: &RateLimitConfig,
+ key: RateLimitKey,
+ config: RateLimitConfig,
) -> Result<RateLimitResult, Report> {
- let key_str = format!("rtl:{}", key.to_hex_string());
+ let key_str = redis_key(&key);
- let current_count = self.redis.get_count(&key_str).await?.unwrap_or(0);
+ let (allowed, current_count, ttl) = self
+ .redis
+ .check_and_increment(&key_str, config.max_count, config.window.as_secs())
+ .await?;
- if current_count >= config.max_count {
- let ttl = self.redis.get_ttl(&key_str).await?;
+ if allowed {
+ Ok(RateLimitResult::Ok(RateLimitOk {
+ current_count,
+ key,
+ config,
+ }))
+ } else {
let retry_after =
std::time::Duration::from_secs(ttl.unwrap_or(config.window.as_secs()));
- Ok(RateLimitResult::Exceeded(RateLimitExceeded {
- key: key_str,
+ Ok(RateLimitResult::Err(RateLimitExceeded {
current_count,
max_count: config.max_count,
retry_after,
}))
- } else {
- Ok(RateLimitResult::Allowed { current_count })
}
}
- async fn increment(&self, key: &RateLimitKey, config: &RateLimitConfig) -> Result<u64, Report> {
- let key_str = format!("rtl:{}", key.to_hex_string());
- let expiry_seconds = config.window.as_secs();
- self.redis
- .increment_with_expiry(&key_str, expiry_seconds)
- .await
+ async fn decrement(&self, key: &RateLimitKey) -> Result<(), Report> {
+ let key_str = redis_key(key);
+ self.redis.decrement(&key_str).await
}
}
diff --git a/rust/cloud-storage/rate_limit/src/outbound/redis/test.rs b/rust/cloud-storage/rate_limit/src/outbound/redis/test.rs
index 9704b4de2b..2f9c6d92a3 100644
--- a/rust/cloud-storage/rate_limit/src/outbound/redis/test.rs
+++ b/rust/cloud-storage/rate_limit/src/outbound/redis/test.rs
@@ -1,7 +1,7 @@
use std::time::Duration;
use crate::{
- RateLimitConfig, RateLimitKey, RateLimitResult, RateLimitServiceImpl,
+ RateLimitConfig, RateLimitKey, RateLimitPort, RateLimitResult, RateLimitServiceImpl,
domain::ports::RateLimitService, outbound::redis::RedisRateLimitAdapter,
};
@@ -14,14 +14,16 @@ fn unique_key(name: &str) -> RateLimitKey {
RateLimitKey::builder(&format!("test_{name}_{}", uuid::Uuid::new_v4())).finish()
}
-fn service() -> RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>> {
- RateLimitServiceImpl {
- repo: RedisRateLimitAdapter {
- redis: redis_client(),
- },
+fn adapter() -> RedisRateLimitAdapter<redis::Client> {
+ RedisRateLimitAdapter {
+ redis: redis_client(),
}
}
+fn service() -> RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>> {
+ RateLimitServiceImpl { repo: adapter() }
+}
+
#[tokio::test]
async fn retry_after_is_populated_when_rate_limit_exceeded() {
let svc = service();
@@ -31,15 +33,12 @@ async fn retry_after_is_populated_when_rate_limit_exceeded() {
window: Duration::from_secs(30),
};
- // First request succeeds and increments the counter.
+ // First request succeeds (check atomically increments the counter).
let ticket = svc
.check_rate_limit(key.clone(), config.clone())
.await
.expect("check_rate_limit failed");
- assert!(matches!(&*ticket, RateLimitResult::Allowed { .. }));
- svc.increment_ticket(ticket)
- .await
- .expect("increment_ticket failed");
+ assert!(ticket.is_ok(), "first request should be allowed");
// Second request should be exceeded.
let ticket = svc
@@ -47,8 +46,8 @@ async fn retry_after_is_populated_when_rate_limit_exceeded() {
.await
.expect("check_rate_limit failed");
- match &*ticket {
- RateLimitResult::Exceeded(exceeded) => {
+ match ticket {
+ RateLimitResult::Err(exceeded) => {
assert!(
!exceeded.retry_after.is_zero(),
"retry_after should be non-zero"
@@ -60,7 +59,7 @@ async fn retry_after_is_populated_when_rate_limit_exceeded() {
config.window,
);
}
- RateLimitResult::Allowed { .. } => {
+ RateLimitResult::Ok(_) => {
panic!("expected rate limit to be exceeded after max_count requests");
}
}
@@ -75,20 +74,20 @@ async fn retry_after_decreases_over_time() {
window: Duration::from_secs(30),
};
- // Exhaust the rate limit.
+ // Exhaust the rate limit (check atomically increments).
let ticket = svc
.check_rate_limit(key.clone(), config.clone())
.await
.unwrap();
- svc.increment_ticket(ticket).await.unwrap();
+ assert!(ticket.is_ok(), "first request should be allowed");
// Check immediately.
let ticket = svc
.check_rate_limit(key.clone(), config.clone())
.await
.unwrap();
- let first_retry_after = match &*ticket {
- RateLimitResult::Exceeded(e) => e.retry_after,
+ let first_retry_after = match ticket {
+ RateLimitResult::Err(e) => e.retry_after,
_ => panic!("expected exceeded"),
};
@@ -96,8 +95,8 @@ async fn retry_after_decreases_over_time() {
tokio::time::sleep(Duration::from_secs(2)).await;
let ticket = svc.check_rate_limit(key, config).await.unwrap();
- let second_retry_after = match &*ticket {
- RateLimitResult::Exceeded(e) => e.retry_after,
+ let second_retry_after = match ticket {
+ RateLimitResult::Err(e) => e.retry_after,
_ => panic!("expected exceeded"),
};
@@ -106,3 +105,177 @@ async fn retry_after_decreases_over_time() {
"retry_after should decrease over time: first={first_retry_after:?}, second={second_retry_after:?}",
);
}
+
+#[tokio::test]
+async fn check_atomically_increments_counter() {
+ let adapter = adapter();
+ let key = unique_key("atomic_incr");
+ let config = RateLimitConfig {
+ max_count: 3,
+ window: Duration::from_secs(30),
+ };
+
+ // Each check should atomically increment, consuming one slot.
+ for i in 1..=3 {
+ let result = adapter.check(key.clone(), config.clone()).await.unwrap();
+ match result {
+ RateLimitResult::Ok(ok) => {
+ assert_eq!(ok.current_count, i, "count after check #{i}");
+ }
+ RateLimitResult::Err(_) => panic!("check #{i} should be allowed"),
+ }
+ }
+
+ // Fourth check should be denied without incrementing past 3.
+ let result = adapter.check(key.clone(), config.clone()).await.unwrap();
+ match result {
+ RateLimitResult::Err(exceeded) => {
+ assert_eq!(exceeded.current_count, 3);
+ assert_eq!(exceeded.max_count, 3);
+ }
+ RateLimitResult::Ok(_) => panic!("fourth check should be denied"),
+ }
+}
+
+#[tokio::test]
+async fn denied_check_does_not_increment() {
+ let client = redis_client();
+ let key = unique_key("denied_no_incr");
+ let key_str = super::redis_key(&key);
+ let config = RateLimitConfig {
+ max_count: 1,
+ window: Duration::from_secs(30),
+ };
+ let adapter = adapter();
+
+ // Exhaust the limit.
+ let result = adapter.check(key.clone(), config.clone()).await.unwrap();
+ assert!(result.is_ok());
+
+ // Hammer the key with denied checks.
+ for _ in 0..5 {
+ let result = adapter.check(key.clone(), config.clone()).await.unwrap();
+ assert!(result.is_err());
+ }
+
+ // Counter should still be 1 — denied checks must not increment.
+ let count: Option<u64> = redis::AsyncCommands::get(
+ &mut client.get_multiplexed_async_connection().await.unwrap(),
+ &key_str,
+ )
+ .await
+ .unwrap();
+ assert_eq!(count, Some(1), "counter should not grow past limit");
+}
+
+#[tokio::test]
+async fn rollback_frees_a_slot() {
+ let svc = service();
+ let key = unique_key("rollback");
+ let config = RateLimitConfig {
+ max_count: 1,
+ window: Duration::from_secs(30),
+ };
+
+ // Use the one allowed slot.
+ let ticket = svc
+ .check_rate_limit(key.clone(), config.clone())
+ .await
+ .unwrap()
+ .expect("first check should succeed");
+
+ // Now the limit is reached.
+ let result = svc
+ .check_rate_limit(key.clone(), config.clone())
+ .await
+ .unwrap();
+ assert!(result.is_err(), "should be denied after exhausting limit");
+
+ // Roll back the ticket (simulating a failed downstream action).
+ svc.rollback_ticket(ticket).await.unwrap();
+
+ // The slot should be free again.
+ let result = svc
+ .check_rate_limit(key.clone(), config.clone())
+ .await
+ .unwrap();
+ assert!(result.is_ok(), "should be allowed after rollback");
+}
+
+#[tokio::test]
+async fn rollback_does_not_go_below_zero() {
+ let client = redis_client();
+ let adapter = adapter();
+ let key = unique_key("rollback_floor");
+ let key_str = super::redis_key(&key);
+
+ // Decrement on a key that was never incremented.
+ adapter.decrement(&key).await.unwrap();
+
+ let count: Option<u64> = redis::AsyncCommands::get(
+ &mut client.get_multiplexed_async_connection().await.unwrap(),
+ &key_str,
+ )
+ .await
+ .unwrap();
+ assert!(
+ count.is_none() || count == Some(0),
+ "counter should not go negative, got {count:?}"
+ );
+}
+
+#[tokio::test]
+async fn concurrent_checks_do_not_exceed_limit() {
+ let key = unique_key("concurrent");
+ let config = RateLimitConfig {
+ max_count: 5,
+ window: Duration::from_secs(30),
+ };
+
+ // Spawn 20 concurrent checks against a limit of 5.
+ let mut handles = Vec::new();
+ for _ in 0..20 {
+ let adapter = adapter();
+ let k = key.clone();
+ let c = config.clone();
+ handles.push(tokio::spawn(async move { adapter.check(k, c).await }));
+ }
+
+ let mut allowed = 0u64;
+ let mut denied = 0u64;
+ for handle in handles {
+ let result = handle.await.unwrap().unwrap();
+ match result {
+ RateLimitResult::Ok(_) => allowed += 1,
+ RateLimitResult::Err(_) => denied += 1,
+ }
+ }
+
+ assert_eq!(allowed, 5, "exactly max_count requests should be allowed");
+ assert_eq!(denied, 15, "the rest should be denied");
+}
+
+#[tokio::test]
+async fn check_and_increment_sets_expiry_on_first_key() {
+ let client = redis_client();
+ let key = unique_key("expiry");
+ let key_str = super::redis_key(&key);
+ let config = RateLimitConfig {
+ max_count: 10,
+ window: Duration::from_secs(60),
+ };
+ let adapter = adapter();
+
+ let _ = adapter.check(key, config).await.unwrap();
+
+ let ttl: i64 = redis::AsyncCommands::ttl(
+ &mut client.get_multiplexed_async_connection().await.unwrap(),
+ &key_str,
+ )
+ .await
+ .unwrap();
+ assert!(
+ ttl > 0 && ttl <= 60,
+ "key should have a TTL within the window, got {ttl}"
+ );
+}
diff --git a/rust/cloud-storage/referral/Cargo.toml b/rust/cloud-storage/referral/Cargo.toml
index 5005479d07..e03c96e8ca 100644
--- a/rust/cloud-storage/referral/Cargo.toml
+++ b/rust/cloud-storage/referral/Cargo.toml
@@ -8,8 +8,10 @@ version = "0.1.0"
axum = [
"dep:axum",
"dep:axum-extra",
+ "dep:ip_extractor",
"dep:model-error-response",
"dep:model_user",
+ "dep:tower",
"dep:utoipa",
]
default = ["axum", "inbound", "outbound", "ports"]
@@ -33,14 +35,16 @@ macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model-entity = { path = "../model-entity" }
notification = { path = "../notification" }
-rate_limit = { path = "../rate_limit" }
+rate_limit = { path = "../rate_limit", features = ["axum"] }
referral_invitation = { path = "../referral_invitation" }
# Axum dependencies (for inbound)
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
+ip_extractor = { path = "../ip_extractor", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
+tower = { workspace = true, optional = true }
utoipa = { workspace = true, optional = true }
@@ -53,10 +57,10 @@ sqlx = { workspace = true, optional = true }
urlencoding = { workspace = true }
[dev-dependencies]
-
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
+rate_limit = { path = "../rate_limit", features = ["axum", "testing"] }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
tower = { workspace = true }
diff --git a/rust/cloud-storage/referral/src/domain/service.rs b/rust/cloud-storage/referral/src/domain/service.rs
index 0efa624034..10393bbd77 100644
--- a/rust/cloud-storage/referral/src/domain/service.rs
+++ b/rust/cloud-storage/referral/src/domain/service.rs
@@ -3,7 +3,7 @@
#[cfg(test)]
mod test;
-use std::{collections::HashSet, ops::Deref, time::Duration};
+use std::{collections::HashSet, ops::Deref};
use macro_user_id::{
email::EmailStr,
@@ -12,7 +12,6 @@ use macro_user_id::{
};
use model_entity::EntityType;
use notification::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress};
-use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitResult, domain::ports::RateLimitService};
use rootcause::compat::boxed_error::IntoBoxedError;
use crate::domain::{
@@ -21,13 +20,11 @@ use crate::domain::{
};
/// The concrete referral service implementation.
-pub struct ReferralServiceImpl<R, Dc, Rl, N> {
+pub struct ReferralServiceImpl<R, Dc, N> {
/// referral repo
pub repo: R,
/// discount client
pub discount_client: Dc,
- /// rate limiter service
- pub rate_limit: Rl,
/// the notification sender
pub notification_ingress: N,
}
@@ -35,56 +32,10 @@ pub struct ReferralServiceImpl<R, Dc, Rl, N> {
impl<
R: ReferralRepo,
Dc: DiscountClient,
- Rl: RateLimitService,
// the constructor for this is Arc<NI> so we use a different bound here
N: Deref<Target = NI> + Send + Sync + 'static,
NI: NotificationIngress,
-> ReferralServiceImpl<R, Dc, Rl, N>
-{
- async fn send_referral_invite_inner(
- &self,
- sending_user: MacroUserIdStr<'_>,
- recipient: EmailStr<'static>,
- ) -> Result<(), ReferralError> {
- let referral_code = self.get_referral_code_for_user(&sending_user.0).await?;
-
- let notification = InviteToMacro {
- recipient_email: recipient.clone(),
- referral_code,
- };
-
- let _res = self
- .notification_ingress
- .send_notification(
- SendNotificationRequestBuilder {
- notification_entity: EntityType::User
- .with_entity_string(sending_user.as_ref().to_string()),
- notification,
- sender_id: Some(sending_user),
- recipient_ids: HashSet::from([MacroUserIdStr::try_from_email(
- recipient.0.as_ref(),
- )
- .map_err(anyhow::Error::from)?]),
- }
- .into_request()
- .with_email(),
- )
- .await
- .map_err(|r| r.into_boxed_error())
- .map_err(anyhow::Error::from_boxed)?;
-
- Ok(())
- }
-}
-
-impl<
- R: ReferralRepo,
- Dc: DiscountClient,
- Rl: RateLimitService,
- // the constructor for this is Arc<NI> so we use a different bound here
- N: Deref<Target = NI> + Send + Sync + 'static,
- NI: NotificationIngress,
-> ReferralService for ReferralServiceImpl<R, Dc, Rl, N>
+> ReferralService for ReferralServiceImpl<R, Dc, N>
{
#[tracing::instrument(skip(self), err)]
async fn get_referral_code_for_user<'a>(
@@ -147,37 +98,39 @@ impl<
Ok(())
}
+ #[tracing::instrument(skip(self), err)]
async fn send_referral_invite(
&self,
sending_user: MacroUserIdStr<'_>,
recipient: EmailStr<'static>,
) -> Result<(), ReferralError> {
- let user_rate_limit = RateLimitKey::builder(&"user_sent_invites")
- .append(&sending_user.as_ref())
- .finish();
- let ticket = self
- .rate_limit
- .check_rate_limit(user_rate_limit, RATE_LIMIT_CONFIG_PER_USER.clone())
+ let referral_code = self.get_referral_code_for_user(&sending_user.0).await?;
+
+ let notification = InviteToMacro {
+ recipient_email: recipient.clone(),
+ referral_code,
+ };
+
+ let _res = self
+ .notification_ingress
+ .send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: EntityType::User
+ .with_entity_string(sending_user.as_ref().to_string()),
+ notification,
+ sender_id: Some(sending_user),
+ recipient_ids: HashSet::from([MacroUserIdStr::try_from_email(
+ recipient.0.as_ref(),
+ )
+ .map_err(anyhow::Error::from)?]),
+ }
+ .into_request()
+ .with_email(),
+ )
.await
.map_err(|r| r.into_boxed_error())
.map_err(anyhow::Error::from_boxed)?;
- if let RateLimitResult::Exceeded(err) = &*ticket {
- return Err(ReferralError::RateLimitExceeded(err.clone()));
- }
-
- let () = self
- .send_referral_invite_inner(sending_user, recipient)
- .await?;
-
- let _ = self.rate_limit.increment_ticket(ticket).await;
-
Ok(())
}
}
-
-/// The fixed window rate limit config for the number of invites a user can send to others
-const RATE_LIMIT_CONFIG_PER_USER: RateLimitConfig = RateLimitConfig {
- max_count: 50,
- window: Duration::from_mins(60),
-};
diff --git a/rust/cloud-storage/referral/src/domain/service/test.rs b/rust/cloud-storage/referral/src/domain/service/test.rs
index c6eebab165..10220fbb45 100644
--- a/rust/cloud-storage/referral/src/domain/service/test.rs
+++ b/rust/cloud-storage/referral/src/domain/service/test.rs
@@ -4,9 +4,6 @@ use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use notification::domain::{
models::SendNotificationRequest, service::NotificationIngress, service::SendNotificationError,
};
-use rate_limit::{
- RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult, RateLimitServiceImpl,
-};
use rootcause::Report;
use crate::domain::{
@@ -46,55 +43,6 @@ impl Deref for MockNotificationIngress {
}
}
-// -- Mock RateLimitPort --
-
-struct MockRateLimitPort {
- should_exceed: bool,
-}
-
-impl rate_limit::RateLimitPort for MockRateLimitPort {
- async fn check(
- &self,
- _key: &RateLimitKey,
- config: &RateLimitConfig,
- ) -> Result<RateLimitResult, Report> {
- if self.should_exceed {
- Ok(RateLimitResult::Exceeded(RateLimitExceeded {
- key: "test_key".to_string(),
- current_count: config.max_count.saturating_add(1),
- max_count: config.max_count,
- retry_after: config.window,
- }))
- } else {
- Ok(RateLimitResult::Allowed { current_count: 1 })
- }
- }
-
- async fn increment(
- &self,
- _key: &RateLimitKey,
- _config: &RateLimitConfig,
- ) -> Result<u64, Report> {
- Ok(1)
- }
-}
-
-fn allowing_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {
- RateLimitServiceImpl {
- repo: MockRateLimitPort {
- should_exceed: false,
- },
- }
-}
-
-fn exceeding_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {
- RateLimitServiceImpl {
- repo: MockRateLimitPort {
- should_exceed: true,
- },
- }
-}
-
fn mock_repo() -> MockReferralRepo {
let mut repo = MockReferralRepo::new();
repo.expect_get_referral_code_for_user().returning(|_| {
@@ -107,18 +55,11 @@ fn mock_discount_client() -> MockDiscountClient {
MockDiscountClient::new()
}
-fn build_service(
- rate_limiter: RateLimitServiceImpl<MockRateLimitPort>,
-) -> ReferralServiceImpl<
- MockReferralRepo,
- MockDiscountClient,
- RateLimitServiceImpl<MockRateLimitPort>,
- MockNotificationIngress,
-> {
+fn build_service()
+-> ReferralServiceImpl<MockReferralRepo, MockDiscountClient, MockNotificationIngress> {
ReferralServiceImpl {
repo: mock_repo(),
discount_client: mock_discount_client(),
- rate_limit: rate_limiter,
notification_ingress: MockNotificationIngress(MockNotificationIngressInner),
}
}
@@ -133,7 +74,7 @@ fn test_recipient() -> EmailStr<'static> {
#[tokio::test]
async fn send_referral_invite_succeeds_when_under_rate_limit() {
- let service = build_service(allowing_rate_limiter());
+ let service = build_service();
let result: Result<(), ReferralError> = service
.send_referral_invite(test_user(), test_recipient())
@@ -142,46 +83,9 @@ async fn send_referral_invite_succeeds_when_under_rate_limit() {
assert!(result.is_ok());
}
-#[tokio::test]
-async fn send_referral_invite_fails_when_rate_limit_exceeded() {
- let service = build_service(exceeding_rate_limiter());
-
- let result: Result<(), ReferralError> = service
- .send_referral_invite(test_user(), test_recipient())
- .await;
-
- assert!(result.is_err());
- assert!(
- matches!(result.unwrap_err(), ReferralError::RateLimitExceeded(_)),
- "expected RateLimitExceeded error"
- );
-}
-
-#[tokio::test]
-async fn rate_limit_error_contains_exceeded_info() {
- let service = build_service(exceeding_rate_limiter());
-
- let err = service
- .send_referral_invite(test_user(), test_recipient())
- .await
- .unwrap_err();
-
- match err {
- ReferralError::RateLimitExceeded(exceeded) => {
- assert!(
- exceeded.current_count > exceeded.max_count,
- "current_count ({}) should exceed max_count ({})",
- exceeded.current_count,
- exceeded.max_count,
- );
- }
- other => panic!("expected RateLimitExceeded, got: {other:?}"),
- }
-}
-
#[tokio::test]
async fn multiple_invites_succeed_when_under_rate_limit() {
- let service = build_service(allowing_rate_limiter());
+ let service = build_service();
for i in 0..5 {
let recipient = EmailStr::try_from(format!("recipient{i}@example.com")).unwrap();
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router.rs b/rust/cloud-storage/referral/src/inbound/axum_router.rs
index f30b2feb84..91be5db6f8 100644
--- a/rust/cloud-storage/referral/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/referral/src/inbound/axum_router.rs
@@ -3,22 +3,21 @@
//! Provides routes:
//! - `GET /code` — get the authenticated user's referral code
-#[cfg(test)]
-mod test;
-
-mod get_referral_code;
-mod send_invite;
-
-use std::sync::Arc;
-
-use axum::{Json, Router, http::StatusCode, response::IntoResponse};
-use model_error_response::ErrorResponse;
-
use crate::domain::models::ReferralError;
use crate::domain::ports::ReferralService;
-
+use axum::{Json, Router, http::StatusCode, response::IntoResponse};
pub use get_referral_code::*;
+use model_error_response::ErrorResponse;
+use rate_limit::RateLimitService;
+use rate_limit::inbound::rate_limit_middleware;
pub use send_invite::*;
+use std::sync::Arc;
+use tower::ServiceBuilder;
+
+mod get_referral_code;
+mod send_invite;
+#[cfg(test)]
+mod test;
impl IntoResponse for ReferralError {
fn into_response(self) -> axum::response::Response {
@@ -43,30 +42,48 @@ impl IntoResponse for ReferralError {
}
/// Router state containing the referral service.
-pub struct ReferralRouterState<T> {
+pub struct ReferralRouterState<T, R> {
/// The referral service implementation.
pub service: Arc<T>,
+ /// the rate limiter service implementation
+ pub rate_limiter: R,
}
-impl<T> Clone for ReferralRouterState<T> {
+impl<T, R: Clone> Clone for ReferralRouterState<T, R> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
+ rate_limiter: self.rate_limiter.clone(),
}
}
}
/// Build the referral router with all endpoints.
-pub fn referral_router<T, S>(state: ReferralRouterState<T>) -> Router<S>
+pub fn referral_router<T, S, R>(state: ReferralRouterState<T, R>) -> Router<S>
where
T: ReferralService,
+ R: RateLimitService + Clone,
S: Send + Sync + 'static,
{
Router::new()
.route(
"/send",
- axum::routing::post(post_referral_invite_handler::<T>),
+ axum::routing::post(post_referral_invite_handler::<T, R>),
+ )
+ .layer(
+ ServiceBuilder::new()
+ .layer(axum::middleware::from_fn_with_state(
+ state.rate_limiter.clone(),
+ rate_limit_middleware::<R, PerUserReferralRateLimit, R>,
+ ))
+ .layer(axum::middleware::from_fn_with_state(
+ state.rate_limiter.clone(),
+ rate_limit_middleware::<R, PerIpReferralRateLimit, R>,
+ )),
+ )
+ .route(
+ "/code",
+ axum::routing::get(get_referral_code_handler::<T, R>),
)
- .route("/code", axum::routing::get(get_referral_code_handler::<T>))
.with_state(state)
}
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs b/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs
index c63d960506..add721ad0d 100644
--- a/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs
@@ -22,8 +22,8 @@ use crate::domain::ports::ReferralService;
)
)]
#[tracing::instrument(skip(state, user_context), err)]
-pub async fn get_referral_code_handler<T: ReferralService>(
- State(state): State<ReferralRouterState<T>>,
+pub async fn get_referral_code_handler<T: ReferralService, R>(
+ State(state): State<ReferralRouterState<T, R>>,
user_context: MacroUserExtractor,
) -> Result<Json<ReferralCode>, ReferralError> {
let code = state
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/send_invite.rs b/rust/cloud-storage/referral/src/inbound/axum_router/send_invite.rs
index bdfefd9f63..95e1e30b11 100644
--- a/rust/cloud-storage/referral/src/inbound/axum_router/send_invite.rs
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/send_invite.rs
@@ -1,10 +1,17 @@
//! Handler for `POST /send`.
+use axum::RequestPartsExt;
+use axum::extract::FromRequestParts;
use axum::http::StatusCode;
use axum::{Json, extract::State};
+use axum_extra::extract::Cached;
+use ip_extractor::ClientIp;
use macro_user_id::email::EmailStr;
use model_user::axum_extractor::MacroUserExtractor;
+use rate_limit::inbound::RateLimitExtractable;
+use rate_limit::{RateLimitConfig, RateLimitKey};
use serde::Deserialize;
+use std::time::Duration;
use super::ReferralRouterState;
use crate::domain::models::ReferralError;
@@ -33,9 +40,9 @@ pub struct SendInviteBody {
)
)]
#[tracing::instrument(skip(state, user_context), err)]
-pub async fn post_referral_invite_handler<T: ReferralService>(
- State(state): State<ReferralRouterState<T>>,
- user_context: MacroUserExtractor,
+pub async fn post_referral_invite_handler<T: ReferralService, R>(
+ State(state): State<ReferralRouterState<T, R>>,
+ Cached(user_context): Cached<MacroUserExtractor>,
Json(SendInviteBody { recipient }): Json<SendInviteBody>,
) -> Result<StatusCode, ReferralError> {
let () = state
@@ -45,3 +52,77 @@ pub async fn post_referral_invite_handler<T: ReferralService>(
Ok(StatusCode::NO_CONTENT)
}
+
+/// the rate limit definition for the per-user rate limit on referring new users
+pub struct PerUserReferralRateLimit(MacroUserExtractor);
+
+impl<S> RateLimitExtractable<S> for PerUserReferralRateLimit
+where
+ S: Send + Sync,
+{
+ fn config() -> rate_limit::RateLimitConfig {
+ // The fixed window rate limit config for the number of invites a user can send to others
+ RateLimitConfig {
+ max_count: 50,
+ window: Duration::from_mins(60),
+ }
+ }
+
+ fn key(&self) -> rate_limit::RateLimitKey {
+ RateLimitKey::builder(&"per-user-referral")
+ .append(&self.0.macro_user_id.as_ref())
+ .finish()
+ }
+}
+
+impl<S> FromRequestParts<S> for PerUserReferralRateLimit
+where
+ S: Send + Sync,
+{
+ type Rejection = <MacroUserExtractor as FromRequestParts<S>>::Rejection;
+
+ async fn from_request_parts(
+ parts: &mut axum::http::request::Parts,
+ state: &S,
+ ) -> Result<Self, Self::Rejection> {
+ let Cached(user): Cached<MacroUserExtractor> = parts.extract_with_state(state).await?;
+ Ok(Self(user))
+ }
+}
+
+/// The struct which impl [RateLimitExtractable] to limit the number of per-ip requests
+/// for the send invite route
+pub struct PerIpReferralRateLimit(ClientIp);
+
+impl<S> RateLimitExtractable<S> for PerIpReferralRateLimit
+where
+ S: Send + Sync,
+{
+ fn config() -> RateLimitConfig {
+ RateLimitConfig {
+ max_count: 50,
+ window: Duration::from_mins(60),
+ }
+ }
+
+ fn key(&self) -> RateLimitKey {
+ RateLimitKey::builder(&"per-ip-referral")
+ .append(&self.0.origin_ip())
+ .finish()
+ }
+}
+
+impl<S> FromRequestParts<S> for PerIpReferralRateLimit
+where
+ S: Send + Sync,
+{
+ type Rejection = <ClientIp as FromRequestParts<S>>::Rejection;
+
+ async fn from_request_parts(
+ parts: &mut axum::http::request::Parts,
+ state: &S,
+ ) -> Result<Self, Self::Rejection> {
+ let ip: ClientIp = parts.extract_with_state(state).await?;
+ Ok(Self(ip))
+ }
+}
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/test.rs b/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
index 0b112ff86c..b99583418d 100644
--- a/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
@@ -1,8 +1,14 @@
+use std::net::SocketAddr;
use std::sync::Arc;
-use axum::{Extension, http::StatusCode};
+use axum::{Extension, extract::ConnectInfo, http::StatusCode};
use http_body_util::BodyExt;
use model_user::UserContext;
+use rate_limit::{
+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult, RateLimitServiceImpl,
+ domain::models::RateLimitOk,
+};
+use rootcause::Report;
use tower::ServiceExt;
use crate::domain::models::{ReferralCode, ReferralError};
@@ -56,7 +62,50 @@ impl ReferralService for MockReferralService {
_sending_user: macro_user_id::user_id::MacroUserIdStr<'_>,
_recipient: macro_user_id::email::EmailStr<'static>,
) -> Result<(), ReferralError> {
- todo!()
+ Ok(())
+ }
+}
+
+#[derive(Clone)]
+struct MockRateLimitPort {
+ should_exceed: bool,
+}
+
+impl rate_limit::RateLimitPort for MockRateLimitPort {
+ async fn check(
+ &self,
+ key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> Result<RateLimitResult, Report> {
+ if self.should_exceed {
+ Ok(Err(RateLimitExceeded {
+ current_count: config.max_count.saturating_add(1),
+ max_count: config.max_count,
+ retry_after: config.window,
+ }))
+ } else {
+ Ok(Ok(RateLimitOk::new_testing_value(0, key, config)))
+ }
+ }
+
+ async fn decrement(&self, _key: &RateLimitKey) -> Result<(), Report> {
+ Ok(())
+ }
+}
+
+fn allowing_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {
+ RateLimitServiceImpl {
+ repo: MockRateLimitPort {
+ should_exceed: false,
+ },
+ }
+}
+
+fn exceeding_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {
+ RateLimitServiceImpl {
+ repo: MockRateLimitPort {
+ should_exceed: true,
+ },
}
}
@@ -69,19 +118,31 @@ fn test_user_context() -> UserContext {
}
}
-fn build_router(service: MockReferralService) -> axum::Router {
+fn build_router(
+ service: MockReferralService,
+ rate_limiter: RateLimitServiceImpl<MockRateLimitPort>,
+) -> axum::Router {
let state = ReferralRouterState {
service: Arc::new(service),
+ rate_limiter,
};
- referral_router(state).layer(Extension(test_user_context()))
+ referral_router(state)
+ .layer(Extension(ConnectInfo(SocketAddr::from((
+ [127, 0, 0, 1],
+ 0,
+ )))))
+ .layer(Extension(test_user_context()))
+}
+
+fn ok_service() -> MockReferralService {
+ MockReferralService {
+ result: Ok(ReferralCode("test-code".to_string())),
+ }
}
#[tokio::test]
async fn test_get_referral_code_success() {
- let service = MockReferralService {
- result: Ok(ReferralCode("test-code".to_string())),
- };
- let app = build_router(service);
+ let app = build_router(ok_service(), allowing_rate_limiter());
let request = axum::http::Request::builder()
.uri("/code")
@@ -103,7 +164,7 @@ async fn test_get_referral_code_internal_error() {
let service = MockReferralService {
result: Err(ReferralError::Internal(anyhow::anyhow!("db error"))),
};
- let app = build_router(service);
+ let app = build_router(service, allowing_rate_limiter());
let request = axum::http::Request::builder()
.uri("/code")
@@ -118,11 +179,9 @@ async fn test_get_referral_code_internal_error() {
#[tokio::test]
async fn test_get_referral_code_unauthenticated() {
- let service = MockReferralService {
- result: Ok(ReferralCode("test-code".to_string())),
- };
let state = ReferralRouterState {
- service: Arc::new(service),
+ service: Arc::new(ok_service()),
+ rate_limiter: allowing_rate_limiter(),
};
// No user context extension — should fail auth
let app: axum::Router = referral_router(state);
@@ -137,3 +196,79 @@ async fn test_get_referral_code_unauthenticated() {
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
+
+#[tokio::test]
+async fn test_send_invite_succeeds_under_rate_limit() {
+ let app = build_router(ok_service(), allowing_rate_limiter());
+
+ let request = axum::http::Request::builder()
+ .uri("/send")
+ .method("POST")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::json!({"recipient": "[email protected]"}).to_string(),
+ ))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::NO_CONTENT);
+}
+
+#[tokio::test]
+async fn test_send_invite_blocked_when_rate_limit_exceeded() {
+ let app = build_router(ok_service(), exceeding_rate_limiter());
+
+ let request = axum::http::Request::builder()
+ .uri("/send")
+ .method("POST")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::json!({"recipient": "[email protected]"}).to_string(),
+ ))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
+}
+
+#[tokio::test]
+async fn test_send_invite_unauthenticated() {
+ let state = ReferralRouterState {
+ service: Arc::new(ok_service()),
+ rate_limiter: allowing_rate_limiter(),
+ };
+ // No user context extension — should fail auth
+ let app: axum::Router = referral_router(state);
+
+ let request = axum::http::Request::builder()
+ .uri("/send")
+ .method("POST")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::json!({"recipient": "[email protected]"}).to_string(),
+ ))
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn test_get_code_not_affected_by_rate_limit() {
+ // GET /code should succeed even when rate limiter would exceed,
+ // because rate limiting middleware only applies to /send
+ let app = build_router(ok_service(), exceeding_rate_limiter());
+
+ let request = axum::http::Request::builder()
+ .uri("/code")
+ .method("GET")
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+}
diff --git a/rust/cloud-storage/seed_cli/src/service/auth/mod.rs b/rust/cloud-storage/seed_cli/src/service/auth/mod.rs
index ab6f220f73..79d0b2557c 100644
--- a/rust/cloud-storage/seed_cli/src/service/auth/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/service/auth/mod.rs
@@ -1,5 +1,7 @@
//! Auth service wrapper.
+use std::net::{IpAddr, Ipv4Addr};
+
#[cfg(test)]
pub use MockSeedAuth as Auth;
#[cfg(not(test))]
@@ -29,7 +31,11 @@ impl SeedAuth {
) -> anyhow::Result<String> {
let result = self
.inner
- .create_user(user, true /*skip_verification*/, "127.0.0.1")
+ .create_user(
+ user,
+ true, /*skip_verification*/
+ IpAddr::V4(Ipv4Addr::LOCALHOST),
+ )
.await?;
Ok(result)