Files

394 lines
12 KiB
C++

#include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <array>
#include <atomic>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace
{
using Void::Net::BodyReader;
using Void::Net::Header;
using Void::Net::HttpClient;
using Void::Net::HttpServer;
using Void::Net::HttpServerOptions;
using Void::Net::Method;
using Void::Net::Request;
using Void::Net::ServerRequest;
using Void::Net::ServerResponse;
std::string raw_http_exchange(std::uint16_t port, std::string_view raw_req)
{
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
Void::Testing::require(fd >= 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
Void::Testing::require(
::connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) ==
0);
std::size_t off = 0;
while (off < raw_req.size()) {
const ssize_t w =
::send(fd, raw_req.data() + off, raw_req.size() - off, 0);
Void::Testing::require(w > 0);
off += static_cast<std::size_t>(w);
}
(void)::shutdown(fd, SHUT_WR);
std::string out;
std::array<char, 4096> buf{};
for (;;) {
const ssize_t r = ::recv(fd, buf.data(), buf.size(), 0);
if (r <= 0) {
break;
}
out.append(buf.data(), static_cast<std::size_t>(r));
}
(void)::close(fd);
return out;
}
std::string read_file_bytes(const std::filesystem::path& p)
{
std::ifstream in{p, std::ios::binary};
Void::Testing::require(in.is_open());
return std::string{std::istreambuf_iterator<char>{in},
std::istreambuf_iterator<char>{}};
}
} // namespace
Void::Testing::Test http_server_ephemeral_methods_and_concurrent_dispatch()
{
HttpServerOptions opts;
opts.bind_host = "127.0.0.1";
opts.port = 0;
HttpServer server{opts};
Void::Testing::require(
server
.add_route(Method::Get, "/items/:id",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 200,
.headers = {Header{"X-Item",
req.parameters.at("id")}},
.body = "get:" + req.parameters.at("id") + "?" +
req.query});
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Post, "/items",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 201, .body = "post:" + req.body});
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Put, "/items/:id",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 200,
.body = "put:" + req.parameters.at("id") + ":" +
req.body});
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Delete, "/items/:id",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 200,
.body = "del:" + req.parameters.at("id")});
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Get, "/boom",
[](const ServerRequest&) -> Void::Net::RouteResult {
return Void::Result::fail(
"internal secret db credentials leaked here");
})
.has_value());
Void::Testing::require(server.start().has_value());
const std::uint16_t port = server.bound_port();
Void::Testing::expect(port > 0);
Void::Testing::expect(server.running());
const std::string base = server.base_url();
HttpClient client;
// GET + query + path param
{
auto r = client.get(base + "/items/alpha?full=1");
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(r->status, std::uint16_t{200});
Void::Testing::expect_eq(r->body, std::string{"get:alpha?full=1"});
Void::Testing::expect_eq(*r->header("x-item"), std::string_view{"alpha"});
}
// HEAD falls back to GET route without response body
{
auto r = client.send(Request{.method = Method::Head,
.url = base + "/items/alpha?full=1"});
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(r->status, std::uint16_t{200});
Void::Testing::expect(r->body.empty());
Void::Testing::expect_eq(*r->header("X-Item"), std::string_view{"alpha"});
}
// POST, PUT, DELETE
{
auto post_r = client.post(base + "/items", "new-payload");
Void::Testing::require(post_r.has_value());
Void::Testing::expect_eq(post_r->status, std::uint16_t{201});
Void::Testing::expect_eq(post_r->body, std::string{"post:new-payload"});
auto put_r = client.send(Request{.method = Method::Put,
.url = base + "/items/beta",
.body = "updated"});
Void::Testing::require(put_r.has_value());
Void::Testing::expect_eq(put_r->status, std::uint16_t{200});
Void::Testing::expect_eq(put_r->body, std::string{"put:beta:updated"});
auto del_r = client.send(Request{.method = Method::Delete,
.url = base + "/items/beta"});
Void::Testing::require(del_r.has_value());
Void::Testing::expect_eq(del_r->status, std::uint16_t{200});
Void::Testing::expect_eq(del_r->body, std::string{"del:beta"});
}
// 404, 405 + Allow, sanitized 500
{
auto r404 = client.get(base + "/missing");
Void::Testing::require(r404.has_value());
Void::Testing::expect_eq(r404->status, std::uint16_t{404});
auto r405 = client.post(base + "/boom", "ignored");
Void::Testing::require(r405.has_value());
Void::Testing::expect_eq(r405->status, std::uint16_t{405});
auto allow = r405->header("Allow");
Void::Testing::require(allow.has_value());
Void::Testing::expect(allow->find("GET") != std::string_view::npos);
auto r500 = client.get(base + "/boom");
Void::Testing::require(r500.has_value());
Void::Testing::expect_eq(r500->status, std::uint16_t{500});
Void::Testing::expect(r500->body.find("secret db credentials") ==
std::string::npos);
}
// Concurrent client burst
{
constexpr int kThreads = 8;
constexpr int kPerThread = 10;
std::atomic<int> ok_count{0};
std::vector<std::thread> threads;
threads.reserve(kThreads);
for (int t = 0; t < kThreads; ++t) {
threads.emplace_back([&, t]() {
HttpClient c;
for (int i = 0; i < kPerThread; ++i) {
const std::string tag =
std::to_string(t) + "-" + std::to_string(i);
auto res = c.get(base + "/items/" + tag);
if (res.has_value() && res->status == 200 &&
res->body == ("get:" + tag + "?")) {
ok_count.fetch_add(1, std::memory_order_relaxed);
}
}
});
}
for (auto& th : threads) {
th.join();
}
Void::Testing::expect_eq(ok_count.load(), kThreads * kPerThread);
}
server.shutdown();
Void::Testing::expect(!server.running());
Void::Testing::expect_eq(server.bound_port(), std::uint16_t{0});
// No dangling listening socket after shutdown().
const int probe = ::socket(AF_INET, SOCK_STREAM, 0);
Void::Testing::require(probe >= 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
Void::Testing::expect(
::connect(probe, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) !=
0);
(void)::close(probe);
}
Void::Testing::Test http_server_limits_smuggling_streaming_and_graceful_drain()
{
Void::FileSystem::TempDir tmp{"void_http_srv_"};
const auto uploaded_path = tmp / "uploaded.bin";
HttpServerOptions opts;
opts.max_header_bytes = 512;
opts.max_body_bytes = 64;
opts.max_streaming_body_bytes = 2U * 1024U * 1024U;
HttpServer server{opts};
Void::Testing::require(
server
.add_route(Method::Post, "/small",
[](const ServerRequest& req) {
return Void::Result::ok(ServerResponse{
.status = 200, .body = req.body});
})
.has_value());
Void::Testing::require(
server
.add_streaming_route(
Method::Put, "/upload",
[&](const ServerRequest&, BodyReader& body)
-> Void::Net::RouteResult {
auto n = body.read_to_file(uploaded_path);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
return ServerResponse{
.status = 201,
.body = std::to_string(*n)};
})
.has_value());
Void::Testing::require(
server
.add_route(Method::Get, "/artifact",
[&](const ServerRequest&) {
return Void::Result::ok(
ServerResponse::from_file(uploaded_path));
})
.has_value());
std::atomic<bool> in_flight_entered{false};
std::atomic<bool> allow_in_flight_exit{false};
Void::Testing::require(
server
.add_route(Method::Get, "/slow",
[&](const ServerRequest&) {
in_flight_entered.store(true,
std::memory_order_release);
while (!allow_in_flight_exit.load(
std::memory_order_acquire)) {
std::this_thread::sleep_for(
std::chrono::milliseconds{5});
}
return Void::Result::ok(
ServerResponse{.status = 200, .body = "drained"});
})
.has_value());
Void::Testing::require(server.start().has_value());
const std::uint16_t port = server.bound_port();
const std::string base = server.base_url();
HttpClient client;
// 1. Oversized buffered body (Content-Length and chunked) rejected with 413.
{
const std::string big(128, 'A');
auto r413 = client.post(base + "/small", big);
Void::Testing::require(r413.has_value());
Void::Testing::expect_eq(r413->status, std::uint16_t{413});
const std::string chunked_big =
"POST /small HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Transfer-Encoding: chunked\r\n"
"Connection: close\r\n\r\n"
"50\r\n" +
std::string(80, 'B') + "\r\n0\r\n\r\n";
const std::string raw_resp = raw_http_exchange(port, chunked_big);
Void::Testing::expect(raw_resp.starts_with("HTTP/1.1 413"));
}
// 2. Oversized header rejected with 431; TE+CL smuggling rejected with 400.
{
const std::string huge_hdr =
"GET /small HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"X-Huge: " +
std::string(700, 'H') + "\r\n\r\n";
const std::string raw_431 = raw_http_exchange(port, huge_hdr);
Void::Testing::expect(raw_431.starts_with("HTTP/1.1 431"));
const std::string smuggle =
"POST /small HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Content-Length: 4\r\n"
"Transfer-Encoding: chunked\r\n\r\n"
"0\r\n\r\n";
const std::string raw_400 = raw_http_exchange(port, smuggle);
Void::Testing::expect(raw_400.starts_with("HTTP/1.1 400"));
}
// 3. Streaming PUT to file + streaming file_body GET (larger than buffered
// max_body_bytes = 64B!).
{
std::string payload(256U * 1024U, '\0');
for (std::size_t i = 0; i < payload.size(); ++i) {
payload[i] = static_cast<char>('a' + (i % 26U));
}
auto put_r = client.send(Request{.method = Method::Put,
.url = base + "/upload",
.body = payload});
Void::Testing::require(put_r.has_value());
Void::Testing::expect_eq(put_r->status, std::uint16_t{201});
Void::Testing::expect_eq(put_r->body,
std::to_string(payload.size()));
Void::Testing::expect_eq(read_file_bytes(uploaded_path), payload);
auto get_r = client.get(base + "/artifact");
Void::Testing::require(get_r.has_value());
Void::Testing::expect_eq(get_r->status, std::uint16_t{200});
Void::Testing::expect_eq(get_r->body, payload);
}
// 4. Graceful shutdown drains active in-flight request cleanly.
{
Void::Result::Result<Void::Net::Response, Void::Result::Error>
slow_result = Void::Result::fail("uninitialized");
std::thread slow_client([&]() {
HttpClient c;
slow_result = c.get(base + "/slow");
});
while (!in_flight_entered.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{2});
}
std::thread releaser([&]() {
std::this_thread::sleep_for(std::chrono::milliseconds{40});
allow_in_flight_exit.store(true, std::memory_order_release);
});
server.shutdown(std::chrono::seconds{2});
releaser.join();
slow_client.join();
Void::Testing::require(slow_result.has_value());
Void::Testing::expect_eq(slow_result->status, std::uint16_t{200});
Void::Testing::expect_eq(slow_result->body, std::string{"drained"});
}
}