diff --git a/CMakeLists.txt b/CMakeLists.txt index 55d0ea2..ff6c82b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ set(CMAKE_POLICY_VERSION_MINIMUM 3.5) cmake_minimum_required(VERSION 3.24) -project(native_streaming VERSION 1.0.24 LANGUAGES CXX) +project(native_streaming VERSION 1.0.25 LANGUAGES CXX) if (NOT CMAKE_MESSAGE_CONTEXT) set(CMAKE_MESSAGE_CONTEXT ${PROJECT_NAME}) diff --git a/changelog b/changelog index 715e3f8..d821e1a 100644 --- a/changelog +++ b/changelog @@ -52,6 +52,19 @@ ## v1.0.15 - Fix issue with retrieving connection endpoint name on server app resuming in debug mode +## v1.0.16 + - Fix MSVC 2017 warning + +## v1.0.17 + - Provide connection endpoint address and port separately + +## v1.0.18 + - Use unsigned short as type for endpoint port number + +## v1.0.19 + - Fix MSVC 32 bit debug configuration runtime crash + - Increase read message size limit to 256 MB to align it with the native transport protocol + ## v1.0.20 - Bump boost version to 1.90.0 @@ -72,3 +85,7 @@ - Add a Client constructor taking a ClientTlsConfig, with an optional callback for TLS handshake failures - Make the Session constructor take the transport-neutral IWsStream instead of WebsocketStream - Return address_in_use when the server is asked to listen on a port it already listens on + +## v1.0.25 + - Reply with HTTP 401 when server rejects authentication + - Pass server's handshake reply to the client's handshake failure callback diff --git a/include/native_streaming/client.hpp b/include/native_streaming/client.hpp index 9c75283..ea6b088 100644 --- a/include/native_streaming/client.hpp +++ b/include/native_streaming/client.hpp @@ -54,6 +54,16 @@ struct ClientTlsConfig #endif +/// @brief HTTP response sent by the server in reply to the websocket upgrade request +using HandshakeResponse = boost::beast::websocket::response_type; + +/// @brief callback called when the websocket handshake fails +/// @param ec error_code object indicates handshake failure +/// @param response the server's reply when it declined the upgrade (ec == websocket::error::upgrade_declined), +/// e.g. 401 Unauthorized on rejected authentication; nullptr otherwise +using OnHandshakeFailCallback = + std::function& response)>; + /// @brief Connects to specified server address, creates and returns new Session via callback when connection established class Client : public std::enable_shared_from_this { @@ -66,7 +76,7 @@ class Client : public std::enable_shared_from_this OnNewSessionCallback onNewSessionCallback, OnCompleteCallback onResolveFailCallback, OnCompleteCallback onConnectFailCallback, - OnCompleteCallback onHandshakeFailCallback, + OnHandshakeFailCallback onWsHandshakeFailCallback, std::shared_ptr ioContextPtr, LogCallback logCallback); @@ -77,7 +87,7 @@ class Client : public std::enable_shared_from_this /// @param onTlsHandshakeFailCallback callback to be called if a handshake fails with an error /// raised by the TLS layer, which means the server was reached but the two could not agree on /// trust - unlike the other failures, retrying such a connection with the same secrets is - /// pointless. If not set, such failures are reported through onHandshakeFailCallback + /// pointless. If not set, such failures are reported through onWsHandshakeFailCallback /// @throw std::invalid_argument tlsConfig is inconsistent, e.g. it names a client certificate /// without a key /// @throw boost::system::system_error a certificate or key file named by tlsConfig is missing or @@ -89,7 +99,7 @@ class Client : public std::enable_shared_from_this OnNewSessionCallback onNewSessionCallback, OnCompleteCallback onResolveFailCallback, OnCompleteCallback onConnectFailCallback, - OnCompleteCallback onHandshakeFailCallback, + OnHandshakeFailCallback onWsHandshakeFailCallback, std::shared_ptr ioContextPtr, LogCallback logCallback, const ClientTlsConfig& tlsConfig, @@ -152,13 +162,16 @@ class Client : public std::enable_shared_from_this /// @brief reports a failed handshake to the caller /// @param ec error_code object describing the failure - void reportHandshakeFailure(const boost::system::error_code& ec); + void reportHandshakeFailure(const boost::system::error_code& ec, const std::shared_ptr& response); /// @brief callback called when web-socket handshake finished for new connection /// @param ec error_code object indicates handshake failure /// @param wsStream websocket stream object associated with connection + /// @param response the server's reply to the upgrade request template - void onUpgradeConnection(const boost::system::error_code& ec, std::shared_ptr wsStream); + void onUpgradeConnection(const boost::system::error_code& ec, + std::shared_ptr wsStream, + const std::shared_ptr& response); /// @brief creates a connection Session using provided web-socket stream object /// @param wsStream web-socket stream object which provides as a R/W interface for connection @@ -221,12 +234,12 @@ class Client : public std::enable_shared_from_this OnCompleteCallback onConnectFailCallback; /// @brief callback to be called if handshake with a remote server is failed - OnCompleteCallback onHandshakeFailCallback; + OnHandshakeFailCallback onWsHandshakeFailCallback; #if NATIVE_STREAMING_ENABLE_TLS /// @brief callback to be called if a handshake fails with an error raised by the TLS layer. - /// May be unset, in which case such failures are reported through onHandshakeFailCallback + /// May be unset, in which case such failures are reported through onWsHandshakeFailCallback OnCompleteCallback onTlsHandshakeFailCallback; #endif diff --git a/include/native_streaming/server.hpp b/include/native_streaming/server.hpp index f51b740..de94f28 100644 --- a/include/native_streaming/server.hpp +++ b/include/native_streaming/server.hpp @@ -197,6 +197,13 @@ class Server : public std::enable_shared_from_this template void startReadAcceptRequest(std::shared_ptr> acceptOp); + /// @brief replies to a rejected upgrade request with HTTP 401 Unauthorized and closes the connection, + /// so the client can tell rejected authentication apart from other connection failures + /// @param wsStream web-socket stream object of the rejected connection + /// @param httpVersion HTTP version of the rejected upgrade request + template + void rejectUnauthorized(const std::shared_ptr& wsStream, unsigned httpVersion); + /// @brief creates a connection Session using provided web-socket stream object /// @param wsStream web-socket stream object which provides as a R/W interface for connection /// @param user context, usualy a pointer to the authenticated user object diff --git a/include/native_streaming/utils/boost_compatibility_utils.hpp b/include/native_streaming/utils/boost_compatibility_utils.hpp index 3d083e1..d139ace 100644 --- a/include/native_streaming/utils/boost_compatibility_utils.hpp +++ b/include/native_streaming/utils/boost_compatibility_utils.hpp @@ -36,6 +36,7 @@ namespace boost_compatibility_utils using WriteCallback = std::function; void async_handshake(WebsocketStream& stream, + boost::beast::websocket::response_type& response, const std::string& host, const std::string& target, const BoostHandler& handler); @@ -43,6 +44,7 @@ namespace boost_compatibility_utils #if NATIVE_STREAMING_ENABLE_TLS void async_handshake(TlsWebsocketStream& stream, + boost::beast::websocket::response_type& response, const std::string& host, const std::string& target, const BoostHandler& handler); diff --git a/src/client.cpp b/src/client.cpp index 93ca378..db3a743 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -20,7 +20,7 @@ Client::Client(const std::string& host, OnNewSessionCallback onNewSessionCallback, OnCompleteCallback onResolveFailCallback, OnCompleteCallback onConnectFailCallback, - OnCompleteCallback onHandshakeFailCallback, + OnHandshakeFailCallback onWsHandshakeFailCallback, std::shared_ptr ioContextPtr, LogCallback logCallback) : ioContextPtr(ioContextPtr) @@ -35,7 +35,7 @@ Client::Client(const std::string& host, , onNewSessionCallback(onNewSessionCallback) , onResolveFailCallback(onResolveFailCallback) , onConnectFailCallback(onConnectFailCallback) - , onHandshakeFailCallback(onHandshakeFailCallback) + , onWsHandshakeFailCallback(onWsHandshakeFailCallback) { } @@ -48,7 +48,7 @@ Client::Client(const std::string& host, OnNewSessionCallback onNewSessionCallback, OnCompleteCallback onResolveFailCallback, OnCompleteCallback onConnectFailCallback, - OnCompleteCallback onHandshakeFailCallback, + OnHandshakeFailCallback onWsHandshakeFailCallback, std::shared_ptr ioContextPtr, LogCallback logCallback, const ClientTlsConfig& tlsConfig, @@ -60,7 +60,7 @@ Client::Client(const std::string& host, onNewSessionCallback, onResolveFailCallback, onConnectFailCallback, - onHandshakeFailCallback, + onWsHandshakeFailCallback, ioContextPtr, logCallback) { @@ -262,7 +262,7 @@ void Client::onTlsHandshake(const boost::system::error_code& ec, std::shared_ptr // the server answered but is not trusted: check its certificate against the configured // certificate authority, and the client certificate if the server requires one NS_LOG_E("TLS handshake operation failed {}", ec.message()); - reportHandshakeFailure(ec); + reportHandshakeFailure(ec, nullptr); } return; } @@ -287,17 +287,22 @@ void Client::startTlsHandshake(std::shared_ptr wsStream) template void Client::startWebsocketHandshake(std::shared_ptr wsStream) { + // Kept so a declined upgrade can be reported together with the server's reply (e.g. 401 Unauthorized). + // The server closes the connection right after its reply. This client sends nothing after the upgrade + // request (RFC 6455), so the close arrives after the reply as an orderly FIN and the reply is read in full. + auto response = std::make_shared(); + auto onHandshakeDone = - [this, weak_self = weak_from_this(), wsStream](const boost::system::error_code& ec) + [this, weak_self = weak_from_this(), wsStream, response](const boost::system::error_code& ec) { if (auto shared_self = weak_self.lock()) - onUpgradeConnection(ec, wsStream); + onUpgradeConnection(ec, wsStream, response); }; - boost_compatibility_utils::async_handshake(*wsStream, host, path, onHandshakeDone); + boost_compatibility_utils::async_handshake(*wsStream, *response, host, path, onHandshakeDone); } -void Client::reportHandshakeFailure(const boost::system::error_code& ec) +void Client::reportHandshakeFailure(const boost::system::error_code& ec, const std::shared_ptr& response) { #if NATIVE_STREAMING_ENABLE_TLS // routing by the category of the error rather than by the step that raised it: under TLS 1.3 the @@ -310,25 +315,37 @@ void Client::reportHandshakeFailure(const boost::system::error_code& ec) } #endif - onHandshakeFailCallback(ec); + onWsHandshakeFailCallback(ec, response); } template -void Client::onUpgradeConnection(const boost::system::error_code& ec, std::shared_ptr wsStream) +void Client::onUpgradeConnection(const boost::system::error_code& ec, + std::shared_ptr wsStream, + const std::shared_ptr& response) { connectionTimeoutTimer.cancel(); if (ec) { - if (ec.value() == boost::asio::error::operation_aborted) + if (ec == boost::asio::error::operation_aborted) { NS_LOG_T("Handshake operation cancelled: {}", ec.message()); onConnectFailCallback(ec); } + else if (ec == boost::beast::websocket::error::upgrade_declined) + { + // The server replied with a status other than 101 Switching Protocols (e.g. 401 Unauthorized) + NS_LOG_E("Handshake operation failed {}: server replied {} {}", ec.message(), response->result_int(), std::string(response->reason())); + reportHandshakeFailure(ec, response); + } else { + // No reply with a status to act on: either the connection failed before a reply was read + // (closed/reset, not an HTTP service, or an older server that closes the connection on rejected + // authentication without replying), so the response is still default-constructed (200 OK), + // or the server replied 101 but the reply failed Beast's websocket header checks NS_LOG_E("Handshake operation failed {}", ec.message()); - reportHandshakeFailure(ec); + reportHandshakeFailure(ec, nullptr); } return; } diff --git a/src/server.cpp b/src/server.cpp index 3b98725..bc13ca4 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include "ws_stream_impl.hpp" @@ -27,6 +28,9 @@ constexpr auto acceptRequestTimeout = std::chrono::seconds(5); constexpr auto rejectedConnectionDrainTimeout = std::chrono::seconds(1); #endif +/// Value of the Server header in every reply to an upgrade request, accepted (101) or rejected (401) +static constexpr const char* SERVER_IDENTITY = BOOST_BEAST_VERSION_STRING " openDAQ-streaming-server"; + } Server::Server(OnNewSessionCallback onNewSessionCallback, @@ -360,13 +364,14 @@ void Server::onReadAcceptRequest(const boost::system::error_code& ec, const std: if (!onAuthenticateCallback(authentication, userContext)) { NS_LOG_I("Websocket authenticaiton failed"); + rejectUnauthorized(wsStream, request.version()); return; } // Set a decorator to change the Server-Agent of the handshake wsStream->set_option(boost::beast::websocket::stream_base::decorator( [](boost::beast::websocket::response_type& res) - { res.set(boost::beast::http::field::server, std::string(BOOST_BEAST_VERSION_STRING) + " openDAQ-streaming-server"); })); + { res.set(boost::beast::http::field::server, SERVER_IDENTITY); })); // Accept the upgrade request boost_compatibility_utils::async_accept(*wsStream, @@ -378,6 +383,39 @@ void Server::onReadAcceptRequest(const boost::system::error_code& ec, const std: }); } +template +void Server::rejectUnauthorized(const std::shared_ptr& wsStream, unsigned httpVersion) +{ + auto response = std::make_shared>( + boost::beast::http::status::unauthorized, httpVersion); + response->set(boost::beast::http::field::server, SERVER_IDENTITY); + response->set(boost::beast::http::field::www_authenticate, "Basic"); + response->keep_alive(false); + response->prepare_payload(); + + // Bound the write so a client that stops reading cannot keep the rejected connection open. + boost::beast::get_lowest_layer(*wsStream).expires_after(std::chrono::seconds(5)); + + boost::beast::http::async_write(wsStream->next_layer(), + *response, + [this, weak_self = weak_from_this(), wsStream, response](const boost::system::error_code& ec, size_t /*size*/) + { + if (auto sharedSelf = weak_self.lock()) + { + if (ec) + NS_LOG_W("Failed to send authentication rejection response: {}", ec.message()); + + // A graceful close sends the 401 first and only then the FIN, so the client + // reads the full response before it sees the connection closed. + // Compliant websocket clients send nothing after the upgrade request until + // they get the response (RFC 6455), so no unread data is pending here. + // A non-compliant client that already sent more data gets a reset instead + // of FIN and may miss the 401 - accepted, the extra bytes are not drained. + boost::beast::get_lowest_layer(*wsStream).close(); + } + }); +} + template void Server::onUpgradeConnection(const boost::system::error_code& ec, std::shared_ptr wsStream, diff --git a/src/utils/boost_compatibility_utils.cpp b/src/utils/boost_compatibility_utils.cpp index 1a08c10..cb12656 100644 --- a/src/utils/boost_compatibility_utils.cpp +++ b/src/utils/boost_compatibility_utils.cpp @@ -8,21 +8,23 @@ BEGIN_NAMESPACE_STREAM_UTILS namespace boost_compatibility_utils { void async_handshake(WebsocketStream& stream, + boost::beast::websocket::response_type& response, const std::string& host, const std::string& target, const BoostHandler& handler) { - stream.async_handshake(host, target, handler); + stream.async_handshake(response, host, target, handler); } #if NATIVE_STREAMING_ENABLE_TLS void async_handshake(TlsWebsocketStream& stream, + boost::beast::websocket::response_type& response, const std::string& host, const std::string& target, const BoostHandler& handler) { - stream.async_handshake(host, target, handler); + stream.async_handshake(response, host, target, handler); } #endif diff --git a/test/test_authentication.cpp b/test/test_authentication.cpp index 694e411..5473c89 100644 --- a/test/test_authentication.cpp +++ b/test/test_authentication.cpp @@ -30,7 +30,11 @@ class AuthenticationTest : public ConnectionTest std::shared_ptr createClient(const Authentication& authentication) { // on failed authentication we should stop waiting for client session - auto onHandshakeFailedCallback = [this](const boost::system::error_code& e) { clientConnectedPromise.set_value(); }; + auto onHandshakeFailedCallback = [this](const boost::system::error_code& e, const std::shared_ptr& response) + { + handshakeResponse = response; + clientConnectedPromise.set_value(); + }; auto client = std::make_shared(CONNECTION_HOST, std::to_string(CONNECTION_PORT), @@ -55,9 +59,13 @@ class AuthenticationTest : public ConnectionTest void resetSessions() { ResetFuturePromise(); + handshakeResponse.reset(); serverSession.reset(); clientSession.reset(); } + + /// server's reply reported to the client's handshake failure callback + std::shared_ptr handshakeResponse; }; @@ -97,6 +105,8 @@ TEST_F(AuthenticationTest, DenyAll) waitForConnection(); ASSERT_FALSE(serverSession.operator bool()); ASSERT_FALSE(clientSession.operator bool()); + ASSERT_TRUE(handshakeResponse); + ASSERT_EQ(handshakeResponse->result(), boost::beast::http::status::unauthorized); resetSessions(); client = createClient(Authentication()); @@ -105,6 +115,8 @@ TEST_F(AuthenticationTest, DenyAll) waitForConnection(); ASSERT_FALSE(serverSession.operator bool()); ASSERT_FALSE(clientSession.operator bool()); + ASSERT_TRUE(handshakeResponse); + ASSERT_EQ(handshakeResponse->result(), boost::beast::http::status::unauthorized); } TEST_F(AuthenticationTest, AllowCorrect) diff --git a/test/test_client.cpp b/test/test_client.cpp index fee5192..dfbf379 100644 --- a/test/test_client.cpp +++ b/test/test_client.cpp @@ -17,7 +17,8 @@ class ClientTest : public TestBase clientConnectFailedFuture = clientConnectFailedPromise.get_future(); onResolveFailedCallback = [this](const boost::system::error_code&) { clientConnectFailedPromise.set_value(); }; onConnectFailedCallback = [this](const boost::system::error_code&) { clientConnectFailedPromise.set_value(); }; - onHandshakeFailedCallback = [this](const boost::system::error_code&) { clientConnectFailedPromise.set_value(); }; + onHandshakeFailedCallback = [this](const boost::system::error_code&, const std::shared_ptr&) + { clientConnectFailedPromise.set_value(); }; } void TearDown() override @@ -28,7 +29,7 @@ class ClientTest : public TestBase std::future clientConnectFailedFuture; OnCompleteCallback onResolveFailedCallback; OnCompleteCallback onConnectFailedCallback; - OnCompleteCallback onHandshakeFailedCallback; + OnHandshakeFailCallback onHandshakeFailedCallback; Authentication authentication; /// Drops created session diff --git a/test/test_connection.hpp b/test/test_connection.hpp index fd24eba..526c605 100644 --- a/test/test_connection.hpp +++ b/test/test_connection.hpp @@ -128,7 +128,7 @@ class ConnectionTest : public TestBase onConnectFailedCallback = [this](const boost::system::error_code& ec) { ADD_FAILURE() << "Connection failed: " << ec.message(); }; - onHandshakeFailedCallback = [this](const boost::system::error_code& ec) + onHandshakeFailedCallback = [this](const boost::system::error_code& ec, const std::shared_ptr&) { ADD_FAILURE() << "Handshake failed: " << ec.message(); }; } @@ -260,7 +260,7 @@ class ConnectionTest : public TestBase OnCompleteCallback onConnectFailedCallback; OnCompleteCallback onResolveFailedCallback; - OnCompleteCallback onHandshakeFailedCallback; + OnHandshakeFailCallback onHandshakeFailedCallback; Authentication authentication; TransportMode transportMode = TransportMode::Plaintext; diff --git a/test/test_tls.cpp b/test/test_tls.cpp index bc40647..ed22266 100644 --- a/test/test_tls.cpp +++ b/test/test_tls.cpp @@ -16,7 +16,8 @@ class TlsConnectionTest : public ConnectionTest // the failures below are what most of these tests are about, so they are recorded rather // than reported, and each test states which one it expects - onHandshakeFailedCallback = [this](const boost::system::error_code& ec) { recordFailure("handshake", ec); }; + onHandshakeFailedCallback = [this](const boost::system::error_code& ec, const std::shared_ptr&) + { recordFailure("handshake", ec); }; onTlsHandshakeFailedCallback = [this](const boost::system::error_code& ec) { recordFailure("tls", ec); }; onConnectFailedCallback = [this](const boost::system::error_code& ec) { recordFailure("connect", ec); }; }