glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! The pieces `glacier generate authentication` builds on: password
//! hashing, session tokens and bearer tokens. The generated app code (a
//! `User` and `Session` model, a sessions controller and an
//! `Authentication` middleware) is yours to read and change, as with Rails'
//! and Phoenix's generators.
//!
//! Passwords are hashed with Argon2id; bcrypt hashes (from Devise or
//! `has_secure_password`) verify too, so an existing app's users can sign
//! in. Session tokens are 32 random bytes;
//! the client holds the token and the database only its SHA-256 digest, so
//! a leaked database can't be used to sign in.

use argon2::Argon2;
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use sha2::{Digest, Sha256};

use crate::context::Context;

/// The password's Argon2id hash, in PHC string format, for a
/// `password_digest` column.
///
/// # Panics
///
/// If the system's random number generator fails.
pub fn hash_password(password: &str) -> String {
    let mut salt = [0u8; 16];
    getrandom::fill(&mut salt).expect("the system's random number generator failed");
    let salt = SaltString::encode_b64(&salt).expect("16 bytes is a valid salt");
    Argon2::default()
        .hash_password(password.as_bytes(), &salt)
        .expect("Argon2 hashes any password")
        .to_string()
}

/// Whether `password` matches `digest`. With no digest (no such user) it
/// still spends the time of a check, so response times don't reveal which
/// email addresses have accounts.
pub fn verify_password(password: &str, digest: Option<&str>) -> bool {
    static DUMMY: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    let (digest, real) = match digest {
        Some(digest) => (digest, true),
        None => (
            DUMMY
                .get_or_init(|| hash_password("dummy password"))
                .as_str(),
            false,
        ),
    };
    // Devise and has_secure_password store bcrypt: `$2a$10$…`.
    if ["$2a$", "$2b$", "$2y$"]
        .iter()
        .any(|v| digest.starts_with(v))
    {
        return real && bcrypt::verify(password, digest).unwrap_or(false);
    }
    let Ok(parsed) = PasswordHash::new(digest) else {
        return false;
    };
    let matches = Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok();
    real && matches
}

/// Whether `digest` should be replaced by a new hash of the password the
/// next time the user signs in: a bcrypt hash from Devise or
/// `has_secure_password` (slower to check than Argon2, and that difference
/// shows who has one), or an Argon2 hash made with other settings than
/// Glacier's now. `User.authenticate_by` rehashes it.
pub fn needs_rehash(digest: &str) -> bool {
    let Ok(parsed) = PasswordHash::new(digest) else {
        return true;
    };
    let current = Argon2::default();
    if parsed.algorithm != argon2::Algorithm::Argon2id.ident() {
        return true;
    }
    let Ok(params) = argon2::Params::try_from(&parsed) else {
        return true;
    };
    let now = current.params();
    (params.m_cost(), params.t_cost(), params.p_cost())
        != (now.m_cost(), now.t_cost(), now.p_cost())
}

/// A signed token for one purpose (`"password_reset"`): the record's id,
/// an expiry, and a hash of `fingerprint` (the password digest, say), so
/// it stops working once that changes, as Rails' `generates_token_for`.
/// Signed with the app's `secret_key_base`, so any of its processes can
/// read it. URL-safe.
pub fn token_for(
    purpose: &str,
    id: i64,
    fingerprint: &str,
    expires_in: impl crate::jobs::Delay,
) -> String {
    let expires = crate::time::now() + expires_in.delay();
    let payload = format!(
        "{purpose}|{id}|{}|{}",
        expires.timestamp(),
        fingerprint_hash(fingerprint)
    );
    let encoded = URL_SAFE_NO_PAD.encode(&payload);
    let signature = URL_SAFE_NO_PAD.encode(hmac::Mac::finalize(token_hmac(&encoded)).into_bytes());
    // No separator: the signature is a fixed 43 characters, and a `.`
    // would read as a format extension in a path (`/passwords/:token`).
    format!("{encoded}{signature}")
}

/// The length of a token's signature: SHA-256's 32 bytes in base64url.
const SIGNATURE_LEN: usize = 43;

/// A token [`token_for`] made, once its signature, purpose and expiry
/// check out.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedToken {
    /// The record it's for.
    pub id: i64,
    fingerprint: String,
}

impl SignedToken {
    /// Whether the record's fingerprint is still the one it was made with:
    /// `signed.matches(&user.password_digest)`.
    pub fn matches(&self, fingerprint: &str) -> bool {
        self.fingerprint == fingerprint_hash(fingerprint)
    }
}

/// The token's record, if it was made for `purpose` by this app and hasn't
/// expired; check [`SignedToken::matches`] against the record too.
pub fn read_token(purpose: &str, token: &str) -> Option<SignedToken> {
    let split = token.len().checked_sub(SIGNATURE_LEN)?;
    if split == 0 || !token.is_char_boundary(split) {
        return None;
    }
    let (encoded, signature) = token.split_at(split);
    let signature = URL_SAFE_NO_PAD.decode(signature).ok()?;
    // In constant time, so timing doesn't reveal a signature's bytes. A
    // token signed with a previous `secret_key_base` still reads.
    let current = crate::request::signing_key();
    let signed = std::iter::once((*current).clone())
        .chain(crate::request::previous_keys())
        .any(|key| hmac::Mac::verify_slice(token_hmac_with(&key, encoded), &signature).is_ok());
    if !signed {
        return None;
    }
    let payload = String::from_utf8(URL_SAFE_NO_PAD.decode(encoded).ok()?).ok()?;
    let mut parts = payload.splitn(4, '|');
    let (made_for, id, expires, fingerprint) =
        (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
    if made_for != purpose || expires.parse::<i64>().ok()? < crate::time::now().timestamp() {
        return None;
    }
    Some(SignedToken {
        id: id.parse().ok()?,
        fingerprint: fingerprint.to_owned(),
    })
}

fn fingerprint_hash(fingerprint: &str) -> String {
    let digest = Sha256::digest(fingerprint.as_bytes());
    URL_SAFE_NO_PAD.encode(&digest[..12])
}

fn token_hmac(payload: &str) -> hmac::Hmac<Sha256> {
    token_hmac_with(&crate::request::signing_key(), payload)
}

fn token_hmac_with(key: &cookie::Key, payload: &str) -> hmac::Hmac<Sha256> {
    use hmac::Mac;
    let mut mac = hmac::Hmac::<Sha256>::new_from_slice(key.signing()).expect("HMAC takes any key");
    mac.update(b"glacier token|");
    mac.update(payload.as_bytes());
    mac
}

/// A new random token for a session (or a password reset link): 32 bytes,
/// base64url-encoded.
///
/// # Panics
///
/// If the system's random number generator fails.
pub fn new_token() -> String {
    let mut bytes = [0u8; 32];
    getrandom::fill(&mut bytes).expect("the system's random number generator failed");
    URL_SAFE_NO_PAD.encode(bytes)
}

/// The SHA-256 digest of a token, hex-encoded: what the database stores.
pub fn token_digest(token: &str) -> String {
    Sha256::digest(token.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// The token from an `Authorization: Bearer <token>` header.
pub fn bearer_token(ctx: &Context) -> Option<&str> {
    let header = ctx.header(http::header::AUTHORIZATION)?;
    let (scheme, token) = header.split_once(' ')?;
    let token = token.trim();
    (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token)
}

pub mod totp;

/// What a request may do when an API token with scopes made it
/// (`limit_to_scopes`); a request without (a browser's session) may do
/// anything its user may.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scopes(pub Vec<String>);

/// Limits the request to `scopes`, as the token that made it allows:
/// `Authentication` calls it for an API token.
pub fn limit_to_scopes(ctx: &mut Context, scopes: Vec<String>) {
    ctx.extensions_mut().insert(Scopes(scopes));
}

/// Refuses a request whose API token lacks `scope` (`"notes:write"`), with
/// `403 Forbidden`; any other request passes. `"notes:*"` grants every
/// `notes:` scope, and `"*"` all of them.
///
/// # Errors
///
/// `403 Forbidden` without the scope.
pub fn require_scope(ctx: &Context, scope: &str) -> crate::Result<()> {
    let Some(Scopes(granted)) = ctx.extensions().get::<Scopes>() else {
        return Ok(());
    };
    let allowed = granted.iter().any(|g| {
        g == "*"
            || g == scope
            || g.strip_suffix('*')
                .is_some_and(|prefix| prefix.ends_with(':') && scope.starts_with(prefix))
    });
    if allowed {
        Ok(())
    } else {
        Err(crate::Error::new(
            http::StatusCode::FORBIDDEN,
            format!("this token doesn't have the `{scope}` scope"),
        ))
    }
}

/// JSON Web Tokens signed with HMAC-SHA256 (`HS256`), as Rails apps using
/// the `jwt` gem issue them.
pub mod jwt {
    use base64::Engine;
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use hmac::{Hmac, Mac};
    use serde_json::{Map, Value};
    use sha2::Sha256;

    /// Why a token was rejected.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum JwtError {
        Malformed,
        Algorithm,
        Signature,
        Expired,
    }

    impl std::fmt::Display for JwtError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(match self {
                JwtError::Malformed => "malformed token",
                JwtError::Algorithm => "token not signed with HS256",
                JwtError::Signature => "invalid token signature",
                JwtError::Expired => "token expired",
            })
        }
    }

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

    fn mac(secret: &[u8]) -> Hmac<Sha256> {
        Hmac::<Sha256>::new_from_slice(secret).expect("HMAC takes a key of any length")
    }

    /// [`encode`] for claims built as a JSON object, as `.glacier` builds
    /// them: `Json.object()`, then `.value("user_id", &id)` for each. A
    /// value that isn't an object signs no claims.
    pub fn sign(claims: &Value, secret: &[u8]) -> String {
        let empty = Map::new();
        encode(claims.as_object().unwrap_or(&empty), secret)
    }

    /// A token carrying `claims` (`{"user_id": 1, "exp": …}`), keys in
    /// the order given.
    pub fn encode(claims: &Map<String, Value>, secret: &[u8]) -> String {
        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256"}"#);
        let payload = URL_SAFE_NO_PAD.encode(Value::Object(claims.clone()).to_string());
        let signing_input = format!("{header}.{payload}");
        let mut mac = mac(secret);
        mac.update(signing_input.as_bytes());
        let signature = URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes());
        format!("{signing_input}.{signature}")
    }

    /// The claims of a token signed with `secret`, after checking its
    /// signature (in constant time) and its `exp`, if it has one.
    pub fn decode(token: &str, secret: &[u8]) -> Result<Map<String, Value>, JwtError> {
        let mut parts = token.trim().split('.');
        let (Some(header), Some(payload), Some(signature), None) =
            (parts.next(), parts.next(), parts.next(), parts.next())
        else {
            return Err(JwtError::Malformed);
        };
        let json = |part: &str| -> Result<Map<String, Value>, JwtError> {
            let bytes = URL_SAFE_NO_PAD
                .decode(part)
                .map_err(|_| JwtError::Malformed)?;
            match serde_json::from_slice(&bytes) {
                Ok(Value::Object(map)) => Ok(map),
                _ => Err(JwtError::Malformed),
            }
        };
        if json(header)?.get("alg").and_then(Value::as_str) != Some("HS256") {
            return Err(JwtError::Algorithm);
        }
        let signature = URL_SAFE_NO_PAD
            .decode(signature)
            .map_err(|_| JwtError::Malformed)?;
        let mut mac = mac(secret);
        mac.update(format!("{header}.{payload}").as_bytes());
        mac.verify_slice(&signature)
            .map_err(|_| JwtError::Signature)?;
        let claims = json(payload)?;
        if let Some(exp) = claims.get("exp") {
            let exp = exp.as_i64().ok_or(JwtError::Malformed)?;
            if exp <= crate::time::now().timestamp() {
                return Err(JwtError::Expired);
            }
        }
        Ok(claims)
    }
}

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

    #[test]
    fn tokens_are_for_one_purpose_one_fingerprint_and_a_while() {
        let token = token_for(
            "password_reset",
            7,
            "digest-1",
            std::time::Duration::from_secs(3600),
        );
        let signed = read_token("password_reset", &token).unwrap();
        assert_eq!(signed.id, 7);
        assert!(signed.matches("digest-1"));
        assert!(!signed.matches("digest-2"), "the password changed");
        assert!(
            read_token("magic_link", &token).is_none(),
            "another purpose"
        );
        let mut forged = token.clone();
        forged.replace_range(0..1, if token.starts_with('a') { "b" } else { "a" });
        assert!(read_token("password_reset", &forged).is_none());
        assert!(read_token("password_reset", "junk").is_none());
        let gone = token_for(
            "password_reset",
            7,
            "digest-1",
            chrono::TimeDelta::seconds(-1),
        );
        assert!(read_token("password_reset", &gone).is_none(), "expired");
    }

    #[test]
    fn old_hashes_need_rehashing() {
        assert!(!needs_rehash(&hash_password("correct horse")));
        let bcrypt = bcrypt::hash("correct horse", 4).unwrap();
        assert!(needs_rehash(&bcrypt));
        assert!(needs_rehash("not a hash"));
    }

    #[test]
    fn hashes_and_verifies_passwords() {
        let digest = hash_password("correct horse");
        assert!(digest.starts_with("$argon2id$"));
        assert_ne!(digest, hash_password("correct horse"), "salted");
        assert!(verify_password("correct horse", Some(&digest)));
        assert!(!verify_password("wrong horse", Some(&digest)));
        assert!(!verify_password("correct horse", None));
        assert!(!verify_password("x", Some("not a hash")));
        // Ruby's BCrypt::Password.create("secret", cost: 4).
        let devise = "$2a$04$KJY25RprEuJvbxVtp0EL6OAwC3ZAHpva.goKBL6bcCq6/HLxIEkUu";
        assert!(
            verify_password("secret", Some(devise)),
            "bcrypt hashes are checked as bcrypt"
        );
        assert!(!verify_password("wrong", Some(devise)));
    }

    #[test]
    fn signs_and_checks_json_web_tokens() {
        use jwt::{JwtError, decode, encode};
        // As Ruby's `JWT.encode({user_id: 1, email: "a@b.c", exp: 4102444800}, "s", "HS256")`.
        let ruby = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6ImFAYi5jIiwiZXhwIjo0MTAyNDQ0ODAwfQ.6DVTKEZh7vTr7ohSSxZEV8iyMg6REQCYy7-nCjR3oVk";
        let mut claims = serde_json::Map::new();
        claims.insert("user_id".into(), 1.into());
        claims.insert("email".into(), "a@b.c".into());
        claims.insert("exp".into(), 4_102_444_800i64.into());
        let token = encode(&claims, b"s");
        assert_eq!(token, ruby, "the same token Ruby's jwt gem makes");
        assert_eq!(decode(&token, b"s").unwrap(), claims);
        assert_eq!(decode(&token, b"other"), Err(JwtError::Signature));
        assert_eq!(decode("a.b", b"s"), Err(JwtError::Malformed));
        claims.insert("exp".into(), 1.into());
        assert_eq!(decode(&encode(&claims, b"s"), b"s"), Err(JwtError::Expired));
    }

    #[test]
    fn makes_tokens_and_digests() {
        let token = new_token();
        assert_eq!(token.len(), 43);
        assert_ne!(token, new_token());
        assert_eq!(
            token_digest("abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }
}