Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix reset! when using namespaced cache store #673

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/rack/attack/cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def delete(unprefixed_key)

def reset!
if store.respond_to?(:delete_matched)
store.delete_matched("#{prefix}*")
store.delete_matched(/#{prefix}*/)
else
raise(
Rack::Attack::IncompatibleStoreError,
Expand Down
3 changes: 2 additions & 1 deletion lib/rack/attack/store_proxy/redis_proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ def delete(key, _options = {})

def delete_matched(matcher, _options = nil)
cursor = "0"
source = matcher.source

rescuing do
# Fetch keys in batches using SCAN to avoid blocking the Redis server.
loop do
cursor, keys = scan(cursor, match: matcher, count: 1000)
cursor, keys = scan(cursor, match: source, count: 1000)
del(*keys) unless keys.empty?
break if cursor == "0"
end
Expand Down
26 changes: 26 additions & 0 deletions spec/rack_attack_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,31 @@
_(redis.get("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
end

if defined?(Redis) && defined?(ActiveSupport::Cache::RedisCacheStore)
it 'should delete rack attack keys' do
redis_cache_store = ActiveSupport::Cache::RedisCacheStore.new(namespace: 'ns')
redis_cache_store.write('key', 'value')
redis_cache_store.write("#{Rack::Attack.cache.prefix}::key", 'value')
Rack::Attack.cache.store = redis_cache_store
Rack::Attack.reset!

_(redis_cache_store.read('key')).must_equal 'value'
_(redis_cache_store.read("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
end

if defined?(ActiveSupport::Cache::MemoryStore)
it 'should delete rack attack keys' do
memory_store = ActiveSupport::Cache::MemoryStore.new(namespace: 'ns')
memory_store.write('key', 'value')
memory_store.write("#{Rack::Attack.cache.prefix}::key", 'value')
Rack::Attack.cache.store = memory_store
Rack::Attack.reset!

_(memory_store.read('key')).must_equal 'value'
_(memory_store.read("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
end
end
end
Loading