From aa1c8b0a8287b49c6ba9c701c0471941b0495c3f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:51:02 +0000 Subject: [PATCH 1/9] fix(core): read a B value with its padding left out or cut short ExtendDB decoded a B value or a BS member with a decoder that requires the "=" padding. It refused YQ, YQ=, YWJjZA and YWJjZA= with a SerializationException. DynamoDB reads them, in an item and in an expression attribute value, and stores the bytes of the padded value. It refuses them in a PartiQL parameter, with the text of their length. DynamoDB refuses a value whose last character carries bits outside a whole byte, such as YR or YWJ, in both places. Measured in us-east-1 on 21 Nov 2026. decode_base64 now decodes with a padding mode that accepts the padding left out or cut short, and keeps the texts of a refusal. decode_padded_base64 keeps the decoder that requires the padding, and the checks of the PartiQL parameters call it. Both share one mapping of a refusal to its text. A value with "=" inside, such as Y=Q=, is #1307. Fixes #1258. --- crates/core/src/partiql/params.rs | 13 ++++++--- crates/core/src/types/attribute_value.rs | 36 ++++++++++++++++++++---- crates/core/src/types/mod.rs | 2 +- tests/test_binary_base64.py | 17 ++++++++--- 4 files changed, 54 insertions(+), 14 deletions(-) diff --git a/crates/core/src/partiql/params.rs b/crates/core/src/partiql/params.rs index dc1b867ae..679dfd8f6 100644 --- a/crates/core/src/partiql/params.rs +++ b/crates/core/src/partiql/params.rs @@ -51,7 +51,7 @@ use serde::Deserialize; use serde_json::{Map, Value}; use super::number::{check_number, parameter_message}; -use crate::types::{AttributeValue, decode_base64}; +use crate::types::{AttributeValue, decode_padded_base64}; use crate::validation::MAX_ITEM_NESTING_DEPTH; use crate::validation::number::validate_and_normalize_number; @@ -114,7 +114,7 @@ fn check_types(value: &Value) -> Result<(), String> { for (tag, payload) in typed_members(members) { match (tag, payload) { ("S" | "N", Value::String(_)) | ("NULL" | "BOOL", Value::Bool(_)) => {} - ("B", Value::String(text)) => drop(decode_base64(text)?), + ("B", Value::String(text)) => drop(decode_padded_base64(text)?), ("SS" | "NS", Value::Array(items)) => { if items .iter() @@ -126,7 +126,7 @@ fn check_types(value: &Value) -> Result<(), String> { ("BS", Value::Array(items)) => { for item in items { match item { - Value::String(text) => drop(decode_base64(text)?), + Value::String(text) => drop(decode_padded_base64(text)?), Value::Null => {} _ => return Err("BS member must be a base64 string".to_owned()), } @@ -597,10 +597,15 @@ mod tests { ), (deep_bool.as_str(), "BOOL value must be a boolean"), // A `B` value or a `BS` member the service cannot decode, with - // its text (measured 2026-11-20). + // its text (measured 2026-11-20). A parameter must carry its `=` + // padding, where an item may leave it out (measured 2026-11-21). ("[{\"B\":\"%%%\"}]", LENGTH_3), ("[{\"BS\":[\"%%%\"]}]", LENGTH_3), ("[{\"B\":\"AQ=\"}]", LENGTH_3), + ( + "[{\"B\":\"YWJjZA\"}]", + "Base64 encoded length is expected a multiple of 4 bytes but found: 6", + ), ("[{\"B\":\"!!!!\"}]", ""), ] { assert_eq!( diff --git a/crates/core/src/types/attribute_value.rs b/crates/core/src/types/attribute_value.rs index 7880cf93b..4c4ba5ac8 100755 --- a/crates/core/src/types/attribute_value.rs +++ b/crates/core/src/types/attribute_value.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64; +use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}; use serde::de::{self, MapAccess, Visitor}; use serde::ser::SerializeMap; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -80,10 +81,28 @@ const BASE64_TEXTS: [&str; 3] = [ "Invalid last non-pad Base64 character dectected", ]; -/// Decode the text of a `B` value or a `BS` member. +/// The decoder of a `B` value or a `BS` member outside a PartiQL parameter. +const UNPADDED: GeneralPurpose = GeneralPurpose::new( + &base64::alphabet::STANDARD, + GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent), +); + +/// Decode the text of a `B` value or a `BS` member. Measured 2026-11-21: the +/// service reads it with its `=` padding left out or cut short, in an item +/// and in an expression attribute value. pub fn decode_base64(text: &str) -> Result, String> { + decode_with(&UNPADDED, text) +} + +/// Decode the text of a `B` value or a `BS` member of a PartiQL parameter, +/// which must carry its `=` padding (measured 2026-11-21). +pub fn decode_padded_base64(text: &str) -> Result, String> { + decode_with(&BASE64, text) +} + +fn decode_with(engine: &GeneralPurpose, text: &str) -> Result, String> { let [too_short, length, last_character] = BASE64_TEXTS; - BASE64.decode(text).map_err(|_| match text.len() { + engine.decode(text).map_err(|_| match text.len() { 1 => too_short.to_owned(), 2 if text == "==" => String::new(), n if n % 4 != 0 => format!("{length}{n}"), @@ -736,8 +755,9 @@ mod tests { ); } - /// The service's answer to each `B` value (measured 2026-11-20): the - /// decoded bytes, or the text of the refusal, empty for no message. A + /// The service's answer to each `B` value (measured 2026-11-20, and + /// 2026-11-21 for the values with their padding left out or cut short): + /// the decoded bytes, or the text of the refusal, empty for no message. A /// `BS` member, and a value inside an `M` or an `L`, get the same text. #[test] fn a_value_that_is_not_base64_gets_the_service_text() { @@ -749,12 +769,17 @@ mod tests { }; let last = || Err("Invalid last non-pad Base64 character dectected".to_owned()); let none = || Err(String::new()); - let rows: [(&str, Result<&str, String>); 48] = [ + let rows: [(&str, Result<&str, String>); 54] = [ ("YWJj", Ok("abc")), ("YQ==", Ok("a")), ("YWE=", Ok("aa")), ("AA==", Ok("\0")), ("AAA=", Ok("\0\0")), + ("YQ", Ok("a")), + ("YQ=", Ok("a")), + ("YWJjZA", Ok("abcd")), + ("YWJjZA=", Ok("abcd")), + ("YWI", Ok("ab")), ("a", short()), ("Y", short()), ("!", short()), @@ -767,6 +792,7 @@ mod tests { ("===", length(3)), ("A==", length(3)), ("YR=", length(3)), + ("YWJ", length(3)), ("YQ==\n", length(5)), ("Y Q==", length(5)), ("abcde", length(5)), diff --git a/crates/core/src/types/mod.rs b/crates/core/src/types/mod.rs index b87d3a5ca..4a82ae8b0 100755 --- a/crates/core/src/types/mod.rs +++ b/crates/core/src/types/mod.rs @@ -13,7 +13,7 @@ mod table; mod transaction; mod warm_throughput; -pub use attribute_value::{AttributeValue, decode_base64, is_base64_refusal}; +pub use attribute_value::{AttributeValue, decode_base64, decode_padded_base64, is_base64_refusal}; pub use backup::{ BackupDescription, BackupDetails, BackupSummary, ContinuousBackupsDescription, GlobalSecondaryIndexInfo, LocalSecondaryIndexInfo, PointInTimeRecoveryDescription, diff --git a/tests/test_binary_base64.py b/tests/test_binary_base64.py index e881e71f3..c94ec08aa 100644 --- a/tests/test_binary_base64.py +++ b/tests/test_binary_base64.py @@ -9,10 +9,12 @@ too short, and a length that is not a multiple of 4 is named, except for "==", which gets no message. A value whose bytes ahead of its closing run of "=" are all base64 characters has an invalid last character, and any other -value gets no message. Every answer below was measured against the service -in us-east-1 on 2026-11-20, each request twice. The table does not exist, so -a value that decodes gets ResourceNotFoundException. boto3 encodes a binary -value itself, so the bodies go out as written. +value gets no message. An item and an expression attribute value may leave +the "=" padding out or cut it short; a PartiQL parameter may not. Every +answer below was measured against the service in us-east-1 on 2026-11-20 +and 2026-11-21, each request twice. The table does not exist, so a value +that decodes gets ResourceNotFoundException. boto3 encodes a binary value +itself, so the bodies go out as written. Dual-target: runs against the service and against extenddb with the same assertions. @@ -66,6 +68,13 @@ def statement(value: dict) -> tuple[str, str, dict]: (put({"B": "YWJj"}), NOT_FOUND), (put({"B": "YQ=="}), NOT_FOUND), (put({"B": "YWE="}), NOT_FOUND), + (put({"B": "YQ"}), NOT_FOUND), + (put({"B": "YQ="}), NOT_FOUND), + (put({"B": "YWJjZA"}), NOT_FOUND), + (put({"B": "YWJjZA="}), NOT_FOUND), + (put({"B": "YWJ"}), length(3)), + (query({"B": "YQ"}), NOT_FOUND), + (statement({"B": "YQ"}), length(2)), (put({"B": "a"}), SHORT), (put({"B": "Y"}), SHORT), (put({"B": "!"}), SHORT), From 1773e2df5fbea64969a5b89ecb7fbe154ec375dd Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:51:51 +0000 Subject: [PATCH 2/9] fix(engine): read an ImportTable B value only in the canonical form ImportTable reads each line of a DYNAMODB_JSON file with the attribute value deserializer of the requests. The previous commit makes that deserializer read a B value with its padding left out or cut short. So ImportTable read the B value YQ as the byte 0x61, where it refused the line before. DynamoDB's ImportTable refuses those values. Two imports of the same 18 files on 2026-11-22, one item per file, gave the same answers. Each import took the item whose B value is YQ==. It refused the items with these B values: YQ, YQ=, Y=Q=, =YQ=, Y-Q=, =A==, YWJjY=Q=, Y=Q, =Y==, =YQA, "Y Q=", Y, == and "Y=Q=\n". It also refused the BS values [Y=Q=, //Q=], [Y=Q=, =YQ=] and [YQ, YQ==]. Each import ended FAILED with ItemValidationError, ImportedItemCount 1 and ErrorCount 17. read_dynamodb_json now refuses a line with a B value or a BS member that is not canonical padded base64. This applies at any depth inside M and L values. The answer is the one the line had before the previous commit: Invalid DynamoDB item at line N. The imports measured values at the top level of the item only. Requests keep the new reading. Refs #1258. --- crates/engine/src/import_export_io.rs | 80 ++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/import_export_io.rs b/crates/engine/src/import_export_io.rs index 349117bcb..e1f1be638 100755 --- a/crates/engine/src/import_export_io.rs +++ b/crates/engine/src/import_export_io.rs @@ -9,6 +9,8 @@ use std::io::BufRead; use std::path::{Path, PathBuf}; use std::sync::Arc; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64; use serde_json::Value; use extenddb_core::error::DynamoDbError; @@ -33,6 +35,10 @@ pub(crate) fn read_items( } /// Read `DynamoDB` JSON format: one JSON object per line with `{"Item": {...}}` wrapper. +/// +/// The service's import reads a `B` value or a `BS` member only as canonical +/// padded base64 (measured 2026-11-22), and the item deserializer reads other +/// forms a request may send, so [`canonical_binaries`] checks the line first. fn read_dynamodb_json(reader: impl BufRead, max_items: u64) -> Result, DynamoDbError> { let mut items = Vec::new(); for (line_num, line) in reader.lines().enumerate() { @@ -56,12 +62,16 @@ fn read_dynamodb_json(reader: impl BufRead, max_items: u64) -> Result, parsed }; - let item: Item = serde_json::from_value(item_value).map_err(|_| { + let invalid_item = || { DynamoDbError::ValidationException(format!( "Invalid DynamoDB item at line {}", line_num + 1 )) - })?; + }; + if !canonical_binaries(&item_value) { + return Err(invalid_item()); + } + let item: Item = serde_json::from_value(item_value).map_err(|_| invalid_item())?; items.push(item); if u64::try_from(items.len()).unwrap_or(u64::MAX) > max_items { return Err(DynamoDbError::ValidationException(format!( @@ -72,6 +82,28 @@ fn read_dynamodb_json(reader: impl BufRead, max_items: u64) -> Result, Ok(items) } +/// Whether every `B` text and `BS` member in `value` decodes with `STANDARD`. +/// Matching member names is safe: a line that parses holds attribute values +/// there, and any other line is refused. `serde_json` caps the depth at 128. +fn canonical_binaries(value: &Value) -> bool { + match value { + Value::Object(members) => { + members + .iter() + .all(|(tag, payload)| match (tag.as_str(), payload) { + ("B", Value::String(text)) => BASE64.decode(text).is_ok(), + ("BS", Value::Array(set)) => set + .iter() + .filter_map(Value::as_str) + .all(|text| BASE64.decode(text).is_ok()), + _ => canonical_binaries(payload), + }) + } + Value::Array(items) => items.iter().all(canonical_binaries), + _ => true, + } +} + /// Read CSV format. fn read_csv( reader: impl BufRead, @@ -674,4 +706,48 @@ mod tests { ] ); } + + /// Measured on DynamoDB on 2026-11-22: an import of the first 18 values, + /// one line `{"Item": {"pk": {"S": ...}, "b": }}` each, imported + /// the `YQ==` line and refused every other line. The last two rows, a + /// value inside an `M` and an `L`, were not measured. + #[test] + fn import_reads_a_binary_only_in_the_canonical_form() { + let rows: [(&str, Option<&[u8]>); 20] = [ + (r#"{"B": "YQ=="}"#, Some(&[0x61])), + (r#"{"B": "YQ"}"#, None), + (r#"{"B": "YQ="}"#, None), + (r#"{"B": "Y=Q="}"#, None), + (r#"{"B": "=YQ="}"#, None), + (r#"{"B": "Y-Q="}"#, None), + (r#"{"B": "=A=="}"#, None), + (r#"{"B": "YWJjY=Q="}"#, None), + (r#"{"B": "Y=Q"}"#, None), + (r#"{"B": "=Y=="}"#, None), + (r#"{"B": "=YQA"}"#, None), + (r#"{"B": "Y Q="}"#, None), + (r#"{"B": "Y"}"#, None), + (r#"{"B": "=="}"#, None), + (r#"{"BS": ["Y=Q=", "//Q="]}"#, None), + (r#"{"BS": ["Y=Q=", "=YQ="]}"#, None), + (r#"{"BS": ["YQ", "YQ=="]}"#, None), + (r#"{"B": "Y=Q=\n"}"#, None), + (r#"{"M": {"b": {"B": "YQ"}}}"#, None), + (r#"{"L": [{"B": "YQ"}]}"#, None), + ]; + let wrong: Vec = rows + .into_iter() + .filter_map(|(value, bytes)| { + let line = format!(r#"{{"Item": {{"pk": {{"S": "row"}}, "b": {value}}}}}"#); + let got = read_dynamodb_json(line.as_bytes(), 10) + .map(|items| items[0]["b"].clone()) + .map_err(|e| message(&e)); + let want = bytes + .map(|bytes| AttributeValue::B(bytes.to_vec())) + .ok_or_else(|| "Invalid DynamoDB item at line 1".to_owned()); + (got != want).then(|| format!("{value}: {got:?}")) + }) + .collect(); + assert!(wrong.is_empty(), "{wrong:#?}"); + } } From 1fe5eff4db8cf17832b951c78fe9e677b1f7e67c Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:48:40 +0000 Subject: [PATCH 3/9] fix(engine): read a BatchWriteItem B value only with its padding An earlier commit of this branch makes the attribute value deserializer read a B value with no padding or with part of its padding. BatchWriteItem reads its request with that deserializer. So it accepted the B value YQ in a PutRequest item and in a DeleteRequest key, where it refused the value before. DynamoDB's BatchWriteItem reads a B value or a BS member only with its padding. Measured in us-east-1 on 2026-11-22, each request twice. The B value YQ in a PutRequest item gave a SerializationException. Its text was "Base64 encoded length is expected a multiple of 4 bytes but found: 2". YQ= gave the same text with 3, and the BS value [YQ] gave it with 2. The DeleteRequest key YQ and the PutRequest key Yg gave it with 2 too. BatchGetItem, TransactGetItems, GetItem, DeleteItem, TransactWriteItems and UpdateItem read the key or value YQ as the byte 0x61. handle_batch_write_item now checks the raw RequestItems with decode_padded_base64 ahead of the deserializer. That is the decoder of the PartiQL parameters. The answer is a SerializationException with the text of that decoder. The walk covers the RequestItems member only, and the deserializer reads the rest of the body as before. The walk over a body's B texts is the one the previous commit added for ImportTable. It moves to extenddb_core::types as check_binaries and takes the decoder as a parameter. ImportTable keeps the standard decoder. The requests of the other operations keep the deserializer's reading. Refs #1258. --- crates/core/src/types/attribute_value.rs | 35 ++++ crates/core/src/types/mod.rs | 4 +- crates/engine/src/batch_write_item.rs | 13 +- .../src/batch_write_item/padding_tests.rs | 161 ++++++++++++++++++ crates/engine/src/import_export_io.rs | 29 +--- 5 files changed, 215 insertions(+), 27 deletions(-) create mode 100644 crates/engine/src/batch_write_item/padding_tests.rs diff --git a/crates/core/src/types/attribute_value.rs b/crates/core/src/types/attribute_value.rs index 4c4ba5ac8..d6c76c7b3 100755 --- a/crates/core/src/types/attribute_value.rs +++ b/crates/core/src/types/attribute_value.rs @@ -124,6 +124,41 @@ pub fn is_base64_refusal(message: &str) -> bool { message.is_empty() || BASE64_TEXTS.iter().any(|text| message.starts_with(text)) } +/// Check every `B` text and `BS` member of a wire value with `decode`, at +/// any depth. An operation whose decoder is not the deserializer's calls it +/// on the raw JSON ahead of deserializing. Matching member names is safe: a +/// value that deserializes holds attribute values there, and any other value +/// is refused. A `B` or `BS` payload of another shape, such as the requests +/// of a table of that name, is walked. `serde_json` caps the depth at 128. +/// +/// # Errors +/// +/// The refusal of the first text `decode` refuses. +pub fn check_binaries( + value: &serde_json::Value, + decode: fn(&str) -> Result, E>, +) -> Result<(), E> { + use serde_json::Value; + match value { + Value::Object(members) => { + members + .iter() + .try_for_each(|(tag, payload)| match (tag.as_str(), payload) { + ("B", Value::String(text)) => decode(text).map(drop), + ("BS", Value::Array(set)) => set.iter().try_for_each(|member| match member { + Value::String(text) => decode(text).map(drop), + other => check_binaries(other, decode), + }), + _ => check_binaries(payload, decode), + }) + } + Value::Array(items) => items + .iter() + .try_for_each(|item| check_binaries(item, decode)), + _ => Ok(()), + } +} + impl<'de> Visitor<'de> for AttributeValueVisitor { type Value = AttributeValue; diff --git a/crates/core/src/types/mod.rs b/crates/core/src/types/mod.rs index 4a82ae8b0..f0cad005c 100755 --- a/crates/core/src/types/mod.rs +++ b/crates/core/src/types/mod.rs @@ -13,7 +13,9 @@ mod table; mod transaction; mod warm_throughput; -pub use attribute_value::{AttributeValue, decode_base64, decode_padded_base64, is_base64_refusal}; +pub use attribute_value::{ + AttributeValue, check_binaries, decode_base64, decode_padded_base64, is_base64_refusal, +}; pub use backup::{ BackupDescription, BackupDetails, BackupSummary, ContinuousBackupsDescription, GlobalSecondaryIndexInfo, LocalSecondaryIndexInfo, PointInTimeRecoveryDescription, diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index 3806e0e44..aba282ea5 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -13,7 +13,7 @@ use extenddb_core::expression::ExpressionMaps; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{ BatchWriteItemInput, BatchWriteItemOutput, Item, KeySchemaElement, ReturnItemCollectionMetrics, - TableKeyInfo, WriteRequest, extract_key, item_size_bytes, + TableKeyInfo, WriteRequest, check_binaries, decode_padded_base64, extract_key, item_size_bytes, }; use extenddb_core::validation::{ AttributeNameRequestForm, IndexKeyRef, validate_attribute_name_sizes, validate_batch_item_keys, @@ -45,6 +45,15 @@ pub async fn handle_batch_write_item( body: Value, ctx: &OperationContext, ) -> Result { + // The service reads a B value or a BS member of this operation only with + // its padding, in a PutRequest item and in a DeleteRequest key, and + // refuses one without it ahead of the rest of the request. Every other + // operation reads the padding left out or cut short (measured + // 2026-11-22), and so does the deserializer, so the raw RequestItems are + // checked with the decoder that requires the padding first. The other + // members of the body are the deserializer's. + check_binaries(&body["RequestItems"], decode_padded_base64) + .map_err(crate::serialization_exception)?; let input: BatchWriteItemInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; @@ -578,6 +587,8 @@ fn collect_icm_if_needed( } } +#[cfg(test)] +mod padding_tests; #[cfg(test)] mod scripted; #[cfg(test)] diff --git a/crates/engine/src/batch_write_item/padding_tests.rs b/crates/engine/src/batch_write_item/padding_tests.rs new file mode 100644 index 000000000..e3eaca9ef --- /dev/null +++ b/crates/engine/src/batch_write_item/padding_tests.rs @@ -0,0 +1,161 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Which operations read a `B` value with its padding left out or cut short. +//! Measured on the service in us-east-1 on 2026-11-22, each request twice, +//! on a table keyed on `pk` (S) and one keyed on `pk` (B): `BatchWriteItem` +//! refuses such a value, and such a `BS` member, in a `PutRequest` item and in +//! a `DeleteRequest` key with the text of its length, and every other +//! operation reads it as the padded value. The rows send each request through +//! [`dispatch`] and read a written item back with a `GetItem`. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::limits::LimitsConfig; +use extenddb_storage::server_components::ServerComponentsOptions; +use extenddb_storage_sqlite::SqliteConfig; + +use crate::{AuthorizedKeyInfo, BackupRuntime, OperationContext, dispatch}; + +/// The table keyed on `pk` (S), whose items are read back. +const S_TABLE: &str = "keyed-on-s"; +/// The table keyed on `pk` (B). +const B_TABLE: &str = "keyed-on-b"; + +/// The service's answer: the message of its `SerializationException`, or the +/// `B` text of the item read back, when the request writes one. +type Answer = Result, String>; + +fn length(n: usize) -> Answer { + Err(format!( + "Base64 encoded length is expected a multiple of 4 bytes but found: {n}" + )) +} + +fn stored(text: &str) -> Answer { + Ok(Some(text.to_owned())) +} + +fn batch(table: &str, request: Value) -> Value { + json!({"RequestItems": {table: [request]}}) +} + +fn put(item: Value) -> Value { + json!({"PutRequest": {"Item": item}}) +} + +/// An item of the S table: its row as the key and `b` as the value. +fn item(row: &str, b: Value) -> Value { + json!({"pk": {"S": row}, "b": b}) +} + +/// The key `YQ` of the B table. +fn b_key() -> Value { + json!({"pk": {"B": "YQ"}}) +} + +/// A context on a bootstrapped `SqliteEngine` in a scratch directory, in the +/// account it bootstrapped, creating its tables ACTIVE. The directory lives +/// as long as the returned guard. +async fn context() -> (OperationContext, TempDir) { + let dir = tempfile::tempdir().expect("a scratch directory"); + let config = SqliteConfig { + path: dir.path().join("catalog.sqlite").display().to_string(), + pool_size: 2, + }; + let mut options = ServerComponentsOptions::default(); + options.bootstrap_if_uninitialized = true; + options.release = "test"; + let components = + (extenddb_storage_sqlite::backend().server_components)(&config, "us-east-1", options) + .await + .unwrap_or_else(|e| panic!("server components: {e:?}")); + let account_id = components + .catalog_store + .default_account_id() + .await + .expect("the catalog is read") + .expect("the bootstrapped account"); + components + .catalog_store + .set_setting("control_plane_delay_seconds", "0") + .await + .expect("the delay is set"); + let ctx = OperationContext { + storage: components.engine, + backup: Arc::new(BackupRuntime::new(1)), + limits: Arc::new(LimitsConfig::default()), + region: Arc::from("us-east-1"), + account_id: Arc::from(account_id), + import_paths: Arc::from(Vec::new()), + export_paths: Arc::from(Vec::new()), + authorized_key_info: AuthorizedKeyInfo::new(), + auth_cache: extenddb_auth::AuthCacheRegistry::default(), + table_key_info_lookup: None, + item_authorizer: None, + }; + (ctx, dir) +} + +#[tokio::test] +async fn batch_write_item_alone_reads_a_binary_only_with_its_padding() { + #[rustfmt::skip] + let rows: [(&str, &str, Value, Answer); 12] = [ + ("w1", "BatchWriteItem", batch(S_TABLE, put(item("w1", json!({"B": "YQ"})))), length(2)), + ("w2", "BatchWriteItem", batch(S_TABLE, put(item("w2", json!({"B": "YQ="})))), length(3)), + ("w4", "BatchWriteItem", batch(S_TABLE, put(item("w4", json!({"BS": ["YQ"]})))), length(2)), + ("w5", "BatchWriteItem", batch(B_TABLE, json!({"DeleteRequest": {"Key": b_key()}})), length(2)), + ("w6", "BatchWriteItem", batch(B_TABLE, put(json!({"pk": {"B": "Yg"}}))), length(2)), + ("w7", "BatchGetItem", json!({"RequestItems": {B_TABLE: {"Keys": [b_key()]}}}), Ok(None)), + ("w8", "TransactGetItems", + json!({"TransactItems": [{"Get": {"TableName": B_TABLE, "Key": b_key()}}]}), Ok(None)), + ("w9", "GetItem", json!({"TableName": B_TABLE, "Key": b_key()}), Ok(None)), + ("w10", "DeleteItem", json!({"TableName": B_TABLE, "Key": b_key()}), Ok(None)), + ("w11", "TransactWriteItems", + json!({"TransactItems": [{"Put": {"TableName": S_TABLE, "Item": item("w11", json!({"B": "YQ"}))}}]}), + stored("YQ==")), + ("w12", "TransactWriteItems", + json!({"TransactItems": [{"Delete": {"TableName": B_TABLE, "Key": b_key()}}]}), Ok(None)), + ("w13", "UpdateItem", + json!({"TableName": S_TABLE, "Key": {"pk": {"S": "w13"}}, + "UpdateExpression": "SET b = :v", "ExpressionAttributeValues": {":v": {"B": "YQ"}}}), + stored("YQ==")), + ]; + let (ctx, _dir) = context().await; + for (table, kind) in [(S_TABLE, "S"), (B_TABLE, "B")] { + let body = json!({ + "TableName": table, + "BillingMode": "PAY_PER_REQUEST", + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": kind}], + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + }); + if let Err(e) = dispatch("CreateTable", body, &ctx, "").await { + panic!("{table}: {e:?}"); + } + } + let mut wrong = Vec::new(); + for (row, operation, body, want) in rows { + let got = match dispatch(operation, body, &ctx, "").await { + Ok(_) => Ok(read_back(&ctx, row).await), + Err(DynamoDbError::SerializationException(message)) => Err(message), + Err(other) => Err(format!("{other:?}")), + }; + if got != want { + wrong.push(format!("{row}: {got:?}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The `B` text of attribute `b` of the item `row` in the S table, if any. +async fn read_back(ctx: &OperationContext, row: &str) -> Option { + let body = json!({"TableName": S_TABLE, "Key": {"pk": {"S": row}}}); + let result = dispatch("GetItem", body, ctx, "").await.expect(row); + result.body["Item"]["b"]["B"] + .as_str() + .map(ToOwned::to_owned) +} diff --git a/crates/engine/src/import_export_io.rs b/crates/engine/src/import_export_io.rs index e1f1be638..aea9558fc 100755 --- a/crates/engine/src/import_export_io.rs +++ b/crates/engine/src/import_export_io.rs @@ -14,7 +14,7 @@ use base64::engine::general_purpose::STANDARD as BASE64; use serde_json::Value; use extenddb_core::error::DynamoDbError; -use extenddb_core::types::{AttributeValue, InputFormat, Item}; +use extenddb_core::types::{AttributeValue, InputFormat, Item, check_binaries}; /// Read items from a file in the specified format. pub(crate) fn read_items( @@ -38,7 +38,8 @@ pub(crate) fn read_items( /// /// The service's import reads a `B` value or a `BS` member only as canonical /// padded base64 (measured 2026-11-22), and the item deserializer reads other -/// forms a request may send, so [`canonical_binaries`] checks the line first. +/// forms a request may send, so `check_binaries` reads the line with the +/// standard decoder first. fn read_dynamodb_json(reader: impl BufRead, max_items: u64) -> Result, DynamoDbError> { let mut items = Vec::new(); for (line_num, line) in reader.lines().enumerate() { @@ -68,7 +69,7 @@ fn read_dynamodb_json(reader: impl BufRead, max_items: u64) -> Result, line_num + 1 )) }; - if !canonical_binaries(&item_value) { + if check_binaries(&item_value, |text| BASE64.decode(text)).is_err() { return Err(invalid_item()); } let item: Item = serde_json::from_value(item_value).map_err(|_| invalid_item())?; @@ -82,28 +83,6 @@ fn read_dynamodb_json(reader: impl BufRead, max_items: u64) -> Result, Ok(items) } -/// Whether every `B` text and `BS` member in `value` decodes with `STANDARD`. -/// Matching member names is safe: a line that parses holds attribute values -/// there, and any other line is refused. `serde_json` caps the depth at 128. -fn canonical_binaries(value: &Value) -> bool { - match value { - Value::Object(members) => { - members - .iter() - .all(|(tag, payload)| match (tag.as_str(), payload) { - ("B", Value::String(text)) => BASE64.decode(text).is_ok(), - ("BS", Value::Array(set)) => set - .iter() - .filter_map(Value::as_str) - .all(|text| BASE64.decode(text).is_ok()), - _ => canonical_binaries(payload), - }) - } - Value::Array(items) => items.iter().all(canonical_binaries), - _ => true, - } -} - /// Read CSV format. fn read_csv( reader: impl BufRead, From e030be210adc771315fec50bcdbe4e51bd8ea3ba Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:52:19 +0000 Subject: [PATCH 4/9] test(engine): say why the two nested import rows expect a refusal The doc comment of import_reads_a_binary_only_in_the_canonical_form says that the rows with YQ inside an M and an L were not measured. It now also gives the reason for their expected answer. The import reads a B value with the standard decoder at any depth, so these rows get the answer of the top-level YQ row. --- crates/engine/src/import_export_io.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/import_export_io.rs b/crates/engine/src/import_export_io.rs index aea9558fc..fbf1b46a8 100755 --- a/crates/engine/src/import_export_io.rs +++ b/crates/engine/src/import_export_io.rs @@ -689,7 +689,9 @@ mod tests { /// Measured on DynamoDB on 2026-11-22: an import of the first 18 values, /// one line `{"Item": {"pk": {"S": ...}, "b": }}` each, imported /// the `YQ==` line and refused every other line. The last two rows, a - /// value inside an `M` and an `L`, were not measured. + /// value inside an `M` and an `L`, were not measured. They expect the + /// answer of the top-level `YQ` row, because the import's decoder + /// refuses `YQ` at any depth. #[test] fn import_reads_a_binary_only_in_the_canonical_form() { let rows: [(&str, Option<&[u8]>); 20] = [ From 6b21d479ca002282ec46661f53b8a1e38ec5da8c Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:20:39 +0000 Subject: [PATCH 5/9] fix(engine): check only the items and keys of BatchWriteItem for padding The padding check of BatchWriteItem read every member named B or BS under RequestItems, at any depth. It refused members that the deserializer skips, such as a B member beside Item. It also decoded a B inside a BS member that is not a string. When an earlier value had the wrong JSON type, the check still reported the B first. DynamoDB answers these requests otherwise (measured 2026-12-02, each body twice, on a table that does not exist): - A B or BS member beside Item, PutRequest or Key gets ResourceNotFoundException. The service does not read it. - {"BS": [{"B": "YQ"}]} gets "Start of structure or map found where not expected". A string where an attribute value belongs gets "Unexpected value type in payload". PutItem gives the same answers. - {"pk": {"S": 1}, "v": {"B": "YQ"}} gets "NUMBER_VALUE cannot be converted to String", and {"v": {"B": "YQ"}, "pk": {"S": 1}} the length text of YQ. The service reads the item in request order. written_values in batch_write_item.rs gives the attribute values of each PutRequest Item and each DeleteRequest Key, in the order the deserializer reads them. padding_refusal checks each value with check_binaries and decode_padded_base64. It gives the refusal only when no value ahead of it has a fault of the wrong JSON type. That check reuses shape_fault of query_key_values.rs, which the Query checks use for the same purpose. It runs only when the decoder refuses a value. check_binaries now takes one attribute value. It reads B, the string members of BS, and the values of M and L, and it leaves every other payload to the deserializer. ImportTable calls it on each value of the item of a line, and its answers do not change. The new test batch_write_item_checks_the_padding_of_the_items_and_keys_alone sends seven measured requests. Rows m4 to m6 expect the answer of a PutItem of the same item. For these rows, the texts of the deserializer differ from the texts of DynamoDB. --- crates/core/src/types/attribute_value.rs | 48 ++++++------ crates/engine/src/batch_write_item.rs | 65 +++++++++++++--- .../src/batch_write_item/padding_tests.rs | 76 ++++++++++++++++--- crates/engine/src/import_export_io.rs | 11 ++- crates/engine/src/query_key_values.rs | 2 +- 5 files changed, 153 insertions(+), 49 deletions(-) diff --git a/crates/core/src/types/attribute_value.rs b/crates/core/src/types/attribute_value.rs index 795c025e2..dde31609a 100755 --- a/crates/core/src/types/attribute_value.rs +++ b/crates/core/src/types/attribute_value.rs @@ -126,12 +126,13 @@ pub fn is_base64_refusal(message: &str) -> bool { message.is_empty() || BASE64_TEXTS.iter().any(|text| message.starts_with(text)) } -/// Check every `B` text and `BS` member of a wire value with `decode`, at -/// any depth. An operation whose decoder is not the deserializer's calls it -/// on the raw JSON ahead of deserializing. Matching member names is safe: a -/// value that deserializes holds attribute values there, and any other value -/// is refused. A `B` or `BS` payload of another shape, such as the requests -/// of a table of that name, is walked. `serde_json` caps the depth at 128. +/// Check the `B` text and each string member of a `BS` of a wire attribute +/// value with `decode`, in the values of its `M` and `L` too, in the order +/// the deserializer reads them. An operation whose decoder is not the +/// deserializer's calls it on the raw JSON ahead of deserializing. A payload +/// of another JSON type, a `BS` member that is not a string and a value that +/// is not a JSON object are left to the deserializer, which refuses them. +/// `serde_json` caps the depth at 128. /// /// # Errors /// @@ -141,24 +142,25 @@ pub fn check_binaries( decode: fn(&str) -> Result, E>, ) -> Result<(), E> { use serde_json::Value; - match value { - Value::Object(members) => { - members + let Value::Object(members) = value else { + return Ok(()); + }; + members + .iter() + .try_for_each(|(tag, payload)| match (tag.as_str(), payload) { + ("B", Value::String(text)) => decode(text).map(drop), + ("BS", Value::Array(set)) => set .iter() - .try_for_each(|(tag, payload)| match (tag.as_str(), payload) { - ("B", Value::String(text)) => decode(text).map(drop), - ("BS", Value::Array(set)) => set.iter().try_for_each(|member| match member { - Value::String(text) => decode(text).map(drop), - other => check_binaries(other, decode), - }), - _ => check_binaries(payload, decode), - }) - } - Value::Array(items) => items - .iter() - .try_for_each(|item| check_binaries(item, decode)), - _ => Ok(()), - } + .filter_map(Value::as_str) + .try_for_each(|text| decode(text).map(drop)), + ("M", Value::Object(entries)) => entries + .values() + .try_for_each(|entry| check_binaries(entry, decode)), + ("L", Value::Array(items)) => items + .iter() + .try_for_each(|item| check_binaries(item, decode)), + _ => Ok(()), + }) } impl<'de> Visitor<'de> for AttributeValueVisitor { diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index aba282ea5..de99ccc2f 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -12,8 +12,9 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::expression::ExpressionMaps; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{ - BatchWriteItemInput, BatchWriteItemOutput, Item, KeySchemaElement, ReturnItemCollectionMetrics, - TableKeyInfo, WriteRequest, check_binaries, decode_padded_base64, extract_key, item_size_bytes, + AttributeValue, BatchWriteItemInput, BatchWriteItemOutput, Item, KeySchemaElement, + ReturnItemCollectionMetrics, TableKeyInfo, WriteRequest, check_binaries, decode_padded_base64, + extract_key, item_size_bytes, }; use extenddb_core::validation::{ AttributeNameRequestForm, IndexKeyRef, validate_attribute_name_sizes, validate_batch_item_keys, @@ -27,6 +28,7 @@ use extenddb_storage::error::StorageError; use crate::OperationContext; use crate::capacity_helpers; use crate::create_table::storage_err_to_dynamo; +use crate::query_key_values::shape_fault; use crate::request_limits; use crate::serialize_output; use crate::stream_capture; @@ -46,14 +48,13 @@ pub async fn handle_batch_write_item( ctx: &OperationContext, ) -> Result { // The service reads a B value or a BS member of this operation only with - // its padding, in a PutRequest item and in a DeleteRequest key, and - // refuses one without it ahead of the rest of the request. Every other - // operation reads the padding left out or cut short (measured - // 2026-11-22), and so does the deserializer, so the raw RequestItems are - // checked with the decoder that requires the padding first. The other - // members of the body are the deserializer's. - check_binaries(&body["RequestItems"], decode_padded_base64) - .map_err(crate::serialization_exception)?; + // its padding, in a PutRequest item and in a DeleteRequest key. Every + // other operation reads the padding left out or cut short (measured + // 2026-11-22), and so does the deserializer, so the items and keys are + // checked with the decoder that requires the padding first. + if let Some(text) = padding_refusal(&body["RequestItems"]) { + return Err(crate::serialization_exception(text)); + } let input: BatchWriteItemInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; @@ -126,6 +127,50 @@ pub async fn handle_batch_write_item( .await } +/// The attribute values of the items and keys of `RequestItems`, in the +/// order the deserializer reads them: the `Item` of each `PutRequest` and +/// the `Key` of each `DeleteRequest`. A member that `WriteRequest`, +/// `PutRequest` or `DeleteRequest` does not model is skipped, as the +/// deserializer skips it. +fn written_values(request_items: &Value) -> impl Iterator { + request_items + .as_object() + .into_iter() + .flat_map(serde_json::Map::values) + .filter_map(Value::as_array) + .flatten() + .filter_map(Value::as_object) + .flatten() + .filter_map(|(member, request)| match member.as_str() { + "PutRequest" => request.get("Item"), + "DeleteRequest" => request.get("Key"), + _ => None, + }) + .filter_map(Value::as_object) + .flat_map(serde_json::Map::values) +} + +/// The refusal of [`decode_padded_base64`] for the first `B` value or `BS` +/// member of the [`written_values`], unless a value ahead of it holds a +/// fault of the wrong JSON type, which the deserializer reports first. The +/// service reads the request in its order (measured 2026-12-02, each body +/// twice, on a table that does not exist: an item `{"pk": {"S": 1}, "v": +/// {"B": "YQ"}}` answers `NUMBER_VALUE cannot be converted to String`, and +/// `{"v": {"B": "YQ"}, "pk": {"S": 1}}` answers the length text of `YQ`). +/// Inside one value, the refusal is reported first. +fn padding_refusal(request_items: &Value) -> Option { + let values: Vec<&Value> = written_values(request_items).collect(); + let (at, text) = values.iter().enumerate().find_map(|(at, value)| { + check_binaries(value, decode_padded_base64) + .err() + .map(|text| (at, text)) + })?; + values[..at] + .iter() + .all(|value| shape_fault::((*value).clone()).is_none()) + .then_some(text) +} + /// Check the whole batch, then write it. /// /// The table lookups, the duplicate-key check and the validation of every diff --git a/crates/engine/src/batch_write_item/padding_tests.rs b/crates/engine/src/batch_write_item/padding_tests.rs index e3eaca9ef..42e42d265 100644 --- a/crates/engine/src/batch_write_item/padding_tests.rs +++ b/crates/engine/src/batch_write_item/padding_tests.rs @@ -125,7 +125,61 @@ async fn batch_write_item_alone_reads_a_binary_only_with_its_padding() { "UpdateExpression": "SET b = :v", "ExpressionAttributeValues": {":v": {"B": "YQ"}}}), stored("YQ==")), ]; - let (ctx, _dir) = context().await; + let (ctx, _dir) = tables().await; + let mut wrong = Vec::new(); + for (row, operation, body, want) in rows { + let got = answer(&ctx, row, operation, body).await; + if got != want { + wrong.push(format!("{row}: {got:?}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The check reads only the items and keys, in the order the deserializer +/// reads them. Measured on the service in us-east-1 on 2026-12-02, each +/// request twice, on a table that does not exist. A `B` or `BS` member beside +/// `Item`, `PutRequest` or `Key` is not read: the service answered +/// `ResourceNotFoundException` (m1 to m3). A `BS` member that is not a +/// string (m4), a string where an attribute value belongs (m5), and a value +/// of the wrong JSON type ahead of a `B` without its padding (m6) get a +/// `SerializationException` of the deserializer. Here each of these gets the +/// answer of a `PutItem` of the same item. A `B` without its padding ahead of +/// such a value gets the text of its length (m7). +#[tokio::test] +async fn batch_write_item_checks_the_padding_of_the_items_and_keys_alone() { + #[rustfmt::skip] + let rows: [(&str, Value, Option); 7] = [ + ("m1", json!({"PutRequest": {"Item": {"pk": {"S": "m1"}}, "B": "x"}}), Some(Ok(None))), + ("m2", json!({"PutRequest": {"Item": {"pk": {"S": "m2"}}}, "BS": ["x"]}), Some(Ok(None))), + ("m3", json!({"DeleteRequest": {"Key": {"pk": {"S": "m3"}}, "B": "x"}}), Some(Ok(None))), + ("m4", put(item("m4", json!({"BS": [{"B": "YQ"}]}))), None), + ("m5", put(json!({"pk": {"S": "m5"}, "B": "YQ"})), None), + ("m6", put(json!({"pk": {"S": 1}, "v": {"B": "YQ"}})), None), + ("m7", put(json!({"a": {"B": "YQ"}, "pk": {"S": 1}})), Some(length(2))), + ]; + let (ctx, _dir) = tables().await; + let mut wrong = Vec::new(); + for (row, request, want) in rows { + let want = match want { + Some(want) => want, + None => { + let item = request["PutRequest"]["Item"].clone(); + let body = json!({"TableName": S_TABLE, "Item": item}); + answer(&ctx, row, "PutItem", body).await + } + }; + let got = answer(&ctx, row, "BatchWriteItem", batch(S_TABLE, request)).await; + if got != want { + wrong.push(format!("{row}: {got:?}, want {want:?}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// A context from [`context`] with the S table and the B table. +async fn tables() -> (OperationContext, TempDir) { + let (ctx, dir) = context().await; for (table, kind) in [(S_TABLE, "S"), (B_TABLE, "B")] { let body = json!({ "TableName": table, @@ -137,18 +191,16 @@ async fn batch_write_item_alone_reads_a_binary_only_with_its_padding() { panic!("{table}: {e:?}"); } } - let mut wrong = Vec::new(); - for (row, operation, body, want) in rows { - let got = match dispatch(operation, body, &ctx, "").await { - Ok(_) => Ok(read_back(&ctx, row).await), - Err(DynamoDbError::SerializationException(message)) => Err(message), - Err(other) => Err(format!("{other:?}")), - }; - if got != want { - wrong.push(format!("{row}: {got:?}")); - } + (ctx, dir) +} + +/// The answer to `body`: the item `row` read back, or the refusal. +async fn answer(ctx: &OperationContext, row: &str, operation: &str, body: Value) -> Answer { + match dispatch(operation, body, ctx, "").await { + Ok(_) => Ok(read_back(ctx, row).await), + Err(DynamoDbError::SerializationException(message)) => Err(message), + Err(other) => Err(format!("{other:?}")), } - assert!(wrong.is_empty(), "{wrong:#?}"); } /// The `B` text of attribute `b` of the item `row` in the S table, if any. diff --git a/crates/engine/src/import_export_io.rs b/crates/engine/src/import_export_io.rs index fbf1b46a8..e59e30dcd 100755 --- a/crates/engine/src/import_export_io.rs +++ b/crates/engine/src/import_export_io.rs @@ -38,8 +38,8 @@ pub(crate) fn read_items( /// /// The service's import reads a `B` value or a `BS` member only as canonical /// padded base64 (measured 2026-11-22), and the item deserializer reads other -/// forms a request may send, so `check_binaries` reads the line with the -/// standard decoder first. +/// forms a request may send, so `check_binaries` reads each value of the +/// item with the standard decoder first. fn read_dynamodb_json(reader: impl BufRead, max_items: u64) -> Result, DynamoDbError> { let mut items = Vec::new(); for (line_num, line) in reader.lines().enumerate() { @@ -69,7 +69,12 @@ fn read_dynamodb_json(reader: impl BufRead, max_items: u64) -> Result, line_num + 1 )) }; - if check_binaries(&item_value, |text| BASE64.decode(text)).is_err() { + let canonical = item_value + .as_object() + .into_iter() + .flat_map(serde_json::Map::values) + .all(|value| check_binaries(value, |text| BASE64.decode(text)).is_ok()); + if !canonical { return Err(invalid_item()); } let item: Item = serde_json::from_value(item_value).map_err(|_| invalid_item())?; diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 8dd925af3..940fa44ad 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -231,7 +231,7 @@ const BOOLEAN_TEXTS: [&str; 10] = ["true", "t", "yes", "y", "1", "false", "f", " /// The deserializer's `SerializationException` for `body` as a `T`, unless it /// is the one for an AttributeValue with an unknown type descriptor. -fn shape_fault(body: Value) -> Option { +pub(crate) fn shape_fault(body: Value) -> Option { match serde_json::from_value::(body).map_err(crate::deserialize_error) { Err(DynamoDbError::SerializationException(msg)) if msg.contains(UNKNOWN_TYPE_DESCRIPTOR) => From 3aadd304c77d91d3d0a6d4f809aea7e238672722 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:59:08 +0000 Subject: [PATCH 6/9] docs(upgrade): list the read of a B value without its full padding Add a v1.2.0 entry at the top of "Behavior Changes by Release" in docs/manuals/07-upgrade-manual.md, above the entries of main and #1260. It gives the values that 1.1.0 refused and this branch reads, the bytes they store, and the requests that still need the padding. --- docs/manuals/07-upgrade-manual.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 879519132..8d02063ae 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -392,6 +392,14 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. +### v1.2.0: a `B` value without its full `=` padding decodes in an item, a key and an expression attribute value + +**What changed** (#1313). ExtendDB now reads a `B` value or a `BS` member with its `=` padding left out or cut short, as DynamoDB does (measured 2026-11-21). It reads such a value in an item, a key and an expression attribute value. 1.1.0 refused it with `SerializationException`. The stored bytes are those of the padded value: `{"B": "YQ"}` and `{"B": "YQ="}` store `YQ==`, and `{"B": "YWI"}` stores `YWI=`. A value with bits past the last byte in its last character still gets `SerializationException`, such as `YR` with `Base64 encoded length is expected a multiple of 4 bytes but found: 2`. + +A PartiQL parameter, BatchWriteItem and ImportTable still read a `B` value only with its padding, as DynamoDB does (measured 2026-11-21 and 2026-11-22). BatchWriteItem checks the padding only in the attribute values of each `PutRequest` `Item` and each `DeleteRequest` `Key` (measured 2026-12-02). + +**Who is affected.** A client or a test that expects the refusal of such a value. The request now succeeds and stores the bytes of the padded value. No catalog migration or configuration change is required, and the stored data does not change. After a rollback to 1.1.0, the server refuses such a value again. Items that 1.2.0 wrote hold the same bytes as items written with the padded value. + ### v1.2.0: `DeleteTable` refuses a table that is already DELETING, and a DELETING table is described without seven members **What changed** (#1411, fixes #602). Two answers change, as DynamoDB gives them (measured 2026-11-23 and 2026-11-30): From 7dfea6aba61b9ed2d276c8bd53c74304859fa055 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:01:56 +0000 Subject: [PATCH 7/9] fix(engine): report a fault ahead of a B in one value as DynamoDB does Inside one value, the padding check of BatchWriteItem reported a B without its padding ahead of an earlier fault of the wrong JSON type. For example, {"S": 1} ahead of {"B": "YQ"} in an M or an L got the length text of YQ. So did an object or a number ahead of "YQ" in a BS. DynamoDB reads inside a value in request order and reports the first fault (measured 2026-12-03, each body twice, on a table that does not exist): - {"M": {"a": {"S": 1}, "b": {"B": "YQ"}}} and the same two values in an L get "NUMBER_VALUE cannot be converted to String". With the B first, both get the length text of YQ. - {"BS": [{"B": "YQ"}, "YQ"]} gets "Start of structure or map found where not expected". {"BS": [1, "YQ"]} gets "only base-64-encoded strings are convertible to bytes". - An SS member of another JSON type in a value ahead of the B gets "NUMBER_VALUE cannot be converted to String". - The read does not stop at an unknown type descriptor or a second type descriptor ahead of the B. It does not stop at a null payload or a null member of a BS or an L either. The B gets the length text of YQ. These are the rules of check_parameter_types, the first pass of the PartiQL parameter checks (measured 2026-11-06). padding_refusal now reads each value of written_values with it. It keeps a base64 refusal and leaves every other fault to the deserializer. This replaces check_binaries and shape_fault in BatchWriteItem, and shape_fault is private again, as on main. The 15 measured rows join batch_write_item_checks_the_padding_of_the_items_and_keys_alone. The five rows with a fault ahead of the B expect the answer of a PutItem of the same item, as m4 to m6 do. The texts of the deserializer differ from the texts of DynamoDB there (#1104, #1012). --- crates/engine/src/batch_write_item.rs | 40 ++++++++---------- .../src/batch_write_item/padding_tests.rs | 42 ++++++++++++++----- crates/engine/src/query_key_values.rs | 2 +- 3 files changed, 50 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index de99ccc2f..e2e0a19f6 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -11,10 +11,10 @@ use serde_json::Value; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::ExpressionMaps; use extenddb_core::limits::LimitsConfig; +use extenddb_core::partiql::params::check_parameter_types; use extenddb_core::types::{ - AttributeValue, BatchWriteItemInput, BatchWriteItemOutput, Item, KeySchemaElement, - ReturnItemCollectionMetrics, TableKeyInfo, WriteRequest, check_binaries, decode_padded_base64, - extract_key, item_size_bytes, + BatchWriteItemInput, BatchWriteItemOutput, Item, KeySchemaElement, ReturnItemCollectionMetrics, + TableKeyInfo, WriteRequest, extract_key, is_base64_refusal, item_size_bytes, }; use extenddb_core::validation::{ AttributeNameRequestForm, IndexKeyRef, validate_attribute_name_sizes, validate_batch_item_keys, @@ -28,7 +28,6 @@ use extenddb_storage::error::StorageError; use crate::OperationContext; use crate::capacity_helpers; use crate::create_table::storage_err_to_dynamo; -use crate::query_key_values::shape_fault; use crate::request_limits; use crate::serialize_output; use crate::stream_capture; @@ -150,25 +149,22 @@ fn written_values(request_items: &Value) -> impl Iterator { .flat_map(serde_json::Map::values) } -/// The refusal of [`decode_padded_base64`] for the first `B` value or `BS` -/// member of the [`written_values`], unless a value ahead of it holds a -/// fault of the wrong JSON type, which the deserializer reports first. The -/// service reads the request in its order (measured 2026-12-02, each body -/// twice, on a table that does not exist: an item `{"pk": {"S": 1}, "v": -/// {"B": "YQ"}}` answers `NUMBER_VALUE cannot be converted to String`, and -/// `{"v": {"B": "YQ"}, "pk": {"S": 1}}` answers the length text of `YQ`). -/// Inside one value, the refusal is reported first. +/// The refusal of the first `B` value or `BS` member of the +/// [`written_values`] that does not decode with its padding, unless a fault +/// of the wrong JSON type comes first, which the deserializer reports. The +/// service reads the items and keys in request order, inside a value too, +/// as it reads PartiQL parameters in its first pass, so +/// [`check_parameter_types`] reads them. Measured 2026-12-02 and 2026-12-03, +/// each body twice, on a table that does not exist: `{"S": 1}` ahead of +/// `{"B": "YQ"}` answers `NUMBER_VALUE cannot be converted to String`, in an +/// item, an `M` and an `L`, and so does `{"SS": [1]}`. A `BS` member that is +/// an object or a number is a fault at its place. An unknown type +/// descriptor, a second type descriptor, a null payload and a null member of +/// a `BS` or an `L` are not: the length text of `YQ` comes first. fn padding_refusal(request_items: &Value) -> Option { - let values: Vec<&Value> = written_values(request_items).collect(); - let (at, text) = values.iter().enumerate().find_map(|(at, value)| { - check_binaries(value, decode_padded_base64) - .err() - .map(|text| (at, text)) - })?; - values[..at] - .iter() - .all(|value| shape_fault::((*value).clone()).is_none()) - .then_some(text) + written_values(request_items) + .find_map(|value| check_parameter_types(std::slice::from_ref(value)).err()) + .filter(|text| is_base64_refusal(text)) } /// Check the whole batch, then write it. diff --git a/crates/engine/src/batch_write_item/padding_tests.rs b/crates/engine/src/batch_write_item/padding_tests.rs index 42e42d265..89b6260aa 100644 --- a/crates/engine/src/batch_write_item/padding_tests.rs +++ b/crates/engine/src/batch_write_item/padding_tests.rs @@ -136,20 +136,25 @@ async fn batch_write_item_alone_reads_a_binary_only_with_its_padding() { assert!(wrong.is_empty(), "{wrong:#?}"); } -/// The check reads only the items and keys, in the order the deserializer -/// reads them. Measured on the service in us-east-1 on 2026-12-02, each -/// request twice, on a table that does not exist. A `B` or `BS` member beside -/// `Item`, `PutRequest` or `Key` is not read: the service answered -/// `ResourceNotFoundException` (m1 to m3). A `BS` member that is not a -/// string (m4), a string where an attribute value belongs (m5), and a value -/// of the wrong JSON type ahead of a `B` without its padding (m6) get a -/// `SerializationException` of the deserializer. Here each of these gets the -/// answer of a `PutItem` of the same item. A `B` without its padding ahead of -/// such a value gets the text of its length (m7). +/// The check reads only the items and keys, in request order, inside a +/// value too. Measured on the service in us-east-1, each request twice, on a +/// table that does not exist: m1 to m7 on 2026-12-02, n1 to n15 on +/// 2026-12-03. A `B` or `BS` member beside `Item`, `PutRequest` or `Key` is +/// not read: the service answered `ResourceNotFoundException` (m1 to m3). A +/// fault of the wrong JSON type gets a `SerializationException` of the +/// deserializer: a `BS` member that is not a string (m4), a string where an +/// attribute value belongs (m5), and such a fault ahead of a `B` without its +/// padding, in the item (m6, n14), an `M` (n1), an `L` (n2) and a `BS` (n5, +/// n6). Here each of these gets the answer of a `PutItem` of the same item. +/// A `B` without its padding ahead of such a fault (m7, n3, n4, n8) gets the +/// text of its length, and so does one after an unknown type descriptor +/// (n9), a second type descriptor (n10 to n12), a null payload (n13) or a +/// null member (n7, n15). #[tokio::test] async fn batch_write_item_checks_the_padding_of_the_items_and_keys_alone() { + let yq = || json!({"B": "YQ"}); #[rustfmt::skip] - let rows: [(&str, Value, Option); 7] = [ + let rows: [(&str, Value, Option); 22] = [ ("m1", json!({"PutRequest": {"Item": {"pk": {"S": "m1"}}, "B": "x"}}), Some(Ok(None))), ("m2", json!({"PutRequest": {"Item": {"pk": {"S": "m2"}}}, "BS": ["x"]}), Some(Ok(None))), ("m3", json!({"DeleteRequest": {"Key": {"pk": {"S": "m3"}}, "B": "x"}}), Some(Ok(None))), @@ -157,6 +162,21 @@ async fn batch_write_item_checks_the_padding_of_the_items_and_keys_alone() { ("m5", put(json!({"pk": {"S": "m5"}, "B": "YQ"})), None), ("m6", put(json!({"pk": {"S": 1}, "v": {"B": "YQ"}})), None), ("m7", put(json!({"a": {"B": "YQ"}, "pk": {"S": 1}})), Some(length(2))), + ("n1", put(item("n1", json!({"M": {"a": {"S": 1}, "b": yq()}}))), None), + ("n2", put(item("n2", json!({"L": [{"S": 1}, yq()]}))), None), + ("n3", put(item("n3", json!({"M": {"a": yq(), "b": {"S": 1}}}))), Some(length(2))), + ("n4", put(item("n4", json!({"L": [yq(), {"S": 1}]}))), Some(length(2))), + ("n5", put(item("n5", json!({"BS": [yq(), "YQ"]}))), None), + ("n6", put(item("n6", json!({"BS": [1, "YQ"]}))), None), + ("n7", put(item("n7", json!({"BS": [null, "YQ"]}))), Some(length(2))), + ("n8", put(item("n8", json!({"BS": ["YQ", 1]}))), Some(length(2))), + ("n9", put(json!({"a": {"X": "y"}, "v": yq()})), Some(length(2))), + ("n10", put(item("n10", json!({"B": "YQ", "S": "x"}))), Some(length(2))), + ("n11", put(item("n11", json!({"M": {"a": {"B": "YQ", "NULL": true}}}))), Some(length(2))), + ("n12", put(item("n12", json!({"S": "x", "B": "YQ"}))), Some(length(2))), + ("n13", put(json!({"pk": {"S": "n13"}, "u": {"S": null}, "v": yq()})), Some(length(2))), + ("n14", put(json!({"pk": {"S": "n14"}, "u": {"SS": [1]}, "v": yq()})), None), + ("n15", put(json!({"pk": {"S": "n15"}, "u": {"L": [null]}, "v": yq()})), Some(length(2))), ]; let (ctx, _dir) = tables().await; let mut wrong = Vec::new(); diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 940fa44ad..8dd925af3 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -231,7 +231,7 @@ const BOOLEAN_TEXTS: [&str; 10] = ["true", "t", "yes", "y", "1", "false", "f", " /// The deserializer's `SerializationException` for `body` as a `T`, unless it /// is the one for an AttributeValue with an unknown type descriptor. -pub(crate) fn shape_fault(body: Value) -> Option { +fn shape_fault(body: Value) -> Option { match serde_json::from_value::(body).map_err(crate::deserialize_error) { Err(DynamoDbError::SerializationException(msg)) if msg.contains(UNKNOWN_TYPE_DESCRIPTOR) => From 6825c8e2ba164e692f3bec45c3a546a57bffb9c8 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:05:53 +0000 Subject: [PATCH 8/9] docs(upgrade): list the BatchWriteItem answers that the read order changes The v1.2.0 entry of this PR now says which BatchWriteItem answers change from 1.1.0. A B without its padding gets the length text beside a second type descriptor, and after an unknown type descriptor or a null. 1.1.0 refused such a request for the other value. A fault of the wrong JSON type ahead of the B keeps its 1.1.0 answer. DynamoDB gives these answers (measured 2026-12-03, each body twice, on a table that does not exist). --- docs/manuals/07-upgrade-manual.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 8d02063ae..4dac98722 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -396,7 +396,7 @@ deployment, even when no catalog migration is required. **What changed** (#1313). ExtendDB now reads a `B` value or a `BS` member with its `=` padding left out or cut short, as DynamoDB does (measured 2026-11-21). It reads such a value in an item, a key and an expression attribute value. 1.1.0 refused it with `SerializationException`. The stored bytes are those of the padded value: `{"B": "YQ"}` and `{"B": "YQ="}` store `YQ==`, and `{"B": "YWI"}` stores `YWI=`. A value with bits past the last byte in its last character still gets `SerializationException`, such as `YR` with `Base64 encoded length is expected a multiple of 4 bytes but found: 2`. -A PartiQL parameter, BatchWriteItem and ImportTable still read a `B` value only with its padding, as DynamoDB does (measured 2026-11-21 and 2026-11-22). BatchWriteItem checks the padding only in the attribute values of each `PutRequest` `Item` and each `DeleteRequest` `Key` (measured 2026-12-02). +A PartiQL parameter, BatchWriteItem and ImportTable still read a `B` value only with its padding, as DynamoDB does (measured 2026-11-21 and 2026-11-22). BatchWriteItem checks the padding only in the attribute values of each `PutRequest` `Item` and each `DeleteRequest` `Key` (measured 2026-12-02). There, a `B` without its padding now gets the length text beside a second type descriptor, and after an unknown type descriptor or a null. DynamoDB gives the same answers (measured 2026-12-03). 1.1.0 refused such a request for the other value. A fault of the wrong JSON type ahead of the `B`, also inside its value, keeps the answer of 1.1.0. **Who is affected.** A client or a test that expects the refusal of such a value. The request now succeeds and stores the bytes of the padded value. No catalog migration or configuration change is required, and the stored data does not change. After a rollback to 1.1.0, the server refuses such a value again. Items that 1.2.0 wrote hold the same bytes as items written with the padded value. From 835b5aed7aa34ea7d2cd02b76f9dd075ec48aada Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:09:52 +0000 Subject: [PATCH 9/9] docs(upgrade): give the 1.1.0 answer of BatchWriteItem as the text of the other fault The v1.2.0 entry said that 1.1.0 refused such a request for the other value. Beside a second type descriptor, the other fault is in the same value. So the entry now says that 1.1.0 answered with the text of the other fault. The PR body gives the same wording. --- docs/manuals/07-upgrade-manual.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 4dac98722..5186d7010 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -396,7 +396,7 @@ deployment, even when no catalog migration is required. **What changed** (#1313). ExtendDB now reads a `B` value or a `BS` member with its `=` padding left out or cut short, as DynamoDB does (measured 2026-11-21). It reads such a value in an item, a key and an expression attribute value. 1.1.0 refused it with `SerializationException`. The stored bytes are those of the padded value: `{"B": "YQ"}` and `{"B": "YQ="}` store `YQ==`, and `{"B": "YWI"}` stores `YWI=`. A value with bits past the last byte in its last character still gets `SerializationException`, such as `YR` with `Base64 encoded length is expected a multiple of 4 bytes but found: 2`. -A PartiQL parameter, BatchWriteItem and ImportTable still read a `B` value only with its padding, as DynamoDB does (measured 2026-11-21 and 2026-11-22). BatchWriteItem checks the padding only in the attribute values of each `PutRequest` `Item` and each `DeleteRequest` `Key` (measured 2026-12-02). There, a `B` without its padding now gets the length text beside a second type descriptor, and after an unknown type descriptor or a null. DynamoDB gives the same answers (measured 2026-12-03). 1.1.0 refused such a request for the other value. A fault of the wrong JSON type ahead of the `B`, also inside its value, keeps the answer of 1.1.0. +A PartiQL parameter, BatchWriteItem and ImportTable still read a `B` value only with its padding, as DynamoDB does (measured 2026-11-21 and 2026-11-22). BatchWriteItem checks the padding only in the attribute values of each `PutRequest` `Item` and each `DeleteRequest` `Key` (measured 2026-12-02). There, a `B` without its padding now gets the length text beside a second type descriptor, and after an unknown type descriptor or a null. DynamoDB gives the same answers (measured 2026-12-03). 1.1.0 refused such a request with the text of the other fault. A fault of the wrong JSON type ahead of the `B`, also inside its value, keeps the answer of 1.1.0. **Who is affected.** A client or a test that expects the refusal of such a value. The request now succeeds and stores the bytes of the padded value. No catalog migration or configuration change is required, and the stored data does not change. After a rollback to 1.1.0, the server refuses such a value again. Items that 1.2.0 wrote hold the same bytes as items written with the padded value.