#!/usr/bin/env python3
"""Local TLS identity/trust exercise. Creates ephemeral certs, no OS trust changes."""
import json
from pathlib import Path
import shutil
import socket
import ssl
import subprocess
import sys
import tempfile
from concurrent.futures import ThreadPoolExecutor


class UnsupportedEnvironment(RuntimeError):
    """Python, the ssl backend or the certificate command cannot run this lab."""


def check_environment():
    """Check everything before any temporary key or certificate is created."""
    problems=[]
    if sys.version_info<(3,10):problems.append(f'Python {sys.version.split()[0]} is below the lab minimum 3.10')
    if not getattr(ssl,'HAS_TLSv1_3',False):problems.append(f'ssl backend {ssl.OPENSSL_VERSION} lacks TLS 1.3')
    openssl=shutil.which('openssl')
    if openssl is None:problems.append('no OpenSSL-compatible command was found')
    if problems:raise UnsupportedEnvironment('; '.join(problems)+'. Use the L13 offline analysis route.')
    return openssl


def read_exact(conn,count):
    data=bytearray()
    while len(data)<count:
        part=conn.recv(count-len(data))
        if not part:raise EOFError("truncated TLS application message")
        data.extend(part)
    return bytes(data)


def demo(strict=False):
    openssl=check_environment()
    with tempfile.TemporaryDirectory(prefix='network-course-tls-') as folder:
        directory=Path(folder);key=directory/'key.pem';cert=directory/'cert.pem';conf=directory/'cert.cnf'
        conf.write_text('[req]\ndistinguished_name=dn\nx509_extensions=ext\nprompt=no\n[dn]\nCN=localhost\n[ext]\nsubjectAltName=DNS:localhost,IP:127.0.0.1\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always\n')
        subprocess.run([openssl,'req','-x509','-newkey','rsa:2048','-nodes','-days','1',
            '-keyout',str(key),'-out',str(cert),'-config',str(conf)],check=True,capture_output=True,timeout=30)
        server_context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        server_context.minimum_version=ssl.TLSVersion.TLSv1_3
        server_context.load_cert_chain(cert,key)
        outcomes=[]
        for label,hostname,trust in [('trusted-name','localhost',True),('wrong-name','wrong.test',True),('untrusted','localhost',False)]:
            with socket.socket() as listener,ThreadPoolExecutor(max_workers=1) as pool:
                listener.bind(('127.0.0.1',0));listener.listen();listener.settimeout(5)
                def serve():
                    with listener.accept()[0] as raw:
                        raw.settimeout(5)
                        try:
                            with server_context.wrap_socket(raw,server_side=True) as conn:
                                data=read_exact(conn,6);conn.sendall(b'reply:'+data)
                                return {'accepted':True}
                        except OSError as exc:return {'accepted':False,'error':type(exc).__name__}
                future=pool.submit(serve)
                context=ssl.create_default_context(cafile=str(cert)) if trust else ssl.create_default_context()
                context.minimum_version=ssl.TLSVersion.TLSv1_3
                if strict:
                    context.verify_flags |= ssl.VERIFY_X509_STRICT | ssl.VERIFY_X509_PARTIAL_CHAIN
                try:
                    with socket.create_connection(listener.getsockname(),timeout=5) as raw:
                        with context.wrap_socket(raw,server_hostname=hostname) as connection:
                            connection.sendall(b'lesson');reply=read_exact(connection,12)
                            result={'case':label,'verified':True,'hostname':hostname,
                                    'tls_version':connection.version(),'reply':reply.decode()}
                except ssl.SSLCertVerificationError as exc:
                    result={'case':label,'verified':False,'hostname':hostname,
                            'error':'SSLCertVerificationError','verify_code':exc.verify_code,'reason':exc.verify_message}
                result['server']=future.result(timeout=6);outcomes.append(result)
        if [item['verified'] for item in outcomes]!=[True,False,False]:
            raise RuntimeError('TLS outcomes differ from the lesson predictions')
        version=subprocess.run([openssl,'version'],check=True,capture_output=True,text=True).stdout.strip()
        return {'kind':'real local TLS; ephemeral self-signed leaf trusted only by explicit SSLContext',
            'openssl_cli':version,'python_ssl':ssl.OPENSSL_VERSION,'strict_requested':strict,'outcomes':outcomes,
            'scope':'No system trust store modified; cert/key deleted on exit; no TLS traffic capture or ECH test.'}


if __name__=='__main__':
    try:print(json.dumps(demo(),ensure_ascii=False,indent=2))
    except UnsupportedEnvironment as exc:
        print(f'L13 cannot run here: {exc}',file=sys.stderr);raise SystemExit(2)
