diff --git a/.github/workflows/h2-proxy.yml b/.github/workflows/h2-proxy.yml new file mode 100644 index 00000000..8ed41d89 --- /dev/null +++ b/.github/workflows/h2-proxy.yml @@ -0,0 +1,30 @@ +name: h2-proxy +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + types: [ opened, reopened, synchronize, labeled, unlabeled ] + workflow_dispatch: + +permissions: + contents: read + +jobs: + h2-proxy: + if: github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'h2-proxy') + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: make test_h2_proxy + run: make -f makefile.dev test_h2_proxy + - uses: actions/upload-artifact@v4 + if: always() + with: + name: h2-proxy-reports + path: | + build/h2-proxy/runs/**/report.json + build/h2-proxy/runs/**/*.log + build/h2-proxy/build.log + retention-days: 14 diff --git a/docker/Dockerfile.h2-proxy b/docker/Dockerfile.h2-proxy new file mode 100644 index 00000000..7496eb87 --- /dev/null +++ b/docker/Dockerfile.h2-proxy @@ -0,0 +1,21 @@ +FROM debian:bookworm-slim AS build +RUN apt-get update && apt-get install -y --no-install-recommends \ + g++ cmake ninja-build zlib1g-dev && rm -rf /var/lib/apt/lists/* +WORKDIR /src +COPY CMakeLists.txt ixwebsocket-config.cmake.in ixwebsocket.pc.in ./ +COPY CMake/ CMake/ +COPY ixwebsocket/ ixwebsocket/ +COPY test/h2_proxy/ test/h2_proxy/ +RUN cmake -S test/h2_proxy -B build -GNinja -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_UNITY_BUILD=ON && cmake --build build --parallel 2 + +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends \ + nghttp2-proxy openssl python3 python3-venv libstdc++6 zlib1g \ + && rm -rf /var/lib/apt/lists/* +COPY test/h2_proxy/requirements.txt /requirements.txt +RUN python3 -m venv /venv && /venv/bin/pip install --no-cache-dir -r /requirements.txt +COPY test/h2_proxy/ /app/test/h2_proxy/ +COPY --from=build /src/build/h2_proxy_server /app/build/h2-proxy/h2_proxy_server +WORKDIR /app +ENTRYPOINT ["/venv/bin/python", "/app/test/h2_proxy/run.py"] diff --git a/docker/Dockerfile.h2-proxy.dockerignore b/docker/Dockerfile.h2-proxy.dockerignore new file mode 100644 index 00000000..35ab417e --- /dev/null +++ b/docker/Dockerfile.h2-proxy.dockerignore @@ -0,0 +1,11 @@ +** +!CMakeLists.txt +!ixwebsocket-config.cmake.in +!ixwebsocket.pc.in +!CMake/ +!CMake/** +!ixwebsocket/ +!ixwebsocket/** +!test/ +!test/h2_proxy/ +!test/h2_proxy/** diff --git a/docs/build.md b/docs/build.md index 7928bdba..7a3e370e 100644 --- a/docs/build.md +++ b/docs/build.md @@ -59,6 +59,11 @@ Autobahn protocol compliance checks run in Docker with the CI check; it also runs on `master` and manually. See the [Autobahn instructions](autobahn.md) for reports and local debugging. +HTTP/2 reverse-proxy compatibility can be tested separately with +`make -f makefile.dev test_h2_proxy`. It checks a TLS/H2 Extended CONNECT client +through nghttpx to an HTTP/1.1 IXWebSocket backend. See the +[H2 proxy test](h2-proxy.md) for coverage, native runs, and the Envoy reproduction. + The library defaults to C++11 and requires C++11 or later. To build with a newer standard, pass `-DCMAKE_CXX_STANDARD=17` (or another supported standard). The CLI and tests inherit this choice; the test framework requires at least C++14. diff --git a/docs/h2-proxy.md b/docs/h2-proxy.md new file mode 100644 index 00000000..0099b5fd --- /dev/null +++ b/docs/h2-proxy.md @@ -0,0 +1,89 @@ +# WebSockets behind an HTTP/2 reverse proxy + +The integration test exercises this flow with the current IXWebSocket source: + +```text +RFC 8441 client -- TLS + HTTP/2 --> nghttpx -- HTTP/1.1 Upgrade --> IXWebSocket +``` + +The frontend client negotiates `h2` through ALPN, waits for +`SETTINGS_ENABLE_CONNECT_PROTOCOL`, and sends Extended CONNECT with +`:protocol: websocket`. It requires an HTTP/2 200 response. It does not fall back +to HTTP/1.1 or send `Sec-WebSocket-Key`; the proxy must synthesize the HTTP/1.1 +handshake for the backend. The backend uses the existing `WebSocketServer` API +and its normal HTTP/1.1 handshake validation. + +## Run locally + +With Docker running, from the repository root: + +```sh +make -f makefile.dev test_h2_proxy +``` + +The target builds the current source, installs the proxy and pinned Python test +clients inside an image, and runs all services in one isolated container. It +publishes no ports and needs no host Python packages or proxy installation. +Docker supplies the test environment; it is not a library dependency. + +Progress prints one PASS line per group. Each run retains `report.json`, backend +logs, and proxy access/error logs under `build/h2-proxy/runs/run-*`. Image build +output goes to `build/h2-proxy/build.log`. Backend/proxy startup, network operations, +and process shutdown have bounded waits. The fixture asks the backend to stop +normally and checks that it joins its workers and exits successfully. + +Coverage includes: + +- TLS certificate validation, ALPN, Extended CONNECT, and HTTP/2 success status. +- Forwarded Origin/custom headers, paths, and query strings. +- Empty, Unicode and binary messages, fragmentation, and ping/pong. +- Per-message deflate enabled and disabled; 256 KiB incompressible messages that + exceed the HTTP/2 flow-control window. +- Three simultaneous WebSocket streams on one HTTP/2 connection. +- Closing or resetting one stream while another continues exchanging messages. +- Client/server-initiated close codes and reasons, followed by a new WebSocket + stream on the same connection. + +After the WebSocket Close exchange, nghttpx can retire a stream with +`RST_STREAM(NO_ERROR)` rather than only END_STREAM. The client accepts that only +when both WebSocket Close frames have been exchanged. Premature resets and other +reset codes fail the test. + +This is a protocol integration test using Python `h2` and `wsproto`, not browser +automation, an Autobahn run, or a performance benchmark. It adds no native HTTP/2 +support to IXWebSocket. It runs separately from the regular unit suite. + +## Native run and Envoy reproduction + +Docker is optional if CMake, a C++11 compiler, zlib development files, Python 3.10+, +OpenSSL's command-line tool, and nghttpx are installed. On macOS, the nghttp2 +Homebrew formula supplies nghttpx: + +```sh +brew install nghttp2 +make -f makefile.dev test_h2_proxy_native +``` + +The runner also includes an Envoy configuration: + +```sh +make -f makefile.dev test_h2_proxy_native H2_PROXY_ARGS='--proxy envoy' +``` + +**Envoy 1.31.0 fails this strict flow:** it translates the Extended CONNECT request +to HTTP/1.1 but omits `Sec-WebSocket-Key`. IXWebSocket correctly returns HTTP 400 +with `Missing Sec-WebSocket-Key value`. This reproduces +[Envoy issue #8547](https://github.com/envoyproxy/envoy/issues/8547); the upstream +[fix proposal #46959](https://github.com/envoyproxy/envoy/pull/46959) was still +unmerged when this test was added. The Envoy mode deliberately reports failure +on affected versions. Neither the test client nor IXWebSocket works around the +proxy defect by supplying a legacy key or weakening backend validation. + +Use the flags `--envoy /path/to/envoy`, `--nghttpx /path/to/nghttpx`, or +`--openssl /path/to/openssl` through `H2_PROXY_ARGS` to select local binaries. + +## CI + +The `h2-proxy` workflow runs on master pushes and manual dispatch. Add the +`h2-proxy` label to opt a PR into the check. It uses the Docker target and uploads +reports and logs even on failure. It does not add time to the unit-test executable. diff --git a/makefile.dev b/makefile.dev index 034ff77a..0832b323 100644 --- a/makefile.dev +++ b/makefile.dev @@ -279,3 +279,16 @@ test_openssl_no_deprecated: cmake -S . -B build -GNinja -UOPENSSL_CRYPTO_LIBRARY -UOPENSSL_SSL_LIBRARY -UOPENSSL_INCLUDE_DIR -DCMAKE_BUILD_TYPE=Debug -DCMAKE_UNITY_BUILD=ON -DUSE_TLS=ON -DUSE_OPEN_SSL=ON -DUSE_LIBRE_SSL=OFF -DUSE_MBED_TLS=OFF -DUSE_NETWORK_FRAMEWORK=OFF -DUSE_SECURE_TRANSPORT=OFF -DUSE_ZLIB=ON -DUSE_TEST=ON -DUSE_WS=ON -DCMAKE_CXX_STANDARD_REQUIRED=ON -DCMAKE_CXX_FLAGS="-DOPENSSL_NO_DEPRECATED -DOPENSSL_API_COMPAT=$(OPENSSL_API_COMPAT) -Werror=deprecated-declarations" cmake --build build --parallel 2 ctest --test-dir build --output-on-failure + +# Standalone external integration test; does not extend the unit suite. +H2_PROXY_ARGS ?= +.PHONY: test_h2_proxy test_h2_proxy_native +test_h2_proxy: + python3 tools/run_h2_proxy.py $(H2_PROXY_ARGS) + +test_h2_proxy_native: + cmake -S test/h2_proxy -B build/h2-proxy -DCMAKE_UNITY_BUILD=ON + cmake --build build/h2-proxy --target h2_proxy_server --parallel + python3 -m venv build/h2-proxy/venv + build/h2-proxy/venv/bin/python -m pip install --disable-pip-version-check -r test/h2_proxy/requirements.txt + build/h2-proxy/venv/bin/python test/h2_proxy/run.py $(H2_PROXY_ARGS) diff --git a/test/h2_proxy/CMakeLists.txt b/test/h2_proxy/CMakeLists.txt new file mode 100644 index 00000000..cf44e228 --- /dev/null +++ b/test/h2_proxy/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.14) +project(ixwebsocket_h2_proxy_test LANGUAGES C CXX) +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# This fixture is an HTTP/1.1 backend. Envoy terminates downstream TLS/H2. +set(USE_TLS OFF CACHE BOOL "" FORCE) +set(USE_NETWORK_FRAMEWORK OFF CACHE BOOL "" FORCE) +set(USE_ZLIB ON CACHE BOOL "" FORCE) +set(USE_TEST OFF CACHE BOOL "" FORCE) +set(USE_WS OFF CACHE BOOL "" FORCE) +set(IXWEBSOCKET_INSTALL OFF CACHE BOOL "" FORCE) +add_subdirectory(../.. ixwebsocket) +add_executable(h2_proxy_server server.cpp) +target_link_libraries(h2_proxy_server PRIVATE ixwebsocket::ixwebsocket) diff --git a/test/h2_proxy/client.py b/test/h2_proxy/client.py new file mode 100644 index 00000000..25af6ac6 --- /dev/null +++ b/test/h2_proxy/client.py @@ -0,0 +1,173 @@ +"""A real RFC 8441 client: TLS/ALPN, H2 Extended CONNECT, then WebSocket frames.""" +from collections import deque +import socket +import ssl +import time + +from h2.config import H2Configuration +from h2.connection import H2Connection +from h2.events import (ConnectionTerminated, DataReceived, ResponseReceived, + StreamEnded, StreamReset) +from h2.settings import SettingCodes +from wsproto import Connection, ConnectionType +from wsproto.events import BytesMessage, CloseConnection, TextMessage +from wsproto.extensions import PerMessageDeflate + + +class Client: + def __init__(self, port, certificate, timeout=5): + context = ssl.create_default_context(cafile=str(certificate)) + context.set_alpn_protocols(["h2"]) + self.socket = context.wrap_socket( + socket.create_connection(("127.0.0.1", port), timeout=timeout), + server_hostname="localhost") + if self.socket.selected_alpn_protocol() != "h2": + self.socket.close() + raise RuntimeError("Proxy did not negotiate h2 through ALPN") + self.timeout = timeout + self.h2 = H2Connection(config=H2Configuration(header_encoding="utf-8")) + self.streams = {} + self.flow_control_waits = 0 + self.h2.initiate_connection() + self.flush() + self.wait(lambda: self.h2.remote_settings[SettingCodes.ENABLE_CONNECT_PROTOCOL] == 1) + + def flush(self): + data = self.h2.data_to_send() + if data: + self.socket.sendall(data) + + def pump(self, deadline): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("Timed out waiting for HTTP/2 or WebSocket progress") + self.socket.settimeout(remaining) + data = self.socket.recv(65536) + if not data: + raise RuntimeError("HTTP/2 connection closed unexpectedly") + for event in self.h2.receive_data(data): + if isinstance(event, ConnectionTerminated): + raise RuntimeError("Unexpected HTTP/2 GOAWAY: " + str(event)) + if isinstance(event, ResponseReceived): + state = self.streams[event.stream_id] + headers = dict(event.headers) + if headers.get(":status") != "200": + raise RuntimeError("Extended CONNECT failed: " + repr(headers)) + extensions = [] + if state["compression"]: + value = headers.get("sec-websocket-extensions", "") + if not value.startswith("permessage-deflate"): + raise RuntimeError("Compression was not negotiated: " + repr(headers)) + state["extension"].finalize(value) + extensions.append(state["extension"]) + elif "sec-websocket-extensions" in headers: + raise RuntimeError("Unexpected compression negotiation") + state["ws"] = Connection(ConnectionType.CLIENT, extensions=extensions) + elif isinstance(event, DataReceived): + state = self.streams[event.stream_id] + if state["ws"] is None: + raise RuntimeError("Data before successful Extended CONNECT") + # Empty DATA (including END_STREAM) carries no WebSocket bytes. + if event.data: + state["ws"].receive_data(event.data) + frames = list(state["ws"].events()) + if any(isinstance(frame, CloseConnection) for frame in frames): + state["close_received"] = True + state["events"].extend(frames) + self.h2.acknowledge_received_data(event.flow_controlled_length, event.stream_id) + elif isinstance(event, StreamEnded): + self.streams[event.stream_id]["ended"] = True + elif isinstance(event, StreamReset): + state = self.streams[event.stream_id] + # nghttpx may retire a completed WebSocket with NO_ERROR after + # forwarding both Close frames. Never accept a premature reset. + if event.error_code or not (state["close_sent"] and state["close_received"]): + raise RuntimeError("Unexpected HTTP/2 RST_STREAM: " + str(event)) + state["ended"] = state["reset"] = True + self.flush() + + def wait(self, predicate): + deadline = time.monotonic() + self.timeout + while not predicate(): + self.pump(deadline) + + def open(self, path, compression=False): + stream = self.h2.get_next_available_stream_id() + extension = PerMessageDeflate(client_no_context_takeover=True, + server_no_context_takeover=True) + self.streams[stream] = dict(ws=None, events=deque(), ended=False, + compression=compression, extension=extension, + close_sent=False, close_received=False, reset=False) + headers = [(":method", "CONNECT"), (":protocol", "websocket"), + (":scheme", "https"), (":authority", "localhost"), (":path", path), + ("sec-websocket-version", "13"), ("origin", "https://client.example"), + ("x-proxy-test", "h2-integration")] + # RFC 8441 replaces the HTTP/1.1 Sec-WebSocket-Key/Accept exchange. + if compression: + headers.append(("sec-websocket-extensions", "permessage-deflate; " + extension.offer())) + self.h2.send_headers(stream, headers, end_stream=False) + self.flush() + self.wait(lambda: self.streams[stream]["ws"] is not None) + return stream + + def send(self, stream, event): + if isinstance(event, CloseConnection): + self.streams[stream]["close_sent"] = True + data = self.streams[stream]["ws"].send(event) + offset = 0 + deadline = time.monotonic() + self.timeout + while offset < len(data): + count = min(self.h2.local_flow_control_window(stream), + self.h2.max_outbound_frame_size, len(data) - offset) + if not count: + self.flow_control_waits += 1 + self.pump(deadline) + continue + self.h2.send_data(stream, data[offset:offset + count]) + offset += count + self.flush() + + def event(self, stream): + state = self.streams[stream] + self.wait(lambda: bool(state["events"]) or state["ended"]) + if not state["events"]: + raise RuntimeError("Stream ended without the expected WebSocket event") + return state["events"].popleft() + + def message(self, stream, expected): + cls = TextMessage if isinstance(expected, str) else BytesMessage + value = "" if isinstance(expected, str) else b"" + while True: + event = self.event(stream) + if not isinstance(event, cls): + raise RuntimeError("Unexpected WebSocket event: " + repr(event)) + value += event.data + if event.message_finished: + if value != expected: + raise RuntimeError("Echoed message differs from the original") + return + + def close_stream(self, stream, server_initiated=False): + if server_initiated: + self.send(stream, TextMessage(data="close-from-server")) + else: + self.send(stream, CloseConnection(code=1000, reason="client close test")) + event = self.event(stream) + code = 4000 if server_initiated else 1000 + reason = "server close test" if server_initiated else "client close test" + if not isinstance(event, CloseConnection) or event.code != code or event.reason != reason: + raise RuntimeError("Unexpected close response: " + repr(event)) + if server_initiated: + self.send(stream, event.response()) + if not self.streams[stream]["reset"]: + self.h2.end_stream(stream) + self.flush() + self.wait(lambda: self.streams[stream]["ended"]) + + def reset_stream(self, stream): + self.h2.reset_stream(stream) + self.streams[stream]["ended"] = True + self.flush() + + def close(self): + self.socket.close() diff --git a/test/h2_proxy/envoy.yaml b/test/h2_proxy/envoy.yaml new file mode 100644 index 00000000..53e02c00 --- /dev/null +++ b/test/h2_proxy/envoy.yaml @@ -0,0 +1,65 @@ +static_resources: + listeners: + - name: websocket_h2 + address: + socket_address: {address: 127.0.0.1, port_value: 0} + filter_chains: + - transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext + common_tls_context: + alpn_protocols: [h2] + tls_certificates: + - certificate_chain: {filename: @CERT@} + private_key: {filename: @KEY@} + filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + stat_prefix: websocket_h2 + codec_type: HTTP2 + http2_protocol_options: {allow_connect: true} + stream_idle_timeout: 15s + upgrade_configs: + - upgrade_type: websocket + route_config: + name: websocket_backend + virtual_hosts: + - name: backend + domains: ["*"] + routes: + - match: {prefix: /} + route: {cluster: ixwebsocket, timeout: 0s} + http_filters: + - name: envoy.filters.http.router + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router + access_log: + - name: envoy.access_loggers.file + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog + path: @ACCESS_LOG@ + log_format: + text_format_source: + inline_string: "%PROTOCOL% %RESPONSE_CODE% %REQ(:PATH)%\n" + clusters: + - name: ixwebsocket + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: ixwebsocket + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: @BACKEND_PORT@} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + explicit_http_config: + http_protocol_options: {} +admin: + access_log_path: @ADMIN_LOG@ + address: + socket_address: {address: 127.0.0.1, port_value: 0} diff --git a/test/h2_proxy/requirements.txt b/test/h2_proxy/requirements.txt new file mode 100644 index 00000000..24acb978 --- /dev/null +++ b/test/h2_proxy/requirements.txt @@ -0,0 +1,5 @@ +h2==4.3.0 +hpack==4.1.0 +hyperframe==6.1.0 +wsproto==1.3.2 +h11==0.16.0 diff --git a/test/h2_proxy/run.py b/test/h2_proxy/run.py new file mode 100644 index 00000000..62a6c16e --- /dev/null +++ b/test/h2_proxy/run.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Exercise TLS/H2 Extended CONNECT -> reverse proxy -> HTTP/1.1 IXWebSocket.""" +import argparse +import json +from pathlib import Path +import random +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import time +import traceback +import urllib.request + +from wsproto.events import BytesMessage, Ping, Pong, TextMessage +from client import Client + +ROOT = Path(__file__).resolve().parents[2] + + +def wait_for(read, processes, timeout=10): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + for process in processes: + if process.poll() is not None: + raise RuntimeError("Test process exited with status " + str(process.returncode)) + try: + result = read() + if result: + return result + except (OSError, ValueError): + pass + time.sleep(0.05) + raise TimeoutError("Test services did not become ready") + + +def start_envoy(args, output, certificate, key, port, processes, logs): + config = (ROOT / "test/h2_proxy/envoy.yaml").read_text() + for token, value in {"CERT": str(certificate), "KEY": str(key), + "ACCESS_LOG": str(output / "access.log"), + "ADMIN_LOG": str(output / "admin.log"), "BACKEND_PORT": port}.items(): + config = config.replace("@" + token + "@", json.dumps(value)) + config_file = output / "envoy.yaml" + config_file.write_text(config) + admin_file = output / "admin-address" + log = (output / "envoy.log").open("w") + logs.append(log) + proxy = subprocess.Popen([args.envoy, "-c", str(config_file), "--disable-hot-restart", + "--concurrency", "1", "--admin-address-path", str(admin_file)], + stdout=log, stderr=subprocess.STDOUT) + processes.append(proxy) + + def proxy_port(): + address = admin_file.read_text().strip() + with urllib.request.urlopen("http://" + address + "/listeners?format=json", timeout=1) as response: + listeners = json.load(response) + return listeners["listener_statuses"][0]["local_address"]["socket_address"]["port_value"] + return wait_for(proxy_port, processes) + + +def start_nghttpx(args, output, certificate, key, backend_port, processes, logs): + # In Docker this loopback namespace contains only the test services. + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + log = (output / "nghttpx.log").open("w") + logs.append(log) + process = subprocess.Popen( + [args.nghttpx, "--frontend=127.0.0.1," + str(port), + "--backend=127.0.0.1," + str(backend_port), "--workers=1", + "--accesslog-file=" + str(output / "access.log"), + "--errorlog-file=/dev/stderr", str(key), str(certificate)], + stdout=log, stderr=subprocess.STDOUT) + processes.append(process) + return port + + +def run(args): + output = ROOT / "build/h2-proxy/runs" + output.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix="run-", dir=output)) + print("Logs and report: " + str(output), flush=True) + processes, logs = [], [] + report = {"passed": [], "alpn": None, "proxy": args.proxy} + started = time.monotonic() + client = None + try: + version = subprocess.run([getattr(args, args.proxy), "--version"], check=True, + capture_output=True, text=True, timeout=5) + report["proxy_version"] = (version.stdout + version.stderr).strip() + backend_log = output / "backend.log" + log = backend_log.open("w") + logs.append(log) + backend = subprocess.Popen([str(args.server)], stdin=subprocess.PIPE, + stdout=log, stderr=subprocess.STDOUT, text=True) + processes.append(backend) + + def backend_port(): + for line in backend_log.read_text().splitlines(): + if line.startswith("READY "): + return int(line.split()[1]) + port = wait_for(backend_port, processes) + certificate, key = output / "cert.pem", output / "key.pem" + config = output / "openssl.cnf" + config.write_text("""[req] + distinguished_name = dn + x509_extensions = extensions + prompt = no + [dn] + CN = localhost + [extensions] + subjectAltName = DNS:localhost,IP:127.0.0.1 + basicConstraints = critical,CA:TRUE + keyUsage = critical,digitalSignature,keyEncipherment,keyCertSign + subjectKeyIdentifier = hash + authorityKeyIdentifier = keyid:always + """) + with (output / "certificate.log").open("w") as log: + subprocess.run([args.openssl, "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-days", "1", "-config", str(config), "-keyout", str(key), + "-out", str(certificate)], check=True, stdout=log, + stderr=subprocess.STDOUT, timeout=15) + if args.proxy == "envoy": + port = start_envoy(args, output, certificate, key, port, processes, logs) + else: + port = start_nghttpx(args, output, certificate, key, port, processes, logs) + client = wait_for(lambda: Client(port, certificate), processes) + report["alpn"] = "h2" + report["downstream_connections"] = 1 + + def passed(name): + print("PASS " + name, flush=True) + report["passed"].append(name) + + for compression in (False, True): + stream = client.open("/echo?compression=" + str(compression).lower(), compression) + passed("Extended CONNECT returns 200; compression=" + str(compression)) + for payload in ("", "Bonjour — 中文 👋", b"", b"\x00\xff\x80binary"): + client.send(stream, TextMessage(data=payload) if isinstance(payload, str) + else BytesMessage(data=payload)) + client.message(stream, payload) + passed("empty, Unicode and binary messages; compression=" + str(compression)) + client.send(stream, TextMessage(data="fragment ", message_finished=False)) + client.send(stream, TextMessage(data="é", message_finished=True)) + client.message(stream, "fragment é") + client.send(stream, Ping(payload=b"proxy-ping")) + event = client.event(stream) + if not isinstance(event, Pong) or event.payload != b"proxy-ping": + raise RuntimeError("Ping/pong payload was not preserved") + payload = random.Random(0).randbytes(256 * 1024) + client.send(stream, BytesMessage(data=payload)) + client.message(stream, payload) + passed("fragmentation, ping/pong and 256 KiB flow control; compression=" + str(compression)) + client.close_stream(stream) + passed("client close code/reason and H2 stream retirement; compression=" + str(compression)) + + streams = [client.open("/multiplex/" + str(i)) for i in range(3)] + for i, stream in enumerate(streams): + client.send(stream, TextMessage(data="stream-" + str(i))) + for i, stream in enumerate(streams): + client.message(stream, "stream-" + str(i)) + client.close_stream(streams[0]) + client.send(streams[1], TextMessage(data="survives-close")) + client.message(streams[1], "survives-close") + client.reset_stream(streams[2]) + client.send(streams[1], TextMessage(data="survives-reset")) + client.message(streams[1], "survives-reset") + client.close_stream(streams[1], server_initiated=True) + passed("multiplexing, isolated close/reset and server close code/reason") + stream = client.open("/after-close") + client.send(stream, TextMessage(data="still connected")) + client.message(stream, "still connected") + client.close_stream(stream) + passed("new WebSocket after earlier streams close on the same H2 connection") + report["outbound_flow_control_waits"] = client.flow_control_waits + if not client.flow_control_waits: + raise RuntimeError("Test did not exercise HTTP/2 send flow control") + transcript = backend_log.read_text() + for path in ("/echo?compression=false", "/echo?compression=true", + "/multiplex/0", "/multiplex/1", "/multiplex/2", "/after-close"): + if "OPEN " + path + "\n" not in transcript: + raise RuntimeError("Backend did not receive the original path: " + path) + passed("HTTP/1.1 backend receives original paths, queries and headers") + report["success"] = True + except Exception as error: + report["success"] = False + report["error"] = str(error) + print("FAIL " + str(error), file=sys.stderr) + with (output / "client.log").open("w") as log: + traceback.print_exc(file=log) + finally: + if client: + client.close() + for process in reversed(processes): + if process.poll() is None: + if process is backend: + # EOF asks the fixture to stop and join its workers. + try: + process.stdin.close() + except OSError: + pass + else: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + for log in logs: + log.close() + if processes: + report["backend_exit_code"] = processes[0].returncode + if processes[0].returncode != 0: + report["success"] = False + report.setdefault("error", "Backend did not stop cleanly") + report["elapsed_seconds"] = round(time.monotonic() - started, 3) + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + return 0 if report.get("success") else 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--server", type=Path, default=ROOT / "build/h2-proxy/h2_proxy_server") + parser.add_argument("--proxy", choices=("nghttpx", "envoy"), default="nghttpx") + parser.add_argument("--nghttpx", default="nghttpx") + parser.add_argument("--envoy", default="envoy") + parser.add_argument("--openssl", default="openssl") + args = parser.parse_args() + if not shutil.which(getattr(args, args.proxy)): + parser.error(args.proxy + " is required; see docs/h2-proxy.md") + signal.signal(signal.SIGTERM, lambda *_: sys.exit(130)) + return run(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/test/h2_proxy/server.cpp b/test/h2_proxy/server.cpp new file mode 100644 index 00000000..f79be7d4 --- /dev/null +++ b/test/h2_proxy/server.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2026 Machine Zone, Inc. All rights reserved. + */ +#include +#include +#include +#include +#include + +int main() +{ + ix::initNetSystem(); + { + std::mutex logMutex; + ix::WebSocketServer server(0, "127.0.0.1"); + server.setOnClientMessageCallback( + [&](std::shared_ptr, + ix::WebSocket& socket, + const ix::WebSocketMessagePtr& message) + { + if (message->type == ix::WebSocketMessageType::Open) + { + const auto& headers = message->openInfo.headers; + const auto marker = headers.find("X-Proxy-Test"); + const auto origin = headers.find("Origin"); + if (marker == headers.end() || marker->second != "h2-integration" || + origin == headers.end() || origin->second != "https://client.example") + { + socket.close(4003, "Proxy headers missing"); + } + std::lock_guard lock(logMutex); + std::cout << "OPEN " << message->openInfo.uri << std::endl; + } + else if (message->type == ix::WebSocketMessageType::Message) + { + if (!message->binary && message->str == "close-from-server") + { + socket.close(4000, "server close test"); + } + else + { + socket.send(message->str, message->binary); + } + } + else if (message->type == ix::WebSocketMessageType::Close) + { + std::lock_guard lock(logMutex); + std::cout << "CLOSE " << message->closeInfo.code << std::endl; + } + }); + const auto listening = server.listen(); + if (!listening.first) + { + std::cerr << listening.second << std::endl; + return 1; + } + server.start(); + std::cout << "READY " << server.getPort() << std::endl; + std::string command; + std::getline(std::cin, command); + server.stop(); + } + ix::uninitNetSystem(); +} diff --git a/tools/run_h2_proxy.py b/tools/run_h2_proxy.py new file mode 100644 index 00000000..1decffc2 --- /dev/null +++ b/tools/run_h2_proxy.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Build and run the isolated HTTP/2 WebSocket reverse-proxy integration test.""" +import os +from pathlib import Path +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + output = ROOT / "build/h2-proxy" + runs = output / "runs" + runs.mkdir(parents=True, exist_ok=True) + image_id = output / ("image-" + uuid.uuid4().hex) + try: + print("Building current IXWebSocket source and H2 proxy test image...", flush=True) + with (output / "build.log").open("w") as log: + subprocess.run(["docker", "build", "--file", str(ROOT / "docker/Dockerfile.h2-proxy"), + "--iidfile", str(image_id), str(ROOT)], check=True, + stdout=log, stderr=subprocess.STDOUT) + command = ["docker", "run", "--rm", "--init", "--network", "none", + "--user", "{}:{}".format(os.getuid(), os.getgid()), + "--env", "PYTHONUNBUFFERED=1", "--volume", + str(runs) + ":/app/build/h2-proxy/runs", + image_id.read_text().strip()] + sys.argv[1:] + return subprocess.run(command).returncode + except (OSError, subprocess.CalledProcessError) as error: + print("H2 proxy test failed: {}. Build log: {}".format(error, output / "build.log"), + file=sys.stderr) + return 1 + except KeyboardInterrupt: + return 130 + finally: + image_id.unlink(missing_ok=True) + print("Reports and service logs: " + str(runs), flush=True) + + +if __name__ == "__main__": + raise SystemExit(main())