105 route tests, matrix crawl, spec and README updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
692 lines
31 KiB
C++
692 lines
31 KiB
C++
#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
|