### Run FastAPI Guard Example App with Docker Compose (Bash) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/index.md This set of commands demonstrates how to clone the FastAPI Guard repository, navigate to the examples directory, and start the example application along with its Redis service using Docker Compose. This is the recommended method for running the example, as it handles all necessary service setups automatically. The application will be accessible at http://0.0.0.0:8000. ```bash # Clone the repository git clone https://github.com/rennf93/fastapi-guard.git cd fastapi-guard/examples # Start the app with Redis docker compose up ``` -------------------------------- ### Run FastAPI Guard Example with Docker Compose Source: https://github.com/rennf93/fastapi-guard/blob/master/examples/README.md Commands to manage the FastAPI Guard example application using Docker Compose. This includes starting, restarting, and stopping the application and its dependencies like Redis. ```bash docker compose up docker compose restart docker compose down ``` -------------------------------- ### Create FastAPI Application with FastAPI Guard Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/first-steps.md This snippet demonstrates the basic setup for a FastAPI application, including importing necessary components from the guard library. It initializes a FastAPI app and imports the SecurityMiddleware, SecurityConfig, and IPInfoManager. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig from guard.handlers.ipinfo_handler import IPInfoManager app = FastAPI() ``` -------------------------------- ### Complete FastAPI Application with Guard Security Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/first-steps.md This is a full example of a FastAPI application secured with FastAPI Guard. It includes the full setup: app initialization, `SecurityConfig` definition with various security options (IP whitelisting/blacklisting, country blocking, rate limiting), middleware addition, and a basic root endpoint. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig from guard.handlers.ipinfo_handler import IPInfoManager app = FastAPI() config = SecurityConfig( geo_ip_handler=IPInfoManager("your_ipinfo_token_here"), enable_redis=True, # Redis enabled redis_url="redis://localhost:6379", whitelist=["192.168.1.1", "2001:db8::1"], blacklist=["10.0.0.1", "2001:db8::2"], blocked_countries=["AR", "IT"], rate_limit=100, custom_log_file="security.log" ) app.add_middleware(SecurityMiddleware, config=config) @app.get("/") async def root(): return {"message": "Hello World"} ``` -------------------------------- ### FastAPI Security Middleware Setup Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/installation.md Demonstrates setting up the SecurityMiddleware for a FastAPI application with various security configurations including IPInfo for geo-blocking, Redis for storage, whitelisting/blacklisting IPs, blocking user agents, and custom logging. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig from guard.handlers.ipinfo_handler import IPInfoManager app = FastAPI() config = SecurityConfig( geo_ip_handler=IPInfoManager("your_ipinfo_token_here"), # NOTE: Required when using country blocking enable_redis=True, # Enabled by default, disable to use in-memory storage redis_url="redis://localhost:6379/0", redis_prefix="prod:security:", whitelist=["192.168.1.1", "2001:db8::1"], blacklist=["10.0.0.1", "2001:db8::2"], blocked_countries=["AR", "IT"], blocked_user_agents=["curl", "wget"], auto_ban_threshold=5, auto_ban_duration=86400, custom_log_file="security.log", ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Full Detection Engine Configuration Example with FastAPI Middleware Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/detection-engine/configuration.md A comprehensive example demonstrating the full detection engine configuration, including core security, engine optimization, performance monitoring, and optional integrations like Redis and agents. This configuration is applied to a FastAPI application using SecurityMiddleware. ```python from fastapi import FastAPI from guard import SecurityMiddleware, SecurityConfig app = FastAPI() # Full detection engine configuration config = SecurityConfig( # Core security settings enable_penetration_detection=True, auto_ban_threshold=5, auto_ban_duration=3600, passive_mode=False, # Set to True for monitoring without blocking # Detection engine optimization detection_compiler_timeout=2.0, detection_max_content_length=10000, detection_preserve_attack_patterns=True, detection_semantic_threshold=0.7, # Performance monitoring detection_anomaly_threshold=3.0, detection_slow_pattern_threshold=0.1, detection_monitor_history_size=1000, detection_max_tracked_patterns=1000, # Redis integration (optional) use_redis=True, redis_host="localhost", redis_port=6379, redis_db=0, # Agent integration (optional) enable_agent=True, agent_api_key="your-api-key", agent_enable_events=True, agent_enable_metrics=True, # Logging custom_log_file="security.log", log_level="WARNING" ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Development Setup Commands for FastAPI Guard Source: https://github.com/rennf93/fastapi-guard/blob/master/CONTRIBUTING.md Commands to set up the development environment for FastAPI Guard using Docker and Makefiles. Includes installing dependencies with 'uv' and stopping containers. ```bash # Install dependencies using 'uv' make install # To stop all containers make stop ``` -------------------------------- ### Async Initialization with Redis Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/api/security-middleware.md An example demonstrating the setup of `SecurityMiddleware` with Redis enabled for asynchronous initialization. It shows the necessary imports and how to configure `SecurityConfig` to use Redis, including providing the connection URL, before adding the middleware to the FastAPI application. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig app = FastAPI() config = SecurityConfig( enable_redis=True, redis_url="redis://localhost:6379" ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### FastAPI Guard Middleware Configuration (Python) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/examples/example-app.md This snippet shows how to initialize a FastAPI application and integrate FastAPI Guard as middleware. It includes configuring security settings such as IP whitelisting and blacklisting. Ensure the 'guard' library is installed. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig # Initialize FastAPI app app = FastAPI(title="FastAPI Guard Playground") # Configure FastAPI Guard config = SecurityConfig( # Whitelist/Blacklist whitelist=["0.0.0.0/32", "0.0.0.0"], blacklist=["192.168.1.100/32", "192.168.1.100"], ... ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Pull FastAPI Guard Example Docker Image (Bash) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/index.md This command pulls the latest version of the FastAPI Guard example application's Docker image from GitHub Container Registry. It's a quick way to get a pre-built example running. You can also specify a version tag to match a specific release of the library. ```bash # Pull the latest version docker pull ghcr.io/rennf93/fastapi-guard-example:latest # Or pull a specific version (matches library releases) docker pull ghcr.io/rennf93/fastapi-guard-example:v4.2.2 ``` -------------------------------- ### Basic SecurityMiddleware Setup in FastAPI Source: https://github.com/rennf93/fastapi-guard/blob/master/README.md This Python code demonstrates the basic setup of the SecurityMiddleware in a FastAPI application. It imports necessary classes from the guard library and initializes the FastAPI app. The SecurityMiddleware is then configured with a SecurityConfig. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig from guard.handlers.ipinfo_handler import IPInfoManager app = FastAPI() ``` -------------------------------- ### Docker Compose for FastAPI Guard Example (YAML) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/examples/example-app.md This Docker Compose configuration sets up the FastAPI Guard example application and a Redis service. It builds the application from a Dockerfile, maps ports, and configures environment variables for Redis connection and IP lookup tokens. This is the recommended way to run the example. ```yaml services: fastapi-guard-example: build: context: . dockerfile: ./Dockerfile command: uvicorn main:app --host 0.0.0.0 --reload ports: - "8000:8000" environment: - REDIS_URL=redis://redis:6379 - REDIS_PREFIX=${REDIS_PREFIX:-"fastapi_guard:"} - IPINFO_TOKEN=${IPINFO_TOKEN:-"test_token"} depends_on: redis: condition: service_started ... ``` -------------------------------- ### Run FastAPI Application with Uvicorn Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/first-steps.md This snippet shows the command-line instruction to run a FastAPI application. It uses `uvicorn` to serve the application, with the `--reload` flag enabled for development, allowing the server to restart automatically on code changes. ```bash uvicorn main:app --reload ``` -------------------------------- ### FastAPI Application Setup with Security Middleware (Python) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/advanced-customizations.md This example shows how to configure and add the SecurityMiddleware to a FastAPI application. It demonstrates using a custom GeoIP handler and specifying blocked countries. The core components are FastAPI, SecurityMiddleware, SecurityConfig, and a custom handler. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig from your_custom_module import CustomGeoIPHandler app = FastAPI() # Use custom handler instead of default IPInfoManager config = SecurityConfig( geo_ip_handler=CustomGeoIPHandler(args), blocked_countries=["CN", "RU"], # Other configuration... ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Basic FastAPI Guard Middleware Setup Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/api/security-middleware.md A fundamental example of adding the `SecurityMiddleware` to a FastAPI application. It shows the necessary imports and how to instantiate `SecurityConfig` with basic settings like rate limiting and HTTPS enforcement, then attach the middleware to the app. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig app = FastAPI() config = SecurityConfig( rate_limit=100, enable_https=True, enable_cors=True ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Agent Integration for Dynamic Security Rules Source: https://context7.com/rennf93/fastapi-guard/llms.txt This example outlines the basic setup for integrating FastAPI Guard with external agents to monitor security events and apply dynamic rules. It shows initializing FastAPI and SecurityConfig, which can then be extended to include agent-based logic for real-time security adjustments. ```python from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware app = FastAPI() # Configuration for agent integration would typically follow here, # potentially involving callbacks or event listeners. # config = SecurityConfig(...) # app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### FastAPI-Guard Configuration Validation Examples Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/configuration/security-config.md Provides examples of how FastAPI-Guard's `SecurityConfig` model validates settings upon initialization. It shows how to catch `ValidationError` for invalid values (e.g., `detection_compiler_timeout` too low) and demonstrates valid ranges for several configuration parameters. ```python # Validation examples try: config = SecurityConfig( detection_compiler_timeout=0.05 # Too low ) except ValidationError as e: print(f"Configuration error: {e}") # Valid ranges config = SecurityConfig( detection_compiler_timeout=2.0, # 0.1 - 30.0 detection_semantic_threshold=0.7, # 0.0 - 1.0 detection_anomaly_threshold=3.0, # 1.0 - 10.0 auto_ban_threshold=5, # 1 - 1000 auto_ban_duration=3600, # 60 - 86400 ) ``` -------------------------------- ### Install FastAPI Guard with Pip Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/installation.md Installs the fastapi-guard package using pip. Ensure Python 3.10 or higher is installed. ```bash pip install fastapi-guard ``` -------------------------------- ### Example SecurityCheck Implementation (Python) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/api/core-architecture.md An example demonstrating how to implement a custom security check by inheriting from the `SecurityCheck` base class. It shows the basic structure including defining `check_name` and initializing with middleware. ```python from guard.core.checks.base import SecurityCheck class ExampleCheck(SecurityCheck): check_name = "example_check" def __init__(self, middleware: "SecurityMiddleware"): self.middleware = middleware ``` -------------------------------- ### FastAPI Guard: Basic Setup with Middleware and Decorator Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/decorators/overview.md Provides a basic setup for using FastAPI Guard, including initializing `SecurityConfig`, creating a `SecurityDecorator` instance, and adding the global `SecurityMiddleware` to the FastAPI application. ```python from fastapi import FastAPI from guard import SecurityMiddleware, SecurityConfig from guard.decorators import SecurityDecorator app = FastAPI() config = SecurityConfig( enable_ip_banning=True, enable_rate_limiting=True, rate_limit_requests=100, rate_limit_window=3600 ) # Create decorator instance guard_deco = SecurityDecorator(config) # Add global middleware app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Example: Load Balancer + Proxy Configuration Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/proxy-security.md This example configuration is suitable for environments with multiple layers of proxies, such as a load balancer followed by an internal proxy. It defines multiple trusted IPs/ranges, sets the proxy depth to 2, and enables trust for X-Forwarded-Proto. ```python config = SecurityConfig( trusted_proxies=[ "10.0.0.1", # Load balancer IP "192.168.1.0/24" # Internal proxy subnet ], trusted_proxy_depth=2, # Two proxies in chain trust_x_forwarded_proto=True ) ``` -------------------------------- ### FastAPI-Guard Full Configuration Example Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/configuration/security-config.md Demonstrates a comprehensive configuration of FastAPI-Guard using the SecurityConfig class. It covers core settings, detection engine parameters, detailed security headers (HSTS, CSP, frame options, etc.), Redis integration, agent settings, and logging. This example shows how to instantiate the SecurityConfig object with numerous parameters. ```python config = SecurityConfig( # Core settings enabled=True, passive_mode=False, # Detection engine enable_penetration_detection=True, detection_compiler_timeout=2.0, detection_max_content_length=10000, detection_preserve_attack_patterns=True, detection_semantic_threshold=0.7, detection_anomaly_threshold=3.0, detection_slow_pattern_threshold=0.1, detection_monitor_history_size=1000, detection_max_tracked_patterns=1000, # Security headers security_headers={ "enabled": True, "hsts": { "max_age": 31536000, # 1 year "include_subdomains": True, "preload": False }, "csp": { "default-src": ["'self'"], "script-src": ["'self'", "https://cdn.example.com"], "style-src": ["'self'", "'unsafe-inline'"], "img-src": ["'self'", "data:", "https:"], "connect-src": ["'self'", "https://api.example.com"], "frame-ancestors": ["'none'"], "base-uri": ["'self'"], "form-action": ["'self'"], }, "frame_options": "DENY", "content_type_options": "nosniff", "xss_protection": "1; mode=block", "referrer_policy": "no-referrer", "permissions_policy": "geolocation=(), microphone=(), camera=()", "custom": { "X-Custom-Header": "CustomValue" } }, # Redis use_redis=True, redis_host="localhost", redis_port=6379, # Agent enable_agent=True, agent_api_key="your-api-key", # Logging custom_log_file="security.log", log_level="WARNING" ) ``` -------------------------------- ### Bash: Environment Variable Configuration Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/detection-engine/configuration.md Shows how to configure FastAPI Guard using environment variables for core settings, detection engine parameters, and performance monitoring thresholds. ```bash # Core settings FASTAPI_GUARD_ENABLE_PENETRATION_DETECTION=true FASTAPI_GUARD_AUTO_BAN_THRESHOLD=5 # Detection engine FASTAPI_GUARD_DETECTION_COMPILER_TIMEOUT=2.0 FASTAPI_GUARD_DETECTION_MAX_CONTENT_LENGTH=10000 FASTAPI_GUARD_DETECTION_SEMANTIC_THRESHOLD=0.7 # Performance monitoring FASTAPI_GUARD_DETECTION_ANOMALY_THRESHOLD=3.0 FASTAPI_GUARD_DETECTION_SLOW_PATTERN_THRESHOLD=0.1 ``` -------------------------------- ### Complex Route Protection Example (Python) Source: https://github.com/rennf93/fastapi-guard/blob/master/README.md This example demonstrates combining multiple FastAPI Guard decorators to create a comprehensive security layer for a sensitive admin endpoint. ```python @app.post("/api/admin/sensitive") @guard_deco.require_https() # Security requirement @guard_deco.require_auth(type="bearer") # Authentication @guard_deco.require_ip(whitelist=["10.0.0.0/8"]) # Access control @guard_deco.rate_limit(requests=5, window=3600) # Rate limiting @guard_deco.suspicious_detection(enabled=True) # Monitoring def admin_endpoint(): return {"status": "admin action"} ``` -------------------------------- ### Multiple Decorators for Rewards Endpoint (Python) Source: https://github.com/rennf93/fastapi-guard/blob/master/README.md This example shows how to apply several decorators to the rewards endpoint for usage monitoring, return pattern monitoring, and country blocking. ```python @app.get("/api/rewards") @guard_deco.usage_monitor(max_calls=50, window=3600, action="ban") @guard_deco.return_monitor("rare_item", max_occurrences=3, window=86400, action="ban") @guard_deco.block_countries(["CN", "RU", "KP"]) def rewards_endpoint(): # This endpoint is protected against: # - Excessive usage (>50 calls/hour results in ban) # - Suspicious return patterns (>3 rare items/day results in ban) # - Geographic restrictions return {"reward": "rare_item", "value": 1000} ``` -------------------------------- ### Run FastAPI Guard Example App with Docker Container Only (Bash) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/index.md This command runs a specific Docker container for the FastAPI Guard example application, mapping port 8000 on the host to port 8000 in the container. This method is an alternative to Docker Compose if you only wish to run the application container without additional services like Redis managed by Compose. It uses the latest available image from GitHub Container Registry. ```bash # Run with default settings docker run -host 0.0.0.0 -p 8000:8000 ghcr.io/rennf93/fastapi-guard-example:latest ``` -------------------------------- ### Python: Monitoring False Positives Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/detection-engine/configuration.md Illustrates how to monitor false positives, particularly when operating in passive mode, and suggests adjusting the `detection_semantic_threshold` based on analysis of logged events. ```python # Track false positive rate if config.passive_mode: # In passive mode, analyze logs for false positives # Adjust detection_semantic_threshold based on findings pass ``` -------------------------------- ### Complex Route Protection Example Source: https://github.com/rennf93/fastapi-guard/blob/master/README.md Demonstrates combining multiple decorators for comprehensive route security. ```APIDOC ## Complex Route Protection ### Description This section shows examples of applying multiple decorators to a single route for layered security. ### Method APPLIED VIA DECORATORS ### Endpoint APPLICABLE TO ANY ROUTE ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python @app.post("/api/admin/sensitive") @guard_deco.require_https() @guard_deco.require_auth(type="bearer") @guard_deco.require_ip(whitelist=["10.0.0.0/8"]) @guard_deco.rate_limit(requests=5, window=3600) @guard_deco.suspicious_detection(enabled=True) def admin_endpoint(): return {"status": "admin action"} @app.get("/api/rewards") @guard_deco.usage_monitor(max_calls=50, window=3600, action="ban") @guard_deco.return_monitor("rare_item", max_occurrences=3, window=86400, action="ban") @guard_deco.block_countries(["CN", "RU", "KP"]) def rewards_endpoint(): return {"reward": "rare_item", "value": 1000} ``` ### Response #### Success Response (200) Route specific response. #### Response Example ```json { "status": "admin action" } ``` OR ```json { "reward": "rare_item", "value": 1000 } ``` ``` -------------------------------- ### Python: Dynamic Configuration and Monitoring Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/detection-engine/configuration.md Demonstrates how to dynamically adjust security settings like the semantic threshold, add custom attack patterns, and retrieve component status at runtime. ```python from guard.handlers.suspatterns_handler import sus_patterns_handler # Adjust semantic threshold dynamically await sus_patterns_handler.configure_semantic_threshold(0.8) # Add custom patterns await sus_patterns_handler.add_pattern( r"(?i)custom_threat_pattern", custom=True ) # Check component status status = await sus_patterns_handler.get_component_status() print(f"Components active: {status}") ``` -------------------------------- ### Add Security Middleware to FastAPI Application Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/first-steps.md This snippet illustrates how to add the `SecurityMiddleware` to a FastAPI application instance using the configured `SecurityConfig`. This integrates the security features provided by FastAPI Guard into the application pipeline. ```python app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Environment-Specific Security Headers Configuration Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/http-security-headers.md This example shows how to configure security headers differently for development and production environments. It dynamically sets HSTS parameters and CSP directives based on the 'ENVIRONMENT' variable, disabling CSP in development. ```python import os is_production = os.getenv("ENVIRONMENT") == "production" config = SecurityConfig( security_headers={ "enabled": True, "hsts": { "max_age": 31536000 if is_production else 0, "include_subdomains": is_production, "preload": is_production }, "csp": { "default-src": ["'self'"], "script-src": ["'self'"].extend([] if is_production else ["'unsafe-inline'"]), "style-src": ["'self'", "'unsafe-inline'"], } if is_production else None # Disable CSP in development } ) ``` -------------------------------- ### Progressive CSP Implementation - Step 1 - Python Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/http-security-headers.md This snippet demonstrates the first step in a progressive Content Security Policy (CSP) implementation with FastAPI Guard, using a permissive policy. It includes directives for default, script, and style sources, along with a report-uri. This approach allows for gradual tightening of security. ```python # Step 1: Permissive policy config = SecurityConfig( security_headers={ "csp": { "default-src": ["'self'"], "script-src": ["'self'", "'unsafe-inline'"], "style-src": ["'self'", "'unsafe-inline'"], "report-uri": ["/api/csp-report"] } } ) ``` -------------------------------- ### Example: Single Reverse Proxy Configuration Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/proxy-security.md This configuration is for a typical setup with a single reverse proxy like Nginx or HAProxy. It sets the trusted proxy IP, specifies a proxy depth of 1, and enables trust for the X-Forwarded-Proto header to correctly identify HTTPS requests. ```python config = SecurityConfig( trusted_proxies=["10.0.0.1"], # Your Nginx/HAProxy IP trusted_proxy_depth=1, # One proxy trust_x_forwarded_proto=True # Trust HTTPS status from proxy ) ``` -------------------------------- ### Configuring CSP for Third-Party Resources Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/http-security-headers.md This example shows how to configure Content Security Policy (CSP) in FastAPI Guard to allow specific third-party resources. It includes directives for default sources, scripts, styles, and fonts, specifying allowed domains like cdn.jsdelivr.net and fonts.googleapis.com. ```python config = SecurityConfig( security_headers={ "csp": { "default-src": ["'self'"], "script-src": ["'self'", "https://cdn.jsdelivr.net"], "style-src": ["'self'", "https://fonts.googleapis.com"], "font-src": ["'self'", "https://fonts.gstatic.com"] } } ) ``` -------------------------------- ### HSTS Rollout Strategy Configuration Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/http-security-headers.md Implements a phased rollout strategy for HSTS. Starts with a short `max_age` and `include_subdomains=False` for initial testing, then increases duration and includes subdomains, and finally enables `preload` for production environments. ```python # Phase 1: Short duration (5 minutes) config = SecurityConfig( security_headers={ "hsts": { "max_age": 300, "include_subdomains": False, "preload": False } } ) # Phase 2: Longer duration (1 week) config = SecurityConfig( security_headers={ "hsts": { "max_age": 604800, "include_subdomains": True, "preload": False } } ) # Phase 3: Production (1 year + preload) config = SecurityConfig( security_headers={ "hsts": { "max_age": 31536000, # Required for preload "include_subdomains": True, # Required for preload "preload": True } } ) ``` -------------------------------- ### HandlerInitializer Methods - Python Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/api/core-architecture.md The HandlerInitializer class centralizes the setup logic for various handlers used by the middleware. It includes methods to initialize Redis connections, agents, and dynamic rule managers. This ensures that all necessary components are properly configured before the middleware starts processing requests. ```python class HandlerInitializer: async def initialize_redis_handlers(self) -> None: """Initialize Redis for all handlers.""" ... async def initialize_agent_for_handlers(self) -> None: """Initialize agent in all handlers.""" ... async def initialize_agent_integrations(self) -> None: """Initialize agent and its integrations.""" ... async def initialize_dynamic_rule_manager(self) -> None: """Initialize dynamic rule manager if configured.""" ... ``` -------------------------------- ### Configure Security Settings for FastAPI Guard Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/first-steps.md This snippet shows how to create a `SecurityConfig` object for FastAPI Guard. It includes settings for IP geolocation with an IPInfoManager, database path, Redis integration, rate limiting, auto-banning, and custom logging. Note that the IPInfo token is required for geolocation. ```python config = SecurityConfig( geo_ip_handler=IPInfoManager("your_ipinfo_token_here"), # NOTE: Required for geolocation db_path="data/ipinfo/country_asn.mmdb", # Optional, default: ./data/ipinfo/country_asn.mmdb enable_redis=True, # Enable Redis integration redis_url="redis://localhost:6379", # Redis URL rate_limit=100, # Max requests per minute auto_ban_threshold=5, # Ban after 5 suspicious requests custom_log_file="security.log" # Custom log file ) ``` -------------------------------- ### Production Setup with File Logging (Python) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/configuration/logging.md Demonstrates setting up FastAPI Guard for production using file and console logging. It configures a custom log file, disables normal request logging to reduce noise, and sets security events to WARNING level. Dependencies include `FastAPI`, `SecurityConfig`, and `SecurityMiddleware` from the `guard` library. ```Python from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware app = FastAPI() # Production configuration config = SecurityConfig( # File + console logging for audit trail custom_log_file="/var/log/fastapi-guard/security.log", # Disable normal request logging to reduce noise log_request_level=None, # Keep security events at WARNING level log_suspicious_level="WARNING", # Other security settings... enable_redis=True, enable_penetration_detection=True, ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Python: Security Configuration Validation Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/detection-engine/configuration.md Illustrates how the Detection Engine validates security configurations upon startup, catching and reporting invalid settings such as an excessively low compiler timeout. ```python try: config = SecurityConfig( detection_compiler_timeout=0.05 # Too low, will be adjusted ) except ValueError as e: print(f"Configuration error: {e}") ``` -------------------------------- ### Apply Route-Level Security with FastAPI Guard Decorators Source: https://github.com/rennf93/fastapi-guard/blob/master/README.md Implement granular security controls on individual FastAPI routes using `fastapi-guard` decorators. This example demonstrates applying rate limiting, IP whitelisting, and country blocking to specific endpoints. Ensure `fastapi-guard` is installed and the `SecurityMiddleware` is added globally. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig from guard.decorators import SecurityDecorator app = FastAPI() config = SecurityConfig() # Create decorator instance guard_deco = SecurityDecorator(config) # Apply decorators to specific routes @app.get("/api/public") def public_endpoint(): return {"data": "public"} @app.get("/api/limited") @guard_deco.rate_limit(requests=10, window=300) # 10 requests per 5 minutes def limited_endpoint(): return {"data": "limited"} @app.get("/api/restricted") @guard_deco.require_ip(whitelist=["192.168.1.0/24"]) @guard_deco.block_countries(["CN", "RU"]) def restricted_endpoint(): return {"data": "restricted"} # Add global middleware app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Apply Multiple Security Decorators to a FastAPI Route Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/api/decorators.md Demonstrates how to apply multiple security decorators from FastAPI Guard to a single FastAPI endpoint. This example shows rate limiting, IP whitelisting, and country blocking applied to a sensitive endpoint. Ensure FastAPI and FastAPI Guard are installed. The `SecurityConfig` object is initialized and passed to `SecurityDecorator`. ```python from fastapi import FastAPI from guard import SecurityConfig from guard.decorators import SecurityDecorator app = FastAPI() config = SecurityConfig() guard_deco = SecurityDecorator(config) @app.get("/api/sensitive") @guard_deco.rate_limit(requests=5, window=300) @guard_deco.require_ip(whitelist=["10.0.0.0/8"]) @guard_deco.block_countries(["CN", "RU"]) def sensitive_endpoint(): return {"data": "sensitive"} ``` -------------------------------- ### FastAPI Middleware Setup with SecurityConfig Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/llms.txt Demonstrates how to integrate FastAPI-Guard's SecurityMiddleware into a FastAPI application. It shows the creation of a SecurityConfig object to define various security parameters such as whitelists, blacklists, rate limits, and cloud provider blocking, and then adds the middleware to the application. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig app = FastAPI() # Basic configuration config = SecurityConfig( whitelist=["192.168.1.1"], blacklist=["10.0.0.1"], rate_limit=100, # requests per minute auto_ban_threshold=5, # ban after 5 suspicious requests block_cloud_providers={"AWS", "GCP", "AZURE"}, allowed_countries=["US", "CA", "GB"], enable_security_headers=True, ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Match Limits to Functionality Examples Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/decorators/content-filtering.md Provides examples of setting appropriate request size limits based on the expected functionality of different endpoints. ```APIDOC ## POST /api/text/process ### Description Endpoint for processing text data with a small request size limit (64KB). ### Method POST ### Endpoint /api/text/process ### Parameters #### Request Body * **text** (str) - The text content to process. ### Response #### Success Response (200) - **result** (str) - The processing result. #### Response Example { "result": "Processed text" } ## POST /api/image/upload ### Description Endpoint for uploading images with a medium request size limit (5MB). ### Method POST ### Endpoint /api/image/upload ### Parameters #### Request Body * **image** (file) - The image file to upload. ### Response #### Success Response (200) - **status** (str) - Upload status. #### Response Example { "status": "Image uploaded" } ## POST /api/video/upload ### Description Endpoint for uploading videos with a large request size limit (100MB). ### Method POST ### Endpoint /api/video/upload ### Parameters #### Request Body * **video** (file) - The video file to upload. ### Response #### Success Response (200) - **status** (str) - Upload status. #### Response Example { "status": "Video uploaded" } ``` -------------------------------- ### Implement Custom Header Validation Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/decorators/content-filtering.md Provides an example of custom validation logic for request headers using the @guard_deco.custom_validation decorator with a custom async function. This example validates the 'API-Version' header. ```python from fastapi import Request, Response async def validate_api_version(request: Request) -> Response | None: """Validate API version header.""" version = request.headers.get("API-Version") if not version: return Response("Missing API-Version header", status_code=400) if version not in ["1.0", "2.0", "2.1"]: return Response("Unsupported API version", status_code=400) return None @app.get("/api/versioned") @guard_deco.custom_validation(validate_api_version) def versioned_endpoint(): return {"message": "Version validated"} ``` -------------------------------- ### Documentation Building Command for FastAPI Guard Source: https://github.com/rennf93/fastapi-guard/blob/master/CONTRIBUTING.md Command to build and serve the documentation for FastAPI Guard locally using MkDocs. ```bash make serve-docs ``` -------------------------------- ### Applying Strict IP Whitelisting in FastAPI Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/decorators/access-control.md Shows how to start with a restrictive IP access control policy, allowing access only from specific internal network ranges. This is the first step in a 'start restrictive, then open up' strategy. ```python from fastapi import FastAPI from fastapi_guard import guard_deco app = FastAPI() # Start with company network only @app.get("/internal-resource") @guard_deco.require_ip(whitelist=["10.0.0.0/8"]) def internal_resource(): return {"data": "Internal data"} ``` -------------------------------- ### Custom Logger Setup - FastAPI Guard Utilities Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/configuration/logging.md Manually set up a custom logger for FastAPI Guard using the `setup_custom_logging` function from `guard.utils`. This function supports both console-only logging (by passing `None`) and console with file logging (by providing a file path). It automatically handles directory creation and uses the 'fastapi_guard' namespace. ```python from guard.utils import setup_custom_logging # Manual setup (if needed outside of middleware) # Console only (no file) logger = setup_custom_logging(None) # Console + file logging logger = setup_custom_logging("security.log") # The logger uses the "fastapi_guard" namespace # All handlers automatically use sub-namespaces like: # - "fastapi_guard.handlers.redis" # - "fastapi_guard.handlers.cloud" # - "fastapi_guard.handlers.ipban" ``` -------------------------------- ### Startup Initialization for Security Middleware Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/api/security-middleware.md This snippet demonstrates how to initialize the SecurityMiddleware upon application startup. It iterates through the application's middleware to find the SecurityMiddleware instance and calls its `initialize` method. This is crucial for setting up security handlers and configurations before the application starts processing requests. ```python from fastapi import FastAPI from guard.middleware import SecurityMiddleware app = FastAPI() @app.on_event("startup") async def startup_event(): # Get middleware instance for middleware in app.user_middleware: if isinstance(middleware.cls, SecurityMiddleware): await middleware.cls.initialize() ``` -------------------------------- ### Configure Strict CSP - None Sources Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/http-security-headers.md Sets up a strict Content Security Policy (CSP) where all content is blocked by default, with specific directives for scripts and styles originating from the same source. This is a strong security posture. ```python config = SecurityConfig( security_headers={ "csp": { "default-src": ["'none'"], "script-src": ["'self'"], "style-src": ["'self'"], "img-src": ["'self'"], "connect-src": ["'self'"], "font-src": ["'self'"], "base-uri": ["'self'"], "form-action": ["'self'"], "frame-ancestors": ["'none'"], "upgrade-insecure-requests": [] } } ) ``` -------------------------------- ### FastAPI Guard: Route-Level Security Decorators Example Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/decorators/overview.md Demonstrates applying security decorators to specific FastAPI routes. This example shows how to use `rate_limit` and `require_ip` decorators to enforce custom security policies on an endpoint, in addition to global middleware. ```python from fastapi import FastAPI from guard import SecurityConfig from guard.decorators import SecurityDecorator app = FastAPI() config = SecurityConfig() guard_deco = SecurityDecorator(config) @app.get("/api/public") def public_endpoint(): return {"message": "This uses global security settings"} @app.get("/api/restricted") @guard_deco.rate_limit(requests=5, window=300) @guard_deco.require_ip(whitelist=["10.0.0.0/8"]) def restricted_endpoint(): return {"message": "This has additional route-specific restrictions"} ``` -------------------------------- ### Layered Content Controls Example Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/decorators/content-filtering.md Demonstrates applying multiple content control decorators in sequence for enhanced security. This example includes checks for JSON content type, maximum request size, trusted referrer, and blocking of bot user agents. ```python @guard_deco.content_type_filter(["application/json"]) @guard_deco.max_request_size(1024 * 1024) @guard_deco.require_referrer(["myapp.com"]) @guard_deco.block_user_agents([r".*bot.*"]) ``` -------------------------------- ### Development Setup with Console Only Logging (Python) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/configuration/logging.md Illustrates configuring FastAPI Guard for development with console-only logging. This setup enables all logging for debugging purposes, sets the log file to None, and activates passive mode for testing. It requires `FastAPI`, `SecurityConfig`, and `SecurityMiddleware`. ```Python from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware app = FastAPI() # Development configuration config = SecurityConfig( # Console-only output for development custom_log_file=None, # No file logging # Enable all logging for debugging log_request_level="INFO", log_suspicious_level="WARNING", # Other settings... passive_mode=True, # Log-only mode for testing ) app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Configure Redis-based Distributed State for FastAPI-Guard Source: https://context7.com/rennf93/fastapi-guard/llms.txt This snippet shows the initial setup for using Redis to manage security state across multiple instances of a FastAPI application. It imports necessary components from FastAPI and FastAPI-Guard, including `SecurityConfig` and `SecurityMiddleware`. The actual Redis configuration would typically follow this setup. ```python from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware app = FastAPI() # Configuration for Redis-based distributed state would follow here # Example: # config = SecurityConfig( # redis_url="redis://localhost:6379/0", # use_redis=True # ) # app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Implement Gradual Rollout Strategies (Python) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/detection-engine/performance-tuning.md Demonstrates two strategies for gradual rollout: a simple feature flag for new patterns and a canary deployment based on user request hashing to control access to new detection settings. It uses a boolean flag `NEW_PATTERNS_ENABLED` and conditional logic based on the hash of the request's client host. ```python # Feature flag for new patterns NEW_PATTERNS_ENABLED = False if NEW_PATTERNS_ENABLED: await sus_patterns_handler.add_pattern(new_pattern, custom=True) # Canary deployment if hash(request.client.host) % 100 < 10: # 10% of users # Use new detection settings config.detection_semantic_threshold = 0.6 else: # Use stable settings config.detection_semantic_threshold = 0.7 ``` -------------------------------- ### RedisManager - Get Key Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/api/redis-manager.md Retrieves the value of a namespaced key from Redis. ```APIDOC ## GET /redis/key/{namespace}/{key} ### Description Retrieves the value of a namespaced key from Redis. Keys are prefixed with the provided namespace. ### Method GET ### Endpoint /redis/key/{namespace}/{key} ### Parameters #### Path Parameters - **namespace** (string) - Required - The namespace for the key. - **key** (string) - Required - The specific key to retrieve. ### Response #### Success Response (200) - **value** (Any) - The value associated with the key. #### Response Example ```json { "value": "retrieved_value" } ``` ``` -------------------------------- ### Configure CSP for Single Page Applications Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/security/http-security-headers.md Configures a CSP suitable for Single Page Applications (SPAs). It allows content from the same origin, permits inline styles and data URIs for images, and specifies allowed external resources for connections and fonts. ```python config = SecurityConfig( security_headers={ "csp": { "default-src": ["'self'"], "script-src": ["'self'"], "style-src": ["'self'", "'unsafe-inline'"], # For dynamic styles "img-src": ["'self'", "data:", "https:"], "connect-src": ["'self'", "https://api.example.com"], "font-src": ["'self'", "https://fonts.gstatic.com"], "frame-ancestors": ["'none'"], "base-uri": ["'self'"] } } ) ``` -------------------------------- ### BehaviorRule Examples: Advanced Pattern Matching (JSON Path, Regex, Status Code) Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/api/behavior-manager.md Provides examples of BehaviorRule configurations for the `return_pattern` type, showcasing advanced pattern matching using JSON paths, regular expressions, and HTTP status codes. These allow for more granular control over what response characteristics trigger an action. ```python # JSON path pattern json_rule = BehaviorRule( rule_type="return_pattern", threshold=5, pattern="json:result.reward.rarity==legendary", window=86400, action="ban" ) # Regex pattern regex_rule = BehaviorRule( rule_type="return_pattern", threshold=10, pattern="regex:(win|victory|success)", window=3600, action="alert" ) # Status code pattern status_rule = BehaviorRule( rule_type="return_pattern", threshold=100, pattern="status:200", window=3600, action="log" ) ``` -------------------------------- ### Implement Custom GeoIPHandler in Python Source: https://github.com/rennf93/fastapi-guard/blob/master/docs/tutorial/advanced-customizations.md An example implementation of a custom GeoIPHandler that uses a local database and optional Redis caching. It demonstrates how to initialize the handler, download or load the GeoIP database, and integrate with the Redis handler provided by FastAPI Guard. ```python from guard.protocols.geo_ip_protocol import GeoIPHandler from guard.protocols.redis_protocol import RedisHandlerProtocol class CustomGeoIPHandler: """Custom handler using Custom GeoIP database""" def __init__(self, license_key: str, db_path: str = "CustomGeoIP.mmdb"): self._initialized = False self.license_key = license_key self.db_path = db_path self.reader = None self.redis = None # Will store the FastAPI Guard's Redis handler @property def is_initialized(self) -> bool: return self.reader is not None async def initialize(self) -> None: """Initialize by downloading or loading the Custom GeoIP database""" import os import somelibrary # Check if we have a cached copy in Redis if self.redis: cached_db = await self.redis.get_key("custom", "database") if cached_db: with open(self.db_path, "wb") as f: f.write(cached_db if isinstance(cached_db, bytes) else cached_db.encode("latin-1")) self.reader = somelibrary.Reader(self.db_path) self._initialized = True return # Download if needed (simplified - in a real app, use your API) if not os.path.exists(self.db_path): # Custom code to download database using license_key pass # Open the database self.reader = somelibrary.Reader(self.db_path) self._initialized = True async def initialize_redis(self, redis_handler: RedisHandlerProtocol) -> None: self.redis = redis_handler def get_country(self, ip: str) -> str | None: if self.reader: return self.reader.country_name_for(ip) return None ```