identity_jose/jws/
decoder.rs

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
// Copyright 2020-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use core::str;
use std::borrow::Cow;

use crate::error::Error;
use crate::error::Result;
use crate::jwk::Jwk;
use crate::jws::JwsAlgorithm;
use crate::jws::JwsHeader;
use crate::jwu::create_message;
use crate::jwu::decode_b64;
use crate::jwu::decode_b64_json;
use crate::jwu::filter_non_empty_bytes;
use crate::jwu::parse_utf8;
use crate::jwu::validate_jws_headers;

use super::JwsVerifier;
use super::VerificationInput;

/// A cryptographically verified decoded token from a JWS.
///
/// Contains the decoded headers and the raw claims.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DecodedJws<'a> {
  /// The decoded protected header.
  pub protected: JwsHeader,
  /// The decoded unprotected header.
  pub unprotected: Option<Box<JwsHeader>>,
  /// The decoded raw claims.
  pub claims: Cow<'a, [u8]>,
}

enum DecodedHeaders {
  Protected(JwsHeader),
  Unprotected(JwsHeader),
  Both {
    protected: JwsHeader,
    // Use box to reduce size
    unprotected: Box<JwsHeader>,
  },
}

impl DecodedHeaders {
  fn new(protected: Option<JwsHeader>, unprotected: Option<JwsHeader>) -> Result<Self> {
    match (protected, unprotected) {
      (Some(protected), Some(unprotected)) => Ok(Self::Both {
        protected,
        unprotected: Box::new(unprotected),
      }),
      (Some(protected), None) => Ok(Self::Protected(protected)),
      (None, Some(unprotected)) => Ok(Self::Unprotected(unprotected)),
      (None, None) => Err(Error::MissingHeader("no headers were decoded")),
    }
  }

  fn protected_header(&self) -> Option<&JwsHeader> {
    match self {
      DecodedHeaders::Protected(ref header) => Some(header),
      DecodedHeaders::Both { ref protected, .. } => Some(protected),
      DecodedHeaders::Unprotected(_) => None,
    }
  }

  fn unprotected_header(&self) -> Option<&JwsHeader> {
    match self {
      DecodedHeaders::Unprotected(ref header) => Some(header),
      DecodedHeaders::Both { ref unprotected, .. } => Some(unprotected.as_ref()),
      DecodedHeaders::Protected(_) => None,
    }
  }
}

/// A partially decoded JWS containing claims, and the decoded verification data
/// for its corresponding signature (headers, signing input and signature). This data
/// can be cryptographically verified using a [`JwsVerifier`]. See [`Self::verify`](Self::verify).
pub struct JwsValidationItem<'a> {
  headers: DecodedHeaders,
  signing_input: Box<[u8]>,
  decoded_signature: Box<[u8]>,
  claims: Cow<'a, [u8]>,
}
impl<'a> JwsValidationItem<'a> {
  /// Returns the decoded protected header if it exists.
  pub fn protected_header(&self) -> Option<&JwsHeader> {
    self.headers.protected_header()
  }

  /// Returns the Nonce from the protected header if it is set.
  pub fn nonce(&self) -> Option<&str> {
    self.protected_header().and_then(|header| header.nonce())
  }

  /// Returns the kid from the protected header if it is set.
  pub fn kid(&self) -> Option<&str> {
    self.protected_header().and_then(|header| header.kid())
  }

  /// Returns the decoded unprotected header if it exists.
  pub fn unprotected_header(&self) -> Option<&JwsHeader> {
    self.headers.unprotected_header()
  }

  /// The algorithm parsed from the protected header if it exists.
  pub fn alg(&self) -> Option<JwsAlgorithm> {
    self.protected_header().and_then(|protected| protected.alg())
  }

  /// Returns the JWS claims.
  pub fn claims(&self) -> &[u8] {
    &self.claims
  }

  /// Returns the signing input .
  ///
  /// See [RFC 7515: section 5.2 part 8.](https://www.rfc-editor.org/rfc/rfc7515#section-5.2) and
  /// [RFC 7797 section 3](https://www.rfc-editor.org/rfc/rfc7797#section-3).
  pub fn signing_input(&self) -> &[u8] {
    &self.signing_input
  }

  /// Returns the decoded JWS signature.
  pub fn decoded_signature(&self) -> &[u8] {
    &self.decoded_signature
  }

  /// Constructs [`VerificationInput`] from this data and passes it to the given `verifier` along with the
  /// provided `public_key`.
  ///
  /// # Errors
  /// Apart from the fallible call to [`JwsVerifier::verify`] this method can also error if there is no
  /// `alg` present in the protected header (in which case the verifier cannot be called) or if the given `public_key`
  /// has a different value present in its `alg` field.
  ///
  /// # Note
  /// One may want to perform other validations before calling this method, such as for instance checking the nonce
  /// (see [`Self::nonce`](Self::nonce())).
  pub fn verify<T>(self, verifier: &T, public_key: &Jwk) -> Result<DecodedJws<'a>>
  where
    T: JwsVerifier,
  {
    // Destructure data
    let JwsValidationItem {
      headers,
      claims,
      signing_input,
      decoded_signature,
    } = self;
    let (protected, unprotected): (JwsHeader, Option<Box<JwsHeader>>) = match headers {
      DecodedHeaders::Protected(protected) => (protected, None),
      DecodedHeaders::Both { protected, unprotected } => (protected, Some(unprotected)),
      DecodedHeaders::Unprotected(_) => return Err(Error::MissingHeader("missing protected header")),
    };

    // Extract and validate alg from the protected header.
    let alg: JwsAlgorithm = protected.alg().ok_or(Error::ProtectedHeaderWithoutAlg)?;
    public_key.check_alg(alg.name())?;

    // Construct verification input
    let input = VerificationInput {
      alg,
      signing_input,
      decoded_signature,
    };
    // Call verifier
    verifier
      .verify(input, public_key)
      .map_err(Error::SignatureVerificationError)?;

    Ok(DecodedJws {
      protected,
      unprotected,
      claims,
    })
  }
}

// =============================================================================================
// Format dependent deserializable helper structs used by the decoder
// =============================================================================================
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct JwsSignature<'a> {
  header: Option<JwsHeader>,
  protected: Option<&'a str>,
  signature: &'a str,
}

#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct General<'a> {
  payload: Option<&'a str>,
  signatures: Vec<JwsSignature<'a>>,
}

#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Flatten<'a> {
  payload: Option<&'a str>,
  #[serde(flatten)]
  signature: JwsSignature<'a>,
}

// =============================================================================
// Decoder
// =============================================================================

/// The [`Decoder`] is responsible for decoding a JWS into one or more [`JwsValidationItems`](JwsValidationItem).
#[derive(Debug, Clone)]
pub struct Decoder;

impl Decoder {
  /// Constructs a new [`Decoder`].
  pub fn new() -> Decoder {
    Self
  }

  /// Decode a JWS encoded with the [JWS compact serialization format](https://www.rfc-editor.org/rfc/rfc7515#section-3.1).
  ///
  ///
  /// ### Working with detached payloads
  ///
  /// A detached payload can be supplied in the `detached_payload` parameter.
  /// [More Info](https://tools.ietf.org/html/rfc7515#appendix-F)
  pub fn decode_compact_serialization<'b>(
    &self,
    jws_bytes: &'b [u8],
    detached_payload: Option<&'b [u8]>,
  ) -> Result<JwsValidationItem<'b>> {
    let mut segments = jws_bytes.split(|byte| *byte == b'.');

    let (Some(protected), Some(payload), Some(signature), None) =
      (segments.next(), segments.next(), segments.next(), segments.next())
    else {
      return Err(Error::InvalidContent("invalid segments count"));
    };

    let signature: JwsSignature<'_> = JwsSignature {
      header: None,
      protected: Some(parse_utf8(protected)?),
      signature: parse_utf8(signature)?,
    };

    let payload = Self::expand_payload(detached_payload, Some(payload))?;

    self.decode_signature(payload, signature)
  }

  /// Decode a JWS encoded with the [flattened JWS JSON serialization format](https://www.rfc-editor.org/rfc/rfc7515#section-7.2.2).
  ///
  /// ### Working with detached payloads
  ///
  /// A detached payload can be supplied in the `detached_payload` parameter.
  /// [More Info](https://tools.ietf.org/html/rfc7515#appendix-F)
  pub fn decode_flattened_serialization<'b>(
    &self,
    jws_bytes: &'b [u8],
    detached_payload: Option<&'b [u8]>,
  ) -> Result<JwsValidationItem<'b>> {
    let data: Flatten<'_> = serde_json::from_slice(jws_bytes).map_err(Error::InvalidJson)?;
    let payload = Self::expand_payload(detached_payload, data.payload)?;
    let signature = data.signature;
    self.decode_signature(payload, signature)
  }

  fn decode_signature<'a, 'b>(
    &self,
    payload: &'b [u8],
    jws_signature: JwsSignature<'a>,
  ) -> Result<JwsValidationItem<'b>> {
    let JwsSignature {
      header: unprotected_header,
      protected,
      signature,
    } = jws_signature;

    let protected_header: Option<JwsHeader> = protected.map(decode_b64_json).transpose()?;
    validate_jws_headers(protected_header.as_ref(), unprotected_header.as_ref())?;

    let protected_bytes: &[u8] = protected.map(str::as_bytes).unwrap_or_default();
    let signing_input: Box<[u8]> = create_message(protected_bytes, payload).into();
    let decoded_signature: Box<[u8]> = decode_b64(signature)?.into();

    let claims: Cow<'b, [u8]> = if protected_header.as_ref().and_then(|value| value.b64()).unwrap_or(true) {
      Cow::Owned(decode_b64(payload)?)
    } else {
      Cow::Borrowed(payload)
    };

    Ok(JwsValidationItem {
      headers: DecodedHeaders::new(protected_header, unprotected_header)?,
      signing_input,
      decoded_signature,
      claims,
    })
  }

  fn expand_payload<'b>(
    detached_payload: Option<&'b [u8]>,
    parsed_payload: Option<&'b (impl AsRef<[u8]> + ?Sized)>,
  ) -> Result<&'b [u8]> {
    match (detached_payload, filter_non_empty_bytes(parsed_payload)) {
      (Some(payload), None) => Ok(payload),
      (None, Some(payload)) => Ok(payload),
      (Some(_), Some(_)) => Err(Error::InvalidContent("multiple payloads")),
      (None, None) => Err(Error::InvalidContent("missing payload")),
    }
  }
}

// =======================================
// General JWS JSON serialization support
// =======================================

/// An iterator over the [`JwsValidationItems`](JwsValidationItem) corresponding to the
/// signatures in a JWS encoded with the general JWS JSON serialization format.  
pub struct JwsValidationIter<'decoder, 'payload, 'signatures> {
  decoder: &'decoder Decoder,
  signatures: std::vec::IntoIter<JwsSignature<'signatures>>,
  payload: &'payload [u8],
}

impl<'payload> Iterator for JwsValidationIter<'_, 'payload, '_> {
  type Item = Result<JwsValidationItem<'payload>>;

  fn next(&mut self) -> Option<Self::Item> {
    self
      .signatures
      .next()
      .map(|signature| self.decoder.decode_signature(self.payload, signature))
  }
}

impl Decoder {
  /// Decode a JWS encoded with the [general JWS JSON serialization format](https://www.rfc-editor.org/rfc/rfc7515#section-7.2.1)
  ///
  ///  
  /// ### Working with detached payloads
  /// A detached payload can be supplied in the `detached_payload` parameter.
  /// [More Info](https://tools.ietf.org/html/rfc7515#appendix-F)
  pub fn decode_general_serialization<'decoder, 'data>(
    &'decoder self,
    jws_bytes: &'data [u8],
    detached_payload: Option<&'data [u8]>,
  ) -> Result<JwsValidationIter<'decoder, 'data, 'data>> {
    let data: General<'data> = serde_json::from_slice(jws_bytes).map_err(Error::InvalidJson)?;

    let payload = Self::expand_payload(detached_payload, data.payload)?;
    let signatures = data.signatures;

    Ok(JwsValidationIter {
      decoder: self,
      payload,
      signatures: signatures.into_iter(),
    })
  }
}

impl Default for Decoder {
  fn default() -> Self {
    Self::new()
  }
}

#[cfg(test)]
mod tests {
  use crate::jwt::JwtClaims;

  use super::*;

  const RFC_7515_APPENDIX_EXAMPLE_CLAIMS: &str = r#"
  {
    "iss":"joe",
    "exp":1300819380,
    "http://example.com/is_root":true
  }
  "#;

  const SIGNING_INPUT_ES256_RFC_7515_APPENDIX_EXAMPLE: &[u8] = &[
    101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 70, 85, 122, 73, 49, 78, 105, 74, 57, 46, 101, 121, 74, 112, 99,
    51, 77, 105, 79, 105, 74, 113, 98, 50, 85, 105, 76, 65, 48, 75, 73, 67, 74, 108, 101, 72, 65, 105, 79, 106, 69,
    122, 77, 68, 65, 52, 77, 84, 107, 122, 79, 68, 65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76,
    121, 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118, 98, 83, 57, 112, 99, 49, 57, 121, 98, 50, 57,
    48, 73, 106, 112, 48, 99, 110, 86, 108, 102, 81,
  ];

  // Test https://www.rfc-editor.org/rfc/rfc7515#appendix-A.6
  #[test]
  fn rfc7515_appendix_a_6() {
    let general_jws_json_serialized: &str = r#"
    {
      "payload": "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ",
      "signatures": [
        {
          "protected": "eyJhbGciOiJSUzI1NiJ9",
          "header": {
            "kid": "2010-12-29"
          },
          "signature": "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw"
        },
        {
          "protected": "eyJhbGciOiJFUzI1NiJ9",
          "header": {
            "kid": "e9bc097a-ce51-4036-9562-d2ade882db0d"
          },
          "signature": "DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q"
        }
      ]
    }"#;

    let claims: JwtClaims<serde_json::Value> = serde_json::from_str(RFC_7515_APPENDIX_EXAMPLE_CLAIMS).unwrap();

    let decoder = Decoder::new();

    let mut signature_iter = decoder
      .decode_general_serialization(general_jws_json_serialized.as_bytes(), None)
      .unwrap()
      .filter_map(|decoded| decoded.ok());

    // Check that the lifetimes are not overly restrictive:
    let first_signature_decoding = signature_iter.next().unwrap();
    let second_signature_decoding = signature_iter.next().unwrap();
    drop(signature_iter);

    // Check assertions for the first signature:
    assert_eq!(first_signature_decoding.alg().unwrap(), JwsAlgorithm::RS256);
    assert_eq!(
      first_signature_decoding
        .unprotected_header()
        .and_then(|value| value.kid())
        .unwrap(),
      "2010-12-29"
    );
    let decoded_claims: JwtClaims<serde_json::Value> =
      serde_json::from_slice(first_signature_decoding.claims()).unwrap();
    assert_eq!(claims, decoded_claims);

    // Check assertions for the second signature:
    assert_eq!(second_signature_decoding.alg().unwrap(), JwsAlgorithm::ES256);
    assert_eq!(
      second_signature_decoding
        .unprotected_header()
        .and_then(|value| value.kid())
        .unwrap(),
      "e9bc097a-ce51-4036-9562-d2ade882db0d"
    );

    let decoded_claims: JwtClaims<serde_json::Value> =
      serde_json::from_slice(second_signature_decoding.claims()).unwrap();
    assert_eq!(decoded_claims, claims);
    assert_eq!(
      SIGNING_INPUT_ES256_RFC_7515_APPENDIX_EXAMPLE,
      second_signature_decoding.signing_input()
    );
  }

  // Test https://www.rfc-editor.org/rfc/rfc7515#appendix-A.7
  #[test]
  fn rfc7515_appendix_a_7() {
    let flattened_jws_json_serialized: &str = r#"
    {
      "payload": "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ",
      "protected":"eyJhbGciOiJFUzI1NiJ9",
      "header": {"kid":"e9bc097a-ce51-4036-9562-d2ade882db0d"},
      "signature": "DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q"
     }
    "#;

    let claims: JwtClaims<serde_json::Value> = serde_json::from_str(RFC_7515_APPENDIX_EXAMPLE_CLAIMS).unwrap();
    let decoder = Decoder::new();
    let decoded = decoder
      .decode_flattened_serialization(flattened_jws_json_serialized.as_bytes(), None)
      .unwrap();
    assert_eq!(decoded.alg().unwrap(), JwsAlgorithm::ES256);
    assert_eq!(
      decoded.unprotected_header().and_then(|value| value.kid()).unwrap(),
      "e9bc097a-ce51-4036-9562-d2ade882db0d"
    );

    assert_eq!(decoded.signing_input(), SIGNING_INPUT_ES256_RFC_7515_APPENDIX_EXAMPLE);
    let decoded_claims: JwtClaims<serde_json::Value> = serde_json::from_slice(decoded.claims()).unwrap();
    assert_eq!(decoded_claims, claims);
  }
}