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
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
//! [![github]](https://github.com/structured-world/structured-webauthn) [![crates-io]](https://crates.io/crates/structured-webauthn) [![docs-rs]](crate)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! `structured-webauthn` is a pure-Rust library for _server-side_
//! [Web Authentication (WebAuthn)](https://www.w3.org/TR/webauthn-3/#sctn-rp-operations) Relying Party
//! (RP) operations.
//!
//! The purpose of a server-side RP library is to be modular so that any client can be used with it as a backend
//! _including_ native applications—WebAuthn technically only covers web applications; however it's relatively easy
//! to adapt to native applications as well. It achieves this by not assuming how data is sent to/from the client;
//! having said that, there are pre-defined serialization formats for "common" deployments which can be used when
//! [`serde`](#serde) is enabled.
//!
//! It started from [`webauthn_rp`](https://git.philomathiclife.com/repos/webauthn_rp/) by Zack Newman;
//! see `NOTICE` for the origin and its license.
//!
//! ## `structured-webauthn` in action
//!
//! ```
//! use core::convert;
//! use structured_webauthn::{
//! AuthenticatedCredential64, DiscoverableAuthentication64, DiscoverableAuthenticationServerState,
//! DiscoverableCredentialRequestOptions, CredentialCreationOptions64, RegisteredCredential64,
//! Registration, RegistrationServerState64,
//! hash::hash_set::{InsertRemoveExpired, MaxLenHashSet},
//! request::{
//! PublicKeyCredentialDescriptor, RpId,
//! auth::AuthenticationVerificationOptions,
//! register::{
//! PublicKeyCredentialUserEntity64, RegistrationVerificationOptions,
//! UserHandle64,
//! },
//! },
//! response::{
//! CredentialId,
//! auth::error::AuthCeremonyErr,
//! register::{CompressedPubKeyOwned, DynamicState, error::RegCeremonyErr},
//! },
//! };
//! # #[cfg(feature = "serde")]
//! use serde::de::{Deserialize, Deserializer};
//! # #[cfg(feature = "serde_relaxed")]
//! use serde_json::Error as JsonErr;
//! /// The RP ID our application uses.
//! const RP_ID: &RpId = &RpId::from_static_domain("example.com").unwrap();
//! /// The registration verification options.
//! const REG_OPTS: &RegistrationVerificationOptions::<'static, 'static, &'static str, &'static str> = &RegistrationVerificationOptions::new();
//! /// The authentication verification options.
//! const AUTH_OPTS: &AuthenticationVerificationOptions::<'static, 'static, &'static str, &'static str> = &AuthenticationVerificationOptions::new();
//! /// Error we return in our application when a function fails.
//! enum AppErr {
//! /// WebAuthn registration ceremony failed.
//! RegCeremony(RegCeremonyErr),
//! /// WebAuthn authentication ceremony failed.
//! AuthCeremony(AuthCeremonyErr),
//! /// Unable to insert a WebAuthn ceremony.
//! WebAuthnCeremonyCreation,
//! /// WebAuthn ceremony does not exist; thus the ceremony could not be completed.
//! MissingWebAuthnCeremony,
//! /// General error related to JSON deserialization.
//! # #[cfg(feature = "serde_relaxed")]
//! Json(JsonErr),
//! /// No account exists associated with a particular `UserHandle64`.
//! NoAccount,
//! /// No credential exists associated with a particular `CredentialId`.
//! NoCredential,
//! /// `CredentialId` exists but the associated `UserHandle64` does not match.
//! CredentialUserIdMismatch,
//! }
//! # #[cfg(feature = "serde_relaxed")]
//! impl From<JsonErr> for AppErr {
//! fn from(value: JsonErr) -> Self {
//! Self::Json(value)
//! }
//! }
//! impl From<RegCeremonyErr> for AppErr {
//! fn from(value: RegCeremonyErr) -> Self {
//! Self::RegCeremony(value)
//! }
//! }
//! impl From<AuthCeremonyErr> for AppErr {
//! fn from(value: AuthCeremonyErr) -> Self {
//! Self::AuthCeremony(value)
//! }
//! }
//! /// First-time account creation.
//! ///
//! /// This gets sent from the user after an account is created on their side. The registration ceremony
//! /// still has to be successfully completed for the account to be created server side. In the event of an error,
//! /// the user should delete the created passkey since it won't be usable.
//! struct AccountReg {
//! registration: Registration,
//! user_name: String,
//! user_display_name: String,
//! }
//! # #[cfg(feature = "serde")]
//! impl<'de> Deserialize<'de> for AccountReg {
//! fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
//! where
//! D: Deserializer<'de>,
//! {
//! // â‹®
//! # panic!("");
//! }
//! }
//! /// Starts account creation.
//! ///
//! /// This only makes sense for greenfield deployments since account information (e.g., user name) would likely
//! /// already exist otherwise. This is similar to credential creation except a random `UserHandle64` is generated and
//! /// will be used for subsequent credential registrations.
//! # #[cfg(feature = "serde_relaxed")]
//! fn start_account_creation(
//! reg_ceremonies: &mut MaxLenHashSet<RegistrationServerState64>,
//! ) -> Result<Vec<u8>, AppErr> {
//! let user_id = UserHandle64::new();
//! let (server, client) =
//! CredentialCreationOptions64::passkey(
//! RP_ID, PublicKeyCredentialUserEntity64 { id: &user_id, name: "", display_name: "", }, Vec::new()
//! )
//! .start_ceremony()
//! .unwrap_or_else(|_e| {
//! unreachable!("we don't manually mutate the options and we assume the server clock is functioning; thus this won't error")
//! });
//! if matches!(reg_ceremonies.insert_remove_all_expired(server), InsertRemoveExpired::Success)
//! {
//! Ok(serde_json::to_vec(&client)
//! .unwrap_or_else(|_e| unreachable!("bug in RegistrationClientState64::serialize")))
//! } else {
//! Err(AppErr::WebAuthnCeremonyCreation)
//! }
//! }
//! /// Finishes account creation.
//! ///
//! /// Pending a successful registration ceremony, a new account associated with the randomly generated
//! /// `UserHandle64` will be created with a corresponding passkey entry. This passkey will be used to
//! /// log into the application.
//! ///
//! /// Note if this errors, then the user should be notified to delete the passkey created on their
//! /// authenticator.
//! # #[cfg(feature = "serde_relaxed")]
//! fn finish_account_creation(
//! reg_ceremonies: &mut MaxLenHashSet<RegistrationServerState64>,
//! client_data: &[u8],
//! ) -> Result<(), AppErr> {
//! let account = serde_json::from_slice::<AccountReg>(client_data)?;
//! insert_account(
//! &account,
//! reg_ceremonies
//! // `Registration::challenge_relaxed` is available iff `serde_relaxed` is enabled.
//! .take(&account.registration.challenge_relaxed()?)
//! .ok_or(AppErr::MissingWebAuthnCeremony)?
//! .verify(
//! RP_ID,
//! &account.registration,
//! REG_OPTS,
//! )?,
//! )
//! }
//! /// Starts passkey registration.
//! ///
//! /// This is used for _existing_ accounts where the user is already logged in and wants to register another
//! /// passkey. This is similar to account creation except we already have the user entity info and we need to
//! /// fetch the registered `PublicKeyCredentialDescriptor`s to avoid accidentally overwriting a passkey on
//! /// the authenticator.
//! # #[cfg(feature = "serde_relaxed")]
//! fn start_cred_registration(
//! user_id: &UserHandle64,
//! reg_ceremonies: &mut MaxLenHashSet<RegistrationServerState64>,
//! ) -> Result<Vec<u8>, AppErr> {
//! let (username, user_display_name, creds) = select_user_info(user_id)?.ok_or(AppErr::NoAccount)?;
//! let (server, client) = CredentialCreationOptions64::passkey(RP_ID, PublicKeyCredentialUserEntity64 { name: &username, id: user_id, display_name: &user_display_name, }, creds)
//! .start_ceremony()
//! .unwrap_or_else(|_e| {
//! unreachable!("we don't manually mutate the options and we assume the server clock is functioning; thus this won't error")
//! });
//! if matches!(reg_ceremonies.insert_remove_all_expired(server), InsertRemoveExpired::Success)
//! {
//! Ok(serde_json::to_vec(&client)
//! .unwrap_or_else(|_e| unreachable!("bug in RegistrationClientState64::serialize")))
//! } else {
//! Err(AppErr::WebAuthnCeremonyCreation)
//! }
//! }
//! /// Finishes passkey registration.
//! ///
//! /// Pending a successful registration ceremony, a new credential associated with the `UserHandle64`
//! /// will be created. This passkey can then be used to log into the application just like any other registered
//! /// passkey.
//! ///
//! /// Note if this errors, then the user should be notified to delete the passkey created on their
//! /// authenticator.
//! # #[cfg(feature = "serde_relaxed")]
//! fn finish_cred_registration(
//! reg_ceremonies: &mut MaxLenHashSet<RegistrationServerState64>,
//! client_data: &[u8],
//! ) -> Result<(), AppErr> {
//! // `Registration::from_json_custom` is available iff `serde_relaxed` is enabled.
//! let registration = Registration::from_json_custom(client_data)?;
//! insert_credential(
//! reg_ceremonies
//! // `Registration::challenge_relaxed` is available iff `serde_relaxed` is enabled.
//! .take(®istration.challenge_relaxed()?)
//! .ok_or(AppErr::MissingWebAuthnCeremony)?
//! .verify(
//! RP_ID,
//! ®istration,
//! REG_OPTS,
//! )?,
//! )
//! }
//! /// Starts the passkey authentication ceremony.
//! # #[cfg(feature = "serde_relaxed")]
//! fn start_auth(
//! auth_ceremonies: &mut MaxLenHashSet<DiscoverableAuthenticationServerState>,
//! ) -> Result<Vec<u8>, AppErr> {
//! let (server, client) = DiscoverableCredentialRequestOptions::passkey(RP_ID)
//! .start_ceremony()
//! .unwrap_or_else(|_e| {
//! unreachable!("we don't manually mutate the options and we assume the server clock is functioning; thus this won't error")
//! });
//! if matches!(auth_ceremonies.insert_remove_all_expired(server), InsertRemoveExpired::Success)
//! {
//! Ok(serde_json::to_vec(&client).unwrap_or_else(|_e| {
//! unreachable!("bug in DiscoverableAuthenticationClientState::serialize")
//! }))
//! } else {
//! Err(AppErr::WebAuthnCeremonyCreation)
//! }
//! }
//! /// Finishes the passkey authentication ceremony.
//! # #[cfg(feature = "serde_relaxed")]
//! fn finish_auth(
//! auth_ceremonies: &mut MaxLenHashSet<DiscoverableAuthenticationServerState>,
//! client_data: &[u8],
//! ) -> Result<(), AppErr> {
//! // `DiscoverableAuthentication64::from_json_custom` is available iff `serde_relaxed` is enabled.
//! let authentication =
//! DiscoverableAuthentication64::from_json_custom(client_data)?;
//! let mut cred = select_credential(
//! authentication.raw_id(),
//! authentication.response().user_handle(),
//! )?
//! .ok_or(AppErr::NoCredential)?;
//! if auth_ceremonies
//! // `DiscoverableAuthentication64::challenge_relaxed` is available iff `serde_relaxed` is enabled.
//! .take(&authentication.challenge_relaxed()?)
//! .ok_or(AppErr::MissingWebAuthnCeremony)?
//! .verify(
//! RP_ID,
//! &authentication,
//! &mut cred,
//! AUTH_OPTS,
//! )?
//! {
//! update_credential(cred.id(), cred.dynamic_state())
//! } else {
//! Ok(())
//! }
//! }
//! /// Writes `account` and `cred` to storage.
//! ///
//! /// # Errors
//! ///
//! /// Errors iff writing `account` or `cred` errors, there already exists a credential using the same
//! /// `CredentialId`, or there already exists an account using the same `UserHandle64`.
//! fn insert_account(
//! account: &AccountReg,
//! cred: RegisteredCredential64<'_>,
//! ) -> Result<(), AppErr> {
//! // â‹®
//! # Ok(())
//! }
//! /// Fetches the user info and registered credentials associated with `user_id`.
//! ///
//! /// # Errors
//! ///
//! /// Errors iff fetching the data errors.
//! fn select_user_info(
//! user_id: &UserHandle64,
//! ) -> Result<
//! Option<(
//! String,
//! String,
//! Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>,
//! )>,
//! AppErr,
//! > {
//! // â‹®
//! # Ok(None)
//! }
//! /// Writes `cred` to storage.
//! ///
//! /// # Errors
//! ///
//! /// Errors iff writing `cred` errors, there already exists a credential using the same `CredentialId`,
//! /// or there does not exist an account under the `UserHandle64`.
//! fn insert_credential(
//! cred: RegisteredCredential64<'_>,
//! ) -> Result<(), AppErr> {
//! // â‹®
//! # Ok(())
//! }
//! /// Fetches the `AuthenticatedCredential` associated with `cred_id` ensuring `user_id` matches the
//! /// `UserHandle64` associated with the account.
//! ///
//! /// # Errors
//! ///
//! /// Errors iff fetching the data errors or the `user_id` does not match the stored `UserHandle64`.
//! fn select_credential<'cred, 'user>(
//! cred_id: CredentialId<&'cred [u8]>,
//! user_id: &'user UserHandle64,
//! ) -> Result<
//! Option<
//! AuthenticatedCredential64<
//! 'cred,
//! 'user,
//! CompressedPubKeyOwned,
//! >,
//! >,
//! AppErr,
//! > {
//! // â‹®
//! # Ok(None)
//! }
//! /// Overwrites the current `DynamicState` associated with `cred_id` with `dynamic_state`.
//! ///
//! /// # Errors
//! ///
//! /// Errors iff writing errors or `cred_id` does not exist.
//! fn update_credential(
//! cred_id: CredentialId<&[u8]>,
//! dynamic_state: DynamicState,
//! ) -> Result<(), AppErr> {
//! // â‹®
//! # Ok(())
//! }
//! ```
//!
//! ## Cargo "features"
//!
//! [`custom`](#custom) or both [`bin`](#bin) and [`serde`](#serde) must be enabled; otherwise a [`compile_error`]
//! will occur.
//!
//! ### `bin`
//!
//! Enables binary (de)serialization via [`Encode`] and [`Decode`]. Since registered credentials will almost always
//! have to be saved to persistent storage, _some_ form of (de)serialization is necessary. In the event `bin` is
//! unsuitable or only partially suitable (e.g., human-readable output is desired), one will need to enable
//! [`custom`](#custom) to allow construction of certain types (e.g., [`AuthenticatedCredential`]).
//!
//! If possible and desired, one may wish to save the data "directly" to avoid any potential temporary allocations.
//! For example [`StaticState::encode`] will return a [`Vec`] containing thousands of bytes if the underlying
//! public key is an ML-DSA key. This additional allocation and copy of data is obviously avoided if
//! [`StaticState`] is stored as a [composite type](https://www.postgresql.org/docs/current/rowtypes.html) or its
//! fields are stored in separate columns when written to a relational database (RDB).
//!
//! ### `custom`
//!
//! Exposes functions (e.g., [`AuthenticatedCredential::new`]) that allows one to construct instances of types that
//! cannot be constructed when [`bin`](#bin) or [`serde`](#serde) is not enabled.
//!
//! ### `serde`
//!
//! This feature _strictly_ adheres to the JSON-motivated definitions. You _will_ encounter clients that send data
//! that cannot be deserialized using this feature. For many [`serde_relaxed`](#serde_relaxed) should be used
//! instead.
//!
//! Enables (de)serialization of data sent to/from the client via [`serde`](https://docs.rs/serde/latest/serde/)
//! based on the JSON-motivated definitions (e.g.,
//! [`RegistrationResponseJSON`](https://www.w3.org/TR/webauthn-3/#dictdef-registrationresponsejson)). Since
//! data has to be sent to/from the client, _some_ form of (de)serialization is necessary. In the event `serde`
//! is unsuitable or only partially suitable, one will need to enable [`custom`](#custom) to allow construction
//! of certain types (e.g., [`Registration`]).
//!
//! Code is _strongly_ encouraged to rely on the [`Deserialize`] implementations as much as possible to reduce the
//! chances of improperly deserializing the client data.
//!
//! Note that clients are free to send data in whatever form works best, so there is no requirement the
//! JSON-motivated definitions are used even when JSON is sent. This is especially relevant since the JSON-motivated
//! definitions were only added in [WebAuthn Level 3](https://www.w3.org/TR/webauthn-3/); thus many deployments only
//! partially conform. Some specific deviations that may require partial customization of deserialization are the
//! following:
//!
//! * [`ArrayBuffer`](https://webidl.spec.whatwg.org/#idl-ArrayBuffer)s encoded using something other than
//! base64url.
//! * `ArrayBuffer`s that are encoded multiple times (including the use of different encodings each time).
//! * Missing fields (e.g.,
//! [`transports`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorattestationresponsejson-transports)).
//! * Different field names (e.g., `extensions` instead of
//! [`clientExtensionResults`](https://www.w3.org/TR/webauthn-3/#dom-registrationresponsejson-clientextensionresults)).
//!
//! ### `serde_relaxed`
//!
//! Automatically enables [`serde`](#serde) in addition to "relaxed" [`Deserialize`] implementations
//! (e.g., [`RegistrationRelaxed`]). Roughly "relaxed" translates to unknown fields being ignored and only
//! the fields necessary for construction of the type are required. Case still matters, duplicate fields are still
//! forbidden, and interrelated data validation is still performed when applicable. This can be useful when one
//! wants to accommodate non-conforming clients or clients that implement older versions of the spec.
//!
//! ### `serializable_server_state`
//!
//! Automatically enables [`bin`](#bin) in addition to [`Encode`] and [`Decode`] implementations for
//! [`RegistrationServerState`], [`DiscoverableAuthenticationServerState`], and
//! [`NonDiscoverableAuthenticationServerState`]. Less accurate [`SystemTime`] is used instead of [`Instant`] for
//! timeout enforcement. This should be enabled if you don't desire to use in-memory collections to store the instances
//! of those types.
//!
//! Note even when written to persistent storage, an application should still periodically remove expired ceremonies.
//! If one is using a relational database (RDB); then one can achieve this by storing [`SentChallenge`],
//! the `Vec` returned from [`Encode::encode`], and [`TimedCeremony::expiration`] and periodically remove all rows
//! whose expiration exceeds the current date and time.
//!
//! ## Registration and authentication
//!
//! Both [registration](https://www.w3.org/TR/webauthn-3/#registration-ceremony) and
//! [authentication](https://www.w3.org/TR/webauthn-3/#authentication-ceremony) ceremonies rely on "challenges", and
//! these challenges are inherently temporary. For this reason the data associated with challenge completion can
//! often be stored in memory without concern for out-of-memory (OOM) conditions. There are several benefits to
//! storing such data in memory:
//!
//! * No data manipulation
//! * By leveraging move semantics, the data sent to the client cannot be mutated once the ceremony begins.
//! * Improved timeout enforcement
//! * By ensuring the same machine that started the ceremony is also used to finish the ceremony, deviation of
//! system clocks is not a concern. Additionally, allowing serialization requires the use of some form of
//! cross-platform "timestamp" (e.g., [Unix time](https://en.wikipedia.org/wiki/Unix_time)) which differ in
//! implementation (e.g., platforms implement leap seconds in different ways) and are often not monotonically
//! increasing. If data resides in memory, a monotonic [`Instant`] can be used instead.
//!
//! It is for those reasons data like [`RegistrationServerState`] are not serializable by default and require the
//! use of in-memory collections (e.g., [`MaxLenHashSet`]). To better ensure OOM is not a concern, RPs should set
//! reasonable timeouts. Since ceremonies can only be completed by moving data (e.g.,
//! [`RegistrationServerState::verify`]), ceremony completion is guaranteed to free up the memory used—
//! `RegistrationServerState` instances are as small as 48 bytes on `x86_64-unknown-linux-gnu` platforms. To avoid
//! issues related to incomplete ceremonies, RPs can periodically iterate the collection for expired ceremonies and
//! remove such data. Other techniques can be employed as well to mitigate OOM, but they are application specific
//! and out-of-scope. If this is undesirable, one can enable [`serializable_server_state`](#serializable_server_state)
//! so that `RegistrationServerState`, [`DiscoverableAuthenticationServerState`], and
//! [`NonDiscoverableAuthenticationServerState`] implement [`Encode`] and [`Decode`]. Another reason one may need to
//! store this information persistently is for load-balancing purposes where the server that started the ceremony is
//! not guaranteed to be the server that finishes the ceremony.
//!
//! ## Supported signature algorithms
//!
//! The only supported signature algorithms are the following:
//!
//! * ML-DSA-87 as defined in [NIST FIPS 204](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.204.pdf). This
//! corresponds to [`CoseAlgorithmIdentifier::Mldsa87`].
//! * ML-DSA-65 as defined in [NIST FIPS 204](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.204.pdf). This
//! corresponds to [`CoseAlgorithmIdentifier::Mldsa65`].
//! * ML-DSA-44 as defined in [NIST FIPS 204](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.204.pdf). This
//! corresponds to [`CoseAlgorithmIdentifier::Mldsa44`].
//! * Ed25519 as defined in [RFC 8032 § 5.1](https://www.rfc-editor.org/rfc/rfc8032#section-5.1). This corresponds
//! to [`CoseAlgorithmIdentifier::Eddsa`].
//! * ECDSA as defined in [SEC 1 Version 2.0 § 4.1](https://www.secg.org/sec1-v2.pdf#subsection.4.1) using SHA-256
//! as the hash function and NIST P-256 as defined in
//! [NIST SP 800-186 § 3.2.1.3](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-186.pdf#%5B%7B%22num%22%3A229%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C70%2C275%2C0%5D)
//! for the underlying elliptic curve. This corresponds to [`CoseAlgorithmIdentifier::Es256`].
//! * ECDSA as defined in SEC 1 Version 2.0 § 4.1 using SHA-384 as the hash function and NIST P-384 as defined in
//! [NIST SP 800-186 § 3.2.1.4](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-186.pdf#%5B%7B%22num%22%3A232%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C70%2C264%2C0%5D)
//! for the underlying elliptic curve. This corresponds to [`CoseAlgorithmIdentifier::Es384`].
//! * RSASSA-PKCS1-v1_5 as defined in [RFC 8017 § 8.2](https://www.rfc-editor.org/rfc/rfc8017#section-8.2) using
//! SHA-256 as the hash function. This corresponds to [`CoseAlgorithmIdentifier::Rs256`].
//!
//! ## Correctness of code
//!
//! This library more strictly adheres to the spec than many other similar libraries including but not limited to
//! the following ways:
//!
//! * [CTAP2 canonical CBOR encoding form](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#ctap2-canonical-cbor-encoding-form).
//! * `Deserialize` implementations requiring _exact_ conformance (e.g., not allowing unknown data).
//! * More thorough interrelated data validation (e.g., all places a Credential ID exists must match).
//! * Implement a lot of recommended (i.e., SHOULD) criteria.
//!
//! Unfortunately like almost all software, this library has not been formally verified; however great care is
//! employed in the following ways:
//!
//! * Leverage move semantics to prevent mutation of data once in a static state.
//! * Ensure a great many invariants via types.
//! * Reduce code duplication.
//! * Reduce variable mutation allowing for simpler algebraic reasoning.
//! * `panic`-free code[^note] (i.e., define true/total functions).
//! * Ensure arithmetic "side effects" don't occur (e.g., overflow).
//! * Aggressive use of compiler and [Clippy](https://doc.rust-lang.org/stable/clippy/lints.html) lints.
//! * Unit tests for common cases, edge cases, and error cases.
//!
//! ## Cryptographic libraries
//!
//! This library does not rely on _any_ sensitive data (e.g., private keys) as only signature verification is
//! ever performed. This means that the only thing that matters with the libraries used is their algorithmic
//! correctness and not other normally essential aspects like susceptibility to side-channel attacks. While I
//! personally believe the libraries that are used are at least as "secure" as alternatives even when dealing with
//! sensitive data, one only needs to audit the correctness of the libraries to be confident in their use. In fact
//! [`curve25519_dalek`](https://docs.rs/curve25519-dalek/latest/curve25519_dalek/#backends) has been formally
//! verified when the [`fiat`](https://github.com/mit-plv/fiat-crypto) backend is used making it _objectively_
//! better than many other libraries whose correctness has not been proven. Two additional benefits of the library
//! choices are simpler APIs making it more likely their use is correct and better cross-platform compatibility.
//!
//! [^note]: `panic`s related to memory allocations or stack overflow are possible since such issues are not
//! formally guarded against.
//#[cfg(not(any(feature = "custom", all(feature = "bin", feature = "serde"))))]
//compile_error!("'custom' must be enabled or both 'bin' and 'serde' must be enabled");
use crate;
use crate;
use crate;
use crateCredentialIdErr;
use crateSerdeJsonErr;
use crate;
use crate::;
use crate::;
use ;
use FromStr;
use ;
use RegistrationRelaxed;
use Deserialize;
use ;
use SystemTimeError;
use ;
/// Contains functionality to (de)serialize data to a data store.
/// Contains functionality for maximum-length hash maps and sets that allocate exactly once.
/// Functionality for starting ceremonies.
///
/// # What kind of credential should I create?
///
/// Without partitioning the possibilities _too_ much, the following are possible authentication flows:
///
/// | Label | Username | Password | Client-side credential | Authenticator-side user verification | Recommended |
/// |-------|----------|----------|------------------------|--------------------------------------|:-----------:|
/// | 1 | Yes | Yes | Required | Yes | ❌ |
/// | 2 | Yes | Yes | Required | No | ❌ |
/// | 3 | Yes | Yes | Optional | Yes | ❌ |
/// | <a name="label4">4</a> | Yes | Yes | Optional | No | âś… |
/// | 5 | Yes | No | Required | Yes | ❌ |
/// | 6 | Yes | No | Required | No | ❌ |
/// | <a name="label7">7</a> | Yes | No | Optional | Yes | âť” |
/// | 8 | Yes | No | Optional | No | ❌ |
/// | 9 | No | Yes | Required | Yes | ❌ |
/// | 10 | No | Yes | Required | No | ❌ |
/// | 11 | No | Yes | Optional | Yes | ❌ |
/// | 12 | No | Yes | Optional | No | ❌ |
/// | <a name="label13">13</a> | No | No | Required | Yes | âś… |
/// | 14 | No | No | Required | No | ❌ |
/// | 15 | No | No | Optional | Yes | ❌ |
/// | 16 | No | No | Optional | No | ❌ |
///
/// * All `Label`s with both `Password` and `Authenticator-side user verification` set to `Yes` are not recommended
/// since the verification done on the authenticator is likely the same "factor" as a password; thus it does not
/// add benefit but only serves as an annoyance to users.
/// * All `Label`s with `Username` or `Password` set to `Yes` and `Client-side credential` set to `Required` are not
/// recommended since you may preclude authenticators that are storage constrained (e.g., security keys).
/// * All `Label`s with `Username` set to `No` and `Client-side credential` set to `Optional` are not possible since
/// RPs would not have a way to identify the set of encrypted credentials to pass to the unknown user.
/// * All `Label`s with `Password` and `Authenticator-side user verification` set to `No` are not recommended since
/// those are single-factor authentication schemes; thus anyone possessing the credential without also passing
/// some form of user verification (e.g., password) would authenticate.
/// * [`Label 7`](#label7) is possible for RPs that are comfortable passing an encrypted credential to a potential user
/// without having that user first pass another form of authentication. For many RPs passing such information even
/// if encrypted is not desirable though.
/// * [`Label 4`](#label4) is ideal as a single-factor flow incorporated within a wider multi-factor authentication (MFA)
/// setup. The easiest way to register such a credential is with
/// [`CredentialCreationOptions::second_factor`].
/// * [`Label 13`](#label13) is ideal for passkey setups as it allows for pleasant UX where a user does not have to type a
/// username nor password while still being secured with MFA with one of the factors being based on public-key
/// cryptography which for many is the most secure form of single-factor authentication. The easiest way to register
/// such a credential is with [`CredentialCreationOptions::passkey`].
///
/// Two other reasons one may prefer to construct client-side credentials is richer support for extensions (e.g.,
/// [`largeBlobKey`](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#sctn-largeBlobKey-extension)
/// for CTAP 2.2 authenticators) and the ability to use both discoverable and nondiscoverable requests. The former is not
/// relevant for this library—at least currently—since the only extensions supported are applicable for both
/// client-side and server-side credentials. The latter can be important especially if an RP wants the ability to
/// seamlessly transition from a username and password scheme to a userless and passwordless one in the future.
///
/// Note the table is purely informative. While helper functions
/// (e.g., [`CredentialCreationOptions::passkey`]) only exist for [`Label 4`](#label4) and
/// [`Label 13`](#label13), one can create any credential since all fields in [`CredentialCreationOptions`]
/// and [`PublicKeyCredentialRequestOptions`] are accessible.
/// Functionality for completing ceremonies.
///
/// Read [`request`] for more information about what credentials one should create.
pub use crate::;
/// Error returned in [`RegCeremonyErr::Credential`] and [`AuthenticatedCredential::new`].
/// Checks if the `static_state` and `dynamic_state` are valid.
///
/// # Errors
///
/// Errors iff `static_state` or `dynamc_state` are invalid.
/// Registered credential that needs to be saved server-side to perform future
/// [authentication ceremonies](https://www.w3.org/TR/webauthn-3/#authentication-ceremony) with
/// [`AuthenticatedCredential`].
///
/// When saving `RegisteredCredential` to persistent storage, one will almost always want to save the contained data
/// separately. The reasons for this are the following:
///
/// * [`CredentialId`]
/// * MUST be globally unique, and it will likely be easier to enforce such uniqueness when it's separate.
/// * Fetching the [`AuthenticatedCredential`] by [`Authentication::raw_id`] when completing the
/// authentication ceremony via [`DiscoverableAuthenticationServerState::verify`] or
/// [`NonDiscoverableAuthenticationServerState::verify`] will likely be easier than alternatives.
/// * [`AuthTransports`]
/// * Fetching [`CredentialId`]s and associated `AuthTransports` by [`UserHandle`] will likely make credential
/// registration easier since one should set [`PublicKeyCredentialCreationOptions::exclude_credentials`] to
/// the [`PublicKeyCredentialDescriptor`]s belonging to a `UserHandle` in order to avoid accidentally
/// overwriting an existing credential on the authenticator.
/// * Fetching `CredentialId`s and associated `AuthTransports` by `UserHandle` will likely make starting
/// authentication ceremonies easier for [`NonDiscoverableCredentialRequestOptions`].
/// * [`UserHandle`]
/// * Fetching the [`AuthenticatedCredential`] by [`DiscoverableAuthentication::raw_id`] must also coincide with
/// verifying the associated `UserHandle` matches [`DiscoverableAuthenticatorAssertion::user_handle`].
/// * Fetching [`CredentialId`]s and associated [`AuthTransports`] by `UserHandle` will likely make credential
/// registration easier since one should set [`PublicKeyCredentialCreationOptions::exclude_credentials`] to
/// the [`PublicKeyCredentialDescriptor`]s belonging to a `UserHandle` in order to avoid accidentally
/// overwriting an existing credential on the authenticator.
/// * Fetching `CredentialId`s and associated `AuthTransports` by `UserHandle` will likely make starting
/// authentication ceremonies easier for [`NonDiscoverableCredentialRequestOptions`].
/// * [`DynamicState`]
/// * `DynamicState` is the only part that is ever updated after a successful authentication ceremony
/// via [`DiscoverableAuthenticationServerState::verify`] or
/// [`NonDiscoverableAuthenticationServerState::verify`]. It being separate allows for smaller and quicker
/// updates.
/// * [`Metadata`]
/// * Informative data that is never used during authentication ceremonies; consequently, one may wish to
/// not even save this information.
/// * [`StaticState`]
/// * All other data exists as part of `StaticState`.
///
/// It is for those reasons that `RegisteredCredential` does not implement [`Encode`] or [`Decode`]; instead its parts
/// do.
///
/// Note that [`RpId`] and user information other than the `UserHandle` are not stored in `RegisteredCredential`.
/// RPs that wish to store such information must do so on their own. Since user information is likely the same
/// for a given `UserHandle` and `RpId` is likely static, it makes little sense to store such information
/// automatically.
///
/// When registering a credential, [`AttestedCredentialData::aaguid`], [`AttestedCredentialData::credential_id`],
/// and [`AttestedCredentialData::credential_public_key`] will be the sources for [`Metadata::aaguid`],
/// [`Self::id`], and [`StaticState::credential_public_key`] respectively. The [`PublicKeyCredentialUserEntity::id`]
/// associated with the [`CredentialCreationOptions`] used to create the `RegisteredCredential` via
/// [`RegistrationServerState::verify`] will be the source for [`Self::user_id`].
///
/// The only way to create this is via `RegistrationServerState::verify`.
/// `RegisteredCredential` based on a [`UserHandle64`].
pub type RegisteredCredential64<'reg> = ;
/// `RegisteredCredential` based on a [`UserHandle16`].
pub type RegisteredCredential16<'reg> = ;
/// Credential used in authentication ceremonies.
///
/// Similar to [`RegisteredCredential`] except designed to only contain the necessary data to complete
/// authentication ceremonies. In particular there is no [`AuthTransports`] or [`Metadata`],
/// [`StaticState::credential_public_key`] is [`CompressedPubKey`] that can own or borrow its data, [`Self::id`] is
/// based on the [`CredentialId`] passed to [`Self::new`] which itself must be from [`Authentication::raw_id`], and
/// [`Self::user_id`] is based on the [`UserHandle`] passed to [`Self::new`] which itself must be the value in
/// persistent storage associated with the `CredentialId`.
///
/// When [`DiscoverableAuthentication`] is used, one can use [`DiscoverableAuthenticatorAssertion::user_handle`]
/// for `Self::user_id` so long as it matches the value in persistent storage.
///
/// Note `PublicKey` should be `CompressedPubKey` for this to be useful.
///
/// The only way to create this is via `Self::new`.
use ;
/// `AuthenticatedCredential` based on a [`UserHandle64`].
pub type AuthenticatedCredential64<'cred, 'user, PublicKey> =
;
/// `AuthenticatedCredential` based on a [`UserHandle16`].
pub type AuthenticatedCredential16<'cred, 'user, PublicKey> =
;
/// `AuthenticatedCredential` that owns the key data.
pub type AuthenticatedCredentialOwned<'cred, 'user, const USER_LEN: usize> =
;
/// `AuthenticatedCredential` that borrows the key data.
pub type AuthenticatedCredentialBorrowed<'cred, 'user, 'key, const USER_LEN: usize> =
;
/// Convenience aggregate error that rolls up all errors into one.