Online
Security Layerv2.1
EncryptionAES-256
JWT Alg.RS256
TLS1.3

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.

Authentication FlowDevice → JWT → API → Resource
Client
Mobile / API
→
POST /auth/token
credentials
→
JWT Issuer
RS256 sign
→
Access Token
15min TTL
→
API Call
Bearer header
→
Middleware
Verify + decode
→
Resource
Authorized

Security Controls Matrix

LayerControlImplementationStrength
REST APIJWT AuthenticationRS256, 15min access + 7d refreshHigh
REST APIRate Limiting100 req/min per IP, burst 20Medium
REST APIInput ValidationPydantic schemas, strict typingHigh
REST APICORS PolicyAllowlist: localhost + mobile appHigh
MQTTTLS 1.3Client certificates, CA pinningHigh
MQTTACL AuthorizationPer-client topic allowlistHigh
WebSocketJWT Upgrade ValidationToken checked on HTTP→WS upgradeHigh
Data at RestSQLite EncryptionSQLCipher AES-256 (planned: v2.2)Planned
Data at RestSupabase RLSRow-Level Security on all tablesHigh
NetworkTLS for all syncTLS 1.3 on Supabase, MQTT, HA APIHigh
DeviceDevice FingerprintMAC + firmware hash for BLE pairingMedium
EmergencyFail-Secure BypassAuth bypassed on /emergency/* routesBy-Design

Threat Model

ThreatLikelihoodMitigationResidual Risk
Unauthorized API AccessMediumJWT RS256, rate limiting, input validationLow
MQTT Topic SpoofingLowClient certificates, TLS 1.3, ACL policyLow
Local SQLite TheftLowSQLCipher (planned), full-disk encryptionMedium
Cloud Data ExfiltrationLowSupabase RLS, encrypted transitLow
BLE Spoofing (Wearable)LowDevice fingerprint, pairing ceremonyLow
Emergency Override AbuseVery LowNetwork isolation, alert on emergency useLow
Secrets in Source CodeLowEnv vars, .env file, no code commitsLow

JWT Middleware

auth/middleware.py
python
# 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/rafiq.conf
bash
# 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/#