"""SecureMed EC2 API. Cognito access tokens are verified on every protected request.""" from __future__ import annotations import os import sqlite3 import uuid from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path import httpx import jwt from fastapi import FastAPI, File, Form, Header, HTTPException, Query, Request, UploadFile from fastapi.responses import FileResponse from jwt import PyJWKClient DB_PATH = Path(os.getenv('DATABASE_PATH', '/data/securemed.db')) REGION = os.getenv('AWS_REGION', '') POOL_ID = os.getenv('COGNITO_USER_POOL_ID', '') CLIENT_ID = os.getenv('COGNITO_CLIENT_ID', '') COGNITO_DOMAIN = os.getenv('COGNITO_DOMAIN', '').rstrip('/') PUBLIC_CALLBACK_URL = os.getenv('PUBLIC_CALLBACK_URL', '') DIAGNOSIS_URL = os.getenv('DIAGNOSIS_URL', 'http://diagnosis:8080/diagnose') MAX_IMAGE_BYTES = 5 * 1024 * 1024 ISSUER = f'https://cognito-idp.{REGION}.amazonaws.com/{POOL_ID}' jwks = PyJWKClient(f'{ISSUER}/.well-known/jwks.json', cache_jwk_set=True, lifespan=300) app = FastAPI(title='SecureMed', docs_url=None, redoc_url=None, openapi_url=None) def connect(): DB_PATH.parent.mkdir(parents=True, exist_ok=True) db = sqlite3.connect(DB_PATH, timeout=10) db.row_factory = sqlite3.Row db.execute('PRAGMA foreign_keys=ON') db.execute('PRAGMA busy_timeout=10000') return db @contextmanager def database(): db = connect() try: yield db db.commit() finally: db.close() def init_db(): with database() as db: db.executescript(''' CREATE TABLE IF NOT EXISTS patients ( patient_id TEXT PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS identities ( sub TEXT PRIMARY KEY, role TEXT NOT NULL CHECK(role IN ('doctor','patient')), patient_id TEXT UNIQUE REFERENCES patients(patient_id) ); CREATE TABLE IF NOT EXISTS diagnoses ( id TEXT PRIMARY KEY, patient_id TEXT NOT NULL REFERENCES patients(patient_id), diagnosis INTEGER NOT NULL CHECK(diagnosis BETWEEN 0 AND 3), created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS diagnoses_patient ON diagnoses(patient_id, created_at); ''') @app.on_event('startup') def startup(): init_db() def claims_from_request(authorization: str | None): if not authorization or not authorization.startswith('Bearer '): raise HTTPException(401, 'Authentication required') token = authorization[7:].strip() if not token or not REGION or not POOL_ID or not CLIENT_ID: raise HTTPException(401, 'Invalid token') try: key = jwks.get_signing_key_from_jwt(token).key claims = jwt.decode(token, key, algorithms=['RS256'], issuer=ISSUER, options={'verify_aud': False, 'require': ['exp', 'iss', 'sub']}, leeway=30) if claims.get('token_use') != 'access' or claims.get('client_id') != CLIENT_ID or not claims.get('sub'): raise ValueError('Wrong token type or client') return claims, token except (jwt.PyJWTError, ValueError) as exc: raise HTTPException(401, 'Invalid or expired token') from exc def identity(authorization: str | None, required_role: str): claims, token = claims_from_request(authorization) groups = claims.get('cognito:groups', []) if not isinstance(groups, list): groups = [] sub = claims['sub'] with database() as db: row = db.execute('SELECT role, patient_id FROM identities WHERE sub=?', (sub,)).fetchone() if required_role == 'doctor': if 'doctor' not in groups or not row or row['role'] != 'doctor': raise HTTPException(403, 'Doctor access required') else: if 'doctor' in groups or (row and row['role'] != 'patient'): raise HTTPException(403, 'Patient access required') if not row: # Cognito only grants doctor membership through administrator setup. # All other authenticated users, including first-time Google users, # are registered as patients on their first protected request. name = user_info_name(token, claims) patient_id = 'P' + uuid.uuid4().hex[:12].upper() db.execute('INSERT INTO patients(patient_id, name) VALUES (?, ?)', (patient_id, name)) db.execute('INSERT INTO identities(sub, role, patient_id) VALUES (?, ?, ?)', (sub, 'patient', patient_id)) row = {'role': 'patient', 'patient_id': patient_id} if row['role'] != required_role: raise HTTPException(403, 'Forbidden') return row['patient_id'] def user_info_name(token: str, claims: dict) -> str: if COGNITO_DOMAIN: try: response = httpx.get(f'{COGNITO_DOMAIN}/oauth2/userInfo', headers={'Authorization': f'Bearer {token}'}, timeout=5) response.raise_for_status() info = response.json() name = info.get('name') or info.get('given_name') or info.get('email') if isinstance(name, str) and name.strip(): return name.strip()[:100] except (httpx.HTTPError, ValueError): pass return str(claims.get('username') or claims['sub'])[:100] def patient_record(patient_id: str): with database() as db: patient = db.execute('SELECT patient_id, name FROM patients WHERE patient_id=?', (patient_id,)).fetchone() if not patient: raise HTTPException(404, 'Patient not found') diagnoses = db.execute('SELECT diagnosis, created_at FROM diagnoses WHERE patient_id=? ORDER BY created_at, id', (patient_id,)).fetchall() return {'patient_id': patient['patient_id'], 'name': patient['name'], 'diagnoses': [{'diagnosis': d['diagnosis'], 'created_at': d['created_at']} for d in diagnoses]} async def scan(patient_id: str, image: UploadFile): patient_record(patient_id) data = await image.read(MAX_IMAGE_BYTES + 1) if not data or len(data) > MAX_IMAGE_BYTES: raise HTTPException(400, 'Image must be between 1 byte and 5 MiB') if data.startswith(b'\x89PNG\r\n\x1a\n'): content_type = 'image/png' elif data.startswith(b'\xff\xd8\xff'): content_type = 'image/jpeg' else: raise HTTPException(400, 'Only JPEG and PNG images are accepted') try: async with httpx.AsyncClient(timeout=35) as client: response = await client.post(DIAGNOSIS_URL, content=data, headers={'Content-Type': content_type}) if response.status_code == 400: raise HTTPException(400, 'Unreadable image') response.raise_for_status() value = response.json().get('diagnosis') if type(value) is not int or value not in range(4): raise ValueError('Invalid diagnosis response') except HTTPException: raise except (httpx.HTTPError, ValueError) as exc: raise HTTPException(502, 'Diagnosis service unavailable') from exc with database() as db: db.execute('INSERT INTO diagnoses(id, patient_id, diagnosis, created_at) VALUES (?, ?, ?, ?)', (str(uuid.uuid4()), patient_id, value, datetime.now(timezone.utc).isoformat())) return value @app.get('/') def website(): return FileResponse(Path(__file__).with_name('index.html'), media_type='text/html', headers={'Cache-Control': 'no-store'}) @app.get('/api/health') def health(): with database() as db: db.execute('SELECT 1').fetchone() return {'status': 'ok'} @app.get('/api/web-config') def web_config(): return {'domain': COGNITO_DOMAIN, 'client_id': CLIENT_ID, 'redirect_uri': PUBLIC_CALLBACK_URL} @app.get('/api/doctor/patients/{patient_id}') def doctor_patient(patient_id: str, authorization: str | None = Header(None)): identity(authorization, 'doctor') return patient_record(patient_id) @app.post('/api/doctor/scan') async def doctor_scan(image: UploadFile = File(...), patient_id: str | None = Form(None), patient_id_query: str | None = Query(None, alias='patient_id'), authorization: str | None = Header(None)): identity(authorization, 'doctor') target = patient_id or patient_id_query if not target: raise HTTPException(400, 'patient_id is required') return {'patient_id': target, 'diagnosis': await scan(target, image)} @app.get('/api/patient/me') def patient_me(authorization: str | None = Header(None)): return patient_record(identity(authorization, 'patient')) @app.post('/api/patient/scan') async def patient_scan(image: UploadFile = File(...), authorization: str | None = Header(None)): patient_id = identity(authorization, 'patient') return {'diagnosis': await scan(patient_id, image)} @app.get('/api/patient/diagnosis') def patient_diagnosis(name: str = Query(..., min_length=1, max_length=100), authorization: str | None = Header(None)): patient_id = identity(authorization, 'patient') record = patient_record(patient_id) if name != record['name']: raise HTTPException(403, 'Forbidden') return record