v1/docs/security-features.md
This document details the authentication and rate limiting features implemented in the WiFi-DensePose API, including configuration options, usage examples, and security best practices.
The API uses JWT (JSON Web Token) based authentication for securing endpoints.
# Location: src/api/middleware/auth.py
class AuthMiddleware(BaseHTTPMiddleware):
"""JWT Authentication middleware."""
Public Endpoints (No authentication required):
/ - Root endpoint/health, /ready, /live - Health check endpoints/docs, /redoc, /openapi.json - API documentation/api/v1/pose/current - Current pose data/api/v1/pose/zones/* - Zone information/api/v1/pose/activities - Activity data/api/v1/pose/stats - Statistics/api/v1/stream/status - Stream statusProtected Endpoints (Authentication required):
/api/v1/pose/analyze - Pose analysis/api/v1/pose/calibrate - System calibration/api/v1/pose/historical - Historical data/api/v1/stream/start - Start streaming/api/v1/stream/stop - Stop streaming/api/v1/stream/clients - Client management/api/v1/stream/broadcast - Broadcasting1. Obtaining a Token:
# Login endpoint (if implemented)
curl -X POST http://localhost:8000/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "user", "password": "password"}'
2. Using Bearer Token:
# Authorization header
curl -X POST http://localhost:8000/api/v1/pose/analyze \
-H "Authorization: Bearer <your-jwt-token>" \
-H "Content-Type: application/json" \
-d '{"data": "..."}'
3. WebSocket Authentication:
// Query parameter for WebSocket
const ws = new WebSocket('ws://localhost:8000/ws/pose?token=<your-jwt-token>');
Alternative authentication method for service-to-service communication.
# Location: src/api/middleware/auth.py
class APIKeyAuth:
"""Alternative API key authentication for service-to-service communication."""
Features:
Usage:
# API Key in header
curl -X GET http://localhost:8000/api/v1/pose/current \
-H "X-API-Key: your-api-key-here"
Support for token revocation and logout functionality.
class TokenBlacklist:
"""Simple in-memory token blacklist for logout functionality."""
The API implements sophisticated rate limiting using a sliding window algorithm with support for different user tiers.
# Location: src/api/middleware/rate_limit.py
class RateLimitMiddleware(BaseHTTPMiddleware):
"""Rate limiting middleware with sliding window algorithm."""
Default Rate Limits:
Path-Specific Limits:
/api/v1/pose/current: 60 requests/minute/api/v1/pose/analyze: 10 requests/minute/api/v1/pose/calibrate: 1 request/5 minutes/api/v1/stream/start: 5 requests/minute/api/v1/stream/stop: 5 requests/minuteRate limit information is included in response headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Window: 3600
X-RateLimit-Reset: 1641234567
When rate limit is exceeded:
HTTP/1.1 429 Too Many Requests
Retry-After: 60
X-RateLimit-Limit: Exceeded
X-RateLimit-Remaining: 0
The system can adjust rate limits based on system load:
class AdaptiveRateLimit:
"""Adaptive rate limiting based on system load."""
Load-based adjustments:
Cross-Origin Resource Sharing (CORS) configuration for browser-based clients.
# Development configuration
cors_config = {
"allow_origins": ["*"],
"allow_credentials": True,
"allow_methods": ["*"],
"allow_headers": ["*"]
}
# Production configuration
cors_config = {
"allow_origins": ["https://app.example.com", "https://admin.example.com"],
"allow_credentials": True,
"allow_methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["Authorization", "Content-Type"]
}
The API includes various security headers for enhanced protection:
class SecurityHeaders:
"""Security headers for API responses."""
Headers included:
X-Content-Type-Options: nosniff - Prevent MIME sniffingX-Frame-Options: DENY - Prevent clickjackingX-XSS-Protection: 1; mode=block - Enable XSS protectionReferrer-Policy: strict-origin-when-cross-origin - Control referrerContent-Security-Policy - Control resource loading# Authentication
ENABLE_AUTHENTICATION=true
SECRET_KEY=your-secret-key-here
JWT_ALGORITHM=HS256
JWT_EXPIRE_HOURS=24
# Rate Limiting
ENABLE_RATE_LIMITING=true
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_AUTHENTICATED_REQUESTS=1000
RATE_LIMIT_WINDOW=3600
# CORS
CORS_ENABLED=true
CORS_ORIGINS=["https://app.example.com"]
CORS_ALLOW_CREDENTIALS=true
# Security
ALLOWED_HOSTS=["api.example.com", "localhost"]
# src/config/settings.py
class Settings(BaseSettings):
# Authentication settings
enable_authentication: bool = Field(default=True)
secret_key: str = Field(...)
jwt_algorithm: str = Field(default="HS256")
jwt_expire_hours: int = Field(default=24)
# Rate limiting settings
enable_rate_limiting: bool = Field(default=True)
rate_limit_requests: int = Field(default=100)
rate_limit_authenticated_requests: int = Field(default=1000)
rate_limit_window: int = Field(default=3600)
# CORS settings
cors_enabled: bool = Field(default=True)
cors_origins: List[str] = Field(default=["*"])
cors_allow_credentials: bool = Field(default=True)
A comprehensive test script is provided to verify security features:
# Run the test script
python test_auth_rate_limit.py
The test script covers:
1. Test Authentication:
# Without token (should fail)
curl -X POST http://localhost:8000/api/v1/pose/analyze
# With token (should succeed)
curl -X POST http://localhost:8000/api/v1/pose/analyze \
-H "Authorization: Bearer <token>"
2. Test Rate Limiting:
# Send multiple requests quickly
for i in {1..150}; do
curl -s -o /dev/null -w "%{http_code}\n" \
http://localhost:8000/api/v1/pose/current
done
3. Test CORS:
# Preflight request
curl -X OPTIONS http://localhost:8000/api/v1/pose/current \
-H "Origin: https://example.com" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: Authorization"
Production Configuration:
Token Management:
Rate Limiting:
API Keys:
Authentication Events:
Rate Limit Violations:
Security Headers:
Common Issues:
401 Unauthorized:
429 Too Many Requests:
CORS Errors:
For development or testing, security features can be disabled:
# Disable authentication
ENABLE_AUTHENTICATION=false
# Disable rate limiting
ENABLE_RATE_LIMITING=false
# Allow all CORS origins
CORS_ORIGINS=["*"]
Warning: Never disable security features in production!