Telemetry and monitoring agent for FastAPI Guard security middleware
Project description
fastapi-guard-agent is a reporting agent for FastAPI Guard. It collects and sends metrics and events from FastAPI Guard to your SaaS backend.
Documentation
🎮 Join our Discord Community - Connect with other developers!
📚 Documentation - Full technical documentation and deep dive into its inner workings.
Features
- Seamless Integration: Works out-of-the-box with
fastapi-guardto collect security events and metrics. - Asynchronous by Design: Built on
asyncioto ensure non-blocking operations and high performance. - Resilient Data Transport: Features a robust HTTP transport layer with automatic retries, exponential backoff, and a circuit breaker pattern for reliable data delivery.
- Efficient Buffering: Events and metrics are buffered in memory and can be persisted to Redis for durability, preventing data loss on application restarts.
- Dynamic Configuration: Can fetch dynamic security rules from the FastAPI Guard SaaS backend, allowing you to update security policies on the fly without redeploying your application.
- Extensible: Uses a protocol-based design, allowing for custom implementations of components like the transport layer or Redis handler.
- Comprehensive Telemetry: Collects detailed
SecurityEventandSecurityMetricdata, providing insights into your application's security posture and performance.
Installation
To install fastapi-guard-agent, use pip:
pip install fastapi-guard-agent
Usage
Basic Setup
Here's a quick example of how to integrate fastapi-guard-agent into a FastAPI application.
First, you need to configure the agent. The agent is a singleton, and you can initialize it in your application's startup event.
# main.py
import asyncio
from fastapi import FastAPI, Request
from fastapi_guard.fastapi_guard import Guard
from guard_agent.client import guard_agent
from guard_agent.models import AgentConfig, SecurityEvent
from guard_agent.utils import get_current_timestamp
app = FastAPI()
# 1. Configure the Guard Agent
agent_config = AgentConfig(
api_key="YOUR_API_KEY",
project_id="YOUR_PROJECT_ID",
# Optional: fine-tune buffering and other settings
buffer_size=500,
flush_interval=60,
)
agent = guard_agent(agent_config)
# 2. Define a custom handler to send data to the agent
class AgentSecurityEventHandler:
async def handle(self, request: Request, exc: Exception):
# This is a simplified example.
# You would create more specific events based on the exception.
event = SecurityEvent(
timestamp=get_current_timestamp(),
event_type="suspicious_request",
ip_address=request.client.host,
endpoint=request.url.path,
method=request.method,
action_taken="log",
reason=str(exc),
)
await agent.send_event(event)
# You can also re-raise the exception or return a response
# raise exc
# 3. Configure fastapi-guard to use your handler
guard = Guard(handlers={"suspicious_request": AgentSecurityEventHandler()})
# 4. Use the guard in your endpoints
@app.get("/")
@guard.protect("suspicious_request")
async def root():
return {"message": "Hello World"}
# 5. Start and stop the agent with FastAPI's lifespan events
@app.on_event("startup")
async def startup_event():
# Optional: If you use Redis for buffer persistence
# from redis.asyncio import Redis
# from fastapi_guard.redis_handler import RedisHandler
# redis_handler = RedisHandler(redis=Redis.from_url("redis://localhost"))
# await agent.initialize_redis(redis_handler)
await agent.start()
@app.on_event("shutdown")
async def shutdown_event():
await agent.stop()
In this example:
- We create an
AgentConfigwith our credentials. - We create a simple handler that constructs a
SecurityEventand sends it to the agent usingagent.send_event(). - We tell
fastapi-guardto use this handler for a custom protection key. - We use
@guard.protect()on an endpoint. - We use FastAPI's
startupandshutdownevents to manage the agent's lifecycle.
Now, when a request is made to the / endpoint, fastapi-guard will invoke our handler, which in turn sends a security event to the agent. The agent will buffer it and send it to the backend.
Detailed Configuration Options
The fastapi-guard-agent is configured using the AgentConfig pydantic model. You create an instance of this class and pass it to the guard_agent factory function to initialize the agent.
from guard_agent.client import guard_agent
from guard_agent.models import AgentConfig
config = AgentConfig(
api_key="YOUR_API_KEY",
project_id="YOUR_PROJECT_ID",
)
agent = guard_agent(config)
AgentConfig Attributes
api_key: str: Required. Your API key for the FastAPI Guard SaaS platform.endpoint: str: The API endpoint for the SaaS platform.- Default:
https://api.fastapi-guard.com
- Default:
project_id: str | None: Your project ID. This is used to associate data with the correct project in the backend.- Default:
None
- Default:
buffer_size: int: The maximum number of events and metrics to hold in the in-memory buffer before they are flushed.- Default:
100
- Default:
flush_interval: int: The interval in seconds at which the buffer is automatically flushed, sending its contents to the backend.- Default:
30
- Default:
enable_metrics: bool: A global switch to enable or disable sending all performance metrics.- Default:
True
- Default:
enable_events: bool: A global switch to enable or disable sending all security events.- Default:
True
- Default:
retry_attempts: int: The number of times the agent will try to resend data if a request fails.- Default:
3
- Default:
timeout: int: The total timeout in seconds for a single HTTP request to the backend.- Default:
30
- Default:
backoff_factor: float: The factor used to calculate the delay between retry attempts (exponential backoff). The delay is calculated asbackoff_factor * (2 ** (attempt - 1)).- Default:
1.0
- Default:
sensitive_headers: list[str]: A list of HTTP header names (case-insensitive) that will be redacted (replaced with[REDACTED]) before being sent.- Default:
["authorization", "cookie", "x-api-key"]
- Default:
max_payload_size: int: The maximum size in bytes for a request or response payload that is included in a security event. Payloads larger than this will be truncated.- Default:
1024
- Default:
Contributing
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Author
Renzo Franceschini - rennf93@users.noreply.github.com
Acknowledgements
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_guard_agent-0.1.1.tar.gz.
File metadata
- Download URL: fastapi_guard_agent-0.1.1.tar.gz
- Upload date:
- Size: 18.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3aeb953a3523c62b21937637ec02673ed7518c7427de625bb1c569bd93b7ae48
|
|
| MD5 |
bc6ca0ea1bac4e2d8bcdf2d07d4ca0c5
|
|
| BLAKE2b-256 |
606a5a77e08bfa47689c950a664f492d4ed27ab3ffd7a538f4701d414b833a8a
|
File details
Details for the file fastapi_guard_agent-0.1.1-py3-none-any.whl.
File metadata
- Download URL: fastapi_guard_agent-0.1.1-py3-none-any.whl
- Upload date:
- Size: 20.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bba9cd91c3538ae07cec6dd6057a9c707b3fc65b26cb60eab594b389cee0a4a3
|
|
| MD5 |
13b5361e5f983247c696cc54eeba5de4
|
|
| BLAKE2b-256 |
accaa220990e1ca8d211cfdff0c9ea2c86d5efb1a0ded60c26a7dfb219f78c9a
|