| title | description | keywords |
|---|---|---|
Release Notes - FastAPI Guard |
Release notes for FastAPI Guard, detailing new features, improvements, and bug fixes |
release notes, fastapi guard, security middleware, api security |
- Configurable cloud IP refresh interval: New
cloud_ip_refresh_intervalconfig field (default: 3600s, valid range: 60-86400s) allows tuning how often cloud provider IP ranges are refreshed. The interval is propagated to Redis TTL for cache consistency. - Change detection logging for cloud IP refreshes: When cloud IP ranges are refreshed, additions and removals are logged per provider (e.g.,
+12 added, -3 removed), providing visibility into IP range mutations. - Context-aware detection engine: Suspicious pattern rules are now tagged with applicable input contexts (
query_param,url_path,header,request_body). Patterns are only evaluated against relevant input sources, reducing false positives. - Structured JSON logging: New
log_format="json"config option outputs logs as structured JSON ({"timestamp": "...", "level": "...", "logger": "...", "message": "..."}), enabling integration with log aggregation systems (ELK, Datadog, CloudWatch). - Per-provider
last_updatedtimestamps:CloudManagernow tracks when each provider's IP ranges were last refreshed viacloud_handler.last_updated["AWS"], returningdatetime | None.
- Geographic rate limit check: Fixed geo-based rate limiting by implementing the missing
_check_geo_rate_limitmethod inRateLimitCheck. Previously, geo rate limits configured via the@security.geo_rate_limitdecorator were stored but never enforced. The rate limit pipeline now correctly evaluates geo-based limits at priority 3 (after endpoint-specific and route-specific limits). - Geo rate limit decorator: Fixed
RateLimitingMixin.geo_rate_limitdecorator to store limits onroute_config.geo_rate_limitsinstead of incorrectly serializing them intorequired_headers. - IPInfo country whitelist fail-closed: When
whitelist_countriesis configured and a client's country cannot be determined,IPInfoManager.check_country_accessnow correctly blocks the request (fail-closed) instead of allowing it through.
- Timezone-aware time windows: Time window restrictions now support configurable timezones via the
timezonefield intime_restrictions. UsesZoneInfofor proper timezone handling with a safe fallback to UTC for invalid timezone strings. - Geo rate limit RouteConfig support: Added
geo_rate_limitsattribute toRouteConfigfor proper type-safe storage of geographic rate limit configurations.
- Whitelisted IP bypass: Whitelisted IPs now correctly bypass rate limiting, cloud provider blocking, user agent filtering, and suspicious activity detection checks. Previously, the whitelist flag was only checked during IP security validation but not propagated to downstream security checks.
- Version bump helper: Added
make bump-version VERSION=x.y.zcommand and.github/scripts/bump_version.pyscript to automate version updates across all project files (pyproject.toml, .mike.yml, versions.json, docs/index.md, changelogs).
- Docker actions: Bumped
docker/login-actionfrom 3 to 4 anddocker/setup-compose-actionfrom 1 to 2. - Pre-commit: Simplified pre-commit checks in scheduled lint workflow and disabled semgrep in pre-commit configuration.
- Python 3.14: Added support for Python 3.14.
- IPInfo redirect URLs: IPInfo API sometimes responds with 302 code, and by not handling the redirect, the database would not be downloaded. Now,
IPInfoManagerclass follows redirects.
Major architectural transformation completed (v4.2.0):
- Middleware Refactoring: Broke down
middleware.pyfrom monolithic file into modular architecture. - Maintainability Improvement: Improved from MI 0.00 (Rank C - "unmaintainable") to MI 54.51 (Rank A)
- Complexity Reduction: Average complexity reduced from ~15 to 2.35 (84.3% improvement)
- Code Reduction: middleware.py reduced by 77.4% through modular extraction
- Test Coverage: Maintained at 100% throughout refactoring
- Zero Breaking Changes: All public APIs remain unchanged
There are now 9 specialized modules (all achieving Rank A maintainability, MI 56-82):
-
checks/- Security check implementations using Chain of Responsibility patternSecurityCheckbase classSecurityCheckPipelinefor orchestration- 17 check implementations in
implementations/
-
events/- Event system for middleware actionsSecurityEventBusfor centralized event dispatchingMetricsCollectorfor request metrics collection
-
initialization/- Handler initialization logicHandlerInitializerfor centralized Redis, Agent, and handler setup
-
responses/- Response handlingErrorResponseFactoryfor response creation and processingResponseContextfor dependency injection
-
routing/- Routing and decorator resolutionRouteConfigResolverfor route configurationRoutingContextfor dependency injection
-
validation/- Request validation utilitiesRequestValidatorfor HTTPS checks, proxy validation, time windowsValidationContextfor dependency injection
-
bypass/- Security bypass handlingBypassHandlerfor passthrough and bypass logicBypassContextfor dependency injection
-
behavioral/- Behavioral rule processingBehavioralProcessorfor usage and return rulesBehavioralContextfor dependency injection
- Faster Development: Faster feature additions
- Better Testability: Each module independently testable
- Improved Performance: Better code organization and caching
- Maintainable Codebase: Single Responsibility Principle applied throughout
For Users: No migration needed - all existing code works unchanged
For Contributors: See ARCHITECTURE_CHANGES.md for detailed module breakdown
Important: The guard/core/* modules are internal implementation details. Always import from public API.
- Added dynamic rule updated event type.
- Enhanced Security Headers: Added 5 new default security headers following OWASP best practices:
X-Permitted-Cross-Domain-Policies: none- Restricts Adobe Flash cross-domain accessX-Download-Options: noopen- Prevents file download execution in Internet ExplorerCross-Origin-Embedder-Policy: require-corp- Controls cross-origin resource embeddingCross-Origin-Opener-Policy: same-origin- Controls cross-origin window interactionsCross-Origin-Resource-Policy: same-origin- Controls cross-origin resource access
- Security Validation Framework: Comprehensive input validation for all header configurations
- Advanced CORS Validation: Runtime validation and logging for CORS misconfiguration attempts
- Security Event Logging: Enhanced logging for security violations and configuration warnings
- Fixed header injection vulnerability in SecurityHeadersManager - preventing injection attacks via newlines and control characters
- Enhanced CORS security - wildcard origins (
*) now properly blocked when credentials are enabled to prevent security bypass - Implemented thread-safe singleton pattern with double-checked locking to prevent race conditions in multi-threaded environments
- Secure cache key generation using SHA256 hashing to prevent cache poisoning attacks
- Added CSP unsafe directive validation - warnings for
'unsafe-inline'and'unsafe-eval'directives - HSTS preload validation - ensures preload requirements (max_age ≥ 31536000, includeSubDomains) are met
- Input validation for all header values - sanitization of control characters and length limits (8192 bytes)
- Performance: Optimized cache key generation using SHA256 with path normalization
- Reliability: Thread-safe singleton implementation prevents multiple instances in concurrent environments
- Security: All header values now validated against injection attacks, newlines, and excessive length
- Monitoring: Improved security event logging for better observability and debugging
- Documentation: Updated security headers documentation with new features and best practices
- Logging Configuration Fix: Fixed
custom_log_fileconfiguration being ignored - file logging now works correctly - Logging Behavior: File logging is now truly optional - only enabled when
custom_log_fileis explicitly set - Namespace Consistency: All FastAPI Guard components now use consistent
fastapi_guard.*logger namespace hierarchy- Root logger:
fastapi_guard - Handlers:
fastapi_guard.handlers.{component} - Decorators:
fastapi_guard.decorators.{component} - Detection Engine:
fastapi_guard.detection_engine
- Root logger:
- Console Output: Console logging is now always enabled for visibility, regardless of file logging configuration
- Passive Mode Enhancement: Fixed passive mode to properly log without blocking for all security checks including rate limiting, suspicious patterns, and decorator violations
- Logger Isolation: FastAPI Guard logs are now properly isolated from user application logs
- Test Compatibility: Logger propagation enabled for better test framework integration
- Documentation: Updated all logging documentation to reflect actual behavior
- Passive Mode Consistency: All security checks now properly respect passive mode - logging violations without blocking requests
- Enhanced Logging Context: Improved log messages with better context for passive mode operations, including trigger information for suspicious patterns
- Sus Patterns Handler Overhaul: Complete redesign of the suspicious patterns detection system with modular architecture
- Pattern Compiler: Safe regex execution with configurable timeouts to prevent ReDoS attacks
- Content Preprocessor: Intelligent content truncation that preserves attack signatures
- Semantic Analyzer: Heuristic-based detection using TF-IDF and n-gram analysis for obfuscated attacks
- Performance Monitor: Real-time tracking of pattern execution times and anomaly detection
- Enhanced Detection API: Rich detection results with threat scores, detailed threat information, and performance metrics
- Lazy Component Initialization: Detection components only load when explicitly configured
- Comprehensive Configuration: New
detection_*configuration options for fine-tuning all components
- Pattern Matching Performance: Timeout protection prevents slow patterns from blocking requests
- Detection Accuracy: Multi-layered approach combines regex patterns with semantic analysis
- Memory Efficiency: Configurable limits on content length and pattern tracking
- Observability: Detailed performance metrics and slow pattern identification
- Backward Compatibility: Legacy
detect_pattern_matchAPI maintained for smooth migration - Agent Integration: Automatic telemetry for pattern detection events and performance metrics
- IMPORTANT: Enhanced ReDoS prevention - Prevent regex bypass due to length limitations on pattern regex. (GHSA-rrf6-pxg8-684g)
- CVE ID: CVE-2025-54365
- Added timeout to avoid catastrophical backtracking and/or regex bypass by length limitation expression.
- Added new
regex_timeoutparameter toSecurityConfigto allow for custom timeout for regex pattern matching.
- IMPORTANT: Prevented ReDoS (Regular Expression Denial of Service - CWE-1333) attacks by replacing unbounded regex quantifiers with bounded ones. (GHSA-j47q-rc62-w448)
- CVE ID: CVE-2025-53539
- Security Decorators: Added comprehensive route-level security decorator system
SecurityDecoratorclass combining all security capabilities- Access control decorators for IP filtering, geographic restrictions, and cloud provider blocking
- Authentication decorators for HTTPS enforcement, auth requirements, and API key validation
- Rate limiting decorators with custom limits and geographic rate limiting
- Behavioral analysis decorators for usage monitoring, return pattern detection, and frequency analysis
- Content filtering decorators for content type validation, size limits, and user agent blocking
- Advanced decorators for time windows, suspicious detection, and honeypot detection
- Route-specific configuration that can override global middleware settings
- Seamless integration with existing SecurityMiddleware
- Behavior Manager: Added behavioral analysis and monitoring system
BehaviorTrackerfor tracking and analyzing user behavior patternsBehaviorRulefor defining behavioral analysis rules- Support for endpoint usage tracking, return pattern analysis, and frequency detection
- Multiple pattern formats including JSON paths, regex, and status codes
- Automated actions (ban, alert, log, throttle) based on behavioral thresholds
- Redis integration for distributed behavioral tracking
- Switched from Poetry to uv for package management
- Fixed
custom_response_modifierimplementation.
- Rate Limiting: Replaced fixed window rate limiting with true sliding window algorithm
- Added atomic Redis Lua script for distributed rate limiting
- Improved timestamp tracking for more accurate request counting
- Fixed edge cases in rate limiting that could cause unexpected 429 errors
- IMPORTANT: Fixed Remote Header Injection vulnerability via X-Forwarded-For manipulation (GHSA-77q8-qmj7-x7pp)
- CVE ID: CVE-2025-46814
- Added secure client IP extraction with trusted proxy validation
- Added new configuration parameters for proxy security:
trusted_proxies: List of trusted proxy IPs or CIDR rangestrusted_proxy_depth: Configurable proxy chain depthtrust_x_forwarded_proto: Option to trust X-Forwarded-Proto header
- IPInfo is now completely optional, you can implement your own
GeoIPHandler - Added protocol-based design for customizable geographical IP handling
- Introduced
GeoIPHandlerprotocol allowing custom implementations - Separated protocol definitions into dedicated modules
- Deprecated
ipinfo_tokenandipinfo_db_pathin favor ofgeo_ip_handler - Improved type safety and code readability
- Added runtime type checking for custom GeoIP handlers
- IpInfo token is now only required when using country filtering or cloud blocking
- Performance: Selective loading of IP geolocation database and cloud IP ranges
- Only download/process IP geolocation data when country filtering is configured
- Only fetch cloud provider IP ranges when cloud blocking is enabled
- Reduced startup time and memory usage when not using all security features
- Added configurable logging levels for normal and suspicious requests
- Enhanced log_activity function to support all logging levels
- Added ability to completely disable request logging
- Improved performance by allowing complete disabling of normal request logging
- Better log level control for different environments (dev/prod)
- Created an interactive FastAPI Guard Playground
- Added
passive_modeoption to log suspicious activity without blocking requests - Enhanced
detect_penetration_attemptfunction to return trigger information
- Added an empty
py.typed - Fixed the
package_dataconfiguration insetup.py - Added
mypyconfiguration topyproject.toml - Added
MANIFEST.in
- Added new pattern management methods to
SusPatternsManager:get_default_patterns()andget_custom_patterns()for separate pattern accessget_default_compiled_patterns()andget_custom_compiled_patterns()for separate compiled pattern access
- Enhanced
remove_pattern()method to return success/failure status
- Fixed issue with default pattern removal in
SusPatternsManager - Improved pattern separation between default and custom patterns
- Added dedicated
RateLimitManagerfor improved rate limiting functionality - TTLCache-based in-memory rate limiting still available
- Extended Redis support for distributed rate limiting
- Fixed rate limiting logic to properly handle rate limiting
- Standardized Singleton pattern across all handlers
- Added new
keysanddelete_patternmethods toRedisManagerfor easy key/pattern retrieval/cleanup
- Added proper typing throughout the codebase
- Added custom Docker container for example app
- Added better Docker Compose support
- Fixed multiple typing issues across test files
- Improved documentation for Docker container usage
- Enhanced serialization of Redis data
- Added Redis integration for distributed state management
- Improved tests & testing coverage (100% coverage)
- Added
db_pathparameter toIPInfoManagerfor custom database locations
- Improved IPInfo database handling with local caching
- Fixed Azure IP ranges download by adding proper User-Agent headers (#19)
- Fixed cloud provider validation logic to properly filter invalid entries
- Resolved test coverage gaps on all test files
- Fixed issue with accepted
HeadersonSwagger UIaccess/requests.
- Fixed package structure to properly include all required modules
- Resolved import issues with handlers package
- Improved package installation reliability