Files
moloapp/example/app/SecurityExtraDemo.cpp
T

431 lines
20 KiB
C++
Raw Normal View History

#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