Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(auth): limit user creation based on ip (#2076)

Will Hutchinsonbdb74f6706d7
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 06681d25cf..f1447025e3 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
@@ -42,7 +42,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)
+ .verify_email(&verification_id, &ip_context.client_ip)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to verify email");
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 ccac693d4d..9cf391fda3 100644
--- a/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs
+++ b/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs
@@ -102,7 +102,7 @@ pub async fn handler(
email: (&lowercase_email).into(),
password: generate_random_password().into(),
username: None,
- }, true)
+ }, true, &ip_context.client_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/user/create_user.rs b/rust/cloud-storage/authentication_service/src/api/user/create_user.rs
index 02f5e6c322..630916d8e2 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
@@ -89,6 +89,7 @@ pub async fn handler(
username: Some(req.username.into()),
},
false,
+ &ip_context.client_ip,
)
.await
.map_err(|e| {
diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
index 08456ef20f..5403e36ee4 100644
--- a/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
@@ -13,13 +13,13 @@ use model::comms::ParticipantRole;
use rand::Rng;
use sqlx::{Pool, Postgres};
-use crate::api::context::ApiContext;
+use crate::{api::context::ApiContext, rate_limit_config::RATE_LIMIT_CONFIG};
use authentication_service::service::user::create_user::create_user;
use fusionauth::error::FusionAuthClientError;
use model::authentication::webhooks::FusionAuthUserWebhook;
/// FusionAuth create user webhook
-#[tracing::instrument(skip(ctx, req, _internal_access), fields(email=%req.event.user.email, fusionauth_user_id=%req.event.user.id, username=?req.event.user.username, event_type=%req.event.event_type))]
+#[tracing::instrument(skip(ctx, req, _internal_access), fields(email=%req.event.user.email, fusionauth_user_id=%req.event.user.id, username=?req.event.user.username, event_type=%req.event.event_type, ip_address=%req.event.info.ip_address))]
pub async fn handler(
State(ctx): State<ApiContext>,
_internal_access: ValidInternalKey,
@@ -55,6 +55,7 @@ pub async fn handler(
Ok(StatusCode::OK.into_response())
}
+#[tracing::instrument(skip(ctx, req), err)]
async fn verify_user_email_webhook(
ctx: &ApiContext,
req: FusionAuthUserWebhook,
@@ -91,12 +92,25 @@ async fn create_user_webhook_complete(
}
}
-#[tracing::instrument(skip(ctx), fields(email=%req.event.user.email, fusionauth_user_id=%req.event.user.id, username=?req.event.user.username, event_type=%req.event.event_type))]
+#[tracing::instrument(skip(ctx, req), err)]
async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> anyhow::Result<()> {
+ let ip_address = req.event.info.ip_address;
let email = req.event.user.email.to_lowercase();
let username = req.event.user.username.unwrap_or(email.clone());
let fusionauth_user_id = req.event.user.id;
+ // rate limit check for user creation
+ let rate_limit = ctx
+ .macro_cache_client
+ .get_create_user_hourly_rate_limit(&ip_address)
+ .await?;
+
+ if let Some(count) = rate_limit
+ && count >= RATE_LIMIT_CONFIG.create_user_hourly.0
+ {
+ anyhow::bail!("rate limit exceeded")
+ }
+
// check if user exists
if let Ok((user_id, stripe_customer_id)) =
macro_db_client::user::get::get_user_id_and_stripe_customer_id_by_email(&ctx.db, &email)
@@ -187,6 +201,13 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
tracing::trace!(email, fusionauth_user_id, elapsed=?start_time.elapsed(), "created user");
+ // Allow to fail silently
+ let _ = ctx
+ .macro_cache_client
+ .increment_create_user_hourly_rate_limit(&ip_address)
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "unable to increment create user rate limit"));
+
Ok(())
}
diff --git a/rust/cloud-storage/authentication_service/src/rate_limit_config.rs b/rust/cloud-storage/authentication_service/src/rate_limit_config.rs
index bd03297beb..3a123550e9 100644
--- a/rust/cloud-storage/authentication_service/src/rate_limit_config.rs
+++ b/rust/cloud-storage/authentication_service/src/rate_limit_config.rs
@@ -12,6 +12,7 @@ pub struct RateLimitConfig {
pub merge_email_minute: (u64, i64),
#[allow(dead_code)]
pub merge_email_daily: (u64, i64),
+ pub create_user_hourly: (u64, i64),
// pub sso: (u64, i64),
}
@@ -26,4 +27,6 @@ pub static RATE_LIMIT_CONFIG: RateLimitConfig = RateLimitConfig {
merge_email_minute: (5, 60),
merge_email_daily: (5, 86400),
+
+ create_user_hourly: (50, 3600),
};
diff --git a/rust/cloud-storage/fusionauth/src/user/create.rs b/rust/cloud-storage/fusionauth/src/user/create.rs
index 8cba781e0d..c7adbd8731 100644
--- a/rust/cloud-storage/fusionauth/src/user/create.rs
+++ b/rust/cloud-storage/fusionauth/src/user/create.rs
@@ -56,10 +56,12 @@ pub(crate) async fn create_user(
client: &AuthedClient,
base_url: &str,
request: CreateUserRequest<'_>,
+ client_ip: &str,
) -> Result<String> {
let res = client
.client()
.post(format!("{base_url}/api/user"))
+ .header("X-Forwarded-For", client_ip)
.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 2e80608221..7dbef44b79 100644
--- a/rust/cloud-storage/fusionauth/src/user/mod.rs
+++ b/rust/cloud-storage/fusionauth/src/user/mod.rs
@@ -24,6 +24,7 @@ impl FusionAuthClient {
&self,
user: create::User<'_>,
skip_verification: bool,
+ client_ip: &str,
) -> Result<String> {
create::create_user(
&self.auth_client,
@@ -33,6 +34,7 @@ impl FusionAuthClient {
skip_verification,
user,
},
+ client_ip,
)
.await
}
@@ -82,13 +84,14 @@ 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) -> Result<()> {
+ pub async fn verify_email(&self, verification_id: &str, client_ip: &str) -> Result<()> {
verify::verify_email(
&self.auth_client,
&self.fusion_auth_base_url,
verify::VerifyEmailRequest {
verification_id: Cow::Borrowed(verification_id),
},
+ client_ip,
)
.await
}
diff --git a/rust/cloud-storage/fusionauth/src/user/verify.rs b/rust/cloud-storage/fusionauth/src/user/verify.rs
index 0b543caef7..da35650671 100644
--- a/rust/cloud-storage/fusionauth/src/user/verify.rs
+++ b/rust/cloud-storage/fusionauth/src/user/verify.rs
@@ -19,10 +19,12 @@ pub(crate) async fn verify_email<'a>(
client: &AuthedClient,
base_url: &str,
verify_email_request: VerifyEmailRequest<'a>,
+ client_ip: &str,
) -> Result<()> {
let res = client
.client()
.post(format!("{base_url}/api/user/verify-email"))
+ .header("X-Forwarded-For", client_ip)
.json(&verify_email_request)
.send()
.await
diff --git a/rust/cloud-storage/macro_cache_client/src/create_user_rate_limit.rs b/rust/cloud-storage/macro_cache_client/src/create_user_rate_limit.rs
new file mode 100644
index 0000000000..2e2e3592aa
--- /dev/null
+++ b/rust/cloud-storage/macro_cache_client/src/create_user_rate_limit.rs
@@ -0,0 +1,30 @@
+use crate::MacroCache;
+
+/// Rate limit expiry for create user hourly
+pub static MACRO_CREATE_USER_HOURLY_EXPIRY_SECONDS: i64 = 60 * 60; // 1 hour in seconds
+
+/// Generates the rate limit key for creating user for a given ip
+macro_rules! macro_create_user_rate_limit_hourly {
+ ($ip:expr) => {
+ format!("rtl_create_user_hourly:{}", $ip)
+ };
+}
+
+impl MacroCache {
+ /// Gets the create user hourly rate limit for a given ip
+ pub async fn get_create_user_hourly_rate_limit(&self, ip: &str) -> anyhow::Result<Option<u64>> {
+ let key = macro_create_user_rate_limit_hourly!(ip);
+ macro_redis::get::get_optional::<u64>(&self.inner, &key).await
+ }
+
+ /// Increments the create user hourly rate limit for a given ip
+ pub async fn increment_create_user_hourly_rate_limit(&self, ip: &str) -> anyhow::Result<()> {
+ let key = macro_create_user_rate_limit_hourly!(ip);
+ macro_redis::incr::incr_with_expiry(
+ &self.inner,
+ &key,
+ MACRO_CREATE_USER_HOURLY_EXPIRY_SECONDS,
+ )
+ .await
+ }
+}
diff --git a/rust/cloud-storage/macro_cache_client/src/lib.rs b/rust/cloud-storage/macro_cache_client/src/lib.rs
index 7937785645..220aea9873 100644
--- a/rust/cloud-storage/macro_cache_client/src/lib.rs
+++ b/rust/cloud-storage/macro_cache_client/src/lib.rs
@@ -6,6 +6,9 @@ pub mod auth;
#[cfg(feature = "auth_rate_limit")]
pub mod passwordless_rate_limit;
+#[cfg(feature = "auth_rate_limit")]
+pub mod create_user_rate_limit;
+
#[cfg(feature = "notification_rate_limit")]
pub mod notification_rate_limit;
diff --git a/rust/cloud-storage/model/src/authentication/webhooks/mod.rs b/rust/cloud-storage/model/src/authentication/webhooks/mod.rs
index 5ffaacf5ea..9a94d03c4e 100644
--- a/rust/cloud-storage/model/src/authentication/webhooks/mod.rs
+++ b/rust/cloud-storage/model/src/authentication/webhooks/mod.rs
@@ -14,11 +14,19 @@ pub struct Event {
pub create_instant: i64,
pub id: String,
pub linked_object_id: String,
+ pub info: EventInfo,
pub user: User,
#[serde(rename = "type")]
pub event_type: String,
}
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct EventInfo {
+ /// IP address of the user the event was initiated for
+ pub ip_address: String,
+}
+
#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct User {
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 727c2a7228..ab6f220f73 100644
--- a/rust/cloud-storage/seed_cli/src/service/auth/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/service/auth/mod.rs
@@ -29,7 +29,7 @@ impl SeedAuth {
) -> anyhow::Result<String> {
let result = self
.inner
- .create_user(user, true /*skip_verification*/)
+ .create_user(user, true /*skip_verification*/, "127.0.0.1")
.await?;
Ok(result)