Skip to content

Commit 45522bd

Browse files
committed
fix(sdk): RSA keys must use exponent 65537, and zero padding changes nothing, in both SDKs
1 parent 778d88c commit 45522bd

7 files changed

Lines changed: 145 additions & 38 deletions

File tree

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

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -241,8 +241,8 @@ pub enum KeyDefect {
241241
/// bits.
242242
#[error("its RSA modulus is {0} bits, outside 2048 to 8192")]
243243
ModulusSize(usize),
244-
/// The RSA exponent is even or under 3.
245-
#[error("its RSA exponent is not an odd number of at least 3")]
244+
/// The RSA exponent is not 65537, the one every SDK's runtime verifies with.
245+
#[error("its RSA exponent is not 65537")]
246246
Exponent,
247247
/// No verifier can be built from it for the token's algorithm.
248248
#[error("no verifier can be built from it")]
@@ -253,6 +253,9 @@ pub enum KeyDefect {
253253
const MIN_MODULUS_BITS: usize = 2048;
254254
/// Longest RSA modulus a key may have, in bits, as aws-lc verifies.
255255
const MAX_MODULUS_BITS: usize = 8192;
256+
/// The only RSA exponent a key may have, big-endian: 65537. Cloudflare Workers imports
257+
/// only 3, 17 and 65537, so a wider rule would let SDKs disagree on a key.
258+
const EXPONENT: [u8; 3] = [1, 0, 1];
256259

257260
/// One signing key a set lists for verification.
258261
#[derive(Clone)]
@@ -265,13 +268,14 @@ struct Key {
265268
decoding: DecodingKey,
266269
/// The modulus's size in bits, not counting leading zero bytes.
267270
modulus_bits: usize,
268-
/// Whether the exponent is odd and at least 3.
271+
/// Whether the exponent is 65537.
269272
exponent_valid: bool,
270273
}
271274

272275
impl Key {
273-
/// Reads the RSA facts of `n` and `e`, big-endian bytes.
274-
fn new(kid: String, alg: Option<Algorithm>, decoding: DecodingKey, n: &[u8], e: &[u8]) -> Self {
276+
/// The key with modulus `n` and exponent `e`, big-endian bytes. Leading zero bytes
277+
/// are dropped, so a padded key verifies as it does in every SDK.
278+
fn new(kid: String, alg: Option<Algorithm>, n: &[u8], e: &[u8]) -> Self {
275279
let significant = |bytes: &[u8]| {
276280
let start = bytes
277281
.iter()
@@ -283,14 +287,12 @@ impl Key {
283287
let modulus_bits = n.first().map_or(0, |first| {
284288
n.len() * 8 - usize::try_from(first.leading_zeros()).unwrap_or(0)
285289
});
286-
let exponent_valid = e.last().is_some_and(|last| last % 2 == 1)
287-
&& (e.len() > 1 || e.first().is_some_and(|first| *first >= 3));
288290
Self {
289291
kid,
290292
alg,
291-
decoding,
293+
decoding: DecodingKey::from_rsa_raw_components(&n, &e),
292294
modulus_bits,
293-
exponent_valid,
295+
exponent_valid: e == EXPONENT,
294296
}
295297
}
296298

@@ -358,8 +360,7 @@ impl KeySet {
358360
else {
359361
continue;
360362
};
361-
let (Ok(decoding), Ok(n), Ok(e)) = (
362-
DecodingKey::from_rsa_components(&jwk.n, &jwk.e),
363+
let (Ok(n), Ok(e)) = (
363364
URL_SAFE_NO_PAD.decode(&jwk.n),
364365
URL_SAFE_NO_PAD.decode(&jwk.e),
365366
) else {
@@ -368,7 +369,7 @@ impl KeySet {
368369
if keys.iter().any(|key| key.kid == jwk.kid) {
369370
return Err(KeyError::DuplicateKeyId(jwk.kid));
370371
}
371-
keys.push(Key::new(jwk.kid, jwk.alg, decoding, &n, &e));
372+
keys.push(Key::new(jwk.kid, jwk.alg, &n, &e));
372373
}
373374
Ok(Self { keys })
374375
}

‎crates/common/tests/sdk_vectors.rs‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -564,17 +564,36 @@ impl Vectors {
564564
),
565565
Expected::error(ErrorCategory::Keys, ErrorReason::UnusableKey),
566566
);
567-
let mut even_exponent = self.jwks(&[OLD_KID]);
568-
even_exponent["keys"][0]["e"] = json!(URL_SAFE_NO_PAD.encode([2]));
567+
// The old key with each of `members`, `n` or `e`, replaced by `component(bytes)`.
568+
let old_key = self.jwks(&[OLD_KID]);
569+
let altered = |members: &[&str], component: &dyn Fn(Vec<u8>) -> Vec<u8>| {
570+
let mut jwks = old_key.clone();
571+
for member in members {
572+
let value = jwks["keys"][0][member].as_str().expect("key member");
573+
let bytes = URL_SAFE_NO_PAD.decode(value).expect("base64url");
574+
jwks["keys"][0][member] = json!(URL_SAFE_NO_PAD.encode(component(bytes)));
575+
}
576+
jwks
577+
};
569578
self.token(
570-
"access-even-exponent",
571-
"an RSA key with an even exponent verifies nothing: the key set is at fault",
572-
access_case(
573-
Self::sign(&self.old, TokenType::Access, &access),
574-
&even_exponent,
575-
),
579+
"access-small-exponent",
580+
"an RSA key whose exponent is not 65537 verifies nothing: the key set is at fault",
581+
access_case(valid.clone(), &altered(&["e"], &|_| vec![3])),
582+
Expected::error(ErrorCategory::Keys, ErrorReason::UnusableKey),
583+
);
584+
self.token(
585+
"access-zero-modulus",
586+
"an RSA modulus of zero bytes alone verifies nothing: the key set is at fault",
587+
access_case(valid.clone(), &altered(&["n"], &|_| vec![0; 257])),
576588
Expected::error(ErrorCategory::Keys, ErrorReason::UnusableKey),
577589
);
590+
let padded = altered(&["n", "e"], &|bytes| [vec![0], bytes].concat());
591+
self.token(
592+
"access-padded-key",
593+
"leading zero bytes in a key's n and e change nothing",
594+
access_case(valid.clone(), &padded),
595+
Expected::ok(&access),
596+
);
578597
let mut incomplete = serde_json::to_value(&access).expect("serialize claims");
579598
incomplete
580599
.as_object_mut()

‎docs/architecture/sdk.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,10 @@ Checks run in this order, and the first failure is reported. Each failure is an
7575
(`unsupported_algorithm`).
7676
5. `kid` names a known key, after at most one refetch (`unknown_key`).
7777
6. The key can verify: an RSA key's modulus is 2048 to 8192 bits, not counting
78-
leading zero bytes, and its exponent odd and at least 3. Any other key is the
79-
key set's fault, a `keys` error (`unusable_key`), not the token's. Then the
80-
signature verifies (`bad_signature`).
78+
leading zero bytes, and its exponent is 65537, the only one every runtime the
79+
SDKs support imports (Cloudflare Workers accepts just 3, 17 and 65537). Any
80+
other key is the key set's fault, a `keys` error (`unusable_key`), not the
81+
token's. Then the signature verifies (`bad_signature`).
8182
7. The claims parse as the shared claim type, so required claims are present and
8283
well typed (`invalid_claims`). A logout token's `events` must hold the
8384
back-channel logout event with an object value, and it must have no `nonce`,
@@ -131,9 +132,9 @@ The SDK caches the issuer's key set:
131132
does not list `verify` are skipped (RFC 7517 §4.3, §5). A set where two keys share a `kid` is rejected as a whole, and the previous
132133
set stays in use.
133134
- An RSA key whose modulus is under 2048 or over 8192 bits, or whose exponent is
134-
even or under 3, verifies nothing: its tokens fail with `unusable_key`, so a
135-
resource server answers 503 and a callback 502, as for any key set the issuer
136-
got wrong.
135+
not 65537, verifies nothing: its tokens fail with `unusable_key`, so a resource
136+
server answers 503 and a callback 502, as for any key set the issuer got wrong.
137+
Leading zero bytes in `n` or `e` change nothing.
137138

138139
This handles signing key rotation: auth publishes the new key before it signs with
139140
it, so tokens from both keys verify during the overlap. Both SDKs' key caches work

‎packages/auth/src/keys.ts‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -165,9 +165,17 @@ const jwkSet = json.object({ keys: json.array((value) => value) });
165165

166166
/** Shortest and longest RSA modulus a key may have, in bits (RFC 7518 §3.3). */
167167
const MODULUS_BITS = { min: 2048, max: 8192 };
168+
/**
169+
* The only RSA exponent a key may have, 65537 in base64url: Cloudflare Workers
170+
* imports only 3, 17 and 65537, so a wider rule would let runtimes disagree on a key.
171+
*/
172+
const EXPONENT = 'AQAB';
168173

169174
/** `bytes` without their leading zero bytes, which add nothing to a big-endian number. */
170-
const significant = (bytes: Uint8Array) => bytes.subarray(Math.max(bytes.findIndex(Boolean), 0));
175+
const significant = (bytes: Uint8Array) => {
176+
const start = bytes.findIndex(Boolean);
177+
return bytes.subarray(start < 0 ? bytes.length : start);
178+
};
171179

172180
/** One signing key a set lists for verification. */
173181
class SigningKey {
@@ -177,34 +185,38 @@ class SigningKey {
177185
readonly algorithms: readonly Algorithm[];
178186
/**
179187
* What keeps the key from verifying, as every SDK judges it: a modulus outside 2048
180-
* to 8192 bits, not counting leading zero bytes, or an exponent that is even or
181-
* under 3. `undefined` for a usable key.
188+
* to 8192 bits, not counting leading zero bytes, or an exponent other than 65537.
189+
* `undefined` for a usable key.
182190
*/
183191
readonly defect: string | undefined;
184-
readonly #jwk: Jwk;
192+
/** The modulus without its leading zero bytes, in base64url, as it is imported. */
193+
readonly #n: string;
185194
/** The imported key, once a token needed it. */
186195
#imported: Promise<CryptoKey> | undefined;
187196

188197
/** A key whose `n` and `e` decoded to `n` and `e`. */
189198
constructor(key: Jwk, n: Uint8Array, e: Uint8Array) {
190199
this.kid = key.kid;
191200
this.algorithms = key.alg === undefined ? ALGORITHMS : [key.alg];
192-
this.#jwk = key;
193201
const [modulus, exponent] = [significant(n), significant(e)];
202+
this.#n = base64.encode(modulus);
194203
const bits = modulus.length === 0 ? 0 : modulus.length * 8 - Math.clz32(modulus[0] ?? 0) + 24;
195-
const last = exponent.at(-1) ?? 0;
196204
if (bits < MODULUS_BITS.min || bits > MODULUS_BITS.max) {
197205
this.defect = `its RSA modulus is ${String(bits)} bits, outside 2048 to 8192`;
198-
} else if (last % 2 === 0 || (exponent.length === 1 && last < 3)) {
199-
this.defect = 'its RSA exponent is not an odd number of at least 3';
206+
} else if (base64.encode(exponent) !== EXPONENT) {
207+
this.defect = 'its RSA exponent is not 65537';
200208
}
201209
}
202210

203-
/** The key, imported for RS256 verification on first use. */
211+
/**
212+
* The key, imported for RS256 verification on first use, without leading zero bytes,
213+
* so a padded key verifies in every runtime. Only a key without a defect is imported,
214+
* so its exponent is 65537.
215+
*/
204216
imported(): Promise<CryptoKey> {
205217
this.#imported ??= crypto.subtle.importKey(
206218
'jwk',
207-
{ kty: this.#jwk.kty, n: this.#jwk.n, e: this.#jwk.e },
219+
{ kty: 'RSA', n: this.#n, e: EXPONENT },
208220
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
209221
false,
210222
['verify']

‎tests/sdk-vectors/tokens/access-padded-key.json‎

Lines changed: 46 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/sdk-vectors/tokens/access-even-exponent.json renamed to tests/sdk-vectors/tokens/access-small-exponent.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎tests/sdk-vectors/tokens/access-zero-modulus.json‎

Lines changed: 28 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)