470 lines
17 KiB
C++
470 lines
17 KiB
C++
#include <Void/Net/Http.hpp>
|
|
#include <Void/Net/HttpCodec.hpp>
|
|
#include <Void/Net/HttpServer.hpp>
|
|
#include <Void/Net/Pool.hpp>
|
|
#include <Void/Net/Server.hpp>
|
|
#include <Void/Net/WebSocket.hpp>
|
|
#include <Void/System/TempDir.hpp>
|
|
#include <Void/Testing/Assert.hpp>
|
|
#include <Void/Testing/Test.hpp>
|
|
#include <Void/Time/Clock.hpp>
|
|
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <cstddef>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <memory>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
namespace
|
|
{
|
|
struct FakeConn final : Void::Net::PooledConnection {
|
|
std::atomic<bool> open{true};
|
|
std::atomic<int>* close_counter{nullptr};
|
|
std::uint64_t id{0};
|
|
|
|
FakeConn(std::uint64_t cid, std::atomic<int>* closes)
|
|
: close_counter(closes), id(cid)
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] bool is_open() const noexcept override
|
|
{
|
|
return open.load(std::memory_order_acquire);
|
|
}
|
|
|
|
void close() noexcept override
|
|
{
|
|
if (open.exchange(false, std::memory_order_acq_rel) &&
|
|
close_counter != nullptr) {
|
|
close_counter->fetch_add(1, std::memory_order_relaxed);
|
|
}
|
|
}
|
|
};
|
|
} // namespace
|
|
|
|
Void::Testing::Test net_http_codec_incremental_chunked_trailers_and_smuggling()
|
|
{
|
|
// 1. Feed chunked request with chunk extension + trailer byte-by-byte.
|
|
const std::string raw_req =
|
|
"POST /upload?x=1 HTTP/1.1\r\n"
|
|
"Host: example.test\r\n"
|
|
"Transfer-Encoding: chunked\r\n"
|
|
"\r\n"
|
|
"5;ext=1\r\n"
|
|
"hello\r\n"
|
|
"6\r\n"
|
|
" world\r\n"
|
|
"0;final=yes\r\n"
|
|
"X-Checksum: abc123\r\n"
|
|
"\r\n";
|
|
|
|
Void::Net::HttpRequestParser req_parser;
|
|
std::size_t total_consumed = 0;
|
|
for (std::size_t i = 0; i < raw_req.size(); ++i) {
|
|
std::size_t c = 0;
|
|
auto res = req_parser.feed(std::string_view{raw_req.data() + i, 1}, c);
|
|
Void::Testing::require(res.has_value());
|
|
total_consumed += c;
|
|
if (i + 1 < raw_req.size()) {
|
|
Void::Testing::expect(*res == Void::Net::HttpParseStatus::NeedMoreData);
|
|
} else {
|
|
Void::Testing::expect(*res == Void::Net::HttpParseStatus::Complete);
|
|
}
|
|
}
|
|
Void::Testing::expect_eq(total_consumed, raw_req.size());
|
|
Void::Testing::expect(req_parser.connection_reusable());
|
|
const auto req = req_parser.take_request();
|
|
Void::Testing::expect(req.method == Void::Net::Method::Post);
|
|
Void::Testing::expect_eq(req.target, std::string{"/upload?x=1"});
|
|
Void::Testing::expect_eq(req.body, std::string{"hello world"});
|
|
Void::Testing::require(req.trailers.size() == 1U);
|
|
Void::Testing::expect_eq(req.trailers[0].name, std::string{"X-Checksum"});
|
|
Void::Testing::expect_eq(req.trailers[0].value, std::string{"abc123"});
|
|
|
|
// 2. Reject smuggling combinations (TE+CL, duplicate CL, bare LF, missing Host).
|
|
const std::vector<std::string> bad_requests{
|
|
"POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n",
|
|
"POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\nContent-Length: 4\r\n\r\nabcd",
|
|
"GET /a HTTP/1.1\r\nHost: x\nX-Bad: 1\r\n\r\n",
|
|
"GET /a HTTP/1.1\r\nUser-Agent: test\r\n\r\n",
|
|
};
|
|
for (const auto& bad : bad_requests) {
|
|
Void::Net::HttpRequestParser p;
|
|
std::size_t c = 0;
|
|
auto r = p.feed(bad, c);
|
|
Void::Testing::expect(!r.has_value());
|
|
Void::Testing::expect(!p.connection_reusable());
|
|
}
|
|
|
|
// 3. Response parser: 100 Continue + 103 Early Hints + 200 OK with body.
|
|
const std::string raw_resp =
|
|
"HTTP/1.1 100 Continue\r\n\r\n"
|
|
"HTTP/1.1 103 Early Hints\r\nLink: </style.css>; rel=preload\r\n\r\n"
|
|
"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndone";
|
|
Void::Net::HttpResponseParser resp_parser;
|
|
std::size_t rc = 0;
|
|
auto rr = resp_parser.feed(raw_resp, rc);
|
|
Void::Testing::require(rr.has_value());
|
|
Void::Testing::expect(*rr == Void::Net::HttpParseStatus::Complete);
|
|
Void::Testing::expect(resp_parser.connection_reusable());
|
|
const auto resp = resp_parser.take_response();
|
|
Void::Testing::expect_eq(resp.status, std::uint16_t{200});
|
|
Void::Testing::expect_eq(resp.body, std::string{"done"});
|
|
Void::Testing::require(resp.informational_statuses.size() == 2U);
|
|
Void::Testing::expect_eq(resp.informational_statuses[0], std::uint16_t{100});
|
|
Void::Testing::expect_eq(resp.informational_statuses[1], std::uint16_t{103});
|
|
|
|
// 4. HEAD response with non-zero Content-Length completes with zero body.
|
|
Void::Net::HttpResponseParser head_parser{{}, Void::Net::Method::Head};
|
|
auto hr = head_parser.feed(
|
|
"HTTP/1.1 200 OK\r\nContent-Length: 9999\r\n\r\n", rc);
|
|
Void::Testing::require(hr.has_value());
|
|
Void::Testing::expect(*hr == Void::Net::HttpParseStatus::Complete);
|
|
Void::Testing::expect(head_parser.response().body.empty());
|
|
|
|
// 5. Close-delimited response completes on EOF and is non-reusable.
|
|
Void::Net::HttpResponseParser close_parser;
|
|
auto cr = close_parser.feed("HTTP/1.1 200 OK\r\n\r\nstreamed", rc);
|
|
Void::Testing::require(cr.has_value());
|
|
Void::Testing::expect(*cr == Void::Net::HttpParseStatus::NeedMoreData);
|
|
Void::Testing::require(close_parser.finish_eof().has_value());
|
|
Void::Testing::expect(close_parser.complete());
|
|
Void::Testing::expect(!close_parser.connection_reusable());
|
|
Void::Testing::expect_eq(close_parser.response().body, std::string{"streamed"});
|
|
}
|
|
|
|
Void::Testing::Test net_connection_pool_isolation_limits_and_clock_eviction()
|
|
{
|
|
Void::Time::ManualClock clock;
|
|
Void::Net::PoolLimits limits;
|
|
limits.max_total_connections = 3;
|
|
limits.max_per_origin = 2;
|
|
limits.max_idle_connections = 2;
|
|
limits.idle_timeout = std::chrono::seconds{10};
|
|
|
|
Void::Net::ConnectionPool pool{limits, clock};
|
|
std::atomic<std::uint64_t> next_id{1};
|
|
std::atomic<int> closes{0};
|
|
|
|
auto factory = [&](const Void::Net::PoolKey&)
|
|
-> Void::Result::Result<std::unique_ptr<Void::Net::PooledConnection>> {
|
|
return std::make_unique<FakeConn>(
|
|
next_id.fetch_add(1, std::memory_order_relaxed), &closes);
|
|
};
|
|
|
|
const Void::Net::PoolKey k1{"https", "api.example", 443, "", 1};
|
|
const Void::Net::PoolKey k1_gen2{"https", "api.example", 443, "", 2};
|
|
const Void::Net::PoolKey k2{"https", "cdn.example", 443, "", 1};
|
|
|
|
// Acquire, mark reusable, return -> second acquire reuses same ID.
|
|
std::uint64_t first_id = 0;
|
|
{
|
|
auto l1 = pool.acquire(k1, factory);
|
|
Void::Testing::require(l1.has_value());
|
|
Void::Testing::expect(!l1->reused());
|
|
first_id = static_cast<FakeConn*>(l1->get())->id;
|
|
l1->mark_reusable(true);
|
|
}
|
|
{
|
|
auto l2 = pool.acquire(k1, factory);
|
|
Void::Testing::require(l2.has_value());
|
|
Void::Testing::expect(l2->reused());
|
|
Void::Testing::expect_eq(static_cast<FakeConn*>(l2->get())->id, first_id);
|
|
// Do NOT mark reusable -> closes dirty on release.
|
|
}
|
|
Void::Testing::expect_eq(closes.load(), 1);
|
|
Void::Testing::expect_eq(pool.stats().closed_dirty, std::uint64_t{1});
|
|
|
|
// Different TLS generation must NOT reuse k1's idle connection.
|
|
{
|
|
auto a = pool.acquire(k1, factory);
|
|
Void::Testing::require(a.has_value());
|
|
a->mark_reusable(true);
|
|
}
|
|
{
|
|
auto b = pool.acquire(k1_gen2, factory);
|
|
Void::Testing::require(b.has_value());
|
|
Void::Testing::expect(!b->reused());
|
|
b->mark_reusable(true);
|
|
}
|
|
|
|
// Deterministic idle timeout eviction via ManualClock.
|
|
Void::Testing::expect_eq(pool.stats().idle_connections, std::size_t{2});
|
|
Void::Testing::require(clock.advance(std::chrono::seconds{11}).has_value());
|
|
Void::Testing::expect_eq(pool.evict_expired(), std::size_t{2});
|
|
Void::Testing::expect_eq(pool.stats().idle_connections, std::size_t{0});
|
|
|
|
// Per-origin limit = 2 rejects 3rd simultaneous active lease on k2.
|
|
auto c1 = pool.acquire(k2, factory);
|
|
auto c2 = pool.acquire(k2, factory);
|
|
auto c3 = pool.acquire(k2, factory);
|
|
Void::Testing::require(c1.has_value());
|
|
Void::Testing::require(c2.has_value());
|
|
Void::Testing::expect(!c3.has_value());
|
|
Void::Testing::expect(c3.error().kind() == Void::Result::ErrorKind::overloaded);
|
|
|
|
pool.shutdown();
|
|
c1->release();
|
|
c2->release();
|
|
Void::Testing::expect_eq(pool.stats().total_connections, std::size_t{0});
|
|
}
|
|
|
|
Void::Testing::Test net_static_file_resolver_open_safe_pins_root_and_rejects_symlinks()
|
|
{
|
|
Void::FileSystem::TempDir tmp{"void_net_static_"};
|
|
const auto root = tmp / "www";
|
|
const auto secret = tmp / "secret.txt";
|
|
std::filesystem::create_directories(root / "sub");
|
|
{
|
|
std::ofstream f{root / "sub" / "index.html"};
|
|
f << "<h1>hello</h1>";
|
|
}
|
|
{
|
|
std::ofstream f{secret};
|
|
f << "top-secret";
|
|
}
|
|
std::filesystem::create_symlink(secret, root / "escape.txt");
|
|
|
|
auto resolver = Void::Net::StaticFileResolver::create(root);
|
|
Void::Testing::require(resolver.has_value());
|
|
|
|
// Directory open resolves index.html beneath pinned descriptor.
|
|
auto opened = resolver->open_safe("/sub/");
|
|
Void::Testing::require(opened.has_value());
|
|
Void::Testing::require(opened->has_value());
|
|
Void::Testing::expect_eq((*opened)->content_type(),
|
|
std::string_view{"text/html; charset=utf-8"});
|
|
auto data = (*opened)->read_all();
|
|
Void::Testing::require(data.has_value());
|
|
Void::Testing::expect_eq(*data, std::string{"<h1>hello</h1>"});
|
|
|
|
// Missing file returns empty optional (not error).
|
|
auto missing = resolver->open_safe("/nope.txt");
|
|
Void::Testing::require(missing.has_value());
|
|
Void::Testing::expect(!missing->has_value());
|
|
|
|
// Symlink inside root is rejected by O_NOFOLLOW.
|
|
auto sym = resolver->open_safe("/escape.txt");
|
|
Void::Testing::expect(!sym.has_value());
|
|
|
|
// Traversal rejected.
|
|
auto trav = resolver->open_safe("/../secret.txt");
|
|
Void::Testing::expect(!trav.has_value());
|
|
}
|
|
|
|
Void::Testing::Test net_http_client_redirects_303_307_and_cross_origin_strip()
|
|
{
|
|
Void::Net::HttpServer server1;
|
|
Void::Net::HttpServer server2;
|
|
|
|
std::atomic<bool> got_auth_on_s2{false};
|
|
Void::Testing::require(
|
|
server2
|
|
.add_route(Void::Net::Method::Get, "/landing",
|
|
[&](const Void::Net::ServerRequest& req)
|
|
-> Void::Net::RouteResult {
|
|
if (req.header("Authorization").has_value()) {
|
|
got_auth_on_s2.store(true);
|
|
}
|
|
return Void::Net::ServerResponse{
|
|
.status = 200, .body = "from-s2"};
|
|
})
|
|
.has_value());
|
|
Void::Testing::require(server2.start().has_value());
|
|
|
|
// 303 on POST -> GET to relative location without body.
|
|
Void::Testing::require(
|
|
server1
|
|
.add_route(Void::Net::Method::Post, "/submit",
|
|
[](const Void::Net::ServerRequest&)
|
|
-> Void::Net::RouteResult {
|
|
return Void::Net::ServerResponse{
|
|
.status = 303,
|
|
.headers = {{"Location", "/done"}},
|
|
.body = ""};
|
|
})
|
|
.has_value());
|
|
Void::Testing::require(
|
|
server1
|
|
.add_route(Void::Net::Method::Get, "/done",
|
|
[](const Void::Net::ServerRequest& req)
|
|
-> Void::Net::RouteResult {
|
|
return Void::Net::ServerResponse{
|
|
.status = 200,
|
|
.body = "get-done:" + req.body};
|
|
})
|
|
.has_value());
|
|
// 307 on POST -> preserves POST + body.
|
|
Void::Testing::require(
|
|
server1
|
|
.add_route(Void::Net::Method::Post, "/temp",
|
|
[](const Void::Net::ServerRequest&)
|
|
-> Void::Net::RouteResult {
|
|
return Void::Net::ServerResponse{
|
|
.status = 307,
|
|
.headers = {{"Location", "/temp-dst"}},
|
|
.body = ""};
|
|
})
|
|
.has_value());
|
|
Void::Testing::require(
|
|
server1
|
|
.add_route(Void::Net::Method::Post, "/temp-dst",
|
|
[](const Void::Net::ServerRequest& req)
|
|
-> Void::Net::RouteResult {
|
|
return Void::Net::ServerResponse{
|
|
.status = 200, .body = "post:" + req.body};
|
|
})
|
|
.has_value());
|
|
// Cross-origin redirect from server1 -> server2.
|
|
Void::Testing::require(
|
|
server1
|
|
.add_route(Void::Net::Method::Get, "/cross",
|
|
[dst = server2.base_url() + "/landing"](
|
|
const Void::Net::ServerRequest&)
|
|
-> Void::Net::RouteResult {
|
|
return Void::Net::ServerResponse{
|
|
.status = 302,
|
|
.headers = {{"Location", dst}},
|
|
.body = ""};
|
|
})
|
|
.has_value());
|
|
Void::Testing::require(server1.start().has_value());
|
|
|
|
Void::Net::HttpClient client;
|
|
client.set_max_redirects(5);
|
|
|
|
auto r303 = client.post(server1.base_url() + "/submit", "payload");
|
|
Void::Testing::require(r303.has_value());
|
|
Void::Testing::expect_eq(r303->status, std::uint16_t{200});
|
|
Void::Testing::expect_eq(r303->body, std::string{"get-done:"});
|
|
|
|
auto r307 = client.post(server1.base_url() + "/temp", "keepme");
|
|
Void::Testing::require(r307.has_value());
|
|
Void::Testing::expect_eq(r307->status, std::uint16_t{200});
|
|
Void::Testing::expect_eq(r307->body, std::string{"post:keepme"});
|
|
|
|
auto rcross = client.get(server1.base_url() + "/cross",
|
|
{{"Authorization", "Bearer top-secret"}});
|
|
Void::Testing::require(rcross.has_value());
|
|
Void::Testing::expect_eq(rcross->status, std::uint16_t{200});
|
|
Void::Testing::expect_eq(rcross->body, std::string{"from-s2"});
|
|
Void::Testing::expect(!got_auth_on_s2.load());
|
|
|
|
server1.shutdown();
|
|
server2.shutdown();
|
|
}
|
|
|
|
Void::Testing::Test net_websocket_rfc6455_codec_and_live_server_roundtrip()
|
|
{
|
|
// 1. RFC 6455 §1.3 official Sec-WebSocket-Accept vector.
|
|
Void::Testing::expect_eq(
|
|
Void::Net::compute_websocket_accept("dGhlIHNhbXBsZSBub25jZQ=="),
|
|
std::string{"s3pPLMBiTxaQ9kYGzzhZRbK+xOo="});
|
|
|
|
// 2. Decoder enforces client masking & strict UTF-8 on text frames.
|
|
Void::Net::WebSocketDecoder server_dec{true};
|
|
Void::Net::WebSocketFrame unmasked;
|
|
unmasked.opcode = Void::Net::WebSocketOpcode::Text;
|
|
unmasked.masked = false;
|
|
auto raw_unmasked = Void::Net::encode_websocket_frame(unmasked);
|
|
Void::Testing::require(raw_unmasked.has_value());
|
|
std::vector<Void::Net::WebSocketMessage> msgs;
|
|
Void::Testing::expect(!server_dec.feed(*raw_unmasked, msgs).has_value());
|
|
|
|
Void::Net::WebSocketDecoder bad_utf8_dec{true};
|
|
Void::Net::WebSocketFrame bad_txt;
|
|
bad_txt.opcode = Void::Net::WebSocketOpcode::Text;
|
|
bad_txt.masked = true;
|
|
bad_txt.mask_key = {std::byte{1}, std::byte{2}, std::byte{3}, std::byte{4}};
|
|
bad_txt.payload = {std::byte{0xFF}, std::byte{0xFE}};
|
|
auto raw_bad_txt = Void::Net::encode_websocket_frame(bad_txt);
|
|
Void::Testing::require(raw_bad_txt.has_value());
|
|
Void::Testing::expect(!bad_utf8_dec.feed(*raw_bad_txt, msgs).has_value());
|
|
|
|
// 3. Live loopback HttpServer WebSocket upgrade + WebSocketClient.
|
|
Void::Net::WebSocketSessions sessions;
|
|
std::atomic<int> closed_count{0};
|
|
sessions.set_events(Void::Net::WebSocketEvents{
|
|
.opened = {},
|
|
.text =
|
|
[](const std::shared_ptr<Void::Net::WebSocketConnection>& conn,
|
|
std::string_view text) {
|
|
(void)conn->send_text("echo:" + std::string{text});
|
|
},
|
|
.binary =
|
|
[](const std::shared_ptr<Void::Net::WebSocketConnection>& conn,
|
|
std::span<const std::byte> data) {
|
|
(void)conn->send_binary(data);
|
|
},
|
|
.closed =
|
|
[&](Void::Net::WebSocketConnectionId,
|
|
const Void::Net::WebSocketClose&) {
|
|
closed_count.fetch_add(1, std::memory_order_relaxed);
|
|
},
|
|
.error = {},
|
|
});
|
|
|
|
Void::Net::HttpServer server;
|
|
Void::Net::WebSocketUpgradeOptions ws_opts;
|
|
ws_opts.supported_subprotocols = {"void.rpc.v1", "chat"};
|
|
Void::Testing::require(
|
|
server.add_websocket_route("/ws/echo", sessions, ws_opts).has_value());
|
|
Void::Testing::require(server.start().has_value());
|
|
|
|
const std::string ws_url =
|
|
"ws://127.0.0.1:" + std::to_string(server.bound_port()) + "/ws/echo";
|
|
Void::Net::WebSocketClient::ConnectOptions copts;
|
|
copts.subprotocol = "void.rpc.v1";
|
|
auto client = Void::Net::WebSocketClient::connect(ws_url, copts);
|
|
Void::Testing::require(client.has_value());
|
|
Void::Testing::require(client->selected_subprotocol().has_value());
|
|
Void::Testing::expect_eq(*client->selected_subprotocol(),
|
|
std::string{"void.rpc.v1"});
|
|
|
|
// Text round-trip.
|
|
Void::Testing::require(client->send_text("hello ws").has_value());
|
|
auto m1 = client->receive();
|
|
Void::Testing::require(m1.has_value());
|
|
Void::Testing::expect(m1->opcode == Void::Net::WebSocketOpcode::Text);
|
|
Void::Testing::expect_eq(std::string{m1->text_view()},
|
|
std::string{"echo:hello ws"});
|
|
|
|
// Fragmented UTF-8 text round-trip (split multi-byte UTF-8 sequence across
|
|
// frames).
|
|
const std::array<std::string_view, 3> frags{"frag-", "\xE2\x9C", "\x94!"};
|
|
Void::Testing::require(client->send_fragmented_text(frags).has_value());
|
|
auto m2 = client->receive();
|
|
Void::Testing::require(m2.has_value());
|
|
Void::Testing::expect_eq(std::string{m2->text_view()},
|
|
std::string{"echo:frag-\xE2\x9C\x94!"});
|
|
|
|
// Binary round-trip.
|
|
const std::array<std::byte, 4> bin{std::byte{0x00}, std::byte{0xDE},
|
|
std::byte{0xAD}, std::byte{0xFF}};
|
|
Void::Testing::require(client->send_binary(bin).has_value());
|
|
auto m3 = client->receive();
|
|
Void::Testing::require(m3.has_value());
|
|
Void::Testing::expect(m3->opcode == Void::Net::WebSocketOpcode::Binary);
|
|
Void::Testing::expect_eq(m3->payload.size(), std::size_t{4});
|
|
Void::Testing::expect(m3->payload[1] == std::byte{0xDE});
|
|
|
|
// Ping -> automatic server Pong echoing payload.
|
|
const std::array<std::byte, 3> ping_bytes{std::byte{'p'}, std::byte{'n'},
|
|
std::byte{'g'}};
|
|
Void::Testing::require(client->send_ping(ping_bytes).has_value());
|
|
auto m4 = client->receive();
|
|
Void::Testing::require(m4.has_value());
|
|
Void::Testing::expect(m4->opcode == Void::Net::WebSocketOpcode::Pong);
|
|
Void::Testing::expect_eq(m4->payload.size(), std::size_t{3});
|
|
|
|
// Graceful close handshake.
|
|
Void::Testing::require(client->close({1000, "done"}).has_value());
|
|
server.shutdown();
|
|
Void::Testing::expect(closed_count.load() >= 1);
|
|
}
|