Class: ThrottleMachines::RackMiddleware::Allow2Ban

Inherits:
Object
  • Object
show all
Defined in:
lib/throttle_machines/rack_middleware/allow2_ban.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options, &block) ⇒ Allow2Ban



8
9
10
11
12
13
14
15
# File 'lib/throttle_machines/rack_middleware/allow2_ban.rb', line 8

def initialize(name, options, &block)
  @name = name
  @block = block

  @maxretry = options[:maxretry] || 5
  @findtime = options[:findtime] || 60
  @bantime = options[:bantime] || 300
end

Instance Attribute Details

#bantimeObject (readonly)

Returns the value of attribute bantime.



6
7
8
# File 'lib/throttle_machines/rack_middleware/allow2_ban.rb', line 6

def bantime
  @bantime
end

#blockObject (readonly)

Returns the value of attribute block.



6
7
8
# File 'lib/throttle_machines/rack_middleware/allow2_ban.rb', line 6

def block
  @block
end

#findtimeObject (readonly)

Returns the value of attribute findtime.



6
7
8
# File 'lib/throttle_machines/rack_middleware/allow2_ban.rb', line 6

def findtime
  @findtime
end

#maxretryObject (readonly)

Returns the value of attribute maxretry.



6
7
8
# File 'lib/throttle_machines/rack_middleware/allow2_ban.rb', line 6

def maxretry
  @maxretry
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/throttle_machines/rack_middleware/allow2_ban.rb', line 6

def name
  @name
end

Instance Method Details

#matched_by?(request) ⇒ Boolean



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/throttle_machines/rack_middleware/allow2_ban.rb', line 17

def matched_by?(request)
  discriminator = discriminator_for(request)
  return false unless discriminator

  # Allow2Ban resets fail2ban counters on successful requests
  # We'll track successful requests and reset the breaker when threshold is met

  success_key = "allow2ban:#{@name}:#{discriminator}"
  fail_key = "fail2ban:#{@name}:#{discriminator}"

  # Count successful requests
  success_limiter = ThrottleMachines.limiter(
    success_key,
    limit: @maxretry,
    period: @findtime,
    algorithm: :fixed_window
  )

  # Check if we've had enough successful requests
  if success_limiter.remaining.zero?
    # Reset the fail2ban breaker (use BreakerMachines circuit)
    breaker = BreakerMachines::Registry.instance.get_or_create_dynamic_circuit(
      fail_key,
      self,
      failure_threshold: @maxretry,
      failure_window: @findtime,
      reset_timeout: @bantime
    )
    breaker.hard_reset

    # Reset our own counter
    ThrottleMachines.storage.reset_counter(success_key, @findtime)
  else
    # Increment success counter
    begin
      success_limiter.throttle!
    rescue ThrottledError
      # We've hit the limit, which triggers the reset above
    end
  end

  false # Allow2Ban never blocks directly
end