gitlab-labkit 4.5.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d6850fbd8d4f1d8d81e2369bc5d27aa0638857e9cf32d2847a6c93f9efe84d9f
4
- data.tar.gz: ac6b4527b4a38f8917e25ed8576628e498e67e20cd4f0d3dfaf9696447cfd9a3
3
+ metadata.gz: 22a38c0fe1a2f28aa538b80348911947c6de64c16d7d870d24835332796faa99
4
+ data.tar.gz: 6259d696d178f3008aefdf91de71731c81d460cef08259555829f15d8abd462c
5
5
  SHA512:
6
- metadata.gz: 80803e406ce6e6da82ed72e252c2e6b59349aae34dc128eb1231688ca071a95ff125d93b882cbdd0ece94897f1ca1c7156cb3abba894421ba54d042e56b961c8
7
- data.tar.gz: 0b8afdf336ae0394ed6dcdea7f597968b3825c13ed01ce1a571a82078532d17e82733aa57a791bf52f26723ad0821be61b785355c25e75479019e605ca71d0de
6
+ metadata.gz: dd404f717fe9cee20cb544ad23cd5aa3195683ac0efe8bf8363988fdb8dcacc4fcaa817ac6f4cb3fcdb4f2e3d193c6d93cc13deea0344067e44fac7f3c593fb3
7
+ data.tar.gz: cc8d6bb5fe6fde8c17f969d4a708bd41901de5f9383f4821e3acf13a2eb35c240a80d18d3853ac5f29b689d7841df254f540233174646204358e698b9e0f643e
@@ -121,6 +121,29 @@ different question than `check`. A matched `:skip` rule terminates `peek`
121
121
  the same way it terminates `check`: matched, `:allow`, no Redis read, no
122
122
  `info`.
123
123
 
124
+ ### Clearing state
125
+
126
+ `Limiter#clear(identifier)` deletes this limiter's counters for one
127
+ identifier, along with any ban a rule carrying `ban_for` has written, and returns the
128
+ number of keys removed.
129
+
130
+ ```ruby
131
+ RACK_LIMITER.clear({ ip: "1.2.3.4" }) # => 2
132
+ ```
133
+
134
+ Counters otherwise only disappear when their window expires; this is the only
135
+ way to end one early. It exists for call sites where a later success should
136
+ wipe earlier failures, such as an authentication ban cleared by a valid
137
+ login.
138
+
139
+ Every rule in the limiter is cleared, matched or not, because a caller
140
+ clearing state after a success knows the identifier rather than which rules
141
+ happened to match on the way in. Each rule is deleted in its own call, since
142
+ rules do not share a Redis Cluster slot. Clearing an identifier with no state
143
+ is a no-op returning `0`. A Redis failure fails open like `check`, leaving the
144
+ rest of the state to expire on its own, and the return value counts whatever
145
+ was removed before the failure.
146
+
124
147
  ## Identifier
125
148
 
126
149
  `Identifier` is a small value object wrapping a hash of caller attributes.
@@ -150,6 +173,8 @@ A `Rule` is a `Data.define` value object with the following fields:
150
173
  | `period` | Window length in seconds. May be a callable resolved on every check. |
151
174
  | `action` | What the rule does when it matches. One of `:limit`, `:log`, `:skip`. Default `:limit`. See [Actions](#actions). |
152
175
  | `characteristics` | Array of identifier keys whose values are folded into the Redis counter key. Each unique combination gets its own counter. |
176
+ | `count_distinct` | Optional identifier key. When set, the rule counts distinct values seen for that key within the window, backed by a Redis SET rather than a counter. Must not overlap `characteristics`. |
177
+ | `ban_for` | Optional ban duration, whole seconds, minimum 1. Changes the accounting; `action` still decides who is blocked. Rejected on `:skip`. May be a callable resolved on every check. |
153
178
 
154
179
  Making `limit` or `period` callable is the supported pattern for
155
180
  runtime-tunable thresholds (e.g. feature flags or database-backed settings):
@@ -229,13 +254,15 @@ flowchart TD
229
254
  Match -->|yes| Skip{rule.action<br/>== :skip?}
230
255
  Skip -->|"yes (no Redis op)"| SkipEmit[Emit rule_evaluations_total<br/>action=skip, result=skip]
231
256
  SkipEmit --> SkipReturn([Return matched=true<br/>action=:allow])
232
- Skip -->|no| Eval["INCR Redis counter<br/>(see Redis sequence below)"]
257
+ Skip -->|no| Ban{"ban_for rule with<br/>a ban in force?"}
258
+ Ban -->|"yes (no increment)"| Build
259
+ Ban -->|no| Eval["INCR Redis counter<br/>(see Redis sequence below)"]
233
260
  Eval --> Build[Build Evaluation<br/>resolve limit/period]
234
261
  Build --> Add[Add evaluation to Result]
235
262
  Add --> Emit[Emit rule_evaluations_total<br/>+ limit/period gauges]
236
- Emit --> Act{"result.block?<br/>(:limit rule over limit)"}
263
+ Emit --> Act{"result.block?<br/>(:limit rule over its limit,<br/>or its ban in force)"}
237
264
  Act -->|yes| Return([Return Result<br/>action=:block])
238
- Act -->|"no (:log, or :limit under limit)"| Iter
265
+ Act -->|"no (:log, or under limit)"| Iter
239
266
  Iter -->|no more rules| Return2([Return Result reporting<br/>most-constraining evaluation,<br/>or matched=false if none])
240
267
  Return --> Check[Emit checks_total<br/>action, matched, error]
241
268
  SkipReturn --> Check
@@ -273,8 +300,9 @@ Metrics table below.
273
300
 
274
301
  The rule's `action` describes what the rule does; the result's `action`
275
302
  describes the outcome — what the caller should do — and is only ever `:allow`
276
- or `:block`. The Redis counter is always incremented when a rule matches,
277
- except for `:skip` rules, which never touch Redis. The `result` label on
303
+ or `:block`. A matching rule increments its counter, with two exceptions:
304
+ `:skip` rules never touch Redis, and a rule carrying `ban_for` whose ban is
305
+ already in force short-circuits before incrementing. The `result` label on
278
306
  `rule_evaluations_total` records what each evaluation decided:
279
307
 
280
308
  | rule action | what it does | exceeded? | result action | `result` label | terminating? |
@@ -285,6 +313,15 @@ except for `:skip` rules, which never touch Redis. The `result` label on
285
313
  | `:log` | count against the limit (observability only) | yes | `:allow` | `log` | no — continue |
286
314
  | `:skip` | don't count (bypass) | n/a | `:allow` | `skip` | yes — stop |
287
315
 
316
+ A rule may also carry `ban_for`, which changes the accounting rather than the
317
+ action. On crossing the limit it writes a ban that outlives the counting
318
+ window, and it stops counting while that ban holds:
319
+
320
+ | rule action | with `ban_for` | exceeded? | result action | `result` label | terminating? |
321
+ |-------------|-----------------------------------------------|-----------|---------------|----------------|---------------|
322
+ | `:limit` | count, or skip counting while banned | yes | `:block` | `banned` | yes — stop |
323
+ | `:log` | same accounting, records what it would do | yes | `:allow` | `banned` | no — continue |
324
+
288
325
  - `:limit` — when exceeded, `Result#action` is `:block` and evaluation
289
326
  terminates. Caller should reject the request (e.g. with HTTP 429). When under
290
327
  the limit, evaluation continues to the next rule.
@@ -301,15 +338,51 @@ except for `:skip` rules, which never touch Redis. The `result` label on
301
338
  inert and the result carries no `info` (`to_response_headers` is `{}`).
302
339
  The match is still observable via `rule_evaluations_total{action="skip"}`.
303
340
  Use this for bypasses.
341
+ - `ban_for` — enforcement that outlives the window, on either counting action.
342
+ On crossing the limit the rule writes a second key that keeps blocking for
343
+ `ban_for` seconds, long after the counter window has expired. While that ban
344
+ is in force the rule reports `exceeded? == true` and does not count, so a
345
+ caller cannot extend its own ban, and `reset_at` reports when the ban lifts
346
+ rather than when the window rolls. Use this where repeated failures should
347
+ cost more than a window, such as authentication attempts. State can be
348
+ discarded early with [`#clear`](#clearing-state).
349
+
350
+ With `action: :limit` the ban blocks. With `action: :log` the rule does all
351
+ of the same accounting, including writing the ban and suppressing counting
352
+ while it holds, and only skips the blocking, so a shadow measures what
353
+ enforcement would have produced rather than approximating it.
354
+
355
+ A `ban_for` shorter than `period` is legal but surprising: the ban can lapse
356
+ while the counter is still over the limit, so `peek` reports not-exceeded
357
+ while the next `check` re-bans immediately. Bans are normally longer than the
358
+ window they are counted in.
359
+
360
+ The duration is whole seconds and must be at least 1, since the ban is
361
+ written with `SET EX`. A callable is checked again each time it resolves, and
362
+ a value under a second raises rather than reaching Redis. Being an error, it
363
+ fails open like any other, so a rule whose `ban_for` cannot resolve stops
364
+ blocking entirely: watch `errors_total` after changing one.
365
+
366
+ Take care combining `ban_for` with `cost:`. One expensive call can cross the
367
+ limit on its own, and with a ban attached that costs the caller the whole ban
368
+ rather than a single rejection. Checking with `peek` first has the same edge,
369
+ since the call it deliberately lets through is enough to start a ban. Bans
370
+ suit counting discrete failures, such as bad credentials, better than they
371
+ suit variable-cost resource limits.
304
372
 
305
373
  ### Redis keys
306
374
 
307
375
  Each matched check writes a key shaped:
308
376
 
309
377
  ```
310
- labkit:rl:<limiter_name>:<rule_name>:<char>:<value>[:<char>:<value>...]
378
+ labkit:rl:{<limiter_name>:<rule_name>:<char>:<value>[:<char>:<value>...]}
311
379
  ```
312
380
 
381
+ The braces are a Redis [hash tag](https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/#hash-tags):
382
+ on a Redis Cluster only the braced part decides the slot, so every key for one
383
+ rule and identifier lands on the same shard. `BAN_SCRIPT` touches two keys in
384
+ one call, and a cluster rejects a script whose keys span slots.
385
+
313
386
  Characteristic values longer than 200 bytes are replaced with a SHA-256
314
387
  hexdigest to bound key length. Missing or empty characteristic values are
315
388
  encoded as `_unknown_`. The TTL is set on the first write of each window and
@@ -317,9 +390,24 @@ is not extended on subsequent increments, so the window is a true fixed
317
390
  window starting at the first request, not a sliding window.
318
391
 
319
392
  A check is a single `EVALSHA` of `INCR_SCRIPT` (or `SADD_SCRIPT` for
320
- `count_distinct` rules). Doing the whole read-modify-write inside Lua means
321
- there is no window between the increment and the `EXPIRE` in which a key
322
- could be left without a TTL.
393
+ `count_distinct` rules, or `BAN_SCRIPT` for rules carrying `ban_for`). Doing the whole
394
+ read-modify-write inside Lua means there is no window between the increment
395
+ and the `EXPIRE` in which a key could be left without a TTL.
396
+
397
+ A rule carrying `ban_for` writes a second key alongside its counter, sharing the
398
+ same hash tag and carrying its own `ban_for` TTL:
399
+
400
+ ```
401
+ labkit:rl:{<limiter_name>:<rule_name>:<char>:<value>[:<char>:<value>...]}:ban
402
+ ```
403
+
404
+ The suffix sits outside the tag, so it cannot change the slot and cannot
405
+ collide with a characteristic value, and both keys are found by the same
406
+ `labkit:rl:{<limiter>:<rule>*` glob. The ban key outlives its counter by
407
+ design: that is the whole point of `ban_for`.
408
+ `BAN_SCRIPT` checks the ban before incrementing, so the ban check,
409
+ the increment and the ban write are one atomic operation and a concurrent
410
+ check cannot miss the threshold crossing.
323
411
 
324
412
  ```mermaid
325
413
  sequenceDiagram
@@ -425,7 +513,7 @@ flooding).
425
513
  | metric | type | labels | meaning |
426
514
  |-----------------------------------------------------|---------|----------------------------------------------|----------------------------------------------------------------------|
427
515
  | `gitlab_labkit_rate_limiter_checks_total` | counter | `rate_limiter`, `action`, `matched`, `error` | Exactly one increment per `check` call, including fail-open. `action` is what the caller should do (`"allow"` or `"block"`); `matched` and `error` are `"true"`/`"false"`. |
428
- | `gitlab_labkit_rate_limiter_rule_evaluations_total` | counter | `rate_limiter`, `rule`, `action`, `result` | One increment per evaluated rule (plus one per matched `:skip` rule). `action` is the configured rule action (`"limit"`, `"log"`, `"skip"`); `result` is what the evaluation decided (`"allow"`, `"block"`, `"log"`, `"skip"` — see the Actions table). |
516
+ | `gitlab_labkit_rate_limiter_rule_evaluations_total` | counter | `rate_limiter`, `rule`, `action`, `result` | One increment per evaluated rule (plus one per matched `:skip` rule). `action` is the configured rule action (`"limit"`, `"log"`, `"skip"`); `result` is what the evaluation decided (`"allow"`, `"block"`, `"log"`, `"skip"`, `"banned"` — see the Actions table). |
429
517
  | `gitlab_labkit_rate_limiter_calls_total` | counter | `rate_limiter`, `rule`, `action` | **Deprecated** — superseded by `checks_total` + `rule_evaluations_total`. Historical per-rule counter: one increment per counted rule (plus one per matched `:skip` rule), `rule="unmatched", action="allow"` when no rule matched. Emitted unchanged during the transition. |
430
518
  | `gitlab_labkit_rate_limiter_errors_total` | counter | `rate_limiter` | **Deprecated** — use `checks_total{error="true"}`. Fail-open events (any `StandardError` in the labkit path); still the only error metric for `peek`. |
431
519
  | `gitlab_labkit_rate_limiter_limit` | gauge | `rate_limiter`, `rule` | Resolved limit at the last check (useful when `limit:` is callable). |
@@ -9,6 +9,7 @@ module Labkit
9
9
  # @api private
10
10
  class Evaluator
11
11
  REDIS_KEY_PREFIX = "labkit:rl"
12
+ BAN_KEY_SUFFIX = ":ban"
12
13
  CHAR_VALUE_MAX_LENGTH = 200
13
14
  MISSING_VALUE_SENTINEL = "_unknown_"
14
15
 
@@ -66,6 +67,50 @@ module Labkit
66
67
  return {count, ttl_after}
67
68
  LUA
68
69
 
70
+ # Atomic ban check + INCR + conditional ban write, for rules carrying
71
+ # ban_for.
72
+ #
73
+ # An active ban short-circuits before the increment, so a banned caller
74
+ # cannot extend its own window, matching Rack::Attack::Allow2Ban. This
75
+ # applies to :log rules too: a shadow that kept counting through its own
76
+ # ban would report more than enforcement would produce. The
77
+ # counter and the ban must be read and written together or a concurrent
78
+ # check can miss the threshold crossing.
79
+ #
80
+ # Returns {count, counter TTL, ban TTL}, where a ban TTL below zero means
81
+ # not banned.
82
+ BAN_SCRIPT = Labkit::Redis::Script.new(<<~LUA)
83
+ local rule_counter_key = KEYS[1]
84
+ local ban_key = KEYS[2]
85
+
86
+ local ttl = ARGV[1]
87
+ local cost = tonumber(ARGV[2])
88
+ local limit = tonumber(ARGV[3])
89
+ local ban_for = tonumber(ARGV[4])
90
+
91
+ -- TTL answers both questions at once: >= 0 means the ban key exists
92
+ -- and tells us how long is left, so no separate EXISTS is needed.
93
+ local ban_ttl = redis.call('TTL', ban_key)
94
+ if ban_ttl >= 0 then
95
+ local existing = redis.call('GET', rule_counter_key)
96
+ return {existing or '0', redis.call('TTL', rule_counter_key), ban_ttl}
97
+ end
98
+
99
+ local count = redis.call('INCRBYFLOAT', rule_counter_key, cost)
100
+ local ttl_after = redis.call('TTL', rule_counter_key)
101
+ if ttl_after < 0 then
102
+ redis.call('EXPIRE', rule_counter_key, ttl)
103
+ ttl_after = tonumber(ttl)
104
+ end
105
+
106
+ if tonumber(count) > limit then
107
+ redis.call('SET', ban_key, '1', 'EX', ban_for)
108
+ return {count, ttl_after, ban_for}
109
+ end
110
+
111
+ return {count, ttl_after, -1}
112
+ LUA
113
+
69
114
  def initialize(name:, rules:, redis:, logger:)
70
115
  @name = name
71
116
  @rules = rules
@@ -100,6 +145,41 @@ module Labkit
100
145
  Result.error
101
146
  end
102
147
 
148
+ # Deletes this limiter's counters, and any bans, for one identifier.
149
+ #
150
+ # Every rule is cleared, matched or not: a caller clearing state after a
151
+ # success knows the identifier, not which rules happened to match on the
152
+ # way in. Rules whose keys do not exist are a no-op.
153
+ #
154
+ # Fails open like {#check}: an unreachable Redis leaves the state to
155
+ # expire on its own rather than raising into the caller.
156
+ def clear(identifier)
157
+ # Counted as we go, so a connection lost mid-loop still reports the keys
158
+ # that did go rather than claiming nothing was cleared.
159
+ removed = 0
160
+
161
+ key_groups = @rules.filter_map do |rule|
162
+ next if rule.action == :skip
163
+
164
+ [build_redis_key(rule, identifier), build_redis_key(rule, identifier, BAN_KEY_SUFFIX)]
165
+ end
166
+
167
+ return 0 if key_groups.empty?
168
+
169
+ # One DEL per rule. The hash tag holds the rule name, so a rule's own
170
+ # keys share a slot but two rules do not, and Redis Cluster rejects a
171
+ # DEL spanning slots.
172
+ @redis.with do |conn|
173
+ key_groups.each { |group| removed += conn.del(*group) }
174
+ end
175
+
176
+ removed
177
+ rescue StandardError => e
178
+ report_error_metrics
179
+ log_error(e, identifier, nil)
180
+ removed
181
+ end
182
+
103
183
  private
104
184
 
105
185
  # Every rule that matches is evaluated and counted; matching does not
@@ -113,6 +193,10 @@ module Labkit
113
193
  # rejected and later rules cannot change that. Rules declared after it
114
194
  # are neither counted nor evaluated, so a blocked request debits every
115
195
  # rule up to and including the one that blocked, and none after it.
196
+ # A :limit rule carrying ban_for counts as over its limit for as long
197
+ # as its ban holds, so it terminates for the whole ban. The same rule
198
+ # with action :log does identical accounting and terminates nothing,
199
+ # which is what makes it a faithful shadow.
116
200
  #
117
201
  # Every other matched rule - :log, and :limit while under its limit - is
118
202
  # counted and collected into the returned Result, which reports the
@@ -212,6 +296,8 @@ module Labkit
212
296
  end
213
297
 
214
298
  def evaluate_rule(rule, identifier, cost, rule_context)
299
+ return evaluate_ban_rule(rule, identifier, cost, rule_context) if rule.ban_for
300
+
215
301
  redis_key = build_redis_key(rule, identifier)
216
302
  resolved_limit = Integer(resolve_value(rule.limit, rule_context))
217
303
  resolved_period = Integer(resolve_value(rule.period, rule_context))
@@ -229,6 +315,8 @@ module Labkit
229
315
  end
230
316
 
231
317
  def peek_rule(rule, identifier, rule_context)
318
+ return peek_ban_rule(rule, identifier, rule_context) if rule.ban_for
319
+
232
320
  redis_key = build_redis_key(rule, identifier)
233
321
  resolved_limit = Integer(resolve_value(rule.limit, rule_context))
234
322
  resolved_period = Integer(resolve_value(rule.period, rule_context))
@@ -237,6 +325,63 @@ module Labkit
237
325
  build_evaluation(rule, resolved_limit, resolved_period, count, ttl)
238
326
  end
239
327
 
328
+ def evaluate_ban_rule(rule, identifier, cost, rule_context)
329
+ resolved_limit = Integer(resolve_value(rule.limit, rule_context))
330
+ resolved_period = Integer(resolve_value(rule.period, rule_context))
331
+ resolved_ban_for = resolve_ban_for(rule, rule_context)
332
+
333
+ count, ttl, ban_ttl = ban_incr_with_ttl(
334
+ build_redis_key(rule, identifier),
335
+ build_redis_key(rule, identifier, BAN_KEY_SUFFIX),
336
+ resolved_period, cost, resolved_limit, resolved_ban_for
337
+ )
338
+
339
+ build_ban_evaluation(rule, resolved_limit, resolved_period, count, ttl, ban_ttl)
340
+ end
341
+
342
+ # A callable ban_for is only checked at construction, so it can still hand
343
+ # back something Redis would reject on the SET that writes the ban. Failing
344
+ # here names ban_for rather than surfacing a line number from the script.
345
+ def resolve_ban_for(rule, rule_context)
346
+ raw = resolve_value(rule.ban_for, rule_context)
347
+ seconds = Integer(raw, exception: false)
348
+ raise ArgumentError, "ban_for resolved to #{raw.inspect}, need at least 1 second" if seconds.nil? || seconds < 1
349
+
350
+ seconds
351
+ end
352
+
353
+ def peek_ban_rule(rule, identifier, rule_context)
354
+ resolved_limit = Integer(resolve_value(rule.limit, rule_context))
355
+ resolved_period = Integer(resolve_value(rule.period, rule_context))
356
+
357
+ count, ttl, ban_ttl = read_ban_with_ttl(
358
+ build_redis_key(rule, identifier),
359
+ build_redis_key(rule, identifier, BAN_KEY_SUFFIX)
360
+ )
361
+
362
+ build_ban_evaluation(rule, resolved_limit, resolved_period, count, ttl, ban_ttl)
363
+ end
364
+
365
+ # A ban blocks whether it was written by this call or an earlier one, so
366
+ # +exceeded+ tracks the ban rather than the count: once the counter window
367
+ # has expired the count can sit below the limit while the ban still holds.
368
+ # reset_at reports when the caller may retry, which is the ban expiry.
369
+ def build_ban_evaluation(rule, resolved_limit, resolved_period, count, ttl, ban_ttl)
370
+ banned = ban_ttl >= 0
371
+ window_remaining = ttl >= 0 ? ttl : resolved_period
372
+
373
+ info = Result::Info.new(
374
+ resolved_limit: resolved_limit, resolved_period: resolved_period,
375
+ count: count,
376
+ # A ban outlives its counter, so count reads 0 once the window has
377
+ # gone. Nothing is remaining while the ban still blocks.
378
+ remaining: banned ? 0 : [resolved_limit - count, 0].max,
379
+ reset_at: Time.now.utc + (banned ? ban_ttl : window_remaining)
380
+ )
381
+
382
+ Result::Evaluation.new(rule: rule, exceeded: banned, info: info)
383
+ end
384
+
240
385
  def build_evaluation(rule, resolved_limit, resolved_period, count, ttl)
241
386
  info = Result::Info.new(
242
387
  resolved_limit: resolved_limit, resolved_period: resolved_period,
@@ -248,12 +393,19 @@ module Labkit
248
393
  Result::Evaluation.new(rule: rule, exceeded: count > resolved_limit, info: info)
249
394
  end
250
395
 
251
- def build_redis_key(rule, identifier)
252
- key = "#{REDIS_KEY_PREFIX}:#{@name}:#{rule.name}"
396
+ # The limiter, rule and characteristics sit inside a Redis hash tag, so a
397
+ # counter and its ban always hash to the same cluster slot. BAN_SCRIPT
398
+ # touches both in one call, and Redis Cluster rejects a script whose keys
399
+ # span slots. +suffix+ is appended outside the tag, so it cannot change
400
+ # the slot and cannot collide with a characteristic value.
401
+ def build_redis_key(rule, identifier, suffix = nil)
402
+ key = "#{REDIS_KEY_PREFIX}:{#{@name}:#{rule.name}"
253
403
  rule.characteristics.each do |char|
254
404
  value = resolve_char_value(char, identifier)
255
- key += ":#{char}:#{encode_char_value(value)}"
405
+ key << ":#{char}:#{encode_char_value(value)}"
256
406
  end
407
+ key << "}"
408
+ key << suffix if suffix
257
409
  key
258
410
  end
259
411
 
@@ -311,6 +463,30 @@ module Labkit
311
463
  end
312
464
  end
313
465
 
466
+ # Atomic ban check + increment + conditional ban write. See BAN_SCRIPT.
467
+ # The returned ban TTL is negative when no ban is in force.
468
+ def ban_incr_with_ttl(counter_key, ban_key, period, cost, limit, ban_for)
469
+ @redis.with do |conn|
470
+ raw_count, ttl, ban_ttl = BAN_SCRIPT.eval(
471
+ conn, keys: [counter_key, ban_key], argv: [period, cost, limit, ban_for]
472
+ )
473
+ [Float(raw_count), Integer(ttl), Integer(ban_ttl)]
474
+ end
475
+ end
476
+
477
+ # Pipelined read of both keys for #peek. No EXPIRE and no SET: peeking a
478
+ # banned identifier must not extend either the window or the ban.
479
+ def read_ban_with_ttl(counter_key, ban_key)
480
+ @redis.with do |conn|
481
+ raw_count, ttl, ban_ttl = conn.pipelined do |pipe|
482
+ pipe.get(counter_key)
483
+ pipe.ttl(counter_key)
484
+ pipe.ttl(ban_key)
485
+ end
486
+ [raw_count.nil? ? 0.0 : Float(raw_count), Integer(ttl), Integer(ban_ttl)]
487
+ end
488
+ end
489
+
314
490
  # Pipelined GET + TTL. No EXPIRE: peek must not extend the window.
315
491
  # A missing key (GET => nil, TTL => -2) is reported as count=0; the
316
492
  # build_evaluation fallback then derives reset_at from the rule period
@@ -402,8 +578,13 @@ module Labkit
402
578
 
403
579
  # An exceeded :log rule reports "log" rather than the "allow" the caller
404
580
  # sees, so shadow rules over their limit stay visible.
581
+ # A ban is not a distinct action, so without this a blocking ban would be
582
+ # indistinguishable from an ordinary block. On a ban_for rule exceeded?
583
+ # means the ban is in force, whether this call wrote it or an earlier one
584
+ # did, which is exactly what is worth counting separately.
405
585
  def evaluation_result(evaluation)
406
586
  return "allow" unless evaluation.exceeded?
587
+ return "banned" if evaluation.rule.ban_for
407
588
 
408
589
  evaluation.rule.action == :limit ? "block" : "log"
409
590
  end
@@ -45,7 +45,7 @@ module Labkit
45
45
  # the rule definition and the call site colocated.
46
46
  # @return [Result]
47
47
  def check(identifier, cost: 1, rule_context: nil)
48
- id = identifier.is_a?(Identifier) ? identifier : Identifier.new(identifier)
48
+ id = to_identifier(identifier)
49
49
  @evaluator.check(id, cost: cost, rule_context: rule_context)
50
50
  end
51
51
 
@@ -65,12 +65,33 @@ module Labkit
65
65
  # @param rule_context [Hash, nil] see {#check}
66
66
  # @return [Result]
67
67
  def peek(identifier, rule_context: nil)
68
- id = identifier.is_a?(Identifier) ? identifier : Identifier.new(identifier)
68
+ id = to_identifier(identifier)
69
69
  @evaluator.peek(id, rule_context: rule_context)
70
70
  end
71
71
 
72
+ # Discards this limiter's state for one identifier: every rule's counter,
73
+ # and any ban written by a rule carrying ban_for.
74
+ #
75
+ # For call sites where a later success should wipe earlier failures, such
76
+ # as an authentication ban cleared by a valid login. Counters otherwise
77
+ # only expire with their window; this is the only way to end one early.
78
+ #
79
+ # Scoped to this limiter and identifier, not to a single rule: a caller
80
+ # clearing after a success knows who succeeded, not which rules matched.
81
+ #
82
+ # @param identifier [Identifier, Hash] caller attributes
83
+ # @return [Integer] number of Redis keys removed; on a Redis error, those
84
+ # removed before it failed
85
+ def clear(identifier)
86
+ @evaluator.clear(to_identifier(identifier))
87
+ end
88
+
72
89
  private
73
90
 
91
+ def to_identifier(identifier)
92
+ identifier.is_a?(Identifier) ? identifier : Identifier.new(identifier)
93
+ end
94
+
74
95
  def validate_name!(name)
75
96
  raise ArgumentError, "name must be a non-empty String" unless name.is_a?(String) && !name.empty?
76
97
  return name if NAME_PATTERN.match?(name)
@@ -133,9 +133,10 @@ module Labkit
133
133
  # exceeded - whether the post-increment count exceeded the resolved limit
134
134
  # info - Result::Info with the per-window counters
135
135
  #
136
- # Evaluations order by constraint: a blocking evaluation (:limit rule over
137
- # its limit) ranks strictly first - it decides the request no matter what
138
- # any other rule reports - then exceeded ones, then fewest remaining.
136
+ # Evaluations order by constraint: a blocking evaluation (a :limit rule over
137
+ # its limit, or one whose ban is still in force) ranks strictly first - it
138
+ # decides the request no matter what any other rule reports - then exceeded
139
+ # ones, then fewest remaining.
139
140
  # remaining floors at 0, so an exceeded :log rule ties with one sitting
140
141
  # exactly on its limit; ranking exceeded ahead keeps a breach from being
141
142
  # hidden by a rule that merely reached its limit.
@@ -14,10 +14,17 @@ module Labkit
14
14
  # period - window in seconds; may be a callable (resolved per check)
15
15
  # action - :limit (enforce; the result blocks when the rule is over
16
16
  # its limit, which also terminates evaluation), :log (count
17
- # and log only, never blocks and never terminates), or
18
- # :skip (bypass: permit and terminate evaluation on match
19
- # without counting; performs no Redis operation, so limit,
20
- # period, characteristics, and count_distinct are inert)
17
+ # and log only, never blocks and never terminates),
18
+ # or :skip (bypass: permit and terminate evaluation on
19
+ # match without counting; performs no Redis operation, so
20
+ # limit, period, characteristics, and count_distinct are
21
+ # inert)
22
+ # ban_for - optional ban duration in seconds. On crossing the limit
23
+ # the rule writes a separate ban key that outlives the
24
+ # counter window, and stops counting while it holds.
25
+ # +action+ still decides who is blocked: :limit enforces
26
+ # the ban, :log records what it would have done. Rejected
27
+ # on :skip. May be a callable, resolved per check.
21
28
  # characteristics - identifier keys used to build the compound Redis counter key
22
29
  # count_distinct - optional Symbol naming an identifier key. When set, the rule
23
30
  # counts the number of distinct values seen for that key within
@@ -28,7 +35,27 @@ module Labkit
28
35
  # +name+ must be a lowercase alphanumeric-and-underscore string of at most 64
29
36
  # characters. It is used as the middle segment of every Redis counter key for
30
37
  # this rule, so changing a rule's name mid-window abandons its in-flight counters.
31
- Rule = Data.define(:name, :match, :limit, :period, :action, :characteristics, :count_distinct) do
38
+ Rule = Data.define(:name, :match, :limit, :period, :action, :characteristics, :count_distinct, :ban_for) do
39
+ # ban_for changes the accounting; action still decides who gets blocked.
40
+ # A :skip rule counts nothing, so it has no limit to cross and no ban to
41
+ # write.
42
+ def self.normalize_ban_for(value, action_sym, count_distinct_sym)
43
+ return nil if value.nil?
44
+
45
+ raise ArgumentError, "ban_for is not valid on a :skip rule" if action_sym == :skip
46
+
47
+ # The ban path counts with INCRBYFLOAT, so a SET-backed rule would
48
+ # silently count calls instead of distinct values.
49
+ raise ArgumentError, "ban_for cannot be combined with count_distinct #{count_distinct_sym.inspect}" if count_distinct_sym
50
+
51
+ return value if value.respond_to?(:call)
52
+ # Whole seconds: the ban is written with SET EX, and anything under a
53
+ # second truncates to 0, which Redis rejects.
54
+ return value if value.is_a?(Numeric) && value >= 1
55
+
56
+ raise ArgumentError, "ban_for must be a Numeric of at least 1 second or a callable, got #{value.inspect}"
57
+ end
58
+
32
59
  def self.normalize_count_distinct(value, characteristics_arr)
33
60
  sym =
34
61
  case value
@@ -44,7 +71,10 @@ module Labkit
44
71
  sym
45
72
  end
46
73
 
47
- def initialize(name:, limit:, period:, characteristics:, match: {}, action: :limit, count_distinct: nil)
74
+ def initialize(
75
+ name:, limit:, period:, characteristics:,
76
+ match: {}, action: :limit, count_distinct: nil, ban_for: nil
77
+ )
48
78
  raise ArgumentError, "name must be a String or Symbol, got #{name.class}" unless name.is_a?(String) || name.is_a?(Symbol)
49
79
 
50
80
  name_str = name.to_s
@@ -59,6 +89,7 @@ module Labkit
59
89
  end
60
90
 
61
91
  characteristics_arr = Array(characteristics).map(&:to_sym).freeze
92
+ count_distinct_sym = self.class.normalize_count_distinct(count_distinct, characteristics_arr)
62
93
 
63
94
  super(
64
95
  name: name_str.freeze,
@@ -67,7 +98,8 @@ module Labkit
67
98
  period: period,
68
99
  action: action_sym,
69
100
  characteristics: characteristics_arr,
70
- count_distinct: self.class.normalize_count_distinct(count_distinct, characteristics_arr)
101
+ count_distinct: count_distinct_sym,
102
+ ban_for: self.class.normalize_ban_for(ban_for, action_sym, count_distinct_sym)
71
103
  )
72
104
  end
73
105
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gitlab-labkit
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.5.0
4
+ version: 4.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andrew Newdigate