From 0ff163abda519fcaa3194eae17e5cb0f69aefbc0 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:39:07 +0000 Subject: [PATCH 01/15] fix(server): parse request bodies nested to the depth the service validates The request handler read the JSON body with serde_json's default deserializer, which refuses a document nested past 128 levels with a SerializationException. A request whose attribute nested deeper was refused before the nesting depth check ran, so a body that the service answers with the document nesting ValidationException got a serialization error here instead. Amazon DynamoDB parses and validates a body nested to at least about 2000 document wrappers (roughly 4000 JSON levels) and answers it with "Nesting Levels have exceeded supported limits". It refuses only a deeper body, and then with a SerializationException that has no message field (measured 2026-11-02, us-east-1). request_parse.rs disables the deserializer's recursion limit for the request body. A byte scan first bounds the structural nesting at 5200 levels (about 2600 wrappers), so a deeper body is refused before any recursive work. Every body the service validates is parsed and reaches the nesting check. Past the ceiling the server answers a SerializationException with an empty message, so error_response omits the message field, as the service does. A shallow or malformed body gets the same SerializationException as before. A body at the ceiling recurses to its depth three times: the parse, the conversion to typed AttributeValues, and the drop of both. In a debug build that takes about 13 MiB of stack, so cmd_serve sizes each serve worker thread at 32 MiB, over twice the measured peak. The request_parse unit tests and the dual-target tests/test_request_nesting_depth.py cover an attribute within the limit, a 63-level attribute, bodies of 120, 300, 1000 and 2000 wrappers that get the nesting ValidationException, and one far past the ceiling that gets the message-less SerializationException. The deep bodies are built as raw JSON and signed, so no client library recurses to produce them. --- crates/app/src/cmd_serve.rs | 9 ++ crates/server/Cargo.toml | 2 +- crates/server/src/handler.rs | 11 +- crates/server/src/lib.rs | 1 + crates/server/src/request_parse.rs | 239 ++++++++++++++++++++++++++++ tests/raw_signed_request.py | 13 +- tests/test_request_nesting_depth.py | 144 +++++++++++++++++ 7 files changed, 407 insertions(+), 12 deletions(-) create mode 100644 crates/server/src/request_parse.rs create mode 100644 tests/test_request_nesting_depth.py diff --git a/crates/app/src/cmd_serve.rs b/crates/app/src/cmd_serve.rs index a754aa4c2..75d24fc0c 100755 --- a/crates/app/src/cmd_serve.rs +++ b/crates/app/src/cmd_serve.rs @@ -277,6 +277,15 @@ pub fn run(args: &ServeArgs, build: BuildInfo) -> anyhow::Result<()> { } let result = tokio::runtime::Builder::new_multi_thread() .enable_all() + // A deeply nested but valid request body is parsed, converted to typed + // AttributeValues, and dropped on a worker thread, each step recursing + // to the body's depth. The request parser caps nesting at 5200 + // structural levels (about 2600 document wrappers; extenddb-server's + // request_parse). Measured 2026-11-02 (debug): an 8 MiB stack overflows + // past about 1500 wrappers, while 32 MiB handles the ceiling and a 5500 + // wrapper body besides. Give each worker 32 MiB, well above the 2 MiB + // default. + .thread_stack_size(32 * 1024 * 1024) .build()? .block_on(extenddb_server::serve(params)); // `serve` has printed the refusal; end with its code, which `migrate` diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index da5da4f74..d2aca1a49 100755 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -25,7 +25,7 @@ tower-http = { workspace = true } hyper = { workspace = true } tokio = { workspace = true } serde = { workspace = true } -serde_json = { workspace = true } +serde_json = { workspace = true, features = ["unbounded_depth"] } tracing = { workspace = true } crc32fast = { workspace = true } uuid = { workspace = true } diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index ef3765bda..a6934b9de 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -77,16 +77,9 @@ pub(crate) async fn handle_request( // --- Pre-auth body validation --- // Real DynamoDB validates request format (empty body, invalid JSON) before // authentication. Malformed requests get 400 regardless of auth state. - let input: Value = match serde_json::from_slice(&body) { + let input: Value = match crate::request_parse::parse_request_value(&body) { Ok(v) => v, - Err(e) => { - return error_response( - &DynamoDbError::SerializationException(format!( - "Start of structure or map found where not expected: {e}" - )), - &request_id, - ); - } + Err(e) => return error_response(&e, &request_id), }; // --- Auth segment --- diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index f608c74d7..cebccad3d 100755 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -22,6 +22,7 @@ mod metrics_endpoint; pub mod rate_limit; mod registration; mod request_helpers; +mod request_parse; mod request_tags; mod response; mod serve; diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs new file mode 100644 index 000000000..50e1f619a --- /dev/null +++ b/crates/server/src/request_parse.rs @@ -0,0 +1,239 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Request body JSON parsing with a bounded nesting depth. +//! +//! `serde_json`'s deserializer refuses any document nested past 128 levels with +//! a recursion error, which the server turned into a `SerializationException`. +//! Amazon DynamoDB instead parses requests nested far past that and answers +//! with the validation that applies (the 32 level document limit, or whichever +//! check runs first), so the parser has to reach those checks rather than +//! refuse the request (measured 2026-11-02: a stored attribute nested 63 levels +//! is a `ValidationException` about the nesting limit, not a serialization +//! error). +//! +//! The recursion limit is therefore disabled, and a byte scan bounds the +//! structural nesting first so a hostile body (a 16 MiB request can nest to +//! millions of levels) cannot overflow the worker stack. The ceiling sits far +//! above the depth any request validation needs and well under the stack a +//! worker is given (see [`MAX_REQUEST_JSON_DEPTH`]). + +use serde::Deserialize; +use serde_json::Value; + +use extenddb_core::error::DynamoDbError; + +/// Largest structural nesting (`{`/`[` openers on one path) the request parser +/// accepts; `serde_json`'s own default is 128. +/// +/// Amazon DynamoDB parses and validates a request body nested to at least about +/// 2000 document wrappers (roughly 4000 structural levels; measured 2026-11-02, +/// us-east-1), answering it with the nesting `ValidationException`, and only +/// refuses a still deeper body with a serialization error. The ceiling sits +/// above that accepted range: 5200 structural levels is about 2600 single-key +/// wrappers, so every body the service validates is parsed here too. +/// +/// A body this deep recurses the same number of levels three times over: the +/// `serde_json` parse, the conversion to typed `AttributeValue`s (which has no +/// recursion limit of its own), and the recursive drop of both. Measured +/// 2026-11-02 (debug): an 8 MiB stack handles about 1500 wrappers and overflows +/// past that, while a 32 MiB stack handles a body at this ceiling and well +/// beyond it (a 5500 wrapper body still completes). `extenddb-app`'s +/// `cmd_serve` gives each worker 32 MiB for that reason, over twice the +/// ceiling's need. A body nested past the ceiling is refused by the byte scan +/// below before any recursive work, so the stack is bounded whatever the depth. +const MAX_REQUEST_JSON_DEPTH: usize = 5200; + +/// Whether `body` nests past [`MAX_REQUEST_JSON_DEPTH`], counting `{` and `[` +/// outside string literals and stopping at the first level over the ceiling. +/// The scan never recurses, so it is safe at any depth. +fn exceeds_max_depth(body: &[u8]) -> bool { + let mut depth: usize = 0; + let mut in_string = false; + let mut escaped = false; + for &b in body { + if in_string { + if escaped { + escaped = false; + } else if b == b'\\' { + escaped = true; + } else if b == b'"' { + in_string = false; + } + continue; + } + match b { + b'"' => in_string = true, + b'{' | b'[' => { + depth += 1; + if depth > MAX_REQUEST_JSON_DEPTH { + return true; + } + } + b'}' | b']' => depth = depth.saturating_sub(1), + _ => {} + } + } + false +} + +/// Parse a request body into a JSON [`Value`], matching +/// `serde_json::from_slice` for everything within the depth ceiling and +/// refusing a body nested past it. +/// +/// A malformed or over deep body is a `SerializationException`, the error the +/// server has always returned for a body it cannot read. +pub(crate) fn parse_request_value(body: &[u8]) -> Result { + if exceeds_max_depth(body) { + // A body nested past what it will parse gets HTTP 400 with + // `{"__type":"com.amazon.coral.service#SerializationException"}` and no + // message field at all (measured 2026-11-02, us-east-1). An empty + // message makes `error_response` omit the field, matching that exactly. + return Err(DynamoDbError::SerializationException(String::new())); + } + // The depth ceiling above keeps the disabled recursion limit from letting a + // deep body overflow the stack. + let mut de = serde_json::Deserializer::from_slice(body); + de.disable_recursion_limit(); + let value = Value::deserialize(&mut de).map_err(|e| serialization_error(&e.to_string()))?; + de.end().map_err(|e| serialization_error(&e.to_string()))?; + Ok(value) +} + +/// The server's long standing wording for a request body it cannot read. +fn serialization_error(detail: &str) -> DynamoDbError { + DynamoDbError::SerializationException(format!( + "Start of structure or map found where not expected: {detail}" + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A PutItem-shaped body whose `data` attribute is `wrappers` single-key + /// maps around a string leaf: `{"M":{"n": ... {"S":"leaf"} ... }}`. + fn deep_body(wrappers: usize) -> Vec { + let mut s = String::from(r#"{"TableName":"t","Item":{"data":"#); + for _ in 0..wrappers { + s.push_str(r#"{"M":{"n":"#); + } + s.push_str(r#"{"S":"leaf"}"#); + for _ in 0..wrappers { + s.push_str("}}"); + } + s.push_str("}}"); + s.into_bytes() + } + + #[test] + fn parses_a_body_nested_past_serde_default() { + // 200 wrappers is ~400 structural levels, well past serde_json's 128 + // limit and under the ceiling, so it must parse rather than refuse. + let body = deep_body(200); + let value = parse_request_value(&body).expect("200 wrappers must parse"); + assert!(value.get("Item").is_some()); + } + + #[test] + fn refuses_a_body_past_the_ceiling_with_an_empty_message() { + // Past the ceiling. The byte scan refuses it before any recursion, so + // this is safe on the default test-thread stack. The refusal is a + // SerializationException with no message, so `error_response` omits the + // message field and matches the service's answer for such a body. + let body = deep_body(MAX_REQUEST_JSON_DEPTH + 50); + let err = parse_request_value(&body).unwrap_err(); + assert!(matches!(err, DynamoDbError::SerializationException(_))); + assert!( + err.message().is_empty(), + "an over-ceiling body must carry no message, got {:?}", + err.message() + ); + } + + #[test] + fn the_depth_scan_brackets_the_ceiling() { + // Scan only (no parse), so this is safe at any depth on the test stack. + assert!( + !exceeds_max_depth(&deep_body(100)), + "100 wrappers is under the ceiling" + ); + assert!( + exceeds_max_depth(&deep_body(MAX_REQUEST_JSON_DEPTH)), + "far past the ceiling" + ); + } + + #[test] + fn matches_serde_for_a_shallow_body() { + let body = br#"{"TableName":"t","Item":{"pk":{"S":"a"}}}"#; + let value = parse_request_value(body).expect("shallow body must parse"); + assert_eq!(value["TableName"], "t"); + } + + #[test] + fn braces_inside_a_string_do_not_count_as_nesting() { + let inner = "{".repeat(MAX_REQUEST_JSON_DEPTH + 100); + let body = format!(r#"{{"TableName":"{inner}"}}"#).into_bytes(); + let value = parse_request_value(&body).expect("braces in a string are not nesting"); + assert!(value.get("TableName").is_some()); + } + + #[test] + fn an_escaped_quote_does_not_end_the_string_scan() { + // The escaped quote keeps the scan inside the string, so the braces that + // follow it are string content and are not counted. + let body = br#"{"k":"a\"{{{{{","x":1}"#; + let value = parse_request_value(body).expect("must parse"); + assert_eq!(value["x"], 1); + } + + #[test] + fn a_malformed_body_is_a_serialization_error() { + let err = parse_request_value(b"{not json").unwrap_err(); + assert!(matches!(err, DynamoDbError::SerializationException(_))); + } + + #[test] + fn trailing_bytes_are_rejected_like_from_slice() { + let err = parse_request_value(br#"{"a":1} tail"#).unwrap_err(); + assert!(matches!(err, DynamoDbError::SerializationException(_))); + } + + #[test] + fn the_ceiling_admits_the_required_depth() { + // The byte scan admits the depth the service validates (2000 wrappers, + // ~4003 structural) and the deepest the ceiling allows (~2598), and + // refuses one wrapper more. The scan never recurses, so this is safe at + // any depth on the test stack. + assert!( + !exceeds_max_depth(&deep_body(2000)), + "2000 wrappers must be admitted" + ); + assert!( + !exceeds_max_depth(&deep_body(2598)), + "the ceiling admits about 2598 wrappers" + ); + assert!( + exceeds_max_depth(&deep_body(2599)), + "one wrapper past the ceiling is refused" + ); + } + + #[test] + fn parses_the_required_depth_on_a_worker_sized_stack() { + // 2000 wrappers (~4003 structural) is within the ceiling and must parse + // into a Value. Parsing this deep recurses past the default test-thread + // stack, so run it on a stack the size `cmd_serve` gives each worker. + let body = deep_body(2000); + std::thread::Builder::new() + .stack_size(32 * 1024 * 1024) + .spawn(move || { + let value = parse_request_value(&body).expect("2000 wrappers must parse"); + assert!(value.get("Item").is_some()); + }) + .unwrap() + .join() + .unwrap(); + } +} diff --git a/tests/raw_signed_request.py b/tests/raw_signed_request.py index 2fe02dfc5..b7f5874fc 100644 --- a/tests/raw_signed_request.py +++ b/tests/raw_signed_request.py @@ -29,8 +29,17 @@ def signed_post( body: Any, session_token: str | None = None, ) -> requests.Response: - """POST ``body`` as JSON to ``operation`` under the DynamoDB JSON-1.0 protocol.""" - payload = json.dumps(body, separators=(",", ":")).encode("utf-8") + """POST ``body`` as JSON to ``operation`` under the DynamoDB JSON-1.0 protocol. + + ``body`` is JSON-encoded here unless it is already ``bytes``: a body nested + too deep for ``json.dumps`` to build without recursing is passed as the raw + bytes it should be sent as. + """ + payload = ( + bytes(body) + if isinstance(body, (bytes, bytearray)) + else json.dumps(body, separators=(",", ":")).encode("utf-8") + ) headers = { "X-Amz-Target": f"DynamoDB_20120810.{operation}", "Content-Type": "application/x-amz-json-1.0", diff --git a/tests/test_request_nesting_depth.py b/tests/test_request_nesting_depth.py new file mode 100644 index 000000000..75cdc21ab --- /dev/null +++ b/tests/test_request_nesting_depth.py @@ -0,0 +1,144 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""A deeply nested request body is parsed and answered by the depth that +applies, not refused by the JSON parser. + +The JSON deserializer used to refuse any body nested past 128 structural levels +with a SerializationException, so a request whose attribute nested past that +never reached the nesting-depth check. Amazon DynamoDB parses such a request and +answers with the document nesting "Nesting Levels have exceeded supported +limits..." ValidationException, and only a body nested past about 2000 wrappers +(roughly 4000 JSON levels) is refused, then with a message-less +SerializationException. Measured against the service (us-east-1, 2026-11-02). + +Dual-target: runs against the service and against ExtendDB on every backend. + +Bodies shallow enough for the client library to serialize without hitting its +own recursion limit use boto3 directly; deeper bodies are built as raw JSON and +signed, so no client library recurses to produce them. +""" + +from __future__ import annotations + +import json +import sys + +import boto3 +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table +from raw_signed_request import signed_post + +# botocore serializes a nested dict recursively, so lift CPython's own limit for +# the boto3 cases below (the raw-JSON cases do not recurse and do not need it). +sys.setrecursionlimit(10_000) + +NEST = "Nesting Levels have exceeded supported limits" +NEST_FULL = ( + "Nesting Levels have exceeded supported limits: " + "Attributes in the item have nested levels beyond supported limit" +) +SERIALIZATION_TYPE = "com.amazon.coral.service#SerializationException" + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + with scoped_table(dynamodb_client) as name: + yield name + + +def _deep(wrappers: int) -> dict: + """`wrappers` single-key maps around a string leaf: depth 1 is + `{"M":{"n":{"S":"leaf"}}}`.""" + value: dict = {"S": "leaf"} + for _ in range(wrappers): + value = {"M": {"n": value}} + return value + + +def _put_error(client, table_name: str, data: dict) -> dict: + with pytest.raises(ClientError) as exc_info: + client.put_item(TableName=table_name, Item={"pk": {"S": "k"}, "data": data}) + return exc_info.value.response["Error"] + + +def _raw_put_body(table_name: str, pk: str, wrappers: int) -> bytes: + """A PutItem body whose `data` attribute is `wrappers` single-key maps around + a string leaf, assembled as raw JSON so nothing recurses to build it.""" + data = '{"M":{"n":' * wrappers + '{"S":"leaf"}' + "}}" * wrappers + return ( + '{"TableName":' + + json.dumps(table_name) + + ',"Item":{"pk":{"S":' + + json.dumps(pk) + + '},"data":' + + data + + "}}" + ).encode("utf-8") + + +def _raw_put(dynamodb_client, table_name: str, pk: str, wrappers: int): + """Sign and POST a raw deep PutItem body with the caller's own credentials.""" + frozen = boto3.Session().get_credentials().get_frozen_credentials() + return signed_post( + dynamodb_client.meta.endpoint_url, + frozen.access_key, + frozen.secret_key, + dynamodb_client.meta.region_name, + "PutItem", + _raw_put_body(table_name, pk, wrappers), + session_token=frozen.token, + ) + + +def test_an_attribute_within_the_limit_is_stored(dynamodb_client, table): + # Positive control: 31 wrappers (leaf at level 32) is within the document + # limit and is stored, so the parse change did not break the accept path. + dynamodb_client.put_item( + TableName=table, Item={"pk": {"S": "ok31"}, "data": _deep(31)} + ) + + +def test_a_63_level_attribute_is_a_nesting_validation_error(dynamodb_client, table): + # 63 wrappers nests the request just past the 128 structural level parse + # limit. The server must read it and answer with the nesting + # ValidationException, not a SerializationException. + err = _put_error(dynamodb_client, table, _deep(63)) + assert err["Code"] == "ValidationException", err + assert err["Message"] == NEST_FULL, err + + +def test_an_attribute_far_past_the_parse_limit_still_validates(dynamodb_client, table): + # Well past the old parse limit and within the request depth ceiling: still + # a nesting ValidationException, never a parse failure. + err = _put_error(dynamodb_client, table, _deep(120)) + assert err["Code"] == "ValidationException", err + assert NEST in err["Message"], err + + +@pytest.mark.parametrize("wrappers", [300, 1000, 2000]) +def test_a_deep_body_within_the_ceiling_is_a_nesting_validation_error( + dynamodb_client, table, wrappers +): + # The service parses a body nested far past the old 128 level parse limit, + # up to at least 2000 wrappers, and answers with the document nesting + # ValidationException. Built as raw JSON so the client does not recurse. + resp = _raw_put(dynamodb_client, table, f"deep{wrappers}", wrappers) + assert resp.status_code == 400, resp.text + err = resp.json() + assert err["__type"].endswith("ValidationException"), err + assert err["message"] == NEST_FULL, err + + +def test_a_body_far_past_the_ceiling_is_a_messageless_serialization_error( + dynamodb_client, table +): + # Far past any depth the service parses. It answers HTTP 400 with the + # SerializationException type and no message field at all. + resp = _raw_put(dynamodb_client, table, "huge", 20_000) + assert resp.status_code == 400, resp.text + err = resp.json() + assert err["__type"] == SERIALIZATION_TYPE, err + assert "message" not in err, err From 3a94df0019d6481459ee65baee5411281c8d506d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:00:50 +0000 Subject: [PATCH 02/15] fix(server): parse a body past serde's depth only after authentication The handler parsed every request body before authentication, with the deserializer's recursion limit disabled and the byte scan's 5200 level ceiling as the only bound. On a runtime whose threads have Tokio's default 2 MiB stack, the parse of an unsigned body within that ceiling overflows the stack and aborts the process (measured 2026-11-12, debug build: 700 single-key wrappers on 2 MiB), so anyone who can reach the listener can take the server down without credentials. extenddb's own serve sizes its workers at 32 MiB, but extenddb_server::serve and start_server are public and run on whatever runtime the caller built. Amazon DynamoDB checks the request's JSON syntax before authentication and refuses an over deep body only after it. Measured 2026-11-12 in us-east-1: an unsigned PutItem of 63, 2000 or 20000 wrappers is a 400 MissingAuthenticationTokenException on every send, a badly signed one is an InvalidSignatureException, and only the signed 20000 wrapper body is the message-less SerializationException. Unsigned malformed JSON is a SerializationException at any depth. The handler now scans the depth first and parses a body within serde_json's default 128 levels before authentication, as it always did on a default stack. A deeper body is parsed only once the caller is authenticated, so no unauthenticated request makes the handling thread recurse past that depth, and an unsigned deep body gets the MissingAuthenticationToken answer the service gives. The stack a thread needs for an authenticated body at the ceiling is now the exported REQUEST_WORKER_STACK_SIZE, used by cmd_serve and the unit test, and the requirement is documented on serve and start_server. The one shape that still differs is an unsigned body that is both malformed and deeper than 128 levels: the service answers SerializationException, the server MissingAuthenticationToken, because checking its syntax would mean recursing before authentication. The ceiling comment no longer claims every body the service validates is parsed. Measured 2026-11-12, 24 sends per depth across four windows: up to 1700 wrappers the service answered the nesting ValidationException on every send, from 1800 wrappers the answer varied per request between that and the message-less SerializationException (4000 wrappers also drew 500 InternalFailure 7 times), 5000 and 20000 wrappers were refused on every send, and an unknown top-level member nested 5201, 6001 or 20000 levels was ignored (200) by PutItem, DescribeTable and ListTables. The 5200 level ceiling (2598 wrappers) sits inside the band where the service itself varies. The scan tests now pin the behaviour the ceiling relies on: an over ceiling attribute behind an escaped quote is counted and refused, 3000 shallow sibling maps (more openers than the ceiling, depth 5) parse, as the service stores them, bodies of exactly 5200 and 5201 levels bracket the ceiling, and a malformed body carries the server's usual message. Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> --- crates/app/src/cmd_serve.rs | 15 +- crates/server/src/handler.rs | 30 +++- crates/server/src/lib.rs | 6 + crates/server/src/request_parse.rs | 223 ++++++++++++++++++++--------- crates/server/src/serve.rs | 3 + 5 files changed, 193 insertions(+), 84 deletions(-) diff --git a/crates/app/src/cmd_serve.rs b/crates/app/src/cmd_serve.rs index 8f2193ff1..069da1872 100755 --- a/crates/app/src/cmd_serve.rs +++ b/crates/app/src/cmd_serve.rs @@ -290,15 +290,12 @@ pub fn run(args: &ServeArgs, build: BuildInfo) -> anyhow::Result<()> { // join it, holding the process open after the drain until SIGKILL. let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() - // A deeply nested but valid request body is parsed, converted to typed - // AttributeValues, and dropped on a worker thread, each step recursing - // to the body's depth. The request parser caps nesting at 5200 - // structural levels (about 2600 document wrappers; extenddb-server's - // request_parse). Measured 2026-11-02 (debug): an 8 MiB stack overflows - // past about 1500 wrappers, while 32 MiB handles the ceiling and a 5500 - // wrapper body besides. Give each worker 32 MiB, well above the 2 MiB - // default. - .thread_stack_size(32 * 1024 * 1024) + // An authenticated request body nested to the parser's ceiling is + // parsed, converted to typed AttributeValues and dropped on a worker + // thread, each step recursing to the body's depth; the server crate + // that sets the ceiling sizes the stack that needs (about twice the + // measured need, far above Tokio's 2 MiB default). + .thread_stack_size(extenddb_server::REQUEST_WORKER_STACK_SIZE) .build()?; let result = crate::run_then_shut_down(runtime, extenddb_server::serve(params)); // `serve` has printed the refusal; end with its code, which `migrate` diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 364c5d43d..b33031513 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -94,11 +94,21 @@ pub(crate) async fn handle_request( } // --- Pre-auth body validation --- - // Real DynamoDB validates request format (empty body, invalid JSON) before - // authentication. Malformed requests get 400 regardless of auth state. - let input: Value = match crate::request_parse::parse_request_value(&body) { - Ok(v) => v, - Err(e) => return error_response(&e, &request_id), + // The service checks the request's JSON syntax before authentication but + // refuses an over deep body only after it (measured 2026-11-12: unsigned, + // a 20000 wrapper PutItem is MissingAuthenticationTokenException; signed, + // SerializationException). A body within serde_json's default depth is + // parsed here, as it always was; a deeper one is only scanned until the + // caller is authenticated, so no unauthenticated request makes this + // thread recurse past that depth (see request_parse). + let depth = crate::request_parse::nesting_depth(&body); + let pre_auth_input = if depth <= crate::request_parse::UNAUTHENTICATED_PARSE_DEPTH { + match crate::request_parse::parse_request_value(&body, depth) { + Ok(v) => Some(v), + Err(e) => return error_response(&e, &request_id), + } + } else { + None }; // --- Auth segment --- @@ -110,6 +120,16 @@ pub(crate) async fn handle_request( #[allow(clippy::cast_precision_loss)] let auth_us = auth_start.elapsed().as_micros() as f64; + // A body deeper than the pre-auth depth is parsed now, on a thread whose + // stack `REQUEST_WORKER_STACK_SIZE` sizes for the ceiling. + let input: Value = match pre_auth_input { + Some(v) => v, + None => match crate::request_parse::parse_request_value(&body, depth) { + Ok(v) => v, + Err(e) => return error_response(&e, &request_id), + }, + }; + let account_id: Arc = match &identity { extenddb_auth::AuthIdentity::User { account_id, .. } | extenddb_auth::AuthIdentity::RoleSession { account_id, .. } => { diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 84fdf822e..afcab0013 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -36,6 +36,7 @@ mod table_name_gate; mod throttle_helpers; mod workers; +pub use request_parse::REQUEST_WORKER_STACK_SIZE; pub use serve::{ BuildInfo, CatalogRefusal, JOB_DRAIN_TIMEOUT, LogTarget, RegistrationLost, ServeParams, WORKER_STOP_TIMEOUT, catalog_refusal, log_to_syslog_raw, serve, @@ -144,6 +145,11 @@ pub const CONNECTION_DRAIN_TIMEOUT: Duration = Duration::from_secs(5); /// It stops on SIGINT or SIGTERM, or when `state`'s admission asks for a /// stop after the serving registration was lost; both drain the listener /// the same way and remove the PID file. +/// +/// The runtime this runs on must give its threads at least +/// [`REQUEST_WORKER_STACK_SIZE`] of stack: an authenticated request body nested +/// to the parser's ceiling recurses to that depth on the handling thread, and +/// Tokio's default 2 MiB overflows there. pub async fn start_server( listener: tokio::net::TcpListener, state: AppState, diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index 50e1f619a..32607db89 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -12,11 +12,16 @@ //! is a `ValidationException` about the nesting limit, not a serialization //! error). //! -//! The recursion limit is therefore disabled, and a byte scan bounds the -//! structural nesting first so a hostile body (a 16 MiB request can nest to -//! millions of levels) cannot overflow the worker stack. The ceiling sits far -//! above the depth any request validation needs and well under the stack a -//! worker is given (see [`MAX_REQUEST_JSON_DEPTH`]). +//! The recursion limit is therefore disabled, and a byte scan ([`nesting_depth`]) +//! bounds the structural nesting first so a hostile body (a 16 MiB request can +//! nest to millions of levels) cannot overflow the worker stack. The service +//! checks a body's JSON syntax before authentication but refuses an over deep +//! body only after it (measured 2026-11-12, us-east-1: unsigned, a 20000 +//! wrapper PutItem is a `MissingAuthenticationTokenException`; signed, a +//! `SerializationException`). The handler follows that order: it parses a body +//! within [`UNAUTHENTICATED_PARSE_DEPTH`] before authentication and a deeper +//! one only after the caller is authenticated, so no request recurses past +//! `serde_json`'s default depth on an unauthenticated connection. use serde::Deserialize; use serde_json::Value; @@ -26,29 +31,57 @@ use extenddb_core::error::DynamoDbError; /// Largest structural nesting (`{`/`[` openers on one path) the request parser /// accepts; `serde_json`'s own default is 128. /// -/// Amazon DynamoDB parses and validates a request body nested to at least about -/// 2000 document wrappers (roughly 4000 structural levels; measured 2026-11-02, -/// us-east-1), answering it with the nesting `ValidationException`, and only -/// refuses a still deeper body with a serialization error. The ceiling sits -/// above that accepted range: 5200 structural levels is about 2600 single-key -/// wrappers, so every body the service validates is parsed here too. +/// Amazon DynamoDB has no fixed ceiling. A PutItem whose attribute is up to +/// about 1700 single-key wrappers (about 3400 structural levels) gets the +/// nesting `ValidationException` on every send; from about 1800 wrappers the +/// answer varies from request to request between that and a message-less +/// `SerializationException`, with 4000 wrappers also drawing a 500 +/// `InternalFailure`; 5000 wrappers and deeper are refused on every send +/// (measured 2026-11-12, us-east-1, 24 sends per depth across four windows). +/// An unknown top-level member is ignored at any depth (20000 levels is a 200). +/// The ceiling, 5200 structural levels or about 2598 wrappers, sits inside the +/// band where the service itself varies: every depth the service answers +/// consistently is parsed here, and a deeper body gets the message-less +/// refusal the service gives in that band. /// /// A body this deep recurses the same number of levels three times over: the /// `serde_json` parse, the conversion to typed `AttributeValue`s (which has no /// recursion limit of its own), and the recursive drop of both. Measured /// 2026-11-02 (debug): an 8 MiB stack handles about 1500 wrappers and overflows /// past that, while a 32 MiB stack handles a body at this ceiling and well -/// beyond it (a 5500 wrapper body still completes). `extenddb-app`'s -/// `cmd_serve` gives each worker 32 MiB for that reason, over twice the -/// ceiling's need. A body nested past the ceiling is refused by the byte scan -/// below before any recursive work, so the stack is bounded whatever the depth. +/// beyond it (a 5500 wrapper body still completes). The thread that handles an +/// authenticated request therefore needs [`REQUEST_WORKER_STACK_SIZE`] of +/// stack. A body nested past the ceiling is refused by the byte scan before any +/// recursive work, so the stack is bounded whatever the depth. const MAX_REQUEST_JSON_DEPTH: usize = 5200; -/// Whether `body` nests past [`MAX_REQUEST_JSON_DEPTH`], counting `{` and `[` -/// outside string literals and stopping at the first level over the ceiling. -/// The scan never recurses, so it is safe at any depth. -fn exceeds_max_depth(body: &[u8]) -> bool { +/// Deepest structural nesting the handler parses before the caller is +/// authenticated: `serde_json`'s default recursion limit, which the server +/// parsed on a default 2 MiB worker stack before the limit was lifted. A body +/// nested deeper is only scanned until authentication succeeds, so an +/// unauthenticated request can never make the handler recurse past this depth. +pub(crate) const UNAUTHENTICATED_PARSE_DEPTH: usize = 128; + +/// Stack each thread that handles requests needs, in bytes. +/// +/// An authenticated body at [`MAX_REQUEST_JSON_DEPTH`] is parsed, converted to +/// typed attribute values and dropped on the handling thread, each step +/// recursing to the body's depth. In a debug build that takes about 13 MiB of +/// stack (measured 2026-11-02), so 32 MiB is about twice the need. On Tokio's +/// default 2 MiB the parse alone overflows well inside the ceiling (measured +/// 2026-11-12, debug: 700 wrappers abort the process). `extenddb-app`'s +/// `cmd_serve` sizes its runtime's threads with this; any other host of +/// [`crate::serve`] or [`crate::start_server`] must do the same. +pub const REQUEST_WORKER_STACK_SIZE: usize = 32 * 1024 * 1024; + +/// The deepest structural nesting in `body`: `{` and `[` openers on one path, +/// counted outside string literals (an escaped quote does not end a literal). +/// Counting stops one level past [`MAX_REQUEST_JSON_DEPTH`], so the result +/// saturates at `MAX_REQUEST_JSON_DEPTH + 1` for a deeper body. The scan never +/// recurses, so it is safe at any depth. +pub(crate) fn nesting_depth(body: &[u8]) -> usize { let mut depth: usize = 0; + let mut deepest: usize = 0; let mut in_string = false; let mut escaped = false; for &b in body { @@ -67,28 +100,30 @@ fn exceeds_max_depth(body: &[u8]) -> bool { b'{' | b'[' => { depth += 1; if depth > MAX_REQUEST_JSON_DEPTH { - return true; + return depth; } + deepest = deepest.max(depth); } b'}' | b']' => depth = depth.saturating_sub(1), _ => {} } } - false + deepest } -/// Parse a request body into a JSON [`Value`], matching -/// `serde_json::from_slice` for everything within the depth ceiling and -/// refusing a body nested past it. +/// Parse a request body whose [`nesting_depth`] is `depth` into a JSON +/// [`Value`], matching `serde_json::from_slice` for everything within the depth +/// ceiling and refusing a body nested past it. /// /// A malformed or over deep body is a `SerializationException`, the error the /// server has always returned for a body it cannot read. -pub(crate) fn parse_request_value(body: &[u8]) -> Result { - if exceeds_max_depth(body) { - // A body nested past what it will parse gets HTTP 400 with +pub(crate) fn parse_request_value(body: &[u8], depth: usize) -> Result { + if depth > MAX_REQUEST_JSON_DEPTH { + // A signed body nested past what the service parses gets HTTP 400 with // `{"__type":"com.amazon.coral.service#SerializationException"}` and no - // message field at all (measured 2026-11-02, us-east-1). An empty - // message makes `error_response` omit the field, matching that exactly. + // message field at all (measured 2026-11-12, us-east-1: 24 of 24 sends + // at 5000 and at 20000 wrappers). An empty message makes + // `error_response` omit the field. return Err(DynamoDbError::SerializationException(String::new())); } // The depth ceiling above keeps the disabled recursion limit from letting a @@ -112,7 +147,8 @@ mod tests { use super::*; /// A PutItem-shaped body whose `data` attribute is `wrappers` single-key - /// maps around a string leaf: `{"M":{"n": ... {"S":"leaf"} ... }}`. + /// maps around a string leaf: `{"M":{"n": ... {"S":"leaf"} ... }}`. Its + /// structural depth is `3 + 2 * wrappers`. fn deep_body(wrappers: usize) -> Vec { let mut s = String::from(r#"{"TableName":"t","Item":{"data":"#); for _ in 0..wrappers { @@ -126,12 +162,25 @@ mod tests { s.into_bytes() } + fn parse(body: &[u8]) -> Result { + parse_request_value(body, nesting_depth(body)) + } + + /// The message a malformed body carries: the server's wording around the + /// deserializer's own description of the fault. + fn expected_message(body: &[u8]) -> String { + let detail = serde_json::from_slice::(body) + .unwrap_err() + .to_string(); + format!("Start of structure or map found where not expected: {detail}") + } + #[test] fn parses_a_body_nested_past_serde_default() { // 200 wrappers is ~400 structural levels, well past serde_json's 128 // limit and under the ceiling, so it must parse rather than refuse. let body = deep_body(200); - let value = parse_request_value(&body).expect("200 wrappers must parse"); + let value = parse(&body).expect("200 wrappers must parse"); assert!(value.get("Item").is_some()); } @@ -142,7 +191,7 @@ mod tests { // SerializationException with no message, so `error_response` omits the // message field and matches the service's answer for such a body. let body = deep_body(MAX_REQUEST_JSON_DEPTH + 50); - let err = parse_request_value(&body).unwrap_err(); + let err = parse(&body).unwrap_err(); assert!(matches!(err, DynamoDbError::SerializationException(_))); assert!( err.message().is_empty(), @@ -152,22 +201,34 @@ mod tests { } #[test] - fn the_depth_scan_brackets_the_ceiling() { + fn the_depth_scan_brackets_the_ceiling_exactly() { // Scan only (no parse), so this is safe at any depth on the test stack. - assert!( - !exceeds_max_depth(&deep_body(100)), - "100 wrappers is under the ceiling" - ); - assert!( - exceeds_max_depth(&deep_body(MAX_REQUEST_JSON_DEPTH)), - "far past the ceiling" - ); + // Rows: body, the depth the scan must report. The scan saturates one + // past the ceiling for a deeper body. + let rows: [(Vec, usize); 5] = [ + (deep_body(100), 203), + (deep_body(2000), 4003), + (b"[".repeat(MAX_REQUEST_JSON_DEPTH), MAX_REQUEST_JSON_DEPTH), + ( + b"[".repeat(MAX_REQUEST_JSON_DEPTH + 1), + MAX_REQUEST_JSON_DEPTH + 1, + ), + ( + deep_body(MAX_REQUEST_JSON_DEPTH), + MAX_REQUEST_JSON_DEPTH + 1, + ), + ]; + for (body, depth) in &rows { + assert_eq!(nesting_depth(body), *depth, "{} bytes", body.len()); + } + assert!(nesting_depth(&rows[2].0) <= MAX_REQUEST_JSON_DEPTH); + assert!(nesting_depth(&rows[3].0) > MAX_REQUEST_JSON_DEPTH); } #[test] fn matches_serde_for_a_shallow_body() { let body = br#"{"TableName":"t","Item":{"pk":{"S":"a"}}}"#; - let value = parse_request_value(body).expect("shallow body must parse"); + let value = parse(body).expect("shallow body must parse"); assert_eq!(value["TableName"], "t"); } @@ -175,7 +236,7 @@ mod tests { fn braces_inside_a_string_do_not_count_as_nesting() { let inner = "{".repeat(MAX_REQUEST_JSON_DEPTH + 100); let body = format!(r#"{{"TableName":"{inner}"}}"#).into_bytes(); - let value = parse_request_value(&body).expect("braces in a string are not nesting"); + let value = parse(&body).expect("braces in a string are not nesting"); assert!(value.get("TableName").is_some()); } @@ -184,52 +245,74 @@ mod tests { // The escaped quote keeps the scan inside the string, so the braces that // follow it are string content and are not counted. let body = br#"{"k":"a\"{{{{{","x":1}"#; - let value = parse_request_value(body).expect("must parse"); + let value = parse(body).expect("must parse"); assert_eq!(value["x"], 1); + // Read the other way (the escaped quote taken as the end of the + // string), every later quote flips the scan's notion of being inside a + // string, and the over-ceiling attribute that follows is miscounted as + // string content. The scan must count it and refuse the body; a + // disabled-limit parse of it would overflow the handling thread. + let openers = "[".repeat(MAX_REQUEST_JSON_DEPTH + 1); + let closers = "]".repeat(MAX_REQUEST_JSON_DEPTH + 1); + let body = format!(r#"{{"k":"a\"b","x":{openers}{closers}}}"#).into_bytes(); + assert!( + nesting_depth(&body) > MAX_REQUEST_JSON_DEPTH, + "the over-ceiling attribute behind an escaped quote must be counted" + ); + assert!(parse(&body).unwrap_err().message().is_empty()); } #[test] - fn a_malformed_body_is_a_serialization_error() { - let err = parse_request_value(b"{not json").unwrap_err(); - assert!(matches!(err, DynamoDbError::SerializationException(_))); + fn many_shallow_siblings_are_not_nesting() { + // 3000 single-map attributes at depth 5 open more braces in total than + // the ceiling; the scan must count depth, not openers, and the body + // must parse. The service stores such an item (measured 2026-11-12). + let mut s = String::from(r#"{"TableName":"t","Item":{"pk":{"S":"k"}"#); + for i in 0..3000 { + s.push_str(&format!(r#","a{i}":{{"M":{{"x":{{"S":"v"}}}}}}"#)); + } + s.push_str("}}"); + let body = s.into_bytes(); + assert_eq!(nesting_depth(&body), 5); + let value = parse(&body).expect("3000 shallow siblings must parse"); + assert_eq!( + value["Item"].as_object().map(serde_json::Map::len), + Some(3001) + ); } #[test] - fn trailing_bytes_are_rejected_like_from_slice() { - let err = parse_request_value(br#"{"a":1} tail"#).unwrap_err(); - assert!(matches!(err, DynamoDbError::SerializationException(_))); + fn a_malformed_body_is_a_serialization_error_with_the_usual_message() { + // Rows: the malformed body. Each gets the server's long standing + // wording around the deserializer's own description, so a change to + // `serialization_error`'s format fails here. + for body in [&b"{not json"[..], br#"{"a":1} tail"#] { + let err = parse(body).unwrap_err(); + assert!(matches!(err, DynamoDbError::SerializationException(_))); + assert_eq!(err.message(), expected_message(body), "{body:?}"); + } } #[test] - fn the_ceiling_admits_the_required_depth() { - // The byte scan admits the depth the service validates (2000 wrappers, - // ~4003 structural) and the deepest the ceiling allows (~2598), and - // refuses one wrapper more. The scan never recurses, so this is safe at - // any depth on the test stack. - assert!( - !exceeds_max_depth(&deep_body(2000)), - "2000 wrappers must be admitted" - ); - assert!( - !exceeds_max_depth(&deep_body(2598)), - "the ceiling admits about 2598 wrappers" - ); - assert!( - exceeds_max_depth(&deep_body(2599)), - "one wrapper past the ceiling is refused" - ); + fn the_unauthenticated_depth_is_serde_json_default() { + // The handler parses a body within this depth before authentication, as + // the server did with the deserializer's default limit on a default + // stack; a deeper one waits for authentication. + assert_eq!(UNAUTHENTICATED_PARSE_DEPTH, 128); + assert!(nesting_depth(&deep_body(62)) <= UNAUTHENTICATED_PARSE_DEPTH); + assert!(nesting_depth(&deep_body(63)) > UNAUTHENTICATED_PARSE_DEPTH); } #[test] fn parses_the_required_depth_on_a_worker_sized_stack() { // 2000 wrappers (~4003 structural) is within the ceiling and must parse // into a Value. Parsing this deep recurses past the default test-thread - // stack, so run it on a stack the size `cmd_serve` gives each worker. + // stack, so run it on the stack a request handling thread must have. let body = deep_body(2000); std::thread::Builder::new() - .stack_size(32 * 1024 * 1024) + .stack_size(REQUEST_WORKER_STACK_SIZE) .spawn(move || { - let value = parse_request_value(&body).expect("2000 wrappers must parse"); + let value = parse(&body).expect("2000 wrappers must parse"); assert!(value.get("Item").is_some()); }) .unwrap() diff --git a/crates/server/src/serve.rs b/crates/server/src/serve.rs index c94e10220..1f316023d 100644 --- a/crates/server/src/serve.rs +++ b/crates/server/src/serve.rs @@ -271,6 +271,9 @@ fn check_request_timeout_secs(secs: u64) -> Result<(), String> { /// after it stopped, the PID file is removed and a fatal message is written /// to the configured [`LogTarget`]. /// +/// The runtime this runs on must give its threads at least +/// [`crate::REQUEST_WORKER_STACK_SIZE`] of stack; see [`crate::start_server`]. +/// /// # Errors /// /// Returns an error if logging init, backend component creation, cache From a3a991bc516c63d25ca124b7c98a15808bfe2d26 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:00:50 +0000 Subject: [PATCH 03/15] test(nesting): accept the service's varying answer past 1700 wrappers The dual-target test pinned a 2000 wrapper PutItem to the nesting ValidationException. The service has no fixed ceiling there: measured 2026-11-12 in us-east-1 with 24 sends per depth across four windows, 300 to 1700 wrappers got the ValidationException on every send, 1800 to 2598 wrappers got it on 22 or 23 of 24 sends and the message-less SerializationException on the rest, 3000 wrappers split 19 to 5, and 5000 and 20000 wrappers were refused on every send. The always-validated cases are now 300, 1000 and 1500 wrappers, the 2000 and 2598 wrapper cases accept either of the two answers, and the far past the ceiling case stays at 20000. The recursion limit botocore needs to serialize the two boto3 built items is set by a fixture for those two cases and restored afterwards instead of for the whole session. Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> --- tests/test_request_nesting_depth.py | 77 +++++++++++++++++++++-------- 1 file changed, 56 insertions(+), 21 deletions(-) diff --git a/tests/test_request_nesting_depth.py b/tests/test_request_nesting_depth.py index 75cdc21ab..12e1f4244 100644 --- a/tests/test_request_nesting_depth.py +++ b/tests/test_request_nesting_depth.py @@ -8,9 +8,12 @@ with a SerializationException, so a request whose attribute nested past that never reached the nesting-depth check. Amazon DynamoDB parses such a request and answers with the document nesting "Nesting Levels have exceeded supported -limits..." ValidationException, and only a body nested past about 2000 wrappers -(roughly 4000 JSON levels) is refused, then with a message-less -SerializationException. Measured against the service (us-east-1, 2026-11-02). +limits..." ValidationException. It has no fixed ceiling: a PutItem attribute of +up to about 1700 single-key wrappers (about 3400 JSON levels) got that +ValidationException on every send, from about 1800 wrappers the answer varied +from request to request between it and a message-less SerializationException, +and 5000 wrappers and deeper got the SerializationException on every send +(us-east-1, 2026-11-12, 24 sends per depth across four windows). Dual-target: runs against the service and against ExtendDB on every backend. @@ -31,10 +34,6 @@ from conftest import scoped_table from raw_signed_request import signed_post -# botocore serializes a nested dict recursively, so lift CPython's own limit for -# the boto3 cases below (the raw-JSON cases do not recurse and do not need it). -sys.setrecursionlimit(10_000) - NEST = "Nesting Levels have exceeded supported limits" NEST_FULL = ( "Nesting Levels have exceeded supported limits: " @@ -49,6 +48,16 @@ def table(dynamodb_client): yield name +@pytest.fixture +def deep_recursion(): + """botocore serializes a nested dict recursively; lift CPython's limit for a + case that builds a deep Item through boto3, and restore it afterwards.""" + previous = sys.getrecursionlimit() + sys.setrecursionlimit(10_000) + yield + sys.setrecursionlimit(previous) + + def _deep(wrappers: int) -> dict: """`wrappers` single-key maps around a string leaf: depth 1 is `{"M":{"n":{"S":"leaf"}}}`.""" @@ -93,6 +102,14 @@ def _raw_put(dynamodb_client, table_name: str, pk: str, wrappers: int): ) +def _is_nesting_validation_error(err: dict) -> bool: + return err["__type"].endswith("ValidationException") and err["message"] == NEST_FULL + + +def _is_messageless_serialization_error(err: dict) -> bool: + return err["__type"] == SERIALIZATION_TYPE and "message" not in err + + def test_an_attribute_within_the_limit_is_stored(dynamodb_client, table): # Positive control: 31 wrappers (leaf at level 32) is within the document # limit and is stored, so the parse change did not break the accept path. @@ -101,7 +118,9 @@ def test_an_attribute_within_the_limit_is_stored(dynamodb_client, table): ) -def test_a_63_level_attribute_is_a_nesting_validation_error(dynamodb_client, table): +def test_a_63_level_attribute_is_a_nesting_validation_error( + dynamodb_client, table, deep_recursion +): # 63 wrappers nests the request just past the 128 structural level parse # limit. The server must read it and answer with the nesting # ValidationException, not a SerializationException. @@ -110,7 +129,9 @@ def test_a_63_level_attribute_is_a_nesting_validation_error(dynamodb_client, tab assert err["Message"] == NEST_FULL, err -def test_an_attribute_far_past_the_parse_limit_still_validates(dynamodb_client, table): +def test_an_attribute_far_past_the_parse_limit_still_validates( + dynamodb_client, table, deep_recursion +): # Well past the old parse limit and within the request depth ceiling: still # a nesting ValidationException, never a parse failure. err = _put_error(dynamodb_client, table, _deep(120)) @@ -118,27 +139,41 @@ def test_an_attribute_far_past_the_parse_limit_still_validates(dynamodb_client, assert NEST in err["Message"], err -@pytest.mark.parametrize("wrappers", [300, 1000, 2000]) -def test_a_deep_body_within_the_ceiling_is_a_nesting_validation_error( +@pytest.mark.parametrize("wrappers", [300, 1000, 1500]) +def test_a_deep_body_the_service_always_validates_is_a_nesting_error( + dynamodb_client, table, wrappers +): + # Up to 1500 wrappers the service answered the document nesting + # ValidationException on every send (24 of 24 per depth). Built as raw JSON + # so the client does not recurse. + resp = _raw_put(dynamodb_client, table, f"deep{wrappers}", wrappers) + assert resp.status_code == 400, resp.text + assert _is_nesting_validation_error(resp.json()), resp.text + + +@pytest.mark.parametrize("wrappers", [2000, 2598]) +def test_a_body_in_the_varying_band_gets_one_of_the_two_answers( dynamodb_client, table, wrappers ): - # The service parses a body nested far past the old 128 level parse limit, - # up to at least 2000 wrappers, and answers with the document nesting - # ValidationException. Built as raw JSON so the client does not recurse. + # From about 1800 wrappers the service's answer varies per request: the + # nesting ValidationException or the message-less SerializationException + # (2000 wrappers: 23 and 1 of 24 in one set of windows, the other way round + # in others). 2598 wrappers is the deepest body the server's ceiling + # admits; it parses it and answers the ValidationException. resp = _raw_put(dynamodb_client, table, f"deep{wrappers}", wrappers) assert resp.status_code == 400, resp.text err = resp.json() - assert err["__type"].endswith("ValidationException"), err - assert err["message"] == NEST_FULL, err + assert _is_nesting_validation_error(err) or _is_messageless_serialization_error( + err + ), err def test_a_body_far_past_the_ceiling_is_a_messageless_serialization_error( dynamodb_client, table ): - # Far past any depth the service parses. It answers HTTP 400 with the - # SerializationException type and no message field at all. + # Far past any depth the service parses (5000 wrappers and deeper were + # refused on every send). It answers HTTP 400 with the SerializationException + # type and no message field at all. resp = _raw_put(dynamodb_client, table, "huge", 20_000) assert resp.status_code == 400, resp.text - err = resp.json() - assert err["__type"] == SERIALIZATION_TYPE, err - assert "message" not in err, err + assert _is_messageless_serialization_error(resp.json()), resp.text From e2e58e398c0289003acae5640340a40ed57f946f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:32:39 +0000 Subject: [PATCH 04/15] test(nesting): retry a 500 in the raw sender and align the depth figures The raw PutItem sender sent once and the two raw tests asserted a 400. The service answers a deep body with 500 InternalFailure now and then. Measured 2026-11-13 in us-east-1: 1500 wrappers 2 of 56 sends, 2000 wrappers 1 of 37, 2598 wrappers 2 of 48. The client library retries a 500 by default, so only the raw cases could fail on one. The sender now sends up to three times while the answer is a 500, with a pause of one and then two seconds. The assertions are unchanged. The depth the service validates on every send is 1500 wrappers, not 1700. Across 2026-11-12 and 2026-11-13, 1700 wrappers drew the message-less SerializationException on 3 of 74 sends. 1500 wrappers drew it on 0 of 104. The module docs and the test comments now give 1500, and the raw cases at 300, 1000 and 1500 wrappers are unchanged. UNAUTHENTICATED_PARSE_DEPTH is 127. serde_json's default recursion limit of 128 parses 127 nested levels and refuses the 128th. At 128 the constant admitted one level more than the server parsed before the limit was lifted. The unit test now parses with serde_json's default limit at the constant and one level past it, instead of restating the number. The malformed-body unit test no longer pins the refusal of trailing bytes, which the service accepts. A signed PutItem with bytes after the closing brace was a 200 on 4 of 4 sends (measured 2026-11-13). The row is a truncated body instead. Typo fix in the cmd_serve stack comment: "the stack that needs" is now "the stack it needs". Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> --- crates/app/src/cmd_serve.rs | 2 +- crates/server/src/request_parse.rs | 43 +++++++++++------ tests/test_request_nesting_depth.py | 74 ++++++++++++++++++----------- 3 files changed, 75 insertions(+), 44 deletions(-) diff --git a/crates/app/src/cmd_serve.rs b/crates/app/src/cmd_serve.rs index 069da1872..05cdeae37 100755 --- a/crates/app/src/cmd_serve.rs +++ b/crates/app/src/cmd_serve.rs @@ -293,7 +293,7 @@ pub fn run(args: &ServeArgs, build: BuildInfo) -> anyhow::Result<()> { // An authenticated request body nested to the parser's ceiling is // parsed, converted to typed AttributeValues and dropped on a worker // thread, each step recursing to the body's depth; the server crate - // that sets the ceiling sizes the stack that needs (about twice the + // that sets the ceiling sizes the stack it needs (about twice the // measured need, far above Tokio's 2 MiB default). .thread_stack_size(extenddb_server::REQUEST_WORKER_STACK_SIZE) .build()?; diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index 32607db89..677e56f63 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -3,8 +3,9 @@ //! Request body JSON parsing with a bounded nesting depth. //! -//! `serde_json`'s deserializer refuses any document nested past 128 levels with -//! a recursion error, which the server turned into a `SerializationException`. +//! `serde_json`'s deserializer refuses any document nested 128 levels deep or +//! deeper with a recursion error, which the server turned into a +//! `SerializationException`. //! Amazon DynamoDB instead parses requests nested far past that and answers //! with the validation that applies (the 32 level document limit, or whichever //! check runs first), so the parser has to reach those checks rather than @@ -32,12 +33,13 @@ use extenddb_core::error::DynamoDbError; /// accepts; `serde_json`'s own default is 128. /// /// Amazon DynamoDB has no fixed ceiling. A PutItem whose attribute is up to -/// about 1700 single-key wrappers (about 3400 structural levels) gets the -/// nesting `ValidationException` on every send; from about 1800 wrappers the +/// 1500 single-key wrappers (about 3000 structural levels) gets the nesting +/// `ValidationException` on every send that is a 400; from 1700 wrappers the /// answer varies from request to request between that and a message-less -/// `SerializationException`, with 4000 wrappers also drawing a 500 -/// `InternalFailure`; 5000 wrappers and deeper are refused on every send -/// (measured 2026-11-12, us-east-1, 24 sends per depth across four windows). +/// `SerializationException`; 5000 wrappers and deeper are refused on every +/// send. At 1500 wrappers and deeper a few sends are a 500 `InternalFailure` +/// instead (measured 2026-11-12 and 2026-11-13, us-east-1, 24 or more sends +/// per depth across several windows). /// An unknown top-level member is ignored at any depth (20000 levels is a 200). /// The ceiling, 5200 structural levels or about 2598 wrappers, sits inside the /// band where the service itself varies: every depth the service answers @@ -56,11 +58,12 @@ use extenddb_core::error::DynamoDbError; const MAX_REQUEST_JSON_DEPTH: usize = 5200; /// Deepest structural nesting the handler parses before the caller is -/// authenticated: `serde_json`'s default recursion limit, which the server -/// parsed on a default 2 MiB worker stack before the limit was lifted. A body -/// nested deeper is only scanned until authentication succeeds, so an -/// unauthenticated request can never make the handler recurse past this depth. -pub(crate) const UNAUTHENTICATED_PARSE_DEPTH: usize = 128; +/// authenticated: the 127 levels `serde_json`'s default recursion limit of 128 +/// accepts (it refuses the 128th), which the server parsed on a default 2 MiB +/// worker stack before the limit was lifted. A body nested deeper is only +/// scanned until authentication succeeds, so an unauthenticated request can +/// never make the handler recurse past this depth. +pub(crate) const UNAUTHENTICATED_PARSE_DEPTH: usize = 127; /// Stack each thread that handles requests needs, in bytes. /// @@ -286,7 +289,7 @@ mod tests { // Rows: the malformed body. Each gets the server's long standing // wording around the deserializer's own description, so a change to // `serialization_error`'s format fails here. - for body in [&b"{not json"[..], br#"{"a":1} tail"#] { + for body in [&b"{not json"[..], br#"{"a":1"#] { let err = parse(body).unwrap_err(); assert!(matches!(err, DynamoDbError::SerializationException(_))); assert_eq!(err.message(), expected_message(body), "{body:?}"); @@ -297,8 +300,18 @@ mod tests { fn the_unauthenticated_depth_is_serde_json_default() { // The handler parses a body within this depth before authentication, as // the server did with the deserializer's default limit on a default - // stack; a deeper one waits for authentication. - assert_eq!(UNAUTHENTICATED_PARSE_DEPTH, 128); + // stack; a deeper one waits for authentication. Checked against + // serde_json itself: with its default limit, a body at this depth + // parses and a body one level deeper is the recursion error. + let nested = |levels: usize| [b"[".repeat(levels), b"]".repeat(levels)].concat(); + serde_json::from_slice::(&nested(UNAUTHENTICATED_PARSE_DEPTH)) + .expect("serde_json's default limit must parse a body at the depth"); + let err = + serde_json::from_slice::(&nested(UNAUTHENTICATED_PARSE_DEPTH + 1)).unwrap_err(); + assert!( + err.to_string().contains("recursion limit exceeded"), + "{err}" + ); assert!(nesting_depth(&deep_body(62)) <= UNAUTHENTICATED_PARSE_DEPTH); assert!(nesting_depth(&deep_body(63)) > UNAUTHENTICATED_PARSE_DEPTH); } diff --git a/tests/test_request_nesting_depth.py b/tests/test_request_nesting_depth.py index 12e1f4244..46f9ce3aa 100644 --- a/tests/test_request_nesting_depth.py +++ b/tests/test_request_nesting_depth.py @@ -4,16 +4,18 @@ """A deeply nested request body is parsed and answered by the depth that applies, not refused by the JSON parser. -The JSON deserializer used to refuse any body nested past 128 structural levels -with a SerializationException, so a request whose attribute nested past that -never reached the nesting-depth check. Amazon DynamoDB parses such a request and -answers with the document nesting "Nesting Levels have exceeded supported -limits..." ValidationException. It has no fixed ceiling: a PutItem attribute of -up to about 1700 single-key wrappers (about 3400 JSON levels) got that -ValidationException on every send, from about 1800 wrappers the answer varied -from request to request between it and a message-less SerializationException, -and 5000 wrappers and deeper got the SerializationException on every send -(us-east-1, 2026-11-12, 24 sends per depth across four windows). +The JSON deserializer used to refuse any body nested 128 or more structural +levels deep with a SerializationException, so a request whose attribute nested +past that never reached the nesting-depth check. Amazon DynamoDB parses such a +request and answers with the document nesting "Nesting Levels have exceeded +supported limits..." ValidationException. It has no fixed ceiling: a PutItem +attribute of up to 1500 single-key wrappers (about 3000 JSON levels) got that +ValidationException on every send that was a 400, from 1700 wrappers the answer +varied from request to request between it and a message-less +SerializationException, and 5000 wrappers and deeper got the +SerializationException on every send. A few sends at 1500 wrappers and deeper +were a 500 InternalFailure instead (us-east-1, 2026-11-12 and 2026-11-13, 24 or +more sends per depth across several windows). Dual-target: runs against the service and against ExtendDB on every backend. @@ -26,6 +28,7 @@ import json import sys +import time import boto3 import pytest @@ -89,17 +92,30 @@ def _raw_put_body(table_name: str, pk: str, wrappers: int) -> bytes: def _raw_put(dynamodb_client, table_name: str, pk: str, wrappers: int): - """Sign and POST a raw deep PutItem body with the caller's own credentials.""" + """Sign and POST a raw deep PutItem body with the caller's own credentials. + + Sent up to three times while the answer is a 500. The service gives a deep + body a 500 InternalFailure now and then (1500 wrappers: 2 of 56 sends; 2000: + 1 of 37; 2598: 2 of 48; us-east-1, 2026-11-13), and the client library + retries a 500 by default, so the boto3 cases in this file never see one. + """ frozen = boto3.Session().get_credentials().get_frozen_credentials() - return signed_post( - dynamodb_client.meta.endpoint_url, - frozen.access_key, - frozen.secret_key, - dynamodb_client.meta.region_name, - "PutItem", - _raw_put_body(table_name, pk, wrappers), - session_token=frozen.token, - ) + body = _raw_put_body(table_name, pk, wrappers) + for attempt in range(3): + if attempt: + time.sleep(attempt) + resp = signed_post( + dynamodb_client.meta.endpoint_url, + frozen.access_key, + frozen.secret_key, + dynamodb_client.meta.region_name, + "PutItem", + body, + session_token=frozen.token, + ) + if resp.status_code != 500: + break + return resp def _is_nesting_validation_error(err: dict) -> bool: @@ -143,9 +159,11 @@ def test_an_attribute_far_past_the_parse_limit_still_validates( def test_a_deep_body_the_service_always_validates_is_a_nesting_error( dynamodb_client, table, wrappers ): - # Up to 1500 wrappers the service answered the document nesting - # ValidationException on every send (24 of 24 per depth). Built as raw JSON - # so the client does not recurse. + # Up to 1500 wrappers the service's 400 was the document nesting + # ValidationException on every send (1500 wrappers: 102 of 104 sends across + # 2026-11-12 and 2026-11-13, the other 2 a 500 that _raw_put retries); from + # 1700 wrappers the answer varies. Built as raw JSON so the client does not + # recurse. resp = _raw_put(dynamodb_client, table, f"deep{wrappers}", wrappers) assert resp.status_code == 400, resp.text assert _is_nesting_validation_error(resp.json()), resp.text @@ -155,11 +173,11 @@ def test_a_deep_body_the_service_always_validates_is_a_nesting_error( def test_a_body_in_the_varying_band_gets_one_of_the_two_answers( dynamodb_client, table, wrappers ): - # From about 1800 wrappers the service's answer varies per request: the - # nesting ValidationException or the message-less SerializationException - # (2000 wrappers: 23 and 1 of 24 in one set of windows, the other way round - # in others). 2598 wrappers is the deepest body the server's ceiling - # admits; it parses it and answers the ValidationException. + # From 1700 wrappers the service's answer varies per request: the nesting + # ValidationException or the message-less SerializationException (2000 + # wrappers: 23 and 1 of 24 in one set of windows, 17 and 14 of 32 in + # another). 2598 wrappers is the deepest body the server's ceiling admits; + # it parses it and answers the ValidationException. resp = _raw_put(dynamodb_client, table, f"deep{wrappers}", wrappers) assert resp.status_code == 400, resp.text err = resp.json() From 99542cb9eccea94d85b0c7d00383c9914a80e563 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:17:06 +0000 Subject: [PATCH 05/15] fix(server): check a deep body's syntax before authentication The handler parses a body nested deeper than 127 levels only after authentication, so a malformed body that deep got the authentication error. The service checks the syntax of every body before authentication. Unsigned or badly signed, the byte `x` followed by 6000 `[` is a 400 SerializationException with no message field on every send. A PutItem body of 63, 200, 2000, 5000 or 20000 wrappers without its last byte gets the same answer. The complete bodies are MissingAuthenticationTokenException unsigned and InvalidSignatureException badly signed (us-east-1, 2026-11-19 and 2026-11-20, 2 sends per shape and signing). `check_request_syntax` runs before authentication for a body deeper than 127 levels. It deserializes the body as `serde::de::IgnoredAny`. serde_json skips such a value in one loop. The loop keeps the kinds of the open containers in a Vec, so the check does not recurse at any depth. The check reads one JSON value, as the service's check does. Bytes after a complete body pass it, and so do an invalid UTF-8 byte and a lone surrogate escape in a string. A body that fails the check gets the SerializationException that the parse after authentication gives. Past the 5200 level ceiling it has no message, and within the ceiling it has the server's usual wording. Two unit tests cover the check on a worker-sized stack and on the default test stack, with a body of 1,000,000 levels. The wire file gains two dual-target cases. A malformed deep body is a SerializationException unsigned and badly signed. A complete deep body, with or without trailing bytes, reaches authentication. The security model manual states the order. --- crates/server/src/handler.rs | 18 +-- crates/server/src/request_parse.rs | 169 ++++++++++++++++++++++++---- docs/manuals/10-security-model.md | 2 +- tests/test_request_nesting_depth.py | 105 +++++++++++++++++ 4 files changed, 267 insertions(+), 27 deletions(-) diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index b33031513..0639401a3 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -94,19 +94,23 @@ pub(crate) async fn handle_request( } // --- Pre-auth body validation --- - // The service checks the request's JSON syntax before authentication but - // refuses an over deep body only after it (measured 2026-11-12: unsigned, - // a 20000 wrapper PutItem is MissingAuthenticationTokenException; signed, - // SerializationException). A body within serde_json's default depth is - // parsed here, as it always was; a deeper one is only scanned until the - // caller is authenticated, so no unauthenticated request makes this - // thread recurse past that depth (see request_parse). + // The service checks the request's JSON syntax before authentication at + // every depth but refuses an over deep body only after it (measured + // 2026-11-19: unsigned, a 20000 wrapper PutItem is + // MissingAuthenticationTokenException, and the same body without its last + // byte SerializationException). A body within serde_json's default depth + // is parsed here, as it always was. A deeper one only has its syntax + // checked, by a walk that does not recurse, until the caller is + // authenticated, so no unauthenticated request makes this thread recurse + // past that depth (see request_parse). let depth = crate::request_parse::nesting_depth(&body); let pre_auth_input = if depth <= crate::request_parse::UNAUTHENTICATED_PARSE_DEPTH { match crate::request_parse::parse_request_value(&body, depth) { Ok(v) => Some(v), Err(e) => return error_response(&e, &request_id), } + } else if let Err(e) = crate::request_parse::check_request_syntax(&body, depth) { + return error_response(&e, &request_id); } else { None }; diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index 677e56f63..fb878ce58 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -16,15 +16,18 @@ //! The recursion limit is therefore disabled, and a byte scan ([`nesting_depth`]) //! bounds the structural nesting first so a hostile body (a 16 MiB request can //! nest to millions of levels) cannot overflow the worker stack. The service -//! checks a body's JSON syntax before authentication but refuses an over deep -//! body only after it (measured 2026-11-12, us-east-1: unsigned, a 20000 -//! wrapper PutItem is a `MissingAuthenticationTokenException`; signed, a -//! `SerializationException`). The handler follows that order: it parses a body -//! within [`UNAUTHENTICATED_PARSE_DEPTH`] before authentication and a deeper -//! one only after the caller is authenticated, so no request recurses past -//! `serde_json`'s default depth on an unauthenticated connection. +//! checks a body's JSON syntax before authentication at every depth but refuses +//! an over deep body only after it (measured 2026-11-19, us-east-1: unsigned, a +//! 20000 wrapper PutItem is a `MissingAuthenticationTokenException`, and the +//! same body without its last byte a `SerializationException`). The handler +//! follows that order. It parses a body within [`UNAUTHENTICATED_PARSE_DEPTH`] +//! before authentication. For a deeper body it runs only +//! [`check_request_syntax`], which does not recurse, and parses the body after +//! the caller is authenticated, so no request recurses past `serde_json`'s +//! default depth on an unauthenticated connection. use serde::Deserialize; +use serde::de::IgnoredAny; use serde_json::Value; use extenddb_core::error::DynamoDbError; @@ -60,9 +63,9 @@ const MAX_REQUEST_JSON_DEPTH: usize = 5200; /// Deepest structural nesting the handler parses before the caller is /// authenticated: the 127 levels `serde_json`'s default recursion limit of 128 /// accepts (it refuses the 128th), which the server parsed on a default 2 MiB -/// worker stack before the limit was lifted. A body nested deeper is only -/// scanned until authentication succeeds, so an unauthenticated request can -/// never make the handler recurse past this depth. +/// worker stack before the limit was lifted. A deeper body only goes through +/// [`check_request_syntax`] until authentication succeeds, so an +/// unauthenticated request can never make the handler recurse past this depth. pub(crate) const UNAUTHENTICATED_PARSE_DEPTH: usize = 127; /// Stack each thread that handles requests needs, in bytes. @@ -122,12 +125,7 @@ pub(crate) fn nesting_depth(body: &[u8]) -> usize { /// server has always returned for a body it cannot read. pub(crate) fn parse_request_value(body: &[u8], depth: usize) -> Result { if depth > MAX_REQUEST_JSON_DEPTH { - // A signed body nested past what the service parses gets HTTP 400 with - // `{"__type":"com.amazon.coral.service#SerializationException"}` and no - // message field at all (measured 2026-11-12, us-east-1: 24 of 24 sends - // at 5000 and at 20000 wrappers). An empty message makes - // `error_response` omit the field. - return Err(DynamoDbError::SerializationException(String::new())); + return Err(over_ceiling_refusal()); } // The depth ceiling above keeps the disabled recursion limit from letting a // deep body overflow the stack. @@ -138,6 +136,39 @@ pub(crate) fn parse_request_value(body: &[u8], depth: usize) -> Result Result<(), DynamoDbError> { + let mut de = serde_json::Deserializer::from_slice(body); + match IgnoredAny::deserialize(&mut de) { + Ok(IgnoredAny) => Ok(()), + Err(_) if depth > MAX_REQUEST_JSON_DEPTH => Err(over_ceiling_refusal()), + Err(e) => Err(serialization_error(&e.to_string())), + } +} + +/// The refusal for a body nested past [`MAX_REQUEST_JSON_DEPTH`]. A signed body +/// nested past what the service parses gets HTTP 400 with +/// `{"__type":"com.amazon.coral.service#SerializationException"}` and no +/// message field at all (measured 2026-11-12, us-east-1: 24 of 24 sends at 5000 +/// and at 20000 wrappers). An empty message makes `error_response` omit the +/// field. +fn over_ceiling_refusal() -> DynamoDbError { + DynamoDbError::SerializationException(String::new()) +} + /// The server's long standing wording for a request body it cannot read. fn serialization_error(detail: &str) -> DynamoDbError { DynamoDbError::SerializationException(format!( @@ -300,9 +331,9 @@ mod tests { fn the_unauthenticated_depth_is_serde_json_default() { // The handler parses a body within this depth before authentication, as // the server did with the deserializer's default limit on a default - // stack; a deeper one waits for authentication. Checked against - // serde_json itself: with its default limit, a body at this depth - // parses and a body one level deeper is the recursion error. + // stack; a deeper one only has its syntax checked until authentication. + // Checked against serde_json itself: with its default limit, a body at + // this depth parses and a body one level deeper is the recursion error. let nested = |levels: usize| [b"[".repeat(levels), b"]".repeat(levels)].concat(); serde_json::from_slice::(&nested(UNAUTHENTICATED_PARSE_DEPTH)) .expect("serde_json's default limit must parse a body at the depth"); @@ -332,4 +363,104 @@ mod tests { .join() .unwrap(); } + + /// `deep_body(wrappers)` without its last byte. + fn truncated_body(wrappers: usize) -> Vec { + let mut body = deep_body(wrappers); + body.pop(); + body + } + + /// `deep_body(wrappers)` with its last `}` written as `]`. + fn wrong_closer_body(wrappers: usize) -> Vec { + let mut body = deep_body(wrappers); + *body.last_mut().unwrap() = b']'; + body + } + + #[test] + fn the_syntax_check_refuses_a_malformed_deep_body_as_the_parse_does() { + // Rows: a body nested past the pre-auth depth with a syntax fault. The + // service refuses each before authentication with a + // SerializationException (measured 2026-11-19, us-east-1, unsigned + // and badly signed). The check must give the refusal that the parse + // after authentication gives the same body. The parse recurses, so the + // rows run on a worker-sized stack. + let rows = [ + [&b"x"[..], &b"[".repeat(6000)].concat(), + [&b"x"[..], &b"[".repeat(200)].concat(), + truncated_body(63), + truncated_body(200), + truncated_body(2000), + truncated_body(20000), + wrong_closer_body(200), + ]; + std::thread::Builder::new() + .stack_size(REQUEST_WORKER_STACK_SIZE) + .spawn(move || { + for body in &rows { + let depth = nesting_depth(body); + assert!(depth > UNAUTHENTICATED_PARSE_DEPTH, "{} bytes", body.len()); + let checked = check_request_syntax(body, depth).unwrap_err(); + let parsed = parse_request_value(body, depth).unwrap_err(); + assert!(matches!(checked, DynamoDbError::SerializationException(_))); + assert_eq!(checked.message(), parsed.message(), "{} bytes", body.len()); + } + }) + .unwrap() + .join() + .unwrap(); + // Past the ceiling the refusal carries no message, which the service + // also gives these bodies; within it, the server's usual wording. + let past = [&b"x"[..], &b"[".repeat(6000)].concat(); + assert!( + check_request_syntax(&past, nesting_depth(&past)) + .unwrap_err() + .message() + .is_empty() + ); + let within = truncated_body(200); + assert_eq!( + check_request_syntax(&within, nesting_depth(&within)) + .unwrap_err() + .message(), + format!( + "Start of structure or map found where not expected: \ + EOF while parsing an object at line 1 column {}", + within.len() + ) + ); + } + + #[test] + fn the_syntax_check_passes_what_the_service_authenticates_first() { + // Rows: bodies the service's check before authentication passes + // (measured 2026-11-19, us-east-1: unsigned, each is a + // MissingAuthenticationTokenException). Complete bodies far past the + // ceiling, bytes after a complete body, an invalid UTF-8 byte in a + // string and a lone surrogate escape. This runs on the default + // test-thread stack, where a parse that recursed a million levels + // would overflow, so it also shows that the check does not recurse. + let leaf = |with: &[u8]| { + let body = deep_body(200); + let at = body.windows(6).position(|w| w == b"\"leaf\"").unwrap(); + [&body[..at], with, &body[at + 6..]].concat() + }; + let rows = [ + [b"[".repeat(1_000_000), b"]".repeat(1_000_000)].concat(), + deep_body(20000), + [deep_body(2000), b"x".to_vec()].concat(), + leaf(b"\"le\xffaf\""), + leaf(br#""le\ud800af""#), + ]; + for body in &rows { + let depth = nesting_depth(body); + assert!(depth > UNAUTHENTICATED_PARSE_DEPTH, "{} bytes", body.len()); + assert!( + check_request_syntax(body, depth).is_ok(), + "{} bytes", + body.len() + ); + } + } } diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 1b7630ba0..2e847a8e4 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -48,7 +48,7 @@ The steps run in this order; every rejection is HTTP 400. 8. Derive the signing key (HMAC-SHA256 chain over date, region, service, "aws4_request") and compare the computed signature with the provided one in constant time; mismatch: `InvalidSignatureException` 9. Apply the deferred decisions from steps 3 and 6, after the signature check so that failure paths take the same time: an inactive key or a wrong or missing token is `UnrecognizedClientException` -Request bodies are parsed before authentication (the service does the same), so a malformed body returns `SerializationException` whatever the signature. Headers not named in `SignedHeaders` do not take part in verification; the service behaves the same way, and clients sign every `x-amz-*` header they send. +A request body's JSON syntax is checked before authentication at every nesting depth (the service does the same), so a malformed body returns `SerializationException` whatever the signature. A body nested deeper than 127 levels is parsed only after the caller is authenticated, so an unauthenticated request never makes a worker thread recurse past that depth. Headers not named in `SignedHeaders` do not take part in verification; the service behaves the same way, and clients sign every `x-amz-*` header they send. #### Credential Types diff --git a/tests/test_request_nesting_depth.py b/tests/test_request_nesting_depth.py index 46f9ce3aa..377e3ba3a 100644 --- a/tests/test_request_nesting_depth.py +++ b/tests/test_request_nesting_depth.py @@ -22,6 +22,11 @@ Bodies shallow enough for the client library to serialize without hitting its own recursion limit use boto3 directly; deeper bodies are built as raw JSON and signed, so no client library recurses to produce them. + +Before authentication the service checks only a body's syntax, at every depth: +a deep body with a syntax fault is a SerializationException unsigned or badly +signed, and a complete deep body gets the authentication error (us-east-1, +2026-11-19). """ from __future__ import annotations @@ -32,6 +37,7 @@ import boto3 import pytest +import requests from botocore.exceptions import ClientError from conftest import scoped_table @@ -195,3 +201,102 @@ def test_a_body_far_past_the_ceiling_is_a_messageless_serialization_error( resp = _raw_put(dynamodb_client, table, "huge", 20_000) assert resp.status_code == 400, resp.text assert _is_messageless_serialization_error(resp.json()), resp.text + + +def _unauthenticated_put(dynamodb_client, endpoint_url, body: bytes, signing: str): + """POST a raw PutItem body with no Authorization header ("unsigned"), or + signed with the caller's access key and a wrong secret key + ("bad-signature").""" + endpoint = dynamodb_client.meta.endpoint_url + if signing == "unsigned": + return requests.post( + endpoint, + data=body, + headers={ + "X-Amz-Target": "DynamoDB_20120810.PutItem", + "Content-Type": "application/x-amz-json-1.0", + }, + # ExtendDB serves a self-signed certificate; the service does not. + verify=endpoint_url is None, + timeout=30, + ) + frozen = boto3.Session().get_credentials().get_frozen_credentials() + secret = frozen.secret_key + wrong_secret = secret[:-1] + ("A" if secret[-1] != "A" else "B") + return signed_post( + endpoint, + frozen.access_key, + wrong_secret, + dynamodb_client.meta.region_name, + "PutItem", + body, + session_token=frozen.token, + ) + + +def _malformed_body(table_name: str, shape: str) -> bytes: + """`x-then-6000-openers` is the byte `x` followed by 6000 `[`; + `truncated-` is the raw PutItem body of `w` wrappers without its last + byte.""" + if shape == "x-then-6000-openers": + return b"x" + b"[" * 6000 + wrappers = int(shape.removeprefix("truncated-")) + return _raw_put_body(table_name, "malformed", wrappers)[:-1] + + +@pytest.mark.parametrize("signing", ["unsigned", "bad-signature"]) +@pytest.mark.parametrize( + "shape", + [ + "x-then-6000-openers", + "truncated-63", + "truncated-200", + "truncated-2000", + "truncated-20000", + ], +) +def test_a_malformed_deep_body_is_refused_before_authentication( + dynamodb_client, endpoint_url, table, shape, signing +): + # Each body nests past the 127 levels ExtendDB parses before + # authentication and has a syntax fault. The service answers each with a + # 400 SerializationException, unsigned and badly signed (2 of 2 sends per + # body and signing, us-east-1, 2026-11-19). + body = _malformed_body(table, shape) + resp = _unauthenticated_put(dynamodb_client, endpoint_url, body, signing) + assert resp.status_code == 400, resp.text + err = resp.json() + assert err["__type"] == SERIALIZATION_TYPE, resp.text + if shape in ("x-then-6000-openers", "truncated-20000"): + # Nested past ExtendDB's 5200 level ceiling, both answers have no + # message field. Within the ceiling ExtendDB's refusal carries its usual + # wording, as for a shallow malformed body, where the service's has no + # message field. + assert "message" not in err, resp.text + + +@pytest.mark.parametrize("signing", ["unsigned", "bad-signature"]) +@pytest.mark.parametrize( + "wrappers, tail", + [(63, b""), (2000, b""), (20000, b""), (2000, b"x")], + ids=["complete-63", "complete-2000", "complete-20000", "complete-2000-then-x"], +) +def test_a_complete_deep_body_reaches_authentication( + dynamodb_client, endpoint_url, table, wrappers, tail, signing +): + # The check before authentication reads one complete JSON value at any + # depth and ignores bytes after it, as the service's does: unsigned, each + # body is MissingAuthenticationTokenException, and badly signed + # InvalidSignatureException (2 of 2 sends each, us-east-1, 2026-11-19). + # ExtendDB's type for the first is MissingAuthenticationToken (#1075). + body = _raw_put_body(table, "unauthenticated", wrappers) + tail + resp = _unauthenticated_put(dynamodb_client, endpoint_url, body, signing) + assert resp.status_code == 400, resp.text + expected = ( + "MissingAuthenticationToken" + if signing == "unsigned" + else "InvalidSignatureException" + ) + assert resp.json()["__type"].startswith( + f"com.amazon.coral.service#{expected}" + ), resp.text From b8fee45ee66f49262d717c334569afb6d6ff5ec8 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:18:00 +0000 Subject: [PATCH 06/15] docs(server): say what the service does with an unknown deep member The comment on the request depth ceiling said that the server parses every depth the service answers consistently. That holds for an attribute. The service ignores an unknown top-level member nested 5201, 6001 or 20000 levels. It answers 200 on PutItem, DescribeTable and ListTables (us-east-1, 2026-11-19, 20 of 20 sends). The server refuses such a body past its 5200 level ceiling. The comment now states both answers. --- crates/server/src/request_parse.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index fb878ce58..e4f1a46e1 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -43,11 +43,15 @@ use extenddb_core::error::DynamoDbError; /// send. At 1500 wrappers and deeper a few sends are a 500 `InternalFailure` /// instead (measured 2026-11-12 and 2026-11-13, us-east-1, 24 or more sends /// per depth across several windows). -/// An unknown top-level member is ignored at any depth (20000 levels is a 200). -/// The ceiling, 5200 structural levels or about 2598 wrappers, sits inside the -/// band where the service itself varies: every depth the service answers -/// consistently is parsed here, and a deeper body gets the message-less -/// refusal the service gives in that band. +/// The service ignores an unknown top-level member: one nested 5201, 6001 or +/// 20000 levels is a 200 on PutItem, DescribeTable and ListTables (measured +/// 2026-11-19, us-east-1). The ceiling, 5200 structural levels or about 2598 +/// wrappers, sits inside the band where the service itself varies. An +/// attribute shallow enough for the service to validate it on every send is +/// parsed here, and a body nested past the ceiling gets the message-less +/// refusal the service gives for an attribute in that band. A body with an +/// unknown top-level member nested past the ceiling is refused here, where +/// the service ignores the member. /// /// A body this deep recurses the same number of levels three times over: the /// `serde_json` parse, the conversion to typed `AttributeValue`s (which has no From 5d719025a1bcbb1dda6406f0a3d152a6228fdd4b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:18:00 +0000 Subject: [PATCH 07/15] test(server): pin the 5200 level ceiling in the depth scan rows The rows of `the_depth_scan_brackets_the_ceiling_exactly` took their depths from `MAX_REQUEST_JSON_DEPTH`, so they moved with the constant and no row failed when it changed. The rows now hold the literal depths 5200 and 5201 and say whether each one is within the ceiling. With the constant at 5199 or at 5201, the test fails. --- crates/server/src/request_parse.rs | 37 +++++++++++++++--------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index e4f1a46e1..f36cc8979 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -241,26 +241,27 @@ mod tests { #[test] fn the_depth_scan_brackets_the_ceiling_exactly() { // Scan only (no parse), so this is safe at any depth on the test stack. - // Rows: body, the depth the scan must report. The scan saturates one - // past the ceiling for a deeper body. - let rows: [(Vec, usize); 5] = [ - (deep_body(100), 203), - (deep_body(2000), 4003), - (b"[".repeat(MAX_REQUEST_JSON_DEPTH), MAX_REQUEST_JSON_DEPTH), - ( - b"[".repeat(MAX_REQUEST_JSON_DEPTH + 1), - MAX_REQUEST_JSON_DEPTH + 1, - ), - ( - deep_body(MAX_REQUEST_JSON_DEPTH), - MAX_REQUEST_JSON_DEPTH + 1, - ), + // Rows: body, the depth the scan must report, whether that depth is + // within the ceiling. The depths are literals, so a ceiling other than + // 5200 fails a row. The scan saturates one past the ceiling for a + // deeper body. + let rows: [(Vec, usize, bool); 5] = [ + (deep_body(100), 203, true), + (deep_body(2000), 4003, true), + (b"[".repeat(5200), 5200, true), + (b"[".repeat(5201), 5201, false), + (deep_body(5200), 5201, false), ]; - for (body, depth) in &rows { - assert_eq!(nesting_depth(body), *depth, "{} bytes", body.len()); + for (body, depth, within) in &rows { + let scanned = nesting_depth(body); + assert_eq!(scanned, *depth, "{} bytes", body.len()); + assert_eq!( + scanned <= MAX_REQUEST_JSON_DEPTH, + *within, + "{} bytes", + body.len() + ); } - assert!(nesting_depth(&rows[2].0) <= MAX_REQUEST_JSON_DEPTH); - assert!(nesting_depth(&rows[3].0) > MAX_REQUEST_JSON_DEPTH); } #[test] From 1f4912543922b55425e5e9bff7bcea6b8aceb428 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:29:53 +0000 Subject: [PATCH 08/15] docs(server): say which deep malformed bodies reach authentication The security manual said that a malformed body returns SerializationException whatever the signature. For a body nested deeper than 127 levels, the check before authentication reads only the first JSON value. It does not check UTF-8 or surrogate escapes in strings. Bytes after that value, an invalid UTF-8 byte and a lone surrogate escape reach authentication, as on the service. Unsigned, the service answers each with MissingAuthenticationTokenException (us-east-1, 2026-11-19). The manual now says so. The comment on the syntax check test said that the check gives the same refusal as the parse after authentication. The message is the same for the structural faults in its rows. For a raw control character in a string, the check reports one column earlier. The comment now says both. The unit test drops two asserts that its row loop and two other tests already cover. It also builds its wrong closer row inline in place of a helper with one caller. The wire test builds each malformed body from a wrappers parameter and no longer parses shape names. --- crates/server/src/request_parse.rs | 36 ++++------------------------- docs/manuals/10-security-model.md | 2 +- tests/test_request_nesting_depth.py | 31 ++++++++----------------- 3 files changed, 16 insertions(+), 53 deletions(-) diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index f36cc8979..42444bd84 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -376,21 +376,15 @@ mod tests { body } - /// `deep_body(wrappers)` with its last `}` written as `]`. - fn wrong_closer_body(wrappers: usize) -> Vec { - let mut body = deep_body(wrappers); - *body.last_mut().unwrap() = b']'; - body - } - #[test] fn the_syntax_check_refuses_a_malformed_deep_body_as_the_parse_does() { // Rows: a body nested past the pre-auth depth with a syntax fault. The // service refuses each before authentication with a // SerializationException (measured 2026-11-19, us-east-1, unsigned - // and badly signed). The check must give the refusal that the parse - // after authentication gives the same body. The parse recurses, so the - // rows run on a worker-sized stack. + // and badly signed). For the structural faults in these rows the check + // gives the message the parse after authentication gives. For a raw + // control character in a string, the skip reports one column earlier. + // The parse recurses, so the rows run on a worker-sized stack. let rows = [ [&b"x"[..], &b"[".repeat(6000)].concat(), [&b"x"[..], &b"[".repeat(200)].concat(), @@ -398,7 +392,7 @@ mod tests { truncated_body(200), truncated_body(2000), truncated_body(20000), - wrong_closer_body(200), + [&truncated_body(200)[..], b"]"].concat(), ]; std::thread::Builder::new() .stack_size(REQUEST_WORKER_STACK_SIZE) @@ -415,26 +409,6 @@ mod tests { .unwrap() .join() .unwrap(); - // Past the ceiling the refusal carries no message, which the service - // also gives these bodies; within it, the server's usual wording. - let past = [&b"x"[..], &b"[".repeat(6000)].concat(); - assert!( - check_request_syntax(&past, nesting_depth(&past)) - .unwrap_err() - .message() - .is_empty() - ); - let within = truncated_body(200); - assert_eq!( - check_request_syntax(&within, nesting_depth(&within)) - .unwrap_err() - .message(), - format!( - "Start of structure or map found where not expected: \ - EOF while parsing an object at line 1 column {}", - within.len() - ) - ); } #[test] diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 2e847a8e4..69cbacbcc 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -48,7 +48,7 @@ The steps run in this order; every rejection is HTTP 400. 8. Derive the signing key (HMAC-SHA256 chain over date, region, service, "aws4_request") and compare the computed signature with the provided one in constant time; mismatch: `InvalidSignatureException` 9. Apply the deferred decisions from steps 3 and 6, after the signature check so that failure paths take the same time: an inactive key or a wrong or missing token is `UnrecognizedClientException` -A request body's JSON syntax is checked before authentication at every nesting depth (the service does the same), so a malformed body returns `SerializationException` whatever the signature. A body nested deeper than 127 levels is parsed only after the caller is authenticated, so an unauthenticated request never makes a worker thread recurse past that depth. Headers not named in `SignedHeaders` do not take part in verification; the service behaves the same way, and clients sign every `x-amz-*` header they send. +A request body's JSON syntax is checked before authentication at every nesting depth (the service does the same). A malformed body therefore returns `SerializationException` whatever the signature. In a body nested deeper than 127 levels, the syntax check reads only the first JSON value. It does not check UTF-8 or surrogate escapes in strings, as on the service. So bytes after that value, an invalid UTF-8 byte or a lone surrogate escape reach authentication, and only the parse after authentication refuses them. A body nested deeper than 127 levels is parsed only after authentication, so an unauthenticated request never makes a worker thread recurse past that depth. Headers not named in `SignedHeaders` do not take part in verification; the service behaves the same way, and clients sign every `x-amz-*` header they send. #### Credential Types diff --git a/tests/test_request_nesting_depth.py b/tests/test_request_nesting_depth.py index 377e3ba3a..505fb55be 100644 --- a/tests/test_request_nesting_depth.py +++ b/tests/test_request_nesting_depth.py @@ -234,40 +234,29 @@ def _unauthenticated_put(dynamodb_client, endpoint_url, body: bytes, signing: st ) -def _malformed_body(table_name: str, shape: str) -> bytes: - """`x-then-6000-openers` is the byte `x` followed by 6000 `[`; - `truncated-` is the raw PutItem body of `w` wrappers without its last - byte.""" - if shape == "x-then-6000-openers": - return b"x" + b"[" * 6000 - wrappers = int(shape.removeprefix("truncated-")) - return _raw_put_body(table_name, "malformed", wrappers)[:-1] - - @pytest.mark.parametrize("signing", ["unsigned", "bad-signature"]) @pytest.mark.parametrize( - "shape", - [ - "x-then-6000-openers", - "truncated-63", - "truncated-200", - "truncated-2000", - "truncated-20000", - ], + "wrappers", + [None, 63, 200, 2000, 20000], + ids=lambda w: "x-then-6000-openers" if w is None else f"truncated-{w}", ) def test_a_malformed_deep_body_is_refused_before_authentication( - dynamodb_client, endpoint_url, table, shape, signing + dynamodb_client, endpoint_url, table, wrappers, signing ): # Each body nests past the 127 levels ExtendDB parses before # authentication and has a syntax fault. The service answers each with a # 400 SerializationException, unsigned and badly signed (2 of 2 sends per # body and signing, us-east-1, 2026-11-19). - body = _malformed_body(table, shape) + body = ( + b"x" + b"[" * 6000 + if wrappers is None + else _raw_put_body(table, "malformed", wrappers)[:-1] + ) resp = _unauthenticated_put(dynamodb_client, endpoint_url, body, signing) assert resp.status_code == 400, resp.text err = resp.json() assert err["__type"] == SERIALIZATION_TYPE, resp.text - if shape in ("x-then-6000-openers", "truncated-20000"): + if wrappers in (None, 20000): # Nested past ExtendDB's 5200 level ceiling, both answers have no # message field. Within the ceiling ExtendDB's refusal carries its usual # wording, as for a shallow malformed body, where the service's has no From c73c1b0e21acccb2c4612ba9d6e067c320cc05df Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:35:57 +0000 Subject: [PATCH 09/15] fix(server): skip a deep body with the service's grammar before authentication The syntax check before authentication deserialized the body as serde::de::IgnoredAny, so it applied serde_json's grammar. The service's check is looser in three lexemes, and it authenticates these deep bodies first, where the check refused them. The forms are the numbers 01, 1., 1e and -, the escape \u12G4 in a string, and NUL, VT or FF between tokens. At 63 and at 20000 wrappers, each is a MissingAuthenticationTokenException unsigned and an InvalidSignatureException badly signed. That held on 2 of 2 sends per body and signing (us-east-1, 2026-11-24). check_request_syntax now calls skip_value, a scan of the body's first JSON value with serde_json's grammar in every lexeme but those three. Whitespace also takes NUL, VT and FF. SOH stays refused. A number is - or a digit and then any run of the bytes number_byte names, 0-9 + - . e E. The four bytes after \u are not read as hex digits. The service takes any byte from 0 to g (0x30 to 0x67) there and refuses the others. Unsigned at 200 wrappers, \u::::, \u@@@@, \uffff, \ugggg, four backslashes and four backticks reach authentication. \u/123, \u12.4, \u12"x, \uhhhh, \uzzzz, \u~~~~, four SOH bytes and four bytes above 0x7F are a SerializationException (us-east-1, 2026-11-24). The scan keeps the closers of the open containers in a Vec, as serde_json's skip does, so it does not recurse at any depth. nesting_depth tracks only strings and escapes, and serde_json's skip cannot be configured, so neither could take the three lexemes. The check still refuses the seven forms the service refuses before authentication. Four sit between tokens or in a literal: SOH before a value, tru, a missing colon and a missing comma. Three sit in a string: a \u before the closing quote, a raw control byte and the escape \q. Each is a SerializationException with no message, unsigned and badly signed (us-east-1, 2026-11-24, and 2026-11-20 for the two string faults). The depth branch stays. A body past the 5200 level ceiling gets the message-less refusal as before. The unit test rows gain the eight forms at 63 and at 20000 wrappers and the seven refused forms at 200. They run on the default test stack. The refusal test changes. It no longer compares the check's message with the parse's, since the scan words its faults itself. It asserts the type, a message within the ceiling and none past it. The wire file gains the same rows, 73 cases in place of 27. --- crates/server/src/request_parse.rs | 308 +++++++++++++++++++++++----- tests/test_request_nesting_depth.py | 97 ++++++--- 2 files changed, 323 insertions(+), 82 deletions(-) diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index 42444bd84..303360d9d 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -27,7 +27,6 @@ //! default depth on an unauthenticated connection. use serde::Deserialize; -use serde::de::IgnoredAny; use serde_json::Value; use extenddb_core::error::DynamoDbError; @@ -143,23 +142,187 @@ pub(crate) fn parse_request_value(body: &[u8], depth: usize) -> Result Result<(), DynamoDbError> { - let mut de = serde_json::Deserializer::from_slice(body); - match IgnoredAny::deserialize(&mut de) { - Ok(IgnoredAny) => Ok(()), - Err(_) if depth > MAX_REQUEST_JSON_DEPTH => Err(over_ceiling_refusal()), - Err(e) => Err(serialization_error(&e.to_string())), + skip_value(body).map_err(|fault| { + if depth > MAX_REQUEST_JSON_DEPTH { + over_ceiling_refusal() + } else { + serialization_error(fault) + } + }) +} + +/// Whether `b` can be part of a number as the service reads one. The service +/// takes a run of these bytes that starts with a digit or `-` as one number. +fn number_byte(b: u8) -> bool { + matches!(b, b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') +} + +/// A cursor over a request body, for [`skip_value`]. +struct Scan<'a> { + body: &'a [u8], + at: usize, +} + +impl Scan<'_> { + /// The byte at the cursor after any whitespace, or `None` at the end of + /// the body. Besides JSON's space, TAB, LF and CR, the service skips NUL, + /// VT and FF between tokens and refuses SOH there (measured 2026-11-24, + /// us-east-1: unsigned, a 200 wrapper `PutItem` with one of the three + /// before a value is a `MissingAuthenticationTokenException`, and with + /// SOH there a `SerializationException`). + fn token(&mut self) -> Option { + while let Some(&b) = self.body.get(self.at) { + if !matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x00 | 0x0b | 0x0c) { + return Some(b); + } + self.at += 1; + } + None + } + + /// The byte at the cursor, which moves past it. + fn next(&mut self) -> Option { + let b = *self.body.get(self.at)?; + self.at += 1; + Some(b) + } + + /// Skip a string literal from after its opening quote to after its + /// closing quote. As in JSON, a raw control byte, or an escape letter + /// other than `"`, `\`, `/`, `b`, `f`, `n`, `r`, `t` and `u`, is a fault. + /// The four bytes after `\u` are not read as hex digits: the service + /// takes any byte from `0` to `g` (0x30 to 0x67) there and refuses the + /// others (measured 2026-11-24, us-east-1, unsigned, 200 wrappers: + /// `\u12G4`, `\u::::`, `\u@@@@`, `\u` and four backslashes, `\u` and four + /// backticks, `\uffff` and `\ugggg` are a + /// `MissingAuthenticationTokenException`; `\u/123`, `\u12.4`, `\u12"x`, + /// `\uhhhh`, `\uzzzz`, `\u~~~~`, `\u` and four SOH bytes, and `\u` and four + /// bytes above 0x7F are a `SerializationException`). + fn skip_string(&mut self) -> Result<(), &'static str> { + loop { + match self.next().ok_or("unterminated string")? { + b'"' => return Ok(()), + b'\\' => match self.next().ok_or("unterminated string")? { + b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {} + b'u' => { + for _ in 0..4 { + if !matches!(self.next(), Some(b'0'..=b'g')) { + return Err("invalid unicode escape"); + } + } + } + _ => return Err("invalid escape"), + }, + 0x00..=0x1f => return Err("control character in string"), + _ => {} + } + } + } + + /// Skip an object key and the colon after it. + fn skip_key(&mut self) -> Result<(), &'static str> { + if self.token() != Some(b'"') { + return Err("key must be a string"); + } + self.at += 1; + self.skip_string()?; + if self.token() != Some(b':') { + return Err("expected `:`"); + } + self.at += 1; + Ok(()) + } + + /// Skip `word`, which must start at the cursor. + fn skip_literal(&mut self, word: &[u8]) -> Result<(), &'static str> { + if !self.body[self.at..].starts_with(word) { + return Err("invalid literal"); + } + self.at += word.len(); + Ok(()) + } +} + +/// Read past the first JSON value of `body` without building it. The grammar +/// is JSON's, as `serde_json` applies it, except in the three lexemes where +/// the service's check before authentication is looser: whitespace also takes +/// NUL, VT and FF ([`Scan::token`]); a number is `-` or a digit and then any +/// run of [`number_byte`]s, so `01`, `1.`, `1e` and `-` pass (measured +/// 2026-11-24, us-east-1, at 63 and 20000 wrappers: unsigned, each is a +/// `MissingAuthenticationTokenException`); and the four bytes after `\u` may +/// be any byte from `0` to `g` ([`Scan::skip_string`]). Bytes after the value +/// are not read. The closers of the open containers sit on a heap stack, one +/// byte per level, so the loop never recurses. +fn skip_value(body: &[u8]) -> Result<(), &'static str> { + let mut scan = Scan { body, at: 0 }; + let mut open: Vec = Vec::new(); + 'value: loop { + match scan.token().ok_or("expected value")? { + opener @ (b'{' | b'[') => { + scan.at += 1; + let closer = if opener == b'{' { b'}' } else { b']' }; + if scan.token() == Some(closer) { + scan.at += 1; + } else { + open.push(closer); + if opener == b'{' { + scan.skip_key()?; + } + continue 'value; + } + } + b'"' => { + scan.at += 1; + scan.skip_string()?; + } + b'-' | b'0'..=b'9' => { + scan.at += 1; + while scan.body.get(scan.at).is_some_and(|&b| number_byte(b)) { + scan.at += 1; + } + } + b't' => scan.skip_literal(b"true")?, + b'f' => scan.skip_literal(b"false")?, + b'n' => scan.skip_literal(b"null")?, + _ => return Err("expected value"), + } + // The value is complete: close containers until a comma starts the + // next member, or the outermost container closes. + loop { + let Some(&closer) = open.last() else { + return Ok(()); + }; + match scan.token() { + Some(b',') => { + scan.at += 1; + if closer == b'}' { + scan.skip_key()?; + } + continue 'value; + } + Some(b) if b == closer => { + scan.at += 1; + open.pop(); + } + Some(_) => return Err("expected `,` or the end of the container"), + None => return Err("unterminated container"), + } + } } } @@ -188,18 +351,40 @@ mod tests { /// maps around a string leaf: `{"M":{"n": ... {"S":"leaf"} ... }}`. Its /// structural depth is `3 + 2 * wrappers`. fn deep_body(wrappers: usize) -> Vec { - let mut s = String::from(r#"{"TableName":"t","Item":{"data":"#); + deep_body_with_leaf(wrappers, br#"{"S":"leaf"}"#) + } + + /// [`deep_body`] with `leaf` in place of `{"S":"leaf"}`. + fn deep_body_with_leaf(wrappers: usize, leaf: &[u8]) -> Vec { + let mut body = br#"{"TableName":"t","Item":{"data":"#.to_vec(); for _ in 0..wrappers { - s.push_str(r#"{"M":{"n":"#); + body.extend_from_slice(br#"{"M":{"n":"#); } - s.push_str(r#"{"S":"leaf"}"#); + body.extend_from_slice(leaf); for _ in 0..wrappers { - s.push_str("}}"); + body.extend_from_slice(b"}}"); } - s.push_str("}}"); - s.into_bytes() + body.extend_from_slice(b"}}"); + body } + /// The leaves the service's check before authentication passes where + /// `serde_json`'s grammar refuses them (measured 2026-11-24, us-east-1, at + /// 63 and 20000 wrappers: unsigned, each is a + /// `MissingAuthenticationTokenException`, and badly signed an + /// `InvalidSignatureException`): the numbers `01`, `1.`, `1e` and `-`, the + /// escape `\u12G4`, and FF, NUL and VT before a value. + const LOOSE_LEAVES: [&[u8]; 8] = [ + br#"{"S":01}"#, + br#"{"S":1.}"#, + br#"{"S":1e}"#, + br#"{"S":-}"#, + br#"{"S":"le\u12G4af"}"#, + b"{\"S\":\x0c\"leaf\"}", + b"{\"S\":\x00\"leaf\"}", + b"{\"S\":\x0b\"leaf\"}", + ]; + fn parse(body: &[u8]) -> Result { parse_request_value(body, nesting_depth(body)) } @@ -377,14 +562,18 @@ mod tests { } #[test] - fn the_syntax_check_refuses_a_malformed_deep_body_as_the_parse_does() { + fn the_syntax_check_refuses_a_malformed_deep_body() { // Rows: a body nested past the pre-auth depth with a syntax fault. The // service refuses each before authentication with a - // SerializationException (measured 2026-11-19, us-east-1, unsigned - // and badly signed). For the structural faults in these rows the check - // gives the message the parse after authentication gives. For a raw - // control character in a string, the skip reports one column earlier. - // The parse recurses, so the rows run on a worker-sized stack. + // SerializationException and no message (measured in us-east-1: + // the structural faults on 2026-11-19, unsigned and badly signed; the + // control byte and the unknown escape in a string on 2026-11-20, + // unsigned, badly signed and signed; the `\u` before the closing + // quote, SOH before a value, `tru`, the missing colon and the missing + // comma on 2026-11-24, unsigned and badly signed). Within the ceiling + // the check's refusal carries the server's wording, and past it no + // message. The check does not recurse, so the rows run on the default + // test-thread stack. let rows = [ [&b"x"[..], &b"[".repeat(6000)].concat(), [&b"x"[..], &b"[".repeat(200)].concat(), @@ -393,45 +582,50 @@ mod tests { truncated_body(2000), truncated_body(20000), [&truncated_body(200)[..], b"]"].concat(), + deep_body_with_leaf(200, br#"{"S":"le\u"}"#), + deep_body_with_leaf(200, b"{\"S\":\x01\"leaf\"}"), + deep_body_with_leaf(200, br#"{"S":tru}"#), + deep_body_with_leaf(200, br#"{"S" "leaf"}"#), + deep_body_with_leaf(200, br#"{"S":"leaf" "T":"x"}"#), + deep_body_with_leaf(200, b"{\"S\":\"le\x01af\"}"), + deep_body_with_leaf(200, br#"{"S":"le\qaf"}"#), ]; - std::thread::Builder::new() - .stack_size(REQUEST_WORKER_STACK_SIZE) - .spawn(move || { - for body in &rows { - let depth = nesting_depth(body); - assert!(depth > UNAUTHENTICATED_PARSE_DEPTH, "{} bytes", body.len()); - let checked = check_request_syntax(body, depth).unwrap_err(); - let parsed = parse_request_value(body, depth).unwrap_err(); - assert!(matches!(checked, DynamoDbError::SerializationException(_))); - assert_eq!(checked.message(), parsed.message(), "{} bytes", body.len()); - } - }) - .unwrap() - .join() - .unwrap(); + for body in &rows { + let depth = nesting_depth(body); + assert!(depth > UNAUTHENTICATED_PARSE_DEPTH, "{} bytes", body.len()); + let err = check_request_syntax(body, depth).unwrap_err(); + assert!(matches!(err, DynamoDbError::SerializationException(_))); + assert_eq!( + err.message().is_empty(), + depth > MAX_REQUEST_JSON_DEPTH, + "{} bytes: {:?}", + body.len(), + err.message() + ); + } } #[test] fn the_syntax_check_passes_what_the_service_authenticates_first() { - // Rows: bodies the service's check before authentication passes + // Rows: bodies the service's check before authentication passes. + // Complete bodies far past the ceiling, bytes after a complete body, + // an invalid UTF-8 byte in a string and a lone surrogate escape // (measured 2026-11-19, us-east-1: unsigned, each is a - // MissingAuthenticationTokenException). Complete bodies far past the - // ceiling, bytes after a complete body, an invalid UTF-8 byte in a - // string and a lone surrogate escape. This runs on the default - // test-thread stack, where a parse that recursed a million levels - // would overflow, so it also shows that the check does not recurse. - let leaf = |with: &[u8]| { - let body = deep_body(200); - let at = body.windows(6).position(|w| w == b"\"leaf\"").unwrap(); - [&body[..at], with, &body[at + 6..]].concat() - }; - let rows = [ + // MissingAuthenticationTokenException), and each leaf of + // `LOOSE_LEAVES` at 63 and at 20000 wrappers (measured 2026-11-24). + // This runs on the default test-thread stack, where a parse that + // recursed a million levels would overflow, so it also shows that the + // check does not recurse. + let mut rows = vec![ [b"[".repeat(1_000_000), b"]".repeat(1_000_000)].concat(), deep_body(20000), [deep_body(2000), b"x".to_vec()].concat(), - leaf(b"\"le\xffaf\""), - leaf(br#""le\ud800af""#), + deep_body_with_leaf(200, b"{\"S\":\"le\xffaf\"}"), + deep_body_with_leaf(200, br#"{"S":"le\ud800af"}"#), ]; + for wrappers in [63, 20000] { + rows.extend(LOOSE_LEAVES.map(|leaf| deep_body_with_leaf(wrappers, leaf))); + } for body in &rows { let depth = nesting_depth(body); assert!(depth > UNAUTHENTICATED_PARSE_DEPTH, "{} bytes", body.len()); diff --git a/tests/test_request_nesting_depth.py b/tests/test_request_nesting_depth.py index 505fb55be..668fd8d61 100644 --- a/tests/test_request_nesting_depth.py +++ b/tests/test_request_nesting_depth.py @@ -26,7 +26,9 @@ Before authentication the service checks only a body's syntax, at every depth: a deep body with a syntax fault is a SerializationException unsigned or badly signed, and a complete deep body gets the authentication error (us-east-1, -2026-11-19). +2026-11-19). That check is looser than JSON's grammar in three lexemes: a +number such as `01`, `1.`, `1e` or `-`, the escape `\\u12G4`, and NUL, VT or FF +between tokens all reach authentication (us-east-1, 2026-11-24). """ from __future__ import annotations @@ -49,6 +51,23 @@ "Attributes in the item have nested levels beyond supported limit" ) SERIALIZATION_TYPE = "com.amazon.coral.service#SerializationException" +LEAF = '{"S":"leaf"}' + +# Leaves the service's check before authentication passes where JSON's grammar +# refuses them: the numbers `01`, `1.`, `1e` and `-`, the escape `\u12G4`, and +# form feed, NUL and vertical tab before a value (us-east-1, 2026-11-24, at 63 +# and 20000 wrappers, 2 of 2 sends each: unsigned +# MissingAuthenticationTokenException, badly signed InvalidSignatureException). +LOOSE_LEAVES = { + "number-01": '{"S":01}', + "number-1.": '{"S":1.}', + "number-1e": '{"S":1e}', + "number-minus": '{"S":-}', + "escape-u12G4": '{"S":"le\\u12G4af"}', + "form-feed-before-value": '{"S":\x0c"leaf"}', + "nul-before-value": '{"S":\x00"leaf"}', + "vertical-tab-before-value": '{"S":\x0b"leaf"}', +} @pytest.fixture(scope="module") @@ -82,10 +101,11 @@ def _put_error(client, table_name: str, data: dict) -> dict: return exc_info.value.response["Error"] -def _raw_put_body(table_name: str, pk: str, wrappers: int) -> bytes: +def _raw_put_body(table_name: str, pk: str, wrappers: int, leaf: str = LEAF) -> bytes: """A PutItem body whose `data` attribute is `wrappers` single-key maps around - a string leaf, assembled as raw JSON so nothing recurses to build it.""" - data = '{"M":{"n":' * wrappers + '{"S":"leaf"}' + "}}" * wrappers + `leaf`, a string leaf unless a row puts a fault there, assembled as raw JSON + so nothing recurses to build it.""" + data = '{"M":{"n":' * wrappers + leaf + "}}" * wrappers return ( '{"TableName":' + json.dumps(table_name) @@ -236,22 +256,38 @@ def _unauthenticated_put(dynamodb_client, endpoint_url, body: bytes, signing: st @pytest.mark.parametrize("signing", ["unsigned", "bad-signature"]) @pytest.mark.parametrize( - "wrappers", - [None, 63, 200, 2000, 20000], - ids=lambda w: "x-then-6000-openers" if w is None else f"truncated-{w}", + "wrappers, leaf", + [ + pytest.param(None, None, id="x-then-6000-openers"), + pytest.param(63, None, id="truncated-63"), + pytest.param(200, None, id="truncated-200"), + pytest.param(2000, None, id="truncated-2000"), + pytest.param(20000, None, id="truncated-20000"), + pytest.param(200, '{"S":"le\\u"}', id="u-before-closing-quote"), + pytest.param(200, '{"S":\x01"leaf"}', id="soh-before-value"), + pytest.param(200, '{"S":tru}', id="tru"), + pytest.param(200, '{"S" "leaf"}', id="missing-colon"), + pytest.param(200, '{"S":"leaf" "T":"x"}', id="missing-comma"), + pytest.param(200, '{"S":"le\x01af"}', id="control-byte-in-string"), + pytest.param(200, '{"S":"le\\qaf"}', id="unknown-escape"), + ], ) def test_a_malformed_deep_body_is_refused_before_authentication( - dynamodb_client, endpoint_url, table, wrappers, signing + dynamodb_client, endpoint_url, table, wrappers, leaf, signing ): # Each body nests past the 127 levels ExtendDB parses before - # authentication and has a syntax fault. The service answers each with a - # 400 SerializationException, unsigned and badly signed (2 of 2 sends per - # body and signing, us-east-1, 2026-11-19). - body = ( - b"x" + b"[" * 6000 - if wrappers is None - else _raw_put_body(table, "malformed", wrappers)[:-1] - ) + # authentication and has a syntax fault: `x` before the openers, the body + # without its last byte, or the fault in the leaf. The service answers + # each with a 400 SerializationException, unsigned and badly signed (2 of 2 + # sends per body and signing, us-east-1: the first five rows 2026-11-19, + # the control byte and the unknown escape 2026-11-20, the other five + # 2026-11-24). + if wrappers is None: + body = b"x" + b"[" * 6000 + elif leaf is None: + body = _raw_put_body(table, "malformed", wrappers)[:-1] + else: + body = _raw_put_body(table, "malformed", wrappers, leaf) resp = _unauthenticated_put(dynamodb_client, endpoint_url, body, signing) assert resp.status_code == 400, resp.text err = resp.json() @@ -266,19 +302,30 @@ def test_a_malformed_deep_body_is_refused_before_authentication( @pytest.mark.parametrize("signing", ["unsigned", "bad-signature"]) @pytest.mark.parametrize( - "wrappers, tail", - [(63, b""), (2000, b""), (20000, b""), (2000, b"x")], - ids=["complete-63", "complete-2000", "complete-20000", "complete-2000-then-x"], + "wrappers, leaf, tail", + [ + pytest.param(63, LEAF, b"", id="complete-63"), + pytest.param(2000, LEAF, b"", id="complete-2000"), + pytest.param(20000, LEAF, b"", id="complete-20000"), + pytest.param(2000, LEAF, b"x", id="complete-2000-then-x"), + ] + + [ + pytest.param(wrappers, leaf, b"", id=f"{name}-{wrappers}") + for wrappers in (63, 20000) + for name, leaf in LOOSE_LEAVES.items() + ], ) def test_a_complete_deep_body_reaches_authentication( - dynamodb_client, endpoint_url, table, wrappers, tail, signing + dynamodb_client, endpoint_url, table, wrappers, leaf, tail, signing ): # The check before authentication reads one complete JSON value at any - # depth and ignores bytes after it, as the service's does: unsigned, each - # body is MissingAuthenticationTokenException, and badly signed - # InvalidSignatureException (2 of 2 sends each, us-east-1, 2026-11-19). - # ExtendDB's type for the first is MissingAuthenticationToken (#1075). - body = _raw_put_body(table, "unauthenticated", wrappers) + tail + # depth and ignores bytes after it, as the service's does, and passes each + # leaf of LOOSE_LEAVES: unsigned, each body is + # MissingAuthenticationTokenException, and badly signed + # InvalidSignatureException (2 of 2 sends each, us-east-1, 2026-11-19 for + # the first four rows and 2026-11-24 for the rest). ExtendDB's type for the + # first is MissingAuthenticationToken (#1075). + body = _raw_put_body(table, "unauthenticated", wrappers, leaf) + tail resp = _unauthenticated_put(dynamodb_client, endpoint_url, body, signing) assert resp.status_code == 400, resp.text expected = ( From bb44727321cb3f4f333295a8b0b18684352e711a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:38:41 +0000 Subject: [PATCH 10/15] test(server): pin the message boundary of the syntax check's refusal The check's refusal carries the server's wording for a body within the 5200 level ceiling and no message for a body past it. No row sat on the boundary, so a check that dropped the message from 5200 levels on passed every test. Two unclosed rows, 5200 and 5201 openers, now hold the boundary: the first must carry a message and the second must not. --- crates/server/src/request_parse.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index 303360d9d..749968785 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -572,8 +572,9 @@ mod tests { // quote, SOH before a value, `tru`, the missing colon and the missing // comma on 2026-11-24, unsigned and badly signed). Within the ceiling // the check's refusal carries the server's wording, and past it no - // message. The check does not recurse, so the rows run on the default - // test-thread stack. + // message. The unclosed rows of exactly 5200 and 5201 openers pin + // that boundary. The check does not recurse, so the rows run on the + // default test-thread stack. let rows = [ [&b"x"[..], &b"[".repeat(6000)].concat(), [&b"x"[..], &b"[".repeat(200)].concat(), @@ -582,6 +583,8 @@ mod tests { truncated_body(2000), truncated_body(20000), [&truncated_body(200)[..], b"]"].concat(), + b"[".repeat(5200), + b"[".repeat(5201), deep_body_with_leaf(200, br#"{"S":"le\u"}"#), deep_body_with_leaf(200, b"{\"S\":\x01\"leaf\"}"), deep_body_with_leaf(200, br#"{"S":tru}"#), From 3dad85616dcfb2052e250342af8187a0cdf9467f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:40:43 +0000 Subject: [PATCH 11/15] docs(server): list the forms the syntax check passes to authentication The security manual said that a malformed body returns SerializationException whatever the signature. It named bytes after the first value, an invalid UTF-8 byte and a lone surrogate escape as the faults that reach authentication. The check before authentication now follows the service in three more lexemes, so the sentence holds only for a body that fails the check. The manual now says so and lists what passes. A number such as 01, 1., 1e or - passes. So does an escape whose four bytes after \u lie between 0 and g. So do NUL, vertical tab and form feed between tokens (us-east-1, 2026-11-24, unsigned and badly signed). --- docs/manuals/10-security-model.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 69cbacbcc..97b7c4a14 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -48,7 +48,7 @@ The steps run in this order; every rejection is HTTP 400. 8. Derive the signing key (HMAC-SHA256 chain over date, region, service, "aws4_request") and compare the computed signature with the provided one in constant time; mismatch: `InvalidSignatureException` 9. Apply the deferred decisions from steps 3 and 6, after the signature check so that failure paths take the same time: an inactive key or a wrong or missing token is `UnrecognizedClientException` -A request body's JSON syntax is checked before authentication at every nesting depth (the service does the same). A malformed body therefore returns `SerializationException` whatever the signature. In a body nested deeper than 127 levels, the syntax check reads only the first JSON value. It does not check UTF-8 or surrogate escapes in strings, as on the service. So bytes after that value, an invalid UTF-8 byte or a lone surrogate escape reach authentication, and only the parse after authentication refuses them. A body nested deeper than 127 levels is parsed only after authentication, so an unauthenticated request never makes a worker thread recurse past that depth. Headers not named in `SignedHeaders` do not take part in verification; the service behaves the same way, and clients sign every `x-amz-*` header they send. +A request body's JSON syntax is checked before authentication at every nesting depth (the service does the same). A body that fails the check returns `SerializationException` whatever the signature. In a body nested deeper than 127 levels, the syntax check reads only the first JSON value. It follows the service in four places. It does not check UTF-8 or surrogate escapes in strings. It reads a number as `-` or a digit and any run of digits, `+`, `-`, `.`, `e` and `E` after it. It takes any byte from `0` to `g` (0x30 to 0x67) as one of the four after `\u`. It skips NUL, vertical tab and form feed between tokens. So bytes after that value, an invalid UTF-8 byte and a lone surrogate escape reach authentication. So do a number such as `01`, `1.`, `1e` or `-`, an escape such as `\u12G4`, and one of those three bytes between tokens. Only the parse after authentication refuses them. A body nested deeper than 127 levels is parsed only after authentication, so an unauthenticated request never makes a worker thread recurse past that depth. Headers not named in `SignedHeaders` do not take part in verification; the service behaves the same way, and clients sign every `x-amz-*` header they send. #### Credential Types From 51cc6384de59d9b70e81b4a117253e4cca693e0a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:07:01 +0000 Subject: [PATCH 12/15] refactor(server): move the syntax scan into its own module request_parse.rs reached 642 lines with the scan and its rows. The scan (number_byte, Scan and skip_value) now sits in request_syntax.rs, 171 lines. request_parse.rs keeps the depth scan, the parse, the check that calls skip_value, and the tests, 483 lines. No line of the scan changed beyond the two pub(crate) markers the module boundary needs. --- crates/server/src/lib.rs | 1 + crates/server/src/request_parse.rs | 171 +--------------------------- crates/server/src/request_syntax.rs | 171 ++++++++++++++++++++++++++++ 3 files changed, 178 insertions(+), 165 deletions(-) create mode 100644 crates/server/src/request_syntax.rs diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index afcab0013..c1cab31d2 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -29,6 +29,7 @@ mod repeated_headers; mod request_attributes; mod request_helpers; mod request_parse; +mod request_syntax; mod request_tags; mod response; mod serve; diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index 749968785..efe7c62d2 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -142,11 +142,12 @@ pub(crate) fn parse_request_value(body: &[u8], depth: usize) -> Result Result Result<(), DynamoDbError> { - skip_value(body).map_err(|fault| { + crate::request_syntax::skip_value(body).map_err(|fault| { if depth > MAX_REQUEST_JSON_DEPTH { over_ceiling_refusal() } else { @@ -166,166 +167,6 @@ pub(crate) fn check_request_syntax(body: &[u8], depth: usize) -> Result<(), Dyna }) } -/// Whether `b` can be part of a number as the service reads one. The service -/// takes a run of these bytes that starts with a digit or `-` as one number. -fn number_byte(b: u8) -> bool { - matches!(b, b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') -} - -/// A cursor over a request body, for [`skip_value`]. -struct Scan<'a> { - body: &'a [u8], - at: usize, -} - -impl Scan<'_> { - /// The byte at the cursor after any whitespace, or `None` at the end of - /// the body. Besides JSON's space, TAB, LF and CR, the service skips NUL, - /// VT and FF between tokens and refuses SOH there (measured 2026-11-24, - /// us-east-1: unsigned, a 200 wrapper `PutItem` with one of the three - /// before a value is a `MissingAuthenticationTokenException`, and with - /// SOH there a `SerializationException`). - fn token(&mut self) -> Option { - while let Some(&b) = self.body.get(self.at) { - if !matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x00 | 0x0b | 0x0c) { - return Some(b); - } - self.at += 1; - } - None - } - - /// The byte at the cursor, which moves past it. - fn next(&mut self) -> Option { - let b = *self.body.get(self.at)?; - self.at += 1; - Some(b) - } - - /// Skip a string literal from after its opening quote to after its - /// closing quote. As in JSON, a raw control byte, or an escape letter - /// other than `"`, `\`, `/`, `b`, `f`, `n`, `r`, `t` and `u`, is a fault. - /// The four bytes after `\u` are not read as hex digits: the service - /// takes any byte from `0` to `g` (0x30 to 0x67) there and refuses the - /// others (measured 2026-11-24, us-east-1, unsigned, 200 wrappers: - /// `\u12G4`, `\u::::`, `\u@@@@`, `\u` and four backslashes, `\u` and four - /// backticks, `\uffff` and `\ugggg` are a - /// `MissingAuthenticationTokenException`; `\u/123`, `\u12.4`, `\u12"x`, - /// `\uhhhh`, `\uzzzz`, `\u~~~~`, `\u` and four SOH bytes, and `\u` and four - /// bytes above 0x7F are a `SerializationException`). - fn skip_string(&mut self) -> Result<(), &'static str> { - loop { - match self.next().ok_or("unterminated string")? { - b'"' => return Ok(()), - b'\\' => match self.next().ok_or("unterminated string")? { - b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {} - b'u' => { - for _ in 0..4 { - if !matches!(self.next(), Some(b'0'..=b'g')) { - return Err("invalid unicode escape"); - } - } - } - _ => return Err("invalid escape"), - }, - 0x00..=0x1f => return Err("control character in string"), - _ => {} - } - } - } - - /// Skip an object key and the colon after it. - fn skip_key(&mut self) -> Result<(), &'static str> { - if self.token() != Some(b'"') { - return Err("key must be a string"); - } - self.at += 1; - self.skip_string()?; - if self.token() != Some(b':') { - return Err("expected `:`"); - } - self.at += 1; - Ok(()) - } - - /// Skip `word`, which must start at the cursor. - fn skip_literal(&mut self, word: &[u8]) -> Result<(), &'static str> { - if !self.body[self.at..].starts_with(word) { - return Err("invalid literal"); - } - self.at += word.len(); - Ok(()) - } -} - -/// Read past the first JSON value of `body` without building it. The grammar -/// is JSON's, as `serde_json` applies it, except in the three lexemes where -/// the service's check before authentication is looser: whitespace also takes -/// NUL, VT and FF ([`Scan::token`]); a number is `-` or a digit and then any -/// run of [`number_byte`]s, so `01`, `1.`, `1e` and `-` pass (measured -/// 2026-11-24, us-east-1, at 63 and 20000 wrappers: unsigned, each is a -/// `MissingAuthenticationTokenException`); and the four bytes after `\u` may -/// be any byte from `0` to `g` ([`Scan::skip_string`]). Bytes after the value -/// are not read. The closers of the open containers sit on a heap stack, one -/// byte per level, so the loop never recurses. -fn skip_value(body: &[u8]) -> Result<(), &'static str> { - let mut scan = Scan { body, at: 0 }; - let mut open: Vec = Vec::new(); - 'value: loop { - match scan.token().ok_or("expected value")? { - opener @ (b'{' | b'[') => { - scan.at += 1; - let closer = if opener == b'{' { b'}' } else { b']' }; - if scan.token() == Some(closer) { - scan.at += 1; - } else { - open.push(closer); - if opener == b'{' { - scan.skip_key()?; - } - continue 'value; - } - } - b'"' => { - scan.at += 1; - scan.skip_string()?; - } - b'-' | b'0'..=b'9' => { - scan.at += 1; - while scan.body.get(scan.at).is_some_and(|&b| number_byte(b)) { - scan.at += 1; - } - } - b't' => scan.skip_literal(b"true")?, - b'f' => scan.skip_literal(b"false")?, - b'n' => scan.skip_literal(b"null")?, - _ => return Err("expected value"), - } - // The value is complete: close containers until a comma starts the - // next member, or the outermost container closes. - loop { - let Some(&closer) = open.last() else { - return Ok(()); - }; - match scan.token() { - Some(b',') => { - scan.at += 1; - if closer == b'}' { - scan.skip_key()?; - } - continue 'value; - } - Some(b) if b == closer => { - scan.at += 1; - open.pop(); - } - Some(_) => return Err("expected `,` or the end of the container"), - None => return Err("unterminated container"), - } - } - } -} - /// The refusal for a body nested past [`MAX_REQUEST_JSON_DEPTH`]. A signed body /// nested past what the service parses gets HTTP 400 with /// `{"__type":"com.amazon.coral.service#SerializationException"}` and no diff --git a/crates/server/src/request_syntax.rs b/crates/server/src/request_syntax.rs new file mode 100644 index 000000000..f83ba167e --- /dev/null +++ b/crates/server/src/request_syntax.rs @@ -0,0 +1,171 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The JSON syntax check a request body gets before authentication. +//! +//! [`skip_value`] reads past a body's first JSON value without building it +//! and without recursing, with the grammar the service applies before +//! authentication: JSON's, except in the three lexemes where the service is +//! looser (whitespace, numbers and the four bytes after `\u`; each is +//! measured in the doc comments below). `request_parse::check_request_syntax` +//! turns its answer into the server's refusal. + +/// Whether `b` can be part of a number as the service reads one. The service +/// takes a run of these bytes that starts with a digit or `-` as one number. +pub(crate) fn number_byte(b: u8) -> bool { + matches!(b, b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') +} + +/// A cursor over a request body, for [`skip_value`]. +struct Scan<'a> { + body: &'a [u8], + at: usize, +} + +impl Scan<'_> { + /// The byte at the cursor after any whitespace, or `None` at the end of + /// the body. Besides JSON's space, TAB, LF and CR, the service skips NUL, + /// VT and FF between tokens and refuses SOH there (measured 2026-11-24, + /// us-east-1: unsigned, a 200 wrapper `PutItem` with one of the three + /// before a value is a `MissingAuthenticationTokenException`, and with + /// SOH there a `SerializationException`). + fn token(&mut self) -> Option { + while let Some(&b) = self.body.get(self.at) { + if !matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x00 | 0x0b | 0x0c) { + return Some(b); + } + self.at += 1; + } + None + } + + /// The byte at the cursor, which moves past it. + fn next(&mut self) -> Option { + let b = *self.body.get(self.at)?; + self.at += 1; + Some(b) + } + + /// Skip a string literal from after its opening quote to after its + /// closing quote. As in JSON, a raw control byte, or an escape letter + /// other than `"`, `\`, `/`, `b`, `f`, `n`, `r`, `t` and `u`, is a fault. + /// The four bytes after `\u` are not read as hex digits: the service + /// takes any byte from `0` to `g` (0x30 to 0x67) there and refuses the + /// others (measured 2026-11-24, us-east-1, unsigned, 200 wrappers: + /// `\u12G4`, `\u::::`, `\u@@@@`, `\u` and four backslashes, `\u` and four + /// backticks, `\uffff` and `\ugggg` are a + /// `MissingAuthenticationTokenException`; `\u/123`, `\u12.4`, `\u12"x`, + /// `\uhhhh`, `\uzzzz`, `\u~~~~`, `\u` and four SOH bytes, and `\u` and four + /// bytes above 0x7F are a `SerializationException`). + fn skip_string(&mut self) -> Result<(), &'static str> { + loop { + match self.next().ok_or("unterminated string")? { + b'"' => return Ok(()), + b'\\' => match self.next().ok_or("unterminated string")? { + b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {} + b'u' => { + for _ in 0..4 { + if !matches!(self.next(), Some(b'0'..=b'g')) { + return Err("invalid unicode escape"); + } + } + } + _ => return Err("invalid escape"), + }, + 0x00..=0x1f => return Err("control character in string"), + _ => {} + } + } + } + + /// Skip an object key and the colon after it. + fn skip_key(&mut self) -> Result<(), &'static str> { + if self.token() != Some(b'"') { + return Err("key must be a string"); + } + self.at += 1; + self.skip_string()?; + if self.token() != Some(b':') { + return Err("expected `:`"); + } + self.at += 1; + Ok(()) + } + + /// Skip `word`, which must start at the cursor. + fn skip_literal(&mut self, word: &[u8]) -> Result<(), &'static str> { + if !self.body[self.at..].starts_with(word) { + return Err("invalid literal"); + } + self.at += word.len(); + Ok(()) + } +} + +/// Read past the first JSON value of `body` without building it. The grammar +/// is JSON's, as `serde_json` applies it, except in the three lexemes where +/// the service's check before authentication is looser: whitespace also takes +/// NUL, VT and FF ([`Scan::token`]); a number is `-` or a digit and then any +/// run of [`number_byte`]s, so `01`, `1.`, `1e` and `-` pass (measured +/// 2026-11-24, us-east-1, at 63 and 20000 wrappers: unsigned, each is a +/// `MissingAuthenticationTokenException`); and the four bytes after `\u` may +/// be any byte from `0` to `g` ([`Scan::skip_string`]). Bytes after the value +/// are not read. The closers of the open containers sit on a heap stack, one +/// byte per level, so the loop never recurses. +pub(crate) fn skip_value(body: &[u8]) -> Result<(), &'static str> { + let mut scan = Scan { body, at: 0 }; + let mut open: Vec = Vec::new(); + 'value: loop { + match scan.token().ok_or("expected value")? { + opener @ (b'{' | b'[') => { + scan.at += 1; + let closer = if opener == b'{' { b'}' } else { b']' }; + if scan.token() == Some(closer) { + scan.at += 1; + } else { + open.push(closer); + if opener == b'{' { + scan.skip_key()?; + } + continue 'value; + } + } + b'"' => { + scan.at += 1; + scan.skip_string()?; + } + b'-' | b'0'..=b'9' => { + scan.at += 1; + while scan.body.get(scan.at).is_some_and(|&b| number_byte(b)) { + scan.at += 1; + } + } + b't' => scan.skip_literal(b"true")?, + b'f' => scan.skip_literal(b"false")?, + b'n' => scan.skip_literal(b"null")?, + _ => return Err("expected value"), + } + // The value is complete: close containers until a comma starts the + // next member, or the outermost container closes. + loop { + let Some(&closer) = open.last() else { + return Ok(()); + }; + match scan.token() { + Some(b',') => { + scan.at += 1; + if closer == b'}' { + scan.skip_key()?; + } + continue 'value; + } + Some(b) if b == closer => { + scan.at += 1; + open.pop(); + } + Some(_) => return Err("expected `,` or the end of the container"), + None => return Err("unterminated container"), + } + } + } +} From 1a9efd7cec7c85861af3e7b4e5716abdee57c5f3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:28:59 +0000 Subject: [PATCH 13/15] refactor(server): run the engine's operation check and admit around the server's parse #1009 moved the checks before dispatch into extenddb_engine::parse_request and ParsedRequest::admit, and the server and the WebAssembly adapter both called them. This branch parses a body with its own parser in request_parse.rs. So the merge of main kept the server's own calls of is_known_operation and refuse_point_in_time_recovery. A check added to admit later would then reach only the adapter. The engine now makes the operation name check a step of its own. check_operation returns a KnownOperation. KnownOperation::with_body pairs it with a body that the entry point parsed and returns the ParsedRequest. parse_request is check_operation and the serde_json parse, as before, so the adapter still calls parse_request(..)?.admit(). The handler calls check_operation before its depth scan. It calls with_body(input).admit() after it authenticates the caller and parses a deep body, in place of its own two calls. No answer changes: the two steps make the same checks at the same points. These docs now say that the server calls check_operation and admit and parses the body itself: - the module doc of pre_dispatch.rs and the doc comments that name the callers - the handler comments and the adapter's module doc - the doc of malformed_body_error - the README's list of the server's checks, which also says that its table does not list the answers where the two parsers differ The five pre_dispatch tests reach check_operation and with_body through parse_request. Three mutants each fail one of them: one accepts every operation, one drops the operation in with_body, and one drops the body. So this commit adds no test. --- README.md | 19 +++--- crates/core/src/error/mod.rs | 7 +- crates/engine/src/lib.rs | 6 +- crates/engine/src/pre_dispatch.rs | 106 ++++++++++++++++++++++------- crates/server/src/handler.rs | 48 +++++++------ crates/wasm-adapter/src/runtime.rs | 27 +++++--- 6 files changed, 142 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 161121574..b1c322cbb 100755 --- a/README.md +++ b/README.md @@ -507,13 +507,16 @@ step does not see. Before the HTTP server passes a request to the engine, its request handler (`handle_request` in `crates/server/src/handler.rs`) and its authorization (`authorize_request` in `crates/server/src/request_helpers.rs`) check it. Both -builds run the checks the engine owns, `parse_request` and -`ParsedRequest::admit` in `crates/engine/src/pre_dispatch.rs`, except on the -operations this build refuses by name before them, whatever the body (see -"What it refuses"). This build makes none of the -server's other checks: it passes the request to the engine's handler for the -operation, so where a check below refuses a request, this build answers what -the handler answers, and the two answers can differ. +builds run the checks the engine owns in `crates/engine/src/pre_dispatch.rs`, +the operation name check `check_operation` and `ParsedRequest::admit`, except +on the operations this build refuses by name before them, whatever the body +(see "What it refuses"). Between the two, this build parses the body with the +engine's `parse_request`, and the server with its own parser +(`crates/server/src/request_parse.rs`), so the two builds can answer a body +differently; the table below does not list those answers. This build makes +none of the server's other checks: it passes the request to the engine's +handler for the operation, so where a check below refuses a request, this +build answers what the handler answers, and the two answers can differ. The server makes the checks in the table for every caller, in developer mode too, except the IAM decision of **signature**, which it makes only outside @@ -541,7 +544,7 @@ PostgreSQL backend registers again with its catalog, or the `AccessDeniedException` "User: is not authorized to perform this operation" it gives a request that passes its signature check and `admit` when its state has no catalog store, which `extenddb serve` never builds. The server's name checks -of a `RestoreTableToPointInTime` never run: `parse_request` refuses one whose +of a `RestoreTableToPointInTime` never run: the body parse refuses one whose body does not parse, the server's authentication one it does not accept, and `admit` every other one, first (this build authenticates nothing, so here `admit` refuses every one whose body parses). Nor do its **table names**, diff --git a/crates/core/src/error/mod.rs b/crates/core/src/error/mod.rs index 94b81c466..437de8ce2 100755 --- a/crates/core/src/error/mod.rs +++ b/crates/core/src/error/mod.rs @@ -402,9 +402,10 @@ fn message_key(error: &DynamoDbError) -> &'static str { /// /// Real DynamoDB validates request format before authentication. The message /// is `Start of structure or map found where not expected: ` followed by the -/// `Display` text of the `serde_json` parse error. Every entry point that -/// parses a raw request body builds the error from this helper so a malformed -/// request gets the same answer on every transport. +/// `Display` text of the `serde_json` parse error. The engine's +/// `parse_request` builds its error from this helper. The HTTP server parses +/// a request body with its own parser (`crates/server/src/request_parse.rs`), +/// whose answer to a body can differ. #[doc(hidden)] #[must_use] pub fn malformed_body_error(error: &serde_json::Error) -> DynamoDbError { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 89a17ce65..e805e3dda 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -50,7 +50,7 @@ mod list_tables; #[cfg(feature = "partiql")] mod partiql; mod pre_dispatch; -pub use pre_dispatch::{ParsedRequest, parse_request}; +pub use pre_dispatch::{KnownOperation, ParsedRequest, check_operation, parse_request}; // `private_fs` creates the private directories the filesystem-backed // import/export use; it has no wasm32 consumer and uses unix/windows file // APIs, so it is compiled only off wasm. @@ -119,8 +119,8 @@ use extenddb_core::types::TableKeyInfo; /// /// Real `DynamoDB` validates the operation name before checking authentication. /// An unknown operation with no auth headers returns `UnknownOperationException`, -/// not `MissingAuthenticationToken`. `parse_request` applies this check, and -/// the server calls it before auth. +/// not `MissingAuthenticationToken`. `check_operation` applies this check: +/// the server calls it before auth, and `parse_request` calls it first. #[must_use] pub fn is_known_operation(operation: &str) -> bool { matches!( diff --git a/crates/engine/src/pre_dispatch.rs b/crates/engine/src/pre_dispatch.rs index 49c56ee71..328f6bb59 100644 --- a/crates/engine/src/pre_dispatch.rs +++ b/crates/engine/src/pre_dispatch.rs @@ -3,28 +3,54 @@ //! The request checks the engine owns, which every entry point calls in one //! order before it dispatches a request into the engine: the operation name, -//! the body parse, and the refusal of point-in-time recovery. +//! then the refusal of point-in-time recovery, with the entry point's parse of +//! the body between them. //! -//! An entry point (the HTTP server, the WebAssembly adapter) calls -//! [`parse_request`] with the operation name and the raw request body, then -//! calls [`ParsedRequest::admit`] on the result to get the body it passes to -//! [`crate::dispatch`]. A check that every request the engine dispatches must -//! pass belongs in one of the two steps: a check that an entry point makes -//! itself reaches only the requests that come through that entry point. +//! An entry point calls [`check_operation`] with the operation name, parses +//! the raw request body, passes the parsed body to +//! [`KnownOperation::with_body`], and calls [`ParsedRequest::admit`] on the +//! result to get the body it passes to [`crate::dispatch`]. [`parse_request`] +//! is `check_operation` and a `serde_json` parse of the body in one call. The +//! WebAssembly adapter calls `parse_request(..)?.admit()`. The HTTP server +//! calls `check_operation` before it parses the body, parses the body with +//! its own parser (`crates/server/src/request_parse.rs`, which bounds the +//! nesting depth and checks the syntax of a deep body before +//! authentication), and calls `with_body(..).admit()` after it authenticates +//! the caller. //! -//! The types fix the order of the two steps: `admit` is a method of -//! [`ParsedRequest`], which only `parse_request` constructs, so `admit` runs -//! only on a request whose operation is known and whose body parsed. The -//! refusal `admit` applies, [`crate::refuse_point_in_time_recovery`], is also -//! public on its own and checks whatever body it is given. +//! A check that every request the engine dispatches must pass belongs in +//! `check_operation` or in `admit`. A check that an entry point makes itself, +//! its parse of the body included, reaches only the requests that come +//! through that entry point. +//! +//! The types fix the order of the steps: `admit` is a method of +//! [`ParsedRequest`], which only `with_body` constructs, and `with_body` is a +//! method of [`KnownOperation`], which only `check_operation` constructs. So +//! `admit` runs only on a request whose operation is known, with the body the +//! entry point parsed. The refusal `admit` applies, +//! [`crate::refuse_point_in_time_recovery`], is also public on its own and +//! checks whatever body it is given. use extenddb_core::error::{DynamoDbError, malformed_body_error}; use serde_json::Value; +/// An operation name the engine dispatches. +/// +/// Returned by [`check_operation`]; [`KnownOperation::with_body`] pairs it +/// with the parsed request body. +// Public for the HTTP server's `handle_request`, not for other users of the +// crate. +#[doc(hidden)] +#[derive(Debug)] +pub struct KnownOperation<'a> { + operation: &'a str, +} + /// A request whose operation name is known and whose body parsed as JSON. /// -/// Returned by [`parse_request`]; [`ParsedRequest::admit`] applies the -/// refusals that follow and yields the body to dispatch. +/// Returned by [`KnownOperation::with_body`] and [`parse_request`]; +/// [`ParsedRequest::admit`] applies the refusals that follow and yields the +/// body to dispatch. // Public for its two callers, the HTTP server's `handle_request` and the // WebAssembly adapter's `Engine::dispatch`, not for other users of the crate. #[doc(hidden)] @@ -34,31 +60,61 @@ pub struct ParsedRequest<'a> { body: Value, } -/// The first step: check that `operation` is one the engine dispatches, then -/// parse `body` as JSON. +/// The first step: check that `operation` is one the engine dispatches. +/// +/// An unknown operation answers `UnknownOperationException` whatever the +/// body, so an entry point calls this before it parses the body. The check +/// does not read the caller's identity, so the server calls it before it +/// authenticates the request: real `DynamoDB` answers an unknown operation +/// before it checks authentication. +/// +/// # Errors +/// +/// `UnknownOperationException` for an operation the engine does not +/// dispatch. +// Public for the HTTP server's `handle_request`, not for other users of the +// crate. +#[doc(hidden)] +pub fn check_operation(operation: &str) -> Result, DynamoDbError> { + if crate::is_known_operation(operation) { + Ok(KnownOperation { operation }) + } else { + Err(DynamoDbError::UnknownOperationException(String::new())) + } +} + +/// [`check_operation`], then a parse of `body` as JSON with `serde_json`'s +/// defaults. /// /// An unknown operation answers `UnknownOperationException` even when the /// body is also malformed, and a body that does not parse answers the -/// `SerializationException` of [`malformed_body_error`]. Neither reads the -/// caller's identity, so the server calls this before it authenticates the -/// request: real `DynamoDB` answers both before it checks authentication. +/// `SerializationException` of [`malformed_body_error`]. /// /// # Errors /// /// `UnknownOperationException` for an operation the engine does not /// dispatch; `SerializationException` for a body that does not parse as JSON. -// Public for its two callers, the HTTP server's `handle_request` and the -// WebAssembly adapter's `Engine::dispatch`, not for other users of the crate. +// Public for the WebAssembly adapter's `Engine::dispatch`, not for other users +// of the crate. #[doc(hidden)] pub fn parse_request<'a>( operation: &'a str, body: &[u8], ) -> Result, DynamoDbError> { - if !crate::is_known_operation(operation) { - return Err(DynamoDbError::UnknownOperationException(String::new())); - } + let operation = check_operation(operation)?; let body = serde_json::from_slice(body).map_err(|e| malformed_body_error(&e))?; - Ok(ParsedRequest { operation, body }) + Ok(operation.with_body(body)) +} + +impl<'a> KnownOperation<'a> { + /// Pair the operation with the request body the entry point parsed. + #[must_use] + pub fn with_body(self, body: Value) -> ParsedRequest<'a> { + ParsedRequest { + operation: self.operation, + body, + } + } } impl ParsedRequest<'_> { diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 53368dde0..841af804e 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -85,13 +85,15 @@ pub(crate) async fn handle_request( // --- Pre-auth operation validation --- // Real DynamoDB validates the operation name before checking authentication. - // An unknown operation returns UnknownOperationException even without auth headers. - if !extenddb_engine::is_known_operation(&operation) { - return error_response( - &DynamoDbError::UnknownOperationException(String::new()), - &request_id, - ); - } + // An unknown operation returns UnknownOperationException even without auth + // headers. `extenddb_engine::check_operation` is the first of the engine's + // two steps, and `admit` below is the second; the module doc of + // extenddb-engine's `src/pre_dispatch.rs` says which checks belong in the + // engine rather than here. + let known_operation = match extenddb_engine::check_operation(&operation) { + Ok(known_operation) => known_operation, + Err(e) => return error_response(&e, &request_id), + }; // --- Pre-auth body validation --- // The service checks the request's JSON syntax before authentication at @@ -141,20 +143,24 @@ pub(crate) async fn handle_request( } }; - // Point-in-time recovery is not in this release: a restore and an enable - // are refused here, for every caller and before any table is read, where - // the service would authorize them first. - if let Some(e) = extenddb_engine::refuse_point_in_time_recovery(&operation, &input) { - tracing::warn!( - request_id = %request_id, - operation = %operation, - principal = crate::authz_resource::cross_account::principal_arn(&identity), - "Point-in-time recovery refused" - ); - record_error_metrics(&state.metrics, &e, &account_id, None, &operation); - state.metrics.record_request_count(&account_id, &operation); - return error_response(&e, &request_id); - } + // Point-in-time recovery is not in this release: `admit` refuses a restore + // and an enable here, for every caller and before any table is read, where + // the service would authorize them first. The point-in-time refusal is the + // only one `admit` makes, so the log line names it. + let input: Value = match known_operation.with_body(input).admit() { + Ok(input) => input, + Err(e) => { + tracing::warn!( + request_id = %request_id, + operation = %operation, + principal = crate::authz_resource::cross_account::principal_arn(&identity), + "Point-in-time recovery refused" + ); + record_error_metrics(&state.metrics, &e, &account_id, None, &operation); + state.metrics.record_request_count(&account_id, &operation); + return error_response(&e, &request_id); + } + }; // --- Authz segment --- let authz_start = std::time::Instant::now(); diff --git a/crates/wasm-adapter/src/runtime.rs b/crates/wasm-adapter/src/runtime.rs index b3b0f5566..3919b040b 100644 --- a/crates/wasm-adapter/src/runtime.rs +++ b/crates/wasm-adapter/src/runtime.rs @@ -25,8 +25,10 @@ //! before the body is parsed, so a body that does not parse gets it too, //! where the server answers `SerializationException`. //! 2. It runs `extenddb_engine::parse_request` and `ParsedRequest::admit`, the -//! pre-dispatch checks the server applies too (the server also -//! authenticates between them; this build authenticates no request). +//! engine's pre-dispatch checks. The server makes the operation name check +//! of `parse_request` (`extenddb_engine::check_operation`) and `admit` too, +//! parses the body with its own parser between them, and authenticates the +//! caller before `admit`; this build authenticates no request. //! 3. It passes the request to [`extenddb_engine::dispatch`], with no backup //! store and no import or export paths configured. //! @@ -41,9 +43,11 @@ //! (`handle_request` in `crates/server/src/handler.rs`) and its authorization //! (`authorize_request` in `crates/server/src/request_helpers.rs`) check it. //! Of the server's checks, [`Engine::dispatch`] runs only the two the engine -//! owns, `extenddb_engine::parse_request` and `ParsedRequest::admit`, and runs -//! neither for an operation [`unsupported_reason`] names, which it refuses -//! first. A request one of the others would refuse gets the answer +//! owns, the operation name check and `ParsedRequest::admit`, which it runs +//! through `extenddb_engine::parse_request`, and runs neither for an +//! operation [`unsupported_reason`] names, which it refuses first. It parses +//! the body with `parse_request`, where the server parses it with its own +//! parser. A request one of the others would refuse gets the answer //! this build gives it anyway: the engine handler's for the operation, or one //! of the refusals above. The README section "Checks the server makes that //! this build does not" describes the others, with the server's answer and @@ -177,12 +181,13 @@ impl Engine { return Err(unsupported(operation, reason)); } - // The engine's own pre-dispatch checks, which the server calls too, in - // the engine's order: the operation name, then the body parse, then the - // engine's refusals of requests no deployment serves (point-in-time - // recovery). The server authenticates between the first two steps and - // the last, and makes its other checks (see the module doc) around - // them; this build authenticates no request and makes none of those. + // The engine's own pre-dispatch checks, in the engine's order: the + // operation name, then the body parse, then the engine's refusals of + // requests no deployment serves (point-in-time recovery). The server + // makes the first and the last too, with its own parse of the body + // between them. It authenticates before the last, and makes its other + // checks (see the module doc) around them; this build authenticates no + // request and makes none of those. let body = extenddb_engine::parse_request(operation, body_json.as_bytes())?.admit()?; let ctx = self.operation_context(); From 027483d86443113b90adbf937f47d613d46cd2ba Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:42:39 +0000 Subject: [PATCH 14/15] docs(wasm): say that admit runs on the result of parse_request The adapter's module doc said that Engine::dispatch runs the operation name check and ParsedRequest::admit through extenddb_engine::parse_request. Of the two, only the name check runs in parse_request. dispatch calls admit on the ParsedRequest that parse_request returns. The sentence now says so. --- crates/wasm-adapter/src/runtime.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/wasm-adapter/src/runtime.rs b/crates/wasm-adapter/src/runtime.rs index 3919b040b..d09f0f5e9 100644 --- a/crates/wasm-adapter/src/runtime.rs +++ b/crates/wasm-adapter/src/runtime.rs @@ -43,15 +43,15 @@ //! (`handle_request` in `crates/server/src/handler.rs`) and its authorization //! (`authorize_request` in `crates/server/src/request_helpers.rs`) check it. //! Of the server's checks, [`Engine::dispatch`] runs only the two the engine -//! owns, the operation name check and `ParsedRequest::admit`, which it runs -//! through `extenddb_engine::parse_request`, and runs neither for an -//! operation [`unsupported_reason`] names, which it refuses first. It parses -//! the body with `parse_request`, where the server parses it with its own -//! parser. A request one of the others would refuse gets the answer -//! this build gives it anyway: the engine handler's for the operation, or one -//! of the refusals above. The README section "Checks the server makes that -//! this build does not" describes the others, with the server's answer and -//! this build's. +//! owns, the operation name check, which it runs through +//! `extenddb_engine::parse_request`, and `ParsedRequest::admit`, and runs +//! neither for an operation [`unsupported_reason`] names, which it refuses +//! first. It parses the body with `parse_request`, where the server parses +//! it with its own parser. A request one of the others would refuse gets +//! the answer this build gives it anyway: the engine handler's for the +//! operation, or one of the refusals above. The README section "Checks the +//! server makes that this build does not" describes the others, with the +//! server's answer and this build's. use std::collections::HashMap; use std::path::PathBuf; From 71b3e1b6dcd1b1ad79fea3ee3408c549ee5f6f71 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:24:47 +0000 Subject: [PATCH 15/15] test(server): pin the edges of the syntax check's looser rules No row held the edges of two of the looser rules of the check before authentication. A check that took any printable byte after \u, dropped + from the number bytes, or let a number start with + or . passed the unit tests and the wire file. New rows sit at 63 and at 20000 wrappers, in the syntax tests of request_parse.rs and in tests/test_request_nesting_depth.py: - The numbers 1+, 1e+5 and 1.eE-+ and the escape \ugggg reach authentication. The + is a number byte, and g is the highest byte the service takes after \u. - The check refuses the numbers +1 and .5 and the escapes \u000/ and \u000h before authentication. A number starts with - or a digit, and / and h are the bytes on either side of 0 to g. The service answers the first four with a MissingAuthenticationTokenException unsigned and an InvalidSignatureException badly signed. It answers the last four with a SerializationException that has no message, unsigned and badly signed. Each answer held on 2 of 2 sends per body and signing (us-east-1, 2026-11-25). --- crates/server/src/request_parse.rs | 35 ++++++++++++++++++++++------- tests/test_request_nesting_depth.py | 33 ++++++++++++++++++++------- 2 files changed, 52 insertions(+), 16 deletions(-) diff --git a/crates/server/src/request_parse.rs b/crates/server/src/request_parse.rs index efe7c62d2..4233652cf 100644 --- a/crates/server/src/request_parse.rs +++ b/crates/server/src/request_parse.rs @@ -209,13 +209,16 @@ mod tests { body } - /// The leaves the service's check before authentication passes where - /// `serde_json`'s grammar refuses them (measured 2026-11-24, us-east-1, at - /// 63 and 20000 wrappers: unsigned, each is a + /// The leaves the service's check before authentication passes (measured + /// in us-east-1 at 63 and 20000 wrappers: unsigned, each is a /// `MissingAuthenticationTokenException`, and badly signed an - /// `InvalidSignatureException`): the numbers `01`, `1.`, `1e` and `-`, the - /// escape `\u12G4`, and FF, NUL and VT before a value. - const LOOSE_LEAVES: [&[u8]; 8] = [ + /// `InvalidSignatureException`). On 2026-11-24: the numbers `01`, `1.`, + /// `1e` and `-`, the escape `\u12G4`, and FF, NUL and VT before a value, + /// which `serde_json`'s grammar refuses. On 2026-11-25, at the edges of the + /// looser rules: the numbers `1+`, `1e+5` and `1.eE-+`, whose `+` is a + /// number byte, and the escape `\ugggg`, whose `g` is the highest byte the + /// service takes after `\u`. + const LOOSE_LEAVES: [&[u8]; 12] = [ br#"{"S":01}"#, br#"{"S":1.}"#, br#"{"S":1e}"#, @@ -224,6 +227,10 @@ mod tests { b"{\"S\":\x0c\"leaf\"}", b"{\"S\":\x00\"leaf\"}", b"{\"S\":\x0b\"leaf\"}", + br#"{"S":1+}"#, + br#"{"S":1e+5}"#, + br#"{"S":1.eE-+}"#, + br#"{"S":"le\uggggaf"}"#, ]; fn parse(body: &[u8]) -> Result { @@ -411,7 +418,10 @@ mod tests { // control byte and the unknown escape in a string on 2026-11-20, // unsigned, badly signed and signed; the `\u` before the closing // quote, SOH before a value, `tru`, the missing colon and the missing - // comma on 2026-11-24, unsigned and badly signed). Within the ceiling + // comma on 2026-11-24, unsigned and badly signed; at 63 and 20000 + // wrappers, a number that starts with `+` or `.`, and `/` and `h`, + // the bytes on either side of the range the service takes after + // `\u`, on 2026-11-25, unsigned and badly signed). Within the ceiling // the check's refusal carries the server's wording, and past it no // message. The unclosed rows of exactly 5200 and 5201 openers pin // that boundary. The check does not recurse, so the rows run on the @@ -433,6 +443,14 @@ mod tests { deep_body_with_leaf(200, br#"{"S":"leaf" "T":"x"}"#), deep_body_with_leaf(200, b"{\"S\":\"le\x01af\"}"), deep_body_with_leaf(200, br#"{"S":"le\qaf"}"#), + deep_body_with_leaf(63, br#"{"S":+1}"#), + deep_body_with_leaf(20000, br#"{"S":+1}"#), + deep_body_with_leaf(63, br#"{"S":.5}"#), + deep_body_with_leaf(20000, br#"{"S":.5}"#), + deep_body_with_leaf(63, br#"{"S":"le\u000/af"}"#), + deep_body_with_leaf(20000, br#"{"S":"le\u000/af"}"#), + deep_body_with_leaf(63, br#"{"S":"le\u000haf"}"#), + deep_body_with_leaf(20000, br#"{"S":"le\u000haf"}"#), ]; for body in &rows { let depth = nesting_depth(body); @@ -456,7 +474,8 @@ mod tests { // an invalid UTF-8 byte in a string and a lone surrogate escape // (measured 2026-11-19, us-east-1: unsigned, each is a // MissingAuthenticationTokenException), and each leaf of - // `LOOSE_LEAVES` at 63 and at 20000 wrappers (measured 2026-11-24). + // `LOOSE_LEAVES` at 63 and at 20000 wrappers (measured 2026-11-24 and + // 2026-11-25). // This runs on the default test-thread stack, where a parse that // recursed a million levels would overflow, so it also shows that the // check does not recurse. diff --git a/tests/test_request_nesting_depth.py b/tests/test_request_nesting_depth.py index 668fd8d61..bff2e6eb7 100644 --- a/tests/test_request_nesting_depth.py +++ b/tests/test_request_nesting_depth.py @@ -53,11 +53,14 @@ SERIALIZATION_TYPE = "com.amazon.coral.service#SerializationException" LEAF = '{"S":"leaf"}' -# Leaves the service's check before authentication passes where JSON's grammar -# refuses them: the numbers `01`, `1.`, `1e` and `-`, the escape `\u12G4`, and -# form feed, NUL and vertical tab before a value (us-east-1, 2026-11-24, at 63 -# and 20000 wrappers, 2 of 2 sends each: unsigned +# Leaves the service's check before authentication passes (us-east-1, at 63 and +# 20000 wrappers, 2 of 2 sends each: unsigned # MissingAuthenticationTokenException, badly signed InvalidSignatureException). +# On 2026-11-24, leaves JSON's grammar refuses: the numbers `01`, `1.`, `1e` and +# `-`, the escape `\u12G4`, and form feed, NUL and vertical tab before a value. +# On 2026-11-25, the edges of the looser rules: the numbers `1+`, `1e+5` and +# `1.eE-+`, whose `+` is a number byte, and the escape `\ugggg`, whose `g` is +# the highest byte the service takes after `\u`. LOOSE_LEAVES = { "number-01": '{"S":01}', "number-1.": '{"S":1.}', @@ -67,6 +70,10 @@ "form-feed-before-value": '{"S":\x0c"leaf"}', "nul-before-value": '{"S":\x00"leaf"}', "vertical-tab-before-value": '{"S":\x0b"leaf"}', + "number-1+": '{"S":1+}', + "number-1e+5": '{"S":1e+5}', + "number-1.eE-+": '{"S":1.eE-+}', + "escape-ugggg": '{"S":"le\\uggggaf"}', } @@ -270,6 +277,14 @@ def _unauthenticated_put(dynamodb_client, endpoint_url, body: bytes, signing: st pytest.param(200, '{"S":"leaf" "T":"x"}', id="missing-comma"), pytest.param(200, '{"S":"le\x01af"}', id="control-byte-in-string"), pytest.param(200, '{"S":"le\\qaf"}', id="unknown-escape"), + pytest.param(63, '{"S":+1}', id="plus-sign-63"), + pytest.param(20000, '{"S":+1}', id="plus-sign-20000"), + pytest.param(63, '{"S":.5}', id="point-first-63"), + pytest.param(20000, '{"S":.5}', id="point-first-20000"), + pytest.param(63, '{"S":"le\\u000/af"}', id="escape-u000-slash-63"), + pytest.param(20000, '{"S":"le\\u000/af"}', id="escape-u000-slash-20000"), + pytest.param(63, '{"S":"le\\u000haf"}', id="escape-u000h-63"), + pytest.param(20000, '{"S":"le\\u000haf"}', id="escape-u000h-20000"), ], ) def test_a_malformed_deep_body_is_refused_before_authentication( @@ -280,8 +295,10 @@ def test_a_malformed_deep_body_is_refused_before_authentication( # without its last byte, or the fault in the leaf. The service answers # each with a 400 SerializationException, unsigned and badly signed (2 of 2 # sends per body and signing, us-east-1: the first five rows 2026-11-19, - # the control byte and the unknown escape 2026-11-20, the other five - # 2026-11-24). + # the control byte and the unknown escape 2026-11-20, the other five at 200 + # wrappers 2026-11-24, and the last eight 2026-11-25: a number that starts + # with `+` or `.`, and `/` and `h`, the bytes on either side of the range + # the service takes after `\u`). if wrappers is None: body = b"x" + b"[" * 6000 elif leaf is None: @@ -323,8 +340,8 @@ def test_a_complete_deep_body_reaches_authentication( # leaf of LOOSE_LEAVES: unsigned, each body is # MissingAuthenticationTokenException, and badly signed # InvalidSignatureException (2 of 2 sends each, us-east-1, 2026-11-19 for - # the first four rows and 2026-11-24 for the rest). ExtendDB's type for the - # first is MissingAuthenticationToken (#1075). + # the first four rows, and for the rest the dates LOOSE_LEAVES gives). + # ExtendDB's type for the first is MissingAuthenticationToken (#1075). body = _raw_put_body(table, "unauthenticated", wrappers, leaf) + tail resp = _unauthenticated_put(dynamodb_client, endpoint_url, body, signing) assert resp.status_code == 400, resp.text