diff --git a/crates/core/src/partiql/params.rs b/crates/core/src/partiql/params.rs index 53fc6e3d8..75d69b266 100644 --- a/crates/core/src/partiql/params.rs +++ b/crates/core/src/partiql/params.rs @@ -49,7 +49,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; pub use crate::validation::number::NUMBER_SET_DUPLICATES; use crate::validation::number::has_equal_numbers; @@ -107,7 +107,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() @@ -119,7 +119,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()), } @@ -582,10 +582,16 @@ 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, 2026-11-21 and 2026-11-25). + // its text (measured 2026-11-20, 2026-11-21 and 2026-11-25). 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 a04740893..dde31609a 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}; @@ -82,10 +83,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}"), @@ -107,6 +126,43 @@ pub fn is_base64_refusal(message: &str) -> bool { message.is_empty() || BASE64_TEXTS.iter().any(|text| message.starts_with(text)) } +/// 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 +/// +/// 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; + 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() + .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 { type Value = AttributeValue; @@ -738,10 +794,11 @@ mod tests { ); } - /// The service's answer to each `B` value (measured 2026-11-20, and - /// 2026-11-25 for `//==` and `++==`): 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. + /// The service's answer to each `B` value (measured 2026-11-20, + /// 2026-11-21 for the values with their padding left out or cut short, + /// and 2026-11-25 for `//==` and `++==`): 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() { let short = || Err("Buffer is too short for base64 encoding".to_owned()); @@ -752,12 +809,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>); 50] = [ + let rows: [(&str, Result<&str, String>); 56] = [ ("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()), @@ -770,6 +832,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 6f64783a9..27f6ed14b 100755 --- a/crates/core/src/types/mod.rs +++ b/crates/core/src/types/mod.rs @@ -14,7 +14,8 @@ mod transaction; mod warm_throughput; pub use attribute_value::{ - AttributeValue, EMPTY_ATTRIBUTE_VALUE, MULTI_ATTRIBUTE_VALUE, decode_base64, is_base64_refusal, + AttributeValue, EMPTY_ATTRIBUTE_VALUE, MULTI_ATTRIBUTE_VALUE, check_binaries, decode_base64, + decode_padded_base64, is_base64_refusal, }; pub use backup::{ BackupDescription, BackupDetails, BackupSummary, ContinuousBackupsDescription, diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index 3806e0e44..e2e0a19f6 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -11,9 +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::{ BatchWriteItemInput, BatchWriteItemOutput, Item, KeySchemaElement, ReturnItemCollectionMetrics, - TableKeyInfo, WriteRequest, extract_key, item_size_bytes, + TableKeyInfo, WriteRequest, extract_key, is_base64_refusal, item_size_bytes, }; use extenddb_core::validation::{ AttributeNameRequestForm, IndexKeyRef, validate_attribute_name_sizes, validate_batch_item_keys, @@ -45,6 +46,14 @@ 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. 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)?; @@ -117,6 +126,47 @@ 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 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 { + 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. /// /// The table lookups, the duplicate-key check and the validation of every @@ -578,6 +628,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..89b6260aa --- /dev/null +++ b/crates/engine/src/batch_write_item/padding_tests.rs @@ -0,0 +1,233 @@ +// 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) = 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 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); 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))), + ("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))), + ("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(); + 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, + "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:?}"); + } + } + (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:?}")), + } +} + +/// 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 349117bcb..e59e30dcd 100755 --- a/crates/engine/src/import_export_io.rs +++ b/crates/engine/src/import_export_io.rs @@ -9,10 +9,12 @@ 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; -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( @@ -33,6 +35,11 @@ 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 `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() { @@ -56,12 +63,21 @@ 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 )) - })?; + }; + 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())?; items.push(item); if u64::try_from(items.len()).unwrap_or(u64::MAX) > max_items { return Err(DynamoDbError::ValidationException(format!( @@ -674,4 +690,50 @@ 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. 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] = [ + (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:#?}"); + } } diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 7a59cdb39..2c7136ad0 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -407,6 +407,14 @@ deployment, even when no catalog migration is required. **Who is affected.** MongoDB deployments whose policies allow or deny on `aws:ResourceTag` for tables being deleted. No catalog migration or configuration change is required. PostgreSQL and SQLite already removed the tags and the catalog row together. +### 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). 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. + ### 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): diff --git a/tests/test_binary_base64.py b/tests/test_binary_base64.py index b8b482763..3ba4d8222 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 and 2026-11-25, 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, +2026-11-21 and 2026-11-25, 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),