identity_kit/jose/compact.rs
1//! Compact JWS serialization (RFC 7515 §7.1): decoding without verification, and encoding with
2//! a [`Signer`].
3
4use core::fmt;
5
6use base64::Engine as _;
7use base64::engine::general_purpose::STANDARD;
8use indexmap::IndexMap;
9use serde::de::DeserializeOwned;
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use super::{Jwk, JwsAlgorithm, JwsError, JwsVerifier, SignError, VerificationError, base64url};
14
15/// The JOSE header of a JWS (RFC 7515 §4).
16///
17/// The registered parameters this crate acts on are fields; everything else, `x5c` and `b64`
18/// included, lives in `additional` in insertion order. `jwk` is the public key the signer claims
19/// to have used; trusting it is the verifier's decision, never the crate's.
20///
21/// # Examples
22///
23/// ```
24/// use identity_kit::jose::{JwsAlgorithm, JwsHeader};
25///
26/// let mut header = JwsHeader::new(JwsAlgorithm::ES256).with_kid("did:example:123#key-1");
27/// header.typ = Some("JWT".to_owned());
28/// assert_eq!(
29/// serde_json::to_string(&header)?,
30/// r#"{"alg":"ES256","typ":"JWT","kid":"did:example:123#key-1"}"#
31/// );
32/// # Ok::<(), serde_json::Error>(())
33/// ```
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[non_exhaustive]
36pub struct JwsHeader {
37 /// The signature algorithm (`alg`).
38 pub alg: JwsAlgorithm,
39 /// The media type of the whole JWS (`typ`), such as `JWT` or `vc+jwt`.
40 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub typ: Option<String>,
42 /// The media type of the payload (`cty`).
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub cty: Option<String>,
45 /// The key id (`kid`); for a DID controller, usually a DID URL with a fragment.
46 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub kid: Option<String>,
48 /// The public key the signature was made with (`jwk`).
49 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub jwk: Option<Jwk>,
51 /// Extensions a recipient must understand (`crit`).
52 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub crit: Option<Vec<String>>,
54 /// Every other header parameter, in insertion order.
55 #[serde(flatten)]
56 pub additional: IndexMap<String, Value>,
57}
58
59impl JwsHeader {
60 /// A header with only `alg` set.
61 pub fn new(alg: JwsAlgorithm) -> Self {
62 Self {
63 alg,
64 typ: None,
65 cty: None,
66 kid: None,
67 jwk: None,
68 crit: None,
69 additional: IndexMap::new(),
70 }
71 }
72
73 /// This header with its `kid` set.
74 #[must_use]
75 pub fn with_kid(mut self, kid: impl Into<String>) -> Self {
76 self.kid = Some(kid.into());
77 self
78 }
79
80 /// This header with its `typ` set.
81 #[must_use]
82 pub fn with_typ(mut self, typ: impl Into<String>) -> Self {
83 self.typ = Some(typ.into());
84 self
85 }
86
87 /// This header with `chain` as its `x5c` parameter (RFC 7515 §4.1.6): DER-encoded
88 /// certificates, the one of the signing key first, each followed by the one that
89 /// certifies it.
90 ///
91 /// HAIP requires more of every `x5c` it defines: the first certificate is not
92 /// self-signed, and the chain leaves out the trust anchor.
93 #[must_use]
94 pub fn with_x5c<C: AsRef<[u8]>>(mut self, chain: &[C]) -> Self {
95 let chain = chain
96 .iter()
97 .map(|certificate| Value::String(STANDARD.encode(certificate)))
98 .collect();
99 self.additional
100 .insert("x5c".to_owned(), Value::Array(chain));
101 self
102 }
103
104 /// The header a token signed by `signer` starts from: its algorithm, and what names its
105 /// key, the certificate chain of [`Signer::x5c`] when it has one, otherwise its
106 /// [`kid`](Signer::kid).
107 pub fn for_signer(signer: &dyn Signer) -> Self {
108 let header = Self::new(signer.alg());
109 // An empty chain names no key: RFC 7515 §4.1.6 has at least the key's own certificate.
110 match signer.x5c().filter(|chain| !chain.is_empty()) {
111 Some(chain) => header.with_x5c(chain),
112 None => Self {
113 kid: signer.kid().map(str::to_owned),
114 ..header
115 },
116 }
117 }
118}
119
120/// A decoded compact JWS: `BASE64URL(header) || '.' || BASE64URL(payload) || '.' ||
121/// BASE64URL(signature)`.
122///
123/// Decoding parses the header and the parts and nothing more: [`CompactJws::verify`] (or any
124/// [`JwsVerifier`]) checks the signature once the caller has resolved the key, which usually
125/// means dereferencing [`kid`](Self::kid) through a DID resolver.
126///
127/// # Examples
128///
129/// ```
130/// use identity_kit::jose::{CompactJws, JwsAlgorithm};
131///
132/// // RFC 8037 Appendix A.4.
133/// let token = "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.\
134/// hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg";
135/// let jws = CompactJws::decode(token)?;
136/// assert_eq!(jws.alg(), JwsAlgorithm::EdDSA);
137/// assert_eq!(jws.kid(), None);
138/// assert_eq!(jws.payload(), b"Example of Ed25519 signing");
139/// assert_eq!(
140/// jws.signing_input(),
141/// b"eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc"
142/// );
143/// assert_eq!(jws.signature().len(), 64);
144/// # Ok::<(), identity_kit::jose::JwsError>(())
145/// ```
146#[derive(Debug, Clone)]
147pub struct CompactJws {
148 token: String,
149 /// Byte offset of the `.` between payload and signature; the signing input ends there.
150 signing_input_end: usize,
151 header: JwsHeader,
152 payload: Vec<u8>,
153 signature: Vec<u8>,
154}
155
156impl CompactJws {
157 /// Parses a compact JWS without verifying it.
158 ///
159 /// # Errors
160 ///
161 /// A [`JwsError`] when the input is not three base64url parts, the header is not a JSON
162 /// object with a supported `alg`, or the header has `crit` or `b64: false`.
163 pub fn decode(token: &str) -> Result<Self, JwsError> {
164 let mut parts = token.split('.');
165 let (Some(header_b64), Some(payload_b64), Some(signature_b64), None) =
166 (parts.next(), parts.next(), parts.next(), parts.next())
167 else {
168 return Err(JwsError::InvalidFormat {
169 parts: token.split('.').count(),
170 });
171 };
172 let header_json = base64url::decode(header_b64)
173 .map_err(|_| JwsError::InvalidBase64Url { part: "header" })?;
174 let header = parse_header(&header_json)?;
175 let payload = base64url::decode(payload_b64)
176 .map_err(|_| JwsError::InvalidBase64Url { part: "payload" })?;
177 let signature = base64url::decode(signature_b64)
178 .map_err(|_| JwsError::InvalidBase64Url { part: "signature" })?;
179 Ok(Self {
180 token: token.to_owned(),
181 signing_input_end: header_b64.len() + 1 + payload_b64.len(),
182 header,
183 payload,
184 signature,
185 })
186 }
187
188 /// The protected header.
189 pub fn header(&self) -> &JwsHeader {
190 &self.header
191 }
192
193 /// The header `alg`.
194 pub fn alg(&self) -> JwsAlgorithm {
195 self.header.alg
196 }
197
198 /// The header `kid`, if any.
199 pub fn kid(&self) -> Option<&str> {
200 self.header.kid.as_deref()
201 }
202
203 /// The JWS signing input: `BASE64URL(header) || '.' || BASE64URL(payload)` as ASCII.
204 pub fn signing_input(&self) -> &[u8] {
205 &self.token.as_bytes()[..self.signing_input_end]
206 }
207
208 /// The decoded payload.
209 pub fn payload(&self) -> &[u8] {
210 &self.payload
211 }
212
213 /// The decoded signature.
214 pub fn signature(&self) -> &[u8] {
215 &self.signature
216 }
217
218 /// The payload read as JSON into `T`, a [`JwtClaims`](super::JwtClaims) set say, unverified:
219 /// nothing about the signature or the claims is checked.
220 ///
221 /// # Errors
222 ///
223 /// [`JwsError::InvalidPayload`] when the payload is not JSON of the shape `T` expects.
224 ///
225 /// # Examples
226 ///
227 /// ```
228 /// use identity_kit::jose::{CompactJws, JwtClaims};
229 ///
230 /// // RFC 7515 Appendix A.3: the RFC 7519 §3.1 claims set, signed with ES256.
231 /// let jws = CompactJws::decode(
232 /// "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGF\
233 /// tcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDx\
234 /// w5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q",
235 /// )?;
236 /// let claims: JwtClaims = jws.claims()?;
237 /// assert_eq!(claims.iss.as_deref(), Some("joe"));
238 /// assert_eq!(claims.exp, Some(1300819380));
239 /// assert_eq!(claims.additional["http://example.com/is_root"], true);
240 /// # Ok::<(), identity_kit::jose::JwsError>(())
241 /// ```
242 pub fn claims<T: DeserializeOwned>(&self) -> Result<T, JwsError> {
243 serde_json::from_slice(&self.payload).map_err(|e| JwsError::InvalidPayload {
244 reason: "not JSON of the expected shape".to_owned(),
245 source: Some(e),
246 })
247 }
248
249 /// The compact serialization as it was decoded.
250 pub fn as_str(&self) -> &str {
251 &self.token
252 }
253
254 /// Verifies the signature with `verifier` under `key` and the header `alg`.
255 ///
256 /// # Errors
257 ///
258 /// Whatever the verifier reports; see [`JwsVerifier::verify`].
259 pub fn verify<V: JwsVerifier + ?Sized>(
260 &self,
261 verifier: &V,
262 key: &Jwk,
263 ) -> Result<(), VerificationError> {
264 verifier.verify(self.alg(), self.signing_input(), &self.signature, key)
265 }
266}
267
268impl fmt::Display for CompactJws {
269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 f.write_str(&self.token)
271 }
272}
273
274impl AsRef<str> for CompactJws {
275 fn as_ref(&self) -> &str {
276 &self.token
277 }
278}
279
280/// A [`JwsError::InvalidHeader`] for `reason`, caused by `source`.
281fn header_error(reason: &str, source: serde_json::Error) -> JwsError {
282 JwsError::InvalidHeader {
283 reason: reason.to_owned(),
284 source: Some(source),
285 }
286}
287
288/// Parses the header JSON, naming an unsupported `alg` and rejecting `crit` and `b64: false`.
289fn parse_header(json: &[u8]) -> Result<JwsHeader, JwsError> {
290 let value: Value = serde_json::from_slice(json).map_err(|e| header_error("not JSON", e))?;
291 let Some(object) = value.as_object() else {
292 return Err(JwsError::InvalidHeader {
293 reason: "not a JSON object".to_owned(),
294 source: None,
295 });
296 };
297 match object.get("alg") {
298 Some(Value::String(alg)) if alg.parse::<JwsAlgorithm>().is_ok() => {}
299 Some(Value::String(alg)) => return Err(JwsError::UnsupportedAlgorithm(alg.clone())),
300 Some(other) => return Err(JwsError::UnsupportedAlgorithm(other.to_string())),
301 None => {
302 return Err(JwsError::InvalidHeader {
303 reason: "missing `alg`".to_owned(),
304 source: None,
305 });
306 }
307 }
308 if object
309 .get("b64")
310 .is_some_and(|b64| b64 != &Value::Bool(true))
311 {
312 return Err(JwsError::UnencodedPayload);
313 }
314 let header: JwsHeader =
315 serde_json::from_value(value).map_err(|e| header_error("a member is malformed", e))?;
316 if let Some(crit) = &header.crit {
317 return Err(JwsError::UnsupportedCritical(crit.clone()));
318 }
319 Ok(header)
320}
321
322/// Produces JWS signatures.
323///
324/// A signer binds one key and one algorithm. Private keys live behind it, in a key store, an HSM
325/// or a cloud service, which is why signing is `async`. The signature is returned in the JWS form
326/// of the algorithm: raw `r || s` for ECDSA, never DER.
327#[async_trait::async_trait]
328pub trait Signer: Send + Sync {
329 /// The algorithm every signature of this signer uses.
330 fn alg(&self) -> JwsAlgorithm;
331
332 /// The key id to put in a header, if the signer has one.
333 fn kid(&self) -> Option<&str>;
334
335 /// The certificate chain of the signing key to put in an `x5c` header, if the signer has
336 /// one: DER-encoded certificates, the key's own first. `None` by default;
337 /// [`CertifiedSigner`] gives a signer one. A signer that wraps another one forwards it.
338 fn x5c(&self) -> Option<&[Vec<u8>]> {
339 None
340 }
341
342 /// Signs `signing_input`.
343 ///
344 /// # Errors
345 ///
346 /// A [`SignError`] wrapping whatever the backend reports.
347 async fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, SignError>;
348}
349
350// Implements `Signer` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`, so
351// that a signer behind a reference or a `Box<dyn Signer>`, as an `Identity` returns one, can
352// be wrapped or passed on. A method added to the trait is added here too: one with a default
353// body would still compile if left out, and calls through these wrappers would then run the
354// default, not `T`'s override. `clippy::missing_trait_methods` turns that omission into an
355// error.
356macro_rules! forward_signer {
357 ($($ty:ty),* $(,)?) => {$(
358 #[async_trait::async_trait]
359 #[deny(clippy::missing_trait_methods)]
360 impl<T: Signer + ?Sized> Signer for $ty {
361 fn alg(&self) -> JwsAlgorithm {
362 (**self).alg()
363 }
364
365 fn kid(&self) -> Option<&str> {
366 (**self).kid()
367 }
368
369 fn x5c(&self) -> Option<&[Vec<u8>]> {
370 (**self).x5c()
371 }
372
373 async fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, SignError> {
374 (**self).sign(signing_input).await
375 }
376 }
377 )*};
378}
379
380forward_signer!(&T, Box<T>, std::sync::Arc<T>);
381
382/// A [`Signer`] with the X.509 certificate chain of its key, for issuers that are identified by
383/// a certificate: the tokens the builders of this crate sign with it carry the chain in an
384/// `x5c` header (RFC 7515 §4.1.6) and no `kid`, as [`JwsHeader::for_signer`] does.
385///
386/// The OpenID4VC High Assurance Interoperability Profile requires this of SD-JWT VCs (§6.1.1)
387/// and Status List Tokens (§6.1), with a chain whose first certificate is not self-signed and
388/// that leaves out the trust anchor. The chain is not checked here: with the `x509` feature,
389/// `X509Resolver::validate` tells whether a verifier trusting a given anchor accepts it.
390///
391/// # Examples
392///
393/// ```
394/// use identity_kit::jose::{CertifiedSigner, JwsAlgorithm, JwsHeader, SignError, Signer};
395///
396/// struct Issuer;
397///
398/// #[async_trait::async_trait]
399/// impl Signer for Issuer {
400/// fn alg(&self) -> JwsAlgorithm { JwsAlgorithm::ES256 }
401/// fn kid(&self) -> Option<&str> { Some("key-1") }
402/// async fn sign(&self, _: &[u8]) -> Result<Vec<u8>, SignError> { Ok(vec![0; 64]) }
403/// }
404///
405/// // The DER of the issuer's certificate and of the CA certificate that issued it.
406/// let chain = vec![b"issuer certificate".to_vec(), b"CA certificate".to_vec()];
407/// let signer = CertifiedSigner::new(Issuer, chain);
408/// let header = JwsHeader::for_signer(&signer);
409/// assert_eq!(
410/// header.additional["x5c"],
411/// serde_json::json!(["aXNzdWVyIGNlcnRpZmljYXRl", "Q0EgY2VydGlmaWNhdGU="])
412/// );
413/// assert_eq!(header.kid, None);
414/// ```
415#[derive(Debug, Clone)]
416pub struct CertifiedSigner<S> {
417 signer: S,
418 chain: Vec<Vec<u8>>,
419}
420
421impl<S: Signer> CertifiedSigner<S> {
422 /// `signer` with `chain`, the DER-encoded certificate of its key followed by the
423 /// certificates that certify it, without the trust anchor.
424 pub fn new(signer: S, chain: Vec<Vec<u8>>) -> Self {
425 Self { signer, chain }
426 }
427
428 /// The signer.
429 pub fn signer(&self) -> &S {
430 &self.signer
431 }
432}
433
434#[async_trait::async_trait]
435impl<S: Signer> Signer for CertifiedSigner<S> {
436 fn alg(&self) -> JwsAlgorithm {
437 self.signer.alg()
438 }
439
440 fn kid(&self) -> Option<&str> {
441 self.signer.kid()
442 }
443
444 fn x5c(&self) -> Option<&[Vec<u8>]> {
445 Some(&self.chain)
446 }
447
448 async fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, SignError> {
449 self.signer.sign(signing_input).await
450 }
451}
452
453/// Encodes `payload` under `header` as a compact JWS signed by `signer`.
454///
455/// The header is serialized as given: `alg` must equal the signer's algorithm, and `kid` is
456/// whatever the caller set (a DID URL, usually), not necessarily [`Signer::kid`].
457///
458/// # Errors
459///
460/// [`JwsError::AlgorithmMismatch`] when `header.alg` differs from the signer's algorithm, and
461/// [`JwsError::Signer`] when signing fails.
462///
463/// # Examples
464///
465/// ```
466/// use identity_kit::jose::{CompactJws, JwsAlgorithm, JwsHeader, SignError, Signer, encode_compact};
467///
468/// struct Rejecting;
469///
470/// #[async_trait::async_trait]
471/// impl Signer for Rejecting {
472/// fn alg(&self) -> JwsAlgorithm { JwsAlgorithm::ES256 }
473/// fn kid(&self) -> Option<&str> { None }
474/// async fn sign(&self, _: &[u8]) -> Result<Vec<u8>, SignError> {
475/// Err(SignError::msg("key store is offline"))
476/// }
477/// }
478///
479/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
480/// let header = JwsHeader::new(JwsAlgorithm::ES256);
481/// let err = encode_compact(&header, b"{}", &Rejecting).await.unwrap_err();
482/// assert_eq!(err.to_string(), "signing failed: key store is offline");
483/// # Ok::<(), Box<dyn std::error::Error>>(())
484/// # })?;
485/// # Ok::<(), Box<dyn std::error::Error>>(())
486/// ```
487pub async fn encode_compact(
488 header: &JwsHeader,
489 payload: &[u8],
490 signer: &dyn Signer,
491) -> Result<String, JwsError> {
492 if header.alg != signer.alg() {
493 return Err(JwsError::AlgorithmMismatch {
494 header: header.alg,
495 signer: signer.alg(),
496 });
497 }
498 // Serializing a header cannot fail: every field is a string, a list, a `Jwk` or a `Value`.
499 let header_json =
500 serde_json::to_vec(header).map_err(|e| header_error("not serializable", e))?;
501 let mut token = base64url::encode(&header_json);
502 token.push('.');
503 token.push_str(&base64url::encode(payload));
504 let signature = signer
505 .sign(token.as_bytes())
506 .await
507 .map_err(JwsError::Signer)?;
508 token.push('.');
509 token.push_str(&base64url::encode(&signature));
510 Ok(token)
511}