"""Real TLS shutdown oracles; fixture failures and unexpected errors fail the gate.""" import argparse import base64 import hashlib import json from pathlib import Path import socket import ssl import subprocess import tempfile import threading import time BACKENDS = ['threaded', 'zio', 'zio4', 'zio-native'] HTTP_MODES = ['default', 'explicit', 'idempotent', 'retire', 'zero-capacity', 'evict', 'active', 'active-concurrent', 'active-cancel', 'active-timeout', 'expired', 'blocked', 'blocked-retire', 'blocked-multi', 'cancel'] WS_MODES = ['default', 'explicit', 'reader', 'writer', 'duplex', 'read-cancel', 'write-cancel', 'expired', 'blocked-writer', 'cancel'] ERRORS = {'active-concurrent':'ShutdownInProgress', 'active-cancel':'Canceled', 'write-cancel':'Canceled', 'active-timeout':'ShutdownTimeout', 'expired':None, 'blocked':'ShutdownTimeout', 'blocked-multi':'ShutdownTimeout', 'blocked-writer':'CloseTimeout', 'cancel':'Canceled', 'unavailable':'ConcurrencyUnavailable'} def receive_head(connection): head=b'' while b'\r\n\r\n' not in head: data=connection.recv(4096) if not data: raise ValueError('incomplete request head') head+=data if len(head)>16384: raise ValueError('oversize request head') return head def exact(connection, size): result=b'' while len(result)1024*1024: raise ValueError('unexpected large client frame') mask=exact(peer,4); data=exact(peer,size) opcode=prefix[0]&15 if opcode>=8 and (not prefix[0]&0x80 or size>125): raise ValueError('invalid control frame') if opcode==8: payload=bytes(byte^mask[index%4] for index,byte in enumerate(data)) if len(payload)==1: raise ValueError('invalid close payload') record['close_frame']=True break if opcode not in (1,2,9,10): raise ValueError('unexpected client opcode') else: raise ValueError('no WebSocket close frame') try: data=peer.recv(1) record['closure']='close_notify' if data==b'' else 'unexpected data' if data==b'': try: peer.unwrap().close() except (ssl.SSLError, OSError): pass except ssl.SSLEOFError: record['closure']='TCP EOF without close_notify' except Exception as error: record['fixture_error']=type(error).__name__+': '+str(error) finally: raw.close() def accept(): try: while not stopped.is_set(): try: raw,_=listener.accept() except socket.timeout: continue thread=threading.Thread(target=serve,args=(raw,)); workers.append(thread); thread.start() if len(workers)>8: raise ValueError('too many fixture connections') except Exception as error: errors.append(type(error).__name__) finally: listener.close() thread=threading.Thread(target=accept); thread.start() try: process=subprocess.run([str(probe),backend,f'https://localhost:{port}/',str(cert),mode],capture_output=True,timeout=8) result=json.loads(process.stdout) if process.returncode==0 else {'crash':process.returncode,'detail':process.stderr.decode(errors='replace')[:2000]} except subprocess.TimeoutExpired: result={'harness_timeout':True} finally: stopped.set(); thread.join(2) for worker in workers: worker.join(6) if thread.is_alive() or any(worker.is_alive() for worker in workers): raise RuntimeError('fixture failed to terminate') expected_error=ERRORS.get(mode) if mode=='expired': expected_error='ShutdownTimeout' if protocol=='http' else 'CloseTimeout' passed=not errors and 'crash' not in result and 'harness_timeout' not in result and result.get('failure') is None and result.get('close_error')==expected_error passed=passed and len(observations)==(3 if mode=='blocked-multi' else 2 if mode=='evict' else 1) forced=blocked or mode in ('expired','unavailable') for record in observations: passed=passed and 'fixture_error' not in record if not forced: passed=passed and record.get('closure')=='close_notify' if protocol=='ws' and not forced: passed=passed and record.get('close_frame') is True if mode.startswith('blocked') or mode in ('cancel','write-cancel'): passed=passed and 0=60_000_000 if protocol=='http' and mode not in ('default','retire','zero-capacity','evict','blocked-retire'): passed=passed and result.get('rejected') is True if protocol=='ws' and mode in ('reader','writer','duplex','read-cancel','write-cancel','blocked-writer','cancel'): passed=passed and result.get('joined') is True return {'backend':backend,'mode':mode,'passed':passed,'result':result,'peers':observations,'fixture_errors':errors} def main(): parser=argparse.ArgumentParser(); parser.add_argument('--probe',type=Path,required=True); parser.add_argument('--protocol',choices=['http','ws'],required=True); parser.add_argument('--backend',action='append',choices=BACKENDS); parser.add_argument('--filter',default=''); args=parser.parse_args() results=[] with tempfile.TemporaryDirectory() as temporary: root=Path(temporary); cert=root/'cert.pem'; key=root/'key.pem' subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(key),'-out',str(cert),'-days','1','-subj','/CN=localhost','-addext','subjectAltName=DNS:localhost,IP:127.0.0.1'],capture_output=True,check=True,timeout=15) context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); context.load_cert_chain(cert,key) for backend in args.backend or BACKENDS: modes=(HTTP_MODES if args.protocol=='http' else WS_MODES)+(['unavailable'] if backend=='threaded' else []) for mode in modes: if args.filter not in mode: continue record=observe(args.probe,context,cert,args.protocol,backend,mode); results.append(record) if not record['passed']: print(json.dumps(record),flush=True) print(json.dumps({'protocol':args.protocol,'executed':len(results),'passed':sum(record['passed'] for record in results)}),flush=True) if not results or not all(record['passed'] for record in results): raise SystemExit(1) if __name__=='__main__': main()