Security Layer
Security Architecture
Multi-layer security designed for a medical edge system where safety is paramount. One critical design decision: emergency routes bypass authentication to guarantee life-safety actions are never blocked by auth failures.
JWT Engine
RS256 · 15min access · 7d refresh
RSA-256 signed JWTs for all API access. Short-lived access tokens prevent replay attacks. Refresh tokens rotated on use.
TLS Layer
TLS 1.3 · Client certificates
All external connections encrypted with TLS 1.3. MQTT requires client certificates. Supabase and HA API over HTTPS.
MQTT ACL
Per-client topic policy
Mosquitto ACL file restricts each client to specific topic patterns. Wearable can only publish to its own device subtree.
Supabase RLS
Row-Level Security · PostgreSQL
All Supabase tables have RLS policies. Data is only accessible to the authenticated patient owner or admin role.
Device Trust
BLE fingerprint · MAC binding
Wearable pairing requires physical proximity ceremony. MAC address + firmware hash bound to patient record.
Fail-Secure Bypass
Safety overrides auth
Emergency API routes accept unauthenticated requests from local subnet. Safety is non-negotiable — auth is not.
Security Controls Matrix
| Layer | Control | Implementation | Strength |
|---|---|---|---|
| REST API | JWT Authentication | RS256, 15min access + 7d refresh | High |
| REST API | Rate Limiting | 100 req/min per IP, burst 20 | Medium |
| REST API | Input Validation | Pydantic schemas, strict typing | High |
| REST API | CORS Policy | Allowlist: localhost + mobile app | High |
| MQTT | TLS 1.3 | Client certificates, CA pinning | High |
| MQTT | ACL Authorization | Per-client topic allowlist | High |
| WebSocket | JWT Upgrade Validation | Token checked on HTTP→WS upgrade | High |
| Data at Rest | SQLite Encryption | SQLCipher AES-256 (planned: v2.2) | Planned |
| Data at Rest | Supabase RLS | Row-Level Security on all tables | High |
| Network | TLS for all sync | TLS 1.3 on Supabase, MQTT, HA API | High |
| Device | Device Fingerprint | MAC + firmware hash for BLE pairing | Medium |
| Emergency | Fail-Secure Bypass | Auth bypassed on /emergency/* routes | By-Design |
Threat Model
| Threat | Likelihood | Mitigation | Residual Risk |
|---|---|---|---|
| Unauthorized API Access | Medium | JWT RS256, rate limiting, input validation | Low |
| MQTT Topic Spoofing | Low | Client certificates, TLS 1.3, ACL policy | Low |
| Local SQLite Theft | Low | SQLCipher (planned), full-disk encryption | Medium |
| Cloud Data Exfiltration | Low | Supabase RLS, encrypted transit | Low |
| BLE Spoofing (Wearable) | Low | Device fingerprint, pairing ceremony | Low |
| Emergency Override Abuse | Very Low | Network isolation, alert on emergency use | Low |
| Secrets in Source Code | Low | Env vars, .env file, no code commits | Low |
JWT Middleware
# FastAPI JWT validation middleware
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer
import jwt
security = HTTPBearer()
async def get_current_user(token = Depends(security)):
try:
payload = jwt.decode(
token.credentials,
settings.JWT_PUBLIC_KEY,
algorithms=["RS256"],
options={"verify_exp": True}
)
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token")
# Emergency bypass — safety > security
async def get_user_or_emergency(request: Request, token = Depends(security)):
if request.url.path.startswith("/api/v1/emergency"):
# Allow local network requests without auth
if request.client.host in settings.LOCAL_SUBNET:
return {"role": "emergency_bypass"}
return await get_current_user(token)MQTT TLS Config
# Mosquitto TLS configuration
# /etc/mosquitto/conf.d/rafiq.conf
listener 1883 localhost # Plain — local only
listener 8883 # TLS — external clients
cafile /certs/ca.crt
certfile /certs/server.crt
keyfile /certs/server.key
tls_version tlsv1.3
require_certificate true # Client certs required
# ACL file
acl_file /etc/mosquitto/acl
# acl (per-client topic allowlist)
user wearable-001
topic read rafiq/wearable/watch-001/#
topic write rafiq/wearable/watch-001/#
user rafiq-core
topic readwrite rafiq/#