-
Notifications
You must be signed in to change notification settings - Fork 5
feat(security): add API rate limiting with slowapi #327
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
58a94a7
feat(security): add API rate limiting with slowapi
5a38f96
chore: remove unused imports in rate limit tests
1143215
fix(tests): update UI tests for rate limiting request parameter
d704971
fix: address code review issues in rate limiting
25b4b87
feat: implement audit logging for rate limit exceeded events
8e036cd
fix: prevent duplicate 'rate limiting disabled' log messages
1f9ada4
feat(api): add rate limiting to all v2 routers
3b0dc53
docs: update docstrings to reflect renamed body parameters
021963b
fix(rate-limiter): address security and config review feedback
ef51320
test(rate-limiter): add integration tests and simplify decorator pattern
f6144c5
style: remove unused import in rate limit integration tests
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| """Rate limiting configuration for CodeFRAME API. | ||
|
|
||
| This module provides configuration for API rate limiting using slowapi. | ||
| Rate limits can be configured via environment variables for flexibility | ||
| across deployment environments. | ||
|
|
||
| Environment Variables: | ||
| RATE_LIMIT_ENABLED: Enable/disable rate limiting (default: true) | ||
| RATE_LIMIT_AUTH: Rate limit for authentication endpoints (default: 10/minute) | ||
| RATE_LIMIT_STANDARD: Rate limit for standard API endpoints (default: 100/minute) | ||
| RATE_LIMIT_AI: Rate limit for AI/expensive operations (default: 20/minute) | ||
| RATE_LIMIT_WEBSOCKET: Rate limit for WebSocket connections (default: 30/minute) | ||
| RATE_LIMIT_STORAGE: Storage backend - memory or redis (default: memory) | ||
| REDIS_URL: Redis connection URL for distributed rate limiting (optional) | ||
| """ | ||
|
|
||
| import logging | ||
| import os | ||
| from dataclasses import dataclass | ||
| from typing import Optional | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _parse_bool(value: str) -> bool: | ||
| """Parse boolean from string, supporting various formats. | ||
|
|
||
| Args: | ||
| value: String value to parse | ||
|
|
||
| Returns: | ||
| Boolean interpretation of the value | ||
| """ | ||
| return value.lower() in ("true", "1", "yes", "on") | ||
|
|
||
|
|
||
| @dataclass | ||
| class RateLimitConfig: | ||
| """Configuration for API rate limiting. | ||
|
|
||
| Attributes: | ||
| auth_limit: Rate limit for authentication endpoints | ||
| standard_limit: Rate limit for standard API endpoints | ||
| ai_limit: Rate limit for AI/expensive operations | ||
| websocket_limit: Rate limit for WebSocket connections | ||
| enabled: Whether rate limiting is enabled | ||
| storage: Storage backend ('memory' or 'redis') | ||
| redis_url: Redis connection URL for distributed rate limiting | ||
| """ | ||
|
|
||
| auth_limit: str = "10/minute" | ||
| standard_limit: str = "100/minute" | ||
| ai_limit: str = "20/minute" | ||
| websocket_limit: str = "30/minute" | ||
| enabled: bool = True | ||
| storage: str = "memory" | ||
| redis_url: Optional[str] = None | ||
|
|
||
| @classmethod | ||
| def from_environment(cls) -> "RateLimitConfig": | ||
| """Create RateLimitConfig from environment variables. | ||
|
|
||
| Returns: | ||
| RateLimitConfig instance with values from environment | ||
| """ | ||
| enabled_str = os.getenv("RATE_LIMIT_ENABLED", "true") | ||
| enabled = _parse_bool(enabled_str) | ||
|
|
||
| auth_limit = os.getenv("RATE_LIMIT_AUTH", "10/minute") | ||
| standard_limit = os.getenv("RATE_LIMIT_STANDARD", "100/minute") | ||
| ai_limit = os.getenv("RATE_LIMIT_AI", "20/minute") | ||
| websocket_limit = os.getenv("RATE_LIMIT_WEBSOCKET", "30/minute") | ||
| storage = os.getenv("RATE_LIMIT_STORAGE", "memory") | ||
| redis_url = os.getenv("REDIS_URL") | ||
|
|
||
| # Validate storage type | ||
| if storage not in ("memory", "redis"): | ||
| logger.warning( | ||
| f"Invalid RATE_LIMIT_STORAGE: {storage}. " | ||
| f"Must be 'memory' or 'redis'. Defaulting to 'memory'." | ||
| ) | ||
| storage = "memory" | ||
|
|
||
| # Warn if redis storage is requested but no URL provided | ||
| if storage == "redis" and not redis_url: | ||
| logger.warning( | ||
| "RATE_LIMIT_STORAGE is 'redis' but REDIS_URL is not set. " | ||
| "Falling back to in-memory storage." | ||
| ) | ||
| storage = "memory" | ||
|
|
||
| return cls( | ||
| auth_limit=auth_limit, | ||
| standard_limit=standard_limit, | ||
| ai_limit=ai_limit, | ||
| websocket_limit=websocket_limit, | ||
| enabled=enabled, | ||
| storage=storage, | ||
| redis_url=redis_url, | ||
| ) | ||
|
|
||
|
|
||
| # Global rate limit config instance | ||
| _rate_limit_config: Optional[RateLimitConfig] = None | ||
|
|
||
|
|
||
| def get_rate_limit_config() -> RateLimitConfig: | ||
| """Get the global rate limit configuration. | ||
|
|
||
| Loads from environment on first call, cached thereafter. | ||
|
|
||
| Returns: | ||
| RateLimitConfig instance | ||
| """ | ||
| global _rate_limit_config | ||
| if _rate_limit_config is None: | ||
| _rate_limit_config = RateLimitConfig.from_environment() | ||
| logger.info( | ||
| f"Rate limit config initialized: " | ||
| f"enabled={_rate_limit_config.enabled}, " | ||
| f"storage={_rate_limit_config.storage}, " | ||
| f"standard={_rate_limit_config.standard_limit}" | ||
| ) | ||
| return _rate_limit_config | ||
|
|
||
|
|
||
| def _reset_rate_limit_config() -> None: | ||
| """Reset the global rate limit configuration. | ||
|
|
||
| Useful for testing to ensure clean state between tests. | ||
| """ | ||
| global _rate_limit_config | ||
| _rate_limit_config = None | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.