rustauth-core 0.2.0

Core types and primitives for RustAuth.
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
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use time::Duration as TimeDuration;

use http::Request;

use super::model_schema::ModelSchemaOptions;
use crate::error::RustAuthError;

/// Rate limiting defaults.
#[derive(Clone)]
pub struct RateLimitOptions {
    pub schema: ModelSchemaOptions,
    pub enabled: Option<bool>,
    pub window: TimeDuration,
    pub max: u64,
    pub storage: RateLimitStorageOption,
    pub custom_rules: Vec<RateLimitPathRule>,
    pub dynamic_rules: Vec<DynamicRateLimitPathRule>,
    pub custom_store: Option<Arc<dyn RateLimitStore>>,
    pub custom_storage: Option<Arc<dyn RateLimitStorage>>,
    pub hybrid: HybridRateLimitOptions,
    pub memory_cleanup_interval: Option<Duration>,
    pub missing_ip_policy: MissingIpPolicy,
}

impl Default for RateLimitOptions {
    fn default() -> Self {
        Self {
            schema: ModelSchemaOptions::default(),
            enabled: None,
            window: TimeDuration::seconds(10),
            max: 100,
            storage: RateLimitStorageOption::Memory,
            custom_rules: Vec::new(),
            dynamic_rules: Vec::new(),
            custom_store: None,
            custom_storage: None,
            hybrid: HybridRateLimitOptions::default(),
            memory_cleanup_interval: Some(Duration::from_secs(60 * 60)),
            missing_ip_policy: MissingIpPolicy::default(),
        }
    }
}

impl RateLimitOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn builder() -> Self {
        Self::new()
    }

    #[must_use]
    pub fn schema(mut self, schema: ModelSchemaOptions) -> Self {
        self.schema = schema;
        self
    }

    pub fn memory() -> Self {
        Self {
            storage: RateLimitStorageOption::Memory,
            ..Self::default()
        }
    }

    pub fn database<S>(store: S) -> Self
    where
        S: RateLimitStore,
    {
        Self::database_arc(Arc::new(store))
    }

    pub fn database_arc(store: Arc<dyn RateLimitStore>) -> Self {
        Self {
            storage: RateLimitStorageOption::Database,
            custom_store: Some(store),
            ..Self::default()
        }
    }

    pub fn secondary_storage<S>(store: S) -> Self
    where
        S: RateLimitStore,
    {
        Self::secondary_storage_arc(Arc::new(store))
    }

    pub fn secondary_storage_arc(store: Arc<dyn RateLimitStore>) -> Self {
        Self {
            storage: RateLimitStorageOption::SecondaryStorage,
            custom_store: Some(store),
            ..Self::default()
        }
    }

    #[must_use]
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }

    #[must_use]
    pub fn window(mut self, window: TimeDuration) -> Self {
        self.window = window;
        self
    }

    #[must_use]
    pub fn max(mut self, max: u64) -> Self {
        self.max = max;
        self
    }

    #[must_use]
    pub fn storage(mut self, storage: RateLimitStorageOption) -> Self {
        self.storage = storage;
        self
    }

    #[must_use]
    pub fn custom_store<S>(mut self, store: S) -> Self
    where
        S: RateLimitStore,
    {
        self.custom_store = Some(Arc::new(store));
        self
    }

    #[must_use]
    pub fn custom_store_arc(mut self, store: Arc<dyn RateLimitStore>) -> Self {
        self.custom_store = Some(store);
        self
    }

    #[must_use]
    pub fn custom_storage(mut self, storage: Arc<dyn RateLimitStorage>) -> Self {
        self.custom_storage = Some(storage);
        self
    }

    #[must_use]
    pub fn custom_rule(mut self, path: impl Into<String>, rule: RateLimitRule) -> Self {
        self.custom_rules.push(RateLimitPathRule {
            path: path.into(),
            rule: Some(rule),
        });
        self
    }

    #[must_use]
    pub fn disabled_path(mut self, path: impl Into<String>) -> Self {
        self.custom_rules.push(RateLimitPathRule {
            path: path.into(),
            rule: None,
        });
        self
    }

    #[must_use]
    pub fn dynamic_rule<P>(mut self, path: impl Into<String>, provider: P) -> Self
    where
        P: RateLimitRuleProvider,
    {
        self.dynamic_rules
            .push(DynamicRateLimitPathRule::new(path, provider));
        self
    }

    #[must_use]
    pub fn hybrid(mut self, hybrid: HybridRateLimitOptions) -> Self {
        self.hybrid = hybrid;
        self
    }

    #[must_use]
    pub fn memory_cleanup_interval(mut self, interval: Option<Duration>) -> Self {
        self.memory_cleanup_interval = interval;
        self
    }

    #[must_use]
    pub fn missing_ip_policy(mut self, policy: MissingIpPolicy) -> Self {
        self.missing_ip_policy = policy;
        self
    }
}

impl fmt::Debug for RateLimitOptions {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RateLimitOptions")
            .field("enabled", &self.enabled)
            .field("window", &self.window)
            .field("max", &self.max)
            .field("storage", &self.storage)
            .field("custom_rules", &self.custom_rules)
            .field("dynamic_rules", &self.dynamic_rules)
            .field(
                "custom_store",
                &self.custom_store.as_ref().map(|_| "<custom-store>"),
            )
            .field(
                "custom_storage",
                &self.custom_storage.as_ref().map(|_| "<custom-storage>"),
            )
            .field("hybrid", &self.hybrid)
            .field("memory_cleanup_interval", &self.memory_cleanup_interval)
            .field("missing_ip_policy", &self.missing_ip_policy)
            .finish()
    }
}

/// A single rate-limit bucket rule.
///
/// `window` is the sliding window length in **seconds** (not milliseconds).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitRule {
    /// Sliding window length in seconds.
    pub window: TimeDuration,
    pub max: u64,
}

impl RateLimitRule {
    pub fn new(window: TimeDuration, max: u64) -> Self {
        Self { window, max }
    }
}

/// Rejects invalid rate-limit rules before any store consumes a record.
pub fn validate_rate_limit_rule(rule: &RateLimitRule) -> Result<i64, RustAuthError> {
    if rule.window.is_zero() {
        return Err(RustAuthError::InvalidConfig(
            "rate limit window must be greater than zero".to_owned(),
        ));
    }
    if rule.max == 0 {
        return Err(RustAuthError::InvalidConfig(
            "rate limit max must be greater than zero".to_owned(),
        ));
    }
    let milliseconds = rule.window.whole_milliseconds();
    if milliseconds <= 0 {
        return Err(RustAuthError::InvalidConfig(
            "rate limit window must be greater than zero".to_owned(),
        ));
    }
    let window_ms = i64::try_from(milliseconds)
        .map_err(|_| RustAuthError::InvalidConfig("rate limit window is too large".to_owned()))?;
    i64::try_from(rule.max)
        .map_err(|_| RustAuthError::InvalidConfig("rate limit max must fit in i64".to_owned()))?;
    Ok(window_ms)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HybridRateLimitOptions {
    pub enabled: bool,
    pub local_multiplier: u64,
}

impl Default for HybridRateLimitOptions {
    fn default() -> Self {
        Self {
            enabled: false,
            local_multiplier: 2,
        }
    }
}

impl HybridRateLimitOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn builder() -> Self {
        Self::new()
    }

    pub fn enabled() -> Self {
        Self {
            enabled: true,
            ..Self::default()
        }
    }

    pub fn disabled() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn set_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    #[must_use]
    pub fn local_multiplier(mut self, multiplier: u64) -> Self {
        self.local_multiplier = multiplier;
        self
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitPathRule {
    pub path: String,
    pub rule: Option<RateLimitRule>,
}

pub trait RateLimitRuleProvider: Send + Sync + 'static {
    fn resolve(
        &self,
        request: &Request<Vec<u8>>,
        current_rule: &RateLimitRule,
    ) -> Result<Option<RateLimitRule>, RustAuthError>;
}

impl<F> RateLimitRuleProvider for F
where
    F: Fn(&Request<Vec<u8>>, &RateLimitRule) -> Result<Option<RateLimitRule>, RustAuthError>
        + Send
        + Sync
        + 'static,
{
    fn resolve(
        &self,
        request: &Request<Vec<u8>>,
        current_rule: &RateLimitRule,
    ) -> Result<Option<RateLimitRule>, RustAuthError> {
        self(request, current_rule)
    }
}

#[derive(Clone)]
pub struct DynamicRateLimitPathRule {
    pub path: String,
    pub provider: Arc<dyn RateLimitRuleProvider>,
}

impl DynamicRateLimitPathRule {
    pub fn new<P>(path: impl Into<String>, provider: P) -> Self
    where
        P: RateLimitRuleProvider,
    {
        Self {
            path: path.into(),
            provider: Arc::new(provider),
        }
    }
}

impl fmt::Debug for DynamicRateLimitPathRule {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DynamicRateLimitPathRule")
            .field("path", &self.path)
            .field("provider", &"<request-aware>")
            .finish()
    }
}

/// Rate limit storage record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitRecord {
    pub key: String,
    pub count: u64,
    pub last_request: i64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitConsumeInput {
    pub key: String,
    pub rule: RateLimitRule,
    /// Current time as Unix epoch **milliseconds**.
    pub now_ms: i64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitDecision {
    pub permitted: bool,
    /// Seconds until the client may retry when `permitted` is false.
    pub retry_after: u64,
    pub limit: u64,
    pub remaining: u64,
    pub reset_after: u64,
}

pub type RateLimitFuture<'a> =
    Pin<Box<dyn Future<Output = Result<RateLimitDecision, RustAuthError>> + Send + 'a>>;

/// Atomic rate limit storage contract.
///
/// Implementations must make the check-and-increment decision in one atomic
/// operation when used for cross-process or distributed enforcement.
pub trait RateLimitStore: Send + Sync + 'static {
    fn consume<'a>(&'a self, input: RateLimitConsumeInput) -> RateLimitFuture<'a>;
}

/// Synchronous storage contract for router-level rate limiting.
///
/// This legacy contract is preserved for compatibility. It is not atomic across
/// multiple processes unless the implementation makes `get`/`set` externally
/// serializable.
pub trait RateLimitStorage: Send + Sync + 'static {
    fn get(&self, key: &str) -> Result<Option<RateLimitRecord>, RustAuthError>;
    fn set(
        &self,
        key: &str,
        value: RateLimitRecord,
        ttl_seconds: u64,
        update: bool,
    ) -> Result<(), RustAuthError>;
}

/// Rate limit storage selector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RateLimitStorageOption {
    Memory,
    Database,
    SecondaryStorage,
}

/// Policy applied when rate limiting is enabled but no client IP can be
/// resolved for a request.
///
/// This guards against a production deployment that enables rate limiting but
/// fails to inject [`RequestClientIp`](crate::rate_limit::RequestClientIp) or
/// configure a trusted IP header, which would otherwise silently disable
/// rate limiting on auth endpoints. The policy is only applied when IP
/// tracking is enabled; if `advanced.ip_address.disable_ip_tracking` is set,
/// per-IP limiting is intentionally skipped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MissingIpPolicy {
    /// Reject the request (fail closed). Secure default.
    #[default]
    Deny,
    /// Rate limit every IP-less request together under a shared anonymous
    /// bucket instead of a per-IP bucket.
    SharedBucket,
    /// Skip rate limiting when no client IP can be resolved (legacy fail-open).
    Allow,
}