rustango 0.60.0

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
//! TOTP — Time-based One-Time Passwords (RFC 6238) for 2FA.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::totp::{TotpSecret, generate, verify, otpauth_url};
//!
//! // Enrollment: generate a fresh secret, store it on the user row
//! let secret = TotpSecret::generate();
//! user.totp_secret = secret.to_base32();
//!
//! // Show user the QR code (encode this URL as a QR):
//! let url = otpauth_url("MyApp", &user.email, &secret);
//!
//! // Verify a 6-digit code from the user's authenticator app:
//! if verify(&secret, "123456", 30, 6, 1) {
//!     // accepted
//! }
//! ```
//!
//! ## Configuration
//!
//! Every function takes `step_secs` (usually 30), `digits` (usually
//! 6) and `window`, the number of steps before and after now that are
//! still accepted. A `window` of 1 allows about 30 seconds of drift.

use std::time::{SystemTime, UNIX_EPOCH};

/// The shortest secret [`TotpSecret::from_base32`] accepts: 80 bits.
pub const MIN_SECRET_BYTES: usize = 10;

/// A TOTP shared secret (raw bytes). Store base32-encoded on the user row.
#[derive(Clone)]
pub struct TotpSecret(pub Vec<u8>);

/// Redacted: a logged secret is a second factor given away (#1875).
impl std::fmt::Debug for TotpSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("TotpSecret(<redacted>)")
    }
}

impl TotpSecret {
    /// Generate a 20-byte random secret, the RFC 4226 minimum.
    ///
    /// It uses [`rand::rngs::OsRng`], the OS random source, not
    /// `thread_rng`. `thread_rng` is a userspace PRNG and is not
    /// guaranteed to be safe for key material on every platform. The
    /// rest of the framework's crypto code uses `OsRng` too.
    #[must_use]
    pub fn generate() -> Self {
        use rand::rngs::OsRng;
        use rand::RngCore;
        let mut bytes = vec![0u8; 20];
        OsRng.fill_bytes(&mut bytes);
        Self(bytes)
    }

    /// Encode the secret as base32 with no padding. Authenticator
    /// apps all read this format.
    #[must_use]
    pub fn to_base32(&self) -> String {
        base32_encode(&self.0)
    }

    /// Decode a base32-encoded secret string (with or without padding).
    /// Returns `None` for invalid base32 or a secret under
    /// [`MIN_SECRET_BYTES`], so an empty column can't become a guessable key.
    #[must_use]
    pub fn from_base32(s: &str) -> Option<Self> {
        base32_decode(s)
            .filter(|b| b.len() >= MIN_SECRET_BYTES)
            .map(Self)
    }
}

/// Generate the TOTP code for `secret` at the current time.
#[must_use]
pub fn generate(secret: &TotpSecret, step_secs: u64, digits: u32) -> String {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    generate_at(secret, now, step_secs, digits)
}

/// Generate the TOTP code for `secret` at a specific unix timestamp.
/// Useful for testing.
#[must_use]
pub fn generate_at(secret: &TotpSecret, unix_secs: u64, step_secs: u64, digits: u32) -> String {
    let counter = unix_secs / step_secs.max(1);
    hotp(&secret.0, counter, digits)
}

/// Check a code the user typed. It accepts any code from `window`
/// steps before now to `window` steps after, to allow clock drift.
#[must_use]
pub fn verify(secret: &TotpSecret, code: &str, step_secs: u64, digits: u32, window: i64) -> bool {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    verify_at(secret, code, now, step_secs, digits, window)
}

/// Verify at a specific unix timestamp — useful for tests.
#[must_use]
pub fn verify_at(
    secret: &TotpSecret,
    code: &str,
    unix_secs: u64,
    step_secs: u64,
    digits: u32,
    window: i64,
) -> bool {
    matched_step_at(secret, code, unix_secs, step_secs, digits, window).is_some()
}

/// [`verify`], returning the time step the code matched. A caller that
/// stores it can refuse the same code twice.
#[must_use]
pub fn matched_step(
    secret: &TotpSecret,
    code: &str,
    step_secs: u64,
    digits: u32,
    window: i64,
) -> Option<u64> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    matched_step_at(secret, code, now, step_secs, digits, window)
}

/// [`matched_step`] at a specific unix timestamp. The latest matching
/// step wins.
#[must_use]
pub fn matched_step_at(
    secret: &TotpSecret,
    code: &str,
    unix_secs: u64,
    step_secs: u64,
    digits: u32,
    window: i64,
) -> Option<u64> {
    let step = step_secs.max(1) as i64;
    let center = (unix_secs as i64) / step;
    let mut matched = None;
    // Every step is checked, so timing does not reveal which one matched.
    for offset in -window..=window {
        let counter: u64 = match (center + offset).try_into() {
            Ok(c) => c,
            Err(_) => continue,
        };
        if crate::crypto::constant_time_compare(
            hotp(&secret.0, counter, digits).as_bytes(),
            code.as_bytes(),
        ) {
            matched = Some(counter);
        }
    }
    matched
}

/// Build the `otpauth://` URI for a secret. Show it as a QR code so
/// the user can enrol with one scan.
#[must_use]
pub fn otpauth_url(issuer: &str, account: &str, secret: &TotpSecret) -> String {
    let label = format!("{}:{}", url_encode(issuer), url_encode(account));
    format!(
        "otpauth://totp/{label}?secret={}&issuer={}&algorithm=SHA1&digits=6&period=30",
        secret.to_base32(),
        url_encode(issuer),
    )
}

// ------------------------------------------------------------------ HOTP (RFC 4226)

/// HMAC-Based One-Time Password — the building block for TOTP.
fn hotp(secret: &[u8], counter: u64, digits: u32) -> String {
    use hmac::{Hmac, Mac};
    use sha1::Sha1;

    let mut mac = <Hmac<Sha1>>::new_from_slice(secret).expect("HMAC accepts any key");
    mac.update(&counter.to_be_bytes());
    let hash = mac.finalize().into_bytes();

    // Dynamic truncation per RFC 4226
    let offset = (hash[hash.len() - 1] & 0x0f) as usize;
    let bin_code = ((hash[offset] & 0x7f) as u32) << 24
        | (hash[offset + 1] as u32) << 16
        | (hash[offset + 2] as u32) << 8
        | (hash[offset + 3] as u32);

    // u64: 10^10 overflows u32 (#1875).
    let modulo = 10u64.pow(digits.min(10));
    let value = u64::from(bin_code) % modulo;
    format!("{:0width$}", value, width = digits as usize)
}

// ------------------------------------------------------------------ Base32

const BASE32_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

fn base32_encode(input: &[u8]) -> String {
    let mut out = String::new();
    let mut buffer = 0u64;
    let mut bits_left = 0;
    for &b in input {
        buffer = (buffer << 8) | u64::from(b);
        bits_left += 8;
        while bits_left >= 5 {
            bits_left -= 5;
            let idx = ((buffer >> bits_left) & 0x1f) as usize;
            out.push(BASE32_ALPHABET[idx] as char);
        }
    }
    if bits_left > 0 {
        let idx = ((buffer << (5 - bits_left)) & 0x1f) as usize;
        out.push(BASE32_ALPHABET[idx] as char);
    }
    out
}

fn base32_decode(input: &str) -> Option<Vec<u8>> {
    let mut buffer = 0u64;
    let mut bits = 0;
    let mut out = Vec::new();
    for c in input.chars() {
        if c == '=' || c.is_whitespace() {
            continue;
        }
        let upper = c.to_ascii_uppercase();
        let val = BASE32_ALPHABET.iter().position(|&b| b == upper as u8)? as u64;
        buffer = (buffer << 5) | val;
        bits += 5;
        if bits >= 8 {
            bits -= 8;
            out.push(((buffer >> bits) & 0xff) as u8);
        }
    }
    Some(out)
}

// ------------------------------------------------------------------ helpers

// The otpauth label and issuer use the RFC 3986 unreserved set, so
// route through the shared `crate::url_codec::url_encode`.
use crate::url_codec::url_encode;

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

    #[test]
    fn rfc6238_test_vector_sha1() {
        // RFC 6238 Appendix B test vectors (SHA1, T=59).
        // Secret: ASCII "12345678901234567890" (20 bytes).
        let secret = TotpSecret(b"12345678901234567890".to_vec());
        let code = generate_at(&secret, 59, 30, 8);
        assert_eq!(code, "94287082");
    }

    #[test]
    fn rfc6238_test_vector_t_1111111109() {
        let secret = TotpSecret(b"12345678901234567890".to_vec());
        let code = generate_at(&secret, 1_111_111_109, 30, 8);
        assert_eq!(code, "07081804");
    }

    #[test]
    fn matched_step_names_the_step_the_code_belongs_to() {
        let s = TotpSecret::generate();
        let t = 1_700_000_000;
        let prev = generate_at(&s, t - 30, 30, 6);
        assert_eq!(matched_step_at(&s, &prev, t, 30, 6, 1), Some(t / 30 - 1));
        let now = generate_at(&s, t, 30, 6);
        assert_eq!(matched_step_at(&s, &now, t, 30, 6, 1), Some(t / 30));
        let far = generate_at(&s, t + 90, 30, 6);
        assert_eq!(matched_step_at(&s, &far, t, 30, 6, 1), None);
    }

    #[test]
    fn ten_digits_do_not_overflow_and_debug_is_redacted() {
        let s = TotpSecret(b"12345678901234567890".to_vec());
        assert_eq!(generate_at(&s, 59, 30, 10).len(), 10);
        assert_eq!(format!("{s:?}"), "TotpSecret(<redacted>)");
    }

    #[test]
    fn generate_returns_correct_digit_count() {
        let s = TotpSecret::generate();
        for digits in [6, 7, 8] {
            let c = generate(&s, 30, digits);
            assert_eq!(c.len(), digits as usize);
            assert!(c.chars().all(|c| c.is_ascii_digit()));
        }
    }

    #[test]
    fn verify_accepts_current_step() {
        let s = TotpSecret(b"12345678901234567890".to_vec());
        let code = generate_at(&s, 100, 30, 6);
        assert!(verify_at(&s, &code, 100, 30, 6, 1));
    }

    #[test]
    fn verify_accepts_within_window() {
        let s = TotpSecret(b"12345678901234567890".to_vec());
        // Code from 30 seconds ago (one step) — should be accepted with window=1
        let code = generate_at(&s, 100 - 30, 30, 6);
        assert!(verify_at(&s, &code, 100, 30, 6, 1));
        // One in the future
        let code = generate_at(&s, 100 + 30, 30, 6);
        assert!(verify_at(&s, &code, 100, 30, 6, 1));
    }

    #[test]
    fn verify_rejects_outside_window() {
        let s = TotpSecret(b"12345678901234567890".to_vec());
        // Code from 5 minutes ago — way outside window=1
        let now = 10_000;
        let code = generate_at(&s, now - 300, 30, 6);
        assert!(!verify_at(&s, &code, now, 30, 6, 1));
    }

    #[test]
    fn verify_rejects_wrong_code() {
        let s = TotpSecret(b"12345678901234567890".to_vec());
        assert!(!verify_at(&s, "000000", 100, 30, 6, 1));
    }

    #[test]
    fn base32_roundtrip() {
        let original: Vec<u8> = (0..20).collect();
        let encoded = base32_encode(&original);
        let decoded = base32_decode(&encoded).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn base32_decode_handles_padding_and_whitespace() {
        let original = b"hello world".to_vec();
        let encoded = base32_encode(&original);
        // Add some padding + whitespace to mimic real-world input
        let messy = format!("{} ==", encoded);
        let decoded = base32_decode(&messy).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn base32_decode_invalid_returns_none() {
        assert_eq!(base32_decode("not valid 0189!!"), None);
    }

    #[test]
    fn secret_from_base32_roundtrip() {
        let s1 = TotpSecret::generate();
        let encoded = s1.to_base32();
        let s2 = TotpSecret::from_base32(&encoded).unwrap();
        assert_eq!(s1.0, s2.0);
    }

    #[test]
    fn from_base32_refuses_a_short_or_empty_secret() {
        assert!(TotpSecret::from_base32("").is_none());
        // 9 bytes, then 10.
        assert!(TotpSecret::from_base32(&base32_encode(&[7; 9])).is_none());
        assert!(TotpSecret::from_base32(&base32_encode(&[7; 10])).is_some());
    }

    #[test]
    fn otpauth_url_format() {
        let secret = TotpSecret(b"12345678901234567890".to_vec());
        let url = otpauth_url("MyApp", "alice@example.com", &secret);
        assert!(url.starts_with("otpauth://totp/MyApp:alice%40example.com?"));
        assert!(url.contains("secret="));
        assert!(url.contains("issuer=MyApp"));
        assert!(url.contains("digits=6"));
        assert!(url.contains("period=30"));
    }

    // ---- pin the RNG quality ----

    #[test]
    fn generate_produces_full_20_byte_secrets() {
        // Catches a change that shortens the secret below the RFC
        // 4226 minimum of 160 bits.
        for _ in 0..16 {
            let s = TotpSecret::generate();
            assert_eq!(s.0.len(), 20, "TOTP secret must be exactly 20 bytes");
        }
    }

    #[test]
    fn generate_produces_unique_secrets() {
        // Each secret holds 160 bits, so a real collision is
        // impossible. A duplicate means the RNG became a constant, a
        // counter, or a badly seeded PRNG.
        use std::collections::HashSet;
        let mut seen: HashSet<Vec<u8>> = HashSet::new();
        for _ in 0..64 {
            let s = TotpSecret::generate();
            assert!(seen.insert(s.0), "duplicate TOTP secret — RNG regressed");
        }
    }

    #[test]
    fn generate_does_not_produce_trivial_secrets() {
        // An all-zero, all-0xff or single-value secret is what a
        // broken RNG produces.
        let s = TotpSecret::generate();
        assert!(s.0.iter().any(|&b| b != 0), "all-zero secret");
        assert!(s.0.iter().any(|&b| b != 0xff), "all-ones secret");
        let first = s.0[0];
        assert!(
            s.0.iter().any(|&b| b != first),
            "fixed-byte secret (every byte = {first:#x}) — RNG returns constant"
        );
    }
}