Comprehensive Rules for building, testing, and deploying multi-modal, AI-driven biometric authentication services.
Your security team demands multi-modal biometric authentication with AI-powered liveness detection. Your ops team needs sub-200ms response times with zero-trust architecture. Your compliance team requires GDPR-compliant template management with immutable audit trails.
Building this from the ground up means months of research, model training, security architecture, and edge deployment complexity. These Cursor Rules give you battle-tested patterns to ship production-ready biometric authentication services in weeks, not quarters.
Modern biometric authentication isn't just "take a photo, compare faces." Production systems require:
Each component involves specialized knowledge spanning computer vision, machine learning, cryptography, and distributed systems. The security implications of getting any piece wrong are catastrophic.
These comprehensive Cursor Rules provide a complete architecture for building enterprise-grade biometric authentication services. You get proven patterns for:
Multi-Modal Authentication Pipeline
@router.post("/authenticate", response_model=AuthResponse)
async def authenticate(request: MultiModalRequest):
# Parallel processing of face + voice + behavior
face_result = await face_auth.verify(request.face_sample)
voice_result = await voice_auth.verify(request.voice_sample)
behavior_score = await behavior_auth.score(request.session_data)
confidence = fusion_engine.combine(face_result, voice_result, behavior_score)
return AuthResponse(authenticated=confidence > 0.95, jwt_token=...)
AI-Powered Liveness Detection
async def verify_liveness(image_sample: bytes) -> bool:
# Real-time anti-spoofing with adaptive thresholds
liveness_score = await ai_detector.analyze(image_sample)
if liveness_score < ADAPTIVE_THRESHOLD:
await audit_logger.log_spoof_attempt(trace_id, user_context)
return False
return True
Privacy-Compliant Template Management
class BiometricTemplate:
def __init__(self, raw_features: np.ndarray, user_salt: bytes):
# Never store raw biometrics - hash immediately
self.template_hash = self._secure_hash(raw_features, user_salt)
self.encrypted_features = self._encrypt_aes256(raw_features)
# Zero-fill raw data
raw_features.fill(0)
Eliminate 3-6 Months of R&D Instead of researching biometric algorithms, training models, and architecting security frameworks, you implement proven patterns immediately. The rules include pre-configured TensorFlow pipelines, OpenCV preprocessing chains, and FastAPI service templates.
Zero Security Architecture Guesswork The rules enforce zero-trust principles, encrypted template storage, and audit-compliant logging patterns from day one. No need to become a cryptography expert or design custom security protocols.
Instant Edge Deployment Capability Built-in ARM64 optimization patterns and container configurations mean your biometric services deploy to edge devices without performance engineering. Sub-150ms inference times are architected in, not retrofitted.
Behavioral Authentication Without Machine Learning Expertise The rules provide keystroke dynamics, mouse patterns, and gait analysis implementations that work out-of-the-box. You get continuous authentication without building ML pipelines from scratch.
# Weeks of research and implementation
import cv2
import tensorflow as tf
# ... hundreds of lines of preprocessing
# ... custom model training code
# ... security implementation from scratch
# ... edge deployment configuration
# ... performance optimization
# Minutes to working authentication service
from app.services import BiometricAuth, LivenessDetector
from app.schemas import AuthRequest, AuthResponse
@router.post("/authenticate")
async def authenticate(request: AuthRequest):
# All complexity handled by proven patterns
result = await biometric_auth.verify_multi_modal(request)
return AuthResponse(authenticated=result.passed, confidence=result.score)
Copy the configuration into your .cursor-rules file. The rules automatically configure your development environment for biometric authentication patterns.
# Cursor generates complete service structure
mkdir biometric-auth-service
cd biometric-auth-service
# Cursor creates /app with api/, models/, services/, schemas/ structure
# Cursor provides complete implementations following the patterns
POST /enroll # Multi-modal template capture with consent
POST /authenticate # Real-time verification with liveness detection
GET /session/verify # Continuous behavioral authentication
DELETE /user/{id} # GDPR-compliant template deletion
The rules guide you through FastAPI service creation, TensorFlow model integration, Redis caching setup, PostgreSQL schema design, and Kubernetes deployment configuration.
Development Velocity
Technical Performance
Operational Benefits
Developer Experience
You stop researching biometric algorithms and start shipping authentication services that handle millions of verifications per day. Your team focuses on business logic while the rules ensure security, performance, and compliance requirements are met automatically.
The difference is measured in months of development time saved and the confidence that comes from battle-tested security patterns rather than custom implementations.
You are an expert in Python, FastAPI, TensorFlow, OpenCV, Docker, Kubernetes, PostgreSQL, Redis, Zero-Trust security, and edge/IoT deployment.
Key Principles
- Privacy-by-Design: Collect the minimum viable biometric data and encrypt it at rest (AES-256) and in transit (TLS 1.3).
- Multi-Modal First: Always design for at least two biometric factors (e.g., face + voice) with configurable fallback paths.
- Continuous & Passive: Prefer behavioral biometrics (keystroke, gait, mouse dynamics) for on-going session validation.
- AI-Driven Accuracy: Embed model self-evaluation; retrain only when drift >2 % EER (Equal Error Rate).
- Zero-Trust Everywhere: Never implicitly trust device, network, or user. Enforce mutual TLS and signed JWT tokens.
- Fail Secure: A failed biometric check must default to denial and log a HIGH event.
- Edge Friendly: Keep model inference <150 ms on ARM64; off-load heavy training to GPU clusters.
- Immutable Infrastructure: Deploy containers with read-only root FS; store mutable state in managed services.
Python
- Use Python ≥3.11 with strict typing (`mypy --strict`).
- Follow PEP-8 plus:
• max-line-length: 100
• use `snake_case` for vars, `PascalCase` for classes, UPPER_SNAKE for constants.
- Prefer `dataclasses` or `pydantic.BaseModel` for data contracts over bare dicts.
- All I/O is async; use `async def` and `await` in FastAPI routes and DB calls.
- Never store raw biometric images; immediately hash (SHA-256) + encrypt before persistence.
- Directory layout:
/app
├── api/ # FastAPI routers
├── models/ # ML models & pre-processing
├── services/ # Business logic (no HTTP)
├── schemas/ # Pydantic DTOs
├── tests/ # Pytest suites
└── infra/ # Docker, Helm, Terraform
- Use `ruff` for linting & import sorting.
Error Handling and Validation
- Run liveness detection before template extraction; abort early on failure.
- Validate all incoming images:
• resolution ≥640×480
• file-size ≤2 MB
• MIME type in {image/jpeg, image/png}
- Use custom Exception hierarchy:
`BiometricError → {LivenessError, MatchError, ConsentError, RateLimitError}`.
- Always return structured error JSON: `{code, message, trace_id}`.
- Protect against replay: enforce one-time nonce bound to the sample and expire after 30 s.
FastAPI
- Use dependency injection for:
• DB sessions (asyncpg / SQLAlchemy 2.0 async)
• Model loaders (TensorFlow / ONNXRuntime)
• Zero-Trust policy engine (OPA via WASM)
- Endpoints:
POST /enroll # capture and store new template (requires 2FA + consent)
POST /authenticate # multi-modal check, returns signed JWT
GET /session/verify # behavioral re-auth, header-only payload
- Apply `@limiter.limit("5/minute")` on authentication endpoints.
- Use `ResponseModel` to enforce output schema.
- Auto-generate OpenAPI docs (`/docs`) but hide internal schemas (`x-internal: true`).
TensorFlow / OpenCV
- Freeze inference graphs; load with `tf.function(jit_compile=True)`.
- Set `tf.config.experimental.set_memory_growth` to avoid OOM on shared GPUs.
- Keep face embeddings at 128-D float32 (512 B) per user; compress with PCA if >1 M users.
- Use OpenCV DNN for real-time face detection → pass ROI to TF model.
- Version models with DVC; store binaries in S3 bucket with server-side encryption.
Testing
- Pytest structure:
tests/
├── unit/ # 100 % logic coverage (pytest-cov)
├── api/ # Test endpoints with HTTPX + pytest-asyncio
└── e2e/ # Docker-Compose spin-up with fake camera/voice streams
- Include spoofing suite: printed face, video replay, silicone fingerprint.
- Acceptance criterion: FAR ≤0.1 %, FRR ≤1 %, latency P95 ≤200 ms.
Performance
- Cache static model artifacts in Redis with SHA tag.
- Use SIMD-optimized preprocessing (`opencv-python-headless==4.9.x` compiled with AVX2).
- Batch inference when traffic >30 QPS; Use `asyncio.gather` + GPU batch size 16.
Security
- Biometric templates hashed using PBKDF2-HMAC-SHA256 with 100k iterations + user-specific salt.
- Store keys in HSM or AWS KMS; rotate every 90 days.
- Consent ledger on blockchain (Hyperledger Fabric) storing hash of consent form + timestamp.
- Implement GDPR Delete: `DELETE /user/{id}` triggers template purge + ledger tombstone.
DevOps
- Dockerfile: multi-stage; builder≫runtime (slim-python-3.11-bullseye). Final image <400 MB.
- Kubernetes: use PodSecurityContext `runAsNonRoot`, `readOnlyRootFilesystem: true`.
- HorizontalPodAutoscaler: CPU 70 %, GPU memory 80 %.
- CI: GitHub Actions → lint, type-check, unit tests, build, push, trivy scan, helm-lint, deploy to staging.
IoT / Edge Integration
- gRPC interface exposed on port 50051 with Protocol Buffers v3.
- Use Hardware Security Module on edge device for private key storage.
- OTA updates signed with ed25519; edge verifies signature before apply.
Logging & Observability
- Log in JSON with trace_id, user_id (hashed), model_version, latency_ms.
- Forward logs to OpenTelemetry collector; view in Grafana-Loki.
- Alert if FAR spikes >0.3 % in last 15 min.
Common Pitfalls & Guards
- Do NOT store raw video streams; process in memory, then zero-fill buffer (`mmap.madvise(DONTNEED)`).
- Ensure camera/voice permission prompts are explicit, not implicit.
- Monitor model drift monthly; schedule re-enrollment campaign if drift >5 %.
Example Code Snippet: FastAPI Enroll Endpoint
```python
@router.post("/enroll", status_code=201, response_model=EnrollResponse)
async def enroll(request: EnrollRequest, user: User = Depends(require_strong_2fa)):
if not request.consent:
raise ConsentError("Explicit consent required")
# Validate & run liveness
sample = Image.open(BytesIO(base64.b64decode(request.face_b64)))
if not await liveness.check(sample):
raise LivenessError("Liveness check failed")
template = biometrics.extract_face_template(sample)
await templates.store(user.id, template)
return EnrollResponse(status="success", template_hash=template.hash)
```