π OpenHands: AI-Driven Development
feat(enterprise): make rate limits configurable via env vars (#14628)
Joe Laverty459b00986b28
diff --git a/enterprise/server/auth/saas_user_auth.py b/enterprise/server/auth/saas_user_auth.pyindex 0619a34dc9..a356e56f02 100644--- a/enterprise/server/auth/saas_user_auth.py+++ b/enterprise/server/auth/saas_user_auth.py@@ -23,6 +23,7 @@ from server.auth.cookie_chunking import read_chunked_cookiefrom server.auth.token_manager import TokenManagerfrom server.logger import loggerfrom server.rate_limit import RateLimiter, create_redis_rate_limiter+from server.utils.rate_limit_utils import RATE_LIMIT_AUTH_WINDOWSfrom sqlalchemy import delete, selectfrom storage.api_key_store import ApiKeyStorefrom storage.auth_tokens import AuthTokens@@ -49,7 +50,7 @@ from openhands.app_server.user_auth.user_auth import AuthType, UserAuthtoken_manager = TokenManager()-rate_limiter: RateLimiter = create_redis_rate_limiter('10/second; 100/minute')+rate_limiter: RateLimiter = create_redis_rate_limiter(RATE_LIMIT_AUTH_WINDOWS)@dataclassdiff --git a/enterprise/server/routes/auth.py b/enterprise/server/routes/auth.pyindex 11f61e21f2..910cb27777 100644--- a/enterprise/server/routes/auth.py+++ b/enterprise/server/routes/auth.py@@ -51,7 +51,11 @@ from server.services.org_invitation_service import (UserAlreadyMemberError,)from server.utils.conversation_utils import get_session_api_key, get_user_id-from server.utils.rate_limit_utils import check_rate_limit_by_user_id+from server.utils.rate_limit_utils import (+ RATE_LIMIT_AUTH_VERIFY_EMAIL_IP_SECONDS,+ RATE_LIMIT_AUTH_VERIFY_EMAIL_USER_SECONDS,+ check_rate_limit_by_user_id,+)from server.utils.url_utils import get_cookie_domain, get_cookie_samesite, get_web_urlfrom sqlalchemy import selectfrom storage.database import a_session_maker@@ -399,16 +403,17 @@ async def keycloak_callback(# Import locally to avoid circular import with email.pyfrom server.routes.email import verify_email- # Rate limit verification emails during auth flow (60 seconds per user)- # This is separate from the manual resend rate limit which uses 30 seconds+ # Rate limit verification emails during auth flow (defaults: 60s per user,+ # 120s per IP; configurable via RATE_LIMIT_AUTH_VERIFY_EMAIL_* env vars).+ # This is separate from the manual resend limit (RATE_LIMIT_EMAIL_RESEND_*).rate_limited = Falsetry:await check_rate_limit_by_user_id(request=request,key_prefix='auth_verify_email',user_id=user_id,- user_rate_limit_seconds=60,- ip_rate_limit_seconds=120,+ user_rate_limit_seconds=RATE_LIMIT_AUTH_VERIFY_EMAIL_USER_SECONDS,+ ip_rate_limit_seconds=RATE_LIMIT_AUTH_VERIFY_EMAIL_IP_SECONDS,)await verify_email(request=request, user_id=user_id, is_auth_flow=True)except HTTPException as e:diff --git a/enterprise/server/routes/email.py b/enterprise/server/routes/email.pyindex 8256c80b94..ce4937a080 100644--- a/enterprise/server/routes/email.py+++ b/enterprise/server/routes/email.py@@ -9,7 +9,11 @@ from server.auth.keycloak_manager import get_keycloak_adminfrom server.auth.saas_user_auth import SaasUserAuthfrom server.constants import IS_LOCAL_ENVfrom server.routes.auth import set_response_cookie-from server.utils.rate_limit_utils import check_rate_limit_by_user_id+from server.utils.rate_limit_utils import (+ RATE_LIMIT_EMAIL_RESEND_IP_SECONDS,+ RATE_LIMIT_EMAIL_RESEND_USER_SECONDS,+ check_rate_limit_by_user_id,+)from server.utils.url_utils import get_web_urlfrom storage.user_store import UserStore@@ -130,14 +134,15 @@ async def resend_email_verification(detail='user_id is required in request body or user must be authenticated',)- # Check rate limit (uses user_id if available, otherwise falls back to IP)- # Use 30 seconds for user-based rate limiting to match frontend cooldown+ # Check rate limit (uses user_id if available, otherwise falls back to IP).+ # Defaults: 30s per user (matches frontend cooldown), 60s per IP (more+ # lenient); configurable via RATE_LIMIT_EMAIL_RESEND_* env vars.await check_rate_limit_by_user_id(request=request,key_prefix='email_resend',user_id=user_id,- user_rate_limit_seconds=30,- ip_rate_limit_seconds=60, # 1 minute for IP-based limiting (more lenient)+ user_rate_limit_seconds=RATE_LIMIT_EMAIL_RESEND_USER_SECONDS,+ ip_rate_limit_seconds=RATE_LIMIT_EMAIL_RESEND_IP_SECONDS,)# Get is_auth_flow from body if provided, default to Falsediff --git a/enterprise/server/routes/org_invitations.py b/enterprise/server/routes/org_invitations.pyindex f04ec035f9..10d693983c 100644--- a/enterprise/server/routes/org_invitations.py+++ b/enterprise/server/routes/org_invitations.py@@ -19,7 +19,10 @@ from server.routes.org_invitation_models import (UserAlreadyMemberError,)from server.services.org_invitation_service import OrgInvitationService-from server.utils.rate_limit_utils import check_rate_limit_by_user_id+from server.utils.rate_limit_utils import (+ RATE_LIMIT_ORG_INVITATION_USER_SECONDS,+ check_rate_limit_by_user_id,+)from storage.org_store import OrgStorefrom storage.role_store import RoleStore@@ -78,12 +81,14 @@ async def create_invitation(HTTPException 403: User lacks permission to inviteHTTPException 429: Rate limit exceeded"""- # Rate limit: 10 invitations per minute per user (6 seconds between requests)+ # Rate limit invitation creation per user (default: 6s between requests, i.e.+ # 10 invitations per minute; configurable via+ # RATE_LIMIT_ORG_INVITATION_USER_SECONDS).await check_rate_limit_by_user_id(request=request,key_prefix='org_invitation_create',user_id=user_id,- user_rate_limit_seconds=6,+ user_rate_limit_seconds=RATE_LIMIT_ORG_INVITATION_USER_SECONDS,)try:diff --git a/enterprise/server/utils/rate_limit_utils.py b/enterprise/server/utils/rate_limit_utils.pyindex 4894c38798..8431d3238f 100644--- a/enterprise/server/utils/rate_limit_utils.py+++ b/enterprise/server/utils/rate_limit_utils.py@@ -1,11 +1,51 @@+import os+from fastapi import HTTPException, Request, statusfrom storage.redis import get_redis_client_asyncfrom openhands.app_server.utils.logger import openhands_logger as logger-# Rate limiting constants-RATE_LIMIT_USER_SECONDS = 120 # 2 minutes per user_id-RATE_LIMIT_IP_SECONDS = 300 # 5 minutes per IP address+# Rate limiting configuration.+#+# Every rate limit below is configurable via an environment variable, falling+# back to the default when the variable is unset.++# Per-user request limiter for authenticated API requests (see+# server.auth.saas_user_auth). Value is a `limits`-style window string, where+# multiple windows are separated by ';', e.g. "10/second; 100/minute".+RATE_LIMIT_AUTH_WINDOWS = os.environ.get(+ 'RATE_LIMIT_AUTH_WINDOWS', '10/second; 100/minute'+)++# Generic fallback windows used by check_rate_limit_by_user_id when a caller does+# not pass its own values.+RATE_LIMIT_USER_SECONDS = int(+ os.environ.get('RATE_LIMIT_USER_SECONDS', '120')+) # 2 minutes per user_id+RATE_LIMIT_IP_SECONDS = int(+ os.environ.get('RATE_LIMIT_IP_SECONDS', '300')+) # 5 minutes per IP address++# Email verification during the auth flow (server.routes.auth).+RATE_LIMIT_AUTH_VERIFY_EMAIL_USER_SECONDS = int(+ os.environ.get('RATE_LIMIT_AUTH_VERIFY_EMAIL_USER_SECONDS', '60')+)+RATE_LIMIT_AUTH_VERIFY_EMAIL_IP_SECONDS = int(+ os.environ.get('RATE_LIMIT_AUTH_VERIFY_EMAIL_IP_SECONDS', '120')+)++# Manual verification email resend (server.routes.email).+RATE_LIMIT_EMAIL_RESEND_USER_SECONDS = int(+ os.environ.get('RATE_LIMIT_EMAIL_RESEND_USER_SECONDS', '30')+)+RATE_LIMIT_EMAIL_RESEND_IP_SECONDS = int(+ os.environ.get('RATE_LIMIT_EMAIL_RESEND_IP_SECONDS', '60')+)++# Organization invitation creation (server.routes.org_invitations).+RATE_LIMIT_ORG_INVITATION_USER_SECONDS = int(+ os.environ.get('RATE_LIMIT_ORG_INVITATION_USER_SECONDS', '6')+)async def check_rate_limit_by_user_id(diff --git a/enterprise/tests/unit/server/test_rate_limit_utils.py b/enterprise/tests/unit/server/test_rate_limit_utils.pyindex 3a32aff04c..7bf3f730c7 100644--- a/enterprise/tests/unit/server/test_rate_limit_utils.py+++ b/enterprise/tests/unit/server/test_rate_limit_utils.py@@ -1,3 +1,4 @@+import importlibfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -268,3 +269,57 @@ async def test_rate_limit_different_users_have_separate_limits(True,RATE_LIMIT_USER_SECONDS,) in call_args_list+++class TestRateLimitEnvConfiguration:+ """Rate limit windows are read from environment variables at import time,+ with a default value for each when the variable is unset."""++ @pytest.mark.parametrize(+ 'const_name,expected_default',+ [+ ('RATE_LIMIT_AUTH_WINDOWS', '10/second; 100/minute'),+ ('RATE_LIMIT_USER_SECONDS', 120),+ ('RATE_LIMIT_IP_SECONDS', 300),+ ('RATE_LIMIT_AUTH_VERIFY_EMAIL_USER_SECONDS', 60),+ ('RATE_LIMIT_AUTH_VERIFY_EMAIL_IP_SECONDS', 120),+ ('RATE_LIMIT_EMAIL_RESEND_USER_SECONDS', 30),+ ('RATE_LIMIT_EMAIL_RESEND_IP_SECONDS', 60),+ ('RATE_LIMIT_ORG_INVITATION_USER_SECONDS', 6),+ ],+ )+ def test_default_values(self, const_name, expected_default):+ import server.utils.rate_limit_utils as rate_limit_utils++ assert getattr(rate_limit_utils, const_name) == expected_default++ def test_environment_variables_override_defaults(self, monkeypatch):+ import server.utils.rate_limit_utils as rate_limit_utils++ overrides = {+ 'RATE_LIMIT_AUTH_WINDOWS': '5/second; 50/minute',+ 'RATE_LIMIT_USER_SECONDS': '11',+ 'RATE_LIMIT_IP_SECONDS': '22',+ 'RATE_LIMIT_AUTH_VERIFY_EMAIL_USER_SECONDS': '33',+ 'RATE_LIMIT_AUTH_VERIFY_EMAIL_IP_SECONDS': '44',+ 'RATE_LIMIT_EMAIL_RESEND_USER_SECONDS': '55',+ 'RATE_LIMIT_EMAIL_RESEND_IP_SECONDS': '66',+ 'RATE_LIMIT_ORG_INVITATION_USER_SECONDS': '77',+ }+ for key, value in overrides.items():+ monkeypatch.setenv(key, value)++ try:+ importlib.reload(rate_limit_utils)+ assert rate_limit_utils.RATE_LIMIT_AUTH_WINDOWS == '5/second; 50/minute'+ assert rate_limit_utils.RATE_LIMIT_USER_SECONDS == 11+ assert rate_limit_utils.RATE_LIMIT_IP_SECONDS == 22+ assert rate_limit_utils.RATE_LIMIT_AUTH_VERIFY_EMAIL_USER_SECONDS == 33+ assert rate_limit_utils.RATE_LIMIT_AUTH_VERIFY_EMAIL_IP_SECONDS == 44+ assert rate_limit_utils.RATE_LIMIT_EMAIL_RESEND_USER_SECONDS == 55+ assert rate_limit_utils.RATE_LIMIT_EMAIL_RESEND_IP_SECONDS == 66+ assert rate_limit_utils.RATE_LIMIT_ORG_INVITATION_USER_SECONDS == 77+ finally:+ # Restore module-level defaults so other tests are unaffected.+ monkeypatch.undo()+ importlib.reload(rate_limit_utils)