Email Injection in Fastapi with Api Keys
Email Injection in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
Email injection occurs when user-controlled data is improperly handled in email-related headers or body content, allowing an attacker to inject additional headers or commands. In Fastapi, this risk can surface when an API accepts an email address or message fields and passes them to a mail-sending routine without strict validation. Using API keys for authentication does not inherently protect against injection; it only identifies the caller. If the API key is leaked, abused, or if the endpoint trusts data from the request without sanitization, an attacker can exploit the email composition logic regardless of authentication.
For example, an endpoint that builds SMTP commands or uses a library that concatenates headers from user input can be tricked into injecting extra headers like Cc:, Bcc:, or even new message lines. Consider a Fastapi route that accepts email and message and forwards them using a helper that does not enforce a safe format:
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
@app.post("/notify")
async def notify(email: str, message: str, x_api_key: str = Header(...)):
# Vulnerable: email used directly without validation
mail_command = f"To: {email}\nSubject: Notification\n\n{message}"
# sendmail-like usage (illustrative)
return {"status": "queued"}
If the email value contains newline characters, an attacker can inject additional headers. API keys authenticate the request but do not sanitize the email content; therefore, the injection remains possible. In a black-box scan, middleBrick tests such unauthenticated surfaces and flags the lack of input validation and output encoding as a finding under Input Validation and Data Exposure checks.
Moreover, API keys stored or transmitted insecurely can be extracted via an injection flaw, amplifying the impact. middleBrick’s checks include detecting whether endpoints that handle email-like fields properly encode or validate inputs, and whether authentication (e.g., API keys) is enforced before data processing. Without proper validation, attackers can manipulate headers, potentially leading to information leakage or spoofed identities, which are highlighted in the report with remediation guidance.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To mitigate email injection in Fastapi when using API keys, treat the API key as an authentication mechanism only, and enforce strict validation and encoding for all user-supplied data used in email composition. Use a structured email library or manual sanitization to ensure headers and bodies cannot be hijacked.
Below is a secure Fastapi example that validates the email format, prevents newline injection, and uses an API key header for authentication. The API key is validated against a predefined set or an external auth service, and the email is sanitized before being used in any mail routine:
from fastapi import FastAPI, Header, HTTPException, Depends
import re
app = FastAPI()
# Simple API key validation (in practice, use a secure store or OAuth)
VALID_API_KEYS = {"s3cr3t-k3y-abc123", "s3cr3t-k3y-xyz789"}
def get_api_key(x_api_key: str = Header(...)):
if x_api_key not in VALID_API_KEYS:
raise HTTPException(status_code=401, detail="Invalid API Key")
return x_api_key
EMAIL_RE = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
def sanitize_email(email: str) -> str:
# Reject newlines and carriage returns to prevent header injection
if "\n" in email or "\r" in email:
raise ValueError("Invalid email format")
if not EMAIL_RE.match(email):
raise ValueError("Invalid email address")
return email.strip()
@app.post("/notify", dependencies=[Depends(get_api_key)])
async def notify(email: str, message: str):
safe_email = sanitize_email(email)
# Use a mail library that handles headers safely, e.g., email.message.EmailMessage
from email.message import EmailMessage
msg = EmailMessage()
msg["To"] = safe_email
msg["Subject"] = "Notification"
msg.set_content(message)
# Placeholder for actual mail sending logic
return {"status": "queued", "to": safe_email}
This approach ensures that API keys remain the gatekeeper for access while the email handling logic is hardened against injection. middleBrick will recognize these practices in scans and note improved scores under Authentication and Input Validation categories.
Additional recommendations include rate limiting to deter brute-force attempts on API keys and monitoring for unusual patterns. If you use the CLI, you can run middlebrick scan <url> to validate your implementation, or integrate the GitHub Action to fail builds when insecure email handling is detected. For continuous assurance, the Pro plan provides scheduled scans and alerts tied to risk thresholds.
Frequently Asked Questions
Does using API keys prevent email injection in Fastapi?
How can I test my Fastapi endpoints for email injection and API key handling?
middlebrick scan <url> or add the GitHub Action to your CI/CD to automatically check for injection risks and authentication issues on each commit.