Advanced coding and architectural rules for building Zero-Trust–compliant back-end services with Python & FastAPI.
Stop building vulnerable APIs. These Cursor Rules transform your Python backend development into a Zero Trust security powerhouse, eliminating the guesswork around secure API design while maintaining development velocity.
You know the pain: security requirements come as afterthoughts, turning your clean codebase into a tangled mess of authentication checks, authorization logic, and compliance patches. Traditional "castle-and-moat" thinking leaves you vulnerable to insider threats, lateral movement, and the reality that your perimeter has already been breached.
Meanwhile, you're wrestling with:
These Cursor Rules implement the "Never Trust, Always Verify" principle directly into your development workflow. Every line of code follows Zero Trust Architecture patterns, giving you secure-by-default APIs that scale with your security requirements.
Your development environment becomes a security-first machine:
# Before: Vulnerable and inconsistent
@app.get("/sensitive-data")
async def get_data(user_id: str):
# Maybe check auth? Maybe not?
return {"data": "sensitive_info"}
# After: Zero Trust enforced automatically
@app.get("/sensitive-data", tags=["admin"])
async def get_data(
current_user: User = Depends(get_current_user, require_mfa=True),
resource_access: ResourceAccess = Depends(verify_resource_scope)
) -> SensitiveDataResponse:
# Authentication, MFA, and authorization handled declaratively
return SensitiveDataResponse(data=encrypt_sensitive_data(data))
Stop Writing Security Boilerplate
Real-Time Threat Response Built-In
Compliance-Ready Architecture
Performance Without Compromise
Traditional Approach (45 minutes of security setup):
# 1. Copy-paste JWT validation from another file
# 2. Figure out which scopes this endpoint needs
# 3. Add manual logging for compliance
# 4. Hope you remembered all the edge cases
Zero Trust Rules (5 minutes, security included):
@app.post("/patient-records", tags=["sensitive"])
async def create_record(
record: PatientRecordCreate,
user: User = Depends(require_healthcare_professional),
audit: AuditLogger = Depends(get_audit_logger)
) -> PatientRecordResponse:
# Authentication, authorization, PII handling, and audit logging
# are handled automatically by the dependency injection system
return await patient_service.create(record, user_context=user)
Before: Grep through logs, correlate across systems, manually trace request flows
After: Every request includes structured security context:
{
"trace_id": "abc123",
"user_id_hash": "sha256:...",
"device_posture": "verified",
"granted_scopes": ["patient:read", "audit:write"],
"mfa_level": "strong",
"risk_score": 0.15
}
Your infrastructure deploys with Zero Trust policies enforced:
# Auto-generated Terraform with security hardened by default
resource "aws_security_group" "api" {
# Only allows traffic from verified devices
# Micro-segmentation rules applied automatically
# Network policies sync with your Python route definitions
}
# Add to your requirements.txt
pip install fastapi[security] pydantic[crypto] python-jose cryptography
# Set up your environment
export JWT_SECRET_KEY="your-secret-from-vault"
export REDIS_URL="redis://localhost:6379"
export SIEM_ENDPOINT="https://your-siem.example.com"
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2AuthorizationCodeBearer
from app.auth import get_current_user, require_mfa, verify_device_posture
from app.monitoring import SecurityEventLogger, AuditTrail
app = FastAPI(title="Zero Trust API")
# Exception handling with PII redaction
app.add_middleware(ZeroTrustExceptionMiddleware)
# Request validation and logging
app.add_middleware(SecurityContextMiddleware)
# Rate limiting with behavioral analysis
app.add_middleware(AdaptiveRateLimitMiddleware)
Apply Zero Trust patterns using FastAPI's dependency system:
@app.get("/api/v1/financial-data")
async def get_financial_data(
# Multi-factor authentication required
user: User = Depends(get_current_user, require_mfa=True),
# Device must pass security posture check
device: Device = Depends(verify_device_posture),
# Resource-level authorization
access: ResourceAccess = Depends(verify_financial_access),
# Automatic audit logging
audit: AuditLogger = Depends(get_audit_logger)
) -> FinancialDataResponse:
# Your business logic here - security is handled declaratively
return await financial_service.get_data(user.id, access.scope)
Security Posture Transformation:
Development Velocity Gains:
Compliance Confidence:
These rules include sophisticated security patterns that would take months to implement manually:
Dynamic Risk Assessment:
@app.post("/high-value-transaction")
async def process_transaction(
transaction: TransactionRequest,
risk_context: RiskContext = Depends(calculate_dynamic_risk),
user: User = Depends(adaptive_authentication) # MFA level adapts to risk
):
# Higher risk transactions automatically require stronger authentication
Micro-Segmentation Enforcement:
# Network policies automatically generated from your route definitions
# Kubernetes NetworkPolicy blocks lateral movement between services
# Only verified API clients can reach sensitive endpoints
Behavioral Analytics Integration:
# UEBA automatically learns normal patterns
# Anomalous behavior triggers step-up authentication
# ML models continuously improve threat detection accuracy
Your Python backend becomes a Zero Trust fortress without sacrificing developer experience. Every commit strengthens your security posture, and every deployment makes your infrastructure more resilient.
Ready to build APIs that security teams trust and attackers fear? These Cursor Rules transform your development workflow from security-vulnerable to security-native, giving you the confidence to ship fast without compromising on protection.
You are an expert in Zero Trust Architecture, Python 3.11, FastAPI, Pydantic v2, AsyncIO, PostgreSQL, Redis, OIDC/OAuth 2.0, AWS, Kubernetes, Terraform, SIEM/UEBA, EDR/XDR.
Key Principles
- Never Trust, Always Verify: authenticate & authorize every request, user, device and workload.
- Least Privilege: default-deny everywhere; grant minimal, time-boxed scopes and roles.
- Micro-Segmentation: isolate traffic with K8s NetworkPolicy / AWS SG; enforce service-level RBAC.
- Continuous Monitoring & Analytics: ship structured logs to SIEM, trigger UEBA & ML anomaly detectors.
- Immutable Infrastructure & GitOps: infra, policies and pipelines are code-reviewed and signed.
- Secrets Management: retrieve at runtime from Vault/Secrets Manager; never commit secrets.
- Short-Lived, Rotating Credentials: access tokens ≤5 min; refresh & signing keys rotated daily.
Python
- Use Python 3.11+ with `mypy --strict`, Black (88 chars), isort.
- All functions and variables are type-hinted; use `Final` for constants and `TypedDict` for dynamic JSON.
- Data in/outside services must be Pydantic models; forbid `Dict[str, Any]` in public interfaces.
- Declare pure functions first, side-effect functions last in each module.
- Avoid global mutable state; inject dependencies via FastAPI `Depends`.
- Only async libraries (`httpx`, `asyncpg`, `aioredis`); block calls wrapped with `run_in_threadpool`.
- Parameterize SQL or use SQLAlchemy Core; prohibit f-string SQL generation (enforced by linters).
- Configuration accessed through a single `AppSettings(BaseSettings)` class; environment variables upper-snake-case.
Error Handling & Validation
- Validate every request body, query, header with Pydantic; `error_on=first`.
- Centralised `ExceptionMiddleware` that:
• maps auth errors → 401, permission errors → 403, validation → 400.
• redacts PII before logging.
• adds `trace_id` + `span_id` headers.
- Fail fast with early returns; happy path last.
- Retries with `tenacity` (`stop_after_attempt=3`, `wait_random_exponential(max=8)`).
- Rate-limit by IP/device and user (`FastAPILimiter`); on abuse trigger circuit-breaker (PyBreaker).
FastAPI (Framework-Specific Rules)
- HTTPS only; forwarded headers validated against allow-list proxies.
- Every route protected with `OAuth2AuthorizationCodeBearer`; scopes checked via dependency injection.
- MFA enforcement: `Depends(get_current_user, require_mfa=True)` on sensitive routes.
- Classify routes with tags: `public`, `internal`, `admin`; apply per-tag RBAC in startup hook.
- Return RFC 9457 Problem Details objects; never leak stack traces to clients.
- JWKS cached in Redis 10 min; ETag aware refresh.
- Emit `Security-Context` response header listing granted scopes (no PII).
Infrastructure, Network & Policy
- Terraform IaC: separate modules for each ZTA pillar (identity, device, network, workload, data).
- VPC default NACL deny; allow via SGs from posture-verified devices only.
- Kubernetes: default `deny` NetworkPolicy, Istio mTLS strict; JWT validated in Envoy.
- OPA/Gatekeeper enforces: no `:latest` images, `runAsNonRoot=true`, label `owner` present.
- Policies (Rego) stored under `/policies`; synced via GitOps.
Testing
- Unit: ≥100 % branch coverage on auth, ACL, crypto utilities.
- Integration: `pytest` against ephemeral Postgres & Redis containers.
- Security: weekly `pip-audit`, `bandit`, Snyk scans; quarterly external penetration tests.
- Compliance: automated HIPAA/GDPR policy tests in CI pipeline.
- Chaos: inject policy denials and network splits – service must fail closed.
Performance & Observability
- Async endpoints respond <250 ms P95; monitor with Prometheus & Grafana.
- Logs → Fluent Bit → Kafka → SIEM; max 500 ms ingestion lag.
- Metrics tagged with `trace_id`, `user_id (hashed)`, `device_id`.
- Auto-scale on CPU ≥70 % or auth latency ≥100 ms.
Security Hardening
- Require `acr` claim ≥ `urn:mfa:strong`; reject tokens missing device posture claim.
- AES-256 encryption at rest (RDS, S3) & TLS 1.3 in transit.
- Field-level encryption for PII columns using envelope keys in KMS.
- Rotate signing/enc keys daily; maintain ≤3 active keys; automated staged rollout.
Directory Structure
- `apps/api` – FastAPI application
- `infra/` – Terraform modules & Helm charts
- `policies/` – Rego & policy-as-code
- `scripts/` – maintenance & DB migrations
- `tests/` – unit, integration, security, chaos tests
Sample OPA Policy (Rego)
```
package zta.access
default allow = false
allow {
input.claims.sub != ""
input.claims.mfa == true
input.resource.sensitivity <= input.claims.max_sensitivity
}
```