CS_TA / checklist.py
zzhang2816's picture
Upload 12 files
78494de verified
Raw History Blame Contribute Delete
9 kB
#!/usr/bin/env python3
"""SecureMed acceptance checklist. Read-only by default; --scan writes test diagnoses."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent
RESULTS = []
def check(label, passed, detail=''):
RESULTS.append((label, bool(passed), detail))
print(f"[{'PASS' if passed else 'FAIL'}] {label}" + (f' — {detail}' if detail else ''))
def request(url, method='GET', token=None, data=None, content_type=None):
headers = {}
if token:
headers['Authorization'] = 'Bearer ' + token
if content_type:
headers['Content-Type'] = content_type
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=12) as resp:
return resp.status, json.loads(resp.read()) if 'json' in resp.headers.get('Content-Type', '') else {}
except urllib.error.HTTPError as exc:
try:
body = json.loads(exc.read())
except ValueError:
body = {}
return exc.code, body
except (urllib.error.URLError, TimeoutError) as exc:
return 0, {'detail': str(exc)}
def login(client, pool_id, client_id, username, password):
return client.initiate_auth(ClientId=client_id, AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={'USERNAME': username, 'PASSWORD': password})['AuthenticationResult']['AccessToken']
def multipart(path, fields=None):
boundary = 'securemed-check-' + os.urandom(8).hex()
parts = []
for key, value in (fields or {}).items():
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode())
data = path.read_bytes()
mime = 'image/png' if path.suffix.lower() == '.png' else 'image/jpeg'
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="image"; filename="{path.name}"\r\nContent-Type: {mime}\r\n\r\n'.encode() + data + b'\r\n')
parts.append(f'--{boundary}--\r\n'.encode())
return b''.join(parts), f'multipart/form-data; boundary={boundary}'
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', help='Deployment origin, e.g. http://EC2_PUBLIC_IP')
parser.add_argument('--accounts', type=Path, help='Private accounts JSON from provisioning script')
parser.add_argument('--scan', type=Path, help='JPEG/PNG test image; performs three persistent scans')
args = parser.parse_args()
required = ['Dockerfile', 'docker-compose.yml', '.env.example', 'README.md',
'api/app.py', 'api/index.html', 'scripts/provision_grading_accounts.py',
'scripts/seed_accounts.py', 'scripts/package.py']
for item in required:
check(f'Package file: {item}', (ROOT / item).is_file())
check('Supplied diagnosis image available',
(ROOT / 'securemed-diagnosis.tar').is_file() or
(ROOT.parent / 'assigment2' / 'securemed-diagnosis.tar').is_file())
if (ROOT / '.env').is_file():
values = dict(line.strip().split('=', 1) for line in (ROOT / '.env').read_text().splitlines()
if '=' in line and not line.lstrip().startswith('#'))
for key in ('AWS_REGION', 'COGNITO_USER_POOL_ID', 'COGNITO_CLIENT_ID', 'COGNITO_DOMAIN'):
check(f'Environment: {key}', bool(values.get(key)) and 'REPLACE_ME' not in values[key])
else:
check('Environment: .env created', False)
try:
result = subprocess.run(['docker', 'compose', 'config', '--format', 'json'], cwd=ROOT,
capture_output=True, text=True, timeout=20)
check('Docker Compose configuration', result.returncode == 0, result.stderr.strip()[:160])
if result.returncode == 0:
compose = json.loads(result.stdout)
services = compose.get('services', {})
check('Diagnosis service not publicly exposed', not services.get('diagnosis', {}).get('ports'))
check('Persistent database volume', bool(services.get('api', {}).get('volumes')))
except (FileNotFoundError, subprocess.TimeoutExpired):
check('Docker Compose configuration', False, 'Docker unavailable')
if not args.base_url:
print('\nLive checks skipped. Add --base-url; add --accounts for role checks.')
return summary()
origin = args.base_url.rstrip('/')
status, body = request(origin + '/api/health')
check('HTTP health', status == 200 and body == {'status': 'ok'}, f'HTTP {status}')
status, _ = request(origin + '/')
check('Website served', status == 200, f'HTTP {status}')
for path in ('/api/doctor/patients/P1001', '/api/patient/me', '/api/patient/diagnosis?name=Alice'):
status, _ = request(origin + path)
check(f'Unauthenticated blocked: {path}', status == 401, f'HTTP {status}')
status, _ = request(origin + '/api/patient/me', token='definitely.invalid.token')
check('Invalid token rejected', status == 401, f'HTTP {status}')
status, config = request(origin + '/api/web-config')
check('Web login configuration', status == 200 and bool(config.get('domain')) and bool(config.get('client_id')) and bool(config.get('redirect_uri')), f'HTTP {status}')
if not args.accounts:
print('Role checks skipped. Add --accounts private_accounts.json.')
return summary()
try:
import boto3
env = dict(line.strip().split('=', 1) for line in (ROOT / '.env').read_text().splitlines()
if '=' in line and not line.lstrip().startswith('#'))
client = boto3.client('cognito-idp', region_name=env['AWS_REGION'])
users = json.loads(args.accounts.read_text())
tokens = {label: login(client, env['COGNITO_USER_POOL_ID'], env['COGNITO_CLIENT_ID'],
details['username'], details['password'])
for label, details in users.items()}
check('Cognito USER_PASSWORD_AUTH: all grading accounts', True)
except Exception as exc:
check('Cognito USER_PASSWORD_AUTH: all grading accounts', False, type(exc).__name__)
return summary()
ids = {'alice': users['alice']['patient_id'], 'bob': users['bob']['patient_id']}
for label in ('alice', 'bob'):
status, body = request(origin + '/api/patient/me', token=tokens[label])
check(f'{label} sees own record', status == 200 and body.get('patient_id') == ids[label], f'HTTP {status}')
status, own = request(origin + '/api/patient/diagnosis?name=' + label.title(), token=tokens[label])
check(f'{label} can query own name', status == 200 and own.get('patient_id') == ids[label], f'HTTP {status}')
other = 'bob' if label == 'alice' else 'alice'
status, _ = request(origin + '/api/patient/diagnosis?name=' + other.title(), token=tokens[label])
check(f'{label} cannot query {other} by name', status == 403, f'HTTP {status}')
status, _ = request(origin + '/api/doctor/patients/' + ids[other], token=tokens[label])
check(f'{label} cannot use doctor API', status == 403, f'HTTP {status}')
status, _ = request(origin + '/api/patient/me', token=tokens['doctor'])
check('Doctor cannot use patient API', status == 403, f'HTTP {status}')
for label, patient_id in ids.items():
status, body = request(origin + '/api/doctor/patients/' + patient_id, token=tokens['doctor'])
check(f'Doctor can view {label}', status == 200 and body.get('patient_id') == patient_id, f'HTTP {status}')
if args.scan:
payload, content_type = multipart(args.scan)
status, body = request(origin + '/api/patient/scan', 'POST', tokens['alice'], payload, content_type)
check('Alice scan stores 0–3 diagnosis', status == 200 and type(body.get('diagnosis')) is int and body['diagnosis'] in range(4), f'HTTP {status}')
payload, content_type = multipart(args.scan)
status, body = request(origin + '/api/doctor/scan?patient_id=' + ids['bob'], 'POST',
tokens['doctor'], payload, content_type)
check('Doctor scan for Bob stores diagnosis', status == 200 and body.get('patient_id') == ids['bob'] and body.get('diagnosis') in range(4), f'HTTP {status}')
for label in ('alice', 'bob'):
status, body = request(origin + '/api/patient/me', token=tokens[label])
check(f'{label} scan persisted', status == 200 and bool(body.get('diagnoses')), f'HTTP {status}')
return summary()
def summary():
passed = sum(ok for _, ok, _ in RESULTS)
print(f'\n{passed}/{len(RESULTS)} automated checks passed.')
print('MANUAL: Verify Google login, doctor/patient web workflows, screenshots, and Canvas private credentials.')
return 0 if passed == len(RESULTS) else 1
if __name__ == '__main__':
sys.exit(main())