ch-auth 0.3.2

Authentication and session primitives with explicit security policies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! In-process authentication rate limiting keyed by the TCP peer address.

use std::collections::hash_map::RandomState;
use std::hash::BuildHasher;
use std::net::IpAddr;
use std::num::{NonZeroU32, NonZeroUsize};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration as MonotonicDuration, Instant};

use dashmap::DashMap;
use time::Duration;

const DEFAULT_MAX_TRACKED_KEYS: usize = 10_000;
const PRUNE_EVERY_CHECKS: u64 = 256;

#[derive(Clone, Debug)]
struct TokenBucket {
    token_units: u128,
    capacity: u128,
    refill_interval_nanos: u128,
    last_refill_at: MonotonicDuration,
    last_seen_at: MonotonicDuration,
    last_seen_order: u64,
}

impl TokenBucket {
    fn new(
        capacity: NonZeroU32,
        refill_interval: MonotonicDuration,
        now: MonotonicDuration,
        access_order: u64,
    ) -> Self {
        let capacity = u128::from(capacity.get());
        let refill_interval_nanos = refill_interval.as_nanos();
        Self {
            token_units: capacity.saturating_mul(refill_interval_nanos),
            capacity,
            refill_interval_nanos,
            last_refill_at: now,
            last_seen_at: now,
            last_seen_order: access_order,
        }
    }

    fn refill(&mut self, now: MonotonicDuration) {
        if now <= self.last_refill_at {
            return;
        }
        let elapsed_nanos = now.saturating_sub(self.last_refill_at).as_nanos();
        let replenished = elapsed_nanos.saturating_mul(self.capacity);
        let maximum = self.capacity.saturating_mul(self.refill_interval_nanos);
        self.token_units = self.token_units.saturating_add(replenished).min(maximum);
        self.last_refill_at = now;
    }

    fn take(&mut self, now: MonotonicDuration, access_order: u64) -> (bool, u32, u64) {
        self.last_seen_at = now;
        self.last_seen_order = access_order;
        self.refill(now);
        if self.token_units >= self.refill_interval_nanos {
            self.token_units -= self.refill_interval_nanos;
            let remaining = self.token_units / self.refill_interval_nanos;
            return (true, u32::try_from(remaining).unwrap_or(u32::MAX), 0);
        }

        let missing_units = self.refill_interval_nanos - self.token_units;
        let retry_after_nanos = missing_units.div_ceil(self.capacity);
        let retry_after_secs =
            u64::try_from(retry_after_nanos.div_ceil(1_000_000_000).max(1)).unwrap_or(u64::MAX);
        (false, 0, retry_after_secs)
    }
}

/// Invalid token-bucket configuration.
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[error("rate-limit refill interval must be positive")]
pub struct RateLimiterConfigError;

/// Result of one rate-limit decision.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RateLimitOutcome {
    /// Whether the request may continue.
    pub allowed: bool,
    /// Tokens remaining after this decision.
    pub remaining: u32,
    /// Maximum bucket capacity.
    pub capacity: u32,
    /// Delay before a rejected client should retry.
    pub retry_after_secs: u64,
}

/// Bounded in-process token-bucket limiter.
///
/// This implementation is intentionally the simple single-instance default.
/// Applications that require cross-instance enforcement should place a
/// distributed limiter at their ingress or provide an application-owned
/// adapter instead of assuming this process-local state is global.
#[derive(Clone, Debug)]
pub struct RateLimiter {
    inner: Arc<RateLimiterInner>,
}

#[derive(Debug)]
struct RateLimiterInner {
    buckets: DashMap<u64, TokenBucket>,
    capacity: NonZeroU32,
    refill_interval: MonotonicDuration,
    max_tracked_keys: usize,
    checks: AtomicU64,
    access_sequence: AtomicU64,
    started_at: Instant,
    key_hasher: RandomState,
    admission: Mutex<()>,
}

impl RateLimiter {
    /// Creates a bounded token-bucket limiter.
    ///
    pub fn new(
        capacity: NonZeroU32,
        refill_interval: Duration,
    ) -> Result<Self, RateLimiterConfigError> {
        Self::with_max_tracked_keys(
            capacity,
            refill_interval,
            NonZeroUsize::new(DEFAULT_MAX_TRACKED_KEYS).expect("constant is non-zero"),
        )
    }

    /// Creates a limiter with an explicit bound for retained client keys.
    pub fn with_max_tracked_keys(
        capacity: NonZeroU32,
        refill_interval: Duration,
        max_tracked_keys: NonZeroUsize,
    ) -> Result<Self, RateLimiterConfigError> {
        let refill_interval = monotonic_duration(refill_interval)?;
        Ok(Self {
            inner: Arc::new(RateLimiterInner {
                buckets: DashMap::new(),
                capacity,
                refill_interval,
                max_tracked_keys: max_tracked_keys.get(),
                checks: AtomicU64::new(0),
                access_sequence: AtomicU64::new(0),
                started_at: Instant::now(),
                key_hasher: RandomState::new(),
                admission: Mutex::new(()),
            }),
        })
    }

    /// Applies the limiter using its monotonic process clock.
    #[must_use]
    pub fn check(&self, key: impl AsRef<str>) -> RateLimitOutcome {
        self.check_at_elapsed(key.as_ref(), self.inner.started_at.elapsed())
    }

    /// Removes the retained budget for one stable application-owned key.
    pub fn reset(&self, key: impl AsRef<str>) {
        let key = self.inner.key_hasher.hash_one(key.as_ref().as_bytes());
        self.inner.buckets.remove(&key);
    }

    fn check_at_elapsed(&self, key: &str, now: MonotonicDuration) -> RateLimitOutcome {
        self.prune_stale_buckets(now);
        let access_order = self.inner.access_sequence.fetch_add(1, Ordering::Relaxed);

        let key = self.inner.key_hasher.hash_one(key.as_bytes());
        if let Some(mut entry) = self.inner.buckets.get_mut(&key) {
            return outcome_from_bucket(entry.value_mut(), self.inner.capacity, now, access_order);
        }

        let _admission = self
            .inner
            .admission
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(mut entry) = self.inner.buckets.get_mut(&key) {
            return outcome_from_bucket(entry.value_mut(), self.inner.capacity, now, access_order);
        }
        self.make_room_for_key(now);
        self.inner.buckets.insert(
            key,
            TokenBucket::new(
                self.inner.capacity,
                self.inner.refill_interval,
                now,
                access_order,
            ),
        );
        let mut entry = self
            .inner
            .buckets
            .get_mut(&key)
            .expect("the admission lock inserts a missing bucket");
        outcome_from_bucket(entry.value_mut(), self.inner.capacity, now, access_order)
    }

    fn prune_stale_buckets(&self, now: MonotonicDuration) {
        let check = self.inner.checks.fetch_add(1, Ordering::Relaxed) + 1;
        if !check.is_multiple_of(PRUNE_EVERY_CHECKS) {
            return;
        }
        let _admission = self
            .inner
            .admission
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let stale_before = now.saturating_sub(self.inner.refill_interval.saturating_mul(2));
        self.inner
            .buckets
            .retain(|_, bucket| bucket.last_seen_at >= stale_before);
    }

    fn make_room_for_key(&self, now: MonotonicDuration) {
        if self.inner.buckets.len() < self.inner.max_tracked_keys {
            return;
        }

        let stale_before = now.saturating_sub(self.inner.refill_interval.saturating_mul(2));
        self.inner
            .buckets
            .retain(|_, bucket| bucket.last_seen_at >= stale_before);
        if self.inner.buckets.len() < self.inner.max_tracked_keys {
            return;
        }

        let oldest = self
            .inner
            .buckets
            .iter()
            .min_by_key(|entry| (entry.value().last_seen_at, entry.value().last_seen_order))
            .map(|entry| *entry.key());
        if let Some(oldest) = oldest {
            self.inner.buckets.remove(&oldest);
        }
    }
}

fn outcome_from_bucket(
    bucket: &mut TokenBucket,
    capacity: NonZeroU32,
    now: MonotonicDuration,
    access_order: u64,
) -> RateLimitOutcome {
    let (allowed, remaining, retry_after_secs) = bucket.take(now, access_order);
    RateLimitOutcome {
        allowed,
        remaining,
        capacity: capacity.get(),
        retry_after_secs,
    }
}

fn monotonic_duration(value: Duration) -> Result<MonotonicDuration, RateLimiterConfigError> {
    if !value.is_positive() {
        return Err(RateLimiterConfigError);
    }
    let nanoseconds = value.whole_nanoseconds();
    let nanoseconds = u64::try_from(nanoseconds).map_err(|_| RateLimiterConfigError)?;
    Ok(MonotonicDuration::from_nanos(nanoseconds))
}

/// Authentication operation whose budget was exceeded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AuthRateLimitScope {
    /// Login attempts from one client address.
    LoginIp,
    /// Login attempts for one normalized account identifier.
    LoginAccount,
    /// Two-factor attempts from one client address.
    TwoFactorIp,
    /// Two-factor attempts for one server-owned account.
    TwoFactorAccount,
    /// Registration attempts from one client address.
    RegistrationIp,
    /// Password-reset attempts from one client address.
    PasswordResetIp,
}

/// Rejected authentication rate-limit decision.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("authentication rate limit exceeded for {scope:?}")]
pub struct AuthRateLimitRejection {
    /// Budget that rejected the request.
    pub scope: AuthRateLimitScope,
    /// Token-bucket decision details.
    pub outcome: RateLimitOutcome,
}

/// Authentication request budgets supplied at startup.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AuthRateLimitPolicy {
    /// Login attempts per client and minute.
    pub login_ip_per_minute: NonZeroU32,
    /// Login attempts per normalized account identifier and minute.
    pub login_account_per_minute: NonZeroU32,
    /// Two-factor attempts per client and minute.
    pub two_factor_ip_per_minute: NonZeroU32,
    /// Two-factor attempts per account and minute, across challenges and clients.
    pub two_factor_account_per_minute: NonZeroU32,
    /// Registration attempts per client and minute.
    pub registration_ip_per_minute: NonZeroU32,
}

impl Default for AuthRateLimitPolicy {
    fn default() -> Self {
        Self {
            login_ip_per_minute: NonZeroU32::new(10).expect("constant is non-zero"),
            login_account_per_minute: NonZeroU32::new(5).expect("constant is non-zero"),
            two_factor_ip_per_minute: NonZeroU32::new(10).expect("constant is non-zero"),
            two_factor_account_per_minute: NonZeroU32::new(5).expect("constant is non-zero"),
            registration_ip_per_minute: NonZeroU32::new(5).expect("constant is non-zero"),
        }
    }
}

/// Authentication limiters shared through app state.
#[derive(Clone, Debug)]
pub struct SecurityState {
    /// CAPTCHA issue budget.
    pub captcha_issuance: RateLimiter,
    /// CAPTCHA validation budget by client.
    pub captcha_validation_ip: RateLimiter,
    /// CAPTCHA validation budget by account identifier.
    pub captcha_validation_account: RateLimiter,
    login_ip: RateLimiter,
    login_account: RateLimiter,
    two_factor_ip: RateLimiter,
    two_factor_account: RateLimiter,
    registration_ip: RateLimiter,
    password_reset_ip: RateLimiter,
}

impl SecurityState {
    /// Creates the default authentication policy.
    #[must_use]
    pub fn new(captcha_budget_per_minute: NonZeroU32) -> Self {
        Self::with_auth_policy(captcha_budget_per_minute, AuthRateLimitPolicy::default())
    }

    /// Creates custom authentication budgets.
    #[must_use]
    pub fn with_auth_policy(
        captcha_budget_per_minute: NonZeroU32,
        auth_policy: AuthRateLimitPolicy,
    ) -> Self {
        let per_minute = Duration::minutes(1);
        Self {
            captcha_issuance: RateLimiter::new(captcha_budget_per_minute, per_minute)
                .expect("one minute is a valid refill interval"),
            captcha_validation_ip: RateLimiter::new(captcha_budget_per_minute, per_minute)
                .expect("one minute is a valid refill interval"),
            captcha_validation_account: RateLimiter::new(captcha_budget_per_minute, per_minute)
                .expect("one minute is a valid refill interval"),
            login_ip: RateLimiter::new(auth_policy.login_ip_per_minute, per_minute)
                .expect("one minute is a valid refill interval"),
            login_account: RateLimiter::new(auth_policy.login_account_per_minute, per_minute)
                .expect("one minute is a valid refill interval"),
            two_factor_ip: RateLimiter::new(auth_policy.two_factor_ip_per_minute, per_minute)
                .expect("one minute is a valid refill interval"),
            two_factor_account: RateLimiter::new(
                auth_policy.two_factor_account_per_minute,
                per_minute,
            )
            .expect("one minute is a valid refill interval"),
            registration_ip: RateLimiter::new(auth_policy.registration_ip_per_minute, per_minute)
                .expect("one minute is a valid refill interval"),
            password_reset_ip: RateLimiter::new(
                NonZeroU32::new(5).expect("constant is non-zero"),
                per_minute,
            )
            .expect("one minute is a valid refill interval"),
        }
    }

    /// Derives a stable client key from the connection's TCP peer address.
    #[must_use]
    pub fn client_key(&self, peer_ip: IpAddr) -> String {
        peer_ip.to_string()
    }

    /// Checks both client and normalized account login budgets.
    pub fn check_login(
        &self,
        client_key: &str,
        account_identifier: &str,
    ) -> Result<(), AuthRateLimitRejection> {
        check_auth_limiter(
            &self.login_ip,
            format!("login:ip:{client_key}"),
            AuthRateLimitScope::LoginIp,
        )?;
        check_auth_limiter(
            &self.login_account,
            format!("login:account:{}", account_identifier.trim().to_lowercase()),
            AuthRateLimitScope::LoginAccount,
        )
    }

    /// Clears login budgets after credentials have been accepted.
    ///
    /// Invalid attempts remain rate limited, while successful sign-ins do not
    /// accumulate into a lockout for the same client or account.
    pub fn reset_login(&self, client_key: &str, account_identifier: &str) {
        self.login_ip.reset(format!("login:ip:{client_key}"));
        self.login_account.reset(format!(
            "login:account:{}",
            account_identifier.trim().to_lowercase()
        ));
    }

    /// Checks the two-factor budget.
    pub fn check_two_factor(&self, client_key: &str) -> Result<(), AuthRateLimitRejection> {
        check_auth_limiter(
            &self.two_factor_ip,
            format!("two-factor:ip:{client_key}"),
            AuthRateLimitScope::TwoFactorIp,
        )
    }

    /// Checks the account budget after validating a server-issued challenge.
    /// The account key is shared across login and settings verification.
    pub fn check_two_factor_account(&self, account_id: &str) -> Result<(), AuthRateLimitRejection> {
        check_auth_limiter(
            &self.two_factor_account,
            account_id,
            AuthRateLimitScope::TwoFactorAccount,
        )
    }

    /// Checks the registration budget.
    pub fn check_registration(&self, client_key: &str) -> Result<(), AuthRateLimitRejection> {
        check_auth_limiter(
            &self.registration_ip,
            format!("registration:ip:{client_key}"),
            AuthRateLimitScope::RegistrationIp,
        )
    }

    /// Checks the password-reset budget before request parsing or password hashing.
    pub fn check_password_reset(&self, client_key: &str) -> Result<(), AuthRateLimitRejection> {
        check_auth_limiter(
            &self.password_reset_ip,
            format!("password-reset:ip:{client_key}"),
            AuthRateLimitScope::PasswordResetIp,
        )
    }
}

fn check_auth_limiter(
    limiter: &RateLimiter,
    key: impl AsRef<str>,
    scope: AuthRateLimitScope,
) -> Result<(), AuthRateLimitRejection> {
    let outcome = limiter.check(key);
    if outcome.allowed {
        Ok(())
    } else {
        Err(AuthRateLimitRejection { scope, outcome })
    }
}

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr};
    use std::num::{NonZeroU32, NonZeroUsize};

    use time::Duration;

    use super::{AuthRateLimitPolicy, RateLimiter, SecurityState};

    #[test]
    fn second_factor_account_budget_survives_client_changes_and_password_success() {
        let security = SecurityState::with_auth_policy(
            100.try_into().unwrap(),
            AuthRateLimitPolicy {
                two_factor_account_per_minute: 2.try_into().unwrap(),
                ..AuthRateLimitPolicy::default()
            },
        );
        assert!(security.check_two_factor("192.0.2.1").is_ok());
        assert!(security.check_two_factor_account("account-a").is_ok());
        security.reset_login("192.0.2.1", "account-a");
        assert!(security.clone().check_two_factor("192.0.2.2").is_ok());
        assert!(
            security
                .clone()
                .check_two_factor_account("account-a")
                .is_ok()
        );
        let rejected = security
            .check_two_factor_account("account-a")
            .expect_err("account budget exhausted");
        assert_eq!(rejected.scope, super::AuthRateLimitScope::TwoFactorAccount);
        assert!(security.check_two_factor_account("account-b").is_ok());
    }

    #[test]
    fn cloned_rate_limiter_shares_buckets() {
        let limiter = RateLimiter::new(NonZeroU32::new(1).unwrap(), Duration::minutes(1))
            .expect("valid limiter");
        let cloned = limiter.clone();
        assert!(limiter.check("same").allowed);
        assert!(!cloned.check("same").allowed);
    }

    #[test]
    fn rejects_non_positive_refill_intervals() {
        assert!(RateLimiter::new(NonZeroU32::new(1).unwrap(), Duration::ZERO).is_err());
    }

    #[test]
    fn bounded_limiter_evicts_oldest_key_without_a_shared_overflow_bucket() {
        let limiter = RateLimiter::with_max_tracked_keys(
            NonZeroU32::new(1).unwrap(),
            Duration::minutes(1),
            NonZeroUsize::new(2).unwrap(),
        )
        .expect("valid limiter");
        let start = std::time::Duration::ZERO;
        assert!(limiter.check_at_elapsed("one", start).allowed);
        assert!(limiter.check_at_elapsed("two", start).allowed);
        assert!(limiter.check_at_elapsed("three", start).allowed);
        assert!(limiter.check_at_elapsed("one", start).allowed);
        assert!(limiter.inner.buckets.len() <= 2);
    }

    #[test]
    fn auth_budgets_are_independent() {
        let state = SecurityState::new(NonZeroU32::new(1).unwrap());
        assert!(state.check_login("client", "user@example.test").is_ok());
        assert!(state.check_registration("client").is_ok());
        assert!(state.check_two_factor("client").is_ok());
        assert!(state.check_password_reset("client").is_ok());
    }

    #[test]
    fn password_reset_budget_is_bounded_per_client_address() {
        let state = SecurityState::new(NonZeroU32::new(100).unwrap());

        for _ in 0..5 {
            assert!(state.check_password_reset("client-a").is_ok());
        }
        let rejection = state
            .check_password_reset("client-a")
            .expect_err("sixth reset attempt in one minute must be rejected");
        assert_eq!(rejection.scope, super::AuthRateLimitScope::PasswordResetIp);
        assert!(state.check_password_reset("client-b").is_ok());
    }

    #[test]
    fn accepted_login_can_reset_consumed_client_and_account_budgets() {
        let one = NonZeroU32::new(1).unwrap();
        let state = SecurityState::with_auth_policy(
            one,
            AuthRateLimitPolicy {
                login_ip_per_minute: one,
                login_account_per_minute: one,
                two_factor_ip_per_minute: one,
                two_factor_account_per_minute: one,
                registration_ip_per_minute: one,
            },
        );

        assert!(state.check_login("client", "user@example.test").is_ok());
        assert!(state.check_login("client", "user@example.test").is_err());

        state.reset_login("client", " USER@EXAMPLE.TEST ");

        assert!(state.check_login("client", "user@example.test").is_ok());
    }

    #[test]
    fn client_keys_use_the_tcp_peer_address() {
        let state = SecurityState::new(NonZeroU32::new(1).unwrap());
        let peer_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 40));
        assert_eq!(state.client_key(peer_ip), "192.0.2.40");
    }
}