"""Fresh tmpfs PG bootstrap with production HBA; isolated network, no host ports/data.""" import json,subprocess,time,uuid,os from pathlib import Path root=Path(__file__).resolve().parents[1];name='mtusi-lab7-bootstrap-check-'+uuid.uuid4().hex[:8] values=dict(line.split('=',1) for line in (root/'.env').read_text().splitlines() if '=' in line) run_env={**os.environ,'POSTGRES_PASSWORD':values['POSTGRES_PASSWORD']} cmd=['docker','run','-d','--name',name,'--network','none','--cpus','1','--memory','512m','--security-opt','no-new-privileges:true','--cap-drop','ALL'] for cap in ['CHOWN','DAC_OVERRIDE','FOWNER','SETGID','SETUID']:cmd+=['--cap-add',cap] cmd+=['--tmpfs','/var/lib/postgresql/data','--tmpfs','/tmp','-e','POSTGRES_PASSWORD','-e','POSTGRES_USER=messenger','-e','POSTGRES_DB=messenger','-v',str(root/'infra/postgres/pg_hba.conf')+':/etc/postgresql/pg_hba.conf:ro','postgres:16.6-alpine','postgres','-c','listen_addresses=127.0.0.1','-c','hba_file=/etc/postgresql/pg_hba.conf'] try: subprocess.run(cmd,check=True,stdout=subprocess.DEVNULL,env=run_env) for _ in range(60): p=subprocess.run(['docker','exec',name,'pg_isready','-U','messenger','-d','messenger'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) if p.returncode==0:break time.sleep(1) else:raise AssertionError('Fresh PG bootstrap timed out') # pg_isready may see the temporary init server; wait until TCP accepts correct password. for _ in range(30): p=subprocess.run(['docker','exec',name,'sh','-c','PGPASSWORD="$POSTGRES_PASSWORD" psql -h127.0.0.1 -Umessenger -dmessenger -Atc "SELECT 1"'],capture_output=True,text=True) if p.returncode==0 and p.stdout.strip()=='1':break time.sleep(1) else:raise AssertionError('SCRAM bootstrap login failed') wrong=subprocess.run(['docker','exec','-e','PGPASSWORD=synthetic_wrong_password',name,'psql','-h127.0.0.1','-Umessenger','-dmessenger','-Atc','SELECT 1'],capture_output=True,text=True) assert wrong.returncode and 'password authentication failed' in wrong.stderr print(json.dumps({'status':'PASS','fresh_cluster_initialized':True,'tcp_correct_password':True,'tcp_wrong_password_denied':True,'persistent_lab_data_untouched':True},indent=2)) finally:subprocess.run(['docker','rm','-f',name],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)