Files
EchoionWeb/tests/HttpSecurityTests.cpp
T
faumaray 3632f2cd43 update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-25 23:44:48 +03:00

301 lines
9.0 KiB
C++

#include "echoion/web/HttpSecurity.hpp"
#include "echoion/web/HttpServer.hpp"
#include <atomic>
#include <chrono>
#include <iostream>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace
{
using Echoion::Web::Security::ShortLinkRateLimiter;
namespace asio = boost::asio;
bool expect(bool condition, std::string_view message)
{
if (!condition) {
std::cerr << message << '\n';
}
return condition;
}
bool testShortSlugs()
{
using Echoion::Web::Security::validShortSlug;
std::string nonAscii(9, 'a');
nonAscii.push_back(static_cast<char>(0xe9));
return expect(validShortSlug("aZ019BcDeF"),
"ASCII short slug was rejected") &&
expect(!validShortSlug("aZ019BcDe_"),
"punctuation was accepted in a short slug") &&
expect(!validShortSlug("short"),
"short slug length was not enforced") &&
expect(!validShortSlug(nonAscii),
"locale-dependent non-ASCII alphanumeric was accepted");
}
bool testCidrsAndForwarding()
{
using Echoion::Web::Security::effectiveClientAddress;
using Echoion::Web::Security::parseTrustedProxyCidrs;
const std::vector<std::string> trustedTexts{"10.0.0.0/8",
"192.0.2.0/24"};
auto trusted = parseTrustedProxyCidrs(trustedTexts);
if (!expect(trusted.has_value(), "valid trusted proxy CIDRs failed")) {
return false;
}
const std::vector<std::string> invalidCidrs{"",
"10.0.0.0/",
"10.0.0.0/33",
"10.0.0.0/-1",
"10.0.0.0/+8",
"10.0.0.0/8 ",
" 10.0.0.0/8",
"2001:db8::/129",
"fe80::1%1/128",
"10.0.0.0/8/9",
"not-an-address"};
for (const auto& invalid : invalidCidrs) {
const std::vector<std::string> one{invalid};
if (!expect(!parseTrustedProxyCidrs(one),
"invalid trusted proxy CIDR was accepted: " +
invalid)) {
return false;
}
}
const std::vector<std::string> mappedV4Text{"192.0.2.0/24"};
auto mappedV4 = parseTrustedProxyCidrs(mappedV4Text);
const std::vector<std::string> mappedV6Text{"::ffff:192.0.2.0/120"};
auto mappedV6 = parseTrustedProxyCidrs(mappedV6Text);
if (!expect(mappedV4 && mappedV6,
"IPv4-mapped test networks did not parse") ||
!expect((*mappedV4)[0].contains(
asio::ip::make_address("::ffff:192.0.2.42")),
"IPv4 CIDR did not match an IPv4-mapped peer") ||
!expect(
(*mappedV6)[0].contains(asio::ip::make_address("192.0.2.42")),
"IPv4-mapped IPv6 CIDR did not match an IPv4 peer")) {
return false;
}
const auto immediate = asio::ip::make_address("10.0.0.10");
if (!expect(effectiveClientAddress(
immediate, "203.0.113.9, 198.51.100.7, 192.0.2.20",
*trusted) == "198.51.100.7",
"X-Forwarded-For was not walked from right to left") ||
!expect(effectiveClientAddress(immediate,
"203.0.113.9, 198.51.100.7",
*trusted) == "198.51.100.7",
"spoofed leftmost forwarded hop was trusted") ||
!expect(effectiveClientAddress(asio::ip::make_address("172.16.0.2"),
"203.0.113.9",
*trusted) == "172.16.0.2",
"untrusted direct peer supplied a forwarded address") ||
!expect(effectiveClientAddress(immediate,
"203.0.113.9, invalid, 192.0.2.20",
*trusted) == "10.0.0.10",
"malformed forwarded chain was partially accepted") ||
!expect(effectiveClientAddress(
asio::ip::make_address("::ffff:10.0.0.10"),
"198.51.100.7", *trusted) == "198.51.100.7",
"IPv4-mapped trusted peer was not recognized") ||
!expect(effectiveClientAddress(immediate,
"203.0.113.9, ::ffff:192.0.2.20",
*trusted) == "203.0.113.9",
"IPv4-mapped trusted intermediary was not recognized") ||
!expect(effectiveClientAddress(
asio::ip::make_address("::ffff:172.16.0.2"),
std::nullopt, *trusted) == "172.16.0.2",
"IPv4-mapped direct address was not normalized")) {
return false;
}
return true;
}
bool testRedirectLocations()
{
using Echoion::Web::Security::validRedirectLocation;
const std::vector<std::string_view> valid{
"https://example.test/watch?v=abc%201#fragment",
"HTTP://example.test/", "http://[2001:db8::1]:8080/path"};
for (const auto location : valid) {
if (!expect(validRedirectLocation(location),
"valid HTTP redirect was rejected")) {
return false;
}
}
const std::vector<std::string_view> invalid{
"",
"ftp://example.test/file",
"/relative/path",
"http:///missing-host",
"https://user@example.test/",
"https://example.test:",
"https://example.test:0/",
"https://example.test:65536/",
"https://example.test/a b"};
for (const auto location : invalid) {
if (!expect(!validRedirectLocation(location),
"unsafe redirect location was accepted")) {
return false;
}
}
for (unsigned int control = 0; control <= 0x20; ++control) {
std::string location = "https://example.test/path";
location.push_back(static_cast<char>(control));
if (!expect(!validRedirectLocation(location),
"ASCII control was accepted in redirect location")) {
return false;
}
}
for (const unsigned int control : {0x7fU, 0x80U, 0x9fU}) {
std::string location = "https://example.test/path";
location.push_back(static_cast<char>(control));
if (!expect(!validRedirectLocation(location),
"DEL/C1 control was accepted in redirect location")) {
return false;
}
}
return true;
}
bool testTrustedProxyRuntimeUpdates()
{
Echoion::Web::HttpServer server;
const std::vector<std::string> initial{"127.0.0.0/8"};
const std::vector<std::string> replacement{"::1/128"};
const std::vector<std::string> invalid{"127.0.0.1/129"};
const std::vector<std::string> none;
return expect(server.setTrustedProxyCidrs(initial).has_value(),
"initial live trusted-proxy update failed") &&
expect(server.setTrustedProxyCidrs(replacement).has_value(),
"replacement live trusted-proxy update failed") &&
expect(!server.setTrustedProxyCidrs(invalid),
"invalid live trusted-proxy update was accepted") &&
expect(server.setTrustedProxyCidrs(none).has_value(),
"clearing live trusted proxies failed");
}
bool testRateLimiterFairnessAndBounds()
{
using namespace std::chrono_literals;
const auto now = ShortLinkRateLimiter::TimePoint{} + 1s;
ShortLinkRateLimiter fair({
.globalRate = 0.0,
.globalBurst = 2.0,
.peerRate = 0.0,
.peerBurst = 1.0,
.maxPeers = 4,
.idleTimeout = 1min,
.sweepInterval = 1min,
});
if (!expect(fair.allow("peer-a", now),
"first peer request was rejected") ||
!expect(!fair.allow("peer-a", now),
"peer burst limit was not enforced") ||
!expect(fair.allow("peer-b", now),
"peer rejection consumed unrelated global capacity")) {
return false;
}
ShortLinkRateLimiter bounded({
.globalRate = 100.0,
.globalBurst = 100.0,
.peerRate = 100.0,
.peerBurst = 2.0,
.maxPeers = 2,
.idleTimeout = 100ms,
.sweepInterval = 1h,
});
if (!expect(bounded.allow("peer-a", now) &&
bounded.allow("peer-b", now),
"bounded limiter rejected initial peers") ||
!expect(!bounded.allow("peer-c", now),
"bounded limiter exceeded its peer cap") ||
!expect(bounded.trackedPeerCount() == 2,
"bounded limiter retained too many peers") ||
!expect(bounded.allow("peer-c", now + 200ms),
"idle peer entries were not evicted") ||
!expect(bounded.trackedPeerCount() <= 2,
"idle eviction broke the peer cap")) {
return false;
}
return true;
}
bool testRateLimiterConcurrency()
{
using namespace std::chrono_literals;
ShortLinkRateLimiter limiter({
.globalRate = 0.0,
.globalBurst = 100.0,
.peerRate = 0.0,
.peerBurst = 5.0,
.maxPeers = 16,
.idleTimeout = 1min,
.sweepInterval = 1min,
});
const auto now = ShortLinkRateLimiter::TimePoint{} + 1s;
std::atomic<unsigned int> allowed{0};
std::vector<std::thread> workers;
workers.reserve(32);
for (int index = 0; index < 32; ++index) {
workers.emplace_back([&] {
if (limiter.allow("one-peer", now)) {
++allowed;
}
});
}
for (auto& worker : workers) {
worker.join();
}
if (!expect(allowed.load() == 5,
"concurrent limiter admitted beyond the peer burst")) {
return false;
}
ShortLinkRateLimiter global({
.globalRate = 0.0,
.globalBurst = 7.0,
.peerRate = 0.0,
.peerBurst = 1.0,
.maxPeers = 64,
.idleTimeout = 1min,
.sweepInterval = 1min,
});
allowed = 0;
workers.clear();
for (int index = 0; index < 32; ++index) {
workers.emplace_back([&, index] {
if (global.allow("peer-" + std::to_string(index), now)) {
++allowed;
}
});
}
for (auto& worker : workers) {
worker.join();
}
return expect(allowed.load() == 7,
"concurrent limiter admitted beyond the global burst");
}
} // namespace
int main()
{
return testShortSlugs() && testCidrsAndForwarding() &&
testRedirectLocations() &&
testTrustedProxyRuntimeUpdates() &&
testRateLimiterFairnessAndBounds() &&
testRateLimiterConcurrency()
? 0
: 1;
}