1 parent
fa30098129
commit
8583a479dd
11 files changed
+1763
-129
No files matched your search
@@ -52,6 +52,18 @@ function(void_fetch_dependency DEP_NAME)
|
||||
endif()
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(DEP_NAME STREQUAL "Sodium")
|
||||
if(TARGET Sodium::Sodium)
|
||||
return()
|
||||
endif()
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
|
||||
add_library(Sodium::Sodium INTERFACE IMPORTED)
|
||||
set_property(TARGET Sodium::Sodium PROPERTY
|
||||
INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM)
|
||||
return()
|
||||
endif()
|
||||
# FIXME: Add if needed external
|
||||
# if(DEP_NAME STREQUAL "glaze")
|
||||
# if(NOT glaze_POPULATED)
|
||||
|
||||
@@ -5,7 +5,15 @@ include(CMakeFindDependencyMacro)
|
||||
set(_void_external_deps "@VOID_EXTERNAL_DEPS_LIST@")
|
||||
foreach(dep IN LISTS _void_external_deps)
|
||||
if(dep STREQUAL "Boost")
|
||||
find_dependency(Boost REQUIRED COMPONENTS stacktrace_backtrace)
|
||||
find_dependency(Boost REQUIRED COMPONENTS stacktrace_backtrace url)
|
||||
elseif(dep STREQUAL "Sodium")
|
||||
find_dependency(PkgConfig REQUIRED)
|
||||
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
|
||||
if(NOT TARGET Sodium::Sodium)
|
||||
add_library(Sodium::Sodium INTERFACE IMPORTED)
|
||||
set_property(TARGET Sodium::Sodium PROPERTY
|
||||
INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM)
|
||||
endif()
|
||||
elseif(NOT TARGET ${dep})
|
||||
find_dependency(${dep})
|
||||
endif()
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <shared_mutex>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
|
||||
using RouteParameters = std::map<std::string, std::string, std::less<>>;
|
||||
|
||||
struct ServerRequest {
|
||||
Method method{Method::Get};
|
||||
std::string path;
|
||||
std::vector<Header> headers;
|
||||
std::string body;
|
||||
RouteParameters parameters;
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const noexcept;
|
||||
};
|
||||
|
||||
struct ServerResponse {
|
||||
std::uint16_t status{200};
|
||||
std::vector<Header> headers;
|
||||
std::string body;
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const noexcept;
|
||||
};
|
||||
|
||||
using RouteResult = Void::Result::Result<ServerResponse>;
|
||||
using RouteHandler = std::function<RouteResult(const ServerRequest&)>;
|
||||
|
||||
/// A transport-neutral method/path router. Patterns support exact segments,
|
||||
/// `:name` parameters, and a final `*name` catch-all. Route registration
|
||||
/// and dispatch are thread-safe; handlers run without the router lock held.
|
||||
class Router
|
||||
{
|
||||
public:
|
||||
|
||||
Router() = default;
|
||||
Router(const Router&) = delete;
|
||||
Router& operator=(const Router&) = delete;
|
||||
Router(Router&&) = delete;
|
||||
Router& operator=(Router&&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
add(Method method, std::string pattern, RouteHandler handler);
|
||||
|
||||
/// A successful empty optional means that no route matched.
|
||||
[[nodiscard]] Void::Result::Result<std::optional<ServerResponse>>
|
||||
dispatch(ServerRequest request) const;
|
||||
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
|
||||
private:
|
||||
|
||||
struct Route {
|
||||
Method method;
|
||||
std::string pattern;
|
||||
std::vector<std::string> segments;
|
||||
RouteHandler handler;
|
||||
};
|
||||
|
||||
mutable std::shared_mutex mutex_;
|
||||
std::vector<Route> routes_;
|
||||
};
|
||||
|
||||
struct StaticFile {
|
||||
std::filesystem::path path;
|
||||
std::string_view content_type;
|
||||
std::uintmax_t size{};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
content_type_for(const std::filesystem::path& path);
|
||||
|
||||
/// Resolves URL paths beneath one canonical document root. Percent-decoded
|
||||
/// traversal, backslashes, control characters, and symlink escapes are
|
||||
/// rejected. Missing files are represented by a successful empty optional.
|
||||
class StaticFileResolver
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<StaticFileResolver>
|
||||
create(std::filesystem::path root,
|
||||
std::string index_file = "index.html");
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<StaticFile>>
|
||||
resolve(std::string_view request_path) const;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& root() const noexcept
|
||||
{
|
||||
return root_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
StaticFileResolver(std::filesystem::path root,
|
||||
std::string index_file)
|
||||
: root_(std::move(root)), index_file_(std::move(index_file))
|
||||
{
|
||||
}
|
||||
|
||||
std::filesystem::path root_;
|
||||
std::string index_file_;
|
||||
};
|
||||
|
||||
struct WebSocketConnectionId {
|
||||
std::uint64_t value{};
|
||||
auto operator<=>(const WebSocketConnectionId&) const = default;
|
||||
};
|
||||
|
||||
struct WebSocketClose {
|
||||
std::uint16_t code{1000};
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
/// Implemented by the concrete WebSocket transport owned by an HTTP server.
|
||||
class WebSocketConnection
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~WebSocketConnection() = default;
|
||||
[[nodiscard]] virtual WebSocketConnectionId id() const noexcept = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
send_text(std::string_view message) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
send_binary(std::span<const std::byte> message) = 0;
|
||||
virtual void close(const WebSocketClose& close) noexcept = 0;
|
||||
};
|
||||
|
||||
struct WebSocketEvents {
|
||||
std::function<void(const std::shared_ptr<WebSocketConnection>&)>
|
||||
opened;
|
||||
std::function<void(const std::shared_ptr<WebSocketConnection>&,
|
||||
std::string_view)>
|
||||
text;
|
||||
std::function<void(const std::shared_ptr<WebSocketConnection>&,
|
||||
std::span<const std::byte>)>
|
||||
binary;
|
||||
std::function<void(WebSocketConnectionId, const WebSocketClose&)>
|
||||
closed;
|
||||
std::function<void(WebSocketConnectionId,
|
||||
const Void::Result::Error&)>
|
||||
error;
|
||||
};
|
||||
|
||||
/// Thread-safe connection ownership and lifecycle dispatch. All callbacks
|
||||
/// and transport close operations run without the registry lock held. Call
|
||||
/// shutdown() for close callbacks; destruction performs a best-effort close
|
||||
/// without invoking user code.
|
||||
class WebSocketSessions
|
||||
{
|
||||
public:
|
||||
|
||||
WebSocketSessions() = default;
|
||||
explicit WebSocketSessions(WebSocketEvents events)
|
||||
: events_(std::move(events))
|
||||
{
|
||||
}
|
||||
~WebSocketSessions() noexcept;
|
||||
|
||||
WebSocketSessions(const WebSocketSessions&) = delete;
|
||||
WebSocketSessions& operator=(const WebSocketSessions&) = delete;
|
||||
WebSocketSessions(WebSocketSessions&&) = delete;
|
||||
WebSocketSessions& operator=(WebSocketSessions&&) = delete;
|
||||
|
||||
void set_events(WebSocketEvents events);
|
||||
|
||||
/// Register a transport connection and emit `opened`. Returns false
|
||||
/// for a duplicate connection ID.
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
open(std::shared_ptr<WebSocketConnection> connection);
|
||||
|
||||
[[nodiscard]] std::shared_ptr<WebSocketConnection>
|
||||
find(WebSocketConnectionId id) const;
|
||||
[[nodiscard]] bool contains(WebSocketConnectionId id) const;
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
|
||||
[[nodiscard]] bool receive_text(WebSocketConnectionId id,
|
||||
std::string_view message) const;
|
||||
[[nodiscard]] bool
|
||||
receive_binary(WebSocketConnectionId id,
|
||||
std::span<const std::byte> message) const;
|
||||
[[nodiscard]] bool fail(WebSocketConnectionId id,
|
||||
const Void::Result::Error& error) const;
|
||||
|
||||
/// Record a transport-initiated close without closing it again.
|
||||
[[nodiscard]] bool disconnect(WebSocketConnectionId id,
|
||||
WebSocketClose close = {});
|
||||
|
||||
/// Remove and actively close one connection.
|
||||
[[nodiscard]] bool close(WebSocketConnectionId id,
|
||||
WebSocketClose close = {});
|
||||
|
||||
/// Remove and actively close every connection. Returns the count.
|
||||
std::size_t shutdown(WebSocketClose close = {1001,
|
||||
"server shutdown"});
|
||||
|
||||
private:
|
||||
|
||||
using Connections = std::map<WebSocketConnectionId,
|
||||
std::shared_ptr<WebSocketConnection>>;
|
||||
|
||||
[[nodiscard]] bool remove(WebSocketConnectionId id,
|
||||
const WebSocketClose& close,
|
||||
bool close_transport);
|
||||
[[nodiscard]] Connections take_all(bool stop_accepting = false);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
Connections connections_;
|
||||
WebSocketEvents events_;
|
||||
bool accepting_{true};
|
||||
};
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
|
||||
/// Cost presets supplied by libsodium for Argon2id password hashing.
|
||||
/// Moderate is the default for stored account passwords; Interactive is
|
||||
/// useful where latency and memory are constrained, including tests.
|
||||
enum class PasswordHashStrength { Interactive, Moderate, Sensitive };
|
||||
|
||||
inline constexpr std::size_t default_token_entropy_bytes = 32;
|
||||
|
||||
/// Generate a URL-safe, unpadded token containing `entropy_bytes` of
|
||||
/// cryptographically secure randomness.
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
random_token(std::size_t entropy_bytes = default_token_entropy_bytes);
|
||||
|
||||
/// Produce a deterministic lowercase hexadecimal BLAKE2b-256 digest.
|
||||
/// Store this digest instead of the bearer token itself.
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
hash_token(std::string_view token);
|
||||
|
||||
/// Verify a token digest without data-dependent comparison timing.
|
||||
/// Malformed digests are treated as a non-match.
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
verify_token(std::string_view token, std::string_view encoded_hash);
|
||||
|
||||
/// Hash a password using libsodium's Argon2id encoded-string format.
|
||||
/// The returned string contains the algorithm, parameters, salt, and hash.
|
||||
[[nodiscard]] Void::Result::Result<std::string> hash_password(
|
||||
std::string_view password,
|
||||
PasswordHashStrength strength = PasswordHashStrength::Moderate);
|
||||
|
||||
/// Verify a password against a libsodium Argon2id encoded hash.
|
||||
/// Malformed hashes are treated as a non-match.
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
verify_password(std::string_view password,
|
||||
std::string_view encoded_hash);
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -0,0 +1,690 @@
|
||||
#include <Void/Net/Server.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <set>
|
||||
#include <system_error>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] bool
|
||||
equal_ascii_case_insensitive(std::string_view left,
|
||||
std::string_view right) noexcept
|
||||
{
|
||||
return left.size() == right.size() &&
|
||||
std::ranges::equal(left, right, [](char lhs, char rhs) {
|
||||
return std::tolower(static_cast<unsigned char>(lhs)) ==
|
||||
std::tolower(static_cast<unsigned char>(rhs));
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
find_header(const std::vector<Header>& headers,
|
||||
std::string_view name) noexcept
|
||||
{
|
||||
for (const auto& header : headers) {
|
||||
if (equal_ascii_case_insensitive(header.name, name)) {
|
||||
return header.value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view path_only(std::string_view path) noexcept
|
||||
{
|
||||
const auto end = path.find_first_of("?#");
|
||||
return path.substr(0, end);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<std::string> split_path(std::string_view path)
|
||||
{
|
||||
std::vector<std::string> segments;
|
||||
std::size_t begin = path.starts_with('/') ? 1 : 0;
|
||||
while (begin < path.size()) {
|
||||
const auto end = path.find('/', begin);
|
||||
const auto segment = path.substr(begin, end - begin);
|
||||
if (!segment.empty()) {
|
||||
segments.emplace_back(segment);
|
||||
}
|
||||
if (end == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
begin = end + 1;
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid_parameter_name(std::string_view name) noexcept
|
||||
{
|
||||
return !name.empty() && std::ranges::all_of(name, [](char value) {
|
||||
const auto c = static_cast<unsigned char>(value);
|
||||
return std::isalnum(c) != 0 || value == '_';
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::string>>
|
||||
compile_pattern(std::string_view pattern)
|
||||
{
|
||||
if (pattern.empty() || !pattern.starts_with('/') ||
|
||||
pattern.find_first_of("?#") != std::string_view::npos) {
|
||||
return Void::Result::fail(
|
||||
"Net::Router: route patterns must be absolute URL paths");
|
||||
}
|
||||
|
||||
auto segments = split_path(pattern);
|
||||
std::set<std::string, std::less<>> names;
|
||||
for (std::size_t index = 0; index < segments.size(); ++index) {
|
||||
const auto& segment = segments[index];
|
||||
if (!segment.starts_with(':') && !segment.starts_with('*')) {
|
||||
continue;
|
||||
}
|
||||
const auto name = std::string_view{segment}.substr(1);
|
||||
if (!valid_parameter_name(name)) {
|
||||
return Void::Result::fail(
|
||||
"Net::Router: invalid route parameter name");
|
||||
}
|
||||
if (!names.emplace(name).second) {
|
||||
return Void::Result::fail(
|
||||
"Net::Router: duplicate route parameter name");
|
||||
}
|
||||
if (segment.starts_with('*') && index + 1 != segments.size()) {
|
||||
return Void::Result::fail(
|
||||
"Net::Router: catch-all parameter must be final");
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<RouteParameters>
|
||||
match_route(const std::vector<std::string>& pattern,
|
||||
const std::vector<std::string>& path)
|
||||
{
|
||||
RouteParameters parameters;
|
||||
std::size_t path_index = 0;
|
||||
for (const auto& segment : pattern) {
|
||||
if (segment.starts_with('*')) {
|
||||
std::string value;
|
||||
for (; path_index < path.size(); ++path_index) {
|
||||
if (!value.empty()) {
|
||||
value += '/';
|
||||
}
|
||||
value += path[path_index];
|
||||
}
|
||||
parameters.emplace(segment.substr(1), std::move(value));
|
||||
return parameters;
|
||||
}
|
||||
if (path_index >= path.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (segment.starts_with(':')) {
|
||||
parameters.emplace(segment.substr(1), path[path_index]);
|
||||
} else if (segment != path[path_index]) {
|
||||
return std::nullopt;
|
||||
}
|
||||
++path_index;
|
||||
}
|
||||
if (path_index != path.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
[[nodiscard]] int segment_specificity(std::string_view segment) noexcept
|
||||
{
|
||||
if (segment.starts_with('*')) {
|
||||
return 0;
|
||||
}
|
||||
if (segment.starts_with(':')) {
|
||||
return 1;
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
more_specific(const std::vector<std::string>& candidate,
|
||||
const std::vector<std::string>& current) noexcept
|
||||
{
|
||||
const auto shared = std::min(candidate.size(), current.size());
|
||||
for (std::size_t index = 0; index < shared; ++index) {
|
||||
const auto candidate_rank =
|
||||
segment_specificity(candidate[index]);
|
||||
const auto current_rank = segment_specificity(current[index]);
|
||||
if (candidate_rank != current_rank) {
|
||||
return candidate_rank > current_rank;
|
||||
}
|
||||
}
|
||||
return candidate.size() > current.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
same_route_shape(const std::vector<std::string>& left,
|
||||
const std::vector<std::string>& right) noexcept
|
||||
{
|
||||
if (left.size() != right.size()) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t index = 0; index < left.size(); ++index) {
|
||||
const auto left_rank = segment_specificity(left[index]);
|
||||
const auto right_rank = segment_specificity(right[index]);
|
||||
if (left_rank != right_rank ||
|
||||
(left_rank == 2 && left[index] != right[index])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] int hex_value(char value) noexcept
|
||||
{
|
||||
if (value >= '0' && value <= '9') {
|
||||
return value - '0';
|
||||
}
|
||||
if (value >= 'a' && value <= 'f') {
|
||||
return value - 'a' + 10;
|
||||
}
|
||||
if (value >= 'A' && value <= 'F') {
|
||||
return value - 'A' + 10;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
decode_url_path(std::string_view request_path)
|
||||
{
|
||||
const auto path = path_only(request_path);
|
||||
if (path.empty() || !path.starts_with('/')) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: request path must be absolute");
|
||||
}
|
||||
|
||||
std::string decoded;
|
||||
decoded.reserve(path.size());
|
||||
for (std::size_t index = 0; index < path.size(); ++index) {
|
||||
unsigned char value = static_cast<unsigned char>(path[index]);
|
||||
if (value == '%') {
|
||||
if (index + 2 >= path.size()) {
|
||||
return Void::Result::fail("Net::StaticFileResolver: "
|
||||
"invalid percent encoding");
|
||||
}
|
||||
const auto high = hex_value(path[index + 1]);
|
||||
const auto low = hex_value(path[index + 2]);
|
||||
if (high < 0 || low < 0) {
|
||||
return Void::Result::fail("Net::StaticFileResolver: "
|
||||
"invalid percent encoding");
|
||||
}
|
||||
value = static_cast<unsigned char>((high << 4) | low);
|
||||
index += 2;
|
||||
}
|
||||
if (value < 0x20 || value == 0x7f || value == '\\') {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: unsafe path character");
|
||||
}
|
||||
decoded += static_cast<char>(value);
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
path_is_within(const std::filesystem::path& root,
|
||||
const std::filesystem::path& candidate) noexcept
|
||||
{
|
||||
auto root_part = root.begin();
|
||||
auto candidate_part = candidate.begin();
|
||||
for (; root_part != root.end(); ++root_part, ++candidate_part) {
|
||||
if (candidate_part == candidate.end() ||
|
||||
*root_part != *candidate_part) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string
|
||||
lowercase_extension(const std::filesystem::path& path)
|
||||
{
|
||||
auto extension = path.extension().string();
|
||||
std::ranges::transform(
|
||||
extension, extension.begin(), [](char value) {
|
||||
return static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(value)));
|
||||
});
|
||||
return extension;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::optional<std::string_view>
|
||||
ServerRequest::header(std::string_view name) const noexcept
|
||||
{
|
||||
return find_header(headers, name);
|
||||
}
|
||||
|
||||
std::optional<std::string_view>
|
||||
ServerResponse::header(std::string_view name) const noexcept
|
||||
{
|
||||
return find_header(headers, name);
|
||||
}
|
||||
|
||||
Void::Result::Result<void> Router::add(Method method, std::string pattern,
|
||||
RouteHandler handler)
|
||||
{
|
||||
if (!handler) {
|
||||
return Void::Result::fail("Net::Router: route handler is empty");
|
||||
}
|
||||
auto segments = compile_pattern(pattern);
|
||||
if (!segments) {
|
||||
return Void::Result::fail(std::move(segments).error());
|
||||
}
|
||||
|
||||
std::unique_lock lock{mutex_};
|
||||
const auto duplicate =
|
||||
std::ranges::find_if(routes_, [&](const Route& route) {
|
||||
return route.method == method &&
|
||||
same_route_shape(route.segments, *segments);
|
||||
});
|
||||
if (duplicate != routes_.end()) {
|
||||
return Void::Result::fail("Net::Router: duplicate route");
|
||||
}
|
||||
routes_.push_back(Route{method, std::move(pattern),
|
||||
std::move(*segments), std::move(handler)});
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<ServerResponse>>
|
||||
Router::dispatch(ServerRequest request) const
|
||||
{
|
||||
if (request.path.empty() || !request.path.starts_with('/')) {
|
||||
return Void::Result::fail(
|
||||
"Net::Router: request path must be absolute");
|
||||
}
|
||||
const auto path = split_path(path_only(request.path));
|
||||
RouteHandler handler;
|
||||
RouteParameters parameters;
|
||||
{
|
||||
std::shared_lock lock{mutex_};
|
||||
const Route* best_route = nullptr;
|
||||
for (const auto& route : routes_) {
|
||||
if (route.method != request.method) {
|
||||
continue;
|
||||
}
|
||||
auto matched = match_route(route.segments, path);
|
||||
if (!matched) {
|
||||
continue;
|
||||
}
|
||||
if (best_route == nullptr ||
|
||||
more_specific(route.segments, best_route->segments)) {
|
||||
best_route = &route;
|
||||
parameters = std::move(*matched);
|
||||
}
|
||||
}
|
||||
if (best_route != nullptr) {
|
||||
handler = best_route->handler;
|
||||
}
|
||||
}
|
||||
|
||||
if (!handler) {
|
||||
return std::optional<ServerResponse>{};
|
||||
}
|
||||
request.parameters = std::move(parameters);
|
||||
auto response = handler(request);
|
||||
if (!response) {
|
||||
return Void::Result::fail(std::move(response).error());
|
||||
}
|
||||
return std::optional<ServerResponse>{std::move(*response)};
|
||||
}
|
||||
|
||||
std::size_t Router::size() const
|
||||
{
|
||||
std::shared_lock lock{mutex_};
|
||||
return routes_.size();
|
||||
}
|
||||
|
||||
std::string_view content_type_for(const std::filesystem::path& path)
|
||||
{
|
||||
const auto extension = lowercase_extension(path);
|
||||
if (extension == ".html" || extension == ".htm") {
|
||||
return "text/html; charset=utf-8";
|
||||
}
|
||||
if (extension == ".css") {
|
||||
return "text/css; charset=utf-8";
|
||||
}
|
||||
if (extension == ".js" || extension == ".mjs") {
|
||||
return "text/javascript; charset=utf-8";
|
||||
}
|
||||
if (extension == ".json" || extension == ".map") {
|
||||
return "application/json; charset=utf-8";
|
||||
}
|
||||
if (extension == ".txt") {
|
||||
return "text/plain; charset=utf-8";
|
||||
}
|
||||
if (extension == ".xml") {
|
||||
return "application/xml; charset=utf-8";
|
||||
}
|
||||
if (extension == ".svg") {
|
||||
return "image/svg+xml";
|
||||
}
|
||||
if (extension == ".png") {
|
||||
return "image/png";
|
||||
}
|
||||
if (extension == ".jpg" || extension == ".jpeg") {
|
||||
return "image/jpeg";
|
||||
}
|
||||
if (extension == ".gif") {
|
||||
return "image/gif";
|
||||
}
|
||||
if (extension == ".webp") {
|
||||
return "image/webp";
|
||||
}
|
||||
if (extension == ".ico") {
|
||||
return "image/x-icon";
|
||||
}
|
||||
if (extension == ".wasm") {
|
||||
return "application/wasm";
|
||||
}
|
||||
if (extension == ".woff") {
|
||||
return "font/woff";
|
||||
}
|
||||
if (extension == ".woff2") {
|
||||
return "font/woff2";
|
||||
}
|
||||
if (extension == ".ttf") {
|
||||
return "font/ttf";
|
||||
}
|
||||
if (extension == ".mp3") {
|
||||
return "audio/mpeg";
|
||||
}
|
||||
if (extension == ".ogg") {
|
||||
return "audio/ogg";
|
||||
}
|
||||
if (extension == ".mp4") {
|
||||
return "video/mp4";
|
||||
}
|
||||
if (extension == ".webm") {
|
||||
return "video/webm";
|
||||
}
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
Void::Result::Result<StaticFileResolver>
|
||||
StaticFileResolver::create(std::filesystem::path root,
|
||||
std::string index_file)
|
||||
{
|
||||
if (index_file.empty() ||
|
||||
std::filesystem::path{index_file}.filename() != index_file ||
|
||||
index_file == "." || index_file == "..") {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: index file must be one filename");
|
||||
}
|
||||
|
||||
std::error_code error;
|
||||
auto canonical_root = std::filesystem::weakly_canonical(root, error);
|
||||
if (error || !std::filesystem::is_directory(canonical_root, error) ||
|
||||
error) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: document root is not a directory");
|
||||
}
|
||||
return StaticFileResolver{std::move(canonical_root),
|
||||
std::move(index_file)};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<StaticFile>>
|
||||
StaticFileResolver::resolve(std::string_view request_path) const
|
||||
{
|
||||
auto decoded = decode_url_path(request_path);
|
||||
if (!decoded) {
|
||||
return Void::Result::fail(std::move(decoded).error());
|
||||
}
|
||||
|
||||
auto candidate = root_;
|
||||
for (const auto& segment : split_path(*decoded)) {
|
||||
if (segment == "." || segment == "..") {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: path traversal rejected");
|
||||
}
|
||||
candidate /= segment;
|
||||
}
|
||||
|
||||
std::error_code error;
|
||||
candidate = std::filesystem::weakly_canonical(candidate, error);
|
||||
if (error) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: path canonicalization failed");
|
||||
}
|
||||
if (!path_is_within(root_, candidate)) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: path escapes document root");
|
||||
}
|
||||
|
||||
if (!std::filesystem::exists(candidate, error)) {
|
||||
if (error) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: file status failed");
|
||||
}
|
||||
return std::optional<StaticFile>{};
|
||||
}
|
||||
if (std::filesystem::is_directory(candidate, error)) {
|
||||
candidate = std::filesystem::weakly_canonical(
|
||||
candidate / index_file_, error);
|
||||
if (error || !path_is_within(root_, candidate)) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: unsafe index path");
|
||||
}
|
||||
}
|
||||
if (!std::filesystem::is_regular_file(candidate, error)) {
|
||||
if (error) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: file status failed");
|
||||
}
|
||||
return std::optional<StaticFile>{};
|
||||
}
|
||||
|
||||
const auto size = std::filesystem::file_size(candidate, error);
|
||||
if (error) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: file size failed");
|
||||
}
|
||||
const auto content_type = content_type_for(candidate);
|
||||
return std::optional<StaticFile>{
|
||||
StaticFile{std::move(candidate), content_type, size}};
|
||||
}
|
||||
|
||||
WebSocketSessions::~WebSocketSessions() noexcept
|
||||
{
|
||||
try {
|
||||
auto connections = take_all(true);
|
||||
const WebSocketClose close{1001, "server shutdown"};
|
||||
for (const auto& [id, connection] : connections) {
|
||||
(void)id;
|
||||
connection->close(close);
|
||||
}
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
|
||||
void WebSocketSessions::set_events(WebSocketEvents events)
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
events_ = std::move(events);
|
||||
}
|
||||
|
||||
Void::Result::Result<bool>
|
||||
WebSocketSessions::open(std::shared_ptr<WebSocketConnection> connection)
|
||||
{
|
||||
if (!connection) {
|
||||
return Void::Result::fail(
|
||||
"Net::WebSocketSessions: connection is null");
|
||||
}
|
||||
|
||||
std::function<void(const std::shared_ptr<WebSocketConnection>&)> opened;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
if (!accepting_) {
|
||||
return false;
|
||||
}
|
||||
if (!connections_.emplace(connection->id(), connection).second) {
|
||||
return false;
|
||||
}
|
||||
opened = events_.opened;
|
||||
}
|
||||
if (opened) {
|
||||
opened(connection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::shared_ptr<WebSocketConnection>
|
||||
WebSocketSessions::find(WebSocketConnectionId id) const
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
const auto found = connections_.find(id);
|
||||
return found == connections_.end() ? nullptr : found->second;
|
||||
}
|
||||
|
||||
bool WebSocketSessions::contains(WebSocketConnectionId id) const
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
return connections_.contains(id);
|
||||
}
|
||||
|
||||
std::size_t WebSocketSessions::size() const
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
return connections_.size();
|
||||
}
|
||||
|
||||
bool WebSocketSessions::receive_text(WebSocketConnectionId id,
|
||||
std::string_view message) const
|
||||
{
|
||||
std::shared_ptr<WebSocketConnection> connection;
|
||||
std::function<void(const std::shared_ptr<WebSocketConnection>&,
|
||||
std::string_view)>
|
||||
callback;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
const auto found = connections_.find(id);
|
||||
if (found == connections_.end()) {
|
||||
return false;
|
||||
}
|
||||
connection = found->second;
|
||||
callback = events_.text;
|
||||
}
|
||||
if (callback) {
|
||||
callback(connection, message);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WebSocketSessions::receive_binary(
|
||||
WebSocketConnectionId id, std::span<const std::byte> message) const
|
||||
{
|
||||
std::shared_ptr<WebSocketConnection> connection;
|
||||
std::function<void(const std::shared_ptr<WebSocketConnection>&,
|
||||
std::span<const std::byte>)>
|
||||
callback;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
const auto found = connections_.find(id);
|
||||
if (found == connections_.end()) {
|
||||
return false;
|
||||
}
|
||||
connection = found->second;
|
||||
callback = events_.binary;
|
||||
}
|
||||
if (callback) {
|
||||
callback(connection, message);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WebSocketSessions::fail(WebSocketConnectionId id,
|
||||
const Void::Result::Error& error) const
|
||||
{
|
||||
std::function<void(WebSocketConnectionId, const Void::Result::Error&)>
|
||||
callback;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
if (!connections_.contains(id)) {
|
||||
return false;
|
||||
}
|
||||
callback = events_.error;
|
||||
}
|
||||
if (callback) {
|
||||
callback(id, error);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WebSocketSessions::disconnect(WebSocketConnectionId id,
|
||||
WebSocketClose close)
|
||||
{
|
||||
return remove(id, close, false);
|
||||
}
|
||||
|
||||
bool WebSocketSessions::close(WebSocketConnectionId id,
|
||||
WebSocketClose close)
|
||||
{
|
||||
return remove(id, close, true);
|
||||
}
|
||||
|
||||
std::size_t WebSocketSessions::shutdown(WebSocketClose close)
|
||||
{
|
||||
auto connections = take_all(true);
|
||||
std::function<void(WebSocketConnectionId, const WebSocketClose&)>
|
||||
closed;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
closed = events_.closed;
|
||||
}
|
||||
for (const auto& [id, connection] : connections) {
|
||||
(void)id;
|
||||
connection->close(close);
|
||||
}
|
||||
if (closed) {
|
||||
for (const auto& [id, connection] : connections) {
|
||||
(void)connection;
|
||||
closed(id, close);
|
||||
}
|
||||
}
|
||||
return connections.size();
|
||||
}
|
||||
|
||||
bool WebSocketSessions::remove(WebSocketConnectionId id,
|
||||
const WebSocketClose& close,
|
||||
bool close_transport)
|
||||
{
|
||||
std::shared_ptr<WebSocketConnection> connection;
|
||||
std::function<void(WebSocketConnectionId, const WebSocketClose&)>
|
||||
closed;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
const auto found = connections_.find(id);
|
||||
if (found == connections_.end()) {
|
||||
return false;
|
||||
}
|
||||
connection = std::move(found->second);
|
||||
connections_.erase(found);
|
||||
closed = events_.closed;
|
||||
}
|
||||
if (close_transport) {
|
||||
connection->close(close);
|
||||
}
|
||||
if (closed) {
|
||||
closed(id, close);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
WebSocketSessions::Connections
|
||||
WebSocketSessions::take_all(bool stop_accepting)
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
if (stop_accepting) {
|
||||
accepting_ = false;
|
||||
}
|
||||
Connections connections;
|
||||
connections.swap(connections_);
|
||||
return connections;
|
||||
}
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,178 @@
|
||||
#include <Void/Security/Security.hpp>
|
||||
|
||||
#include <sodium.h>
|
||||
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
namespace
|
||||
{
|
||||
struct PasswordLimits {
|
||||
unsigned long long operations;
|
||||
std::size_t memory;
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> ensure_sodium()
|
||||
{
|
||||
static const bool initialized = sodium_init() >= 0;
|
||||
if (!initialized) {
|
||||
return Void::Result::fail(
|
||||
"Security: libsodium initialization failed");
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<PasswordLimits>
|
||||
password_limits(PasswordHashStrength strength) noexcept
|
||||
{
|
||||
switch (strength) {
|
||||
case PasswordHashStrength::Interactive:
|
||||
return PasswordLimits{crypto_pwhash_OPSLIMIT_INTERACTIVE,
|
||||
crypto_pwhash_MEMLIMIT_INTERACTIVE};
|
||||
case PasswordHashStrength::Moderate:
|
||||
return PasswordLimits{crypto_pwhash_OPSLIMIT_MODERATE,
|
||||
crypto_pwhash_MEMLIMIT_MODERATE};
|
||||
case PasswordHashStrength::Sensitive:
|
||||
return PasswordLimits{crypto_pwhash_OPSLIMIT_SENSITIVE,
|
||||
crypto_pwhash_MEMLIMIT_SENSITIVE};
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::array<unsigned char, crypto_generichash_BYTES>
|
||||
token_digest(std::string_view token) noexcept
|
||||
{
|
||||
std::array<unsigned char, crypto_generichash_BYTES> digest{};
|
||||
(void)crypto_generichash(
|
||||
digest.data(), digest.size(),
|
||||
reinterpret_cast<const unsigned char*>(token.data()),
|
||||
token.size(), nullptr, 0);
|
||||
return digest;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::string> random_token(std::size_t entropy_bytes)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
if (entropy_bytes == 0) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: entropy must be greater than zero");
|
||||
}
|
||||
if (entropy_bytes >
|
||||
(std::numeric_limits<std::size_t>::max() - 2) / 4 * 3) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: entropy size is too large");
|
||||
}
|
||||
|
||||
std::vector<unsigned char> random(entropy_bytes);
|
||||
randombytes_buf(random.data(), random.size());
|
||||
|
||||
const auto encoded_size = sodium_base64_ENCODED_LEN(
|
||||
random.size(), sodium_base64_VARIANT_URLSAFE_NO_PADDING);
|
||||
std::string encoded(encoded_size, '\0');
|
||||
const auto* result = sodium_bin2base64(
|
||||
encoded.data(), encoded.size(), random.data(), random.size(),
|
||||
sodium_base64_VARIANT_URLSAFE_NO_PADDING);
|
||||
sodium_memzero(random.data(), random.size());
|
||||
if (result == nullptr) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: base64 encoding failed");
|
||||
}
|
||||
encoded.resize(std::strlen(encoded.c_str()));
|
||||
return encoded;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string> hash_token(std::string_view token)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
|
||||
const auto digest = token_digest(token);
|
||||
std::array<char, crypto_generichash_BYTES * 2 + 1> encoded{};
|
||||
(void)sodium_bin2hex(encoded.data(), encoded.size(), digest.data(),
|
||||
digest.size());
|
||||
return std::string{encoded.data(), encoded.size() - 1};
|
||||
}
|
||||
|
||||
Void::Result::Result<bool> verify_token(std::string_view token,
|
||||
std::string_view encoded_hash)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
|
||||
constexpr auto encoded_length = crypto_generichash_BYTES * 2;
|
||||
if (encoded_hash.size() != encoded_length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::array<unsigned char, crypto_generichash_BYTES> expected{};
|
||||
std::size_t decoded_length = 0;
|
||||
if (sodium_hex2bin(expected.data(), expected.size(),
|
||||
encoded_hash.data(), encoded_hash.size(), nullptr,
|
||||
&decoded_length, nullptr) != 0 ||
|
||||
decoded_length != expected.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto actual = token_digest(token);
|
||||
return sodium_memcmp(actual.data(), expected.data(), actual.size()) ==
|
||||
0;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string>
|
||||
hash_password(std::string_view password, PasswordHashStrength strength)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
if (password.size() > crypto_pwhash_PASSWD_MAX) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: password is too long");
|
||||
}
|
||||
|
||||
const auto limits = password_limits(strength);
|
||||
if (!limits) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: invalid strength");
|
||||
}
|
||||
|
||||
std::array<char, crypto_pwhash_STRBYTES> encoded{};
|
||||
if (crypto_pwhash_str_alg(
|
||||
encoded.data(), password.data(),
|
||||
static_cast<unsigned long long>(password.size()),
|
||||
limits->operations, limits->memory,
|
||||
crypto_pwhash_ALG_ARGON2ID13) != 0) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: Argon2id hashing failed");
|
||||
}
|
||||
return std::string{encoded.data()};
|
||||
}
|
||||
|
||||
Void::Result::Result<bool> verify_password(std::string_view password,
|
||||
std::string_view encoded_hash)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
if (password.size() > crypto_pwhash_PASSWD_MAX ||
|
||||
encoded_hash.empty() ||
|
||||
encoded_hash.find('\0') != std::string_view::npos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string terminated_hash{encoded_hash};
|
||||
return crypto_pwhash_str_verify(
|
||||
terminated_hash.c_str(), password.data(),
|
||||
static_cast<unsigned long long>(password.size())) == 0;
|
||||
}
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(Security
|
||||
INTERNAL_DEPS Functional
|
||||
EXTERNAL_DEPS Sodium::Sodium
|
||||
)
|
||||
@@ -19,6 +19,25 @@ namespace
|
||||
std::ifstream f(p);
|
||||
return {std::istreambuf_iterator<char>(f), {}};
|
||||
}
|
||||
|
||||
std::size_t archive_count(const std::filesystem::path& path)
|
||||
{
|
||||
const auto directory = path.parent_path() / "history";
|
||||
if (!std::filesystem::exists(directory)) {
|
||||
return 0;
|
||||
}
|
||||
const auto prefix = path.stem().string() + "-";
|
||||
std::size_t count = 0;
|
||||
for (const auto& entry :
|
||||
std::filesystem::directory_iterator(directory)) {
|
||||
const auto filename = entry.path().filename().string();
|
||||
if (entry.is_regular_file() && filename.starts_with(prefix) &&
|
||||
entry.path().extension() == path.extension()) {
|
||||
++count;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class SplitFileLoggerTests : public Void::Testing::Fixture
|
||||
@@ -135,8 +154,8 @@ class HistoryLoggerTests : public Void::Testing::Fixture
|
||||
std::to_string(i));
|
||||
}
|
||||
}
|
||||
auto rotated = path;
|
||||
rotated += ".1";
|
||||
Void::Testing::expect(std::filesystem::exists(rotated));
|
||||
const auto archives = archive_count(path);
|
||||
Void::Testing::expect(archives >= 1);
|
||||
Void::Testing::expect(archives <= 3);
|
||||
}
|
||||
};
|
||||
+144
-125
@@ -1,7 +1,7 @@
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Log/ConsoleLogger.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Fixture.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
@@ -14,170 +14,189 @@
|
||||
|
||||
using namespace Void::Logging;
|
||||
|
||||
// ── NullLogger / CallbackLogger ───────────────────────────────────────────────
|
||||
namespace
|
||||
{
|
||||
std::size_t archive_count(const std::filesystem::path& path)
|
||||
{
|
||||
const auto directory = path.parent_path() / "history";
|
||||
if (!std::filesystem::exists(directory)) {
|
||||
return 0;
|
||||
}
|
||||
const auto prefix = path.stem().string() + "-";
|
||||
std::size_t count = 0;
|
||||
for (const auto& entry :
|
||||
std::filesystem::directory_iterator(directory)) {
|
||||
const auto filename = entry.path().filename().string();
|
||||
if (entry.is_regular_file() && filename.starts_with(prefix) &&
|
||||
entry.path().extension() == path.extension()) {
|
||||
++count;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ── NullLogger / CallbackLogger
|
||||
// ───────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test null_logger_swallows_everything()
|
||||
{
|
||||
NullLogger log;
|
||||
log.fatal("into the void");
|
||||
log.flush();
|
||||
Void::Testing::expect(true); // reached without crashing
|
||||
NullLogger log;
|
||||
log.fatal("into the void");
|
||||
log.flush();
|
||||
Void::Testing::expect(true); // reached without crashing
|
||||
}
|
||||
|
||||
Void::Testing::Test callback_logger_receives_entry_fields()
|
||||
{
|
||||
Entry got;
|
||||
CallbackLogger log{[&](const Entry& e) { got = e; },
|
||||
Mode::Immediate};
|
||||
log.warning("payload");
|
||||
Void::Testing::expect(got.level == Level::Warning);
|
||||
Void::Testing::expect_eq(got.message, std::string{"payload"});
|
||||
Entry got;
|
||||
CallbackLogger log{[&](const Entry& e) { got = e; }, Mode::Immediate};
|
||||
log.warning("payload");
|
||||
Void::Testing::expect(got.level == Level::Warning);
|
||||
Void::Testing::expect_eq(got.message, std::string{"payload"});
|
||||
}
|
||||
|
||||
// ── MultiLogger ───────────────────────────────────────────────────────────────
|
||||
// ── MultiLogger
|
||||
// ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test multi_logger_fans_out_to_all_children()
|
||||
{
|
||||
int a = 0;
|
||||
int b = 0;
|
||||
MultiLogger multi;
|
||||
multi.add(std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++a; }, Mode::Immediate));
|
||||
multi.add(std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++b; }, Mode::Immediate));
|
||||
int a = 0;
|
||||
int b = 0;
|
||||
MultiLogger multi;
|
||||
multi.add(std::make_shared<CallbackLogger>([&](const Entry&) { ++a; },
|
||||
Mode::Immediate));
|
||||
multi.add(std::make_shared<CallbackLogger>([&](const Entry&) { ++b; },
|
||||
Mode::Immediate));
|
||||
|
||||
multi.info("to both");
|
||||
Void::Testing::expect_eq(a, 1);
|
||||
Void::Testing::expect_eq(b, 1);
|
||||
Void::Testing::expect_eq(multi.child_count(), std::size_t{2});
|
||||
multi.info("to both");
|
||||
Void::Testing::expect_eq(a, 1);
|
||||
Void::Testing::expect_eq(b, 1);
|
||||
Void::Testing::expect_eq(multi.child_count(), std::size_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test multi_logger_children_keep_own_levels()
|
||||
{
|
||||
int verbose_count = 0;
|
||||
int errors_only = 0;
|
||||
auto verbose = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++verbose_count; }, Mode::Immediate);
|
||||
auto strict = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++errors_only; }, Mode::Immediate);
|
||||
strict->set_level(Level::Error);
|
||||
int verbose_count = 0;
|
||||
int errors_only = 0;
|
||||
auto verbose = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++verbose_count; }, Mode::Immediate);
|
||||
auto strict = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++errors_only; }, Mode::Immediate);
|
||||
strict->set_level(Level::Error);
|
||||
|
||||
MultiLogger multi;
|
||||
multi.add(verbose);
|
||||
multi.add(strict);
|
||||
MultiLogger multi;
|
||||
multi.add(verbose);
|
||||
multi.add(strict);
|
||||
|
||||
multi.info("info");
|
||||
multi.error("error");
|
||||
Void::Testing::expect_eq(verbose_count, 2);
|
||||
Void::Testing::expect_eq(errors_only, 1);
|
||||
multi.info("info");
|
||||
multi.error("error");
|
||||
Void::Testing::expect_eq(verbose_count, 2);
|
||||
Void::Testing::expect_eq(errors_only, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test multi_logger_relays_async_children_with_flush()
|
||||
{
|
||||
int delivered = 0;
|
||||
auto async_child = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++delivered; }); // Async by default
|
||||
MultiLogger multi;
|
||||
multi.add(async_child);
|
||||
int delivered = 0;
|
||||
auto async_child = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++delivered; }); // Async by default
|
||||
MultiLogger multi;
|
||||
multi.add(async_child);
|
||||
|
||||
multi.info("queued in child");
|
||||
multi.flush(); // flushes children too
|
||||
Void::Testing::expect_eq(delivered, 1);
|
||||
multi.info("queued in child");
|
||||
multi.flush(); // flushes children too
|
||||
Void::Testing::expect_eq(delivered, 1);
|
||||
}
|
||||
|
||||
// ── ConsoleLogger + Formatter ─────────────────────────────────────────────────
|
||||
// ── ConsoleLogger + Formatter
|
||||
// ─────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test console_logger_uses_installed_formatter()
|
||||
{
|
||||
std::ostringstream out;
|
||||
{
|
||||
ConsoleLogger log{out, Mode::Immediate};
|
||||
log.set_formatter(
|
||||
std::make_shared<PatternFormatter>("{level}>{message}"));
|
||||
log.info("custom format");
|
||||
}
|
||||
Void::Testing::expect_eq(out.str(),
|
||||
std::string{"Info>custom format\n"});
|
||||
std::ostringstream out;
|
||||
{
|
||||
ConsoleLogger log{out, Mode::Immediate};
|
||||
log.set_formatter(
|
||||
std::make_shared<PatternFormatter>("{level}>{message}"));
|
||||
log.info("custom format");
|
||||
}
|
||||
Void::Testing::expect_eq(out.str(), std::string{"Info>custom format\n"});
|
||||
}
|
||||
|
||||
// ── RotatingFileLogger ────────────────────────────────────────────────────────
|
||||
// ── RotatingFileLogger
|
||||
// ────────────────────────────────────────────────────────
|
||||
|
||||
class RotatingFileLoggerTests : public Void::Testing::Fixture
|
||||
{
|
||||
public:
|
||||
public:
|
||||
|
||||
std::filesystem::path dir;
|
||||
std::filesystem::path file;
|
||||
std::filesystem::path dir;
|
||||
std::filesystem::path file;
|
||||
|
||||
void setup() override
|
||||
{
|
||||
dir = std::filesystem::temp_directory_path() /
|
||||
"void_rotating_test";
|
||||
std::filesystem::remove_all(dir);
|
||||
std::filesystem::create_directories(dir);
|
||||
file = dir / "app.log";
|
||||
}
|
||||
void setup() override
|
||||
{
|
||||
dir = std::filesystem::temp_directory_path() / "void_rotating_test";
|
||||
std::filesystem::remove_all(dir);
|
||||
std::filesystem::create_directories(dir);
|
||||
file = dir / "app.log";
|
||||
}
|
||||
|
||||
void teardown() override { std::filesystem::remove_all(dir); }
|
||||
void teardown() override { std::filesystem::remove_all(dir); }
|
||||
|
||||
static std::string slurp(const std::filesystem::path& p)
|
||||
{
|
||||
std::ifstream f(p);
|
||||
return {std::istreambuf_iterator<char>(f), {}};
|
||||
}
|
||||
static std::string slurp(const std::filesystem::path& p)
|
||||
{
|
||||
std::ifstream f(p);
|
||||
return {std::istreambuf_iterator<char>(f), {}};
|
||||
}
|
||||
|
||||
Void::Testing::Test writes_and_flushes()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger log{file};
|
||||
log.info("rotating hello");
|
||||
}
|
||||
Void::Testing::expect(slurp(file).find("rotating hello") !=
|
||||
std::string::npos);
|
||||
}
|
||||
Void::Testing::Test writes_and_flushes()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger log{file};
|
||||
log.info("rotating hello");
|
||||
}
|
||||
Void::Testing::expect(slurp(file).find("rotating hello") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test rotates_when_size_exceeded()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger::Options opt;
|
||||
opt.max_bytes = 256;
|
||||
opt.max_files = 3;
|
||||
opt.mode = Mode::Immediate;
|
||||
RotatingFileLogger log{file, opt};
|
||||
for (int i = 0; i < 40; ++i) {
|
||||
log.info("a reasonably long line to fill the file " +
|
||||
std::to_string(i));
|
||||
}
|
||||
}
|
||||
Void::Testing::expect(std::filesystem::exists(file));
|
||||
auto rotated = file;
|
||||
rotated += ".1";
|
||||
Void::Testing::expect(std::filesystem::exists(rotated));
|
||||
// The bound holds: no file beyond .3
|
||||
auto beyond = file;
|
||||
beyond += ".4";
|
||||
Void::Testing::expect(!std::filesystem::exists(beyond));
|
||||
}
|
||||
Void::Testing::Test rotates_when_size_exceeded()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger::Options opt;
|
||||
opt.max_bytes = 256;
|
||||
opt.max_files = 3;
|
||||
opt.mode = Mode::Immediate;
|
||||
RotatingFileLogger log{file, opt};
|
||||
for (int i = 0; i < 40; ++i) {
|
||||
log.info("a reasonably long line to fill the file " +
|
||||
std::to_string(i));
|
||||
}
|
||||
}
|
||||
Void::Testing::expect(std::filesystem::exists(file));
|
||||
const auto archives = archive_count(file);
|
||||
Void::Testing::expect(archives >= 1);
|
||||
Void::Testing::expect(archives <= 3);
|
||||
}
|
||||
|
||||
Void::Testing::Test open_factory_rejects_bad_path()
|
||||
{
|
||||
auto r = RotatingFileLogger::open(
|
||||
"/this/path/does/not/exist/app.log");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
Void::Testing::Test open_factory_rejects_bad_path()
|
||||
{
|
||||
auto r =
|
||||
RotatingFileLogger::open("/this/path/does/not/exist/app.log");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test async_rotation_under_load()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger::Options opt;
|
||||
opt.max_bytes = 512;
|
||||
opt.max_files = 2;
|
||||
RotatingFileLogger log{file, opt}; // Async default
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
log.info("async rotation line " + std::to_string(i));
|
||||
}
|
||||
log.flush();
|
||||
}
|
||||
Void::Testing::expect(std::filesystem::exists(file));
|
||||
}
|
||||
Void::Testing::Test async_rotation_under_load()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger::Options opt;
|
||||
opt.max_bytes = 512;
|
||||
opt.max_files = 2;
|
||||
RotatingFileLogger log{file, opt}; // Async default
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
log.info("async rotation line " + std::to_string(i));
|
||||
}
|
||||
log.flush();
|
||||
}
|
||||
Void::Testing::expect(std::filesystem::exists(file));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,330 @@
|
||||
#include <Void/Net/Server.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Net::Method;
|
||||
using Void::Net::Router;
|
||||
using Void::Net::ServerRequest;
|
||||
using Void::Net::ServerResponse;
|
||||
using Void::Net::StaticFileResolver;
|
||||
using Void::Net::WebSocketClose;
|
||||
using Void::Net::WebSocketConnection;
|
||||
using Void::Net::WebSocketConnectionId;
|
||||
using Void::Net::WebSocketEvents;
|
||||
using Void::Net::WebSocketSessions;
|
||||
using Void::Testing::Test;
|
||||
|
||||
void write_file(const std::filesystem::path& path, std::string_view body)
|
||||
{
|
||||
std::filesystem::create_directories(path.parent_path());
|
||||
std::ofstream output{path, std::ios::binary};
|
||||
output << body;
|
||||
}
|
||||
|
||||
struct FakeConnection final : WebSocketConnection {
|
||||
explicit FakeConnection(std::uint64_t value) : id_{value} {}
|
||||
|
||||
[[nodiscard]] WebSocketConnectionId id() const noexcept override
|
||||
{
|
||||
return id_;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_text(std::string_view message) override
|
||||
{
|
||||
sent_text.emplace_back(message);
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_binary(std::span<const std::byte> message) override
|
||||
{
|
||||
sent_binary.emplace_back(message.begin(), message.end());
|
||||
return {};
|
||||
}
|
||||
|
||||
void close(const WebSocketClose& info) noexcept override
|
||||
{
|
||||
closed = true;
|
||||
close_code = info.code;
|
||||
}
|
||||
|
||||
WebSocketConnectionId id_;
|
||||
std::vector<std::string> sent_text;
|
||||
std::vector<std::vector<std::byte>> sent_binary;
|
||||
bool closed{false};
|
||||
std::uint16_t close_code{};
|
||||
};
|
||||
|
||||
struct RouterTests : Void::Testing::Suite<RouterTests> {
|
||||
Test routes_by_method_and_extracts_parameters()
|
||||
{
|
||||
Router router;
|
||||
auto added = router.add(
|
||||
Method::Get, "/rooms/:room/members/:member",
|
||||
[](const ServerRequest& request) {
|
||||
return Void::Result::ok(ServerResponse{
|
||||
.status = 200,
|
||||
.body = request.parameters.at("room") + ":" +
|
||||
request.parameters.at("member")});
|
||||
});
|
||||
Void::Testing::require(added.has_value());
|
||||
|
||||
auto response = router.dispatch(
|
||||
ServerRequest{.method = Method::Get,
|
||||
.path = "/rooms/alpha/members/7?full=1"});
|
||||
Void::Testing::require(response.has_value());
|
||||
Void::Testing::require(response->has_value());
|
||||
Void::Testing::expect_eq((*response)->body,
|
||||
std::string{"alpha:7"});
|
||||
|
||||
auto miss = router.dispatch(ServerRequest{
|
||||
.method = Method::Post, .path = "/rooms/alpha/members/7"});
|
||||
Void::Testing::require(miss.has_value());
|
||||
Void::Testing::expect(!miss->has_value());
|
||||
}
|
||||
|
||||
Test final_catch_all_captures_remaining_path()
|
||||
{
|
||||
Router router;
|
||||
Void::Testing::require(
|
||||
router
|
||||
.add(Method::Get, "/assets/*path",
|
||||
[](const ServerRequest& request) {
|
||||
return Void::Result::ok(ServerResponse{
|
||||
.body = request.parameters.at("path")});
|
||||
})
|
||||
.has_value());
|
||||
auto response = router.dispatch(ServerRequest{
|
||||
.method = Method::Get, .path = "/assets/js/app.js"});
|
||||
Void::Testing::require(response.has_value());
|
||||
Void::Testing::require(response->has_value());
|
||||
Void::Testing::expect_eq((*response)->body,
|
||||
std::string{"js/app.js"});
|
||||
}
|
||||
|
||||
Test static_route_takes_precedence_over_parameter_route()
|
||||
{
|
||||
Router router;
|
||||
Void::Testing::require(
|
||||
router
|
||||
.add(Method::Get, "/rooms/:room",
|
||||
[](const ServerRequest&) {
|
||||
return Void::Result::ok(
|
||||
ServerResponse{.body = "parameter"});
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
router
|
||||
.add(Method::Get, "/rooms/new",
|
||||
[](const ServerRequest&) {
|
||||
return Void::Result::ok(
|
||||
ServerResponse{.body = "static"});
|
||||
})
|
||||
.has_value());
|
||||
|
||||
auto response = router.dispatch(
|
||||
ServerRequest{.method = Method::Get, .path = "/rooms/new"});
|
||||
Void::Testing::require(response.has_value());
|
||||
Void::Testing::require(response->has_value());
|
||||
Void::Testing::expect_eq((*response)->body,
|
||||
std::string{"static"});
|
||||
}
|
||||
|
||||
Test rejects_invalid_and_duplicate_patterns()
|
||||
{
|
||||
Router router;
|
||||
auto handler = [](const ServerRequest&) {
|
||||
return Void::Result::ok(ServerResponse{});
|
||||
};
|
||||
Void::Testing::expect(
|
||||
!router.add(Method::Get, "relative", handler));
|
||||
Void::Testing::expect(
|
||||
!router.add(Method::Get, "/bad/*path/tail", handler));
|
||||
Void::Testing::require(
|
||||
router.add(Method::Get, "/health", handler).has_value());
|
||||
Void::Testing::expect(
|
||||
!router.add(Method::Get, "/health", handler).has_value());
|
||||
Void::Testing::require(
|
||||
router.add(Method::Get, "/users/:id", handler).has_value());
|
||||
Void::Testing::expect(
|
||||
!router.add(Method::Get, "/users/:name", handler)
|
||||
.has_value());
|
||||
}
|
||||
|
||||
Test header_lookup_is_case_insensitive()
|
||||
{
|
||||
ServerRequest request{
|
||||
.headers = {{"Content-Type", "application/json"}}};
|
||||
Void::Testing::require(
|
||||
request.header("content-type").has_value());
|
||||
Void::Testing::expect_eq(*request.header("CONTENT-TYPE"),
|
||||
std::string_view{"application/json"});
|
||||
}
|
||||
};
|
||||
|
||||
struct StaticFileTests : Void::Testing::Suite<StaticFileTests> {
|
||||
Test resolves_index_assets_and_content_types()
|
||||
{
|
||||
Void::FileSystem::TempDir directory{"void_net_static_"};
|
||||
write_file(directory / "index.html", "index");
|
||||
write_file(directory / "assets/app.js", "script");
|
||||
auto resolver = StaticFileResolver::create(directory.path());
|
||||
Void::Testing::require(resolver.has_value());
|
||||
|
||||
auto index = resolver->resolve("/");
|
||||
auto script = resolver->resolve("/assets/app.js?v=1");
|
||||
Void::Testing::require(index.has_value() && index->has_value());
|
||||
Void::Testing::require(script.has_value() &&
|
||||
script->has_value());
|
||||
Void::Testing::expect_eq((*index)->path.filename(),
|
||||
std::filesystem::path{"index.html"});
|
||||
Void::Testing::expect_eq(
|
||||
(*script)->content_type,
|
||||
std::string_view{"text/javascript; charset=utf-8"});
|
||||
Void::Testing::expect_eq((*script)->size,
|
||||
static_cast<std::uintmax_t>(6));
|
||||
}
|
||||
|
||||
Test rejects_plain_encoded_and_backslash_traversal()
|
||||
{
|
||||
Void::FileSystem::TempDir directory{"void_net_static_"};
|
||||
auto resolver = StaticFileResolver::create(directory.path());
|
||||
Void::Testing::require(resolver.has_value());
|
||||
Void::Testing::expect(
|
||||
!resolver->resolve("/../secret").has_value());
|
||||
Void::Testing::expect(
|
||||
!resolver->resolve("/%2e%2e/secret").has_value());
|
||||
Void::Testing::expect(
|
||||
!resolver->resolve("/..%2fsecret").has_value());
|
||||
Void::Testing::expect(
|
||||
!resolver->resolve("/dir%5csecret").has_value());
|
||||
}
|
||||
|
||||
Test missing_file_is_a_successful_empty_result()
|
||||
{
|
||||
Void::FileSystem::TempDir directory{"void_net_static_"};
|
||||
auto resolver = StaticFileResolver::create(directory.path());
|
||||
Void::Testing::require(resolver.has_value());
|
||||
auto missing = resolver->resolve("/missing.txt");
|
||||
Void::Testing::require(missing.has_value());
|
||||
Void::Testing::expect(!missing->has_value());
|
||||
}
|
||||
|
||||
Test rejects_symlinks_that_escape_the_document_root()
|
||||
{
|
||||
Void::FileSystem::TempDir root{"void_net_root_"};
|
||||
Void::FileSystem::TempDir outside{"void_net_outside_"};
|
||||
write_file(outside / "secret.txt", "secret");
|
||||
std::error_code error;
|
||||
std::filesystem::create_directory_symlink(
|
||||
outside.path(), root / "escape", error);
|
||||
if (error) {
|
||||
Void::Testing::skip(
|
||||
std::string_view{"directory symlinks are unavailable"});
|
||||
}
|
||||
auto resolver = StaticFileResolver::create(root.path());
|
||||
Void::Testing::require(resolver.has_value());
|
||||
Void::Testing::expect(
|
||||
!resolver->resolve("/escape/secret.txt").has_value());
|
||||
}
|
||||
};
|
||||
|
||||
struct WebSocketTests : Void::Testing::Suite<WebSocketTests> {
|
||||
Test lifecycle_callbacks_run_outside_registry_lock()
|
||||
{
|
||||
WebSocketSessions sessions;
|
||||
std::size_t opened = 0;
|
||||
std::string received;
|
||||
std::uint16_t close_code = 0;
|
||||
sessions.set_events(WebSocketEvents{
|
||||
.opened =
|
||||
[&](const auto& connection) {
|
||||
++opened;
|
||||
Void::Testing::expect(
|
||||
sessions.contains(connection->id()));
|
||||
},
|
||||
.text =
|
||||
[&](const auto& connection, std::string_view message) {
|
||||
Void::Testing::expect(
|
||||
sessions.find(connection->id()) != nullptr);
|
||||
received = message;
|
||||
},
|
||||
.closed =
|
||||
[&](WebSocketConnectionId,
|
||||
const WebSocketClose& close) {
|
||||
close_code = close.code;
|
||||
}});
|
||||
|
||||
auto connection = std::make_shared<FakeConnection>(7);
|
||||
auto accepted = sessions.open(connection);
|
||||
Void::Testing::require(accepted.has_value() && *accepted);
|
||||
Void::Testing::expect_eq(opened, static_cast<std::size_t>(1));
|
||||
Void::Testing::expect(sessions.receive_text({7}, "hello"));
|
||||
Void::Testing::expect_eq(received, std::string{"hello"});
|
||||
Void::Testing::expect(
|
||||
sessions.close({7}, WebSocketClose{1008, "policy"}));
|
||||
Void::Testing::expect(connection->closed);
|
||||
Void::Testing::expect_eq(connection->close_code,
|
||||
static_cast<std::uint16_t>(1008));
|
||||
Void::Testing::expect_eq(close_code,
|
||||
static_cast<std::uint16_t>(1008));
|
||||
Void::Testing::expect_eq(sessions.size(),
|
||||
static_cast<std::size_t>(0));
|
||||
}
|
||||
|
||||
Test duplicate_and_unknown_connections_are_ignored()
|
||||
{
|
||||
WebSocketSessions sessions;
|
||||
auto first = std::make_shared<FakeConnection>(9);
|
||||
auto duplicate = std::make_shared<FakeConnection>(9);
|
||||
auto accepted = sessions.open(first);
|
||||
auto rejected = sessions.open(duplicate);
|
||||
Void::Testing::require(accepted.has_value() && *accepted);
|
||||
Void::Testing::require(rejected.has_value());
|
||||
Void::Testing::expect(!*rejected);
|
||||
Void::Testing::expect(!sessions.receive_text({99}, "ignored"));
|
||||
Void::Testing::expect(!sessions.disconnect({99}));
|
||||
}
|
||||
|
||||
Test transport_disconnect_does_not_close_transport_again()
|
||||
{
|
||||
WebSocketSessions sessions;
|
||||
auto connection = std::make_shared<FakeConnection>(11);
|
||||
Void::Testing::require(*sessions.open(connection));
|
||||
Void::Testing::expect(
|
||||
sessions.disconnect({11}, {1000, "done"}));
|
||||
Void::Testing::expect(!connection->closed);
|
||||
}
|
||||
|
||||
Test shutdown_closes_every_connection_once()
|
||||
{
|
||||
WebSocketSessions sessions;
|
||||
auto first = std::make_shared<FakeConnection>(1);
|
||||
auto second = std::make_shared<FakeConnection>(2);
|
||||
Void::Testing::require(*sessions.open(first));
|
||||
Void::Testing::require(*sessions.open(second));
|
||||
Void::Testing::expect_eq(sessions.shutdown(),
|
||||
static_cast<std::size_t>(2));
|
||||
Void::Testing::expect(first->closed && second->closed);
|
||||
Void::Testing::expect_eq(sessions.shutdown(),
|
||||
static_cast<std::size_t>(0));
|
||||
auto after_shutdown =
|
||||
sessions.open(std::make_shared<FakeConnection>(3));
|
||||
Void::Testing::require(after_shutdown.has_value());
|
||||
Void::Testing::expect(!*after_shutdown);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,95 @@
|
||||
#include <Void/Security/Security.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Security::PasswordHashStrength;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct SecurityTests : Void::Testing::Suite<SecurityTests> {
|
||||
Test random_tokens_are_url_safe_and_unique()
|
||||
{
|
||||
auto first = Void::Security::random_token();
|
||||
auto second = Void::Security::random_token();
|
||||
Void::Testing::require(first.has_value());
|
||||
Void::Testing::require(second.has_value());
|
||||
Void::Testing::expect_eq(first->size(),
|
||||
static_cast<std::size_t>(43));
|
||||
Void::Testing::expect(first->find_first_of("+/=") ==
|
||||
std::string::npos);
|
||||
Void::Testing::expect_ne(*first, *second);
|
||||
}
|
||||
|
||||
Test random_token_rejects_zero_entropy()
|
||||
{
|
||||
Void::Testing::expect(
|
||||
!Void::Security::random_token(0).has_value());
|
||||
}
|
||||
|
||||
Test token_hash_is_deterministic_and_verifies_in_constant_time()
|
||||
{
|
||||
auto first = Void::Security::hash_token("session-secret");
|
||||
auto second = Void::Security::hash_token("session-secret");
|
||||
Void::Testing::require(first.has_value());
|
||||
Void::Testing::require(second.has_value());
|
||||
Void::Testing::expect_eq(*first, *second);
|
||||
Void::Testing::expect_eq(first->size(),
|
||||
static_cast<std::size_t>(64));
|
||||
|
||||
auto valid =
|
||||
Void::Security::verify_token("session-secret", *first);
|
||||
auto invalid =
|
||||
Void::Security::verify_token("other-secret", *first);
|
||||
Void::Testing::require(valid.has_value());
|
||||
Void::Testing::require(invalid.has_value());
|
||||
Void::Testing::expect(*valid);
|
||||
Void::Testing::expect(!*invalid);
|
||||
}
|
||||
|
||||
Test token_verification_rejects_malformed_digest()
|
||||
{
|
||||
auto malformed =
|
||||
Void::Security::verify_token("token", "not-hex");
|
||||
Void::Testing::require(malformed.has_value());
|
||||
Void::Testing::expect(!*malformed);
|
||||
}
|
||||
|
||||
Test password_hash_uses_argon2id_and_random_salts()
|
||||
{
|
||||
auto first = Void::Security::hash_password(
|
||||
"correct horse battery staple",
|
||||
PasswordHashStrength::Interactive);
|
||||
auto second = Void::Security::hash_password(
|
||||
"correct horse battery staple",
|
||||
PasswordHashStrength::Interactive);
|
||||
Void::Testing::require(first.has_value());
|
||||
Void::Testing::require(second.has_value());
|
||||
Void::Testing::expect(first->starts_with("$argon2id$"));
|
||||
Void::Testing::expect_ne(*first, *second);
|
||||
}
|
||||
|
||||
Test password_verification_accepts_only_the_original_password()
|
||||
{
|
||||
auto encoded = Void::Security::hash_password(
|
||||
"correct horse battery staple",
|
||||
PasswordHashStrength::Interactive);
|
||||
Void::Testing::require(encoded.has_value());
|
||||
|
||||
auto valid = Void::Security::verify_password(
|
||||
"correct horse battery staple", *encoded);
|
||||
auto invalid =
|
||||
Void::Security::verify_password("incorrect", *encoded);
|
||||
auto malformed = Void::Security::verify_password(
|
||||
"correct horse battery staple", "$argon2id$broken");
|
||||
Void::Testing::require(valid.has_value());
|
||||
Void::Testing::require(invalid.has_value());
|
||||
Void::Testing::require(malformed.has_value());
|
||||
Void::Testing::expect(*valid);
|
||||
Void::Testing::expect(!*invalid);
|
||||
Void::Testing::expect(!*malformed);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
Reference in new issue
Block a user