Эх сурвалжийг харах

fix: throttle the throttle log to once per bucket per minute SV-125

novitax asked for the volume split and gave a concrete answer rather than a
preference: keep the per-caller line per refusal, aggregate the per-function
one. Half of that is adopted and half is refused, and the refused half is the
interesting one.

THEIR PREMISE FOR THE PER-CALLER LINE DOES NOT HOLD. They argued it was safe
per refusal because its count is "bounded by distinct abusive callers rather
than by request volume". It is not: a refused caller that keeps sending is
refused on EVERY request - a refusal costs nothing, which is deliberate - so
one determined address produces one line per request exactly as the
per-function line does. Their conclusion was right for the case they reasoned
about and does not survive being applied to the other, so both are throttled
identically.

Nothing is lost by aggregating both, and this is the part that makes the
decision easy: the VOLUME of refusals is already one line per 429 in the
access log. The journal only has to answer what the access log cannot, which
is WHICH ceiling fired. Their own framing is what the pair now protects - the
two causes have opposite remedies, so drowning one in the other loses the
distinction at exactly the moment it matters.

Both lines moved to WARN and are emitted once per bucket per minute, via a
`RateLimiter::Decision` carrying `firstRefusalInWindow`. That flag lives on the
window entry the sweep and the cap ALREADY govern, so it adds no state and
nothing new to bound - a separate "have I logged this?" map keyed on a caller
address would have reintroduced precisely the unbounded attacker-controlled
growth that had to be fixed before a per-caller throttle could exist at all.

The per-function line now says the caller it names is NOT necessarily the
cause, because under saturation it is whoever arrived first, and an operator
reading an address beside a throttle message will reasonably assume otherwise.

AND A FALSIFICATION CAUGHT ONE OF MY OWN NEW TESTS NOT TESTING ITS NAME.
Deleting the explicit `refusalLogged = false` reset left every test GREEN: the
sweep erases the stale entry, so a new window is flagged because the entry is
new, not because of that assignment. The line is kept as a guard for a future
path that reuses an entry without sweeping, and both it and the test now say
what the falsification showed - the test is a correct end-to-end assertion
about what an operator sees and is NOT a test of the reset. Four tests, two
falsified directions; the "always flag" direction reddens three of them.

1542/1542 serial.
fszontagh 6 өдөр өмнө
parent
commit
42de665d7b

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.22.1
+0.22.2

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 0 - 1
api/llms.txt


+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.22.1",
+    "version": "0.22.2",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {

+ 48 - 12
src/handlers/function_dispatch.cpp

@@ -435,10 +435,12 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     // Only where a caller exists. An empty address means nothing trustworthy
     // resolved, and bucketing those together would charge every such request
     // to one shared counter - a throttle keyed on "" rather than on a caller.
-    if (policies[idx]->rateLimitPerCallerPerMin > 0 && !clientIp.empty() &&
-        !rateLimiter().allow(
-            functions::fnCallerThrottleBucket(project, functionId, clientIp),
-            policies[idx]->rateLimitPerCallerPerMin)) {
+    const RateLimiter::Decision callerDecision =
+        (policies[idx]->rateLimitPerCallerPerMin > 0 && !clientIp.empty())
+            ? rateLimiter().check(functions::fnCallerThrottleBucket(project, functionId, clientIp),
+                                  policies[idx]->rateLimitPerCallerPerMin)
+            : RateLimiter::Decision{true, false};
+    if (!callerDecision.allowed) {
         res.set_header("Retry-After", std::to_string(kRetryAfterRateLimitedSec));
         // WHICH ceiling fired is recorded for the OPERATOR and withheld from
         // the caller, because the two audiences need opposite things.
@@ -452,23 +454,57 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
         // apart - asked for by a consumer who could see the symptom and not
         // the cause. The address is already in our access log, so naming it
         // here discloses nothing new.
-        spdlog::info("fn throttle: PER-CALLER ceiling {} reached for {}/{} by {}",
-                     policies[idx]->rateLimitPerCallerPerMin, project, functionId, clientIp);
+        // ONCE PER CALLER PER MINUTE, not once per refused request.
+        //
+        // A consumer argued this line was safe to emit per refusal because its
+        // count is "bounded by distinct abusive callers rather than by request
+        // volume". That premise does not hold: a refused caller that keeps
+        // sending is refused on EVERY request, so one determined address
+        // produces one line per request exactly as the per-function line does.
+        // Their conclusion was right for the per-function case and the
+        // reasoning does not survive being applied to this one, so both are
+        // throttled the same way.
+        //
+        // Nothing is lost by it: the VOLUME of refusals is already one line
+        // per 429 in the access log, so the journal only has to answer the
+        // question the access log cannot - WHICH ceiling fired. Logged at
+        // warn, not info: a caller hitting its own ceiling is the one an
+        // operator may need to go and find.
+        if (callerDecision.firstRefusalInWindow)
+            spdlog::warn("fn throttle: PER-CALLER ceiling {}/min reached for {}/{} by {} "
+                         "(further refusals this minute are not logged; count them in the "
+                         "access log)",
+                         policies[idx]->rateLimitPerCallerPerMin, project, functionId, clientIp);
         sendJson(res, 429,
                  errorBody("rate_limited", "this function's per-minute limit is exhausted"));
         return;
     }
 
-    if (policies[idx]->rateLimitPerMin > 0 &&
-        !rateLimiter().allow(functions::fnHttpThrottleBucket(project, functionId),
-                             policies[idx]->rateLimitPerMin)) {
+    const RateLimiter::Decision fnDecision =
+        policies[idx]->rateLimitPerMin > 0
+            ? rateLimiter().check(functions::fnHttpThrottleBucket(project, functionId),
+                                  policies[idx]->rateLimitPerMin)
+            : RateLimiter::Decision{true, false};
+    if (!fnDecision.allowed) {
         res.set_header("Retry-After", std::to_string(kRetryAfterRateLimitedSec));
         // The sibling of the line above, and worded to be greppable as a pair:
         // this one means the function is globally saturated rather than one
         // caller misbehaving, which is the distinction that decides the fix.
-        spdlog::info("fn throttle: PER-FUNCTION ceiling {} reached for {}/{} (caller {})",
-                     policies[idx]->rateLimitPerMin, project, functionId,
-                     clientIp.empty() ? "unresolved" : clientIp.c_str());
+        // ONCE PER FUNCTION PER MINUTE. Global saturation refuses EVERY caller,
+        // so volume is precisely when this fires and a line per refusal would
+        // bury the per-caller lines that identify the cause - which is the
+        // thing this pair exists to distinguish. The first line is the alert.
+        //
+        // The caller is named for context only and is NOT the culprit here:
+        // under saturation it is whichever request happened to arrive first.
+        // Saying so in the line, because an operator reading an address next
+        // to a throttle message will reasonably assume it is to blame.
+        if (fnDecision.firstRefusalInWindow)
+            spdlog::warn("fn throttle: PER-FUNCTION ceiling {}/min reached for {}/{} - the "
+                         "function is saturated, so every caller is being refused; first "
+                         "refused caller this minute was {} (not necessarily the cause)",
+                         policies[idx]->rateLimitPerMin, project, functionId,
+                         clientIp.empty() ? std::string("unresolved") : clientIp);
         sendJson(res, 429,
                  errorBody("rate_limited", "this function's per-minute limit is exhausted"));
         return;

+ 20 - 5
src/rate_limiter.cpp

@@ -16,7 +16,11 @@ void RateLimiter::sweepLocked(int64_t minute) {
 }
 
 bool RateLimiter::allow(const std::string& keyId, uint32_t limitPerMin) {
-    if (limitPerMin == 0) return true;
+    return check(keyId, limitPerMin).allowed;
+}
+
+RateLimiter::Decision RateLimiter::check(const std::string& keyId, uint32_t limitPerMin) {
+    if (limitPerMin == 0) return Decision{true, false};
     std::lock_guard<std::mutex> lk(mu_);
     int64_t minute = now_() / 60;
     if (minute != lastSweptMinute_) {
@@ -33,15 +37,26 @@ bool RateLimiter::allow(const std::string& keyId, uint32_t limitPerMin) {
                              "untracked and therefore unlimited until the next minute",
                              windows_.size());
             overCapacity_ = true;
-            return true;
+            return Decision{true, false};
         }
         it = windows_.emplace(keyId, Window{}).first;
     }
     auto& w = it->second;
-    if (w.minute != minute) { w.minute = minute; w.count = 0; }
-    if (w.count >= limitPerMin) return false;
+    // `refusalLogged` is reset here for completeness, but THE SWEEP is what
+    // actually clears it: a stale entry is erased when the minute advances, so
+    // the next refusal for that key is flagged because the entry is new rather
+    // than because of this assignment. Confirmed by falsification - deleting
+    // the reset leaves every test green. Kept as a guard for any future path
+    // that reuses an entry across windows without sweeping; do NOT read it as
+    // load-bearing today.
+    if (w.minute != minute) { w.minute = minute; w.count = 0; w.refusalLogged = false; }
+    if (w.count >= limitPerMin) {
+        const bool first = !w.refusalLogged;
+        w.refusalLogged = true;
+        return Decision{false, first};
+    }
     ++w.count;
-    return true;
+    return Decision{true, false};
 }
 void RateLimiter::setClockForTesting(std::function<int64_t()> fn) {
     std::lock_guard<std::mutex> lk(mu_); now_ = std::move(fn);

+ 26 - 1
src/rate_limiter.hpp

@@ -41,8 +41,33 @@ public:
     /// count.
     static constexpr std::size_t kMaxWindows = 100000;
 
+    /// The outcome of one check, for a caller that wants to LOG a refusal
+    /// without logging one per request.
+    ///
+    /// `firstRefusalInWindow` exists because the two audiences for a refusal
+    /// need different volumes. A sustained flood refuses on every request, so
+    /// a log line per refusal repeats one fact thousands of times and buries
+    /// the lines that identify the cause underneath it. The FIRST refusal in a
+    /// window is the whole signal; the rest is volume, and volume is already
+    /// in the access log, where every 429 is one line.
+    ///
+    /// It costs no new state and nothing to bound: the window entry this flag
+    /// lives on is the same one the sweep and the cap already govern, so it
+    /// cannot grow a table of its own. That mattered - a separate
+    /// "have I logged this?" map keyed on a caller address would have
+    /// reintroduced exactly the unbounded, attacker-controlled growth that had
+    /// to be fixed here before a per-caller throttle could exist at all.
+    struct Decision {
+        bool allowed = true;
+        /// True only on the first refusal for this key in this minute.
+        bool firstRefusalInWindow = false;
+    };
+
     RateLimiter();
     bool allow(const std::string& keyId, uint32_t limitPerMin); // true if under limit; 0 = unlimited
+    /// `allow()` with the logging hint. `allow()` is a thin wrapper, so the
+    /// call sites that do not log are unchanged.
+    Decision check(const std::string& keyId, uint32_t limitPerMin);
     void setClockForTesting(std::function<int64_t()> fn);
 
     /// Tracked keys. For tests and for an operator asking whether the cap is
@@ -55,7 +80,7 @@ public:
 private:
     void sweepLocked(int64_t minute);
 
-    struct Window { int64_t minute = -1; uint32_t count = 0; };
+    struct Window { int64_t minute = -1; uint32_t count = 0; bool refusalLogged = false; };
     std::unordered_map<std::string, Window> windows_;
     std::function<int64_t()> now_;   // epoch seconds
     int64_t lastSweptMinute_ = -1;

+ 79 - 0
tests/test_rate_limiter.cpp

@@ -66,3 +66,82 @@ TEST(RateLimiter, CapacityClearsAfterASweepSoTheLimitComesBack) {
     EXPECT_TRUE(rl.allow("fresh", 2));
     EXPECT_FALSE(rl.allow("fresh", 2));
 }
+
+// ─── The logging hint: once per key per window, bounded by construction ───
+//
+// Asked for by a consumer worried about log volume. Their reasoning was right
+// for the per-function line and WRONG for the per-caller one, on a premise
+// worth recording: they argued the per-caller line was bounded by "distinct
+// abusive callers rather than request volume". It is not - a refused caller
+// that keeps sending is refused on every request, so one determined address
+// produces one line per request. These tests pin the behaviour that makes
+// both safe.
+
+TEST(RateLimiterDecision, OnlyTheFirstRefusalInAWindowIsFlagged) {
+    RateLimiter rl;
+    int64_t now = 1'000'000;
+    rl.setClockForTesting([&now] { return now; });
+
+    EXPECT_TRUE(rl.check("k", 1).allowed) << "the first call is under the limit";
+
+    const auto first = rl.check("k", 1);
+    EXPECT_FALSE(first.allowed);
+    EXPECT_TRUE(first.firstRefusalInWindow) << "the first refusal is the alert";
+
+    // THE POINT: a flood is refused on every request, and must log once.
+    for (int i = 0; i < 50; ++i) {
+        const auto again = rl.check("k", 1);
+        EXPECT_FALSE(again.allowed);
+        EXPECT_FALSE(again.firstRefusalInWindow)
+            << "refusal " << i << " must not be flagged; a line per refused request is "
+               "exactly the volume this flag exists to avoid";
+    }
+}
+
+TEST(RateLimiterDecision, ANewWindowGetsItsOwnFirstRefusal) {
+    // The pairing: without this, an operator sees one line ever and a flood
+    // that resumes an hour later is silent.
+    //
+    // WHAT THIS DOES NOT PIN, stated because the name would otherwise imply
+    // it: the property holds because the SWEEP erases the stale entry, not
+    // because of the explicit `refusalLogged = false`. Deleting that
+    // assignment leaves this test green - measured, not assumed. So this is a
+    // correct end-to-end assertion about the behaviour an operator sees, and
+    // it is NOT a test of the reset line. A future change that made the sweep
+    // lazy would break the property and this test would catch it, which is
+    // the coverage that matters.
+    RateLimiter rl;
+    int64_t now = 1'000'000;
+    rl.setClockForTesting([&now] { return now; });
+
+    rl.check("k", 1);
+    ASSERT_TRUE(rl.check("k", 1).firstRefusalInWindow);
+    ASSERT_FALSE(rl.check("k", 1).firstRefusalInWindow);
+
+    now += 60;  // next minute
+    EXPECT_TRUE(rl.check("k", 1).allowed) << "a new window admits again";
+    EXPECT_TRUE(rl.check("k", 1).firstRefusalInWindow)
+        << "the flag must reset per window, or a later flood is never reported";
+}
+
+TEST(RateLimiterDecision, TwoKeysAreFlaggedIndEPENDENTLY) {
+    // One caller being noisy must not silence the report about another, which
+    // is the case where the per-caller line is worth the most.
+    RateLimiter rl;
+    int64_t now = 1'000'000;
+    rl.setClockForTesting([&now] { return now; });
+
+    rl.check("a", 1); ASSERT_TRUE(rl.check("a", 1).firstRefusalInWindow);
+    ASSERT_FALSE(rl.check("a", 1).firstRefusalInWindow);
+
+    rl.check("b", 1);
+    EXPECT_TRUE(rl.check("b", 1).firstRefusalInWindow)
+        << "a second caller's first refusal is its own news";
+}
+
+TEST(RateLimiterDecision, AnUnlimitedKeyIsNeverRefusedAndNeverFlagged) {
+    RateLimiter rl;
+    const auto d = rl.check("k", 0);
+    EXPECT_TRUE(d.allowed);
+    EXPECT_FALSE(d.firstRefusalInWindow);
+}

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно