1use core::fmt;
5use core::time::Duration;
6use std::error::Error;
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use rustls_pki_types::pem::PemObject as _;
10use rustls_pki_types::{CertificateDer, TrustAnchor, UnixTime};
11use sha2::{Digest as _, Sha256};
12use webpki::{EndEntityCert, ExtendedKeyUsageValidator, KeyPurposeIdIter};
13use x509_cert::Certificate;
14use x509_cert::der::{Decode as _, Encode as _};
15use x509_cert::ext::pkix::name::GeneralName;
16use x509_cert::ext::pkix::{
17 AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAltName, SubjectKeyIdentifier,
18};
19use x509_cert::spki::SubjectPublicKeyInfoRef;
20
21use super::{KeyReference, KeyResolutionError, KeyResolver, KeyRole};
22use crate::jose::{Jwk, base64url};
23
24const EC_PUBLIC_KEY: &str = "1.2.840.10045.2.1";
26const SECP256R1: &str = "1.2.840.10045.3.1.7";
28const SECP384R1: &str = "1.3.132.0.34";
30#[cfg(feature = "secp256k1")]
32const SECP256K1: &str = "1.3.132.0.10";
33const ED25519: &str = "1.3.101.112";
35const RSA_ENCRYPTION: &str = "1.2.840.113549.1.1.1";
37const MIN_RSA_BITS: usize = 2048;
39
40#[derive(Clone)]
116pub struct X509Resolver {
117 anchors: Vec<Anchor>,
118}
119
120#[derive(Clone)]
122struct Anchor {
123 der: CertificateDer<'static>,
124 not_before: i64,
125 not_after: i64,
126}
127
128impl X509Resolver {
129 pub const MAX_CHAIN_LENGTH: usize = 10;
131
132 pub fn new<I, C>(anchors: I) -> Result<Self, X509Error>
146 where
147 I: IntoIterator<Item = C>,
148 C: Into<Vec<u8>>,
149 {
150 let anchors = anchors
151 .into_iter()
152 .enumerate()
153 .map(|(index, anchor)| {
154 let der = CertificateDer::from(anchor.into());
155 let certificate = X509Certificate::parse(&der)
156 .map_err(|e| X509Error::invalid_certificate(index, e))?;
157 webpki::anchor_from_trusted_cert(&der)
158 .map_err(|e| X509Error::invalid_certificate(index, e))?;
159 if !certificate.may_issue() {
160 return Err(X509Error::TrustAnchorNotCa { index });
161 }
162 Ok(Anchor {
163 der,
164 not_before: certificate.not_before,
165 not_after: certificate.not_after,
166 })
167 })
168 .collect::<Result<_, _>>()?;
169 Ok(Self { anchors })
170 }
171
172 pub fn from_pem(pem: &str) -> Result<Self, X509Error> {
180 let anchors = CertificateDer::pem_slice_iter(pem.as_bytes())
181 .map(|certificate| certificate.map(|certificate| certificate.to_vec()))
182 .collect::<Result<Vec<_>, _>>()
183 .map_err(|e| X509Error::InvalidPem(e.to_string()))?;
184 if anchors.is_empty() {
185 return Err(X509Error::InvalidPem("no certificate".to_owned()));
186 }
187 Self::new(anchors)
188 }
189
190 pub fn anchors(&self) -> impl Iterator<Item = &[u8]> {
192 self.anchors.iter().map(|anchor| anchor.der.as_ref())
193 }
194
195 pub fn validate(&self, chain: &[Vec<u8>], now: i64) -> Result<Jwk, X509Error> {
202 let (leaf_der, intermediates) = chain.split_first().ok_or(X509Error::EmptyChain)?;
203 if chain.len() > Self::MAX_CHAIN_LENGTH {
204 return Err(X509Error::ChainTooLong {
205 length: chain.len(),
206 max: Self::MAX_CHAIN_LENGTH,
207 });
208 }
209 let certificates = chain
210 .iter()
211 .enumerate()
212 .map(|(index, certificate)| {
213 X509Certificate::parse(certificate)
214 .map_err(|e| X509Error::invalid_certificate(index, e))
215 })
216 .collect::<Result<Vec<_>, _>>()?;
217 let leaf = &certificates[0];
218 if leaf.is_self_issued() {
219 return Err(X509Error::SelfSigned);
220 }
221
222 let time = u64::try_from(now)
223 .map(|now| UnixTime::since_unix_epoch(Duration::from_secs(now)))
224 .map_err(|_| X509Error::InvalidTime(now))?;
225 let anchors = self
226 .anchors
227 .iter()
228 .map(|anchor| webpki::anchor_from_trusted_cert(&anchor.der))
229 .collect::<Result<Vec<_>, _>>()
230 .map_err(|e| X509Error::PathValidation(Box::new(e)))?;
231 let check_path = |path: &webpki::VerifiedPath<'_>| {
234 for intermediate in path.intermediate_certificates() {
236 let der = intermediate.der();
237 let may_issue = certificates
238 .iter()
239 .find(|certificate| certificate.der == der.as_ref())
240 .is_some_and(X509Certificate::may_issue);
241 if !may_issue {
242 return Err(webpki::Error::EndEntityUsedAsCa);
243 }
244 }
245 anchor_validity(path.anchor(), anchors.iter().zip(&self.anchors), now)
246 };
247 let intermediates: Vec<CertificateDer<'_>> = intermediates
248 .iter()
249 .map(|certificate| CertificateDer::from(certificate.as_slice()))
250 .collect();
251 let leaf_der = CertificateDer::from(leaf_der.as_slice());
252 let end_entity =
253 EndEntityCert::try_from(&leaf_der).map_err(|e| X509Error::invalid_certificate(0, e))?;
254 end_entity
255 .verify_for_usage(
256 webpki::ALL_VERIFICATION_ALGS,
257 &anchors,
258 &intermediates,
259 time,
260 AnyExtendedKeyUsage,
261 None,
262 Some(&check_path),
263 )
264 .map_err(|e| X509Error::PathValidation(Box::new(e)))?;
265
266 if !leaf.may_sign_tokens() {
267 return Err(X509Error::KeyUsage);
268 }
269 leaf.public_key()
270 }
271}
272
273impl fmt::Debug for X509Resolver {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.debug_struct("X509Resolver")
276 .field("anchors", &self.anchors.len())
277 .finish()
278 }
279}
280
281#[async_trait::async_trait]
282impl KeyResolver for X509Resolver {
283 async fn resolve_key(
284 &self,
285 key: &KeyReference,
286 role: KeyRole,
287 ) -> Result<Jwk, KeyResolutionError> {
288 let now = SystemTime::now()
289 .duration_since(UNIX_EPOCH)
290 .map_or(0, |elapsed| {
291 i64::try_from(elapsed.as_secs()).unwrap_or(i64::MAX)
292 });
293 self.resolve_key_at(key, role, now).await
294 }
295
296 async fn resolve_key_at(
297 &self,
298 key: &KeyReference,
299 _: KeyRole,
300 now: i64,
301 ) -> Result<Jwk, KeyResolutionError> {
302 match key {
303 KeyReference::X509Chain(chain) => {
304 self.validate(chain, now).map_err(KeyResolutionError::new)
305 }
306 other => Err(KeyResolutionError::unsupported(other)),
307 }
308 }
309}
310
311fn anchor_validity<'a>(
319 used: &TrustAnchor<'_>,
320 configured: impl IntoIterator<Item = (&'a TrustAnchor<'a>, &'a Anchor)>,
321 now: i64,
322) -> Result<(), webpki::Error> {
323 let mut error = webpki::Error::UnknownIssuer;
324 for (anchor, certificate) in configured {
325 if anchor.subject != used.subject
326 || anchor.subject_public_key_info != used.subject_public_key_info
327 || anchor.name_constraints != used.name_constraints
328 {
329 continue;
330 }
331 match outside_validity(now, certificate.not_before, certificate.not_after) {
332 None => return Ok(()),
333 Some(outside) => error = outside,
334 }
335 }
336 Err(error)
337}
338
339fn outside_validity(now: i64, not_before: i64, not_after: i64) -> Option<webpki::Error> {
342 let time = |seconds: i64| {
343 UnixTime::since_unix_epoch(Duration::from_secs(u64::try_from(seconds).unwrap_or(0)))
344 };
345 if now < not_before {
346 Some(webpki::Error::CertNotValidYet {
347 time: time(now),
348 not_before: time(not_before),
349 })
350 } else if now > not_after {
351 Some(webpki::Error::CertExpired {
352 time: time(now),
353 not_after: time(not_after),
354 })
355 } else {
356 None
357 }
358}
359
360struct AnyExtendedKeyUsage;
363
364impl ExtendedKeyUsageValidator for AnyExtendedKeyUsage {
365 fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), webpki::Error> {
366 for purpose in iter {
368 purpose?;
369 }
370 Ok(())
371 }
372}
373
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
376struct Usage {
377 digital_signature: bool,
378 non_repudiation: bool,
379 key_cert_sign: bool,
380}
381
382#[derive(Clone, PartialEq, Eq)]
403pub struct X509Certificate {
404 der: Vec<u8>,
405 subject: String,
406 issuer: String,
407 self_issued: bool,
408 ca: bool,
409 dns_names: Vec<String>,
410 uris: Vec<String>,
411 not_before: i64,
412 not_after: i64,
413 subject_key_identifier: Option<Vec<u8>>,
414 authority_key_identifier: Option<Vec<u8>>,
415 key_usage: Option<Usage>,
416 public_key: Vec<u8>,
417}
418
419impl X509Certificate {
420 pub fn from_der(der: &[u8]) -> Result<Self, X509Error> {
427 Self::parse(der).map_err(|e| X509Error::invalid_certificate(0, e))
428 }
429
430 fn parse(der: &[u8]) -> Result<Self, x509_cert::der::Error> {
431 let certificate = Certificate::from_der(der)?;
432 let tbs = certificate.tbs_certificate();
433 let (mut dns_names, mut uris) = (Vec::new(), Vec::new());
434 if let Some((_, SubjectAltName(names))) = tbs.get_extension::<SubjectAltName>()? {
435 for name in names {
436 match name {
437 GeneralName::DnsName(name) => dns_names.push(name.to_string()),
438 GeneralName::UniformResourceIdentifier(uri) => uris.push(uri.to_string()),
439 _ => {}
440 }
441 }
442 }
443 let subject_key_identifier = tbs
444 .get_extension::<SubjectKeyIdentifier>()?
445 .map(|(_, identifier)| identifier.0.as_bytes().to_vec());
446 let authority_key_identifier = tbs
447 .get_extension::<AuthorityKeyIdentifier>()?
448 .and_then(|(_, identifier)| identifier.key_identifier)
449 .map(|identifier| identifier.as_bytes().to_vec());
450 let key_usage = tbs.get_extension::<KeyUsage>()?.map(|(_, usage)| Usage {
451 digital_signature: usage.digital_signature(),
452 non_repudiation: usage.non_repudiation(),
453 key_cert_sign: usage.key_cert_sign(),
454 });
455 let ca = tbs
456 .get_extension::<BasicConstraints>()?
457 .is_some_and(|(_, constraints)| constraints.ca);
458 let seconds = |time: x509_cert::time::Time| {
459 i64::try_from(time.to_unix_duration().as_secs()).unwrap_or(i64::MAX)
460 };
461 Ok(Self {
462 der: der.to_vec(),
463 subject: tbs.subject().to_string(),
464 issuer: tbs.issuer().to_string(),
465 self_issued: tbs.subject().to_der()? == tbs.issuer().to_der()?,
466 ca,
467 dns_names,
468 uris,
469 not_before: seconds(tbs.validity().not_before),
470 not_after: seconds(tbs.validity().not_after),
471 subject_key_identifier,
472 authority_key_identifier,
473 key_usage,
474 public_key: tbs.subject_public_key_info().to_der()?,
475 })
476 }
477
478 pub fn der(&self) -> &[u8] {
480 &self.der
481 }
482
483 pub fn subject(&self) -> &str {
485 &self.subject
486 }
487
488 pub fn issuer(&self) -> &str {
490 &self.issuer
491 }
492
493 pub fn is_self_issued(&self) -> bool {
496 self.self_issued
497 }
498
499 pub fn is_ca(&self) -> bool {
501 self.ca
502 }
503
504 pub fn dns_names(&self) -> &[String] {
506 &self.dns_names
507 }
508
509 pub fn uris(&self) -> &[String] {
511 &self.uris
512 }
513
514 pub fn not_before(&self) -> i64 {
516 self.not_before
517 }
518
519 pub fn not_after(&self) -> i64 {
521 self.not_after
522 }
523
524 pub fn subject_key_identifier(&self) -> Option<&[u8]> {
526 self.subject_key_identifier.as_deref()
527 }
528
529 pub fn authority_key_identifier(&self) -> Option<&[u8]> {
532 self.authority_key_identifier.as_deref()
533 }
534
535 pub fn sha256_thumbprint(&self) -> String {
538 base64url::encode(&Sha256::digest(&self.der))
539 }
540
541 pub fn public_key(&self) -> Result<Jwk, X509Error> {
548 jwk_from_spki(&self.public_key)
549 }
550
551 pub fn binds(&self, identifier: &str) -> bool {
566 let Ok(url) = url::Url::parse(identifier) else {
567 return false;
568 };
569 if url.scheme() != "https"
570 || !url.username().is_empty()
571 || url.password().is_some()
572 || url.query().is_some()
573 || url.fragment().is_some()
574 {
575 return false;
576 }
577 let Some(url::Host::Domain(host)) = url.host() else {
578 return false;
579 };
580 let canonical = url.as_str();
584 let written_canonically = identifier == canonical
585 || (url.path() == "/" && canonical.strip_suffix('/') == Some(identifier));
586 written_canonically
587 && self
588 .dns_names
589 .iter()
590 .any(|name| !name.contains('*') && name.eq_ignore_ascii_case(host))
591 }
592
593 fn may_issue(&self) -> bool {
596 self.ca && self.key_usage.is_none_or(|usage| usage.key_cert_sign)
597 }
598
599 fn may_sign_tokens(&self) -> bool {
602 self.key_usage.is_none_or(|usage| {
603 (usage.digital_signature || usage.non_repudiation) && !usage.key_cert_sign
604 })
605 }
606}
607
608impl fmt::Debug for X509Certificate {
609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610 f.debug_struct("X509Certificate")
611 .field("subject", &self.subject)
612 .field("issuer", &self.issuer)
613 .field("dns_names", &self.dns_names)
614 .field("uris", &self.uris)
615 .field("not_before", &self.not_before)
616 .field("not_after", &self.not_after)
617 .finish_non_exhaustive()
618 }
619}
620
621fn jwk_from_spki(der: &[u8]) -> Result<Jwk, X509Error> {
623 let invalid = |e: &dyn fmt::Display| X509Error::InvalidKey(e.to_string());
624 let spki = SubjectPublicKeyInfoRef::from_der(der).map_err(|e| invalid(&e))?;
625 let key = spki.subject_public_key.raw_bytes();
626 let algorithm = spki.algorithm.oid.to_string();
627 match algorithm.as_str() {
628 EC_PUBLIC_KEY => {
629 let curve = spki
630 .algorithm
631 .parameters_oid()
632 .map_err(|e| invalid(&e))?
633 .to_string();
634 match curve.as_str() {
635 SECP256R1 => Jwk::from_p256_public(key).map_err(|e| invalid(&e)),
636 SECP384R1 => p384_jwk(key),
637 #[cfg(feature = "secp256k1")]
638 SECP256K1 => Jwk::from_secp256k1_public(key).map_err(|e| invalid(&e)),
639 _ => Err(X509Error::UnsupportedKey(format!("elliptic curve {curve}"))),
640 }
641 }
642 ED25519 => Jwk::from_ed25519_public(key).map_err(|e| invalid(&e)),
643 RSA_ENCRYPTION => {
644 let jwk = Jwk::from_pkcs1_der(key).map_err(|e| invalid(&e))?;
645 let (modulus, _) = jwk.rsa_public_components().map_err(|e| invalid(&e))?;
646 let bits = modulus
647 .iter()
648 .position(|&byte| byte != 0)
649 .map_or(0, |first| {
650 (modulus.len() - first) * 8 - modulus[first].leading_zeros() as usize
651 });
652 if bits < MIN_RSA_BITS {
653 return Err(X509Error::UnsupportedKey(format!(
654 "RSA key of {bits} bits, shorter than {MIN_RSA_BITS}"
655 )));
656 }
657 Ok(jwk)
658 }
659 _ => Err(X509Error::UnsupportedKey(format!("algorithm {algorithm}"))),
660 }
661}
662
663fn p384_jwk(point: &[u8]) -> Result<Jwk, X509Error> {
665 const COORDINATE: usize = 48;
666 let invalid = || X509Error::InvalidKey("not an uncompressed P-384 point".to_owned());
667 let (tag, coordinates) = point.split_first().ok_or_else(invalid)?;
668 if *tag != 0x04 || coordinates.len() != 2 * COORDINATE {
669 return Err(invalid());
670 }
671 let (x, y) = coordinates.split_at(COORDINATE);
672 serde_json::from_value(serde_json::json!({
673 "kty": "EC",
674 "crv": "P-384",
675 "x": base64url::encode(x),
676 "y": base64url::encode(y),
677 }))
678 .map_err(|e| X509Error::InvalidKey(e.to_string()))
679}
680
681#[derive(Debug, thiserror::Error)]
683#[non_exhaustive]
684pub enum X509Error {
685 #[error("the certificate chain is empty")]
687 EmptyChain,
688 #[error("the certificate chain has {length} certificates, more than {max}")]
690 ChainTooLong {
691 length: usize,
693 max: usize,
695 },
696 #[error("certificate {index} is invalid: {source}")]
698 InvalidCertificate {
699 index: usize,
701 #[source]
703 source: Box<dyn Error + Send + Sync>,
704 },
705 #[error("invalid PEM: {0}")]
707 InvalidPem(String),
708 #[error("the signing certificate is self-signed")]
712 SelfSigned,
713 #[error("the validation time {0} is before 1970")]
715 InvalidTime(i64),
716 #[error("the certificate chain does not validate: {0}")]
719 PathValidation(#[source] Box<dyn Error + Send + Sync>),
720 #[error("trust anchor {index} is not a CA certificate")]
722 TrustAnchorNotCa {
723 index: usize,
725 },
726 #[error("the signing certificate's key usage does not allow signing a token")]
729 KeyUsage,
730 #[error("unsupported certificate key: {0}")]
732 UnsupportedKey(String),
733 #[error("invalid certificate key: {0}")]
735 InvalidKey(String),
736}
737
738impl X509Error {
739 fn invalid_certificate<E: Error + Send + Sync + 'static>(index: usize, source: E) -> Self {
741 Self::InvalidCertificate {
742 index,
743 source: Box::new(source),
744 }
745 }
746}
747
748#[cfg(test)]
749mod tests {
750 use super::*;
751
752 #[test]
753 fn validity_is_inclusive_at_both_ends() {
754 for now in [100, 150, 200] {
755 assert!(outside_validity(now, 100, 200).is_none(), "{now}");
756 }
757 assert!(matches!(
758 outside_validity(99, 100, 200),
759 Some(webpki::Error::CertNotValidYet { .. })
760 ));
761 assert!(matches!(
762 outside_validity(201, 100, 200),
763 Some(webpki::Error::CertExpired { .. })
764 ));
765 }
766
767 #[test]
772 fn anchor_validity_is_that_of_the_anchor_the_path_was_verified_under() {
773 use rustls_pki_types::Der;
774
775 let anchor = |constraints: Option<&'static [u8]>| TrustAnchor {
776 subject: Der::from_slice(b"subject"),
777 subject_public_key_info: Der::from_slice(b"key"),
778 name_constraints: constraints.map(Der::from_slice),
779 };
780 let valid = |not_before, not_after| Anchor {
781 der: CertificateDer::from(Vec::new()),
782 not_before,
783 not_after,
784 };
785 let (unconstrained, constrained) = (anchor(None), anchor(Some(b"allowed.example")));
786 let (expired, current) = (valid(100, 200), valid(150, 300));
787 let now = 250;
788
789 let configured = [(&unconstrained, &expired), (&constrained, ¤t)];
790 assert!(matches!(
791 anchor_validity(&unconstrained, configured, now),
792 Err(webpki::Error::CertExpired { .. })
793 ));
794 assert!(anchor_validity(&constrained, configured, now).is_ok());
795
796 for configured in [
798 [(&unconstrained, &expired), (&unconstrained, ¤t)],
799 [(&unconstrained, ¤t), (&unconstrained, &expired)],
800 ] {
801 assert!(anchor_validity(&unconstrained, configured, now).is_ok());
802 }
803 let other = TrustAnchor {
805 subject: Der::from_slice(b"other"),
806 ..anchor(None)
807 };
808 assert!(matches!(
809 anchor_validity(&other, configured, now),
810 Err(webpki::Error::UnknownIssuer)
811 ));
812 }
813
814 fn certificate(dns_names: &[&str], uris: &[&str], usage: Option<Usage>) -> X509Certificate {
816 X509Certificate {
817 der: Vec::new(),
818 subject: "CN=example".to_owned(),
819 issuer: "CN=ca".to_owned(),
820 self_issued: false,
821 ca: false,
822 dns_names: dns_names.iter().map(|&name| name.to_owned()).collect(),
823 uris: uris.iter().map(|&uri| uri.to_owned()).collect(),
824 not_before: 0,
825 not_after: 0,
826 subject_key_identifier: None,
827 authority_key_identifier: None,
828 key_usage: usage,
829 public_key: Vec::new(),
830 }
831 }
832
833 #[test]
835 fn binds_only_canonical_https_urls() {
836 let named = certificate(&["issuer.example", "xn--mnchen-3ya.example"], &[], None);
837 for bound in [
838 "https://issuer.example",
839 "https://issuer.example/",
840 "https://issuer.example/tenant/1",
841 "https://issuer.example:8443/tenant/",
842 "https://xn--mnchen-3ya.example",
843 ] {
844 assert!(named.binds(bound), "{bound}");
845 }
846 for unbound in [
847 "https://victim.example",
849 "https://issuer.example.victim.example",
850 "https://victim.example@issuer.example",
851 "https://victim.example:pw@issuer.example/",
852 "https://issuer.example\\@victim.example",
853 "https://issuer.example?x=https://victim.example",
854 "https://issuer.example#https://victim.example",
855 " https://issuer.example",
857 "https://issuer.example ",
858 "https:issuer.example",
859 "https:\\\\issuer.example",
860 "https://issuer.exam\tple",
861 "https://ISSUER.example",
862 "HTTPS://issuer.example",
863 "https://issuer.example.",
864 "https://issuer.example:443",
865 "https://%69ssuer.example",
866 "https://\u{ff49}ssuer.example",
867 "https://m\u{fc}nchen.example",
868 "http://issuer.example",
870 "issuer.example",
871 "did:web:issuer.example",
872 "",
873 ] {
874 assert!(!named.binds(unbound), "{unbound:?}");
875 }
876 let address = certificate(&["192.168.1.1"], &[], None);
878 for unbound in [
879 "https://192.168.1.1",
880 "https://0xc0.0xa8.1.1",
881 "https://3232235777",
882 ] {
883 assert!(!address.binds(unbound), "{unbound}");
884 }
885 let wild = certificate(&["*.issuer.example", "*", ""], &[], None);
887 for unbound in [
888 "https://a.issuer.example",
889 "https://*.issuer.example",
890 "https://",
891 ] {
892 assert!(!wild.binds(unbound), "{unbound}");
893 }
894 }
895
896 #[test]
899 fn uri_names_bind_nothing() {
900 let uris = [
901 "https://victim.example",
902 "did:web:victim.example",
903 "https://issuer.example/tenant",
904 "",
905 ];
906 let without_dns_names = certificate(&[], &uris, None);
907 for uri in uris {
908 assert!(!without_dns_names.binds(uri), "{uri:?}");
909 }
910 let with_dns_name = certificate(&["issuer.example"], &uris, None);
911 assert!(with_dns_name.binds("https://issuer.example/tenant"));
912 for unbound in ["https://victim.example", "did:web:victim.example", ""] {
913 assert!(!with_dns_name.binds(unbound), "{unbound:?}");
914 }
915 }
916
917 #[test]
920 fn key_usage_decides_what_a_key_signs() {
921 let usage = |digital_signature, non_repudiation, key_cert_sign| {
922 Some(Usage {
923 digital_signature,
924 non_repudiation,
925 key_cert_sign,
926 })
927 };
928 let leaf = |usage| certificate(&[], &[], usage);
929 for signs in [
930 None,
931 usage(true, false, false),
932 usage(false, true, false),
933 usage(true, true, false),
934 ] {
935 assert!(leaf(signs).may_sign_tokens(), "{signs:?}");
936 }
937 for refused in [
938 usage(false, false, false),
939 usage(true, false, true),
940 usage(false, true, true),
941 usage(false, false, true),
942 ] {
943 assert!(!leaf(refused).may_sign_tokens(), "{refused:?}");
944 }
945
946 let ca = |usage| X509Certificate {
947 ca: true,
948 ..certificate(&[], &[], usage)
949 };
950 assert!(ca(None).may_issue());
951 assert!(ca(usage(false, false, true)).may_issue());
952 assert!(ca(usage(true, false, true)).may_issue());
953 assert!(!ca(usage(true, false, false)).may_issue());
954 assert!(!leaf(usage(false, false, true)).may_issue());
956 assert!(!leaf(None).may_issue());
957 }
958
959 #[test]
960 fn p384_points_are_uncompressed() {
961 let mut point = vec![0x04];
962 point.extend([0x11; 48]);
963 point.extend([0x22; 48]);
964 let jwk = serde_json::to_value(p384_jwk(&point).unwrap()).unwrap();
965 assert_eq!(jwk["crv"], "P-384");
966 assert_eq!(
967 base64url::decode(jwk["x"].as_str().unwrap()).unwrap(),
968 [0x11; 48]
969 );
970 assert_eq!(
971 base64url::decode(jwk["y"].as_str().unwrap()).unwrap(),
972 [0x22; 48]
973 );
974 let mut compressed = vec![0x02];
976 compressed.extend([0x11; 48]);
977 for invalid in [&compressed[..], &point[..96], &[]] {
978 assert!(matches!(p384_jwk(invalid), Err(X509Error::InvalidKey(_))));
979 }
980 }
981}