rustango 0.60.7

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! Pluggable password-hasher chain with **upgrade-on-login**.
//!
//! Every entry implements [`PasswordHasher`]. The **first** entry is
//! the preferred hasher: it writes all new hashes. When a login
//! matches an older hasher, the outcome carries a fresh hash in the
//! preferred format, so the caller can store the upgrade. That is how
//! you move a user base from bcrypt or pbkdf2 to argon2id without
//! asking anyone to reset a password.
//!
//! ```ignore
//! use rustango::password_hashers::{
//!     PasswordHasherChain, Argon2idHasher, VerifyOutcome,
//! };
//!
//! let chain = PasswordHasherChain::new()
//!     .with(Box::new(Argon2idHasher))
//!     .with(Box::new(LegacyBcryptHasher::new())); // user-provided
//!
//! match chain.verify(&form_password, &user.password_hash)? {
//!     VerifyOutcome::Match { needs_rehash: Some(new_hash) } => {
//!         // login succeeded against an older hasher — persist the
//!         // freshly minted argon2id hash so future logins are fast.
//!         user.update_password_hash(&new_hash).await?;
//!     }
//!     VerifyOutcome::Match { needs_rehash: None } => {}  // up-to-date
//!     VerifyOutcome::Mismatch => { /* 401 */ }
//! }
//! ```
//!
//! ## How `identify()` works
//!
//! [`PasswordHasher::identify`] returns `true` when the stored hash
//! was written by that hasher. Implementations match a leading
//! marker: `"$argon2id$"`, bcrypt's `"$2b$"`, `"pbkdf2_sha256$"`.
//!
//! Verification uses the first hasher that claims the hash, so order
//! only matters for `hash()`, which always takes the first entry.
//!
//! [`PasswordHasher`]: crate::password_hashers::PasswordHasher
//! [`PasswordHasher::identify`]: crate::password_hashers::PasswordHasher::identify

use std::fmt;

// ------------------------------------------------------------------ HasherError

#[derive(Debug)]
#[non_exhaustive]
pub enum HasherError {
    /// Hashing failed, usually an RNG or allocation failure.
    Hash(String),
    /// The stored hash is corrupt: the hasher claimed the format but
    /// could not parse it. Not the same as a mismatch, which means it
    /// parsed and the password was wrong.
    Malformed(String),
    /// No hasher in the chain knows this format. Either the row is
    /// corrupt, or a hasher was dropped from the chain before its
    /// users were migrated.
    NoMatchingHasher,
    /// No hashing slot freed up in time (the `*_async` calls only).
    Busy,
}

impl fmt::Display for HasherError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Hash(msg) => write!(f, "password hash error: {msg}"),
            Self::Malformed(msg) => write!(f, "malformed stored hash: {msg}"),
            Self::NoMatchingHasher => {
                f.write_str("no hasher in the chain recognized the stored hash format")
            }
            Self::Busy => f.write_str("password hashing is busy"),
        }
    }
}

impl std::error::Error for HasherError {}

// ------------------------------------------------------------------ VerifyOutcome

/// Result of `PasswordHasherChain::verify`. When the hash that
/// matched came from an older hasher, `needs_rehash` holds a fresh
/// hash in the preferred format for the caller to store.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifyOutcome {
    Match { needs_rehash: Option<String> },
    Mismatch,
}

impl VerifyOutcome {
    /// `true` when the password matched, rehash needed or not.
    #[must_use]
    pub fn is_match(&self) -> bool {
        matches!(self, Self::Match { .. })
    }

    /// The rehash value, if there is one.
    #[must_use]
    pub fn rehash(&self) -> Option<&str> {
        match self {
            Self::Match {
                needs_rehash: Some(s),
            } => Some(s.as_str()),
            _ => None,
        }
    }
}

// ------------------------------------------------------------------ PasswordHasher

/// One hasher's algorithm. Sync: hashing is CPU-bound and needs no
/// executor.
pub trait PasswordHasher: Send + Sync {
    /// Algorithm name (`"argon2id"`, `"bcrypt"`, …), for telemetry and
    /// tests. Not part of the stored format.
    fn algorithm(&self) -> &'static str;

    /// Produce a stored-hash string for `password`. Use a slow, salted
    /// algorithm with a fresh salt per password — argon2id, bcrypt, or
    /// pbkdf2 at a high iteration count. A plain digest is guessable
    /// at billions of tries per second.
    fn hash(&self, password: &str) -> Result<String, HasherError>;

    /// Verify against a hash THIS hasher produced. Compare in constant
    /// time so timing cannot leak how close a guess was. The chain
    /// calls this only after [`Self::identify`] says yes, so the
    /// format is yours to parse.
    fn verify(&self, password: &str, stored: &str) -> Result<bool, HasherError>;

    /// `true` if this hasher produced `stored`. Usually a match on the
    /// leading marker (`"$argon2id$"`, `"$2b$"`, `"pbkdf2_sha256$"`).
    fn identify(&self, stored: &str) -> bool;

    /// `true` when `stored` is this hasher's format but weaker than what
    /// [`Self::hash`] writes now. Default `false`.
    fn needs_rehash(&self, _stored: &str) -> bool {
        false
    }
}

// ------------------------------------------------------------------ PasswordHasherChain

/// Ordered list of hashers. First entry = preferred hasher.
#[derive(Default)]
pub struct PasswordHasherChain {
    hashers: Vec<Box<dyn PasswordHasher>>,
}

impl PasswordHasherChain {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Append a hasher. The first one registered is the preferred
    /// hasher: it writes new hashes and is the rehash target.
    #[must_use]
    pub fn with(mut self, h: Box<dyn PasswordHasher>) -> Self {
        self.hashers.push(h);
        self
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.hashers.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.hashers.is_empty()
    }

    /// Hash with the preferred hasher (first in the chain).
    pub fn hash(&self, password: &str) -> Result<String, HasherError> {
        let preferred = self.hashers.first().ok_or_else(|| {
            HasherError::Hash("PasswordHasherChain has no hashers registered".into())
        })?;
        preferred.hash(password)
    }

    /// Verify `password` against `stored`, using the first hasher
    /// that identifies the format. If that is not the preferred
    /// hasher, the outcome carries a fresh hash to store.
    pub fn verify(&self, password: &str, stored: &str) -> Result<VerifyOutcome, HasherError> {
        let (idx, hasher) = self
            .hashers
            .iter()
            .enumerate()
            .find(|(_, h)| h.identify(stored))
            .ok_or(HasherError::NoMatchingHasher)?;

        if !hasher.verify(password, stored)? {
            return Ok(VerifyOutcome::Mismatch);
        }
        // Matched. Rehash unless it was the preferred hasher at today's cost.
        let needs_rehash = if idx == 0 && !hasher.needs_rehash(stored) {
            None
        } else {
            // The preferred hasher mints the upgrade.
            Some(self.hashers[0].hash(password)?)
        };
        Ok(VerifyOutcome::Match { needs_rehash })
    }

    /// `true` if the chain knows the format of `stored`.
    #[must_use]
    pub fn identifies(&self, stored: &str) -> bool {
        self.hashers.iter().any(|h| h.identify(stored))
    }
}

/// Async variants: the chain runs on the shared argon2 queue, so it
/// does not park a runtime worker.
#[cfg(feature = "passwords")]
impl PasswordHasherChain {
    /// [`Self::hash`] on the blocking pool.
    ///
    /// # Errors
    /// As [`Self::hash`], or [`HasherError::Busy`].
    pub async fn hash_async(
        self: &std::sync::Arc<Self>,
        password: &str,
    ) -> Result<String, HasherError> {
        let (chain, password) = (std::sync::Arc::clone(self), password.to_owned());
        crate::passwords::off_runtime(move || chain.hash(&password))
            .await
            .map_err(|_| HasherError::Busy)?
    }

    /// [`Self::verify`] on the blocking pool.
    ///
    /// # Errors
    /// As [`Self::verify`], or [`HasherError::Busy`].
    pub async fn verify_async(
        self: &std::sync::Arc<Self>,
        password: &str,
        stored: &str,
    ) -> Result<VerifyOutcome, HasherError> {
        let chain = std::sync::Arc::clone(self);
        let (password, stored) = (password.to_owned(), stored.to_owned());
        crate::passwords::off_runtime(move || chain.verify(&password, &stored))
            .await
            .map_err(|_| HasherError::Busy)?
    }
}

// ------------------------------------------------------------------ Argon2idHasher

/// Argon2id hasher over [`crate::passwords::hash`] /
/// [`crate::passwords::verify`]. Put it first in the chain. From async
/// code use [`PasswordHasherChain::verify_async`].
#[cfg(feature = "passwords")]
pub struct Argon2idHasher;

#[cfg(feature = "passwords")]
#[allow(clippy::disallowed_methods)] // a sync trait
impl PasswordHasher for Argon2idHasher {
    fn algorithm(&self) -> &'static str {
        "argon2id"
    }
    fn hash(&self, password: &str) -> Result<String, HasherError> {
        crate::passwords::hash(password).map_err(|e| HasherError::Hash(e.to_string()))
    }
    fn verify(&self, password: &str, stored: &str) -> Result<bool, HasherError> {
        crate::passwords::verify(password, stored)
            .map_err(|e| HasherError::Malformed(e.to_string()))
    }
    fn identify(&self, stored: &str) -> bool {
        stored.starts_with("$argon2id$")
    }
    fn needs_rehash(&self, stored: &str) -> bool {
        crate::passwords::needs_rehash(stored)
    }
}

// ------------------------------------------------------------------ Tests

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    /// Test-only hasher storing `"legacy$<password>"` verbatim, so the
    /// chain can be tested without a bcrypt dev-dependency.
    struct LegacyPlainHasher {
        // Counts rehash calls.
        hash_calls: Mutex<usize>,
    }
    impl LegacyPlainHasher {
        fn new() -> Self {
            Self {
                hash_calls: Mutex::new(0),
            }
        }
    }
    impl PasswordHasher for LegacyPlainHasher {
        fn algorithm(&self) -> &'static str {
            "legacy"
        }
        fn hash(&self, password: &str) -> Result<String, HasherError> {
            *self.hash_calls.lock().unwrap() += 1;
            Ok(format!("legacy${password}"))
        }
        fn verify(&self, password: &str, stored: &str) -> Result<bool, HasherError> {
            let expected = stored
                .strip_prefix("legacy$")
                .ok_or_else(|| HasherError::Malformed(stored.into()))?;
            Ok(expected == password)
        }
        fn identify(&self, stored: &str) -> bool {
            stored.starts_with("legacy$")
        }
    }

    /// Second test hasher with another format, to check the chain
    /// picks the right one per stored format.
    struct AltLegacyHasher;
    impl PasswordHasher for AltLegacyHasher {
        fn algorithm(&self) -> &'static str {
            "alt_legacy"
        }
        fn hash(&self, password: &str) -> Result<String, HasherError> {
            Ok(format!("alt!{password}"))
        }
        fn verify(&self, password: &str, stored: &str) -> Result<bool, HasherError> {
            let expected = stored
                .strip_prefix("alt!")
                .ok_or_else(|| HasherError::Malformed(stored.into()))?;
            Ok(expected == password)
        }
        fn identify(&self, stored: &str) -> bool {
            stored.starts_with("alt!")
        }
    }

    #[test]
    fn empty_chain_hash_errors() {
        let chain = PasswordHasherChain::new();
        assert!(chain.is_empty());
        let err = chain.hash("anything").unwrap_err();
        assert!(matches!(err, HasherError::Hash(_)));
    }

    #[test]
    fn hash_uses_preferred_hasher() {
        let chain = PasswordHasherChain::new()
            .with(Box::new(LegacyPlainHasher::new()))
            .with(Box::new(AltLegacyHasher));
        let h = chain.hash("hunter2").unwrap();
        // Preferred = LegacyPlainHasher → "legacy$..."
        assert!(h.starts_with("legacy$"), "got: {h}");
    }

    #[test]
    fn verify_match_against_preferred_returns_no_rehash() {
        let chain = PasswordHasherChain::new().with(Box::new(LegacyPlainHasher::new()));
        let outcome = chain.verify("hunter2", "legacy$hunter2").unwrap();
        assert_eq!(outcome, VerifyOutcome::Match { needs_rehash: None });
        assert!(outcome.is_match());
        assert!(outcome.rehash().is_none());
    }

    #[test]
    fn verify_match_against_older_hasher_returns_rehash() {
        // Preferred = AltLegacyHasher, legacy = LegacyPlainHasher.
        let chain = PasswordHasherChain::new()
            .with(Box::new(AltLegacyHasher))
            .with(Box::new(LegacyPlainHasher::new()));
        let outcome = chain.verify("hunter2", "legacy$hunter2").unwrap();
        match outcome {
            VerifyOutcome::Match {
                needs_rehash: Some(new_hash),
            } => {
                // The new hash uses the preferred "alt!" format.
                assert!(new_hash.starts_with("alt!"), "got: {new_hash}");
                assert_eq!(new_hash, "alt!hunter2");
            }
            other => panic!("expected Match with rehash, got: {other:?}"),
        }
    }

    #[test]
    fn verify_mismatch_against_known_format() {
        let chain = PasswordHasherChain::new().with(Box::new(LegacyPlainHasher::new()));
        let outcome = chain.verify("wrong", "legacy$hunter2").unwrap();
        assert_eq!(outcome, VerifyOutcome::Mismatch);
        assert!(!outcome.is_match());
    }

    #[test]
    fn verify_unknown_format_errors_with_no_matching_hasher() {
        let chain = PasswordHasherChain::new().with(Box::new(LegacyPlainHasher::new()));
        let err = chain.verify("anything", "$2b$bcrypt-style").unwrap_err();
        assert!(matches!(err, HasherError::NoMatchingHasher));
    }

    #[test]
    fn identifies_walks_chain() {
        let chain = PasswordHasherChain::new()
            .with(Box::new(LegacyPlainHasher::new()))
            .with(Box::new(AltLegacyHasher));
        assert!(chain.identifies("legacy$x"));
        assert!(chain.identifies("alt!x"));
        assert!(!chain.identifies("$argon2id$x"));
    }

    #[test]
    fn chain_picks_right_hasher_per_format() {
        let chain = PasswordHasherChain::new()
            .with(Box::new(LegacyPlainHasher::new()))
            .with(Box::new(AltLegacyHasher));
        // "alt!…" routes to AltLegacyHasher at index 1, so it rehashes.
        let outcome = chain.verify("hunter2", "alt!hunter2").unwrap();
        match outcome {
            VerifyOutcome::Match {
                needs_rehash: Some(new),
            } => assert!(new.starts_with("legacy$"), "got: {new}"),
            other => panic!("expected Match w/ rehash, got: {other:?}"),
        }
    }

    #[test]
    fn hasher_error_display() {
        assert_eq!(
            format!("{}", HasherError::Hash("rng".into())),
            "password hash error: rng"
        );
        assert_eq!(
            format!("{}", HasherError::Malformed("nope".into())),
            "malformed stored hash: nope"
        );
        assert!(format!("{}", HasherError::NoMatchingHasher).contains("no hasher"));
    }

    // ---------- Argon2idHasher, gated on the `passwords` feature ----------

    #[cfg(feature = "passwords")]
    #[test]
    fn argon2id_hasher_round_trip() {
        let h = Argon2idHasher;
        let stored = h.hash("CorrectHorseBatteryStaple!42").unwrap();
        assert!(h.identify(&stored));
        assert!(h.verify("CorrectHorseBatteryStaple!42", &stored).unwrap());
        assert!(!h.verify("wrong", &stored).unwrap());
    }

    #[cfg(feature = "passwords")]
    #[test]
    fn argon2id_identify_rejects_other_formats() {
        let h = Argon2idHasher;
        assert!(!h.identify("$2b$bcrypt"));
        assert!(!h.identify("legacy$plain"));
        assert!(!h.identify(""));
    }

    #[cfg(feature = "passwords")]
    #[test]
    fn chain_with_argon2id_as_preferred_upgrades_legacy() {
        let chain = PasswordHasherChain::new()
            .with(Box::new(Argon2idHasher))
            .with(Box::new(LegacyPlainHasher::new()));
        // Stored as legacy; logging in upgrades to argon2id.
        let outcome = chain.verify("hunter2", "legacy$hunter2").unwrap();
        let VerifyOutcome::Match {
            needs_rehash: Some(new_hash),
        } = outcome
        else {
            panic!("expected upgrade-on-login, got: {outcome:?}");
        };
        assert!(new_hash.starts_with("$argon2id$"));
        // The new hash verifies through the chain too.
        let re = chain.verify("hunter2", &new_hash).unwrap();
        assert_eq!(re, VerifyOutcome::Match { needs_rehash: None });
    }

    /// #1875 — an argon2id hash below today's cost is upgraded on login.
    #[cfg(feature = "passwords")]
    #[test]
    fn chain_rehashes_weaker_argon2id() {
        use argon2::password_hash::{rand_core::OsRng, PasswordHasher as _, SaltString};
        let weak = argon2::Argon2::new(
            argon2::Algorithm::Argon2id,
            argon2::Version::V0x13,
            argon2::Params::new(8_192, 1, 1, None).unwrap(),
        )
        .hash_password(b"hunter2", &SaltString::generate(&mut OsRng))
        .unwrap()
        .to_string();
        let chain = PasswordHasherChain::new().with(Box::new(Argon2idHasher));
        let outcome = chain.verify("hunter2", &weak).unwrap();
        let new_hash = outcome.rehash().expect("weaker cost is rehashed");
        assert!(!crate::passwords::needs_rehash(new_hash));
        let again = chain.verify("hunter2", new_hash).unwrap();
        assert_eq!(again, VerifyOutcome::Match { needs_rehash: None });
    }

    #[cfg(feature = "passwords")]
    #[tokio::test(flavor = "current_thread")]
    async fn async_chain_does_not_block_the_runtime() {
        use crate::passwords::ticks_while;
        let chain = std::sync::Arc::new(PasswordHasherChain::new().with(Box::new(Argon2idHasher)));
        let (h, n) = ticks_while(chain.hash_async("hunter2")).await;
        assert!(n >= 2, "hash_async stalled the runtime ({n} ticks)");
        let (ok, n) = ticks_while(chain.verify_async("hunter2", &h.unwrap())).await;
        assert_eq!(ok.unwrap(), VerifyOutcome::Match { needs_rehash: None });
        assert!(n >= 2, "verify_async stalled the runtime ({n} ticks)");
    }
}