entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! `WebAuthn` PRF (Pseudo-Random Function) extension helpers.
//!
//! The PRF extension (W3C `WebAuthn` Level 3, formerly the CTAP2.1
//! `hmac-secret` extension on the wire) lets a relying party derive a
//! credential-scoped 32-byte secret on the authenticator. The output
//! never leaves the client, which is what makes it suitable as a
//! key-encryption-key (KEK) for end-to-end-encrypted vault material:
//! the server learns whether PRF was honoured, but never learns the
//! KEK itself.
//!
//! This module covers only the **request-side** wire format and the
//! **response-side** flag detection. The upstream `webauthn-rs` 0.5.x
//! API does not surface PRF directly (it exposes the CTAP2 `hmac-secret`
//! layer beneath), so this module operates at the JSON layer: we splice
//! a `prf` extension object into the challenge JSON before handing it
//! to the user agent, and we read the `prf.enabled` / `prf.results`
//! flag back out of the user agent's response. The cryptographic
//! validation of the surrounding assertion stays inside `webauthn-rs`.
//!
//! # Salt selection
//!
//! Each credential gets its own random 32-byte salt at registration
//! time. The salt is stored by the relying party (the plan's
//! `user_passkeys.prf_salt` column) and is replayed verbatim on every
//! subsequent authentication. Deterministic per-credential salting
//! guarantees the same PRF output across sessions, which is what makes
//! the wrap stable and the unwrap repeatable.
//!
//! The salt is wrapped in a [`PrfSalt`] newtype that:
//!
//! * Holds exactly 32 bytes — the PRF input is fixed-width per spec.
//! * Implements neither `Display` nor an unredacted `Debug`. The salt
//!   itself is not a secret in the cryptographic sense (it's public
//!   per-credential metadata stored alongside the credential), but
//!   keeping it out of logs prevents accidental correlation across
//!   audit trails.

use core::fmt;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::crypto::zeroize::Zeroizing;
use crate::crypto::{RandomError, fill_random};
use crate::encoding::base64url_encode;
use crate::webauthn::error::WebAuthnError;

/// Fixed byte length of a PRF salt (per W3C `WebAuthn` L3 §10.1.4).
pub const PRF_SALT_LEN: usize = 32;

// ---------------------------------------------------------------------------
// PrfSalt
// ---------------------------------------------------------------------------

/// A 32-byte PRF salt bound to a single credential.
///
/// Generate one at registration time via [`PrfSalt::generate`], persist
/// it alongside the credential, and replay it on every authentication
/// for that credential. The salt is not a secret in the cryptographic
/// sense, but its `Debug` impl is redacted to keep it out of audit
/// logs.
// `Zeroizing<T>` deliberately omits `PartialEq` to keep secret material
// off non-constant-time comparison paths; the salt itself is not a
// cryptographic secret (it's per-credential public metadata), but
// preserving the omission keeps the type's compare-via-bytes contract
// uniform across the crate.
#[derive(Clone)]
pub struct PrfSalt {
    bytes: Zeroizing<Vec<u8>>,
}

impl PrfSalt {
    /// Generates a new random 32-byte PRF salt.
    ///
    /// # Errors
    ///
    /// Returns the underlying [`RandomError`] if the platform CSPRNG is
    /// unavailable. This is the same failure surface as
    /// [`fill_random`].
    pub fn generate() -> Result<Self, RandomError> {
        let mut buf = vec![0u8; PRF_SALT_LEN];
        fill_random(&mut buf)?;
        Ok(Self {
            bytes: Zeroizing::new(buf),
        })
    }

    /// Constructs a `PrfSalt` from caller-supplied bytes.
    ///
    /// # Errors
    ///
    /// Returns [`WebAuthnError::invalid_configuration`] if `bytes` is
    /// not exactly [`PRF_SALT_LEN`] (32) bytes long.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, WebAuthnError> {
        if bytes.len() != PRF_SALT_LEN {
            return Err(WebAuthnError::invalid_configuration(format!(
                "prf salt must be {PRF_SALT_LEN} bytes, got {}",
                bytes.len()
            )));
        }
        Ok(Self {
            bytes: Zeroizing::new(bytes),
        })
    }

    /// Returns the salt as raw bytes.
    #[must_use]
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Returns the salt as URL-safe base64 (no padding), the on-wire
    /// encoding required by the `WebAuthn` PRF extension.
    #[must_use]
    #[inline]
    pub fn to_base64url(&self) -> String {
        base64url_encode(&self.bytes)
    }
}

impl fmt::Debug for PrfSalt {
    /// SECURITY: Redacted to keep per-credential salts out of audit logs.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PrfSalt").finish_non_exhaustive()
    }
}

impl Serialize for PrfSalt {
    /// Serialized as its raw bytes so a credential carrying a PRF salt can
    /// be persisted and replayed on later authentications. The salt is
    /// per-credential metadata, not a cryptographic secret (the PRF output
    /// never leaves the client), so persisting it is intended.
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.as_bytes().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for PrfSalt {
    /// Reconstructed from raw bytes via [`PrfSalt::from_bytes`] (which
    /// enforces the 32-byte length invariant).
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let bytes = Vec::<u8>::deserialize(deserializer)?;
        Self::from_bytes(bytes).map_err(serde::de::Error::custom)
    }
}

// ---------------------------------------------------------------------------
// Request payload (registration)
// ---------------------------------------------------------------------------

/// The PRF extension request payload for a registration ceremony.
///
/// At registration time, we only need to *signal* that the authenticator
/// should generate PRF material for this credential. The client agent
/// (browser or platform API) inspects `prf.eval.first` and decides
/// whether to enroll the credential with PRF capability. `to_json_value`
/// emits the `eval`-only shape, which is what W3C `WebAuthn` L3 specifies for
/// `create()`. (The doc previously claimed both `eval` and `enabled: true`
/// were sent; only `eval` ever was.)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrfRegistrationRequest {
    /// Salt under `eval.first`; encoded as URL-safe base64 (no padding).
    pub eval_first_b64url: String,
}

impl PrfRegistrationRequest {
    /// Builds a registration-side PRF request from a credential salt.
    #[must_use]
    pub fn from_salt(salt: &PrfSalt) -> Self {
        Self {
            eval_first_b64url: salt.to_base64url(),
        }
    }

    /// Renders this request as the JSON object the user agent expects
    /// under `publicKey.extensions.prf`.
    #[must_use]
    pub fn to_json_value(&self) -> Value {
        serde_json::json!({
            "eval": {
                "first": self.eval_first_b64url,
            },
        })
    }
}

// ---------------------------------------------------------------------------
// Request payload (authentication)
// ---------------------------------------------------------------------------

/// The PRF extension request payload for an authentication ceremony.
///
/// At authentication time, the relying party must supply the credential
/// salt under `eval.first`. The user agent invokes the authenticator's
/// hmac-secret, prefixed with the `WebAuthn` PRF context string, and
/// returns the 32-byte output under `clientExtensionResults.prf.results`.
/// That output never reaches the server; only the *presence* of the
/// `results` field is observed, and that is what
/// [`PrfClientResult::was_honored`] checks.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrfAuthenticationRequest {
    /// Salt under `eval.first`; encoded as URL-safe base64 (no padding).
    pub eval_first_b64url: String,
}

impl PrfAuthenticationRequest {
    /// Builds an authentication-side PRF request from a credential salt.
    #[must_use]
    pub fn from_salt(salt: &PrfSalt) -> Self {
        Self {
            eval_first_b64url: salt.to_base64url(),
        }
    }

    /// Renders this request as the JSON object the user agent expects
    /// under `publicKey.extensions.prf`.
    #[must_use]
    pub fn to_json_value(&self) -> Value {
        serde_json::json!({
            "eval": {
                "first": self.eval_first_b64url,
            },
        })
    }
}

/// Builds the authentication-side PRF extension value using
/// `evalByCredential` (`WebAuthn` L3): each credential ID maps to its own
/// salt under `first`, so the authenticator derives PRF output with the
/// **correct** salt for whichever credential ends up signing.
///
/// This is required for a user with more than one PRF credential: a single
/// `eval.first` would send one credential's salt for all of them, so signing
/// with a *different* credential would derive a different KEK than the one the
/// data was wrapped under — silently breaking unwrap. Returns `None` if no
/// credential carries a salt.
///
/// `entries` pairs each credential's raw ID with its salt. The returned value
/// is spliced under `publicKey.extensions.prf` by
/// [`merge_prf_extension`](super::merge_prf_extension).
#[must_use]
pub(crate) fn eval_by_credential_value(entries: &[(&[u8], &PrfSalt)]) -> Option<Value> {
    if entries.is_empty() {
        return None;
    }
    let mut by_cred = serde_json::Map::with_capacity(entries.len());
    for (cred_id, salt) in entries {
        by_cred.insert(
            base64url_encode(cred_id),
            serde_json::json!({ "first": salt.to_base64url() }),
        );
    }
    Some(serde_json::json!({ "evalByCredential": by_cred }))
}

// ---------------------------------------------------------------------------
// Response inspection
// ---------------------------------------------------------------------------

/// Result of looking at the PRF section of a `clientExtensionResults`
/// object.
///
/// The relying party never receives the PRF output bytes themselves
/// (that's the whole point of PRF — the secret stays on the client).
/// What it sees is one of three states:
///
/// * [`PrfClientResult::Honored`] — the authenticator generated PRF
///   material and the client used it. For registration, this means the
///   credential is PRF-capable for future authentications; the
///   `user_passkeys.prf_supported` flag is set. For authentication,
///   this means the client successfully derived its KEK.
/// * [`PrfClientResult::Unsupported`] — the authenticator did not
///   honor the extension. The credential is still valid; vault unlock
///   falls back to the master password path.
/// * [`PrfClientResult::Absent`] — the response did not include any
///   `prf` block at all. Treated identically to `Unsupported` by the
///   relying party.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrfClientResult {
    /// The authenticator generated PRF material.
    Honored,
    /// The authenticator declined the extension.
    Unsupported,
    /// The response carried no `prf` block.
    Absent,
}

impl PrfClientResult {
    /// Returns `true` iff PRF material was successfully generated.
    #[must_use]
    #[inline]
    pub fn was_honored(self) -> bool {
        matches!(self, Self::Honored)
    }
}

// ---------------------------------------------------------------------------
// Wire-format inspection (registration)
// ---------------------------------------------------------------------------

/// Inspects a registration response's `clientExtensionResults` object
/// for the `prf` block.
///
/// The `WebAuthn` L3 spec uses `prf.enabled: bool` at registration time
/// to signal whether the authenticator agreed to generate PRF material.
/// Some browsers also include `prf.results` if the registration ceremony
/// requested `eval` (which we always do for compatibility). Either
/// signal counts as "honored".
#[must_use]
pub fn inspect_registration_response(client_extension_results: &Value) -> PrfClientResult {
    let Some(prf) = client_extension_results.get("prf") else {
        return PrfClientResult::Absent;
    };

    // `enabled` is authoritative when present: `true` means the
    // authenticator agreed to generate PRF material, `false` is an explicit
    // decline that overrides any stray `results` block.
    match prf.get("enabled").and_then(Value::as_bool) {
        Some(true) => return PrfClientResult::Honored,
        Some(false) => return PrfClientResult::Unsupported,
        None => {}
    }

    // `enabled` absent: fall back to a `results` block, which some browsers
    // emit when registration requested `eval`. Require a non-null object —
    // an explicit `results: null` is malformed and must not read as honored.
    if prf.get("results").and_then(Value::as_object).is_some() {
        return PrfClientResult::Honored;
    }

    // `prf` block present but empty or unrecognised shape — treat as
    // unsupported rather than absent to record that the authenticator
    // did acknowledge the extension.
    PrfClientResult::Unsupported
}

// ---------------------------------------------------------------------------
// Wire-format inspection (authentication)
// ---------------------------------------------------------------------------

/// Inspects an authentication response's `clientExtensionResults` for
/// the `prf` block.
///
/// At authentication time the signal is `prf.results.first`: a 32-byte
/// base64url string. If present, the client successfully evaluated the
/// PRF and the relying party can return the stored wrap row. If absent,
/// the relying party returns no wrap and the client falls back to the
/// master password unlock path.
#[must_use]
pub fn inspect_authentication_response(client_extension_results: &Value) -> PrfClientResult {
    let Some(prf) = client_extension_results.get("prf") else {
        return PrfClientResult::Absent;
    };

    // `first` must be a non-null base64url string. An explicit `null` (or any
    // non-string shape) means no PRF output was derived — `Value::get` returns
    // `Some(Value::Null)` for `"first": null`, so a bare `.is_some()` would
    // wrongly read that as honored. Require an actual string.
    if let Some(results) = prf.get("results") {
        if results.get("first").and_then(Value::as_str).is_some() {
            return PrfClientResult::Honored;
        }
    }

    PrfClientResult::Unsupported
}

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

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

    #[test]
    fn salt_generate_is_correct_length() {
        let salt = PrfSalt::generate().unwrap();
        assert_eq!(salt.as_bytes().len(), PRF_SALT_LEN);
    }

    #[test]
    fn salt_from_bytes_correct_length() {
        let salt = PrfSalt::from_bytes(vec![0u8; PRF_SALT_LEN]).unwrap();
        assert_eq!(salt.as_bytes(), &[0u8; PRF_SALT_LEN]);
    }

    #[test]
    fn salt_from_bytes_rejects_short_input() {
        let err = PrfSalt::from_bytes(vec![0u8; 16]).unwrap_err();
        assert!(err.is_invalid_configuration());
    }

    #[test]
    fn salt_from_bytes_rejects_long_input() {
        let err = PrfSalt::from_bytes(vec![0u8; 64]).unwrap_err();
        assert!(err.is_invalid_configuration());
    }

    #[test]
    fn salt_debug_redacts() {
        let salt = PrfSalt::from_bytes(vec![0xAB; PRF_SALT_LEN]).unwrap();
        let dbg = format!("{salt:?}");
        assert!(dbg.contains("PrfSalt"));
        // Hex of 0xAB
        assert!(!dbg.contains("AB"));
        assert!(!dbg.contains("ab"));
    }

    #[test]
    fn salt_base64url_round_trip_stable() {
        let bytes: Vec<u8> = (0u8..32).collect();
        let salt = PrfSalt::from_bytes(bytes.clone()).unwrap();
        let s1 = salt.to_base64url();
        let s2 = salt.to_base64url();
        assert_eq!(s1, s2);
        // No padding, URL-safe alphabet.
        assert!(!s1.contains('='));
        assert!(!s1.contains('+'));
        assert!(!s1.contains('/'));
    }

    #[test]
    fn prf_client_result_was_honored() {
        assert!(PrfClientResult::Honored.was_honored());
        assert!(!PrfClientResult::Unsupported.was_honored());
        assert!(!PrfClientResult::Absent.was_honored());
    }

    #[test]
    fn registration_request_to_json_value_shape() {
        let salt = PrfSalt::from_bytes(vec![1u8; PRF_SALT_LEN]).unwrap();
        let req = PrfRegistrationRequest::from_salt(&salt);
        let v = req.to_json_value();
        assert_eq!(v["eval"]["first"], salt.to_base64url());
    }

    #[test]
    fn authentication_request_to_json_value_shape() {
        let salt = PrfSalt::from_bytes(vec![2u8; PRF_SALT_LEN]).unwrap();
        let req = PrfAuthenticationRequest::from_salt(&salt);
        let v = req.to_json_value();
        assert_eq!(v["eval"]["first"], salt.to_base64url());
    }

    #[test]
    fn inspect_registration_response_enabled_true() {
        let v = serde_json::json!({"prf": {"enabled": true}});
        assert_eq!(inspect_registration_response(&v), PrfClientResult::Honored);
    }

    #[test]
    fn inspect_registration_response_results_present() {
        let v = serde_json::json!({"prf": {"results": {"first": "AAAA"}}});
        assert_eq!(inspect_registration_response(&v), PrfClientResult::Honored);
    }

    #[test]
    fn inspect_registration_response_enabled_false_overrides_results() {
        // `enabled: false` is an authoritative decline at registration and
        // must win even if a stray `results` block is also present.
        let v = serde_json::json!({"prf": {"enabled": false, "results": {"first": "AAAA"}}});
        assert_eq!(
            inspect_registration_response(&v),
            PrfClientResult::Unsupported
        );
    }

    #[test]
    fn inspect_registration_response_enabled_false() {
        let v = serde_json::json!({"prf": {"enabled": false}});
        assert_eq!(
            inspect_registration_response(&v),
            PrfClientResult::Unsupported
        );
    }

    #[test]
    fn inspect_registration_response_absent() {
        let v = serde_json::json!({});
        assert_eq!(inspect_registration_response(&v), PrfClientResult::Absent);
    }

    #[test]
    fn inspect_authentication_response_results_first_present() {
        let v = serde_json::json!({"prf": {"results": {"first": "AAAA"}}});
        assert_eq!(
            inspect_authentication_response(&v),
            PrfClientResult::Honored
        );
    }

    #[test]
    fn inspect_authentication_response_no_results() {
        let v = serde_json::json!({"prf": {}});
        assert_eq!(
            inspect_authentication_response(&v),
            PrfClientResult::Unsupported
        );
    }

    #[test]
    fn inspect_authentication_response_absent() {
        let v = serde_json::json!({});
        assert_eq!(inspect_authentication_response(&v), PrfClientResult::Absent);
    }

    #[test]
    fn inspect_authentication_response_first_null_is_not_honored() {
        // `serde_json::Value::get` returns `Some(Value::Null)` for an explicit
        // `null`; a bare `.is_some()` would wrongly treat that as honored.
        let v = serde_json::json!({"prf": {"results": {"first": null}}});
        assert_eq!(
            inspect_authentication_response(&v),
            PrfClientResult::Unsupported
        );
    }

    #[test]
    fn inspect_authentication_response_first_non_string_is_not_honored() {
        let v = serde_json::json!({"prf": {"results": {"first": 123}}});
        assert_eq!(
            inspect_authentication_response(&v),
            PrfClientResult::Unsupported
        );
    }

    #[test]
    fn eval_by_credential_maps_each_credential_to_its_own_salt() {
        let salt_a = PrfSalt::from_bytes(vec![0xAAu8; PRF_SALT_LEN]).unwrap();
        let salt_b = PrfSalt::from_bytes(vec![0xBBu8; PRF_SALT_LEN]).unwrap();
        let cred_a: &[u8] = b"cred-a";
        let cred_b: &[u8] = b"cred-b";

        let v = eval_by_credential_value(&[(cred_a, &salt_a), (cred_b, &salt_b)]).unwrap();
        let by_cred = v
            .get("evalByCredential")
            .and_then(Value::as_object)
            .unwrap();

        // One entry per credential, keyed by base64url(credential_id), each
        // carrying its OWN salt under `first`.
        assert_eq!(by_cred.len(), 2);
        let key_a = crate::encoding::base64url_encode(cred_a);
        let key_b = crate::encoding::base64url_encode(cred_b);
        assert_eq!(
            by_cred[&key_a]["first"].as_str().unwrap(),
            salt_a.to_base64url()
        );
        assert_eq!(
            by_cred[&key_b]["first"].as_str().unwrap(),
            salt_b.to_base64url()
        );
        assert_ne!(salt_a.to_base64url(), salt_b.to_base64url());
    }

    #[test]
    fn eval_by_credential_empty_is_none() {
        assert!(eval_by_credential_value(&[]).is_none());
    }

    #[test]
    fn inspect_registration_response_results_null_is_not_honored() {
        // `enabled` absent and `results: null` is a malformed shape — it must
        // not read as honored.
        let v = serde_json::json!({"prf": {"results": null}});
        assert_eq!(
            inspect_registration_response(&v),
            PrfClientResult::Unsupported
        );
    }

    #[test]
    fn salt_determinism_same_input_same_output() {
        // Same input bytes must always produce the same wire-encoded
        // form. This is the property the consumer relies on to make
        // PRF wrap/unwrap stable across sessions.
        let bytes: Vec<u8> = (0u8..32).map(|i| i.wrapping_mul(7)).collect();
        let a = PrfSalt::from_bytes(bytes.clone()).unwrap();
        let b = PrfSalt::from_bytes(bytes).unwrap();
        assert_eq!(a.to_base64url(), b.to_base64url());
        assert_eq!(a.as_bytes(), b.as_bytes());
    }
}