Files
HealthAppRepositoryB/tools/verify-admission-correction.py
T

178 lines
9.0 KiB
Python

#!/usr/bin/env python3
"""Native HTTPS admission regression on a fresh disposable B database; no A data.
Requires Docker, a published B release and .NET 10. Saves only aggregate results.
"""
import argparse
import collections
import concurrent.futures
import hashlib
import http.client
import json
import os
from pathlib import Path
import secrets
import socket
import ssl
import subprocess
import tempfile
import threading
import time
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--release', required=True)
parser.add_argument('--dotnet', required=True)
parser.add_argument('--output', required=True)
a = parser.parse_args()
repository = Path(__file__).resolve().parents[1]
release = Path(a.release).resolve()
output = Path(a.output).resolve()
if output.exists():
parser.error('Use a new output file; previous evidence is never overwritten')
name = 'healthapp-b-admission-' + secrets.token_hex(4)
secret = secrets.token_hex(24)
env = dict(os.environ, POSTGRES_PASSWORD=secret)
def run(command, **kwargs):
result = subprocess.run(command, capture_output=True, text=True, **kwargs)
if result.returncode:
raise RuntimeError('Test infrastructure command failed: ' + command[0])
return result.stdout
application = None
started_database = False
with tempfile.TemporaryDirectory(prefix='healthapp-b-admission-') as temporary:
root = Path(temporary)
try:
run(['docker', 'run', '--rm', '-d', '--name', name, '-p', '127.0.0.1::5432',
'-e', 'POSTGRES_PASSWORD', 'postgres:18.6'], env=env)
started_database = True
for _ in range(100):
if subprocess.run(['docker', 'exec', name, 'pg_isready', '-h', '127.0.0.1', '-U', 'postgres'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:
break
time.sleep(.2)
else:
raise RuntimeError('Disposable PostgreSQL TCP listener did not become ready')
database_port = json.loads(run(['docker', 'inspect', '--format',
'{{json .NetworkSettings.Ports}}', name]))['5432/tcp'][0]['HostPort']
def sql(command):
return run(['docker', 'exec', '-i', name, 'psql', '-U', 'postgres',
'-v', 'ON_ERROR_STOP=1'], input=command)
sql("CREATE ROLE regression_runtime LOGIN PASSWORD 'disposable-only' NOSUPERUSER NOCREATEDB NOCREATEROLE;")
for module in ['Profile', 'Observations']:
sql((repository / f'src/Modules/{module}/Migrations/001-{module.lower()}.sql').read_text())
sql('REVOKE CREATE ON SCHEMA public FROM PUBLIC; '
'GRANT USAGE ON SCHEMA profile,observations TO regression_runtime; '
'GRANT SELECT,INSERT,UPDATE ON profile.patient TO regression_runtime; '
'GRANT SELECT,INSERT,UPDATE,DELETE ON observations.observation TO regression_runtime; '
'GRANT SELECT ON profile.schema_version,observations.schema_version TO regression_runtime;')
with socket.socket() as listener:
listener.bind(('127.0.0.1', 0))
port = listener.getsockname()[1]
plan = root / 'plan'
runtime = root / 'runtime'
run([a.dotnet, str(release / 'provisioner/HealthApp.Provisioning.dll'), 'prepare',
'--plan', str(plan), '--host', '127.0.0.1', '--port', str(port), '--root', str(runtime)])
installation = json.loads((plan / 'installation.json').read_text())
settings = installation['Settings']
assert not any(key.startswith('Resources:') for key in settings)
settings['ConnectionStrings:HealthDatabase'] = (
f'Host=127.0.0.1;Port={database_port};Database=postgres;Username=regression_runtime;Password=disposable-only')
settings['Kestrel:Certificates:Default:Path'] = str(plan / 'application.pfx')
(runtime / 'var/lib/healthapp-b/keys').mkdir(parents=True, exist_ok=True)
# Existing installations retain these obsolete settings. They must not
# resurrect the old admission gates or blanket deadline.
settings.update({'Resources:MaxConcurrentAssessments': '4',
'Resources:MaxConcurrentRequests': '32',
'Resources:RequestDeadlineSeconds': '0.001'})
configuration = root / 'configuration.json'
configuration.write_text(json.dumps(settings))
configuration.chmod(0o600)
env.update(HEALTHAPP_CONFIGURATION_FILE=str(configuration), ASPNETCORE_ENVIRONMENT='Production')
context = ssl.create_default_context(cafile=str(plan / 'healthapp-ca.crt'))
context.verify_flags &= ~ssl.VERIFY_X509_STRICT
token = None
def connection():
return http.client.HTTPSConnection('127.0.0.1', port, context=context, timeout=30)
def request(method, path, body=None):
client = connection()
try:
headers = {'Content-Type': 'application/json'}
if token:
headers['Authorization'] = 'Bearer ' + token
client.request(method, path, json.dumps(body) if body is not None else None, headers)
response = client.getresponse()
return response.status, response.read(), response.getheader('Retry-After')
finally:
client.close()
with (root / 'application.log').open('w') as log:
application = subprocess.Popen([a.dotnet, str(release / 'app/HealthApp.dll')], env=env,
stdout=log, stderr=log)
for _ in range(100):
try:
if request('GET', '/api/measurement-guidance')[0] == 200:
break
except OSError:
pass
if application.poll() is not None:
raise RuntimeError('Native test application exited during startup')
time.sleep(.1)
else:
raise RuntimeError('Native test application failed to become ready')
account = installation['Accounts'][0]
status, body, _ = request('POST', '/api/authentication/login',
{'accountId': account['AccountId'], 'password': account['Password']})
assert status == 200
token = json.loads(body)['accessToken']
status, body, _ = request('POST', '/api/patients',
{'name': 'Synthetic regression', 'dateOfBirth': '1990-01-01'})
assert status == 201
patient = json.loads(body)['patientId']
status, _, _ = request('POST', f'/api/patients/{patient}/observations',
{'measuredAt': '2026-09-12T08:00:00', 'systolic': 128, 'diastolic': 82, 'pulse': 68})
assert status == 201
results = []
for endpoint in ['insights', 'trends', 'overview']:
path = f'/api/patients/{patient}/{endpoint}?from=2026-09-01&to=2026-09-30'
for width in [5, 26, 40]:
for repeat in range(3):
barrier = threading.Barrier(width)
def worker(_):
client = connection()
try:
client.connect()
barrier.wait(timeout=30)
client.request('GET', path, headers={'Authorization': 'Bearer ' + token})
response = client.getresponse()
response.read()
assert response.getheader('Retry-After') is None
return response.status
finally:
client.close()
with concurrent.futures.ThreadPoolExecutor(max_workers=width) as workers:
counts = collections.Counter(workers.map(worker, range(width)))
assert counts == {200: width}, (endpoint, width, counts)
results.append({'endpoint': endpoint, 'concurrency': width,
'repeat': repeat + 1, 'statuses': dict(counts)})
print(endpoint, width, 'all requests succeeded', flush=True)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps({'result': 'passed', 'requests': sum(sum(x['statuses'].values()) for x in results),
'applicationDllSha256': hashlib.sha256((release / 'app/HealthApp.dll').read_bytes()).hexdigest(),
'results': results, 'scope': 'native HTTPS, restricted runtime role, disposable PostgreSQL 18.6; not a four-hour run'}, indent=2) + '\n')
finally:
if application is not None:
application.terminate()
application.wait(timeout=20)
if started_database:
subprocess.run(['docker', 'stop', name], stdout=subprocess.DEVNULL, check=True)