# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR80
# Experiment: verified local tls 1 2 1 3 and hostname failure
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR80 | Verified local TLS 1.2/1.3 and hostname failure
# Execute the named operation; expose states and assert the laboratory invariant.
import json



DEFAULT={'version': '1.3', 'hostname': 'localhost'}
ALTERNATE={'hostname': 'wrong.lab'}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    version=params['version']
    hostname=params['hostname']
    import re
    if version not in ('1.2','1.3') or not isinstance(hostname,str) or not re.fullmatch(r'[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?',hostname):
        raise ValueError('Use TLS 1.2/1.3 and a lowercase classroom DNS name')
    import ssl,tempfile
    from pathlib import Path
    from datetime import datetime,timedelta,timezone
    from cryptography import x509
    from cryptography.x509.oid import NameOID
    from cryptography.hazmat.primitives import hashes,serialization
    from cryptography.hazmat.primitives.asymmetric import ec
    now=datetime.now(timezone.utc);ca=ec.generate_private_key(ec.SECP256R1());leaf=ec.generate_private_key(ec.SECP256R1());N=lambda s:x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,s)]);root=N('PSUT local CA');cert=lambda subject,issuer,key,signer,isca:x509.CertificateBuilder().subject_name(subject).issuer_name(issuer).public_key(key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(days=1)).not_valid_after(now+timedelta(days=1)).add_extension(x509.BasicConstraints(ca=isca,path_length=0 if isca else None),True).add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False).add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(signer.public_key()),False).add_extension(x509.KeyUsage(digital_signature=True,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=isca,crl_sign=isca,encipher_only=None,decipher_only=None),True).sign(signer,hashes.SHA256())
    rootcert=cert(root,root,ca,ca,True);leafcert=cert(N('localhost'),root,leaf,ca,False);ver=ssl.TLSVersion.TLSv1_3 if version=='1.3' else ssl.TLSVersion.TLSv1_2
    steps=[]
    with tempfile.TemporaryDirectory() as tmp:
        p=Path(tmp);(p/'cert.pem').write_bytes(leafcert.public_bytes(serialization.Encoding.PEM));(p/'key.pem').write_bytes(leaf.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));server=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);server.load_cert_chain(p/'cert.pem',p/'key.pem');client=ssl.create_default_context(cadata=rootcert.public_bytes(serialization.Encoding.PEM).decode());server.minimum_version=server.maximum_version=client.minimum_version=client.maximum_version=ver
        ci,co,si,so=[ssl.MemoryBIO() for i in range(4)];c=client.wrap_bio(ci,co,server_hostname=hostname);s=server.wrap_bio(si,so,server_side=True);done=[False,False];error=None
        for i in range(30):
            try:
                for j,obj in enumerate((c,s)):
                    if not done[j]:
                        try:obj.do_handshake();done[j]=True
                        except ssl.SSLWantReadError:pass
                    out,inp=(co,si) if j==0 else (so,ci);buf=out.read();inp.write(buf);steps.append({'flight':i,'sender':'client' if j==0 else 'server','wire_bytes':len(buf),'complete':done[j]})
                if all(done):break
            except ssl.SSLCertVerificationError as e:error=e.verify_message;break
        if all(done):
            msg=b'GET / HTTP/1.0\r\n\r\n';c.write(msg);wire=co.read();si.write(wire);read=s.read();result={'verified':True,'version':c.version(),'payload_recovered':read==msg,'plaintext_visible_in_wire':msg in wire}
        else:result={'verified':False,'error':error}
    # Independently check the stated mathematical or protocol invariant.
    assert result["verified"]==(hostname=="localhost") and (not result["verified"] or result["payload_recovered"]), "verification failed"
    return {"steps":steps,"result":result}

if __name__ == "__main__":
    import argparse
    parser=argparse.ArgumentParser();parser.add_argument("--inputs",default="{}");parser.add_argument("--test",action="store_true");args=parser.parse_args()
    if args.test:
        for case in [{},ALTERNATE]:run(case)
        print("PASS")
    else:print(json.dumps(run(json.loads(args.inputs)),indent=2))
