Spaces:
Paused

yaz / docs /security.md
anaselamr's picture
feat: Sprint 44 — ProductRegistry, Azul/Luiz layer, 13 migrations, doc cleanup
383d839
|
Raw History Blame Contribute Delete
5.73 kB

YAZ Care Platform — Security Reference

Authentication

JWT Strategy

Environment Algorithm Key Type
Development HS256 Symmetric (JWT_SECRET_KEY)
Production RS256 Asymmetric (JWT_PRIVATE_KEY + JWT_PUBLIC_KEY)

Token lifetimes:

  • Access token: 15 minutes (ACCESS_TOKEN_TTL=900)
  • Refresh token: 7 days (REFRESH_TOKEN_TTL=604800), delivered as HttpOnly cookie

JWT Claims:

{
  "sub": "user-uuid",
  "org_id": "tenant-uuid",
  "roles": ["surgeon"],
  "type": "access",
  "jti": "unique-token-id",
  "iat": 1700000000,
  "exp": 1700000900,
  "iss": "yaz-care",
  "aud": "yaz-care-api"
}

jti Revocation:
On logout or token invalidation: jwt:blocklist:{jti} → Redis SET EX {remaining_ttl}.
Every request checks is_revoked(jti) before accepting the token.

Key Generation (RS256):

# Generate RSA key pair
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem

# Set env vars (encode newlines for .env)
JWT_PRIVATE_KEY=$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' private.pem)
JWT_PUBLIC_KEY=$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' public.pem)

Password Hashing

Algorithm: Argon2id (replaces bcrypt for all new hashes)

Parameters:

  • time_cost=3
  • memory_cost=65536 (64 MB)
  • parallelism=4

Legacy bcrypt hashes are verified during login and rehashed to Argon2id transparently (needs_rehash() check).
Module: src/core/auth/passwords.py


RBAC Matrix

Role Cases Surgery Billing Documents Users Admin
super_admin RW RW RW RW RW RW
clinic_admin RW RW RW RW RW —
surgeon RW RW R RW — —
assistant R R — R — —
accountant R — RW R — —
viewer R R — R — —
patient R (own) — R (own) R (own) — —

FastAPI dependency: require_role(["surgeon", "clinic_admin"])


PII Vault

Patient PII is never stored in main case tables.

Architecture

Case table:     patient_ref_id (UUID only — safe to log, expose in URLs)
PatientPII:     full_name, phone, national_id, dob, email, address
                (all fields: AES-256-GCM encrypted via PIIField SQLAlchemy type)

Encryption

  • Algorithm: AES-256-GCM (authenticated encryption, tamper-evident)
  • Key source (priority):
    1. PII_VAULT_KEY env var (base64-encoded 32 bytes)
    2. AWS KMS envelope (PII_VAULT_KMS_KEY + PII_VAULT_ENCRYPTED_DEK)
    3. HashiCorp Vault transit (PII_VAULT_TRANSIT + PII_VAULT_ENCRYPTED_DEK)

Key Generation

# Generate a 32-byte AES key (production)
python3 -c "import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())"

Access Control

  • Decryption on-demand only (never in batch queries)
  • Every decryption emits PATIENT_PII_DECRYPTED audit event
  • Key rotation: re-encrypt all rows with new key, then rotate PII_VAULT_KEY

Module: src/core/patients/__init__.py


Security Headers

All responses include (via SecurityHeadersMiddleware):

X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Content-Security-Policy: default-src 'self'; ...
Strict-Transport-Security: max-age=31536000 (production only)

Module: src/core/security/headers.py


Rate Limiting

  • Library: slowapi (Starlette-native wrapper for limits)
  • Auth endpoints: 10/minute per IP
  • Write endpoints: 30/minute per user
  • Read endpoints: 120/minute per user

CORS

In production, only https:// origins are accepted:

def get_cors_origins() -> list[str]:
    if is_production():
        return [o for o in settings.security.cors_origins if o.startswith("https://")]
    return settings.security.cors_origins

Set: CORS_ORIGINS=https://app.yaz.ma,https://admin.yaz.ma


Secrets Management

Production: HashiCorp Vault Dynamic Credentials

DATABASE_URL → postgres://yaz:${rotating_pass}@... (expires in 1h)

Configure VAULT_ADDR + VAULT_TOKEN (or AppRole auth).

Alternative: SOPS + age

# Encrypt
sops --encrypt --age $(cat .age-key.pub) .env.production > .env.production.enc
# Decrypt at startup
sops --decrypt .env.production.enc | export $(...)

CI Secrets

All CI secrets in GitHub Actions Secrets:

  • JWT_SECRET_KEY — HS256 test secret
  • PII_VAULT_KEY — test encryption key
  • POSTGRES_PASSWORD — derived per-job
  • GITLEAKS_LICENSE — for gitleaks action

Never commit:

  • .env files with real values
  • Private keys, certificates
  • API keys, SMTP passwords

Module: src/core/database/audit.py — Secret scanning in CI: gitleaks on every push.


MFA

All users can enroll TOTP (Google Authenticator, Authy, etc.):

POST /api/v1/auth/mfa/enroll   → { secret, qr_code_url, backup_codes }
POST /api/v1/auth/mfa/verify   → { mfa_token }  (short-lived, 5 min)
POST /api/v1/auth/login        → requires mfa_token after password OK
  • Library: pyotp
  • Backup codes: 8 single-use codes, stored hashed (Argon2id)
  • MFA_BYPASSED audit event when super_admin bypasses

HIPAA Compliance

  • PHI never in URLs, query strings, logs, or error messages
  • All PHI access creates PATIENT_DATA_ACCESSED audit event
  • Audit trail is append-only with DB-level NO UPDATE/DELETE rules
  • Soft delete: records are never permanently deleted
  • sensitive=True log field marks any logging near PHI
  • PII vault with field-level encryption (AES-256-GCM)