feat(net): implement VL-004 HttpServer and VL-005 streaming HttpClient with secure TLS
This commit is contained in:
1 parent
22c8538754
commit
66baae74a0
12 files changed
+3984
-119
No files matched your search
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user