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

Add a contains_key method #172

Open
wants to merge 3 commits into
base: master
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
4 changes: 4 additions & 0 deletions governor/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
`DefaultKeyedRateLimiter` to cut down on type-typing of typical rate
limiters in struct and function definitions. Requested in
[#85](https://github.com/antifuchs/governor/issues/85).
* New method `contains_key` that can be used to check if a
`RateLimiter` has a given key (which can be used to prevent
arbitrary attacker-controlled memory usage in case of a DDoS
attack).

### Changed
* The API for `.check_n` and `.until_n` (and their keyed counterpart)
Expand Down
2 changes: 2 additions & 0 deletions governor/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ pub trait StateStore {
fn measure_and_replace<T, F, E>(&self, key: &Self::Key, f: F) -> Result<T, E>
where
F: Fn(Option<Nanos>) -> Result<(T, Nanos), E>;

fn contains_key(&self, key: &Self::Key) -> bool;
}

/// A rate limiter.
Expand Down
6 changes: 6 additions & 0 deletions governor/src/state/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,10 @@ mod test {
fn not_keyed_impls_coverage() {
assert_eq!(NotKeyed::NonKey, NotKeyed::NonKey);
}

#[test]
fn not_keyed_contains_key_impls_coverage() {
let state = InMemoryState::default();
assert!(state.contains_key(&NotKeyed::NonKey));
}
}
4 changes: 4 additions & 0 deletions governor/src/state/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ impl StateStore for InMemoryState {
{
self.measure_and_replace_one(f)
}

fn contains_key(&self, _key: &Self::Key) -> bool {
true
}
}

impl Debug for InMemoryState {
Expand Down
16 changes: 16 additions & 0 deletions governor/src/state/keyed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,17 @@ where
C: clock::Clock,
MW: RateLimitingMiddleware<C::Instant>,
{
/// Check whether a given key already exists in the state store.
///
/// This method returns true if the key is already occupying
/// memory (that is, if an underlying hash map state store would
/// return true on its `contains_key` method). Particularly, it will
/// also return true on keys that would be dropped by
/// [`ShrinkableKeyedStateStore::retain_recent`].
pub fn contains_key(&self, key: &K) -> bool {
self.state.contains_key(key)
}

/// Allow a single cell through the rate limiter for the given key.
///
/// If the rate limit is reached, `check_key` returns information about the earliest
Expand Down Expand Up @@ -252,6 +263,10 @@ mod test {
impl<K: Hash + Eq + Clone> StateStore for NaiveKeyedStateStore<K> {
type Key = K;

fn contains_key(&self, _key: &Self::Key) -> bool {
false
}

fn measure_and_replace<T, F, E>(&self, _key: &Self::Key, f: F) -> Result<T, E>
where
F: Fn(Option<Nanos>) -> Result<(T, Nanos), E>,
Expand Down Expand Up @@ -283,6 +298,7 @@ mod test {
NaiveKeyedStateStore::default(),
&FakeRelativeClock::default(),
);
assert_eq!(false, lim.contains_key(&1u32));
assert_eq!(lim.check_key(&1u32), Ok(()));
assert!(lim.is_empty());
assert_eq!(lim.len(), 0);
Expand Down
4 changes: 4 additions & 0 deletions governor/src/state/keyed/dashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ impl<K: Hash + Eq + Clone> StateStore for DashMapStateStore<K> {
let entry = self.entry(key.clone()).or_default();
(*entry).measure_and_replace_one(f)
}

fn contains_key(&self, key: &Self::Key) -> bool {
self.contains_key(key)
}
}

/// # Keyed rate limiters - [`DashMap`]-backed
Expand Down
5 changes: 5 additions & 0 deletions governor/src/state/keyed/hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ impl<K: Hash + Eq + Clone> StateStore for HashMapStateStore<K> {
.or_insert_with(InMemoryState::default);
entry.measure_and_replace_one(f)
}

fn contains_key(&self, key: &Self::Key) -> bool {
let map = self.lock();
(*map).contains_key(key)
}
}

impl<K: Hash + Eq + Clone> ShrinkableKeyedStateStore<K> for HashMapStateStore<K> {
Expand Down
2 changes: 2 additions & 0 deletions governor/tests/keyed_dashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ fn accepts_first_cell() {
let clock = FakeRelativeClock::default();
let lb = RateLimiter::dashmap_with_clock(Quota::per_second(nonzero!(5u32)), &clock);
for key in KEYS {
assert!(!lb.contains_key(&key));
assert_eq!(Ok(()), lb.check_key(&key), "key {:?}", key);
assert!(lb.contains_key(&key));
}
}

Expand Down
2 changes: 2 additions & 0 deletions governor/tests/keyed_hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ fn accepts_first_cell() {
let clock = FakeRelativeClock::default();
let lb = RateLimiter::hashmap_with_clock(Quota::per_second(nonzero!(5u32)), &clock);
for key in KEYS {
assert!(!lb.contains_key(&key));
assert_eq!(Ok(()), lb.check_key(&key), "key {:?}", key);
assert!(lb.contains_key(&key));
}
}

Expand Down