From 40e5f3d2e311dfbdd3fa710822e7a34a34208f01 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:22:11 -0300 Subject: [PATCH 1/3] beast: bound what a WebSocket client's handshake reads A client's handshake reads the server's HTTP response with Beast's default parser limits, 8 KiB of header and 8 MiB of a refused upgrade's body, outside the caller's allocator. Natively that is Boost.Beast's own code and on Wasm the shipped copy, neither of which this library corrects, so the plain stream keeps those limits. websocket::bounded_handshake_stream is a next layer between the WebSocket stream and its transport. It parses the response's header with Beast's own parser under websocket::response_limits (8 KiB of header, 1 KiB after a refusal's header by default) and fails the handshake with http::error::header_limit or body_limit after reading at most both bounds; a 101 passes through unchanged. It starts its transport's operations through function pointers, so that misc-no-recursion sees no cycle through it in a consumer's lint. The WASI facade now passes an allocator-tagged construction on to an allocator-using next layer, as Boost does natively. handshake_test.cpp refuses upgrades with declared, streamed and chunked megabyte bodies and answers one with a long header, against local stand-ins, on native, WASIp2 and WASIp3; the TLS protocol test repeats the refusal and an echo whose shutdown passes through the layer. --- AGENTS.md | 5 + doc/beast.adoc | 54 ++ doc/changelog.adoc | 1 + include/webcpp/beast/websocket.hpp | 16 + .../websocket/bounded_handshake_stream.hpp | 536 ++++++++++++++ test/Jamfile | 3 + test/handshake_test.cpp | 679 ++++++++++++++++++ test/tls/protocol.cpp | 197 +++++ 8 files changed, 1491 insertions(+) create mode 100644 include/webcpp/beast/websocket/bounded_handshake_stream.hpp create mode 100644 test/handshake_test.cpp diff --git a/AGENTS.md b/AGENTS.md index aab0ec3..2b25dae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,6 +29,11 @@ Read the superproject's [AGENTS.md](../../AGENTS.md) and every file hash before lint exempts that corpus's upstream style and notices. Change generated application adaptations through their generator, never by editing its outputs. Both the adapted sources and their generator are linted. +- `websocket/bounded_handshake_stream.hpp` bounds a client's handshake response + as a next layer, without correcting upstream: native Boost.Beast and the shipped + engine keep upstream's 8 MiB. It parses with Beast's own `basic_parser` and starts + its transport's operations through function pointers, so that misc-no-recursion + sees no cycle through it in a consumer's lint; keep both when changing it. - TLS shutdown cancellation tests synchronize on the peer's observed close_notify. Cancelling a lowest layer between two internal socket operations is not proof that a pending shutdown read was cancelled. WebSocket close already tears down diff --git a/doc/beast.adoc b/doc/beast.adoc index 07b0435..751f3d5 100644 --- a/doc/beast.adoc +++ b/doc/beast.adoc @@ -182,6 +182,52 @@ do not change the compiler configuration or remove upstream Boost overloads; use `exception-handling=off` for a complete build without exception handling. Prefer upstream error-code overloads when recovery is required. +[#beast-bounded-handshake] +=== Bound a client's handshake response + +A WebSocket client's handshake reads the server's HTTP response with Beast's parser +and its default limits: 8 KiB of header and, for a response that refuses the upgrade, +8 MiB of body, in memory no allocator of the program's reaches. Natively that is +Boost.Beast's own code; on WASI it is the shipped copy of it. A client that connects +to servers it does not trust places `websocket::bounded_handshake_stream` between the +WebSocket stream and its transport, from +``, and sets its +`response_limits`: + +[source] +---- +include::{library-root}/test/handshake_test.cpp[tag=bounded-handshake,indent=0] +---- + +The limits default to Beast's 8 KiB of header and 1 KiB after the header of a refusal. +The handshake is the stream's own, unchanged: + +[source] +---- +include::{library-root}/test/handshake_test.cpp[tag=bounded-handshake-call,indent=0] +---- + +A header longer than its bound fails the handshake with `http::error::header_limit`. +A refusal that declares a longer body fails it with `http::error::body_limit` as soon +as its header is read, before the handshake reserves that body; one that sends more +bytes after its header than the bound fails it with the same error. In all, the layer +reads at most the two bounds of a response. A refusal within them fails with +`websocket::error::upgrade_declined`, its status and body in the response, as upstream +does. A 101 response passes through: every later read and write is the transport's. + +Over TLS the TLS stream is one layer further down, `ws.next_layer().next_layer()`, for +its settings and its handshake; teardown after a close is the transport's own. Natively +and on WASI, a WebSocket stream constructed with `std::allocator_arg` and an allocator +passes them on to the layer, which keeps there the rare header line that two reads split. + +The plain WebSocket stream keeps upstream's limits: natively it is Boost.Beast's own +type, and the shipped Wasm engine applies no protocol correction. Bounding is a choice +of the client, and the layer is meant for a client: a server's accept reads a request, +which the layer refuses as a malformed response. On Emscripten the browser's WebSocket +reads its own handshake response and exposes none of it to the page. The layer compiles +there for the guest engine of `` over a supplied +channel; its runtime tests run natively and on WASIp2/P3 only. + [#beast-explanation] == Explanation: separate messages from transport @@ -246,6 +292,7 @@ API or transport detail of the original program is available. |Explicit supplied-stream counterpart |Borrowed descriptors |CLI input/output; asynchronous WebSocket via pollables |CLI input/output |Caller-supplied channel |Raw TCP HTTP/WebSocket listener |Available |Available with network grants |Available |Unavailable |Host HTTP WebSocket upgrade |Not applicable |Not provided by host adapter |Use guest socket backend |Browser WebSocket client only +|Bounded client handshake response |Bounded next layer |Bounded next layer |Bounded next layer |Browser-owned; compiled for a supplied channel |Native CPU-parallel threads |Available |Unavailable |Cooperative WASI threads only |Not implied by this backend |=== @@ -290,6 +337,13 @@ include::application-matrix.adoc[] * `socket_test.cpp` exchanges real HTTP and binary WebSocket payloads, completes both sides of a close handshake, and verifies a stalled peer reaches the stream timeout. Each case has a five-second outer deadline. +* `handshake_test.cpp` answers a client's upgrade with refusals of a megabyte, declared, + streamed and chunked, and with long 101 headers: the bounded layer fails each with + Beast's limit error after reading at most its bounds, synchronously too, and a + refusal's handshake allocates under 64 KiB. A refusal within the bounds and a 101 + read seven bytes at a time, through the layer's allocator, complete as upstream's do. + `test/tls/protocol.cpp` repeats the refusal and an echo whose TLS shutdown passes + through the layer. * `ssl_test.cpp` checks SNI copying and rejection without replacing an existing valid name. It does not claim that an SNI setting authenticates the peer. * `config_test.cpp` checks compiler/global/library exception configuration, both diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 7139b11..6717b47 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,6 +16,7 @@ Changes to the unreleased Beast facade. // tag::unreleased[] * Fixed browser HTTP and WebSocket transfers with shared Wasm memory. * Added current application coverage and shared Release parser measurements. +* Added a WebSocket client layer that bounds the handshake response it reads. // end::unreleased[] [#beast-changelog-0-1-0] diff --git a/include/webcpp/beast/websocket.hpp b/include/webcpp/beast/websocket.hpp index 6ba9da9..f3384c9 100644 --- a/include/webcpp/beast/websocket.hpp +++ b/include/webcpp/beast/websocket.hpp @@ -106,9 +106,25 @@ class stream : public ::webcpp::beast_backend::websocket::stream + requires(!std::uses_allocator_v) explicit stream([[maybe_unused]] std::allocator_arg_t tag, [[maybe_unused]] const Allocator& allocator, Args&&... args) : base(std::forward(args)...) {} + + /** + Constructs an allocator-using underlying stream with the allocator, as upstream does natively. + + @tparam Allocator The allocator type, which the underlying stream's `allocator_type` takes. + @tparam Args The underlying stream's other constructor argument types. + @param tag Passed on to the underlying stream with the allocator. + @param allocator The underlying stream's allocator, such as a bounded handshake's. + @param args The underlying stream's other constructor arguments. + @note Upstream stream-state allocation is unchanged, as with the other allocator constructor. + */ + template + requires std::uses_allocator_v + explicit stream(std::allocator_arg_t tag, const Allocator& allocator, Args&&... args) + : base(tag, allocator, std::forward(args)...) {} }; #endif // WEBCPP_TARGET_NATIVE } // namespace webcpp::beast::websocket diff --git a/include/webcpp/beast/websocket/bounded_handshake_stream.hpp b/include/webcpp/beast/websocket/bounded_handshake_stream.hpp new file mode 100644 index 0000000..6853aca --- /dev/null +++ b/include/webcpp/beast/websocket/bounded_handshake_stream.hpp @@ -0,0 +1,536 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_BEAST_WEBSOCKET_BOUNDED_HANDSHAKE_STREAM_HPP +#define WEBCPP_BEAST_WEBSOCKET_BOUNDED_HANDSHAKE_STREAM_HPP + +#include + +#include WEBCPP_ASIO_BACKEND_HEADER(async_result.hpp) // lint-world: completion tokens only +#include WEBCPP_ASIO_BACKEND_HEADER(buffer.hpp) // lint-world: memory buffers only +#include WEBCPP_BEAST_BACKEND_HEADER(core/async_base.hpp) // lint-world: completion handlers only +#include WEBCPP_BEAST_BACKEND_HEADER(core/buffers_prefix.hpp) // lint-world: memory buffers only +#include WEBCPP_BEAST_BACKEND_HEADER(core/flat_buffer.hpp) // lint-world: memory buffers only +#include WEBCPP_BEAST_BACKEND_HEADER(core/role.hpp) // lint-world: teardown role only +#include WEBCPP_BEAST_BACKEND_HEADER(http/basic_parser.hpp) // lint-world: parses bytes only +#include WEBCPP_BEAST_BACKEND_HEADER(http/error.hpp) // lint-world: error codes only +#include WEBCPP_BEAST_BACKEND_HEADER(websocket/teardown.hpp) // lint-world: forwards teardown +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::beast::detail { +/** Reads a handshake response's status line and fields with Beast's parser, keeping its status. */ +class handshake_response_parser final : public ::webcpp::beast_backend::http::basic_parser { + using error_code = boost::system::error_code; + using string_view = ::webcpp::beast_backend::string_view; + + int status_ = 0; + +protected: + void on_request_impl(::webcpp::beast_backend::http::verb /*method*/, + string_view /*method_string*/, string_view /*target*/, int /*version*/, + error_code& /*ec*/) override {} + + void on_response_impl(int code, string_view /*reason*/, int /*version*/, + error_code& /*ec*/) override { + status_ = code; + } + + void on_field_impl(::webcpp::beast_backend::http::field /*name*/, string_view /*name_string*/, + string_view /*value*/, error_code& /*ec*/) override {} + + void on_trailer_field_impl(::webcpp::beast_backend::http::field /*name*/, + string_view /*name_string*/, string_view /*value*/, + error_code& /*ec*/) override {} + + void on_header_impl(error_code& /*ec*/) override {} + + void on_body_init_impl(const boost::optional& /*content_length*/, + error_code& /*ec*/) override {} + + std::size_t on_body_impl(string_view body, error_code& /*ec*/) override { return body.size(); } + + void on_chunk_header_impl(std::uint64_t /*size*/, string_view /*extensions*/, + error_code& /*ec*/) override {} + + std::size_t on_chunk_body_impl(std::uint64_t /*remain*/, string_view body, + error_code& /*ec*/) override { + return body.size(); + } + + void on_finish_impl(error_code& /*ec*/) override {} + +public: + /** The status code of the status line, or 0 before it is read. + @return The status code. */ + [[nodiscard]] int status() const noexcept { return status_; } +}; + +/** The first `size` bytes of `buffers`, as a plain buffer when the sequence is one buffer. + @tparam MutableBufferSequence The buffer sequence type. + @param size The most bytes to keep. + @param buffers The buffers to take them from. + @return A buffer sequence of at most `size` bytes. */ +template +auto read_prefix(std::size_t size, const MutableBufferSequence& buffers) { + if constexpr (std::is_convertible_v) { + // Beast's TCP stream takes a prefix of what it is given, which it cannot do of its own + // single-buffer prefix: a plain buffer keeps that layer working. + return ::webcpp::asio_backend::buffer(::webcpp::asio_backend::mutable_buffer(buffers), + size); + } else { + return ::webcpp::beast_backend::buffers_prefix(size, buffers); + } +} +} // namespace webcpp::beast::detail + +// NOLINTNEXTLINE(modernize-concat-nested-namespaces): Emscripten adds the policy's inline namespace +namespace webcpp::beast { +#ifdef WEBCPP_TARGET_EMSCRIPTEN +// The page's facade declares its WebSocket names in the unsupported-setting policy's namespace. +#ifdef WEBCPP_BEAST_UNSUPPORTED_IGNORE +inline namespace unsupported_ignore { +#else +inline namespace unsupported_error { +#endif +#endif +namespace websocket { + +/** + Bounds on the HTTP response that a client's WebSocket handshake reads. + + A response that accepts the upgrade, status 101, ends with its header. A response that refuses it + may carry a body, which the handshake reads into its response, as upstream does, up to `body` + bytes. +*/ +struct response_limits { + /** + The most bytes of the status line and fields, line ends included, defaulting to 8 KiB. + + It is Beast's own limit on a response header, which the handshake's parser also keeps, so a + larger value reads no more. + */ + std::uint32_t header = 8 * 1024; + /** + The most bytes read after the header of a response that refuses the upgrade, defaulting to + 1 KiB. + + They are counted as they arrive, chunk framing included; a declared `Content-Length` above it + fails as soon as the header is read. Zero discards every refusal's body. + */ + std::uint64_t body = 1024; +}; + +/** + A client's next layer that bounds the HTTP response its WebSocket handshake reads. + + Upstream's handshake reads the server's response with a parser of Beast's default limits, 8 KiB of + header and 8 MiB of body, whatever the status, in memory no allocator of the caller's reaches. A + hostile server can thus answer each connection with a refusal of 8 MiB. Placed between the + WebSocket stream and its transport, this layer reads the response's header through Beast's own + parser with `response_limits::header` and `response_limits::body` as its limits, and hands the + handshake no more than these bounds allow. + + A header longer than the bound fails the read with `http::error::header_limit`, after at most + `response_limits::header` bytes. A refusal that declares a longer body fails it with + `http::error::body_limit` once its header is read, before the handshake reserves anything for it, + and one that sends more than `response_limits::body` bytes after its header fails it with the + same error, once they have arrived or when the handshake asks for them. A response of status 101 + ends the layer's work: every later read and write is the next layer's, unchanged. + + In all, the layer reads at most `header + body` bytes of a response before its error. The + handshake then fails with that error, as upstream's fails when its own parser's limits are + exceeded, its response left as upstream leaves it then. Beast's types and algorithms are + unchanged: natively the WebSocket stream above is Boost.Beast's own, on WASI the shipped copy of + it. On Emscripten the page's WebSocket reads its own response; there the layer serves only the + guest engine of `` over a supplied channel. + + @code + using transport = beast::ssl_stream; + websocket::stream> ws(executor, tls); + ws.next_layer().limits({.body = 0}); // a refusal's body is never read + // The TLS handshake is one layer further down, then the WebSocket handshake as before. + ws.next_layer().next_layer().async_handshake(ssl::stream_base::client, on_tls); + ws.async_handshake(host, target, on_upgrade); + @endcode + + @tparam NextLayer The transport, an AsyncStream or SyncStream such as `tcp_stream` or + `ssl_stream`, which the layer constructs from its arguments. + @tparam Allocator The allocator that keeps the unparsed part of a header line split between two + reads; a line read whole needs no memory. + @note For a client's handshake only: a server's accept reads a request, which fails this layer's + response parser. A WebSocket stream constructed with `std::allocator_arg` and an allocator passes + them on to this layer, natively as upstream does and on WASI because the layer declares + `allocator_type`. + @see response_limits +*/ +template > +class bounded_handshake_stream { + enum class phase : std::uint8_t { header, body, open, failed }; + + NextLayer next_; + response_limits limits_; + ::webcpp::beast::detail::handshake_response_parser parser_; + ::webcpp::beast_backend::basic_flat_buffer pending_; + std::uint64_t allowance_ = 0; + phase phase_ = phase::header; + boost::system::error_code error_; + + // The bytes the next read may take; zero, with the error that ends the handshake, past them. + std::size_t allowance(boost::system::error_code& ec) { + if (phase_ == phase::failed) { + ec = error_; + return 0; + } + if (allowance_ == 0) { + ec = fail(phase_ == phase::header ? ::webcpp::beast_backend::http::error::header_limit + : ::webcpp::beast_backend::http::error::body_limit); + return 0; + } + return static_cast( + std::min(allowance_, std::numeric_limits::max())); + } + + boost::system::error_code fail(boost::system::error_code ec) { + error_ = ec; + phase_ = phase::failed; + pending_.clear(); + pending_.shrink_to_fit(); + return ec; + } + + // Accounts for `transferred` bytes just read into `buffers`; an error withholds them. + template + boost::system::error_code on_read(const MutableBufferSequence& buffers, + std::size_t transferred) { + allowance_ -= transferred; + if (phase_ != phase::header || transferred == 0) { + return {}; + } + namespace net = ::webcpp::asio_backend; + boost::system::error_code ec; + std::size_t after_header = 0; + const net::mutable_buffer first = *net::buffer_sequence_begin(buffers); + if (pending_.size() == 0 && first.size() >= transferred) { + // Parsed where it was read; only a line that the read split is kept. + const net::const_buffer read(first.data(), transferred); + const auto used = parser_.put(read, ec); + after_header = transferred - used; + if (ec == ::webcpp::beast_backend::http::error::need_more) { + pending_.commit(net::buffer_copy(pending_.prepare(after_header), read + used)); + } + } else { + pending_.commit(net::buffer_copy(pending_.prepare(transferred), buffers, transferred)); + pending_.consume(parser_.put(pending_.data(), ec)); + after_header = pending_.size(); + } + if (ec == ::webcpp::beast_backend::http::error::need_more) { + return {}; + } + if (ec) { + return fail(ec); + } + pending_.clear(); + pending_.shrink_to_fit(); + if (parser_.status() == 101) { + phase_ = phase::open; + return {}; + } + if (after_header > limits_.body) { + return fail(::webcpp::beast_backend::http::error::body_limit); + } + phase_ = phase::body; + allowance_ = limits_.body - after_header; + return {}; + } + + // Beast's composed operations start the layer's next operation from the completion of the + // last: a loop of asynchronous operations, each started once the call that started the last has + // returned. The layer starts its transport's operations through a pointer, so that the analysis + // of calls (misc-no-recursion) sees no cycle through it, here or in a program that uses it, + // where its reports would land in Beast's own headers. + template + static auto transport_read(NextLayer& next, const MutableBufferSequence& buffers, + ReadToken&& token) { + return next.async_read_some(buffers, std::forward(token)); + } + + template + static auto transport_write(NextLayer& next, const ConstBufferSequence& buffers, + WriteToken&& token) { + return next.async_write_some(buffers, std::forward(token)); + } + + template + static void transport_teardown(::webcpp::beast_backend::role_type role, NextLayer& next, + TeardownHandler&& handler) { + using ::webcpp::beast_backend::websocket::async_teardown; + async_teardown(role, next, std::forward(handler)); + } + + // A read of the response, within its bounds. + template + class read_op : public ::webcpp::beast_backend::async_base { + bounded_handshake_stream& stream_; + MutableBufferSequence buffers_; + + public: + template + read_op(Handler&& handler, bounded_handshake_stream& stream, + const MutableBufferSequence& buffers) + : ::webcpp::beast_backend::async_base( + std::forward(handler), stream.get_executor()), + stream_(stream), + buffers_(buffers) {} + + // Starts the transport's read, or completes at once, as if posted, past the bounds. + static void start(read_op op) { + boost::system::error_code ec; + const auto allowed = op.stream_.allowance(ec); + if (ec) { + op.complete(false, ec, std::size_t{0}); + return; + } + const auto prefix = ::webcpp::beast::detail::read_prefix(allowed, op.buffers_); + auto* const read = &transport_read; + read(op.stream_.next_, prefix, std::move(op)); + } + + void operator()(boost::system::error_code ec, std::size_t transferred) { + if (const auto limit = stream_.on_read(buffers_, transferred)) { + ec = limit; + transferred = 0; + } + this->complete_now(ec, transferred); + } + }; + + struct run_read_op { + bounded_handshake_stream* self; + + template + void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers) const { + if (self->phase_ == phase::open) { + auto* const read = &transport_read; + read(self->next_, buffers, std::forward(handler)); + return; + } + using op = read_op>; + auto* const start = &op::start; + start(op(std::forward(handler), *self, buffers)); + } + }; + +public: + /** The transport below this layer. */ + using next_layer_type = NextLayer; + /** The allocator of a split header line, which makes the layer allocator-aware. */ + using allocator_type = Allocator; + /** The transport's executor. */ + using executor_type = NextLayer::executor_type; + + /** + Constructs the transport from the arguments, with the default limits. + @tparam First The first argument's type. + @tparam Rest The other arguments' types. + @param first The first argument of the transport's constructor. + @param rest The other arguments of the transport's constructor. + */ + template + requires(!std::is_same_v, std::allocator_arg_t> && + !std::is_same_v, bounded_handshake_stream>) + explicit bounded_handshake_stream(First&& first, Rest&&... rest) + : next_(std::forward(first), std::forward(rest)...) { + limits(limits_); + } + + /** + Constructs the transport from the arguments, keeping a split header line in `allocator`. + @tparam Args The transport's constructor argument types. + @param tag Selects this constructor. + @param allocator The allocator of a header line split between two reads. + @param args The arguments of the transport's constructor. + */ + template + explicit bounded_handshake_stream([[maybe_unused]] std::allocator_arg_t tag, + const Allocator& allocator, Args&&... args) + : next_(std::forward(args)...), pending_(allocator) { + limits(limits_); + } + + /** The transport's executor. + @return The executor. */ + executor_type get_executor() noexcept { return next_.get_executor(); } + + /** The transport below this layer. + @return A reference to it. */ + next_layer_type& next_layer() noexcept { return next_; } + + /** The transport below this layer. + @return A reference to it. */ + [[nodiscard]] const next_layer_type& next_layer() const noexcept { return next_; } + + /** The bounds the handshake reads within. + @return The bounds. */ + [[nodiscard]] response_limits limits() const noexcept { return limits_; } + + /** + Sets the bounds the handshake reads within. + @param value The bounds. + @pre No byte of the response has been read: set them before the handshake. + */ + void limits(response_limits value) { + limits_ = value; + allowance_ = value.header; + parser_.header_limit(value.header); + parser_.body_limit(value.body); + } + + /** + Reads some bytes, within the bounds until a 101 response's header is read. + @tparam MutableBufferSequence The buffer sequence type. + @param buffers The buffers to read into. + @param ec Set to the transport's error, or to the limit the response exceeded. + @return The number of bytes read, 0 on a limit error. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers, boost::system::error_code& ec) { + if (phase_ == phase::open) { + return next_.read_some(buffers, ec); + } + const auto allowed = allowance(ec); + if (ec) { + return 0; + } + const auto transferred = + next_.read_some(::webcpp::beast::detail::read_prefix(allowed, buffers), ec); + if (const auto limit = on_read(buffers, transferred)) { + ec = limit; + return 0; + } + return transferred; + } + + /** + Reads some bytes, within the bounds until a 101 response's header is read. + @tparam MutableBufferSequence The buffer sequence type. + @param buffers The buffers to read into. + @return The number of bytes read. + @throws boost::system::system_error On the transport's error or an exceeded limit, raised + through `boost::throw_exception`, as Beast's SyncReadStream requires of this overload. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers) { + boost::system::error_code ec; + const auto transferred = read_some(buffers, ec); + if (ec) { + boost::throw_exception(boost::system::system_error(ec)); + } + return transferred; + } + + /** + Writes some bytes to the transport, unchanged. + @tparam ConstBufferSequence The buffer sequence type. + @param buffers The bytes to write. + @param ec Set to the transport's error. + @return The number of bytes written. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers, boost::system::error_code& ec) { + return next_.write_some(buffers, ec); + } + + /** + Writes some bytes to the transport, unchanged. + @tparam ConstBufferSequence The buffer sequence type. + @param buffers The bytes to write. + @return The number of bytes written. + @throws boost::system::system_error On the transport's error, as the transport raises it. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers) { + return next_.write_some(buffers); + } + + /** + Starts reading some bytes, within the bounds until a 101 response's header is read. + + Once that header is read, it is the transport's own read, its handler passed through. + @tparam MutableBufferSequence The buffer sequence type. + @tparam ReadToken The completion token for `void(error_code, std::size_t)`. + @param buffers The buffers to read into, which must outlive the operation. + @param token The completion token; on an exceeded limit, its error with 0 bytes. + @return What the completion token makes of the operation. + */ + template > + auto async_read_some(const MutableBufferSequence& buffers, ReadToken&& token = ReadToken()) { + return ::webcpp::asio_backend::async_initiate( + run_read_op{this}, token, buffers); + } + + /** + Starts writing some bytes to the transport, unchanged. + @tparam ConstBufferSequence The buffer sequence type. + @tparam WriteToken The completion token for `void(error_code, std::size_t)`. + @param buffers The bytes to write, which must outlive the operation. + @param token The completion token. + @return What the completion token makes of the operation. + */ + template > + auto async_write_some(const ConstBufferSequence& buffers, WriteToken&& token = WriteToken()) { + auto* const write = &transport_write; + return write(next_, buffers, std::forward(token)); + } + + /** + Tears the transport down after a WebSocket close, as its own teardown does. + @param role The local endpoint's role. + @param stream The layer whose transport is torn down. + @param ec Set to the transport's error. + */ + friend void teardown(::webcpp::beast_backend::role_type role, bounded_handshake_stream& stream, + boost::system::error_code& ec) { + using ::webcpp::beast_backend::websocket::teardown; + teardown(role, stream.next_, ec); + } + + /** + Starts tearing the transport down after a WebSocket close, as its own teardown does. + @tparam TeardownHandler The handler for `void(error_code)`. + @param role The local endpoint's role. + @param stream The layer whose transport is torn down. + @param handler Invoked when the transport's teardown completes. + */ + template + friend void async_teardown(::webcpp::beast_backend::role_type role, + bounded_handshake_stream& stream, TeardownHandler&& handler) { + auto* const teardown = &transport_teardown; + teardown(role, stream.next_, std::forward(handler)); + } +}; + +} // namespace websocket +#ifdef WEBCPP_TARGET_EMSCRIPTEN +} +#endif +} // namespace webcpp::beast + +#endif diff --git a/test/Jamfile b/test/Jamfile index fa819c3..39cc2a3 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -27,8 +27,11 @@ webcpp.compile-fail conflicting_policies : config_test.cpp webcpp.run message : message_test.cpp ; webcpp.headers-alone beast : ../include : beast/tcp_stream.hpp beast/websocket.hpp beast/http/read.hpp beast/http/write.hpp + beast/websocket/bounded_handshake_stream.hpp : /webcpp/beast//sockets : native wasip2 wasip3 emscripten ; webcpp.run socket : socket_test.cpp : /webcpp/beast//sockets : native wasip2 wasip3 ; +webcpp.run handshake : handshake_test.cpp : /webcpp/beast//sockets + : native wasip2 wasip3 ; # One header unit supplies the combined dependencies for aggregate analysis. # A browser parse must never acquire guest OpenSSL through that combination. diff --git a/test/handshake_test.cpp b/test/handshake_test.cpp new file mode 100644 index 0000000..349128a --- /dev/null +++ b/test/handshake_test.cpp @@ -0,0 +1,679 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A client's WebSocket handshake over the bounded next layer, against local stand-ins that refuse +// the upgrade with a large body or answer it with a long header. A counting layer below it records +// the bytes the client reads from TCP, and the global allocation functions count what the +// handshake allocates, so each case sees how much a hostile server could make it read and hold. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace beast = webcpp::beast; +namespace http = beast::http; +namespace websocket = beast::websocket; +using tcp = webcpp::asio::ip::tcp; +using boost::system::error_code; +using namespace std::chrono_literals; + +namespace { +// Global replacement operators can reach only process-wide test counters. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +bool measuring = false; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t allocated = 0; + +void* allocate(std::size_t size, std::size_t alignment) { + if (measuring) { + allocated += size; + } + alignment = std::max(alignment, alignof(std::max_align_t)); + auto* pointer = std::aligned_alloc( + alignment, ((std::max(size, std::size_t{1}) + alignment - 1) / alignment) * alignment); + if (pointer == nullptr) { + boost::throw_exception(std::bad_alloc()); + } + return pointer; +} +} // namespace + +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name): standard replacement signatures +void* operator new(std::size_t size) { + return allocate(size, alignof(std::max_align_t)); +} + +void* operator new[](std::size_t size) { + return allocate(size, alignof(std::max_align_t)); +} + +void* operator new(std::size_t size, std::align_val_t alignment) { + return allocate(size, static_cast(alignment)); +} + +void* operator new[](std::size_t size, std::align_val_t alignment) { + return allocate(size, static_cast(alignment)); +} + +void operator delete(void* pointer) noexcept { + std::free(pointer); +} + +void operator delete[](void* pointer) noexcept { + std::free(pointer); +} + +void operator delete(void* pointer, std::size_t /*unused*/) noexcept { + std::free(pointer); +} + +void operator delete[](void* pointer, std::size_t /*unused*/) noexcept { + std::free(pointer); +} + +void operator delete(void* pointer, std::align_val_t /*unused*/) noexcept { + std::free(pointer); +} + +void operator delete[](void* pointer, std::align_val_t /*unused*/) noexcept { + std::free(pointer); +} + +void operator delete(void* pointer, std::size_t /*unused*/, std::align_val_t /*unused*/) noexcept { + std::free(pointer); +} + +void operator delete[](void* pointer, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + std::free(pointer); +} + +// NOLINTEND(readability-inconsistent-declaration-parameter-name) + +namespace { + +constexpr std::size_t mebibyte = std::size_t{1024} * 1024; +// Far below the megabyte a refusal sends, far above what a bounded handshake allocates. +constexpr std::size_t allocation_ceiling = std::size_t{64} * 1024; + +/** The first `size` bytes of `buffers`, as a plain buffer when the sequence is one buffer. */ +template +auto prefix(std::size_t size, const Buffers& buffers) { + if constexpr (std::is_convertible_v) { + // Beast cannot take a prefix of its own single-buffer prefix, as its TCP stream does. + return webcpp::asio::buffer(webcpp::asio::mutable_buffer(buffers), size); + } else { + return beast::buffers_prefix(size, buffers); + } +} + +/** + A TCP stream that counts the bytes read from it and reads at most `chunk` bytes at a time, so that + a header's lines can be made to span reads. +*/ +class counted_stream { + beast::tcp_stream next_; + std::size_t* read_; + std::size_t chunk_; + +public: + using executor_type = beast::tcp_stream::executor_type; + + counted_stream(webcpp::asio::io_context& context, std::size_t& read, + std::size_t chunk = std::numeric_limits::max()) + : next_(context), read_(&read), chunk_(chunk) {} + + executor_type get_executor() noexcept { return next_.get_executor(); } + + beast::tcp_stream& next_layer() noexcept { return next_; } + + [[nodiscard]] const beast::tcp_stream& next_layer() const noexcept { return next_; } + + template + std::size_t read_some(const Buffers& buffers, error_code& ec) { + const auto transferred = next_.read_some(prefix(chunk_, buffers), ec); + *read_ += transferred; + return transferred; + } + + template + std::size_t write_some(const Buffers& buffers, error_code& ec) { + return next_.write_some(buffers, ec); + } + + template + auto async_read_some(const Buffers& buffers, Token&& token) { + return webcpp::asio::async_initiate( + [this](auto handler, const Buffers& target) { + next_.async_read_some(prefix(chunk_, target), + [read = read_, handler = std::move(handler)]( + error_code ec, std::size_t transferred) mutable { + *read += transferred; + std::move(handler)(ec, transferred); + }); + }, + token, buffers); + } + + template + auto async_write_some(const Buffers& buffers, Token&& token) { + return next_.async_write_some(buffers, std::forward(token)); + } + + template + friend void async_teardown(beast::role_type role, counted_stream& stream, Handler&& handler) { + using webcpp::beast_backend::websocket::async_teardown; + async_teardown(role, stream.next_, std::forward(handler)); + } +}; + +using bounded_layer = websocket::bounded_handshake_stream; +using client_stream = websocket::stream; + +/** What a client's handshake did: its result, the response, and what it read and allocated. */ +struct handshake_result { + error_code error; + std::size_t read = 0; + std::size_t allocated = 0; + websocket::response_type response; +}; + +/** Starts measuring what the handshake allocates. */ +void start_measuring() { + measuring = true; + allocated = 0; +} + +/** Stops measuring, and returns what the handshake allocated. */ +std::size_t stop_measuring() { + measuring = false; + return allocated; +} + +/** + A handshake against a stand-in that reads the upgrade request, answers `answer` and then ends + its output, as a server that refuses the upgrade does. +*/ +class answer_exchange { + webcpp::asio::io_context context_; + tcp::acceptor listener_{context_, {webcpp::asio::ip::address_v4::loopback(), 0}}; + tcp::socket peer_{context_}; + const std::string& answer_; + handshake_result& result_; + client_stream client_; + beast::flat_buffer input_; + http::request request_; + webcpp::asio::steady_timer deadline_{context_, 5s}; + + void expired(error_code ec) { + if (!ec) { + BOOST_ERROR("Refused handshake exceeded its deadline"); + beast::get_lowest_layer(client_).close(); + BOOST_TEST(!peer_.close(ec)); + } + } + + void accepted(error_code ec) { + if (!BOOST_TEST(!ec)) { + return; + } + http::async_read(peer_, input_, request_, + beast::bind_front_handler(&answer_exchange::received, this)); + } + + void received(error_code ec, [[maybe_unused]] std::size_t transferred) { + if (!BOOST_TEST(!ec)) { + return; + } + // The write ends when the client has read it all, or when the client closes. + webcpp::asio::async_write(peer_, webcpp::asio::buffer(answer_), + beast::bind_front_handler(&answer_exchange::answered, this)); + } + + void answered(error_code ec, [[maybe_unused]] std::size_t transferred) { + if (!ec) { + // The end of the output ends a body that runs to it. + BOOST_TEST(!peer_.shutdown(tcp::socket::shutdown_send, ec)); + } + } + + void connected(error_code ec) { + if (!BOOST_TEST(!ec)) { + return; + } + start_measuring(); + client_.async_handshake(result_.response, "localhost", "/relay", + beast::bind_front_handler(&answer_exchange::handshaken, this)); + } + + void handshaken(error_code ec) { + result_.allocated = stop_measuring(); + result_.error = ec; + beast::get_lowest_layer(client_).close(); + deadline_.cancel(); + } + +public: + answer_exchange(const std::string& answer, websocket::response_limits limits, std::size_t chunk, + handshake_result& result) + : answer_(answer), result_(result), client_(context_, result.read, chunk) { + client_.next_layer().limits(limits); + } + + void run() { + deadline_.async_wait(beast::bind_front_handler(&answer_exchange::expired, this)); + listener_.async_accept(peer_, beast::bind_front_handler(&answer_exchange::accepted, this)); + beast::get_lowest_layer(client_).async_connect( + listener_.local_endpoint(), + beast::bind_front_handler(&answer_exchange::connected, this)); + context_.run(); // lint-run: drive the refused handshake against its local stand-in + } +}; + +/** Runs a handshake against a stand-in that answers `answer`, then ends its output. */ +handshake_result against_answer(const std::string& answer, websocket::response_limits limits, + std::size_t chunk = std::numeric_limits::max()) { + handshake_result result; + answer_exchange exchange(answer, limits, chunk, result); + exchange.run(); + return result; +} + +/** + A handshake against a Beast server whose 101 response carries a field of `filler` bytes, then, + when the handshake succeeds, a binary echo and the closing handshake. +*/ +template +class upgrade_exchange { + webcpp::asio::io_context& context_; + Client& client_; + handshake_result& result_; + tcp::acceptor listener_{context_, {webcpp::asio::ip::address_v4::loopback(), 0}}; + websocket::stream server_{context_}; + beast::flat_buffer server_data_; + beast::flat_buffer client_data_; + const std::string payload{"binary\0message", 14}; + bool echoed_ = false; + webcpp::asio::steady_timer deadline_{context_, 5s}; + + void expired(error_code ec) { + if (!ec) { + BOOST_ERROR("Upgrade exceeded its deadline"); + beast::get_lowest_layer(client_).close(); + beast::get_lowest_layer(server_).close(); + } + } + + void accepted(error_code ec) { + if (!BOOST_TEST(!ec)) { + return; + } + server_.async_accept(beast::bind_front_handler(&upgrade_exchange::upgraded, this)); + } + + void upgraded(error_code ec) { + if (ec) { + return; // the client gave up on a response it bounded + } + server_.async_read(server_data_, beast::bind_front_handler(&upgrade_exchange::echo, this)); + } + + void echo(error_code ec, [[maybe_unused]] std::size_t transferred) { + if (ec) { + return; // the client's close, or the connection it dropped + } + server_.binary(true); + server_.async_write(server_data_.data(), + beast::bind_front_handler(&upgrade_exchange::echoed, this)); + } + + void echoed(error_code ec, [[maybe_unused]] std::size_t transferred) { + BOOST_TEST(!ec); + server_data_.consume(server_data_.size()); + server_.async_read(server_data_, [](error_code, std::size_t) {}); + } + + void connected(error_code ec) { + if (!BOOST_TEST(!ec)) { + return; + } + start_measuring(); + client_.async_handshake(result_.response, "localhost", "/relay", + beast::bind_front_handler(&upgrade_exchange::handshaken, this)); + } + + void handshaken(error_code ec) { + result_.allocated = stop_measuring(); + result_.error = ec; + if (ec) { + beast::get_lowest_layer(client_).close(); + deadline_.cancel(); + return; + } + client_.binary(true); + client_.async_write(webcpp::asio::buffer(payload), + beast::bind_front_handler(&upgrade_exchange::written, this)); + } + + void written(error_code ec, [[maybe_unused]] std::size_t transferred) { + if (!BOOST_TEST(!ec)) { + return; + } + client_.async_read(client_data_, beast::bind_front_handler(&upgrade_exchange::read, this)); + } + + void read(error_code ec, [[maybe_unused]] std::size_t transferred) { + BOOST_TEST(!ec); + echoed_ = beast::buffers_to_string(client_data_.data()) == payload; + client_.async_close(websocket::close_code::normal, + beast::bind_front_handler(&upgrade_exchange::closed, this)); + } + + void closed(error_code ec) { + BOOST_TEST(!ec); + deadline_.cancel(); + } + +public: + upgrade_exchange(webcpp::asio::io_context& context, Client& client, std::size_t filler, + handshake_result& result) + : context_(context), client_(client), result_(result) { + server_.set_option( + websocket::stream_base::decorator([filler](websocket::response_type& response) { + if (filler != 0) { + response.set("X-Filler", std::string(filler, 'f')); + } + })); + } + + void run() { + deadline_.async_wait(beast::bind_front_handler(&upgrade_exchange::expired, this)); + listener_.async_accept(beast::get_lowest_layer(server_).socket(), + beast::bind_front_handler(&upgrade_exchange::accepted, this)); + beast::get_lowest_layer(client_).async_connect( + listener_.local_endpoint(), + beast::bind_front_handler(&upgrade_exchange::connected, this)); + context_.run(); // lint-run: drive the upgrade, the echo and the closing handshake + if (!result_.error) { + BOOST_TEST(echoed_); + } + } +}; + +/** Runs a handshake against a Beast server whose 101 carries a field of `filler` bytes. */ +template +handshake_result against_server(Client& client, webcpp::asio::io_context& context, + std::size_t filler) { + handshake_result result; + upgrade_exchange exchange(context, client, filler, result); + exchange.run(); + return result; +} + +// A refusal that declares a megabyte fails at its header, before the body is read or reserved. +void test_declared_body() { + const auto answer = "HTTP/1.1 403 Forbidden\r\nContent-Length: " + std::to_string(mebibyte) + + "\r\n\r\n" + std::string(mebibyte, 'x'); + const websocket::response_limits limits; + const auto result = against_answer(answer, limits); + BOOST_TEST(result.error == http::error::body_limit); + BOOST_TEST_LE(result.read, std::size_t{limits.header}); + BOOST_TEST_LT(result.allocated, allocation_ceiling); +} + +// A refusal whose body runs to the end of the stream stops after the bound. +void test_streamed_body() { + const auto answer = + "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\n\r\n" + std::string(mebibyte, 'x'); + const websocket::response_limits limits; + const auto result = against_answer(answer, limits); + BOOST_TEST(result.error == http::error::body_limit); + BOOST_TEST_LE(result.read, std::size_t{limits.header} + limits.body); + BOOST_TEST_LT(result.allocated, allocation_ceiling); +} + +// A chunked refusal is bounded by its bytes on the wire, its chunk framing included. +void test_chunked_body() { + std::string answer = "HTTP/1.1 403 Forbidden\r\nTransfer-Encoding: chunked\r\n\r\n"; + for (int i = 0; i < 1024; ++i) { + answer += "400\r\n" + std::string(1024, 'x') + "\r\n"; + } + answer += "0\r\n\r\n"; + const websocket::response_limits limits; + const auto result = against_answer(answer, limits); + BOOST_TEST(result.error == http::error::body_limit); + BOOST_TEST_LE(result.read, std::size_t{limits.header} + limits.body); + BOOST_TEST_LT(result.allocated, allocation_ceiling); +} + +// A refusal within the bound is read whole, as upstream reads it, a few bytes at a time here. +void test_short_refusal() { + const std::string answer = + "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: 9\r\n\r\nForbidden"; + const websocket::response_limits limits; + const auto result = against_answer(answer, limits, 7); + BOOST_TEST(result.error == websocket::error::upgrade_declined); + BOOST_TEST(result.response.result() == http::status::forbidden); + BOOST_TEST_EQ(result.response.body(), "Forbidden"); + BOOST_TEST_EQ(result.read, answer.size()); +} + +// A body bound of zero still reads a refusal without a body, and fails one with a body unread. +void test_discarded_body() { + const std::string answer = "HTTP/1.1 429 Too Many Requests\r\nContent-Length: 0\r\n\r\n"; + const auto result = against_answer(answer, {.body = 0}); + BOOST_TEST(result.error == websocket::error::upgrade_declined); + BOOST_TEST(result.response.result() == http::status::too_many_requests); + + const auto refused = + against_answer("HTTP/1.1 403 Forbidden\r\nContent-Length: 9\r\n\r\nForbidden", {.body = 0}); + BOOST_TEST(refused.error == http::error::body_limit); +} + +// A 101 whose header is longer than the default bound fails after reading at most that bound. +// The server shares the process and builds that header, so only the client's reads are measured. +void test_long_header() { + webcpp::asio::io_context context; + std::size_t read = 0; + client_stream client(context, read); + const auto result = against_server(client, context, std::size_t{32} * 1024); + BOOST_TEST(result.error == http::error::header_limit); + BOOST_TEST_LE(read, std::size_t{websocket::response_limits{}.header}); +} + +// A header bound below a valid 101's header fails the upgrade that the default bound accepts. +void test_header_bound() { + { + webcpp::asio::io_context context; + std::size_t read = 0; + client_stream client(context, read); + client.next_layer().limits({.header = 1024}); + const auto result = against_server(client, context, 4096); + BOOST_TEST(result.error == http::error::header_limit); + BOOST_TEST_LE(read, std::size_t{1024}); + } + { + webcpp::asio::io_context context; + std::size_t read = 0; + client_stream client(context, read); + const auto result = against_server(client, context, 4096); + BOOST_TEST(!result.error); + BOOST_TEST(result.response.result() == http::status::switching_protocols); + } +} + +/** Counts what a resource allocates and still holds. */ +class counting_resource : public std::pmr::memory_resource { +public: + std::size_t allocations = 0; + std::size_t outstanding = 0; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++allocations; + outstanding += bytes; + return std::pmr::new_delete_resource()->allocate(bytes, alignment); + } + + void do_deallocate(void* pointer, std::size_t bytes, std::size_t alignment) override { + outstanding -= bytes; + std::pmr::new_delete_resource()->deallocate(pointer, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } +}; + +// A successful upgrade passes through, its header lines spanning reads of a few bytes, which the +// layer keeps in the allocator it is given, and releases once the header is read. +void test_upgrade() { + using pmr_layer = + websocket::bounded_handshake_stream>; + counting_resource resource; + webcpp::asio::io_context context; + std::size_t read = 0; + websocket::stream client(std::allocator_arg, + std::pmr::polymorphic_allocator(&resource), context, + read, std::size_t{7}); + const auto result = against_server(client, context, 0); + BOOST_TEST(!result.error); + BOOST_TEST(result.response.result() == http::status::switching_protocols); + BOOST_TEST_GT(resource.allocations, std::size_t{0}); + BOOST_TEST_EQ(resource.outstanding, std::size_t{0}); +} + +// The synchronous handshake reads through the same bound. +void test_synchronous() { + webcpp::asio::io_context context; + tcp::acceptor listener(context, {webcpp::asio::ip::address_v4::loopback(), 0}); + std::size_t read = 0; + client_stream client(context, read); + error_code ec; + if (!BOOST_TEST( + !beast::get_lowest_layer(client).socket().connect(listener.local_endpoint(), ec))) { + return; + } + tcp::socket peer(context); + if (!BOOST_TEST(!listener.accept(peer, ec))) { + return; + } + // Answered before the request is read, so that one thread can play both parts. + const std::string answer = + "HTTP/1.1 403 Forbidden\r\nContent-Length: " + std::to_string(mebibyte) + "\r\n\r\nxxxx"; + webcpp::asio::write(peer, webcpp::asio::buffer(answer), ec); + if (!BOOST_TEST(!ec)) { + return; + } + // A client that read past the header would otherwise wait for the rest of the body forever. + BOOST_TEST(!peer.shutdown(tcp::socket::shutdown_send, ec)); + websocket::response_type response; + client.handshake(response, "localhost", "/relay", ec); + BOOST_TEST(ec == http::error::body_limit); + BOOST_TEST_LE(read, std::size_t{websocket::response_limits{}.header}); +} + +// The page's example: a client that reads no byte of a refusal's body. +void test_documented() { + webcpp::asio::io_context context; + tcp::acceptor listener(context, {webcpp::asio::ip::address_v4::loopback(), 0}); + tcp::socket peer(context); + const std::string answer = "HTTP/1.1 403 Forbidden\r\nContent-Length: 9\r\n\r\nForbidden"; + beast::flat_buffer input; + http::request request; + bool refused = false; + listener.async_accept(peer, [&](error_code ec) { + if (!BOOST_TEST(!ec)) { + return; + } + http::async_read(peer, input, request, [&](error_code read_error, std::size_t) { + if (!read_error) { + webcpp::asio::async_write(peer, webcpp::asio::buffer(answer), + [](error_code, std::size_t) {}); + } + }); + }); + // tag::bounded-handshake[] + // Beast's WebSocket stream over the bounded layer, over its transport: TCP here. + websocket::stream> ws(context); + // At most 4 KiB of response header, and no byte of a refusal's body. + ws.next_layer().limits({.header = 4 * 1024, .body = 0}); + // end::bounded-handshake[] + webcpp::asio::steady_timer deadline(context, 5s); + deadline.async_wait([&](error_code ec) { + if (!ec) { + BOOST_ERROR("Documented handshake exceeded its deadline"); + beast::get_lowest_layer(ws).close(); + BOOST_TEST(!peer.close(ec)); + } + }); + beast::get_lowest_layer(ws).async_connect(listener.local_endpoint(), [&](error_code ec) { + if (!BOOST_TEST(!ec)) { + return; + } + // tag::bounded-handshake-call[] + ws.async_handshake("localhost", "/relay", [&](error_code handshake_error) { + // The server refused with a body: the handshake fails before reading it. + refused = handshake_error == http::error::body_limit; + beast::get_lowest_layer(ws).close(); + deadline.cancel(); + }); + // end::bounded-handshake-call[] + }); + context.run(); // lint-run: drive the documented handshake against its local stand-in + BOOST_TEST(refused); +} + +void test_defaults() { + constexpr websocket::response_limits limits; + static_assert(limits.header == 8 * 1024); + static_assert(limits.body == 1024); + static_assert(beast::is_async_stream::value); + static_assert(beast::is_sync_stream::value); + static_assert(std::is_same_v, beast::tcp_stream>); +} + +} // namespace + +int main() { + test_defaults(); + test_declared_body(); + test_streamed_body(); + test_chunked_body(); + test_short_refusal(); + test_discarded_body(); + test_long_header(); + test_header_bound(); + test_upgrade(); + test_synchronous(); + test_documented(); + return boost::report_errors(); +} diff --git a/test/tls/protocol.cpp b/test/tls/protocol.cpp index 76667a3..9669175 100644 --- a/test/tls/protocol.cpp +++ b/test/tls/protocol.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -406,6 +407,196 @@ class exchange { BOOST_TEST(finished_); } }; + +// A WebSocket client over TLS through the bounded handshake layer, as a relay client is: a refused +// upgrade with a megabyte body fails at the bound, and an accepted one echoes and closes, its TLS +// shut down through the layer. +class bounded_exchange { + using client_stream = + ws::stream>>; + + bool refuse_; + webcpp::asio::io_context context_; + ssl::context server_context_; + ssl::context client_context_; + tcp::acceptor listener_{context_, {webcpp::asio::ip::address_v4::loopback(), 0}}; + ws::stream> server_; + client_stream client_; + webcpp::asio::steady_timer deadline_{context_, 5s}; + beast::flat_buffer server_buffer_; + beast::flat_buffer client_buffer_; + http::request request_; + const std::string refusal = + "HTTP/1.1 403 Forbidden\r\n\r\n" + std::string(std::size_t{1024} * 1024, 'x'); + const std::string payload{"bounded\0payload", 15}; + int closed_ = 0; + bool finished_ = false; + + void finish() { + if (finished_) { + return; + } + finished_ = true; + deadline_.cancel(); + close_checked(listener_); + close_checked(beast::get_lowest_layer(client_).socket()); + close_checked(beast::get_lowest_layer(server_).socket()); + } + + void expired(error_code ec) { + if (!ec) { + BOOST_ERROR("Bounded Beast TLS exchange exceeded its deadline"); + finish(); + } + } + + void accepted(error_code ec) { + if (finished_ || !BOOST_TEST(!ec)) { + return; + } + server_.next_layer().async_handshake( + ssl::stream_base::server, + beast::bind_front_handler(&bounded_exchange::server_ready, this)); + } + + void server_ready(error_code ec) { + if (finished_ || !BOOST_TEST(!ec)) { + return; + } + if (refuse_) { + http::async_read(server_.next_layer(), server_buffer_, request_, + beast::bind_front_handler(&bounded_exchange::refuse, this)); + return; + } + server_.async_accept(beast::bind_front_handler(&bounded_exchange::upgraded, this)); + } + + void refuse(error_code ec, [[maybe_unused]] std::size_t bytes) { + if (finished_ || !BOOST_TEST(!ec)) { + return; + } + // Ends when the client has dropped the connection. + webcpp::asio::async_write(server_.next_layer(), webcpp::asio::buffer(refusal), + [](error_code, std::size_t) {}); + } + + void upgraded(error_code ec) { + if (!BOOST_TEST(!ec)) { + finish(); + return; + } + server_.async_read(server_buffer_, + beast::bind_front_handler(&bounded_exchange::echo, this)); + } + + void echo(error_code ec, [[maybe_unused]] std::size_t bytes) { + if (!BOOST_TEST(!ec)) { + finish(); + return; + } + server_.binary(true); + server_.async_write(server_buffer_.data(), + beast::bind_front_handler(&bounded_exchange::echoed, this)); + } + + void echoed(error_code ec, [[maybe_unused]] std::size_t bytes) { + BOOST_TEST(!ec); + server_buffer_.consume(server_buffer_.size()); + server_.async_read(server_buffer_, [this](error_code close_error, std::size_t) { + BOOST_TEST(close_error == ws::error::closed); + closed(server_.next_layer()); + }); + } + + void connected(error_code ec) { + if (!BOOST_TEST(!ec)) { + finish(); + return; + } + client_.next_layer().next_layer().async_handshake( + ssl::stream_base::client, + beast::bind_front_handler(&bounded_exchange::client_ready, this)); + } + + void client_ready(error_code ec) { + if (!BOOST_TEST(!ec)) { + finish(); + return; + } + client_.async_handshake("localhost", "/echo", + beast::bind_front_handler(&bounded_exchange::handshaken, this)); + } + + void handshaken(error_code ec) { + if (refuse_) { + BOOST_TEST(ec == http::error::body_limit); + finish(); + return; + } + if (!BOOST_TEST(!ec)) { + finish(); + return; + } + client_.binary(true); + client_.async_write(webcpp::asio::buffer(payload), + beast::bind_front_handler(&bounded_exchange::sent, this)); + } + + void sent(error_code ec, [[maybe_unused]] std::size_t bytes) { + if (!BOOST_TEST(!ec)) { + finish(); + return; + } + client_.async_read(client_buffer_, + beast::bind_front_handler(&bounded_exchange::received, this)); + } + + void received(error_code ec, [[maybe_unused]] std::size_t bytes) { + BOOST_TEST(!ec); + BOOST_TEST_EQ(beast::buffers_to_string(client_buffer_.data()), payload); + client_.async_close(ws::close_code::normal, [this](error_code close_error) { + BOOST_TEST(!close_error); + closed(client_.next_layer().next_layer()); + }); + } + + void closed(beast::ssl_stream& tls) { + // The WebSocket teardown shut TLS down and closed the transport, through the layer too. + const auto state = static_cast(SSL_get_shutdown(tls.native_handle())); + BOOST_TEST_NE(state & SSL_SENT_SHUTDOWN, 0); + BOOST_TEST_NE(state & SSL_RECEIVED_SHUTDOWN, 0); + BOOST_TEST(!beast::get_lowest_layer(tls).socket().is_open()); + if (++closed_ == 2) { + finish(); + } + } + +public: + bounded_exchange(bool refuse, std::string_view certificate, std::string_view key, + std::string_view authorities, int version) + : refuse_(refuse), + server_context_(server_context(certificate, key, version)), + client_context_(client_context(authorities, true)), + server_(context_, server_context_), + client_(context_, client_context_) { + auto& tls = client_.next_layer().next_layer(); + error_code ec; + BOOST_TEST(!tls.set_verify_callback(ssl::host_name_verification("localhost"), ec)); + BOOST_TEST(!ec); + BOOST_TEST(beast::set_server_name(tls, "localhost").has_value()); + } + + void run() { + deadline_.async_wait(beast::bind_front_handler(&bounded_exchange::expired, this)); + listener_.async_accept(beast::get_lowest_layer(server_).socket(), + beast::bind_front_handler(&bounded_exchange::accepted, this)); + beast::get_lowest_layer(client_).async_connect( + listener_.local_endpoint(), + beast::bind_front_handler(&bounded_exchange::connected, this)); + context_.run(); // lint-run: bounded real TLS peers share this test context + BOOST_TEST(finished_); + } +}; } // namespace int main(int argc, char* const* argv) { @@ -428,5 +619,11 @@ int main(int argc, char* const* argv) { exchange current(mode, argv[1], argv[2], argv[3], version); current.run(); } + for (const bool refuse : {true, false}) { + std::printf("Beast TLS %s bounded handshake, %s\n", argv[4], + refuse ? "refused" : "accepted"); + bounded_exchange current(refuse, argv[1], argv[2], argv[3], version); + current.run(); + } return boost::report_errors(); } From ae79a7944144010d59c66057bac2b5bd199c831f Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 06:42:47 -0300 Subject: [PATCH 2/3] beast: the TLS stream bound to a named reference, not reached by a fluent chain The lint's fluent-chains rule refused two calls of async_handshake on next_layer().next_layer(): in the example of bounded_handshake_stream's Doc Comment and in the TLS protocol test's bounded exchange. Both now bind the TLS stream to a reference first, as the rule asks. The example also starts the WebSocket handshake from the TLS handshake's completion handler, which hands a TLS error to on_upgrade, where it started both handshakes one after the other. It compiles as written natively, and the reference page shows it so. --- .../beast/websocket/bounded_handshake_stream.hpp | 12 +++++++++--- test/tls/protocol.cpp | 6 +++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/include/webcpp/beast/websocket/bounded_handshake_stream.hpp b/include/webcpp/beast/websocket/bounded_handshake_stream.hpp index 6853aca..e901ce4 100644 --- a/include/webcpp/beast/websocket/bounded_handshake_stream.hpp +++ b/include/webcpp/beast/websocket/bounded_handshake_stream.hpp @@ -162,9 +162,15 @@ struct response_limits { using transport = beast::ssl_stream; websocket::stream> ws(executor, tls); ws.next_layer().limits({.body = 0}); // a refusal's body is never read - // The TLS handshake is one layer further down, then the WebSocket handshake as before. - ws.next_layer().next_layer().async_handshake(ssl::stream_base::client, on_tls); - ws.async_handshake(host, target, on_upgrade); + // The TLS stream is one layer further down: its handshake first, then the WebSocket one. + transport& tls_stream = ws.next_layer().next_layer(); + tls_stream.async_handshake(ssl::stream_base::client, [&](boost::system::error_code ec) { + if (ec) { + on_upgrade(ec); + } else { + ws.async_handshake(host, target, on_upgrade); + } + }); @endcode @tparam NextLayer The transport, an AsyncStream or SyncStream such as `tcp_stream` or diff --git a/test/tls/protocol.cpp b/test/tls/protocol.cpp index 9669175..e9cd5e4 100644 --- a/test/tls/protocol.cpp +++ b/test/tls/protocol.cpp @@ -513,9 +513,9 @@ class bounded_exchange { finish(); return; } - client_.next_layer().next_layer().async_handshake( - ssl::stream_base::client, - beast::bind_front_handler(&bounded_exchange::client_ready, this)); + auto& tls = client_.next_layer().next_layer(); + tls.async_handshake(ssl::stream_base::client, + beast::bind_front_handler(&bounded_exchange::client_ready, this)); } void client_ready(error_code ec) { From 8763e1d93dca87994bb87c56eb18ca51accf00d3 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 12:37:21 -0300 Subject: [PATCH 3/3] beast: the handshake test allocates aligned memory as the Microsoft C library does MSVC's C library has no aligned_alloc, so the test's counting operator new failed to compile on both MSVC lanes; it takes _aligned_malloc and gives back with _aligned_free there, as asio's and document's allocation tests do. --- test/handshake_test.cpp | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/test/handshake_test.cpp b/test/handshake_test.cpp index 349128a..9888c9a 100644 --- a/test/handshake_test.cpp +++ b/test/handshake_test.cpp @@ -38,6 +38,10 @@ #include #include +#ifdef _MSC_VER +#include +#endif + namespace beast = webcpp::beast; namespace http = beast::http; namespace websocket = beast::websocket; @@ -57,13 +61,28 @@ void* allocate(std::size_t size, std::size_t alignment) { allocated += size; } alignment = std::max(alignment, alignof(std::max_align_t)); - auto* pointer = std::aligned_alloc( - alignment, ((std::max(size, std::size_t{1}) + alignment - 1) / alignment) * alignment); + const std::size_t bytes = + ((std::max(size, std::size_t{1}) + alignment - 1) / alignment) * alignment; +#ifdef _MSC_VER + // The Microsoft C library has no aligned_alloc: _aligned_malloc, which _aligned_free gives + // back. + void* pointer = _aligned_malloc(bytes, alignment); +#else + void* pointer = std::aligned_alloc(alignment, bytes); +#endif if (pointer == nullptr) { boost::throw_exception(std::bad_alloc()); } return pointer; } + +void release(void* pointer) noexcept { +#ifdef _MSC_VER + _aligned_free(pointer); +#else + std::free(pointer); +#endif +} } // namespace // NOLINTBEGIN(readability-inconsistent-declaration-parameter-name): standard replacement signatures @@ -84,36 +103,36 @@ void* operator new[](std::size_t size, std::align_val_t alignment) { } void operator delete(void* pointer) noexcept { - std::free(pointer); + release(pointer); } void operator delete[](void* pointer) noexcept { - std::free(pointer); + release(pointer); } void operator delete(void* pointer, std::size_t /*unused*/) noexcept { - std::free(pointer); + release(pointer); } void operator delete[](void* pointer, std::size_t /*unused*/) noexcept { - std::free(pointer); + release(pointer); } void operator delete(void* pointer, std::align_val_t /*unused*/) noexcept { - std::free(pointer); + release(pointer); } void operator delete[](void* pointer, std::align_val_t /*unused*/) noexcept { - std::free(pointer); + release(pointer); } void operator delete(void* pointer, std::size_t /*unused*/, std::align_val_t /*unused*/) noexcept { - std::free(pointer); + release(pointer); } void operator delete[](void* pointer, std::size_t /*unused*/, std::align_val_t /*unused*/) noexcept { - std::free(pointer); + release(pointer); } // NOLINTEND(readability-inconsistent-declaration-parameter-name)