yubikit 1.0.0-beta.0

YubiKey management library
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
// Copyright 2026 Yubico AB
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! WebAuthn client for performing registration and authentication ceremonies.

use crate::cbor;
use crate::core::Connection;
use crate::ctap2::types::AuthenticatorOptions;
use crate::ctap2::{
    ClientPin, Ctap2Error, Ctap2Pin, Ctap2Session, CtapStatus, Permissions, PinProtocol,
};

use super::extensions::{self, prf};
use super::types::{
    AuthenticationResponse, AuthenticatorAssertionResponse, AuthenticatorAttachment,
    AuthenticatorAttestationResponse, CollectedClientData, PublicKeyCredentialCreationOptions,
    PublicKeyCredentialDescriptor, PublicKeyCredentialRequestOptions, PublicKeyCredentialType,
    RegistrationResponse, ResidentKeyRequirement, UserVerificationRequirement,
};

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors that can occur during WebAuthn operations.
#[derive(Debug)]
pub enum ClientError<E: std::error::Error + Send + Sync + 'static> {
    /// A CTAP2-level error from the authenticator.
    Ctap(Ctap2Error<E>),
    /// User verification is required but not configured on the authenticator.
    ConfigurationUnsupported(String),
    /// The user's PIN is required but was not provided.
    PinRequired,
    /// A request parameter was invalid.
    BadRequest(String),
}

impl<E: std::error::Error + Send + Sync + 'static> From<Ctap2Error<E>> for ClientError<E> {
    fn from(e: Ctap2Error<E>) -> Self {
        Self::Ctap(e)
    }
}

impl<E: std::error::Error + Send + Sync + 'static> std::fmt::Display for ClientError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Ctap(e) => write!(f, "CTAP error: {e}"),
            Self::ConfigurationUnsupported(msg) => write!(f, "configuration unsupported: {msg}"),
            Self::PinRequired => write!(f, "PIN required"),
            Self::BadRequest(msg) => write!(f, "bad request: {msg}"),
        }
    }
}

impl<E: std::error::Error + Send + Sync + 'static> std::error::Error for ClientError<E> {}

// ---------------------------------------------------------------------------
// Traits
// ---------------------------------------------------------------------------

/// User interaction callbacks for PIN/UV prompts.
pub trait UserInteraction {
    /// Called when the authenticator is waiting for user presence (touch).
    fn prompt_up(&self);

    /// Called when a PIN is needed. Return the PIN, or `None` to cancel.
    fn request_pin(&self, permissions: Permissions, rp_id: Option<&str>) -> Option<Ctap2Pin>;

    /// Called when built-in user verification (e.g. biometrics) is available.
    /// Return `true` to proceed with UV, or `false` to fall back to PIN.
    fn request_uv(&self, permissions: Permissions, rp_id: Option<&str>) -> bool;
}

/// Collects client data and determines the effective RP ID for a ceremony.
pub trait ClientDataCollector {
    /// Collect client data for a registration or authentication request.
    ///
    /// Returns the [`CollectedClientData`] (containing the JSON-serialized
    /// client data) and the effective RP ID string.
    fn collect_create(
        &self,
        options: &PublicKeyCredentialCreationOptions,
    ) -> Result<(CollectedClientData, String), String>;

    /// Collect client data for an authentication request.
    fn collect_get(
        &self,
        options: &PublicKeyCredentialRequestOptions,
    ) -> Result<(CollectedClientData, String), String>;
}

/// Default [`ClientDataCollector`] with a fixed origin.
///
/// When `rp.id` is absent from the options, the effective RP ID is derived
/// from the origin's host (per the WebAuthn spec).
pub struct DefaultClientDataCollector {
    origin: String,
}

impl DefaultClientDataCollector {
    /// Create a new collector with the given origin (e.g. `"https://example.com"`).
    pub fn new(origin: impl Into<String>) -> Self {
        Self {
            origin: origin.into(),
        }
    }

    /// Derive the effective RP ID from the options, falling back to the
    /// origin's host when `rp.id` / `rp_id` is `None`.
    fn effective_rp_id_create(
        &self,
        options: &PublicKeyCredentialCreationOptions,
    ) -> Result<String, String> {
        if let Some(id) = &options.rp.id {
            return Ok(id.clone());
        }
        self.rp_id_from_origin()
    }

    fn effective_rp_id_get(
        &self,
        options: &PublicKeyCredentialRequestOptions,
    ) -> Result<String, String> {
        if let Some(id) = &options.rp_id {
            return Ok(id.clone());
        }
        self.rp_id_from_origin()
    }

    fn rp_id_from_origin(&self) -> Result<String, String> {
        // Parse "https://host[:port][/...]" without pulling in the url crate.
        let rest = self
            .origin
            .strip_prefix("https://")
            .ok_or("RP ID required for non-https origin")?;
        let host = rest.split('/').next().unwrap_or(rest);
        // Strip port if present
        let host = if let Some(bracket_end) = host.find(']') {
            // IPv6: [::1]:port
            &host[..bracket_end + 1]
        } else {
            host.split(':').next().unwrap_or(host)
        };
        if host.is_empty() {
            return Err("Origin has no host".to_string());
        }
        Ok(host.to_string())
    }
}

impl ClientDataCollector for DefaultClientDataCollector {
    fn collect_create(
        &self,
        options: &PublicKeyCredentialCreationOptions,
    ) -> Result<(CollectedClientData, String), String> {
        let rp_id = self.effective_rp_id_create(options)?;
        let client_data =
            CollectedClientData::create("webauthn.create", &options.challenge, &self.origin, false);
        Ok((client_data, rp_id))
    }

    fn collect_get(
        &self,
        options: &PublicKeyCredentialRequestOptions,
    ) -> Result<(CollectedClientData, String), String> {
        let rp_id = self.effective_rp_id_get(options)?;
        let client_data =
            CollectedClientData::create("webauthn.get", &options.challenge, &self.origin, false);
        Ok((client_data, rp_id))
    }
}

// ---------------------------------------------------------------------------
// WebAuthn client
// ---------------------------------------------------------------------------

/// WebAuthn client that wraps a [`Ctap2Session`](crate::ctap2::Ctap2Session) and performs registration
/// and authentication ceremonies.
pub struct WebAuthnClient<C: Connection + 'static, U: UserInteraction, D: ClientDataCollector> {
    session: Option<Ctap2Session<C>>,
    user_interaction: U,
    client_data_collector: D,
    extensions: Vec<Box<dyn extensions::Ctap2Extension>>,
}

impl<C: Connection + 'static, U: UserInteraction, D: ClientDataCollector> WebAuthnClient<C, U, D> {
    /// Create a new WebAuthn client with the default set of extensions.
    pub fn new(session: Ctap2Session<C>, user_interaction: U, client_data_collector: D) -> Self {
        Self {
            session: Some(session),
            user_interaction,
            client_data_collector,
            extensions: extensions::default_extensions(),
        }
    }

    /// Create a new WebAuthn client with a custom set of extensions.
    pub fn with_extensions(
        session: Ctap2Session<C>,
        user_interaction: U,
        client_data_collector: D,
        extensions: Vec<Box<dyn extensions::Ctap2Extension>>,
    ) -> Self {
        Self {
            session: Some(session),
            user_interaction,
            client_data_collector,
            extensions,
        }
    }

    /// Consume the client and return the underlying session.
    pub fn into_session(self) -> Ctap2Session<C> {
        self.session.expect("session already taken")
    }

    /// Access the session's cached (initial) authenticator info.
    ///
    /// Use for static capabilities (extensions, max sizes, protocols).
    /// For mutable state (clientPin, uv) use `get_info()` on the session.
    fn cached_info(&self) -> &crate::ctap2::Info {
        &self
            .session
            .as_ref()
            .expect("session already taken")
            .cached_info
    }

    /// Temporarily take the session, run `f`, and restore it afterward.
    fn with_session<R>(&mut self, f: impl FnOnce(&mut Ctap2Session<C>) -> R) -> R {
        let mut session = self.session.take().expect("session already taken");
        let result = f(&mut session);
        self.session = Some(session);
        result
    }

    /// Temporarily wrap the session in a [`ClientPin`] with the given protocol,
    /// run `f`, and restore the session afterward.
    fn with_client_pin<R>(
        &mut self,
        protocol: PinProtocol,
        f: impl FnOnce(&mut ClientPin<C>) -> R,
    ) -> R {
        let session = self.session.take().expect("session already taken");
        let mut client_pin = ClientPin::new_with_protocol(session, protocol);
        let result = f(&mut client_pin);
        self.session = Some(client_pin.into_session());
        result
    }

    // -----------------------------------------------------------------------
    // Registration (makeCredential)
    // -----------------------------------------------------------------------

    /// Perform a WebAuthn registration ceremony.
    pub fn make_credential(
        &mut self,
        options: &PublicKeyCredentialCreationOptions,
        cancel: Option<&dyn Fn() -> bool>,
    ) -> Result<RegistrationResponse, ClientError<C::Error>> {
        let (client_data, rp_id) = self
            .client_data_collector
            .collect_create(options)
            .map_err(ClientError::BadRequest)?;
        let client_data_hash = client_data.hash();

        // Determine resident key and UV requirements
        let selection = options.authenticator_selection.as_ref();
        let mut uv_requirement = selection
            .and_then(|s| s.user_verification)
            .unwrap_or_default();
        let rk_requirement = selection.and_then(|s| s.resident_key).unwrap_or_default();

        let rk = matches!(
            rk_requirement,
            ResidentKeyRequirement::Required | ResidentKeyRequirement::Preferred
        );

        log::debug!("makeCredential: rp_id={rp_id}, rk={rk}, uv={uv_requirement:?}");

        // Convert WebAuthn RP to CTAP2 (different field requirements)
        let ctap2_rp = options.rp.to_ctap2(&rp_id);

        let enterprise_attestation = match options.attestation {
            Some(super::types::AttestationConveyancePreference::Enterprise) => Some(1u32),
            _ => None,
        };

        let hmac_state_out;
        let mut processors;
        let att_resp = loop {
            // Initialize extension processors (inside loop — may change with UV retry)
            processors = self.init_registration_processors(options)?;

            // Need GET_ASSERTION permission if we have an exclude list to filter
            let mut permissions = Permissions::MAKE_CREDENTIAL;
            if options.exclude_credentials.is_some() {
                permissions |= Permissions::GET_ASSERTION;
            }
            // Add permissions from extensions
            for proc in &processors {
                permissions |= proc.permissions();
            }

            // Get PIN/UV token
            let (token, protocol, internal_uv) =
                self.get_token(uv_requirement, permissions, Some(&rp_id))?;

            // Pre-flight filtering of exclude list
            let exclude_cred = if let Some(ref exclude_list) = options.exclude_credentials {
                log::debug!(
                    "Filtering exclude list ({} credentials)",
                    exclude_list.len()
                );
                self.filter_creds(&rp_id, exclude_list, protocol, token.as_deref())?
            } else {
                None
            };

            // Compute pin_uv_param for the actual request
            let (pin_uv_param, pin_uv_protocol) =
                compute_pin_uv_param(token.as_deref(), protocol, &client_data_hash);

            let authenticator_options = AuthenticatorOptions {
                rk: Some(rk),
                uv: if internal_uv { Some(true) } else { None },
                up: None,
            };

            // Build the filtered exclude list (single matching cred, or None)
            let filtered_exclude: Option<Vec<PublicKeyCredentialDescriptor>>;
            let exclude_slice = if let Some(cred) = exclude_cred {
                filtered_exclude = Some(vec![cred]);
                filtered_exclude.as_deref()
            } else {
                None
            };

            // Build extension inputs (must be inside loop — ECDH key agreement
            // for hmac-secret is tied to the PIN protocol session)
            let (ext_cbor, hmac_state) =
                self.build_registration_extensions(&processors, protocol)?;

            let mut session = self.session.take().expect("session already taken");
            let interaction = &self.user_interaction;
            let mut on_keepalive = |status: u8| {
                if status == 0x02 {
                    interaction.prompt_up();
                }
            };
            let result = session.make_credential(
                &client_data_hash,
                &ctap2_rp,
                &options.user,
                &options.pub_key_cred_params,
                exclude_slice,
                ext_cbor,
                Some(&authenticator_options),
                pin_uv_param.as_deref(),
                pin_uv_protocol,
                enterprise_attestation,
                Some(&mut on_keepalive),
                cancel,
            );
            self.session = Some(session);
            match result {
                Ok(resp) => {
                    hmac_state_out = hmac_state;
                    break resp;
                }
                Err(e) => {
                    // Authenticator requires UV — retry with Required
                    if is_puat_required(&e)
                        && uv_requirement != UserVerificationRequirement::Required
                    {
                        log::debug!("Got PuatRequired, retrying with uv=required");
                        uv_requirement = UserVerificationRequirement::Required;
                        continue;
                    }
                    return Err(e.into());
                }
            }
        };

        log::info!("Credential created (fmt={})", att_resp.fmt);

        // Build the attestation object CBOR (fmt, authData, attStmt)
        let att_obj_cbor = cbor::encode(&cbor::Value::Map(vec![
            (
                cbor::Value::Text("fmt".into()),
                cbor::Value::Text(att_resp.fmt),
            ),
            (
                cbor::Value::Text("authData".into()),
                cbor::Value::Bytes(att_resp.auth_data.clone()),
            ),
            (cbor::Value::Text("attStmt".into()), att_resp.att_stmt),
        ]));

        // Extract credential ID from auth_data
        let credential_id = extract_credential_id(&att_resp.auth_data)
            .ok_or_else(|| ClientError::BadRequest("no credential data in auth_data".into()))?;

        // Parse extension outputs
        let ext_outputs = self.parse_registration_extensions(
            &processors,
            &att_resp.auth_data,
            hmac_state_out.as_ref(),
            att_resp.large_blob_key.is_some(),
            rk,
            att_resp.unsigned_extension_outputs.as_ref(),
        );

        Ok(RegistrationResponse {
            id: credential_id,
            response: AuthenticatorAttestationResponse {
                client_data_json: client_data.as_bytes().to_vec(),
                attestation_object: att_obj_cbor,
            },
            authenticator_attachment: Some(AuthenticatorAttachment::CrossPlatform),
            type_: PublicKeyCredentialType::PublicKey,
            client_extension_results: ext_outputs,
        })
    }

    // -----------------------------------------------------------------------
    // Authentication (getAssertion)
    // -----------------------------------------------------------------------

    /// Perform a WebAuthn authentication ceremony.
    ///
    /// Returns a list of authentication responses (one per matching credential;
    /// typically one unless the authenticator has multiple discoverable
    /// credentials for the RP).
    pub fn get_assertion(
        &mut self,
        options: &PublicKeyCredentialRequestOptions,
        cancel: Option<&dyn Fn() -> bool>,
    ) -> Result<Vec<AuthenticationResponse>, ClientError<C::Error>> {
        let (client_data, rp_id) = self
            .client_data_collector
            .collect_get(options)
            .map_err(ClientError::BadRequest)?;
        let client_data_hash = client_data.hash();

        let mut uv_requirement = options.user_verification.unwrap_or_default();
        let allow_count = options
            .allow_credentials
            .as_ref()
            .map(|c| c.len())
            .unwrap_or(0);
        log::debug!("getAssertion: rp_id={rp_id}, uv={uv_requirement:?}, allow_list={allow_count}");

        // These are populated inside the retry loop and used after
        let first;
        let mut token;
        let mut protocol;
        let hmac_state_out;
        let mut processors;

        loop {
            // Initialize extension processors
            processors = self.init_authentication_processors(options)?;

            let mut permissions = Permissions::GET_ASSERTION;
            // Add permissions from extensions
            for proc in &processors {
                permissions |= proc.permissions();
            }

            let (tok, proto, internal_uv) =
                self.get_token(uv_requirement, permissions, Some(&rp_id))?;
            token = tok;
            protocol = proto;

            // Pre-flight filtering of allow list
            let selected_cred_id: Option<Vec<u8>>;
            let filtered_allow: Option<Vec<PublicKeyCredentialDescriptor>>;
            let allow_slice = if let Some(ref allow_list) = options.allow_credentials {
                log::debug!("Filtering allow list ({} credentials)", allow_list.len());
                let selected = self.filter_creds(&rp_id, allow_list, protocol, token.as_deref())?;
                if let Some(cred) = selected {
                    selected_cred_id = Some(cred.id.clone());
                    filtered_allow = Some(vec![cred]);
                    filtered_allow.as_deref()
                } else if !allow_list.is_empty() {
                    selected_cred_id = None;
                    filtered_allow = Some(vec![PublicKeyCredentialDescriptor {
                        type_: allow_list[0].type_,
                        id: vec![0],
                        transports: None,
                    }]);
                    filtered_allow.as_deref()
                } else {
                    selected_cred_id = None;
                    None
                }
            } else {
                selected_cred_id = None;
                None
            };

            // Compute pin_uv_param for the actual request
            let (pin_uv_param, pin_uv_protocol) =
                compute_pin_uv_param(token.as_deref(), protocol, &client_data_hash);

            let authenticator_options = AuthenticatorOptions {
                rk: None,
                uv: if internal_uv { Some(true) } else { None },
                up: None,
            };

            // Build extension inputs (must be inside loop — ECDH key agreement
            // for hmac-secret is tied to the PIN protocol session)
            let (ext_cbor, hmac_state) = self.build_authentication_extensions(
                &processors,
                protocol,
                selected_cred_id.as_deref(),
            )?;

            let mut session = self.session.take().expect("session already taken");
            let interaction = &self.user_interaction;
            let mut on_keepalive = |status: u8| {
                if status == 0x02 {
                    interaction.prompt_up();
                }
            };

            match session.get_assertion(
                &rp_id,
                &client_data_hash,
                allow_slice,
                ext_cbor,
                Some(&authenticator_options),
                pin_uv_param.as_deref(),
                pin_uv_protocol,
                Some(&mut on_keepalive),
                cancel,
            ) {
                Ok(resp) => {
                    self.session = Some(session);
                    hmac_state_out = hmac_state;
                    first = resp;
                    break;
                }
                Err(e) => {
                    self.session = Some(session);
                    // Authenticator requires UV — retry with Required
                    if is_puat_required(&e)
                        && uv_requirement != UserVerificationRequirement::Required
                    {
                        log::debug!("Got PuatRequired, retrying with uv=required");
                        uv_requirement = UserVerificationRequirement::Required;
                        continue;
                    }
                    return Err(e.into());
                }
            }
        }

        let total = first.number_of_credentials.unwrap_or(1) as usize;
        log::info!("Got {total} assertion(s) for rp_id={rp_id}");
        let client_data_json = client_data.as_bytes().to_vec();

        // Parse extension outputs for the first assertion
        let first_cred_id = first
            .credential
            .as_ref()
            .map(|c| c.id.clone())
            .unwrap_or_default();

        let ext_outputs = self.parse_authentication_extensions(
            &processors,
            &first.auth_data,
            hmac_state_out.as_ref(),
        );

        // Handle large blob read/write if requested
        let large_blob_output = if let Some(ref ext) = options.extensions {
            if let Some(ref lb_input) = ext.large_blob {
                let session = self.session.take().expect("session already taken");
                let (s, output) = self.process_large_blob(
                    session,
                    lb_input,
                    first.large_blob_key.as_deref(),
                    token.as_deref(),
                    protocol,
                );
                self.session = Some(s);
                output
            } else {
                None
            }
        } else {
            None
        };

        let mut ext_outputs = ext_outputs;
        if let Some(lb_out) = large_blob_output {
            let outputs = ext_outputs.get_or_insert_with(Default::default);
            outputs.large_blob = Some(lb_out);
        }

        let mut responses = Vec::with_capacity(total);
        responses.push(AuthenticationResponse {
            id: first_cred_id,
            response: AuthenticatorAssertionResponse {
                client_data_json: client_data_json.clone(),
                authenticator_data: first.auth_data,
                signature: first.signature,
                user_handle: first.user.map(|u| u.id),
            },
            authenticator_attachment: Some(AuthenticatorAttachment::CrossPlatform),
            type_: PublicKeyCredentialType::PublicKey,
            client_extension_results: ext_outputs,
        });

        // Additional assertions (getNextAssertion)
        for _ in 1..total {
            let next = self.with_session(|session| session.get_next_assertion())?;
            let credential_id = next
                .credential
                .as_ref()
                .map(|c| c.id.clone())
                .unwrap_or_default();

            let next_ext_outputs = self.parse_authentication_extensions(
                &processors,
                &next.auth_data,
                hmac_state_out.as_ref(),
            );

            responses.push(AuthenticationResponse {
                id: credential_id,
                response: AuthenticatorAssertionResponse {
                    client_data_json: client_data_json.clone(),
                    authenticator_data: next.auth_data,
                    signature: next.signature,
                    user_handle: next.user.map(|u| u.id),
                },
                authenticator_attachment: Some(AuthenticatorAttachment::CrossPlatform),
                type_: PublicKeyCredentialType::PublicKey,
                client_extension_results: next_ext_outputs,
            });
        }

        Ok(responses)
    }

    // -----------------------------------------------------------------------
    // Extension processing
    // -----------------------------------------------------------------------

    /// Initialize extension processors for makeCredential.
    fn init_registration_processors(
        &self,
        options: &PublicKeyCredentialCreationOptions,
    ) -> Result<Vec<Box<dyn extensions::RegistrationProcessor>>, ClientError<C::Error>> {
        let info = self.cached_info();
        let mut processors: Vec<Box<dyn extensions::RegistrationProcessor>> = Vec::new();
        for ext in &self.extensions {
            match ext.make_credential(info, options) {
                Ok(Some(p)) => processors.push(p),
                Ok(None) => {}
                Err(e) => return Err(ClientError::ConfigurationUnsupported(e)),
            }
        }
        Ok(processors)
    }

    /// Initialize extension processors for getAssertion.
    fn init_authentication_processors(
        &self,
        options: &PublicKeyCredentialRequestOptions,
    ) -> Result<Vec<Box<dyn extensions::AuthenticationProcessor>>, ClientError<C::Error>> {
        let info = self.cached_info();
        let mut processors: Vec<Box<dyn extensions::AuthenticationProcessor>> = Vec::new();
        for ext in &self.extensions {
            match ext.get_assertion(info, options) {
                Ok(Some(p)) => processors.push(p),
                Ok(None) => {}
                Err(e) => return Err(ClientError::ConfigurationUnsupported(e)),
            }
        }
        Ok(processors)
    }

    /// Build CTAP2 extension CBOR from registration processors.
    fn build_registration_extensions(
        &mut self,
        processors: &[Box<dyn extensions::RegistrationProcessor>],
        protocol: Option<PinProtocol>,
    ) -> Result<(Option<cbor::Value>, Option<prf::HmacSecretState>), ClientError<C::Error>> {
        let mut ctx = extensions::ExtensionContext::new(protocol);

        // Obtain hmac-secret shared secret if needed (any PRF processor will use it)
        if let Some(state) = self.get_hmac_secret_state(protocol)? {
            ctx.hmac_secret_state = Some(state);
        }

        let mut entries: Vec<(String, cbor::Value)> = Vec::new();
        for proc in processors {
            match proc.prepare_inputs(&mut ctx) {
                Ok(inputs) => entries.extend(inputs),
                Err(e) => return Err(ClientError::ConfigurationUnsupported(e)),
            }
        }

        let hmac_state = ctx.hmac_secret_state;
        let inputs = extensions::build_extensions_cbor(entries)
            .map_err(ClientError::ConfigurationUnsupported)?;
        Ok((inputs, hmac_state))
    }

    /// Build CTAP2 extension CBOR from authentication processors.
    fn build_authentication_extensions(
        &mut self,
        processors: &[Box<dyn extensions::AuthenticationProcessor>],
        protocol: Option<PinProtocol>,
        selected_cred_id: Option<&[u8]>,
    ) -> Result<(Option<cbor::Value>, Option<prf::HmacSecretState>), ClientError<C::Error>> {
        let mut ctx = extensions::ExtensionContext::new(protocol);

        // Obtain hmac-secret shared secret if needed
        if let Some(state) = self.get_hmac_secret_state(protocol)? {
            ctx.hmac_secret_state = Some(state);
        }

        let mut entries: Vec<(String, cbor::Value)> = Vec::new();
        for proc in processors {
            match proc.prepare_inputs(selected_cred_id, &mut ctx) {
                Ok(inputs) => entries.extend(inputs),
                Err(e) => return Err(ClientError::ConfigurationUnsupported(e)),
            }
        }

        let hmac_state = ctx.hmac_secret_state;
        let inputs = extensions::build_extensions_cbor(entries)
            .map_err(ClientError::ConfigurationUnsupported)?;
        Ok((inputs, hmac_state))
    }

    /// Parse extension outputs from a makeCredential response.
    fn parse_registration_extensions(
        &self,
        processors: &[Box<dyn extensions::RegistrationProcessor>],
        auth_data: &[u8],
        hmac_state: Option<&prf::HmacSecretState>,
        has_large_blob_key: bool,
        rk: bool,
        unsigned_ext_outputs: Option<&cbor::Value>,
    ) -> Option<extensions::RegistrationExtensionOutputs> {
        let auth_exts = extensions::parse_auth_data_extensions(auth_data);
        let auth_exts_ref = auth_exts.as_deref();

        let ctx = extensions::OutputContext {
            rk,
            auth_data_extensions: auth_exts_ref,
            unsigned_extension_outputs: unsigned_ext_outputs,
            has_large_blob_key,
            hmac_secret_state: hmac_state,
        };

        let mut outputs = extensions::RegistrationExtensionOutputs::default();
        for proc in processors {
            proc.prepare_outputs(&ctx, &mut outputs);
        }

        // Check if any field was populated
        let has_output = outputs.prf.is_some()
            || outputs.cred_protect.is_some()
            || outputs.cred_blob.is_some()
            || outputs.large_blob.is_some()
            || outputs.cred_props.is_some()
            || outputs.min_pin_length.is_some()
            || outputs.preview_sign.is_some();

        if has_output { Some(outputs) } else { None }
    }

    /// Parse extension outputs from a getAssertion response.
    fn parse_authentication_extensions(
        &self,
        processors: &[Box<dyn extensions::AuthenticationProcessor>],
        auth_data: &[u8],
        hmac_state: Option<&prf::HmacSecretState>,
    ) -> Option<extensions::AuthenticationExtensionOutputs> {
        let auth_exts = extensions::parse_auth_data_extensions(auth_data);
        let auth_exts_ref = auth_exts.as_deref();

        let ctx = extensions::OutputContext {
            rk: false,
            auth_data_extensions: auth_exts_ref,
            unsigned_extension_outputs: None,
            has_large_blob_key: false,
            hmac_secret_state: hmac_state,
        };

        let mut outputs = extensions::AuthenticationExtensionOutputs::default();
        for proc in processors {
            proc.prepare_outputs(&ctx, &mut outputs);
        }

        // Check if any field was populated
        let has_output = outputs.prf.is_some()
            || outputs.cred_blob.is_some()
            || outputs.large_blob.is_some()
            || outputs.preview_sign.is_some();

        if has_output { Some(outputs) } else { None }
    }

    /// Perform ECDH key agreement for hmac-secret.
    fn get_hmac_secret_state(
        &mut self,
        protocol: Option<PinProtocol>,
    ) -> Result<Option<prf::HmacSecretState>, ClientError<C::Error>> {
        let proto = match protocol {
            Some(p) => p,
            None => {
                let info = self.cached_info();
                if info.pin_uv_protocols.contains(&2) {
                    PinProtocol::V2
                } else if info.pin_uv_protocols.contains(&1) {
                    PinProtocol::V1
                } else {
                    return Ok(None);
                }
            }
        };

        // Get authenticator's key agreement key via ClientPin
        let (peer_key, shared_secret) = self.with_client_pin(proto, |cp| cp.get_shared_secret())?;

        Ok(Some(prf::HmacSecretState::new(
            proto,
            peer_key,
            shared_secret,
        )))
    }

    /// Process large blob read/write after authentication.
    /// Takes ownership of the session and returns it.
    fn process_large_blob(
        &self,
        session: Ctap2Session<C>,
        input: &extensions::large_blob::AuthenticationInput,
        large_blob_key: Option<&[u8]>,
        token: Option<&[u8]>,
        protocol: Option<PinProtocol>,
    ) -> (
        Ctap2Session<C>,
        Option<extensions::large_blob::AuthenticationOutput>,
    ) {
        use crate::ctap2::LargeBlobs;

        let Some(key) = large_blob_key else {
            return (session, None);
        };

        // For reads we don't need a PIN token, but LargeBlobs::new requires
        // a protocol.  Use V2 as a default for read-only operations — the
        // protocol/token are only exercised on writes.
        let proto = protocol.unwrap_or(PinProtocol::V2);
        let token_bytes = token.unwrap_or(&[]);

        let mut large_blobs = match LargeBlobs::new(session, proto, token_bytes.to_vec()) {
            Ok(lb) => lb,
            Err(_) => {
                unreachable!("LargeBlobs::new failed after support check");
            }
        };

        let output = if input.read == Some(true) {
            // Read does not use the PIN token at all
            match large_blobs.get_blob(key) {
                Ok(blob) => Some(extensions::large_blob::AuthenticationOutput {
                    blob,
                    written: None,
                }),
                Err(_) => Some(extensions::large_blob::AuthenticationOutput {
                    blob: None,
                    written: None,
                }),
            }
        } else if let Some(ref data) = input.write {
            match large_blobs.put_blob(key, data) {
                Ok(()) => Some(extensions::large_blob::AuthenticationOutput {
                    blob: None,
                    written: Some(true),
                }),
                Err(_) => Some(extensions::large_blob::AuthenticationOutput {
                    blob: None,
                    written: Some(false),
                }),
            }
        } else {
            None
        };

        (large_blobs.into_session(), output)
    }

    // -----------------------------------------------------------------------
    // Pre-flight credential filtering
    // -----------------------------------------------------------------------

    /// Filter a credential list against the authenticator using silent
    /// `getAssertion` calls (UP=false).
    ///
    /// Returns the first matching credential, or `None` if no matches.
    /// Credentials whose ID exceeds the authenticator's `max_cred_id_length`
    /// are silently skipped.
    fn filter_creds(
        &mut self,
        rp_id: &str,
        cred_list: &[PublicKeyCredentialDescriptor],
        protocol: Option<PinProtocol>,
        token: Option<&[u8]>,
    ) -> Result<Option<PublicKeyCredentialDescriptor>, ClientError<C::Error>> {
        let info = self.cached_info();

        // Filter out credential IDs that are too long
        let filtered: Vec<&PublicKeyCredentialDescriptor> =
            if let Some(max_len) = info.max_cred_id_length {
                cred_list.iter().filter(|c| c.id.len() <= max_len).collect()
            } else {
                cred_list.iter().collect()
            };

        if filtered.is_empty() {
            return Ok(None);
        }

        // Compute pin_uv_param for the silent assertion (dummy client_data_hash)
        let dummy_hash = [0u8; 32];
        let (pin_uv_param, pin_uv_protocol) = compute_pin_uv_param(token, protocol, &dummy_hash);

        let no_up = AuthenticatorOptions {
            rk: None,
            uv: None,
            up: Some(false),
        };

        let mut max_creds = info.max_creds_in_list.unwrap_or(1);
        let mut remaining: &[&PublicKeyCredentialDescriptor] = &filtered;

        while !remaining.is_empty() {
            let chunk_size = max_creds.min(remaining.len());
            let chunk: Vec<PublicKeyCredentialDescriptor> = remaining[..chunk_size]
                .iter()
                .map(|c| (*c).clone())
                .collect();

            let result = self.with_session(|session| {
                session.get_assertion(
                    rp_id,
                    &dummy_hash,
                    Some(&chunk),
                    None,
                    Some(&no_up),
                    pin_uv_param.as_deref(),
                    pin_uv_protocol,
                    None,
                    None,
                )
            });

            match result {
                Ok(resp) => {
                    log::debug!("Pre-flight filter: credential matched in chunk");
                    if chunk.len() == 1 {
                        // Credential ID may be omitted from single-cred responses
                        return Ok(Some(chunk.into_iter().next().unwrap()));
                    }
                    // Multiple creds in chunk — use the returned credential
                    if let Some(cred) = resp.credential {
                        return Ok(Some(cred));
                    }
                    return Ok(Some(chunk.into_iter().next().unwrap()));
                }
                Err(Ctap2Error::StatusError(CtapStatus::NoCredentials)) => {
                    // None in this chunk, try next
                    remaining = &remaining[chunk_size..];
                }
                Err(Ctap2Error::StatusError(CtapStatus::RequestTooLarge)) if max_creds > 1 => {
                    // Message too large, try smaller chunks
                    max_creds = (max_creds - 1).max(1);
                }
                Err(e) => return Err(e.into()),
            }
        }

        Ok(None)
    }

    // -----------------------------------------------------------------------
    // PIN / UV helpers
    // -----------------------------------------------------------------------

    /// Determine whether UV should be used, and if so, obtain a PIN/UV token.
    ///
    /// Returns `(token, protocol, internal_uv)`.
    fn get_token(
        &mut self,
        uv_requirement: UserVerificationRequirement,
        permissions: Permissions,
        rp_id: Option<&str>,
    ) -> Result<(Option<Vec<u8>>, Option<PinProtocol>, bool), ClientError<C::Error>> {
        if !self.should_use_uv(uv_requirement, permissions)? {
            log::debug!("UV not needed for uv={uv_requirement:?}");
            return Ok((None, None, false));
        }

        self.obtain_token(permissions, rp_id)
    }

    fn obtain_token(
        &mut self,
        permissions: Permissions,
        rp_id: Option<&str>,
    ) -> Result<(Option<Vec<u8>>, Option<PinProtocol>, bool), ClientError<C::Error>> {
        // Fetch current info — mutable state (clientPin, uv) may have changed
        let info = self.with_session(|session| session.get_info())?;

        // Select protocol
        let protocol = if info.pin_uv_protocols.contains(&2) {
            crate::ctap2::PinProtocol::V2
        } else if info.pin_uv_protocols.contains(&1) {
            crate::ctap2::PinProtocol::V1
        } else {
            return Err(ClientError::ConfigurationUnsupported(
                "no supported PIN/UV protocol".into(),
            ));
        };

        // Try UV first if supported
        if info.options.get("uv").copied().unwrap_or(false)
            && info.options.get("pinUvAuthToken").copied().unwrap_or(false)
        {
            if self.user_interaction.request_uv(permissions, rp_id) {
                log::debug!("Attempting UV token (protocol {protocol:?})");
                let result = self.with_client_pin(protocol, |cp| {
                    cp.get_uv_token(Some(permissions), rp_id, None, None)
                });
                match result {
                    Ok(token) => {
                        log::debug!("UV token obtained");
                        return Ok((Some(token), Some(protocol), false));
                    }
                    Err(e) => {
                        log::debug!("UV token failed: {e}, falling through to PIN");
                    }
                }
            }
        } else if info.options.get("uv").copied().unwrap_or(false) {
            // Device has internal UV but no pinUvAuthToken — use internal UV
            if self.user_interaction.request_uv(permissions, rp_id) {
                log::debug!("Using internal UV (no pinUvAuthToken)");
                return Ok((None, Some(protocol), true));
            }
        }

        // Fall back to PIN
        if info.options.get("clientPin").copied().unwrap_or(false) {
            if let Some(pin) = self.user_interaction.request_pin(permissions, rp_id) {
                log::debug!("Attempting PIN token (protocol {protocol:?})");
                let result = self.with_client_pin(protocol, |cp| {
                    cp.get_pin_token(&pin, Some(permissions), rp_id)
                });
                match result {
                    Ok(token) => {
                        log::debug!("PIN token obtained");
                        return Ok((Some(token), Some(protocol), false));
                    }
                    Err(e) => return Err(ClientError::Ctap(e)),
                }
            } else {
                log::debug!("PIN required but not provided");
                return Err(ClientError::PinRequired);
            }
        }

        Err(ClientError::ConfigurationUnsupported(
            "user verification required but not configured/supported".into(),
        ))
    }

    /// Determine whether user verification should be performed.
    fn should_use_uv(
        &mut self,
        uv_requirement: UserVerificationRequirement,
        permissions: Permissions,
    ) -> Result<bool, ClientError<C::Error>> {
        // Fetch current info — mutable state (clientPin, uv) may have changed
        let info = self.with_session(|session| session.get_info())?;

        let uv_configured = info.options.get("uv").copied().unwrap_or(false)
            || info.options.get("clientPin").copied().unwrap_or(false)
            || info.options.get("bioEnroll").copied().unwrap_or(false);

        let uv_supported = info.options.contains_key("uv")
            || info.options.contains_key("clientPin")
            || info.options.contains_key("bioEnroll");

        match uv_requirement {
            UserVerificationRequirement::Required => Ok(true),
            UserVerificationRequirement::Preferred => Ok(uv_supported),
            UserVerificationRequirement::Discouraged => {
                // Even if discouraged, UV may still be needed:
                // - alwaysUv option
                // - makeCredential when makeCredUvNotRqd is not set
                if info.options.get("alwaysUv").copied().unwrap_or(false) && uv_configured {
                    return Ok(true);
                }

                let mc = permissions.bits() & Permissions::MAKE_CREDENTIAL.bits() != 0;
                let make_cred_uv_not_rqd = info
                    .options
                    .get("makeCredUvNotRqd")
                    .copied()
                    .unwrap_or(false);

                if mc && !make_cred_uv_not_rqd && uv_configured {
                    return Ok(true);
                }

                // Additional permissions beyond MC/GA always need UV
                let additional = permissions.bits()
                    & !(Permissions::MAKE_CREDENTIAL.bits() | Permissions::GET_ASSERTION.bits());
                if additional != 0 && uv_configured {
                    return Ok(true);
                }

                Ok(false)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Check whether a CTAP2 error is `PuatRequired`.
fn is_puat_required<E: std::error::Error + Send + Sync + 'static>(e: &Ctap2Error<E>) -> bool {
    matches!(e, Ctap2Error::StatusError(CtapStatus::PuatRequired))
}

/// Compute the `pin_uv_param` and protocol version from a token and protocol.
fn compute_pin_uv_param(
    token: Option<&[u8]>,
    protocol: Option<PinProtocol>,
    client_data_hash: &[u8],
) -> (Option<Vec<u8>>, Option<u32>) {
    match (token, protocol) {
        (Some(token), Some(protocol)) => {
            let param = protocol.authenticate(token, client_data_hash);
            (Some(param), Some(protocol.version()))
        }
        (None, Some(protocol)) => (None, Some(protocol.version())),
        _ => (None, None),
    }
}

/// Extract the credential ID from authenticator data containing attested
/// credential data.
///
/// Layout: rpIdHash(32) + flags(1) + counter(4) + aaguid(16) + credIdLen(2) + credId
fn extract_credential_id(auth_data: &[u8]) -> Option<Vec<u8>> {
    // Minimum: 32 + 1 + 4 + 16 + 2 = 55 bytes
    if auth_data.len() < 55 {
        return None;
    }

    let flags = auth_data[32];
    // AT flag (bit 6) must be set
    if flags & 0x40 == 0 {
        return None;
    }

    let cred_id_len = u16::from_be_bytes([auth_data[53], auth_data[54]]) as usize;
    let cred_id_start = 55;
    let cred_id_end = cred_id_start + cred_id_len;

    if auth_data.len() < cred_id_end {
        return None;
    }

    Some(auth_data[cred_id_start..cred_id_end].to_vec())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Version;
    use crate::ctap::CtapSession;
    use crate::fido::{CtapHidCapability, FidoConnection, FidoError};

    struct InfoOnlyConnection;

    impl Connection for InfoOnlyConnection {
        type Error = FidoError;

        fn close(&mut self) {}
    }

    impl FidoConnection for InfoOnlyConnection {
        fn call(
            &mut self,
            cmd: u8,
            data: &[u8],
            _on_keepalive: Option<&mut dyn FnMut(u8)>,
            _cancel: Option<&dyn Fn() -> bool>,
        ) -> Result<Vec<u8>, FidoError> {
            assert_eq!(cmd, 0x10);
            assert_eq!(data, &[0x04], "Unexpected authenticator command");
            let info = cbor::Value::Map(vec![(
                cbor::Value::Int(2),
                cbor::Value::Array(vec![cbor::Value::Text("credProtect".into())]),
            )]);
            let mut response = vec![0];
            response.extend_from_slice(&info.encode());
            Ok(response)
        }

        fn device_version(&self) -> Version {
            Version(5, 7, 2)
        }

        fn capabilities(&self) -> CtapHidCapability {
            CtapHidCapability::from_raw(CtapHidCapability::CBOR)
        }
    }

    struct NoInteraction;

    impl UserInteraction for NoInteraction {
        fn prompt_up(&self) {
            panic!("Unexpected touch request");
        }

        fn request_pin(&self, _: Permissions, _: Option<&str>) -> Option<Ctap2Pin> {
            panic!("Unexpected PIN request");
        }

        fn request_uv(&self, _: Permissions, _: Option<&str>) -> bool {
            panic!("Unexpected UV request");
        }
    }

    struct ExtraCredProtect;

    impl extensions::Ctap2Extension for ExtraCredProtect {
        fn make_credential(
            &self,
            _: &crate::ctap2::Info,
            _: &PublicKeyCredentialCreationOptions,
        ) -> Result<Option<Box<dyn extensions::RegistrationProcessor>>, String> {
            Ok(Some(Box::new(Self)))
        }

        fn get_assertion(
            &self,
            _: &crate::ctap2::Info,
            _: &PublicKeyCredentialRequestOptions,
        ) -> Result<Option<Box<dyn extensions::AuthenticationProcessor>>, String> {
            Ok(Some(Box::new(Self)))
        }
    }

    impl extensions::RegistrationProcessor for ExtraCredProtect {
        fn prepare_inputs(
            &self,
            _: &mut extensions::ExtensionContext,
        ) -> Result<Vec<(String, cbor::Value)>, String> {
            Ok(vec![("credProtect".into(), cbor::Value::Int(1))])
        }

        fn prepare_outputs(
            &self,
            _: &extensions::OutputContext<'_>,
            _: &mut extensions::RegistrationExtensionOutputs,
        ) {
        }
    }

    impl extensions::AuthenticationProcessor for ExtraCredProtect {
        fn prepare_inputs(
            &self,
            _: Option<&[u8]>,
            _: &mut extensions::ExtensionContext,
        ) -> Result<Vec<(String, cbor::Value)>, String> {
            Ok(vec![("credProtect".into(), cbor::Value::Int(1))])
        }

        fn prepare_outputs(
            &self,
            _: &extensions::OutputContext<'_>,
            _: &mut extensions::AuthenticationExtensionOutputs,
        ) {
        }
    }

    #[test]
    fn test_extension_collisions_block_registration_and_authentication() {
        let session = CtapSession::new_fido(InfoOnlyConnection)
            .map_err(|(e, _)| e)
            .unwrap();
        let session = Ctap2Session::new(session).map_err(|(e, _)| e).unwrap();
        let mut client = WebAuthnClient::with_extensions(
            session,
            NoInteraction,
            DefaultClientDataCollector::new("https://example.com"),
            vec![
                Box::new(extensions::cred_protect::CredProtectExtension),
                Box::new(ExtraCredProtect),
            ],
        );
        let options = PublicKeyCredentialCreationOptions::from_json(
            r#"{
                "rp": {"id": "example.com", "name": "Example"},
                "user": {"id": "AQ", "name": "user", "displayName": "User"},
                "challenge": "AQ",
                "pubKeyCredParams": [{"type": "public-key", "alg": -7}],
                "authenticatorSelection": {"userVerification": "discouraged"},
                "extensions": {
                    "credentialProtectionPolicy": "userVerificationRequired",
                    "enforceCredentialProtectionPolicy": true
                }
            }"#,
        )
        .unwrap();
        assert!(matches!(
            client.make_credential(&options, None),
            Err(ClientError::ConfigurationUnsupported(message))
                if message == "Duplicate extension input: credProtect"
        ));

        client.extensions = vec![Box::new(ExtraCredProtect), Box::new(ExtraCredProtect)];
        let options = PublicKeyCredentialRequestOptions::from_json(
            r#"{"challenge": "AQ", "rpId": "example.com", "userVerification": "discouraged"}"#,
        )
        .unwrap();
        assert!(matches!(
            client.get_assertion(&options, None),
            Err(ClientError::ConfigurationUnsupported(message))
                if message == "Duplicate extension input: credProtect"
        ));
        client.with_session(|session| session.get_info()).unwrap();
    }

    #[test]
    fn test_extract_credential_id() {
        // Build a minimal auth_data with AT flag and credential data
        let mut auth_data = vec![0u8; 55 + 4]; // 55 header + 4 byte cred ID
        auth_data[32] = 0x41; // UP + AT flags
        // counter at [33..37] = 0
        // aaguid at [37..53] = 0
        auth_data[53] = 0x00; // credIdLen high byte
        auth_data[54] = 0x04; // credIdLen low byte = 4
        auth_data[55] = 0xAA;
        auth_data[56] = 0xBB;
        auth_data[57] = 0xCC;
        auth_data[58] = 0xDD;

        let id = extract_credential_id(&auth_data).unwrap();
        assert_eq!(id, vec![0xAA, 0xBB, 0xCC, 0xDD]);
    }

    #[test]
    fn test_extract_credential_id_no_at_flag() {
        let mut auth_data = vec![0u8; 59];
        auth_data[32] = 0x01; // UP only, no AT
        assert!(extract_credential_id(&auth_data).is_none());
    }

    #[test]
    fn test_extract_credential_id_too_short() {
        let auth_data = vec![0u8; 40];
        assert!(extract_credential_id(&auth_data).is_none());
    }
}