Securing AgenticAPI endpoints is critical to protect sensitive data and ensure reliable operation, especially for AI agents executing automated tasks. While full security features like OAuth2 and API key authentication are planned for AgenticAPI v0.4.0, this document outlines best practices for securing APIs, including rate limiting (available now) and a forward-looking example of OAuth2 setup. These practices help prevent unauthorized access, abuse, and performance degradation.
Security Principles #
- Authentication: Verify the identity of clients (agents or users) using OAuth2 or API keys.
- Authorization: Restrict access to endpoints based on scopes or roles.
- Rate Limiting: Control request frequency to prevent abuse and ensure fair usage.
- Input Validation: Use Pydantic schemas to validate payloads and prevent injection attacks.
- Error Handling: Avoid leaking sensitive information in error responses.
Current Security Features #
AgenticAPI currently supports rate limiting via the slowapi
library to manage request volumes. This is implemented as a middleware in FastAPI, limiting requests per client IP.
Example: Rate Limiting
from fastapi import FastAPI
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
app = FastAPI()
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@app.get("/health")
@limiter.limit("5/minute") # 5 requests per minute per IP
async def health_check():
return {"status": "healthy"}
This limits clients to 5 requests per minute, returning a 429 Too Many Requests
response if exceeded.
Planned Security Features (v0.4.0) #
AgenticAPI v0.4.0 will introduce OAuth2 authentication to restrict endpoint access and API key support for simpler agent integrations. Below is a planned example of OAuth2 setup using FastAPI.
Example: OAuth2 Setup (Planned)
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from typing import Dict, Any
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Mock user database
users_db = {
"agent1": {"username": "agent1", "password": "secret", "scopes": ["data:read", "notify:send"]}
}
class Token(BaseModel):
access_token: str
token_type: str
async def get_current_user(token: str = Depends(oauth2_scheme)):
# Simulate token validation
username = "agent1" if token == "valid-token" else None
if not username or username not in users_db:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Bearer"}
)
return users_db[username]
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = users_db.get(form_data.username)
if not user or user["password"] != form_data.password:
raise HTTPException(status_code=400, detail="Incorrect username or password")
# Simulate token generation
return {"access_token": "valid-token", "token_type": "bearer"}
@app.api_route("/document", methods=["SUMMARIZE"])
async def summarize_document(query: Dict[str, Any], user: Dict = Depends(get_current_user)):
if "data:read" not in user["scopes"]:
raise HTTPException(status_code=403, detail="Not authorized")
# Simulate summarization
return {"summary": "Report highlights key trends."}
Token Request:
curl -X POST http://localhost:8000/token -H "Content-Type: application/x-www-form-urlencoded" -d "username=agent1&password=secret"
Response:
{
"access_token": "valid-token",
"token_type": "bearer"
}
Protected Request:
curl -X SUMMARIZE http://localhost:8000/document -H "Authorization: Bearer valid-token" -H "Content-Type: application/json" -d '{
"document_id": "doc_001",
"format": "text"
}'
Response:
{
"summary": "Report highlights key trends."
}
- OAuth2: Requires a token for access, validated against user scopes.
- Scopes: Restrict actions (e.g.,
data:read
forSUMMARIZE
). - Planned for v0.4.0: Full OAuth2 implementation with token management.
Best Practices #
- Enable Rate Limiting: Apply
slowapi
to all endpoints to prevent abuse. - Validate Inputs: Use Pydantic schemas to sanitize payloads.
- Secure Tokens: Store API keys or OAuth2 tokens securely (planned for v0.4.0).
- Log Access: Monitor requests to detect unauthorized attempts.
- Minimize Error Details: Avoid exposing sensitive information in
failed
responses.
Next Steps #
- Explore REST Compatibility for REST client support.
- Learn about AI Agent Integration for agent connectivity.
- Try Implementing Custom Verbs with security.