Net: add TLS client stream and SMTP submission (closes #48)

This commit is contained in:
faumaray committed 2026-12-03 16:37:13 +03:00
1 parent 72148da7b2
commit 44686a4444
8 files changed
+2787 -1

No files matched your search

+472
View File
@@ -0,0 +1,472 @@
#include <Void/Net/Http.hpp>
#include <Void/Net/Smtp.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Text/Base64.hpp>
#include "../../helpers/NetTlsSupport.hpp"
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace
{
using namespace std::chrono_literals;
using Void::Testing::NetSupport::GeneratedCert;
using Void::Testing::NetSupport::LoopbackListener;
using Void::Testing::NetSupport::ScratchDir;
enum class SmtpMode {
implicit_tls,
starttls,
starttls_rejected,
no_starttls,
auth_fail,
stall,
};
struct FakeSmtpServer {
LoopbackListener listener;
SSL_CTX* ctx{nullptr};
std::thread worker;
std::vector<std::string> commands;
std::string message_data;
bool starttls_attempted{false};
FakeSmtpServer(const GeneratedCert& cert, SmtpMode mode)
{
ctx = SSL_CTX_new(TLS_server_method());
Void::Testing::require(ctx != nullptr);
Void::Testing::require(
SSL_CTX_use_certificate_file(
ctx, cert.cert_file.c_str(), SSL_FILETYPE_PEM) == 1);
Void::Testing::require(
SSL_CTX_use_PrivateKey_file(
ctx, cert.key_file.c_str(), SSL_FILETYPE_PEM) == 1);
worker = std::thread([this, mode] { serve(mode); });
}
FakeSmtpServer(const FakeSmtpServer&) = delete;
FakeSmtpServer& operator=(const FakeSmtpServer&) = delete;
void join()
{
if (worker.joinable()) {
worker.join();
}
}
~FakeSmtpServer()
{
join();
if (ctx != nullptr) {
SSL_CTX_free(ctx);
}
}
void serve(SmtpMode mode)
{
const int connection = listener.accept_one();
if (connection < 0) {
return;
}
if (mode == SmtpMode::stall) {
char byte = 0;
while (::recv(connection, &byte, 1, 0) > 0) {
}
::close(connection);
return;
}
SSL* ssl = nullptr;
bool tls = false;
if (mode == SmtpMode::implicit_tls ||
mode == SmtpMode::auth_fail) {
ssl = SSL_new(ctx);
SSL_set_fd(ssl, connection);
const int accepted = SSL_accept(ssl);
if (accepted != 1) {
SSL_free(ssl);
::close(connection);
return;
}
tls = true;
}
std::string pending;
const auto send = [&](std::string_view text) {
if (tls) {
(void)SSL_write(ssl, text.data(),
static_cast<int>(text.size()));
} else {
(void)Void::Testing::NetSupport::write_all(
connection, text);
}
};
const auto read_line = [&]() -> std::optional<std::string> {
for (;;) {
const std::size_t end = pending.find("\r\n");
if (end != std::string::npos) {
std::string line = pending.substr(0, end);
pending.erase(0, end + 2);
return line;
}
char buffer[1024];
const int count =
tls ? SSL_read(ssl, buffer,
static_cast<int>(sizeof(buffer)))
: static_cast<int>(::recv(
connection, buffer, sizeof(buffer), 0));
if (count <= 0) {
return std::nullopt;
}
pending.append(buffer,
static_cast<std::size_t>(count));
}
};
send("220 fake ESMTP\r\n");
for (;;) {
auto line = read_line();
if (!line.has_value()) {
break;
}
commands.push_back(*line);
if (line->starts_with("EHLO")) {
if (!tls && (mode == SmtpMode::starttls ||
mode == SmtpMode::starttls_rejected)) {
send("250-fake\r\n250-STARTTLS\r\n"
"250 SIZE 1048576\r\n");
} else {
send("250-fake\r\n250-AUTH PLAIN\r\n"
"250 SIZE 1048576\r\n");
}
} else if (line->starts_with("STARTTLS")) {
starttls_attempted = true;
if (mode == SmtpMode::starttls_rejected) {
send("454 TLS not available\r\n");
} else {
send("220 go ahead\r\n");
ssl = SSL_new(ctx);
SSL_set_fd(ssl, connection);
if (SSL_accept(ssl) != 1) {
break;
}
tls = true;
}
} else if (line->starts_with("AUTH ")) {
if (mode == SmtpMode::auth_fail) {
send("535 bad credentials\r\n");
} else {
send("235 authenticated\r\n");
}
} else if (line->starts_with("MAIL")) {
send("250 ok\r\n");
} else if (line->starts_with("RCPT")) {
send("250 ok\r\n");
} else if (line->starts_with("DATA")) {
send("354 send it\r\n");
std::string data;
for (;;) {
auto body_line = read_line();
if (!body_line.has_value()) {
break;
}
if (*body_line == ".") {
break;
}
if (body_line->starts_with("..")) {
data += body_line->substr(1);
} else {
data += *body_line;
}
data += "\r\n";
}
message_data = std::move(data);
send("250 queued\r\n");
} else if (line->starts_with("QUIT")) {
send("221 bye\r\n");
break;
} else {
send("250 ok\r\n");
}
}
if (ssl != nullptr) {
SSL_shutdown(ssl);
SSL_free(ssl);
}
::close(connection);
}
};
[[nodiscard]] Void::Net::SmtpOptions
make_options(std::uint16_t port, std::string ca_file = {})
{
Void::Net::SmtpOptions options;
options.host = "127.0.0.1";
options.port = port;
options.ca_file = std::move(ca_file);
options.connect_timeout = 2s;
options.io_timeout = 5s;
return options;
}
[[nodiscard]] std::string expected_auth_token()
{
std::string payload;
payload.push_back('\0');
payload += "user";
payload.push_back('\0');
payload += "pass";
return Void::Encoding::Base64::encode(payload);
}
[[nodiscard]] bool contains_command(
const std::vector<std::string>& commands, std::string_view prefix)
{
for (const auto& command : commands) {
if (command.starts_with(prefix)) {
return true;
}
}
return false;
}
} // namespace
Void::Testing::Test smtp_starttls_submission_authenticates_and_dot_stuffs()
{
ScratchDir scratch{"void_smtp_starttls_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtp");
FakeSmtpServer server{cert, SmtpMode::starttls};
auto options = make_options(server.listener.port, cert.cert_file.string());
options.credentials = Void::Net::SmtpCredentials{.username = "user",
.password = "pass"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(client.has_value());
Void::Testing::expect(client->secure());
Void::Net::SmtpMessage message;
message.from = "sender@example.test";
message.recipients = {"one@example.test", "two@example.test"};
message.data = "Subject: hi\r\n\r\n.first line\nsecond line\r\nthird";
auto sent = client->send(message);
Void::Testing::require(sent.has_value());
Void::Testing::require(client->quit().has_value());
server.join();
Void::Testing::expect(server.starttls_attempted);
Void::Testing::expect(contains_command(
server.commands, "AUTH PLAIN " + expected_auth_token()));
Void::Testing::expect(contains_command(server.commands,
"MAIL FROM:<sender@example.test>"));
Void::Testing::expect(contains_command(
server.commands, "RCPT TO:<one@example.test>"));
Void::Testing::expect(contains_command(
server.commands, "RCPT TO:<two@example.test>"));
Void::Testing::expect(contains_command(server.commands, "DATA"));
Void::Testing::expect_eq(
server.message_data,
std::string{"Subject: hi\r\n\r\n.first line\r\nsecond line\r\n"
"third\r\n"});
}
Void::Testing::Test smtp_implicit_tls_submission()
{
ScratchDir scratch{"void_smtp_implicit_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtpimp");
FakeSmtpServer server{cert, SmtpMode::implicit_tls};
auto options = make_options(server.listener.port, cert.cert_file.string());
options.security = Void::Net::SmtpSecurity::implicit_tls;
options.credentials = Void::Net::SmtpCredentials{.username = "user",
.password = "pass"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(client.has_value());
Void::Testing::expect(client->secure());
Void::Net::SmtpMessage message;
message.from = "a@example.test";
message.recipients = {"b@example.test"};
message.data = "hello\r\n";
Void::Testing::require(client->send(message).has_value());
Void::Testing::require(client->quit().has_value());
server.join();
Void::Testing::expect(contains_command(
server.commands, "AUTH PLAIN " + expected_auth_token()));
Void::Testing::expect_eq(server.message_data,
std::string{"hello\r\n"});
}
Void::Testing::Test smtp_never_sends_credentials_without_starttls()
{
ScratchDir scratch{"void_smtp_downgrade_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtpdg");
// Server does not advertise STARTTLS: the client must fail before AUTH.
{
FakeSmtpServer server{cert, SmtpMode::no_starttls};
auto options =
make_options(server.listener.port, cert.cert_file.string());
options.credentials = Void::Net::SmtpCredentials{
.username = "user", .password = "pass"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::tls_required));
server.join();
Void::Testing::expect(
!contains_command(server.commands, "AUTH"));
Void::Testing::expect(
!contains_command(server.commands, "MAIL"));
}
// Server advertises STARTTLS but rejects it: no credentials either.
{
FakeSmtpServer server{cert, SmtpMode::starttls_rejected};
auto options =
make_options(server.listener.port, cert.cert_file.string());
options.credentials = Void::Net::SmtpCredentials{
.username = "user", .password = "pass"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::smtp_rejected));
server.join();
Void::Testing::expect(server.starttls_attempted);
Void::Testing::expect(
!contains_command(server.commands, "AUTH"));
}
}
Void::Testing::Test smtp_rejects_oversized_messages()
{
ScratchDir scratch{"void_smtp_oversize_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtpbig");
// Client-side bound.
{
FakeSmtpServer server{cert, SmtpMode::implicit_tls};
auto options =
make_options(server.listener.port, cert.cert_file.string());
options.security = Void::Net::SmtpSecurity::implicit_tls;
options.limits.max_message_bytes = 16;
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(client.has_value());
Void::Net::SmtpMessage message;
message.from = "a@example.test";
message.recipients = {"b@example.test"};
message.data = std::string(17, 'x');
auto sent = client->send(message);
Void::Testing::require(!sent.has_value());
Void::Testing::expect_eq(
sent.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::payload_too_large));
client->close();
server.join();
Void::Testing::expect(
!contains_command(server.commands, "MAIL"));
}
// Server SIZE capability bound (server advertises SIZE 1048576).
{
FakeSmtpServer server{cert, SmtpMode::implicit_tls};
auto options =
make_options(server.listener.port, cert.cert_file.string());
options.security = Void::Net::SmtpSecurity::implicit_tls;
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(client.has_value());
Void::Net::SmtpMessage message;
message.from = "a@example.test";
message.recipients = {"b@example.test"};
message.data = std::string(1048577, 'x');
auto sent = client->send(message);
Void::Testing::require(!sent.has_value());
Void::Testing::expect_eq(
sent.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::payload_too_large));
client->close();
server.join();
}
}
Void::Testing::Test smtp_auth_failure_is_reported()
{
ScratchDir scratch{"void_smtp_auth_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtpauth");
FakeSmtpServer server{cert, SmtpMode::auth_fail};
auto options = make_options(server.listener.port, cert.cert_file.string());
options.security = Void::Net::SmtpSecurity::implicit_tls;
options.credentials = Void::Net::SmtpCredentials{.username = "user",
.password = "wrong"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::auth_failed));
server.join();
}
Void::Testing::Test smtp_trust_and_cancellation()
{
ScratchDir scratch{"void_smtp_trust_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtptrust");
// Untrusted certificate: TLS failure, never plaintext fallback.
{
FakeSmtpServer server{cert, SmtpMode::implicit_tls};
auto options = make_options(server.listener.port);
options.security = Void::Net::SmtpSecurity::implicit_tls;
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::tls_error));
server.join();
}
// Cancellation while waiting for the greeting.
{
FakeSmtpServer server{cert, SmtpMode::stall};
auto options = make_options(server.listener.port);
std::stop_source stop;
options.stop = stop.get_token();
std::jthread killer([&stop] {
std::this_thread::sleep_for(50ms);
stop.request_stop();
});
const auto start = std::chrono::steady_clock::now();
auto client = Void::Net::SmtpClient::connect(options);
const auto elapsed = std::chrono::steady_clock::now() - start;
killer.join();
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::cancelled));
Void::Testing::expect(elapsed < 3s);
server.join();
}
}