jwk-simple 0.5.0

JWK/JWKS for Rust and WASM (RFC 7517, 7518, 7638, 8037, 9864) with jwt-simple integration
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
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
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
//! WebCrypto integration for browser/WASM environments.
//!
//! This module provides conversions from jwk-simple [`Key`] types to
//! [`web_sys::JsonWebKey`] for use with the browser's SubtleCrypto API,
//! as well as helper functions for importing keys as [`web_sys::CryptoKey`].
//!
//! # Supported Key Types
//!
//! | Key Type | Curve/Algorithm | WebCrypto Support |
//! |----------|-----------------|-------------------|
//! | RSA | RS256/RS384/RS512 | Yes (RSASSA-PKCS1-v1_5) |
//! | RSA | PS256/PS384/PS512 | Yes (RSA-PSS) |
//! | EC | P-256 | Yes (ECDSA) |
//! | EC | P-384 | Yes (ECDSA) |
//! | EC | P-521 | Yes (ECDSA) |
//! | EC | secp256k1 | **No** |
//! | OKP | Ed25519/Ed448 | **No** |
//! | OKP | X25519/X448 | **No** |
//! | Symmetric | HMAC | Yes |
//! | Symmetric | AES-GCM, AES-KW | Yes |
//!
//! # Examples
//!
//! ## Converting a Key to JsonWebKey
//!
//! ```ignore
//! use jwk_simple::Key;
//! use std::convert::TryInto;
//!
//! let key: Key = serde_json::from_str(jwk_json)?;
//! let web_jwk: web_sys::JsonWebKey = (&key).try_into()?;
//! ```
//!
//! ## Importing a Key for Signature Verification
//!
//! ```ignore
//! use jwk_simple::{Key, web_crypto};
//! use jwk_simple::Algorithm;
//!
//! let key: Key = serde_json::from_str(jwk_json)?;
//! let crypto_key = web_crypto::import_verify_key_for_alg(&key, &Algorithm::Rs256).await?;
//!
//! // Use with SubtleCrypto.verify()
//! let subtle = web_crypto::get_subtle_crypto()?;
//! // ... perform verification
//! ```
//!
//! # Limitations
//!
//! WebCrypto does not support:
//! - **OKP keys** (Ed25519, Ed448, X25519, X448) - These use Edwards/Montgomery curves
//!   which are not part of the WebCrypto specification.
//! - **secp256k1 curve** - While popular in cryptocurrency applications, this curve
//!   is not supported by WebCrypto.
//!
//! Attempting to convert these key types will return an
//! [`Error::UnsupportedForWebCrypto`] error.

use js_sys::{Array, Object, Reflect};
use std::convert::TryFrom;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
#[cfg(all(feature = "cloudflare", target_arch = "wasm32"))]
use web_sys::Crypto;
use web_sys::{CryptoKey, SubtleCrypto};

use crate::error::{Error, Result};
use crate::jwk::{Algorithm, EcCurve, Key, KeyOperation, KeyParams};
#[cfg(test)]
use crate::jwks::KeyMatcher;

// ============================================================================
// SubtleCrypto Access
// ============================================================================

/// Gets the SubtleCrypto interface from the current environment.
///
/// This function works in both browser (Window) and Web Worker contexts.
///
/// # Errors
///
/// Returns an error if the crypto API is not available in the current context.
///
/// # Examples
///
/// ```ignore
/// let subtle = web_crypto::get_subtle_crypto()?;
/// ```
pub fn get_subtle_crypto() -> Result<SubtleCrypto> {
    #[cfg(all(feature = "cloudflare", target_arch = "wasm32"))]
    {
        // Cloudflare does expose `crypto` in the global scope but
        // the global scope may not be able to cast into `WorkerGlobalScope`.
        let global = js_sys::global();
        let crypto_field_name = JsValue::from_str("crypto");
        if let Ok(crypto_field) = Reflect::get(&global, &crypto_field_name)
            && let Ok(crypto) = crypto_field.dyn_into::<Crypto>()
        {
            return Ok(crypto.subtle());
        }
    }

    // Try window first (browser context)
    if let Some(window) = web_sys::window()
        && let Ok(crypto) = window.crypto()
    {
        return Ok(crypto.subtle());
    }

    // Try WorkerGlobalScope (Web Worker context)
    let global = js_sys::global();
    if let Ok(worker_scope) = global.dyn_into::<web_sys::WorkerGlobalScope>()
        && let Ok(crypto) = worker_scope.crypto()
    {
        return Ok(crypto.subtle());
    }

    Err(Error::WebCrypto(
        "crypto API not available in this context".to_string(),
    ))
}

// ============================================================================
// Key to JsonWebKey Conversion
// ============================================================================

/// Conversion from [`Key`] to [`web_sys::JsonWebKey`] for WebCrypto usage.
///
/// # Supported Key Types
///
/// - **RSA**: All RSA keys are supported
/// - **EC**: P-256, P-384, P-521 curves are supported; secp256k1 is NOT supported
/// - **Symmetric**: All symmetric keys are supported
/// - **OKP**: NOT supported (Ed25519, Ed448, X25519, X448)
///
/// # Errors
///
/// Returns [`Error::UnsupportedForWebCrypto`] if the key type or curve is not
/// supported by WebCrypto.
///
/// # Examples
///
/// ```ignore
/// use jwk_simple::Key;
/// use std::convert::TryInto;
///
/// let key: Key = serde_json::from_str(r#"{"kty":"RSA","n":"...","e":"AQAB"}"#)?;
/// let jwk: web_sys::JsonWebKey = (&key).try_into()?;
/// assert_eq!(jwk.get_kty(), "RSA");
/// ```
impl TryFrom<&Key> for web_sys::JsonWebKey {
    type Error = Error;

    fn try_from(key: &Key) -> Result<Self> {
        // Keep conversion-level validation focused on key material shape.
        // Full JWK metadata validation (including `use`/`key_ops`/x509 checks)
        // is context-dependent and should be performed by callers that need it.
        // This also avoids enforcing `key.alg` in explicit-alg import flows.
        key.params().validate()?;

        // Validate that the key type is supported
        validate_webcrypto_support(key)?;

        let jwk = web_sys::JsonWebKey::new(key.kty().as_str());

        // Set common optional fields
        // Note: `kid` is not part of the WebCrypto JsonWebKey dictionary,
        // so it is not set here.

        if let Some(alg) = key.alg() {
            jwk.set_alg(alg.as_str());
        }

        if let Some(key_use) = key.key_use() {
            jwk.set_use(key_use.as_str());
        }

        if let Some(key_ops) = key.key_ops() {
            let ops = Array::new();
            for op in key_ops {
                ops.push(&JsValue::from_str(op.as_str()));
            }
            jwk.set_key_ops(&ops);
        }

        // Set type-specific parameters
        match key.params() {
            KeyParams::Rsa(params) => {
                // Public key components (always present)
                jwk.set_n(&params.n.to_base64url());
                jwk.set_e(&params.e.to_base64url());

                // Private key components (optional)
                if let Some(d) = &params.d {
                    jwk.set_d(&d.to_base64url());
                }
                if let Some(p) = &params.p {
                    jwk.set_p(&p.to_base64url());
                }
                if let Some(q) = &params.q {
                    jwk.set_q(&q.to_base64url());
                }
                if let Some(dp) = &params.dp {
                    jwk.set_dp(&dp.to_base64url());
                }
                if let Some(dq) = &params.dq {
                    jwk.set_dq(&dq.to_base64url());
                }
                if let Some(qi) = &params.qi {
                    jwk.set_qi(&qi.to_base64url());
                }
                // Note: 'oth' (other primes) is not supported by web_sys::JsonWebKey
            }
            KeyParams::Ec(params) => {
                jwk.set_crv(params.crv.as_str());
                jwk.set_x(&params.x.to_base64url());
                jwk.set_y(&params.y.to_base64url());

                if let Some(d) = &params.d {
                    jwk.set_d(&d.to_base64url());
                }
            }
            KeyParams::Symmetric(params) => {
                jwk.set_k(&params.k.to_base64url());
            }
            KeyParams::Okp(_) => {
                // This should never be reached due to validate_webcrypto_support
                return Err(Error::UnsupportedForWebCrypto {
                    reason: "OKP keys (Ed25519, Ed448, X25519, X448) are not supported by WebCrypto",
                });
            }
        }

        Ok(jwk)
    }
}

/// Validates that a key is supported by WebCrypto.
fn validate_webcrypto_support(key: &Key) -> Result<()> {
    match key.params() {
        KeyParams::Okp(_) => Err(Error::UnsupportedForWebCrypto {
            reason: "OKP keys (Ed25519, Ed448, X25519, X448) are not supported by WebCrypto",
        }),
        KeyParams::Ec(params) => {
            if params.crv == EcCurve::Secp256k1 {
                Err(Error::UnsupportedForWebCrypto {
                    reason: "secp256k1 curve is not supported by WebCrypto",
                })
            } else {
                Ok(())
            }
        }
        KeyParams::Rsa(_) | KeyParams::Symmetric(_) => Ok(()),
    }
}

// ============================================================================
// Algorithm Object Builders
// ============================================================================

/// Builds a WebCrypto algorithm object for the given key.
///
/// The algorithm object is used with `SubtleCrypto.importKey()`.
fn build_algorithm_object(key: &Key, usage: KeyUsage) -> Result<Object> {
    build_algorithm_object_with_alg(key, usage, None)
}

fn build_algorithm_object_for_alg(key: &Key, alg: &Algorithm, usage: KeyUsage) -> Result<Object> {
    build_algorithm_object_with_alg(key, usage, Some(alg))
}

fn build_algorithm_object_with_alg(
    key: &Key,
    usage: KeyUsage,
    alg_override: Option<&Algorithm>,
) -> Result<Object> {
    match key.params() {
        KeyParams::Rsa(_) => build_rsa_algorithm(key, usage, alg_override),
        KeyParams::Ec(params) => {
            // When an explicit algorithm is provided, validate that it is
            // compatible with the key's curve before building the import
            // algorithm object. This catches mismatches like ES384 with a
            // P-256 key early, instead of letting them surface as opaque
            // WebCrypto errors during verify/sign.
            if let Some(alg) = alg_override {
                let expected_curve = match alg {
                    Algorithm::Es256 => Some(EcCurve::P256),
                    Algorithm::Es384 => Some(EcCurve::P384),
                    Algorithm::Es512 => Some(EcCurve::P521),
                    _ => None,
                };
                match expected_curve {
                    Some(curve) if curve != params.crv => {
                        return Err(Error::WebCrypto(format!(
                            "algorithm {} requires curve {}, but the key uses {}",
                            alg.as_str(),
                            curve.as_str(),
                            params.crv.as_str(),
                        )));
                    }
                    None => {
                        return Err(Error::WebCrypto(format!(
                            "algorithm {} is not supported for EC key import in WebCrypto",
                            alg.as_str(),
                        )));
                    }
                    _ => {} // curve matches, proceed
                }
            }
            build_ec_algorithm(params.crv, usage)
        }
        KeyParams::Symmetric(_) => build_symmetric_algorithm(key, usage, alg_override),
        KeyParams::Okp(_) => Err(Error::UnsupportedForWebCrypto {
            reason: "OKP keys are not supported by WebCrypto",
        }),
    }
}

fn validate_usage_algorithm_compatibility(usage: KeyUsage, alg: &Algorithm) -> Result<()> {
    let allowed = match usage {
        KeyUsage::Verify => matches!(
            alg,
            Algorithm::Rs256
                | Algorithm::Rs384
                | Algorithm::Rs512
                | Algorithm::Ps256
                | Algorithm::Ps384
                | Algorithm::Ps512
                | Algorithm::Es256
                | Algorithm::Es384
                | Algorithm::Es512
                | Algorithm::Hs256
                | Algorithm::Hs384
                | Algorithm::Hs512
        ),
        KeyUsage::Sign => matches!(
            alg,
            Algorithm::Rs256
                | Algorithm::Rs384
                | Algorithm::Rs512
                | Algorithm::Ps256
                | Algorithm::Ps384
                | Algorithm::Ps512
                | Algorithm::Es256
                | Algorithm::Es384
                | Algorithm::Es512
                | Algorithm::Hs256
                | Algorithm::Hs384
                | Algorithm::Hs512
        ),
        KeyUsage::Encrypt => matches!(
            alg,
            Algorithm::RsaOaep
                | Algorithm::RsaOaep256
                | Algorithm::RsaOaep384
                | Algorithm::RsaOaep512
                | Algorithm::A128gcm
                | Algorithm::A192gcm
                | Algorithm::A256gcm
        ),
        KeyUsage::Decrypt => matches!(
            alg,
            Algorithm::RsaOaep
                | Algorithm::RsaOaep256
                | Algorithm::RsaOaep384
                | Algorithm::RsaOaep512
                | Algorithm::A128gcm
                | Algorithm::A192gcm
                | Algorithm::A256gcm
        ),
        KeyUsage::WrapKey => matches!(
            alg,
            Algorithm::RsaOaep
                | Algorithm::RsaOaep256
                | Algorithm::RsaOaep384
                | Algorithm::RsaOaep512
                | Algorithm::A128kw
                | Algorithm::A192kw
                | Algorithm::A256kw
        ),
        KeyUsage::UnwrapKey => matches!(
            alg,
            Algorithm::RsaOaep
                | Algorithm::RsaOaep256
                | Algorithm::RsaOaep384
                | Algorithm::RsaOaep512
                | Algorithm::A128kw
                | Algorithm::A192kw
                | Algorithm::A256kw
        ),
    };

    if allowed {
        Ok(())
    } else {
        Err(Error::UnsupportedForWebCrypto {
            reason: "algorithm is not compatible with requested key usage",
        })
    }
}

fn validate_key_for_webcrypto_usage_with_alg(
    key: &Key,
    usage: KeyUsage,
    alg: &Algorithm,
) -> Result<()> {
    validate_usage_algorithm_compatibility(usage, alg)?;
    // Use the override variant: the caller explicitly provides the algorithm,
    // so we must not reject keys whose declared `alg` differs from the
    // requested one.
    key.validate_for_use_with_alg_override(alg, [key_operation_for_usage(usage)])
}

fn validate_key_for_webcrypto_usage(key: &Key, usage: KeyUsage) -> Result<()> {
    let requested_op = key_operation_for_usage(usage);

    if let Some(alg) = key.alg() {
        validate_usage_algorithm_compatibility(usage, alg)?;
        key.validate_for_use(alg, [requested_op])?;
        return Ok(());
    }

    // No algorithm on key: structural validation + operation intent only.
    // `validate()` already enforced `use`/`key_ops` consistency and uniqueness,
    // so we call the intent-only helper directly.
    key.validate()?;
    key.check_operation_capability(std::slice::from_ref(&requested_op))?;
    key.validate_operation_intent_for_all(std::slice::from_ref(&requested_op))?;

    Ok(())
}

fn key_operation_for_usage(usage: KeyUsage) -> KeyOperation {
    match usage {
        KeyUsage::Sign => KeyOperation::Sign,
        KeyUsage::Verify => KeyOperation::Verify,
        KeyUsage::Encrypt => KeyOperation::Encrypt,
        KeyUsage::Decrypt => KeyOperation::Decrypt,
        KeyUsage::WrapKey => KeyOperation::WrapKey,
        KeyUsage::UnwrapKey => KeyOperation::UnwrapKey,
    }
}

/// Key usage category for determining the appropriate algorithm.
///
/// This is used by the low-level [`import_key_for_usage`] and
/// [`import_key_for_usage_with_alg`] functions to select the correct
/// WebCrypto algorithm parameters at import time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyUsage {
    /// The key will be used for signing.
    Sign,
    /// The key will be used for signature verification.
    Verify,
    /// The key will be used for encryption.
    Encrypt,
    /// The key will be used for decryption.
    Decrypt,
    /// The key will be used for wrapping other keys.
    WrapKey,
    /// The key will be used for unwrapping other keys.
    UnwrapKey,
}

fn usage_strings_for_usage(usage: KeyUsage) -> &'static [&'static str] {
    match usage {
        KeyUsage::Sign => &["sign"],
        KeyUsage::Verify => &["verify"],
        KeyUsage::Encrypt => &["encrypt"],
        KeyUsage::Decrypt => &["decrypt"],
        KeyUsage::WrapKey => &["wrapKey"],
        KeyUsage::UnwrapKey => &["unwrapKey"],
    }
}

/// Builds an RSA algorithm object.
///
/// The algorithm is determined from (in order of priority):
/// 1. The `alg_override` parameter (if provided)
/// 2. The key's `alg` field (if present)
///
/// If neither is available, an error is returned because WebCrypto requires
/// the hash algorithm to be specified at import time and a wrong default
/// (e.g., SHA-256 for a key intended for RS384) would cause silent
/// verification failures.
fn build_rsa_algorithm(
    key: &Key,
    _usage: KeyUsage,
    alg_override: Option<&Algorithm>,
) -> Result<Object> {
    let obj = Object::new();

    // Use the override first, then fall back to the key's own algorithm
    let effective_alg = alg_override.or(key.alg());

    // Determine algorithm name and hash based on the effective algorithm
    let (alg_name, hash) = match effective_alg {
        Some(Algorithm::Rs256) => ("RSASSA-PKCS1-v1_5", "SHA-256"),
        Some(Algorithm::Rs384) => ("RSASSA-PKCS1-v1_5", "SHA-384"),
        Some(Algorithm::Rs512) => ("RSASSA-PKCS1-v1_5", "SHA-512"),
        Some(Algorithm::Ps256) => ("RSA-PSS", "SHA-256"),
        Some(Algorithm::Ps384) => ("RSA-PSS", "SHA-384"),
        Some(Algorithm::Ps512) => ("RSA-PSS", "SHA-512"),
        Some(Algorithm::RsaOaep) => ("RSA-OAEP", "SHA-1"),
        Some(Algorithm::RsaOaep256) => ("RSA-OAEP", "SHA-256"),
        Some(Algorithm::RsaOaep384) => ("RSA-OAEP", "SHA-384"),
        Some(Algorithm::RsaOaep512) => ("RSA-OAEP", "SHA-512"),
        _ => {
            return Err(Error::WebCrypto(
                "RSA key import requires an algorithm to determine the hash function; \
                 set the `alg` field on the key or use an import function that accepts \
                 an explicit algorithm (e.g., `import_verify_key_for_alg`)"
                    .to_string(),
            ));
        }
    };

    Reflect::set(&obj, &"name".into(), &alg_name.into())
        .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;

    // Set hash algorithm
    let hash_obj = Object::new();
    Reflect::set(&hash_obj, &"name".into(), &hash.into())
        .map_err(|e| Error::WebCrypto(format!("failed to set hash name: {:?}", e)))?;
    Reflect::set(&obj, &"hash".into(), &hash_obj.into())
        .map_err(|e| Error::WebCrypto(format!("failed to set hash: {:?}", e)))?;

    Ok(obj)
}

/// Builds an EC algorithm object.
fn build_ec_algorithm(curve: EcCurve, usage: KeyUsage) -> Result<Object> {
    let obj = Object::new();

    let alg_name = match usage {
        KeyUsage::Sign | KeyUsage::Verify => "ECDSA",
        KeyUsage::Encrypt | KeyUsage::Decrypt | KeyUsage::WrapKey | KeyUsage::UnwrapKey => {
            return Err(Error::UnsupportedForWebCrypto {
                reason: "EC key derivation (ECDH) and direct encrypt/decrypt/wrap/unwrap \
                         are not yet supported by this library; \
                         only ECDSA sign/verify is currently implemented for EC keys",
            });
        }
    };

    Reflect::set(&obj, &"name".into(), &alg_name.into())
        .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;

    let named_curve = match curve {
        EcCurve::P256 => "P-256",
        EcCurve::P384 => "P-384",
        EcCurve::P521 => "P-521",
        EcCurve::Secp256k1 => {
            return Err(Error::UnsupportedForWebCrypto {
                reason: "secp256k1 curve is not supported by WebCrypto",
            });
        }
    };

    Reflect::set(&obj, &"namedCurve".into(), &named_curve.into())
        .map_err(|e| Error::WebCrypto(format!("failed to set namedCurve: {:?}", e)))?;

    Ok(obj)
}

/// Builds a symmetric key algorithm object.
///
/// The algorithm is determined from (in order of priority):
/// 1. The `alg_override` parameter (if provided)
/// 2. The key's `alg` field (if present)
///
/// If neither is available, an error is returned because WebCrypto requires
/// the hash algorithm to be specified at import time for HMAC keys, and a
/// wrong default would cause silent verification failures.
fn build_symmetric_algorithm(
    key: &Key,
    _usage: KeyUsage,
    alg_override: Option<&Algorithm>,
) -> Result<Object> {
    let obj = Object::new();

    // Use the override first, then fall back to the key's own algorithm
    let effective_alg = alg_override.or(key.alg());

    let (alg_name, extra) = match effective_alg {
        Some(Algorithm::Hs256) => ("HMAC", Some(("hash", "SHA-256"))),
        Some(Algorithm::Hs384) => ("HMAC", Some(("hash", "SHA-384"))),
        Some(Algorithm::Hs512) => ("HMAC", Some(("hash", "SHA-512"))),
        // AES-KW and AES-GCM importKey takes no algorithm parameters beyond the name.
        // The key size is determined from the imported key material itself.
        // See W3C WebCrypto spec sections 30.3.4 (AES-KW) and 29.4.4 (AES-GCM).
        Some(Algorithm::A128kw) | Some(Algorithm::A192kw) | Some(Algorithm::A256kw) => {
            ("AES-KW", None)
        }
        Some(Algorithm::A128gcm) | Some(Algorithm::A192gcm) | Some(Algorithm::A256gcm) => {
            ("AES-GCM", None)
        }
        Some(Algorithm::A128cbcHs256)
        | Some(Algorithm::A192cbcHs384)
        | Some(Algorithm::A256cbcHs512) => {
            return Err(Error::UnsupportedForWebCrypto {
                reason: "AES-CBC-HS algorithms (A128CBC-HS256, A192CBC-HS384, A256CBC-HS512) \
                         are composite authenticated encryption algorithms requiring split-key \
                         handling (AES-CBC + HMAC) which WebCrypto does not natively support",
            });
        }
        _ => {
            return Err(Error::WebCrypto(
                "symmetric key import requires an algorithm to determine the operation; \
                 set the `alg` field on the key or use an import function that accepts \
                 an explicit algorithm (e.g., `import_verify_key_for_alg`)"
                    .to_string(),
            ));
        }
    };

    Reflect::set(&obj, &"name".into(), &alg_name.into())
        .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;

    if let Some((prop, val)) = extra {
        debug_assert_eq!(prop, "hash", "only HMAC uses extra parameters");
        let hash_obj = Object::new();
        Reflect::set(&hash_obj, &"name".into(), &val.into())
            .map_err(|e| Error::WebCrypto(format!("failed to set hash name: {:?}", e)))?;
        Reflect::set(&obj, &"hash".into(), &hash_obj.into())
            .map_err(|e| Error::WebCrypto(format!("failed to set hash: {:?}", e)))?;
    }

    Ok(obj)
}

/// Builds a WebCrypto algorithm object for use with `SubtleCrypto.verify()`.
///
/// This is different from the import algorithm: `verify()` requires algorithm-specific
/// parameters like `saltLength` (RSA-PSS) or `hash` (ECDSA), while not needing
/// parameters like `namedCurve` that are only needed during import.
///
/// # Supported Algorithms
///
/// | Algorithm | Verify Object |
/// |-----------|---------------|
/// | RS256/384/512 | `{ name: "RSASSA-PKCS1-v1_5" }` |
/// | PS256/384/512 | `{ name: "RSA-PSS", saltLength }` |
/// | ES256/384/512 | `{ name: "ECDSA", hash }` |
/// | HS256/384/512 | `{ name: "HMAC" }` |
///
/// # Errors
///
/// Returns [`Error::UnsupportedForWebCrypto`] if the algorithm is not supported
/// by WebCrypto (e.g., EdDSA, Ed25519, Ed448, ES256K).
///
/// # Examples
///
/// ```ignore
/// use jwk_simple::{Algorithm, web_crypto};
///
/// let alg = Algorithm::Rs256;
/// let verify_algo = web_crypto::build_verify_algorithm(&alg)?;
///
/// // Use with SubtleCrypto.verify()
/// let subtle = web_crypto::get_subtle_crypto()?;
/// let result = subtle.verify_with_object_and_buffer_source_and_buffer_source(
///     &verify_algo, &crypto_key, &signature, &data,
/// )?;
/// ```
pub fn build_verify_algorithm(alg: &Algorithm) -> Result<Object> {
    let obj = Object::new();

    match alg {
        // RSASSA-PKCS1-v1_5: only needs the algorithm name
        Algorithm::Rs256 | Algorithm::Rs384 | Algorithm::Rs512 => {
            Reflect::set(&obj, &"name".into(), &"RSASSA-PKCS1-v1_5".into())
                .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;
        }

        // RSA-PSS: needs algorithm name and salt length (= hash output size in bytes)
        Algorithm::Ps256 => {
            Reflect::set(&obj, &"name".into(), &"RSA-PSS".into())
                .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;
            Reflect::set(&obj, &"saltLength".into(), &32.into())
                .map_err(|e| Error::WebCrypto(format!("failed to set saltLength: {:?}", e)))?;
        }
        Algorithm::Ps384 => {
            Reflect::set(&obj, &"name".into(), &"RSA-PSS".into())
                .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;
            Reflect::set(&obj, &"saltLength".into(), &48.into())
                .map_err(|e| Error::WebCrypto(format!("failed to set saltLength: {:?}", e)))?;
        }
        Algorithm::Ps512 => {
            Reflect::set(&obj, &"name".into(), &"RSA-PSS".into())
                .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;
            Reflect::set(&obj, &"saltLength".into(), &64.into())
                .map_err(|e| Error::WebCrypto(format!("failed to set saltLength: {:?}", e)))?;
        }

        // ECDSA: needs algorithm name and hash
        Algorithm::Es256 | Algorithm::Es384 | Algorithm::Es512 => {
            Reflect::set(&obj, &"name".into(), &"ECDSA".into())
                .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;

            let hash = match alg {
                Algorithm::Es256 => "SHA-256",
                Algorithm::Es384 => "SHA-384",
                Algorithm::Es512 => "SHA-512",
                _ => unreachable!(),
            };

            let hash_obj = Object::new();
            Reflect::set(&hash_obj, &"name".into(), &hash.into())
                .map_err(|e| Error::WebCrypto(format!("failed to set hash name: {:?}", e)))?;
            Reflect::set(&obj, &"hash".into(), &hash_obj.into())
                .map_err(|e| Error::WebCrypto(format!("failed to set hash: {:?}", e)))?;
        }

        // HMAC: only needs the algorithm name
        Algorithm::Hs256 | Algorithm::Hs384 | Algorithm::Hs512 => {
            Reflect::set(&obj, &"name".into(), &"HMAC".into())
                .map_err(|e| Error::WebCrypto(format!("failed to set algorithm name: {:?}", e)))?;
        }

        _ => {
            return Err(Error::UnsupportedForWebCrypto {
                reason: "algorithm not supported for WebCrypto verify",
            });
        }
    }

    Ok(obj)
}

// ============================================================================
// Key Import Functions
// ============================================================================

/// Imports a JWK as a [`CryptoKey`] for signature verification.
///
/// This requires the key's `alg` field to be set for RSA and HMAC keys, because
/// WebCrypto locks the hash algorithm at import time. EC keys do not require `alg`
/// since the curve already determines the algorithm parameters.
///
/// **For keys without an `alg` field** (common in JWKS from OIDC providers), use
/// [`import_verify_key_for_alg`] instead, passing the algorithm from the JWT header.
///
/// # Supported Key Types
///
/// - RSA public keys (RS256, RS384, RS512, PS256, PS384, PS512) - requires `alg`
/// - EC public keys (P-256, P-384, P-521)
/// - HMAC symmetric keys (HS256, HS384, HS512) - requires `alg`
///
/// # Errors
///
/// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
/// - [`Error::WebCrypto`] if the import operation fails or the key is missing
///   a required `alg` field (RSA/HMAC only)
///
/// # Examples
///
/// ```ignore
/// use jwk_simple::{web_crypto, KeySet};
///
/// let jwks: KeySet = serde_json::from_str(jwks_json)?;
/// let key = jwks.get_by_kid("my-key-id").unwrap();
///
/// // Works when the key has an `alg` field set
/// let crypto_key = web_crypto::import_verify_key(key).await?;
/// ```
pub async fn import_verify_key(key: &Key) -> Result<CryptoKey> {
    import_key_for_usage(key, KeyUsage::Verify).await
}

/// Imports a JWK as a [`CryptoKey`] for signing.
///
/// This requires a private key (RSA or EC with the `d` parameter) and, for RSA
/// and HMAC keys, the key's `alg` field must be set because WebCrypto locks the
/// hash algorithm at import time.
///
/// **For keys without an `alg` field**, use [`import_sign_key_for_alg`] instead.
///
/// # Errors
///
/// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
/// - [`Error::WebCrypto`] if the import operation fails (e.g., missing private key
///   or missing `alg` field for RSA/HMAC)
///
/// # Examples
///
/// ```ignore
/// let crypto_key = web_crypto::import_sign_key(&private_key).await?;
/// ```
pub async fn import_sign_key(key: &Key) -> Result<CryptoKey> {
    import_key_for_usage(key, KeyUsage::Sign).await
}

/// Imports a JWK as a [`CryptoKey`] for encryption.
///
/// This requires the key's `alg` field to be set for RSA and symmetric keys,
/// because WebCrypto requires the import algorithm to be specified.
/// For keys without an `alg` field, use [`import_key_for_usage_with_alg`]
/// with [`KeyUsage::Encrypt`] and an explicit algorithm.
///
/// # Supported Key Types
///
/// - RSA public keys (RSA-OAEP)
/// - Symmetric keys (AES-GCM)
///
/// # Errors
///
/// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
/// - [`Error::WebCrypto`] if the import operation fails (including missing `alg`)
pub async fn import_encrypt_key(key: &Key) -> Result<CryptoKey> {
    if matches!(key.params(), KeyParams::Ec(_)) {
        return Err(Error::UnsupportedForWebCrypto {
            reason: "EC keys do not support direct encryption; \
                     use ECDH key agreement (deriveKey/deriveBits) instead",
        });
    }
    import_key_for_usage(key, KeyUsage::Encrypt).await
}

/// Imports a JWK as a [`CryptoKey`] for decryption.
///
/// This requires a private key (RSA) or symmetric key.
/// This also requires the key's `alg` field to be set for RSA and symmetric keys,
/// because WebCrypto requires the import algorithm to be specified.
/// For keys without an `alg` field, use [`import_key_for_usage_with_alg`]
/// with [`KeyUsage::Decrypt`] and an explicit algorithm.
///
/// # Errors
///
/// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
/// - [`Error::WebCrypto`] if the import operation fails (including missing `alg`)
pub async fn import_decrypt_key(key: &Key) -> Result<CryptoKey> {
    if matches!(key.params(), KeyParams::Ec(_)) {
        return Err(Error::UnsupportedForWebCrypto {
            reason: "EC keys do not support direct decryption; \
                     use ECDH key agreement (deriveKey/deriveBits) instead",
        });
    }
    import_key_for_usage(key, KeyUsage::Decrypt).await
}

/// Imports a JWK as a [`CryptoKey`] for key wrapping.
///
/// This requires the key's `alg` field to be set for RSA and symmetric keys,
/// because WebCrypto requires the import algorithm to be specified.
/// For keys without an `alg` field, use [`import_key_for_usage_with_alg`]
/// with [`KeyUsage::WrapKey`] and an explicit algorithm.
///
/// # Supported Key Types
///
/// - RSA public keys (RSA-OAEP)
/// - Symmetric keys (AES-KW)
pub async fn import_wrap_key(key: &Key) -> Result<CryptoKey> {
    if matches!(key.params(), KeyParams::Ec(_)) {
        return Err(Error::UnsupportedForWebCrypto {
            reason: "EC keys do not support direct key wrapping; \
                     use ECDH key agreement (deriveKey/deriveBits) instead",
        });
    }
    import_key_for_usage(key, KeyUsage::WrapKey).await
}

/// Imports a JWK as a [`CryptoKey`] for key unwrapping.
///
/// This requires the key's `alg` field to be set for RSA and symmetric keys,
/// because WebCrypto requires the import algorithm to be specified.
/// For keys without an `alg` field, use [`import_key_for_usage_with_alg`]
/// with [`KeyUsage::UnwrapKey`] and an explicit algorithm.
///
/// # Supported Key Types
///
/// - RSA private keys (RSA-OAEP)
/// - Symmetric keys (AES-KW)
pub async fn import_unwrap_key(key: &Key) -> Result<CryptoKey> {
    if matches!(key.params(), KeyParams::Ec(_)) {
        return Err(Error::UnsupportedForWebCrypto {
            reason: "EC keys do not support direct key unwrapping; \
                     use ECDH key agreement (deriveKey/deriveBits) instead",
        });
    }
    import_key_for_usage(key, KeyUsage::UnwrapKey).await
}

/// Imports a JWK as a [`CryptoKey`] for signature verification with an explicit algorithm.
///
/// This is useful when the key's `alg` field is absent (common in JWKS from OIDC providers).
/// WebCrypto locks the hash algorithm at import time, so the algorithm must be known
/// before importing the key. Using this function avoids a potential mismatch between
/// the import algorithm and the verification algorithm.
///
/// # Supported Algorithms
///
/// - RSA: RS256, RS384, RS512, PS256, PS384, PS512
/// - EC: ES256, ES384, ES512
/// - HMAC: HS256, HS384, HS512
///
/// # Errors
///
/// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
/// - [`Error::WebCrypto`] if the import operation fails
///
/// # Examples
///
/// ```ignore
/// use jwk_simple::{Algorithm, web_crypto, KeySet};
///
/// let jwks: KeySet = serde_json::from_str(jwks_json)?;
/// let key = jwks.get_by_kid("my-key-id").unwrap();
/// // Use the algorithm from the JWT header, not the key
/// let crypto_key = web_crypto::import_verify_key_for_alg(key, &Algorithm::Rs384).await?;
/// ```
pub async fn import_verify_key_for_alg(key: &Key, alg: &Algorithm) -> Result<CryptoKey> {
    import_key_for_usage_with_alg(key, KeyUsage::Verify, alg).await
}

/// Imports a JWK as a [`CryptoKey`] for signing with an explicit algorithm.
///
/// This is useful when the key's `alg` field is absent. See
/// [`import_verify_key_for_alg`] for more details on why this matters.
///
/// # Errors
///
/// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
/// - [`Error::WebCrypto`] if the import operation fails
pub async fn import_sign_key_for_alg(key: &Key, alg: &Algorithm) -> Result<CryptoKey> {
    import_key_for_usage_with_alg(key, KeyUsage::Sign, alg).await
}

/// Imports a JWK as a [`CryptoKey`] for a typed key usage.
///
/// The key must have an `alg` field set so that the correct WebCrypto algorithm
/// parameters can be determined. For RSA and HMAC keys without an `alg` field,
/// use [`import_key_for_usage_with_alg`] instead.
///
/// # Errors
///
/// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
/// - [`Error::WebCrypto`] if the import operation fails or the key is missing
///   a required `alg` field
pub async fn import_key_for_usage(key: &Key, usage: KeyUsage) -> Result<CryptoKey> {
    validate_key_for_webcrypto_usage(key, usage)?;

    let jwk = web_sys::JsonWebKey::try_from(key)?;
    let algorithm = build_algorithm_object(key, usage)?;

    import_crypto_key(jwk, &algorithm, usage_strings_for_usage(usage)).await
}

/// Imports a JWK as a [`CryptoKey`] for a typed key usage and an explicit algorithm.
///
/// The `alg` parameter overrides the key's own `alg`
/// field, ensuring the correct WebCrypto algorithm parameters are used at import time.
///
/// # Errors
///
/// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
/// - [`Error::WebCrypto`] if the import operation fails
pub async fn import_key_for_usage_with_alg(
    key: &Key,
    usage: KeyUsage,
    alg: &Algorithm,
) -> Result<CryptoKey> {
    validate_key_for_webcrypto_usage_with_alg(key, usage, alg)?;
    let jwk = web_sys::JsonWebKey::try_from(key)?;

    // Override the JWK's `alg` field to match the explicit algorithm.
    // WebCrypto validates that the JWK `alg` (if present) is consistent with
    // the algorithm parameter passed to importKey(). Without this override,
    // importing a key whose `alg` differs from the explicit algorithm would
    // fail with a DataError.
    jwk.set_alg(alg.as_str());

    let algorithm = build_algorithm_object_for_alg(key, alg, usage)?;

    import_crypto_key(jwk, &algorithm, usage_strings_for_usage(usage)).await
}

/// Internal helper that performs the actual SubtleCrypto.importKey() call.
async fn import_crypto_key(
    jwk: web_sys::JsonWebKey,
    algorithm: &Object,
    usages: &[&str],
) -> Result<CryptoKey> {
    let key_usages = Array::new();
    for u in usages {
        key_usages.push(&JsValue::from_str(u));
    }

    let subtle = get_subtle_crypto()?;

    // Import the key
    let promise = subtle
        .import_key_with_object("jwk", &jwk.into(), algorithm, false, &key_usages)
        .map_err(|e| Error::WebCrypto(format!("import_key failed: {:?}", e)))?;

    let result = JsFuture::from(promise)
        .await
        .map_err(|e| Error::WebCrypto(format!("import_key promise rejected: {:?}", e)))?;

    Ok(result.unchecked_into())
}

// ============================================================================
// Convenience Methods on Key
// ============================================================================

impl Key {
    /// Returns `true` if this key can be used with WebCrypto.
    ///
    /// OKP keys and secp256k1 EC keys are not supported by WebCrypto.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// if key.is_web_crypto_compatible() {
    ///     let crypto_key = key.import_as_verify_key_for_alg(&alg).await?;
    /// }
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "web-crypto")))]
    pub fn is_web_crypto_compatible(&self) -> bool {
        validate_webcrypto_support(self).is_ok()
    }

    /// Imports this key as a [`CryptoKey`] for signature verification.
    ///
    /// RSA and HMAC keys must have their `alg` field set. For keys without `alg`
    /// (common in JWKS from OIDC providers), use
    /// [`import_as_verify_key_for_alg`](Key::import_as_verify_key_for_alg) instead.
    ///
    /// # Errors
    ///
    /// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
    /// - [`Error::WebCrypto`] if the import operation fails or the key is missing
    ///   a required `alg` field (RSA/HMAC only)
    #[cfg_attr(docsrs, doc(cfg(feature = "web-crypto")))]
    pub async fn import_as_verify_key(&self) -> Result<CryptoKey> {
        import_verify_key(self).await
    }

    /// Imports this key as a [`CryptoKey`] for signing.
    ///
    /// RSA and HMAC keys must have their `alg` field set. For keys without `alg`,
    /// use [`import_as_sign_key_for_alg`](Key::import_as_sign_key_for_alg) instead.
    ///
    /// # Errors
    ///
    /// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
    /// - [`Error::WebCrypto`] if the import operation fails or the key is missing
    ///   a required `alg` field (RSA/HMAC only)
    #[cfg_attr(docsrs, doc(cfg(feature = "web-crypto")))]
    pub async fn import_as_sign_key(&self) -> Result<CryptoKey> {
        import_sign_key(self).await
    }

    /// Imports this key as a [`CryptoKey`] for encryption.
    ///
    /// # Errors
    ///
    /// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
    /// - [`Error::WebCrypto`] if the import operation fails
    #[cfg_attr(docsrs, doc(cfg(feature = "web-crypto")))]
    pub async fn import_as_encrypt_key(&self) -> Result<CryptoKey> {
        import_encrypt_key(self).await
    }

    /// Imports this key as a [`CryptoKey`] for decryption.
    ///
    /// # Errors
    ///
    /// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
    /// - [`Error::WebCrypto`] if the import operation fails
    #[cfg_attr(docsrs, doc(cfg(feature = "web-crypto")))]
    pub async fn import_as_decrypt_key(&self) -> Result<CryptoKey> {
        import_decrypt_key(self).await
    }

    /// Imports this key as a [`CryptoKey`] for signature verification with an explicit algorithm.
    ///
    /// This is useful when the key's `alg` field is absent (common in JWKS from
    /// OIDC providers). WebCrypto locks the hash algorithm at import time, so the
    /// algorithm must be known before importing. The `alg` parameter overrides the
    /// key's own `alg` field.
    ///
    /// # Errors
    ///
    /// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
    /// - [`Error::WebCrypto`] if the import operation fails
    #[cfg_attr(docsrs, doc(cfg(feature = "web-crypto")))]
    pub async fn import_as_verify_key_for_alg(&self, alg: &Algorithm) -> Result<CryptoKey> {
        import_verify_key_for_alg(self, alg).await
    }

    /// Imports this key as a [`CryptoKey`] for signing with an explicit algorithm.
    ///
    /// This is useful when the key's `alg` field is absent. See
    /// [`Key::import_as_verify_key_for_alg`] for more details.
    ///
    /// # Errors
    ///
    /// - [`Error::UnsupportedForWebCrypto`] if the key type is not supported
    /// - [`Error::WebCrypto`] if the import operation fails
    #[cfg_attr(docsrs, doc(cfg(feature = "web-crypto")))]
    pub async fn import_as_sign_key_for_alg(&self, alg: &Algorithm) -> Result<CryptoKey> {
        import_sign_key_for_alg(self, alg).await
    }
}

// ============================================================================
// Tests
// ============================================================================

// Validation tests that can run on any target (no web_sys dependencies).
#[cfg(test)]
mod validation_tests {
    use super::*;
    use crate::jwks::KeySet;

    const RFC_RSA_PUBLIC_KEY: &str = r#"{
        "kty": "RSA",
        "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
        "e": "AQAB"
    }"#;

    const RFC_EC_P256_PUBLIC_KEY: &str = r#"{
        "kty": "EC",
        "crv": "P-256",
        "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
        "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"
    }"#;

    const EC_SECP256K1_KEY: &str = r#"{
        "kty": "EC",
        "crv": "secp256k1",
        "x": "WbbXwISW8TLWM3IDLGm1cX_3IrYgWl_bzcLe0tSCDj4",
        "y": "KGk8DRQHPeV4S3Oq2jVJLNSV_3ngGgbfHTKsS5aw30c"
    }"#;

    const OKP_ED25519_KEY: &str = r#"{
        "kty": "OKP",
        "crv": "Ed25519",
        "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"
    }"#;

    const SYMMETRIC_KEY: &str = r#"{
        "kty": "oct",
        "k": "AyM32w-8O0TGsGDYX0MlWy-9XQP-xrryrP7gkXKfY5WhoLxmT3fzfVr7LXqgDDFSfowWBY-u6bSH5f9kBZ_n7Q",
        "alg": "HS256"
    }"#;

    #[test]
    fn test_validate_rsa_supported() {
        let key: Key = serde_json::from_str(RFC_RSA_PUBLIC_KEY).unwrap();
        assert!(validate_webcrypto_support(&key).is_ok());
    }

    #[test]
    fn test_validate_ec_p256_supported() {
        let key: Key = serde_json::from_str(RFC_EC_P256_PUBLIC_KEY).unwrap();
        assert!(validate_webcrypto_support(&key).is_ok());
    }

    #[test]
    fn test_validate_symmetric_supported() {
        let key: Key = serde_json::from_str(SYMMETRIC_KEY).unwrap();
        assert!(validate_webcrypto_support(&key).is_ok());
    }

    #[test]
    fn test_validate_okp_unsupported() {
        let key: Key = serde_json::from_str(OKP_ED25519_KEY).unwrap();
        let result = validate_webcrypto_support(&key);
        assert!(matches!(result, Err(Error::UnsupportedForWebCrypto { .. })));
    }

    #[test]
    fn test_validate_secp256k1_unsupported() {
        let key: Key = serde_json::from_str(EC_SECP256K1_KEY).unwrap();
        let result = validate_webcrypto_support(&key);
        assert!(matches!(result, Err(Error::UnsupportedForWebCrypto { .. })));
    }

    #[test]
    fn test_is_web_crypto_compatible_rsa() {
        let key: Key = serde_json::from_str(RFC_RSA_PUBLIC_KEY).unwrap();
        assert!(key.is_web_crypto_compatible());
    }

    #[test]
    fn test_is_web_crypto_compatible_okp() {
        let key: Key = serde_json::from_str(OKP_ED25519_KEY).unwrap();
        assert!(!key.is_web_crypto_compatible());
    }

    #[test]
    fn test_is_web_crypto_compatible_secp256k1() {
        let key: Key = serde_json::from_str(EC_SECP256K1_KEY).unwrap();
        assert!(!key.is_web_crypto_compatible());
    }

    #[test]
    fn test_usage_algorithm_compatibility_rejects_mismatch() {
        let result = validate_usage_algorithm_compatibility(KeyUsage::Encrypt, &Algorithm::Rs256);
        assert!(matches!(result, Err(Error::UnsupportedForWebCrypto { .. })));

        let result =
            validate_usage_algorithm_compatibility(KeyUsage::Verify, &Algorithm::RsaOaep256);
        assert!(matches!(result, Err(Error::UnsupportedForWebCrypto { .. })));
    }

    #[test]
    fn test_usage_algorithm_compatibility_accepts_valid_pairs() {
        assert!(
            validate_usage_algorithm_compatibility(KeyUsage::Verify, &Algorithm::Rs256).is_ok()
        );
        assert!(
            validate_usage_algorithm_compatibility(KeyUsage::Encrypt, &Algorithm::RsaOaep256)
                .is_ok()
        );
        assert!(
            validate_usage_algorithm_compatibility(KeyUsage::WrapKey, &Algorithm::A128kw).is_ok()
        );
    }

    #[test]
    fn test_import_usage_validation_enforces_metadata_when_alg_present() {
        let key: Key = serde_json::from_str(SYMMETRIC_KEY).unwrap();
        let key = key.with_key_ops([crate::KeyOperation::Sign, crate::KeyOperation::Sign]);

        let result = validate_key_for_webcrypto_usage(&key, KeyUsage::Sign);
        assert!(result.is_err(), "duplicate key_ops must be rejected");
    }

    #[test]
    fn test_validate_key_for_webcrypto_usage_rejects_incompatible_use() {
        let json = r#"{
            "kty": "RSA",
            "use": "enc",
            "alg": "RS256",
            "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
            "e": "AQAB"
        }"#;

        let key: Key = serde_json::from_str(json).unwrap();
        let result = validate_key_for_webcrypto_usage(&key, KeyUsage::Verify);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_key_for_webcrypto_usage_allows_missing_optional_metadata() {
        let json = r#"{
            "kty": "RSA",
            "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
            "e": "AQAB"
        }"#;

        let key: Key = serde_json::from_str(json).unwrap();
        let result = validate_key_for_webcrypto_usage(&key, KeyUsage::Verify);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_key_for_webcrypto_usage_rejects_incompatible_use_without_alg() {
        let json = r#"{
            "kty": "RSA",
            "use": "enc",
            "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
            "e": "AQAB"
        }"#;

        let key: Key = serde_json::from_str(json).unwrap();
        let result = validate_key_for_webcrypto_usage(&key, KeyUsage::Verify);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_key_for_webcrypto_usage_with_alg_allows_declared_algorithm_override() {
        // SYMMETRIC_KEY declares alg: HS256 but the caller explicitly requests
        // HS384.  validate_key_for_webcrypto_usage_with_alg uses the override
        // path which intentionally skips the declared-algorithm-match check,
        // so this must succeed (the 512-bit key satisfies HS384's 384-bit
        // minimum).
        let key: Key = serde_json::from_str(SYMMETRIC_KEY).unwrap();

        let result =
            validate_key_for_webcrypto_usage_with_alg(&key, KeyUsage::Verify, &Algorithm::Hs384);
        assert!(
            result.is_ok(),
            "explicit alg override should skip declared-algorithm mismatch check: {result:?}"
        );
    }

    #[test]
    fn test_validate_key_for_webcrypto_usage_rejects_public_sign_key_without_alg() {
        let json = r#"{
            "kty": "RSA",
            "use": "sig",
            "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
            "e": "AQAB"
        }"#;

        let key: Key = serde_json::from_str(json).unwrap();
        let result = validate_key_for_webcrypto_usage(&key, KeyUsage::Sign);
        assert!(result.is_err());
    }

    #[test]
    fn test_select_verify_key_strict_for_web_crypto_flow() {
        let json = r#"{"keys": [
            {"kty": "RSA", "kid": "rsa-verify", "use": "sig", "alg": "RS256", "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw", "e": "AQAB"}
        ]}"#;

        let jwks: KeySet = serde_json::from_str(json).unwrap();
        let key = jwks
            .selector(&[Algorithm::Rs256])
            .select(KeyMatcher::new(KeyOperation::Verify, Algorithm::Rs256).with_kid("rsa-verify"))
            .unwrap();

        assert_eq!(key.kid(), Some("rsa-verify"));
    }

    #[test]
    fn test_select_signing_key_strict_for_web_crypto_flow() {
        let json = r#"{"keys": [
            {"kty": "EC", "kid": "ec-sign", "use": "sig", "alg": "ES256", "crv": "P-256", "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", "d": "870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE"}
        ]}"#;

        let jwks: KeySet = serde_json::from_str(json).unwrap();
        let key = jwks
            .selector(&[])
            .select(KeyMatcher::new(KeyOperation::Sign, Algorithm::Es256).with_kid("ec-sign"))
            .unwrap();

        assert_eq!(key.kid(), Some("ec-sign"));
    }
}

// Tests that use web_sys types - only compiled for wasm32 targets.
// For WASM integration tests, see tests/web_crypto.rs which uses wasm_bindgen_test.
#[cfg(all(test, target_arch = "wasm32"))]
mod tests {
    use super::*;

    // Test RSA public key from RFC 7517 Appendix A.1
    const RFC_RSA_PUBLIC_KEY: &str = r#"{
        "kty": "RSA",
        "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
        "e": "AQAB"
    }"#;

    // Test EC P-256 public key from RFC 7517 Appendix A.1
    const RFC_EC_P256_PUBLIC_KEY: &str = r#"{
        "kty": "EC",
        "crv": "P-256",
        "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
        "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"
    }"#;

    // Test EC secp256k1 key (unsupported)
    const EC_SECP256K1_KEY: &str = r#"{
        "kty": "EC",
        "crv": "secp256k1",
        "x": "WbbXwISW8TLWM3IDLGm1cX_3IrYgWl_bzcLe0tSCDj4",
        "y": "KGk8DRQHPeV4S3Oq2jVJLNSV_3ngGgbfHTKsS5aw30c"
    }"#;

    // Test OKP Ed25519 key (unsupported)
    const OKP_ED25519_KEY: &str = r#"{
        "kty": "OKP",
        "crv": "Ed25519",
        "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"
    }"#;

    // Test symmetric key
    const SYMMETRIC_KEY: &str = r#"{
        "kty": "oct",
        "k": "AyM32w-8O0TGsGDYX0MlWy-9XQP-xrryrP7gkXKfY5WhoLxmT3fzfVr7LXqgDDFSfowWBY-u6bSH5f9kBZ_n7Q",
        "alg": "HS256"
    }"#;

    #[test]
    fn test_rsa_key_to_json_web_key() {
        let key: Key = serde_json::from_str(RFC_RSA_PUBLIC_KEY).unwrap();
        let jwk = web_sys::JsonWebKey::try_from(&key).unwrap();
        assert_eq!(jwk.get_kty(), "RSA");
        assert!(jwk.get_n().is_some());
        assert!(jwk.get_e().is_some());
        assert!(jwk.get_d().is_none()); // Public key only
    }

    #[test]
    fn test_ec_p256_key_to_json_web_key() {
        let key: Key = serde_json::from_str(RFC_EC_P256_PUBLIC_KEY).unwrap();
        let jwk = web_sys::JsonWebKey::try_from(&key).unwrap();
        assert_eq!(jwk.get_kty(), "EC");
        assert_eq!(jwk.get_crv(), Some("P-256".to_string()));
        assert!(jwk.get_x().is_some());
        assert!(jwk.get_y().is_some());
    }

    #[test]
    fn test_symmetric_key_to_json_web_key() {
        let key: Key = serde_json::from_str(SYMMETRIC_KEY).unwrap();
        let jwk = web_sys::JsonWebKey::try_from(&key).unwrap();
        assert_eq!(jwk.get_kty(), "oct");
        assert!(jwk.get_k().is_some());
    }

    #[test]
    fn test_okp_key_unsupported() {
        let key: Key = serde_json::from_str(OKP_ED25519_KEY).unwrap();
        let result = web_sys::JsonWebKey::try_from(&key);
        assert!(matches!(result, Err(Error::UnsupportedForWebCrypto { .. })));
    }

    #[test]
    fn test_secp256k1_key_unsupported() {
        let key: Key = serde_json::from_str(EC_SECP256K1_KEY).unwrap();
        let result = web_sys::JsonWebKey::try_from(&key);
        assert!(matches!(result, Err(Error::UnsupportedForWebCrypto { .. })));
    }

    #[test]
    fn test_is_web_crypto_compatible() {
        let rsa_key: Key = serde_json::from_str(RFC_RSA_PUBLIC_KEY).unwrap();
        assert!(rsa_key.is_web_crypto_compatible());

        let ec_key: Key = serde_json::from_str(RFC_EC_P256_PUBLIC_KEY).unwrap();
        assert!(ec_key.is_web_crypto_compatible());

        let okp_key: Key = serde_json::from_str(OKP_ED25519_KEY).unwrap();
        assert!(!okp_key.is_web_crypto_compatible());

        let secp256k1_key: Key = serde_json::from_str(EC_SECP256K1_KEY).unwrap();
        assert!(!secp256k1_key.is_web_crypto_compatible());
    }

    #[test]
    fn test_validate_webcrypto_support_rsa() {
        let key: Key = serde_json::from_str(RFC_RSA_PUBLIC_KEY).unwrap();
        assert!(validate_webcrypto_support(&key).is_ok());
    }

    #[test]
    fn test_validate_webcrypto_support_ec_p256() {
        let key: Key = serde_json::from_str(RFC_EC_P256_PUBLIC_KEY).unwrap();
        assert!(validate_webcrypto_support(&key).is_ok());
    }

    #[test]
    fn test_validate_webcrypto_support_symmetric() {
        let key: Key = serde_json::from_str(SYMMETRIC_KEY).unwrap();
        assert!(validate_webcrypto_support(&key).is_ok());
    }

    #[test]
    fn test_build_rsa_algorithm_with_explicit_alg() {
        let key: Key = serde_json::from_str(RFC_RSA_PUBLIC_KEY).unwrap();
        let alg =
            build_algorithm_object_for_alg(&key, &Algorithm::Rs256, KeyUsage::Verify).unwrap();

        let name = Reflect::get(&alg, &"name".into()).unwrap();
        assert_eq!(name.as_string().unwrap(), "RSASSA-PKCS1-v1_5");
    }

    #[test]
    fn test_build_rsa_algorithm_without_alg_errors() {
        let key: Key = serde_json::from_str(RFC_RSA_PUBLIC_KEY).unwrap();
        let result = build_algorithm_object(&key, KeyUsage::Verify);
        assert!(result.is_err(), "RSA key without alg should error");
    }

    #[test]
    fn test_build_ec_algorithm() {
        let key: Key = serde_json::from_str(RFC_EC_P256_PUBLIC_KEY).unwrap();
        let alg = build_algorithm_object(&key, KeyUsage::Verify).unwrap();

        let name = Reflect::get(&alg, &"name".into()).unwrap();
        assert_eq!(name.as_string().unwrap(), "ECDSA");

        let curve = Reflect::get(&alg, &"namedCurve".into()).unwrap();
        assert_eq!(curve.as_string().unwrap(), "P-256");
    }

    #[test]
    fn test_build_hmac_algorithm() {
        let key: Key = serde_json::from_str(SYMMETRIC_KEY).unwrap();
        let alg = build_algorithm_object(&key, KeyUsage::Sign).unwrap();

        let name = Reflect::get(&alg, &"name".into()).unwrap();
        assert_eq!(name.as_string().unwrap(), "HMAC");
    }

    #[test]
    fn test_build_verify_algorithm_rs256() {
        let alg = Algorithm::Rs256;
        let obj = build_verify_algorithm(&alg).unwrap();

        let name = Reflect::get(&obj, &"name".into()).unwrap();
        assert_eq!(name.as_string().unwrap(), "RSASSA-PKCS1-v1_5");

        // RSASSA-PKCS1-v1_5 verify does NOT need hash
        let hash = Reflect::get(&obj, &"hash".into()).unwrap();
        assert!(hash.is_undefined());
    }

    #[test]
    fn test_build_verify_algorithm_ps256() {
        let alg = Algorithm::Ps256;
        let obj = build_verify_algorithm(&alg).unwrap();

        let name = Reflect::get(&obj, &"name".into()).unwrap();
        assert_eq!(name.as_string().unwrap(), "RSA-PSS");

        let salt_length = Reflect::get(&obj, &"saltLength".into()).unwrap();
        assert_eq!(salt_length.as_f64().unwrap() as u32, 32);
    }

    #[test]
    fn test_build_verify_algorithm_ps384() {
        let alg = Algorithm::Ps384;
        let obj = build_verify_algorithm(&alg).unwrap();

        let salt_length = Reflect::get(&obj, &"saltLength".into()).unwrap();
        assert_eq!(salt_length.as_f64().unwrap() as u32, 48);
    }

    #[test]
    fn test_build_verify_algorithm_ps512() {
        let alg = Algorithm::Ps512;
        let obj = build_verify_algorithm(&alg).unwrap();

        let salt_length = Reflect::get(&obj, &"saltLength".into()).unwrap();
        assert_eq!(salt_length.as_f64().unwrap() as u32, 64);
    }

    #[test]
    fn test_build_verify_algorithm_es256() {
        let alg = Algorithm::Es256;
        let obj = build_verify_algorithm(&alg).unwrap();

        let name = Reflect::get(&obj, &"name".into()).unwrap();
        assert_eq!(name.as_string().unwrap(), "ECDSA");

        let hash = Reflect::get(&obj, &"hash".into()).unwrap();
        let hash_name = Reflect::get(&hash, &"name".into()).unwrap();
        assert_eq!(hash_name.as_string().unwrap(), "SHA-256");
    }

    #[test]
    fn test_build_verify_algorithm_es384() {
        let alg = Algorithm::Es384;
        let obj = build_verify_algorithm(&alg).unwrap();

        let hash = Reflect::get(&obj, &"hash".into()).unwrap();
        let hash_name = Reflect::get(&hash, &"name".into()).unwrap();
        assert_eq!(hash_name.as_string().unwrap(), "SHA-384");
    }

    #[test]
    fn test_build_verify_algorithm_es512() {
        let alg = Algorithm::Es512;
        let obj = build_verify_algorithm(&alg).unwrap();

        let hash = Reflect::get(&obj, &"hash".into()).unwrap();
        let hash_name = Reflect::get(&hash, &"name".into()).unwrap();
        assert_eq!(hash_name.as_string().unwrap(), "SHA-512");
    }

    #[test]
    fn test_build_verify_algorithm_hs256() {
        let alg = Algorithm::Hs256;
        let obj = build_verify_algorithm(&alg).unwrap();

        let name = Reflect::get(&obj, &"name".into()).unwrap();
        assert_eq!(name.as_string().unwrap(), "HMAC");
    }

    #[test]
    fn test_build_verify_algorithm_unsupported() {
        let alg = Algorithm::EdDsa;
        let result = build_verify_algorithm(&alg);
        assert!(result.is_err());

        let alg = Algorithm::Ed25519;
        let result = build_verify_algorithm(&alg);
        assert!(result.is_err());

        let alg = Algorithm::Ed448;
        let result = build_verify_algorithm(&alg);
        assert!(result.is_err());
    }
}