Deliver portable native Architecture B deployment and final verification
This commit is contained in:
1 parent
f451b55de1
commit
36740d2492
92 files changed
+10939
-926
No files matched your search
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "synthetic-comparison-1",
|
||||
"profile": {"name": "Synthetic comparison patient", "dateOfBirth": "1980-01-01", "contactInfo": "comparison@example.test"},
|
||||
"observations": [
|
||||
{"measuredAt": "2026-09-10T08:00:00", "systolic": 150, "diastolic": 92, "pulse": 70, "measurementContext": {"setting": "Home", "activityCondition": "AtRest", "restDurationMinutes": 5, "bodyPosition": "Seated", "measuredArm": "Left", "deviceDetails": "Synthetic device", "cuffDetails": "Synthetic cuff"}},
|
||||
{"measuredAt": "2026-09-11T08:00:00", "systolic": 140, "diastolic": 88, "pulse": 68, "measurementContext": {"setting": "Home", "activityCondition": "AtRest", "restDurationMinutes": 5, "bodyPosition": "Seated", "measuredArm": "Left", "deviceDetails": "Synthetic device", "cuffDetails": "Synthetic cuff"}},
|
||||
{"measuredAt": "2026-09-12T08:00:00", "systolic": 160, "diastolic": 95, "pulse": 80, "measurementContext": {"setting": "Clinic", "activityCondition": "AtRest"}},
|
||||
{"measuredAt": "2026-09-13T08:00:00", "systolic": 145, "diastolic": 90, "pulse": 110, "measurementContext": {"setting": "Home", "activityCondition": "AfterActivity"}, "context": "After activity", "note": "Synthetic departure from routine"},
|
||||
{"measuredAt": "2026-09-14T08:00:00", "systolic": 130, "diastolic": 84, "pulse": 65, "context": "Synthetic historical text; setting unknown"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Initialize a fresh disposable comparison instance via the unchanged public API.
|
||||
Never run on an existing Architecture A database/production deployment.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import pathlib
|
||||
import ssl
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--url', required=True)
|
||||
parser.add_argument('--ca', required=True)
|
||||
parser.add_argument('--account-file', required=True, help='Owner-only JSON with accountId/password')
|
||||
parser.add_argument('--dataset', default=str(pathlib.Path(__file__).with_name('dataset.json')))
|
||||
parser.add_argument('--output', required=True, help='New manifest filename')
|
||||
args = parser.parse_args()
|
||||
output = pathlib.Path(args.output)
|
||||
if output.exists():
|
||||
raise SystemExit('Output manifest already exists; refusing overwrite.')
|
||||
if not args.url.startswith('https://'):
|
||||
raise SystemExit('Verified HTTPS is required.')
|
||||
credentials_path = pathlib.Path(args.account_file)
|
||||
if credentials_path.stat().st_mode & 0o077:
|
||||
raise SystemExit('Credentials file must be owner-only.')
|
||||
credentials = json.loads(credentials_path.read_text())
|
||||
data_bytes = pathlib.Path(args.dataset).read_bytes()
|
||||
data = json.loads(data_bytes)
|
||||
context = ssl.create_default_context(cafile=args.ca)
|
||||
token = None
|
||||
|
||||
def request(path, payload):
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if token:
|
||||
headers['Authorization'] = 'Bearer ' + token
|
||||
query = urllib.request.Request(args.url.rstrip('/') + path,
|
||||
data=json.dumps(payload).encode(), headers=headers)
|
||||
with urllib.request.urlopen(query, context=context, timeout=30) as response:
|
||||
return json.load(response)
|
||||
|
||||
try:
|
||||
token = request('/api/authentication/login', credentials)['accessToken']
|
||||
patient = request('/api/patients', data['profile'])
|
||||
observations = [request('/api/patients/' + patient['patientId'] + '/observations', item)
|
||||
for item in data['observations']]
|
||||
except urllib.error.HTTPError as error:
|
||||
raise SystemExit('Initialization stopped at HTTP ' + str(error.code) +
|
||||
'; inspect the fresh test instance. No mutation retry or automatic cleanup performed.')
|
||||
output.write_text(json.dumps({'datasetVersion': data['version'],
|
||||
'datasetSha256': hashlib.sha256(data_bytes).hexdigest(),
|
||||
'patientId': patient['patientId'],
|
||||
'observationIds': [item['observationId'] for item in observations]}, indent=2) + '\n')
|
||||
print('Fresh synthetic dataset initialized; manifest written. No credentials recorded.')
|
||||
@@ -0,0 +1,6 @@
|
||||
# Verification environment only; Architecture B is installed natively by systemd inside it.
|
||||
FROM debian:12-slim
|
||||
ENV container=docker
|
||||
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y systemd systemd-sysv dbus ca-certificates curl procps && apt-get clean
|
||||
STOPSIGNAL SIGRTMIN+3
|
||||
CMD ["/sbin/init"]
|
||||
@@ -0,0 +1,7 @@
|
||||
# Native installer verification environments
|
||||
|
||||
These optional test harnesses execute the real installer and systemd service in isolated Debian 12 environments. Docker is test infrastructure, not an application deployment requirement. Administrative Docker access and privileged containers are needed for systemd; no Architecture A resources or host data directories are mounted.
|
||||
|
||||
Build a fresh release, then set `HEALTHAPP_RELEASE=/absolute/bundle` and run `python3 tools/native-install-test/local.py` and `python3 tools/native-install-test/remote.py`. The local harness builds the verification image first; run it before remote on a fresh machine. Both remove their own test containers. Remote also removes its own network/certificate volume and checks verified hostname rejection plus absence of local PostgreSQL.
|
||||
|
||||
Evidence includes actual distribution/runtime, PID/DB/HTTPS/workflow/restart, protected config permissions, and no-overwrite checks. It does not validate bare-metal networking, every intended distribution, HA, clinical validity or energy efficiency. Package/runtime versions come from feeds and are recorded; they must be controlled separately in a measurement setup.
|
||||
@@ -0,0 +1,35 @@
|
||||
import pathlib,subprocess,secrets,json,time
|
||||
import os
|
||||
root=pathlib.Path(__file__).resolve().parents[2]
|
||||
bundle=pathlib.Path(os.environ['HEALTHAPP_RELEASE']).resolve()
|
||||
name='healthapp-b-native-'+secrets.token_hex(4)
|
||||
image='healthapp-b-systemd-test:debian12'
|
||||
evidence=root/'ImplementationPlan/evidence';evidence.mkdir(exist_ok=True)
|
||||
def run(args,check=True):
|
||||
r=subprocess.run(args,capture_output=True,text=True)
|
||||
if check and r.returncode:raise RuntimeError('Command failed: '+str(args[:3])+'\n'+(r.stdout+r.stderr)[-4000:])
|
||||
return r
|
||||
run(['docker','build','-t',image,str(root/'tools/native-install-test')])
|
||||
run(['docker','run','--rm','-d','--privileged','--cgroupns=private','--tmpfs','/run','--tmpfs','/run/lock','--name',name,image])
|
||||
try:
|
||||
for _ in range(60):
|
||||
r=run(['docker','exec',name,'systemctl','is-system-running'],False)
|
||||
if r.stdout.strip() in ('running','degraded'):break
|
||||
time.sleep(.5)
|
||||
else:raise RuntimeError('systemd did not start')
|
||||
run(['docker','cp',str(bundle),name+':/release'])
|
||||
result=run(['docker','exec',name,'bash','/release/install.sh','--host','localhost'],False)
|
||||
(evidence/'native-debian12.log').write_text(result.stdout+result.stderr)
|
||||
print((result.stdout+result.stderr)[-5000:])
|
||||
if result.returncode:
|
||||
logs=run(['docker','exec',name,'journalctl','-u','healthapp-b','--no-pager','-n','40'],False)
|
||||
print(logs.stdout[-4000:]);raise RuntimeError('native installation failed')
|
||||
config_mode=run(['docker','exec',name,'stat','-c','%a %U %G','/etc/healthapp-b/appsettings.json']).stdout.strip()
|
||||
if config_mode!='640 root healthapp-b':raise RuntimeError('runtime configuration permissions are incorrect')
|
||||
before=run(['docker','exec',name,'sha256sum','/etc/healthapp-b/appsettings.json']).stdout
|
||||
duplicate=run(['docker','exec',name,'bash','/release/install.sh','--host','localhost'],False)
|
||||
if duplicate.returncode==0 or before!=run(['docker','exec',name,'sha256sum','/etc/healthapp-b/appsettings.json']).stdout:raise RuntimeError('existing installation was overwritten')
|
||||
data={'environment':run(['docker','exec',name,'cat','/etc/os-release']).stdout,'runtime':run(['docker','exec',name,'dotnet','--list-runtimes']).stdout,'applicationPID':run(['docker','exec',name,'systemctl','show','healthapp-b','--property','MainPID','--value']).stdout.strip(),'databaseStatus':run(['docker','exec',name,'pg_isready']).stdout.strip(),'result':'passed','overwriteRejected':True,'runtimeConfigMode':config_mode,'isolation':'Disposable privileged systemd Linux container; native installer/unit/services executed; not physical-host or measurement evidence'}
|
||||
(evidence/'native-debian12-summary.json').write_text(json.dumps(data,indent=2)+'\n')
|
||||
print('Native Debian 12 installation passed.')
|
||||
finally:run(['docker','stop',name],False)
|
||||
@@ -0,0 +1,42 @@
|
||||
import pathlib,subprocess,secrets,json,time,tempfile
|
||||
import os
|
||||
root=pathlib.Path(__file__).resolve().parents[2]
|
||||
bundle=pathlib.Path(os.environ['HEALTHAPP_RELEASE']).resolve()
|
||||
identity=secrets.token_hex(4);name='healthapp-b-remote-app-'+identity;db='healthapp-b-remote-db-'+identity;network='healthapp-b-remote-net-'+identity;volume='healthapp-b-remote-cert-'+identity
|
||||
password=secrets.token_hex(32);temporary=pathlib.Path(tempfile.mkdtemp(prefix='healthapp-b-remote-'))
|
||||
evidence=root/'ImplementationPlan/evidence'
|
||||
def run(args,check=True):
|
||||
r=subprocess.run(args,capture_output=True,text=True)
|
||||
if check and r.returncode:raise RuntimeError('Command failed: '+str(args[:3])+'\n'+(r.stdout+r.stderr).replace(password,'[redacted]')[-3500:])
|
||||
return r
|
||||
run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(temporary/'server.key'),'-out',str(temporary/'server.crt'),'-subj','/CN=b-database','-days','2','-addext','subjectAltName=DNS:b-database'])
|
||||
run(['docker','network','create',network]);run(['docker','volume','create',volume])
|
||||
try:
|
||||
run(['docker','run','--rm','--user','0','--entrypoint','sh','-v',str(temporary)+':/input:ro','-v',volume+':/certs','postgres:18.6','-c','cp /input/server.key /input/server.crt /certs/ && chown 999:999 /certs/server.key /certs/server.crt && chmod 600 /certs/server.key'])
|
||||
run(['docker','run','--rm','-d','--name',db,'--network',network,'--network-alias','b-database','--network-alias','wrong-b-database','-v',volume+':/certs:ro','-e','POSTGRES_PASSWORD='+password,'postgres:18.6','postgres','-c','ssl=on','-c','ssl_cert_file=/certs/server.crt','-c','ssl_key_file=/certs/server.key'])
|
||||
for _ in range(60):
|
||||
if run(['docker','exec',db,'pg_isready','-U','postgres'],False).returncode==0:break
|
||||
time.sleep(.5)
|
||||
else:raise RuntimeError('TLS database did not start')
|
||||
run(['docker','run','--rm','-d','--privileged','--cgroupns=private','--tmpfs','/run','--tmpfs','/run/lock','--name',name,'--network',network,'healthapp-b-systemd-test:debian12'])
|
||||
for _ in range(60):
|
||||
if run(['docker','exec',name,'systemctl','is-system-running'],False).stdout.strip() in ('running','degraded'):break
|
||||
time.sleep(.5)
|
||||
run(['docker','cp',str(bundle),name+':/release']);run(['docker','cp',str(temporary/'server.crt'),name+':/root/db-ca.crt'])
|
||||
admin=temporary/'admin.connection';admin.write_text('Host=b-database;Database=postgres;Username=postgres;Password='+password+';SslMode=VerifyFull;RootCertificate=/root/db-ca.crt');admin.chmod(0o600)
|
||||
run(['docker','cp',str(admin),name+':/root/admin.connection']);run(['docker','exec',name,'chmod','600','/root/admin.connection'])
|
||||
r=run(['docker','exec',name,'bash','/release/install.sh','--mode','remote','--host','localhost','--postgres-admin-file','/root/admin.connection'],False)
|
||||
(evidence/'native-debian12-remote.log').write_text((r.stdout+r.stderr).replace(password,'[redacted]'));print((r.stdout+r.stderr).replace(password,'[redacted]')[-4500:])
|
||||
if r.returncode:
|
||||
print(run(['docker','exec',name,'journalctl','-u','healthapp-b','--no-pager','-n','30'],False).stdout[-3000:]);raise RuntimeError('remote installation failed')
|
||||
config_mode=run(['docker','exec',name,'stat','-c','%a %U %G','/etc/healthapp-b/appsettings.json']).stdout.strip()
|
||||
if config_mode!='640 root healthapp-b':raise RuntimeError('runtime configuration permissions are incorrect')
|
||||
noServer=run(['docker','exec',name,'sh','-c','! command -v postgres && ! command -v pg_isready'],False).returncode==0
|
||||
if not noServer:raise RuntimeError('remote mode installed local PostgreSQL')
|
||||
run(['docker','exec',name,'sh','-c',"mkdir /root/wrong-name && sed 's/Host=b-database/Host=wrong-b-database/g' /var/lib/healthapp-b-installation/deployment/installation.json > /root/wrong-name/installation.json"])
|
||||
negative=run(['docker','exec',name,'dotnet','/release/provisioner/HealthApp.Provisioning.dll','verify-database','--plan','/root/wrong-name'],False)
|
||||
if negative.returncode==0:raise RuntimeError('wrong TLS hostname was accepted')
|
||||
summary={'environment':run(['docker','exec',name,'cat','/etc/os-release']).stdout,'runtime':run(['docker','exec',name,'dotnet','--list-runtimes']).stdout,'database':'PostgreSQL 18.6 separate container/host namespace; TLS certificate SAN b-database','sslMode':'VerifyFull','wrongHostnameRejected':True,'localPostgresInstalled':False,'result':'passed','runtimeConfigMode':config_mode,'isolation':'Separate disposable systemd app and TLS DB containers; no Architecture A database access; not measurement-host evidence'}
|
||||
(evidence/'native-debian12-remote-summary.json').write_text(json.dumps(summary,indent=2)+'\n');print('Remote Debian 12 native installation passed; local PostgreSQL absent.')
|
||||
finally:
|
||||
run(['docker','stop',name],False);run(['docker','stop',db],False);run(['docker','volume','rm',volume],False);run(['docker','network','rm',network],False)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Optional Docker-backed test harness; deployment itself remains native Linux/systemd."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import secrets
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--reference', action='store_true', help='Run the preserved B-local A baseline')
|
||||
parser.add_argument('--image', default='postgres:18.6')
|
||||
args = parser.parse_args()
|
||||
repository = pathlib.Path(__file__).resolve().parents[1]
|
||||
cwd = repository / 'Reference/ArchitectureA' if args.reference else repository
|
||||
evidence = repository / 'ImplementationPlan/evidence'
|
||||
evidence.mkdir(exist_ok=True)
|
||||
label = 'reference' if args.reference else 'b'
|
||||
name = 'healthapp-b-tests-' + secrets.token_hex(4)
|
||||
password = secrets.token_hex(32)
|
||||
container_env = dict(os.environ, POSTGRES_PASSWORD=password)
|
||||
subprocess.run(['docker', 'run', '--rm', '-d', '--name', name, '-p', '127.0.0.1::5432',
|
||||
'-e', 'POSTGRES_PASSWORD', args.image], env=container_env,
|
||||
stdout=subprocess.DEVNULL, check=True)
|
||||
try:
|
||||
for attempt in range(60):
|
||||
if subprocess.run(['docker', 'exec', name, 'pg_isready', '-U', 'postgres'],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:
|
||||
break
|
||||
time.sleep(.5)
|
||||
else:
|
||||
raise RuntimeError('Disposable database did not start.')
|
||||
ports = json.loads(subprocess.check_output(
|
||||
['docker', 'inspect', '--format', '{{json .NetworkSettings.Ports}}', name], text=True))
|
||||
port = ports['5432/tcp'][0]['HostPort']
|
||||
env = dict(os.environ, TEST_POSTGRES_CONNECTION='Host=127.0.0.1;Port=' + port +
|
||||
';Database=postgres;Username=postgres;Password=' + password)
|
||||
dotnet = os.environ.get('HEALTHAPP_DOTNET', 'dotnet')
|
||||
for stage, command in [('build', ['build', 'HealthApp.slnx', '-c', 'Release']),
|
||||
('tests', ['test', 'HealthApp.slnx', '-c', 'Release', '--no-build',
|
||||
'--logger', 'trx', '--results-directory', str(evidence / (label + '-trx'))])]:
|
||||
result = subprocess.run([dotnet, *command], cwd=cwd, env=env, capture_output=True, text=True)
|
||||
output = (result.stdout + result.stderr).replace(password, '[redacted]')
|
||||
(evidence / (label + '-' + stage + '.log')).write_text(output)
|
||||
print(output[-5000:])
|
||||
if result.returncode:
|
||||
raise SystemExit(result.returncode)
|
||||
finally:
|
||||
subprocess.run(['docker', 'stop', name], stdout=subprocess.DEVNULL, check=True)
|
||||
Reference in new issue
Block a user