diff --git a/pkgs/id/crates/id-core/src/canonical_cbor.rs b/pkgs/id/crates/id-core/src/canonical_cbor.rs index 4e7fbb2251..6000bde08a 100644 --- a/pkgs/id/crates/id-core/src/canonical_cbor.rs +++ b/pkgs/id/crates/id-core/src/canonical_cbor.rs @@ -129,7 +129,13 @@ fn encode_argument(major: u8, value: u64, out: &mut Vec) { } } -fn encode_into(value: &Value, out: &mut Vec) -> Result<(), CborError> { +/// Encodes `value` at nesting `depth`, with the decoder's exact depth rule (#11315): a +/// value deeper than [`MAX_NESTING_DEPTH`] is refused, so every encoding round-trips and +/// a caller-built deep value cannot exhaust the stack. +fn encode_into(value: &Value, out: &mut Vec, depth: u32) -> Result<(), CborError> { + if depth > MAX_NESTING_DEPTH { + return Err(CborError::TooDeeplyNested); + } match value { Value::Null => out.push(0xf6), Value::Bool(false) => out.push(0xf4), @@ -150,7 +156,7 @@ fn encode_into(value: &Value, out: &mut Vec) -> Result<(), CborError> { Value::Array(items) => { encode_argument(4, items.len() as u64, out); for item in items { - encode_into(item, out)?; + encode_into(item, out, depth + 1)?; } } Value::Map(entries) => { @@ -162,7 +168,7 @@ fn encode_into(value: &Value, out: &mut Vec) -> Result<(), CborError> { return Err(CborError::InvalidMapKey); } let mut key_bytes = Vec::new(); - encode_into(key, &mut key_bytes)?; + encode_into(key, &mut key_bytes, depth + 1)?; if encoded.iter().any(|(existing, _)| *existing == key_bytes) { return Err(CborError::DuplicateKey); } @@ -172,7 +178,7 @@ fn encode_into(value: &Value, out: &mut Vec) -> Result<(), CborError> { encode_argument(5, encoded.len() as u64, out); for (key_bytes, val) in encoded { out.extend_from_slice(&key_bytes); - encode_into(val, out)?; + encode_into(val, out, depth + 1)?; } } } @@ -182,7 +188,7 @@ fn encode_into(value: &Value, out: &mut Vec) -> Result<(), CborError> { /// Encode a value in the canonical profile. pub fn encode_canonical(value: &Value) -> Result, CborError> { let mut out = Vec::new(); - encode_into(value, &mut out)?; + encode_into(value, &mut out, 0)?; Ok(out) } diff --git a/pkgs/id/crates/id-core/tests/canonical_cbor_vectors.rs b/pkgs/id/crates/id-core/tests/canonical_cbor_vectors.rs index f99bc564a8..56f8e04532 100644 --- a/pkgs/id/crates/id-core/tests/canonical_cbor_vectors.rs +++ b/pkgs/id/crates/id-core/tests/canonical_cbor_vectors.rs @@ -187,6 +187,40 @@ fn nesting_deeper_than_the_limit_rejects() { assert_eq!(decode_canonical(&deeper), Err(CborError::TooDeeplyNested)); } +/// `levels` nested arrays around a `0` leaf, built as a value. +fn nested_arrays(levels: usize) -> Value { + let mut value = Value::UInt(0); + for _ in 0..levels { + value = Value::Array(vec![value]); + } + value +} + +#[test] +fn encoder_applies_the_decoders_depth_limit() { + use id_core::canonical_cbor::MAX_NESTING_DEPTH; + + // #11315: at the limit the encoder succeeds and the bytes decode back. + let at_limit = nested_arrays(MAX_NESTING_DEPTH as usize); + let bytes = encode_canonical(&at_limit).unwrap(); + assert_eq!(decode_canonical(&bytes).unwrap(), at_limit); + + // One level deeper is refused by the encoder with the decoder's error, + // instead of producing bytes the decoder rejects. + let deeper = nested_arrays(MAX_NESTING_DEPTH as usize + 1); + assert_eq!(encode_canonical(&deeper), Err(CborError::TooDeeplyNested)); + + // The same rule through a map value. + let in_map = Value::Map(vec![(text("k"), nested_arrays(MAX_NESTING_DEPTH as usize))]); + assert_eq!(encode_canonical(&in_map), Err(CborError::TooDeeplyNested)); + + // Far deeper caller-built values fail fast instead of recursing without bound. + assert_eq!( + encode_canonical(&nested_arrays(10_000)), + Err(CborError::TooDeeplyNested) + ); +} + #[test] fn unknown_critical_fields_reject_and_others_tolerate() { let record = Value::Map(vec![ diff --git a/pkgs/id/hosted-worker/src/canonical-cbor.ts b/pkgs/id/hosted-worker/src/canonical-cbor.ts index e2e841a4aa..aa23cc053f 100644 --- a/pkgs/id/hosted-worker/src/canonical-cbor.ts +++ b/pkgs/id/hosted-worker/src/canonical-cbor.ts @@ -76,7 +76,9 @@ function isKey(value: CborValue): boolean { return value.kind === "text" || value.kind === "uint" || value.kind === "int"; } -function encodeInto(value: CborValue, out: number[]): void { +function encodeInto(value: CborValue, out: number[], depth: number): void { + // #11315: refuse what decodeCanonical would refuse, and bound recursion. + if (depth > MAX_NESTING_DEPTH) throw new CborError("TooDeeplyNested"); switch (value.kind) { case "null": out.push(0xf6); @@ -102,14 +104,14 @@ function encodeInto(value: CborValue, out: number[]): void { } case "array": encodeArgument(4, BigInt(value.value.length), out); - for (const item of value.value) encodeInto(item, out); + for (const item of value.value) encodeInto(item, out, depth + 1); return; case "map": { const encoded: { keyBytes: Uint8Array; val: CborValue }[] = []; for (const [key, val] of value.value) { if (!isKey(key)) throw new CborError("InvalidMapKey"); const keyOut: number[] = []; - encodeInto(key, keyOut); + encodeInto(key, keyOut, depth + 1); const keyBytes = new Uint8Array(keyOut); if (encoded.some((e) => compareBytes(e.keyBytes, keyBytes) === 0)) { throw new CborError("DuplicateKey"); @@ -120,7 +122,7 @@ function encodeInto(value: CborValue, out: number[]): void { encodeArgument(5, BigInt(encoded.length), out); for (const { keyBytes, val } of encoded) { out.push(...keyBytes); - encodeInto(val, out); + encodeInto(val, out, depth + 1); } return; } @@ -130,7 +132,7 @@ function encodeInto(value: CborValue, out: number[]): void { /** Encode a value in the canonical profile. */ export function encodeCanonical(value: CborValue): Uint8Array { const out: number[] = []; - encodeInto(value, out); + encodeInto(value, out, 0); return new Uint8Array(out); } diff --git a/pkgs/id/hosted-worker/test/canonical-cbor.test.ts b/pkgs/id/hosted-worker/test/canonical-cbor.test.ts index 6ea94a7230..9dce808fa6 100644 --- a/pkgs/id/hosted-worker/test/canonical-cbor.test.ts +++ b/pkgs/id/hosted-worker/test/canonical-cbor.test.ts @@ -124,6 +124,31 @@ test("nesting deeper than the limit rejects", () => { ); }); +/** `levels` nested arrays around a `0` leaf, built as a value. */ +function nestedArrays(levels: number): CborValue { + let value: CborValue = uint(0n); + for (let i = 0; i < levels; i++) value = { kind: "array", value: [value] }; + return value; +} + +const tooDeep = (err: unknown) => err instanceof CborError && err.code === "TooDeeplyNested"; + +test("the encoder applies the decoder's depth limit", () => { + // #11315: at the limit the encoder succeeds and the bytes decode back. + const atLimit = nestedArrays(MAX_NESTING_DEPTH); + assert.deepEqual(decodeCanonical(encodeCanonical(atLimit)), atLimit); + + // One level deeper is refused by the encoder with the decoder's error. + assert.throws(() => encodeCanonical(nestedArrays(MAX_NESTING_DEPTH + 1)), tooDeep); + + // The same rule through a map value. + const inMap: CborValue = { kind: "map", value: [[text("k"), nestedArrays(MAX_NESTING_DEPTH)]] }; + assert.throws(() => encodeCanonical(inMap), tooDeep); + + // Far deeper values fail fast instead of overflowing the stack. + assert.throws(() => encodeCanonical(nestedArrays(100_000)), tooDeep); +}); + test("unknown critical fields reject and others tolerate", () => { const record: CborValue = { kind: "map",