feat(workflow): example covers security, platform, enterprise and resilience features
105 route tests, matrix crawl, spec and README updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -51,6 +51,22 @@ std::shared_ptr<fw::Application> build_application(Services& services) {
|
||||
register_stats_demo(stats, services);
|
||||
app->include_router("", stats);
|
||||
|
||||
fw::Router security_extra;
|
||||
register_security_extra_demo(security_extra, services);
|
||||
app->include_router("", security_extra);
|
||||
|
||||
fw::Router platform;
|
||||
register_platform_demo(platform, services);
|
||||
app->include_router("", platform);
|
||||
|
||||
fw::Router enterprise;
|
||||
register_enterprise_demo(enterprise, services);
|
||||
app->include_router("", enterprise);
|
||||
|
||||
fw::Router resilience;
|
||||
register_resilience_demo(resilience, services);
|
||||
app->include_router("", resilience);
|
||||
|
||||
register_chain_demo(app, services);
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../fw/App.hpp"
|
||||
#include "../fw/Data.hpp"
|
||||
@@ -47,6 +49,12 @@ struct Services {
|
||||
std::shared_ptr<fw::OpenApi> openapi = std::make_shared<fw::OpenApi>();
|
||||
std::shared_ptr<fw::Environment> templates =
|
||||
std::make_shared<fw::Environment>();
|
||||
// Feature matrix rows (feature, route) shown on the index page. Each
|
||||
// register_*_demo adds its own rows with add_feature().
|
||||
std::vector<std::pair<std::string, std::string>> features;
|
||||
void add_feature(std::string feature, std::string route) {
|
||||
features.emplace_back(std::move(feature), std::move(route));
|
||||
}
|
||||
std::map<std::string, std::string> embedded;
|
||||
std::string static_root = "example/static";
|
||||
std::string cookie_secret = "living-example-secret";
|
||||
@@ -64,6 +72,10 @@ void register_formats_demo(fw::Router& router, Services& services);
|
||||
void register_realtime_demo(fw::Router& router, Services& services);
|
||||
void register_ops_demo(fw::Router& router, Services& services);
|
||||
void register_stats_demo(fw::Router& router, Services& services);
|
||||
void register_security_extra_demo(fw::Router& router, Services& services);
|
||||
void register_platform_demo(fw::Router& router, Services& services);
|
||||
void register_enterprise_demo(fw::Router& router, Services& services);
|
||||
void register_resilience_demo(fw::Router& router, Services& services);
|
||||
|
||||
void load_templates(Services& services);
|
||||
void load_embedded(Services& services);
|
||||
|
||||
@@ -72,7 +72,10 @@ void register_data_demo(fw::Router& router, Services& services) {
|
||||
|
||||
router.get("/kv/items", "kv-get", [kv](fw::Request req) {
|
||||
std::string key = req.query_or("key", "");
|
||||
if (key.empty()) return fw::JsonResponse("{\"error\":\"key required\"}", 400);
|
||||
if (key.empty())
|
||||
return fw::JsonResponse("{\"entries\":" + std::to_string(kv->size()) +
|
||||
",\"usage\":\"GET ?key=<key>, POST key+value\"}",
|
||||
200);
|
||||
std::string value;
|
||||
if (!kv->get(key, value))
|
||||
return fw::JsonResponse("{\"error\":\"not found\"}", 404);
|
||||
|
||||
@@ -0,0 +1,691 @@
|
||||
#include "App.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
#include "FormUi.hpp"
|
||||
#include "../fw/Enterprise.hpp"
|
||||
#include "../fw/Router.hpp"
|
||||
#include "../fw/Templates.hpp"
|
||||
#include "../fw/Validate.hpp"
|
||||
|
||||
namespace molo::example::app {
|
||||
|
||||
namespace {
|
||||
|
||||
using fw::Response;
|
||||
using fw::Request;
|
||||
|
||||
// All enterprise demo state lives here, owned through one shared_ptr.
|
||||
struct Hub {
|
||||
fw::TenantResolver resolver;
|
||||
fw::TenantCatalog catalog;
|
||||
fw::TenantData data;
|
||||
fw::TenantQuota quota;
|
||||
fw::FeatureFlags flags;
|
||||
fw::ConfigOverlay config;
|
||||
fw::TenantMetrics metrics;
|
||||
fw::AuditChain chain;
|
||||
fw::RetentionStore retention;
|
||||
fw::SubjectStore subjects;
|
||||
fw::ApiKeyStore keys;
|
||||
fw::QuotaLedger ledger;
|
||||
fw::VersionTable versions;
|
||||
Hub() {
|
||||
chain.append("system", "boot", "audit", "chain started");
|
||||
chain.append("ada", "login", "session", "from [IP]");
|
||||
chain.append("bob", "export", "report", "monthly report");
|
||||
}
|
||||
};
|
||||
using HubPtr = std::shared_ptr<Hub>;
|
||||
|
||||
std::string q(const std::string& s) { return "\"" + fw::json_escape(s) + "\""; }
|
||||
|
||||
std::map<std::string, std::string> input(const Request& req) {
|
||||
auto in = fw::parse_json_object_flat(req.body);
|
||||
if (in.empty()) in = fw::parse_form(req.body);
|
||||
return in;
|
||||
}
|
||||
|
||||
std::string get_or(const std::map<std::string, std::string>& m, const std::string& k,
|
||||
const std::string& d = "") {
|
||||
auto it = m.find(k);
|
||||
return it == m.end() ? d : it->second;
|
||||
}
|
||||
|
||||
bool json_client(const Request& req) { return !wants_html(req); }
|
||||
|
||||
Response page(fw::Environment* env, const std::string& heading, const std::string& body,
|
||||
int status = 200) {
|
||||
fw::TemplateCtx c;
|
||||
c["title"] = heading;
|
||||
c["heading"] = heading;
|
||||
c["body"] = body;
|
||||
return Response(status, env->render("ent_page.html", c), "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
Response form_page(fw::Environment* env, FormView& v, int status = 200) {
|
||||
return Response(status, env->render("form_page.html", v.ctx()), "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
Response form_fail(fw::Environment* env, const Request& req, FormView& v,
|
||||
const fw::ValidationError& e,
|
||||
const std::map<std::string, std::string>& in) {
|
||||
if (json_client(req)) return fw::JsonResponse(e.to_json(), 422);
|
||||
v.values = in;
|
||||
v.error = &e;
|
||||
return form_page(env, v, 422);
|
||||
}
|
||||
|
||||
Response form_ok(fw::Environment* env, const Request& req, FormView& v,
|
||||
const std::string& notice, const std::string& json, int status = 200) {
|
||||
if (json_client(req)) return fw::JsonResponse(json, status);
|
||||
v.notice = notice;
|
||||
v.done = true;
|
||||
return form_page(env, v, status);
|
||||
}
|
||||
|
||||
std::string table(const std::vector<std::string>& head,
|
||||
const std::vector<std::vector<std::string>>& rows) {
|
||||
std::string t = "<div class=\"scroll\"><table><thead><tr>";
|
||||
for (const auto& h : head) t += "<th>" + fw::html_escape(h) + "</th>";
|
||||
t += "</tr></thead><tbody>";
|
||||
for (const auto& r : rows) {
|
||||
t += "<tr>";
|
||||
for (const auto& c : r) t += "<td>" + fw::html_escape(c) + "</td>";
|
||||
t += "</tr>";
|
||||
}
|
||||
return t + "</tbody></table></div>";
|
||||
}
|
||||
|
||||
std::string form_html(const std::string& action, const std::string& label,
|
||||
const std::vector<std::pair<std::string, std::string>>& fields,
|
||||
const std::string& button) {
|
||||
std::string f = "<form method=\"post\" action=\"" + action + "\"><h2>" +
|
||||
fw::html_escape(label) + "</h2>";
|
||||
for (const auto& [name, lab] : fields)
|
||||
f += "<div class=\"field\"><label for=\"" + name + "\">" + fw::html_escape(lab) +
|
||||
"</label><input id=\"" + name + "\" name=\"" + name + "\"></div>";
|
||||
return f + "<button type=\"submit\">" + button + "</button></form>";
|
||||
}
|
||||
|
||||
// ---- tenancy ---------------------------------------------------------------
|
||||
struct Tctx {
|
||||
fw::TenantRef ref;
|
||||
const fw::Tenant* tenant = nullptr;
|
||||
std::optional<Response> failure;
|
||||
};
|
||||
|
||||
Tctx tenant_of(const Hub& h, const Request& req, const std::string& path_tenant = "") {
|
||||
Tctx c;
|
||||
c.ref = h.resolver.resolve(req, path_tenant);
|
||||
if (!c.ref.error.empty()) {
|
||||
c.failure = fw::problem_response(400, "Bad tenant id", c.ref.error, req.path);
|
||||
return c;
|
||||
}
|
||||
c.tenant = h.catalog.find(c.ref.id);
|
||||
if (!c.tenant)
|
||||
c.failure = fw::problem_response(404, "Unknown tenant", "no tenant " + c.ref.id, req.path);
|
||||
return c;
|
||||
}
|
||||
|
||||
std::string tenant_json(const Tctx& c) {
|
||||
return "{\"tenant\":" + q(c.ref.id) + ",\"source\":" + q(c.ref.source) +
|
||||
",\"plan\":" + q(c.tenant ? c.tenant->plan : "") + "}";
|
||||
}
|
||||
|
||||
void register_tenancy(fw::Router& router, Services& services, const HubPtr& hub,
|
||||
fw::Environment* env) {
|
||||
router.get("/tenancy/resolve", "tenancy-resolve", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
hub->metrics.inc(c.ref.id, "resolve");
|
||||
return fw::JsonResponse(tenant_json(c));
|
||||
});
|
||||
router.get("/tenancy/t/{tenant}/whoami", "tenancy-path", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req, req.param_or("tenant", ""));
|
||||
if (c.failure) return *c.failure;
|
||||
hub->metrics.inc(c.ref.id, "whoami");
|
||||
return fw::JsonResponse(tenant_json(c));
|
||||
});
|
||||
|
||||
router.get("/tenancy/data", "tenancy-data", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
hub->metrics.inc(c.ref.id, "data.list");
|
||||
std::string items;
|
||||
for (const auto& i : hub->data.list(c.ref.id)) items += (items.empty() ? "" : ",") + q(i);
|
||||
return fw::JsonResponse("{\"tenant\":" + q(c.ref.id) + ",\"items\":[" + items + "]}");
|
||||
});
|
||||
router.post("/tenancy/data", "tenancy-data-add", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
std::string item = get_or(input(req), "item");
|
||||
if (item.empty() || item.size() > 200)
|
||||
return fw::problem_response(422, "Invalid item", "item must be 1-200 chars", req.path);
|
||||
if (!hub->data.add(c.ref.id, item))
|
||||
return fw::problem_response(429, "Tenant data cap", "50 items per tenant", req.path);
|
||||
hub->metrics.inc(c.ref.id, "data.add");
|
||||
return fw::JsonResponse("{\"ok\":true,\"tenant\":" + q(c.ref.id) + "}", 201);
|
||||
});
|
||||
|
||||
auto quota_json = [hub](const Tctx& c) {
|
||||
return "{\"tenant\":" + q(c.ref.id) + ",\"plan\":" + q(c.tenant->plan) +
|
||||
",\"used\":" + std::to_string(hub->quota.used(c.ref.id)) +
|
||||
",\"limit\":" + std::to_string(fw::TenantQuota::limit_for(c.tenant->plan)) + "}";
|
||||
};
|
||||
router.get("/tenancy/quota", "tenancy-quota", [hub, quota_json](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
return fw::JsonResponse(quota_json(c));
|
||||
});
|
||||
router.post("/tenancy/quota", "tenancy-quota-use", [hub, quota_json](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
if (!hub->quota.consume(c.ref.id, c.tenant->plan)) {
|
||||
hub->metrics.inc(c.ref.id, "quota.denied");
|
||||
Response r = fw::problem_response(429, "Quota exceeded", quota_json(c), req.path);
|
||||
r.headers.set("Retry-After", "60");
|
||||
return r;
|
||||
}
|
||||
hub->metrics.inc(c.ref.id, "quota.used");
|
||||
return fw::JsonResponse(quota_json(c));
|
||||
});
|
||||
|
||||
router.get("/tenancy/flags", "tenancy-flags", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
std::string out;
|
||||
for (const auto& [f, on] : hub->flags.effective(c.ref.id))
|
||||
out += (out.empty() ? "" : ",") + q(f) + ":" + (on ? "true" : "false");
|
||||
return fw::JsonResponse("{\"tenant\":" + q(c.ref.id) + ",\"flags\":{" + out + "}}");
|
||||
});
|
||||
router.post("/tenancy/flags", "tenancy-flags-set", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
auto in = input(req);
|
||||
std::string flag = get_or(in, "flag"), on = get_or(in, "enabled");
|
||||
if (!hub->flags.known(flag))
|
||||
return fw::problem_response(422, "Unknown flag", "flag " + flag, req.path);
|
||||
if (on != "true" && on != "false")
|
||||
return fw::problem_response(422, "Invalid value", "enabled must be true or false", req.path);
|
||||
if (!hub->flags.set(c.ref.id, flag, on == "true"))
|
||||
return fw::problem_response(429, "Flag cap", "override cap reached", req.path);
|
||||
hub->metrics.inc(c.ref.id, "flags.set");
|
||||
return fw::JsonResponse("{\"ok\":true,\"flag\":" + q(flag) + ",\"enabled\":" + on + "}");
|
||||
});
|
||||
|
||||
router.get("/tenancy/config", "tenancy-config", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
std::string out;
|
||||
for (const auto& [k, v] : hub->config.effective(c.ref.id))
|
||||
out += (out.empty() ? "" : ",") + q(k) + ":" + q(v);
|
||||
return fw::JsonResponse("{\"tenant\":" + q(c.ref.id) + ",\"config\":{" + out + "}}");
|
||||
});
|
||||
router.post("/tenancy/config", "tenancy-config-set", [hub](Request req) -> Response {
|
||||
Tctx c = tenant_of(*hub, req);
|
||||
if (c.failure) return *c.failure;
|
||||
auto in = input(req);
|
||||
std::string key = get_or(in, "key"), value = get_or(in, "value");
|
||||
if (!hub->config.known(key))
|
||||
return fw::problem_response(422, "Unknown key", "key " + key, req.path);
|
||||
if (value.empty() || value.size() > 64)
|
||||
return fw::problem_response(422, "Invalid value", "value must be 1-64 chars", req.path);
|
||||
if (!hub->config.set(c.ref.id, key, value))
|
||||
return fw::problem_response(429, "Config cap", "override cap reached", req.path);
|
||||
hub->metrics.inc(c.ref.id, "config.set");
|
||||
return fw::JsonResponse("{\"ok\":true}");
|
||||
});
|
||||
|
||||
router.get("/tenancy/metrics", "tenancy-metrics", [hub](Request req) -> Response {
|
||||
(void)req;
|
||||
std::string out;
|
||||
for (const auto& [t, m] : hub->metrics.all()) {
|
||||
std::string inner;
|
||||
for (const auto& [k, v] : m)
|
||||
inner += (inner.empty() ? "" : ",") + q(k) + ":" + std::to_string(v);
|
||||
out += (out.empty() ? "" : ",") + q(t) + ":{" + inner + "}";
|
||||
}
|
||||
return fw::JsonResponse("{\"tenants\":{" + out + "}}");
|
||||
});
|
||||
|
||||
auto prov_view = [] {
|
||||
FormView v;
|
||||
v.title = "Provision a tenant";
|
||||
v.action = "/tenancy/provision";
|
||||
v.submit = "Provision";
|
||||
v.fields = {{"id", "Tenant id", "text", "2-32 chars: a-z, 0-9, dash"},
|
||||
{"name", "Name", "text", ""},
|
||||
{"plan", "Plan", "text", "free or pro"}};
|
||||
return v;
|
||||
};
|
||||
router.get("/tenancy/provision", "tenancy-provision-form", [env, prov_view](Request) {
|
||||
FormView v = prov_view();
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.post("/tenancy/provision", "tenancy-provision",
|
||||
[hub, env, prov_view](Request req) -> Response {
|
||||
FormView v = prov_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"id", fw::FieldType::String, true, 2, 32, 0, 0, false, ""},
|
||||
{"name", fw::FieldType::String, true, 1, 80, 0, 0, false, ""},
|
||||
{"plan", fw::FieldType::String, false, 0, 8, 0, 0, false, "free"}});
|
||||
try {
|
||||
auto clean = m.validate(in);
|
||||
std::vector<fw::FieldError> bad;
|
||||
if (!fw::TenantResolver::valid_id(clean["id"]))
|
||||
bad.push_back({"id", "use a-z, 0-9 and dash only"});
|
||||
if (clean["plan"] != "free" && clean["plan"] != "pro")
|
||||
bad.push_back({"plan", "must be free or pro"});
|
||||
if (!bad.empty()) throw fw::ValidationError(bad);
|
||||
std::string why = hub->catalog.provision(clean["id"], clean["name"], clean["plan"]);
|
||||
if (!why.empty()) throw fw::ValidationError({{"id", why}});
|
||||
return form_ok(env, req, v, "Tenant " + clean["id"] + " provisioned.",
|
||||
"{\"ok\":true,\"tenant\":" + q(clean["id"]) + "}", 201);
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
services.add_feature("Tenant resolution (header, subdomain, path)", "/tenancy/resolve");
|
||||
services.add_feature("Tenant path resolution", "/tenancy/t/demo/whoami");
|
||||
services.add_feature("Tenant data isolation", "/tenancy/data");
|
||||
services.add_feature("Tenant quotas", "/tenancy/quota");
|
||||
services.add_feature("Tenant feature flags", "/tenancy/flags");
|
||||
services.add_feature("Tenant config overlay", "/tenancy/config");
|
||||
services.add_feature("Per-tenant metrics", "/tenancy/metrics");
|
||||
services.add_feature("Tenant provisioning form", "/tenancy/provision");
|
||||
}
|
||||
|
||||
// ---- audit -----------------------------------------------------------------
|
||||
std::string records_json(const fw::AuditChain& chain) {
|
||||
std::string out;
|
||||
for (const auto& r : chain.records())
|
||||
out += std::string(out.empty() ? "" : ",") + "{\"index\":" + std::to_string(r.index) +
|
||||
",\"actor\":" + q(r.actor) + ",\"action\":" + q(r.action) +
|
||||
",\"subject\":" + q(r.subject) + ",\"detail\":" + q(r.detail) +
|
||||
",\"hash\":" + q(r.hash) + "}";
|
||||
return out;
|
||||
}
|
||||
|
||||
void register_audit(fw::Router& router, Services& services, const HubPtr& hub,
|
||||
fw::Environment* env) {
|
||||
auto log_view = [] {
|
||||
FormView v;
|
||||
v.title = "Append audit record";
|
||||
v.action = "/audit/log";
|
||||
v.submit = "Append";
|
||||
v.fields = {{"actor", "Actor", "text", ""},
|
||||
{"action", "Action", "text", ""},
|
||||
{"subject", "Subject", "text", ""},
|
||||
{"detail", "Detail", "textarea", "PII is redacted before storage"}};
|
||||
return v;
|
||||
};
|
||||
|
||||
router.get("/audit/log", "audit-log", [hub, env](Request req) -> Response {
|
||||
if (json_client(req))
|
||||
return fw::JsonResponse("{\"records\":[" + records_json(hub->chain) + "]}");
|
||||
std::vector<std::vector<std::string>> rows;
|
||||
for (const auto& r : hub->chain.records())
|
||||
rows.push_back({std::to_string(r.index), r.actor, r.action, r.subject, r.detail,
|
||||
r.hash.substr(0, 12)});
|
||||
auto bad = hub->chain.verify();
|
||||
std::string status = bad ? "<p class=\"error\">Chain broken at index " +
|
||||
std::to_string(*bad) + "</p>"
|
||||
: "<p class=\"ok\">Chain intact (" +
|
||||
std::to_string(hub->chain.records().size()) + " records)</p>";
|
||||
return page(env, "Audit log",
|
||||
status + table({"#", "Actor", "Action", "Subject", "Detail", "Hash"}, rows) +
|
||||
form_html("/audit/log", "Append record",
|
||||
{{"actor", "Actor"}, {"action", "Action"},
|
||||
{"subject", "Subject"}, {"detail", "Detail"}},
|
||||
"Append") +
|
||||
"<p><a href=\"/audit/verify\">Verify</a></p>");
|
||||
});
|
||||
router.post("/audit/log", "audit-log-append", [hub, env, log_view](Request req) -> Response {
|
||||
FormView v = log_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"actor", fw::FieldType::String, true, 1, 40, 0, 0, false, ""},
|
||||
{"action", fw::FieldType::String, true, 1, 40, 0, 0, false, ""},
|
||||
{"subject", fw::FieldType::String, true, 1, 80, 0, 0, false, ""},
|
||||
{"detail", fw::FieldType::String, false, 0, 500, 0, 0, false, ""}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
if (!hub->chain.append(c["actor"], c["action"], c["subject"],
|
||||
fw::PiiMasker::redact(c["detail"])))
|
||||
throw fw::ValidationError({{"actor", "audit log is full (500 records, append-only)"}});
|
||||
return form_ok(env, req, v, "Record appended.",
|
||||
"{\"ok\":true,\"index\":" + std::to_string(hub->chain.records().size() - 1) + "}",
|
||||
201);
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/audit/verify", "audit-verify", [hub](Request) {
|
||||
auto bad = hub->chain.verify();
|
||||
return fw::JsonResponse(std::string("{\"intact\":") + (bad ? "false" : "true") +
|
||||
",\"records\":" + std::to_string(hub->chain.records().size()) +
|
||||
",\"first_broken\":" + (bad ? std::to_string(*bad) : "null") + "}");
|
||||
});
|
||||
router.post("/audit/tamper", "audit-tamper", [hub](Request req) -> Response {
|
||||
std::string idx = get_or(input(req), "index");
|
||||
std::size_t i = 0;
|
||||
if (idx.empty() || idx.size() > 6 || idx.find_first_not_of("0123456789") != std::string::npos)
|
||||
return fw::problem_response(422, "Invalid index", "index must be a number", req.path);
|
||||
i = std::stoul(idx);
|
||||
if (!hub->chain.tamper(i))
|
||||
return fw::problem_response(404, "No such record", "index " + idx, req.path);
|
||||
return fw::JsonResponse("{\"tampered\":" + idx + "}");
|
||||
});
|
||||
|
||||
router.get("/audit/mask", "audit-mask", [](Request req) {
|
||||
std::string email = req.query_or("email", "ada.lovelace@example.com");
|
||||
std::string card = req.query_or("card", "4111 1111 1111 1111");
|
||||
std::string text = req.query_or("text", "mail ada@example.com card 4111 1111 1111 1111 ssn 123-45-6789 from 10.0.0.7");
|
||||
std::size_t hits = 0;
|
||||
std::string red = fw::PiiMasker::redact(text, &hits);
|
||||
return fw::JsonResponse("{\"email\":" + q(fw::PiiMasker::mask_email(email.substr(0, 120))) +
|
||||
",\"card\":" + q(fw::PiiMasker::mask_card(card.substr(0, 40))) +
|
||||
",\"redacted\":" + q(red) + ",\"redactions\":" +
|
||||
std::to_string(hits) + "}");
|
||||
});
|
||||
|
||||
auto retention_json = [hub] {
|
||||
std::string e, x;
|
||||
for (const auto& r : hub->retention.entries())
|
||||
e += std::string(e.empty() ? "" : ",") + "{\"id\":" + q(r.id) + ",\"class\":" + q(r.klass) +
|
||||
",\"age_days\":" + std::to_string(r.age_days) + ",\"hold\":" +
|
||||
(r.hold ? "true" : "false") + "}";
|
||||
for (const auto& id : hub->retention.expired()) x += (x.empty() ? "" : ",") + q(id);
|
||||
return "{\"entries\":[" + e + "],\"expired\":[" + x + "]}";
|
||||
};
|
||||
router.get("/audit/retention", "audit-retention", [env, retention_json, hub](Request req) -> Response {
|
||||
if (json_client(req)) return fw::JsonResponse(retention_json());
|
||||
std::vector<std::vector<std::string>> rows;
|
||||
auto exp = hub->retention.expired();
|
||||
for (const auto& r : hub->retention.entries())
|
||||
rows.push_back({r.id, r.klass, std::to_string(r.age_days),
|
||||
std::to_string(fw::RetentionStore::max_age(r.klass)),
|
||||
r.hold ? "legal hold" : (std::find(exp.begin(), exp.end(), r.id) != exp.end() ? "expired" : "keep")});
|
||||
return page(env, "Retention",
|
||||
table({"Id", "Class", "Age (d)", "Max (d)", "State"}, rows) +
|
||||
form_html("/audit/retention/hold", "Legal hold",
|
||||
{{"id", "Entry id"}, {"hold", "true or false"}}, "Set hold") +
|
||||
form_html("/audit/retention/purge", "Purge expired (dry run unless confirm=yes)",
|
||||
{{"confirm", "Type yes to run"}}, "Purge"));
|
||||
});
|
||||
router.post("/audit/retention/hold", "audit-retention-hold", [hub](Request req) -> Response {
|
||||
auto in = input(req);
|
||||
std::string hold = get_or(in, "hold");
|
||||
if (hold != "true" && hold != "false")
|
||||
return fw::problem_response(422, "Invalid hold", "hold must be true or false", req.path);
|
||||
if (!hub->retention.set_hold(get_or(in, "id"), hold == "true"))
|
||||
return fw::problem_response(404, "No such entry", get_or(in, "id"), req.path);
|
||||
hub->chain.append("system", "legal-hold", get_or(in, "id"), "hold=" + hold);
|
||||
return fw::JsonResponse("{\"ok\":true,\"hold\":" + hold + "}");
|
||||
});
|
||||
router.post("/audit/retention/purge", "audit-retention-purge", [hub](Request req) -> Response {
|
||||
bool confirm = get_or(input(req), "confirm") == "yes";
|
||||
auto exp = hub->retention.expired();
|
||||
std::size_t n = confirm ? hub->retention.purge() : 0;
|
||||
if (confirm) hub->chain.append("system", "purge", "retention", std::to_string(n) + " removed");
|
||||
return fw::JsonResponse(std::string("{\"dry_run\":") + (confirm ? "false" : "true") +
|
||||
",\"would_purge\":" + std::to_string(exp.size()) +
|
||||
",\"purged\":" + std::to_string(n) + "}");
|
||||
});
|
||||
|
||||
auto erase_view = [] {
|
||||
FormView v;
|
||||
v.title = "Data subject erasure";
|
||||
v.action = "/audit/subject/erase";
|
||||
v.submit = "Erase";
|
||||
v.fields = {{"subject", "Subject email", "email", "cascades across all tables"},
|
||||
{"confirm", "Confirm", "text", "type yes to erase"}};
|
||||
return v;
|
||||
};
|
||||
router.get("/audit/subject", "audit-subject", [env, erase_view](Request) {
|
||||
FormView v = erase_view();
|
||||
v.notice = "Export first: /audit/subject/export?subject=ada@example.com";
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.get("/audit/subject/export", "audit-subject-export", [hub](Request req) -> Response {
|
||||
std::string s = req.query_or("subject", "");
|
||||
if (s.empty() || s.size() > 120)
|
||||
return fw::problem_response(400, "Missing subject", "?subject= is required", req.path);
|
||||
std::string out;
|
||||
for (const auto& [t, rows] : hub->subjects.export_for(s)) {
|
||||
std::string r;
|
||||
for (const auto& x : rows) r += (r.empty() ? "" : ",") + q(x);
|
||||
out += std::string(out.empty() ? "" : ",") + q(t) + ":[" + r + "]";
|
||||
}
|
||||
return fw::JsonResponse("{\"subject\":" + q(s) + ",\"data\":{" + out + "}}");
|
||||
});
|
||||
router.post("/audit/subject/erase", "audit-subject-erase",
|
||||
[hub, env, erase_view](Request req) -> Response {
|
||||
FormView v = erase_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"subject", fw::FieldType::Email, true, 3, 120, 0, 0, false, ""},
|
||||
{"confirm", fw::FieldType::String, true, 1, 8, 0, 0, false, ""}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
if (c["confirm"] != "yes") throw fw::ValidationError({{"confirm", "type yes to confirm"}});
|
||||
std::size_t n = hub->subjects.erase(c["subject"]);
|
||||
hub->chain.append("system", "erasure", fw::sha256_hex(c["subject"]).substr(0, 16),
|
||||
std::to_string(n) + " rows removed");
|
||||
return form_ok(env, req, v, std::to_string(n) + " rows erased.",
|
||||
"{\"ok\":true,\"erased\":" + std::to_string(n) + "}");
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
services.add_feature("Hash-chained audit log", "/audit/log");
|
||||
services.add_feature("Audit tamper detection", "/audit/verify");
|
||||
services.add_feature("PII masking and redaction", "/audit/mask");
|
||||
services.add_feature("Retention and legal hold", "/audit/retention");
|
||||
services.add_feature("Data subject export and erasure", "/audit/subject");
|
||||
}
|
||||
|
||||
// ---- governance ------------------------------------------------------------
|
||||
void register_governance(fw::Router& router, Services& services, const HubPtr& hub,
|
||||
fw::Environment* env) {
|
||||
auto key_view = [] {
|
||||
FormView v;
|
||||
v.title = "Issue an API key";
|
||||
v.action = "/governance/keys";
|
||||
v.submit = "Issue";
|
||||
v.fields = {{"owner", "Owner", "text", ""},
|
||||
{"tier", "Tier", "text", "free or pro"},
|
||||
{"scopes", "Scopes", "text", "comma separated, e.g. read,write"}};
|
||||
return v;
|
||||
};
|
||||
router.get("/governance/keys", "governance-keys-form", [env, key_view](Request) {
|
||||
FormView v = key_view();
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.post("/governance/keys", "governance-keys", [hub, env, key_view](Request req) -> Response {
|
||||
FormView v = key_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"owner", fw::FieldType::String, true, 1, 60, 0, 0, false, ""},
|
||||
{"tier", fw::FieldType::String, false, 0, 8, 0, 0, false, "free"},
|
||||
{"scopes", fw::FieldType::String, false, 0, 100, 0, 0, false, "read"}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
if (c["tier"] != "free" && c["tier"] != "pro")
|
||||
throw fw::ValidationError({{"tier", "must be free or pro"}});
|
||||
std::set<std::string> scopes;
|
||||
std::stringstream ss(c["scopes"]);
|
||||
for (std::string s; std::getline(ss, s, ',');)
|
||||
if (!s.empty()) scopes.insert(s);
|
||||
std::string id;
|
||||
std::string key = hub->keys.issue(c["owner"], c["tier"], scopes, &id);
|
||||
if (key.empty()) throw fw::ValidationError({{"owner", "key cap reached (64)"}});
|
||||
return form_ok(env, req, v, "Key " + id + ": " + key + " (shown once)",
|
||||
"{\"id\":" + q(id) + ",\"key\":" + q(key) + "}", 201);
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
router.post("/governance/keys/{id}/revoke", "governance-keys-revoke", [hub](Request req) -> Response {
|
||||
if (!hub->keys.revoke(req.param_or("id", "")))
|
||||
return fw::problem_response(404, "No such key", req.param_or("id", ""), req.path);
|
||||
return fw::JsonResponse("{\"revoked\":true}");
|
||||
});
|
||||
|
||||
router.get("/governance/whoami", "governance-whoami", [hub](Request req) -> Response {
|
||||
const fw::ApiKeyInfo* info = nullptr;
|
||||
switch (hub->keys.authenticate(req.headers.get("X-API-Key"), "read", &info)) {
|
||||
case fw::KeyResult::Ok: break;
|
||||
case fw::KeyResult::Missing:
|
||||
return fw::problem_response(401, "Missing key", "send X-API-Key", req.path);
|
||||
case fw::KeyResult::Unknown:
|
||||
return fw::problem_response(401, "Unknown key", "key not recognised", req.path);
|
||||
case fw::KeyResult::Revoked:
|
||||
return fw::problem_response(401, "Revoked key", "key was revoked", req.path);
|
||||
case fw::KeyResult::Forbidden:
|
||||
return fw::problem_response(403, "Missing scope", "scope read required", req.path);
|
||||
}
|
||||
fw::TierPolicy tier = fw::TierTable::find(info->tier);
|
||||
bool ok = hub->ledger.charge(info->id, tier);
|
||||
Response r = ok ? fw::JsonResponse("{\"id\":" + q(info->id) + ",\"owner\":" + q(info->owner) +
|
||||
",\"tier\":" + q(tier.name) + "}")
|
||||
: fw::problem_response(429, "Rate limit exceeded", "tier " + tier.name, req.path);
|
||||
hub->ledger.headers(info->id, tier, r.headers);
|
||||
return r;
|
||||
});
|
||||
router.get("/governance/tiers", "governance-tiers", [](Request) {
|
||||
auto t = [](const char* n) {
|
||||
auto p = fw::TierTable::find(n);
|
||||
return "{\"tier\":" + q(p.name) + ",\"per_min\":" + std::to_string(p.per_min) + "}";
|
||||
};
|
||||
return fw::JsonResponse("{\"tiers\":[" + t("free") + "," + t("pro") + "]}");
|
||||
});
|
||||
|
||||
auto item = [hub](const char* ver) {
|
||||
return [hub, ver](Request) {
|
||||
Response r = fw::JsonResponse(std::string("{\"version\":\"") + ver + "\",\"items\":[1,2,3]}");
|
||||
hub->versions.annotate(ver, r.headers);
|
||||
return r;
|
||||
};
|
||||
};
|
||||
router.get("/v1/items", "v1-items", item("v1"));
|
||||
router.get("/v2/items", "v2-items", item("v2"));
|
||||
router.get("/governance/versions", "governance-versions", [hub](Request) {
|
||||
std::string out;
|
||||
for (const auto& v : hub->versions.all())
|
||||
out += std::string(out.empty() ? "" : ",") + "{\"version\":" + q(v.name) +
|
||||
",\"deprecated\":" + (v.deprecated ? "true" : "false") +
|
||||
",\"sunset\":" + q(v.sunset) + "}";
|
||||
return fw::JsonResponse("{\"versions\":[" + out + "]}");
|
||||
});
|
||||
|
||||
auto lint_view = [] {
|
||||
FormView v;
|
||||
v.title = "Route linter";
|
||||
v.action = "/governance/lint";
|
||||
v.submit = "Lint";
|
||||
v.fields = {{"paths", "Paths", "textarea", "one path per line, max 100"}};
|
||||
return v;
|
||||
};
|
||||
router.get("/governance/lint", "governance-lint-form", [env, lint_view](Request) {
|
||||
FormView v = lint_view();
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.post("/governance/lint", "governance-lint", [env, lint_view](Request req) -> Response {
|
||||
FormView v = lint_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"paths", fw::FieldType::String, true, 1, 4000, 0, 0, false, ""}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
std::vector<std::string> paths;
|
||||
std::stringstream ss(c["paths"]);
|
||||
for (std::string s; std::getline(ss, s);) {
|
||||
while (!s.empty() && (s.back() == '\r' || s.back() == ' ')) s.pop_back();
|
||||
if (!s.empty()) paths.push_back(s);
|
||||
}
|
||||
auto findings = fw::RouteLinter::lint(paths);
|
||||
std::string out, text;
|
||||
for (const auto& f : findings) {
|
||||
out += std::string(out.empty() ? "" : ",") + "{\"path\":" + q(f.path) + ",\"rule\":" + q(f.rule) + "}";
|
||||
text += f.path + " " + f.rule + "; ";
|
||||
}
|
||||
return form_ok(env, req, v, findings.empty() ? "No findings." : text,
|
||||
"{\"findings\":[" + out + "]}");
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
auto diff_view = [] {
|
||||
FormView v;
|
||||
v.title = "Spec differ";
|
||||
v.action = "/governance/diff";
|
||||
v.submit = "Compare";
|
||||
v.fields = {{"before", "Before", "textarea", "METHOD /path required=a,b optional=c"},
|
||||
{"after", "After", "textarea", ""}};
|
||||
return v;
|
||||
};
|
||||
router.get("/governance/diff", "governance-diff-form", [env, diff_view](Request) {
|
||||
FormView v = diff_view();
|
||||
return form_page(env, v);
|
||||
});
|
||||
router.post("/governance/diff", "governance-diff", [env, diff_view](Request req) -> Response {
|
||||
FormView v = diff_view();
|
||||
auto in = input(req);
|
||||
fw::Model m({{"before", fw::FieldType::String, true, 1, 8000, 0, 0, false, ""},
|
||||
{"after", fw::FieldType::String, true, 1, 8000, 0, 0, false, ""}});
|
||||
try {
|
||||
auto c = m.validate(in);
|
||||
auto findings = fw::SpecDiffer::diff(c["before"], c["after"]);
|
||||
std::string out, text;
|
||||
std::size_t breaking = 0;
|
||||
for (const auto& f : findings) {
|
||||
if (f.kind == "breaking") ++breaking;
|
||||
out += std::string(out.empty() ? "" : ",") + "{\"kind\":" + q(f.kind) +
|
||||
",\"operation\":" + q(f.operation) + ",\"detail\":" + q(f.detail) + "}";
|
||||
text += f.kind + ": " + f.operation + " " + f.detail + "; ";
|
||||
}
|
||||
return form_ok(env, req, v, findings.empty() ? "No changes." : text,
|
||||
"{\"breaking\":" + std::to_string(breaking) + ",\"findings\":[" + out + "]}");
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return form_fail(env, req, v, e, in);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/governance/problem", "governance-problem", [](Request) {
|
||||
return fw::JsonResponse("{\"try\":\"/governance/problem/404\",\"format\":\"RFC 7807\"}");
|
||||
});
|
||||
router.get("/governance/problem/{status}", "governance-problem-status", [](Request req) -> Response {
|
||||
std::string s = req.param_or("status", "");
|
||||
if (s.size() != 3 || s.find_first_not_of("0123456789") != std::string::npos ||
|
||||
std::stoi(s) < 400 || std::stoi(s) > 599)
|
||||
return fw::problem_response(400, "Bad status", "status must be 400-599", req.path);
|
||||
int st = std::stoi(s);
|
||||
return fw::problem_response(st, fw::status_text(st), "Example problem for " + s, req.path);
|
||||
});
|
||||
|
||||
services.add_feature("API keys with scopes", "/governance/keys");
|
||||
services.add_feature("Tiers and rate limit headers", "/governance/tiers");
|
||||
services.add_feature("API versions (Deprecation, Sunset)", "/v1/items");
|
||||
services.add_feature("API version list", "/governance/versions");
|
||||
services.add_feature("Route linter", "/governance/lint");
|
||||
services.add_feature("OpenAPI spec differ", "/governance/diff");
|
||||
services.add_feature("RFC 7807 problem+json", "/governance/problem");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_enterprise_demo(fw::Router& router, Services& services) {
|
||||
auto hub = std::make_shared<Hub>();
|
||||
fw::Environment* env = services.templates.get();
|
||||
env->add_template("ent_page.html",
|
||||
"{% extends \"base.html\" %}{% block content %}<h1>{{ heading }}</h1>"
|
||||
"{{ body|safe }}{% endblock %}");
|
||||
register_tenancy(router, services, hub, env);
|
||||
register_audit(router, services, hub, env);
|
||||
register_governance(router, services, hub, env);
|
||||
}
|
||||
|
||||
} // namespace molo::example::app
|
||||
@@ -10,8 +10,8 @@ namespace {
|
||||
|
||||
const char* kFeatures[][2] = {
|
||||
{"routing", "/routing/hello/world"},
|
||||
{"views", "/views/greet"},
|
||||
{"routers", "/routers/nested/deep"},
|
||||
{"views", "/routing/views/greet"},
|
||||
{"routers", "/routing/routers/nested/deep"},
|
||||
{"chaining", "/app1/app1/app1/whoami"},
|
||||
{"orm-sqlite", "/orm/users?backend=sqlite"},
|
||||
{"orm-postgres", "/orm/users?backend=postgres"},
|
||||
@@ -50,9 +50,10 @@ const char* kFeatures[][2] = {
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_index(fw::Router& router, Services& services) {
|
||||
fw::Environment* env = services.templates.get();
|
||||
router.get("/", "index", [env](fw::Request req) {
|
||||
void register_index(fw::Router& router, Services& services_ref) {
|
||||
fw::Environment* env = services_ref.templates.get();
|
||||
Services* services = &services_ref;
|
||||
router.get("/", "index", [env, services](fw::Request req) {
|
||||
fw::TemplateCtx ctx;
|
||||
ctx["title"] = std::string("MoloApp living example");
|
||||
ctx["show_matrix"] = std::string("true");
|
||||
@@ -60,6 +61,9 @@ void register_index(fw::Router& router, Services& services) {
|
||||
for (const auto& [feature, route] : kFeatures) {
|
||||
rows.push_back({{"feature", feature}, {"route", route}});
|
||||
}
|
||||
for (const auto& [feature, route] : services->features) {
|
||||
rows.push_back({{"feature", feature}, {"route", route}});
|
||||
}
|
||||
ctx["matrix"] = rows;
|
||||
(void)req;
|
||||
return fw::Response(200, env->render("index.html", ctx),
|
||||
|
||||
@@ -186,6 +186,13 @@ void register_ops_demo(fw::Router& router, Services& services) {
|
||||
return fw::JsonResponse(body, 200);
|
||||
});
|
||||
|
||||
router.get("/workflow/release", "workflow-usage", [](fw::Request req) {
|
||||
(void)req;
|
||||
return fw::JsonResponse(
|
||||
"{\"usage\":\"POST commits=feat: add x|fix: y (Conventional "
|
||||
"Commits separated by |)\",\"base_version\":\"0.1.0\"}",
|
||||
200);
|
||||
});
|
||||
router.post("/workflow/release", "workflow", [](fw::Request req) {
|
||||
auto input = fw::parse_json_object_flat(req.body);
|
||||
if (input.empty()) input = fw::parse_form(req.body);
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "App.hpp"
|
||||
#include "FormUi.hpp"
|
||||
#include "../fw/Cookies.hpp"
|
||||
#include "../fw/Platform.hpp"
|
||||
#include "../fw/Router.hpp"
|
||||
#include "../fw/Templates.hpp"
|
||||
#include "../fw/Validate.hpp"
|
||||
|
||||
namespace molo::example::app {
|
||||
|
||||
namespace {
|
||||
|
||||
namespace pc = fw::platform_caps;
|
||||
|
||||
std::string esc(const std::string& s) { return fw::html_escape(s); }
|
||||
|
||||
bool parse_long_in(const std::string& s, long lo, long hi, long& out) {
|
||||
if (s.empty() || s.size() > 12) return false;
|
||||
std::size_t i = (s[0] == '-') ? 1 : 0;
|
||||
if (i == s.size()) return false;
|
||||
for (std::size_t k = i; k < s.size(); ++k)
|
||||
if (s[k] < '0' || s[k] > '9') return false;
|
||||
out = std::atol(s.c_str());
|
||||
return out >= lo && out <= hi;
|
||||
}
|
||||
|
||||
// All state of this feature group lives here, shared by the route lambdas.
|
||||
class PlatformDemo {
|
||||
public:
|
||||
PlatformDemo(Services& services)
|
||||
: env_(services.templates.get()),
|
||||
prom_(services.metrics.get(), services.stats.get()) {
|
||||
env_->add_template(
|
||||
"platform_page.html",
|
||||
"{% extends \"base.html\" %}{% block content %}<h1>{{ title }}</h1>"
|
||||
"{{ body|safe }}{% endblock %}");
|
||||
seed_catalog();
|
||||
for (const char* t : {"templates", "embedded-assets", "seed-data"})
|
||||
health_.add_startup_task(t, true);
|
||||
for (const char* c : {"database", "cache", "workers"})
|
||||
health_.add_check(c, true);
|
||||
seed_di();
|
||||
logs_.log(fw::LogLevel::Info, "platform demo ready", "boot");
|
||||
doc_ = "Conditional GET demo document.\n0123456789abcdefghijklmnopqrstuvwxyz\n";
|
||||
}
|
||||
|
||||
void mount(fw::Router& r);
|
||||
|
||||
private:
|
||||
fw::Response page(const std::string& title, const std::string& body,
|
||||
int status = 200) const {
|
||||
fw::TemplateCtx ctx;
|
||||
ctx["title"] = title;
|
||||
ctx["body"] = body;
|
||||
return fw::Response(status, env_->render("platform_page.html", ctx),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
fw::Response form_page(const FormView& v, int status = 200) const {
|
||||
return fw::Response(status, env_->render("form_page.html", v.ctx()),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
static fw::Response json(const std::string& body, int status = 200) {
|
||||
fw::Response r(status, body, "application/json");
|
||||
r.headers.set("Cache-Control", "no-store");
|
||||
return r;
|
||||
}
|
||||
static fw::Response see_other(const std::string& to) {
|
||||
fw::Response r(303, "", "text/plain; charset=utf-8");
|
||||
r.headers.set("Location", to);
|
||||
return r;
|
||||
}
|
||||
fw::Response invalid(const FormView& base, const fw::Request& req,
|
||||
const fw::ValidationError& e) const {
|
||||
if (!wants_html(req)) return json(e.to_json(), 422);
|
||||
FormView v = base;
|
||||
v.values = fw::parse_form(req.body);
|
||||
v.error = &e;
|
||||
return form_page(v, 422);
|
||||
}
|
||||
static std::string corr(const fw::Request& req) {
|
||||
std::string c = req.headers.get("X-Correlation-ID");
|
||||
return c.empty() ? req.correlation_id : c;
|
||||
}
|
||||
|
||||
void seed_catalog();
|
||||
void seed_di();
|
||||
void mount_i18n(fw::Router& r);
|
||||
void mount_http(fw::Router& r);
|
||||
void mount_ops(fw::Router& r);
|
||||
void mount_observability(fw::Router& r);
|
||||
void mount_app(fw::Router& r);
|
||||
void mount_expose(fw::Router& r);
|
||||
|
||||
fw::Environment* env_;
|
||||
fw::MessageCatalog catalog_;
|
||||
fw::HealthRegistry health_;
|
||||
fw::PrometheusExporter prom_;
|
||||
fw::LogRing logs_;
|
||||
fw::TraceContextFactory trace_;
|
||||
fw::ServiceRegistry di_;
|
||||
fw::ExposeStats expose_;
|
||||
std::mutex doc_mu_;
|
||||
std::string doc_;
|
||||
std::shared_ptr<unsigned long> instance_counter_ =
|
||||
std::make_shared<unsigned long>(0);
|
||||
};
|
||||
|
||||
void PlatformDemo::seed_catalog() {
|
||||
catalog_.add("en", "welcome", {"Welcome"});
|
||||
catalog_.add("en", "items", {"%d item", "%d items"});
|
||||
catalog_.add("nl", "welcome", {"Welkom"});
|
||||
catalog_.add("nl", "items", {"%d item", "%d items"});
|
||||
catalog_.add("de", "welcome", {"Willkommen"});
|
||||
catalog_.add("de", "items", {"%d Artikel", "%d Artikel"});
|
||||
catalog_.add("fr", "welcome", {"Bienvenue"});
|
||||
catalog_.add("fr", "items", {"%d article", "%d articles"});
|
||||
catalog_.add("ru", "welcome", {"Добро пожаловать"});
|
||||
catalog_.add("ru", "items", {"%d предмет", "%d предмета", "%d предметов"});
|
||||
catalog_.add("ja", "welcome", {"ようこそ"});
|
||||
catalog_.add("ja", "items", {"%d 個"});
|
||||
}
|
||||
|
||||
void PlatformDemo::seed_di() {
|
||||
auto counter = instance_counter_;
|
||||
auto make = [counter](std::string prefix) {
|
||||
return [counter, prefix]() { return prefix + "#" + std::to_string(++*counter); };
|
||||
};
|
||||
di_.add("config", fw::Lifetime::Singleton, make("Config"));
|
||||
di_.add("logger", fw::Lifetime::Singleton, make("Logger"));
|
||||
di_.add("request-context", fw::Lifetime::Scoped, make("RequestContext"));
|
||||
di_.add("mailer", fw::Lifetime::Transient, make("Mailer"));
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_i18n(fw::Router& r) {
|
||||
r.get("/i18n", "i18n-page", [this](fw::Request req) {
|
||||
std::string lang_param = req.query_or("lang", "");
|
||||
std::string accept = req.headers.get("Accept-Language");
|
||||
std::string locale = fw::negotiate_locale(lang_param, accept, catalog_);
|
||||
std::string source = catalog_.has_locale(fw::negotiate_locale(lang_param, "", catalog_)) &&
|
||||
!lang_param.empty() &&
|
||||
fw::negotiate_locale(lang_param, "", catalog_) == locale
|
||||
? "?lang parameter"
|
||||
: (locale != catalog_.default_locale() ? "Accept-Language header"
|
||||
: "default");
|
||||
std::string n_text = req.query_or("n", "3");
|
||||
long n = 0;
|
||||
std::string n_error;
|
||||
if (!parse_long_in(n_text, 0, pc::kMaxPluralN, n))
|
||||
n_error = "must be a whole number from 0 to " + std::to_string(pc::kMaxPluralN);
|
||||
std::string body = "<p>Active locale: <strong>" + esc(locale) +
|
||||
"</strong> <span class=\"hint\">(from " + source + ")</span></p>";
|
||||
body += "<form method=\"get\" action=\"/i18n\"><div class=\"field\">"
|
||||
"<label for=\"f-lang\">Language</label><select id=\"f-lang\" name=\"lang\">";
|
||||
for (const auto& l : catalog_.locales())
|
||||
body += "<option value=\"" + l + "\"" + (l == locale ? " selected" : "") +
|
||||
">" + l + "</option>";
|
||||
body += "</select></div><div class=\"field" + std::string(n_error.empty() ? "" : " invalid") +
|
||||
"\"><label for=\"f-n\">Count</label><input id=\"f-n\" type=\"number\" name=\"n\" value=\"" +
|
||||
esc(n_text) + "\">";
|
||||
if (!n_error.empty())
|
||||
body += "<p class=\"field-error\" id=\"e-n\">" + esc(n_error) + "</p>";
|
||||
body += "</div><button type=\"submit\">Translate</button></form>";
|
||||
if (n_error.empty()) {
|
||||
body += "<h2>" + esc(catalog_.translate(locale, "welcome")) + "</h2>";
|
||||
body += "<p id=\"plural\">" + esc(catalog_.translate(locale, "items", n)) + "</p>";
|
||||
body += "<p class=\"hint\">Plural form " +
|
||||
std::to_string(fw::PluralRule::index(locale, n)) + " of " +
|
||||
std::to_string(fw::PluralRule::forms(locale)) + ".</p>";
|
||||
}
|
||||
body += "<p>Switch: ";
|
||||
for (const auto& l : catalog_.locales())
|
||||
body += "<a href=\"/i18n?lang=" + l + "&n=" + (n_error.empty() ? std::to_string(n) : "3") +
|
||||
"\">" + l + "</a> ";
|
||||
body += "</p><p><a href=\"/i18n/po?lang=" + locale + "\">catalog as .po</a></p>";
|
||||
fw::Response res = page("Internationalisation", body, n_error.empty() ? 200 : 422);
|
||||
res.headers.set("Content-Language", locale);
|
||||
res.headers.set("Vary", "Accept-Language");
|
||||
return res;
|
||||
});
|
||||
|
||||
r.get("/i18n/po", "i18n-po", [this](fw::Request req) {
|
||||
std::string locale = req.query_or("lang", "en");
|
||||
if (!catalog_.has_locale(locale))
|
||||
return fw::Response(404, "unknown locale\n", "text/plain; charset=utf-8");
|
||||
return fw::Response(200, catalog_.to_po(locale), "text/plain; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_http(fw::Router& r) {
|
||||
r.get("/compress/demo", "compress-demo", [](fw::Request req) {
|
||||
long size = 2000;
|
||||
if (req.query.count("size") &&
|
||||
!parse_long_in(req.query_or("size", ""), 0, (long)pc::kMaxCompressBody, size))
|
||||
return fw::Response(422, "size must be 0 to " + std::to_string(pc::kMaxCompressBody) + "\n",
|
||||
"text/plain; charset=utf-8");
|
||||
std::string body;
|
||||
const std::string unit = "MoloApp compresses repetitive text well. ";
|
||||
while ((long)body.size() < size) body += unit;
|
||||
body.resize((std::size_t)size);
|
||||
fw::Response res(200, body, "text/plain; charset=utf-8");
|
||||
res.headers.set("Vary", "Accept-Encoding");
|
||||
res.headers.set("X-Original-Length", std::to_string(body.size()));
|
||||
if (body.size() >= pc::kCompressMin &&
|
||||
fw::accepts_encoding(req.headers.get("Accept-Encoding"), "gzip")) {
|
||||
res.body = fw::gzip_stored(body);
|
||||
res.headers.set("Content-Encoding", "gzip");
|
||||
}
|
||||
return res;
|
||||
});
|
||||
|
||||
r.get("/conditional/doc", "conditional-get", [this](fw::Request req) {
|
||||
std::string doc;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(doc_mu_);
|
||||
doc = doc_;
|
||||
}
|
||||
std::string etag = fw::make_etag(doc);
|
||||
fw::Response res(200, doc, "text/plain; charset=utf-8");
|
||||
res.headers.set("ETag", etag);
|
||||
res.headers.set("Accept-Ranges", "bytes");
|
||||
res.headers.set("Cache-Control", "no-cache");
|
||||
if (fw::etag_matches(req.headers.get("If-None-Match"), etag)) {
|
||||
res.status = 304;
|
||||
res.body.clear();
|
||||
return res;
|
||||
}
|
||||
fw::ByteRange range = fw::parse_range(req.headers.get("Range"), doc.size());
|
||||
if (range.kind == fw::ByteRange::Kind::Unsatisfiable) {
|
||||
res.status = 416;
|
||||
res.body.clear();
|
||||
res.headers.set("Content-Range", "bytes */" + std::to_string(doc.size()));
|
||||
} else if (range.kind == fw::ByteRange::Kind::Ok) {
|
||||
res.status = 206;
|
||||
res.body = doc.substr(range.first, range.last - range.first + 1);
|
||||
res.headers.set("Content-Range", "bytes " + std::to_string(range.first) + "-" +
|
||||
std::to_string(range.last) + "/" +
|
||||
std::to_string(doc.size()));
|
||||
}
|
||||
return res;
|
||||
});
|
||||
|
||||
r.post("/conditional/doc", "conditional-put", [this](fw::Request req) {
|
||||
if (req.body.size() > pc::kMaxDocBytes)
|
||||
return json("{\"error\":\"too_large\",\"max\":" + std::to_string(pc::kMaxDocBytes) + "}", 413);
|
||||
if (req.body.empty())
|
||||
return json("{\"error\":\"validation\",\"message\":\"body is required\"}", 422);
|
||||
std::lock_guard<std::mutex> lock(doc_mu_);
|
||||
std::string match = req.headers.get("If-Match");
|
||||
if (!match.empty() && !fw::etag_matches(match, fw::make_etag(doc_)))
|
||||
return json("{\"error\":\"precondition_failed\",\"etag\":\"" +
|
||||
fw::json_escape(fw::make_etag(doc_)) + "\"}", 412);
|
||||
doc_ = req.body;
|
||||
fw::Response res = json("{\"bytes\":" + std::to_string(doc_.size()) + "}");
|
||||
res.headers.set("ETag", fw::make_etag(doc_));
|
||||
return res;
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_ops(fw::Router& r) {
|
||||
r.get("/healthz", "healthz", [this](fw::Request) { return json(health_.liveness_json()); });
|
||||
r.get("/readyz", "readyz", [this](fw::Request) {
|
||||
return json(health_.readiness_json(), health_.ready() ? 200 : 503);
|
||||
});
|
||||
r.get("/startupz", "startupz", [this](fw::Request) {
|
||||
return json(health_.startup_json(), health_.startup_complete() ? 200 : 503);
|
||||
});
|
||||
r.post("/readyz/checks/{name}", "readyz-toggle", [this](fw::Request req) {
|
||||
std::string state = req.query_or("state", "");
|
||||
if (state != "up" && state != "down")
|
||||
return json("{\"error\":\"validation\",\"message\":\"state must be up or down\"}", 422);
|
||||
if (!health_.set_check(req.param_or("name", ""), state == "up"))
|
||||
return json("{\"error\":\"not_found\",\"message\":\"unknown check\"}", 404);
|
||||
return json(health_.readiness_json(), health_.ready() ? 200 : 503);
|
||||
});
|
||||
r.post("/startupz/tasks/{name}", "startupz-toggle", [this](fw::Request req) {
|
||||
std::string state = req.query_or("state", "");
|
||||
if (state != "done" && state != "pending")
|
||||
return json("{\"error\":\"validation\",\"message\":\"state must be done or pending\"}", 422);
|
||||
if (!health_.set_startup_task(req.param_or("name", ""), state == "done"))
|
||||
return json("{\"error\":\"not_found\",\"message\":\"unknown task\"}", 404);
|
||||
return json(health_.startup_json(), health_.startup_complete() ? 200 : 503);
|
||||
});
|
||||
r.get("/metrics", "prometheus", [this](fw::Request) {
|
||||
return fw::Response(200, prom_.render(), "text/plain; version=0.0.4; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_observability(fw::Router& r) {
|
||||
auto emit_view = []() {
|
||||
FormView v;
|
||||
v.title = "Write a log record";
|
||||
v.action = "/logging/emit";
|
||||
v.submit = "Log";
|
||||
v.fields = {{"level", "Level", "text", "debug, info, warn or error"},
|
||||
{"message", "Message", "text", "secrets like password=x are redacted"}};
|
||||
return v;
|
||||
};
|
||||
r.get("/logging/emit", "logging-form", [this, emit_view](fw::Request) {
|
||||
return form_page(emit_view());
|
||||
});
|
||||
r.post("/logging/emit", "logging-emit", [this, emit_view](fw::Request req) {
|
||||
auto input = fw::parse_form(req.body);
|
||||
if (req.headers.get("Content-Type").find("application/json") != std::string::npos)
|
||||
input = fw::parse_json_object_flat(req.body);
|
||||
std::vector<fw::FieldError> fails;
|
||||
fw::LogLevel level = fw::LogLevel::Info;
|
||||
if (input["level"].empty()) fails.push_back({"level", "is required"});
|
||||
else if (!fw::parse_level(input["level"], level))
|
||||
fails.push_back({"level", "must be debug, info, warn or error"});
|
||||
if (input["message"].empty()) fails.push_back({"message", "is required"});
|
||||
else if (input["message"].size() > 300)
|
||||
fails.push_back({"message", "must be at most 300 characters"});
|
||||
if (!fails.empty()) return invalid(emit_view(), req, fw::ValidationError(fails));
|
||||
logs_.log(level, input["message"], corr(req));
|
||||
if (!wants_html(req)) return json("{\"ok\":true,\"size\":" + std::to_string(logs_.size()) + "}");
|
||||
return see_other("/logging/records");
|
||||
});
|
||||
r.get("/logging/records", "logging-records", [this](fw::Request req) {
|
||||
long n = 20;
|
||||
fw::LogLevel min = fw::LogLevel::Debug;
|
||||
if (req.query.count("n") && !parse_long_in(req.query_or("n", ""), 1, 100, n))
|
||||
return page("Log records", "<p class=\"error\">n must be a whole number from 1 to 100</p>", 422);
|
||||
if (req.query.count("level") && !fw::parse_level(req.query_or("level", ""), min))
|
||||
return page("Log records", "<p class=\"error\">level must be debug, info, warn or error</p>", 422);
|
||||
auto recs = logs_.last((std::size_t)n, min);
|
||||
if (req.query_or("format", "") == "json") {
|
||||
std::string out;
|
||||
for (const auto& rec : recs) out += fw::LogRing::to_json(rec) + "\n";
|
||||
return fw::Response(200, out, "application/x-ndjson");
|
||||
}
|
||||
std::string body = "<p class=\"hint\">Ring keeps the last " + std::to_string(pc::kLogRing) +
|
||||
" records (now " + std::to_string(logs_.size()) + "). Showing " +
|
||||
std::to_string(recs.size()) + ". <a href=\"/logging/emit\">Write one</a>, "
|
||||
"<a href=\"/logging/records?format=json\">JSON lines</a>.</p>"
|
||||
"<div class=\"scroll\"><table><thead><tr><th>#</th><th>Level</th>"
|
||||
"<th>Message</th><th>Correlation</th></tr></thead><tbody>";
|
||||
for (const auto& rec : recs)
|
||||
body += "<tr><td>" + std::to_string(rec.seq) + "</td><td>" + fw::level_name(rec.level) +
|
||||
"</td><td>" + esc(rec.message) + "</td><td>" + esc(rec.correlation_id) + "</td></tr>";
|
||||
body += "</tbody></table></div>";
|
||||
return page("Log records", body);
|
||||
});
|
||||
|
||||
r.get("/context/trace", "context-trace", [this](fw::Request req) {
|
||||
fw::TraceContext ctx = trace_.from_header(req.headers.get("traceparent"));
|
||||
std::string cid = corr(req);
|
||||
std::string out = "{\"correlation_id\":\"" + fw::json_escape(cid) +
|
||||
"\",\"continued\":" + (ctx.parent_span_id.empty() ? "false" : "true") +
|
||||
",\"parent_valid\":" + (ctx.parent_valid ? "true" : "false") +
|
||||
",\"trace_id\":\"" + ctx.trace_id + "\",\"parent_span_id\":\"" +
|
||||
ctx.parent_span_id + "\",\"span_id\":\"" + ctx.span_id +
|
||||
"\",\"traceparent\":\"" + ctx.traceparent() + "\"}";
|
||||
fw::Response res = json(out);
|
||||
res.headers.set("traceparent", ctx.traceparent());
|
||||
res.headers.set("X-Correlation-ID", cid);
|
||||
return res;
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_app(fw::Router& r) {
|
||||
r.get("/di/services", "di-services", [this](fw::Request) {
|
||||
std::string body = "<div class=\"scroll\"><table><thead><tr><th>Service</th><th>Lifetime</th>"
|
||||
"<th>Created</th><th>Resolved</th></tr></thead><tbody>";
|
||||
for (const auto& e : di_.list())
|
||||
body += "<tr><td><a href=\"/di/resolve/" + esc(e.name) + "\">" + esc(e.name) + "</a></td><td>" +
|
||||
fw::lifetime_name(e.lifetime) + "</td><td>" + std::to_string(e.created) +
|
||||
"</td><td>" + std::to_string(e.resolved) + "</td></tr>";
|
||||
body += "</tbody></table></div><p class=\"hint\">Singletons are built once, scoped once per "
|
||||
"?scope= key, transients on every resolve.</p>";
|
||||
return page("Dependency injection", body);
|
||||
});
|
||||
r.get("/di/resolve/{name}", "di-resolve", [this](fw::Request req) {
|
||||
std::string name = req.param_or("name", "");
|
||||
std::string instance;
|
||||
if (!di_.resolve(name, req.query_or("scope", "default"), instance))
|
||||
return json("{\"error\":\"not_found\",\"message\":\"unknown service\"}", 404);
|
||||
return json("{\"name\":\"" + fw::json_escape(name) + "\",\"instance\":\"" +
|
||||
fw::json_escape(instance) + "\"}");
|
||||
});
|
||||
|
||||
FormView flash_view;
|
||||
flash_view.title = "Set a flash message";
|
||||
flash_view.action = "/flash/set";
|
||||
flash_view.submit = "Save and redirect";
|
||||
flash_view.fields = {{"message", "Message", "text", "shown once on the next page"}};
|
||||
r.get("/flash/set", "flash-form", [this, flash_view](fw::Request) { return form_page(flash_view); });
|
||||
r.post("/flash/set", "flash-set", [this, flash_view](fw::Request req) {
|
||||
fw::Model model({{"message", fw::FieldType::String, true, 1, 120, 0, 0, false, ""}});
|
||||
std::map<std::string, std::string> clean;
|
||||
try {
|
||||
clean = fw::Form(model).bind(req);
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return invalid(flash_view, req, e);
|
||||
}
|
||||
std::string cookie = fw::make_set_cookie("flash", fw::FlashCodec::encode(clean["message"]),
|
||||
"/", true, false, "Lax", 60);
|
||||
fw::Response res = wants_html(req) ? see_other("/flash") : json("{\"ok\":true}");
|
||||
res.headers.set("Set-Cookie", cookie);
|
||||
return res;
|
||||
});
|
||||
r.get("/flash", "flash-show", [this](fw::Request req) {
|
||||
std::string msg;
|
||||
bool has = fw::FlashCodec::decode(req.cookie_or("flash", ""), msg);
|
||||
std::string body;
|
||||
if (has) body += "<p class=\"ok\" role=\"status\">" + esc(msg) + "</p>";
|
||||
else body += "<p class=\"hint\">No flash message. It is shown once after a POST.</p>";
|
||||
body += "<p><a href=\"/flash/set\">Set a message</a></p>";
|
||||
fw::Response res = page("Flash messages", body);
|
||||
if (has) res.headers.set("Set-Cookie", fw::make_set_cookie("flash", "", "/", true, false, "Lax", 0));
|
||||
return res;
|
||||
});
|
||||
|
||||
r.any({fw::Method::Get, fw::Method::Post}, "/middleware/demo", "middleware-demo",
|
||||
[this](fw::Request req) {
|
||||
std::vector<fw::Middleware> chain;
|
||||
chain.push_back([](fw::Request q, fw::Next next) { // secure headers
|
||||
fw::Response res = next(std::move(q));
|
||||
res.headers.set("X-Content-Type-Options", "nosniff");
|
||||
res.headers.set("X-Frame-Options", "DENY");
|
||||
res.headers.set("Referrer-Policy", "no-referrer");
|
||||
return res;
|
||||
});
|
||||
chain.push_back([](fw::Request q, fw::Next next) { // body limit
|
||||
if (q.body.size() > 64)
|
||||
return fw::Response(413, "{\"error\":\"too_large\",\"max\":64}", "application/json");
|
||||
return next(std::move(q));
|
||||
});
|
||||
chain.push_back([](fw::Request q, fw::Next next) { // timing
|
||||
auto t0 = std::chrono::steady_clock::now();
|
||||
fw::Response res = next(std::move(q));
|
||||
long us = (long)std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
res.headers.set("X-Response-Time-Us", std::to_string(us));
|
||||
return res;
|
||||
});
|
||||
fw::Next end = [this](fw::Request q) {
|
||||
return page("Middleware builtins",
|
||||
"<p>This response passed through three builtin middlewares: secure headers, "
|
||||
"body limit (64 bytes) and timing. Inspect the response headers.</p>"
|
||||
"<p class=\"hint\">Received " + std::to_string(q.body.size()) + " body bytes.</p>");
|
||||
};
|
||||
for (std::size_t i = chain.size(); i > 0; --i) {
|
||||
fw::Middleware mw = chain[i - 1];
|
||||
fw::Next inner = end;
|
||||
end = [mw, inner](fw::Request q) { return mw(std::move(q), inner); };
|
||||
}
|
||||
return end(std::move(req));
|
||||
});
|
||||
|
||||
r.get("/cli/commands", "cli-commands", [this](fw::Request req) {
|
||||
static const std::vector<std::pair<std::string, std::string>> cmds = {
|
||||
{"new", "Scaffold a project (Makefile, AGENTS.md, .env.json, assets, templates, locales, git init)."},
|
||||
{"serve", "Dev server; --reload watches and rebuilds."},
|
||||
{"build", "Build, optionally embedding assets first."},
|
||||
{"embed", "Turn a static dir into constexpr C++ arrays, optionally gzip."},
|
||||
{"migrate", "Preview (--check) or apply (--apply) database migrations."},
|
||||
{"health", "Local liveness and readiness summary."},
|
||||
{"supervisor", "start, stop, restart, status, logs."},
|
||||
{"task", "enqueue, retry, cancel, inspect on the background queue."},
|
||||
{"ai", "new and continue: the AI agent."},
|
||||
{"expose", "serve, agent, list, stats, expose-key: reverse tunnels."},
|
||||
{"verify", "Offline artifact verification."},
|
||||
{"supply-check", "Pin and advisory gate."},
|
||||
{"release", "Ordered release gate."},
|
||||
{"rollout", "Staged deploys."},
|
||||
{"rollback", "Revert a rollout."},
|
||||
{"experiment", "Chaos and experiments."},
|
||||
{"debug", "Debug helpers."}};
|
||||
if (!wants_html(req)) {
|
||||
std::string out = "{\"commands\":[";
|
||||
for (std::size_t i = 0; i < cmds.size(); ++i)
|
||||
out += std::string(i ? "," : "") + "{\"name\":\"" + cmds[i].first + "\",\"summary\":\"" +
|
||||
fw::json_escape(cmds[i].second) + "\"}";
|
||||
return json(out + "]}");
|
||||
}
|
||||
std::string body = "<p class=\"hint\">Run <code>molo help <command></code> for full help.</p>"
|
||||
"<div class=\"scroll\"><table><thead><tr><th>Command</th><th>What it does</th>"
|
||||
"</tr></thead><tbody>";
|
||||
for (const auto& [n, s] : cmds)
|
||||
body += "<tr><td><code>molo " + n + "</code></td><td>" + esc(s) + "</td></tr>";
|
||||
body += "</tbody></table></div>";
|
||||
return page("molo commands", body);
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount_expose(fw::Router& r) {
|
||||
FormView view;
|
||||
view.title = "Record a tunnel request";
|
||||
view.action = "/expose/record";
|
||||
view.submit = "Record";
|
||||
view.fields = {{"method", "Method", "text", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"},
|
||||
{"bytes_up", "Bytes up", "number", "0 to 1000000000"},
|
||||
{"bytes_down", "Bytes down", "number", "0 to 1000000000"},
|
||||
{"micros", "Latency (microseconds)", "number", "0 to 60000000"}};
|
||||
r.get("/expose/record", "expose-form", [this, view](fw::Request) { return form_page(view); });
|
||||
r.post("/expose/record", "expose-record", [this, view](fw::Request req) {
|
||||
fw::Model model(
|
||||
{{"method", fw::FieldType::String, true, 3, 7, 0, 0, false, ""},
|
||||
{"bytes_up", fw::FieldType::Integer, true, 0, 0, 0, 1000000000, true, ""},
|
||||
{"bytes_down", fw::FieldType::Integer, true, 0, 0, 0, 1000000000, true, ""},
|
||||
{"micros", fw::FieldType::Integer, true, 0, 0, 0, 60000000, true, ""}});
|
||||
std::map<std::string, std::string> c;
|
||||
try {
|
||||
c = fw::Form(model).bind(req);
|
||||
if (!fw::ExposeStats::known_method(c["method"]))
|
||||
throw fw::ValidationError({{"method", "must be an HTTP method in capitals"}});
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return invalid(view, req, e);
|
||||
}
|
||||
expose_.record(c["method"], std::stoul(c["bytes_up"]), std::stoul(c["bytes_down"]),
|
||||
std::stoul(c["micros"]));
|
||||
if (!wants_html(req)) return json("{\"ok\":true}");
|
||||
return see_other("/expose/stats");
|
||||
});
|
||||
r.get("/expose/stats", "expose-stats", [this](fw::Request req) {
|
||||
auto snap = expose_.snapshot();
|
||||
auto kb = [](unsigned long b) { char x[32]; std::snprintf(x, sizeof x, "%.1f", b / 1024.0); return std::string(x); };
|
||||
auto f2 = [](double v) { char x[32]; std::snprintf(x, sizeof x, "%.2f", v); return std::string(x); };
|
||||
if (!wants_html(req)) {
|
||||
std::string out = "{\"methods\":{";
|
||||
bool first = true;
|
||||
for (const auto& [m, row] : snap) {
|
||||
out += std::string(first ? "" : ",") + "\"" + m + "\":{\"count\":" + std::to_string(row.count) +
|
||||
",\"kb_up\":" + kb(row.bytes_up) + ",\"kb_down\":" + kb(row.bytes_down) +
|
||||
",\"kb_s_up\":" + f2(row.kb_s_up) + ",\"kb_s_down\":" + f2(row.kb_s_down) +
|
||||
",\"avg_ms\":" + f2(row.avg_ms()) + "}";
|
||||
first = false;
|
||||
}
|
||||
return json(out + "}}");
|
||||
}
|
||||
std::string body = "<p class=\"hint\">Mirror of <code>molo expose stats</code>. Rates are a "
|
||||
"60 second window. <a href=\"/expose/record\">Record a request</a>.</p>"
|
||||
"<div class=\"scroll\"><table><thead><tr><th>Method</th><th>Count</th>"
|
||||
"<th>kB up</th><th>kB down</th><th>kB/s up</th><th>kB/s down</th>"
|
||||
"<th>Avg ms</th></tr></thead><tbody>";
|
||||
for (const auto& [m, row] : snap)
|
||||
body += "<tr><td>" + m + "</td><td>" + std::to_string(row.count) + "</td><td>" + kb(row.bytes_up) +
|
||||
"</td><td>" + kb(row.bytes_down) + "</td><td>" + f2(row.kb_s_up) + "</td><td>" +
|
||||
f2(row.kb_s_down) + "</td><td>" + f2(row.avg_ms()) + "</td></tr>";
|
||||
body += "</tbody></table></div>";
|
||||
return page("Expose stats", body);
|
||||
});
|
||||
}
|
||||
|
||||
void PlatformDemo::mount(fw::Router& r) {
|
||||
mount_i18n(r);
|
||||
mount_http(r);
|
||||
mount_ops(r);
|
||||
mount_observability(r);
|
||||
mount_app(r);
|
||||
mount_expose(r);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_platform_demo(fw::Router& router, Services& services) {
|
||||
auto demo = std::make_shared<PlatformDemo>(services);
|
||||
// Routes capture the raw pointer; the router owner keeps `demo` alive by
|
||||
// holding it in a static-lifetime registry below (bounded: one per app).
|
||||
static std::vector<std::shared_ptr<PlatformDemo>> keep;
|
||||
if (keep.size() >= 64) throw std::runtime_error("platform demo instance cap");
|
||||
keep.push_back(demo);
|
||||
demo->mount(router);
|
||||
|
||||
services.add_feature("i18n", "/i18n");
|
||||
services.add_feature("gzip compression", "/compress/demo");
|
||||
services.add_feature("conditional GET and ranges", "/conditional/doc");
|
||||
services.add_feature("liveness probe", "/healthz");
|
||||
services.add_feature("readiness probe", "/readyz");
|
||||
services.add_feature("startup gate", "/startupz");
|
||||
services.add_feature("prometheus metrics", "/metrics");
|
||||
services.add_feature("structured logging", "/logging/records");
|
||||
services.add_feature("trace context", "/context/trace");
|
||||
services.add_feature("DI container", "/di/services");
|
||||
services.add_feature("flash messages", "/flash");
|
||||
services.add_feature("middleware builtins", "/middleware/demo");
|
||||
services.add_feature("expose stats", "/expose/stats");
|
||||
services.add_feature("CLI commands", "/cli/commands");
|
||||
}
|
||||
|
||||
} // namespace molo::example::app
|
||||
@@ -70,6 +70,11 @@ void register_realtime_demo(fw::Router& router, Services& services) {
|
||||
return fw::Response(207, webdav->propfind_xml("/files/"),
|
||||
"application/xml");
|
||||
});
|
||||
router.get("/webdav/files/", "webdav-index", [webdav](fw::Request req) {
|
||||
(void)req;
|
||||
return fw::Response(200, webdav->propfind_xml("/files/"),
|
||||
"application/xml");
|
||||
});
|
||||
router.any({fw::Method::Get}, "/webdav/files/{name}", "webdav-get",
|
||||
[webdav](fw::Request req) -> fw::Response {
|
||||
std::string content;
|
||||
|
||||
@@ -0,0 +1,621 @@
|
||||
#include "App.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "../fw/Resilience.hpp"
|
||||
#include "../fw/Router.hpp"
|
||||
#include "../fw/Templates.hpp"
|
||||
#include "../fw/Validate.hpp"
|
||||
#include "FormUi.hpp"
|
||||
|
||||
// Interactive lab pages for operability, supply chain, clients and data depth.
|
||||
// Each page is a LabPage: a GET that renders the lab state plus one POST route
|
||||
// per button. HTML clients get the page back, JSON clients get the lab state;
|
||||
// validation failures render the shared inline-error form (422).
|
||||
|
||||
namespace molo::example::app {
|
||||
|
||||
namespace {
|
||||
|
||||
using Params = std::map<std::string, std::string>;
|
||||
|
||||
const char kLabPage[] = R"LAB({% extends "base.html" %}
|
||||
{% block content %}
|
||||
<h1>{{ title }}</h1>
|
||||
<p class="hint">{{ intro }}</p>
|
||||
{% if notice %}<p class="ok" role="status">{{ notice }}</p>{% endif %}
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>State</th><th>Value</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in rows %}
|
||||
<tr><td>{{ r.k }}</td><td>{{ r.v }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
{% for a in actions %}
|
||||
{{ a.html|safe }}
|
||||
{% endfor %}
|
||||
<h2>Log</h2>
|
||||
<ul>
|
||||
{% for l in log %}
|
||||
<li>{{ l.line }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endblock %}
|
||||
)LAB";
|
||||
|
||||
// Throws the standard field error when `value` is not one of `allowed`.
|
||||
void require_in(const std::string& field, const std::string& value,
|
||||
const std::vector<std::string>& allowed) {
|
||||
if (std::find(allowed.begin(), allowed.end(), value) != allowed.end()) return;
|
||||
std::string list;
|
||||
for (const auto& a : allowed) list += (list.empty() ? "" : ", ") + a;
|
||||
throw fw::ValidationError({{field, "must be one of: " + list}});
|
||||
}
|
||||
|
||||
// One button (with its inputs) on a lab page and the handler behind it.
|
||||
class ActionSpec {
|
||||
public:
|
||||
ActionSpec(std::string sub, std::string label)
|
||||
: sub_(std::move(sub)), label_(std::move(label)) {}
|
||||
|
||||
ActionSpec& num(const std::string& name, const std::string& label, long lo,
|
||||
long hi, const std::string& def, const std::string& hint = "") {
|
||||
model_.push_back({name, fw::FieldType::Integer, false, 0, 1024, lo, hi,
|
||||
true, def});
|
||||
form_.push_back({name, label, "number",
|
||||
hint.empty() ? std::to_string(lo) + " to " + std::to_string(hi)
|
||||
: hint});
|
||||
defaults_[name] = def;
|
||||
return *this;
|
||||
}
|
||||
ActionSpec& text(const std::string& name, const std::string& label,
|
||||
std::size_t min, std::size_t max, const std::string& def,
|
||||
const std::string& hint = "", bool required = true) {
|
||||
model_.push_back({name, fw::FieldType::String, required, min, max, 0, 0,
|
||||
false, required ? "" : def});
|
||||
form_.push_back({name, label, "text", hint});
|
||||
defaults_[name] = def;
|
||||
return *this;
|
||||
}
|
||||
ActionSpec& run(std::function<std::string(const Params&)> fn) {
|
||||
run_ = std::move(fn);
|
||||
return *this;
|
||||
}
|
||||
ActionSpec& dynamic_defaults(std::function<Params()> fn) {
|
||||
dyn_ = std::move(fn);
|
||||
return *this;
|
||||
}
|
||||
|
||||
const std::string& sub() const { return sub_; }
|
||||
const std::string& label() const { return label_; }
|
||||
const std::vector<FormField>& form() const { return form_; }
|
||||
fw::Model model() const { return fw::Model(model_); }
|
||||
Params defaults() const {
|
||||
Params d = defaults_;
|
||||
if (dyn_)
|
||||
for (const auto& [k, v] : dyn_()) d[k] = v;
|
||||
return d;
|
||||
}
|
||||
std::string execute(const Params& p) const { return run_ ? run_(p) : ""; }
|
||||
|
||||
private:
|
||||
std::string sub_, label_;
|
||||
std::vector<fw::Field> model_;
|
||||
std::vector<FormField> form_;
|
||||
Params defaults_;
|
||||
std::function<Params()> dyn_;
|
||||
std::function<std::string(const Params&)> run_;
|
||||
};
|
||||
|
||||
class LabPage {
|
||||
public:
|
||||
LabPage(fw::Environment* env, std::string path, std::string title,
|
||||
std::string intro, std::shared_ptr<fw::Lab> lab)
|
||||
: env_(env),
|
||||
path_(std::move(path)),
|
||||
title_(std::move(title)),
|
||||
intro_(std::move(intro)),
|
||||
lab_(std::move(lab)) {}
|
||||
|
||||
ActionSpec& action(std::string sub, std::string label) {
|
||||
actions_.emplace_back(std::move(sub), std::move(label));
|
||||
return actions_.back();
|
||||
}
|
||||
void extra_rows(std::function<fw::LabRows()> fn) { extra_ = std::move(fn); }
|
||||
|
||||
fw::Response page(int status, const std::string& notice) const {
|
||||
fw::TemplateCtx ctx;
|
||||
ctx["title"] = title_;
|
||||
ctx["intro"] = intro_;
|
||||
ctx["notice"] = notice;
|
||||
fw::TemplateList rows, acts, log;
|
||||
fw::LabRows all = lab_->rows();
|
||||
if (extra_)
|
||||
for (auto& r : extra_()) all.push_back(std::move(r));
|
||||
for (const auto& [k, v] : all) rows.push_back({{"k", k}, {"v", v}});
|
||||
for (const auto& a : actions_) acts.push_back({{"html", action_html(a)}});
|
||||
for (const auto& l : lab_->log()) log.push_back({{"line", l}});
|
||||
ctx["rows"] = rows;
|
||||
ctx["actions"] = acts;
|
||||
ctx["log"] = log;
|
||||
return fw::Response(status, env_->render("lab_page.html", ctx),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
fw::Response invalid(const ActionSpec& a, const fw::Request& req,
|
||||
const fw::ValidationError& e) const {
|
||||
if (!wants_html(req)) return fw::JsonResponse(e.to_json(), 422);
|
||||
FormView v;
|
||||
v.title = a.label();
|
||||
v.action = path_ + a.sub();
|
||||
v.submit = a.label();
|
||||
v.fields = a.form();
|
||||
v.values = a.defaults();
|
||||
for (const auto& [k, val] : fw::parse_form(req.body)) v.values[k] = val;
|
||||
v.error = &e;
|
||||
return fw::Response(422, env_->render("form_page.html", v.ctx()),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
fw::Response handle(std::size_t i, const fw::Request& req) const {
|
||||
const ActionSpec& a = actions_[i];
|
||||
std::string notice;
|
||||
try {
|
||||
notice = a.execute(fw::Form(a.model()).bind(req));
|
||||
} catch (const fw::ValidationError& e) {
|
||||
return invalid(a, req, e);
|
||||
}
|
||||
if (!wants_html(req)) return fw::JsonResponse(lab_->json(), 200);
|
||||
return page(200, notice);
|
||||
}
|
||||
|
||||
void mount(fw::Router& router, const std::shared_ptr<LabPage>& self,
|
||||
const std::string& name) {
|
||||
router.get(path_, name, [self](fw::Request) { return self->page(200, ""); });
|
||||
for (std::size_t i = 0; i < actions_.size(); ++i)
|
||||
router.post(path_ + actions_[i].sub(), name + actions_[i].sub(),
|
||||
[self, i](fw::Request req) { return self->handle(i, req); });
|
||||
}
|
||||
|
||||
private:
|
||||
std::string action_html(const ActionSpec& a) const {
|
||||
std::string h = "<form method=\"post\" class=\"toolbar\" action=\"" +
|
||||
fw::html_escape(path_ + a.sub()) + "\">";
|
||||
Params d = a.defaults();
|
||||
for (const auto& f : a.form()) {
|
||||
h += "<label class=\"inline\">" + fw::html_escape(f.label) +
|
||||
" <input type=\"" + f.type + "\" name=\"" + fw::html_escape(f.name) +
|
||||
"\" value=\"" + fw::html_escape(d[f.name]) +
|
||||
"\" style=\"max-width:9rem\" title=\"" + fw::html_escape(f.hint) +
|
||||
"\"></label>";
|
||||
}
|
||||
return h + "<button type=\"submit\">" + fw::html_escape(a.label()) +
|
||||
"</button></form>";
|
||||
}
|
||||
|
||||
fw::Environment* env_;
|
||||
std::string path_, title_, intro_;
|
||||
std::shared_ptr<fw::Lab> lab_;
|
||||
std::deque<ActionSpec> actions_; // deque: stable references while adding
|
||||
std::function<fw::LabRows()> extra_;
|
||||
};
|
||||
|
||||
long to_long(const Params& p, const std::string& k) {
|
||||
return std::stol(p.at(k));
|
||||
}
|
||||
|
||||
// Builds, wires and registers one lab page in the index matrix.
|
||||
class Mounter {
|
||||
public:
|
||||
Mounter(fw::Router& router, Services& services,
|
||||
std::shared_ptr<fw::DebugRegistry> registry)
|
||||
: router_(router), services_(services), registry_(std::move(registry)) {}
|
||||
|
||||
std::shared_ptr<LabPage> page(const std::string& feature,
|
||||
const std::string& path,
|
||||
const std::string& title,
|
||||
const std::string& intro,
|
||||
std::shared_ptr<fw::Lab> lab) {
|
||||
auto p = std::make_shared<LabPage>(services_.templates.get(), path, title,
|
||||
intro, std::move(lab));
|
||||
pending_.push_back({p, feature, path});
|
||||
return p;
|
||||
}
|
||||
void finish() {
|
||||
for (auto& e : pending_) {
|
||||
e.page->mount(router_, e.page, e.path);
|
||||
services_.add_feature(e.feature, e.path);
|
||||
}
|
||||
pending_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
std::shared_ptr<LabPage> page;
|
||||
std::string feature, path;
|
||||
};
|
||||
fw::Router& router_;
|
||||
Services& services_;
|
||||
std::shared_ptr<fw::DebugRegistry> registry_;
|
||||
std::vector<Entry> pending_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_resilience_demo(fw::Router& router, Services& services) {
|
||||
services.templates->add_template("lab_page.html", kLabPage);
|
||||
auto registry = std::make_shared<fw::DebugRegistry>();
|
||||
Mounter m(router, services, registry);
|
||||
|
||||
// ---- operability: resilience -------------------------------------------
|
||||
auto bclock = std::make_shared<fw::ManualClock>();
|
||||
auto breaker = std::make_shared<fw::CircuitBreaker>(bclock);
|
||||
registry->add(breaker);
|
||||
auto p = m.page("Circuit breaker", "/operability/breaker", "Circuit breaker",
|
||||
"Three failures open the breaker, calls are rejected while "
|
||||
"open, 30 s of injected clock time later it goes half-open "
|
||||
"and one good call closes it again.",
|
||||
breaker);
|
||||
p->action("/success", "Call succeeds").run([breaker](const Params&) {
|
||||
return breaker->call(true) ? "call recorded" : "rejected: breaker open";
|
||||
});
|
||||
p->action("/failure", "Call fails").run([breaker](const Params&) {
|
||||
return breaker->call(false) ? "failure recorded" : "rejected: breaker open";
|
||||
});
|
||||
p->action("/tick", "Advance 10 s").run([breaker](const Params&) {
|
||||
breaker->tick(10000);
|
||||
return "clock advanced 10 s";
|
||||
});
|
||||
|
||||
auto bulkhead = std::make_shared<fw::Bulkhead>();
|
||||
registry->add(bulkhead);
|
||||
p = m.page("Bulkhead", "/operability/bulkhead", "Bulkhead",
|
||||
"Two concurrent slots and a queue of one; the fourth caller is "
|
||||
"rejected instead of starving the rest.",
|
||||
bulkhead);
|
||||
p->action("/acquire", "Take a slot").run([bulkhead](const Params&) {
|
||||
switch (bulkhead->acquire()) {
|
||||
case fw::Bulkhead::Admission::Admitted: return "admitted";
|
||||
case fw::Bulkhead::Admission::Queued: return "queued";
|
||||
default: return "rejected: compartment full";
|
||||
}
|
||||
});
|
||||
p->action("/release", "Release a slot").run([bulkhead](const Params&) {
|
||||
return bulkhead->release() ? "released" : "nothing to release";
|
||||
});
|
||||
|
||||
auto shedder = std::make_shared<fw::Shedder>();
|
||||
registry->add(shedder);
|
||||
p = m.page("Load shedder", "/operability/shedder", "Load shedder",
|
||||
"Limit 3 in flight. Low priority work is shed first (at 2), high "
|
||||
"priority only at the limit.",
|
||||
shedder);
|
||||
p->action("/enter", "Start request")
|
||||
.text("priority", "Priority", 1, 8, "low", "low or high", false)
|
||||
.run([shedder](const Params& q) {
|
||||
require_in("priority", q.at("priority"), {"low", "high"});
|
||||
return shedder->enter(q.at("priority") == "high") ? "accepted" : "shed";
|
||||
});
|
||||
p->action("/leave", "Finish request").run([shedder](const Params&) {
|
||||
return shedder->leave() ? "finished" : "nothing in flight";
|
||||
});
|
||||
|
||||
auto deadline = std::make_shared<fw::DeadlineLab>();
|
||||
registry->add(deadline);
|
||||
p = m.page("Deadline propagation", "/operability/deadline",
|
||||
"Deadline propagation",
|
||||
"One budget travels through every hop; each hop costs 30 ms and a "
|
||||
"hop that cannot finish in time is skipped.",
|
||||
deadline);
|
||||
p->action("/run", "Run chain")
|
||||
.num("budget_ms", "Budget ms", 0, 5000, "100")
|
||||
.num("hops", "Hops", 1, 10, "3")
|
||||
.run([deadline](const Params& q) {
|
||||
int hop = deadline->run(to_long(q, "budget_ms"), (int)to_long(q, "hops"));
|
||||
return hop ? "deadline exceeded at hop " + std::to_string(hop)
|
||||
: std::string("all hops finished in budget");
|
||||
});
|
||||
|
||||
auto slo = std::make_shared<fw::SloBudget>();
|
||||
registry->add(slo);
|
||||
p = m.page("SLO error budget", "/operability/slo", "SLO error budget",
|
||||
"95.0% target over the last 100 events. The error budget is how "
|
||||
"many bad events the window still allows.",
|
||||
slo);
|
||||
p->action("/good", "Good event").run([slo](const Params&) {
|
||||
slo->record(true);
|
||||
return "good event recorded";
|
||||
});
|
||||
p->action("/bad", "Bad event").run([slo](const Params&) {
|
||||
slo->record(false);
|
||||
return "bad event recorded";
|
||||
});
|
||||
p->action("/reset", "Reset window").run([slo](const Params&) {
|
||||
slo->reset();
|
||||
return "window reset";
|
||||
});
|
||||
|
||||
// ---- operability: chaos, deploy, coordination ---------------------------
|
||||
auto chaos = std::make_shared<fw::ChaosLab>();
|
||||
registry->add(chaos);
|
||||
p = m.page("Chaos experiment", "/operability/chaos", "Chaos experiment",
|
||||
"Fault injection with a hard blast radius: at most 50 percent and "
|
||||
"5 faults over 10 calls. Armed 0 is a dry run and injects nothing.",
|
||||
chaos);
|
||||
p->action("/run", "Run experiment")
|
||||
.num("percent", "Percent", 0, fw::labcaps::kMaxPercent, "20")
|
||||
.num("max_faults", "Max faults", 1, fw::labcaps::kMaxFaults, "2")
|
||||
.num("armed", "Armed", 0, 1, "0", "0 dry run, 1 armed")
|
||||
.run([chaos](const Params& q) {
|
||||
auto r = chaos->run((int)to_long(q, "percent"),
|
||||
(int)to_long(q, "max_faults"), to_long(q, "armed") == 1);
|
||||
return std::string(r.armed ? "armed: " : "dry run: ") +
|
||||
std::to_string(r.injected) + " injected, " +
|
||||
std::to_string(r.planned) + " planned";
|
||||
});
|
||||
|
||||
auto deploy = std::make_shared<fw::DeployLab>();
|
||||
registry->add(deploy);
|
||||
p = m.page("Deploy strategies", "/operability/deploy", "Deploy strategies",
|
||||
"Rolling replaces one instance per step; blue-green prepares a "
|
||||
"green fleet and switches in one step. Rollback restores the "
|
||||
"previous fleet.",
|
||||
deploy);
|
||||
p->action("/start", "Start rollout")
|
||||
.text("strategy", "Strategy", 1, 16, "rolling", "rolling or bluegreen", false)
|
||||
.text("version", "Version", 1, 16, "v2", "", false)
|
||||
.run([deploy](const Params& q) {
|
||||
require_in("strategy", q.at("strategy"), {"rolling", "bluegreen"});
|
||||
return deploy->start(q.at("strategy"), q.at("version"))
|
||||
? "rollout started"
|
||||
: "a rollout is already in progress";
|
||||
});
|
||||
p->action("/step", "Next step").run([deploy](const Params&) {
|
||||
return deploy->step() ? "step done" : "no rollout in progress";
|
||||
});
|
||||
p->action("/rollback", "Roll back").run([deploy](const Params&) {
|
||||
return deploy->rollback() ? "rolled back" : "nothing to roll back";
|
||||
});
|
||||
|
||||
auto cclock = std::make_shared<fw::ManualClock>();
|
||||
auto coord = std::make_shared<fw::CoordLab>(cclock);
|
||||
registry->add(coord);
|
||||
p = m.page("Lease, election, fenced lock", "/operability/coord",
|
||||
"Coordination",
|
||||
"Lease, leader election and distributed lock share one rule: a "
|
||||
"new holder gets a higher fencing token, and writes with a stale "
|
||||
"token are rejected. Leases last 10 s of injected time.",
|
||||
coord);
|
||||
p->action("/acquire", "Acquire")
|
||||
.text("key", "Key", 1, 16, "lock", "lease, lock or leader", false)
|
||||
.text("owner", "Owner", 1, 32, "a", "", true)
|
||||
.run([coord](const Params& q) {
|
||||
require_in("key", q.at("key"), {"lease", "lock", "leader"});
|
||||
auto g = coord->acquire(q.at("key"), q.at("owner"));
|
||||
return g.ok ? "granted token " + std::to_string(g.token)
|
||||
: "denied, held by " + g.holder;
|
||||
});
|
||||
p->action("/release", "Release")
|
||||
.text("key", "Key", 1, 16, "lock", "lease, lock or leader", false)
|
||||
.text("owner", "Owner", 1, 32, "a", "", true)
|
||||
.run([coord](const Params& q) {
|
||||
require_in("key", q.at("key"), {"lease", "lock", "leader"});
|
||||
return coord->release(q.at("key"), q.at("owner")) ? "released"
|
||||
: "not the holder";
|
||||
});
|
||||
p->action("/write", "Fenced write")
|
||||
.text("key", "Key", 1, 16, "lock", "lease, lock or leader", false)
|
||||
.num("token", "Token", 0, 1000000, "1")
|
||||
.run([coord](const Params& q) {
|
||||
require_in("key", q.at("key"), {"lease", "lock", "leader"});
|
||||
return coord->write(q.at("key"), to_long(q, "token"))
|
||||
? "write accepted"
|
||||
: "write rejected: stale fencing token";
|
||||
});
|
||||
p->action("/tick", "Advance 6 s").run([coord](const Params&) {
|
||||
coord->tick(6000);
|
||||
return "clock advanced 6 s";
|
||||
});
|
||||
|
||||
// ---- supply chain -------------------------------------------------------
|
||||
auto supply = std::make_shared<fw::SupplyChainLab>();
|
||||
registry->add(supply);
|
||||
p = m.page("Supply chain gate", "/supplychain", "Supply chain gate",
|
||||
"Illustrative SBOM of this example (CycloneDX shape), dependency "
|
||||
"pins, an advisory scan and an attestation check. The gate passes "
|
||||
"only when all three pass. The digest is FNV-1a, not a signature.",
|
||||
supply);
|
||||
p->action("/advisory", "Publish advisory for chartjs 4.4.1")
|
||||
.run([supply](const Params&) {
|
||||
return supply->add_advisory("chartjs", "4.4.1") ? "advisory published"
|
||||
: "advisory db full";
|
||||
});
|
||||
p->action("/tamper", "Tamper with chartjs").run([supply](const Params&) {
|
||||
supply->tamper();
|
||||
return "component changed after attestation";
|
||||
});
|
||||
p->action("/verify", "Verify attestation")
|
||||
.text("digest", "Digest", 16, 16, "", "16 hex characters of sbom_digest")
|
||||
.dynamic_defaults([supply] { return Params{{"digest", supply->attested()}}; })
|
||||
.run([supply](const Params& q) {
|
||||
return supply->verify(q.at("digest")) ? "attestation verified"
|
||||
: "attestation FAILED";
|
||||
});
|
||||
p->action("/reset", "Regenerate and attest").run([supply](const Params&) {
|
||||
supply->reset();
|
||||
return "sbom regenerated";
|
||||
});
|
||||
router.get("/supplychain/sbom.json", "supplychain-sbom",
|
||||
[supply](fw::Request) {
|
||||
return fw::JsonResponse(supply->cyclonedx(), 200);
|
||||
});
|
||||
|
||||
// ---- clients depth ------------------------------------------------------
|
||||
auto retry = std::make_shared<fw::ClientRetryLab>();
|
||||
registry->add(retry);
|
||||
p = m.page("Client retry and backoff", "/clients/retry",
|
||||
"Client retry and backoff",
|
||||
"In-process transport that fails the first N calls. 5xx is "
|
||||
"retried with doubling backoff capped at 800 ms and at most 5 "
|
||||
"attempts; 4xx is never retried. Waits are virtual.",
|
||||
retry);
|
||||
p->action("/run", "Send request")
|
||||
.num("failures", "Failures", 0, 10, "2")
|
||||
.num("max_attempts", "Max attempts", 1, fw::labcaps::kMaxAttempts, "3")
|
||||
.num("status", "Failure status", 400, 599, "503")
|
||||
.run([retry](const Params& q) {
|
||||
auto o = retry->run((int)to_long(q, "failures"),
|
||||
(int)to_long(q, "max_attempts"),
|
||||
(int)to_long(q, "status"));
|
||||
return "final status " + std::to_string(o.status) + " after " +
|
||||
std::to_string(o.attempts) + " attempt(s)";
|
||||
});
|
||||
|
||||
auto session = std::make_shared<fw::ClientSessionLab>();
|
||||
registry->add(session);
|
||||
p = m.page("Client session: cookies, pool, proxy, auth", "/clients/session",
|
||||
"Client session",
|
||||
"Each request goes through the in-process transport: the server "
|
||||
"sets cookies into the jar, connections are pooled and reused, a "
|
||||
"proxy change opens a new connection, and the auth scheme sets the "
|
||||
"Authorization header.",
|
||||
session);
|
||||
p->action("/request", "Send request")
|
||||
.text("auth", "Auth", 1, 8, "none", "none, basic or bearer", false)
|
||||
.text("proxy", "Proxy", 0, 80, "", "http://host:port or empty", false)
|
||||
.run([session](const Params& q) {
|
||||
require_in("auth", q.at("auth"), {"none", "basic", "bearer"});
|
||||
auto px = q.count("proxy") ? q.at("proxy") : std::string();
|
||||
if (!fw::ClientSessionLab::valid_proxy(px))
|
||||
throw fw::ValidationError(
|
||||
{{"proxy", "must be empty or http(s)/socks5://host:port"}});
|
||||
auto h = session->request(q.at("auth"), px);
|
||||
std::string out = "sent:";
|
||||
for (const auto& [k, v] : h) out += " " + k + "=" + v + ";";
|
||||
return out;
|
||||
});
|
||||
|
||||
// ---- data depth ---------------------------------------------------------
|
||||
auto mig = std::make_shared<fw::MigrationLab>();
|
||||
registry->add(mig);
|
||||
p = m.page("Migrations: check then apply", "/data/migrations",
|
||||
"Migrations",
|
||||
"Preview shows what apply would run without changing anything. "
|
||||
"Apply runs pending steps in order. Drift drops a table out of "
|
||||
"band and heal re-creates it from its migration.",
|
||||
mig);
|
||||
p->extra_rows([mig] {
|
||||
fw::LabRows r;
|
||||
for (const auto& line : mig->check()) r.emplace_back("preview", line);
|
||||
return r;
|
||||
});
|
||||
p->action("/apply", "Apply")
|
||||
.num("limit", "Steps", 1, 3, "3")
|
||||
.run([mig](const Params& q) {
|
||||
int n = mig->apply((int)to_long(q, "limit"));
|
||||
return std::to_string(n) + " migration(s) applied";
|
||||
});
|
||||
p->action("/drift", "Drop posts table").run([mig](const Params&) {
|
||||
mig->drop_table("posts");
|
||||
return "posts dropped out of band";
|
||||
});
|
||||
p->action("/heal", "Heal drift").run([mig](const Params&) {
|
||||
return std::to_string(mig->heal()) + " table(s) healed";
|
||||
});
|
||||
|
||||
auto tx = std::make_shared<fw::TxLab>();
|
||||
registry->add(tx);
|
||||
p = m.page("Transaction rollback", "/data/transaction", "Transaction rollback",
|
||||
"Transfer between alice and bob inside a transaction. Overdrafts "
|
||||
"and a failure after the debit roll back, so no money is lost.",
|
||||
tx);
|
||||
p->action("/transfer", "Transfer")
|
||||
.text("from", "From", 1, 8, "alice", "alice or bob", false)
|
||||
.text("to", "To", 1, 8, "bob", "alice or bob", false)
|
||||
.num("amount", "Amount", 1, 1000, "30")
|
||||
.num("fail_after_debit", "Fail after debit", 0, 1, "0", "0 or 1")
|
||||
.run([tx](const Params& q) {
|
||||
require_in("from", q.at("from"), {"alice", "bob"});
|
||||
require_in("to", q.at("to"), {"alice", "bob"});
|
||||
if (q.at("from") == q.at("to"))
|
||||
throw fw::ValidationError({{"to", "must differ from the source"}});
|
||||
return tx->transfer(q.at("from"), q.at("to"), to_long(q, "amount"),
|
||||
to_long(q, "fail_after_debit") == 1);
|
||||
});
|
||||
|
||||
auto query = std::make_shared<fw::QueryLab>();
|
||||
registry->add(query);
|
||||
p = m.page("Query builder and relations", "/data/query",
|
||||
"Query builder and relations",
|
||||
"Builds a joined SELECT over users has-many posts and runs it on "
|
||||
"in-memory tables. User 0 means all users.",
|
||||
query);
|
||||
p->action("/run", "Run query")
|
||||
.num("user_id", "User id", 0, 2, "0")
|
||||
.text("order", "Order", 1, 8, "id", "id or title", false)
|
||||
.num("limit", "Limit", 1, 10, "5")
|
||||
.run([query](const Params& q) {
|
||||
require_in("order", q.at("order"), {"id", "title"});
|
||||
auto r = query->run(to_long(q, "user_id"), q.at("order"),
|
||||
(int)to_long(q, "limit"));
|
||||
return std::to_string(r.rows.size()) + " row(s)";
|
||||
});
|
||||
|
||||
auto flight = std::make_shared<fw::SingleFlightLab>();
|
||||
registry->add(flight);
|
||||
p = m.page("Singleflight", "/data/singleflight", "Singleflight",
|
||||
"Concurrent callers asking for the same key share one load. The "
|
||||
"loader waits for the other callers to join, so the result is "
|
||||
"deterministic. At most 16 threads.",
|
||||
flight);
|
||||
p->action("/run", "Run callers")
|
||||
.num("callers", "Callers", 1, fw::labcaps::kMaxThreads, "8")
|
||||
.run([flight](const Params& q) {
|
||||
int callers = (int)to_long(q, "callers");
|
||||
int loads = flight->run(callers);
|
||||
return std::to_string(callers) + " callers, " + std::to_string(loads) +
|
||||
" load(s)";
|
||||
});
|
||||
|
||||
auto tclock = std::make_shared<fw::ManualClock>();
|
||||
auto ttl = std::make_shared<fw::TtlLab>(tclock);
|
||||
registry->add(ttl);
|
||||
p = m.page("TTL store, LRU, pubsub", "/data/ttl", "TTL store",
|
||||
"Memory store with per-key TTL on injected time, LRU eviction at "
|
||||
"5 entries, and a pubsub topic kv.events announcing every change.",
|
||||
ttl);
|
||||
p->extra_rows([ttl] {
|
||||
fw::LabRows r;
|
||||
for (const auto& e : ttl->events()) r.emplace_back("event", e);
|
||||
return r;
|
||||
});
|
||||
p->action("/set", "Set key")
|
||||
.text("key", "Key", 1, 16, "", "", true)
|
||||
.text("value", "Value", 1, 32, "", "", true)
|
||||
.num("ttl_s", "TTL s", 1, 60, "10")
|
||||
.run([ttl](const Params& q) {
|
||||
ttl->set(q.at("key"), q.at("value"), to_long(q, "ttl_s"));
|
||||
return "stored " + q.at("key");
|
||||
});
|
||||
p->action("/get", "Get key")
|
||||
.text("key", "Key", 1, 16, "", "", true)
|
||||
.run([ttl](const Params& q) {
|
||||
std::string v;
|
||||
return ttl->get(q.at("key"), v) ? "hit: " + v : std::string("miss");
|
||||
});
|
||||
p->action("/tick", "Advance 5 s").run([ttl](const Params&) {
|
||||
ttl->tick(5000);
|
||||
return "clock advanced 5 s";
|
||||
});
|
||||
|
||||
m.finish();
|
||||
|
||||
router.get("/operability/debug", "operability-debug",
|
||||
[registry](fw::Request) {
|
||||
return fw::JsonResponse(registry->snapshot(), 200);
|
||||
});
|
||||
services.add_feature("Debug snapshot", "/operability/debug");
|
||||
}
|
||||
|
||||
} // namespace molo::example::app
|
||||
@@ -69,6 +69,20 @@ void register_security_demo(fw::Router& router, Services& services) {
|
||||
return res;
|
||||
});
|
||||
|
||||
router.get("/uploads/file", "upload-list", [uploads](fw::Request req) {
|
||||
(void)req;
|
||||
std::string body = "{\"files\":[";
|
||||
bool first = true;
|
||||
for (const auto& u : uploads->list()) {
|
||||
body += std::string(first ? "" : ",") + "{\"file\":\"" +
|
||||
fw::json_escape(u.filename) + "\",\"size\":" +
|
||||
std::to_string(u.size) + "}";
|
||||
first = false;
|
||||
}
|
||||
return fw::JsonResponse(
|
||||
body + "],\"usage\":\"POST body to /uploads/file?filename=<name>\"}",
|
||||
200);
|
||||
});
|
||||
router.post("/uploads/file", "upload", [uploads](fw::Request req) {
|
||||
std::string filename = req.query_or("filename", "upload.txt");
|
||||
std::string content_type =
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
#include "App.hpp"
|
||||
|
||||
#include "FormUi.hpp"
|
||||
#include "../fw/Cookies.hpp"
|
||||
#include "../fw/Router.hpp"
|
||||
#include "../fw/SecurityExtra.hpp"
|
||||
#include "../fw/Validate.hpp"
|
||||
|
||||
namespace molo::example::app {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char* kHtml = "text/html; charset=utf-8";
|
||||
|
||||
// Shared state of this group, owned by the closures through shared_ptr.
|
||||
struct SecState {
|
||||
fw::DenialSink denials;
|
||||
fw::CsrfGuard csrf;
|
||||
fw::CorsPolicy cors;
|
||||
fw::RateLimiter limiter;
|
||||
fw::CspReportStore csp_reports;
|
||||
fw::PermissionGuard perms;
|
||||
fw::SecretsProvider secrets;
|
||||
explicit SecState(const std::string& secret)
|
||||
: csrf(secret),
|
||||
cors({"https://app.example.com", "https://admin.example.com"}),
|
||||
limiter(5, 60) {}
|
||||
};
|
||||
|
||||
// One place that renders a FormView and maps failures to HTML or JSON.
|
||||
class FormPage {
|
||||
public:
|
||||
FormPage(fw::Environment* env, SecState* st) : env_(env), st_(st) {}
|
||||
|
||||
fw::Response show(const FormView& v, int status = 200) const {
|
||||
return fw::Response(status, env_->render("form_page.html", v.ctx()), kHtml);
|
||||
}
|
||||
fw::Response fail(FormView v, const fw::Request& req, const std::string& guard,
|
||||
const std::string& field, const std::string& message,
|
||||
int status) const {
|
||||
st_->denials.record(guard, message);
|
||||
if (!wants_html(req))
|
||||
return fw::JsonResponse("{\"error\":\"" + fw::json_escape(guard) +
|
||||
"\",\"field\":\"" + fw::json_escape(field) +
|
||||
"\",\"message\":\"" +
|
||||
fw::json_escape(message) + "\"}",
|
||||
status);
|
||||
fw::ValidationError err({{field, message}});
|
||||
v.values = fw::parse_form(req.body);
|
||||
v.error = &err;
|
||||
return show(v, status);
|
||||
}
|
||||
fw::Response ok(FormView v, const fw::Request& req, const std::string& notice,
|
||||
const std::string& json, int status = 200) const {
|
||||
if (!wants_html(req)) return fw::JsonResponse(json, status);
|
||||
v.done = true;
|
||||
v.notice = notice;
|
||||
return show(v, status);
|
||||
}
|
||||
|
||||
private:
|
||||
fw::Environment* env_;
|
||||
SecState* st_;
|
||||
};
|
||||
|
||||
std::map<std::string, std::string> input_of(const fw::Request& req) {
|
||||
if (req.headers.get("Content-Type").find("json") != std::string::npos)
|
||||
return fw::parse_json_object_flat(req.body);
|
||||
return fw::parse_form(req.body);
|
||||
}
|
||||
|
||||
std::string get(const std::map<std::string, std::string>& m, const std::string& k) {
|
||||
auto it = m.find(k);
|
||||
return it == m.end() ? "" : it->second;
|
||||
}
|
||||
|
||||
FormView make_view(const std::string& title, const std::string& action,
|
||||
const std::string& submit, std::vector<FormField> fields) {
|
||||
FormView v;
|
||||
v.title = title;
|
||||
v.action = action;
|
||||
v.submit = submit;
|
||||
v.fields = std::move(fields);
|
||||
return v;
|
||||
}
|
||||
|
||||
std::string json_list(const std::vector<std::string>& items) {
|
||||
std::string out = "[";
|
||||
for (std::size_t i = 0; i < items.size(); ++i)
|
||||
out += (i ? "," : "") + std::string("\"") + fw::json_escape(items[i]) + "\"";
|
||||
return out + "]";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_security_extra_demo(fw::Router& router, Services& services) {
|
||||
auto st = std::make_shared<SecState>(services.cookie_secret + "-csrf");
|
||||
fw::Environment* env = services.templates.get();
|
||||
FormPage page(env, st.get());
|
||||
auto auth = services.auth;
|
||||
auto sessions = services.sessions;
|
||||
std::string secret = services.cookie_secret;
|
||||
|
||||
// ---- CSRF --------------------------------------------------------------
|
||||
auto csrf_view = [](const std::string& token) {
|
||||
FormView v = make_view("CSRF protected form", "/security/csrf", "Save",
|
||||
{{"csrf_token", "CSRF token", "text",
|
||||
"issued by the server; edit it to see a 403"},
|
||||
{"note", "Note", "text", "any text, 1 to 80 chars"}});
|
||||
v.values["csrf_token"] = token;
|
||||
return v;
|
||||
};
|
||||
router.get("/security/csrf", "csrf-form", [st, page, csrf_view](fw::Request) -> fw::Response {
|
||||
return page.show(csrf_view(st->csrf.issue()));
|
||||
});
|
||||
router.post("/security/csrf", "csrf-post", [st, page, csrf_view](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
FormView v = csrf_view("");
|
||||
if (!st->csrf.verify(get(in, "csrf_token")))
|
||||
return page.fail(v, req, "CsrfGuard", "csrf_token",
|
||||
"missing or invalid CSRF token, reload the form", 403);
|
||||
std::string note = get(in, "note");
|
||||
if (note.empty() || note.size() > 80)
|
||||
return page.fail(v, req, "Validation", "note", "must be 1 to 80 characters", 422);
|
||||
return page.ok(v, req, "Saved: " + note,
|
||||
"{\"ok\":true,\"note\":\"" + fw::json_escape(note) + "\"}");
|
||||
});
|
||||
|
||||
// ---- CORS --------------------------------------------------------------
|
||||
router.get("/security/cors", "cors-info", [st](fw::Request) -> fw::Response {
|
||||
return fw::JsonResponse(
|
||||
"{\"allowed_origins\":[\"https://app.example.com\",\"https://admin.example.com\"],"
|
||||
"\"usage\":\"OPTIONS /security/cors with Origin and Access-Control-Request-Method\"}");
|
||||
});
|
||||
router.options("/security/cors", "cors-preflight", [st](fw::Request req) -> fw::Response {
|
||||
fw::Response res(204, "", "text/plain");
|
||||
if (!st->cors.apply_preflight(req, res)) {
|
||||
st->denials.record("CorsPolicy", "origin not allowed: " + req.headers.get("Origin"));
|
||||
return fw::JsonResponse("{\"error\":\"origin not allowed\"}", 403);
|
||||
}
|
||||
return res;
|
||||
});
|
||||
|
||||
// ---- Rate limiting -----------------------------------------------------
|
||||
router.get("/security/rate", "rate-limited", [st](fw::Request req) -> fw::Response {
|
||||
std::string key = req.headers.get("X-Client-Id");
|
||||
if (key.empty() || key.size() > 64) key = "anon";
|
||||
int retry = 0, remaining = 0;
|
||||
if (!st->limiter.hit(key, retry, remaining)) {
|
||||
st->denials.record("RateLimiter", "limit hit for " + key);
|
||||
fw::Response res = fw::JsonResponse(
|
||||
"{\"error\":\"rate_limited\",\"retry_after\":" + std::to_string(retry) + "}", 429);
|
||||
res.headers.set("Retry-After", std::to_string(retry));
|
||||
return res;
|
||||
}
|
||||
fw::Response res = fw::JsonResponse(
|
||||
"{\"ok\":true,\"limit\":" + std::to_string(st->limiter.limit()) +
|
||||
",\"window_seconds\":" + std::to_string(st->limiter.window()) +
|
||||
",\"remaining\":" + std::to_string(remaining) + "}");
|
||||
res.headers.set("X-RateLimit-Remaining", std::to_string(remaining));
|
||||
return res;
|
||||
});
|
||||
|
||||
// ---- Security headers --------------------------------------------------
|
||||
router.get("/security/headers", "security-headers", [](fw::Request) -> fw::Response {
|
||||
std::string names = "[";
|
||||
bool first = true;
|
||||
for (const auto& [k, v] : fw::SecurityHeaders::defaults()) {
|
||||
names += std::string(first ? "" : ",") + "{\"name\":\"" + k +
|
||||
"\",\"value\":\"" + fw::json_escape(v) + "\"}";
|
||||
first = false;
|
||||
}
|
||||
fw::Response res = fw::JsonResponse("{\"applied\":" + names + "]}");
|
||||
fw::SecurityHeaders::apply(res);
|
||||
return res;
|
||||
});
|
||||
|
||||
// ---- CSP with nonce and report endpoint --------------------------------
|
||||
router.get("/csp/page", "csp-page", [](fw::Request) -> fw::Response {
|
||||
std::string nonce = fw::SecureRandom::token_hex(16);
|
||||
fw::CspBuilder csp;
|
||||
csp.script_nonce(nonce).report_uri("/csp/report");
|
||||
std::string body =
|
||||
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
||||
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
|
||||
"<title>CSP nonce</title></head><body><h1>CSP nonce demo</h1>"
|
||||
"<p id=\"out\">Script blocked.</p><p>Nonce: <code>" + nonce +
|
||||
"</code></p><p><a href=\"/csp/report\">Violation reports</a></p>"
|
||||
"<script nonce=\"" + nonce +
|
||||
"\">document.getElementById('out').textContent='Nonce script ran.';</script>"
|
||||
"</body></html>";
|
||||
fw::Response res(200, body, kHtml);
|
||||
res.headers.set(csp.header_name(), csp.build());
|
||||
return res;
|
||||
});
|
||||
router.get("/csp/report", "csp-report-list", [st](fw::Request) -> fw::Response {
|
||||
std::string out = "{\"total\":" + std::to_string(st->csp_reports.total()) + ",\"reports\":[";
|
||||
bool first = true;
|
||||
for (const auto& r : st->csp_reports.list()) {
|
||||
out += std::string(first ? "" : ",") + "\"" + fw::json_escape(r) + "\"";
|
||||
first = false;
|
||||
}
|
||||
return fw::JsonResponse(out + "]}");
|
||||
});
|
||||
router.post("/csp/report", "csp-report", [st](fw::Request req) -> fw::Response {
|
||||
if (!st->csp_reports.add(req.body)) {
|
||||
st->denials.record("CspReport", "empty or oversized report");
|
||||
return fw::JsonResponse("{\"error\":\"report empty or over 4096 bytes\"}", 400);
|
||||
}
|
||||
return fw::Response(204, "", "text/plain");
|
||||
});
|
||||
|
||||
// ---- Crypto: hash and HMAC --------------------------------------------
|
||||
auto hash_view = []() {
|
||||
return make_view("SHA-256 and HMAC-SHA256", "/crypto/hash", "Hash",
|
||||
{{"text", "Text", "text", "up to 4096 bytes"},
|
||||
{"key", "HMAC key", "text", "optional, default demo-key"}});
|
||||
};
|
||||
router.get("/crypto/hash", "crypto-hash-form", [page, hash_view](fw::Request) -> fw::Response {
|
||||
return page.show(hash_view());
|
||||
});
|
||||
router.post("/crypto/hash", "crypto-hash", [page, hash_view](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
std::string text = get(in, "text");
|
||||
std::string key = get(in, "key");
|
||||
if (key.empty()) key = "demo-key";
|
||||
if (text.empty() || text.size() > fw::secaps::kMaxHashInput)
|
||||
return page.fail(hash_view(), req, "Validation", "text",
|
||||
"must be 1 to 4096 bytes", 422);
|
||||
std::string sha = fw::Sha256::hex(text);
|
||||
std::string mac = fw::to_hex(fw::Hmac::sha256(key, text));
|
||||
return page.ok(hash_view(), req, "sha256=" + sha + " hmac=" + mac,
|
||||
"{\"sha256\":\"" + sha + "\",\"hmac_sha256\":\"" + mac + "\"}");
|
||||
});
|
||||
|
||||
// ---- Crypto: secure random --------------------------------------------
|
||||
router.get("/crypto/random", "crypto-random", [](fw::Request req) -> fw::Response {
|
||||
long n = 16;
|
||||
try { n = std::stol(req.query_or("bytes", "16")); } catch (...) { n = -1; }
|
||||
if (n < 1 || n > static_cast<long>(fw::secaps::kMaxRandomBytes))
|
||||
return fw::JsonResponse("{\"error\":\"bytes must be 1 to 64\"}", 400);
|
||||
return fw::JsonResponse("{\"bytes\":" + std::to_string(n) + ",\"token\":\"" +
|
||||
fw::SecureRandom::token_hex(static_cast<std::size_t>(n)) + "\"}");
|
||||
});
|
||||
|
||||
// ---- Crypto: password hashing -----------------------------------------
|
||||
auto pw_view = []() {
|
||||
return make_view("Password hashing (DEMO)", "/crypto/password", "Hash",
|
||||
{{"password", "Password", "password",
|
||||
"8 to 128 chars; salted PBKDF2 at demo rounds, not production"}});
|
||||
};
|
||||
router.get("/crypto/password", "crypto-password-form", [page, pw_view](fw::Request) -> fw::Response {
|
||||
return page.show(pw_view());
|
||||
});
|
||||
router.post("/crypto/password", "crypto-password", [page, pw_view](fw::Request req) -> fw::Response {
|
||||
std::string pw = get(input_of(req), "password");
|
||||
if (pw.size() < 8 || pw.size() > 128)
|
||||
return page.fail(pw_view(), req, "Validation", "password",
|
||||
"must be 8 to 128 characters", 422);
|
||||
std::string stored = fw::PasswordHasher::hash(pw);
|
||||
bool good = fw::PasswordHasher::verify(pw, stored);
|
||||
bool bad = fw::PasswordHasher::verify(pw + "x", stored);
|
||||
return page.ok(pw_view(), req,
|
||||
"Stored form: " + stored + " (verify ok: " + (good ? "yes" : "no") +
|
||||
", wrong password: " + (bad ? "accepted" : "rejected") + ")",
|
||||
"{\"stored\":\"" + stored + "\",\"verify\":" + (good ? "true" : "false") +
|
||||
",\"verify_wrong\":" + (bad ? "true" : "false") + "}");
|
||||
});
|
||||
|
||||
// ---- Roles and permissions --------------------------------------------
|
||||
router.get("/security/roles", "roles-info", [st](fw::Request) -> fw::Response {
|
||||
std::string out = "{\"tokens\":{\"viewer-token\":\"viewer\",\"editor-token\":\"editor\","
|
||||
"\"admin-token\":\"admin\"},\"roles\":{";
|
||||
bool first = true;
|
||||
for (const char* r : {"viewer", "editor", "admin"}) {
|
||||
out += std::string(first ? "" : ",") + "\"" + r + "\":" + json_list(st->perms.permissions(r));
|
||||
first = false;
|
||||
}
|
||||
return fw::JsonResponse(out + "},\"usage\":\"GET /security/admin with Authorization: Bearer <token>\"}");
|
||||
});
|
||||
router.get("/security/admin", "admin-area", [st](fw::Request req) -> fw::Response {
|
||||
std::string role;
|
||||
auto verdict = st->perms.check(req.headers.get("Authorization"), "admin:manage", role);
|
||||
if (verdict == fw::PermissionGuard::Verdict::Unauthenticated) {
|
||||
st->denials.record("Guard", "unauthenticated");
|
||||
fw::Response res = fw::JsonResponse("{\"error\":\"authentication required\"}", 401);
|
||||
res.headers.set("WWW-Authenticate", "Bearer");
|
||||
return res;
|
||||
}
|
||||
if (verdict == fw::PermissionGuard::Verdict::Forbidden) {
|
||||
st->denials.record("Guard", "role " + role + " lacks admin:manage");
|
||||
return fw::JsonResponse("{\"error\":\"forbidden\",\"role\":\"" + role + "\"}", 403);
|
||||
}
|
||||
return fw::JsonResponse("{\"ok\":true,\"role\":\"" + role + "\"}");
|
||||
});
|
||||
|
||||
// ---- Secrets provider -------------------------------------------------
|
||||
router.get("/security/secrets", "secrets", [st](fw::Request req) -> fw::Response {
|
||||
std::string name = req.query_or("name", "");
|
||||
if (!name.empty()) {
|
||||
std::string m;
|
||||
if (!st->secrets.masked(name, m))
|
||||
return fw::JsonResponse("{\"error\":\"unknown secret\"}", 404);
|
||||
return fw::JsonResponse("{\"name\":\"" + fw::json_escape(name) + "\",\"value\":\"" + m + "\"}");
|
||||
}
|
||||
return fw::JsonResponse("{\"names\":" + json_list(st->secrets.names()) +
|
||||
",\"note\":\"values are always masked\"}");
|
||||
});
|
||||
|
||||
// ---- Upload validation ------------------------------------------------
|
||||
auto up_view = []() {
|
||||
return make_view("Upload validation", "/security/upload", "Check",
|
||||
{{"filename", "File name", "text", "pdf, png or txt"},
|
||||
{"content_hex", "Content (hex bytes)", "text",
|
||||
"pdf starts 255044462d, png starts 89504e47, max 1024 bytes"}});
|
||||
};
|
||||
router.get("/security/upload", "upload-check-form", [page, up_view](fw::Request) -> fw::Response {
|
||||
return page.show(up_view());
|
||||
});
|
||||
router.post("/security/upload", "upload-check", [page, up_view](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
std::string bytes;
|
||||
std::string hex = get(in, "content_hex");
|
||||
if (hex.size() > fw::secaps::kMaxUploadHex || !fw::from_hex(hex, bytes))
|
||||
return page.fail(up_view(), req, "UploadValidator", "content_hex",
|
||||
"must be an even number of hex digits, at most 4096", 422);
|
||||
std::string why = fw::UploadValidator::check(get(in, "filename"), bytes);
|
||||
if (!why.empty()) {
|
||||
bool big = why.find("too large") != std::string::npos;
|
||||
return page.fail(up_view(), req, "UploadValidator",
|
||||
why.find("file name") != std::string::npos ||
|
||||
why.find("extension") != std::string::npos
|
||||
? "filename"
|
||||
: "content_hex",
|
||||
why, big ? 413 : 422);
|
||||
}
|
||||
return page.ok(up_view(), req, "Accepted " + get(in, "filename") + " (" +
|
||||
std::to_string(bytes.size()) + " bytes)",
|
||||
"{\"ok\":true,\"size\":" + std::to_string(bytes.size()) + "}");
|
||||
});
|
||||
|
||||
// ---- SQL safety and path guard ----------------------------------------
|
||||
auto guard_view = []() {
|
||||
return make_view("SQL and path guard", "/security/guard", "Check",
|
||||
{{"kind", "Kind", "text", "sql or path"},
|
||||
{"value", "Value", "text", "try ' OR 1=1 -- or ../etc/passwd"}});
|
||||
};
|
||||
router.get("/security/guard", "guard-form", [page, guard_view](fw::Request) -> fw::Response {
|
||||
return page.show(guard_view());
|
||||
});
|
||||
router.post("/security/guard", "guard-check", [page, guard_view](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
std::string kind = get(in, "kind"), value = get(in, "value");
|
||||
if (kind != "sql" && kind != "path")
|
||||
return page.fail(guard_view(), req, "Validation", "kind", "must be sql or path", 422);
|
||||
if (value.empty() || value.size() > fw::secaps::kMaxInputLen)
|
||||
return page.fail(guard_view(), req, "Validation", "value", "must be 1 to 512 characters", 422);
|
||||
std::string why = kind == "sql" ? fw::SqlSafety::check(value) : fw::PathGuard::check(value);
|
||||
if (!why.empty())
|
||||
return page.fail(guard_view(), req, kind == "sql" ? "SqlSafety" : "PathGuard", "value", why, 422);
|
||||
return page.ok(guard_view(), req, "Value is safe for " + kind,
|
||||
"{\"ok\":true,\"kind\":\"" + kind + "\"}");
|
||||
});
|
||||
|
||||
// ---- Denial sink ------------------------------------------------------
|
||||
router.get("/security/denials", "denials", [st](fw::Request) -> fw::Response {
|
||||
std::string out = "{\"total\":" + std::to_string(st->denials.total()) + ",\"recent\":[";
|
||||
bool first = true;
|
||||
for (const auto& d : st->denials.list()) {
|
||||
out += std::string(first ? "" : ",") + "{\"guard\":\"" + fw::json_escape(d.guard) +
|
||||
"\",\"reason\":\"" + fw::json_escape(d.reason) + "\"}";
|
||||
first = false;
|
||||
}
|
||||
return fw::JsonResponse(out + "]}");
|
||||
});
|
||||
|
||||
// ---- Login form with session cookie -----------------------------------
|
||||
auto login_view = []() {
|
||||
return make_view("Sign in", "/security/login", "Sign in",
|
||||
{{"username", "Username", "text", "demo: ada"},
|
||||
{"password", "Password", "password", "demo: correct-horse"}});
|
||||
};
|
||||
router.get("/security/login", "login-form", [page, login_view](fw::Request) -> fw::Response {
|
||||
return page.show(login_view());
|
||||
});
|
||||
router.post("/security/login", "login-post",
|
||||
[page, login_view, auth, sessions, secret](fw::Request req) -> fw::Response {
|
||||
auto in = input_of(req);
|
||||
std::string user = get(in, "username");
|
||||
if (user.empty() || user.size() > 64)
|
||||
return page.fail(login_view(), req, "Validation", "username", "is required (max 64)", 422);
|
||||
if (get(in, "password").empty())
|
||||
return page.fail(login_view(), req, "Validation", "password", "is required", 422);
|
||||
if (!auth->check(user, get(in, "password")))
|
||||
return page.fail(login_view(), req, "Authenticator", "password", "wrong username or password", 401);
|
||||
std::string id = sessions->create();
|
||||
sessions->put(id, "user", user);
|
||||
fw::Response res = page.ok(login_view(), req, "Signed in as " + user,
|
||||
"{\"user\":\"" + fw::json_escape(user) + "\"}");
|
||||
res.headers.set("Set-Cookie", fw::make_set_cookie("login_sid", fw::cookie_sign(id, secret),
|
||||
"/", true, false, "Lax", 3600));
|
||||
return res;
|
||||
});
|
||||
router.get("/security/whoami", "whoami", [sessions, secret](fw::Request req) -> fw::Response {
|
||||
std::string id;
|
||||
std::map<std::string, std::string> data;
|
||||
if (!fw::cookie_verify(req.cookie_or("login_sid", ""), secret, id) ||
|
||||
!sessions->get(id, data) || !data.count("user"))
|
||||
return fw::JsonResponse("{\"error\":\"not signed in\"}", 401);
|
||||
return fw::JsonResponse("{\"user\":\"" + fw::json_escape(data["user"]) + "\"}");
|
||||
});
|
||||
|
||||
services.add_feature("CSRF token form", "/security/csrf");
|
||||
services.add_feature("CORS preflight allowlist", "/security/cors");
|
||||
services.add_feature("Rate limiter (429 + Retry-After)", "/security/rate");
|
||||
services.add_feature("Security headers", "/security/headers");
|
||||
services.add_feature("CSP nonce page", "/csp/page");
|
||||
services.add_feature("CSP report endpoint", "/csp/report");
|
||||
services.add_feature("SHA-256 and HMAC", "/crypto/hash");
|
||||
services.add_feature("Secure random token", "/crypto/random");
|
||||
services.add_feature("Password hashing (demo)", "/crypto/password");
|
||||
services.add_feature("Roles and permissions", "/security/roles");
|
||||
services.add_feature("Secrets provider (masked)", "/security/secrets");
|
||||
services.add_feature("Upload validation", "/security/upload");
|
||||
services.add_feature("SQL and path guard", "/security/guard");
|
||||
services.add_feature("Denial sink", "/security/denials");
|
||||
services.add_feature("Login form with session cookie", "/security/login");
|
||||
}
|
||||
|
||||
} // namespace molo::example::app
|
||||
Reference in New Issue
Block a user