Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .github/workflows/h2-proxy.yml
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions docker/Dockerfile.h2-proxy
Original file line number Diff line number Diff line change
@@ -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"]
11 changes: 11 additions & 0 deletions docker/Dockerfile.h2-proxy.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
**
!CMakeLists.txt
!ixwebsocket-config.cmake.in
!ixwebsocket.pc.in
!CMake/
!CMake/**
!ixwebsocket/
!ixwebsocket/**
!test/
!test/h2_proxy/
!test/h2_proxy/**
5 changes: 5 additions & 0 deletions docs/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
89 changes: 89 additions & 0 deletions docs/h2-proxy.md
Original file line number Diff line number Diff line change
@@ -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.
13 changes: 13 additions & 0 deletions makefile.dev
Original file line number Diff line number Diff line change
Expand Up @@ -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)
16 changes: 16 additions & 0 deletions test/h2_proxy/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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)
173 changes: 173 additions & 0 deletions test/h2_proxy/client.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading