moq-token 0.5.14

Media over QUIC - Token Generation and Validation
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
use crate::error::KeyError;
use crate::generate::generate;
use crate::{Algorithm, Claims};
use base64::Engine;
use elliptic_curve::SecretKey;
use elliptic_curve::pkcs8::EncodePrivateKey;
use jsonwebtoken::{DecodingKey, EncodingKey, Header};
use rsa::BigUint;
use rsa::pkcs1::EncodeRsaPrivateKey;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::sync::OnceLock;
use std::{collections::HashSet, fmt, path::Path as StdPath};

/// Cryptographic operations that a key can perform.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[serde(rename_all = "camelCase")]
pub enum KeyOperation {
	Sign,
	Verify,
	Decrypt,
	Encrypt,
}

/// <https://datatracker.ietf.org/doc/html/rfc7518#section-6>
#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "kty")]
pub enum KeyType {
	/// <https://datatracker.ietf.org/doc/html/rfc7518#section-6.2>
	EC {
		#[serde(rename = "crv")]
		curve: EllipticCurve,
		/// The X-coordinate of an EC key
		#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
		x: Vec<u8>,
		/// The Y-coordinate of an EC key
		#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
		y: Vec<u8>,
		/// The private value of an EC key
		#[serde(
			default,
			skip_serializing_if = "Option::is_none",
			serialize_with = "serialize_base64url_optional",
			deserialize_with = "deserialize_base64url_optional"
		)]
		d: Option<Vec<u8>>,
	},
	/// <https://datatracker.ietf.org/doc/html/rfc7518#section-6.3>
	RSA {
		#[serde(flatten)]
		public: RsaPublicKey,
		#[serde(flatten, skip_serializing_if = "Option::is_none")]
		private: Option<RsaPrivateKey>,
	},
	/// <https://datatracker.ietf.org/doc/html/rfc7518#section-6.4>
	#[serde(rename = "oct")]
	OCT {
		/// The secret key as base64url (unpadded).
		#[serde(
			rename = "k",
			default,
			serialize_with = "serialize_base64url",
			deserialize_with = "deserialize_base64url"
		)]
		secret: Vec<u8>,
	},
	/// <https://datatracker.ietf.org/doc/html/rfc8037#section-2>
	OKP {
		#[serde(rename = "crv")]
		curve: EllipticCurve,
		#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
		x: Vec<u8>,
		#[serde(
			rename = "d",
			default,
			skip_serializing_if = "Option::is_none",
			serialize_with = "serialize_base64url_optional",
			deserialize_with = "deserialize_base64url_optional"
		)]
		d: Option<Vec<u8>>,
	},
}

/// Supported elliptic curves for EC and OKP key types.
///
/// See <https://datatracker.ietf.org/doc/html/rfc7518#section-6.2.1.1>
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
pub enum EllipticCurve {
	#[serde(rename = "P-256")]
	P256,
	#[serde(rename = "P-384")]
	P384,
	// jsonwebtoken doesn't support the ES512 algorithm, so we can't implement this
	// #[serde(rename = "P-521")]
	// P521,
	#[serde(rename = "Ed25519")]
	Ed25519,
}

/// RSA public key parameters.
///
/// See <https://datatracker.ietf.org/doc/html/rfc7518#section-6.3.1>
#[derive(Clone, Serialize, Deserialize)]
pub struct RsaPublicKey {
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub n: Vec<u8>,
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub e: Vec<u8>,
}

/// RSA private key parameters.
///
/// See <https://datatracker.ietf.org/doc/html/rfc7518#section-6.3.2>
#[derive(Clone, Serialize, Deserialize)]
pub struct RsaPrivateKey {
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub d: Vec<u8>,
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub p: Vec<u8>,
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub q: Vec<u8>,
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub dp: Vec<u8>,
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub dq: Vec<u8>,
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub qi: Vec<u8>,
	#[serde(skip_serializing_if = "Option::is_none")]
	pub oth: Option<Vec<RsaAdditionalPrime>>,
}

/// Additional prime information for multi-prime RSA keys.
#[derive(Clone, Serialize, Deserialize)]
pub struct RsaAdditionalPrime {
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub r: Vec<u8>,
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub d: Vec<u8>,
	#[serde(serialize_with = "serialize_base64url", deserialize_with = "deserialize_base64url")]
	pub t: Vec<u8>,
}

/// JWK, almost to spec (<https://datatracker.ietf.org/doc/html/rfc7517>) but not quite the same
/// because it's annoying to implement.
#[derive(Clone, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub struct Key {
	/// The algorithm used by the key.
	#[serde(rename = "alg")]
	pub algorithm: Algorithm,

	/// The operations that the key can perform.
	#[serde(rename = "key_ops")]
	pub operations: HashSet<KeyOperation>,

	/// Defaults to KeyType::OCT
	#[serde(flatten)]
	pub key: KeyType,

	/// The key ID, useful for rotating keys.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub kid: Option<crate::KeyId>,

	// Cached for performance reasons, unfortunately.
	#[serde(skip)]
	pub(crate) decode: OnceLock<DecodingKey>,

	#[serde(skip)]
	pub(crate) encode: OnceLock<EncodingKey>,
}

impl<'de> Deserialize<'de> for Key {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		let mut value = serde_json::Value::deserialize(deserializer)?;

		// Normally the "kty" parameter is required in a JWK: https://datatracker.ietf.org/doc/html/rfc7517#section-4.1
		// But for backwards compatibility we need to default to "oct" because in a previous
		// implementation the parameter was omitted, and we want to keep previously generated tokens valid
		if let Some(obj) = value.as_object_mut()
			&& !obj.contains_key("kty")
		{
			obj.insert("kty".to_string(), serde_json::Value::String("oct".to_string()));
		}

		Self::deserialize(value).map_err(serde::de::Error::custom)
	}
}

impl Serialize for Key {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		Self::serialize(self, serializer)
	}
}

impl fmt::Debug for Key {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("Key")
			.field("algorithm", &self.algorithm)
			.field("operations", &self.operations)
			.field("kid", &self.kid)
			.finish()
	}
}

impl Key {
	#[allow(clippy::should_implement_trait)]
	pub fn from_str(s: &str) -> crate::Result<Self> {
		Ok(serde_json::from_str(s)?)
	}

	/// Load a key from a file, auto-detecting JSON or base64url encoding.
	pub fn from_file<P: AsRef<StdPath>>(path: P) -> crate::Result<Self> {
		let contents = std::fs::read_to_string(&path)?;
		Self::from_encoded(&contents)
	}

	/// Async version of [`from_file`](Self::from_file), using `tokio::fs`.
	#[cfg(feature = "tokio")]
	pub async fn from_file_async<P: AsRef<StdPath>>(path: P) -> crate::Result<Self> {
		let contents = tokio::fs::read_to_string(path).await?;
		Self::from_encoded(&contents)
	}

	/// Parse a key from a string, auto-detecting JSON or base64url encoding.
	fn from_encoded(contents: &str) -> crate::Result<Self> {
		let contents = contents.trim();
		if contents.starts_with('{') {
			Ok(serde_json::from_str(contents)?)
		} else {
			let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(contents)?;
			let json = String::from_utf8(decoded)?;
			Ok(serde_json::from_str(&json)?)
		}
	}

	pub fn to_str(&self) -> crate::Result<String> {
		Ok(serde_json::to_string(self)?)
	}

	/// Write the key to a file as JSON.
	pub fn to_file<P: AsRef<StdPath>>(&self, path: P) -> crate::Result<()> {
		let json = serde_json::to_string_pretty(self)?;
		std::fs::write(path, json)?;
		Ok(())
	}

	/// Write the key to a file as base64url-encoded JSON.
	pub fn to_file_base64url<P: AsRef<StdPath>>(&self, path: P) -> crate::Result<()> {
		let json = serde_json::to_string(self)?;
		let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json.as_bytes());
		std::fs::write(path, encoded)?;
		Ok(())
	}

	pub fn to_public(&self) -> crate::Result<Self> {
		if !self.operations.contains(&KeyOperation::Verify) {
			return Err(KeyError::VerifyUnsupported.into());
		}

		let key = match self.key {
			KeyType::RSA { ref public, .. } => KeyType::RSA {
				public: public.clone(),
				private: None,
			},
			KeyType::EC {
				ref x,
				ref y,
				ref curve,
				..
			} => KeyType::EC {
				x: x.clone(),
				y: y.clone(),
				curve: curve.clone(),
				d: None,
			},
			KeyType::OCT { .. } => return Err(KeyError::NoPublicKey.into()),
			KeyType::OKP { ref x, ref curve, .. } => KeyType::OKP {
				x: x.clone(),
				curve: curve.clone(),
				d: None,
			},
		};

		Ok(Self {
			algorithm: self.algorithm,
			operations: [KeyOperation::Verify].into(),
			key,
			kid: self.kid.clone(),
			decode: Default::default(),
			encode: Default::default(),
		})
	}

	fn to_decoding_key(&self) -> crate::Result<&DecodingKey> {
		if let Some(key) = self.decode.get() {
			return Ok(key);
		}

		let decoding_key = match self.key {
			KeyType::OCT { ref secret } => match self.algorithm {
				Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => DecodingKey::from_secret(secret),
				_ => return Err(KeyError::InvalidAlgorithm.into()),
			},
			KeyType::EC {
				ref curve,
				ref x,
				ref y,
				..
			} => match curve {
				EllipticCurve::P256 => {
					if self.algorithm != Algorithm::ES256 {
						return Err(KeyError::InvalidAlgorithmForCurve("P-256").into());
					}
					if x.len() != 32 || y.len() != 32 {
						return Err(KeyError::InvalidCoordinateLength("P-256").into());
					}

					DecodingKey::from_ec_components(
						base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(x).as_ref(),
						base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(y).as_ref(),
					)?
				}
				EllipticCurve::P384 => {
					if self.algorithm != Algorithm::ES384 {
						return Err(KeyError::InvalidAlgorithmForCurve("P-384").into());
					}
					if x.len() != 48 || y.len() != 48 {
						return Err(KeyError::InvalidCoordinateLength("P-384").into());
					}

					DecodingKey::from_ec_components(
						base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(x).as_ref(),
						base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(y).as_ref(),
					)?
				}
				_ => return Err(KeyError::InvalidCurve("EC").into()),
			},
			KeyType::OKP { ref curve, ref x, .. } => match curve {
				EllipticCurve::Ed25519 => {
					if self.algorithm != Algorithm::EdDSA {
						return Err(KeyError::InvalidAlgorithmForCurve("Ed25519").into());
					}

					DecodingKey::from_ed_components(
						base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(x).as_ref(),
					)?
				}
				_ => return Err(KeyError::InvalidCurve("OKP").into()),
			},
			KeyType::RSA { ref public, .. } => {
				DecodingKey::from_rsa_raw_components(public.n.as_ref(), public.e.as_ref())
			}
		};

		Ok(self.decode.get_or_init(|| decoding_key))
	}

	fn to_encoding_key(&self) -> crate::Result<&EncodingKey> {
		if let Some(key) = self.encode.get() {
			return Ok(key);
		}

		let encoding_key = match self.key {
			KeyType::OCT { ref secret } => match self.algorithm {
				Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => EncodingKey::from_secret(secret),
				_ => return Err(KeyError::InvalidAlgorithm.into()),
			},
			KeyType::EC { ref curve, ref d, .. } => {
				let d = d.as_ref().ok_or(KeyError::MissingPrivateKey)?;

				match curve {
					EllipticCurve::P256 => {
						let secret_key = SecretKey::<p256::NistP256>::from_slice(d)?;
						let doc = secret_key.to_pkcs8_der()?;
						EncodingKey::from_ec_der(doc.as_bytes())
					}
					EllipticCurve::P384 => {
						let secret_key = SecretKey::<p384::NistP384>::from_slice(d)?;
						let doc = secret_key.to_pkcs8_der()?;
						EncodingKey::from_ec_der(doc.as_bytes())
					}
					_ => return Err(KeyError::InvalidCurve("EC").into()),
				}
			}
			KeyType::OKP {
				ref curve,
				ref d,
				ref x,
			} => {
				let d = d.as_ref().ok_or(KeyError::MissingPrivateKey)?;

				let key_pair =
					aws_lc_rs::signature::Ed25519KeyPair::from_seed_and_public_key(d.as_slice(), x.as_slice())?;

				match curve {
					EllipticCurve::Ed25519 => EncodingKey::from_ed_der(key_pair.to_pkcs8()?.as_ref()),
					_ => return Err(KeyError::InvalidCurve("OKP").into()),
				}
			}
			KeyType::RSA {
				ref public,
				ref private,
			} => {
				let n = BigUint::from_bytes_be(&public.n);
				let e = BigUint::from_bytes_be(&public.e);
				let private = private.as_ref().ok_or(KeyError::MissingPrivateKey)?;
				let d = BigUint::from_bytes_be(&private.d);
				let p = BigUint::from_bytes_be(&private.p);
				let q = BigUint::from_bytes_be(&private.q);

				let rsa = rsa::RsaPrivateKey::from_components(n, e, d, vec![p, q]);
				let pem = rsa?.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF);

				EncodingKey::from_rsa_pem(pem?.as_bytes())?
			}
		};

		Ok(self.encode.get_or_init(|| encoding_key))
	}

	pub fn decode(&self, token: &str) -> crate::Result<Claims> {
		if !self.operations.contains(&KeyOperation::Verify) {
			return Err(KeyError::VerifyUnsupported.into());
		}

		let decode = self.to_decoding_key()?;

		let mut validation = jsonwebtoken::Validation::new(self.algorithm.into());
		validation.required_spec_claims = Default::default(); // Don't require exp, but still validate it if present
		validation.validate_exp = false; // We validate exp ourselves to handle null values

		let token = jsonwebtoken::decode::<Claims>(token, decode, &validation)?;

		if let Some(exp) = token.claims.expires
			&& exp < std::time::SystemTime::now()
		{
			return Err(crate::Error::TokenExpired);
		}

		token.claims.validate()?;

		Ok(token.claims)
	}

	pub fn encode(&self, payload: &Claims) -> crate::Result<String> {
		if !self.operations.contains(&KeyOperation::Sign) {
			return Err(KeyError::SignUnsupported.into());
		}

		payload.validate()?;

		let encode = self.to_encoding_key()?;

		let mut header = Header::new(self.algorithm.into());
		header.kid = self.kid.as_ref().map(|k| k.to_string());
		let token = jsonwebtoken::encode(&header, &payload, encode)?;
		Ok(token)
	}

	/// Generate a key pair for the given algorithm, returning the private and public keys.
	pub fn generate(algorithm: Algorithm, id: Option<crate::KeyId>) -> crate::Result<Self> {
		generate(algorithm, id)
	}
}

/// Serialize bytes as base64url without padding
fn serialize_base64url<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes);
	serializer.serialize_str(&encoded)
}

fn serialize_base64url_optional<S>(bytes: &Option<Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	match bytes {
		Some(b) => serialize_base64url(b, serializer),
		None => serializer.serialize_none(),
	}
}

/// Deserialize base64url string to bytes, supporting both padded and unpadded formats for backwards compatibility
fn deserialize_base64url<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
	D: Deserializer<'de>,
{
	let s = String::deserialize(deserializer)?;

	// Try to decode as unpadded base64url first (preferred format)
	base64::engine::general_purpose::URL_SAFE_NO_PAD
		.decode(&s)
		.or_else(|_| {
			// Fall back to padded base64url for backwards compatibility
			base64::engine::general_purpose::URL_SAFE.decode(&s)
		})
		.map_err(serde::de::Error::custom)
}

fn deserialize_base64url_optional<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
where
	D: Deserializer<'de>,
{
	let s: Option<String> = Option::deserialize(deserializer)?;
	match s {
		Some(s) => {
			let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
				.decode(&s)
				.or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(&s))
				.map_err(serde::de::Error::custom)?;
			Ok(Some(decoded))
		}
		None => Ok(None),
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use std::time::{Duration, SystemTime};

	fn create_test_key() -> Key {
		Key {
			algorithm: Algorithm::HS256,
			operations: [KeyOperation::Sign, KeyOperation::Verify].into(),
			key: KeyType::OCT {
				secret: b"test-secret-that-is-long-enough-for-hmac-sha256".to_vec(),
			},
			kid: Some(crate::KeyId::decode("test-key-1").unwrap()),
			decode: Default::default(),
			encode: Default::default(),
		}
	}

	fn create_test_claims() -> Claims {
		Claims {
			root: "test-path".to_string(),
			publish: vec!["test-pub".into()],
			cluster: false,
			subscribe: vec!["test-sub".into()],
			expires: Some(SystemTime::now() + Duration::from_secs(3600)),
			issued: Some(SystemTime::now()),
		}
	}

	#[test]
	fn test_key_from_str_valid() {
		let key = create_test_key();
		let json = key.to_str().unwrap();
		let loaded_key = Key::from_str(&json).unwrap();

		assert_eq!(loaded_key.algorithm, key.algorithm);
		assert_eq!(loaded_key.operations, key.operations);
		match (loaded_key.key, key.key) {
			(KeyType::OCT { secret: loaded_secret }, KeyType::OCT { secret }) => {
				assert_eq!(loaded_secret, secret);
			}
			_ => panic!("Expected OCT key"),
		}
		assert_eq!(loaded_key.kid, key.kid);
	}

	/// Tests whether Key::from_str() works for keys without a kty value to fall back to OCT
	#[test]
	fn test_key_oct_backwards_compatibility() {
		let json = r#"{"alg":"HS256","key_ops":["sign","verify"],"k":"Fp8kipWUJeUFqeSqWym_tRC_tyI8z-QpqopIGrbrD68"}"#;
		let key = Key::from_str(json);

		assert!(key.is_ok());
		let key = key.unwrap();

		if let KeyType::OCT { ref secret, .. } = key.key {
			let base64_key = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(secret);
			assert_eq!(base64_key, "Fp8kipWUJeUFqeSqWym_tRC_tyI8z-QpqopIGrbrD68");
		} else {
			panic!("Expected OCT key");
		}

		let key_str = key.to_str();
		assert!(key_str.is_ok());
		let key_str = key_str.unwrap();

		// After serializing again it must contain the kty
		assert!(key_str.contains("\"alg\":\"HS256\""));
		assert!(key_str.contains("\"key_ops\""));
		assert!(key_str.contains("\"sign\""));
		assert!(key_str.contains("\"verify\""));
		assert!(key_str.contains("\"kty\":\"oct\""));
	}

	#[test]
	fn test_key_from_str_invalid_json() {
		let result = Key::from_str("invalid json");
		assert!(result.is_err());
	}

	#[test]
	fn test_key_to_str() {
		let key = create_test_key();
		let json = key.to_str().unwrap();
		assert!(json.contains("\"alg\":\"HS256\""));
		assert!(json.contains("\"key_ops\""));
		assert!(json.contains("\"sign\""));
		assert!(json.contains("\"verify\""));
		assert!(json.contains("\"kid\":\"test-key-1\""));
		assert!(json.contains("\"kty\":\"oct\""));
	}

	#[test]
	fn test_key_sign_success() {
		let key = create_test_key();
		let claims = create_test_claims();
		let token = key.encode(&claims).unwrap();

		assert!(!token.is_empty());
		assert_eq!(token.matches('.').count(), 2); // JWT format: header.payload.signature
	}

	#[test]
	fn test_key_sign_no_permission() {
		let mut key = create_test_key();
		key.operations = [KeyOperation::Verify].into();
		let claims = create_test_claims();

		let result = key.encode(&claims);
		assert!(result.is_err());
		assert!(result.unwrap_err().to_string().contains("key does not support signing"));
	}

	#[test]
	fn test_key_sign_invalid_claims() {
		let key = create_test_key();
		let invalid_claims = Claims {
			root: "test-path".to_string(),
			publish: vec![],
			subscribe: vec![],
			cluster: false,
			expires: None,
			issued: None,
		};

		let result = key.encode(&invalid_claims);
		assert!(result.is_err());
		assert!(
			result
				.unwrap_err()
				.to_string()
				.contains("no publish or subscribe allowed; token is useless")
		);
	}

	#[test]
	fn test_key_verify_success() {
		let key = create_test_key();
		let claims = create_test_claims();
		let token = key.encode(&claims).unwrap();

		let verified_claims = key.decode(&token).unwrap();
		assert_eq!(verified_claims.root, claims.root);
		assert_eq!(verified_claims.publish, claims.publish);
		assert_eq!(verified_claims.subscribe, claims.subscribe);
		assert_eq!(verified_claims.cluster, claims.cluster);
	}

	#[test]
	fn test_key_verify_no_permission() {
		let mut key = create_test_key();
		key.operations = [KeyOperation::Sign].into();

		let result = key.decode("some.jwt.token");
		assert!(result.is_err());
		assert!(
			result
				.unwrap_err()
				.to_string()
				.contains("key does not support verification")
		);
	}

	#[test]
	fn test_key_verify_invalid_token() {
		let key = create_test_key();
		let result = key.decode("invalid-token");
		assert!(result.is_err());
	}

	#[test]
	fn test_key_verify_path_mismatch() {
		let key = create_test_key();
		let claims = create_test_claims();
		let token = key.encode(&claims).unwrap();

		// This test was expecting a path mismatch error, but now decode succeeds
		let result = key.decode(&token);
		assert!(result.is_ok());
	}

	#[test]
	fn test_key_verify_expired_token() {
		let key = create_test_key();
		let mut claims = create_test_claims();
		claims.expires = Some(SystemTime::now() - Duration::from_secs(3600)); // 1 hour ago
		let token = key.encode(&claims).unwrap();

		let result = key.decode(&token);
		assert!(result.is_err());
	}

	#[test]
	fn test_key_verify_token_without_exp() {
		let key = create_test_key();
		let claims = Claims {
			root: "test-path".to_string(),
			publish: vec!["".to_string()],
			subscribe: vec!["".to_string()],
			cluster: false,
			expires: None,
			issued: None,
		};
		let token = key.encode(&claims).unwrap();

		let verified_claims = key.decode(&token).unwrap();
		assert_eq!(verified_claims.root, claims.root);
		assert_eq!(verified_claims.publish, claims.publish);
		assert_eq!(verified_claims.subscribe, claims.subscribe);
		assert_eq!(verified_claims.expires, None);
	}

	#[test]
	fn test_key_round_trip() {
		let key = create_test_key();
		let original_claims = Claims {
			root: "test-path".to_string(),
			publish: vec!["test-pub".into()],
			subscribe: vec!["test-sub".into()],
			cluster: true,
			expires: Some(SystemTime::now() + Duration::from_secs(3600)),
			issued: Some(SystemTime::now()),
		};

		let token = key.encode(&original_claims).unwrap();
		let verified_claims = key.decode(&token).unwrap();

		assert_eq!(verified_claims.root, original_claims.root);
		assert_eq!(verified_claims.publish, original_claims.publish);
		assert_eq!(verified_claims.subscribe, original_claims.subscribe);
		assert_eq!(verified_claims.cluster, original_claims.cluster);
	}

	#[test]
	fn test_key_generate_hs256() {
		let key = Key::generate(Algorithm::HS256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert_eq!(key.algorithm, Algorithm::HS256);
		assert_eq!(key.kid, Some(crate::KeyId::decode("test-id").unwrap()));
		assert_eq!(key.operations, [KeyOperation::Sign, KeyOperation::Verify].into());

		match key.key {
			KeyType::OCT { ref secret } => assert_eq!(secret.len(), 32),
			_ => panic!("Expected OCT key"),
		}
	}

	#[test]
	fn test_key_generate_hs384() {
		let key = Key::generate(Algorithm::HS384, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert_eq!(key.algorithm, Algorithm::HS384);

		match key.key {
			KeyType::OCT { ref secret } => assert_eq!(secret.len(), 48),
			_ => panic!("Expected OCT key"),
		}
	}

	#[test]
	fn test_key_generate_hs512() {
		let key = Key::generate(Algorithm::HS512, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert_eq!(key.algorithm, Algorithm::HS512);

		match key.key {
			KeyType::OCT { ref secret } => assert_eq!(secret.len(), 64),
			_ => panic!("Expected OCT key"),
		}
	}

	#[test]
	fn test_key_generate_rs512() {
		let key = Key::generate(Algorithm::RS512, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert_eq!(key.algorithm, Algorithm::RS512);
		assert!(matches!(key.key, KeyType::RSA { .. }));
		match key.key {
			KeyType::RSA {
				ref public,
				ref private,
			} => {
				assert!(private.is_some());
				assert_eq!(public.n.len(), 256);
				assert_eq!(public.e.len(), 3);
			}
			_ => panic!("Expected RSA key"),
		}
	}

	#[test]
	fn test_key_generate_es256() {
		let key = Key::generate(Algorithm::ES256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert_eq!(key.algorithm, Algorithm::ES256);
		assert!(matches!(key.key, KeyType::EC { .. }))
	}

	#[test]
	fn test_key_generate_ps512() {
		let key = Key::generate(Algorithm::PS512, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert_eq!(key.algorithm, Algorithm::PS512);
		assert!(matches!(key.key, KeyType::RSA { .. }));
	}

	#[test]
	fn test_key_generate_eddsa() {
		let key = Key::generate(Algorithm::EdDSA, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert_eq!(key.algorithm, Algorithm::EdDSA);
		assert!(matches!(key.key, KeyType::OKP { .. }));
	}

	#[test]
	fn test_key_generate_without_id() {
		let key = Key::generate(Algorithm::HS256, None);
		assert!(key.is_ok());
		let key = key.unwrap();

		assert_eq!(key.algorithm, Algorithm::HS256);
		assert_eq!(key.kid, None);
		assert_eq!(key.operations, [KeyOperation::Sign, KeyOperation::Verify].into());
	}

	#[test]
	fn test_public_key_conversion_hmac() {
		let key = Key::generate(Algorithm::HS256, Some(crate::KeyId::decode("test-id").unwrap()))
			.expect("HMAC key generation failed");

		assert!(key.to_public().is_err());
	}

	#[test]
	fn test_public_key_conversion_rsa() {
		let key = Key::generate(Algorithm::RS256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		let public_key = key.to_public().unwrap();
		assert_eq!(key.kid, public_key.kid);
		assert_eq!(public_key.operations, [KeyOperation::Verify].into());
		assert!(public_key.encode.get().is_none());
		assert!(public_key.decode.get().is_none());
		assert!(matches!(public_key.key, KeyType::RSA { .. }));

		if let KeyType::RSA { public, private } = &public_key.key {
			assert!(private.is_none());

			if let KeyType::RSA { public: src_public, .. } = &key.key {
				assert_eq!(public.e, src_public.e);
				assert_eq!(public.n, src_public.n);
			} else {
				unreachable!("Expected RSA key")
			}
		} else {
			unreachable!("Expected RSA key");
		}
	}

	#[test]
	fn test_public_key_conversion_es() {
		let key = Key::generate(Algorithm::ES256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		let public_key = key.to_public().unwrap();
		assert_eq!(key.kid, public_key.kid);
		assert_eq!(public_key.operations, [KeyOperation::Verify].into());
		assert!(public_key.encode.get().is_none());
		assert!(public_key.decode.get().is_none());
		assert!(matches!(public_key.key, KeyType::EC { .. }));

		if let KeyType::EC { x, y, d, curve } = &public_key.key {
			assert!(d.is_none());

			if let KeyType::EC {
				x: src_x,
				y: src_y,
				curve: src_curve,
				..
			} = &key.key
			{
				assert_eq!(x, src_x);
				assert_eq!(y, src_y);
				assert_eq!(curve, src_curve);
			} else {
				unreachable!("Expected EC key")
			}
		} else {
			unreachable!("Expected EC key");
		}
	}

	#[test]
	fn test_public_key_conversion_ed() {
		let key = Key::generate(Algorithm::EdDSA, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		let public_key = key.to_public().unwrap();
		assert_eq!(key.kid, public_key.kid);
		assert_eq!(public_key.operations, [KeyOperation::Verify].into());
		assert!(public_key.encode.get().is_none());
		assert!(public_key.decode.get().is_none());
		assert!(matches!(public_key.key, KeyType::OKP { .. }));

		if let KeyType::OKP { x, d, curve } = &public_key.key {
			assert!(d.is_none());

			if let KeyType::OKP {
				x: src_x,
				curve: src_curve,
				..
			} = &key.key
			{
				assert_eq!(x, src_x);
				assert_eq!(curve, src_curve);
			} else {
				unreachable!("Expected OKP key")
			}
		} else {
			unreachable!("Expected OKP key");
		}
	}

	#[test]
	fn test_key_generate_sign_verify_cycle() {
		let key = Key::generate(Algorithm::HS256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		let claims = create_test_claims();

		let token = key.encode(&claims).unwrap();
		let verified_claims = key.decode(&token).unwrap();

		assert_eq!(verified_claims.root, claims.root);
		assert_eq!(verified_claims.publish, claims.publish);
		assert_eq!(verified_claims.subscribe, claims.subscribe);
		assert_eq!(verified_claims.cluster, claims.cluster);
	}

	#[test]
	fn test_key_debug_no_secret() {
		let key = create_test_key();
		let debug_str = format!("{key:?}");

		assert!(debug_str.contains("algorithm: HS256"));
		assert!(debug_str.contains("operations"));
		assert!(debug_str.contains("kid: Some(KeyId(\"test-key-1\"))"));
		assert!(!debug_str.contains("secret")); // Should not contain secret
	}

	#[test]
	fn test_key_operations_enum() {
		let sign_op = KeyOperation::Sign;
		let verify_op = KeyOperation::Verify;
		let decrypt_op = KeyOperation::Decrypt;
		let encrypt_op = KeyOperation::Encrypt;

		assert_eq!(sign_op, KeyOperation::Sign);
		assert_eq!(verify_op, KeyOperation::Verify);
		assert_eq!(decrypt_op, KeyOperation::Decrypt);
		assert_eq!(encrypt_op, KeyOperation::Encrypt);

		assert_ne!(sign_op, verify_op);
		assert_ne!(decrypt_op, encrypt_op);
	}

	#[test]
	fn test_key_operations_serde() {
		let operations = [KeyOperation::Sign, KeyOperation::Verify];
		let json = serde_json::to_string(&operations).unwrap();
		assert!(json.contains("\"sign\""));
		assert!(json.contains("\"verify\""));

		let deserialized: Vec<KeyOperation> = serde_json::from_str(&json).unwrap();
		assert_eq!(deserialized, operations);
	}

	#[test]
	fn test_key_serde() {
		let key = create_test_key();
		let json = serde_json::to_string(&key).unwrap();
		let deserialized: Key = serde_json::from_str(&json).unwrap();

		assert_eq!(deserialized.algorithm, key.algorithm);
		assert_eq!(deserialized.operations, key.operations);
		assert_eq!(deserialized.kid, key.kid);

		if let (
			KeyType::OCT {
				secret: original_secret,
			},
			KeyType::OCT {
				secret: deserialized_secret,
			},
		) = (&key.key, &deserialized.key)
		{
			assert_eq!(deserialized_secret, original_secret);
		} else {
			panic!("Expected both keys to be OCT variant");
		}
	}

	#[test]
	fn test_key_clone() {
		let key = create_test_key();
		let cloned = key.clone();

		assert_eq!(cloned.algorithm, key.algorithm);
		assert_eq!(cloned.operations, key.operations);
		assert_eq!(cloned.kid, key.kid);

		if let (
			KeyType::OCT {
				secret: original_secret,
			},
			KeyType::OCT { secret: cloned_secret },
		) = (&key.key, &cloned.key)
		{
			assert_eq!(cloned_secret, original_secret);
		} else {
			panic!("Expected both keys to be OCT variant");
		}
	}

	#[test]
	fn test_hmac_algorithms() {
		let key_256 = Key::generate(Algorithm::HS256, Some(crate::KeyId::decode("test-id").unwrap()));
		let key_384 = Key::generate(Algorithm::HS384, Some(crate::KeyId::decode("test-id").unwrap()));
		let key_512 = Key::generate(Algorithm::HS512, Some(crate::KeyId::decode("test-id").unwrap()));

		let claims = create_test_claims();

		// Test that each algorithm can sign and verify
		for key in [key_256, key_384, key_512] {
			assert!(key.is_ok());
			let key = key.unwrap();

			let token = key.encode(&claims).unwrap();
			let verified_claims = key.decode(&token).unwrap();
			assert_eq!(verified_claims.root, claims.root);
		}
	}

	#[test]
	fn test_rsa_pkcs1_asymmetric_algorithms() {
		let key_rs256 = Key::generate(Algorithm::RS256, Some(crate::KeyId::decode("test-id").unwrap()));
		let key_rs384 = Key::generate(Algorithm::RS384, Some(crate::KeyId::decode("test-id").unwrap()));
		let key_rs512 = Key::generate(Algorithm::RS512, Some(crate::KeyId::decode("test-id").unwrap()));

		for key in [key_rs256, key_rs384, key_rs512] {
			test_asymmetric_key(key);
		}
	}

	#[test]
	fn test_rsa_pss_asymmetric_algorithms() {
		let key_ps256 = Key::generate(Algorithm::PS256, Some(crate::KeyId::decode("test-id").unwrap()));
		let key_ps384 = Key::generate(Algorithm::PS384, Some(crate::KeyId::decode("test-id").unwrap()));
		let key_ps512 = Key::generate(Algorithm::PS512, Some(crate::KeyId::decode("test-id").unwrap()));

		for key in [key_ps256, key_ps384, key_ps512] {
			test_asymmetric_key(key);
		}
	}

	#[test]
	fn test_ec_asymmetric_algorithms() {
		let key_es256 = Key::generate(Algorithm::ES256, Some(crate::KeyId::decode("test-id").unwrap()));
		let key_es384 = Key::generate(Algorithm::ES384, Some(crate::KeyId::decode("test-id").unwrap()));

		for key in [key_es256, key_es384] {
			test_asymmetric_key(key);
		}
	}

	#[test]
	fn test_ed_asymmetric_algorithms() {
		let key_eddsa = Key::generate(Algorithm::EdDSA, Some(crate::KeyId::decode("test-id").unwrap()));

		test_asymmetric_key(key_eddsa);
	}

	fn test_asymmetric_key(key: crate::Result<Key>) {
		assert!(key.is_ok());
		let key = key.unwrap();

		let claims = create_test_claims();
		let token = key.encode(&claims).unwrap();

		let private_verified_claims = key.decode(&token).unwrap();
		assert_eq!(
			private_verified_claims.root, claims.root,
			"validation using private key"
		);

		let public_verified_claims = key.to_public().unwrap().decode(&token).unwrap();
		assert_eq!(public_verified_claims.root, claims.root, "validation using public key");
	}

	#[test]
	fn test_cross_algorithm_verification_fails() {
		let key_256 = Key::generate(Algorithm::HS256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key_256.is_ok());
		let key_256 = key_256.unwrap();

		let key_384 = Key::generate(Algorithm::HS384, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key_384.is_ok());
		let key_384 = key_384.unwrap();

		let claims = create_test_claims();
		let token = key_256.encode(&claims).unwrap();

		// Different algorithm should fail verification
		let result = key_384.decode(&token);
		assert!(result.is_err());
	}

	#[test]
	fn test_asymmetric_cross_algorithm_verification_fails() {
		let key_rs256 = Key::generate(Algorithm::RS256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key_rs256.is_ok());
		let key_rs256 = key_rs256.unwrap();

		let key_ps256 = Key::generate(Algorithm::PS256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key_ps256.is_ok());
		let key_ps256 = key_ps256.unwrap();

		let claims = create_test_claims();
		let token = key_rs256.encode(&claims).unwrap();

		// Different algorithm should fail verification
		let private_result = key_ps256.decode(&token);
		let public_result = key_ps256.to_public().unwrap().decode(&token);
		assert!(private_result.is_err());
		assert!(public_result.is_err());
	}

	#[test]
	fn test_rsa_pkcs1_public_key_conversion() {
		let key = Key::generate(Algorithm::RS256, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert!(key.operations.contains(&KeyOperation::Sign));
		assert!(key.operations.contains(&KeyOperation::Verify));

		let public_key = key.to_public().unwrap();
		assert!(!public_key.operations.contains(&KeyOperation::Sign));
		assert!(public_key.operations.contains(&KeyOperation::Verify));

		match key.key {
			KeyType::RSA {
				ref public,
				ref private,
			} => {
				assert!(private.is_some());
				assert_eq!(public.n.len(), 256);
				assert_eq!(public.e.len(), 3);

				match public_key.key {
					KeyType::RSA {
						public: ref guest_public,
						private: ref public_private,
					} => {
						assert!(public_private.is_none());
						assert_eq!(public.n, guest_public.n);
						assert_eq!(public.e, guest_public.e);
					}
					_ => panic!("Expected public key to be an RSA key"),
				}
			}
			_ => panic!("Expected private key to be an RSA key"),
		}
	}

	#[test]
	fn test_rsa_pss_public_key_conversion() {
		let key = Key::generate(Algorithm::PS384, Some(crate::KeyId::decode("test-id").unwrap()));
		assert!(key.is_ok());
		let key = key.unwrap();

		assert!(key.operations.contains(&KeyOperation::Sign));
		assert!(key.operations.contains(&KeyOperation::Verify));

		let public_key = key.to_public().unwrap();
		assert!(!public_key.operations.contains(&KeyOperation::Sign));
		assert!(public_key.operations.contains(&KeyOperation::Verify));

		match key.key {
			KeyType::RSA {
				ref public,
				ref private,
			} => {
				assert!(private.is_some());
				assert_eq!(public.n.len(), 256);
				assert_eq!(public.e.len(), 3);

				match public_key.key {
					KeyType::RSA {
						public: ref guest_public,
						private: ref public_private,
					} => {
						assert!(public_private.is_none());
						assert_eq!(public.n, guest_public.n);
						assert_eq!(public.e, guest_public.e);
					}
					_ => panic!("Expected public key to be an RSA key"),
				}
			}
			_ => panic!("Expected private key to be an RSA key"),
		}
	}

	#[test]
	fn test_base64url_serialization() {
		let key = create_test_key();
		let json = serde_json::to_string(&key).unwrap();

		// Check that the secret is base64url encoded without padding
		let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
		let k_value = parsed["k"].as_str().unwrap();

		// Base64url should not contain padding characters
		assert!(!k_value.contains('='));
		assert!(!k_value.contains('+'));
		assert!(!k_value.contains('/'));

		// Verify it decodes correctly
		let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
			.decode(k_value)
			.unwrap();

		if let KeyType::OCT {
			secret: original_secret,
		} = &key.key
		{
			assert_eq!(decoded, *original_secret);
		} else {
			panic!("Expected both keys to be OCT variant");
		}
	}

	#[test]
	fn test_backwards_compatibility_unpadded_base64url() {
		// Create a JSON with unpadded base64url (new format)
		let unpadded_json = r#"{"kty":"oct","alg":"HS256","key_ops":["sign","verify"],"k":"dGVzdC1zZWNyZXQtdGhhdC1pcy1sb25nLWVub3VnaC1mb3ItaG1hYy1zaGEyNTY","kid":"test-key-1"}"#;

		// Should be able to deserialize new format
		let key: Key = serde_json::from_str(unpadded_json).unwrap();
		assert_eq!(key.algorithm, Algorithm::HS256);
		assert_eq!(key.kid, Some(crate::KeyId::decode("test-key-1").unwrap()));

		if let KeyType::OCT { secret } = &key.key {
			assert_eq!(secret, b"test-secret-that-is-long-enough-for-hmac-sha256");
		} else {
			panic!("Expected key to be OCT variant");
		}
	}

	#[test]
	fn test_backwards_compatibility_padded_base64url() {
		// Create a JSON with padded base64url (old format) - same secret but with padding
		let padded_json = r#"{"kty":"oct","alg":"HS256","key_ops":["sign","verify"],"k":"dGVzdC1zZWNyZXQtdGhhdC1pcy1sb25nLWVub3VnaC1mb3ItaG1hYy1zaGEyNTY=","kid":"test-key-1"}"#;

		// Should be able to deserialize old format for backwards compatibility
		let key: Key = serde_json::from_str(padded_json).unwrap();
		assert_eq!(key.algorithm, Algorithm::HS256);
		assert_eq!(key.kid, Some(crate::KeyId::decode("test-key-1").unwrap()));

		if let KeyType::OCT { secret } = &key.key {
			assert_eq!(secret, b"test-secret-that-is-long-enough-for-hmac-sha256");
		} else {
			panic!("Expected key to be OCT variant");
		}
	}

	// Tests that Rust can load keys generated by the JS @moq/token package
	// and verify tokens signed by JS.
	//
	// Generated with: bun -e 'import { generate } from "./js/token/src/generate.ts"; ...'
	// See js/token/src/interop.test.ts for the JS-side counterpart.

	/// JS-generated HS256 key (from @moq/token generate("HS256", "js-test-key"))
	const JS_HS256_KEY: &str = r#"{"kty":"oct","alg":"HS256","k":"xm6xsSkfFqzPU3KfcbAcF2_h0OkStxQ_nNqVPYl0ync","kid":"js-test-key","key_ops":["sign","verify"],"guest":[],"guest_sub":[],"guest_pub":[]}"#;

	/// JS-generated HS256 token (from @moq/token sign(key, {root:"live", put:["camera1"], get:["camera1","camera2"]}))
	const JS_HS256_TOKEN: &str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImpzLXRlc3Qta2V5In0.eyJyb290IjoibGl2ZSIsInB1dCI6WyJjYW1lcmExIl0sImdldCI6WyJjYW1lcmExIiwiY2FtZXJhMiJdLCJpYXQiOjE3NzUxNzY3NTR9.tHNQtHh_HCIKxXOexDCM7AkjqWzbULLZzjEckfOGRfY";

	/// JS-generated EdDSA private key (from @moq/token generate("EdDSA", "js-eddsa-key"))
	const JS_EDDSA_PRIVATE_KEY: &str = r#"{"kty":"OKP","alg":"EdDSA","crv":"Ed25519","x":"UiU9fT_SdBBpkFtJPRCY0gX1jK_Dr9syYLFuEz4QUM4","d":"lm-L_PV3ksuQ-KrFBgFMDJqAZC3_Z6Z5UC4ZQY5OoDQ","kid":"js-eddsa-key","key_ops":["sign","verify"],"guest":[],"guest_sub":[],"guest_pub":[]}"#;

	/// JS-generated EdDSA public key (from @moq/token toPublicKey(key))
	const JS_EDDSA_PUBLIC_KEY: &str = r#"{"kty":"OKP","alg":"EdDSA","crv":"Ed25519","x":"UiU9fT_SdBBpkFtJPRCY0gX1jK_Dr9syYLFuEz4QUM4","kid":"js-eddsa-key","guest":[],"guest_sub":[],"guest_pub":[],"key_ops":["verify"]}"#;

	/// JS-generated EdDSA token (from @moq/token sign(key, {root:"stream", put:["video"]}))
	const JS_EDDSA_TOKEN: &str = "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCIsImtpZCI6ImpzLWVkZHNhLWtleSJ9.eyJyb290Ijoic3RyZWFtIiwicHV0IjpbInZpZGVvIl0sImlhdCI6MTc3NTE3Njc1Nn0.l9rUMHjPSXWKSXRP3mmeMgTAywtqpdqQehhViWaPrKxax1Y2D9KRIYTixYz-b6PI-AoHQYusHWeeLu_HRw2cAg";

	#[test]
	fn test_js_hs256_key_load() {
		let key = Key::from_str(JS_HS256_KEY).unwrap();
		assert_eq!(key.algorithm, Algorithm::HS256);
		assert_eq!(key.kid, Some(crate::KeyId::decode("js-test-key").unwrap()));
	}

	#[test]
	fn test_js_hs256_token_verify() {
		let key = Key::from_str(JS_HS256_KEY).unwrap();
		let claims = key.decode(JS_HS256_TOKEN).unwrap();
		assert_eq!(claims.root, "live");
		assert_eq!(claims.publish, vec!["camera1"]);
		assert_eq!(claims.subscribe, vec!["camera1", "camera2"]);
	}

	#[test]
	fn test_js_hs256_sign_and_roundtrip() {
		let key = Key::from_str(JS_HS256_KEY).unwrap();
		let claims = Claims {
			root: "rust-test".to_string(),
			publish: vec!["pub1".into()],
			subscribe: vec!["sub1".into()],
			..Default::default()
		};
		let token = key.encode(&claims).unwrap();
		let verified = key.decode(&token).unwrap();
		assert_eq!(verified.root, "rust-test");
		assert_eq!(verified.publish, vec!["pub1"]);
	}

	#[test]
	fn test_js_eddsa_key_load() {
		let private_key = Key::from_str(JS_EDDSA_PRIVATE_KEY).unwrap();
		assert_eq!(private_key.algorithm, Algorithm::EdDSA);
		assert!(matches!(private_key.key, KeyType::OKP { .. }));

		let public_key = Key::from_str(JS_EDDSA_PUBLIC_KEY).unwrap();
		assert_eq!(public_key.algorithm, Algorithm::EdDSA);
	}

	#[test]
	fn test_js_eddsa_token_verify_with_private_key() {
		let key = Key::from_str(JS_EDDSA_PRIVATE_KEY).unwrap();
		let claims = key.decode(JS_EDDSA_TOKEN).unwrap();
		assert_eq!(claims.root, "stream");
		assert_eq!(claims.publish, vec!["video"]);
	}

	#[test]
	fn test_js_eddsa_token_verify_with_public_key() {
		let key = Key::from_str(JS_EDDSA_PUBLIC_KEY).unwrap();
		let claims = key.decode(JS_EDDSA_TOKEN).unwrap();
		assert_eq!(claims.root, "stream");
		assert_eq!(claims.publish, vec!["video"]);
	}

	#[test]
	fn test_js_token_wrong_key_fails() {
		// Generate a different HS256 key
		let wrong_key = Key::generate(Algorithm::HS256, None).unwrap();
		let result = wrong_key.decode(JS_HS256_TOKEN);
		assert!(result.is_err());
	}

	#[test]
	fn test_js_eddsa_token_wrong_key_fails() {
		// Try verifying EdDSA token with the HS256 key
		let wrong_key = Key::from_str(JS_HS256_KEY).unwrap();
		let result = wrong_key.decode(JS_EDDSA_TOKEN);
		assert!(result.is_err());
	}

	#[test]
	fn test_file_io_base64url() {
		let key = create_test_key();
		let temp_dir = std::env::temp_dir();
		let temp_path = temp_dir.join("test_jwk.key");

		// Write key to file as base64url
		key.to_file_base64url(&temp_path).unwrap();

		// Read file contents
		let contents = std::fs::read_to_string(&temp_path).unwrap();

		// Should be base64url encoded
		assert!(!contents.contains('{'));
		assert!(!contents.contains('}'));
		assert!(!contents.contains('"'));

		// Decode and verify it's valid JSON
		let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
			.decode(&contents)
			.unwrap();
		let json_str = String::from_utf8(decoded).unwrap();
		let _: serde_json::Value = serde_json::from_str(&json_str).unwrap();

		// Read key back from file
		let loaded_key = Key::from_file(&temp_path).unwrap();
		assert_eq!(loaded_key.algorithm, key.algorithm);
		assert_eq!(loaded_key.operations, key.operations);
		assert_eq!(loaded_key.kid, key.kid);

		if let (
			KeyType::OCT {
				secret: original_secret,
			},
			KeyType::OCT { secret: loaded_secret },
		) = (&key.key, &loaded_key.key)
		{
			assert_eq!(loaded_secret, original_secret);
		} else {
			panic!("Expected both keys to be OCT variant");
		}

		// Clean up
		std::fs::remove_file(temp_path).ok();
	}
}