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
#![allow(missing_docs)]

//! Integration tests for the public `webauthn` API.
//!
//! These tests exercise the data-flow paths a consumer of the crate
//! traverses without driving a real authenticator:
//!
//! * `RelyingParty` builder validation (negative cases for the
//!   origin / RP-ID checks).
//! * `PrfSalt` determinism — the property that makes client-side
//!   wrap / unwrap stable across sessions.
//! * `PrfRegistrationRequest` / `PrfAuthenticationRequest` wire-form
//!   construction.
//! * `inspect_registration_response` / `inspect_authentication_response`
//!   over crafted `clientExtensionResults` JSON, covering the three
//!   PRF outcome states (`Honored` / `Unsupported` / `Absent`).
//! * `PasskeyCredentialStore` empty-state behaviour through the in-
//!   memory implementation (unknown credential → `None`,
//!   double-remove → false).
//! * Public taxonomy of `WebAuthnError` (every `is_*` predicate is
//!   exported and stable as a compile-time-asserted function pointer).
//!
//! ## Negative cases for the cryptographic surface
//!
//! Origin mismatch, RP-ID mismatch, sign-count rollback, and
//! attestation failure are surfaced by `WebAuthnError` variants
//! constructed inside the crate by the `webauthn-rs` error mapper.
//! Their constructors are `pub(crate)` — same pattern as `AuthError`
//! — so the negative-path *unit tests* live alongside the constructors
//! in `src/webauthn/error.rs`. Driving end-to-end cryptographic
//! failures from an integration test would require either an in-tree
//! authenticator simulator (not present) or a `webauthn-rs` round-
//! trip fixture, neither of which is in Phase 1 scope. Phase 2 will
//! be able to exercise these paths through `#[sqlx::test]` handler
//! tests once the HTTP layer wraps the ceremonies.
//!
//! Likewise, the "register/authenticate happy path with/without PRF"
//! data-flow tests live in `src/webauthn/mod.rs` and `src/webauthn/
//! prf.rs`: they cover the salt persistence, the `prf_supported` flag
//! propagation through `StoredPasskey` serialisation, and the
//! `clientExtensionResults` inspection. The integration suite here
//! covers the *public API contract* — the surface a downstream crate
//! can build against — without requiring a live authenticator.

use entropy_auth::webauthn::{
    InMemoryPasskeyStore, PRF_SALT_LEN, PasskeyCredentialStore, PasskeyUser,
    PrfAuthenticationRequest, PrfClientResult, PrfRegistrationRequest, PrfSalt,
    RegistrationCeremony, RelyingParty, Uuid, WebAuthnError, prf,
};

// ---------------------------------------------------------------------------
// RelyingParty builder
// ---------------------------------------------------------------------------

#[test]
fn rp_builder_happy_path() {
    let rp = RelyingParty::builder("example.com", "Example Corp")
        .origin("https://example.com")
        .build()
        .expect("valid configuration should build");
    assert_eq!(rp.rp_id(), "example.com");
    assert_eq!(rp.rp_name(), "Example Corp");
    assert_eq!(rp.origins(), &["https://example.com".to_owned()]);
}

#[test]
fn rp_builder_accepts_multiple_origins() {
    let rp = RelyingParty::builder("example.com", "Example")
        .origin("https://example.com")
        .origin("https://app.example.com")
        .build()
        .expect("multi-origin should build");
    assert_eq!(rp.origins().len(), 2);
}

#[test]
fn rp_builder_rejects_empty_rp_id() {
    // SECURITY: An empty rp_id would let an attacker site claim to be
    // any relying party. Reject at builder time.
    let err = RelyingParty::builder("", "Example")
        .origin("https://example.com")
        .build()
        .expect_err("empty rp_id must be rejected");
    assert!(err.is_invalid_configuration());
    assert!(
        !err.is_origin_mismatch() && !err.is_rp_id_mismatch(),
        "config errors must not masquerade as runtime taxonomies",
    );
}

#[test]
fn rp_builder_rejects_no_origins() {
    // SECURITY: Without an origin allowlist every origin would be
    // implicitly trusted. Reject at builder time.
    let err = RelyingParty::builder("example.com", "Example")
        .build()
        .expect_err("missing origins must be rejected");
    assert!(err.is_invalid_configuration());
}

#[test]
fn rp_builder_rejects_malformed_origin() {
    let err = RelyingParty::builder("example.com", "Example")
        .origin("not a valid url")
        .build()
        .expect_err("malformed origin must be rejected");
    assert!(err.is_invalid_configuration());
}

#[test]
fn rp_debug_does_not_leak_internals() {
    let rp = RelyingParty::builder("example.com", "Example")
        .origin("https://example.com")
        .build()
        .unwrap();
    let dbg = format!("{rp:?}");
    assert!(dbg.contains("example.com"));
    // The internal `webauthn-rs` Webauthn handle must not be exposed
    // verbatim — its Debug output may include challenge-state internals.
    assert!(!dbg.contains("webauthn-rs"));
}

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

#[test]
fn prf_salt_generate_is_correct_length() {
    let salt = PrfSalt::generate().expect("CSPRNG should produce 32 bytes");
    assert_eq!(salt.as_bytes().len(), PRF_SALT_LEN);
}

#[test]
fn prf_salt_two_generations_differ() {
    let a = PrfSalt::generate().unwrap();
    let b = PrfSalt::generate().unwrap();
    assert_ne!(a.as_bytes(), b.as_bytes(), "random salts must differ");
}

#[test]
fn prf_salt_from_bytes_round_trip() {
    let bytes: Vec<u8> = (0u8..32).collect();
    let salt = PrfSalt::from_bytes(bytes.clone()).unwrap();
    assert_eq!(salt.as_bytes(), bytes.as_slice());
}

#[test]
fn prf_salt_rejects_wrong_length() {
    let too_short = PrfSalt::from_bytes(vec![0; 16]).unwrap_err();
    assert!(too_short.is_invalid_configuration());
    let too_long = PrfSalt::from_bytes(vec![0; 64]).unwrap_err();
    assert!(too_long.is_invalid_configuration());
}

#[test]
fn prf_salt_determinism_same_input_same_wire_form() {
    // SECURITY: This is the core property that makes the client-side
    // wrap / unwrap stable. The same salt MUST always produce the same
    // base64url wire form so the authenticator derives the same PRF
    // output on every authentication, which is what makes the same
    // KEK derivable, which is what makes the same wrapped symmetric
    // key unwrappable. If this property breaks, every PRF-capable
    // credential becomes a one-shot.
    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());
}

#[test]
fn prf_salt_wire_form_is_url_safe_unpadded() {
    let salt = PrfSalt::from_bytes(vec![0xFFu8; 32]).unwrap();
    let wire = salt.to_base64url();
    assert!(!wire.contains('='), "no padding");
    assert!(!wire.contains('+'), "no standard-base64 plus");
    assert!(!wire.contains('/'), "no standard-base64 slash");
}

#[test]
fn prf_salt_debug_redacts_bytes() {
    // SECURITY: The salt is not a secret in the cryptographic sense
    // but its `Debug` impl is redacted so it does not appear in audit
    // logs.
    let salt = PrfSalt::from_bytes(vec![0xAB; PRF_SALT_LEN]).unwrap();
    let dbg = format!("{salt:?}");
    assert!(dbg.contains("PrfSalt"));
    assert!(!dbg.contains("AB"), "redacted form must not expose bytes");
    assert!(!dbg.contains("ab"));
}

// ---------------------------------------------------------------------------
// PRF wire-form requests
// ---------------------------------------------------------------------------

#[test]
fn registration_request_payload_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_payload_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 registration_request_round_trip_serde() {
    // The registration request struct is `Serialize + Deserialize` so
    // a Phase-2 HTTP handler can persist it server-side alongside the
    // challenge state if needed.
    let salt = PrfSalt::from_bytes(vec![3u8; PRF_SALT_LEN]).unwrap();
    let req = PrfRegistrationRequest::from_salt(&salt);
    let s = serde_json::to_string(&req).unwrap();
    let back: PrfRegistrationRequest = serde_json::from_str(&s).unwrap();
    assert_eq!(back.eval_first_b64url, salt.to_base64url());
}

// ---------------------------------------------------------------------------
// PRF response inspection
// ---------------------------------------------------------------------------

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

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

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

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

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

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

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

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

// ---------------------------------------------------------------------------
// InMemoryPasskeyStore: empty-state behaviour
// ---------------------------------------------------------------------------

#[test]
fn unknown_credential_lookup_returns_none() {
    // Surrogate for "unknown credential rejected": at the store layer,
    // unknown credentials yield `Ok(None)`. The authentication
    // ceremony lifts this into `WebAuthnError::credential_not_found`
    // — see `src/webauthn/error.rs` unit tests for the variant
    // surface and the in-module ceremony unit tests for the lift.
    let store = InMemoryPasskeyStore::new();
    let result = store.lookup_by_credential_id(b"does-not-exist").unwrap();
    assert!(result.is_none(), "unknown credential must return None");
}

#[test]
fn unknown_user_lookup_returns_empty_vec() {
    let store = InMemoryPasskeyStore::new();
    let result = store.lookup_by_user(b"nobody").unwrap();
    assert!(result.is_empty());
}

#[test]
fn remove_unknown_credential_returns_false() {
    let mut store = InMemoryPasskeyStore::new();
    assert!(
        !store.remove(b"never-stored").unwrap(),
        "remove on empty store returns false",
    );
}

#[test]
fn update_unknown_credential_is_noop() {
    let mut store = InMemoryPasskeyStore::new();
    // Updates on unknown credentials are silently dropped — the
    // store has no row to update. This mirrors how the SQL layer
    // will behave: an UPDATE that matches zero rows is not an error.
    store.update_sign_count(b"never-stored", 42).unwrap();
    let after = store.lookup_by_credential_id(b"never-stored").unwrap();
    assert!(after.is_none());
}

// ---------------------------------------------------------------------------
// WebAuthnError taxonomy contract (every public `is_*` predicate)
// ---------------------------------------------------------------------------

#[test]
fn webauthn_error_public_query_surface_is_present() {
    // The `is_*` predicates are the contract Phase 2 relies on when
    // mapping `WebAuthnError` to HTTP error codes. This compile-time
    // assertion ensures every predicate stays exported.
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_invalid_configuration;
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_challenge_mismatch;
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_attestation_failed;
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_origin_mismatch;
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_rp_id_mismatch;
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_credential_not_found;
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_sign_count_rollback;
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_user_verification_failed;
    let _: fn(&WebAuthnError) -> bool = WebAuthnError::is_internal;
    let _: fn(&WebAuthnError) -> Option<&str> = WebAuthnError::detail;
}

// ---------------------------------------------------------------------------
// RegistrationChallenge / AuthenticationChallenge: merged_challenge_json
// ---------------------------------------------------------------------------

fn build_rp() -> RelyingParty {
    RelyingParty::builder("example.com", "Example")
        .origin("https://example.com")
        .build()
        .expect("rp should build")
}

fn begin_registration(request_prf: bool) -> entropy_auth::webauthn::RegistrationChallenge {
    let rp = build_rp();
    RegistrationCeremony::begin(
        &rp,
        PasskeyUser {
            id: Uuid::new_v4(),
            name: "alice@example.com".to_owned(),
            display_name: "Alice".to_owned(),
        },
        None,
        request_prf,
    )
    .expect("ceremony should begin")
}

#[test]
fn registration_merged_challenge_json_includes_prf_under_extensions() {
    let challenge = begin_registration(true);
    let merged = challenge.merged_challenge_json();
    let prf_eval_first = merged
        .pointer("/publicKey/extensions/prf/eval/first")
        .expect("merged JSON must expose publicKey.extensions.prf.eval.first when PRF requested");
    let prf_first_str = prf_eval_first.as_str().expect("eval.first is a string");
    assert_eq!(
        prf_first_str,
        challenge
            .prf_salt()
            .expect("PRF was requested")
            .to_base64url(),
        "PRF salt under merged JSON must match the salt returned via prf_salt()",
    );
}

#[test]
fn registration_merged_challenge_json_omits_prf_when_not_requested() {
    let challenge = begin_registration(false);
    let merged = challenge.merged_challenge_json();
    assert!(
        merged.pointer("/publicKey/extensions/prf").is_none(),
        "merged JSON must NOT contain publicKey.extensions.prf when PRF was not requested",
    );
    assert!(challenge.prf_salt().is_none());
    assert!(challenge.prf_extension_json().is_none());
}

#[test]
fn registration_merged_challenge_json_preserves_other_keys() {
    // SECURITY: the merge must not clobber any other fields webauthn-rs
    // has placed under `publicKey` or `publicKey.extensions`. webauthn-rs
    // 0.5 sets cred_protect / uvm / cred_props on every registration; our
    // merge MUST leave those alone.
    let challenge = begin_registration(true);
    let merged = challenge.merged_challenge_json();
    let raw = challenge.challenge_json();

    let public_key = merged
        .get("publicKey")
        .and_then(|v| v.as_object())
        .expect("publicKey is an object");
    for (key, value) in public_key {
        if key == "extensions" {
            continue;
        }
        assert_eq!(
            Some(value),
            raw.get("publicKey").and_then(|v| v.get(key)),
            "merge must preserve publicKey.{key} verbatim",
        );
    }

    // Every extension key the raw challenge already had must be
    // preserved verbatim under the merged challenge's extensions.
    if let Some(raw_exts) = raw
        .get("publicKey")
        .and_then(|pk| pk.get("extensions"))
        .and_then(|e| e.as_object())
    {
        let merged_exts = merged
            .get("publicKey")
            .and_then(|pk| pk.get("extensions"))
            .and_then(|e| e.as_object())
            .expect("merged extensions object present");
        for (key, value) in raw_exts {
            assert_eq!(
                Some(value),
                merged_exts.get(key),
                "merge must preserve publicKey.extensions.{key} verbatim",
            );
        }
    }
}

#[test]
fn registration_merged_challenge_json_is_idempotent() {
    let challenge = begin_registration(true);
    let once = challenge.merged_challenge_json();
    // Re-extract: cloning the result and merging-again with the same
    // PRF extension JSON must produce the same value.
    let twice = {
        let mut v = once.clone();
        if let (Some(prf_ext), Some(extensions)) = (
            challenge.prf_extension_json(),
            v.get_mut("publicKey")
                .and_then(|pk| pk.get_mut("extensions"))
                .and_then(|e| e.as_object_mut()),
        ) {
            extensions.insert("prf".to_owned(), prf_ext.clone());
        }
        v
    };
    assert_eq!(once, twice, "merged_challenge_json must be idempotent");
}

// ---------------------------------------------------------------------------
// RegistrationChallenge::into_state_with_salt
// ---------------------------------------------------------------------------

#[test]
fn registration_into_state_with_salt_returns_same_bytes_as_borrowed_accessor() {
    // SECURITY/CORRECTNESS: the persistence-flow accessor must return
    // exactly the same salt bytes the borrowed accessor exposed. If
    // these ever diverged, a caller that mixed the two APIs would
    // round-trip a wrong salt and silently disable PRF on finish.
    let challenge = begin_registration(true);
    let borrowed = challenge
        .prf_salt()
        .expect("PRF was requested")
        .as_bytes()
        .to_vec();
    let (_state, owned_salt) = challenge.into_state_with_salt();
    let owned = owned_salt
        .expect("PRF salt must round-trip")
        .as_bytes()
        .to_vec();
    assert_eq!(
        owned, borrowed,
        "into_state_with_salt must return the exact bytes prf_salt() borrowed",
    );
}

#[test]
fn registration_into_state_with_salt_none_when_prf_not_requested() {
    let challenge = begin_registration(false);
    let (_state, salt) = challenge.into_state_with_salt();
    assert!(
        salt.is_none(),
        "salt slot must be None when PRF was not requested at begin()",
    );
}

#[test]
fn registration_into_state_with_salt_some_when_prf_requested() {
    let challenge = begin_registration(true);
    let expected = challenge
        .prf_salt()
        .expect("PRF was requested")
        .as_bytes()
        .to_vec();
    let (_state, salt) = challenge.into_state_with_salt();
    let actual = salt.expect("salt slot must be Some when PRF was requested");
    assert_eq!(
        actual.as_bytes(),
        expected.as_slice(),
        "consumed salt bytes must equal the bytes prf_salt() returned before consumption",
    );
    assert_eq!(actual.as_bytes().len(), PRF_SALT_LEN);
}

// ---------------------------------------------------------------------------
// AuthenticationChallenge: merged JSON
// ---------------------------------------------------------------------------

#[test]
fn authentication_merged_challenge_json_omits_prf_when_no_credentials() {
    let rp = build_rp();
    // No allow_credentials → no PRF salt → no PRF extension JSON.
    let challenge = entropy_auth::webauthn::AuthenticationCeremony::begin(&rp, &[])
        .expect("authentication ceremony should begin");
    let merged = challenge.merged_challenge_json();
    assert!(
        merged.pointer("/publicKey/extensions/prf").is_none(),
        "authentication merged JSON must NOT contain prf when no PRF-capable cred is provided",
    );
    assert!(challenge.prf_extension_json().is_none());
}

#[test]
fn webauthn_error_has_no_prf_predicate() {
    // SECURITY: Plan §2.2 — missing PRF is a *flag*, never an error.
    // There is no `is_prf_*` predicate by design. This test exists
    // primarily as a hook for `git blame` to flag any future PR that
    // adds one.
    //
    // We list every predicate we *do* support; if a new one is added,
    // the contributor will see this comment in code review.
    // The binding exists purely to assert these items compile/resolve.
    #[allow(clippy::no_effect_underscore_binding)]
    let _surface = (
        WebAuthnError::is_invalid_configuration as fn(&WebAuthnError) -> bool,
        WebAuthnError::is_challenge_mismatch as fn(&WebAuthnError) -> bool,
        WebAuthnError::is_attestation_failed as fn(&WebAuthnError) -> bool,
        WebAuthnError::is_origin_mismatch as fn(&WebAuthnError) -> bool,
        WebAuthnError::is_rp_id_mismatch as fn(&WebAuthnError) -> bool,
        WebAuthnError::is_credential_not_found as fn(&WebAuthnError) -> bool,
        WebAuthnError::is_sign_count_rollback as fn(&WebAuthnError) -> bool,
        WebAuthnError::is_user_verification_failed as fn(&WebAuthnError) -> bool,
        WebAuthnError::is_internal as fn(&WebAuthnError) -> bool,
    );
}