From 7d43a45d45144318e1c80c38d276ccd06c348860 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 03:02:58 -0800 Subject: [PATCH 1/3] chore(quest): claim quest/m1/auth-key-strictness.md Quest-Claim: 8bb684819ad3cfe1 From 9c0dcbb7a13790e71426fd0c271bfdff65f87b9d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 03:29:07 -0800 Subject: [PATCH 2/3] fix(auth): @moq/auth refuses the keys moq-auth refuses @moq/auth parses keys and key sets with a JSON parser that refuses what serde_json does (a repeated member it reads, nesting past 127, a lone surrogate, a number out of range) and decodes key fields as moq-auth's strict base64url decoder does. moq-auth now refuses a repeated RSA private member too, which it kept the last of. Co-Authored-By: Claude Opus 5.5 --- js/auth/src/corpus.test.ts | 8 +- js/auth/src/json.ts | 144 ++++++++++++++++++++++++++++++++ js/auth/src/key.test.ts | 8 +- js/auth/src/key.ts | 65 +++++++------- js/auth/src/set.ts | 7 +- quest/m1/auth-key-strictness.md | 29 ------- rs/moq-auth/src/corpus.rs | 18 ++-- rs/moq-auth/src/fuzz.rs | 6 +- rs/moq-auth/src/key.rs | 44 ++++++++-- rs/moq-auth/tests/corpus.json | 105 +++++++++++++++++++++++ 10 files changed, 354 insertions(+), 80 deletions(-) create mode 100644 js/auth/src/json.ts delete mode 100644 quest/m1/auth-key-strictness.md diff --git a/js/auth/src/corpus.test.ts b/js/auth/src/corpus.test.ts index fd6e89a7809..da7063377a0 100644 --- a/js/auth/src/corpus.test.ts +++ b/js/auth/src/corpus.test.ts @@ -54,9 +54,13 @@ describe("tokens", () => { } }); +// A key or set given as a string is its raw text, for what a JSON value cannot spell, +// such as a repeated member. +const text = (document: unknown) => (typeof document === "string" ? document : JSON.stringify(document)); + const sections: [string, Case[], (input: unknown) => unknown][] = [ - ["jwk", corpus.jwk, (jwk) => Key.parse(JSON.stringify(jwk))], - ["sets", corpus.sets, (jwks) => KeySet.parse(JSON.stringify(jwks))], + ["jwk", corpus.jwk, (jwk) => Key.parse(text(jwk))], + ["sets", corpus.sets, (jwks) => KeySet.parse(text(jwks))], ["grants", corpus.grants, (grant) => GrantSchema.parse(grant)], ]; for (const [section, cases, parse] of sections) { diff --git a/js/auth/src/json.ts b/js/auth/src/json.ts new file mode 100644 index 00000000000..9385d163158 --- /dev/null +++ b/js/auth/src/json.ts @@ -0,0 +1,144 @@ +// A JSON parser that refuses what `moq-auth`'s serde_json refuses, so a key loads in both +// languages or in neither. +// +// `JSON.parse` keeps a repeated member's last value, while serde refuses a field it reads +// twice and ignores the members it doesn't read. So a repeated member parses here as +// `REPEATED`, which every schema refuses where it reads the member and strips where it +// doesn't. Beyond that it refuses the inputs serde_json does and `JSON.parse` doesn't: +// nesting past serde_json's recursion limit, a lone surrogate, and a number too large for +// a double. + +// What a member parses to when its object repeats it. +const REPEATED = Symbol("repeated member"); + +// serde_json refuses a document nesting arrays and objects 128 deep. +const MAX_DEPTH = 127; + +const WHITESPACE = /[ \t\n\r]*/y; +const NUMBER = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y; +// biome-ignore lint/suspicious/noControlCharactersInRegex: JSON refuses an unescaped control character in a string. +const PLAIN = /[^"\\\u0000-\u001f]*/y; +const LONE_SURROGATE = /\p{Surrogate}/u; +const ESCAPES: Record = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" }; + +/** Parse a JSON document as `moq-auth` does. Throws on anything serde_json refuses. */ +export function parse(text: string): unknown { + const parser = new Parser(text); + const value = parser.value(0); + parser.skip(); + if (parser.pos !== text.length) parser.fail("trailing characters"); + return value; +} + +class Parser { + readonly text: string; + pos = 0; + + constructor(text: string) { + this.text = text; + } + + fail(message: string): never { + throw new SyntaxError(`invalid JSON: ${message} at offset ${this.pos}`); + } + + skip(): void { + this.pos += this.match(WHITESPACE).length; + } + + match(pattern: RegExp): string { + pattern.lastIndex = this.pos; + return pattern.exec(this.text)?.[0] ?? ""; + } + + eat(char: string): boolean { + this.skip(); + if (this.text[this.pos] !== char) return false; + this.pos++; + return true; + } + + value(depth: number): unknown { + this.skip(); + const char = this.text[this.pos]; + if (char === "{" || char === "[") { + if (depth === MAX_DEPTH) this.fail("recursion limit exceeded"); + this.pos++; + return char === "{" ? this.object(depth + 1) : this.array(depth + 1); + } + if (char === '"') return this.string(); + for (const [word, value] of [ + ["true", true], + ["false", false], + ["null", null], + ] as const) { + if (this.text.startsWith(word, this.pos)) { + this.pos += word.length; + return value; + } + } + const number = this.match(NUMBER); + if (!number) this.fail("expected value"); + this.pos += number.length; + const value = Number(number); + if (!Number.isFinite(value)) this.fail("number out of range"); + return value; + } + + object(depth: number): Record { + const object: Record = {}; + if (this.eat("}")) return object; + do { + this.skip(); + if (this.text[this.pos] !== '"') this.fail("expected member name"); + const key = this.string(); + if (!this.eat(":")) this.fail("expected `:`"); + const value = this.value(depth); + // Defined rather than assigned, so a `__proto__` member stays a plain member. + Object.defineProperty(object, key, { + value: Object.hasOwn(object, key) ? REPEATED : value, + enumerable: true, + writable: true, + configurable: true, + }); + } while (this.eat(",")); + if (!this.eat("}")) this.fail("expected `,` or `}`"); + return object; + } + + array(depth: number): unknown[] { + const array: unknown[] = []; + if (this.eat("]")) return array; + do array.push(this.value(depth)); + while (this.eat(",")); + if (!this.eat("]")) this.fail("expected `,` or `]`"); + return array; + } + + string(): string { + this.pos++; // the opening quote + let out = ""; + for (;;) { + const plain = this.match(PLAIN); + out += plain; + this.pos += plain.length; + const char = this.text[this.pos++]; + if (char === '"') break; + if (char === undefined) this.fail("unterminated string"); + if (char !== "\\") this.fail("control character in string"); + const escaped = this.text[this.pos++]; + if (escaped === "u") { + const hex = this.text.slice(this.pos, this.pos + 4); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail("invalid unicode escape"); + out += String.fromCharCode(Number.parseInt(hex, 16)); + this.pos += 4; + } else { + const decoded = escaped === undefined ? undefined : ESCAPES[escaped]; + if (decoded === undefined) this.fail("invalid escape"); + out += decoded; + } + } + if (LONE_SURROGATE.test(out)) this.fail("lone surrogate"); + return out; + } +} diff --git a/js/auth/src/key.test.ts b/js/auth/src/key.test.ts index 61e5349cea0..2b354d979e3 100644 --- a/js/auth/src/key.test.ts +++ b/js/auth/src/key.test.ts @@ -150,7 +150,7 @@ test("parse - a field with non-base64 characters is refused, whatever its length expect(() => Key.parse(encodeJwk(invalidKey))).toThrow(); }); -test("parse - accepts a JWK in standard padded base64", () => { +test("parse - refuses a JWK in standard padded base64, as moq-auth does", () => { // The note survives as "+" and "/" in standard base64, and the kid length forces padding. const json = JSON.stringify({ ...testKey, kid: "key-1", note: "~~~???" }); const encoded = Buffer.from(json).toString("base64"); @@ -158,9 +158,9 @@ test("parse - accepts a JWK in standard padded base64", () => { expect(encoded).toMatch(/\//); expect(encoded).toMatch(/=$/); - const key = Key.parse(encoded); - expect(key.kid).toBe("key-1"); - expect((key as { k?: string }).k).toBe(testKey.k); + expect(() => Key.parse(encoded)).toThrow(/invalid base64url/); + expect(() => Key.parse(encoded.replace(/=+$/, ""))).toThrow(/invalid base64url/); + expect(Key.parse(Buffer.from(json).toString("base64url")).kid).toBe("key-1"); }); test("generate - an HMAC secret is unpadded base64url that round-trips", async () => { diff --git a/js/auth/src/key.ts b/js/auth/src/key.ts index 448caaf5fb8..56d15dcdcd5 100644 --- a/js/auth/src/key.ts +++ b/js/auth/src/key.ts @@ -3,6 +3,7 @@ import * as jose from "jose"; import * as z from "zod/mini"; import { type Algorithm, AlgorithmSchema } from "./algorithm.ts"; import { type Claims, ClaimsSchema, ScopeSchema, scopeAllows } from "./claims.ts"; +import * as Json from "./json.ts"; import * as Path from "./path.ts"; import { encodeGrants, nestRates } from "./wire.ts"; @@ -35,7 +36,7 @@ const EC_ALGORITHM_TO_CURVE: Record<"ES256" | "ES384", "P-256" | "P-384"> = { const Base64FieldSchema = z.string().check( z.minLength(1), - z.refine((value) => decodeBase64Flexible(value) !== null, { + z.refine((value) => decodeBase64url(value, true) !== null, { message: "Field must be valid base64url data", }), ); @@ -130,30 +131,30 @@ function toPublic(key: Key): PublicKey { /** Parse a key from a string, auto-detecting JSON or base64url encoding. */ function parse(jwk: string): Key { - const trimmed = jwk.trim(); + // Trimmed as Rust's `str::trim` does, which differs from `String.trim` on U+0085 and U+FEFF. + const trimmed = jwk.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, ""); - let data: unknown; - if (trimmed.startsWith("{")) { - // Plain JSON - try { - data = JSON.parse(trimmed); - } catch { - throw new Error("Failed to parse JWK: invalid JSON format"); - } - } else { - // Base64url encoded JSON - const decoded = decodeBase64Flexible(trimmed); + let json = trimmed; + if (!trimmed.startsWith("{")) { + // Base64url encoded JSON, unpadded as both languages write it. + const decoded = decodeBase64url(trimmed, false); if (!decoded) { throw new Error("Failed to decode JWK: invalid base64url encoding"); } try { - const jsonString = new TextDecoder().decode(decoded); - data = JSON.parse(jsonString); + json = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(decoded); } catch { - throw new Error("Failed to parse JWK: invalid JSON format after base64url decode"); + throw new Error("Failed to decode JWK: invalid UTF-8 after base64url decode"); } } + let data: unknown; + try { + data = Json.parse(json); + } catch (error) { + throw new Error(`Failed to parse JWK: ${error instanceof Error ? error.message : "invalid JSON"}`); + } + try { return KeySchema.parse(data); } catch (error) { @@ -413,7 +414,7 @@ function keyIssue( switch (key.kty) { case "oct": { if (!HMAC_ALGORITHMS.has(key.alg)) return `Algorithm ${key.alg} is incompatible with oct keys`; - const secret = decodeBase64Flexible(key.k); + const secret = decodeBase64url(key.k, true); if (!secret || secret.byteLength < MIN_HMAC_SECRET_BYTES) { return `Secret must be at least ${MIN_HMAC_SECRET_BYTES} bytes when decoded`; } @@ -428,8 +429,8 @@ function keyIssue( if (key.crv !== expectedCurve) return `Algorithm ${key.alg} requires curve ${expectedCurve}`; const length = key.crv === "P-256" ? 32 : 48; if ( - decodeBase64Flexible(key.x)?.byteLength !== length || - decodeBase64Flexible(key.y)?.byteLength !== length + decodeBase64url(key.x, true)?.byteLength !== length || + decodeBase64url(key.y, true)?.byteLength !== length ) { return `Coordinates must be ${length} bytes for ${key.crv}`; } @@ -483,16 +484,20 @@ async function importJoseKey(key: Key | PublicKey): Promise, } -/// A document under `jwk`, `jwks`, or `grant`, and whether it is accepted. +/// A document under `jwk`, `jwks`, or `grant`, and whether it is accepted. A key or set +/// given as a string is its raw text, for what a JSON value cannot spell, such as a +/// repeated member. #[derive(Deserialize)] struct Case { name: String, @@ -97,18 +99,24 @@ fn tokens() { } } +/// A document's text: a string as written, anything else serialized. +fn text(document: Value) -> String { + match document { + Value::String(text) => text, + document => document.to_string(), + } +} + #[test] fn documents() { let corpus = corpus(); type Parse = fn(Value) -> Result<(), String>; let parsers: [(&str, Vec, Parse); 3] = [ ("jwk", corpus.jwk, |jwk| { - Key::from_str(&jwk.to_string()).map(drop).map_err(|err| err.to_string()) + Key::from_str(&text(jwk)).map(drop).map_err(|err| err.to_string()) }), ("sets", corpus.sets, |jwks| { - KeySet::from_str(&jwks.to_string()) - .map(drop) - .map_err(|err| err.to_string()) + KeySet::from_str(&text(jwks)).map(drop).map_err(|err| err.to_string()) }), ("grants", corpus.grants, |grant| { let grant: Grant = serde_json::from_value(grant).map_err(|err| err.to_string())?; diff --git a/rs/moq-auth/src/fuzz.rs b/rs/moq-auth/src/fuzz.rs index 38a0164e8ec..9f0af1d453d 100644 --- a/rs/moq-auth/src/fuzz.rs +++ b/rs/moq-auth/src/fuzz.rs @@ -338,11 +338,13 @@ pub fn seeds() -> Vec { for jwk in corpus["keys"].as_object().expect("keys").values() { push("jwk", 0, &jwk.to_string()); } + // A case given as a string is the document's raw text. + let text = |document: &Value| document.as_str().map_or_else(|| document.to_string(), str::to_owned); for case in corpus["jwk"].as_array().expect("jwk cases") { - push("jwk", 0, &case["jwk"].to_string()); + push("jwk", 0, &text(&case["jwk"])); } for case in corpus["sets"].as_array().expect("set cases") { - push("jwk", 1, &case["jwks"].to_string()); + push("jwk", 1, &text(&case["jwks"])); } for key in KEYS { push("jwk", 0, key); diff --git a/rs/moq-auth/src/key.rs b/rs/moq-auth/src/key.rs index a9dc3180582..2fffbf71ff1 100644 --- a/rs/moq-auth/src/key.rs +++ b/rs/moq-auth/src/key.rs @@ -152,20 +152,42 @@ pub struct RsaPrivateKey { pub oth: Option>, } +const RSA_PRIVATE_FIELDS: [&str; 6] = ["d", "p", "q", "dp", "dq", "qi"]; + // Flattening Option otherwise swallows missing-field errors and turns // malformed private keys into public keys. Decide whether private material exists first. fn deserialize_rsa_private<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { - let fields = serde_json::Map::::deserialize(deserializer)?; + // The leftover members, refusing a repeated private one as every other field does, so its + // value never depends on which copy a parser keeps. Unread members may repeat. + struct Fields; + + impl<'de> serde::de::Visitor<'de> for Fields { + type Value = serde_json::Map; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a JWK object") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut fields = serde_json::Map::new(); + while let Some((key, value)) = map.next_entry::()? { + if RSA_PRIVATE_FIELDS.contains(&key.as_str()) && fields.contains_key(&key) { + return Err(serde::de::Error::custom(format!("duplicate field `{key}`"))); + } + fields.insert(key, value); + } + Ok(fields) + } + } + + let fields = deserializer.deserialize_map(Fields)?; if fields.contains_key("oth") { return Err(serde::de::Error::custom("multi-prime RSA (oth) is unsupported")); } - if ["d", "p", "q", "dp", "dq", "qi"] - .iter() - .any(|field| fields.contains_key(*field)) - { + if RSA_PRIVATE_FIELDS.iter().any(|field| fields.contains_key(*field)) { serde_json::from_value(serde_json::Value::Object(fields)) .map(Some) .map_err(serde::de::Error::custom) @@ -1539,6 +1561,18 @@ mod tests { } } + #[test] + fn private_rsa_refuses_a_repeated_member() { + let key = Key::generate(Algorithm::RS256, None).unwrap(); + let json = serde_json::to_string(&key).unwrap(); + for field in RSA_PRIVATE_FIELDS { + // The flattened private fields are read apart from the rest, so check each one. + let repeated = format!("{{\"{field}\":\"AQ\",{}", &json[1..]); + let error = Key::from_str(&repeated).expect_err(field); + assert!(error.to_string().contains("duplicate field"), "{field}: {error}"); + } + } + #[test] fn private_rsa_rejects_other_primes() { let key = Key::generate(Algorithm::RS256, None).unwrap(); diff --git a/rs/moq-auth/tests/corpus.json b/rs/moq-auth/tests/corpus.json index 41abda31207..1af3d691317 100644 --- a/rs/moq-auth/tests/corpus.json +++ b/rs/moq-auth/tests/corpus.json @@ -329,6 +329,101 @@ "d": "" }, "valid": false + }, + { + "name": "a_padded_field", + "jwk": { + "kty": "oct", + "alg": "HS256", + "k": "jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA=" + }, + "valid": true + }, + { + "name": "nonzero_trailing_bits", + "jwk": { + "kty": "oct", + "alg": "HS256", + "k": "jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQB" + }, + "valid": false + }, + { + "name": "nonzero_trailing_bits_behind_padding", + "jwk": { + "kty": "oct", + "alg": "HS256", + "k": "jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQB=" + }, + "valid": false + }, + { + "name": "a_field_with_whitespace", + "jwk": { + "kty": "oct", + "alg": "HS256", + "k": " jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA" + }, + "valid": false + }, + { + "name": "a_field_in_the_standard_alphabet", + "jwk": { + "kty": "oct", + "alg": "HS256", + "k": "jvS2B/SKkvhtObaiKg9n2vq/Iqdus+nVCVVYBWf0BQA" + }, + "valid": false + }, + { + "name": "a_repeated_member", + "jwk": "{\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\",\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}", + "valid": false + }, + { + "name": "a_repeated_scope_member", + "jwk": "{\"scope\":{\"root\":\"a\",\"root\":\"b\",\"publish\":[\"**\"]},\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}", + "valid": false + }, + { + "name": "a_repeated_unread_member", + "jwk": "{\"note\":1,\"note\":2,\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}", + "valid": true + }, + { + "name": "base64url_encoded", + "jwk": "eyJrdHkiOiJvY3QiLCJhbGciOiJIUzI1NiIsImsiOiJqdlMyQl9TS2t2aHRPYmFpS2c5bjJ2cV9JcWR1cy1uVkNWVllCV2YwQlFBIn0", + "valid": true + }, + { + "name": "base64url_encoded_with_padding", + "jwk": "eyJrdHkiOiJvY3QiLCJhbGciOiJIUzI1NiIsImsiOiJqdlMyQl9TS2t2aHRPYmFpS2c5bjJ2cV9JcWR1cy1uVkNWVllCV2YwQlFBIn0=", + "valid": false + }, + { + "name": "a_byte_order_mark", + "jwk": "\ufeff{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}", + "valid": false + }, + { + "name": "a_lone_surrogate", + "jwk": "{\"note\":\"\\ud800\",\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}", + "valid": false + }, + { + "name": "nesting_at_the_recursion_limit", + "jwk": "{\"note\":[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]],\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}", + "valid": true + }, + { + "name": "nesting_past_the_recursion_limit", + "jwk": "{\"note\":[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]],\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}", + "valid": false + }, + { + "name": "a_number_out_of_range", + "jwk": "{\"note\":1e400,\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}", + "valid": false } ], "sets": [ @@ -406,6 +501,16 @@ ] }, "valid": false + }, + { + "name": "a_repeated_keys_member", + "jwks": "{\"keys\":[],\"keys\":[{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}]}", + "valid": false + }, + { + "name": "leading_unicode_whitespace", + "jwks": "\u00a0{\"keys\":[{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}]}", + "valid": false } ], "grants": [ From e265faebee2311741db244cfc9ba382bb4c54f0f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 09:54:22 -0800 Subject: [PATCH 3/3] fix(moq-auth): a key set refuses an unread member serde_json would refuse in a key KeySet read a plain RawKeySet, so serde_json skipped an unknown top-level member through ignore_value, checking only its syntax: 1e400, a lone surrogate, or nesting past the recursion limit got through, while @moq/auth's KeySet.parse refuses them. A flattened catch-all buffers every member as a key's own members are, so both refuse them. A repeated unread member stays accepted in both. Co-Authored-By: Claude Opus 5.5 --- rs/moq-auth/src/set.rs | 5 +++++ rs/moq-auth/tests/corpus.json | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/rs/moq-auth/src/set.rs b/rs/moq-auth/src/set.rs index a3e9ce1ac03..dc51590a814 100644 --- a/rs/moq-auth/src/set.rs +++ b/rs/moq-auth/src/set.rs @@ -35,6 +35,11 @@ impl<'de> Deserialize<'de> for KeySet { #[derive(Deserialize)] struct RawKeySet { keys: Vec, + // Without a catch-all, serde_json skips an unread member checking only its syntax, + // so `1e400`, a lone surrogate, or nesting past the recursion limit got through. + // Flattening buffers every member, refusing those as a key's own members are. + #[serde(flatten)] + _unread: std::collections::HashMap, } let raw = RawKeySet::deserialize(deserializer)?; diff --git a/rs/moq-auth/tests/corpus.json b/rs/moq-auth/tests/corpus.json index 1af3d691317..1ed782f1126 100644 --- a/rs/moq-auth/tests/corpus.json +++ b/rs/moq-auth/tests/corpus.json @@ -507,6 +507,26 @@ "jwks": "{\"keys\":[],\"keys\":[{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}]}", "valid": false }, + { + "name": "a_repeated_unread_member", + "jwks": "{\"note\":1,\"note\":2,\"keys\":[{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}]}", + "valid": true + }, + { + "name": "an_unread_member_out_of_range", + "jwks": "{\"keys\":[{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}],\"note\":1e400}", + "valid": false + }, + { + "name": "an_unread_member_with_a_lone_surrogate", + "jwks": "{\"keys\":[{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}],\"note\":\"\\ud800\"}", + "valid": false + }, + { + "name": "an_unread_member_nested_too_deep", + "jwks": "{\"keys\":[{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}],\"note\":[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}", + "valid": false + }, { "name": "leading_unicode_whitespace", "jwks": "\u00a0{\"keys\":[{\"kty\":\"oct\",\"alg\":\"HS256\",\"k\":\"jvS2B_SKkvhtObaiKg9n2vq_Iqdus-nVCVVYBWf0BQA\"}]}",