Cross Site Request Forgery in Fastapi with Dynamodb
Cross Site Request Forgery in Fastapi with Dynamodb — how this specific combination creates or exposes the vulnerability
Cross Site Request Forgery (CSRF) in a FastAPI application that uses DynamoDB arises from the interaction between cookie-based session handling (or missing anti-CSRF tokens) and state-changing operations that directly mutate DynamoDB resources. While FastAPI encourages explicit dependency injection and can be configured without session cookies, many integrations rely on cookies for authentication or convenience. If a FastAPI route that writes to DynamoDB is accessible via a browser context and lacks anti-CSRF protections, a malicious site can trick a logged-in user’s browser into issuing unintended authenticated requests.
Consider a FastAPI endpoint that accepts a POST to update a DynamoDB item representing a user’s profile. If authentication is cookie-based and the endpoint does not validate a CSRF token, an attacker can craft a form on a malicious site that submits to this endpoint with arbitrary but crafted parameters (e.g., changing email or roles). Because the user’s credentials (e.g., session cookie) are automatically included, the request succeeds from the server’s perspective. DynamoDB does not inherently provide CSRF protection; it simply processes the requests it receives. Therefore, the vulnerability is not in DynamoDB itself but in how FastAPI routes orchestrate access to DynamoDB without enforcing anti-CSRF controls for state-changing methods.
The risk is compounded when responses from DynamoDB are reflected in the browser without proper safeguards. For example, if a FastAPI route performs a UpdateItem on DynamoDB and then returns the updated item to the client, an attacker may leverage stored responses or error messages to infer behavior or chain further attacks. Because this scanning capability combines OpenAPI/Swagger spec analysis with runtime checks, it can detect endpoints that accept state-changing methods without CSRF mitigations and highlight them in reports, mapping findings to frameworks such as OWASP API Top 10 and SOC2 controls.
Using the middleBrick CLI, you can scan such a service to surface these concerns: middlebrick scan https://api.example.com/openapi.json. The scan runs 12 checks in parallel, including Authentication and BOLA/IDOR, and surfaces findings with severity and remediation guidance without requiring credentials. For teams using CI/CD, the GitHub Action can enforce a threshold so that builds fail if the risk score drops below an acceptable level, while the Web Dashboard and MCP Server integrations help track and explore findings directly from development tools.
Dynamodb-Specific Remediation in Fastapi — concrete code fixes
To remediate CSRF in FastAPI when interacting with DynamoDB, implement anti-CSRF tokens on state-changing endpoints and enforce strict SameSite and Secure cookie attributes if cookies are used. For APIs consumed by browsers, prefer anti-CSRF tokens or custom headers (e.g., X-Requested-With) and avoid relying solely on cookies for authorization. Below are concrete code examples for a FastAPI app using boto3 with DynamoDB that incorporate these protections.
Example 1: Anti-CSRF token validation for a DynamoDB write endpoint
from fastapi import FastAPI, Depends, Cookie, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
import boto3
import uuid
import hashlib
import hmac
app = FastAPI()
# Allow only trusted origins in production
app.add_middleware(
CORSMiddleware,
allow_origins=["https://your-frontend.com"],
allow_credentials=True,
allow_methods=["POST", "GET"],
allow_headers=["*"],
)
# In-memory store for demo tokens; use a secure store in production
def generate_csrf_token(session_id: str) -> str:
secret = b"your-256-bit-secret" # store securely, e.g., AWS Secrets Manager
return hmac.new(secret, session_id.encode(), hashlib.sha256).hexdigest()
def get_db():
# Configure region and credentials via environment or IAM roles
return boto3.resource("dynamodb", region_name="us-east-1")
@app.post("/profile/update-email")
async def update_email(
new_email: str,
csrf_token: str = Cookie(...),
session_id: str = Cookie(...),
dynamodb=Depends(get_db)
):
expected = generate_csrf_token(session_id)
if not hmac.compare_digest(csrf_token, expected):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid CSRF token")
table = dynamodb.Table("UserProfiles")
response = table.update_item(
Key={"user_id": session_id},
UpdateExpression="SET email = :val",
ExpressionAttributeValues={":val": new_email},
ReturnValues="UPDATED_NEW"
)
return {"status": "ok", "updated": response.get("Attributes")}
Example 2: Secure cookie setup and SameSite enforcement
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
app = FastAPI()
@app.post("/login")
def login(response: Response):
# Set secure, SameSite cookies for session management
response.set_cookie(
key="session_id",
value="unique-session-identifier",
httponly=True,
secure=True,
samesite="strict",
max_age=3600
)
response.set_cookie(
key="csrf_token",
value=generate_csrf_token("unique-session-identifier"),
httponly=False, # JavaScript needs access for header/token injection
secure=True,
samesite="strict",
max_age=3600
)
return {"message": "logged in"}
These examples demonstrate how to integrate CSRF protections with DynamoDB operations in FastAPI. The scanning capability of middleBrick can validate that such controls are present by analyzing the OpenAPI specification and correlating it with runtime tests, providing findings with severity and remediation steps. For ongoing assurance, the Pro plan’s continuous monitoring and the GitHub Action can alert teams if a new endpoint lacks CSRF mitigations, while the Web Dashboard helps track improvements over time.