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
//! Compact JWS serialization (RFC 7515 §7.1): decoding without verification, and encoding with
//! a [`Signer`].

use core::fmt;

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use indexmap::IndexMap;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::{Jwk, JwsAlgorithm, JwsError, JwsVerifier, SignError, VerificationError, base64url};

/// The JOSE header of a JWS (RFC 7515 §4).
///
/// The registered parameters this crate acts on are fields; everything else, `x5c` and `b64`
/// included, lives in `additional` in insertion order. `jwk` is the public key the signer claims
/// to have used; trusting it is the verifier's decision, never the crate's.
///
/// # Examples
///
/// ```
/// use identity_kit::jose::{JwsAlgorithm, JwsHeader};
///
/// let mut header = JwsHeader::new(JwsAlgorithm::ES256).with_kid("did:example:123#key-1");
/// header.typ = Some("JWT".to_owned());
/// assert_eq!(
///     serde_json::to_string(&header)?,
///     r#"{"alg":"ES256","typ":"JWT","kid":"did:example:123#key-1"}"#
/// );
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct JwsHeader {
    /// The signature algorithm (`alg`).
    pub alg: JwsAlgorithm,
    /// The media type of the whole JWS (`typ`), such as `JWT` or `vc+jwt`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub typ: Option<String>,
    /// The media type of the payload (`cty`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cty: Option<String>,
    /// The key id (`kid`); for a DID controller, usually a DID URL with a fragment.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kid: Option<String>,
    /// The public key the signature was made with (`jwk`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jwk: Option<Jwk>,
    /// Extensions a recipient must understand (`crit`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crit: Option<Vec<String>>,
    /// Every other header parameter, in insertion order.
    #[serde(flatten)]
    pub additional: IndexMap<String, Value>,
}

impl JwsHeader {
    /// A header with only `alg` set.
    pub fn new(alg: JwsAlgorithm) -> Self {
        Self {
            alg,
            typ: None,
            cty: None,
            kid: None,
            jwk: None,
            crit: None,
            additional: IndexMap::new(),
        }
    }

    /// This header with its `kid` set.
    #[must_use]
    pub fn with_kid(mut self, kid: impl Into<String>) -> Self {
        self.kid = Some(kid.into());
        self
    }

    /// This header with its `typ` set.
    #[must_use]
    pub fn with_typ(mut self, typ: impl Into<String>) -> Self {
        self.typ = Some(typ.into());
        self
    }

    /// This header with `chain` as its `x5c` parameter (RFC 7515 §4.1.6): DER-encoded
    /// certificates, the one of the signing key first, each followed by the one that
    /// certifies it.
    ///
    /// HAIP requires more of every `x5c` it defines: the first certificate is not
    /// self-signed, and the chain leaves out the trust anchor.
    #[must_use]
    pub fn with_x5c<C: AsRef<[u8]>>(mut self, chain: &[C]) -> Self {
        let chain = chain
            .iter()
            .map(|certificate| Value::String(STANDARD.encode(certificate)))
            .collect();
        self.additional
            .insert("x5c".to_owned(), Value::Array(chain));
        self
    }

    /// The header a token signed by `signer` starts from: its algorithm, and what names its
    /// key, the certificate chain of [`Signer::x5c`] when it has one, otherwise its
    /// [`kid`](Signer::kid).
    pub fn for_signer(signer: &dyn Signer) -> Self {
        let header = Self::new(signer.alg());
        // An empty chain names no key: RFC 7515 §4.1.6 has at least the key's own certificate.
        match signer.x5c().filter(|chain| !chain.is_empty()) {
            Some(chain) => header.with_x5c(chain),
            None => Self {
                kid: signer.kid().map(str::to_owned),
                ..header
            },
        }
    }
}

/// A decoded compact JWS: `BASE64URL(header) || '.' || BASE64URL(payload) || '.' ||
/// BASE64URL(signature)`.
///
/// Decoding parses the header and the parts and nothing more: [`CompactJws::verify`] (or any
/// [`JwsVerifier`]) checks the signature once the caller has resolved the key, which usually
/// means dereferencing [`kid`](Self::kid) through a DID resolver.
///
/// # Examples
///
/// ```
/// use identity_kit::jose::{CompactJws, JwsAlgorithm};
///
/// // RFC 8037 Appendix A.4.
/// let token = "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.\
///              hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg";
/// let jws = CompactJws::decode(token)?;
/// assert_eq!(jws.alg(), JwsAlgorithm::EdDSA);
/// assert_eq!(jws.kid(), None);
/// assert_eq!(jws.payload(), b"Example of Ed25519 signing");
/// assert_eq!(
///     jws.signing_input(),
///     b"eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc"
/// );
/// assert_eq!(jws.signature().len(), 64);
/// # Ok::<(), identity_kit::jose::JwsError>(())
/// ```
#[derive(Debug, Clone)]
pub struct CompactJws {
    token: String,
    /// Byte offset of the `.` between payload and signature; the signing input ends there.
    signing_input_end: usize,
    header: JwsHeader,
    payload: Vec<u8>,
    signature: Vec<u8>,
}

impl CompactJws {
    /// Parses a compact JWS without verifying it.
    ///
    /// # Errors
    ///
    /// A [`JwsError`] when the input is not three base64url parts, the header is not a JSON
    /// object with a supported `alg`, or the header has `crit` or `b64: false`.
    pub fn decode(token: &str) -> Result<Self, JwsError> {
        let mut parts = token.split('.');
        let (Some(header_b64), Some(payload_b64), Some(signature_b64), None) =
            (parts.next(), parts.next(), parts.next(), parts.next())
        else {
            return Err(JwsError::InvalidFormat {
                parts: token.split('.').count(),
            });
        };
        let header_json = base64url::decode(header_b64)
            .map_err(|_| JwsError::InvalidBase64Url { part: "header" })?;
        let header = parse_header(&header_json)?;
        let payload = base64url::decode(payload_b64)
            .map_err(|_| JwsError::InvalidBase64Url { part: "payload" })?;
        let signature = base64url::decode(signature_b64)
            .map_err(|_| JwsError::InvalidBase64Url { part: "signature" })?;
        Ok(Self {
            token: token.to_owned(),
            signing_input_end: header_b64.len() + 1 + payload_b64.len(),
            header,
            payload,
            signature,
        })
    }

    /// The protected header.
    pub fn header(&self) -> &JwsHeader {
        &self.header
    }

    /// The header `alg`.
    pub fn alg(&self) -> JwsAlgorithm {
        self.header.alg
    }

    /// The header `kid`, if any.
    pub fn kid(&self) -> Option<&str> {
        self.header.kid.as_deref()
    }

    /// The JWS signing input: `BASE64URL(header) || '.' || BASE64URL(payload)` as ASCII.
    pub fn signing_input(&self) -> &[u8] {
        &self.token.as_bytes()[..self.signing_input_end]
    }

    /// The decoded payload.
    pub fn payload(&self) -> &[u8] {
        &self.payload
    }

    /// The decoded signature.
    pub fn signature(&self) -> &[u8] {
        &self.signature
    }

    /// The payload read as JSON into `T`, a [`JwtClaims`](super::JwtClaims) set say, unverified:
    /// nothing about the signature or the claims is checked.
    ///
    /// # Errors
    ///
    /// [`JwsError::InvalidPayload`] when the payload is not JSON of the shape `T` expects.
    ///
    /// # Examples
    ///
    /// ```
    /// use identity_kit::jose::{CompactJws, JwtClaims};
    ///
    /// // RFC 7515 Appendix A.3: the RFC 7519 §3.1 claims set, signed with ES256.
    /// let jws = CompactJws::decode(
    ///     "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGF\
    ///      tcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDx\
    ///      w5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q",
    /// )?;
    /// let claims: JwtClaims = jws.claims()?;
    /// assert_eq!(claims.iss.as_deref(), Some("joe"));
    /// assert_eq!(claims.exp, Some(1300819380));
    /// assert_eq!(claims.additional["http://example.com/is_root"], true);
    /// # Ok::<(), identity_kit::jose::JwsError>(())
    /// ```
    pub fn claims<T: DeserializeOwned>(&self) -> Result<T, JwsError> {
        serde_json::from_slice(&self.payload).map_err(|e| JwsError::InvalidPayload {
            reason: "not JSON of the expected shape".to_owned(),
            source: Some(e),
        })
    }

    /// The compact serialization as it was decoded.
    pub fn as_str(&self) -> &str {
        &self.token
    }

    /// Verifies the signature with `verifier` under `key` and the header `alg`.
    ///
    /// # Errors
    ///
    /// Whatever the verifier reports; see [`JwsVerifier::verify`].
    pub fn verify<V: JwsVerifier + ?Sized>(
        &self,
        verifier: &V,
        key: &Jwk,
    ) -> Result<(), VerificationError> {
        verifier.verify(self.alg(), self.signing_input(), &self.signature, key)
    }
}

impl fmt::Display for CompactJws {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.token)
    }
}

impl AsRef<str> for CompactJws {
    fn as_ref(&self) -> &str {
        &self.token
    }
}

/// A [`JwsError::InvalidHeader`] for `reason`, caused by `source`.
fn header_error(reason: &str, source: serde_json::Error) -> JwsError {
    JwsError::InvalidHeader {
        reason: reason.to_owned(),
        source: Some(source),
    }
}

/// Parses the header JSON, naming an unsupported `alg` and rejecting `crit` and `b64: false`.
fn parse_header(json: &[u8]) -> Result<JwsHeader, JwsError> {
    let value: Value = serde_json::from_slice(json).map_err(|e| header_error("not JSON", e))?;
    let Some(object) = value.as_object() else {
        return Err(JwsError::InvalidHeader {
            reason: "not a JSON object".to_owned(),
            source: None,
        });
    };
    match object.get("alg") {
        Some(Value::String(alg)) if alg.parse::<JwsAlgorithm>().is_ok() => {}
        Some(Value::String(alg)) => return Err(JwsError::UnsupportedAlgorithm(alg.clone())),
        Some(other) => return Err(JwsError::UnsupportedAlgorithm(other.to_string())),
        None => {
            return Err(JwsError::InvalidHeader {
                reason: "missing `alg`".to_owned(),
                source: None,
            });
        }
    }
    if object
        .get("b64")
        .is_some_and(|b64| b64 != &Value::Bool(true))
    {
        return Err(JwsError::UnencodedPayload);
    }
    let header: JwsHeader =
        serde_json::from_value(value).map_err(|e| header_error("a member is malformed", e))?;
    if let Some(crit) = &header.crit {
        return Err(JwsError::UnsupportedCritical(crit.clone()));
    }
    Ok(header)
}

/// Produces JWS signatures.
///
/// A signer binds one key and one algorithm. Private keys live behind it, in a key store, an HSM
/// or a cloud service, which is why signing is `async`. The signature is returned in the JWS form
/// of the algorithm: raw `r || s` for ECDSA, never DER.
#[async_trait::async_trait]
pub trait Signer: Send + Sync {
    /// The algorithm every signature of this signer uses.
    fn alg(&self) -> JwsAlgorithm;

    /// The key id to put in a header, if the signer has one.
    fn kid(&self) -> Option<&str>;

    /// The certificate chain of the signing key to put in an `x5c` header, if the signer has
    /// one: DER-encoded certificates, the key's own first. `None` by default;
    /// [`CertifiedSigner`] gives a signer one. A signer that wraps another one forwards it.
    fn x5c(&self) -> Option<&[Vec<u8>]> {
        None
    }

    /// Signs `signing_input`.
    ///
    /// # Errors
    ///
    /// A [`SignError`] wrapping whatever the backend reports.
    async fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, SignError>;
}

// Implements `Signer` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`, so
// that a signer behind a reference or a `Box<dyn Signer>`, as an `Identity` returns one, can
// be wrapped or passed on. 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_signer {
    ($($ty:ty),* $(,)?) => {$(
        #[async_trait::async_trait]
        #[deny(clippy::missing_trait_methods)]
        impl<T: Signer + ?Sized> Signer for $ty {
            fn alg(&self) -> JwsAlgorithm {
                (**self).alg()
            }

            fn kid(&self) -> Option<&str> {
                (**self).kid()
            }

            fn x5c(&self) -> Option<&[Vec<u8>]> {
                (**self).x5c()
            }

            async fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, SignError> {
                (**self).sign(signing_input).await
            }
        }
    )*};
}

forward_signer!(&T, Box<T>, std::sync::Arc<T>);

/// A [`Signer`] with the X.509 certificate chain of its key, for issuers that are identified by
/// a certificate: the tokens the builders of this crate sign with it carry the chain in an
/// `x5c` header (RFC 7515 §4.1.6) and no `kid`, as [`JwsHeader::for_signer`] does.
///
/// The OpenID4VC High Assurance Interoperability Profile requires this of SD-JWT VCs (§6.1.1)
/// and Status List Tokens (§6.1), with a chain whose first certificate is not self-signed and
/// that leaves out the trust anchor. The chain is not checked here: with the `x509` feature,
/// `X509Resolver::validate` tells whether a verifier trusting a given anchor accepts it.
///
/// # Examples
///
/// ```
/// use identity_kit::jose::{CertifiedSigner, JwsAlgorithm, JwsHeader, SignError, Signer};
///
/// struct Issuer;
///
/// #[async_trait::async_trait]
/// impl Signer for Issuer {
///     fn alg(&self) -> JwsAlgorithm { JwsAlgorithm::ES256 }
///     fn kid(&self) -> Option<&str> { Some("key-1") }
///     async fn sign(&self, _: &[u8]) -> Result<Vec<u8>, SignError> { Ok(vec![0; 64]) }
/// }
///
/// // The DER of the issuer's certificate and of the CA certificate that issued it.
/// let chain = vec![b"issuer certificate".to_vec(), b"CA certificate".to_vec()];
/// let signer = CertifiedSigner::new(Issuer, chain);
/// let header = JwsHeader::for_signer(&signer);
/// assert_eq!(
///     header.additional["x5c"],
///     serde_json::json!(["aXNzdWVyIGNlcnRpZmljYXRl", "Q0EgY2VydGlmaWNhdGU="])
/// );
/// assert_eq!(header.kid, None);
/// ```
#[derive(Debug, Clone)]
pub struct CertifiedSigner<S> {
    signer: S,
    chain: Vec<Vec<u8>>,
}

impl<S: Signer> CertifiedSigner<S> {
    /// `signer` with `chain`, the DER-encoded certificate of its key followed by the
    /// certificates that certify it, without the trust anchor.
    pub fn new(signer: S, chain: Vec<Vec<u8>>) -> Self {
        Self { signer, chain }
    }

    /// The signer.
    pub fn signer(&self) -> &S {
        &self.signer
    }
}

#[async_trait::async_trait]
impl<S: Signer> Signer for CertifiedSigner<S> {
    fn alg(&self) -> JwsAlgorithm {
        self.signer.alg()
    }

    fn kid(&self) -> Option<&str> {
        self.signer.kid()
    }

    fn x5c(&self) -> Option<&[Vec<u8>]> {
        Some(&self.chain)
    }

    async fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, SignError> {
        self.signer.sign(signing_input).await
    }
}

/// Encodes `payload` under `header` as a compact JWS signed by `signer`.
///
/// The header is serialized as given: `alg` must equal the signer's algorithm, and `kid` is
/// whatever the caller set (a DID URL, usually), not necessarily [`Signer::kid`].
///
/// # Errors
///
/// [`JwsError::AlgorithmMismatch`] when `header.alg` differs from the signer's algorithm, and
/// [`JwsError::Signer`] when signing fails.
///
/// # Examples
///
/// ```
/// use identity_kit::jose::{CompactJws, JwsAlgorithm, JwsHeader, SignError, Signer, encode_compact};
///
/// struct Rejecting;
///
/// #[async_trait::async_trait]
/// impl Signer for Rejecting {
///     fn alg(&self) -> JwsAlgorithm { JwsAlgorithm::ES256 }
///     fn kid(&self) -> Option<&str> { None }
///     async fn sign(&self, _: &[u8]) -> Result<Vec<u8>, SignError> {
///         Err(SignError::msg("key store is offline"))
///     }
/// }
///
/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
/// let header = JwsHeader::new(JwsAlgorithm::ES256);
/// let err = encode_compact(&header, b"{}", &Rejecting).await.unwrap_err();
/// assert_eq!(err.to_string(), "signing failed: key store is offline");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub async fn encode_compact(
    header: &JwsHeader,
    payload: &[u8],
    signer: &dyn Signer,
) -> Result<String, JwsError> {
    if header.alg != signer.alg() {
        return Err(JwsError::AlgorithmMismatch {
            header: header.alg,
            signer: signer.alg(),
        });
    }
    // Serializing a header cannot fail: every field is a string, a list, a `Jwk` or a `Value`.
    let header_json =
        serde_json::to_vec(header).map_err(|e| header_error("not serializable", e))?;
    let mut token = base64url::encode(&header_json);
    token.push('.');
    token.push_str(&base64url::encode(payload));
    let signature = signer
        .sign(token.as_bytes())
        .await
        .map_err(JwsError::Signer)?;
    token.push('.');
    token.push_str(&base64url::encode(&signature));
    Ok(token)
}