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
+62
View File
@@ -0,0 +1,62 @@
// Compile-all: every header in this part must compile in one TU.
#include "app/app/application.h"
#include "app/app/plugin.h"
#include "app/async/task.h"
#include "app/caps.h"
#include "app/di/container.h"
#include "app/errors/handler.h"
#include "app/errors/http_error.h"
#include "app/forms/form.h"
#include "app/forms/multipart.h"
#include "app/forms/urlencoded.h"
#include "app/http_msg/cookies.h"
#include "app/http_msg/headers.h"
#include "app/http_msg/html.h"
#include "app/http_msg/method.h"
#include "app/http_msg/query.h"
#include "app/http_msg/request.h"
#include "app/http_msg/response.h"
#include "app/middleware/builtins.h"
#include "app/middleware/chain.h"
#include "app/middleware/middleware.h"
#include "app/negotiate/accept.h"
#include "app/negotiate/negotiator.h"
#include "app/routing/path_compiler.h"
#include "app/routing/route.h"
#include "app/routing/router.h"
#include "app/seams/request_id.h"
#include "app/seams/session.h"
#include "app/templates/ast.h"
#include "app/templates/cache.h"
#include "app/templates/context.h"
#include "app/templates/environment.h"
#include "app/templates/filters.h"
#include "app/templates/lexer.h"
#include "app/templates/loaders.h"
#include "app/templates/parser.h"
#include "app/templates/predicates.h"
#include "app/templates/renderer.h"
#include "app/templates/response.h"
#include "app/validate/errors.h"
#include "app/validate/field.h"
#include "app/validate/json.h"
#include "app/validate/model.h"
#include "app/validate/value.h"
#include "app/views/adapters.h"
#include "app/views/flash.h"
#include "app/views/view.h"
#include <iostream>
#include <type_traits>
// R4: raw strings never convert implicitly to a 200 text response.
static_assert(!std::is_convertible_v<std::string, molo::app::http_msg::Response>);
static_assert(!std::is_convertible_v<const char*, molo::app::http_msg::Response>);
static_assert(!std::is_constructible_v<molo::app::http_msg::TextResponse, int>);
int main() {
molo::app::app::Application app;
(void)app.total_routes();
std::cout << "PASS compile_all\n";
return 0;
}
+92
View File
@@ -0,0 +1,92 @@
#pragma once
// Shared integration-test helper: every test drives Application::handle
// (real routing, middleware, validation, negotiation, errors). Test files
// mirror URL paths under tests/src/app/.
#include <iostream>
#include <map>
#include <string>
#include "app/app/application.h"
#include "app/async/task.h"
#include "app/http_msg/request.h"
#include "app/http_msg/response.h"
#include "app/validate/json.h"
#include "app/validate/value.h"
#include "app/views/adapters.h"
static int g_failures = 0;
static int g_checks = 0;
#define CHECK(cond, msg) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failures; \
std::cerr << "FAIL line " << __LINE__ << ": " << msg << "\n"; \
} \
} while (0)
#define CHECK_EQ_STR(a, b, msg) \
do { \
++g_checks; \
std::string _a = (a); \
std::string _b = (b); \
if (_a != _b) { \
++g_failures; \
std::cerr << "FAIL line " << __LINE__ << ": " << msg << "\n got: [" << _a \
<< "]\n want: [" << _b << "]\n"; \
} \
} while (0)
#define CHECK_EQ_INT(a, b, msg) \
do { \
++g_checks; \
long long _a = (long long)(a); \
long long _b = (long long)(b); \
if (_a != _b) { \
++g_failures; \
std::cerr << "FAIL line " << __LINE__ << ": " << msg << " got " << _a \
<< " want " << _b << "\n"; \
} \
} while (0)
inline molo::app::http_msg::Request make_request(
const std::string& method, const std::string& target,
const std::map<std::string, std::string>& headers = {}, const std::string& body = "") {
using namespace molo::app::http_msg;
Method m = parse_method(method).value();
std::string path = target;
std::string qraw;
std::size_t q = target.find('?');
if (q != std::string::npos) {
path = target.substr(0, q);
qraw = target.substr(q + 1);
}
Headers h;
for (const auto& kv : headers) h.set(kv.first, kv.second);
Request req(m, path, Query::parse(qraw), h, body);
req.set_query_raw(qraw);
return req;
}
inline molo::app::http_msg::Response run_request(molo::app::app::Application& app,
molo::app::http_msg::Request& req) {
return molo::app::async::run(app.handle(req));
}
inline molo::app::http_msg::Response get(molo::app::app::Application& app,
const std::string& target,
const std::map<std::string, std::string>& headers = {}) {
molo::app::http_msg::Request req = make_request("GET", target, headers);
return run_request(app, req);
}
inline int test_report(const std::string& name) {
if (g_failures == 0) {
std::cout << "PASS " << name << " (" << g_checks << " checks)\n";
return 0;
}
std::cout << "FAIL " << name << " (" << g_failures << "/" << g_checks << " failed)\n";
return 1;
}
+63
View File
@@ -0,0 +1,63 @@
// V9: app scope shared, request scope isolated, cycles fail quoting.
#include "../_testlib.h"
#include <atomic>
using namespace molo::app;
int main() {
app::Application app;
app.di().provide_value("greeting", std::string("hello"));
std::atomic<int> builds{0};
app.di().provide_typed<int>(
"ticket",
[&builds](di::Resolver&) {
return builds.fetch_add(1) + 1;
},
di::Scope::Request);
app.router().get("/who", views::adapt([](http_msg::Request& req) {
di::RequestScope* scope = app::Application::di_scope(req);
std::string greeting = scope->get_as<std::string>("greeting");
int first = scope->get_as<int>("ticket");
int second = scope->get_as<int>("ticket");
std::string out = greeting + " " + std::to_string(first) + " " + std::to_string(second);
return http_msg::TextResponse(out);
}));
app.startup();
http_msg::Response r1 = get(app, "/who");
http_msg::Response r2 = get(app, "/who");
CHECK_EQ_STR(r1.body(), "hello 1 1", "request scope caches within one request");
CHECK_EQ_STR(r2.body(), "hello 2 2", "request scope is fresh per request");
CHECK_EQ_INT(builds.load(), 2, "request factory ran once per request");
app::Application cyc;
cyc.di().provide("a", [](di::Resolver& r) -> std::any {
return r.get("b");
}, di::Scope::App, {"b"});
cyc.di().provide("b", [](di::Resolver& r) -> std::any {
return r.get("a");
}, di::Scope::App, {"a"});
bool threw = false;
std::string msg;
try {
cyc.startup();
} catch (const di::CycleError& e) {
threw = true;
msg = e.what();
}
CHECK(threw, "dependency cycle fails startup");
CHECK(msg.find("'a'") != std::string::npos, "cycle quotes first provider");
CHECK(msg.find("'b'") != std::string::npos, "cycle quotes second provider");
app::Application dup;
dup.di().provide_value("x", 1);
bool dup_threw = false;
try {
dup.di().provide_value("x", 2);
} catch (const di::DiError&) {
dup_threw = true;
}
CHECK(dup_threw, "duplicate DI provider fails loudly");
return test_report("di/scopes");
}
+47
View File
@@ -0,0 +1,47 @@
// V5: mapped exceptions render exact JSON and HTML shapes; 500 hides
// internals; request_id is present in both.
#include "../_testlib.h"
using namespace molo::app;
int main() {
app::Application app;
app.router().get("/bad", views::adapt([](http_msg::Request&) -> http_msg::Response {
throw errors::BadRequest("custom bad");
}));
app.router().get("/deny", views::adapt([](http_msg::Request&) -> http_msg::Response {
throw errors::Forbidden();
}));
app.router().get("/leak", views::adapt([](http_msg::Request&) -> http_msg::Response {
throw std::runtime_error("secret db password hunter2");
}));
app.startup();
http_msg::Response j = get(app, "/bad");
CHECK_EQ_INT(j.status(), 400, "BadRequest maps to 400");
CHECK_EQ_STR(j.content_type(), "application/json", "API error is JSON");
validate::Value parsed = validate::parse_json(j.body());
const auto* root = std::get_if<validate::Object>(&parsed.storage());
const auto* err = std::get_if<validate::Object>(&root->at("error").storage());
CHECK_EQ_STR(err->at("code").as_text(), "bad_request", "error code field");
CHECK_EQ_STR(err->at("message").as_text(), "custom bad", "error message field");
CHECK(!err->at("request_id").as_text().empty(), "JSON error carries request_id");
http_msg::Response page = get(app, "/deny", {{"accept", "text/html"}});
CHECK_EQ_INT(page.status(), 403, "Forbidden maps to 403");
CHECK(page.content_type().find("text/html") != std::string::npos, "browser error is HTML");
CHECK(page.body().find("viewport") != std::string::npos, "error page is responsive");
CHECK(page.body().find("forbidden") != std::string::npos, "error page shows code");
CHECK(page.body().find("req-") != std::string::npos, "HTML error carries request_id");
http_msg::Response leak = get(app, "/leak");
CHECK_EQ_INT(leak.status(), 500, "unknown exception maps to 500");
CHECK(leak.body().find("hunter2") == std::string::npos, "500 hides internals");
CHECK(leak.body().find("internal server error") != std::string::npos,
"500 shows fixed message");
http_msg::Response leak_html = get(app, "/leak", {{"accept", "text/html"}});
CHECK_EQ_INT(leak_html.status(), 500, "HTML unknown exception maps to 500");
CHECK(leak_html.body().find("hunter2") == std::string::npos, "HTML 500 hides internals");
return test_report("errors/render");
}
+92
View File
@@ -0,0 +1,92 @@
// V10: JSON, urlencoded and multipart bind the same model; cap fixtures
// are rejected with the documented status.
#include "../_testlib.h"
using namespace molo::app;
static std::shared_ptr<validate::Model> user_model() {
auto m = std::make_shared<validate::Model>("user");
validate::Field name("username", validate::FieldType::String);
name.required().min_len(3);
validate::Field age("age", validate::FieldType::Int);
age.required().ge(0);
m->field(name).field(age);
return m;
}
int main() {
app::Application app;
routing::RouteOptions o;
o.name = "create";
o.body_model = user_model();
app.router().post("/users", views::adapt([](http_msg::Request& req) {
const validate::Object* b = req.validated("body");
std::string out = b->at("username").as_text() + ":" +
std::to_string((long long)b->at("age").as_number());
return http_msg::TextResponse(out);
}), o);
routing::RouteOptions tiny;
tiny.name = "tiny";
tiny.body_model = user_model();
tiny.max_body = 10;
app.router().post("/tiny", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("tiny");
}), tiny);
app.startup();
http_msg::Request json =
make_request("POST", "/users", {{"content-type", "application/json"}},
R"({"username":"ada","age":36})");
CHECK_EQ_STR(run_request(app, json).body(), "ada:36", "JSON binds to model");
http_msg::Request url =
make_request("POST", "/users", {{"content-type", "application/x-www-form-urlencoded"}},
"username=ada&age=36");
CHECK_EQ_STR(run_request(app, url).body(), "ada:36", "urlencoded binds to model");
std::string mp =
"--B\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\nada\r\n"
"--B\r\nContent-Disposition: form-data; name=\"age\"\r\n\r\n36\r\n"
"--B--\r\n";
http_msg::Request multi =
make_request("POST", "/users", {{"content-type", "multipart/form-data; boundary=B"}}, mp);
CHECK_EQ_STR(run_request(app, multi).body(), "ada:36", "multipart binds to model");
http_msg::Request bad =
make_request("POST", "/users", {{"content-type", "application/json"}},
R"({"username":"al","age":-1})");
http_msg::Response v = run_request(app, bad);
CHECK_EQ_INT(v.status(), 422, "bad body fields yield one 422");
CHECK(v.body().find("[\"body\",\"username\"]") != std::string::npos, "username failure listed");
CHECK(v.body().find("[\"body\",\"age\"]") != std::string::npos, "age failure listed");
// 1001 urlencoded fields exceed the form cap.
std::string many;
for (int i = 0; i < 1001; ++i) {
if (i) many += '&';
many += "f" + std::to_string(i) + "=v";
}
http_msg::Request flood =
make_request("POST", "/users", {{"content-type", "application/x-www-form-urlencoded"}}, many);
CHECK_EQ_INT(run_request(app, flood).status(), 413, "1001 fields rejected with 413");
// JSON depth 33 exceeds the depth cap.
std::string deep(33, '[');
deep += std::string(33, ']');
http_msg::Request deep_req =
make_request("POST", "/users", {{"content-type", "application/json"}}, deep);
CHECK_EQ_INT(run_request(app, deep_req).status(), 400, "depth 33 rejected with 400");
// Oversized single value exceeds the 1 MiB cap.
std::string big(1048577, 'x');
http_msg::Request big_req = make_request(
"POST", "/users", {{"content-type", "application/x-www-form-urlencoded"}}, "v=" + big);
CHECK_EQ_INT(run_request(app, big_req).status(), 413, "oversized value rejected with 413");
// Per-route document cap.
http_msg::Request over =
make_request("POST", "/tiny", {{"content-type", "application/json"}},
R"({"username":"ada","age":36})");
CHECK_EQ_INT(run_request(app, over).status(), 413, "per-route max_body enforced");
return test_report("forms/bind");
}
+65
View File
@@ -0,0 +1,65 @@
// V1: response subclass round-trips through the real stack.
#include "../_testlib.h"
using namespace molo::app;
int main() {
app::Application app;
routing::RouteOptions o;
app.router().get("/ping", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("pong");
}));
app.router().get("/user", views::adapt([](http_msg::Request&) {
validate::Object u;
u["name"] = validate::Value("ada");
u["id"] = validate::Value(7);
return http_msg::Response(http_msg::JsonResponse(validate::Value(u)));
}));
app.router().get("/page", views::adapt([](http_msg::Request&) {
return http_msg::Response(http_msg::HtmlResponse("<h1>hi</h1>"));
}));
app.router().get("/feed", views::adapt([](http_msg::Request&) {
return http_msg::Response(http_msg::XmlResponse("<a/>"));
}));
app.router().get("/old", views::adapt([](http_msg::Request&) {
return http_msg::Response(http_msg::RedirectResponse::temporary("/page"));
}));
app.router().get("/moved", views::adapt([](http_msg::Request&) {
return http_msg::Response(http_msg::RedirectResponse::permanent("/page"));
}));
app.startup();
http_msg::Response t = get(app, "/ping");
CHECK_EQ_INT(t.status(), 200, "text status");
CHECK_EQ_STR(t.body(), "pong", "text body");
CHECK_EQ_STR(t.content_type(), "text/plain; charset=utf-8", "text content type");
http_msg::Response j = get(app, "/user");
CHECK_EQ_INT(j.status(), 200, "json status");
CHECK_EQ_STR(j.content_type(), "application/json", "json content type");
validate::Value parsed = validate::parse_json(j.body());
const auto* obj = std::get_if<validate::Object>(&parsed.storage());
CHECK(obj != nullptr, "json body parses to object");
CHECK(obj != nullptr && obj->at("name") == validate::Value("ada"), "json name field");
CHECK(obj != nullptr && obj->at("id") == validate::Value(7), "json id field");
http_msg::Response h = get(app, "/page");
CHECK_EQ_INT(h.status(), 200, "html status");
CHECK_EQ_STR(h.content_type(), "text/html; charset=utf-8", "html content type");
CHECK_EQ_STR(h.body(), "<h1>hi</h1>", "html body");
http_msg::Response x = get(app, "/feed");
CHECK_EQ_INT(x.status(), 200, "xml status");
CHECK_EQ_STR(x.content_type(), "application/xml; charset=utf-8", "xml content type");
http_msg::Response r307 = get(app, "/old");
CHECK_EQ_INT(r307.status(), 307, "temporary redirect keeps method with 307");
CHECK_EQ_STR(r307.headers().get("location"), "/page", "307 location");
http_msg::Response r308 = get(app, "/moved");
CHECK_EQ_INT(r308.status(), 308, "permanent redirect keeps method with 308");
CHECK_EQ_STR(r308.headers().get("location"), "/page", "308 location");
CHECK(!t.headers().get("x-request-id").empty(), "request id echoed on response");
return test_report("health/ping");
}
+96
View File
@@ -0,0 +1,96 @@
// V8: onion order, double-Next failure, short-circuit.
#include "../_testlib.h"
using namespace molo::app;
struct Probe : public middleware::Middleware {
std::string id;
std::vector<std::string>* log;
Probe(std::string i, std::vector<std::string>* l) : id(std::move(i)), log(l) {}
middleware::Category category() const override { return middleware::Category::User; }
std::string name() const override { return "probe_" + id; }
async::Task<http_msg::Response> handle(http_msg::Request& req,
middleware::Next next) override {
log->push_back("in_" + id);
http_msg::Response res = co_await next(req);
log->push_back("out_" + id);
co_return res;
}
};
struct ShortCircuit : public middleware::Middleware {
middleware::Category category() const override { return middleware::Category::User; }
std::string name() const override { return "short"; }
async::Task<http_msg::Response> handle(http_msg::Request&,
middleware::Next) override {
co_return http_msg::TextResponse("blocked");
}
};
struct DoubleNext : public middleware::Middleware {
middleware::Category category() const override { return middleware::Category::User; }
std::string name() const override { return "double"; }
async::Task<http_msg::Response> handle(http_msg::Request& req,
middleware::Next next) override {
http_msg::Response first = co_await next(req);
http_msg::Response second = co_await next(req);
(void)second;
co_return first;
}
};
struct WrongOrder : public middleware::Middleware {
middleware::Category category() const override { return middleware::Category::Security; }
std::string name() const override { return "late_security"; }
async::Task<http_msg::Response> handle(http_msg::Request& req,
middleware::Next next) override {
co_return co_await next(req);
}
};
int main() {
std::vector<std::string> log;
app::Application app;
app.chain().use(std::make_shared<Probe>("A", &log));
app.chain().use(std::make_shared<Probe>("B", &log));
app.router().get("/x", views::adapt([&log](http_msg::Request&) {
log.push_back("handler");
return http_msg::TextResponse("x");
}));
app.startup();
CHECK_EQ_STR(get(app, "/x").body(), "x", "chain reaches handler");
std::string seq;
for (const auto& e : log) seq += e + ",";
CHECK_EQ_STR(seq, "in_A,in_B,handler,out_B,out_A,", "middleware onion order");
bool order_threw = false;
try {
app.chain().use(std::make_shared<WrongOrder>());
} catch (const middleware::ChainOrderError& e) {
order_threw = true;
CHECK(std::string(e.what()).find("late_security") != std::string::npos,
"order error names the layer");
}
CHECK(order_threw, "cross-category reorder fails loudly");
app::Application cut;
cut.chain().use(std::make_shared<ShortCircuit>());
bool reached = false;
cut.router().get("/x", views::adapt([&reached](http_msg::Request&) {
reached = true;
return http_msg::TextResponse("x");
}));
cut.startup();
CHECK_EQ_STR(get(cut, "/x").body(), "blocked", "short-circuit answers directly");
CHECK(!reached, "short-circuit never reaches the handler");
app::Application dbl;
dbl.chain().use(std::make_shared<DoubleNext>());
dbl.router().get("/x", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("x");
}));
dbl.startup();
http_msg::Response res = get(dbl, "/x");
CHECK_EQ_INT(res.status(), 500, "double Next fails loudly as 500");
return test_report("middleware/order");
}
+102
View File
@@ -0,0 +1,102 @@
// V3: prefixed includes, triple-nested mount, startup diagnostics.
#include "../_testlib.h"
using namespace molo::app;
int main() {
// Prefixed include_router.
app::Application app;
routing::Router users;
routing::RouteOptions o;
o.name = "user_list";
users.get("/users", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("list");
}), o);
app.include_router("/api", users);
app.startup();
CHECK_EQ_STR(get(app, "/api/users").body(), "list", "prefixed include serves");
CHECK_EQ_STR(app.url_for("user_list"), "/api/users", "url_for sees merged path");
// Triple-nested mount: /app1/app1/app1.
auto inner = std::make_shared<app::Application>();
routing::RouteOptions deep;
deep.name = "deep";
inner->router().get("/app1", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("deep");
}), deep);
auto mid = std::make_shared<app::Application>();
mid->mount("/app1", inner);
app::Application top;
top.mount("/app1", mid);
top.startup();
CHECK_EQ_STR(get(top, "/app1/app1/app1").body(), "deep", "triple mount merges paths");
CHECK_EQ_STR(top.url_for("app1:app1:deep"), "/app1/app1/app1", "url_for crosses mounts");
// Duplicate names fail startup with quoted paths.
app::Application dup;
routing::RouteOptions d1;
d1.name = "dup";
dup.router().get("/a", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("a");
}), d1);
routing::RouteOptions d2;
d2.name = "dup";
dup.router().get("/b", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("b");
}), d2);
bool dup_threw = false;
std::string dup_msg;
try {
dup.startup();
} catch (const app::StartupError& e) {
dup_threw = true;
dup_msg = e.what();
}
CHECK(dup_threw, "duplicate route names fail startup");
CHECK(dup_msg.find("'/a'") != std::string::npos, "diagnostic quotes first path");
CHECK(dup_msg.find("'/b'") != std::string::npos, "diagnostic quotes second path");
CHECK(dup_msg.find("dup") != std::string::npos, "diagnostic names the route");
// Unknown converter fails fast naming the route.
routing::Router bad;
bool conv_threw = false;
std::string conv_msg;
try {
routing::RouteOptions bo;
bo.name = "broken";
bad.get("/x/{id:uuid}", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("x");
}), bo);
} catch (const routing::PathCompileError& e) {
conv_threw = true;
conv_msg = e.what();
}
CHECK(conv_threw, "unknown converter is a startup error");
CHECK(conv_msg.find("uuid") != std::string::npos, "diagnostic names the converter");
CHECK(conv_msg.find("broken") != std::string::npos, "diagnostic names the route");
// slash_insensitive registers both forms with 308 to the declared form.
app::Application slash;
routing::RouteOptions so;
so.name = "canon";
so.slash_insensitive = true;
slash.router().get("/canon", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("canon");
}), so);
slash.startup();
CHECK_EQ_STR(get(slash, "/canon").body(), "canon", "declared slash form serves");
http_msg::Response redir = get(slash, "/canon/");
CHECK_EQ_INT(redir.status(), 308, "alternate slash form 308-redirects");
CHECK_EQ_STR(redir.headers().get("location"), "/canon", "redirect targets declared form");
bool frozen_threw = false;
try {
slash.router().get("/late", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("late");
}));
} catch (const routing::PathCompileError& e) {
frozen_threw = std::string(e.what()).find("frozen") != std::string::npos;
}
CHECK(frozen_threw, "routes freeze at startup");
return test_report("mount/nested");
}
+74
View File
@@ -0,0 +1,74 @@
// V6: q-weighted Accept picks the format; 406 lists available types;
// wrong Content-Type yields 415; format override is opt-in.
#include "../_testlib.h"
using namespace molo::app;
static http_msg::Response variant_data() {
validate::Object d;
d["name"] = validate::Value("ada");
return http_msg::Response(http_msg::VariantResponse(
validate::Value(d), {"application/json", "text/html"}));
}
int main() {
app::Application app;
routing::RouteOptions o;
o.name = "data";
o.produces = {"application/json", "text/html"};
app.router().get("/data", views::adapt([](http_msg::Request&) { return variant_data(); }), o);
routing::RouteOptions f;
f.name = "flex";
f.produces = {"application/json", "text/html"};
f.allow_format_override = true;
app.router().get("/flex", views::adapt([](http_msg::Request&) { return variant_data(); }), f);
routing::RouteOptions s;
s.name = "submit";
s.consumes = {"application/json"};
app.router().post("/submit", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("stored");
}), s);
app.startup();
http_msg::Response def = get(app, "/data");
CHECK_EQ_STR(def.content_type(), "application/json", "missing Accept means first produces");
http_msg::Response html = get(app, "/data", {{"accept", "text/html"}});
CHECK(html.content_type().find("text/html") != std::string::npos, "exact match wins");
CHECK(html.body().find("ada") != std::string::npos, "html variant renders data");
http_msg::Response q =
get(app, "/data", {{"accept", "text/html;q=0.5, application/json;q=0.9"}});
CHECK_EQ_STR(q.content_type(), "application/json", "higher q wins");
http_msg::Response star = get(app, "/data", {{"accept", "text/*"}});
CHECK(star.content_type().find("text/html") != std::string::npos, "type star matches");
http_msg::Response none = get(app, "/data", {{"accept", "image/png"}});
CHECK_EQ_INT(none.status(), 406, "no match yields 406");
validate::Value parsed = validate::parse_json(none.body());
const auto* root = std::get_if<validate::Object>(&parsed.storage());
CHECK(root != nullptr && root->count("Detail"), "406 uses capital Detail shape");
const auto* inner = std::get_if<validate::Object>(&root->at("Detail").storage());
const auto* avail = std::get_if<validate::Array>(&inner->at("available").storage());
CHECK(avail != nullptr && avail->size() == 2, "406 lists available types");
http_msg::Response over =
get(app, "/flex?format=html", {{"accept", "application/json"}});
CHECK(over.content_type().find("text/html") != std::string::npos,
"format override wins when allowed");
http_msg::Response ignored =
get(app, "/data?format=html", {{"accept", "application/json"}});
CHECK_EQ_STR(ignored.content_type(), "application/json",
"format override ignored when not allowed");
http_msg::Request bad =
make_request("POST", "/submit", {{"content-type", "text/plain"}}, "x");
http_msg::Response r415 = run_request(app, bad);
CHECK_EQ_INT(r415.status(), 415, "unconsumed content type yields 415");
http_msg::Request good =
make_request("POST", "/submit", {{"content-type", "application/json"}}, "{}");
CHECK_EQ_INT(run_request(app, good).status(), 200, "consumed content type passes");
return test_report("negotiate/select");
}
+75
View File
@@ -0,0 +1,75 @@
// V12: plugin hooks fire in order; undeclared access is denied.
#include "../_testlib.h"
using namespace molo::app;
int main() {
std::vector<std::string> events;
app::Application app;
app::Plugin plugin;
plugin.name = "watcher";
plugin.capabilities = {"routes", "di", "errors"};
plugin.hooks.route_added = [&events](app::PluginContext& ctx, const routing::Route& route) {
events.push_back("route_added:" + route.options().name + ":" +
std::to_string(ctx.route_count()));
};
plugin.hooks.app_started = [&events](app::PluginContext& ctx) {
events.push_back(std::string("app_started:") + (ctx.di_has("nope") ? "yes" : "no"));
};
plugin.hooks.error_render = [&events](app::PluginContext& ctx, int status,
const std::string& code) {
events.push_back("error_render:" + std::to_string(status) + ":" + code + ":" +
ctx.last_error_code());
};
app.plugins().register_plugin(plugin);
routing::RouteOptions a;
a.name = "first";
app.router().get("/a", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("a");
}), a);
routing::RouteOptions b;
b.name = "second";
app.router().get("/b", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("b");
}), b);
app.startup();
CHECK_EQ_INT((long long)events.size(), 3, "startup fires route hooks plus started");
CHECK(events.size() > 0 && events[0] == "route_added:first:2", "first route hook with count");
CHECK(events.size() > 1 && events[1] == "route_added:second:2", "second route hook");
CHECK(events.size() > 2 && events[2] == "app_started:no", "started hook after routes");
CHECK_EQ_INT(get(app, "/missing").status(), 404, "missing route is 404");
CHECK(events.size() == 4 && events[3] == "error_render:404:not_found:not_found",
"error hook fires with status and code");
// Undeclared access is denied.
app::Application locked;
app::Plugin nosy;
nosy.name = "nosy";
nosy.capabilities = {};
nosy.hooks.app_started = [](app::PluginContext& ctx) { (void)ctx.route_count(); };
locked.plugins().register_plugin(nosy);
bool denied = false;
try {
locked.startup();
} catch (const app::PluginAccessError& e) {
denied = true;
CHECK(std::string(e.what()).find("nosy") != std::string::npos, "denial names plugin");
CHECK(std::string(e.what()).find("routes") != std::string::npos, "denial names capability");
}
CHECK(denied, "undeclared capability access throws");
// Unknown capabilities are rejected at registration.
app::Application reg;
app::Plugin bad;
bad.name = "bad";
bad.capabilities = {"kernel"};
bool reg_threw = false;
try {
reg.plugins().register_plugin(bad);
} catch (const app::PluginAccessError&) {
reg_threw = true;
}
CHECK(reg_threw, "unknown capability rejected at registration");
return test_report("plugins/hooks");
}
+220
View File
@@ -0,0 +1,220 @@
// V11: template engine fixtures through the real stack.
#include "../_testlib.h"
#include <filesystem>
#include <fstream>
#include "app/templates/response.h"
using namespace molo::app;
static templates::Environment make_env() {
templates::Environment env;
auto dict = std::make_shared<templates::DictLoader>();
dict->set("base.html",
"<html><head><title>{% block title %}base{% endblock %}</title></head>"
"<body>{% block body %}empty{% endblock %}</body></html>");
dict->set("child.html",
"{% extends \"base.html\" %}{% block title %}kid{% endblock %}"
"{% block body %}Hello {{ name }}!{% endblock %}");
dict->set("head.html", "<header>HEAD</header>");
dict->set("page.html", "{% include \"head.html\" %}<main>{{ n }}</main>");
dict->set("cond.html", "{% if n > 1 %}big{% elif n == 1 %}one{% else %}none{% endif %}");
dict->set("loop.html",
"{% for u in users %}{{ loop.index }}:{{ u }}{% if not loop.last %},{% endif %}"
"{% else %}nobody{% endfor %}");
dict->set("filt.html", "{{ name|upper }}|{{ items|join(\", \") }}|{{ missing|default(\"d\") }}");
dict->set("tests.html",
"{% if x is defined %}D{% endif %}{% if y is none %}N{% endif %}"
"{% if n is even %}E{% endif %}{% if s is string %}S{% endif %}");
dict->set("mac.html", "{% macro greet(who, punct=\"!\") %}Hi {{ who }}{{ punct }}{% endmacro %}"
"{{ greet(\"ada\") }}{{ greet(\"bob\", punct=\"?\") }}");
dict->set("xss.html", "A{{ name }}B{{ name|safe }}C");
dict->set("raw.txt", "{{ name }}");
dict->set("loopvar.html", "{{ loop.length }}"); // unused outside loops
dict->set("set.html", "{% set t = a ~ b %}{{ t }}");
dict->set("esc.html", "{% autoescape false %}{{ name }}{% endautoescape %}");
env.add_loader(dict);
env.set_undefined_policy(templates::UndefinedPolicy::Chain);
return env;
}
int main() {
templates::Environment env = make_env();
validate::Object ctx;
ctx["name"] = validate::Value("ada");
CHECK(env.render("child.html", ctx).find("<title>kid</title>") != std::string::npos,
"extends overrides title block");
CHECK(env.render("child.html", ctx).find("Hello ada!") != std::string::npos,
"extends overrides body block");
CHECK(env.render("child.html", ctx).find("empty") == std::string::npos,
"parent default body replaced");
CHECK(env.render("page.html", ctx).find("<header>HEAD</header>") != std::string::npos,
"include renders partial");
validate::Object c2;
c2["n"] = validate::Value(5);
CHECK_EQ_STR(env.render("cond.html", c2), "big", "if branch");
c2["n"] = validate::Value(1);
CHECK_EQ_STR(env.render("cond.html", c2), "one", "elif branch");
c2["n"] = validate::Value(0);
CHECK_EQ_STR(env.render("cond.html", c2), "none", "else branch");
validate::Object loop;
validate::Array users;
users.emplace_back("a");
users.emplace_back("b");
loop["users"] = validate::Value(users);
CHECK_EQ_STR(env.render("loop.html", loop), "1:a,2:b", "for with loop.index and loop.last");
validate::Object empty;
empty["users"] = validate::Value(validate::Array{});
CHECK_EQ_STR(env.render("loop.html", empty), "nobody", "for else on empty");
validate::Object flt;
flt["name"] = validate::Value("ada");
validate::Array items;
items.emplace_back("x");
items.emplace_back("y");
flt["items"] = validate::Value(items);
CHECK_EQ_STR(env.render("filt.html", flt), "ADA|x, y|d", "filters upper join default");
validate::Object tst;
tst["x"] = validate::Value(1);
tst["y"] = validate::Value::null();
tst["n"] = validate::Value(4);
tst["s"] = validate::Value("hi");
CHECK_EQ_STR(env.render("tests.html", tst), "DNES", "tests defined none even string");
CHECK(env.render("mac.html", {}).find("Hi ada!") != std::string::npos, "macro call");
CHECK(env.render("mac.html", {}).find("Hi bob?") != std::string::npos, "macro kwarg");
validate::Object evil;
evil["name"] = validate::Value("<script>alert(1)</script>");
std::string xss = env.render("xss.html", evil);
CHECK(xss.find("&lt;script&gt;") != std::string::npos, "autoescape neutralizes markup");
CHECK(xss.find("B<script>alert(1)</script>C") != std::string::npos, "safe opts out");
CHECK_EQ_STR(env.render("raw.txt", evil), "<script>alert(1)</script>",
"txt template leaves text raw");
CHECK_EQ_STR(env.render("esc.html", evil), "<script>alert(1)</script>",
"autoescape block opts out");
validate::Object ab;
ab["a"] = validate::Value("x");
ab["b"] = validate::Value("y");
CHECK_EQ_STR(env.render("set.html", ab), "xy", "set with concat");
// Undefined policies.
templates::Environment strict = make_env();
strict.set_undefined_policy(templates::UndefinedPolicy::Strict);
bool strict_threw = false;
try {
strict.render_source("{{ nope }}", "t.html", {});
} catch (const templates::UndefinedError&) {
strict_threw = true;
}
CHECK(strict_threw, "strict undefined throws");
CHECK_EQ_STR(env.render_source("{{ nope }}", "t.html", {}), "", "chain renders empty");
// TemplateResponse through the stack.
app::Application app;
app.templates_env().add_loader(std::make_shared<templates::DictLoader>(
std::map<std::string, std::string>{{"hi.html", "<p>Hi {{ name }}!</p>"}}));
app.router().get("/hi", views::adapt([&app](http_msg::Request&) {
validate::Object c;
c["name"] = validate::Value("ada");
return http_msg::Response(templates::TemplateResponse(app.templates_env(), "hi.html", c));
}));
app.startup();
http_msg::Response tr = get(app, "/hi");
CHECK_EQ_INT(tr.status(), 200, "template route serves");
CHECK(tr.body().find("Hi ada!") != std::string::npos, "template route renders context");
// Include depth cap aborts safely.
templates::Environment deep = make_env();
auto chain = std::make_shared<templates::DictLoader>();
for (int i = 0; i < 18; ++i) {
chain->set("d" + std::to_string(i) + ".html",
"{% include \"d" + std::to_string(i + 1) + ".html\" %}");
}
chain->set("d18.html", "bottom");
deep.add_loader(chain);
bool depth_threw = false;
try {
deep.render("d0.html", {});
} catch (const templates::TemplateError&) {
depth_threw = true;
}
CHECK(depth_threw, "include depth 17 aborts safely");
// Loop iteration cap aborts safely.
validate::Object big;
validate::Array many;
many.reserve(100001);
for (int i = 0; i < 100001; ++i) many.emplace_back(i);
big["items"] = validate::Value(many);
bool loop_threw = false;
try {
env.render_source("{% for i in items %}{{ i }}{% endfor %}", "t.html", big);
} catch (const templates::TemplateError&) {
loop_threw = true;
}
CHECK(loop_threw, "100001 loop iterations abort safely");
// Output cap aborts safely.
std::string wide;
for (int i = 0; i < 400; ++i) wide += "{{ 'x' * 100000 }}";
bool out_threw = false;
try {
env.render_source(wide, "t.html", {});
} catch (const templates::TemplateError&) {
out_threw = true;
}
CHECK(out_threw, "render output over 32 MiB aborts safely");
// Traversal protection.
bool trav_threw = false;
try {
templates::FileLoader::sanitize("../../etc/passwd");
if (templates::FileLoader::sanitize("../../etc/passwd").empty()) trav_threw = true;
} catch (...) {
trav_threw = true;
}
CHECK(trav_threw, "template loader rejects traversal");
// Dev reload vs prod cache through real files.
std::filesystem::create_directories("build/tmp_templates");
{
std::ofstream f("build/tmp_templates/live.html");
f << "v1";
}
templates::Environment prod;
prod.add_loader(std::make_shared<templates::FileLoader>("build/tmp_templates"));
CHECK_EQ_STR(prod.render("live.html", {}), "v1", "prod renders file");
{
std::ofstream f("build/tmp_templates/live.html");
f << "v2";
}
CHECK_EQ_STR(prod.render("live.html", {}), "v1", "prod serves compiled cache");
templates::Environment dev;
dev.add_loader(std::make_shared<templates::FileLoader>("build/tmp_templates"));
dev.set_dev_reload(true);
CHECK_EQ_STR(dev.render("live.html", {}), "v2", "dev reload picks up edits");
// Cache holds at most 512 entries.
templates::Environment cache_env = make_env();
for (int i = 0; i < 520; ++i) {
cache_env.render_source("x", "t" + std::to_string(i) + ".html", {});
}
(void)cache_env;
templates::Environment cache2;
auto many_loader = std::make_shared<templates::DictLoader>();
for (int i = 0; i < 520; ++i) {
many_loader->set("k" + std::to_string(i) + ".html", "x");
}
cache2.add_loader(many_loader);
for (int i = 0; i < 520; ++i) cache2.render("k" + std::to_string(i) + ".html", {});
CHECK_EQ_INT((long long)cache2.cache().size(), 512, "compiled cache capped at 512 LRU");
return test_report("templates/render");
}
+75
View File
@@ -0,0 +1,75 @@
// V2: static/converter/catch-all matches, 404 shape, 405 Allow, url_for.
#include "../_testlib.h"
using namespace molo::app;
int main() {
app::Application app;
app.router().get("/users/me", views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("me");
}));
routing::RouteOptions detail;
detail.name = "user_detail";
app.router().get("/users/{id:int}", views::adapt([](http_msg::Request& req) {
return http_msg::TextResponse("user " + req.path_param("id"));
}), detail);
routing::RouteOptions file;
file.name = "file_catch";
app.router().get("/files/{rest:path}", views::adapt([](http_msg::Request& req) {
return http_msg::TextResponse("file " + req.path_param("rest"));
}), file);
routing::RouteOptions multi;
multi.name = "multi";
app.router().add({http_msg::Method::GET, http_msg::Method::POST}, "/multi",
views::adapt([](http_msg::Request&) {
return http_msg::TextResponse("m");
}),
multi);
app.startup();
CHECK_EQ_STR(get(app, "/users/me").body(), "me", "static route wins over converter");
CHECK_EQ_STR(get(app, "/users/42").body(), "user 42", "int converter binds");
CHECK_EQ_STR(get(app, "/files/a/b/c").body(), "file a/b/c", "path catch-all binds rest");
http_msg::Response nf = get(app, "/nope");
CHECK_EQ_INT(nf.status(), 404, "missing route is 404");
validate::Value body = validate::parse_json(nf.body());
const auto* root = std::get_if<validate::Object>(&body.storage());
CHECK(root != nullptr && root->count("error"), "404 has error shape");
const auto* inner = std::get_if<validate::Object>(&root->at("error").storage());
CHECK(inner != nullptr && inner->at("code") == validate::Value("not_found"),
"404 code is not_found");
CHECK(inner != nullptr && !inner->at("request_id").as_text().empty(),
"404 carries request_id");
http_msg::Request bad = make_request("POST", "/users/me");
http_msg::Response m = run_request(app, bad);
CHECK_EQ_INT(m.status(), 405, "method mismatch is 405");
CHECK_EQ_STR(m.headers().get("allow"), "GET", "405 Allow lists GET");
http_msg::Request bad2 = make_request("DELETE", "/multi");
http_msg::Response m2 = run_request(app, bad2);
CHECK_EQ_INT(m2.status(), 405, "multi-method mismatch is 405");
CHECK_EQ_STR(m2.headers().get("allow"), "GET, POST", "405 Allow exact value");
CHECK_EQ_STR(app.url_for("user_detail", {{"id", "7"}}), "/users/7", "url_for converter");
CHECK_EQ_STR(app.url_for("file_catch", {{"rest", "a/b"}}), "/files/a/b", "url_for catch-all");
CHECK_EQ_STR(app.url_for("multi", {}, "a=1"), "/multi?a=1", "url_for with query");
bool threw = false;
try {
app.url_for("no_such_route");
} catch (const errors::NotFound&) {
threw = true;
}
CHECK(threw, "url_for unknown name throws NotFound");
bool slash_404 = (get(app, "/users/me/").status() == 404);
CHECK(slash_404, "trailing slash is strict by default");
std::string long_path = "/" + std::string(2048, 'x');
http_msg::Response too_long = get(app, long_path);
CHECK_EQ_INT(too_long.status(), 414, "overlong path yields 414");
CHECK(!too_long.headers().get("x-request-id").empty(), "414 echoes request id");
return test_report("users/detail");
}
+75
View File
@@ -0,0 +1,75 @@
// V4: one 422 listing every bad field across path, query, header, cookie.
#include "../_testlib.h"
using namespace molo::app;
static std::shared_ptr<validate::Model> query_model() {
auto m = std::make_shared<validate::Model>("q");
validate::Field age("age", validate::FieldType::Int);
age.required().ge(0);
validate::Field name("name", validate::FieldType::String);
name.required().min_len(2);
m->field(age).field(name);
return m;
}
int main() {
app::Application app;
routing::RouteOptions o;
o.name = "search";
o.query_model = query_model();
auto hm = std::make_shared<validate::Model>("h");
validate::Field token("x-token", validate::FieldType::String);
token.required();
hm->field(token);
o.header_model = hm;
auto cm = std::make_shared<validate::Model>("c");
validate::Field sess("session", validate::FieldType::String);
sess.required();
cm->field(sess);
o.cookie_model = cm;
app.router().get("/search", views::adapt([](http_msg::Request& req) {
const validate::Object* q = req.validated("query");
return http_msg::TextResponse("ok " + q->at("name").as_text());
}), o);
routing::RouteOptions u;
u.name = "user";
app.router().get("/users/{id:int}", views::adapt([](http_msg::Request& req) {
return http_msg::TextResponse("user " + req.path_param("id"));
}), u);
app.startup();
http_msg::Response good =
get(app, "/search?age=3&name=ada", {{"x-token", "t"}, {"cookie", "session=s"}});
CHECK_EQ_INT(good.status(), 200, "valid input binds");
CHECK_EQ_STR(good.body(), "ok ada", "validated value reaches handler");
// Four violations at once: age, name, header, cookie.
http_msg::Response bad = get(app, "/search?age=-1&name=x");
CHECK_EQ_INT(bad.status(), 422, "invalid input yields 422");
validate::Value parsed = validate::parse_json(bad.body());
const auto* root = std::get_if<validate::Object>(&parsed.storage());
CHECK(root != nullptr && root->count("detail"), "422 has detail shape");
const auto* detail = std::get_if<validate::Array>(&root->at("detail").storage());
CHECK(detail != nullptr && detail->size() == 4, "422 lists every bad field at once");
std::string joined;
for (const auto& item : *detail) {
const auto* f = std::get_if<validate::Object>(&item.storage());
const auto* loc = std::get_if<validate::Array>(&f->at("loc").storage());
for (const auto& part : *loc) joined += part.as_text() + ".";
joined += ";";
CHECK(!f->at("msg").as_text().empty(), "failure carries msg");
CHECK(!f->at("type").as_text().empty(), "failure carries type");
}
CHECK(joined.find("query.age") != std::string::npos, "query age failure listed");
CHECK(joined.find("query.name") != std::string::npos, "query name failure listed");
CHECK(joined.find("header.x-token") != std::string::npos, "header failure listed");
CHECK(joined.find("cookie.session") != std::string::npos, "cookie failure listed");
// Path converter failure is a 422 with path loc.
http_msg::Response pint = get(app, "/users/abc");
CHECK_EQ_INT(pint.status(), 422, "bad path converter yields 422");
CHECK(pint.body().find("\"path\"") != std::string::npos, "path loc present");
CHECK(pint.body().find("\"id\"") != std::string::npos, "path param name present");
return test_report("validate/input");
}
+54
View File
@@ -0,0 +1,54 @@
// V7: view method dispatch, 405 on unimplemented, redirects, flash-once.
#include "../_testlib.h"
using namespace molo::app;
class UserView : public views::View {
public:
using View::View;
async::Task<http_msg::Response> get() override {
std::string out = "got " + request().path_param("id");
co_return http_msg::TextResponse(out);
}
async::Task<http_msg::Response> post() override {
co_return http_msg::TextResponse("posted");
}
std::vector<std::string> allowed_methods() const override { return {"GET", "POST"}; }
};
int main() {
app::Application app;
app.router().add({http_msg::Method::GET, http_msg::Method::POST, http_msg::Method::PUT},
"/users/{id:int}", views::view_handler<UserView>());
app.router().get("/flash", views::adapt([](http_msg::Request& req) {
http_msg::Response res = http_msg::TextResponse("flashed");
views::Flash::flash(req, res, "info", "hello once");
return res;
}));
app.router().get("/show", views::adapt([](http_msg::Request& req) {
std::vector<seams::FlashMessage> msgs = views::Flash::take(req);
std::string out;
for (const auto& m : msgs) out += m.level + ":" + m.text + ";";
return http_msg::TextResponse(out);
}));
app.startup();
CHECK_EQ_STR(get(app, "/users/9").body(), "got 9", "view dispatches GET");
http_msg::Request post = make_request("POST", "/users/9");
CHECK_EQ_STR(run_request(app, post).body(), "posted", "view dispatches POST");
http_msg::Request put = make_request("PUT", "/users/9");
http_msg::Response m = run_request(app, put);
CHECK_EQ_INT(m.status(), 405, "unimplemented view method yields 405");
CHECK_EQ_STR(m.headers().get("allow"), "GET, POST", "view 405 Allow value");
http_msg::Response f1 = get(app, "/flash");
CHECK_EQ_INT(f1.status(), 200, "flash route serves");
std::string set_cookie = f1.headers().get("set-cookie");
CHECK(set_cookie.find("molo_session=") != std::string::npos, "flash sets session cookie");
std::string cookie = set_cookie.substr(0, set_cookie.find(';'));
http_msg::Response s1 = get(app, "/show", {{"cookie", cookie}});
CHECK_EQ_STR(s1.body(), "info:hello once;", "flash appears on next request");
http_msg::Response s2 = get(app, "/show", {{"cookie", cookie}});
CHECK_EQ_STR(s2.body(), "", "flash appears exactly once");
return test_report("views/dispatch");
}