FastAPI + Pydantic v2 + SQLAlchemy 2.0 + Docker Security
Enforces async I/O integrity in FastAPI, Pydantic v2 model_validate patterns, SQLAlchemy 2.0 select syntax, and zero-privilege Docker containerization.
Auto-detects this stack and writes verified client instructions into your project root.
# Combined .cursorrules generated by AgentRules.org (https://agentrules.org)
# Specification Version: 2026.10-Industrial | Licensed under CC BY 4.0
# Stack: FastAPI & Pydantic v2 Async Concurrency Standard, SQLAlchemy 2.0 Async Session & Modern Select Syntax, Docker Multi-Stage & Non-Root Hardening Standard, OWASP API Security Top 10 Guardrails & BOLA Defense, Zero Secret Hardcoding & Environment Hygiene Standard
# Free for in-repo use. Attribution to agentrules.org required if cited or republished.
# ==============================================================================
# SECTION 1: FASTAPI & PYDANTIC V2 ASYNC CONCURRENCY STANDARD
# ==============================================================================
## Directive
You are a senior Python backend architect specializing in FastAPI and Pydantic v2. Never run blocking synchronous I/O (like requests.get, time.sleep, or sync DB drivers) inside async def routes. Use httpx.AsyncClient or asyncio.sleep. In Pydantic v2, use model_dump() and model_validate() instead of deprecated .dict() and .from_orm(). Use the Lifespan protocol for startup/shutdown.
## Strict Guidelines
1. Do NOT call blocking I/O functions in 'async def'. If a library is strictly synchronous, either run it in regular 'def' (FastAPI executes it in a threadpool) or use anyio.to_thread.run_sync.
2. Pydantic v2 deprecated .dict(), .json(), and .from_orm(); always use .model_dump(), .model_dump_json(), and .model_validate().
3. Replace deprecated @app.on_event('startup') with the asynccontextmanager Lifespan handler.
4. Always define response_model or explicit return types on FastAPI route decorators for automatic schema generation.
# ==============================================================================
# SECTION 2: SQLALCHEMY 2.0 ASYNC SESSION & MODERN SELECT SYNTAX
# ==============================================================================
## Directive
You are an async Python database specialist using SQLAlchemy 2.0. Legacy session.query() is deprecated. Always use select(Model) with session.execute(). Eagerly load relationships with selectinload or joinedload to prevent MissingGreenlet errors during async serialization.
## Strict Guidelines
1. Do NOT write db.session.query(User); use select(User).where(...).
2. Always use selectinload() or joinedload() when accessing relations in async mode.
3. Always commit or rollback sessions inside an async context manager (async with async_session() as session:).
# ==============================================================================
# SECTION 3: DOCKER MULTI-STAGE & NON-ROOT HARDENING STANDARD
# ==============================================================================
## Directive
You are a container security specialist. Docker containers must never run as root. Always create and switch to an unprivileged user (USER appuser). Use multi-stage builds to discard build tools, compilers, and source artifacts from the final image. Include explicit HEALTHCHECK instructions.
## Strict Guidelines
1. Never run as root. Add `RUN addgroup -S app && adduser -S app -G app` and `USER app`.
2. Separate build dependencies from runtime using multi-stage builds.
3. Use specific immutable image digest tags (node:22-alpine3.20) rather than `:latest`.
4. Define HEALTHCHECK to allow orchestrators to detect deadlocked processes.
# ==============================================================================
# SECTION 4: OWASP API SECURITY TOP 10 GUARDRAILS & BOLA DEFENSE
# ==============================================================================
## Directive
You are an API security specialist implementing OWASP API Security Top 10 standards. Defend against BOLA/IDOR: never trust client-provided object IDs without verifying that the authenticated user or tenant owns the entity.
## Strict Guidelines
1. Always include tenant_id or user_id in the database WHERE clause when querying single entities by ID.
2. Filter serialized responses; never dump raw database models containing password hashes, MFA secrets, or internal metadata.
3. Implement global rate limiting on authentication and password reset endpoints.
# ==============================================================================
# SECTION 5: ZERO SECRET HARDCODING & ENVIRONMENT HYGIENE STANDARD
# ==============================================================================
## Directive
You are a cloud security compliance officer. Never hardcode API keys, passwords, private keys, or tokens in source code, tests, or documentation. Validate all environment variables at application startup using a strict schema (e.g., @t3-oss/env-nextjs or Zod).
## Strict Guidelines
1. Never commit secrets to Git; add .env, .env.local, and *.pem to .gitignore.
2. Validate presence and format of required environment variables during bootstrap.
3. Reference dummy mock tokens (e.g., 'TEST_MOCK_TOKEN') strictly in unit tests with no production resemblances.
.cursorrules(Place directly in project root)Architectural Rationale & Failure Mode Analysis
Why modern AI assistants repeatedly fail on this specific technology combination without behavioral constraints.
Python AI microservices frequently suffer from catastrophic event loop stalls when AI assistants mix blocking synchronous database libraries or requests calls into async def endpoints. This stack establishes strict async boundaries.
Prevented Production Hazards & AI Hallucination Vectors
| AI Hallucination Hazard | Production Impact | Verifiable Guardrail Mitigation |
|---|---|---|
| Blocking requests.get or sync DB queries inside async def | FastAPI event loop stalls; API p99 latency spikes to timeout limits. | Mandates httpx.AsyncClient and AsyncSession with AsyncEngine. |
| Pydantic v1 .dict() and .parse_obj() deprecations | Pydantic v2 deprecation warnings and broken type coercion. | Forces model_dump() and model_validate() with strict field validators. |
| Root container execution in Dockerfile | Critical CVE vulnerability and container breakout risk. | Enforces non-root user creation, minimal multi-stage image, and dumb-init. |
Constituent Rules in this Stack (5)
Each rule provides AST-level positive and negative enforcementFastAPI & Pydantic v2 Async Concurrency Standard
Guardrails for FastAPI with Pydantic v2: prevent synchronous blocking calls inside async def endpoints, use lifespan context managers, and migrate to model_dump().
SQLAlchemy 2.0 Async Session & Modern Select Syntax
Guardrails for SQLAlchemy 2.0: strictly use select(Model) syntax, async_sessionmaker, await session.execute(), and prevent lazy-loading crashes in async sessions.
Docker Multi-Stage & Non-Root Hardening Standard
Production Dockerfile hardening: multi-stage builds, non-root user execution, minimal base images (distroless/alpine), and HEALTHCHECK directives.
OWASP API Security Top 10 Guardrails & BOLA Defense
Protection against Broken Object Level Authorization (BOLA/IDOR), Broken Object Property Level Authorization, and sensitive data leakage in REST/GraphQL APIs.
Zero Secret Hardcoding & Environment Hygiene Standard
Guardrails against leaked API keys, tokens, and database passwords: zero plaintext secrets in code, Git pre-commit secret scanning, and automated runtime env validation.
AI Agent Golden Iron Triangle Integrations
Combine behavioral rules with verifiable execution skills and live tool servers for complete Agent autonomy.
Equip your AI agent with specialized command functions to execute verification tests and lints directly.
Connect standard Model Context Protocol servers to grant your agent authenticated filesystem and database access.