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/app/src/cmd_serve.rs b/crates/app/src/cmd_serve.rs index 5ae4e2d5e..05cdeae37 100755 --- a/crates/app/src/cmd_serve.rs +++ b/crates/app/src/cmd_serve.rs @@ -290,6 +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() + // 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 it 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/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/Cargo.toml b/crates/server/Cargo.toml index 4b49f73d5..9008b1a72 100755 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -39,7 +39,7 @@ hyper = { workspace = true } hyper-util = { 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 3a5091cc0..841af804e 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -83,19 +83,40 @@ pub(crate) async fn handle_request( Err(e) => return error_response(&e, &request_id), }; - // --- Pre-auth request checks --- - // Real DynamoDB validates the operation name, then the request format - // (empty body, invalid JSON), before checking authentication: an unknown - // operation returns UnknownOperationException even without auth headers, - // and a malformed request gets 400 regardless of auth state. - // `extenddb_engine::parse_request` makes both checks, in that order; the - // module doc of extenddb-engine's `src/pre_dispatch.rs` says which checks - // belong in the engine rather than here. - let request = match extenddb_engine::parse_request(&operation, &body) { - Ok(request) => request, + // --- Pre-auth operation validation --- + // Real DynamoDB validates the operation name before checking authentication. + // 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 + // 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 + }; + // --- Auth segment --- let auth_start = std::time::Instant::now(); let identity = match state.auth.authenticate(&headers, &body).await { @@ -105,6 +126,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, .. } => { @@ -116,7 +147,7 @@ pub(crate) async fn handle_request( // 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 request.admit() { + let input: Value = match known_operation.with_body(input).admit() { Ok(input) => input, Err(e) => { tracing::warn!( diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index c80ccde4c..8fa62d404 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -30,6 +30,8 @@ mod registration; mod repeated_headers; mod request_attributes; mod request_helpers; +mod request_parse; +mod request_syntax; mod request_tags; mod response; mod serve; @@ -37,6 +39,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, @@ -145,6 +148,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 new file mode 100644 index 000000000..4233652cf --- /dev/null +++ b/crates/server/src/request_parse.rs @@ -0,0 +1,502 @@ +// 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 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 +//! 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 ([`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 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_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 has no fixed ceiling. A PutItem whose attribute is up to +/// 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`; 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). +/// 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 +/// 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). 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; + +/// 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 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. +/// +/// 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 { + 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 depth; + } + deepest = deepest.max(depth); + } + b'}' | b']' => depth = depth.saturating_sub(1), + _ => {} + } + } + deepest +} + +/// 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], depth: usize) -> Result { + if depth > MAX_REQUEST_JSON_DEPTH { + return Err(over_ceiling_refusal()); + } + // 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) +} + +/// Check the JSON syntax of a request body whose [`nesting_depth`] is `depth` +/// without building it, so the handler can refuse a malformed body nested past +/// [`UNAUTHENTICATED_PARSE_DEPTH`] before authentication, as the service does. +/// [`crate::request_syntax::skip_value`] reads the body's first value in one +/// loop that keeps the closers of the open containers on a heap stack, so the +/// check does not recurse at any depth. +/// +/// The check reads one JSON value with the grammar +/// [`crate::request_syntax::skip_value`] describes. +/// Bytes after a complete body, an invalid UTF-8 byte in a string and a lone +/// surrogate escape pass it (measured 2026-11-19, us-east-1: unsigned, each is +/// a `MissingAuthenticationTokenException`). So do the numbers `01`, `1.`, +/// `1e` and `-`, the escape `\u12G4`, and NUL, VT and FF between tokens +/// (measured 2026-11-24, us-east-1, at 63 and 20000 wrappers: unsigned, each +/// is a `MissingAuthenticationTokenException`, and badly signed an +/// `InvalidSignatureException`). A body that fails it gets a +/// `SerializationException`, with no message past the ceiling, as from +/// [`parse_request_value`], and with the server's usual wording within it. +pub(crate) fn check_request_syntax(body: &[u8], depth: usize) -> Result<(), DynamoDbError> { + crate::request_syntax::skip_value(body).map_err(|fault| { + if depth > MAX_REQUEST_JSON_DEPTH { + over_ceiling_refusal() + } else { + serialization_error(fault) + } + }) +} + +/// 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!( + "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"} ... }}`. Its + /// structural depth is `3 + 2 * wrappers`. + fn deep_body(wrappers: usize) -> Vec { + 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 { + body.extend_from_slice(br#"{"M":{"n":"#); + } + body.extend_from_slice(leaf); + for _ in 0..wrappers { + body.extend_from_slice(b"}}"); + } + body.extend_from_slice(b"}}"); + body + } + + /// 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`). 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}"#, + br#"{"S":-}"#, + br#"{"S":"le\u12G4af"}"#, + 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 { + 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(&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(&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_exactly() { + // Scan only (no parse), so this is safe at any depth on the test stack. + // 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, 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() + ); + } + } + + #[test] + fn matches_serde_for_a_shallow_body() { + let body = br#"{"TableName":"t","Item":{"pk":{"S":"a"}}}"#; + let value = parse(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(&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(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 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 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"#] { + let err = parse(body).unwrap_err(); + assert!(matches!(err, DynamoDbError::SerializationException(_))); + assert_eq!(err.message(), expected_message(body), "{body:?}"); + } + } + + #[test] + 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 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"); + 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); + } + + #[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 the stack a request handling thread must have. + let body = deep_body(2000); + std::thread::Builder::new() + .stack_size(REQUEST_WORKER_STACK_SIZE) + .spawn(move || { + let value = parse(&body).expect("2000 wrappers must parse"); + assert!(value.get("Item").is_some()); + }) + .unwrap() + .join() + .unwrap(); + } + + /// `deep_body(wrappers)` without its last byte. + fn truncated_body(wrappers: usize) -> Vec { + let mut body = deep_body(wrappers); + body.pop(); + body + } + + #[test] + 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 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; 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 + // default test-thread 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), + [&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}"#), + 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"}"#), + 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); + 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. + // 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), and each leaf of + // `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. + 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(), + 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()); + assert!( + check_request_syntax(body, depth).is_ok(), + "{} bytes", + body.len() + ); + } + } +} 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"), + } + } + } +} diff --git a/crates/server/src/serve.rs b/crates/server/src/serve.rs index 788593630..fa5f97657 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 diff --git a/crates/wasm-adapter/src/runtime.rs b/crates/wasm-adapter/src/runtime.rs index b3b0f5566..d09f0f5e9 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,13 +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, `extenddb_engine::parse_request` and `ParsedRequest::admit`, and runs +//! 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. 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. +//! 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; @@ -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(); diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index b3569ef53..f97be7c82 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -63,7 +63,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). 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 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..bff2e6eb7 --- /dev/null +++ b/tests/test_request_nesting_depth.py @@ -0,0 +1,355 @@ +# 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 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. + +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). 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 + +import json +import sys +import time + +import boto3 +import pytest +import requests +from botocore.exceptions import ClientError + +from conftest import scoped_table +from raw_signed_request import signed_post + +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" +LEAF = '{"S":"leaf"}' + +# 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.}', + "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"}', + "number-1+": '{"S":1+}', + "number-1e+5": '{"S":1e+5}', + "number-1.eE-+": '{"S":1.eE-+}', + "escape-ugggg": '{"S":"le\\uggggaf"}', +} + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + with scoped_table(dynamodb_client) as name: + 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"}}}`.""" + 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, leaf: str = LEAF) -> bytes: + """A PutItem body whose `data` attribute is `wrappers` single-key maps around + `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) + + ',"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. + + 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() + 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: + 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. + 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, 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. + 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, 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)) + assert err["Code"] == "ValidationException", err + assert NEST in err["Message"], err + + +@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'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 + + +@pytest.mark.parametrize("wrappers", [2000, 2598]) +def test_a_body_in_the_varying_band_gets_one_of_the_two_answers( + dynamodb_client, table, wrappers +): + # 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() + 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 (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 + 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, + ) + + +@pytest.mark.parametrize("signing", ["unsigned", "bad-signature"]) +@pytest.mark.parametrize( + "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"), + 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( + dynamodb_client, endpoint_url, table, wrappers, leaf, signing +): + # Each body nests past the 127 levels ExtendDB parses before + # 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 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: + 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() + assert err["__type"] == SERIALIZATION_TYPE, resp.text + 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 + # message field. + assert "message" not in err, resp.text + + +@pytest.mark.parametrize("signing", ["unsigned", "bad-signature"]) +@pytest.mark.parametrize( + "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, 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, 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 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 + expected = ( + "MissingAuthenticationToken" + if signing == "unsigned" + else "InvalidSignatureException" + ) + assert resp.json()["__type"].startswith( + f"com.amazon.coral.service#{expected}" + ), resp.text