"""Fresh local PostgreSQL authentication/URI observations. No cloud account.""" from pathlib import Path import hashlib import json import subprocess import time import uuid from urllib.parse import quote ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / 'docs/verification/stage-b' SEALED = ROOT / 'evaluation/sealed/postgres' SEALED.mkdir(parents=True, exist_ok=True) if (SEALED / 'manifest.json').exists(): raise SystemExit('Existing cohort: do not overwrite sealed observations') name = 'dee-holdout-pg-' + uuid.uuid4().hex[:10] # Deliberately synthetic, local-only test credential. Never a production secret. password = 'ProspectiveLocalPass#37' commands = [] cases = [] def run(label, args, record_output=True): r = subprocess.run(args, cwd=ROOT, capture_output=True, timeout=60) commands.append({'id': label, 'command': args, 'exit': r.returncode}) if record_output: folder = SEALED / 'observations' / label folder.mkdir(parents=True, exist_ok=True) (folder / 'stdout.txt').write_bytes(r.stdout) (folder / 'stderr.txt').write_bytes(r.stderr) return r def save(case_id, text, family, required, negative, evidence, options=None): folder = SEALED / case_id folder.mkdir(exist_ok=True) (folder / 'input.txt').write_bytes(text) cases.append({'id': case_id, 'group': 'postgres-auth-reproduction' if family == 'database-connection' else 'postgres-uri-reproduction', 'family': family, 'entry': 'diagnose', 'requiredRules': required, 'negative': negative, 'options': options or {}, 'provenance': 'reproduction', 'canaries': [password] if family == 'database-url' else [], 'inputs': {'input.txt': {'sha256': hashlib.sha256(text).hexdigest(), 'bytes': len(text)}}, 'evidence': evidence, 'sources': ['https://www.postgresql.org/docs/current/auth-peer.html', 'https://www.postgresql.org/docs/current/client-authentication-problems.html', 'https://www.postgresql.org/docs/current/libpq-connect.html']}) try: created = run('start', ['docker', 'run', '-d', '--rm', '--name', name, '--network', 'none', '--memory=512m', '--pids-limit=128', '--tmpfs', '/var/lib/postgresql/data:rw', '-e', 'POSTGRES_PASSWORD=' + password, '-e', 'POSTGRES_INITDB_ARGS=--auth-local=peer --auth-host=scram-sha-256', 'postgres:17-alpine']) assert created.returncode == 0, 'PostgreSQL container did not start' ready = False for _ in range(60): check = run('readiness', ['docker', 'exec', name, 'pg_isready', '-U', 'postgres'], False) if check.returncode == 0: ready = True break time.sleep(0.5) assert ready, 'PostgreSQL did not become ready' version = run('version', ['docker', 'exec', name, 'psql', '--version']).stdout.decode().strip() peer = run('peer-failure', ['docker', 'exec', '--user', 'nobody', name, 'psql', '-U', 'postgres', '-d', 'postgres', '-c', 'SELECT 1']) assert peer.returncode != 0 and b'Peer authentication failed' in peer.stderr, 'Peer reproduction did not produce the declared failure' save('pg-peer-failure', peer.stderr, 'database-connection', ['database-connection.peer-auth-failed'], False, {'exit': peer.returncode, 'psql': version, 'osUser': 'nobody', 'databaseRole': 'postgres'}) bad = run('password-failure', ['docker', 'exec', '-e', 'PGPASSWORD=deliberately-wrong', name, 'psql', '-h', '127.0.0.1', '-U', 'postgres', '-d', 'postgres', '-c', 'SELECT 1']) assert bad.returncode != 0 and b'password authentication failed' in bad.stderr, 'Password reproduction did not produce the declared failure' save('pg-password-failure', bad.stderr, 'database-connection', ['database-connection.password-auth-failed'], False, {'exit': bad.returncode, 'psql': version, 'transport': 'TCP'}) good = run('auth-control', ['docker', 'exec', '-e', 'PGPASSWORD=' + password, name, 'psql', '-h', '127.0.0.1', '-U', 'postgres', '-d', 'postgres', '-Atc', 'SELECT 1']) assert good.returncode == 0 and good.stdout.strip() == b'1', 'Authenticated control did not succeed' save('pg-auth-control', good.stdout, 'database-connection', [], True, {'exit': good.returncode, 'psql': version, 'queryResult': 1}) uri = 'postgresql://postgres:' + password + '@127.0.0.1:5432/postgres' encoded = 'postgresql://postgres:' + quote(password, safe='') + '@127.0.0.1:5432/postgres' encoded_result = run('uri-encoded-control', ['docker', 'exec', name, 'psql', encoded, '-Atc', 'SELECT 1']) assert encoded_result.returncode == 0 and encoded_result.stdout.strip() == b'1', 'Encoded URI control failed' raw_result = run('uri-raw-observation', ['docker', 'exec', name, 'psql', uri, '-Atc', 'SELECT 1']) # Ground truth follows actual client behavior, never the engine's output. accepted = raw_result.returncode == 0 and raw_result.stdout.strip() == b'1' save('pg-uri-raw-observation', uri.encode(), 'database-url', [] if accepted else ['database-url.password-needs-encoding'], accepted, {'rawExit': raw_result.returncode, 'rawUriAccepted': accepted, 'encodedControlExit': encoded_result.returncode, 'psql': version}, {'client': 'psql'}) (SEALED / 'manifest.json').write_text(json.dumps({'schema': '0.1', 'engineFrozenAt': '4b862c6', 'split': 'prospective-holdout', 'cases': cases, 'commands': commands}, indent=2) + '\n', encoding='utf-8') print(json.dumps({'collection': 'postgres', 'status': 'collected', 'cases': len(cases), 'groups': len(set(c['group'] for c in cases)), 'rawInputsPrinted': False})) except Exception as error: (SEALED / 'collection-failure.json').write_text(json.dumps({'reason': str(error), 'commands': commands, 'collectedCases': [c['id'] for c in cases]}, indent=2) + '\n', encoding='utf-8') raise finally: stopped = run('stop', ['docker', 'stop', name], False) (OUT / 'postgres-collection-lifecycle.json').write_text(json.dumps({'container': name, 'stopExit': stopped.returncode, 'hostPortsPublished': False, 'cloudDatabaseUsed': False}, indent=2) + '\n', encoding='utf-8')