Skip to content

Commit ea46187

Browse files
committed
fix(crypto): a token's header is checked before its payload and signature are decoded
Review of #495: `Compact::split` decoded all three segments, so a token with `crit` and a malformed payload was `malformed` in Rust but `unsupported_critical_header` in TypeScript. Splitting now decodes the header alone; `Split::decode` decodes the rest once the caller's header checks pass, as every SDK orders them. `MAX_TOKEN_BYTES` is no longer exported.
1 parent 32851d0 commit ea46187

4 files changed

Lines changed: 72 additions & 25 deletions

File tree

‎crates/auth-sdk/src/keys.rs‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use sourceorigin_common::protocol::{
1212
sdk::{ErrorCategory, ErrorReason, SdkError},
1313
};
1414
pub use sourceorigin_crypto::KeyDefect;
15-
use sourceorigin_crypto::{Compact, Rs256VerifyingKey, VerifyError};
15+
use sourceorigin_crypto::{Compact, Malformed, Rs256VerifyingKey, VerifyError};
1616
use std::{
1717
fmt,
1818
sync::{Arc, Mutex, MutexGuard, PoisonError},
@@ -74,6 +74,11 @@ impl JwsHeader {
7474
/// Err(TokenError::WrongType { .. })
7575
/// ));
7676
/// assert!(matches!(Jws::parse("two.segments"), Err(TokenError::Malformed(_))));
77+
/// // The header's checks come first, whatever follows it.
78+
/// assert!(matches!(
79+
/// Jws::parse("eyJhbGciOiJSUzI1NiIsImNyaXQiOltdfQ.not*base64.not*base64"),
80+
/// Err(TokenError::UnsupportedCriticalHeader)
81+
/// ));
7782
/// # Ok::<(), TokenError>(())
7883
/// ```
7984
#[derive(Clone)]
@@ -102,14 +107,17 @@ impl<'a> Jws<'a> {
102107
/// 16 KiB, with a JSON header; [`TokenError::UnsupportedCriticalHeader`] if that
103108
/// header sets `crit`.
104109
pub fn parse(token: &'a str) -> Result<Self, TokenError> {
105-
let compact =
106-
Compact::split(token).map_err(|malformed| TokenError::Malformed(malformed.0))?;
107-
let header: JwsHeader = serde_json::from_slice(compact.header())
110+
let malformed = |malformed: Malformed| TokenError::Malformed(malformed.0);
111+
let split = Compact::split(token).map_err(malformed)?;
112+
let header: JwsHeader = serde_json::from_slice(split.header())
108113
.map_err(|_| TokenError::Malformed("the header is not a JWS header"))?;
109114
if header.crit.is_some() {
110115
return Err(TokenError::UnsupportedCriticalHeader);
111116
}
112-
Ok(Self { header, compact })
117+
Ok(Self {
118+
header,
119+
compact: split.decode().map_err(malformed)?,
120+
})
113121
}
114122

115123
/// The protected header.

‎crates/crypto/src/jws.rs‎

Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
//! ```
77
//! use sourceorigin_crypto::{Compact, KeyDefect, Rs256VerifyingKey, VerifyError};
88
//!
9-
//! let token = Compact::split("eyJhbGciOiJSUzI1NiJ9.e30.c2lnbmF0dXJl")?;
10-
//! assert_eq!(token.header(), br#"{"alg":"RS256"}"#);
9+
//! let split = Compact::split("eyJhbGciOiJSUzI1NiJ9.e30.c2lnbmF0dXJl")?;
10+
//! assert_eq!(split.header(), br#"{"alg":"RS256"}"#);
11+
//! // The header passed the caller's checks, so the rest is decoded.
12+
//! let token = split.decode()?;
1113
//! // A 1024-bit modulus verifies nothing: the key is at fault, not the token.
1214
//! let weak = Rs256VerifyingKey::new(&[0xc5; 128], &[1, 0, 1]);
1315
//! assert!(matches!(weak.defect(), Some(KeyDefect::ModulusSize(1024))));
@@ -26,7 +28,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
2628
use thiserror::Error;
2729

2830
/// Longest compact token read, in bytes: decoding is bounded before it starts.
29-
pub const MAX_TOKEN_BYTES: usize = 16 * 1024;
31+
const MAX_TOKEN_BYTES: usize = 16 * 1024;
3032
/// Shortest RSA modulus a key may have, in bits (RFC 7518 §3.3).
3133
const MIN_MODULUS_BITS: usize = 2048;
3234
/// Longest RSA modulus a key may have, in bits, as aws-lc verifies.
@@ -40,6 +42,49 @@ const EXPONENT: [u8; 3] = [1, 0, 1];
4042
#[error("{0}")]
4143
pub struct Malformed(pub &'static str);
4244

45+
/// A compact JWS split into its three segments, with only its header decoded.
46+
/// The caller checks the header first, then decodes the rest, so a header that
47+
/// fails its checks is reported before a malformed payload or signature, in the
48+
/// order every SDK reports failures.
49+
pub struct Split<'a> {
50+
/// The decoded protected header, JSON as sent.
51+
header: Vec<u8>,
52+
/// `header.payload`, the bytes the signature covers.
53+
signing_input: &'a str,
54+
/// The base64url payload.
55+
payload: &'a str,
56+
/// The base64url signature.
57+
signature: &'a str,
58+
}
59+
60+
impl<'a> Split<'a> {
61+
/// The decoded protected header, for the caller to parse under its policy.
62+
#[must_use]
63+
pub fn header(&self) -> &[u8] {
64+
&self.header
65+
}
66+
67+
/// Decodes the payload and signature.
68+
///
69+
/// # Errors
70+
/// [`Malformed`] for a segment that is not unpadded base64url.
71+
pub fn decode(self) -> Result<Compact<'a>, Malformed> {
72+
Ok(Compact {
73+
header: self.header,
74+
signing_input: self.signing_input,
75+
payload: decode(self.payload)?,
76+
signature: decode(self.signature)?,
77+
})
78+
}
79+
}
80+
81+
/// A segment's unpadded base64url, decoded.
82+
fn decode(segment: &str) -> Result<Vec<u8>, Malformed> {
83+
URL_SAFE_NO_PAD
84+
.decode(segment)
85+
.map_err(|_| Malformed("a segment is not base64url"))
86+
}
87+
4388
/// A compact JWS (RFC 7515 §7.1) split into its decoded parts. Nothing is
4489
/// verified: read the header, verify the signature, and only then the payload.
4590
#[derive(Clone)]
@@ -55,13 +100,13 @@ pub struct Compact<'a> {
55100
}
56101

57102
impl<'a> Compact<'a> {
58-
/// Splits a token of at most [`MAX_TOKEN_BYTES`] into exactly three base64url
59-
/// segments and decodes them.
103+
/// Splits a token of at most 16 KiB into exactly three segments
104+
/// and decodes its header.
60105
///
61106
/// # Errors
62-
/// [`Malformed`] for a longer token, another number of segments, or a segment
107+
/// [`Malformed`] for a longer token, another number of segments, or a header
63108
/// that is not unpadded base64url.
64-
pub fn split(token: &'a str) -> Result<Self, Malformed> {
109+
pub fn split(token: &'a str) -> Result<Split<'a>, Malformed> {
65110
if token.len() > MAX_TOKEN_BYTES {
66111
return Err(Malformed("the token exceeds 16 KiB"));
67112
}
@@ -74,16 +119,11 @@ impl<'a> Compact<'a> {
74119
) else {
75120
return Err(Malformed("the token is not three segments"));
76121
};
77-
let decode = |segment: &str| {
78-
URL_SAFE_NO_PAD
79-
.decode(segment)
80-
.map_err(|_| Malformed("a segment is not base64url"))
81-
};
82-
Ok(Self {
122+
Ok(Split {
83123
header: decode(header)?,
84124
signing_input: &token[..header.len() + 1 + payload.len()],
85-
payload: decode(payload)?,
86-
signature: decode(signature)?,
125+
payload,
126+
signature,
87127
})
88128
}
89129

‎crates/crypto/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ mod scram;
1010
mod sealing;
1111
/// RSA signing and verification of compact JWTs, by key set.
1212
mod signing;
13-
pub use jws::{Compact, KeyDefect, MAX_TOKEN_BYTES, Malformed, Rs256VerifyingKey, VerifyError};
13+
pub use jws::{Compact, KeyDefect, Malformed, Rs256VerifyingKey, Split, VerifyError};
1414
pub use note::{NoteKey, NoteVerifier, NoteVerifiers};
1515
pub use scram::ScramVerifier;
1616
pub use sealing::{KeyEncryptionKey, SealingKey};

‎crates/crypto/src/signing/mod.rs‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,10 @@ struct Token<'a> {
5353
impl<'a> Token<'a> {
5454
/// Splits a bounded token into exactly three parts and parses its header.
5555
fn parse(token: &'a str) -> Result<Self, CryptoError> {
56-
let compact = Compact::split(token).map_err(|_| CryptoError::InvalidToken)?;
56+
let split = Compact::split(token).map_err(|_| CryptoError::InvalidToken)?;
5757
Ok(Self {
58-
header: serde_json::from_slice(compact.header())?,
59-
compact,
58+
header: serde_json::from_slice(split.header())?,
59+
compact: split.decode().map_err(|_| CryptoError::InvalidToken)?,
6060
})
6161
}
6262
}
@@ -105,7 +105,6 @@ impl PublicKey {
105105
/// The key's JWK thumbprint (RFC 7638): the SHA-256 digest of its required
106106
/// members, in lexicographic order and canonical form, so it names the key
107107
/// itself, whatever its `kid` or how its JWK spells it.
108-
///
109108
#[must_use]
110109
pub fn thumbprint(&self) -> Digest {
111110
let members = match self.jwk.kty {

0 commit comments

Comments
 (0)