### Install All Araxys Features Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Install the complete Araxys package, including all optional dependencies. This provides access to all security modules and integrations. ```bash pip install araxys[all] ``` -------------------------------- ### Install Araxys with Prometheus Metrics Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Install Araxys with Prometheus support to expose API metrics. This allows for monitoring of request counts, latency, and other performance indicators. ```bash pip install araxys[prometheus] ``` -------------------------------- ### Install Araxys with Webhook Support Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Install Araxys with webhook support to enable the delivery of security events to external services. This is useful for real-time security monitoring and alerting. ```bash pip install araxys[webhooks] ``` -------------------------------- ### Install Araxys Core Package Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Install the core Araxys package for basic functionality using pip. This version includes in-memory backends for security features. ```bash pip install araxys ``` -------------------------------- ### Install Araxys with Redis Support Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Install Araxys with Redis support for production environments. This enables persistent storage for security features like sessions and rate limiting. ```bash pip install araxys[redis] ``` -------------------------------- ### Manage API Keys with Araxys CLI Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Install the Araxys CLI with `pip install "araxys[cli]"` and configure your Redis URL using the `ARAXYS_REDIS_URL` environment variable. The CLI allows creating, listing, and revoking API keys. ```bash # Install with CLI dependencies pip install "araxys[cli]" # Configure your storage export ARAXYS_REDIS_URL="redis://localhost:6379" # Create a new key araxys keys create --owner "service-a" --scopes "read,write" --ttl 90 # List active keys in a beautiful table araxys keys list # Revoke a key by its prefix araxys keys revoke [prefix] ``` -------------------------------- ### Install Araxys with OpenTelemetry Tracing Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Install Araxys with OpenTelemetry support to enable distributed tracing for your API requests. This helps in monitoring and debugging. ```bash pip install araxys[opentelemetry] ``` -------------------------------- ### Initialize AraxysShield with Full Protection Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Set up the AraxysShield with a comprehensive configuration for full API protection. Ensure your secret key is at least 32 characters long. Redis is optional; omitting `redis_url` uses in-memory storage. ```python from fastapi import FastAPI from araxys import AraxysShield, AraxysConfig app = FastAPI() shield = AraxysShield( app, AraxysConfig( secret_key="super-secret-key-at-least-32-chars!", redis_url="redis://localhost:6379", # Optional — omit for in-memory cors={"allow_origins": ["https://myapp.com"], "allow_methods": ["GET", "POST"]}, ip_access={"enabled": True, "mode": "block", "blocklist": ["10.0.0.0/8"]}, rate_limit={"window_seconds": 60, "max_requests": 100}, honeypotஸ்ப{"paths": ["/admin/config", "/wp-admin", "/.env"]}, brute_forceஸ்ப{"enabled": True, "max_attempts": 5}, csrfஸ்ப{"enabled": True}, secure_headersஸ்ப{"enabled": True}, sanitizeஸ்ப{"enabled": True}, auditஸ்ப{"encrypt": True, "log_file": "audit.log"}, telemetryஸ்ப{"enabled": True, "service_name": "my-api"}, metricsஸ்ப{"enabled": True}, ), ) ``` -------------------------------- ### Initialize Araxys Shield Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Instantiate AraxysShield with the FastAPI app and configuration. Ensure `secret_key` is a high-entropy string and `redis_url` is provided for necessary features. ```python from araxys import AraxysShield, AraxysConfig shield = AraxysShield(app, AraxysConfig(secret_key="...", redis_url="...")) ``` -------------------------------- ### Enable Observability with OTEL and Prometheus Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Configure OpenTelemetry tracing and Prometheus metrics by setting `telemetry.enabled` and `metrics.enabled` to `True` in `AraxysConfig`. Service name can also be configured. ```python config = AraxysConfig( secret_key="...", telemetry={"enabled": True, "service_name": "my-api"}, metrics={"enabled": True}, ) # Spans auto-created for every HTTP request. # GET /metrics exposes Prometheus counters and histogram. ``` -------------------------------- ### Create a New Araxys Key Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Command to create a new API key with specified owner and scopes. The scopes determine the key's permissions. ```bash araxys keys create --owner "name" --scopes "read,write" ``` -------------------------------- ### Initialize Araxys Shield with FastAPI Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Integrate Araxys into your FastAPI application by initializing the AraxysShield with your app instance and configuration. This setup protects your API with three lines of code. ```python from fastapi import FastAPI from araxys import AraxysShield, AraxysConfig app = FastAPI() shield = AraxysShield(app, AraxysConfig(secret_key="your-32-char-secret-key-here!!!!")) # That's it. Your API is now protected. 🛡️ ``` -------------------------------- ### Create and Use API Keys with Araxys Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Generate API keys with specified owners, scopes, and time-to-live (TTL). The raw key is shown only once upon creation. Use `require_api_key` dependency to protect endpoints. ```python from fastapi import Depends from araxys import Scope from araxys.api_keys.dependencies import require_api_key from araxys.api_keys.models import APIKeyRecord # Create a key key = await shield.api_key_manager.create_key( owner="service-a", scopes=[Scope.READ, Scope.WRITE], ttl_days=90, ) print(f"Save this key: {key.raw_key}") # Shown only once! # Protect an endpoint @app.get("/data") async def get_data( key: APIKeyRecord = Depends( require_api_key(Scope.READ, manager=shield.api_key_manager) ), ): return {"data": "protected", "owner": key.owner} ``` -------------------------------- ### Configure Webhook Delivery Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Enable and configure webhook delivery for events like rate limit exceedances or honeypot triggers. Specify URLs for each event type. Delivery uses exponential retries and is non-blocking. ```python config = AraxysConfig( secret_key="...", webhooks={ "enabled": True, "urls": { "rate_limit_exceeded": ["https://hooks.slack.com/"], "honeypot_triggered": ["https://api.security.example.com/alerts"], }, }, ) # Events delivered with 1s/2s/4s exponential retry, non-blocking. ``` -------------------------------- ### Configure Araxys with Environment Variables Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Set environment variables with the ARAXYS_ prefix to configure various security settings. This is a common method for deploying Araxys in production environments. ```bash export ARAXYS_SECRET_KEY="your-production-secret-key-here!" export ARAXYS_REDIS_URL="redis://localhost:6379" export ARAXYS_CORS__ALLOW_ORIGINS='["https://myapp.com"]' export ARAXYS_IP_ACCESS__ENABLED="true" export ARAXYS_METRICS__ENABLED="true" ``` -------------------------------- ### Configure IP Access Control in Araxys Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Set up IP access control to either allow or block specific IP addresses or ranges. The 'allow' mode requires an explicit `allowlist`. ```python # Allow mode — only listed IPs get through config = AraxysConfig( secret_key="...", ip_accessஸ்ப{"enabled": True, "mode": "allow", "allowlist": ["10.0.1.0/24", "192.168.1.100"]}, ) ``` -------------------------------- ### Apply Password Policy Dependency Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Enforce password complexity rules using `password_policy_dependency`. Pass a `PasswordPolicyConfig` instance to customize requirements. ```python from araxys import password_policy_dependency, PasswordPolicyConfig @app.post("/register") async def register(password: str = Depends(password_policy_dependency(PasswordPolicyConfig()))): return {"status": "ok"} ``` -------------------------------- ### Run Pytest Tests with Coverage Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Run pytest tests and generate a code coverage report. This command includes the --cov flag to measure coverage and --cov-report=term-missing to display missing lines in the terminal. ```bash uv run pytest tests/ --cov=araxys --cov-report=term-missing ``` -------------------------------- ### Configure Brute Force and Password Policy Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Enforce brute force protection and a password policy for authentication endpoints. The `password_policy_dependency` automatically validates passwords against defined criteria (e.g., min 8 chars, upper, lower, digit, special). ```python from fastapi import Depends from araxys import password_policy_dependency, PasswordPolicyConfig @app.post("/auth/register") async def register( password: str = Depends(password_policy_dependency(PasswordPolicyConfig())), ): # Password already validated — min 8 chars, upper, lower, digit, special return {"status": "registered"} ``` -------------------------------- ### Implement JWT Authentication with Token Rotation Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Issue JWT token pairs (access and refresh) upon login, and allow token rotation using the refresh token. Protected endpoints use `require_jwt` dependency, validating the access token and scopes. ```python from fastapi import Depends from araxys import Scope from araxys.jwt_auth.dependencies import require_jwt from araxys.jwt_auth.tokens import TokenPayload # Login — issue tokens @app.post("/auth/login") async def login(username: str, password: str): # ... validate credentials ... pair = await shield.jwt_manager.create_token_pair( subject=user.id, scopes=[Scope.READ, Scope.WRITE], ) return pair.model_dump() # Refresh — rotate tokens (old refresh token is blacklisted) @app.post("/auth/refresh") async def refresh(refresh_token: str): new_pair = await shield.jwt_manager.rotate_tokens(refresh_token) return new_pair.model_dump() # Protected endpoint @app.get("/profile") async def profile( user: TokenPayload = Depends( require_jwt(Scope.READ, jwt_manager=shield.jwt_manager) ), ): return {"user_id": user.sub, "scopes": user.scopes} ``` -------------------------------- ### Set Araxys Context with Redis URL Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Use this command to set the Redis connection URL for the Araxys CLI. Ensure the URL is correctly formatted. ```bash export ARAXYS_REDIS_URL="redis://..." ``` -------------------------------- ### Configure CORS with Araxys Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Customize Cross-Origin Resource Sharing settings by providing `allow_origins` and `allow_methods` to `CORSConfig`. Defaults to an empty `allow_origins`, which can cause 400 errors for cross-origin requests. ```python from araxys import CORSConfig config = AraxysConfig( secret_key="...", cors=CORSConfig(allow_origins=["https://app.example.com"], allow_methods=["GET", "POST"]), ) ``` -------------------------------- ### Programmatic Araxys Configuration Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Configure Araxys settings programmatically using Python classes for detailed control over security features like CORS, rate limiting, and honeypots. Ensure all necessary configuration classes are imported. ```python from araxys import AraxysConfig, RateLimitConfig, HoneypotConfig, CORSConfig config = AraxysConfig( secret_key="...", cors=CORSConfig(allow_origins=["https://app.example.com"]), ip_access={"enabled": True, "mode": "hybrid"}, rate_limit=RateLimitConfig( max_requests=200, window_seconds=120, ban_threshold=10, ban_duration_seconds=600, escalation_multiplier=3.0, ), honeypot=HoneypotConfig( paths=["/admin", "/wp-login.php", "/.git/config"], ban_duration_seconds=7200, ), brute_force={"enabled": True, "max_attempts": 5}, csrf={"enabled": True}, telemetry={"enabled": True, "service_name": "my-api"}, metrics={"enabled": True}, jwt={"access_token_ttl_minutes": 15, "refresh_token_ttl_days": 30}, audit={"encrypt": True, "log_file": "/var/log/araxys/audit.log"}, ) ``` -------------------------------- ### Run Pytest Tests Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Execute all tests for the Araxys project using pytest. This command runs tests verbosely to provide detailed output. ```bash uv run pytest tests/ -v ``` -------------------------------- ### Implement CSRF Protection for a Route Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Protect specific routes against Cross-Site Request Forgery (CSRF) attacks using the `csrf_protected` dependency. This is an opt-in mechanism for state-changing endpoints. ```python from fastapi import Depends from araxys import csrf_protected, CSRFConfig # Per-route opt-in — only state-changing endpoints @app.post("/submit", dependencies=[Depends(csrf_protected(CSRFConfig()))]) async def submit_form(): return {"status": "ok"} ``` -------------------------------- ### Implement CSRF Protection on a Route Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Protect specific routes against Cross-Site Request Forgery by including `csrf_protected` in route dependencies. An empty `CSRFConfig` uses default settings. ```python from fastapi import Depends from araxys import csrf_protected, CSRFConfig @app.post("/submit", dependencies=[Depends(csrf_protected(CSRFConfig()))]) async def submit_form(): return {"status": "ok"} ``` -------------------------------- ### Configure CORS Policy in Araxys Source: https://github.com/samuel-urrego/araxys/blob/main/README.md Configure Cross-Origin Resource Sharing (CORS) by specifying allowed origins and methods. If `allow_origins` is empty, all cross-origin requests are denied by default (fail-closed). ```python # Fail-closed by default — explicitly allow origins config = AraxysConfig( secret_key="...", cors={"allow_origins": ["https://app.example.com"], "allow_methods": ["GET", "POST", "PUT"]}, ) # CORS middleware is always registered. Empty allow_origins = deny all. ``` -------------------------------- ### Secure Route with Scoped API Keys Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Restrict access to routes based on API key scopes using `require_api_key`. Define required scopes using the `Scope` enum. ```python from fastapi import Depends from araxys.api_keys.dependencies import require_api_key from araxys.core.types import Scope @app.get("/secure", dependencies=[Depends(require_api_key(scopes=[Scope.WRITE]))]) async def secure_endpoint(): return {"status": "ok"} ``` -------------------------------- ### Araxys Middleware Chain Order Source: https://github.com/samuel-urrego/araxys/blob/main/README.md The order of middleware in the chain is crucial for security. Outer middleware is applied first, followed by inner middleware. This specific order ensures that requests are processed through various security layers sequentially. ```text CORS → SecureHeaders → Telemetry → RateLimit → BruteForce → IP Access → Honeypot → Sanitize ``` -------------------------------- ### Perform Graceful Shutdown Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Call `shield.shutdown()` during application shutdown to ensure proper cleanup of background tasks, including the event bus, session cleanup loop, and webhook delivery tasks. ```python # On app shutdown await shield.shutdown() # Stops event bus, session cleanup loop, and webhook delivery tasks. ``` -------------------------------- ### Revoke an Existing Araxys Key Source: https://github.com/samuel-urrego/araxys/blob/main/AI.md Command to revoke an existing API key using its prefix. This action cannot be undone. ```bash araxys keys revoke ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.