python-fastapi-web-server-security

This document is designed as a security spec that supports:

FastAPI (Python) Web Security Spec (FastAPI 0.128.x, Python 3.x) ([PyPI][1])

This document is designed as a security spec that supports:

  1. Secure-by-default code generation for new FastAPI code.
  2. Security review / vulnerability hunting in existing FastAPI code (passive “notice issues while working” and active “scan the repo and report findings”).

It is intentionally written as a set of normative requirements (“MUST/SHOULD/MAY”) plus audit rules (what bad patterns look like, how to detect them, and how to fix/mitigate them).

FastAPI is commonly deployed with an ASGI server (e.g., Uvicorn) and is built on Starlette + Pydantic, so this spec covers those layers where they affect security. ([PyPI][1])


0) Safety, boundaries, and anti-abuse constraints (MUST FOLLOW)


1) Operating modes

1.1 Generation mode (default)

When asked to write new FastAPI code or modify existing code:

1.2 Passive review mode (always on while editing)

While working anywhere in a FastAPI repo (even if the user did not ask for a security scan):

1.3 Active audit mode (explicit scan request)

When the user asks to “scan”, “audit”, or “hunt for vulns”:

Recommended audit order:

  1. App entrypoints / deployment scripts / Dockerfiles / Procfiles / Helm/terraform.
  2. ASGI server configuration (Uvicorn/Gunicorn), proxy settings, debug/reload settings.
  3. FastAPI app configuration (docs exposure, middleware, trusted hosts, CORS).
  4. Authn/Authz design (dependencies, JWT/session handling, password storage).
  5. Cookie/session usage + CSRF (if cookies are used).
  6. Input validation and output shaping (Pydantic models, mass assignment, excessive data exposure).
  7. Template rendering and XSS/SSTI (if HTML is served).
  8. File handling (uploads + downloads), StaticFiles, Range support.
  9. Injection classes (SQL, command execution, unsafe deserialization).
  10. Outbound requests (SSRF), redirect handling, WebSockets security.

2) Definitions and review guidance

2.1 Untrusted input (treat as attacker-controlled unless proven otherwise)

Examples include:

2.2 State-changing request

A request is state-changing if it can create/update/delete data, change auth/session state, trigger side effects (purchase, email send, webhook send), or initiate privileged actions.

2.3 Required audit finding format

For each issue found, output:


3) Secure baseline: minimum production configuration (MUST in production)

This is the smallest “production baseline” that prevents common FastAPI/ASGI misconfigurations.

Baseline goals:


4) Rules (generation + audit)

Each rule contains: required practice, insecure patterns, detection hints, and remediation.

FASTAPI-DEPLOY-001: Do not use auto-reload / dev-only server modes in production

Severity: High (if production)

Required:

Insecure patterns:

Detection hints:

Fix:

Note:


FASTAPI-DEPLOY-002: Debug mode MUST be disabled in production

Severity: Critical

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-OPENAPI-001: OpenAPI and interactive docs MUST be disabled or protected in production

Severity: Medium (can be High in sensitive/internal apps)

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-AUTH-001: Authentication MUST be explicit and consistently enforced via dependencies

Severity: High

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-AUTH-002: Use standard auth transports; avoid secrets in URLs

Severity: High

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-AUTH-003: Password storage MUST be strongly hashed; never store plaintext passwords

Severity: Critical

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-AUTH-004: JWT validation MUST be strict; JWTs MUST NOT carry secrets

Severity: High

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-AUTHZ-001: Authorization MUST be enforced per-object and per-property

Severity: High

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-SESS-001: If using cookie-based sessions and TLS, cookie attributes MUST be secure in production

Severity: High (only if TLS is enabled)

Required (production, HTTPS):

Insecure patterns:

Detection hints:

Fix:


FASTAPI-SESS-002: Do not store sensitive secrets in signed session cookies

Severity: High

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-CSRF-001: Cookie-authenticated state-changing requests MUST be CSRF-protected

Severity: High

Note: This only applies if using cookie based auth. If the application uses header or token based auth such as Authorization header, then CSRF is not an issue.

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-VALID-001: Request parsing and validation MUST be schema-driven; prevent mass assignment

Severity: Medium (especially for APIs that write to DB)

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-RESP-001: Prevent excessive data exposure via response models and explicit serialization

Severity: Medium

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-XSS-001: Prevent reflected/stored XSS in HTML responses and templates

Severity: High (if the service serves HTML)

Required:

Insecure patterns:

Detection hints:

Fix:

Note:


FASTAPI-SSTI-001: Never render untrusted templates (Server-Side Template Injection)

Severity: Critical

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-HEADERS-001: Set essential security headers (in app or at the edge)

Severity: Medium

Required (typical API/web app):

NOTE:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-CORS-001: CORS MUST be explicit and least-privilege

Severity: Medium (High if misconfigured with credentials)

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-HOST-001: Host header MUST be validated in production

Severity: Low

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-PROXY-001: Reverse proxy trust MUST be configured correctly

Severity: High (when behind a proxy)

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-LIMITS-001: Request and multipart limits MUST be enforced to prevent DoS

Severity: Low

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-FILES-001: Prevent path traversal and unsafe static file exposure

Severity: High

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-FILES-002: Mitigate Range-header DoS on file-serving endpoints

Severity: Low (if affected versions and file serving is enabled)

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-UPLOAD-001: File uploads MUST be validated, stored safely, and served safely

Severity: Medium

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-INJECT-001: Prevent SQL injection (use parameterized queries / ORM)

Severity: High

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-INJECT-002: Prevent OS command injection

Severity: Critical to High (depends on exposure)

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-SSRF-001: Prevent server-side request forgery (SSRF) in outbound HTTP

Severity: Medium (can be High in cloud/VPC environments)

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-REDIRECT-001: Prevent open redirects

Severity: Low

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-WS-001: WebSocket endpoints MUST be authenticated and protected against cross-site abuse

Severity: Medium to High (depends on data/privilege)

Required:

Insecure patterns:

Detection hints:

Fix:


FASTAPI-SUPPLY-001: Dependency and patch hygiene (focus on security-relevant deps)

Severity: Low

Required:

Audit focus examples (historical):

Detection hints:

Fix:


5) Practical scanning heuristics (how to “hunt”)

When actively scanning, use these high-signal patterns:

Always try to confirm:


6) Sources (accessed 2026-01-27)

Primary framework documentation:

ASGI/server stack documentation:

Security standards and cheat sheets:

Template safety references:

Selected supply-chain/advisory references (Starlette examples):

[1]: https://pypi.org/project/fastapi/ "https://pypi.org/project/fastapi/" [2]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html "https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html" [3]: https://starlette.dev/websockets/?utm_source=chatgpt.com "Websockets" [4]: https://pypi.org/project/uvicorn/ "https://pypi.org/project/uvicorn/" [5]: https://pypi.org/project/starlette/ "https://pypi.org/project/starlette/" [6]: https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html?utm_source=chatgpt.com "HTTP Security Response Headers Cheat Sheet" [7]: https://fastapi.tiangolo.com/reference/dependencies/?utm_source=chatgpt.com "Dependencies - Depends() and Security() - FastAPI" [8]: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html "https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html" [9]: https://advisories.gitlab.com/pkg/pypi/starlette/CVE-2024-47874/ "Starlette Denial of service (DoS) via multipart/form-data | GitLab Advisory Database" [10]: https://advisories.gitlab.com/pkg/pypi/starlette/CVE-2023-29159/ "Starlette has Path Traversal vulnerability in StaticFiles | GitLab Advisory Database" [11]: https://fastapi.tiangolo.com/tutorial/security/first-steps/?utm_source=chatgpt.com "Security - First Steps - FastAPI" [12]: https://fastapi.tiangolo.com/tutorial/response-model/ "https://fastapi.tiangolo.com/tutorial/response-model/" [13]: https://owasp.org/API-Security/editions/2023/en/0x11-t10/ "https://owasp.org/API-Security/editions/2023/en/0x11-t10/" [14]: https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html "https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html" [15]: https://fastapi.tiangolo.com/tutorial/extra-models/ "https://fastapi.tiangolo.com/tutorial/extra-models/" [16]: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html "https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html" [17]: https://owasp.org/www-project-web-security-testing-guide/v41/4-Web_Application_Security_Testing/07-Input_Validation_Testing/18-Testing_for_Server_Side_Template_Injection?utm_source=chatgpt.com "Testing for Server Side Template Injection" [18]: https://jinja.palletsprojects.com/en/stable/sandbox/?utm_source=chatgpt.com "Sandbox — Jinja Documentation (3.1.x)" [19]: https://advisories.gitlab.com/pkg/pypi/starlette/CVE-2025-62727/ "Starlette vulnerable to O(n^2) DoS via Range header merging in `starlette.responses.FileResponse` | GitLab Advisory Database" [20]: https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html "https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html" [21]: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html" [22]: https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html "https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html" [23]: https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html "https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html" [24]: https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html?utm_source=chatgpt.com "Unvalidated Redirects and Forwards Cheat Sheet" [25]: https://cheatsheetseries.owasp.org/cheatsheets/WebSocket_Security_Cheat_Sheet.html?utm_source=chatgpt.com "WebSocket Security - OWASP Cheat Sheet Series" [26]: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/11-Client-side_Testing/10-Testing_WebSockets?utm_source=chatgpt.com "WSTG - Latest | OWASP Foundation" [27]: https://fastapi.tiangolo.com/advanced/websockets/?utm_source=chatgpt.com "WebSockets - FastAPI" [28]: https://fastapi.tiangolo.com/reference/apirouter/?utm_source=chatgpt.com "APIRouter class - FastAPI" [29]: https://docs.pydantic.dev/latest/ "https://docs.pydantic.dev/latest/"