rate_limiter.hpp 3.1 KB

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