Files
Library/tests/helpers/NetTlsSupport.hpp
T

190 lines
5.3 KiB
C++

#pragma once
// Shared test-only support for loopback TLS/SMTP fixtures.
#include <Void/Testing/Assert.hpp>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>
#include <filesystem>
#include <memory>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
namespace Void::Testing::NetSupport
{
inline std::filesystem::path make_scratch_dir(std::string_view prefix)
{
static unsigned counter = 0;
auto path = std::filesystem::temp_directory_path() /
(std::string{prefix} + std::to_string(::getpid()) + "_" +
std::to_string(counter++));
std::filesystem::create_directories(path);
return path;
}
struct ScratchDir {
std::filesystem::path path;
explicit ScratchDir(std::string_view prefix)
: path(make_scratch_dir(prefix))
{
}
ScratchDir(const ScratchDir&) = delete;
ScratchDir& operator=(const ScratchDir&) = delete;
~ScratchDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
struct GeneratedCert {
std::filesystem::path cert_file;
std::filesystem::path key_file;
};
inline 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};
}
/// Bound TCP listener on 127.0.0.1 with an ephemeral port.
struct LoopbackListener {
int fd{-1};
std::uint16_t port{0};
LoopbackListener()
{
fd = ::socket(AF_INET, SOCK_STREAM, 0);
Void::Testing::require(fd >= 0);
int yes = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(yes));
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
address.sin_port = 0;
Void::Testing::require(
::bind(fd, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == 0);
socklen_t length = sizeof(address);
Void::Testing::require(
::getsockname(fd, reinterpret_cast<sockaddr*>(&address),
&length) == 0);
port = ntohs(address.sin_port);
Void::Testing::require(::listen(fd, 4) == 0);
}
LoopbackListener(const LoopbackListener&) = delete;
LoopbackListener& operator=(const LoopbackListener&) = delete;
~LoopbackListener()
{
if (fd >= 0) {
::close(fd);
}
}
[[nodiscard]] int accept_one() const
{
return ::accept(fd, nullptr, nullptr);
}
};
inline bool write_all(int fd, std::string_view data)
{
while (!data.empty()) {
const ssize_t written =
::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
if (written <= 0) {
if (written < 0 && errno == EINTR) {
continue;
}
return false;
}
data.remove_prefix(static_cast<std::size_t>(written));
}
return true;
}
/// Read until `delimiter` is found or `max_bytes` is exceeded.
inline std::string read_until(int fd, std::string_view delimiter,
std::size_t max_bytes)
{
std::string buffer;
while (buffer.find(delimiter) == std::string::npos &&
buffer.size() <= max_bytes) {
char chunk[1024];
const ssize_t count = ::recv(fd, chunk, sizeof(chunk), 0);
if (count <= 0) {
break;
}
buffer.append(chunk, static_cast<std::size_t>(count));
}
return buffer;
}
} // namespace Void::Testing::NetSupport