Actionable security best-practice guidelines for building and operating cloud-hosted Python/FastAPI services under Zero-Trust, ISO/IEC 27001:2022, NIST CSF 2.0, and PCI DSS 4.0 requirements.
Security isn't a feature you add later—it's the foundation you build on. These Cursor Rules transform your Python/FastAPI development into a security-first process that meets enterprise compliance requirements without slowing you down.
Every Python API you deploy faces immediate threats:
Traditional security approaches fail because they're reactive—you discover vulnerabilities after attackers do. Meanwhile, meeting compliance requirements like Zero Trust architecture, quantum-resistant crypto planning, and comprehensive audit logging becomes a months-long project that blocks feature development.
These rules implement defense-in-depth directly in your development workflow, automatically enforcing:
Instead of retrofitting security, you build it in from line one.
Before: Manually implementing JWT, session management, MFA integration
# Typical unsecure authentication
@app.post("/login")
def login(username: str, password: str):
# No input validation
# Plain text password comparison
# No rate limiting
# No audit logging
return {"token": "basic_jwt"}
After: Enterprise-grade security with the rules
@app.post("/login", dependencies=[Depends(rate_limiter)])
async def login(credentials: UserCredentials): # Pydantic validation
if await user_exists(credentials.email): # Guard clause
if argon2_hasher.verify(credentials.password, stored_hash): # Quantum-resistant hashing
token = create_jwt(user_id, expires_delta=timedelta(minutes=15)) # Short-lived tokens
await log_security_event("login_success", user_id) # Audit trail
return {"access_token": token, "token_type": "bearer"}
await log_security_event("login_failed", credentials.email)
raise HTTPException(status_code=401, detail="authentication_failed")
Before: Manual dependency updates, discovering vulnerabilities in production
# Manual, error-prone process
pip install requests
# No vulnerability checking
# No automated updates
# Security issues discovered weeks later
After: Automated security scanning with build gates
# pyproject.toml with security enforcement
[tool.pip-audit]
require-hashes = true
desc = true
format = "json"
[build-system]
# Automated CVSS ≥7 blocking in CI
# Weekly pip-compile --upgrade PRs
# Dependabot integration with auto-merge for patches
Before: Stack traces and internal details exposed to attackers
@app.get("/user/{user_id}")
def get_user(user_id: int):
user = db.query(User).filter(User.id == user_id).first()
return user # Exposes internal database structure
After: Secure error handling with RFC 7807 compliance
@app.exception_handler(ValidationError)
async def validation_exception_handler(request: Request, exc: ValidationError):
await log_security_event("validation_error", {
"path": request.url.path,
"errors": exc.errors()
})
return JSONResponse(
status_code=422,
content={
"type": "https://example.com/probs/validation-error",
"title": "Validation Error",
"status": 422,
"instance": request.url.path
}
)
Add the Cursor Rules to your project
# Copy the rules to .cursor-rules/security.md
# Cursor will automatically apply security patterns
Initialize secure project structure
mkdir -p src/{api,core,db,security,workers,tests}
mkdir -p infra/{terraform,k8s}
mkdir -p docs/ir # Incident response runbooks
Set up pyproject.toml with security requirements
[project]
requires-python = ">=3.12"
dependencies = [
"fastapi[all]",
"pydantic[email]",
"argon2-cffi",
"cryptography",
"structlog",
"slowapi"
]
Enable AWS security services
# terraform/security.tf - Generated with rules
resource "aws_guardduty_detector" "main" {
enable = true
}
resource "aws_cloudtrail" "audit" {
name = "security-audit"
s3_bucket_name = aws_s3_bucket.audit_logs.bucket
}
Set up automated scanning
# .github/workflows/security.yml - Auto-generated
- name: Run Semgrep SAST
uses: returntocorp/semgrep-action@v1
- name: Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
With the rules active, Cursor automatically:
# Auto-generated structured logging
import structlog
logger = structlog.get_logger()
@app.middleware("http")
async def security_logging_middleware(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
await logger.ainfo("api_request",
method=request.method,
path=request.url.path,
status_code=response.status_code,
duration=time.time() - start_time,
user_id=get_current_user_id(request)
)
return response
Your next API deployment can be your most secure one. These rules don't just prevent vulnerabilities—they transform how you think about security, making it an accelerator rather than a blocker for your development process.
Stop treating security as technical debt. Start building Python APIs that enterprises trust from day one.
You are an expert in Security-First Python Cloud stack:
- Python 3.12 (+ typing & asyncio)
- FastAPI / Pydantic v2
- PostgreSQL & SQLAlchemy 2.x
- Docker, Kubernetes (EKS)
- Terraform + AWS (IAM, KMS)
- CI/CD (GitHub Actions) with DevSecOps scanners (Semgrep, Trivy, tfsec)
- AI-assisted threat intelligence & anomaly detection
- Zero Trust architecture and quantum-resistant crypto readiness
Key Principles
- Defence-in-depth across code, identity, data, network, and logging.
- "Never trust, always verify" – continuous authentication & authorization.
- Secure-by-default: deny-all, least-privilege, immutable infrastructure.
- Map every control to ISO/IEC 27001:2022, NIST CSF 2.0, PCI DSS 4.0, and CIS Controls.
- Shift-left security: automate SAST, DAST, SCA, IaC scans in CI.
- Cryptography: enforce TLS 1.3, AEAD (AES-GCM), libsodium; plan quantum-resistant migration (Kyber/Dilithium) for long-lived data.
- Centralized structured logging (JSON) with ≥ 365-day retention; forward to SIEM.
- Continuous threat-intel feed & AI-driven anomaly detection.
Python
- Require `pyproject.toml` (`requires-python = ">=3.12"`).
- Enforce static types; CI runs `mypy --strict`.
- Use `secrets` for cryptographic randomness; forbid `random` for security ops.
- Never hard-code credentials; pull from AWS Secrets Manager/Vault.
- No `eval`/`exec`; if unavoidable sandbox with `restrictedpython`.
- Use context managers; always close DB/IO in `finally`.
- JSON logging via `structlog`; redact PII & secrets.
- Manage deps with `pip-tools`; block build on CVSS ≥ 7 via `pip-audit`.
- Module naming: `snake_case`; max 500 LOC; functions ≤ 50 LOC.
Error Handling and Validation
- Validate all inbound data with Pydantic (strict mode) → 400 responses on failure.
- Handle errors early; use guard clauses; avoid nested `try/except`.
- Global FastAPI exception handler returns RFC 7807 Problem Details; strip stack traces in prod.
- Wrap crypto/IO libs; re-raise high-level `CryptoError`, `ServiceError` only.
- Implement exponential back-off (max 5 retries, jitter) for remote calls.
FastAPI
- Use async endpoints; off-load blocking tasks to Celery/Redis.
- Dependency injection for auth (`OAuth2PasswordBearer`, `HTTPBearer`).
- JWT (ES256) lifetime ≤ 15 min; rotate via JWKS; enforce MFA (TOTP/FIDO2).
- Enable CORS with explicit origins; no `*` in prod.
- Rate-limit with `slowapi` (default 100 req/min/user).
- Set security headers: `Content-Security-Policy`, `Strict-Transport-Security`, `X-Content-Type-Options`.
- Password hashing: Argon2id (t≥3, m≥64 MiB, p≥4).
Testing
- Unit: `pytest`; aim 90 %+ coverage; 100 % on auth/crypto.
- Integration: Testcontainers for Postgres/Redis; run in GitHub Actions.
- Fuzz: `atheris` on deserialization & parsing code.
- Weekly DAST: `zaproxy` scripted scan of staging.
- Pen-test images with Trivy and check SBOM (CycloneDX).
Performance
- Budget: 150 ms P95 per endpoint.
- Use `asyncpg` pool, HTTP keep-alive, gzip.
- Cache public GETs (CloudFront) with `Cache-Control: immutable, max-age=31536000`.
- Offload ML threat analytics to worker tier; bound queue size.
Security (Cloud & Infra)
- Terraform: enforce OPA/Checkov policies; no public S3, no open security groups.
- Network: Calico layer-7 policies; mandatory mTLS pod-to-pod.
- Data: Envelope encryption (KMS CMK) on RDS & S3; row-level encryption for sensitive columns.
- Monitoring: CloudTrail, GuardDuty, EKS audit logs; retain ≥ 1 year.
- Incident response runbooks in `docs/ir/`; dry-run quarterly.
- Quantum readiness backlog ticketed; evaluate NIST PQC finalists.
CI/CD
- Signed commits (GPG/Sigstore); signed OCI images (`cosign`).
- GitHub OIDC → AWS IAM; no long-lived access keys.
- SAST (Semgrep), SCA (Dependabot), IaC (tfsec), DAST (zaproxy) gates; block merge on "high" issues.
- Auto-open JIRA tickets for critical findings; SLA ≤ 72 h.
Common Pitfalls & Mitigations
- Secret leakage in logs: add log-scrubber middleware.
- Over-privileged IAM: run AWS IAM Access Analyzer daily.
- Unpatched dependencies: weekly `pip-compile --upgrade`, trigger PR.
- Relying on internal traffic trust: enable mutual TLS.
- PII in querystrings: switch to POST body; scrub server logs.
Example Snippets
```python
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, Field, EmailStr, constr, ValidationError
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
class UserIn(BaseModel):
email: EmailStr
password: constr(min_length=12, max_length=128)
@app.post("/register", status_code=status.HTTP_201_CREATED)
async def register(user: UserIn):
# guard clause – already exists?
if await user_exists(user.email):
raise HTTPException(status_code=409, detail="user_exists")
hashed = argon2_hasher.hash(user.password)
await save_user(user.email, hashed)
return {"status": "created"}
```
Directory Layout
```
src/
api/ # FastAPI routers
core/ # domain logic
db/ # SQLAlchemy models
security/ # crypto, auth, rate-limit
workers/ # Celery tasks
tests/
infra/
terraform/
k8s/
```