async def serve(handler, host="", port=0, context=None): async def handle(client): host, port = client.remote_address() logger.debug("New HTTP connection: %s:%i", host, port) client = HTTPServerClient(handler, client) await client.process() logger.info("Starting HTTP server at %s:%i", host, port) async with tls.serve(handle, host, port, context): yield logger.info("HTTP server is closed")
async def test_tls(): async def handler(client): assert await client.recv() == b"hi" await client.send(b"hello") # Create a self signed certificate pkey = tls.TLSPrivateKey.generate() cert = tls.TLSCertificate.generate(pkey) cert.subject["CN"] = NAME cert.issuer["CN"] = NAME cert.sign(pkey) context = tls.TLSContext() context.set_certificate(cert, pkey) async with tls.serve(handler, IP, 12345, context): context = tls.TLSContext() context.set_authority(cert) async with tls.connect(NAME, 12345, context) as client: assert client.remote_address() == (IP, 12345) await client.send(b"hi") assert await client.recv() == b"hello"
async def test_handshake_failure(): async def handler(client): assert await client.recv() == b"hi" await client.send(b"hello") pkey = tls.TLSPrivateKey.generate() cert = tls.TLSCertificate.generate(pkey) cert.subject["CN"] = NAME cert.issuer["CN"] = NAME cert.sign(pkey) context = tls.TLSContext() context.set_certificate(cert, pkey) async with tls.serve(handler, IP, 12345, context): context = tls.TLSContext() with pytest.raises(ssl.SSLCertVerificationError): async with tls.connect(NAME, 12345, context) as client: pass context.set_authority(cert) async with tls.connect(NAME, 12345, context) as client: await client.send(b"hi") assert await client.recv() == b"hello"
def serve_transport_socket(handler, settings, host, port, context): transport = settings["prudp.transport"] if transport == settings.TRANSPORT_TCP: return tls.serve(handler, host, port, context) return websocket.serve(handler, host, port, context, protocol="NEX")