utopia-auth 0.1.1

The password hash algorithms of utopia-php/auth: PECL scrypt, Firebase's modified scrypt and phpass.
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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Passkey registration and sign-in ceremonies, driven by a software
//! authenticator.
//!
//! PHP: `tests/Passkeys/CeremonyTest.php`, `tests/Passkeys/OriginTest.php`.

#![cfg(feature = "service")]

use p256::ecdsa::SigningKey;
use p256::ecdsa::signature::Signer as _;
use php_std::json::{self, Flags};
use php_std::{Array, Value};
use serde_json::{Value as Json, json};
use sha2::{Digest, Sha256};
use utopia_auth::Error;
use utopia_auth::passkeys::{Ceremony, Credential, Origin, RelyingParty};

const ORIGIN: &str = "http://localhost:3000";

const FLAG_USER_PRESENT: u8 = 0x01;
const FLAG_USER_VERIFIED: u8 = 0x04;
const FLAG_BACKUP_ELIGIBLE: u8 = 0x08;
const FLAG_BACKED_UP: u8 = 0x10;
const FLAG_ATTESTED: u8 = 0x40;

// ---------------------------------------------------------------------------
// The software authenticator (PHP: tests/Passkeys/Authenticator.php)
// ---------------------------------------------------------------------------

fn random_bytes(n: usize) -> Vec<u8> {
    let mut b = vec![0u8; n];
    getrandom::fill(&mut b).expect("random bytes");
    b
}

/// `Authenticator::encode()`: unpadded base64url.
fn encode(value: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut out = String::new();
    for chunk in value.chunks(3) {
        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        for i in 0..=chunk.len() {
            out.push(char::from(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize]));
        }
    }
    out
}

/// `Authenticator::decode()`.
fn decode(value: &str) -> Vec<u8> {
    let mut out = Vec::new();
    let (mut acc, mut bits) = (0u32, 0);
    for c in value.bytes() {
        let v = match c {
            b'A'..=b'Z' => c - b'A',
            b'a'..=b'z' => c - b'a' + 26,
            b'0'..=b'9' => c - b'0' + 52,
            b'-' | b'+' => 62,
            b'_' | b'/' => 63,
            _ => continue,
        };
        acc = (acc << 6) | u32::from(v);
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((acc >> bits) as u8);
        }
    }
    out
}

/// A CBOR major type head with its argument.
fn cbor_head(major: u8, n: usize) -> Vec<u8> {
    let major = major << 5;
    match n {
        0..=23 => vec![major | n as u8],
        24..=0xff => vec![major | 24, n as u8],
        _ => {
            let mut h = vec![major | 25];
            h.extend_from_slice(&u16::try_from(n).expect("short CBOR item").to_be_bytes());
            h
        }
    }
}

fn cbor_bytes(b: &[u8]) -> Vec<u8> {
    [cbor_head(2, b.len()), b.to_vec()].concat()
}

fn cbor_text(t: &str) -> Vec<u8> {
    [cbor_head(3, t.len()), t.as_bytes().to_vec()].concat()
}

/// Reads a nested string from options, failing loudly when the shape is unexpected.
fn string<'a>(data: &'a Json, path: &[&str]) -> &'a str {
    let mut value = data;
    for key in path {
        value = value.get(key).unwrap_or_else(|| panic!("Missing \"{}\"", path.join(".")));
    }
    value.as_str().unwrap_or_else(|| panic!("\"{}\" is not a string", path.join(".")))
}

/// PHP array → JSON, as the browser sees the options.
fn to_json(options: &Array) -> Json {
    let encoded = json::encode(&Value::Array(options.clone()), Flags::THROW_ON_ERROR, json::DEFAULT_DEPTH).unwrap();
    serde_json::from_str(&encoded).unwrap()
}

/// JSON → PHP array, as the server decodes the browser's credential.
fn to_array(value: &Json) -> Array {
    match json::decode(value.to_string().as_bytes(), Some(true), json::DEFAULT_DEPTH, Flags::THROW_ON_ERROR).unwrap() {
        Value::Array(a) => a,
        other => panic!("not an array: {other:?}"),
    }
}

/// Merges `extra` over `options`, as PHP's `$extra + $options` does.
fn merge(extra: Json, options: &Json) -> Json {
    let mut merged = options.clone();
    for (key, value) in extra.as_object().unwrap() {
        merged[key] = value.clone();
    }
    merged
}

/// Software WebAuthn authenticator holding one ES256 passkey, used to drive
/// registration and sign-in ceremonies without a browser.
struct Authenticator {
    credential_id: Vec<u8>,
    user_handle: Vec<u8>,
    counter: i64,
    backup_eligible: bool,
    user_verified: bool,
    key: SigningKey,
}

impl Authenticator {
    fn new() -> Self {
        Self::with(true, true)
    }

    fn with(backup_eligible: bool, user_verified: bool) -> Self {
        let key = loop {
            if let Ok(key) = SigningKey::from_slice(&random_bytes(32)) {
                break key;
            }
        };
        Self { credential_id: random_bytes(16), user_handle: vec![], counter: 0, backup_eligible, user_verified, key }
    }

    /// The `PublicKeyCredential.toJSON()` of a registration for `options`.
    fn register(&mut self, options: &Json, origin: &str, rp_id: Option<&str>) -> Array {
        let rp_id = rp_id.unwrap_or_else(|| string(options, &["rp", "id"]));
        self.user_handle = decode(string(options, &["user", "id"]));

        let client_data = json!({
            "type": "webauthn.create",
            "challenge": string(options, &["challenge"]),
            "origin": origin,
            "crossOrigin": false,
        })
        .to_string();

        let point = self.key.verifying_key().to_sec1_point(false);
        let point = point.as_bytes();
        let (x, y) = (&point[1..33], &point[33..65]);
        // {1: 2, 3: -7, -1: 1, -2: x, -3: y}
        let public_key =
            [&[0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21][..], &cbor_bytes(x), &[0x22], &cbor_bytes(y)].concat();

        let mut authenticator_data = self.authenticator_data(rp_id, FLAG_ATTESTED);
        authenticator_data.extend_from_slice(&[0; 16]);
        authenticator_data.extend_from_slice(&u16::try_from(self.credential_id.len()).unwrap().to_be_bytes());
        authenticator_data.extend_from_slice(&self.credential_id);
        authenticator_data.extend_from_slice(&public_key);

        let attestation = [
            cbor_head(5, 3),
            cbor_text("fmt"),
            cbor_text("none"),
            cbor_text("attStmt"),
            cbor_head(5, 0),
            cbor_text("authData"),
            cbor_bytes(&authenticator_data),
        ]
        .concat();

        to_array(&json!({
            "id": encode(&self.credential_id),
            "rawId": encode(&self.credential_id),
            "type": "public-key",
            "response": {
                "clientDataJSON": encode(client_data.as_bytes()),
                "attestationObject": encode(&attestation),
                "transports": ["internal"],
            },
            "clientExtensionResults": {},
        }))
    }

    /// The `PublicKeyCredential.toJSON()` of a sign-in for `options`.
    fn authenticate(&mut self, options: &Json, origin: &str, rp_id: Option<&str>, cross_origin: bool) -> Array {
        let rp_id = rp_id.unwrap_or_else(|| string(options, &["rpId"]));
        self.counter += 1;

        let client_data = json!({
            "type": "webauthn.get",
            "challenge": string(options, &["challenge"]),
            "origin": origin,
            "crossOrigin": cross_origin,
        })
        .to_string();

        let authenticator_data = self.authenticator_data(rp_id, 0);
        let signed = [&authenticator_data[..], &Sha256::digest(client_data.as_bytes())].concat();
        let signature: p256::ecdsa::Signature = self.key.sign(&signed);

        to_array(&json!({
            "id": encode(&self.credential_id),
            "rawId": encode(&self.credential_id),
            "type": "public-key",
            "response": {
                "clientDataJSON": encode(client_data.as_bytes()),
                "authenticatorData": encode(&authenticator_data),
                "signature": encode(signature.to_der().as_bytes()),
                "userHandle": encode(&self.user_handle),
            },
            "clientExtensionResults": {},
        }))
    }

    fn authenticator_data(&self, rp_id: &str, mut flags: u8) -> Vec<u8> {
        flags |= FLAG_USER_PRESENT;
        if self.user_verified {
            flags |= FLAG_USER_VERIFIED;
        }
        if self.backup_eligible {
            flags |= FLAG_BACKUP_ELIGIBLE | FLAG_BACKED_UP;
        }
        // pack('N', $counter): the low 32 bits.
        [&Sha256::digest(rp_id.as_bytes())[..], &[flags], &(self.counter as u32).to_be_bytes()].concat()
    }
}

// ---------------------------------------------------------------------------
// Helpers (PHP: CeremonyTest's setUp, register() and signIn())
// ---------------------------------------------------------------------------

fn ceremony() -> Ceremony {
    Ceremony::new(RelyingParty::new("localhost", "Test", vec![ORIGIN.into()]))
}

fn register(ceremony: &Ceremony, authenticator: &mut Authenticator) -> Credential {
    let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
    let credential = authenticator.register(&to_json(&challenge.options), ORIGIN, None);
    ceremony.verify_registration(challenge.state.as_bytes(), &credential).unwrap()
}

fn try_sign_in(
    ceremony: &Ceremony,
    authenticator: &mut Authenticator,
    credential: &Credential,
) -> Result<Credential, Error> {
    let challenge = ceremony.authenticate().unwrap();
    let response = authenticator.authenticate(&to_json(&challenge.options), ORIGIN, None, false);
    ceremony.verify_authentication(challenge.state.as_bytes(), &response, &credential.record)
}

fn sign_in(ceremony: &Ceremony, authenticator: &mut Authenticator, credential: &Credential) -> Credential {
    try_sign_in(ceremony, authenticator, credential).unwrap()
}

/// `expectException(Exception::class)`: a `Utopia\Auth\Passkeys\Exception`.
#[track_caller]
fn assert_rejected<T: std::fmt::Debug>(result: Result<T, Error>) {
    match result {
        Err(Error::Passkey(_)) => {}
        other => panic!("expected a passkey error, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// CeremonyTest
// ---------------------------------------------------------------------------

#[test]
fn registration_options() {
    let options = to_json(&ceremony().register(b"user@example.com", b"User", &[]).unwrap().options);

    assert_eq!(string(&options, &["rp", "id"]), "localhost");
    assert_eq!(string(&options, &["user", "name"]), "user@example.com");
    assert_eq!(string(&options, &["authenticatorSelection", "residentKey"]), "required");
    assert_eq!(string(&options, &["authenticatorSelection", "userVerification"]), "required");
    assert_eq!(string(&options, &["attestation"]), "none");
}

#[test]
fn existing_passkeys_are_excluded_and_share_the_user_handle() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::new();
    let first = register(&ceremony, &mut authenticator);

    let options = to_json(&ceremony.register(b"user@example.com", b"User", &[first.record]).unwrap().options);

    assert_eq!(
        options["excludeCredentials"],
        json!([{"type": "public-key", "id": encode(&authenticator.credential_id), "transports": ["internal"]}])
    );
    assert_eq!(string(&options, &["user", "id"]), encode(&authenticator.user_handle));
}

#[test]
fn excluded_passkey_without_transports_sends_empty_transports() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::new();
    let mut record = register(&ceremony, &mut authenticator).record;
    record.set(php_std::ArrayKey::from_bytes(b"transports"), Value::Array(Array::new()));

    let options = to_json(&ceremony.register(b"user@example.com", b"User", &[record]).unwrap().options);

    assert_eq!(
        options["excludeCredentials"],
        json!([{"type": "public-key", "id": encode(&authenticator.credential_id), "transports": []}])
    );
}

#[test]
fn register_and_sign_in() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::new();
    let registered = register(&ceremony, &mut authenticator);

    let signed_in = sign_in(&ceremony, &mut authenticator, &registered);
    assert_eq!(registered.identifier, signed_in.identifier);
}

#[test]
fn identify_matches_the_registered_passkey() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::new();
    let registered = register(&ceremony, &mut authenticator);

    let challenge = ceremony.authenticate().unwrap();
    let response = authenticator.authenticate(&to_json(&challenge.options), ORIGIN, None, false);
    assert_eq!(registered.identifier, ceremony.identify(&response).unwrap());
}

#[test]
fn record_survives_storage() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::new();
    let registered = register(&ceremony, &mut authenticator);
    let stored = to_array(&to_json(&registered.record));

    let credential = Credential { identifier: registered.identifier.clone(), record: stored };
    assert_eq!(registered.identifier, sign_in(&ceremony, &mut authenticator, &credential).identifier);
}

#[test]
fn synced_passkey_allows_non_increasing_counter() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::with(true, true);
    let registered = register(&ceremony, &mut authenticator);
    let credential = sign_in(&ceremony, &mut authenticator, &registered);

    authenticator.counter = 0;
    assert_eq!(credential.identifier, sign_in(&ceremony, &mut authenticator, &credential).identifier);
}

#[test]
fn device_bound_passkey_rejects_non_increasing_counter() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::with(false, true);
    let registered = register(&ceremony, &mut authenticator);
    let credential = sign_in(&ceremony, &mut authenticator, &registered);

    authenticator.counter = 0;
    assert_rejected(try_sign_in(&ceremony, &mut authenticator, &credential));
}

#[test]
fn device_bound_passkey_without_counter_signs_in() {
    // Some authenticators never implement a counter and always report zero
    let ceremony = ceremony();
    let mut authenticator = Authenticator::with(false, true);
    let mut credential = register(&ceremony, &mut authenticator);

    for _ in 0..2 {
        authenticator.counter = -1;
        credential = sign_in(&ceremony, &mut authenticator, &credential);
        assert!(!credential.identifier.is_empty());
    }
}

#[test]
fn backup_eligibility_cannot_change() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::with(false, true);
    let credential = register(&ceremony, &mut authenticator);

    authenticator.backup_eligible = true;
    assert_rejected(try_sign_in(&ceremony, &mut authenticator, &credential));
}

/// `testRejectsInvalidRegistration` with one `invalidRegistrations` case.
fn rejects_invalid_registration(credential: impl FnOnce(&mut Authenticator, &Json) -> Array) {
    let ceremony = ceremony();
    let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();

    let credential = credential(&mut Authenticator::new(), &to_json(&challenge.options));
    assert_rejected(ceremony.verify_registration(challenge.state.as_bytes(), &credential));
}

#[test]
fn rejects_invalid_registration_wrong_origin() {
    rejects_invalid_registration(|a, o| a.register(o, "http://localhost:4000", None));
}

#[test]
fn rejects_invalid_registration_subdomain_origin() {
    rejects_invalid_registration(|a, o| a.register(o, "http://evil.localhost:3000", None));
}

#[test]
fn rejects_invalid_registration_wrong_rp_id() {
    rejects_invalid_registration(|a, o| a.register(o, ORIGIN, Some("example.com")));
}

#[test]
fn rejects_invalid_registration_other_challenge() {
    rejects_invalid_registration(|a, o| {
        a.register(&merge(json!({"challenge": encode(&random_bytes(32))}), o), ORIGIN, None)
    });
}

#[test]
fn rejects_invalid_registration_no_user_verification() {
    rejects_invalid_registration(|a, o| {
        a.user_verified = false;
        a.register(o, ORIGIN, None)
    });
}

#[test]
fn rejects_invalid_registration_malformed() {
    rejects_invalid_registration(|_, _| {
        to_array(&json!({"id": "abc", "type": "public-key", "response": {"clientDataJSON": "e30"}}))
    });
}

#[test]
fn rejects_invalid_registration_missing_response() {
    rejects_invalid_registration(|_, _| to_array(&json!({"id": "abc", "rawId": "abc", "type": "public-key"})));
}

#[test]
fn rejects_sign_in_credential_for_registration() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::new();
    register(&ceremony, &mut authenticator);
    let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();

    let options = merge(json!({"rpId": "localhost"}), &to_json(&challenge.options));
    let credential = authenticator.authenticate(&options, ORIGIN, None, false);
    assert_rejected(ceremony.verify_registration(challenge.state.as_bytes(), &credential));
}

/// `testRejectsInvalidSignIn` with one `invalidSignIns` case.
fn rejects_invalid_sign_in(origin: &str, rp_id: Option<&str>, cross_origin: bool) {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::new();
    let registered = register(&ceremony, &mut authenticator);
    let challenge = ceremony.authenticate().unwrap();

    let response = authenticator.authenticate(&to_json(&challenge.options), origin, rp_id, cross_origin);
    assert_rejected(ceremony.verify_authentication(challenge.state.as_bytes(), &response, &registered.record));
}

#[test]
fn rejects_invalid_sign_in_wrong_origin() {
    rejects_invalid_sign_in("http://localhost:4000", None, false);
}

#[test]
fn rejects_invalid_sign_in_wrong_rp_id() {
    rejects_invalid_sign_in(ORIGIN, Some("example.com"), false);
}

#[test]
fn rejects_invalid_sign_in_cross_origin_iframe() {
    rejects_invalid_sign_in(ORIGIN, None, true);
}

#[test]
fn rejects_signature_from_another_key() {
    let ceremony = ceremony();
    let mut authenticator = Authenticator::new();
    let registered = register(&ceremony, &mut authenticator);

    let mut impostor = Authenticator::new();
    impostor.credential_id = authenticator.credential_id.clone();
    impostor.user_handle = authenticator.user_handle.clone();
    impostor.counter = 10;

    assert_rejected(try_sign_in(&ceremony, &mut impostor, &registered));
}

#[test]
fn rejects_malformed_state() {
    assert_rejected(ceremony().verify_authentication(b"not json", &Array::new(), &Array::new()));
}

#[test]
fn rejects_malformed_credential_when_identifying() {
    assert_rejected(ceremony().identify(&to_array(&json!({"id": "abc"}))));
}

#[test]
fn portless_localhost_origin_allows_any_port() {
    let ceremony = Ceremony::new(RelyingParty::new("localhost", "Test", vec!["http://localhost".into()]));
    let mut authenticator = Authenticator::new();

    let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
    let credential = authenticator.register(&to_json(&challenge.options), "http://localhost:5173", None);
    let registered = ceremony.verify_registration(challenge.state.as_bytes(), &credential).unwrap();

    let challenge = ceremony.authenticate().unwrap();
    let response = authenticator.authenticate(&to_json(&challenge.options), "http://localhost:3000", None, false);
    let signed_in = ceremony.verify_authentication(challenge.state.as_bytes(), &response, &registered.record).unwrap();
    assert_eq!(registered.identifier, signed_in.identifier);

    let challenge = ceremony.authenticate().unwrap();
    let response = authenticator.authenticate(&to_json(&challenge.options), "https://localhost:3000", None, false);
    assert_rejected(ceremony.verify_authentication(challenge.state.as_bytes(), &response, &registered.record));
}

#[test]
fn portless_localhost_origin_rejects_a_path() {
    let ceremony = Ceremony::new(RelyingParty::new("localhost", "Test", vec!["http://localhost".into()]));
    let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();

    let credential = Authenticator::new().register(&to_json(&challenge.options), "http://localhost:5173/login", None);
    assert_rejected(ceremony.verify_registration(challenge.state.as_bytes(), &credential));
}

/// `testWildcardOriginAllowsSubdomains` with one `wildcardOrigins` case.
fn wildcard_origin(origin: &str, allowed: bool) {
    let ceremony = Ceremony::new(RelyingParty::new("example.com", "Test", vec!["https://*.example.com".into()]));
    let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
    let credential = Authenticator::new().register(&to_json(&challenge.options), origin, Some("example.com"));

    let result = ceremony.verify_registration(challenge.state.as_bytes(), &credential);
    if allowed {
        assert!(!result.unwrap().identifier.is_empty());
    } else {
        assert_rejected(result);
    }
}

#[test]
fn wildcard_origin_allows_subdomain() {
    wildcard_origin("https://app.example.com", true);
}

#[test]
fn wildcard_origin_allows_nested_subdomain() {
    wildcard_origin("https://eu.app.example.com", true);
}

#[test]
fn wildcard_origin_rejects_apex() {
    wildcard_origin("https://example.com", false);
}

#[test]
fn wildcard_origin_rejects_lookalike() {
    wildcard_origin("https://evilexample.com", false);
}

#[test]
fn wildcard_origin_rejects_http() {
    wildcard_origin("http://app.example.com", false);
}

#[test]
fn wildcard_origin_rejects_port() {
    wildcard_origin("https://app.example.com:8443", false);
}

#[test]
fn wildcard_origin_rejects_path() {
    wildcard_origin("https://app.example.com/login", false);
}

#[test]
fn portless_origin_allows_only_default_port_outside_localhost() {
    let ceremony = Ceremony::new(RelyingParty::new("example.com", "Test", vec!["https://example.com".into()]));
    let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();

    let credential =
        Authenticator::new().register(&to_json(&challenge.options), "https://example.com:8443", Some("example.com"));
    assert_rejected(ceremony.verify_registration(challenge.state.as_bytes(), &credential));
}

#[test]
fn android_app_origin_matches_exactly() {
    let app = "android:apk-key-hash:FG3pg8VzBlDY7rmVLzT8ZBagg0LmHb6oigSWsj_PROU";
    let ceremony =
        Ceremony::new(RelyingParty::new("example.com", "Test", vec!["https://example.com".into(), app.into()]));
    let mut authenticator = Authenticator::new();

    let challenge = ceremony.register(b"user@example.com", b"User", &[]).unwrap();
    let credential = authenticator.register(&to_json(&challenge.options), app, None);
    let registered = ceremony.verify_registration(challenge.state.as_bytes(), &credential).unwrap();

    let challenge = ceremony.authenticate().unwrap();
    let response = authenticator.authenticate(&to_json(&challenge.options), "https://example.com", None, false);
    let signed_in = ceremony.verify_authentication(challenge.state.as_bytes(), &response, &registered.record).unwrap();
    assert_eq!(registered.identifier, signed_in.identifier);

    let challenge = ceremony.authenticate().unwrap();
    let response = authenticator.authenticate(
        &to_json(&challenge.options),
        "android:apk-key-hash:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
        None,
        false,
    );
    assert_rejected(ceremony.verify_authentication(challenge.state.as_bytes(), &response, &registered.record));
}

#[test]
fn fingerprint_ignores_origin_order() {
    let a = RelyingParty::new("example.com", "A", vec!["https://a.example.com".into(), "https://example.com".into()]);
    let b = RelyingParty::new("example.com", "B", vec!["https://example.com".into(), "https://a.example.com".into()]);
    let c = RelyingParty::new("example.com", "A", vec!["https://example.com".into()]);

    assert_eq!(a.fingerprint(), b.fingerprint());
    assert_ne!(a.fingerprint(), c.fingerprint());
}

// ---------------------------------------------------------------------------
// OriginTest
// ---------------------------------------------------------------------------

#[test]
fn origin_normalize() {
    let origins: [(&str, &str, &str, Option<&str>); 17] = [
        ("rp id", "example.com", "https://example.com", Some("https://example.com")),
        ("trailing slash", "example.com", "https://example.com/", Some("https://example.com")),
        ("subdomain with default port", "example.com", "https://app.example.com:443", Some("https://app.example.com")),
        ("custom port", "example.com", "https://example.com:8443", Some("https://example.com:8443")),
        ("http", "example.com", "http://example.com", None),
        ("other domain", "example.com", "https://evil.com", None),
        ("suffix lookalike", "example.com", "https://notexample.com", None),
        ("path", "example.com", "https://example.com/login", None),
        ("credentials", "example.com", "https://user:pass@example.com", None),
        ("query", "example.com", "https://example.com?next=1", None),
        ("empty fragment", "example.com", "https://example.com#", None),
        ("uppercase", "example.com", "https://EXAMPLE.com", None),
        ("no scheme", "example.com", "example.com", None),
        ("localhost over http", "localhost", "http://localhost:3000", Some("http://localhost:3000")),
        ("localhost default port", "localhost", "http://localhost:80", Some("http://localhost")),
        ("localhost over https", "localhost", "https://localhost", Some("https://localhost")),
        ("loopback ip", "localhost", "http://127.0.0.1:3000", None),
    ];
    for (name, rp_id, origin, expected) in origins {
        assert_eq!(Origin::new(rp_id).normalize(origin.as_bytes()).as_deref(), expected, "{name}");
    }
}