#pragma once #include #include #include #include #include #include namespace svapi { /// Fixed-window counters, keyed on whatever the caller decides identity is. /// /// THE WINDOW IS FIXED, NOT SLIDING (`now / 60`), and that is observable: a /// burst spends the whole allowance at once and every later call in that /// wall-clock minute is refused rather than draining smoothly, and a burst /// straddling a boundary can land 2x the limit inside a rolling 60 s. A /// REFUSAL COSTS NOTHING - `allow()` increments only on the admitting path - so /// a client retrying a 429 is not digging its own counter deeper, which is the /// opposite of what most callers assume. /// /// THE KEY SPACE IS BOUNDED, AND IT HAS TO BE NOW THAT IT IS NOT ONLY KEY IDS. /// `windows_` used to grow forever: every unseen key default-constructed an /// entry and nothing ever removed one. That was safe only because every key was /// an API key id and a deployment has a dozen of those - a property of the /// CALLERS, not of this class, written down nowhere. The moment anything is /// keyed on a source address the key space becomes attacker-controlled, and an /// unauthenticated flood against a public /fn route would grow this map without /// bound on a box that is already on swap. Two mechanisms, deliberately both: /// - a SWEEP when the minute advances, which is what makes the steady state /// proportional to callers-per-minute rather than to callers-ever; and /// - a hard CAP, because a flood inside one minute outruns any sweep. /// /// AT THE CAP IT FAILS OPEN, which is the uncomfortable choice and the right /// one. Refusing unknown keys when the table is full would let an attacker /// deny service to everyone else by spraying addresses - a denial of service /// achieved by being refused, which is exactly the shape the /fn ordering rule /// already exists to prevent. A limiter bounds damage; it is not an /// authorization control, and it must not become one by accident. class RateLimiter { public: /// Entries kept before new keys stop being tracked. ~100k x ~64 B is a few /// MB, which fits a small box while being far above any honest caller /// count. static constexpr std::size_t kMaxWindows = 100000; RateLimiter(); bool allow(const std::string& keyId, uint32_t limitPerMin); // true if under limit; 0 = unlimited void setClockForTesting(std::function fn); /// Tracked keys. For tests and for an operator asking whether the cap is /// being reached; NOT a request counter. std::size_t trackedKeys() const; /// True once the cap has been hit since the last sweep, i.e. some keys are /// currently untracked and therefore unlimited. bool overCapacity() const; private: void sweepLocked(int64_t minute); struct Window { int64_t minute = -1; uint32_t count = 0; }; std::unordered_map windows_; std::function now_; // epoch seconds int64_t lastSweptMinute_ = -1; bool overCapacity_ = false; mutable std::mutex mu_; }; RateLimiter& rateLimiter(); // process singleton }