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
420
421
422
423
424
425
426
427
428
429
//! WebAuthn registration + authentication ceremonies (#392).
//!
//! These orchestrate the [`super::verify`] primitives into the two
//! server-side verification steps, plus the challenge + options helpers
//! the browser's `navigator.credentials.create()/get()` need. The crypto
//! is pure-Rust (`p256` / `ciborium`); see the module docs.
//!
//! Scope: **ES256** keys, **`none`/self attestation** (no cert-chain
//! verification). The caller is responsible for storing the per-ceremony
//! `challenge` (e.g. in the session) between the `*_options` and `verify_*`
//! calls, and for persisting the credential via [`super::register`] /
//! advancing the counter via [`super::update_sign_count`].

use super::error::PasskeyError;
use super::verify;

/// A fresh 32-byte ceremony challenge. Stash it (session) between issuing
/// the options and verifying the client's response.
#[must_use]
pub fn generate_challenge() -> Vec<u8> {
    use rand::RngCore as _;
    let mut buf = [0u8; 32];
    rand::rngs::OsRng.fill_bytes(&mut buf);
    buf.to_vec()
}

/// What a verified registration yields — store these via
/// [`super::register`].
#[derive(Debug, Clone)]
pub struct RegistrationOutcome {
    /// base64url (no pad) of the raw credential id.
    pub credential_id: String,
    /// COSE-encoded public key bytes.
    pub cose_public_key: Vec<u8>,
    /// The authenticator's initial signature counter.
    pub sign_count: i64,
}

/// Verify a registration response (WebAuthn §7.1, `none`/self attestation).
///
/// `challenge` is the value handed to [`registration_options_json`];
/// `client_data_json` + `attestation_object` are the decoded
/// `response.clientDataJSON` / `response.attestationObject` from the
/// browser.
///
/// # Errors
/// The matching [`PasskeyError`] for whichever check fails.
pub fn verify_registration(
    challenge: &[u8],
    rp_id: &str,
    allowed_origins: &[String],
    client_data_json: &[u8],
    attestation_object: &[u8],
) -> Result<RegistrationOutcome, PasskeyError> {
    // 1. clientDataJSON: type / challenge / origin.
    verify::parse_and_verify_client_data(
        client_data_json,
        "webauthn.create",
        challenge,
        allowed_origins,
    )?;

    // 2. attestationObject CBOR → authData byte string.
    let value: ciborium::value::Value = ciborium::de::from_reader(attestation_object)
        .map_err(|e| PasskeyError::Cbor(e.to_string()))?;
    let auth_data_bytes = extract_auth_data(&value)?;

    // 3. authData: rpIdHash, UP flag, attested credential data.
    let ad = verify::parse_authenticator_data(&auth_data_bytes)?;
    verify::verify_rp_id(&ad, rp_id)?;
    if !ad.user_present() {
        return Err(PasskeyError::UserNotPresent);
    }
    let attested = ad.attested.ok_or_else(|| {
        PasskeyError::AuthData("registration authData has no attested credential data".into())
    })?;
    // `none`/self attestation: trust the embedded key (no cert chain).
    // The COSE key was already validated as a parseable P-256 ES256 key
    // by `parse_authenticator_data` → `canonicalize_cose_key`; confirm it
    // builds a verifying key so we never store an unusable credential.
    verify::cose_es256_key(&attested.cose_public_key)?;

    Ok(RegistrationOutcome {
        credential_id: verify::b64url_encode(&attested.credential_id),
        cose_public_key: attested.cose_public_key,
        sign_count: i64::from(ad.sign_count),
    })
}

/// Verify an authentication (assertion) response (WebAuthn §7.2).
/// Returns the new signature counter and the UV flag.
///
/// # Errors
/// The matching [`PasskeyError`] for whichever check fails (including
/// [`PasskeyError::CounterRegression`] on a non-advancing counter).
#[allow(clippy::too_many_arguments)]
pub fn verify_authentication(
    challenge: &[u8],
    rp_id: &str,
    allowed_origins: &[String],
    stored_cose_public_key: &[u8],
    stored_sign_count: i64,
    client_data_json: &[u8],
    authenticator_data: &[u8],
    signature_der: &[u8],
) -> Result<AuthenticationOutcome, PasskeyError> {
    verify::parse_and_verify_client_data(
        client_data_json,
        "webauthn.get",
        challenge,
        allowed_origins,
    )?;
    let ad = verify::parse_authenticator_data(authenticator_data)?;
    verify::verify_rp_id(&ad, rp_id)?;
    if !ad.user_present() {
        return Err(PasskeyError::UserNotPresent);
    }
    verify::verify_es256_assertion(
        stored_cose_public_key,
        authenticator_data,
        client_data_json,
        signature_der,
    )?;
    // WebAuthn §7.2 step 21: once either count is non-zero it must advance,
    // so a clone can't reset a stored counter to 0.
    let new = i64::from(ad.sign_count);
    if (new != 0 || stored_sign_count != 0) && new <= stored_sign_count {
        return Err(PasskeyError::CounterRegression);
    }
    Ok(AuthenticationOutcome {
        sign_count: new,
        user_verified: ad.user_verified(),
    })
}

/// What a verified assertion yields.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct AuthenticationOutcome {
    /// New signature counter; persist via [`super::update_sign_count`].
    pub sign_count: i64,
    /// The UV flag: the user passed a PIN or biometric, not just a touch.
    /// Refuse when your policy needs user verification.
    pub user_verified: bool,
}

/// `PublicKeyCredentialCreationOptions` JSON for
/// `navigator.credentials.create({ publicKey })`. `user_id` is encoded
/// base64url; `exclude` lists the user's existing credential ids (their
/// stored base64url form) so the authenticator won't double-register.
#[must_use]
pub fn registration_options_json(
    rp_id: &str,
    rp_name: &str,
    user_id: &[u8],
    user_name: &str,
    challenge: &[u8],
    exclude_credential_ids: &[String],
) -> serde_json::Value {
    let exclude: Vec<serde_json::Value> = exclude_credential_ids
        .iter()
        .map(|id| serde_json::json!({ "type": "public-key", "id": id }))
        .collect();
    serde_json::json!({
        "challenge": verify::b64url_encode(challenge),
        "rp": { "id": rp_id, "name": rp_name },
        "user": {
            "id": verify::b64url_encode(user_id),
            "name": user_name,
            "displayName": user_name,
        },
        // -7 = ES256 (the only algorithm this slice verifies).
        "pubKeyCredParams": [ { "type": "public-key", "alg": -7 } ],
        "timeout": 60000,
        "attestation": "none",
        "excludeCredentials": exclude,
        "authenticatorSelection": { "userVerification": "preferred", "residentKey": "preferred" },
    })
}

/// `PublicKeyCredentialRequestOptions` JSON for
/// `navigator.credentials.get({ publicKey })`. `allow_credential_ids` are
/// the user's stored base64url credential ids.
#[must_use]
pub fn authentication_options_json(
    rp_id: &str,
    challenge: &[u8],
    allow_credential_ids: &[String],
) -> serde_json::Value {
    let allow: Vec<serde_json::Value> = allow_credential_ids
        .iter()
        .map(|id| serde_json::json!({ "type": "public-key", "id": id }))
        .collect();
    serde_json::json!({
        "challenge": verify::b64url_encode(challenge),
        "rpId": rp_id,
        "timeout": 60000,
        "userVerification": "preferred",
        "allowCredentials": allow,
    })
}

/// Pull the `authData` byte string out of an attestationObject CBOR map.
fn extract_auth_data(value: &ciborium::value::Value) -> Result<Vec<u8>, PasskeyError> {
    use ciborium::value::Value;
    let Value::Map(entries) = value else {
        return Err(PasskeyError::AuthData(
            "attestationObject is not a CBOR map".into(),
        ));
    };
    for (k, v) in entries {
        if let Value::Text(key) = k {
            if key == "authData" {
                if let Value::Bytes(b) = v {
                    return Ok(b.clone());
                }
                return Err(PasskeyError::AuthData(
                    "authData is not a byte string".into(),
                ));
            }
        }
    }
    Err(PasskeyError::AuthData(
        "attestationObject has no authData".into(),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use ciborium::value::{Integer, Value};
    use p256::ecdsa::{signature::Signer as _, Signature, SigningKey};
    use sha2::{Digest, Sha256};

    fn os_rng() -> p256::elliptic_curve::rand_core::OsRng {
        p256::elliptic_curve::rand_core::OsRng
    }

    fn cose_key_of(vk: &p256::ecdsa::VerifyingKey) -> Vec<u8> {
        let pt = vk.to_encoded_point(false);
        let map = Value::Map(vec![
            (
                Value::Integer(Integer::from(1)),
                Value::Integer(Integer::from(2)),
            ),
            (
                Value::Integer(Integer::from(3)),
                Value::Integer(Integer::from(-7)),
            ),
            (
                Value::Integer(Integer::from(-1)),
                Value::Integer(Integer::from(1)),
            ),
            (
                Value::Integer(Integer::from(-2)),
                Value::Bytes(pt.x().unwrap().to_vec()),
            ),
            (
                Value::Integer(Integer::from(-3)),
                Value::Bytes(pt.y().unwrap().to_vec()),
            ),
        ]);
        let mut out = Vec::new();
        ciborium::ser::into_writer(&map, &mut out).unwrap();
        out
    }

    fn rp_hash(rp_id: &str) -> [u8; 32] {
        let mut h = Sha256::new();
        h.update(rp_id.as_bytes());
        h.finalize().into()
    }

    /// Build registration authData with attested credential data.
    fn reg_auth_data(rp_id: &str, cred_id: &[u8], cose: &[u8], count: u32) -> Vec<u8> {
        let mut d = Vec::new();
        d.extend_from_slice(&rp_hash(rp_id));
        d.push(0b0100_0001); // UP | AT
        d.extend_from_slice(&count.to_be_bytes());
        d.extend_from_slice(&[0u8; 16]); // aaguid
        #[allow(clippy::cast_possible_truncation)]
        d.extend_from_slice(&(cred_id.len() as u16).to_be_bytes());
        d.extend_from_slice(cred_id);
        d.extend_from_slice(cose);
        d
    }

    fn attestation_object(auth_data: &[u8]) -> Vec<u8> {
        let map = Value::Map(vec![
            (Value::Text("fmt".into()), Value::Text("none".into())),
            (Value::Text("attStmt".into()), Value::Map(vec![])),
            (
                Value::Text("authData".into()),
                Value::Bytes(auth_data.to_vec()),
            ),
        ]);
        let mut out = Vec::new();
        ciborium::ser::into_writer(&map, &mut out).unwrap();
        out
    }

    fn client_data(ty: &str, challenge: &[u8], origin: &str) -> Vec<u8> {
        serde_json::to_vec(&serde_json::json!({
            "type": ty,
            "challenge": verify::b64url_encode(challenge),
            "origin": origin,
        }))
        .unwrap()
    }

    #[test]
    fn full_register_then_authenticate_round_trip() {
        let rp_id = "example.com";
        let origins = vec!["https://example.com".to_owned()];
        let sk = SigningKey::random(&mut os_rng());
        let cose = cose_key_of(sk.verifying_key());
        let cred_id = b"credential-handle-1";

        // ---- Registration ----
        let reg_challenge = generate_challenge();
        let reg_ad = reg_auth_data(rp_id, cred_id, &cose, 1);
        let att_obj = attestation_object(&reg_ad);
        let reg_client = client_data("webauthn.create", &reg_challenge, "https://example.com");

        let outcome =
            verify_registration(&reg_challenge, rp_id, &origins, &reg_client, &att_obj).unwrap();
        assert_eq!(outcome.credential_id, verify::b64url_encode(cred_id));
        assert_eq!(outcome.sign_count, 1);
        // The stored key must verify a signature from `sk`.
        verify::cose_es256_key(&outcome.cose_public_key).unwrap();

        // ---- Authentication with the registered key ----
        let auth_challenge = generate_challenge();
        let auth_ad = {
            let mut d = Vec::new();
            d.extend_from_slice(&rp_hash(rp_id));
            d.push(0b0000_0001); // UP only (no AT on assertions)
            d.extend_from_slice(&2u32.to_be_bytes()); // count advanced 1 → 2
            d
        };
        let auth_client = client_data("webauthn.get", &auth_challenge, "https://example.com");
        let mut signed = auth_ad.clone();
        let mut ch = Sha256::new();
        ch.update(&auth_client);
        signed.extend_from_slice(&ch.finalize());
        let sig: Signature = sk.sign(&signed);

        let new_count = verify_authentication(
            &auth_challenge,
            rp_id,
            &origins,
            &outcome.cose_public_key,
            outcome.sign_count,
            &auth_client,
            &auth_ad,
            sig.to_der().as_bytes(),
        )
        .unwrap();
        assert_eq!(new_count.sign_count, 2);
        assert!(!new_count.user_verified);
    }

    /// Sign an assertion with `flags` and `count`, verify it against `stored`.
    fn assert_with(
        flags: u8,
        count: u32,
        stored: i64,
    ) -> Result<AuthenticationOutcome, PasskeyError> {
        let rp_id = "example.com";
        let origins = vec!["https://example.com".to_owned()];
        let sk = SigningKey::random(&mut os_rng());
        let cose = cose_key_of(sk.verifying_key());

        let challenge = generate_challenge();
        let mut ad = Vec::new();
        ad.extend_from_slice(&rp_hash(rp_id));
        ad.push(flags);
        ad.extend_from_slice(&count.to_be_bytes());
        let client = client_data("webauthn.get", &challenge, "https://example.com");
        let mut signed = ad.clone();
        let mut h = Sha256::new();
        h.update(&client);
        signed.extend_from_slice(&h.finalize());
        let sig: Signature = sk.sign(&signed);

        verify_authentication(
            &challenge,
            rp_id,
            &origins,
            &cose,
            stored,
            &client,
            &ad,
            sig.to_der().as_bytes(),
        )
    }

    #[test]
    fn counter_regression_is_rejected() {
        // Stored count 5 > presented 3 → regression rejected.
        let r = assert_with(0b0000_0001, 3, 5);
        assert!(matches!(r, Err(PasskeyError::CounterRegression)));
    }

    #[test]
    fn clone_resetting_counter_to_zero_is_rejected() {
        let r = assert_with(0b0000_0001, 0, 5);
        assert!(matches!(r, Err(PasskeyError::CounterRegression)));
        // An authenticator with no counter (0 → 0) still works.
        assert_eq!(assert_with(0b0000_0001, 0, 0).unwrap().sign_count, 0);
    }

    #[test]
    fn user_verified_flag_is_returned() {
        assert!(assert_with(0b0000_0101, 1, 0).unwrap().user_verified);
        assert!(!assert_with(0b0000_0001, 1, 0).unwrap().user_verified);
    }

    #[test]
    fn options_json_has_required_shape() {
        let reg =
            registration_options_json("example.com", "Example", b"user1", "alice", b"chal", &[]);
        assert_eq!(reg["rp"]["id"], "example.com");
        assert_eq!(reg["pubKeyCredParams"][0]["alg"], -7);
        let auth = authentication_options_json("example.com", b"chal", &["abc".to_owned()]);
        assert_eq!(auth["rpId"], "example.com");
        assert_eq!(auth["allowCredentials"][0]["id"], "abc");
    }
}