identity-kit 0.5.1

DID, key management and verifiable credential primitives
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
//! `KeyReference`, `KeyRole` and `KeyResolver`: where a token says its key is, and the trait
//! that finds it.

use core::fmt;
use std::error::Error;
use std::sync::Arc;

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use url::Url;

use super::dereference::{public_key, verification_method_in};
use super::{DereferenceError, Resolver};
use crate::did::{Did, DidDocument, DidError, DidUrl, VerificationRelationship};
use crate::jose::{CompactJws, Jwk, base64url};

/// Where a token says the key that signed it is (ADR 0006).
///
/// A JWT names its key in one of several ways: a DID URL in `kid`, a `#fragment` in `kid`
/// relative to a DID `iss`, a `kid` into the key set an HTTPS `iss` publishes, the key itself in
/// a `jwk` header, a certificate chain in `x5c`, or a key set URL in `jku`.
/// [`from_jws`](Self::from_jws) reads which from a JWS header; `sd_jwt_vc` builds one from a
/// `cnf` claim. A [`KeyResolver`] turns it into a key.
///
/// Resolving a reference says nothing about trust: a key by value resolves to itself whoever
/// made the token. Once the signature verifies, [`binds_to`](Self::binds_to) checks that the key
/// belongs to the party the token claims.
///
/// # Examples
///
/// ```
/// use identity_kit::jose::{CompactJws, JwtClaims};
/// use identity_kit::resolver::{KeyReference, KeyReferenceError};
///
/// // {"alg":"EdDSA","kid":"#key-1"}.{"iss":"did:example:123"}
/// let jws = CompactJws::decode(
///     "eyJhbGciOiJFZERTQSIsImtpZCI6IiNrZXktMSJ9.eyJpc3MiOiJkaWQ6ZXhhbXBsZToxMjMifQ.c2lnbmF0dXJl",
/// )?;
/// let claims: JwtClaims = jws.claims()?;
/// let reference = KeyReference::from_jws(&jws, claims.iss.as_deref())?;
/// assert_eq!(reference.to_string(), "did:example:123#key-1");
///
/// // A relative `kid` needs a DID to resolve against.
/// assert!(matches!(
///     KeyReference::from_jws(&jws, None),
///     Err(KeyReferenceError::RelativeKidWithoutIssuer(_))
/// ));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyReference {
    /// A verification method: a `kid` that is an absolute DID URL, or a `#fragment` joined with
    /// a DID `iss`.
    DidUrl(DidUrl),
    /// The public key itself, from a `jwk` header or `cnf.jwk`.
    Jwk(Box<Jwk>),
    /// An `x5c` certificate chain, DER, leaf first. `X509Resolver` (feature `x509`) resolves
    /// it against the application's trust anchors.
    X509Chain(Vec<Vec<u8>>),
    /// The key `kid` names in the key set of the HTTPS issuer `issuer` (SD-JWT VC ยง3.5).
    Jwks {
        /// The issuer, the `iss` of the token.
        issuer: Url,
        /// The `kid` of the key in the issuer's key set.
        kid: String,
    },
    /// The key set at `url`, from `jku`, and the `kid` that selects a key in it. No resolver in
    /// the crate handles it yet.
    Jku {
        /// The key set URL.
        url: Url,
        /// The `kid`, if the token has one.
        kid: Option<String>,
    },
}

impl KeyReference {
    /// Where the key of `jws` is, given the `iss` of its claims (when `iss` is a string): the
    /// first of the [`candidates`](Self::candidates).
    ///
    /// The header parameters are tried in this order, and the first that applies decides:
    ///
    /// 1. A `kid` that parses as a DID URL is [`DidUrl`](Self::DidUrl). A path or DID
    ///    parameters such as `versionId` are refused: they could select a document version
    ///    that still lists a retired key (ADR 0004).
    /// 2. A `kid` starting with `#` is joined with `iss` into a [`DidUrl`](Self::DidUrl) when
    ///    `iss` is a DID, and refused otherwise.
    /// 3. An `x5c` header is [`X509Chain`](Self::X509Chain), each certificate base64-decoded
    ///    but not parsed.
    /// 4. Another `kid`, with an `https` `iss`, is [`Jwks`](Self::Jwks).
    /// 5. A `jwk` header is [`Jwk`](Self::Jwk); a private key there is refused.
    /// 6. A `jku` header is [`Jku`](Self::Jku), with the `kid` when there is one.
    ///
    /// A certificate chain comes before the issuer's key set and a key by value: it is in the
    /// token, so it costs no request, and it is validated against trust anchors, where a
    /// `jwk` header only asserts itself (ADR 0008).
    ///
    /// # Errors
    ///
    /// A [`KeyReferenceError`]: [`Missing`](KeyReferenceError::Missing) when the header names no
    /// key, otherwise the parameter that is wrong.
    pub fn from_jws(jws: &CompactJws, iss: Option<&str>) -> Result<Self, KeyReferenceError> {
        Self::candidates(jws, iss).map(|mut candidates| candidates.swap_remove(0))
    }

    /// Every reference the header of `jws` makes, in the order [`from_jws`](Self::from_jws)
    /// lists; never empty.
    ///
    /// A token can carry the inputs of more than one mechanism, an `x5c` chain next to a `kid`
    /// and an HTTPS `iss`, say. Which one applies is the verifier's policy, not the token's
    /// (SD-JWT VC ยง3.5): a validator asks its [`KeyResolver`] for each candidate in turn and
    /// takes the first the resolver handles, so the resolvers an application configures are
    /// that policy. A candidate the resolver handles and fails to resolve ends the search.
    ///
    /// A malformed `x5c`, `jwk` or `jku` is skipped when another parameter makes a reference,
    /// as is a `kid` that names nothing by itself. A `kid` that is refused outright ends the
    /// search, whatever else the header carries: a DID URL with a path or DID parameters, or a
    /// `#fragment` without a DID `iss` to join it with.
    ///
    /// # Errors
    ///
    /// As [`from_jws`](Self::from_jws), when no parameter makes a reference.
    pub fn candidates(jws: &CompactJws, iss: Option<&str>) -> Result<Vec<Self>, KeyReferenceError> {
        let header = jws.header();
        let mut candidates = Vec::new();
        let (mut kid_error, mut error) = (None, None);
        let mut key_set = None;
        if let Some(kid) = header.kid.as_deref() {
            match Self::from_kid(kid, iss)? {
                Ok(reference @ Self::Jwks { .. }) => key_set = Some(reference),
                Ok(reference) => candidates.push(reference),
                Err(source) => {
                    kid_error = Some(KeyReferenceError::InvalidKid {
                        kid: kid.to_owned(),
                        source,
                    });
                }
            }
        }
        if let Some(x5c) = header.additional.get("x5c") {
            match x5c_chain(x5c) {
                Ok(chain) => candidates.push(Self::X509Chain(chain)),
                Err(e) => error = error.or(Some(e)),
            }
        }
        candidates.extend(key_set);
        if let Some(jwk) = &header.jwk {
            if jwk.is_private() {
                error = error.or(Some(KeyReferenceError::InvalidJwk(
                    "the `jwk` header holds a private key".to_owned(),
                )));
            } else {
                candidates.push(Self::Jwk(Box::new(jwk.clone())));
            }
        }
        if let Some(jku) = header.additional.get("jku") {
            let url = jku
                .as_str()
                .ok_or_else(|| KeyReferenceError::InvalidUrl {
                    parameter: "jku",
                    value: jku.to_string(),
                    reason: "not a string".to_owned(),
                })
                .and_then(|jku| parse_url("jku", jku));
            match url {
                Ok(url) => candidates.push(Self::Jku {
                    url,
                    kid: header.kid.clone(),
                }),
                Err(e) => error = error.or(Some(e)),
            }
        }
        if candidates.is_empty() {
            return Err(error.or(kid_error).unwrap_or(KeyReferenceError::Missing));
        }
        Ok(candidates)
    }

    /// The reference `kid` makes with `iss`: a [`DidUrl`](Self::DidUrl) for a DID URL or a
    /// `#fragment` of a DID `iss`, a [`Jwks`](Self::Jwks) for another `kid` of an `https`
    /// `iss`, or why `kid` is not a DID URL when it makes none.
    fn from_kid(kid: &str, iss: Option<&str>) -> Result<Result<Self, DidError>, KeyReferenceError> {
        let not_did_url = match DidUrl::parse(kid) {
            Ok(url) => return did_url(url).map(Ok),
            Err(error) => error,
        };
        if kid.starts_with('#') {
            let did = iss
                .and_then(|iss| Did::parse(iss).ok())
                .ok_or_else(|| KeyReferenceError::RelativeKidWithoutIssuer(kid.to_owned()))?;
            let url = did
                .join(kid)
                .map_err(|source| KeyReferenceError::InvalidKid {
                    kid: kid.to_owned(),
                    source,
                })?;
            return did_url(url).map(Ok);
        }
        if let Some(issuer) = iss
            .and_then(|iss| Url::parse(iss).ok())
            .filter(|issuer| issuer.scheme() == "https")
        {
            return Ok(Ok(Self::Jwks {
                issuer,
                kid: kid.to_owned(),
            }));
        }
        Ok(Err(not_did_url))
    }

    /// Whether `key`, which this reference resolved to and which verified the signature,
    /// belongs to `party`, the issuer or holder the token claims:
    ///
    /// | Reference | Binds when |
    /// |---|---|
    /// | [`DidUrl`](Self::DidUrl) | `party` is the DID of the URL |
    /// | [`Jwk`](Self::Jwk) | `party` is the `did:jwk` of `key`, or its RFC 7638 SHA-256 thumbprint, or absent (a SIOPv2 self-issued `sub`) |
    /// | [`Jwks`](Self::Jwks) | `party` is the issuer URL (compared as parsed URLs) |
    /// | [`X509Chain`](Self::X509Chain) | with the `x509` feature: `party` is absent, or an `https` URL whose host is a DNS name of the first certificate (`X509Certificate::binds`) |
    /// | [`Jku`](Self::Jku) | never, until the crate resolves it |
    ///
    /// A key by value and a certificate chain can bind to no party; a validator that requires
    /// an issuer or holder passes it. With a certificate chain, the party that signed is the
    /// subject of the first certificate, and a claimed `iss` is not authenticated by the chain
    /// (SD-JWT VC ยง3.5): it binds only when the certificate names its host. A DID never binds
    /// to a chain.
    ///
    /// # Examples
    ///
    /// ```
    /// use identity_kit::did::DidUrl;
    /// use identity_kit::jose::Jwk;
    /// use identity_kit::resolver::KeyReference;
    ///
    /// // RFC 8037 Appendix A.2.
    /// let key: Jwk = serde_json::from_str(
    ///     r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
    /// )?;
    /// let by_value = KeyReference::Jwk(Box::new(key.clone()));
    /// // RFC 8037 Appendix A.3.
    /// assert!(by_value.binds_to(Some("kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"), &key));
    /// assert!(by_value.binds_to(None, &key));
    /// assert!(!by_value.binds_to(Some("did:example:123"), &key));
    ///
    /// let by_url = KeyReference::DidUrl(DidUrl::parse("did:example:123#key-1")?);
    /// assert!(by_url.binds_to(Some("did:example:123"), &key));
    /// assert!(!by_url.binds_to(Some("did:example:456"), &key));
    /// assert!(!by_url.binds_to(None, &key));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn binds_to(&self, party: Option<&str>, key: &Jwk) -> bool {
        match (self, party) {
            (Self::DidUrl(url), Some(party)) => {
                Did::parse(party).is_ok_and(|did| did == *url.did())
            }
            (Self::Jwk(_), None) => true,
            (Self::Jwk(_), Some(party)) => is_key_identifier(party, key),
            (Self::Jwks { issuer, .. }, Some(party)) => {
                Url::parse(party).is_ok_and(|party| party == *issuer)
            }
            #[cfg(feature = "x509")]
            (Self::X509Chain(_), None) => true,
            #[cfg(feature = "x509")]
            (Self::X509Chain(chain), Some(party)) => chain
                .first()
                .and_then(|leaf| super::X509Certificate::from_der(leaf).ok())
                .is_some_and(|leaf| leaf.binds(party)),
            _ => false,
        }
    }
}

impl fmt::Display for KeyReference {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DidUrl(url) => fmt::Display::fmt(url, f),
            Self::Jwk(jwk) => match jwk.thumbprint_sha256() {
                Ok(thumbprint) => write!(f, "JWK {thumbprint}"),
                Err(_) => f.write_str("JWK"),
            },
            Self::X509Chain(chain) => write!(f, "`x5c` chain of {} certificates", chain.len()),
            Self::Jwks { issuer, kid } => write!(f, "`{kid}` of issuer `{issuer}`"),
            Self::Jku {
                url,
                kid: Some(kid),
            } => write!(f, "`{kid}` of `{url}`"),
            Self::Jku { url, kid: None } => write!(f, "the key of `{url}`"),
        }
    }
}

/// `url`, refused when it carries a path or DID parameters.
fn did_url(url: DidUrl) -> Result<KeyReference, KeyReferenceError> {
    if url.path().is_some() || url.query().is_some() {
        return Err(KeyReferenceError::KidWithParameters(url));
    }
    Ok(KeyReference::DidUrl(url))
}

/// The certificates of an `x5c` header: an array of standard base64 DER (RFC 7515 ยง4.1.6).
fn x5c_chain(x5c: &serde_json::Value) -> Result<Vec<Vec<u8>>, KeyReferenceError> {
    let invalid = |reason: &str| KeyReferenceError::InvalidX5c(reason.to_owned());
    let certificates = x5c.as_array().ok_or_else(|| invalid("not an array"))?;
    if certificates.is_empty() {
        return Err(invalid("the chain is empty"));
    }
    certificates
        .iter()
        .map(|certificate| {
            let certificate = certificate
                .as_str()
                .ok_or_else(|| invalid("a certificate is not a string"))?;
            STANDARD
                .decode(certificate)
                .map_err(|_| invalid("a certificate is not base64"))
        })
        .collect()
}

/// `value` of `parameter` as an absolute URL.
fn parse_url(parameter: &'static str, value: &str) -> Result<Url, KeyReferenceError> {
    Url::parse(value).map_err(|e| KeyReferenceError::InvalidUrl {
        parameter,
        value: value.to_owned(),
        reason: e.to_string(),
    })
}

/// Whether `party` is the `did:jwk` or the RFC 7638 SHA-256 thumbprint of `key`.
fn is_key_identifier(party: &str, key: &Jwk) -> bool {
    let Ok(thumbprint) = key.thumbprint_sha256() else {
        return false;
    };
    if party == thumbprint {
        return true;
    }
    // A `did:jwk` names the key by value, in whatever member order its creator serialized it;
    // the thumbprint compares the required members only.
    Did::parse(party)
        .ok()
        .filter(|did| did.method() == "jwk")
        .and_then(|did| base64url::decode(did.method_specific_id()).ok())
        .and_then(|json| serde_json::from_slice::<Jwk>(&json).ok())
        .and_then(|jwk| jwk.thumbprint_sha256().ok())
        .is_some_and(|named| named == thumbprint)
}

/// Why a token names no key this crate can look for.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum KeyReferenceError {
    /// The token names no key: no `kid`, `jwk`, `x5c` or `jku` (or, in `cnf`, no `jwk`, `kid`
    /// or `jku`).
    #[error("the token names no key: no `kid`, `jwk`, `x5c` or `jku`")]
    Missing,
    /// The `kid` is a `#fragment` and `iss` is not a DID to resolve it against.
    #[error("`kid` {0:?} is relative and `iss` is not a DID")]
    RelativeKidWithoutIssuer(String),
    /// The `kid` is neither a DID URL nor anything else the token resolves it with.
    #[error("`kid` {kid:?} is not a DID URL: {source}")]
    InvalidKid {
        /// The `kid`.
        kid: String,
        /// Why it is not a DID URL.
        #[source]
        source: DidError,
    },
    /// The `kid` carries a path or DID parameters. `versionId` and `versionTime` could select a
    /// document version that still lists a retired key, so only `did:โ€ฆ#fragment` keys are
    /// accepted.
    #[error("`kid` `{0}` carries a path or DID parameters")]
    KidWithParameters(DidUrl),
    /// The key by value is not usable: it holds private material, say.
    #[error("invalid `jwk`: {0}")]
    InvalidJwk(String),
    /// The `x5c` header is not an array of base64 certificates.
    #[error("invalid `x5c`: {0}")]
    InvalidX5c(String),
    /// A URL parameter (`jku`) is not an absolute URL.
    #[error("`{parameter}` {value:?} is not a URL: {reason}")]
    InvalidUrl {
        /// The parameter.
        parameter: &'static str,
        /// Its value.
        value: String,
        /// Why it did not parse.
        reason: String,
    },
    /// The confirmation names its key only by a method the crate does not resolve, such as
    /// `x5t#S256` or `jwe`.
    #[error("`cnf` names its key only by `{0}`, which is not supported")]
    UnsupportedConfirmation(String),
}

/// The role a key plays in a token, which decides what a DID document must say about it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum KeyRole {
    /// The key signs as the issuer of a credential or status list: `assertionMethod`. The
    /// default.
    #[default]
    Issuer,
    /// The key proves possession by the subject or holder (a presentation, a key binding JWT,
    /// an ID token): `authentication`.
    Subject,
}

impl KeyRole {
    /// The verification relationship a DID document must list a key of this role under.
    pub fn relationship(self) -> VerificationRelationship {
        match self {
            Self::Issuer => VerificationRelationship::AssertionMethod,
            Self::Subject => VerificationRelationship::Authentication,
        }
    }
}

/// Finds the public key a [`KeyReference`] names.
///
/// [`Resolver`] implements it for DID URLs, [`JwkResolver`] for keys by value and, with the
/// `jwks` feature, `JwksResolver` for the key sets of HTTPS issuers;
/// [`CompositeKeyResolver`] combines them. An application can implement it over a cache, a
/// fixed set of trusted keys, or a reference the crate does not resolve.
#[async_trait::async_trait]
pub trait KeyResolver: Send + Sync {
    /// The public key `key` names, usable in `role`.
    ///
    /// # Errors
    ///
    /// [`KeyResolutionError::Unsupported`] for a kind of reference this resolver does not
    /// handle, which lets a [`CompositeKeyResolver`] try the next one; any other
    /// [`KeyResolutionError`] when the key cannot be found or used.
    async fn resolve_key(
        &self,
        key: &KeyReference,
        role: KeyRole,
    ) -> Result<Jwk, KeyResolutionError>;

    /// The public key `key` names, usable in `role` at `now`, the validation time in seconds
    /// since the Unix epoch.
    ///
    /// The validators call this method, with the time they validate at. The default ignores
    /// the time and calls [`resolve_key`](Self::resolve_key), which is right for a key that
    /// does not depend on it; a resolver whose answer does, such as `X509Resolver` with the
    /// validity periods of certificates, implements it.
    ///
    /// A resolver that wraps another one (a cache, a filter, a logger) must implement this
    /// method too and forward it: left to the default, it would answer for the current time
    /// whatever time the validator asked for, and a certificate chain would be validated at
    /// the wrong one.
    ///
    /// # Errors
    ///
    /// As [`resolve_key`](Self::resolve_key).
    async fn resolve_key_at(
        &self,
        key: &KeyReference,
        role: KeyRole,
        now: i64,
    ) -> Result<Jwk, KeyResolutionError> {
        let _ = now;
        self.resolve_key(key, role).await
    }
}

/// The key of `jws`, `iss` being the issuer its claims name, for `role` at `now`: the first of
/// the [candidates](KeyReference::candidates) that `resolver` handles, with its reference.
///
/// # Errors
///
/// [`JwsKeyError::Reference`] when the header names no key, and [`JwsKeyError::Resolution`]
/// with the candidate that failed, or with the first one when the resolver handles none.
pub(crate) async fn resolve_jws_key<R: KeyResolver + ?Sized>(
    resolver: &R,
    jws: &CompactJws,
    iss: Option<&str>,
    role: KeyRole,
    now: i64,
) -> Result<(KeyReference, Jwk), JwsKeyError> {
    let mut unsupported = None;
    for reference in KeyReference::candidates(jws, iss).map_err(JwsKeyError::Reference)? {
        match resolver.resolve_key_at(&reference, role, now).await {
            Ok(key) => return Ok((reference, key)),
            Err(source) if source.is_unsupported() => {
                unsupported.get_or_insert(JwsKeyError::Resolution {
                    key: Box::new(reference),
                    source,
                });
            }
            Err(source) => {
                return Err(JwsKeyError::Resolution {
                    key: Box::new(reference),
                    source,
                });
            }
        }
    }
    // `candidates` is never empty, so a search without a key ended on an unsupported one.
    Err(unsupported.unwrap_or(JwsKeyError::Reference(KeyReferenceError::Missing)))
}

/// Why [`resolve_jws_key`] found no key.
#[derive(Debug)]
pub(crate) enum JwsKeyError {
    /// The token names no key.
    Reference(KeyReferenceError),
    /// The resolver did not resolve `key`.
    Resolution {
        /// The reference.
        key: Box<KeyReference>,
        /// Why it did not resolve.
        source: KeyResolutionError,
    },
}

// Implements `KeyResolver` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`.
// A method added to the trait is added here too: one with a default body would still compile
// if left out, and calls through these wrappers would then run the default, not `T`'s
// override. `clippy::missing_trait_methods` turns that omission into an error.
macro_rules! forward_key_resolver {
    ($($ty:ty),* $(,)?) => {$(
        #[async_trait::async_trait]
        #[deny(clippy::missing_trait_methods)]
        impl<T: KeyResolver + ?Sized> KeyResolver for $ty {
            async fn resolve_key(
                &self,
                key: &KeyReference,
                role: KeyRole,
            ) -> Result<Jwk, KeyResolutionError> {
                (**self).resolve_key(key, role).await
            }

            async fn resolve_key_at(
                &self,
                key: &KeyReference,
                role: KeyRole,
                now: i64,
            ) -> Result<Jwk, KeyResolutionError> {
                (**self).resolve_key_at(key, role, now).await
            }
        }
    )*};
}

forward_key_resolver!(&T, Box<T>, Arc<T>);

/// Resolves a [`KeyReference::DidUrl`] by dereferencing it to a verification method listed
/// under the relationship of the role; every other reference is
/// [`Unsupported`](KeyResolutionError::Unsupported).
#[async_trait::async_trait]
impl KeyResolver for Resolver {
    async fn resolve_key(
        &self,
        key: &KeyReference,
        role: KeyRole,
    ) -> Result<Jwk, KeyResolutionError> {
        match key {
            KeyReference::DidUrl(url) => self
                .resolve_public_key(url, Some(role.relationship()))
                .await
                .map_err(KeyResolutionError::from),
            other => Err(KeyResolutionError::unsupported(other)),
        }
    }
}

/// Resolves a [`KeyReference::Jwk`] to its public part; every other reference is
/// [`Unsupported`](KeyResolutionError::Unsupported).
///
/// Anybody can put a key in a `jwk` header, so the key says nothing about who signed: a
/// validator accepts it only when the claimed party is that key's `did:jwk` or thumbprint
/// ([`KeyReference::binds_to`]). Add it to a [`CompositeKeyResolver`] to accept such tokens.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct JwkResolver;

#[async_trait::async_trait]
impl KeyResolver for JwkResolver {
    async fn resolve_key(&self, key: &KeyReference, _: KeyRole) -> Result<Jwk, KeyResolutionError> {
        match key {
            KeyReference::Jwk(jwk) => Ok(jwk.public()),
            other => Err(KeyResolutionError::unsupported(other)),
        }
    }
}

/// Resolves a [`KeyReference::DidUrl`] against DID documents supplied by the caller, without
/// resolving the DID again: a document resolved to read its services, or one the caller
/// fetched or publishes itself.
///
/// A DID URL of one of the documents' DIDs resolves to the verification method its fragment
/// names, which must be usable for the relationship of the role, as [`Resolver`] would:
/// `publicKeyJwk` as it is, `publicKeyMultibase` decoded as a Multikey. Every other reference
/// is [`Unsupported`](KeyResolutionError::Unsupported), so that a [`CompositeKeyResolver`]
/// tries the next resolver: a DID URL of another DID, and one with a path or query, such as a
/// `versionId`, which names a document other than the one supplied.
///
/// # Examples
///
/// The caller supplies a presentation's holder document; issuers' keys still resolve over the
/// network.
///
/// ```
/// # #[cfg(feature = "did-key")]
/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
/// use identity_kit::did::{DidDocument, DidUrl};
/// use identity_kit::jose::Jwk;
/// use identity_kit::methods::DidKey;
/// use identity_kit::resolver::{
///     CompositeKeyResolver, DocumentKeyResolver, KeyReference, KeyResolver as _, KeyRole,
///     Resolver,
/// };
///
/// // The holder's `did:web` document, already resolved; its key is RFC 7515 Appendix A.3's.
/// let holder: DidDocument = serde_json::from_str(r##"{
///   "id": "did:web:holder.example",
///   "verificationMethod": [{
///     "id": "did:web:holder.example#key-1",
///     "type": "JsonWebKey",
///     "controller": "did:web:holder.example",
///     "publicKeyJwk": {
///       "kty": "EC", "crv": "P-256",
///       "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
///       "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
///     }
///   }],
///   "authentication": ["#key-1"]
/// }"##)?;
/// let resolver = CompositeKeyResolver::new()
///     .with(DocumentKeyResolver::new(holder))
///     .with(Resolver::builder().with(DidKey::default()).build());
///
/// let holder_key = KeyReference::DidUrl("did:web:holder.example#key-1".parse()?);
/// let jwk = resolver.resolve_key(&holder_key, KeyRole::Subject).await?;
/// assert_eq!(jwk.kty(), "EC");
/// // Listed under `authentication` only: not a key the holder issues with.
/// assert!(resolver.resolve_key(&holder_key, KeyRole::Issuer).await.is_err());
///
/// // An issuer's `did:key` falls through to the `Resolver`: RFC 8037 Appendix A.2's key.
/// let issuer = DidKey::did(&serde_json::from_str::<Jwk>(
///     r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
/// )?)?;
/// let issuer_key: DidUrl = issuer.join(&format!("#{}", issuer.method_specific_id()))?;
/// assert!(resolver.resolve_key(&KeyReference::DidUrl(issuer_key), KeyRole::Issuer).await.is_ok());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct DocumentKeyResolver {
    documents: Vec<DidDocument>,
}

impl DocumentKeyResolver {
    /// A resolver over `document`.
    pub fn new(document: DidDocument) -> Self {
        Self {
            documents: vec![document],
        }
    }

    /// This resolver over `document` as well. A document of a DID already supplied replaces the
    /// earlier one.
    #[must_use]
    pub fn with(mut self, document: DidDocument) -> Self {
        self.documents.retain(|supplied| supplied.id != document.id);
        self.documents.push(document);
        self
    }

    /// The documents it resolves against.
    pub fn documents(&self) -> &[DidDocument] {
        &self.documents
    }
}

#[async_trait::async_trait]
impl KeyResolver for DocumentKeyResolver {
    async fn resolve_key(
        &self,
        key: &KeyReference,
        role: KeyRole,
    ) -> Result<Jwk, KeyResolutionError> {
        let KeyReference::DidUrl(url) = key else {
            return Err(KeyResolutionError::unsupported(key));
        };
        let document = self
            .documents
            .iter()
            .find(|document| document.id == *url.did())
            .filter(|_| url.path().is_none() && url.query().is_none());
        let Some(document) = document else {
            return Err(KeyResolutionError::unsupported(key));
        };
        verification_method_in(document, url, Some(role.relationship()))
            .and_then(public_key)
            .map_err(KeyResolutionError::from)
    }
}

/// Resolvers tried in order: the first answer other than
/// [`Unsupported`](KeyResolutionError::Unsupported) is the answer, an error included.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "did-key")]
/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
/// use identity_kit::jose::Jwk;
/// use identity_kit::methods::DidKey;
/// use identity_kit::resolver::{CompositeKeyResolver, JwkResolver, KeyReference, KeyResolver as _, KeyRole, Resolver};
///
/// let resolver = CompositeKeyResolver::new()
///     .with(Resolver::builder().with(DidKey::default()).build())
///     .with(JwkResolver);
///
/// // RFC 8037 Appendix A.2.
/// let key: Jwk = serde_json::from_str(
///     r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
/// )?;
/// let resolved = resolver.resolve_key(&KeyReference::Jwk(Box::new(key.clone())), KeyRole::Issuer).await?;
/// assert_eq!(resolved, key);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Default)]
pub struct CompositeKeyResolver {
    resolvers: Vec<Arc<dyn KeyResolver>>,
}

impl CompositeKeyResolver {
    /// A resolver with nothing to try: every reference is unsupported.
    pub fn new() -> Self {
        Self::default()
    }

    /// This resolver trying `resolver` after the ones added before.
    #[must_use]
    pub fn with(mut self, resolver: impl KeyResolver + 'static) -> Self {
        self.resolvers.push(Arc::new(resolver));
        self
    }

    /// This resolver trying the shared `resolver` after the ones added before.
    #[must_use]
    pub fn with_shared(mut self, resolver: Arc<dyn KeyResolver>) -> Self {
        self.resolvers.push(resolver);
        self
    }

    /// How many resolvers it tries.
    pub fn len(&self) -> usize {
        self.resolvers.len()
    }

    /// Whether it has no resolver to try.
    pub fn is_empty(&self) -> bool {
        self.resolvers.is_empty()
    }
}

impl fmt::Debug for CompositeKeyResolver {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompositeKeyResolver")
            .field("resolvers", &self.resolvers.len())
            .finish()
    }
}

#[async_trait::async_trait]
impl KeyResolver for CompositeKeyResolver {
    async fn resolve_key(
        &self,
        key: &KeyReference,
        role: KeyRole,
    ) -> Result<Jwk, KeyResolutionError> {
        for resolver in &self.resolvers {
            match resolver.resolve_key(key, role).await {
                Err(KeyResolutionError::Unsupported(_)) => {}
                answer => return answer,
            }
        }
        Err(KeyResolutionError::unsupported(key))
    }

    async fn resolve_key_at(
        &self,
        key: &KeyReference,
        role: KeyRole,
        now: i64,
    ) -> Result<Jwk, KeyResolutionError> {
        for resolver in &self.resolvers {
            match resolver.resolve_key_at(key, role, now).await {
                Err(KeyResolutionError::Unsupported(_)) => {}
                answer => return answer,
            }
        }
        Err(KeyResolutionError::unsupported(key))
    }
}

/// Why a [`KeyResolver`] found no key.
#[derive(Debug)]
#[non_exhaustive]
pub enum KeyResolutionError {
    /// The resolver does not handle this kind of reference.
    Unsupported(Box<KeyReference>),
    /// The resolver handles the reference and could not find or use the key.
    Failed(Box<dyn Error + Send + Sync + 'static>),
}

impl KeyResolutionError {
    /// The resolver does not handle `key`.
    pub fn unsupported(key: &KeyReference) -> Self {
        Self::Unsupported(Box::new(key.clone()))
    }

    /// A failure caused by `error`.
    pub fn new<E: Error + Send + Sync + 'static>(error: E) -> Self {
        Self::Failed(Box::new(error))
    }

    /// A failure described by `message` only.
    pub fn msg<M: fmt::Display>(message: M) -> Self {
        Self::Failed(message.to_string().into())
    }

    /// Whether the resolver does not handle the reference.
    pub fn is_unsupported(&self) -> bool {
        matches!(self, Self::Unsupported(_))
    }

    /// The error that caused a failure.
    pub fn inner(&self) -> Option<&(dyn Error + Send + Sync + 'static)> {
        match self {
            Self::Failed(error) => Some(&**error),
            Self::Unsupported(_) => None,
        }
    }
}

impl fmt::Display for KeyResolutionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unsupported(reference) => write!(f, "no resolver handles {reference}"),
            Self::Failed(error) => fmt::Display::fmt(error, f),
        }
    }
}

impl Error for KeyResolutionError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Failed(error) => error.source(),
            Self::Unsupported(_) => None,
        }
    }
}

impl From<DereferenceError> for KeyResolutionError {
    fn from(error: DereferenceError) -> Self {
        Self::new(error)
    }
}