feat: implement MoloApp plans 01-15 with integration

Full C++23 framework tree: runtime, observability, security,
data, app, realtime, supervisor, clients, CLI, example plus
enterprise tenancy, audit, operability, governance,
supplychain. Postgres via docker compose for tests.
This commit is contained in:
2026-10-23 18:20:04 +02:00
parent 54068f1953
commit 3c4334cec9
1068 changed files with 100899 additions and 2 deletions
+158
View File
@@ -0,0 +1,158 @@
// Auth test: Basic parsing, login paths, re-auth gate, route guards.
#include <cstdint>
#include <cstdio>
#include <memory>
#include <string>
#include "Authenticator.h"
#include "DenialSink.h"
#include "Guard.h"
#include "HttpMessageView.h"
#include "PasswordHasher.h"
using namespace molo::security::auth;
using molo::security::guard::HttpRequestView;
using molo::security::guard::NullSink;
using molo::security::session::Session;
static int failures = 0;
static void check(bool ok, const char* name) {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) ++failures;
}
struct TestUsers : IUserStore {
Account acct;
bool has = false;
bool find(const std::string& username, Account& out) override {
if (!has || username != "alice") return false;
out = acct;
return true;
}
bool store_rehash(const std::string& username, const std::string& encoded) override {
if (username != "alice") return false;
acct.argon2id_hash = encoded;
return true;
}
};
int main() {
NullSink sink;
// Basic parsing.
{
HttpRequestView r;
r.headers.emplace_back("authorization", "Basic YWxpY2U6czNjcml0"); // alice:s3crit
auto c = Authenticator::parse_basic(r);
check(c.present && c.username == "alice" && c.password == "s3crit", "basic parse");
HttpRequestView r2;
check(!Authenticator::parse_basic(r2).present, "basic missing");
HttpRequestView r3;
r3.headers.emplace_back("authorization", "Basic !!!");
check(!Authenticator::parse_basic(r3).present, "basic malformed");
HttpRequestView r4;
r4.headers.emplace_back("authorization", "Basic bm9jb2xvbg=="); // "nocolon"
check(!Authenticator::parse_basic(r4).present, "basic no colon");
}
// Login ok / bad / unknown at small test params.
auto users = std::make_shared<TestUsers>();
{
molo::security::crypto::PasswordHasher::Params p;
p.memory_kib = 8;
p.passes = 1;
p.lanes = 1;
std::string enc;
check(molo::security::crypto::PasswordHasher::hash_password("s3crit", p, enc), "mk hash");
users->acct.user_id = "u-1";
users->acct.argon2id_hash = enc;
users->acct.roles = {{"reader", {{{"read"}}}}};
users->has = true;
}
{
Authenticator auth(users, sink);
std::uint64_t now = 5000;
auth.set_clock([&] { return now; });
HttpRequestView r;
r.now_unix_sec = now;
r.path = "/login";
BasicCredentials good{"alice", "s3crit", true};
BasicCredentials bad{"alice", "wrong", true};
BasicCredentials unknown{"mallory", "x", true};
Session s;
check(auth.login(good, "10.0.0.1", s, r) == Authenticator::LoginResult::Ok &&
s.user_id == "u-1",
"login ok");
// Rehash to OWASP params happened on login; restore small hash for speed.
{
molo::security::crypto::PasswordHasher::Params p;
p.memory_kib = 8;
p.passes = 1;
p.lanes = 1;
std::string enc;
molo::security::crypto::PasswordHasher::hash_password("s3crit", p, enc);
users->acct.argon2id_hash = enc;
}
Session s2;
check(auth.login(bad, "10.0.0.1", s2, r) == Authenticator::LoginResult::BadCredentials,
"login bad password");
Session s3;
check(auth.login(unknown, "10.0.0.2", s3, r) ==
Authenticator::LoginResult::BadCredentials,
"login unknown user");
// Rate limit: 10/min budget, 11th attempt trips.
Authenticator::LoginResult last = Authenticator::LoginResult::Ok;
for (int i = 0; i < 12; ++i) {
Session tmp;
BasicCredentials fresh{"mallory", "nope", true};
last = auth.login(fresh, "10.7.7.7", tmp, r);
}
check(last == Authenticator::LoginResult::RateLimited, "login rate limit trips");
}
// Locked account.
{
auto locked = std::make_shared<TestUsers>();
locked->has = true;
locked->acct.user_id = "u-2";
locked->acct.argon2id_hash = "";
Authenticator auth(locked, sink);
HttpRequestView r;
Session s;
BasicCredentials c{"alice", "anything", true};
check(auth.login(c, "10.0.0.9", s, r) == Authenticator::LoginResult::Locked, "locked");
}
// Re-auth gate.
{
Session s;
s.privilege = Session::Privilege::User;
s.last_reauth_at = 1000;
check(Authenticator::reauth_fresh(s, 1000 + 9 * 60), "reauth fresh");
check(!Authenticator::reauth_fresh(s, 1000 + 11 * 60), "reauth stale");
Authenticator::mark_reauth(s, 2000);
check(Authenticator::reauth_fresh(s, 2000), "reauth marked");
Session anon;
check(!Authenticator::reauth_fresh(anon, 2000), "reauth anon denied");
}
// Route guards: deny by default.
{
Session anon;
HttpRequestView r;
auto v = Guard::check_logged(anon, {}, {{{"read"}}}, r, sink);
check(!v.allowed && v.http_status == 401, "guard anon 401");
Session user;
user.privilege = Session::Privilege::User;
std::vector<Role> roles = {{"reader", {{{"read"}}}}};
auto v2 = Guard::check(user, roles, {{{"read"}}});
check(v2.allowed, "guard granted");
auto v3 = Guard::check(user, roles, {{{"admin"}}});
check(!v3.allowed && v3.http_status == 403, "guard forbidden 403");
auto v4 = Guard::check(user, {}, {});
check(v4.allowed, "guard no requirements passes authed");
}
std::printf(failures == 0 ? "ALL AUTH TESTS PASSED\n" : "FAILURES: %d\n", failures);
return failures == 0 ? 0 : 1;
}
+308
View File
@@ -0,0 +1,308 @@
// Security crypto test: primitives, key hierarchy, password hashing.
// Standalone: links libsecurity only. Exit 0 on full pass, 1 otherwise.
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
#include "AesGcm.h"
#include "Base64.h"
#include "Blake2b.h"
#include "ChaCha20Poly1305.h"
#include "CryptoBox.h"
#include "Hmac.h"
#include "KeyHierarchy.h"
#include "PasswordHasher.h"
#include "SecureRandom.h"
#include "Sha256.h"
using namespace molo::security::crypto;
static int failures = 0;
static void check(bool ok, const char* name) {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) ++failures;
}
static std::string hex(const std::uint8_t* d, std::size_t n) {
static const char* k = "0123456789abcdef";
std::string o;
for (std::size_t i = 0; i < n; ++i) {
o.push_back(k[d[i] >> 4]);
o.push_back(k[d[i] & 15]);
}
return o;
}
static std::string hex(const std::vector<std::uint8_t>& v) {
return hex(v.data(), v.size());
}
int main() {
// Base64 RFC 4648 vectors.
check(Base64::encode(std::string()) == "", "b64 empty");
check(Base64::encode("f") == "Zg==", "b64 f");
check(Base64::encode("foobar") == "Zm9vYmFy", "b64 foobar");
{
std::string out;
check(Base64::decode("Zm9vYmFy", out) && out == "foobar", "b64 decode");
check(!Base64::decode("Zm9vYmF!", out), "b64 reject bad char");
check(!Base64::decode("abc", out), "b64 reject bad length");
check(Base64::encode_url("foobar") == "Zm9vYmFy", "b64url foobar");
check(Base64::decode_url("Zm9vYmFy", out) && out == "foobar", "b64url decode");
check(!Base64::decode_url("a", out), "b64url reject len 1 mod 4");
}
// SHA-256 FIPS vectors.
check(Sha256::hex(Sha256::hash("")) ==
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"sha256 empty");
check(Sha256::hex(Sha256::hash("abc")) ==
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
"sha256 abc");
{
Sha256 s;
std::string a(1000, 'a');
for (int i = 0; i < 1000; ++i) s.update(a);
check(Sha256::hex(s.final()) ==
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0",
"sha256 1M a");
}
// HMAC-SHA-256 RFC 4231 cases 1..3.
{
std::uint8_t k1[20];
for (int i = 0; i < 20; ++i) k1[i] = 0x0b;
auto t1 = Hmac::sha256(k1, 20, (const std::uint8_t*)"Hi There", 8);
check(Hmac::hex(t1) == "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
"hmac case1");
auto t2 = Hmac::sha256("Jefe", "what do ya want for nothing?");
check(Hmac::hex(t2) == "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
"hmac case2");
std::uint8_t k3[20], d3[50];
for (int i = 0; i < 20; ++i) k3[i] = 0xaa;
for (int i = 0; i < 50; ++i) d3[i] = 0xdd;
auto t3 = Hmac::sha256(k3, 20, d3, 50);
check(Hmac::hex(t3) == "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe",
"hmac case3");
}
// HKDF RFC 5869 case 1 (cross-checked with openssl).
{
std::uint8_t ikm[22], salt[13], info[10];
for (int i = 0; i < 22; ++i) ikm[i] = 0x0b;
for (int i = 0; i < 13; ++i) salt[i] = (std::uint8_t)i;
for (int i = 0; i < 10; ++i) info[i] = (std::uint8_t)(0xf0 + i);
std::uint8_t okm[42];
check(Hkdf::derive(ikm, 22, salt, 13, info, 10, okm, 42) &&
hex(okm, 42) ==
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b8"
"87185865",
"hkdf case1");
}
// BLAKE2b (cross-checked with python hashlib).
{
auto h = Blake2b::hash(nullptr, 0, 64);
check(hex(h) ==
"786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee58"
"5313896444934eb04b903a685b1448b755d56f701afe9be2ce",
"blake2b empty");
auto h2 = Blake2b::hash((const std::uint8_t*)"abc", 3, 64);
check(hex(h2) ==
"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab79"
"2dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923",
"blake2b abc");
}
// AES-256-GCM (cross-checked with python cryptography).
{
std::uint8_t key[32] = {0}, nonce[12] = {0}, tag[16], dummy = 0;
check(AesGcm::seal(key, nonce, nullptr, 0, nullptr, 0, &dummy, tag) &&
hex(tag, 16) == "530f8afbc74536b9a963b4f1c4cb738b",
"aesgcm zero tag");
std::uint8_t pt[16] = {0}, ct[16], back[16];
check(AesGcm::seal(key, nonce, nullptr, 0, pt, 16, ct, tag) &&
hex(ct, 16) == "cea7403d4d606b6e074ec5d3baf39d18" &&
hex(tag, 16) == "d0d1c8a799996bf0265b98b5d48ab919",
"aesgcm zero block");
check(AesGcm::open(key, nonce, nullptr, 0, ct, 16, tag, back), "aesgcm roundtrip");
tag[0] ^= 1;
std::uint8_t untouched[16];
for (int i = 0; i < 16; ++i) untouched[i] = 0xAA;
check(!AesGcm::open(key, nonce, nullptr, 0, ct, 16, tag, untouched) &&
untouched[0] == 0xAA,
"aesgcm tamper fails closed");
}
// ChaCha20-Poly1305 RFC 8439 A.5 (cross-checked with python cryptography).
{
std::uint8_t key[32], nonce[12] = {0, 0, 0, 9, 0, 0, 0, 74, 0, 0, 0, 0};
for (int i = 0; i < 32; ++i) key[i] = (std::uint8_t)i;
std::uint8_t aad[12] = {0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2,
0xc3, 0xc4, 0xc5, 0xc6, 0xc7};
std::string pt =
"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the "
"future, sunscreen would be it.";
std::vector<std::uint8_t> ct(pt.size()), back(pt.size());
std::uint8_t tag[16];
check(ChaCha20Poly1305::seal(key, nonce, aad, 12, (const std::uint8_t*)pt.data(), pt.size(),
ct.data(), tag) &&
hex(tag, 16) == "a0dcd40f06b40fe14d7d51791c187b9b" &&
hex(ct).substr(0, 32) == "5c90838db44879743e6bfd58c64e05a8",
"chacha A.5 vector");
check(ChaCha20Poly1305::open(key, nonce, aad, 12, ct.data(), ct.size(), tag, back.data()) &&
std::string((char*)back.data(), back.size()) == pt,
"chacha roundtrip");
ct[0] ^= 1;
check(!ChaCha20Poly1305::open(key, nonce, aad, 12, ct.data(), ct.size(), tag, back.data()),
"chacha tamper fails closed");
}
// SecureRandom basics.
{
auto a = SecureRandom::bytes(32);
auto b = SecureRandom::bytes(32);
check(a.size() == 32 && b.size() == 32 && a != b, "csprng unique");
check(SecureRandom::constant_time_equal("abc", "abc") &&
!SecureRandom::constant_time_equal("abc", "abd") &&
!SecureRandom::constant_time_equal("abc", "abcd"),
"ct equal");
check(SecureRandom::token(16).size() == 22, "token length");
check(SecureRandom::bytes(0).empty(), "zero bytes ok");
check(!SecureRandom::bytes(nullptr, 4), "null fails closed");
}
// KeyHierarchy: seed, derive, rotate, overlap, expiry.
{
KeyHierarchy kh;
std::uint8_t out[32];
check(!kh.subkey(1, KeyHierarchy::Purpose::Data, out), "no key before seed");
check(kh.seed_random(), "seed random");
check(kh.current_epoch() == 1, "epoch 1");
std::uint8_t d1[32], c1[32];
check(kh.subkey(1, KeyHierarchy::Purpose::Data, d1), "derive data e1");
check(kh.subkey(1, KeyHierarchy::Purpose::Cookies, c1), "derive cookies e1");
check(std::string((char*)d1, 32) != std::string((char*)c1, 32), "purpose separation");
check(kh.rotate(1000), "rotate");
check(kh.current_epoch() == 2, "epoch 2");
check(kh.subkey(1, KeyHierarchy::Purpose::Data, out), "old epoch readable in window");
check(kh.rotate(1000 + 25 * 3600), "rotate after window");
check(!kh.subkey(1, KeyHierarchy::Purpose::Data, out), "old epoch expired");
KeyHierarchy::KeyId id{7, KeyHierarchy::Purpose::Csrf}, back;
check(KeyHierarchy::KeyId::decode(id.encode(), back) && back.epoch == 7 &&
back.purpose == KeyHierarchy::Purpose::Csrf,
"keyid codec");
check(!KeyHierarchy::KeyId::decode("bogus", back), "keyid reject");
}
// CryptoBox envelopes, both algorithms.
for (auto alg : {CryptoBox::Alg::AesGcm, CryptoBox::Alg::ChaCha20Poly1305}) {
KeyHierarchy kh;
check(kh.seed_random(), "box seed");
CryptoBox box(kh, alg);
std::string env, plain;
const char* tag = alg == CryptoBox::Alg::AesGcm ? "aes" : "chacha";
char name[64];
std::snprintf(name, sizeof name, "box %s roundtrip", tag);
check(box.seal("hello envelope", KeyHierarchy::Purpose::Data, env) &&
box.open(env, KeyHierarchy::Purpose::Data, plain) && plain == "hello envelope",
name);
std::snprintf(name, sizeof name, "box %s wrong purpose", tag);
check(!box.open(env, KeyHierarchy::Purpose::Cookies, plain), name);
std::snprintf(name, sizeof name, "box %s tamper", tag);
std::string bad = env;
bad[bad.size() / 2] ^= 1;
check(!box.open(bad, KeyHierarchy::Purpose::Data, plain), name);
std::snprintf(name, sizeof name, "box %s rotation overlap", tag);
check(kh.rotate(5000) && box.open(env, KeyHierarchy::Purpose::Data, plain) &&
plain == "hello envelope",
name);
}
// Argon2id oracle vectors (python argon2-cffi, Type.ID).
struct ArgonCase {
const char* pwd;
std::size_t pwd_len; // 0 means use full literal below via marker
const char* salt;
std::uint32_t t, m, p, len;
const char* hex;
};
const ArgonCase cases[] = {
{"password", 8, "somesalt", 2, 8, 1, 32,
"fdb4ddb6d5887131b66f0b2a3740c077dd05b755845861f6b5a1dde8b1071646"},
{"password", 8, "somesalt", 3, 64, 1, 32,
"b9e3bfda58fb95f1e1e479af4e01bfade5a0dba34d400a254f770462674169e6"},
{"hello world", 11, "12345678", 1, 256, 1, 16, "134c882631b4af2720ffb6f4d1c54ac8"},
{"", 0, "emptypass", 1, 8, 1, 24, "0c520f6d084e137c8163c2811be4505efaa8d6058083adc4"},
{"password", 8, "somesalt", 2, 16, 2, 32,
"747d7631b182faf749d7efc31aec31df4ecfe3b57c792f53800ac2c9978b4888"},
};
for (std::size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) {
const auto& c = cases[i];
PasswordHasher::Params prm;
prm.passes = c.t;
prm.memory_kib = c.m;
prm.lanes = c.p;
prm.hash_len = c.len;
prm.salt_len = std::uint32_t(std::string(c.salt).size());
std::vector<std::uint8_t> tag;
std::string pwd(c.pwd, c.pwd_len);
bool ok = PasswordHasher::derive(pwd, c.salt, "", "", prm, tag);
char name[64];
std::snprintf(name, sizeof name, "argon2id oracle case %zu", i);
check(ok && hex(tag) == c.hex, name);
}
{ // 100-byte password, 1 MiB memory, 64-byte tag
PasswordHasher::Params prm;
prm.passes = 2;
prm.memory_kib = 1024;
prm.lanes = 1;
prm.hash_len = 64;
prm.salt_len = 16;
std::vector<std::uint8_t> tag;
check(PasswordHasher::derive(std::string(100, 'p'), std::string(16, 's'), "", "", prm,
tag) &&
hex(tag) ==
"f27d9a7175df6d14e8ebef7318b5a546df0a04102752abcd1dcd288eb00c547ae84f4ffe7fc"
"b1115282b7aa6e0dd013ec2ffac6298469155254a84efdde0cb04",
"argon2id oracle case 5");
}
// Password hash/verify round trip at small test params.
{
PasswordHasher::Params prm;
prm.memory_kib = 8;
prm.passes = 1;
prm.lanes = 1;
std::string enc;
check(PasswordHasher::hash_password("s3cret!", prm, enc), "hash small");
check(PasswordHasher::verify("s3cret!", enc), "verify good");
check(!PasswordHasher::verify("s3cret?", enc), "verify bad");
check(!PasswordHasher::verify("s3cret!", "$argon2id$v=19$m=8,t=1,p=1$broken"),
"verify malformed");
PasswordHasher::Params weak = prm;
weak.memory_kib = 8;
PasswordHasher::Params strong = prm;
strong.memory_kib = 64;
check(!PasswordHasher::needs_rehash(enc, weak), "no rehash same params");
check(PasswordHasher::needs_rehash(enc, strong), "rehash stronger params");
std::string encp;
check(PasswordHasher::hash_password_peppered("pw", "pepper", prm, encp) &&
PasswordHasher::verify_peppered("pw", "pepper", encp) &&
!PasswordHasher::verify_peppered("pw", "wrong", encp) &&
!PasswordHasher::verify("pw", encp),
"pepper roundtrip");
}
// OWASP defaults sanity.
{
auto d = PasswordHasher::owasp_defaults();
check(d.memory_kib == 19456 && d.passes == 2 && d.lanes == 1 && d.salt_len == 16,
"owasp params");
}
std::printf(failures == 0 ? "ALL CRYPTO TESTS PASSED\n" : "FAILURES: %d\n", failures);
return failures == 0 ? 0 : 1;
}
+256
View File
@@ -0,0 +1,256 @@
// Guard test: CSRF, CORS, headers, rate limit, body limits, paths, SQL.
#include <cstdint>
#include <cstdio>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include "BodyLimits.h"
#include "CorsPolicy.h"
#include "CsrfGuard.h"
#include "DenialSink.h"
#include "HttpMessageView.h"
#include "PathGuard.h"
#include "RateLimiter.h"
#include "SecurityHeaders.h"
#include "Session.h"
#include "SqlSafety.h"
using namespace molo::security::guard;
using molo::security::session::Session;
static int failures = 0;
static void check(bool ok, const char* name) {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) ++failures;
}
static HttpRequestView post(const std::string& path) {
HttpRequestView r;
r.method = "POST";
r.path = path;
r.peer_ip = "10.0.0.1";
r.now_unix_sec = 1000;
return r;
}
static Session mk_session() {
Session s;
s.id = "AAAAAAAAAAAAAAAAAAAAAA";
s.csrf_token = "tok-123";
return s;
}
int main() {
NullSink sink;
// CSRF: synchronizer via header and form field.
{
CsrfGuard g(CsrfGuard::Policy(), "hmac-key-for-tests", sink);
Session s = mk_session();
auto r = post("/submit");
HttpResponseView res;
check(!g.enforce(r, res, s) && res.status == 403, "csrf missing token 403");
auto r2 = post("/submit");
r2.headers.emplace_back("x-csrf-token", "tok-123");
check(g.enforce(r2, res, s), "csrf header token passes");
auto r3 = post("/submit");
check(g.check(r3, s, "tok-123") == CsrfGuard::Verdict::Allow, "csrf form field passes");
Session other = mk_session();
other.id = "BBBBBBBBBBBBBBBBBBBBBB";
other.csrf_token = "tok-999";
auto r4 = post("/submit");
r4.headers.emplace_back("x-csrf-token", "tok-123");
check(g.check(r4, other) == CsrfGuard::Verdict::Deny, "csrf foreign token fails");
HttpRequestView safe;
safe.method = "GET";
check(g.check(safe, s) == CsrfGuard::Verdict::Allow, "csrf safe method passes");
}
// CSRF: signed double-submit fallback.
{
CsrfGuard g(CsrfGuard::Policy(), "hmac-key-for-tests", sink);
Session s = mk_session();
std::string nonce = "n-1";
std::string cookie = nonce + "." + g.fallback_token(s.id, nonce);
auto r = post("/submit");
r.headers.emplace_back("cookie", "molo_csrf=" + cookie);
r.headers.emplace_back("x-csrf-token", cookie);
check(g.check(r, s) == CsrfGuard::Verdict::Allow, "csrf fallback passes");
auto r2 = post("/submit");
r2.headers.emplace_back("cookie", "molo_csrf=" + cookie);
r2.headers.emplace_back("x-csrf-token", "tampered");
check(g.check(r2, s) == CsrfGuard::Verdict::Deny, "csrf fallback echo fails");
}
// CSRF: Fetch Metadata block and exemptions.
{
CsrfGuard::Policy p;
p.exempt_paths = {"/hooks/stripe"};
CsrfGuard g(p, "k", sink);
Session s = mk_session();
auto r = post("/submit");
r.headers.emplace_back("sec-fetch-site", "cross-site");
r.headers.emplace_back("x-csrf-token", "tok-123");
check(g.check(r, s) == CsrfGuard::Verdict::Deny, "csrf cross-site blocked");
auto r2 = post("/hooks/stripe");
check(g.check(r2, s) == CsrfGuard::Verdict::Exempt, "csrf exempt path");
}
// CORS: default deny, allow-list, preflight, wildcard guard.
{
CorsPolicy::Policy p;
check(CorsPolicy::validate(p).empty(), "cors empty valid");
CorsPolicy::Policy bad;
bad.allow_origins = {"*"};
bad.allow_credentials = true;
check(!CorsPolicy::validate(bad).empty(), "cors wildcard+creds rejected");
CorsPolicy closed(p, sink);
auto r = post("/api");
r.headers.emplace_back("origin", "https://evil.test");
HttpResponseView res;
closed.apply(r, res);
check(res.header("Access-Control-Allow-Origin").empty(), "cors default deny");
CorsPolicy::Policy open;
open.allow_origins = {"https://app.test"};
open.allow_credentials = true;
CorsPolicy c(open, sink);
auto r2 = post("/api");
r2.headers.emplace_back("origin", "https://app.test");
HttpResponseView res2;
c.apply(r2, res2);
check(res2.header("Access-Control-Allow-Origin") == "https://app.test" &&
res2.header("Access-Control-Allow-Credentials") == "true",
"cors exact origin with creds");
HttpRequestView pre;
pre.method = "OPTIONS";
pre.path = "/api";
pre.headers.emplace_back("origin", "https://app.test");
pre.headers.emplace_back("access-control-request-method", "POST");
HttpResponseView res3;
check(c.preflight(pre, res3) && res3.status == 204 &&
!res3.header("Access-Control-Allow-Methods").empty(),
"cors preflight");
HttpRequestView pre2 = pre;
pre2.headers.clear();
pre2.headers.emplace_back("origin", "https://evil.test");
pre2.headers.emplace_back("access-control-request-method", "POST");
HttpResponseView res4;
check(c.preflight(pre2, res4) && res4.status == 403, "cors preflight deny");
}
// Security headers: all six families, TLS-gated HSTS, opt-out.
{
SecurityHeaders h;
HttpRequestView r;
r.is_tls = true;
r.path = "/";
HttpResponseView res;
h.apply(r, res);
check(!res.header("Strict-Transport-Security").empty() &&
res.header("X-Frame-Options") == "DENY" &&
res.header("X-Content-Type-Options") == "nosniff" &&
!res.header("Referrer-Policy").empty() &&
!res.header("Permissions-Policy").empty() &&
!res.header("Content-Security-Policy").empty(),
"headers six families");
HttpRequestView plain;
plain.path = "/";
HttpResponseView res2;
h.apply(plain, res2);
check(res2.header("Strict-Transport-Security").empty() &&
!res2.header("X-Frame-Options").empty(),
"hsts tls only");
SecurityHeaders::Policy p;
p.opt_out_paths = {"/legacy"};
SecurityHeaders h2(p);
HttpRequestView leg;
leg.is_tls = true;
leg.path = "/legacy";
HttpResponseView res3;
h2.apply(leg, res3);
check(res3.header("X-Frame-Options").empty(), "headers opt-out");
}
// Rate limiter: burst then 429 with Retry-After.
{
RateLimiter::Policy p;
p.per_ip = {5, 1, 10}; // 5/min, no burst headroom
p.per_user = {1000, 2, 10};
RateLimiter lim(p, &sink);
std::uint64_t now = 9000;
lim.set_clock([&] { return now; });
HttpRequestView r;
r.peer_ip = "10.1.1.1";
r.path = "/t";
int allowed = 0;
for (int i = 0; i < 7; ++i) {
if (lim.check(r, "").allowed) ++allowed;
}
check(allowed == 5, "ratelimit burst cap");
HttpResponseView res;
check(!lim.enforce(r, res, "") && res.status == 429 &&
!res.header("Retry-After").empty(),
"ratelimit 429 with retry-after");
now += 61;
check(lim.check(r, "").allowed, "ratelimit refills");
}
// Body limits: 431/413 mapping, JSON depth, form fields.
{
BodyLimits lim(BodyLimits::Policy(), sink);
HttpRequestView r;
HttpResponseView res;
check(!lim.enforce(lim.check_headers(17000, 100, r), r, res) && res.status == 431,
"limits headers total 431");
check(!lim.enforce(lim.check_headers(100, 9000, r), r, res), "limits single 431");
check(!lim.enforce(lim.check_body(2 * 1024 * 1024, 0, r), r, res) && res.status == 413,
"limits body 413");
check(lim.enforce(lim.check_body(2 * 1024 * 1024, 5 * 1024 * 1024, r), r, res),
"limits route override");
check(!lim.enforce(lim.check_body(11 * 1024 * 1024, 100 * 1024 * 1024, r), r, res),
"limits override capped at 10MB");
std::string deep(33, '[');
check(!lim.check_json_depth(deep, r), "limits json depth 33");
check(lim.check_json_depth("{\"a\":[1,2]}", r), "limits json ok");
check(!lim.check_form_fields(1001, r) && lim.check_form_fields(1000, r),
"limits form fields");
}
// Path guard: traversal, abs, drive, symlink, jail.
{
std::string out;
check(PathGuard::canonicalize("/a/b/../c", out) && out == "/a/c", "path canonical");
check(!PathGuard::canonicalize("/../etc", out), "path climb rejected");
check(!PathGuard::canonicalize("/a/../../x", out), "path deep climb");
check(!PathGuard::canonicalize("C:\\win", out), "path drive rejected");
::mkdir("/tmp/molo_path_root", 0755);
::mkdir("/tmp/molo_path_root/sub", 0755);
::unlink("/tmp/molo_path_root/link");
check(::symlink("/etc", "/tmp/molo_path_root/link") == 0, "path fixture symlink");
check(PathGuard::check("/tmp/molo_path_root", "/sub", out, &sink, nullptr) &&
out == "/tmp/molo_path_root/sub",
"path jail ok");
check(!PathGuard::check("/tmp/molo_path_root", "/link/passwd", out, &sink, nullptr),
"path symlink rejected");
check(PathGuard::check("/tmp/molo_path_root", "/link", out, &sink, nullptr, true),
"path symlink allowed when opted in");
::unlink("/tmp/molo_path_root/link");
}
// SQL safety contract.
{
BoundQuery q{"SELECT * FROM t WHERE a = ? AND b = ?",
{{BoundValue::Type::Text, "x"}, {BoundValue::Type::Int, "1"}}};
std::string reason;
check(SqlSafety::check(q, reason), "sql bound ok");
BoundQuery bad{"SELECT * FROM t WHERE a = ?",
{{BoundValue::Type::Text, "x"}, {BoundValue::Type::Int, "1"}}};
check(!SqlSafety::check(bad, reason), "sql arity mismatch");
check(SqlSafety::quote_identifier("users") == "\"users\"", "sql quote ok");
check(SqlSafety::quote_identifier("a;b").empty(), "sql quote rejects");
}
std::printf(failures == 0 ? "ALL GUARD TESTS PASSED\n" : "FAILURES: %d\n", failures);
return failures == 0 ? 0 : 1;
}
@@ -0,0 +1,88 @@
// Secrets test: JSON parsing, file plus env override, rotation, redaction.
#include <cstdint>
#include <cstdio>
#include <string>
#include <unordered_map>
#include "SecretsProvider.h"
using namespace molo::security::secret;
static int failures = 0;
static void check(bool ok, const char* name) {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) ++failures;
}
int main() {
// JSON parser.
{
std::unordered_map<std::string, std::string> m;
check(SecretsProvider::parse_json_object("{\"a\":\"b\",\"n\":42,\"t\":true}", m) &&
m["a"] == "b" && m["n"] == "42" && m["t"] == "true",
"json flat");
check(SecretsProvider::parse_json_object("{\"o\":{\"k\":\"v\"}}", m) && m["o.k"] == "v",
"json nested");
check(!SecretsProvider::parse_json_object("{bad", m), "json malformed");
check(!SecretsProvider::parse_json_object("{\"a\":\"b\"} trailing", m), "json trailing");
}
// File load with env override winning.
const char* path = "/tmp/molo_test_env.json";
{
FILE* fp = ::fopen(path, "w");
::fputs("{\"master_key\":\"file-value-0123456789abcdef\","
"\"workers\":4,\"debug\":false}",
fp);
::fclose(fp);
}
{
SecretsProvider sp;
sp.declare({"master_key", true, 16, 128});
sp.declare({"workers", false, 0, 16});
sp.declare({"debug", false, 0, 16});
::setenv("workers", "8", 1);
std::string reason;
check(sp.load(path, reason), "secrets load");
std::string v;
check(sp.get("master_key", v) && v == "file-value-0123456789abcdef", "secrets file value");
std::uint64_t n = 0;
check(sp.get_u64("workers", n) && n == 8, "secrets env override wins");
bool b = true;
check(sp.get_bool("debug", b) && !b, "secrets typed bool");
::unsetenv("workers");
auto red = sp.redacted();
bool leak = false;
for (const auto& line : red) {
if (line.find("file-value") != std::string::npos) leak = true;
}
check(!leak && red.size() == 3, "secrets redacted dump");
check(reason.empty(), "secrets no reason on success");
}
// Missing required fails with a value-free reason.
{
SecretsProvider sp;
sp.declare({"must_have", true, 1, 64});
std::string reason;
check(!sp.load("/tmp/molo_test_env.json", reason) &&
reason.find("must_have") != std::string::npos,
"secrets missing required");
}
// Rotation swaps values, rejects unknown names.
{
SecretsProvider sp;
sp.declare({"k", false, 1, 64});
std::string reason;
check(sp.load("", reason), "secrets empty path ok");
check(sp.rotate("k", "v1"), "rotate set");
std::string v;
check(sp.get("k", v) && v == "v1", "rotate read");
check(sp.rotate("k", "v2") && sp.get("k", v) && v == "v2", "rotate swap");
check(!sp.rotate("nope", "x"), "rotate unknown rejected");
}
std::printf(failures == 0 ? "ALL SECRETS TESTS PASSED\n" : "FAILURES: %d\n", failures);
return failures == 0 ? 0 : 1;
}
+155
View File
@@ -0,0 +1,155 @@
// Session test: manager lifecycle, timeouts, rotation, both stores.
#include <cstdint>
#include <cstdio>
#include <memory>
#include <string>
#include "DbStore.h"
#include "DenialSink.h"
#include "HttpMessageView.h"
#include "MemoryStore.h"
#include "SessionManager.h"
using namespace molo::security::session;
using molo::security::guard::HttpRequestView;
using molo::security::guard::HttpResponseView;
using molo::security::guard::NullSink;
static int failures = 0;
static void check(bool ok, const char* name) {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) ++failures;
}
struct FakeRows : IDbSessionRows {
MemoryStore mem;
bool select(const std::string& id, Session& out) override { return mem.get(id, 0, out); }
bool upsert(const Session& s) override { return mem.put(s); }
bool erase(const std::string& id) override { return mem.destroy(id); }
std::size_t erase_expired(std::uint64_t now) override { return mem.sweep(now); }
};
static HttpRequestView req_with_cookie(const std::string& id, std::uint64_t now) {
HttpRequestView r;
r.now_unix_sec = now;
r.peer_ip = "10.0.0.1";
r.path = "/app";
if (!id.empty()) r.headers.emplace_back("cookie", "__Host-molo_sid=" + id);
return r;
}
int main() {
NullSink sink;
// Fresh request mints an anonymous session.
{
auto store = std::make_shared<MemoryStore>();
SessionManager mgr(store, SessionPolicy(), sink);
Session s;
auto r = mgr.load(req_with_cookie("", 1000), s);
check(r == SessionManager::LoadResult::Fresh && s.id.size() == 22, "fresh mints id");
HttpResponseView res;
mgr.save(s, res);
check(res.header("Set-Cookie").find("__Host-molo_sid=") != std::string::npos &&
res.header("Set-Cookie").find("Secure") != std::string::npos &&
res.header("Set-Cookie").find("HttpOnly") != std::string::npos &&
res.header("Set-Cookie").find("SameSite=Strict") != std::string::npos,
"cookie flags");
}
// Resume, idle timeout, absolute cap.
{
auto store = std::make_shared<MemoryStore>();
SessionManager mgr(store, SessionPolicy(), sink);
Session s;
mgr.load(req_with_cookie("", 1000), s);
HttpResponseView res;
mgr.save(s, res);
Session s2;
check(mgr.load(req_with_cookie(s.id, 1100), s2) == SessionManager::LoadResult::Resumed &&
s2.id == s.id,
"resume");
Session s3;
check(mgr.load(req_with_cookie(s.id, 1100 + 31 * 60), s3) ==
SessionManager::LoadResult::ExpiredIdle,
"idle expiry at 31 min");
Session s4;
mgr.load(req_with_cookie("", 2000), s4);
mgr.save(s4, res);
Session s5;
check(mgr.load(req_with_cookie(s4.id, 2000 + 12 * 3600 + 1), s5) !=
SessionManager::LoadResult::Resumed,
"absolute expiry enforced");
}
// Rotation on privilege change, old ID dies.
{
auto store = std::make_shared<MemoryStore>();
SessionManager mgr(store, SessionPolicy(), sink);
Session s;
mgr.load(req_with_cookie("", 1000), s);
HttpResponseView res;
mgr.save(s, res);
std::string old = s.id;
check(mgr.set_privilege(s, Session::Privilege::User, res, 1001) && s.id != old,
"privilege rotates id");
Session probe;
check(!store->get(old, 1001, probe), "old id dead");
check(store->get(s.id, 1001, probe) && probe.privilege == Session::Privilege::User,
"new id live");
mgr.logout(s, res);
check(!store->get(s.id, 1002, probe) &&
res.header_all("Set-Cookie").back().find("Max-Age=0") != std::string::npos,
"logout destroys and clears");
}
// Unknown cookie fails closed with a fresh ID.
{
auto store = std::make_shared<MemoryStore>();
SessionManager mgr(store, SessionPolicy(), sink);
Session s;
check(mgr.load(req_with_cookie("AAAAAAAAAAAAAAAAAAAAAA", 1000), s) ==
SessionManager::LoadResult::Invalid &&
s.id != "AAAAAAAAAAAAAAAAAAAAAA",
"unknown cookie invalid");
}
// MemoryStore caps and sweep.
{
MemoryStore tiny(2);
Session a, b, c;
a.id = "AAAAAAAAAAAAAAAAAAAAAA";
b.id = "BBBBBBBBBBBBBBBBBBBBBB";
c.id = "CCCCCCCCCCCCCCCCCCCCCC";
a.absolute_expiry = 100;
b.absolute_expiry = 200;
c.absolute_expiry = 300;
check(tiny.put(a) && tiny.put(b) && tiny.put(c) && tiny.size() == 2, "cap evicts oldest");
check(!tiny.get("AAAAAAAAAAAAAAAAAAAAAA", 50, a), "evicted entry gone");
check(tiny.sweep(250) == 1 && tiny.size() == 1, "sweep expires");
Session bad;
bad.id = "short";
check(!tiny.put(bad), "bad shape rejected");
}
// DbStore over fake rows, plus null-rows fail-closed.
{
auto rows = std::make_shared<FakeRows>();
DbStore db(rows);
Session s;
s.id = "DDDDDDDDDDDDDDDDDDDDDD";
s.absolute_expiry = 5000;
check(db.put(s), "db put");
Session out;
check(db.get(s.id, 100, out), "db get");
s.id = "EEEEEEEEEEEEEEEEEEEEEE";
check(db.rotate("DDDDDDDDDDDDDDDDDDDDDD", s), "db rotate");
check(!db.get("DDDDDDDDDDDDDDDDDDDDDD", 100, out), "db old gone");
check(db.destroy(s.id), "db destroy");
DbStore nulldb(nullptr);
check(!nulldb.put(s) && !nulldb.get("x", 0, out), "null rows fail closed");
}
std::printf(failures == 0 ? "ALL SESSION TESTS PASSED\n" : "FAILURES: %d\n", failures);
return failures == 0 ? 0 : 1;
}
+198
View File
@@ -0,0 +1,198 @@
// TLS test: config validation, stub fail-closed, acceptor driver with a
// fake backend (handshake ok, SNI reject, timeout, backoff, unavailable).
#include <cstdint>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
#include "TlsAcceptor.h"
#include "TlsBackend.h"
#include "TlsConfig.h"
#include "TlsContext.h"
#include "WolfSslBackend.h"
using namespace molo::security::tls;
static int failures = 0;
static void check(bool ok, const char* name) {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) ++failures;
}
// Fake backend: scripted handshake (WantRead once, then Done).
struct FakeSession : ITlsSession {
int steps = 0;
std::string sni;
bool fail = false;
explicit FakeSession(std::string s, bool f = false) : sni(std::move(s)), fail(f) {}
TlsStep handshake_step(const std::uint8_t*, std::size_t, std::vector<std::uint8_t>& out) override {
if (fail) return TlsStep::Failed;
if (steps == 0) {
++steps;
out = {0x16, 0x03};
return TlsStep::WantRead;
}
return TlsStep::Done;
}
bool decrypt(const std::uint8_t*, std::size_t, std::vector<std::uint8_t>&, std::size_t) override {
return true;
}
bool encrypt(const std::uint8_t*, std::size_t, std::vector<std::uint8_t>&) override {
return true;
}
std::string alpn_selected() const override { return "h2"; }
std::string sni_hostname() const override { return sni; }
std::string cipher_name() const override { return "TLS_AES_128_GCM_SHA256"; }
std::string last_error() const override { return fail ? "scripted fail" : ""; }
bool shutdown(std::vector<std::uint8_t>&) override { return true; }
};
struct FakeBackend : ITlsBackend {
std::string sni = "example.com";
bool fail = false;
std::string name() const override { return "fake"; }
bool available() const override { return true; }
bool configure(const TlsConfig&, std::string&) override { return true; }
bool reload_certs(std::string&) override { return true; }
std::unique_ptr<ITlsSession> new_session(TlsRole) override {
return std::unique_ptr<ITlsSession>(new FakeSession(sni, fail));
}
};
struct FakeHooks : ITlsConnHooks {
std::vector<std::uint64_t> closed;
std::vector<std::uint64_t> promoted;
std::string last_alpn;
bool send_ok = true;
bool send_bytes(std::uint64_t, const std::vector<std::uint8_t>&) override { return send_ok; }
void close_conn(std::uint64_t id, const std::string&) override { closed.push_back(id); }
void promote_conn(std::uint64_t id, std::unique_ptr<ITlsSession>, const std::string& alpn) override {
promoted.push_back(id);
last_alpn = alpn;
}
};
int main() {
// Config validation.
TlsConfig good;
good.cert_path = "/etc/molo/cert.pem";
good.key_path = "/etc/molo/key.pem";
check(good.validate().empty(), "tls config valid");
TlsConfig bad12 = good;
bad12.min_version_minor = 3; // TLS 1.2 attempt
check(!bad12.validate().empty(), "tls 1.2 rejected");
TlsConfig badcert = good;
badcert.key_path.clear();
check(!badcert.validate().empty(), "tls missing key rejected");
TlsConfig badto = good;
badto.handshake_timeout_ms = 100;
check(!badto.validate().empty(), "tls tiny timeout rejected");
// Stub backend fails closed with a marked reason.
{
WolfSslBackend stub;
check(!WolfSslBackend::kNativeBuild, "stub build marked");
check(!stub.available(), "stub unavailable");
std::string reason;
check(!stub.configure(good, reason) && reason.find("STUB") != std::string::npos,
"stub configure fails closed");
auto s = stub.new_session(TlsRole::Server);
std::vector<std::uint8_t> out;
check(s && s->handshake_step(nullptr, 0, out) == TlsStep::Unavailable,
"stub session unavailable");
}
// Context boot + reload with fake backend.
TlsContext ctx;
{
std::string reason;
check(ctx.boot(std::unique_ptr<ITlsBackend>(new FakeBackend), good, reason), "ctx boot");
check(ctx.booted(), "ctx booted");
check(ctx.reload_certs(reason), "ctx reload");
auto s = ctx.new_session(TlsRole::Server);
check(s && ctx.stats().sessions_opened == 1, "ctx session");
}
{
TlsContext ctx2;
std::string reason;
check(!ctx2.boot(std::unique_ptr<ITlsBackend>(new FakeBackend), bad12, reason),
"ctx boot rejects bad config");
}
// Acceptor: happy path handshake.
{
FakeHooks hooks;
TlsAcceptor acc(ctx, hooks);
std::uint64_t now = 100000;
acc.set_clock([&] { return now; });
check(acc.on_accept(1, "10.0.0.1"), "accept ok");
std::uint8_t hello[4] = {0x16, 0x03, 0x01, 0x00};
acc.on_bytes(1, hello, sizeof hello);
check(hooks.promoted.size() == 1 && hooks.last_alpn == "h2", "handshake promotes");
check(acc.counters().completed == 1, "counter completed");
}
// Acceptor: SNI reject with allow-list.
{
FakeHooks hooks;
TlsAcceptorPolicy pol;
pol.sni_allow = {"allowed.test"};
TlsAcceptor acc(ctx, hooks, pol);
acc.set_clock([] { return std::uint64_t(100000); });
bool logged = false;
acc.set_sni_log([&](const SniDecision& d) {
logged = !d.allowed && d.hostname == "example.com";
});
check(acc.on_accept(2, "10.0.0.2"), "accept sni case");
std::uint8_t hello[4] = {0x16, 0x03, 0x01, 0x00};
acc.on_bytes(2, hello, sizeof hello);
check(hooks.closed.size() == 1 && acc.counters().sni_rejected == 1 && logged,
"sni rejected and logged");
}
// Acceptor: handshake timeout sweep.
{
FakeHooks hooks;
TlsAcceptor acc(ctx, hooks);
std::uint64_t now = 200000;
acc.set_clock([&] { return now; });
check(acc.on_accept(3, "10.0.0.3"), "accept timeout case");
now += 6000;
check(acc.on_tick() == 1 && acc.counters().timed_out == 1 && hooks.closed.size() == 1,
"timeout sweep closes");
}
// Acceptor: failure backoff per IP.
{
ctx.new_session(TlsRole::Server); // keep stats moving
TlsContext fctx;
std::string reason;
auto fb = new FakeBackend;
fb->fail = true;
fctx.boot(std::unique_ptr<ITlsBackend>(fb), good, reason);
FakeHooks hooks;
TlsAcceptor acc(fctx, hooks);
acc.set_clock([] { return std::uint64_t(300000); });
std::uint8_t hello[1] = {0};
for (int i = 0; i < 5; ++i) {
std::uint64_t id = 10 + std::uint64_t(i);
if (acc.on_accept(id, "10.9.9.9")) acc.on_bytes(id, hello, 1);
}
check(acc.counters().failed == 5, "five failures counted");
check(!acc.on_accept(99, "10.9.9.9") && acc.counters().backoff_rejected == 1,
"backoff rejects sixth accept");
}
// Acceptor: unavailable backend (stub context) fails closed.
{
TlsContext stub_ctx; // never booted
FakeHooks hooks;
TlsAcceptor acc(stub_ctx, hooks);
check(!acc.on_accept(5, "10.0.0.5") && acc.counters().unavailable == 1,
"unbooted context fails closed");
}
std::printf(failures == 0 ? "ALL TLS TESTS PASSED\n" : "FAILURES: %d\n", failures);
return failures == 0 ? 0 : 1;
}
+117
View File
@@ -0,0 +1,117 @@
// Upload test: validator traps and store flow with stub AV.
#include <cstdint>
#include <cstdio>
#include <memory>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include "DenialSink.h"
#include "HttpMessageView.h"
#include "UploadStore.h"
#include "UploadValidator.h"
using namespace molo::security::upload;
using molo::security::guard::HttpRequestView;
using molo::security::guard::NullSink;
static int failures = 0;
static void check(bool ok, const char* name) {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) ++failures;
}
static UploadFile mk(const std::string& name, std::vector<std::uint8_t> bytes) {
UploadFile f;
f.field_name = "file";
f.client_filename = name;
f.content_type = "application/octet-stream";
f.bytes = std::move(bytes);
return f;
}
static std::vector<std::uint8_t> png_bytes() {
std::vector<std::uint8_t> b = {0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 1, 2, 3};
return b;
}
struct InfectedScanner : IAvScanner {
ScanResult scan(const std::string&) override { return ScanResult::Infected; }
};
int main() {
NullSink sink;
HttpRequestView req;
req.path = "/upload";
// Validator traps.
{
UploadValidator v(UploadValidator::Policy(), sink);
check(v.check(mk("a.png", png_bytes()), req) == UploadValidator::Verdict::Allow,
"upload valid png");
check(v.check(mk("x.jpg.php", png_bytes()), req) != UploadValidator::Verdict::Allow,
"upload double extension");
check(v.check(mk("x.pHp", png_bytes()), req) != UploadValidator::Verdict::Allow,
"upload case trick");
std::string nulled = std::string("a.png\0.php", 10);
check(v.check(mk(nulled, png_bytes()), req) != UploadValidator::Verdict::Allow,
"upload null byte");
std::vector<std::uint8_t> elf = {'E', 'L', 'F', '!', 0, 0, 0, 0};
UploadFile spoof = mk("run.png", elf);
spoof.content_type = "image/png";
check(v.check(spoof, req) == UploadValidator::Verdict::MagicMismatch,
"upload spoofed content-type");
UploadFile big = mk("big.png", std::vector<std::uint8_t>(11 * 1024 * 1024, 0));
check(v.check(big, req) == UploadValidator::Verdict::TooLarge, "upload too large");
check(!v.check_count(5, req) && v.check_count(4, req), "upload count cap");
std::vector<std::uint8_t> zip = {'P', 'K', 0x03, 0x04, 0, 0};
check(v.check(mk("doc.docx", zip), req) == UploadValidator::Verdict::Allow,
"upload docx zip-family");
}
// Store flow with clean and infected scanners.
const char* tmpd = "/tmp/molo_up_tmp";
const char* stdir = "/tmp/molo_up_store";
const char* qdir = "/tmp/molo_up_quar";
::mkdir(tmpd, 0700);
::mkdir(stdir, 0700);
::mkdir(qdir, 0700);
{
UploadStore::Policy p{tmpd, stdir, qdir, 1024 * 1024, 3600};
check(UploadStore::validate(p).empty(), "store policy valid");
UploadStore::Policy bad = p;
bad.store_dir = tmpd;
check(!UploadStore::validate(bad).empty(), "store dirs distinct");
auto clean = std::make_shared<AllowAllScanner>();
UploadStore store(p, clean, sink);
StoredUpload out;
check(store.store(mk("a.png", png_bytes()), "png", 1000, out, req), "store clean");
check(out.full_path.compare(0, std::string(stdir).size(), stdir) == 0 &&
out.storage_name != "a.png",
"store generated name outside webroot");
struct stat st{};
check(::stat(out.full_path.c_str(), &st) == 0 && (st.st_mode & 0777) == 0600,
"store 0600 perms");
UploadFile big = mk("b.png", std::vector<std::uint8_t>(2 * 1024 * 1024, 0));
check(!store.store(big, "png", 1000, out, req), "store quota");
auto evil = std::make_shared<InfectedScanner>();
UploadStore store2(p, evil, sink);
check(!store2.store(mk("c.png", png_bytes()), "png", 1000, out, req),
"store infected quarantined");
}
// Temp sweep removes stale files only.
{
UploadStore::Policy p{tmpd, stdir, qdir, 1024 * 1024, 10};
UploadStore store(p, std::make_shared<AllowAllScanner>(), sink);
FILE* fp = ::fopen("/tmp/molo_up_tmp/AAAA-ttl.tmp", "w");
if (fp) {
::fputs("x", fp);
::fclose(fp);
}
// Far-future clock makes the just-written file stale by TTL.
check(store.sweep_temp(4000000000ULL) >= 1, "sweep stale temp");
}
std::printf(failures == 0 ? "ALL UPLOAD TESTS PASSED\n" : "FAILURES: %d\n", failures);
return failures == 0 ? 0 : 1;
}