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:
@@ -0,0 +1,544 @@
|
||||
#include "Enterprise.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <regex>
|
||||
#include <sstream>
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace {
|
||||
|
||||
std::uint32_t rotr(std::uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
|
||||
|
||||
std::vector<std::string> split(const std::string& s, char sep) {
|
||||
std::vector<std::string> out;
|
||||
std::string cur;
|
||||
for (char c : s) {
|
||||
if (c == sep) {
|
||||
out.push_back(cur);
|
||||
cur.clear();
|
||||
} else {
|
||||
cur += c;
|
||||
}
|
||||
}
|
||||
out.push_back(cur);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string trim(const std::string& s) {
|
||||
std::size_t a = s.find_first_not_of(" \t\r\n");
|
||||
if (a == std::string::npos) return "";
|
||||
return s.substr(a, s.find_last_not_of(" \t\r\n") - a + 1);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string sha256_hex(const std::string& data) {
|
||||
static const std::uint32_t k[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
|
||||
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
||||
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
|
||||
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
||||
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
||||
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
|
||||
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
std::string msg = data;
|
||||
const std::uint64_t bits = static_cast<std::uint64_t>(data.size()) * 8;
|
||||
msg += static_cast<char>(0x80);
|
||||
while (msg.size() % 64 != 56) msg += '\0';
|
||||
for (int i = 7; i >= 0; --i) msg += static_cast<char>((bits >> (i * 8)) & 0xff);
|
||||
for (std::size_t off = 0; off < msg.size(); off += 64) {
|
||||
std::uint32_t w[64];
|
||||
for (int i = 0; i < 16; ++i)
|
||||
w[i] = (static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + i * 4])) << 24) |
|
||||
(static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + i * 4 + 1])) << 16) |
|
||||
(static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + i * 4 + 2])) << 8) |
|
||||
static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + i * 4 + 3]));
|
||||
for (int i = 16; i < 64; ++i) {
|
||||
std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5],
|
||||
g = h[6], hh = h[7];
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
std::uint32_t s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
||||
std::uint32_t ch = (e & f) ^ (~e & g);
|
||||
std::uint32_t t1 = hh + s1 + ch + k[i] + w[i];
|
||||
std::uint32_t s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
||||
std::uint32_t mj = (a & b) ^ (a & c) ^ (b & c);
|
||||
std::uint32_t t2 = s0 + mj;
|
||||
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||
}
|
||||
static const char* hex = "0123456789abcdef";
|
||||
std::string out;
|
||||
for (std::uint32_t v : h)
|
||||
for (int i = 28; i >= 0; i -= 4) out += hex[(v >> i) & 0xf];
|
||||
return out;
|
||||
}
|
||||
|
||||
Response problem_response(int status, const std::string& title,
|
||||
const std::string& detail,
|
||||
const std::string& instance) {
|
||||
std::string body = "{\"type\":\"about:blank\",\"title\":\"" + json_escape(title) +
|
||||
"\",\"status\":" + std::to_string(status) +
|
||||
",\"detail\":\"" + json_escape(detail) + "\"";
|
||||
if (!instance.empty()) body += ",\"instance\":\"" + json_escape(instance) + "\"";
|
||||
body += "}";
|
||||
return Response(status, body, "application/problem+json");
|
||||
}
|
||||
|
||||
// ---- tenancy ---------------------------------------------------------------
|
||||
bool TenantResolver::valid_id(const std::string& id) {
|
||||
if (id.size() < 2 || id.size() > 32) return false;
|
||||
for (char c : id)
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) return false;
|
||||
return id.front() != '-' && id.back() != '-';
|
||||
}
|
||||
|
||||
TenantRef TenantResolver::resolve(const Request& req,
|
||||
const std::string& path_tenant) const {
|
||||
TenantRef ref;
|
||||
std::string host = req.headers.get("Host");
|
||||
if (req.headers.has("X-Tenant-ID")) {
|
||||
ref.id = req.headers.get("X-Tenant-ID");
|
||||
ref.source = "header";
|
||||
} else if (!path_tenant.empty()) {
|
||||
ref.id = path_tenant;
|
||||
ref.source = "path";
|
||||
} else if (std::count(host.begin(), host.end(), '.') >= 2) {
|
||||
ref.id = host.substr(0, host.find('.'));
|
||||
ref.source = "subdomain";
|
||||
} else {
|
||||
ref.id = kDefaultTenant;
|
||||
ref.source = "default";
|
||||
}
|
||||
if (!valid_id(ref.id)) ref.error = "tenant id must be 2-32 chars of a-z, 0-9, '-'";
|
||||
return ref;
|
||||
}
|
||||
|
||||
TenantCatalog::TenantCatalog() {
|
||||
tenants_["demo"] = {"demo", "Demo Inc", "free"};
|
||||
tenants_["acme"] = {"acme", "Acme Corp", "pro"};
|
||||
tenants_["globex"] = {"globex", "Globex", "free"};
|
||||
}
|
||||
|
||||
const Tenant* TenantCatalog::find(const std::string& id) const {
|
||||
auto it = tenants_.find(id);
|
||||
return it == tenants_.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
std::string TenantCatalog::provision(const std::string& id, const std::string& name,
|
||||
const std::string& plan) {
|
||||
if (!TenantResolver::valid_id(id)) return "bad id";
|
||||
if (tenants_.count(id)) return "exists";
|
||||
if (tenants_.size() >= kMaxTenants) return "tenant cap reached";
|
||||
tenants_[id] = {id, name, plan};
|
||||
return "";
|
||||
}
|
||||
|
||||
std::vector<Tenant> TenantCatalog::list() const {
|
||||
std::vector<Tenant> out;
|
||||
for (const auto& [k, v] : tenants_) out.push_back(v);
|
||||
return out;
|
||||
}
|
||||
|
||||
bool TenantData::add(const std::string& tenant, const std::string& item) {
|
||||
auto& rows = rows_[tenant];
|
||||
if (rows.size() >= kMaxPerTenant) return false;
|
||||
rows.push_back(item);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::string> TenantData::list(const std::string& tenant) const {
|
||||
auto it = rows_.find(tenant);
|
||||
return it == rows_.end() ? std::vector<std::string>{} : it->second;
|
||||
}
|
||||
|
||||
std::size_t TenantQuota::limit_for(const std::string& plan) {
|
||||
return plan == "pro" ? 10 : 3;
|
||||
}
|
||||
|
||||
bool TenantQuota::consume(const std::string& tenant, const std::string& plan) {
|
||||
auto& u = used_[tenant];
|
||||
if (u >= limit_for(plan)) return false;
|
||||
++u;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::size_t TenantQuota::used(const std::string& tenant) const {
|
||||
auto it = used_.find(tenant);
|
||||
return it == used_.end() ? 0 : it->second;
|
||||
}
|
||||
|
||||
FeatureFlags::FeatureFlags() {
|
||||
defaults_ = {{"beta-ui", false}, {"export", true}, {"audit-log", true}};
|
||||
}
|
||||
|
||||
bool FeatureFlags::known(const std::string& flag) const {
|
||||
return defaults_.count(flag) > 0;
|
||||
}
|
||||
|
||||
bool FeatureFlags::enabled(const std::string& tenant, const std::string& flag) const {
|
||||
auto o = overrides_.find(tenant + "/" + flag);
|
||||
if (o != overrides_.end()) return o->second;
|
||||
auto d = defaults_.find(flag);
|
||||
return d != defaults_.end() && d->second;
|
||||
}
|
||||
|
||||
bool FeatureFlags::set(const std::string& tenant, const std::string& flag, bool on) {
|
||||
const std::string key = tenant + "/" + flag;
|
||||
if (!overrides_.count(key) && overrides_.size() >= kMaxOverrides) return false;
|
||||
overrides_[key] = on;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::map<std::string, bool> FeatureFlags::effective(const std::string& tenant) const {
|
||||
std::map<std::string, bool> out;
|
||||
for (const auto& [f, v] : defaults_) out[f] = enabled(tenant, f);
|
||||
return out;
|
||||
}
|
||||
|
||||
ConfigOverlay::ConfigOverlay() {
|
||||
base_ = {{"theme", "light"}, {"page_size", "20"}, {"locale", "en"}};
|
||||
}
|
||||
|
||||
bool ConfigOverlay::known(const std::string& key) const { return base_.count(key) > 0; }
|
||||
|
||||
bool ConfigOverlay::set(const std::string& tenant, const std::string& key,
|
||||
const std::string& value) {
|
||||
std::size_t total = 0;
|
||||
for (const auto& [t, m] : overlay_) total += m.size();
|
||||
if (total >= kMaxOverrides && !overlay_[tenant].count(key)) return false;
|
||||
overlay_[tenant][key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> ConfigOverlay::effective(const std::string& tenant) const {
|
||||
auto out = base_;
|
||||
auto it = overlay_.find(tenant);
|
||||
if (it != overlay_.end())
|
||||
for (const auto& [k, v] : it->second) out[k] = v;
|
||||
return out;
|
||||
}
|
||||
|
||||
void TenantMetrics::inc(const std::string& tenant, const std::string& name) {
|
||||
++counters_[tenant][name];
|
||||
}
|
||||
|
||||
std::map<std::string, std::map<std::string, std::uint64_t>> TenantMetrics::all() const {
|
||||
return counters_;
|
||||
}
|
||||
|
||||
// ---- audit -----------------------------------------------------------------
|
||||
std::string AuditChain::hash_of(const AuditRecord& r) {
|
||||
return sha256_hex(std::to_string(r.index) + "|" + r.actor + "|" + r.action + "|" +
|
||||
r.subject + "|" + r.detail + "|" + r.prev);
|
||||
}
|
||||
|
||||
bool AuditChain::append(const std::string& actor, const std::string& action,
|
||||
const std::string& subject, const std::string& detail) {
|
||||
if (records_.size() >= kMaxRecords) return false;
|
||||
AuditRecord r;
|
||||
r.index = records_.size();
|
||||
r.actor = actor;
|
||||
r.action = action;
|
||||
r.subject = subject;
|
||||
r.detail = detail;
|
||||
r.prev = records_.empty() ? std::string(64, '0') : records_.back().hash;
|
||||
r.hash = hash_of(r);
|
||||
records_.push_back(r);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<std::size_t> AuditChain::verify() const {
|
||||
std::string prev(64, '0');
|
||||
for (const auto& r : records_) {
|
||||
if (r.prev != prev || hash_of(r) != r.hash) return r.index;
|
||||
prev = r.hash;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool AuditChain::tamper(std::size_t index) {
|
||||
if (index >= records_.size()) return false;
|
||||
records_[index].detail += " (edited)";
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string PiiMasker::mask_email(const std::string& v) {
|
||||
auto at = v.find('@');
|
||||
if (at == std::string::npos || at == 0) return std::string(v.size(), '*');
|
||||
return v.substr(0, 1) + std::string(at - 1, '*') + v.substr(at);
|
||||
}
|
||||
|
||||
std::string PiiMasker::mask_card(const std::string& v) {
|
||||
std::string digits;
|
||||
for (char c : v)
|
||||
if (c >= '0' && c <= '9') digits += c;
|
||||
if (digits.size() < 4) return std::string(digits.size(), '*');
|
||||
return std::string(digits.size() - 4, '*') + digits.substr(digits.size() - 4);
|
||||
}
|
||||
|
||||
std::string PiiMasker::redact(const std::string& text, std::size_t* hits) {
|
||||
static const std::vector<std::pair<std::regex, std::string>> patterns = {
|
||||
{std::regex(R"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})"), "[EMAIL]"},
|
||||
{std::regex(R"(\b(?:\d[ -]?){13,16}\b)"), "[CARD]"},
|
||||
{std::regex(R"(\b\d{3}-\d{2}-\d{4}\b)"), "[SSN]"},
|
||||
{std::regex(R"(\b\d{1,3}(?:\.\d{1,3}){3}\b)"), "[IP]"}};
|
||||
std::string out = text.substr(0, 2000);
|
||||
std::size_t n = 0;
|
||||
for (const auto& [re, tag] : patterns) {
|
||||
n += static_cast<std::size_t>(std::distance(
|
||||
std::sregex_iterator(out.begin(), out.end(), re), std::sregex_iterator()));
|
||||
out = std::regex_replace(out, re, tag);
|
||||
}
|
||||
if (hits) *hits = n;
|
||||
return out;
|
||||
}
|
||||
|
||||
RetentionStore::RetentionStore() {
|
||||
entries_ = {{"r1", "session", 45, false}, {"r2", "session", 3, false},
|
||||
{"r3", "invoice", 400, false}, {"r4", "invoice", 3000, false},
|
||||
{"r5", "log", 120, false}};
|
||||
}
|
||||
|
||||
int RetentionStore::max_age(const std::string& klass) {
|
||||
if (klass == "session") return 30;
|
||||
if (klass == "log") return 90;
|
||||
return 2555; // invoice: 7 years
|
||||
}
|
||||
|
||||
bool RetentionStore::set_hold(const std::string& id, bool hold) {
|
||||
for (auto& e : entries_)
|
||||
if (e.id == id) {
|
||||
e.hold = hold;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::string> RetentionStore::expired() const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& e : entries_)
|
||||
if (!e.hold && e.age_days > max_age(e.klass)) out.push_back(e.id);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::size_t RetentionStore::purge() {
|
||||
auto ids = expired();
|
||||
entries_.erase(std::remove_if(entries_.begin(), entries_.end(),
|
||||
[&](const RetentionEntry& e) {
|
||||
return std::find(ids.begin(), ids.end(), e.id) != ids.end();
|
||||
}),
|
||||
entries_.end());
|
||||
return ids.size();
|
||||
}
|
||||
|
||||
SubjectStore::SubjectStore() {
|
||||
tables_["profiles"] = {{"ada@example.com", "name=Ada"}, {"bob@example.com", "name=Bob"}};
|
||||
tables_["orders"] = {{"ada@example.com", "order=1001"}, {"ada@example.com", "order=1002"},
|
||||
{"bob@example.com", "order=2001"}};
|
||||
tables_["sessions"] = {{"ada@example.com", "ip=[IP]"}};
|
||||
}
|
||||
|
||||
std::map<std::string, std::vector<std::string>> SubjectStore::export_for(
|
||||
const std::string& subject) const {
|
||||
std::map<std::string, std::vector<std::string>> out;
|
||||
for (const auto& [t, rows] : tables_)
|
||||
for (const auto& [s, d] : rows)
|
||||
if (s == subject) out[t].push_back(d);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::size_t SubjectStore::erase(const std::string& subject) {
|
||||
std::size_t n = 0;
|
||||
for (auto& [t, rows] : tables_) {
|
||||
auto before = rows.size();
|
||||
rows.erase(std::remove_if(rows.begin(), rows.end(),
|
||||
[&](const auto& r) { return r.first == subject; }),
|
||||
rows.end());
|
||||
n += before - rows.size();
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---- governance ------------------------------------------------------------
|
||||
std::string ApiKeyStore::issue(const std::string& owner, const std::string& tier,
|
||||
const std::set<std::string>& scopes,
|
||||
std::string* id_out) {
|
||||
if (keys_.size() >= kMaxKeys) return "";
|
||||
++counter_;
|
||||
std::string secret = sha256_hex("molo-key|" + owner + "|" + std::to_string(counter_));
|
||||
std::string key = "mk_" + secret.substr(0, 32);
|
||||
ApiKeyInfo info;
|
||||
info.id = "key" + std::to_string(counter_);
|
||||
info.owner = owner;
|
||||
info.tier = tier;
|
||||
info.scopes = scopes;
|
||||
info.hash = sha256_hex(key);
|
||||
keys_.push_back(info);
|
||||
if (id_out) *id_out = info.id;
|
||||
return key;
|
||||
}
|
||||
|
||||
bool ApiKeyStore::revoke(const std::string& id) {
|
||||
for (auto& k : keys_)
|
||||
if (k.id == id) {
|
||||
k.revoked = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
KeyResult ApiKeyStore::authenticate(const std::string& key, const std::string& scope,
|
||||
const ApiKeyInfo** info) const {
|
||||
if (key.empty()) return KeyResult::Missing;
|
||||
const std::string h = sha256_hex(key);
|
||||
for (const auto& k : keys_) {
|
||||
if (k.hash != h) continue;
|
||||
if (info) *info = &k;
|
||||
if (k.revoked) return KeyResult::Revoked;
|
||||
if (!scope.empty() && !k.scopes.count(scope)) return KeyResult::Forbidden;
|
||||
return KeyResult::Ok;
|
||||
}
|
||||
return KeyResult::Unknown;
|
||||
}
|
||||
|
||||
TierPolicy TierTable::find(const std::string& tier) {
|
||||
if (tier == "pro") return {"pro", 10};
|
||||
return {"free", 3};
|
||||
}
|
||||
|
||||
bool QuotaLedger::charge(const std::string& key_id, const TierPolicy& policy) {
|
||||
auto& u = used_[key_id];
|
||||
if (u < policy.per_min * 100) ++u; // hard cap on the counter itself
|
||||
return u <= policy.per_min;
|
||||
}
|
||||
|
||||
std::size_t QuotaLedger::used(const std::string& key_id) const {
|
||||
auto it = used_.find(key_id);
|
||||
return it == used_.end() ? 0 : it->second;
|
||||
}
|
||||
|
||||
void QuotaLedger::headers(const std::string& key_id, const TierPolicy& policy,
|
||||
Headers& out) const {
|
||||
std::size_t u = used(key_id);
|
||||
std::size_t remaining = u >= policy.per_min ? 0 : policy.per_min - u;
|
||||
out.set("X-Tier", policy.name);
|
||||
out.set("X-RateLimit-Limit", std::to_string(policy.per_min));
|
||||
out.set("X-RateLimit-Remaining", std::to_string(remaining));
|
||||
out.set("X-RateLimit-Reset", "60");
|
||||
if (u > policy.per_min) out.set("Retry-After", "60");
|
||||
}
|
||||
|
||||
VersionTable::VersionTable() {
|
||||
versions_ = {{"v1", true, "Sat, 31 Dec 2033 23:59:59 GMT", "/v2"},
|
||||
{"v2", false, "", ""}};
|
||||
}
|
||||
|
||||
const ApiVersion* VersionTable::find(const std::string& name) const {
|
||||
for (const auto& v : versions_)
|
||||
if (v.name == name) return &v;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void VersionTable::annotate(const std::string& name, Headers& out) const {
|
||||
const ApiVersion* v = find(name);
|
||||
if (!v) return;
|
||||
out.set("X-API-Version", v->name);
|
||||
if (!v->deprecated) return;
|
||||
out.set("Deprecation", "true");
|
||||
if (!v->sunset.empty()) out.set("Sunset", v->sunset);
|
||||
if (!v->successor.empty())
|
||||
out.set("Link", "<" + v->successor + "/items>; rel=\"successor-version\"");
|
||||
}
|
||||
|
||||
std::vector<LintFinding> RouteLinter::lint(const std::vector<std::string>& paths) {
|
||||
static const std::vector<std::string> verbs = {"get", "create", "delete", "update",
|
||||
"fetch", "remove"};
|
||||
std::vector<LintFinding> out;
|
||||
std::size_t n = 0;
|
||||
for (const auto& p : paths) {
|
||||
if (++n > kMaxPaths) break;
|
||||
if (p.size() > 1 && p.back() == '/') out.push_back({p, "no-trailing-slash"});
|
||||
for (char c : p)
|
||||
if (c >= 'A' && c <= 'Z') {
|
||||
out.push_back({p, "lowercase-only"});
|
||||
break;
|
||||
}
|
||||
if (p.find('_') != std::string::npos) out.push_back({p, "kebab-case"});
|
||||
for (const auto& seg : split(p, '/'))
|
||||
if (std::find(verbs.begin(), verbs.end(), seg) != verbs.end()) {
|
||||
out.push_back({p, "no-verbs-in-path"});
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct Op {
|
||||
std::set<std::string> required, optional;
|
||||
};
|
||||
|
||||
std::map<std::string, Op> parse_snapshot(const std::string& s) {
|
||||
std::map<std::string, Op> ops;
|
||||
std::size_t lines = 0;
|
||||
for (const auto& raw : split(s, '\n')) {
|
||||
std::string line = trim(raw);
|
||||
if (line.empty()) continue;
|
||||
if (++lines > SpecDiffer::kMaxLines) break;
|
||||
std::istringstream in(line);
|
||||
std::string method, path, tok;
|
||||
in >> method >> path;
|
||||
Op op;
|
||||
while (in >> tok) {
|
||||
auto eq = tok.find('=');
|
||||
if (eq == std::string::npos) continue;
|
||||
auto names = split(tok.substr(eq + 1), ',');
|
||||
auto& dst = tok.substr(0, eq) == "required" ? op.required : op.optional;
|
||||
for (auto& n : names)
|
||||
if (!n.empty()) dst.insert(n);
|
||||
}
|
||||
ops[method + " " + path] = op;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<DiffFinding> SpecDiffer::diff(const std::string& before,
|
||||
const std::string& after) {
|
||||
auto a = parse_snapshot(before);
|
||||
auto b = parse_snapshot(after);
|
||||
std::vector<DiffFinding> out;
|
||||
for (const auto& [name, op] : a) {
|
||||
auto it = b.find(name);
|
||||
if (it == b.end()) {
|
||||
out.push_back({"breaking", name, "operation removed"});
|
||||
continue;
|
||||
}
|
||||
for (const auto& r : it->second.required)
|
||||
if (!op.required.count(r))
|
||||
out.push_back({"breaking", name, "new required parameter " + r});
|
||||
for (const auto& r : op.required)
|
||||
if (!it->second.required.count(r) && !it->second.optional.count(r))
|
||||
out.push_back({"breaking", name, "parameter removed " + r});
|
||||
}
|
||||
for (const auto& [name, op] : b)
|
||||
if (!a.count(name)) out.push_back({"compatible", name, "operation added"});
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,269 @@
|
||||
#pragma once
|
||||
|
||||
// Enterprise framework skeleton for the living example: multi-tenancy, audit
|
||||
// and compliance, API governance. Every class is bounded by a hard cap.
|
||||
// Gaps versus the real modules are listed in the report of the owning plan:
|
||||
// src/tenancy/*, src/audit/*, src/governance/*.
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "Http.hpp"
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
// ---- shared helpers -------------------------------------------------------
|
||||
std::string sha256_hex(const std::string& data); // self-contained SHA-256
|
||||
|
||||
// RFC 7807 problem+json (mirrors src/governance/problem.h).
|
||||
Response problem_response(int status, const std::string& title,
|
||||
const std::string& detail,
|
||||
const std::string& instance = "");
|
||||
|
||||
// ---- multi-tenancy (src/tenancy) -----------------------------------------
|
||||
struct TenantRef {
|
||||
std::string id;
|
||||
std::string source; // header, path, subdomain, default
|
||||
std::string error; // non-empty when the id is malformed
|
||||
};
|
||||
|
||||
class TenantResolver {
|
||||
public:
|
||||
static constexpr const char* kDefaultTenant = "demo";
|
||||
static bool valid_id(const std::string& id);
|
||||
// Precedence: header X-Tenant-ID, then path param, then Host subdomain.
|
||||
TenantRef resolve(const Request& req, const std::string& path_tenant = "") const;
|
||||
};
|
||||
|
||||
struct Tenant {
|
||||
std::string id, name, plan; // plan: free or pro
|
||||
};
|
||||
|
||||
class TenantCatalog {
|
||||
public:
|
||||
static constexpr std::size_t kMaxTenants = 64;
|
||||
TenantCatalog();
|
||||
const Tenant* find(const std::string& id) const;
|
||||
// Returns empty on success, else the failure reason.
|
||||
std::string provision(const std::string& id, const std::string& name,
|
||||
const std::string& plan);
|
||||
std::vector<Tenant> list() const;
|
||||
|
||||
private:
|
||||
std::map<std::string, Tenant> tenants_;
|
||||
};
|
||||
|
||||
// Data isolation: every access is keyed by tenant id.
|
||||
class TenantData {
|
||||
public:
|
||||
static constexpr std::size_t kMaxPerTenant = 50;
|
||||
bool add(const std::string& tenant, const std::string& item);
|
||||
std::vector<std::string> list(const std::string& tenant) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::vector<std::string>> rows_;
|
||||
};
|
||||
|
||||
class TenantQuota {
|
||||
public:
|
||||
static std::size_t limit_for(const std::string& plan);
|
||||
bool consume(const std::string& tenant, const std::string& plan);
|
||||
std::size_t used(const std::string& tenant) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::size_t> used_;
|
||||
};
|
||||
|
||||
class FeatureFlags {
|
||||
public:
|
||||
static constexpr std::size_t kMaxOverrides = 128;
|
||||
FeatureFlags();
|
||||
bool enabled(const std::string& tenant, const std::string& flag) const;
|
||||
bool set(const std::string& tenant, const std::string& flag, bool on);
|
||||
bool known(const std::string& flag) const;
|
||||
std::map<std::string, bool> effective(const std::string& tenant) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, bool> defaults_;
|
||||
std::map<std::string, bool> overrides_; // "tenant/flag"
|
||||
};
|
||||
|
||||
class ConfigOverlay {
|
||||
public:
|
||||
static constexpr std::size_t kMaxOverrides = 128;
|
||||
ConfigOverlay();
|
||||
bool set(const std::string& tenant, const std::string& key,
|
||||
const std::string& value);
|
||||
std::map<std::string, std::string> effective(const std::string& tenant) const;
|
||||
bool known(const std::string& key) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> base_;
|
||||
std::map<std::string, std::map<std::string, std::string>> overlay_;
|
||||
};
|
||||
|
||||
class TenantMetrics {
|
||||
public:
|
||||
void inc(const std::string& tenant, const std::string& name);
|
||||
std::map<std::string, std::map<std::string, std::uint64_t>> all() const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::map<std::string, std::uint64_t>> counters_;
|
||||
};
|
||||
|
||||
// ---- audit and compliance (src/audit) ------------------------------------
|
||||
struct AuditRecord {
|
||||
std::size_t index = 0;
|
||||
std::string actor, action, subject, detail, prev, hash;
|
||||
};
|
||||
|
||||
class AuditChain {
|
||||
public:
|
||||
static constexpr std::size_t kMaxRecords = 500;
|
||||
// False when the cap is reached (append-only: never evicts).
|
||||
bool append(const std::string& actor, const std::string& action,
|
||||
const std::string& subject, const std::string& detail);
|
||||
// First index whose hash or link is wrong, or nullopt when intact.
|
||||
std::optional<std::size_t> verify() const;
|
||||
bool tamper(std::size_t index); // test hook: flips one detail
|
||||
const std::vector<AuditRecord>& records() const { return records_; }
|
||||
|
||||
private:
|
||||
static std::string hash_of(const AuditRecord& r);
|
||||
std::vector<AuditRecord> records_;
|
||||
};
|
||||
|
||||
class PiiMasker {
|
||||
public:
|
||||
static std::string mask_email(const std::string& v);
|
||||
static std::string mask_card(const std::string& v);
|
||||
// Redaction patterns over free text: email, card, ssn, ipv4.
|
||||
static std::string redact(const std::string& text, std::size_t* hits = nullptr);
|
||||
};
|
||||
|
||||
struct RetentionEntry {
|
||||
std::string id, klass;
|
||||
int age_days = 0;
|
||||
bool hold = false;
|
||||
};
|
||||
|
||||
class RetentionStore {
|
||||
public:
|
||||
RetentionStore();
|
||||
static int max_age(const std::string& klass); // policy per class
|
||||
bool set_hold(const std::string& id, bool hold);
|
||||
// Dry run reports; a real purge removes. Held entries are never touched.
|
||||
std::vector<std::string> expired() const;
|
||||
std::size_t purge();
|
||||
const std::vector<RetentionEntry>& entries() const { return entries_; }
|
||||
|
||||
private:
|
||||
std::vector<RetentionEntry> entries_;
|
||||
};
|
||||
|
||||
class SubjectStore {
|
||||
public:
|
||||
SubjectStore();
|
||||
// table -> list of rows for subject
|
||||
std::map<std::string, std::vector<std::string>> export_for(
|
||||
const std::string& subject) const;
|
||||
// Cascade erase across all tables, returns rows removed.
|
||||
std::size_t erase(const std::string& subject);
|
||||
|
||||
private:
|
||||
std::map<std::string, std::vector<std::pair<std::string, std::string>>> tables_;
|
||||
};
|
||||
|
||||
// ---- API governance (src/governance) -------------------------------------
|
||||
struct ApiKeyInfo {
|
||||
std::string id, owner, tier, hash;
|
||||
std::set<std::string> scopes;
|
||||
bool revoked = false;
|
||||
};
|
||||
|
||||
enum class KeyResult { Ok, Missing, Unknown, Revoked, Forbidden };
|
||||
|
||||
class ApiKeyStore {
|
||||
public:
|
||||
static constexpr std::size_t kMaxKeys = 64;
|
||||
// Returns the plaintext key once; only the hash is stored. Empty at cap.
|
||||
std::string issue(const std::string& owner, const std::string& tier,
|
||||
const std::set<std::string>& scopes, std::string* id_out);
|
||||
bool revoke(const std::string& id);
|
||||
KeyResult authenticate(const std::string& key, const std::string& scope,
|
||||
const ApiKeyInfo** info) const;
|
||||
std::size_t size() const { return keys_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<ApiKeyInfo> keys_;
|
||||
std::uint64_t counter_ = 0;
|
||||
};
|
||||
|
||||
struct TierPolicy {
|
||||
std::string name;
|
||||
std::size_t per_min = 0;
|
||||
};
|
||||
|
||||
class TierTable {
|
||||
public:
|
||||
static TierPolicy find(const std::string& tier);
|
||||
};
|
||||
|
||||
class QuotaLedger {
|
||||
public:
|
||||
// True when the call is within the tier budget; always counts the call.
|
||||
bool charge(const std::string& key_id, const TierPolicy& policy);
|
||||
std::size_t used(const std::string& key_id) const;
|
||||
void headers(const std::string& key_id, const TierPolicy& policy,
|
||||
Headers& out) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::size_t> used_;
|
||||
};
|
||||
|
||||
struct ApiVersion {
|
||||
std::string name;
|
||||
bool deprecated = false;
|
||||
std::string sunset; // HTTP date
|
||||
std::string successor; // path prefix
|
||||
};
|
||||
|
||||
class VersionTable {
|
||||
public:
|
||||
VersionTable();
|
||||
const ApiVersion* find(const std::string& name) const;
|
||||
void annotate(const std::string& name, Headers& out) const;
|
||||
const std::vector<ApiVersion>& all() const { return versions_; }
|
||||
|
||||
private:
|
||||
std::vector<ApiVersion> versions_;
|
||||
};
|
||||
|
||||
struct LintFinding {
|
||||
std::string path, rule;
|
||||
};
|
||||
|
||||
class RouteLinter {
|
||||
public:
|
||||
static constexpr std::size_t kMaxPaths = 100;
|
||||
static std::vector<LintFinding> lint(const std::vector<std::string>& paths);
|
||||
};
|
||||
|
||||
struct DiffFinding {
|
||||
std::string kind, operation; // kind: breaking or compatible
|
||||
std::string detail;
|
||||
};
|
||||
|
||||
class SpecDiffer {
|
||||
public:
|
||||
static constexpr std::size_t kMaxLines = 200;
|
||||
// Snapshot line: "METHOD /path required=a,b optional=c"
|
||||
static std::vector<DiffFinding> diff(const std::string& before,
|
||||
const std::string& after);
|
||||
};
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,695 @@
|
||||
#include "Platform.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string lower(std::string s) {
|
||||
for (char& c : s) c = (char)std::tolower((unsigned char)c);
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string trim(const std::string& s) {
|
||||
std::size_t a = s.find_first_not_of(" \t");
|
||||
if (a == std::string::npos) return "";
|
||||
return s.substr(a, s.find_last_not_of(" \t") - a + 1);
|
||||
}
|
||||
|
||||
std::vector<std::string> split(const std::string& s, char sep) {
|
||||
std::vector<std::string> out;
|
||||
std::size_t start = 0;
|
||||
while (true) {
|
||||
std::size_t at = s.find(sep, start);
|
||||
out.push_back(trim(s.substr(start, at == std::string::npos ? at : at - start)));
|
||||
if (at == std::string::npos) break;
|
||||
start = at + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// "gzip;q=0.5" -> token "gzip", q 0.5. Missing q is 1.
|
||||
void token_q(const std::string& part, std::string& token, double& q) {
|
||||
std::size_t semi = part.find(';');
|
||||
token = lower(trim(part.substr(0, semi)));
|
||||
q = 1.0;
|
||||
if (semi == std::string::npos) return;
|
||||
std::string rest = lower(trim(part.substr(semi + 1)));
|
||||
if (rest.rfind("q=", 0) == 0) q = std::atof(rest.c_str() + 2);
|
||||
}
|
||||
|
||||
bool parse_size(const std::string& s, std::size_t& out) {
|
||||
if (s.empty() || s.size() > 15) return false;
|
||||
std::size_t v = 0;
|
||||
for (char c : s) {
|
||||
if (c < '0' || c > '9') return false;
|
||||
v = v * 10 + (std::size_t)(c - '0');
|
||||
}
|
||||
out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string hex_pad(unsigned long long v, std::size_t digits) {
|
||||
char buf[40];
|
||||
std::snprintf(buf, sizeof(buf), "%0*llx", (int)digits, v);
|
||||
std::string s = buf;
|
||||
return s.substr(s.size() - digits);
|
||||
}
|
||||
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---- i18n -----------------------------------------------------------------
|
||||
|
||||
int PluralRule::forms(const std::string& locale) {
|
||||
if (locale == "ru") return 3;
|
||||
if (locale == "ja") return 1;
|
||||
return 2;
|
||||
}
|
||||
|
||||
int PluralRule::index(const std::string& locale, long n) {
|
||||
if (n < 0) n = -n;
|
||||
if (locale == "ja") return 0;
|
||||
if (locale == "fr") return n < 2 ? 0 : 1;
|
||||
if (locale == "ru") {
|
||||
if (n % 10 == 1 && n % 100 != 11) return 0;
|
||||
if (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)) return 1;
|
||||
return 2;
|
||||
}
|
||||
return n == 1 ? 0 : 1;
|
||||
}
|
||||
|
||||
bool MessageCatalog::add(const std::string& locale, const std::string& msgid,
|
||||
std::vector<std::string> forms) {
|
||||
if (!data_.count(locale) && data_.size() >= platform_caps::kMaxLocales)
|
||||
return false;
|
||||
auto& msgs = data_[locale];
|
||||
if (!msgs.count(msgid) && msgs.size() >= platform_caps::kMaxMessages)
|
||||
return false;
|
||||
msgs[msgid] = std::move(forms);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string MessageCatalog::translate(const std::string& locale,
|
||||
const std::string& msgid, long n) const {
|
||||
for (const std::string& loc : {locale, default_}) {
|
||||
auto l = data_.find(loc);
|
||||
if (l == data_.end()) continue;
|
||||
auto m = l->second.find(msgid);
|
||||
if (m == l->second.end() || m->second.empty()) continue;
|
||||
std::size_t idx = (std::size_t)PluralRule::index(loc, n);
|
||||
const std::string& form = m->second[std::min(idx, m->second.size() - 1)];
|
||||
std::string out = form;
|
||||
std::size_t at = out.find("%d");
|
||||
if (at != std::string::npos) out.replace(at, 2, std::to_string(n));
|
||||
return out;
|
||||
}
|
||||
return msgid;
|
||||
}
|
||||
|
||||
std::vector<std::string> MessageCatalog::locales() const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& [k, v] : data_) out.push_back(k);
|
||||
return out;
|
||||
}
|
||||
|
||||
bool MessageCatalog::has_locale(const std::string& locale) const {
|
||||
return data_.count(locale) > 0;
|
||||
}
|
||||
|
||||
std::string MessageCatalog::to_po(const std::string& locale) const {
|
||||
auto l = data_.find(locale);
|
||||
std::string out = "msgid \"\"\nmsgstr \"\"\n\"Language: " + locale +
|
||||
"\\n\"\n\"Plural-Forms: nplurals=" +
|
||||
std::to_string(PluralRule::forms(locale)) + ";\\n\"\n";
|
||||
if (l == data_.end()) return out;
|
||||
for (const auto& [id, forms] : l->second) {
|
||||
out += "\nmsgid \"" + id + "\"\n";
|
||||
if (forms.size() == 1) {
|
||||
out += "msgstr \"" + forms[0] + "\"\n";
|
||||
} else {
|
||||
out += "msgid_plural \"" + id + "\"\n";
|
||||
for (std::size_t i = 0; i < forms.size(); ++i)
|
||||
out += "msgstr[" + std::to_string(i) + "] \"" + forms[i] + "\"\n";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void MessageCatalog::set_default(std::string locale) {
|
||||
default_ = std::move(locale);
|
||||
}
|
||||
const std::string& MessageCatalog::default_locale() const { return default_; }
|
||||
|
||||
std::string negotiate_locale(const std::string& lang_param,
|
||||
const std::string& accept_language,
|
||||
const MessageCatalog& catalog) {
|
||||
std::string forced = lower(lang_param);
|
||||
if (catalog.has_locale(forced)) return forced;
|
||||
std::string best = catalog.default_locale();
|
||||
double best_q = 0;
|
||||
for (const std::string& part : split(accept_language, ',')) {
|
||||
if (part.empty()) continue;
|
||||
std::string tag;
|
||||
double q;
|
||||
token_q(part, tag, q);
|
||||
std::string primary = tag.substr(0, tag.find('-'));
|
||||
std::string pick = catalog.has_locale(tag) ? tag
|
||||
: catalog.has_locale(primary) ? primary
|
||||
: "";
|
||||
if (!pick.empty() && q > best_q) {
|
||||
best = pick;
|
||||
best_q = q;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ---- compression ----------------------------------------------------------
|
||||
|
||||
std::uint32_t crc32(const std::string& data) {
|
||||
std::uint32_t crc = 0xFFFFFFFFu;
|
||||
for (unsigned char c : data) {
|
||||
crc ^= c;
|
||||
for (int k = 0; k < 8; ++k) crc = (crc >> 1) ^ (0xEDB88320u & (0u - (crc & 1u)));
|
||||
}
|
||||
return ~crc;
|
||||
}
|
||||
|
||||
namespace {
|
||||
void put_le32(std::string& out, std::uint32_t v) {
|
||||
for (int i = 0; i < 4; ++i) out.push_back((char)((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string gzip_stored(const std::string& data) {
|
||||
std::string out("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff", 10);
|
||||
std::size_t pos = 0;
|
||||
do {
|
||||
std::size_t n = std::min<std::size_t>(65535, data.size() - pos);
|
||||
bool last = pos + n >= data.size();
|
||||
out.push_back(last ? 1 : 0);
|
||||
out.push_back((char)(n & 0xFF));
|
||||
out.push_back((char)(n >> 8));
|
||||
out.push_back((char)(~n & 0xFF));
|
||||
out.push_back((char)((~n >> 8) & 0xFF));
|
||||
out.append(data, pos, n);
|
||||
pos += n;
|
||||
} while (pos < data.size());
|
||||
put_le32(out, crc32(data));
|
||||
put_le32(out, (std::uint32_t)data.size());
|
||||
return out;
|
||||
}
|
||||
|
||||
bool accepts_encoding(const std::string& accept_encoding,
|
||||
const std::string& coding) {
|
||||
bool star = false;
|
||||
for (const std::string& part : split(accept_encoding, ',')) {
|
||||
std::string tag;
|
||||
double q;
|
||||
token_q(part, tag, q);
|
||||
if (tag == coding) return q > 0;
|
||||
if (tag == "*" && q > 0) star = true;
|
||||
}
|
||||
return star;
|
||||
}
|
||||
|
||||
// ---- conditional GET and ranges -------------------------------------------
|
||||
|
||||
std::string make_etag(const std::string& body) {
|
||||
std::uint64_t h = 1469598103934665603ull;
|
||||
for (unsigned char c : body) {
|
||||
h ^= c;
|
||||
h *= 1099511628211ull;
|
||||
}
|
||||
return "\"" + hex_pad(h, 16) + "-" + std::to_string(body.size()) + "\"";
|
||||
}
|
||||
|
||||
bool etag_matches(const std::string& header, const std::string& etag) {
|
||||
if (trim(header) == "*") return true;
|
||||
for (std::string tag : split(header, ',')) {
|
||||
if (tag.rfind("W/", 0) == 0) tag = tag.substr(2);
|
||||
if (!tag.empty() && tag == etag) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ByteRange parse_range(const std::string& header, std::size_t size) {
|
||||
ByteRange r;
|
||||
if (header.rfind("bytes=", 0) != 0) return r;
|
||||
std::string spec = trim(header.substr(6));
|
||||
if (spec.find(',') != std::string::npos) return r;
|
||||
std::size_t dash = spec.find('-');
|
||||
if (dash == std::string::npos) return r;
|
||||
std::string a = spec.substr(0, dash), b = spec.substr(dash + 1);
|
||||
std::size_t first = 0, last = 0;
|
||||
if (a.empty()) {
|
||||
std::size_t n;
|
||||
if (!parse_size(b, n)) return r;
|
||||
r.kind = (n == 0 || size == 0) ? ByteRange::Kind::Unsatisfiable
|
||||
: ByteRange::Kind::Ok;
|
||||
if (r.kind == ByteRange::Kind::Ok) {
|
||||
r.first = n >= size ? 0 : size - n;
|
||||
r.last = size - 1;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
if (!parse_size(a, first)) return r;
|
||||
if (b.empty()) {
|
||||
last = size ? size - 1 : 0;
|
||||
} else if (!parse_size(b, last)) {
|
||||
return r;
|
||||
}
|
||||
if (first >= size || first > last) {
|
||||
r.kind = ByteRange::Kind::Unsatisfiable;
|
||||
return r;
|
||||
}
|
||||
r.kind = ByteRange::Kind::Ok;
|
||||
r.first = first;
|
||||
r.last = std::min(last, size - 1);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ---- health probes --------------------------------------------------------
|
||||
|
||||
bool HealthRegistry::add_check(const std::string& name, bool up) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (!checks_.count(name) && checks_.size() >= platform_caps::kMaxChecks)
|
||||
return false;
|
||||
checks_[name] = up;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::set_check(const std::string& name, bool up) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = checks_.find(name);
|
||||
if (it == checks_.end()) return false;
|
||||
it->second = up;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::add_startup_task(const std::string& name, bool done) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (!tasks_.count(name) && tasks_.size() >= platform_caps::kMaxChecks)
|
||||
return false;
|
||||
tasks_[name] = done;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::set_startup_task(const std::string& name, bool done) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = tasks_.find(name);
|
||||
if (it == tasks_.end()) return false;
|
||||
it->second = done;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::startup_complete() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
for (const auto& [k, v] : tasks_)
|
||||
if (!v) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HealthRegistry::ready() const {
|
||||
if (!startup_complete()) return false;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
for (const auto& [k, v] : checks_)
|
||||
if (!v) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::string bool_map_json(const std::map<std::string, bool>& m,
|
||||
const char* up, const char* down) {
|
||||
std::string out = "{";
|
||||
bool first = true;
|
||||
for (const auto& [k, v] : m) {
|
||||
out += std::string(first ? "" : ",") + "\"" + json_escape(k) + "\":\"" +
|
||||
(v ? up : down) + "\"";
|
||||
first = false;
|
||||
}
|
||||
return out + "}";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string HealthRegistry::liveness_json() const {
|
||||
long up = (long)std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::steady_clock::now() - started_)
|
||||
.count();
|
||||
return "{\"status\":\"alive\",\"uptime_seconds\":" + std::to_string(up) + "}";
|
||||
}
|
||||
|
||||
std::string HealthRegistry::readiness_json() const {
|
||||
bool ok = ready();
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return std::string("{\"status\":\"") + (ok ? "ready" : "not_ready") +
|
||||
"\",\"checks\":" + bool_map_json(checks_, "up", "down") + "}";
|
||||
}
|
||||
|
||||
std::string HealthRegistry::startup_json() const {
|
||||
bool ok = startup_complete();
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return std::string("{\"status\":\"") + (ok ? "started" : "starting") +
|
||||
"\",\"tasks\":" + bool_map_json(tasks_, "done", "pending") + "}";
|
||||
}
|
||||
|
||||
// ---- Prometheus -----------------------------------------------------------
|
||||
|
||||
PrometheusExporter::PrometheusExporter(const Metrics* metrics,
|
||||
const Stats* stats)
|
||||
: metrics_(metrics), stats_(stats) {}
|
||||
|
||||
std::string PrometheusExporter::sanitize(const std::string& name) {
|
||||
std::string out;
|
||||
for (char c : name) {
|
||||
bool ok = std::isalnum((unsigned char)c) || c == '_' || c == ':';
|
||||
out.push_back(ok ? c : '_');
|
||||
}
|
||||
if (out.empty() || std::isdigit((unsigned char)out[0])) out.insert(0, "_");
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string PrometheusExporter::render() const {
|
||||
std::string out;
|
||||
auto sample = [&out](const std::string& name, const char* type,
|
||||
const std::string& help, const std::string& value) {
|
||||
out += "# HELP " + name + " " + help + "\n# TYPE " + name + " " + type +
|
||||
"\n" + name + " " + value + "\n";
|
||||
};
|
||||
sample("molo_http_requests_total", "counter", "Requests served.",
|
||||
std::to_string(stats_->total_requests()));
|
||||
sample("molo_http_connections_total", "counter", "Connections accepted.",
|
||||
std::to_string(stats_->total_connections()));
|
||||
sample("molo_http_connections_active", "gauge", "Open connections.",
|
||||
std::to_string(stats_->active_connections()));
|
||||
for (const auto& [k, v] : metrics_->snapshot()) {
|
||||
char buf[64];
|
||||
std::snprintf(buf, sizeof(buf), "%g", v);
|
||||
sample("molo_example_" + sanitize(k), "gauge",
|
||||
"Example metric " + k + ".", buf);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- structured logging ---------------------------------------------------
|
||||
|
||||
bool parse_level(const std::string& name, LogLevel& out) {
|
||||
std::string n = lower(name);
|
||||
if (n == "debug") out = LogLevel::Debug;
|
||||
else if (n == "info") out = LogLevel::Info;
|
||||
else if (n == "warn") out = LogLevel::Warn;
|
||||
else if (n == "error") out = LogLevel::Error;
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string level_name(LogLevel level) {
|
||||
switch (level) {
|
||||
case LogLevel::Debug: return "debug";
|
||||
case LogLevel::Info: return "info";
|
||||
case LogLevel::Warn: return "warn";
|
||||
case LogLevel::Error: return "error";
|
||||
}
|
||||
return "info";
|
||||
}
|
||||
|
||||
std::string LogRing::redact(const std::string& message) {
|
||||
static const char* keys[] = {"password", "passwd", "token", "secret",
|
||||
"authorization", "api_key", "apikey"};
|
||||
std::string out = message;
|
||||
std::string low = lower(out);
|
||||
for (const char* key : keys) {
|
||||
std::string k = key;
|
||||
std::size_t from = 0;
|
||||
while ((from = low.find(k, from)) != std::string::npos) {
|
||||
std::size_t p = from + k.size();
|
||||
from = p;
|
||||
if (p >= out.size() || (out[p] != '=' && out[p] != ':')) continue;
|
||||
++p;
|
||||
while (p < out.size() && out[p] == ' ') ++p;
|
||||
std::size_t e = p;
|
||||
while (e < out.size() && !std::isspace((unsigned char)out[e]) &&
|
||||
out[e] != ',' && out[e] != ';' && out[e] != '&')
|
||||
++e;
|
||||
out.replace(p, e - p, "***");
|
||||
low = lower(out);
|
||||
from = p;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void LogRing::log(LogLevel level, std::string message,
|
||||
std::string correlation_id) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (level < min_) {
|
||||
++filtered_;
|
||||
return;
|
||||
}
|
||||
LogRecord r;
|
||||
r.seq = next_seq_++;
|
||||
r.ts = (long)std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
r.level = level;
|
||||
if (message.size() > platform_caps::kLogMessage)
|
||||
message.resize(platform_caps::kLogMessage);
|
||||
r.message = redact(message);
|
||||
r.correlation_id = std::move(correlation_id);
|
||||
ring_.push_back(std::move(r));
|
||||
while (ring_.size() > platform_caps::kLogRing) ring_.pop_front();
|
||||
}
|
||||
|
||||
std::vector<LogRecord> LogRing::last(std::size_t n, LogLevel min) const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
std::vector<LogRecord> out;
|
||||
for (auto it = ring_.rbegin(); it != ring_.rend() && out.size() < n; ++it)
|
||||
if (it->level >= min) out.push_back(*it);
|
||||
return out;
|
||||
}
|
||||
|
||||
void LogRing::set_min_level(LogLevel level) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
min_ = level;
|
||||
}
|
||||
LogLevel LogRing::min_level() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return min_;
|
||||
}
|
||||
std::size_t LogRing::size() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return ring_.size();
|
||||
}
|
||||
unsigned long LogRing::dropped_below_min() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return filtered_;
|
||||
}
|
||||
|
||||
std::string LogRing::to_json(const LogRecord& r) {
|
||||
return "{\"seq\":" + std::to_string(r.seq) + ",\"ts\":" +
|
||||
std::to_string(r.ts) + ",\"level\":\"" + level_name(r.level) +
|
||||
"\",\"msg\":\"" + json_escape(r.message) + "\",\"correlation_id\":\"" +
|
||||
json_escape(r.correlation_id) + "\"}";
|
||||
}
|
||||
|
||||
// ---- trace context --------------------------------------------------------
|
||||
|
||||
std::string TraceContext::traceparent() const {
|
||||
return "00-" + trace_id + "-" + span_id + "-" + flags;
|
||||
}
|
||||
|
||||
std::string TraceContextFactory::next_hex(std::size_t digits) {
|
||||
unsigned long long v = ++counter_;
|
||||
v *= 0x9E3779B97F4A7C15ull;
|
||||
std::string out = hex_pad(v, 16);
|
||||
while (out.size() < digits) out += hex_pad(v * (out.size() + 7), 16);
|
||||
return out.substr(0, digits);
|
||||
}
|
||||
|
||||
TraceContext TraceContextFactory::from_header(const std::string& header) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
TraceContext ctx;
|
||||
ctx.had_parent = !header.empty();
|
||||
auto parts = split(header, '-');
|
||||
auto is_hex = [](const std::string& s) {
|
||||
return !s.empty() && std::all_of(s.begin(), s.end(), [](char c) {
|
||||
return std::isxdigit((unsigned char)c) && !std::isupper((unsigned char)c);
|
||||
});
|
||||
};
|
||||
bool ok = parts.size() == 4 && parts[0].size() == 2 && is_hex(parts[0]) &&
|
||||
parts[0] != "ff" && parts[1].size() == 32 && is_hex(parts[1]) &&
|
||||
parts[1] != std::string(32, '0') && parts[2].size() == 16 &&
|
||||
is_hex(parts[2]) && parts[2] != std::string(16, '0') &&
|
||||
parts[3].size() == 2 && is_hex(parts[3]);
|
||||
if (ok) {
|
||||
ctx.trace_id = parts[1];
|
||||
ctx.parent_span_id = parts[2];
|
||||
ctx.flags = parts[3];
|
||||
} else {
|
||||
ctx.parent_valid = !ctx.had_parent;
|
||||
ctx.trace_id = next_hex(32);
|
||||
}
|
||||
ctx.span_id = next_hex(16);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// ---- DI registry ----------------------------------------------------------
|
||||
|
||||
std::string lifetime_name(Lifetime l) {
|
||||
switch (l) {
|
||||
case Lifetime::Singleton: return "singleton";
|
||||
case Lifetime::Scoped: return "scoped";
|
||||
case Lifetime::Transient: return "transient";
|
||||
}
|
||||
return "singleton";
|
||||
}
|
||||
|
||||
bool ServiceRegistry::add(const std::string& name, Lifetime lifetime,
|
||||
std::function<std::string()> factory) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (!slots_.count(name) && slots_.size() >= platform_caps::kMaxServices)
|
||||
return false;
|
||||
Slot s;
|
||||
s.lifetime = lifetime;
|
||||
s.factory = std::move(factory);
|
||||
slots_[name] = std::move(s);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ServiceRegistry::resolve(const std::string& name, const std::string& scope,
|
||||
std::string& out) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = slots_.find(name);
|
||||
if (it == slots_.end()) return false;
|
||||
Slot& s = it->second;
|
||||
++s.resolved;
|
||||
if (s.lifetime == Lifetime::Singleton) {
|
||||
if (!s.built) {
|
||||
s.instance = s.factory();
|
||||
s.built = true;
|
||||
++s.created;
|
||||
}
|
||||
out = s.instance;
|
||||
} else if (s.lifetime == Lifetime::Scoped) {
|
||||
auto sc = s.scoped.find(scope);
|
||||
if (sc == s.scoped.end()) {
|
||||
if (s.scoped.size() >= 16) s.scoped.clear();
|
||||
sc = s.scoped.emplace(scope, s.factory()).first;
|
||||
++s.created;
|
||||
}
|
||||
out = sc->second;
|
||||
} else {
|
||||
out = s.factory();
|
||||
++s.created;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<ServiceRegistry::Entry> ServiceRegistry::list() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
std::vector<Entry> out;
|
||||
for (const auto& [k, s] : slots_)
|
||||
out.push_back({k, s.lifetime, s.created, s.resolved});
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- flash messages -------------------------------------------------------
|
||||
|
||||
std::string FlashCodec::encode(const std::string& message) {
|
||||
std::string m = message.substr(0, platform_caps::kFlashBytes);
|
||||
std::string out;
|
||||
for (unsigned char c : m) out += hex_pad(c, 2);
|
||||
return out;
|
||||
}
|
||||
|
||||
bool FlashCodec::decode(const std::string& cookie, std::string& message) {
|
||||
if (cookie.empty() || cookie.size() % 2 || cookie.size() > platform_caps::kFlashBytes * 2)
|
||||
return false;
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < cookie.size(); i += 2) {
|
||||
if (!std::isxdigit((unsigned char)cookie[i]) ||
|
||||
!std::isxdigit((unsigned char)cookie[i + 1]))
|
||||
return false;
|
||||
out.push_back((char)std::stoi(cookie.substr(i, 2), nullptr, 16));
|
||||
}
|
||||
message = out;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- expose stats ---------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
constexpr std::size_t kBuckets =
|
||||
(std::size_t)(platform_caps::kExposeWindowSec / platform_caps::kExposeBucketSec);
|
||||
}
|
||||
|
||||
ExposeStats::ExposeStats(long (*now_sec)()) : clock_(now_sec) {}
|
||||
|
||||
void ExposeStats::set_clock(long (*now_sec)()) { clock_ = now_sec; }
|
||||
|
||||
long ExposeStats::now() const {
|
||||
if (clock_) return clock_();
|
||||
return (long)std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
bool ExposeStats::known_method(const std::string& m) {
|
||||
static const char* names[] = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"};
|
||||
for (const char* n : names)
|
||||
if (m == n) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ExposeStats::record(const std::string& method, unsigned long up,
|
||||
unsigned long down, unsigned long micros) {
|
||||
if (!known_method(method)) return false;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
ExposeRow& row = rows_[method];
|
||||
++row.count;
|
||||
row.bytes_up += up;
|
||||
row.bytes_down += down;
|
||||
row.micros += micros;
|
||||
auto& win = windows_[method];
|
||||
if (win.empty()) win.resize(kBuckets);
|
||||
long slot = now() / platform_caps::kExposeBucketSec;
|
||||
Bucket& b = win[(std::size_t)slot % kBuckets];
|
||||
if (b.slot != slot) b = Bucket{slot, 0, 0};
|
||||
b.up += up;
|
||||
b.down += down;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::map<std::string, ExposeRow> ExposeStats::snapshot() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
std::map<std::string, ExposeRow> out;
|
||||
ExposeRow total;
|
||||
long cur = now() / platform_caps::kExposeBucketSec;
|
||||
for (const auto& [m, row] : rows_) {
|
||||
ExposeRow r = row;
|
||||
unsigned long up = 0, down = 0;
|
||||
for (const Bucket& b : windows_.at(m))
|
||||
if (b.slot > cur - (long)kBuckets && b.slot <= cur) {
|
||||
up += b.up;
|
||||
down += b.down;
|
||||
}
|
||||
r.kb_s_up = up / 1024.0 / platform_caps::kExposeWindowSec;
|
||||
r.kb_s_down = down / 1024.0 / platform_caps::kExposeWindowSec;
|
||||
total.count += r.count;
|
||||
total.bytes_up += r.bytes_up;
|
||||
total.bytes_down += r.bytes_down;
|
||||
total.micros += r.micros;
|
||||
total.kb_s_up += r.kb_s_up;
|
||||
total.kb_s_down += r.kb_s_down;
|
||||
out[m] = r;
|
||||
}
|
||||
out["_total"] = total;
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,272 @@
|
||||
#pragma once
|
||||
|
||||
// Platform framework skeleton for the living example (namespace molo::example::fw):
|
||||
// i18n, gzip negotiation, ETag and Range, health probes, Prometheus export,
|
||||
// structured log ring, W3C trace context, DI registry, flash cookies,
|
||||
// expose stats. Every store has a hard cap; past a cap input is rejected or
|
||||
// the oldest entry is dropped, never grown.
|
||||
// Gap: the real modules are src/cli/i18n, src/runtime/compress,
|
||||
// src/runtime/static/etag.*, src/cli/ops, src/observability, src/app/di,
|
||||
// src/app/views/flash.h and src/realtime/expose/stats.*.
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "App.hpp"
|
||||
#include "Http.hpp"
|
||||
#include "Observ.hpp"
|
||||
#include "Stats.hpp"
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace platform_caps {
|
||||
inline constexpr std::size_t kMaxLocales = 8;
|
||||
inline constexpr std::size_t kMaxMessages = 64;
|
||||
inline constexpr long kMaxPluralN = 1000000;
|
||||
inline constexpr std::size_t kMaxCompressBody = 65536;
|
||||
inline constexpr std::size_t kCompressMin = 256;
|
||||
inline constexpr std::size_t kMaxDocBytes = 4096;
|
||||
inline constexpr std::size_t kMaxChecks = 32;
|
||||
inline constexpr std::size_t kLogRing = 200;
|
||||
inline constexpr std::size_t kLogMessage = 500;
|
||||
inline constexpr std::size_t kMaxServices = 64;
|
||||
inline constexpr std::size_t kFlashBytes = 200;
|
||||
inline constexpr std::size_t kExposeMethods = 16;
|
||||
inline constexpr long kExposeWindowSec = 60;
|
||||
inline constexpr long kExposeBucketSec = 10;
|
||||
} // namespace platform_caps
|
||||
|
||||
// ---- i18n -----------------------------------------------------------------
|
||||
|
||||
class PluralRule {
|
||||
public:
|
||||
// Form index for count n in locale (en/nl/de: 2 forms, fr: 2, ru: 3, ja: 1).
|
||||
static int index(const std::string& locale, long n);
|
||||
static int forms(const std::string& locale);
|
||||
};
|
||||
|
||||
class MessageCatalog {
|
||||
public:
|
||||
bool add(const std::string& locale, const std::string& msgid,
|
||||
std::vector<std::string> forms);
|
||||
// Plural-aware lookup; falls back to the default locale, then the msgid.
|
||||
std::string translate(const std::string& locale, const std::string& msgid,
|
||||
long n = 1) const;
|
||||
std::vector<std::string> locales() const;
|
||||
bool has_locale(const std::string& locale) const;
|
||||
// gettext .po style dump of one locale.
|
||||
std::string to_po(const std::string& locale) const;
|
||||
void set_default(std::string locale);
|
||||
const std::string& default_locale() const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::map<std::string, std::vector<std::string>>> data_;
|
||||
std::string default_ = "en";
|
||||
};
|
||||
|
||||
// ?lang beats Accept-Language (q-weighted) beats the default.
|
||||
std::string negotiate_locale(const std::string& lang_param,
|
||||
const std::string& accept_language,
|
||||
const MessageCatalog& catalog);
|
||||
|
||||
// ---- compression ----------------------------------------------------------
|
||||
|
||||
std::uint32_t crc32(const std::string& data);
|
||||
// Valid gzip member using stored deflate blocks (same approach as
|
||||
// src/cli/embed/gzip_stored.cpp). Gap: no real LZ77 (src/runtime/compress/gzip.cpp).
|
||||
std::string gzip_stored(const std::string& data);
|
||||
bool accepts_encoding(const std::string& accept_encoding,
|
||||
const std::string& coding);
|
||||
|
||||
// ---- conditional GET and ranges -------------------------------------------
|
||||
|
||||
std::string make_etag(const std::string& body);
|
||||
// True when If-None-Match (list, weak tags, or *) matches etag.
|
||||
bool etag_matches(const std::string& header, const std::string& etag);
|
||||
|
||||
struct ByteRange {
|
||||
enum class Kind { None, Ok, Unsatisfiable } kind = Kind::None;
|
||||
std::size_t first = 0;
|
||||
std::size_t last = 0; // inclusive
|
||||
};
|
||||
// Single range only: "a-b", "a-", "-n". Multi-range is ignored (Kind::None).
|
||||
ByteRange parse_range(const std::string& header, std::size_t size);
|
||||
|
||||
// ---- health probes --------------------------------------------------------
|
||||
|
||||
class HealthRegistry {
|
||||
public:
|
||||
bool add_check(const std::string& name, bool up);
|
||||
bool set_check(const std::string& name, bool up);
|
||||
bool add_startup_task(const std::string& name, bool done);
|
||||
bool set_startup_task(const std::string& name, bool done);
|
||||
bool startup_complete() const;
|
||||
bool ready() const;
|
||||
std::string liveness_json() const;
|
||||
std::string readiness_json() const;
|
||||
std::string startup_json() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::map<std::string, bool> checks_;
|
||||
std::map<std::string, bool> tasks_;
|
||||
std::chrono::steady_clock::time_point started_ =
|
||||
std::chrono::steady_clock::now();
|
||||
};
|
||||
|
||||
// ---- Prometheus -----------------------------------------------------------
|
||||
|
||||
class PrometheusExporter {
|
||||
public:
|
||||
PrometheusExporter(const Metrics* metrics, const Stats* stats);
|
||||
// text exposition format 0.0.4: HELP, TYPE, samples.
|
||||
std::string render() const;
|
||||
static std::string sanitize(const std::string& name);
|
||||
|
||||
private:
|
||||
const Metrics* metrics_;
|
||||
const Stats* stats_;
|
||||
};
|
||||
|
||||
// ---- structured logging ---------------------------------------------------
|
||||
|
||||
enum class LogLevel { Debug = 0, Info = 1, Warn = 2, Error = 3 };
|
||||
bool parse_level(const std::string& name, LogLevel& out);
|
||||
std::string level_name(LogLevel level);
|
||||
|
||||
struct LogRecord {
|
||||
unsigned long seq = 0;
|
||||
long ts = 0;
|
||||
LogLevel level = LogLevel::Info;
|
||||
std::string message;
|
||||
std::string correlation_id;
|
||||
};
|
||||
|
||||
class LogRing {
|
||||
public:
|
||||
// Redacts secret=value style fields, caps the message, drops the oldest.
|
||||
void log(LogLevel level, std::string message, std::string correlation_id);
|
||||
std::vector<LogRecord> last(std::size_t n, LogLevel min) const;
|
||||
void set_min_level(LogLevel level);
|
||||
LogLevel min_level() const;
|
||||
std::size_t size() const;
|
||||
unsigned long dropped_below_min() const;
|
||||
static std::string redact(const std::string& message);
|
||||
static std::string to_json(const LogRecord& record);
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::deque<LogRecord> ring_;
|
||||
LogLevel min_ = LogLevel::Debug;
|
||||
unsigned long next_seq_ = 1;
|
||||
unsigned long filtered_ = 0;
|
||||
};
|
||||
|
||||
// ---- trace context --------------------------------------------------------
|
||||
|
||||
struct TraceContext {
|
||||
bool had_parent = false;
|
||||
bool parent_valid = true;
|
||||
std::string trace_id;
|
||||
std::string parent_span_id;
|
||||
std::string span_id;
|
||||
std::string flags = "01";
|
||||
std::string traceparent() const;
|
||||
};
|
||||
|
||||
class TraceContextFactory {
|
||||
public:
|
||||
// Continues a valid W3C traceparent, else starts a new trace.
|
||||
TraceContext from_header(const std::string& traceparent);
|
||||
|
||||
private:
|
||||
std::string next_hex(std::size_t digits);
|
||||
std::mutex mu_;
|
||||
unsigned long long counter_ = 0x1000;
|
||||
};
|
||||
|
||||
// ---- DI registry ----------------------------------------------------------
|
||||
|
||||
enum class Lifetime { Singleton, Scoped, Transient };
|
||||
std::string lifetime_name(Lifetime lifetime);
|
||||
|
||||
class ServiceRegistry {
|
||||
public:
|
||||
bool add(const std::string& name, Lifetime lifetime,
|
||||
std::function<std::string()> factory);
|
||||
// Singleton built once, scoped once per scope key (max 16 kept), transient
|
||||
// on every call.
|
||||
bool resolve(const std::string& name, const std::string& scope,
|
||||
std::string& out);
|
||||
struct Entry {
|
||||
std::string name;
|
||||
Lifetime lifetime;
|
||||
unsigned long created;
|
||||
unsigned long resolved;
|
||||
};
|
||||
std::vector<Entry> list() const;
|
||||
|
||||
private:
|
||||
struct Slot {
|
||||
Lifetime lifetime;
|
||||
std::function<std::string()> factory;
|
||||
std::string instance;
|
||||
std::map<std::string, std::string> scoped;
|
||||
bool built = false;
|
||||
unsigned long created = 0;
|
||||
unsigned long resolved = 0;
|
||||
};
|
||||
mutable std::mutex mu_;
|
||||
std::map<std::string, Slot> slots_;
|
||||
};
|
||||
|
||||
// ---- flash messages -------------------------------------------------------
|
||||
|
||||
class FlashCodec {
|
||||
public:
|
||||
static std::string encode(const std::string& message);
|
||||
static bool decode(const std::string& cookie, std::string& message);
|
||||
};
|
||||
|
||||
// ---- expose stats ---------------------------------------------------------
|
||||
|
||||
struct ExposeRow {
|
||||
unsigned long count = 0;
|
||||
unsigned long bytes_up = 0;
|
||||
unsigned long bytes_down = 0;
|
||||
unsigned long micros = 0;
|
||||
double kb_s_up = 0;
|
||||
double kb_s_down = 0;
|
||||
double avg_ms() const { return count ? micros / 1000.0 / count : 0.0; }
|
||||
};
|
||||
|
||||
class ExposeStats {
|
||||
public:
|
||||
explicit ExposeStats(long (*now_sec)() = nullptr);
|
||||
bool record(const std::string& method, unsigned long up,
|
||||
unsigned long down, unsigned long micros);
|
||||
// Rows by method plus "_total"; windowed kB/s over the last 60 s.
|
||||
std::map<std::string, ExposeRow> snapshot() const;
|
||||
void set_clock(long (*now_sec)());
|
||||
static bool known_method(const std::string& method);
|
||||
|
||||
private:
|
||||
struct Bucket {
|
||||
long slot = -1;
|
||||
unsigned long up = 0;
|
||||
unsigned long down = 0;
|
||||
};
|
||||
long now() const;
|
||||
mutable std::mutex mu_;
|
||||
long (*clock_)() = nullptr;
|
||||
std::map<std::string, ExposeRow> rows_;
|
||||
std::map<std::string, std::vector<Bucket>> windows_;
|
||||
};
|
||||
|
||||
} // namespace molo::example::fw
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,408 @@
|
||||
#pragma once
|
||||
|
||||
// Resilience, delivery, supply chain, clients and data-depth skeletons for the
|
||||
// living example (namespace molo::example::fw). Every class is a Lab: a small
|
||||
// self-contained state machine with injectable time, a bounded log, and a
|
||||
// uniform rows() view that the demo pages and the debug snapshot render.
|
||||
// Gaps are listed per class next to the real module in src/.
|
||||
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace labcaps {
|
||||
constexpr std::size_t kLogLines = 20; // bounded log per lab
|
||||
constexpr long kMaxAdvanceMs = 3600000; // one clock step, 1 hour
|
||||
constexpr int kMaxThreads = 16; // singleflight callers
|
||||
constexpr std::size_t kMaxEntries = 5; // ttl store capacity (LRU)
|
||||
constexpr std::size_t kMaxAdvisories = 8; // supplychain advisory db
|
||||
constexpr int kMaxAttempts = 5; // client retry ceiling
|
||||
constexpr int kMaxFaults = 5; // chaos blast radius (faults)
|
||||
constexpr int kMaxPercent = 50; // chaos blast radius (percent)
|
||||
} // namespace labcaps
|
||||
|
||||
using LabRows = std::vector<std::pair<std::string, std::string>>;
|
||||
|
||||
// Injectable time so every state machine is deterministic in tests.
|
||||
class ManualClock {
|
||||
public:
|
||||
long now() const { return now_; }
|
||||
void advance(long ms);
|
||||
|
||||
private:
|
||||
long now_ = 0;
|
||||
};
|
||||
|
||||
std::string fnv_hex(const std::string& data); // 64 bit FNV-1a, hex
|
||||
std::string base64_encode(const std::string& data);
|
||||
|
||||
class Lab {
|
||||
public:
|
||||
virtual ~Lab() = default;
|
||||
virtual std::string name() const = 0;
|
||||
virtual LabRows rows() const = 0;
|
||||
std::vector<std::string> log() const;
|
||||
std::string json() const; // {"name":..,"state":{..},"log":[..]}
|
||||
|
||||
protected:
|
||||
void note(std::string line); // caller holds mu_
|
||||
mutable std::recursive_mutex mu_;
|
||||
|
||||
private:
|
||||
std::deque<std::string> log_;
|
||||
};
|
||||
|
||||
// src/operability/resilience/breaker.h
|
||||
class CircuitBreaker : public Lab {
|
||||
public:
|
||||
enum class State { Closed, Open, HalfOpen };
|
||||
CircuitBreaker(std::shared_ptr<ManualClock> clock, int threshold = 3,
|
||||
long open_ms = 30000);
|
||||
// Records one call. Returns false when the breaker rejected it (open).
|
||||
bool call(bool success);
|
||||
void tick(long ms);
|
||||
State state() const;
|
||||
std::string name() const override { return "breaker"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
State effective() const;
|
||||
std::shared_ptr<ManualClock> clock_;
|
||||
int threshold_;
|
||||
long open_ms_;
|
||||
State state_ = State::Closed;
|
||||
int failures_ = 0;
|
||||
long opened_at_ = 0;
|
||||
int rejected_ = 0;
|
||||
};
|
||||
std::string breaker_state_name(CircuitBreaker::State s);
|
||||
|
||||
// src/operability/resilience/bulkhead.h
|
||||
class Bulkhead : public Lab {
|
||||
public:
|
||||
enum class Admission { Admitted, Queued, Rejected };
|
||||
Bulkhead(int max_active = 2, int max_queue = 1);
|
||||
Admission acquire();
|
||||
bool release(); // false when nothing to release
|
||||
std::string name() const override { return "bulkhead"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
int max_active_, max_queue_, active_ = 0, queued_ = 0, rejected_ = 0;
|
||||
};
|
||||
|
||||
// src/operability/resilience/shedder.h
|
||||
class Shedder : public Lab {
|
||||
public:
|
||||
explicit Shedder(int limit = 3) : limit_(limit) {}
|
||||
// low priority is shed at 2/3 of the limit, high only at the limit.
|
||||
bool enter(bool high);
|
||||
bool leave();
|
||||
std::string name() const override { return "shedder"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
int limit_, inflight_ = 0, shed_low_ = 0, shed_high_ = 0;
|
||||
};
|
||||
|
||||
// src/operability/resilience/deadline.h
|
||||
class DeadlineLab : public Lab {
|
||||
public:
|
||||
static constexpr long kHopCostMs = 30;
|
||||
// Walks `hops` downstream calls against one propagated budget.
|
||||
// Returns the hop that expired (1 based) or 0 when all finished.
|
||||
int run(long budget_ms, int hops);
|
||||
std::string name() const override { return "deadline"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
long budget_ms_ = 0, remaining_ms_ = 0;
|
||||
int hops_ = 0, expired_hop_ = 0;
|
||||
bool ran_ = false;
|
||||
};
|
||||
|
||||
// src/operability/resilience/slo.h
|
||||
class SloBudget : public Lab {
|
||||
public:
|
||||
static constexpr std::size_t kWindow = 100; // ring of the last 100 events
|
||||
SloBudget(int target_permille = 950) : target_(target_permille) {}
|
||||
void record(bool good);
|
||||
void reset();
|
||||
long budget_remaining() const; // allowed bad events minus actual bad
|
||||
std::string name() const override { return "slo"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
int target_;
|
||||
std::deque<bool> window_;
|
||||
};
|
||||
|
||||
// src/operability/chaos/experiment.h, injector.h
|
||||
class ChaosLab : public Lab {
|
||||
public:
|
||||
static constexpr int kCalls = 10; // simulated calls per experiment
|
||||
struct Result {
|
||||
int percent = 0, max_faults = 0, planned = 0, injected = 0;
|
||||
bool armed = false;
|
||||
};
|
||||
// Deterministic: an accumulator injects a fault every 100/percent calls.
|
||||
// Dry run (armed=false) plans faults but never injects them.
|
||||
Result run(int percent, int max_faults, bool armed);
|
||||
std::string name() const override { return "chaos"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
Result last_;
|
||||
int runs_ = 0, total_injected_ = 0;
|
||||
};
|
||||
|
||||
// src/operability/deploy/rolling.h, blue_green.h, lifecycle.h
|
||||
class DeployLab : public Lab {
|
||||
public:
|
||||
enum class Phase { Idle, InProgress, Done, RolledBack };
|
||||
DeployLab();
|
||||
bool start(const std::string& strategy, const std::string& version);
|
||||
bool step();
|
||||
bool rollback();
|
||||
Phase phase() const;
|
||||
std::string name() const override { return "deploy"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::vector<std::string> fleet_, previous_;
|
||||
std::string strategy_ = "none", target_;
|
||||
int green_stage_ = 0; // blue-green: 0 prepare, 1 switched
|
||||
Phase phase_ = Phase::Idle;
|
||||
};
|
||||
std::string deploy_phase_name(DeployLab::Phase p);
|
||||
|
||||
// src/operability/coord/lease.h, election.h, dist_lock.h, fence.h
|
||||
class CoordLab : public Lab {
|
||||
public:
|
||||
struct Grant {
|
||||
bool ok = false;
|
||||
long token = 0;
|
||||
std::string holder;
|
||||
};
|
||||
explicit CoordLab(std::shared_ptr<ManualClock> clock, long ttl_ms = 10000);
|
||||
Grant acquire(const std::string& key, const std::string& owner);
|
||||
bool release(const std::string& key, const std::string& owner);
|
||||
// Fenced write: accepted only when token >= the highest token seen.
|
||||
bool write(const std::string& key, long token);
|
||||
void tick(long ms);
|
||||
static bool known_key(const std::string& key);
|
||||
std::string name() const override { return "coord"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
struct Slot {
|
||||
std::string holder;
|
||||
long expires = 0, token = 0, fence = 0;
|
||||
};
|
||||
std::shared_ptr<ManualClock> clock_;
|
||||
long ttl_ms_;
|
||||
std::map<std::string, Slot> slots_;
|
||||
};
|
||||
|
||||
// src/operability/debug/endpoint.h, snapshot.h
|
||||
class DebugRegistry {
|
||||
public:
|
||||
void add(std::shared_ptr<Lab> lab);
|
||||
std::string snapshot() const; // {"labs":{name:{..}}}
|
||||
std::size_t size() const { return labs_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<Lab>> labs_;
|
||||
};
|
||||
|
||||
// src/supplychain/sbom, policy, attest
|
||||
class SupplyChainLab : public Lab {
|
||||
public:
|
||||
struct Component {
|
||||
std::string name, version, license;
|
||||
};
|
||||
SupplyChainLab();
|
||||
bool add_advisory(const std::string& component, const std::string& version);
|
||||
void tamper();
|
||||
void reset();
|
||||
// True when `digest` equals the attested and the current SBOM digest.
|
||||
bool verify(const std::string& digest);
|
||||
std::string digest() const;
|
||||
std::string attested() const { return attested_; }
|
||||
bool gate() const;
|
||||
std::string cyclonedx() const;
|
||||
std::string name() const override { return "supplychain"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
bool pins_ok() const;
|
||||
bool advisories_ok() const;
|
||||
std::vector<Component> components_;
|
||||
std::map<std::string, std::string> pins_;
|
||||
std::vector<std::pair<std::string, std::string>> advisories_;
|
||||
std::string attested_;
|
||||
int verified_ = 0; // 0 none, 1 ok, -1 failed
|
||||
};
|
||||
|
||||
// src/clients/retry.h
|
||||
class ClientRetryLab : public Lab {
|
||||
public:
|
||||
struct Outcome {
|
||||
int attempts = 0, status = 0;
|
||||
long waited_ms = 0;
|
||||
bool gave_up = false;
|
||||
};
|
||||
// The in-process transport fails the first `failures` calls with `status`.
|
||||
// 5xx is retried with capped exponential backoff; 4xx never is.
|
||||
Outcome run(int failures, int max_attempts, int status);
|
||||
std::string name() const override { return "client-retry"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
static constexpr long kBaseMs = 100, kCapMs = 800;
|
||||
Outcome last_;
|
||||
int runs_ = 0;
|
||||
};
|
||||
|
||||
// src/clients/cookies.h, pool.h, proxy.h, auth.h
|
||||
class ClientSessionLab : public Lab {
|
||||
public:
|
||||
ClientSessionLab();
|
||||
static bool valid_proxy(const std::string& proxy);
|
||||
// One request through the in-process transport; returns the request headers.
|
||||
std::map<std::string, std::string> request(const std::string& auth,
|
||||
const std::string& proxy);
|
||||
std::string name() const override { return "client-session"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> jar_;
|
||||
int created_ = 0, reused_ = 0, idle_ = 0, requests_ = 0;
|
||||
std::string proxy_ = "direct", auth_ = "none";
|
||||
};
|
||||
|
||||
// src/data/orm/migration.hpp, migrator.hpp, healer.hpp
|
||||
class MigrationLab : public Lab {
|
||||
public:
|
||||
struct Step {
|
||||
std::string id, sql, table;
|
||||
};
|
||||
MigrationLab();
|
||||
// check: what apply would do, nothing changes.
|
||||
std::vector<std::string> check() const;
|
||||
int apply(int limit);
|
||||
void drop_table(const std::string& table); // simulated drift
|
||||
int heal(); // re-apply drifted creates
|
||||
std::vector<std::string> drift() const;
|
||||
std::string name() const override { return "migrations"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::vector<Step> steps_;
|
||||
std::vector<std::string> applied_;
|
||||
std::map<std::string, std::string> tables_; // table -> columns
|
||||
};
|
||||
|
||||
// src/data/transaction.hpp
|
||||
class TxLab : public Lab {
|
||||
public:
|
||||
TxLab();
|
||||
// Returns "committed", or the rollback reason.
|
||||
std::string transfer(const std::string& from, const std::string& to,
|
||||
long amount, bool fail_after_debit);
|
||||
long balance(const std::string& who) const;
|
||||
std::string name() const override { return "transaction"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::map<std::string, long> accounts_;
|
||||
int commits_ = 0, rollbacks_ = 0;
|
||||
};
|
||||
|
||||
// src/data/orm/query.hpp, relations.hpp
|
||||
class QueryLab : public Lab {
|
||||
public:
|
||||
struct Result {
|
||||
std::string sql;
|
||||
std::vector<std::map<std::string, std::string>> rows;
|
||||
};
|
||||
QueryLab();
|
||||
// Builds "SELECT ... FROM posts [WHERE user_id = ?] ORDER BY .. LIMIT n"
|
||||
// and executes it against the in-memory users/posts tables (has-many).
|
||||
Result run(long user_id, const std::string& order, int limit);
|
||||
std::string name() const override { return "query"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::vector<std::map<std::string, std::string>> users_, posts_;
|
||||
Result last_;
|
||||
};
|
||||
|
||||
// src/data/cache/singleflight.hpp
|
||||
class SingleFlight {
|
||||
public:
|
||||
// Concurrent callers of one key share a single loader execution.
|
||||
std::string run(const std::string& key,
|
||||
const std::function<std::string()>& loader);
|
||||
int waiters(const std::string& key) const;
|
||||
|
||||
private:
|
||||
struct Call {
|
||||
bool done = false;
|
||||
int waiters = 0;
|
||||
std::string value;
|
||||
};
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable_any cv_;
|
||||
std::map<std::string, std::shared_ptr<Call>> calls_;
|
||||
};
|
||||
|
||||
class SingleFlightLab : public Lab {
|
||||
public:
|
||||
SingleFlightLab();
|
||||
// Starts `callers` threads on one key; returns loader executions.
|
||||
int run(int callers);
|
||||
std::string name() const override { return "singleflight"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
std::unique_ptr<SingleFlight> flight_;
|
||||
int callers_ = 0, loads_ = 0, runs_ = 0;
|
||||
};
|
||||
|
||||
// src/data/kv/memory.hpp, src/data/cache/policy.hpp, src/data/pubsub/broker.hpp
|
||||
class TtlLab : public Lab {
|
||||
public:
|
||||
explicit TtlLab(std::shared_ptr<ManualClock> clock);
|
||||
void set(const std::string& key, const std::string& value, long ttl_s);
|
||||
// Returns true and fills value on a live hit.
|
||||
bool get(const std::string& key, std::string& value);
|
||||
void tick(long ms);
|
||||
std::size_t size() const;
|
||||
std::vector<std::string> events() const; // pubsub topic "kv.events"
|
||||
std::string name() const override { return "ttl"; }
|
||||
LabRows rows() const override;
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
std::string value;
|
||||
long expires = 0, touched = 0;
|
||||
};
|
||||
void sweep();
|
||||
void publish(const std::string& event);
|
||||
std::shared_ptr<ManualClock> clock_;
|
||||
std::map<std::string, Entry> entries_;
|
||||
std::deque<std::string> events_;
|
||||
long seq_ = 0;
|
||||
int hits_ = 0, misses_ = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,390 @@
|
||||
#include "SecurityExtra.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace {
|
||||
const char* kHex = "0123456789abcdef";
|
||||
inline std::uint32_t rotr(std::uint32_t x, int n) {
|
||||
return (x >> n) | (x << (32 - n));
|
||||
}
|
||||
const std::uint32_t kK[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
|
||||
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
||||
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
|
||||
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
||||
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
||||
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
|
||||
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
} // namespace
|
||||
|
||||
std::string to_hex(const std::string& raw) {
|
||||
std::string out;
|
||||
out.reserve(raw.size() * 2);
|
||||
for (unsigned char c : raw) {
|
||||
out += kHex[c >> 4];
|
||||
out += kHex[c & 15];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool from_hex(const std::string& hex, std::string& raw) {
|
||||
raw.clear();
|
||||
if (hex.size() % 2 != 0) return false;
|
||||
auto val = [](char c) -> int {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
};
|
||||
for (std::size_t i = 0; i < hex.size(); i += 2) {
|
||||
int a = val(hex[i]), b = val(hex[i + 1]);
|
||||
if (a < 0 || b < 0) return false;
|
||||
raw += static_cast<char>(a * 16 + b);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool constant_time_equal(const std::string& a, const std::string& b) {
|
||||
unsigned char diff = a.size() == b.size() ? 0 : 1;
|
||||
std::size_t n = std::min(a.size(), b.size());
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
diff |= static_cast<unsigned char>(a[i] ^ b[i]);
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
std::string Sha256::digest(const std::string& data) {
|
||||
std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
std::string msg = data;
|
||||
std::uint64_t bits = static_cast<std::uint64_t>(data.size()) * 8;
|
||||
msg += static_cast<char>(0x80);
|
||||
while (msg.size() % 64 != 56) msg += '\0';
|
||||
for (int i = 7; i >= 0; --i) msg += static_cast<char>((bits >> (i * 8)) & 0xff);
|
||||
for (std::size_t off = 0; off < msg.size(); off += 64) {
|
||||
std::uint32_t w[64];
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
const unsigned char* p =
|
||||
reinterpret_cast<const unsigned char*>(msg.data()) + off + i * 4;
|
||||
w[i] = (std::uint32_t(p[0]) << 24) | (std::uint32_t(p[1]) << 16) |
|
||||
(std::uint32_t(p[2]) << 8) | p[3];
|
||||
}
|
||||
for (int i = 16; i < 64; ++i) {
|
||||
std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5],
|
||||
g = h[6], hh = h[7];
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
std::uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
||||
std::uint32_t ch = (e & f) ^ (~e & g);
|
||||
std::uint32_t t1 = hh + S1 + ch + kK[i] + w[i];
|
||||
std::uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
||||
std::uint32_t mj = (a & b) ^ (a & c) ^ (b & c);
|
||||
std::uint32_t t2 = S0 + mj;
|
||||
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||
}
|
||||
std::string out;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
for (int s = 24; s >= 0; s -= 8) out += static_cast<char>((h[i] >> s) & 0xff);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Sha256::hex(const std::string& data) { return to_hex(digest(data)); }
|
||||
|
||||
std::string Hmac::sha256(const std::string& key, const std::string& data) {
|
||||
std::string k = key.size() > 64 ? Sha256::digest(key) : key;
|
||||
k.resize(64, '\0');
|
||||
std::string ipad(64, '\0'), opad(64, '\0');
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
ipad[i] = static_cast<char>(k[i] ^ 0x36);
|
||||
opad[i] = static_cast<char>(k[i] ^ 0x5c);
|
||||
}
|
||||
return Sha256::digest(opad + Sha256::digest(ipad + data));
|
||||
}
|
||||
|
||||
std::string SecureRandom::bytes(std::size_t n) {
|
||||
n = std::min(n, secaps::kMaxRandomBytes);
|
||||
std::string out(n, '\0');
|
||||
std::FILE* f = std::fopen("/dev/urandom", "rb");
|
||||
if (!f) throw std::runtime_error("no secure random source");
|
||||
std::size_t got = std::fread(out.data(), 1, n, f);
|
||||
std::fclose(f);
|
||||
if (got != n) throw std::runtime_error("short read from urandom");
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string SecureRandom::token_hex(std::size_t n) { return to_hex(bytes(n)); }
|
||||
|
||||
namespace {
|
||||
std::string pbkdf2(const std::string& pw, const std::string& salt, int rounds) {
|
||||
std::string u = Hmac::sha256(pw, salt + std::string("\0\0\0\1", 4));
|
||||
std::string t = u;
|
||||
for (int i = 1; i < rounds; ++i) {
|
||||
u = Hmac::sha256(pw, u);
|
||||
for (std::size_t j = 0; j < t.size(); ++j) t[j] = static_cast<char>(t[j] ^ u[j]);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string PasswordHasher::hash(const std::string& password) {
|
||||
std::string salt = SecureRandom::bytes(16);
|
||||
return "pbkdf2-demo$" + std::to_string(secaps::kDemoPbkdf2Rounds) + "$" +
|
||||
to_hex(salt) + "$" +
|
||||
to_hex(pbkdf2(password, salt, secaps::kDemoPbkdf2Rounds));
|
||||
}
|
||||
|
||||
bool PasswordHasher::verify(const std::string& password, const std::string& stored) {
|
||||
std::vector<std::string> parts;
|
||||
std::size_t pos = 0;
|
||||
while (true) {
|
||||
std::size_t d = stored.find('$', pos);
|
||||
parts.push_back(stored.substr(pos, d == std::string::npos ? d : d - pos));
|
||||
if (d == std::string::npos) break;
|
||||
pos = d + 1;
|
||||
}
|
||||
if (parts.size() != 4 || parts[0] != "pbkdf2-demo") return false;
|
||||
int rounds = 0;
|
||||
try { rounds = std::stoi(parts[1]); } catch (...) { return false; }
|
||||
if (rounds < 1 || rounds > 100000) return false;
|
||||
std::string salt;
|
||||
if (!from_hex(parts[2], salt)) return false;
|
||||
return constant_time_equal(to_hex(pbkdf2(password, salt, rounds)), parts[3]);
|
||||
}
|
||||
|
||||
void DenialSink::record(const std::string& guard, const std::string& reason) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
++total_;
|
||||
if (ring_.size() >= secaps::kMaxDenials) ring_.erase(ring_.begin());
|
||||
ring_.push_back({guard, reason});
|
||||
}
|
||||
std::vector<Denial> DenialSink::list() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return ring_;
|
||||
}
|
||||
std::size_t DenialSink::total() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return total_;
|
||||
}
|
||||
|
||||
std::string CsrfGuard::issue() const {
|
||||
std::string nonce = SecureRandom::token_hex(16);
|
||||
return nonce + "." + to_hex(Hmac::sha256(secret_, nonce));
|
||||
}
|
||||
bool CsrfGuard::verify(const std::string& token) const {
|
||||
std::size_t dot = token.find('.');
|
||||
if (dot == std::string::npos || dot == 0 || token.size() > 200) return false;
|
||||
std::string nonce = token.substr(0, dot);
|
||||
return constant_time_equal(token.substr(dot + 1),
|
||||
to_hex(Hmac::sha256(secret_, nonce)));
|
||||
}
|
||||
|
||||
bool CorsPolicy::allowed(const std::string& origin) const {
|
||||
return !origin.empty() && origins_.count(origin) > 0;
|
||||
}
|
||||
bool CorsPolicy::apply_preflight(const Request& req, Response& res) const {
|
||||
std::string origin = req.headers.get("Origin");
|
||||
if (!allowed(origin)) return false;
|
||||
res.headers.set("Access-Control-Allow-Origin", origin);
|
||||
res.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
res.headers.set("Access-Control-Max-Age", "600");
|
||||
res.headers.set("Vary", "Origin");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RateLimiter::hit(const std::string& key, int& retry_after, int& remaining) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
auto win = std::chrono::seconds(window_);
|
||||
if (slots_.size() >= secaps::kMaxRateKeys && !slots_.count(key)) {
|
||||
for (auto it = slots_.begin(); it != slots_.end();)
|
||||
it = (now - it->second.start >= win) ? slots_.erase(it) : std::next(it);
|
||||
if (slots_.size() >= secaps::kMaxRateKeys) { // floor: refuse new keys
|
||||
retry_after = window_;
|
||||
remaining = 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Slot& s = slots_[key];
|
||||
if (s.count == 0 || now - s.start >= win) {
|
||||
s.start = now;
|
||||
s.count = 0;
|
||||
}
|
||||
if (s.count >= limit_) {
|
||||
auto left = std::chrono::duration_cast<std::chrono::seconds>(win - (now - s.start));
|
||||
retry_after = std::max(1, static_cast<int>(left.count()) + 1);
|
||||
remaining = 0;
|
||||
return false;
|
||||
}
|
||||
++s.count;
|
||||
retry_after = 0;
|
||||
remaining = limit_ - s.count;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, std::string>> SecurityHeaders::defaults() {
|
||||
return {{"X-Content-Type-Options", "nosniff"},
|
||||
{"X-Frame-Options", "DENY"},
|
||||
{"Referrer-Policy", "no-referrer"},
|
||||
{"Strict-Transport-Security", "max-age=31536000; includeSubDomains"},
|
||||
{"Cross-Origin-Opener-Policy", "same-origin"},
|
||||
{"Permissions-Policy", "camera=(), microphone=(), geolocation=()"}};
|
||||
}
|
||||
void SecurityHeaders::apply(Response& res) {
|
||||
for (const auto& [k, v] : defaults()) res.headers.set(k, v);
|
||||
}
|
||||
|
||||
CspBuilder::CspBuilder() {
|
||||
directives_["default-src"] = "'none'";
|
||||
directives_["script-src"] = "'self'";
|
||||
directives_["style-src"] = "'self'";
|
||||
directives_["img-src"] = "'self'";
|
||||
directives_["frame-ancestors"] = "'none'";
|
||||
}
|
||||
CspBuilder& CspBuilder::script_nonce(const std::string& nonce) {
|
||||
directives_["script-src"] = "'self' 'nonce-" + nonce + "'";
|
||||
return *this;
|
||||
}
|
||||
CspBuilder& CspBuilder::report_uri(const std::string& uri) {
|
||||
directives_["report-uri"] = uri;
|
||||
return *this;
|
||||
}
|
||||
CspBuilder& CspBuilder::enforce() {
|
||||
report_only_ = false;
|
||||
return *this;
|
||||
}
|
||||
std::string CspBuilder::header_name() const {
|
||||
return report_only_ ? "Content-Security-Policy-Report-Only"
|
||||
: "Content-Security-Policy";
|
||||
}
|
||||
std::string CspBuilder::build() const {
|
||||
std::string out;
|
||||
for (const auto& [k, v] : directives_) out += (out.empty() ? "" : "; ") + k + " " + v;
|
||||
return out;
|
||||
}
|
||||
|
||||
bool CspReportStore::add(const std::string& body) {
|
||||
if (body.empty() || body.size() > 4096) return false;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
++total_;
|
||||
if (reports_.size() >= secaps::kMaxCspReports) reports_.erase(reports_.begin());
|
||||
reports_.push_back(body);
|
||||
return true;
|
||||
}
|
||||
std::vector<std::string> CspReportStore::list() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return reports_;
|
||||
}
|
||||
std::size_t CspReportStore::total() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return total_;
|
||||
}
|
||||
|
||||
PermissionGuard::PermissionGuard() {
|
||||
token_role_ = {{"viewer-token", "viewer"}, {"editor-token", "editor"},
|
||||
{"admin-token", "admin"}};
|
||||
role_perms_["viewer"] = {"doc:read"};
|
||||
role_perms_["editor"] = {"doc:read", "doc:write"};
|
||||
role_perms_["admin"] = {"doc:read", "doc:write", "admin:manage"};
|
||||
}
|
||||
PermissionGuard::Verdict PermissionGuard::check(const std::string& authorization,
|
||||
const std::string& permission,
|
||||
std::string& role) const {
|
||||
role.clear();
|
||||
const std::string prefix = "Bearer ";
|
||||
if (authorization.compare(0, prefix.size(), prefix) != 0)
|
||||
return Verdict::Unauthenticated;
|
||||
auto it = token_role_.find(authorization.substr(prefix.size()));
|
||||
if (it == token_role_.end()) return Verdict::Unauthenticated;
|
||||
role = it->second;
|
||||
return role_perms_.at(role).count(permission) ? Verdict::Allow
|
||||
: Verdict::Forbidden;
|
||||
}
|
||||
std::vector<std::string> PermissionGuard::permissions(const std::string& role) const {
|
||||
auto it = role_perms_.find(role);
|
||||
if (it == role_perms_.end()) return {};
|
||||
return {it->second.begin(), it->second.end()};
|
||||
}
|
||||
|
||||
SecretsProvider::SecretsProvider() {
|
||||
values_ = {{"DB_PASSWORD", "demo-db-password-1234"},
|
||||
{"API_KEY", "demo-api-key-abcdef"},
|
||||
{"SIGNING_KEY", "demo-signing-key-zz"}};
|
||||
}
|
||||
std::vector<std::string> SecretsProvider::names() const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& [k, v] : values_) out.push_back(k);
|
||||
return out;
|
||||
}
|
||||
bool SecretsProvider::masked(const std::string& name, std::string& out) const {
|
||||
auto it = values_.find(name);
|
||||
if (it == values_.end()) return false;
|
||||
const std::string& v = it->second;
|
||||
out = v.substr(0, 2) + std::string(v.size() - 4, '*') + v.substr(v.size() - 2);
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::string lower(std::string s) {
|
||||
for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
|
||||
return s;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string SqlSafety::check(const std::string& value) {
|
||||
std::string v = lower(value);
|
||||
for (const char* bad : {"--", ";", "/*", "' or ", "\" or ", "union select",
|
||||
"drop table", "xp_"})
|
||||
if (v.find(bad) != std::string::npos)
|
||||
return std::string("SQL metacharacter or keyword rejected: ") + bad;
|
||||
return "";
|
||||
}
|
||||
std::string PathGuard::check(const std::string& value) {
|
||||
std::string v = lower(value);
|
||||
if (v.find('\0') != std::string::npos) return "NUL byte rejected";
|
||||
if (!v.empty() && v[0] == '/') return "absolute path rejected";
|
||||
for (const char* bad : {"..", "%2e", "\\"})
|
||||
if (v.find(bad) != std::string::npos)
|
||||
return std::string("traversal sequence rejected: ") + bad;
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string UploadValidator::check(const std::string& filename,
|
||||
const std::string& bytes) {
|
||||
if (filename.empty() || filename.size() > 255) return "file name length must be 1 to 255";
|
||||
if (filename.find('/') != std::string::npos ||
|
||||
filename.find('\\') != std::string::npos || filename.find("..") != std::string::npos)
|
||||
return "file name must not contain path parts";
|
||||
std::size_t dot = filename.rfind('.');
|
||||
if (dot == std::string::npos) return "extension not allowed (use pdf, png, txt)";
|
||||
std::string ext = lower(filename.substr(dot + 1));
|
||||
if (ext != "pdf" && ext != "png" && ext != "txt")
|
||||
return "extension not allowed (use pdf, png, txt)";
|
||||
if (bytes.size() > kMaxFileBytes) return "file too large (max 1024 bytes)";
|
||||
if (bytes.empty()) return "file is empty";
|
||||
if (ext == "pdf" && bytes.compare(0, 5, "%PDF-") != 0)
|
||||
return "content does not match pdf magic bytes";
|
||||
if (ext == "png" && bytes.compare(0, 4, "\x89PNG") != 0)
|
||||
return "content does not match png magic bytes";
|
||||
if (ext == "txt")
|
||||
for (unsigned char c : bytes)
|
||||
if (c < 9 || (c > 13 && c < 32) || c == 127)
|
||||
return "txt content contains binary bytes";
|
||||
return "";
|
||||
}
|
||||
|
||||
} // namespace molo::example::fw
|
||||
@@ -0,0 +1,201 @@
|
||||
#pragma once
|
||||
|
||||
// SecurityExtra framework skeleton for the living example (namespace
|
||||
// molo::example::fw). Mirrors names and behavior of src/security/{guard,
|
||||
// crypto,auth,secret,upload} and src/cli/csp in small, readable form.
|
||||
// Every container has a hard cap. Crypto here is real SHA-256/HMAC but the
|
||||
// password hasher uses DEMO iteration counts: not for production use.
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "Http.hpp"
|
||||
|
||||
namespace molo::example::fw {
|
||||
|
||||
namespace secaps {
|
||||
inline constexpr std::size_t kMaxDenials = 100;
|
||||
inline constexpr std::size_t kMaxRateKeys = 1024;
|
||||
inline constexpr std::size_t kMaxCspReports = 50;
|
||||
inline constexpr std::size_t kMaxRandomBytes = 64;
|
||||
inline constexpr std::size_t kMaxHashInput = 4096;
|
||||
inline constexpr std::size_t kMaxUploadHex = 4096;
|
||||
inline constexpr std::size_t kMaxInputLen = 512;
|
||||
inline constexpr int kDemoPbkdf2Rounds = 2000; // real: 600000+
|
||||
} // namespace secaps
|
||||
|
||||
std::string to_hex(const std::string& raw);
|
||||
bool from_hex(const std::string& hex, std::string& raw);
|
||||
bool constant_time_equal(const std::string& a, const std::string& b);
|
||||
|
||||
// Mirrors src/security/crypto/Sha256.h and Hmac.h.
|
||||
class Sha256 {
|
||||
public:
|
||||
static std::string digest(const std::string& data); // 32 raw bytes
|
||||
static std::string hex(const std::string& data);
|
||||
};
|
||||
|
||||
class Hmac {
|
||||
public:
|
||||
static std::string sha256(const std::string& key, const std::string& data);
|
||||
};
|
||||
|
||||
// Mirrors SecureRandom.h: /dev/urandom, capped length.
|
||||
class SecureRandom {
|
||||
public:
|
||||
static std::string bytes(std::size_t n);
|
||||
static std::string token_hex(std::size_t n);
|
||||
};
|
||||
|
||||
// Mirrors PasswordHasher.h with PBKDF2-HMAC-SHA256 at demo rounds.
|
||||
class PasswordHasher {
|
||||
public:
|
||||
static std::string hash(const std::string& password); // "pbkdf2$r$salt$dk"
|
||||
static bool verify(const std::string& password, const std::string& stored);
|
||||
};
|
||||
|
||||
// Mirrors guard/DenialSink.h: capped ring of why requests were refused.
|
||||
struct Denial {
|
||||
std::string guard;
|
||||
std::string reason;
|
||||
};
|
||||
class DenialSink {
|
||||
public:
|
||||
void record(const std::string& guard, const std::string& reason);
|
||||
std::vector<Denial> list() const;
|
||||
std::size_t total() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::vector<Denial> ring_;
|
||||
std::size_t total_ = 0;
|
||||
};
|
||||
|
||||
// Mirrors guard/CsrfGuard.h: stateless signed token "nonce.mac".
|
||||
class CsrfGuard {
|
||||
public:
|
||||
explicit CsrfGuard(std::string secret) : secret_(std::move(secret)) {}
|
||||
std::string issue() const;
|
||||
bool verify(const std::string& token) const;
|
||||
|
||||
private:
|
||||
std::string secret_;
|
||||
};
|
||||
|
||||
// Mirrors guard/CorsPolicy.h: exact-origin allowlist, no wildcard with creds.
|
||||
class CorsPolicy {
|
||||
public:
|
||||
explicit CorsPolicy(std::set<std::string> origins)
|
||||
: origins_(std::move(origins)) {}
|
||||
bool allowed(const std::string& origin) const;
|
||||
// Fills Access-Control-* headers when the origin is allowed.
|
||||
bool apply_preflight(const Request& req, Response& res) const;
|
||||
|
||||
private:
|
||||
std::set<std::string> origins_;
|
||||
};
|
||||
|
||||
// Mirrors guard/RateLimiter.h: fixed window per key, capped key table.
|
||||
class RateLimiter {
|
||||
public:
|
||||
RateLimiter(int limit, int window_seconds)
|
||||
: limit_(limit), window_(window_seconds) {}
|
||||
// Returns true when allowed; else sets retry_after (seconds, >= 1).
|
||||
bool hit(const std::string& key, int& retry_after, int& remaining);
|
||||
int limit() const { return limit_; }
|
||||
int window() const { return window_; }
|
||||
|
||||
private:
|
||||
struct Slot {
|
||||
std::chrono::steady_clock::time_point start;
|
||||
int count = 0;
|
||||
};
|
||||
std::mutex mu_;
|
||||
std::map<std::string, Slot> slots_;
|
||||
int limit_;
|
||||
int window_;
|
||||
};
|
||||
|
||||
// Mirrors guard/SecurityHeaders.h.
|
||||
class SecurityHeaders {
|
||||
public:
|
||||
static std::vector<std::pair<std::string, std::string>> defaults();
|
||||
static void apply(Response& res);
|
||||
};
|
||||
|
||||
// Mirrors src/cli/csp: builder, per-request nonce, capped report store.
|
||||
class CspBuilder {
|
||||
public:
|
||||
CspBuilder();
|
||||
CspBuilder& script_nonce(const std::string& nonce);
|
||||
CspBuilder& report_uri(const std::string& uri);
|
||||
CspBuilder& enforce();
|
||||
std::string header_name() const;
|
||||
std::string build() const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> directives_;
|
||||
bool report_only_ = true;
|
||||
};
|
||||
class CspReportStore {
|
||||
public:
|
||||
bool add(const std::string& body); // false when body is empty/too large
|
||||
std::vector<std::string> list() const;
|
||||
std::size_t total() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::vector<std::string> reports_;
|
||||
std::size_t total_ = 0;
|
||||
};
|
||||
|
||||
// Mirrors auth/Permission.h + Guard.h: token -> role -> permission set.
|
||||
class PermissionGuard {
|
||||
public:
|
||||
PermissionGuard();
|
||||
enum class Verdict { Allow, Unauthenticated, Forbidden };
|
||||
Verdict check(const std::string& authorization,
|
||||
const std::string& permission, std::string& role) const;
|
||||
std::vector<std::string> permissions(const std::string& role) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> token_role_;
|
||||
std::map<std::string, std::set<std::string>> role_perms_;
|
||||
};
|
||||
|
||||
// Mirrors secret/SecretsProvider.h; values never leave except masked.
|
||||
class SecretsProvider {
|
||||
public:
|
||||
SecretsProvider();
|
||||
std::vector<std::string> names() const;
|
||||
bool masked(const std::string& name, std::string& out) const;
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> values_;
|
||||
};
|
||||
|
||||
// Mirrors guard/SqlSafety.h and PathGuard.h: returns "" when safe, else reason.
|
||||
class SqlSafety {
|
||||
public:
|
||||
static std::string check(const std::string& value);
|
||||
};
|
||||
class PathGuard {
|
||||
public:
|
||||
static std::string check(const std::string& value);
|
||||
};
|
||||
|
||||
// Mirrors upload/UploadValidator.h: ext allowlist, size cap, magic bytes.
|
||||
class UploadValidator {
|
||||
public:
|
||||
static constexpr std::size_t kMaxFileBytes = 1024;
|
||||
static std::string check(const std::string& filename,
|
||||
const std::string& bytes); // "" when allowed
|
||||
};
|
||||
|
||||
} // namespace molo::example::fw
|
||||
Reference in New Issue
Block a user