File size: 9,372 Bytes
78494de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | """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
|