feat(net): implement VL-004 HttpServer and VL-005 streaming HttpClient with secure TLS

This commit is contained in:
faumaray committed 2026-11-26 21:47:15 +03:00
1 parent 22c8538754
commit 66baae74a0
12 files changed
+3984 -119

No files matched your search

+182 -2
View File
@@ -4,13 +4,79 @@
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
namespace Void::Net
{
enum class NetErrorCode : std::int32_t {
none = 0,
invalid_url = 1,
invalid_argument = 2,
connect_failed = 3,
tls_error = 4,
protocol_error = 5,
timeout = 6,
cancelled = 7,
quota_exceeded = 8,
io_error = 9,
redirect_blocked = 10,
payload_too_large = 11,
headers_too_large = 12
};
[[nodiscard]] inline Void::Result::Error
make_net_error(NetErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case NetErrorCode::none:
kind = ErrorKind::internal;
break;
case NetErrorCode::invalid_url:
case NetErrorCode::invalid_argument:
case NetErrorCode::redirect_blocked:
kind = ErrorKind::invalid_argument;
break;
case NetErrorCode::connect_failed:
case NetErrorCode::io_error:
kind = ErrorKind::io;
break;
case NetErrorCode::tls_error:
case NetErrorCode::protocol_error:
kind = ErrorKind::corrupt;
break;
case NetErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case NetErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case NetErrorCode::quota_exceeded:
case NetErrorCode::payload_too_large:
case NetErrorCode::headers_too_large:
kind = ErrorKind::exhausted;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kNetErrorDomain,
static_cast<std::int32_t>(code)},
sys_err};
}
enum class Method { Get, Post, Put, Delete, Patch, Head, Options };
@@ -62,6 +128,54 @@ namespace Void::Net
}
};
struct HttpClientOptions {
ProxyConfig proxy{};
std::string user_agent{"Void.Net/1.0"};
bool verify_tls{true};
std::string ca_file{};
std::uint64_t max_body_size{64ULL * 1024 * 1024};
int max_redirects{0};
bool allow_insecure_redirects{false};
};
struct TransferProgress {
std::uint64_t bytes_transferred{0};
std::optional<std::uint64_t> total_bytes{};
};
struct DownloadOptions {
std::vector<Header> headers{};
std::chrono::seconds timeout{30};
std::uint64_t max_bytes{0};
std::stop_token stop{};
std::function<void(std::span<const std::byte>)> on_chunk{};
std::function<void(const TransferProgress&)> on_progress{};
};
struct DownloadResult {
std::uint16_t status{0};
std::vector<Header> headers{};
std::uint64_t bytes_written{0};
std::chrono::milliseconds elapsed{0};
[[nodiscard]] bool ok() const noexcept
{
return status >= 200 && status < 300;
}
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const;
};
struct UploadOptions {
Method method{Method::Put};
std::vector<Header> headers{};
std::string content_type{"application/octet-stream"};
std::chrono::seconds timeout{30};
std::uint64_t max_upload_bytes{0};
std::stop_token stop{};
std::function<void(const TransferProgress&)> on_progress{};
};
/// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL.
/// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS.
/// Generic: no application-specific defaults beyond a configurable
@@ -73,6 +187,12 @@ namespace Void::Net
HttpClient() = default;
explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {}
explicit HttpClient(HttpClientOptions options);
/// Preset with TLS peer & hostname certificate verification enabled
/// by default (`verify_tls = true`).
[[nodiscard]] static HttpClient
secure(ProxyConfig proxy = {});
void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); }
[[nodiscard]] const ProxyConfig& proxy() const noexcept
@@ -83,9 +203,33 @@ namespace Void::Net
/// Default User-Agent applied when a request sets none.
void set_user_agent(std::string ua) { m_user_agent = std::move(ua); }
/// Verify TLS peer certificates (default: false, matching common
/// scraping/proxy use; enable for security-sensitive callers).
/// Verify TLS peer certificates (default constructor keeps `false`
/// for 1.x compatibility; `HttpClient::secure()` defaults `true`).
void set_verify_tls(bool on) noexcept { m_verify_tls = on; }
[[nodiscard]] bool verify_tls() const noexcept
{
return m_verify_tls;
}
/// Optional custom PEM CA bundle/certificate file used when
/// `verify_tls` is enabled.
void set_ca_file(std::string ca_file)
{
m_ca_file = std::move(ca_file);
}
[[nodiscard]] const std::string& ca_file() const noexcept
{
return m_ca_file;
}
void set_allow_insecure_redirects(bool allow) noexcept
{
m_allow_insecure_redirects = allow;
}
[[nodiscard]] bool allow_insecure_redirects() const noexcept
{
return m_allow_insecure_redirects;
}
/// Maximum response body size in bytes. 0 means unlimited. Default
/// is 64 MiB (Beast's own default of ~1 MiB is too small for binary
@@ -100,12 +244,34 @@ namespace Void::Net
/// header). Opt-in so callers that inspect redirects keep working.
void set_max_redirects(int n) noexcept { m_max_redirects = n; }
/// Format request method, scrubbed URL, and headers for logs while
/// redacting `Authorization`, `Proxy-Authorization`, `Cookie`, and
/// `X-Api-Key`.
[[nodiscard]] static std::string
format_request_diagnostics(const Request& req);
/// Execute a request. A per-request `Request::proxy` is not modelled;
/// the client-level proxy applies. Returns an Error only on transport
/// failure — a non-2xx HTTP response is a successful Result.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
send(const Request& req) const;
/// Stream response body directly to `destination` without buffering
/// the full payload in memory, enforcing `options.max_bytes` and
/// `options.stop` cancellation.
[[nodiscard]] Void::Result::Result<DownloadResult,
Void::Result::Error>
download_to_file(std::string_view url,
const std::filesystem::path& destination,
const DownloadOptions& options = {}) const;
/// Stream a regular file directly as the HTTP request body without
/// buffering the full file in memory.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
upload_file(std::string_view url,
const std::filesystem::path& source_path,
const UploadOptions& options = {}) const;
// Convenience wrappers.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
get(std::string_view url,
@@ -113,14 +279,28 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post(std::string_view url, std::string body,
std::vector<Header> headers = {}) const;
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
put_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> headers = {},
std::string content_type =
"application/octet-stream") const;
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> headers = {},
std::string content_type =
"application/octet-stream") const;
private:
ProxyConfig m_proxy{};
std::string m_user_agent = "Void.Net/1.0";
bool m_verify_tls = false;
std::string m_ca_file{};
std::uint64_t m_max_body = 64ull * 1024 * 1024;
int m_max_redirects = 0;
bool m_allow_insecure_redirects = false;
};
} // namespace Void::Net
+108
View File
@@ -0,0 +1,108 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
namespace Void::Net
{
struct HttpServerOptions {
std::string bind_host{"127.0.0.1"};
std::uint16_t port{0};
std::size_t max_header_bytes{64ULL * 1024};
std::size_t max_headers{128};
std::uint64_t max_body_bytes{16ULL * 1024 * 1024};
std::uint64_t max_streaming_body_bytes{512ULL * 1024 * 1024};
std::size_t max_concurrent_connections{64};
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
int listen_backlog{128};
};
/// Streaming request body reader passed to streaming HTTP route handlers.
class BodyReader
{
public:
struct State;
explicit BodyReader(State& state) noexcept : m_state(&state) {}
BodyReader(const BodyReader&) = delete;
BodyReader& operator=(const BodyReader&) = delete;
[[nodiscard]] std::optional<std::uint64_t>
content_length() const noexcept;
[[nodiscard]] bool is_chunked() const noexcept;
[[nodiscard]] std::uint64_t bytes_read() const noexcept;
/// Read up to dst.size() decoded body bytes. Returns 0 at EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read_some(std::span<std::byte> dst);
/// Stream the request body atomically to `destination`, enforcing
/// `max_bytes` (or server max_streaming_body_bytes when 0).
[[nodiscard]] Void::Result::Result<std::uint64_t>
read_to_file(const std::filesystem::path& destination,
std::uint64_t max_bytes = 0);
private:
State* m_state{nullptr};
};
using StreamingRouteHandler =
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
/// `Void::Net::Router` and streaming routes via `BodyReader`.
class HttpServer
{
public:
explicit HttpServer(HttpServerOptions options = {});
explicit HttpServer(Router& external_router,
HttpServerOptions options = {});
~HttpServer() noexcept;
HttpServer(HttpServer&&) noexcept;
HttpServer& operator=(HttpServer&&) noexcept;
HttpServer(const HttpServer&) = delete;
HttpServer& operator=(const HttpServer&) = delete;
[[nodiscard]] Router& router() noexcept;
[[nodiscard]] Void::Result::Result<void>
add_route(Method method, std::string pattern,
RouteHandler handler);
[[nodiscard]] Void::Result::Result<void>
add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler);
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
std::chrono::seconds{5}) noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] std::uint16_t bound_port() const noexcept;
[[nodiscard]] std::string bind_address() const;
[[nodiscard]] std::string base_url() const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
} // namespace Void::Net
+10
View File
@@ -30,6 +30,7 @@ namespace Void::Net
std::vector<Header> headers;
std::string body;
RouteParameters parameters;
std::string query{};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
@@ -39,6 +40,12 @@ namespace Void::Net
std::uint16_t status{200};
std::vector<Header> headers;
std::string body;
std::optional<std::filesystem::path> file_body{};
[[nodiscard]] static ServerResponse
from_file(std::filesystem::path path,
std::string content_type = {},
std::uint16_t status = 200);
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
@@ -67,6 +74,9 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<std::optional<ServerResponse>>
dispatch(ServerRequest request) const;
[[nodiscard]] std::vector<Method>
allowed_methods(std::string_view path) const;
[[nodiscard]] std::size_t size() const;
private:
+1009 -108
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+34
View File
@@ -260,6 +260,21 @@ namespace Void::Net
return find_header(headers, name);
}
ServerResponse ServerResponse::from_file(std::filesystem::path path,
std::string content_type,
std::uint16_t status)
{
if (content_type.empty()) {
content_type = std::string{content_type_for(path)};
}
return ServerResponse{
.status = status,
.headers = {Header{"Content-Type", std::move(content_type)}},
.body = {},
.file_body = std::move(path),
};
}
std::optional<std::string_view>
ServerResponse::header(std::string_view name) const noexcept
{
@@ -334,6 +349,25 @@ namespace Void::Net
return std::optional<ServerResponse>{std::move(*response)};
}
std::vector<Method> Router::allowed_methods(std::string_view path) const
{
if (path.empty() || !path.starts_with('/')) {
return {};
}
const auto segments = split_path(path_only(path));
std::vector<Method> methods;
{
std::shared_lock lock{mutex_};
for (const auto& route : routes_) {
if (match_route(route.segments, segments).has_value() &&
std::ranges::find(methods, route.method) == methods.end()) {
methods.push_back(route.method);
}
}
}
return methods;
}
std::size_t Router::size() const
{
std::shared_lock lock{mutex_};
+3
View File
@@ -133,6 +133,9 @@ if(_all_generated)
if(TARGET OpenSSL::Crypto)
target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto)
endif()
if(TARGET OpenSSL::SSL)
target_link_libraries(VoidTests PRIVATE OpenSSL::SSL)
endif()
if(TARGET SQLite3::SQLite3)
target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3)
endif()
+8
View File
@@ -292,6 +292,14 @@ if(_has_fsm)
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_net Net Functional Text)
if(_has_net)
run_consumer(NetOnly "${install_prefix}" "NetOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
# Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation)
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidNetOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Net)
add_executable(void_net_only_consumer main.cpp)
target_link_libraries(void_net_only_consumer PRIVATE Void::Net)
target_compile_features(void_net_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME NetOnlyConsumer COMMAND void_net_only_consumer)
+31
View File
@@ -0,0 +1,31 @@
#include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <string>
int main()
{
Void::Net::HttpServer server;
if (!server
.add_route(Void::Net::Method::Get, "/ping",
[](const Void::Net::ServerRequest&) {
return Void::Result::ok(Void::Net::ServerResponse{
.status = 200, .body = "pong"});
})
.has_value()) {
return 1;
}
if (!server.start().has_value() || server.bound_port() == 0) {
return 2;
}
auto client = Void::Net::HttpClient::secure();
if (!client.verify_tls()) {
return 3;
}
auto resp = client.get(server.base_url() + "/ping");
server.shutdown();
if (!resp.has_value() || resp->status != 200 || resp->body != "pong") {
return 4;
}
return 0;
}
+358 -9
View File
@@ -1,19 +1,34 @@
#include <Void/Crypto/Crypto.hpp>
#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 <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <arpa/inet.h>
#include <atomic>
#include <filesystem>
#include <fstream>
#include <netinet/in.h>
#include <stop_token>
#include <string>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <vector>
namespace
{
// Minimal one-shot HTTP/1.1 server on a chosen loopback port. Accepts one
// connection, reads the request (ignored beyond headers), and replies with
// a fixed 200 body. Runs on a detached helper thread; the test joins it.
// a fixed 200 body.
struct OneShotServer {
int fd = -1;
std::uint16_t port = 0;
@@ -29,7 +44,7 @@ namespace
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = 0; // ephemeral
addr.sin_port = 0;
::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
socklen_t len = sizeof(addr);
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
@@ -59,6 +74,126 @@ namespace
if (fd >= 0) ::close(fd);
}
};
struct GeneratedCert {
std::filesystem::path cert_file;
std::filesystem::path key_file;
};
GeneratedCert generate_self_signed_cert(const std::filesystem::path& dir,
const char* san_value,
const char* tag)
{
using PkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using X509Ptr = std::unique_ptr<X509, decltype(&X509_free)>;
using ExtPtr =
std::unique_ptr<X509_EXTENSION, decltype(&X509_EXTENSION_free)>;
PkeyPtr pkey{EVP_RSA_gen(2048), &EVP_PKEY_free};
Void::Testing::require(static_cast<bool>(pkey));
X509Ptr cert{X509_new(), &X509_free};
Void::Testing::require(static_cast<bool>(cert));
X509_set_version(cert.get(), 2);
ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), 1);
X509_gmtime_adj(X509_get_notBefore(cert.get()), -60);
X509_gmtime_adj(X509_get_notAfter(cert.get()), 3600);
X509_set_pubkey(cert.get(), pkey.get());
X509_NAME* name = X509_get_subject_name(cert.get());
X509_NAME_add_entry_by_txt(
name, "CN", MBSTRING_ASC,
reinterpret_cast<const unsigned char*>("127.0.0.1"), -1, -1, 0);
X509_set_issuer_name(cert.get(), name);
X509V3_CTX ctx{};
X509V3_set_ctx_nodb(&ctx);
X509V3_set_ctx(&ctx, cert.get(), cert.get(), nullptr, nullptr, 0);
ExtPtr ext{X509V3_EXT_conf_nid(nullptr, &ctx, NID_subject_alt_name,
const_cast<char*>(san_value)),
&X509_EXTENSION_free};
Void::Testing::require(static_cast<bool>(ext));
Void::Testing::require(X509_add_ext(cert.get(), ext.get(), -1) == 1);
Void::Testing::require(
X509_sign(cert.get(), pkey.get(), EVP_sha256()) > 0);
const auto cert_path = dir / (std::string{"cert_"} + tag + ".pem");
const auto key_path = dir / (std::string{"key_"} + tag + ".pem");
FILE* cf = std::fopen(cert_path.c_str(), "wb");
Void::Testing::require(cf != nullptr);
Void::Testing::require(PEM_write_X509(cf, cert.get()) == 1);
std::fclose(cf);
FILE* kf = std::fopen(key_path.c_str(), "wb");
Void::Testing::require(kf != nullptr);
Void::Testing::require(PEM_write_PrivateKey(kf, pkey.get(), nullptr,
nullptr, 0, nullptr,
nullptr) == 1);
std::fclose(kf);
return GeneratedCert{cert_path, key_path};
}
struct OneShotTlsServer {
int fd = -1;
std::uint16_t port = 0;
SSL_CTX* ctx = nullptr;
std::thread worker;
OneShotTlsServer(const GeneratedCert& creds, std::string body)
{
ctx = SSL_CTX_new(TLS_server_method());
Void::Testing::require(ctx != nullptr);
Void::Testing::require(
SSL_CTX_use_certificate_file(ctx, creds.cert_file.c_str(),
SSL_FILETYPE_PEM) == 1);
Void::Testing::require(
SSL_CTX_use_PrivateKey_file(ctx, creds.key_file.c_str(),
SSL_FILETYPE_PEM) == 1);
fd = ::socket(AF_INET, SOCK_STREAM, 0);
int yes = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = 0;
Void::Testing::require(
::bind(fd, reinterpret_cast<sockaddr*>(&addr),
sizeof(addr)) == 0);
socklen_t len = sizeof(addr);
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
port = ntohs(addr.sin_port);
Void::Testing::require(::listen(fd, 1) == 0);
worker = std::thread([this, body = std::move(body)]() {
const int conn = ::accept(fd, nullptr, nullptr);
if (conn < 0) return;
SSL* ssl = SSL_new(ctx);
SSL_set_fd(ssl, conn);
if (SSL_accept(ssl) == 1) {
char buf[2048];
(void)SSL_read(ssl, buf, sizeof(buf));
const std::string resp =
"HTTP/1.1 200 OK\r\nContent-Length: " +
std::to_string(body.size()) +
"\r\nConnection: close\r\n\r\n" + body;
(void)SSL_write(ssl, resp.data(),
static_cast<int>(resp.size()));
SSL_shutdown(ssl);
}
SSL_free(ssl);
::close(conn);
});
}
~OneShotTlsServer()
{
if (worker.joinable()) worker.join();
if (fd >= 0) ::close(fd);
if (ctx != nullptr) SSL_CTX_free(ctx);
}
};
} // namespace
Void::Testing::Test http_client_get_localhost_round_trip()
@@ -74,7 +209,6 @@ Void::Testing::Test http_client_get_localhost_round_trip()
Void::Testing::expect_eq(resp->status, static_cast<std::uint16_t>(200));
Void::Testing::expect_eq(resp->body, std::string{"hello from void"});
Void::Testing::expect(resp->ok());
// Request line reached the server with the right target.
Void::Testing::expect(server.last_request.find("GET /ping HTTP/1.1") !=
std::string::npos);
}
@@ -106,16 +240,12 @@ Void::Testing::Test http_client_invalid_url_is_error()
Void::Testing::Test http_client_connection_refused_is_error()
{
Void::Net::HttpClient client;
// Port 1 on loopback: nothing listening.
const auto resp = client.get("http://127.0.0.1:1/");
Void::Testing::expect(!resp.has_value());
}
Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
{
// A server that accepts and then never responds. Without an enforced
// Request::timeout the sync read blocks forever (Asio's sync emulation
// poll()s on would-block with no deadline).
struct StallServer {
int fd = -1;
std::uint16_t port = 0;
@@ -138,7 +268,6 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
::listen(fd, 1);
worker = std::thread([this] {
conn = ::accept(fd, nullptr, nullptr);
// Never write a byte; hold the connection open.
});
}
@@ -161,6 +290,226 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
const auto elapsed = std::chrono::steady_clock::now() - start;
Void::Testing::expect(!resp.has_value());
// Well under the old "forever": the deadline tripped around 1s.
Void::Testing::expect(elapsed < std::chrono::seconds{5});
}
Void::Testing::Test http_client_streaming_upload_download_quota_and_cancel()
{
Void::FileSystem::TempDir tmp{"void_http_stream_"};
const auto upload_src = tmp / "upload_4mib.bin";
const auto server_stored = tmp / "server_copy.bin";
const auto dl_dst = tmp / "downloaded.bin";
const auto dl_quota_fail = tmp / "should_not_exist.bin";
// Generate deterministic 4 MiB test file.
constexpr std::size_t kSize = 4ULL * 1024ULL * 1024ULL;
std::string expected_data(kSize, '\0');
for (std::size_t i = 0; i < kSize; ++i) {
expected_data[i] = static_cast<char>((i * 131U) & 0xFFU);
}
{
std::ofstream out{upload_src, std::ios::binary | std::ios::trunc};
Void::Testing::require(out.is_open());
out.write(expected_data.data(),
static_cast<std::streamsize>(expected_data.size()));
out.close();
}
auto expected_digest = Void::Crypto::sha256_file(upload_src);
Void::Testing::require(expected_digest.has_value());
Void::Net::HttpServer server;
Void::Testing::require(
server
.add_streaming_route(
Void::Net::Method::Put, "/blob",
[&](const Void::Net::ServerRequest&,
Void::Net::BodyReader& reader) -> Void::Net::RouteResult {
auto n = reader.read_to_file(server_stored);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
return Void::Net::ServerResponse{
.status = 201, .body = std::to_string(*n)};
})
.has_value());
Void::Testing::require(
server
.add_route(Void::Net::Method::Get, "/blob",
[&](const Void::Net::ServerRequest&) {
return Void::Result::ok(
Void::Net::ServerResponse::from_file(
server_stored));
})
.has_value());
std::atomic<bool> slow_entered{false};
std::atomic<bool> release_hang{false};
Void::Testing::require(
server
.add_route(Void::Net::Method::Get, "/hang",
[&](const Void::Net::ServerRequest&) {
slow_entered.store(true, std::memory_order_release);
for (int i = 0;
i < 600 &&
!release_hang.load(std::memory_order_acquire);
++i) {
std::this_thread::sleep_for(
std::chrono::milliseconds{5});
}
return Void::Result::ok(
Void::Net::ServerResponse{.status = 200,
.body = "late"});
})
.has_value());
Void::Testing::require(server.start().has_value());
const std::string base = server.base_url();
auto client = Void::Net::HttpClient::secure();
Void::Testing::expect(client.verify_tls());
// 1. Streaming 4 MiB upload with progress callback.
std::uint64_t last_up = 0;
std::size_t up_callbacks = 0;
Void::Net::UploadOptions up_opts;
up_opts.on_progress = [&](const Void::Net::TransferProgress& p) {
Void::Testing::expect(p.bytes_transferred >= last_up);
last_up = p.bytes_transferred;
++up_callbacks;
};
auto up_res = client.upload_file(base + "/blob", upload_src, up_opts);
Void::Testing::require(up_res.has_value());
Void::Testing::expect_eq(up_res->status, std::uint16_t{201});
Void::Testing::expect_eq(last_up, static_cast<std::uint64_t>(kSize));
Void::Testing::expect(up_callbacks > 1U);
// 2. Streaming 4 MiB download with on_chunk incremental SHA-256 verification.
auto chunk_hasher =
Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
Void::Testing::require(chunk_hasher.has_value());
std::uint64_t last_dn = 0;
Void::Net::DownloadOptions dl_opts;
dl_opts.max_bytes = kSize;
dl_opts.on_chunk = [&](std::span<const std::byte> data) {
Void::Testing::require(chunk_hasher->update(data).has_value());
};
dl_opts.on_progress = [&](const Void::Net::TransferProgress& p) {
Void::Testing::expect(p.bytes_transferred >= last_dn);
last_dn = p.bytes_transferred;
};
auto dl_res = client.download_to_file(base + "/blob", dl_dst, dl_opts);
Void::Testing::require(dl_res.has_value());
Void::Testing::expect_eq(dl_res->status, std::uint16_t{200});
Void::Testing::expect_eq(dl_res->bytes_written,
static_cast<std::uint64_t>(kSize));
auto streamed_digest = chunk_hasher->finalize();
Void::Testing::require(streamed_digest.has_value());
Void::Testing::expect_eq(*streamed_digest, *expected_digest);
auto file_digest = Void::Crypto::sha256_file(dl_dst);
Void::Testing::require(file_digest.has_value());
Void::Testing::expect_eq(*file_digest, *expected_digest);
// 3. Quota overflow aborts cleanly with quota_exceeded and leaves no file.
Void::Net::DownloadOptions tight_opts;
tight_opts.max_bytes = 1024U * 1024U; // < 4 MiB
auto quota_err =
client.download_to_file(base + "/blob", dl_quota_fail, tight_opts);
Void::Testing::require(!quota_err.has_value());
Void::Testing::expect_eq(
quota_err.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::quota_exceeded));
Void::Testing::expect(!std::filesystem::exists(dl_quota_fail));
// 4. std::stop_token cancels an in-flight stalled download promptly.
{
std::stop_source stop_src;
Void::Net::DownloadOptions cancel_opts;
cancel_opts.stop = stop_src.get_token();
std::jthread killer([&]() {
while (!slow_entered.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{2});
}
std::this_thread::sleep_for(std::chrono::milliseconds{30});
stop_src.request_stop();
});
const auto t0 = std::chrono::steady_clock::now();
auto c_res = client.download_to_file(
base + "/hang", tmp / "cancelled.bin", cancel_opts);
const auto elapsed = std::chrono::steady_clock::now() - t0;
killer.join();
Void::Testing::require(!c_res.has_value());
Void::Testing::expect_eq(
c_res.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::cancelled));
Void::Testing::expect(elapsed < std::chrono::seconds{2});
Void::Testing::expect(!std::filesystem::exists(tmp / "cancelled.bin"));
release_hang.store(true, std::memory_order_release);
}
server.shutdown();
}
Void::Testing::Test http_client_secure_tls_verification_and_redaction()
{
// 1. Authorization & secret header redaction in diagnostics.
Void::Net::Request req;
req.method = Void::Net::Method::Get;
req.url = "https://user:superpass@registry.example/v1/pkg";
req.headers = {
{"Authorization", "Bearer top-secret-token-value"},
{"Proxy-Authorization", "Basic dXNlcjpwYXNz"},
{"Cookie", "session=secret-cookie"},
{"Accept", "application/json"},
};
const std::string diag =
Void::Net::HttpClient::format_request_diagnostics(req);
Void::Testing::expect(diag.find("top-secret-token-value") ==
std::string::npos);
Void::Testing::expect(diag.find("dXNlcjpwYXNz") == std::string::npos);
Void::Testing::expect(diag.find("secret-cookie") == std::string::npos);
Void::Testing::expect(diag.find("superpass") == std::string::npos);
Void::Testing::expect(diag.find("<redacted>") != std::string::npos);
Void::Testing::expect(diag.find("application/json") != std::string::npos);
// 2. Local TLS server verification checks.
Void::FileSystem::TempDir tmp{"void_http_tls_"};
const auto good_cert =
generate_self_signed_cert(tmp.path(), "IP:127.0.0.1", "good");
const auto bad_san_cert =
generate_self_signed_cert(tmp.path(), "DNS:wrong.invalid", "badsan");
// a) Untrusted self-signed cert is rejected by default on secure().
{
OneShotTlsServer tls_srv{good_cert, "tls-secret"};
auto client = Void::Net::HttpClient::secure();
auto r = client.get(
"https://127.0.0.1:" + std::to_string(tls_srv.port) + "/ok");
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::tls_error));
}
// b) Trusted CA + matching IP:127.0.0.1 SAN succeeds.
{
OneShotTlsServer tls_srv{good_cert, "tls-verified-ok"};
auto client = Void::Net::HttpClient::secure();
client.set_ca_file(good_cert.cert_file.string());
auto r = client.get(
"https://127.0.0.1:" + std::to_string(tls_srv.port) + "/ok");
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(r->status, std::uint16_t{200});
Void::Testing::expect_eq(r->body, std::string{"tls-verified-ok"});
}
// c) Trusted CA + mismatched SAN (DNS:wrong.invalid != 127.0.0.1) fails.
{
OneShotTlsServer tls_srv{bad_san_cert, "should-fail"};
auto client = Void::Net::HttpClient::secure();
client.set_ca_file(bad_san_cert.cert_file.string());
auto r = client.get(
"https://127.0.0.1:" + std::to_string(tls_srv.port) + "/bad");
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::tls_error));
}
}
+393
View File
@@ -0,0 +1,393 @@
#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"});
}
}